@open-mercato/core 0.11.1-develop.8531.1.9c9f5e2b21 → 0.11.1-develop.8533.1.c51008db92
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/auth/api/login.js +3 -1
- package/dist/modules/auth/api/login.js.map +2 -2
- package/dist/modules/customers/commands/companies.js +8 -5
- package/dist/modules/customers/commands/companies.js.map +2 -2
- package/dist/modules/customers/commands/people.js +10 -7
- package/dist/modules/customers/commands/people.js.map +2 -2
- package/dist/modules/customers/commands/shared.js +6 -4
- package/dist/modules/customers/commands/shared.js.map +2 -2
- package/dist/modules/sales/commands/documents.js +52 -22
- package/dist/modules/sales/commands/documents.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/api/login.ts +10 -1
- package/src/modules/customers/commands/companies.ts +14 -7
- package/src/modules/customers/commands/people.ts +16 -9
- package/src/modules/customers/commands/shared.ts +7 -4
- package/src/modules/sales/commands/documents.ts +88 -38
package/.turbo/turbo-build.log
CHANGED
|
@@ -257,6 +257,8 @@ async function handleLoginRequest(req) {
|
|
|
257
257
|
const authTokenReplacedByInterceptor = authTokenForCookie !== token;
|
|
258
258
|
const res = NextResponse.json(interceptedBody, { status: interceptedResponse.statusCode });
|
|
259
259
|
res.cookies.set("auth_token", authTokenForCookie, { httpOnly: true, path: "/", sameSite: "lax", secure: process.env.NODE_ENV === "production", maxAge: accessTokenMaxAgeSeconds });
|
|
260
|
+
res.cookies.set("om_selected_org", "", { path: "/", maxAge: 0 });
|
|
261
|
+
res.cookies.set("om_selected_tenant", "", { path: "/", maxAge: 0 });
|
|
260
262
|
if (remember && refreshTokenForCookie) {
|
|
261
263
|
const expiresAt = new Date(Date.now() + rememberMeDays * 24 * 60 * 60 * 1e3);
|
|
262
264
|
res.cookies.set("session_token", refreshTokenForCookie, { httpOnly: true, path: "/", sameSite: "lax", secure: process.env.NODE_ENV === "production", expires: expiresAt });
|
|
@@ -283,7 +285,7 @@ const loginErrorSchema = z.object({
|
|
|
283
285
|
});
|
|
284
286
|
const loginMethodDoc = {
|
|
285
287
|
summary: "Authenticate user credentials",
|
|
286
|
-
description: "Validates the submitted credentials and issues a bearer token cookie for subsequent API calls.",
|
|
288
|
+
description: "Validates the submitted credentials and issues a bearer token cookie for subsequent API calls. A successful login also clears the organization-scope selection cookies (`om_selected_org`, `om_selected_tenant`) so a selection left by a previous user in the same browser cannot re-scope the new session; failed logins leave them untouched.",
|
|
287
289
|
tags: ["Authentication & Accounts"],
|
|
288
290
|
requestBody: {
|
|
289
291
|
contentType: "application/x-www-form-urlencoded",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/auth/api/login.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { userLoginSchema } from '@open-mercato/core/modules/auth/data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { signJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { EventBus } from '@open-mercato/events/types'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'\nimport { checkAuthRateLimit, resetAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'\nimport { runCustomRouteAfterInterceptors } from '@open-mercato/shared/lib/crud/custom-route-interceptor'\nimport { sanitizeRedirectPath } from '@open-mercato/core/modules/auth/lib/safeRedirect'\nimport { getAppBaseUrl, isCrossSiteBrowserRequest } from '@open-mercato/shared/lib/url'\nimport { handleAuthRouteError } from '@open-mercato/core/modules/auth/api/routeError'\nimport { isAuthSessionRejectedError } from '@open-mercato/core/modules/auth/lib/sessionEligibility'\nimport { isStaffTenantActive } from '@open-mercato/core/modules/auth/lib/tenantEligibility'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('auth.api')\n\nfunction reportLoginFailure(\n error: unknown,\n code: 'auth.login_interceptor_failed' | 'auth.login_revoke_failed',\n message: string,\n attributes?: Record<string, string | number | boolean>,\n): void {\n try {\n logger.error(message, { err: error, code, ...(attributes ?? {}) })\n } catch {\n // Never let logging prevent the fail-closed response.\n }\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'auth',\n code,\n ...(attributes ? { attributes } : {}),\n })\n } catch (telemetryError) {\n try {\n logger.warn('Failed to report auth login error to telemetry', { err: telemetryError, code })\n } catch {\n // Never let telemetry prevent the fail-closed response.\n }\n }\n}\n\nconst loginRateLimitConfig = readEndpointRateLimitConfig('LOGIN', {\n points: 5, duration: 60, blockDuration: 60, keyPrefix: 'login',\n})\nconst loginIpRateLimitConfig = readEndpointRateLimitConfig('LOGIN_IP', {\n points: 20, duration: 60, blockDuration: 60, keyPrefix: 'login-ip',\n})\n\nexport const metadata = { requireAuth: false }\n\n// validation comes from userLoginSchema\n\ntype ParsedLoginForm = {\n email: string\n password: string\n remember: boolean\n tenantIdRaw: string\n requiredRoles: string[]\n redirectTo: string\n}\n\nfunction parseRequiredRoles(rawValue: string): string[] {\n return rawValue\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n}\n\nasync function parseLoginForm(req: Request): Promise<ParsedLoginForm> {\n const rawContentType = req.headers.get('content-type') ?? ''\n const contentType = rawContentType.split(';')[0].trim().toLowerCase()\n\n try {\n if (contentType === 'application/x-www-form-urlencoded') {\n const body = await req.text()\n const params = new URLSearchParams(body)\n const requireRoleRaw = String(params.get('requireRole') ?? params.get('role') ?? '').trim()\n return {\n email: String(params.get('email') ?? ''),\n password: String(params.get('password') ?? ''),\n remember: parseBooleanToken(params.get('remember')) === true,\n tenantIdRaw: String(params.get('tenantId') ?? params.get('tenant') ?? '').trim(),\n requiredRoles: requireRoleRaw ? parseRequiredRoles(requireRoleRaw) : [],\n redirectTo: String(params.get('redirect') ?? ''),\n }\n }\n\n const form = await req.formData()\n const requireRoleRaw = String(form.get('requireRole') ?? form.get('role') ?? '').trim()\n return {\n email: String(form.get('email') ?? ''),\n password: String(form.get('password') ?? ''),\n remember: parseBooleanToken(form.get('remember')?.toString()) === true,\n tenantIdRaw: String(form.get('tenantId') ?? form.get('tenant') ?? '').trim(),\n requiredRoles: requireRoleRaw ? parseRequiredRoles(requireRoleRaw) : [],\n redirectTo: String(form.get('redirect') ?? ''),\n }\n } catch {\n return {\n email: '',\n password: '',\n remember: false,\n tenantIdRaw: '',\n requiredRoles: [],\n redirectTo: '',\n }\n }\n}\n\n// Resolving translations can itself be what failed, so the generic message is\n// recovered defensively \u2014 the error path must never throw a second time.\nasync function resolveGenericLoginError(): Promise<string> {\n try {\n const { translate } = await resolveTranslations()\n return translate('auth.login.errors.generic', 'An error occurred. Please try again.')\n } catch {\n return 'An error occurred. Please try again.'\n }\n}\n\nexport async function POST(req: Request) {\n try {\n return await handleLoginRequest(req)\n } catch (error) {\n return handleAuthRouteError(error, {\n scope: 'auth.login',\n message: await resolveGenericLoginError(),\n })\n }\n}\n\nasync function handleLoginRequest(req: Request) {\n const { translate } = await resolveTranslations()\n if (isCrossSiteBrowserRequest(req)) {\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.crossSiteRequest', 'This sign-in request did not come from this application. Open the sign-in page and try again.') }, { status: 403 })\n }\n const { email, password, remember, tenantIdRaw, requiredRoles, redirectTo } = await parseLoginForm(req)\n // Rate limit \u2014 two layers, both checked before validation and DB work\n const { error: rateLimitError, compoundKey: rateLimitCompoundKey } = await checkAuthRateLimit({\n req, ipConfig: loginIpRateLimitConfig, compoundConfig: loginRateLimitConfig, compoundIdentifier: email,\n isolateByIdentifierWithoutTrustedIp: true,\n })\n if (rateLimitError) return rateLimitError\n const parsed = userLoginSchema.pick({ email: true, password: true, tenantId: true }).safeParse({\n email,\n password,\n tenantId: tenantIdRaw || undefined,\n })\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.invalidCredentials', 'Invalid credentials') }, { status: 400 })\n }\n const container = await createRequestContainer()\n const auth = (container.resolve('authService') as AuthService)\n const tenantId = parsed.data.tenantId ?? null\n let user = null\n if (tenantId) {\n user = await auth.findUserByEmailAndTenant(parsed.data.email, tenantId)\n } else {\n const users = await auth.findUsersByEmail(parsed.data.email)\n // Never disclose that an email is registered across multiple tenants \u2014 a\n // password-independent 400-vs-401 response is an account/topology oracle\n // (issue #2242). Treat an ambiguous match as no resolvable user and fall\n // through to the uniform invalid-credentials path; tenant-selection\n // guidance is delivered out-of-band via the activation/login link.\n user = users.length === 1 ? users[0] : null\n }\n // Always verify the password \u2014 verifyPassword runs a constant-time bcrypt\n // comparison even when the user is missing or has no hash \u2014 so unknown-email,\n // wrong-password, and multi-tenant cases return an identical 401 with\n // identical latency.\n const ok = await auth.verifyPassword(user, parsed.data.password)\n const tenantActive = user ? await isStaffTenantActive(container.resolve('em'), user.tenantId) : false\n if (!user || !ok || user.isConfirmed === false || !tenantActive) {\n // The 401 body stays identical for every branch so the response never reveals\n // which one fired. `reason` goes to the audit stream instead, where separating a\n // deactivated account from a mistyped password is the whole point \u2014 otherwise\n // repeated attempts against a disabled account look like ordinary fat-fingering.\n let reason: string\n if (user && user.isConfirmed === false) reason = 'account_deactivated'\n else if (user && !tenantActive) reason = 'tenant_unavailable'\n else if (user?.passwordHash) reason = 'invalid_password'\n else reason = 'invalid_credentials'\n void emitAuthEvent('auth.login.failed', { email: parsed.data.email, reason }).catch(() => undefined)\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.invalidCredentials', 'Invalid email or password') }, { status: 401 })\n }\n // Optional role requirement\n if (requiredRoles.length) {\n const userRoleNames = await auth.getUserRoles(user, tenantId ?? (user.tenantId ? String(user.tenantId) : null))\n const authorized = requiredRoles.some(r => userRoleNames.includes(r))\n if (!authorized) {\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.permissionDenied', 'Not authorized for this area') }, { status: 403 })\n }\n }\n await auth.updateLastLoginAt(user)\n // Reset rate limit counter on successful login so legitimate users aren't penalized for prior typos\n if (rateLimitCompoundKey) {\n await resetAuthRateLimit(rateLimitCompoundKey, loginRateLimitConfig)\n }\n const resolvedTenantId = tenantId ?? (user.tenantId ? String(user.tenantId) : null)\n const userRoleNames = await auth.getUserRoles(user, resolvedTenantId)\n try {\n const eventBus = (container.resolve('eventBus') as EventBus)\n void eventBus.emitEvent('query_index.coverage.warmup', {\n tenantId: resolvedTenantId,\n }).catch(() => undefined)\n } catch {\n // optional warmup\n }\n const rememberMeDays = Number(process.env.REMEMBER_ME_DAYS || '30')\n const accessTokenMaxAgeSeconds = 60 * 60 * 8\n const sessionExpiresAt = remember\n ? new Date(Date.now() + rememberMeDays * 24 * 60 * 60 * 1000)\n : new Date(Date.now() + accessTokenMaxAgeSeconds * 1000)\n let createdSession: Awaited<ReturnType<AuthService['createSession']>>\n try {\n createdSession = await auth.createSession(user, sessionExpiresAt)\n } catch (error) {\n if (!isAuthSessionRejectedError(error)) throw error\n void emitAuthEvent('auth.login.failed', { email: parsed.data.email, reason: 'account_deactivated' }).catch(() => undefined)\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.invalidCredentials', 'Invalid email or password') }, { status: 401 })\n }\n const { session: loginSession, token: sessionRefreshToken } = createdSession\n const token = signJwt({\n sub: String(user.id),\n sid: String(loginSession.id),\n tenantId: resolvedTenantId,\n orgId: user.organizationId ? String(user.organizationId) : null,\n email: user.email,\n roles: userRoleNames\n })\n const responseData: { ok: true; token: string; redirect: string; refreshToken?: string } = {\n ok: true,\n token,\n redirect: sanitizeRedirectPath(redirectTo, getAppBaseUrl(req), '/backend'),\n }\n if (remember) {\n responseData.refreshToken = sessionRefreshToken\n }\n const em = container.resolve('em')\n const interceptedResponse = await runCustomRouteAfterInterceptors({\n routePath: 'auth/login',\n method: 'POST',\n request: {\n method: 'POST',\n url: req.url,\n body: {\n email: parsed.data.email,\n tenantId: parsed.data.tenantId ?? undefined,\n remember,\n requireRole: requiredRoles.length > 0 ? requiredRoles : undefined,\n },\n headers: Object.fromEntries(req.headers.entries()),\n },\n response: {\n statusCode: 200,\n body: responseData,\n headers: {},\n },\n context: {\n em,\n container,\n },\n })\n if (!interceptedResponse.ok) {\n const interceptorError = new Error(`Login after-interceptor failed with status ${interceptedResponse.statusCode}`)\n reportLoginFailure(\n interceptorError,\n 'auth.login_interceptor_failed',\n 'Login after-interceptor failed; revoking provisional session and denying login',\n { statusCode: interceptedResponse.statusCode },\n )\n try {\n await auth.deleteSessionById(String(loginSession.id))\n } catch (error) {\n reportLoginFailure(\n error,\n 'auth.login_revoke_failed',\n 'Failed to revoke provisional session after login after-interceptor failure',\n )\n }\n void emitAuthEvent('auth.login.failed', {\n email: parsed.data.email,\n reason: 'after_interceptor_failed',\n }).catch(() => undefined)\n return NextResponse.json(\n { ok: false, error: translate('auth.login.errors.generic', 'An error occurred. Please try again.') },\n { status: interceptedResponse.statusCode },\n )\n }\n void emitAuthEvent('auth.login.success', { id: String(user.id), email: user.email, tenantId: resolvedTenantId, organizationId: user.organizationId ? String(user.organizationId) : null }).catch(() => undefined)\n\n const interceptedBody = interceptedResponse.body\n const authTokenForCookie = typeof interceptedBody.token === 'string' && interceptedBody.token.length > 0\n ? interceptedBody.token\n : token\n const refreshTokenForCookie = typeof interceptedBody.refreshToken === 'string'\n ? interceptedBody.refreshToken\n : undefined\n\n // An interceptor that swaps the issued token (the MFA challenge hands back a provisional\n // `mfa_pending` token) has not completed authentication. Any `session_token` still in the\n // browser from an earlier login would let `GET /api/auth/session/refresh` mint a full staff\n // token and skip the outstanding second factor, so it is cleared alongside the swap.\n const authTokenReplacedByInterceptor = authTokenForCookie !== token\n\n const res = NextResponse.json(interceptedBody, { status: interceptedResponse.statusCode })\n res.cookies.set('auth_token', authTokenForCookie, { httpOnly: true, path: '/', sameSite: 'lax', secure: process.env.NODE_ENV === 'production', maxAge: accessTokenMaxAgeSeconds })\n if (remember && refreshTokenForCookie) {\n const expiresAt = new Date(Date.now() + rememberMeDays * 24 * 60 * 60 * 1000)\n res.cookies.set('session_token', refreshTokenForCookie, { httpOnly: true, path: '/', sameSite: 'lax', secure: process.env.NODE_ENV === 'production', expires: expiresAt })\n } else if (!remember && !authTokenReplacedByInterceptor) {\n res.cookies.set('session_token', sessionRefreshToken, { httpOnly: true, path: '/', sameSite: 'lax', secure: process.env.NODE_ENV === 'production', maxAge: accessTokenMaxAgeSeconds })\n } else if (authTokenReplacedByInterceptor) {\n res.cookies.set('session_token', '', { httpOnly: true, path: '/', sameSite: 'lax', secure: process.env.NODE_ENV === 'production', maxAge: 0 })\n }\n return res\n}\n\nconst loginRequestSchema = userLoginSchema.extend({\n password: z.string().min(6).describe('User password'),\n remember: z.enum(['on', '1', 'true']).optional().describe('Persist the session (submit `on`, `1`, or `true`).'),\n}).describe('Login form payload')\n\nconst loginSuccessSchema = z.object({\n ok: z.literal(true),\n token: z.string().describe('JWT token issued for subsequent API calls'),\n redirect: z.string().nullable().describe('Next location the client should navigate to'),\n refreshToken: z.string().optional().describe('Long-lived refresh token for obtaining new access tokens (only present when remember=true)'),\n})\n\nconst loginErrorSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n})\n\nconst loginMethodDoc: OpenApiMethodDoc = {\n summary: 'Authenticate user credentials',\n description: 'Validates the submitted credentials and issues a bearer token cookie for subsequent API calls.',\n tags: ['Authentication & Accounts'],\n requestBody: {\n contentType: 'application/x-www-form-urlencoded',\n schema: loginRequestSchema,\n description: 'Form-encoded payload captured from the login form.',\n },\n responses: [\n {\n status: 200,\n description: 'Authentication succeeded',\n schema: loginSuccessSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: loginErrorSchema },\n { status: 401, description: 'Invalid credentials', schema: loginErrorSchema },\n { status: 403, description: 'User lacks required role, or the request was submitted cross-site', schema: loginErrorSchema },\n { status: 429, description: 'Too many login attempts', schema: rateLimitErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Authenticate user credentials',\n description: 'Accepts login form submissions and manages cookie/session issuance.',\n methods: {\n POST: loginMethodDoc,\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AAEvC,SAAS,eAAe;AACxB,SAAS,2BAA2B;AAEpC,SAAS,yBAAyB;AAClC,SAAS,qBAAqB;AAC9B,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB,0BAA0B;AACvD,SAAS,uCAAuC;AAChD,SAAS,4BAA4B;AACrC,SAAS,eAAe,iCAAiC;AACzD,SAAS,4BAA4B;AACrC,SAAS,kCAAkC;AAC3C,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,UAAU;AAEtC,SAAS,mBACP,OACA,MACA,SACA,YACM;AACN,MAAI;AACF,WAAO,MAAM,SAAS,EAAE,KAAK,OAAO,MAAM,GAAI,cAAc,CAAC,EAAG,CAAC;AAAA,EACnE,QAAQ;AAAA,EAER;AACA,MAAI;AACF,wBAAoB,GAAG,YAAY,OAAO;AAAA,MACxC,QAAQ;AAAA,MACR;AAAA,MACA,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;AAAA,IACrC,CAAC;AAAA,EACH,SAAS,gBAAgB;AACvB,QAAI;AACF,aAAO,KAAK,kDAAkD,EAAE,KAAK,gBAAgB,KAAK,CAAC;AAAA,IAC7F,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEA,MAAM,uBAAuB,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,cAAc,QAAQ,yBAAyB,CAAC;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { userLoginSchema } from '@open-mercato/core/modules/auth/data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { signJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { EventBus } from '@open-mercato/events/types'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'\nimport { checkAuthRateLimit, resetAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'\nimport { runCustomRouteAfterInterceptors } from '@open-mercato/shared/lib/crud/custom-route-interceptor'\nimport { sanitizeRedirectPath } from '@open-mercato/core/modules/auth/lib/safeRedirect'\nimport { getAppBaseUrl, isCrossSiteBrowserRequest } from '@open-mercato/shared/lib/url'\nimport { handleAuthRouteError } from '@open-mercato/core/modules/auth/api/routeError'\nimport { isAuthSessionRejectedError } from '@open-mercato/core/modules/auth/lib/sessionEligibility'\nimport { isStaffTenantActive } from '@open-mercato/core/modules/auth/lib/tenantEligibility'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('auth.api')\n\nfunction reportLoginFailure(\n error: unknown,\n code: 'auth.login_interceptor_failed' | 'auth.login_revoke_failed',\n message: string,\n attributes?: Record<string, string | number | boolean>,\n): void {\n try {\n logger.error(message, { err: error, code, ...(attributes ?? {}) })\n } catch {\n // Never let logging prevent the fail-closed response.\n }\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'auth',\n code,\n ...(attributes ? { attributes } : {}),\n })\n } catch (telemetryError) {\n try {\n logger.warn('Failed to report auth login error to telemetry', { err: telemetryError, code })\n } catch {\n // Never let telemetry prevent the fail-closed response.\n }\n }\n}\n\nconst loginRateLimitConfig = readEndpointRateLimitConfig('LOGIN', {\n points: 5, duration: 60, blockDuration: 60, keyPrefix: 'login',\n})\nconst loginIpRateLimitConfig = readEndpointRateLimitConfig('LOGIN_IP', {\n points: 20, duration: 60, blockDuration: 60, keyPrefix: 'login-ip',\n})\n\nexport const metadata = { requireAuth: false }\n\n// validation comes from userLoginSchema\n\ntype ParsedLoginForm = {\n email: string\n password: string\n remember: boolean\n tenantIdRaw: string\n requiredRoles: string[]\n redirectTo: string\n}\n\nfunction parseRequiredRoles(rawValue: string): string[] {\n return rawValue\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n}\n\nasync function parseLoginForm(req: Request): Promise<ParsedLoginForm> {\n const rawContentType = req.headers.get('content-type') ?? ''\n const contentType = rawContentType.split(';')[0].trim().toLowerCase()\n\n try {\n if (contentType === 'application/x-www-form-urlencoded') {\n const body = await req.text()\n const params = new URLSearchParams(body)\n const requireRoleRaw = String(params.get('requireRole') ?? params.get('role') ?? '').trim()\n return {\n email: String(params.get('email') ?? ''),\n password: String(params.get('password') ?? ''),\n remember: parseBooleanToken(params.get('remember')) === true,\n tenantIdRaw: String(params.get('tenantId') ?? params.get('tenant') ?? '').trim(),\n requiredRoles: requireRoleRaw ? parseRequiredRoles(requireRoleRaw) : [],\n redirectTo: String(params.get('redirect') ?? ''),\n }\n }\n\n const form = await req.formData()\n const requireRoleRaw = String(form.get('requireRole') ?? form.get('role') ?? '').trim()\n return {\n email: String(form.get('email') ?? ''),\n password: String(form.get('password') ?? ''),\n remember: parseBooleanToken(form.get('remember')?.toString()) === true,\n tenantIdRaw: String(form.get('tenantId') ?? form.get('tenant') ?? '').trim(),\n requiredRoles: requireRoleRaw ? parseRequiredRoles(requireRoleRaw) : [],\n redirectTo: String(form.get('redirect') ?? ''),\n }\n } catch {\n return {\n email: '',\n password: '',\n remember: false,\n tenantIdRaw: '',\n requiredRoles: [],\n redirectTo: '',\n }\n }\n}\n\n// Resolving translations can itself be what failed, so the generic message is\n// recovered defensively \u2014 the error path must never throw a second time.\nasync function resolveGenericLoginError(): Promise<string> {\n try {\n const { translate } = await resolveTranslations()\n return translate('auth.login.errors.generic', 'An error occurred. Please try again.')\n } catch {\n return 'An error occurred. Please try again.'\n }\n}\n\nexport async function POST(req: Request) {\n try {\n return await handleLoginRequest(req)\n } catch (error) {\n return handleAuthRouteError(error, {\n scope: 'auth.login',\n message: await resolveGenericLoginError(),\n })\n }\n}\n\nasync function handleLoginRequest(req: Request) {\n const { translate } = await resolveTranslations()\n if (isCrossSiteBrowserRequest(req)) {\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.crossSiteRequest', 'This sign-in request did not come from this application. Open the sign-in page and try again.') }, { status: 403 })\n }\n const { email, password, remember, tenantIdRaw, requiredRoles, redirectTo } = await parseLoginForm(req)\n // Rate limit \u2014 two layers, both checked before validation and DB work\n const { error: rateLimitError, compoundKey: rateLimitCompoundKey } = await checkAuthRateLimit({\n req, ipConfig: loginIpRateLimitConfig, compoundConfig: loginRateLimitConfig, compoundIdentifier: email,\n isolateByIdentifierWithoutTrustedIp: true,\n })\n if (rateLimitError) return rateLimitError\n const parsed = userLoginSchema.pick({ email: true, password: true, tenantId: true }).safeParse({\n email,\n password,\n tenantId: tenantIdRaw || undefined,\n })\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.invalidCredentials', 'Invalid credentials') }, { status: 400 })\n }\n const container = await createRequestContainer()\n const auth = (container.resolve('authService') as AuthService)\n const tenantId = parsed.data.tenantId ?? null\n let user = null\n if (tenantId) {\n user = await auth.findUserByEmailAndTenant(parsed.data.email, tenantId)\n } else {\n const users = await auth.findUsersByEmail(parsed.data.email)\n // Never disclose that an email is registered across multiple tenants \u2014 a\n // password-independent 400-vs-401 response is an account/topology oracle\n // (issue #2242). Treat an ambiguous match as no resolvable user and fall\n // through to the uniform invalid-credentials path; tenant-selection\n // guidance is delivered out-of-band via the activation/login link.\n user = users.length === 1 ? users[0] : null\n }\n // Always verify the password \u2014 verifyPassword runs a constant-time bcrypt\n // comparison even when the user is missing or has no hash \u2014 so unknown-email,\n // wrong-password, and multi-tenant cases return an identical 401 with\n // identical latency.\n const ok = await auth.verifyPassword(user, parsed.data.password)\n const tenantActive = user ? await isStaffTenantActive(container.resolve('em'), user.tenantId) : false\n if (!user || !ok || user.isConfirmed === false || !tenantActive) {\n // The 401 body stays identical for every branch so the response never reveals\n // which one fired. `reason` goes to the audit stream instead, where separating a\n // deactivated account from a mistyped password is the whole point \u2014 otherwise\n // repeated attempts against a disabled account look like ordinary fat-fingering.\n let reason: string\n if (user && user.isConfirmed === false) reason = 'account_deactivated'\n else if (user && !tenantActive) reason = 'tenant_unavailable'\n else if (user?.passwordHash) reason = 'invalid_password'\n else reason = 'invalid_credentials'\n void emitAuthEvent('auth.login.failed', { email: parsed.data.email, reason }).catch(() => undefined)\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.invalidCredentials', 'Invalid email or password') }, { status: 401 })\n }\n // Optional role requirement\n if (requiredRoles.length) {\n const userRoleNames = await auth.getUserRoles(user, tenantId ?? (user.tenantId ? String(user.tenantId) : null))\n const authorized = requiredRoles.some(r => userRoleNames.includes(r))\n if (!authorized) {\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.permissionDenied', 'Not authorized for this area') }, { status: 403 })\n }\n }\n await auth.updateLastLoginAt(user)\n // Reset rate limit counter on successful login so legitimate users aren't penalized for prior typos\n if (rateLimitCompoundKey) {\n await resetAuthRateLimit(rateLimitCompoundKey, loginRateLimitConfig)\n }\n const resolvedTenantId = tenantId ?? (user.tenantId ? String(user.tenantId) : null)\n const userRoleNames = await auth.getUserRoles(user, resolvedTenantId)\n try {\n const eventBus = (container.resolve('eventBus') as EventBus)\n void eventBus.emitEvent('query_index.coverage.warmup', {\n tenantId: resolvedTenantId,\n }).catch(() => undefined)\n } catch {\n // optional warmup\n }\n const rememberMeDays = Number(process.env.REMEMBER_ME_DAYS || '30')\n const accessTokenMaxAgeSeconds = 60 * 60 * 8\n const sessionExpiresAt = remember\n ? new Date(Date.now() + rememberMeDays * 24 * 60 * 60 * 1000)\n : new Date(Date.now() + accessTokenMaxAgeSeconds * 1000)\n let createdSession: Awaited<ReturnType<AuthService['createSession']>>\n try {\n createdSession = await auth.createSession(user, sessionExpiresAt)\n } catch (error) {\n if (!isAuthSessionRejectedError(error)) throw error\n void emitAuthEvent('auth.login.failed', { email: parsed.data.email, reason: 'account_deactivated' }).catch(() => undefined)\n return NextResponse.json({ ok: false, error: translate('auth.login.errors.invalidCredentials', 'Invalid email or password') }, { status: 401 })\n }\n const { session: loginSession, token: sessionRefreshToken } = createdSession\n const token = signJwt({\n sub: String(user.id),\n sid: String(loginSession.id),\n tenantId: resolvedTenantId,\n orgId: user.organizationId ? String(user.organizationId) : null,\n email: user.email,\n roles: userRoleNames\n })\n const responseData: { ok: true; token: string; redirect: string; refreshToken?: string } = {\n ok: true,\n token,\n redirect: sanitizeRedirectPath(redirectTo, getAppBaseUrl(req), '/backend'),\n }\n if (remember) {\n responseData.refreshToken = sessionRefreshToken\n }\n const em = container.resolve('em')\n const interceptedResponse = await runCustomRouteAfterInterceptors({\n routePath: 'auth/login',\n method: 'POST',\n request: {\n method: 'POST',\n url: req.url,\n body: {\n email: parsed.data.email,\n tenantId: parsed.data.tenantId ?? undefined,\n remember,\n requireRole: requiredRoles.length > 0 ? requiredRoles : undefined,\n },\n headers: Object.fromEntries(req.headers.entries()),\n },\n response: {\n statusCode: 200,\n body: responseData,\n headers: {},\n },\n context: {\n em,\n container,\n },\n })\n if (!interceptedResponse.ok) {\n const interceptorError = new Error(`Login after-interceptor failed with status ${interceptedResponse.statusCode}`)\n reportLoginFailure(\n interceptorError,\n 'auth.login_interceptor_failed',\n 'Login after-interceptor failed; revoking provisional session and denying login',\n { statusCode: interceptedResponse.statusCode },\n )\n try {\n await auth.deleteSessionById(String(loginSession.id))\n } catch (error) {\n reportLoginFailure(\n error,\n 'auth.login_revoke_failed',\n 'Failed to revoke provisional session after login after-interceptor failure',\n )\n }\n void emitAuthEvent('auth.login.failed', {\n email: parsed.data.email,\n reason: 'after_interceptor_failed',\n }).catch(() => undefined)\n return NextResponse.json(\n { ok: false, error: translate('auth.login.errors.generic', 'An error occurred. Please try again.') },\n { status: interceptedResponse.statusCode },\n )\n }\n void emitAuthEvent('auth.login.success', { id: String(user.id), email: user.email, tenantId: resolvedTenantId, organizationId: user.organizationId ? String(user.organizationId) : null }).catch(() => undefined)\n\n const interceptedBody = interceptedResponse.body\n const authTokenForCookie = typeof interceptedBody.token === 'string' && interceptedBody.token.length > 0\n ? interceptedBody.token\n : token\n const refreshTokenForCookie = typeof interceptedBody.refreshToken === 'string'\n ? interceptedBody.refreshToken\n : undefined\n\n // An interceptor that swaps the issued token (the MFA challenge hands back a provisional\n // `mfa_pending` token) has not completed authentication. Any `session_token` still in the\n // browser from an earlier login would let `GET /api/auth/session/refresh` mint a full staff\n // token and skip the outstanding second factor, so it is cleared alongside the swap.\n const authTokenReplacedByInterceptor = authTokenForCookie !== token\n\n const res = NextResponse.json(interceptedBody, { status: interceptedResponse.statusCode })\n res.cookies.set('auth_token', authTokenForCookie, { httpOnly: true, path: '/', sameSite: 'lax', secure: process.env.NODE_ENV === 'production', maxAge: accessTokenMaxAgeSeconds })\n // A successful login changes the browser's identity. The scope-selection cookies\n // (`om_selected_org`, `om_selected_tenant`) outlive sessions by design (30-day\n // client-side max-age) and `applySuperAdminScope` honors them for super-admins\n // without checking who made the selection, so a selection left by a previous user\n // would silently re-scope this one under the previous user's tenant/organization.\n // Expire both next to the identity cookies, mirroring logout (#7465). Refresh and\n // profile re-issue tokens for the SAME user and deliberately keep the selection.\n res.cookies.set('om_selected_org', '', { path: '/', maxAge: 0 })\n res.cookies.set('om_selected_tenant', '', { path: '/', maxAge: 0 })\n if (remember && refreshTokenForCookie) {\n const expiresAt = new Date(Date.now() + rememberMeDays * 24 * 60 * 60 * 1000)\n res.cookies.set('session_token', refreshTokenForCookie, { httpOnly: true, path: '/', sameSite: 'lax', secure: process.env.NODE_ENV === 'production', expires: expiresAt })\n } else if (!remember && !authTokenReplacedByInterceptor) {\n res.cookies.set('session_token', sessionRefreshToken, { httpOnly: true, path: '/', sameSite: 'lax', secure: process.env.NODE_ENV === 'production', maxAge: accessTokenMaxAgeSeconds })\n } else if (authTokenReplacedByInterceptor) {\n res.cookies.set('session_token', '', { httpOnly: true, path: '/', sameSite: 'lax', secure: process.env.NODE_ENV === 'production', maxAge: 0 })\n }\n return res\n}\n\nconst loginRequestSchema = userLoginSchema.extend({\n password: z.string().min(6).describe('User password'),\n remember: z.enum(['on', '1', 'true']).optional().describe('Persist the session (submit `on`, `1`, or `true`).'),\n}).describe('Login form payload')\n\nconst loginSuccessSchema = z.object({\n ok: z.literal(true),\n token: z.string().describe('JWT token issued for subsequent API calls'),\n redirect: z.string().nullable().describe('Next location the client should navigate to'),\n refreshToken: z.string().optional().describe('Long-lived refresh token for obtaining new access tokens (only present when remember=true)'),\n})\n\nconst loginErrorSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n})\n\nconst loginMethodDoc: OpenApiMethodDoc = {\n summary: 'Authenticate user credentials',\n description: 'Validates the submitted credentials and issues a bearer token cookie for subsequent API calls. A successful login also clears the organization-scope selection cookies (`om_selected_org`, `om_selected_tenant`) so a selection left by a previous user in the same browser cannot re-scope the new session; failed logins leave them untouched.',\n tags: ['Authentication & Accounts'],\n requestBody: {\n contentType: 'application/x-www-form-urlencoded',\n schema: loginRequestSchema,\n description: 'Form-encoded payload captured from the login form.',\n },\n responses: [\n {\n status: 200,\n description: 'Authentication succeeded',\n schema: loginSuccessSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: loginErrorSchema },\n { status: 401, description: 'Invalid credentials', schema: loginErrorSchema },\n { status: 403, description: 'User lacks required role, or the request was submitted cross-site', schema: loginErrorSchema },\n { status: 429, description: 'Too many login attempts', schema: rateLimitErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Authenticate user credentials',\n description: 'Accepts login form submissions and manages cookie/session issuance.',\n methods: {\n POST: loginMethodDoc,\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AAEvC,SAAS,eAAe;AACxB,SAAS,2BAA2B;AAEpC,SAAS,yBAAyB;AAClC,SAAS,qBAAqB;AAC9B,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB,0BAA0B;AACvD,SAAS,uCAAuC;AAChD,SAAS,4BAA4B;AACrC,SAAS,eAAe,iCAAiC;AACzD,SAAS,4BAA4B;AACrC,SAAS,kCAAkC;AAC3C,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,UAAU;AAEtC,SAAS,mBACP,OACA,MACA,SACA,YACM;AACN,MAAI;AACF,WAAO,MAAM,SAAS,EAAE,KAAK,OAAO,MAAM,GAAI,cAAc,CAAC,EAAG,CAAC;AAAA,EACnE,QAAQ;AAAA,EAER;AACA,MAAI;AACF,wBAAoB,GAAG,YAAY,OAAO;AAAA,MACxC,QAAQ;AAAA,MACR;AAAA,MACA,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;AAAA,IACrC,CAAC;AAAA,EACH,SAAS,gBAAgB;AACvB,QAAI;AACF,aAAO,KAAK,kDAAkD,EAAE,KAAK,gBAAgB,KAAK,CAAC;AAAA,IAC7F,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEA,MAAM,uBAAuB,4BAA4B,SAAS;AAAA,EAChE,QAAQ;AAAA,EAAG,UAAU;AAAA,EAA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AAM,mBAAmB,EAAE,OAAO;AAAA,EAChC,IAAI,EAAE,QAAQ,KAAK;AAAA,EACnB,OAAO,EAAE,OAAO;AAClB,CAAC;AAED,MAAM,iBAAmC;AAAA,EACvC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,2BAA2B;AAAA,EAClC,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT;AAAA,MACE,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,QAAQ;AAAA,IACV;AAAA,EACF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,iBAAiB;AAAA,IAC1E,EAAE,QAAQ,KAAK,aAAa,uBAAuB,QAAQ,iBAAiB;AAAA,IAC5E,EAAE,QAAQ,KAAK,aAAa,qEAAqE,QAAQ,iBAAiB;AAAA,IAC1H,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,qBAAqB;AAAA,EACtF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS;AAAA,IACP,MAAM;AAAA,EACR;AACF;",
|
|
6
6
|
"names": ["requireRoleRaw", "userRoleNames"]
|
|
7
7
|
}
|
|
@@ -571,7 +571,7 @@ const createCompanyCommand = {
|
|
|
571
571
|
}
|
|
572
572
|
const restoredProfile = profile;
|
|
573
573
|
await withAtomicFlush(em, [
|
|
574
|
-
() => syncEntityTags(em, restoredEntity, after.tagIds)
|
|
574
|
+
() => syncEntityTags(em, restoredEntity, after.tagIds, { ignoreMissing: true })
|
|
575
575
|
], { transaction: true });
|
|
576
576
|
const restoreValues = buildCustomFieldResetMap(after.custom, void 0);
|
|
577
577
|
if (Object.keys(restoreValues).length) {
|
|
@@ -602,7 +602,7 @@ const updateCompanyCommand = {
|
|
|
602
602
|
const snapshot = await loadCompanySnapshot(em, parsed.id, ctx);
|
|
603
603
|
return snapshot ? { before: snapshot } : {};
|
|
604
604
|
},
|
|
605
|
-
async execute(rawInput, ctx) {
|
|
605
|
+
async execute(rawInput, ctx, ignoreMissingTags = false) {
|
|
606
606
|
const { parsed: parsedInput, custom } = parseWithCustomFields(companyUpdateSchema, rawInput);
|
|
607
607
|
const parsed = withExactAmounts(parsedInput, rawInput, ["annualRevenue"]);
|
|
608
608
|
const em = ctx.container.resolve("em").fork();
|
|
@@ -671,7 +671,7 @@ const updateCompanyCommand = {
|
|
|
671
671
|
record.updatedAt = /* @__PURE__ */ new Date();
|
|
672
672
|
}
|
|
673
673
|
},
|
|
674
|
-
() => syncEntityTags(em, record, parsed.tags)
|
|
674
|
+
() => syncEntityTags(em, record, parsed.tags, { ignoreMissing: ignoreMissingTags })
|
|
675
675
|
], { transaction: true });
|
|
676
676
|
await setCompanyCustomFields(ctx, record.id, profile.id, record.organizationId, record.tenantId, custom);
|
|
677
677
|
const de = ctx.container.resolve("dataEngine");
|
|
@@ -803,7 +803,7 @@ const updateCompanyCommand = {
|
|
|
803
803
|
profile.annualRevenue = before.profile.annualRevenue;
|
|
804
804
|
}
|
|
805
805
|
await em.flush();
|
|
806
|
-
await syncEntityTags(em, entity, before.tagIds);
|
|
806
|
+
await syncEntityTags(em, entity, before.tagIds, { ignoreMissing: true });
|
|
807
807
|
await em.flush();
|
|
808
808
|
await em.nativeDelete(CustomerDealCompanyLink, { company: entity });
|
|
809
809
|
if (before.deals?.length) {
|
|
@@ -872,6 +872,9 @@ const updateCompanyCommand = {
|
|
|
872
872
|
if (Object.keys(resetValues).length) {
|
|
873
873
|
await setCompanyCustomFields(ctx, entity.id, profile.id, entity.organizationId, entity.tenantId, resetValues);
|
|
874
874
|
}
|
|
875
|
+
},
|
|
876
|
+
redo({ input, ctx }) {
|
|
877
|
+
return updateCompanyCommand.execute(input, ctx, true);
|
|
875
878
|
}
|
|
876
879
|
};
|
|
877
880
|
const deleteCompanyCommand = {
|
|
@@ -1146,7 +1149,7 @@ const deleteCompanyCommand = {
|
|
|
1146
1149
|
let dealMap = /* @__PURE__ */ new Map();
|
|
1147
1150
|
let restoredLabelAssignments = [];
|
|
1148
1151
|
await withAtomicFlush(em, [
|
|
1149
|
-
() => syncEntityTags(em, entity, before.tagIds),
|
|
1152
|
+
() => syncEntityTags(em, entity, before.tagIds, { ignoreMissing: true }),
|
|
1150
1153
|
async () => {
|
|
1151
1154
|
const relatedDealIds = /* @__PURE__ */ new Set();
|
|
1152
1155
|
for (const link of beforeDeals) relatedDealIds.add(link.dealId);
|