Merge release/delivery (IAM single sign-on) into the triage work

Brings the four release/delivery commits (IAM SSO for the admin panel,
both apps and the API; IAM env in docker-compose) onto fix/issues-triage.

Conflicts:
- customer-auth.service.ts imports: both kept.
- both apps' api/client.ts: both kept (AccountingBalance/WageQuote, and
  iamAppUrl).
- all build output (admin-panel, user-app, user-app-v2 dist, and the api
  release bundle): rebuilt from the merged source instead of picking a
  side.

Fixed while verifying:
- The IAM change calls iam.browserBootstrapUrl after every login, but
  the identity-service stand-ins in three test files lacked it. 15 tests
  failed on release/delivery itself.
- SMS relay: SMS_RELAY_PLATFORM was read but never sent, so the gateway
  never got `platform` (documented body: phone, host, text, platform).
  relayConfig() now returns it ("default" → null) and the request carries
  it. sms.service.spec now passes.

All 249 API tests pass; the three front-ends type-check and build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
s.esmaeili
2026-10-10 09:03:53 +03:30
co-authored by Claude Opus 5.5
315 changed files with 82919 additions and 7020 deletions
+46 -1
View File
@@ -1,4 +1,5 @@
import { Body, Controller, Get, Headers, HttpCode, Ip, Post } from '@nestjs/common';
import { Body, Controller, Get, Headers, HttpCode, Ip, Post, Query, Res } from '@nestjs/common';
import type { Response } from 'express';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { CurrentAdmin, Public } from './guards';
@@ -26,9 +27,53 @@ export class AuthController {
return this.authService.login(dto, ip, userAgent);
}
@Public()
@Get('sso/start')
startSso(@Query('redirect_uri') redirectUri: string | undefined, @Res({ passthrough: true }) res: Response) {
const started = this.authService.beginBrowserSso(redirectUri);
if (!started) return { enabled: false, authorize_url: null };
res.setHeader('Set-Cookie', started.cookie);
return { enabled: true, authorize_url: started.authorizeUrl };
}
@Public()
@Post('sso/callback')
@HttpCode(200)
ssoCallback(
@Body() body: { code?: string; state?: string },
@Headers('cookie') cookieHeader: string | undefined,
@Ip() ip: string,
@Headers('user-agent') userAgent: string | undefined,
@Res({ passthrough: true }) res: Response,
) {
res.setHeader('Set-Cookie', 'gb_admin_iam_sso=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax');
return this.authService.completeBrowserSso(
readCookie(cookieHeader, 'gb_admin_iam_sso'),
body.code ?? '',
body.state ?? '',
ip,
userAgent,
);
}
@Public()
@Get('sso/logout-url')
ssoLogoutUrl(@Query('return_url') returnUrl?: string) {
return { logout_url: this.authService.centralLogoutUrl(returnUrl) };
}
/** Legacy `users/show` — the router guard's permission refresh. */
@Get('me')
me(@CurrentAdmin() admin: AuthenticatedAdmin) {
return this.authService.showData(admin.id);
}
}
function readCookie(header: string | undefined, name: string): string | null {
if (!header) return null;
for (const part of header.split(';')) {
const [key, ...rest] = part.trim().split('=');
if (key === name) return decodeURIComponent(rest.join('='));
}
return null;
}
@@ -72,7 +72,7 @@ describe('AuthService login', () => {
service: new AuthService(
prisma as never,
jwt as never,
iam as IamService,
{ browserBootstrapUrl: () => null, ...iam } as IamService,
sessions as AdminSessionService,
),
prisma,
+155
View File
@@ -1,3 +1,4 @@
import { createHash, createHmac, randomBytes } from 'node:crypto';
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../../prisma/prisma.service';
@@ -8,6 +9,7 @@ import {
type IamIdentity,
} from '../iam/iam.service';
import { AdminSessionService } from '../sessions/admin-session.service';
import { envList, envOr, envOrNull, pickExactUri } from '../../common/env';
import type { LoginDto } from './dto/login.dto';
import { compareLocalHash } from './password-hash';
@@ -75,6 +77,130 @@ export class AuthService {
});
}
const bootstrap = this.iam.browserBootstrapUrl(verified.identity?.browserTicket);
return {
id: user.id,
name: user.fullName,
fullName: user.fullName,
mobile: user.mobile,
role: user.role,
ut: user.userTypeId,
branch_id: user.branchId,
api_token: apiToken,
roles: (user.userType?.permissions ?? []).map((p) => ({ rid: p.rid })),
...(bootstrap ? { iamBootstrapUrl: bootstrap } : {}),
};
}
beginBrowserSso(requestedRedirect?: string): { authorizeUrl: string; cookie: string } | null {
if (!this.iam.enabled) return null;
const redirectUri = pickExactUri(requestedRedirect, [
envOrNull('IAM_ADMIN_REDIRECT_URI'),
...envList('IAM_ADMIN_REDIRECT_URIS'),
]);
const clientId = envOrNull('IAM_CLIENT_ID');
if (!redirectUri || !clientId) return null;
const state = randomBytes(24).toString('base64url');
const nonce = randomBytes(24).toString('base64url');
const verifier = randomBytes(48).toString('base64url');
const challenge = createHash('sha256').update(verifier).digest('base64url');
const payload = Buffer.from(JSON.stringify({ state, nonce, verifier, redirectUri })).toString('base64url');
const sig = createHmac('sha256', this.ssoSecret()).update(payload).digest('base64url');
const secure = redirectUri.startsWith('https:');
const cookie =
`gb_admin_iam_sso=${payload}.${sig}; HttpOnly; Path=/; Max-Age=180; SameSite=Lax` +
(secure ? '; Secure' : '');
const url = new URL(`${this.iam.issuer}/oauth/authorize`);
url.searchParams.set('response_type', 'code');
url.searchParams.set('client_id', clientId);
url.searchParams.set('redirect_uri', redirectUri);
url.searchParams.set('scope', 'openid profile email');
url.searchParams.set('state', state);
url.searchParams.set('nonce', nonce);
url.searchParams.set('code_challenge', challenge);
url.searchParams.set('code_challenge_method', 'S256');
url.searchParams.set('prompt', 'none');
return { authorizeUrl: url.toString(), cookie };
}
async completeBrowserSso(cookieValue: string | null, code: string, state: string, ip?: string, userAgent?: string) {
const pending = this.readSsoCookie(cookieValue);
if (!pending || pending.state !== state) {
throw new UnauthorizedException('درخواست ورود مشترک معتبر نیست');
}
const claims = await this.iam.exchangeAuthorizationCode(code, pending.verifier, pending.redirectUri);
if (!claims.phoneNumber) {
throw new UnauthorizedException('هویت مشترک شماره موبایل ندارد');
}
const user = await this.prisma.adminUser.findFirst({
where: { mobile: { in: mobileVariants(claims.phoneNumber) }, isActive: true },
include: { userType: { include: { permissions: true } } },
});
if (!user) {
throw new UnauthorizedException('حساب مدیری با این شماره در این سامانه نیست');
}
const identity: IamIdentity = {
sub: claims.sub,
email: null,
phoneNumber: claims.phoneNumber,
firstName: null,
lastName: null,
sessionId: claims.sessionId,
browserTicket: null,
};
return this.issueAdminToken(user, identity, ip, userAgent);
}
centralLogoutUrl(requestedReturn?: string): string | null {
if (!this.iam.enabled) return null;
const redirect = pickExactUri(requestedReturn, [
envOrNull('IAM_ADMIN_POST_LOGOUT_REDIRECT_URI'),
envOrNull('IAM_ADMIN_BROWSER_RETURN_URL'),
...envList('IAM_ADMIN_ALLOWED_RETURN_URLS'),
]);
const clientId = envOrNull('IAM_CLIENT_ID');
if (!redirect || !clientId) return null;
const url = new URL(`${this.iam.issuer}/oauth/logout`);
url.searchParams.set('client_id', clientId);
url.searchParams.set('post_logout_redirect_uri', redirect);
return url.toString();
}
private async issueAdminToken(
user: {
id: string;
fullName: string;
mobile: string;
role: string;
userTypeId: number | null;
branchId: string | null;
userType: { permissions: { rid: string }[] } | null;
},
identity: IamIdentity | undefined,
ip?: string,
userAgent?: string,
) {
const jti = this.sessions.newTokenId();
const apiToken = await this.jwt.signAsync({
sub: user.id,
mobile: user.mobile,
...(jti ? { jti } : {}),
});
if (jti) {
await this.sessions.record({
jti,
adminUserId: user.id,
iamSessionId: identity?.sessionId ?? null,
iamSub: identity?.sub ?? null,
ipAddress: ip ?? null,
userAgent: userAgent ?? null,
});
}
return {
id: user.id,
name: user.fullName,
@@ -88,6 +214,27 @@ export class AuthService {
};
}
private ssoSecret(): string {
return envOrNull('JWT_SECRET') || envOr('IAM_CLIENT_SECRET', 'iam-sso');
}
private readSsoCookie(value: string | null): { state: string; verifier: string; redirectUri: string } | null {
if (!value || !value.includes('.')) return null;
const split = value.lastIndexOf('.');
const payload = value.slice(0, split);
const sig = value.slice(split + 1);
const expected = createHmac('sha256', this.ssoSecret()).update(payload).digest('base64url');
if (expected.length !== sig.length) return null;
let same = 0;
for (let i = 0; i < expected.length; i++) same |= expected.charCodeAt(i) ^ sig.charCodeAt(i);
if (same !== 0) return null;
try {
return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
} catch {
return null;
}
}
/**
* Password check, optionally delegated to the central identity service.
*
@@ -170,3 +317,11 @@ export class AuthService {
};
}
}
function mobileVariants(raw: string): string[] {
const digits = raw.replace(/\D/g, '');
const variants = new Set<string>([raw.trim(), digits]);
if (digits.startsWith('98') && digits.length >= 12) variants.add(`0${digits.slice(2)}`);
if (digits.startsWith('0') && digits.length === 11) variants.add(`98${digits.slice(1)}`);
return [...variants].filter((value) => value !== '');
}