@open-mercato/core 0.10.1-develop.7691.1.d8af406541 → 0.10.1-develop.7699.1.5236fabda0
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/autologin.js +3 -1
- package/dist/modules/auth/api/autologin.js.map +2 -2
- package/dist/modules/auth/api/login.js +4 -1
- package/dist/modules/auth/api/login.js.map +2 -2
- package/dist/modules/auth/lib/sessionIntegrity.js +2 -0
- package/dist/modules/auth/lib/sessionIntegrity.js.map +2 -2
- package/dist/modules/auth/lib/tenantEligibility.js +16 -0
- package/dist/modules/auth/lib/tenantEligibility.js.map +7 -0
- package/dist/modules/auth/services/authService.js +5 -0
- package/dist/modules/auth/services/authService.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/domain-mappings/[id]/health-check.js +5 -5
- package/dist/modules/customer_accounts/api/admin/domain-mappings/[id]/health-check.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/domain-mappings/[id]/verify.js +5 -5
- package/dist/modules/customer_accounts/api/admin/domain-mappings/[id]/verify.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/domain-mappings.js +36 -14
- package/dist/modules/customer_accounts/api/admin/domain-mappings.js.map +2 -2
- package/dist/modules/customer_accounts/api/login.js +2 -1
- package/dist/modules/customer_accounts/api/login.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerAuth.js +2 -0
- package/dist/modules/customer_accounts/lib/customerAuth.js.map +2 -2
- package/dist/modules/customer_accounts/lib/tenantEligibility.js +16 -0
- package/dist/modules/customer_accounts/lib/tenantEligibility.js.map +7 -0
- package/dist/modules/customer_accounts/services/customerInvitationService.js +2 -0
- package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerSessionService.js +2 -0
- package/dist/modules/customer_accounts/services/customerSessionService.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerTokenService.js +2 -0
- package/dist/modules/customer_accounts/services/customerTokenService.js.map +2 -2
- package/dist/modules/customer_accounts/services/domainMappingService.js +5 -2
- package/dist/modules/customer_accounts/services/domainMappingService.js.map +2 -2
- package/dist/modules/customers/components/linking/LinkEntityDialog.js +10 -2
- package/dist/modules/customers/components/linking/LinkEntityDialog.js.map +2 -2
- package/dist/modules/sales/backend/sales/documents/[id]/page.js +17 -3
- package/dist/modules/sales/backend/sales/documents/[id]/page.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/api/autologin.ts +3 -1
- package/src/modules/auth/api/login.ts +4 -1
- package/src/modules/auth/lib/sessionIntegrity.ts +2 -0
- package/src/modules/auth/lib/tenantEligibility.ts +17 -0
- package/src/modules/auth/services/authService.ts +5 -0
- package/src/modules/customer_accounts/api/admin/domain-mappings/[id]/health-check.ts +5 -5
- package/src/modules/customer_accounts/api/admin/domain-mappings/[id]/verify.ts +5 -5
- package/src/modules/customer_accounts/api/admin/domain-mappings.ts +38 -16
- package/src/modules/customer_accounts/api/login.ts +3 -1
- package/src/modules/customer_accounts/lib/customerAuth.ts +2 -0
- package/src/modules/customer_accounts/lib/tenantEligibility.ts +14 -0
- package/src/modules/customer_accounts/services/customerInvitationService.ts +2 -0
- package/src/modules/customer_accounts/services/customerSessionService.ts +2 -0
- package/src/modules/customer_accounts/services/customerTokenService.ts +2 -0
- package/src/modules/customer_accounts/services/domainMappingService.ts +3 -0
- package/src/modules/customers/components/linking/LinkEntityDialog.tsx +10 -2
- package/src/modules/sales/backend/sales/documents/[id]/page.tsx +15 -2
package/.turbo/turbo-build.log
CHANGED
|
@@ -6,6 +6,7 @@ import { buildSafeRedirectResponse, resolveTrustedRedirectBase } from "@open-mer
|
|
|
6
6
|
import { sanitizeRedirectPath } from "@open-mercato/core/modules/auth/lib/safeRedirect";
|
|
7
7
|
import { resolveAutoLoginCredentials } from "@open-mercato/core/modules/auth/lib/autologin";
|
|
8
8
|
import { emitAuthEvent } from "@open-mercato/core/modules/auth/events";
|
|
9
|
+
import { isStaffTenantActive } from "@open-mercato/core/modules/auth/lib/tenantEligibility";
|
|
9
10
|
const metadata = { requireAuth: false };
|
|
10
11
|
const accessTokenMaxAgeSeconds = 60 * 60 * 8;
|
|
11
12
|
const logger = createLogger("auth").child({ component: "autologin" });
|
|
@@ -31,7 +32,8 @@ async function GET(req) {
|
|
|
31
32
|
user = users.length === 1 ? users[0] : null;
|
|
32
33
|
}
|
|
33
34
|
const ok = await auth.verifyPassword(user, credentials.password);
|
|
34
|
-
|
|
35
|
+
const tenantActive = user ? await isStaffTenantActive(container.resolve("em"), user.tenantId) : false;
|
|
36
|
+
if (!user || !ok || !tenantActive) {
|
|
35
37
|
logger.warn("OM_AUTOLOGIN credentials did not resolve to a single valid user; falling back to login");
|
|
36
38
|
return buildSafeRedirectResponse(req, "/login");
|
|
37
39
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/auth/api/autologin.ts"],
|
|
4
|
-
"sourcesContent": ["import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { signJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { buildSafeRedirectResponse, resolveTrustedRedirectBase } from '@open-mercato/core/modules/auth/lib/requestRedirect'\nimport { sanitizeRedirectPath } from '@open-mercato/core/modules/auth/lib/safeRedirect'\nimport { resolveAutoLoginCredentials } from '@open-mercato/core/modules/auth/lib/autologin'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\n\nexport const metadata = { requireAuth: false }\n\nconst accessTokenMaxAgeSeconds = 60 * 60 * 8\nconst logger = createLogger('auth').child({ component: 'autologin' })\n\n// Demo-only convenience: when OM_AUTOLOGIN_* credentials are configured, sign the\n// visitor in with those credentials and redirect into the app. Gated entirely\n// behind env vars \u2014 the homepage only routes here when they are set. On any\n// failure (feature off, bad credentials) it falls back to the manual login form\n// so a misconfigured demo can never loop.\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const baseUrl = resolveTrustedRedirectBase(req) ?? url.origin\n const redirectTo = sanitizeRedirectPath(url.searchParams.get('redirect'), baseUrl, '/backend')\n\n const credentials = resolveAutoLoginCredentials()\n if (!credentials) {\n return buildSafeRedirectResponse(req, '/login')\n }\n\n // Already signed in \u2014 go straight to the app instead of re-issuing a session.\n const existing = await getAuthFromRequest(req)\n if (existing) {\n return buildSafeRedirectResponse(req, redirectTo)\n }\n\n const container = await createRequestContainer()\n const auth = container.resolve<AuthService>('authService')\n\n let user = null\n if (credentials.tenantId) {\n user = await auth.findUserByEmailAndTenant(credentials.email, credentials.tenantId)\n } else {\n const users = await auth.findUsersByEmail(credentials.email)\n user = users.length === 1 ? users[0] : null\n }\n\n const ok = await auth.verifyPassword(user, credentials.password)\n if (!user || !ok) {\n // Misconfigured demo credentials \u2014 never loop; drop to the manual form.\n logger.warn('OM_AUTOLOGIN credentials did not resolve to a single valid user; falling back to login')\n return buildSafeRedirectResponse(req, '/login')\n }\n\n const resolvedTenantId = credentials.tenantId ?? (user.tenantId ? String(user.tenantId) : null)\n const roles = await auth.getUserRoles(user, resolvedTenantId)\n await auth.updateLastLoginAt(user)\n const expiresAt = new Date(Date.now() + accessTokenMaxAgeSeconds * 1000)\n const { session } = await auth.createSession(user, expiresAt)\n const token = signJwt({\n sub: String(user.id),\n sid: String(session.id),\n tenantId: resolvedTenantId,\n orgId: user.organizationId ? String(user.organizationId) : null,\n email: user.email,\n roles,\n })\n void emitAuthEvent('auth.login.success', {\n id: String(user.id),\n email: user.email,\n tenantId: resolvedTenantId,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n }).catch(() => undefined)\n\n const res = buildSafeRedirectResponse(req, redirectTo)\n res.cookies.set('auth_token', token, {\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: accessTokenMaxAgeSeconds,\n })\n return res\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Demo autologin',\n methods: {\n GET: {\n summary: 'Auto sign-in using env-configured demo credentials',\n description:\n 'When OM_AUTOLOGIN_EMAIL / OM_AUTOLOGIN_PASSWORD are configured, signs the visitor in with those credentials and redirects into the app. Intended for single-tenant demo instances only. Falls back to the login page when disabled or misconfigured.',\n responses: [\n { status: 307, description: 'Redirect into the app (or to /login on failure)', mediaType: 'text/html' },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,2BAA2B,kCAAkC;AACtE,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,qBAAqB;
|
|
4
|
+
"sourcesContent": ["import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { signJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { buildSafeRedirectResponse, resolveTrustedRedirectBase } from '@open-mercato/core/modules/auth/lib/requestRedirect'\nimport { sanitizeRedirectPath } from '@open-mercato/core/modules/auth/lib/safeRedirect'\nimport { resolveAutoLoginCredentials } from '@open-mercato/core/modules/auth/lib/autologin'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\nimport { isStaffTenantActive } from '@open-mercato/core/modules/auth/lib/tenantEligibility'\n\nexport const metadata = { requireAuth: false }\n\nconst accessTokenMaxAgeSeconds = 60 * 60 * 8\nconst logger = createLogger('auth').child({ component: 'autologin' })\n\n// Demo-only convenience: when OM_AUTOLOGIN_* credentials are configured, sign the\n// visitor in with those credentials and redirect into the app. Gated entirely\n// behind env vars \u2014 the homepage only routes here when they are set. On any\n// failure (feature off, bad credentials) it falls back to the manual login form\n// so a misconfigured demo can never loop.\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const baseUrl = resolveTrustedRedirectBase(req) ?? url.origin\n const redirectTo = sanitizeRedirectPath(url.searchParams.get('redirect'), baseUrl, '/backend')\n\n const credentials = resolveAutoLoginCredentials()\n if (!credentials) {\n return buildSafeRedirectResponse(req, '/login')\n }\n\n // Already signed in \u2014 go straight to the app instead of re-issuing a session.\n const existing = await getAuthFromRequest(req)\n if (existing) {\n return buildSafeRedirectResponse(req, redirectTo)\n }\n\n const container = await createRequestContainer()\n const auth = container.resolve<AuthService>('authService')\n\n let user = null\n if (credentials.tenantId) {\n user = await auth.findUserByEmailAndTenant(credentials.email, credentials.tenantId)\n } else {\n const users = await auth.findUsersByEmail(credentials.email)\n user = users.length === 1 ? users[0] : null\n }\n\n const ok = await auth.verifyPassword(user, credentials.password)\n const tenantActive = user ? await isStaffTenantActive(container.resolve('em'), user.tenantId) : false\n if (!user || !ok || !tenantActive) {\n // Misconfigured demo credentials \u2014 never loop; drop to the manual form.\n logger.warn('OM_AUTOLOGIN credentials did not resolve to a single valid user; falling back to login')\n return buildSafeRedirectResponse(req, '/login')\n }\n\n const resolvedTenantId = credentials.tenantId ?? (user.tenantId ? String(user.tenantId) : null)\n const roles = await auth.getUserRoles(user, resolvedTenantId)\n await auth.updateLastLoginAt(user)\n const expiresAt = new Date(Date.now() + accessTokenMaxAgeSeconds * 1000)\n const { session } = await auth.createSession(user, expiresAt)\n const token = signJwt({\n sub: String(user.id),\n sid: String(session.id),\n tenantId: resolvedTenantId,\n orgId: user.organizationId ? String(user.organizationId) : null,\n email: user.email,\n roles,\n })\n void emitAuthEvent('auth.login.success', {\n id: String(user.id),\n email: user.email,\n tenantId: resolvedTenantId,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n }).catch(() => undefined)\n\n const res = buildSafeRedirectResponse(req, redirectTo)\n res.cookies.set('auth_token', token, {\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: accessTokenMaxAgeSeconds,\n })\n return res\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Demo autologin',\n methods: {\n GET: {\n summary: 'Auto sign-in using env-configured demo credentials',\n description:\n 'When OM_AUTOLOGIN_EMAIL / OM_AUTOLOGIN_PASSWORD are configured, signs the visitor in with those credentials and redirects into the app. Intended for single-tenant demo instances only. Falls back to the login page when disabled or misconfigured.',\n responses: [\n { status: 307, description: 'Redirect into the app (or to /login on failure)', mediaType: 'text/html' },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,2BAA2B,kCAAkC;AACtE,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AAE7B,MAAM,WAAW,EAAE,aAAa,MAAM;AAE7C,MAAM,2BAA2B,KAAK,KAAK;AAC3C,MAAM,SAAS,aAAa,MAAM,EAAE,MAAM,EAAE,WAAW,YAAY,CAAC;AAOpE,eAAsB,IAAI,KAAc;AACtC,QAAM,MAAM,IAAI,IAAI,IAAI,GAAG;AAC3B,QAAM,UAAU,2BAA2B,GAAG,KAAK,IAAI;AACvD,QAAM,aAAa,qBAAqB,IAAI,aAAa,IAAI,UAAU,GAAG,SAAS,UAAU;AAE7F,QAAM,cAAc,4BAA4B;AAChD,MAAI,CAAC,aAAa;AAChB,WAAO,0BAA0B,KAAK,QAAQ;AAAA,EAChD;AAGA,QAAM,WAAW,MAAM,mBAAmB,GAAG;AAC7C,MAAI,UAAU;AACZ,WAAO,0BAA0B,KAAK,UAAU;AAAA,EAClD;AAE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AA,EACtE,CAAC,EAAE,MAAM,MAAM,MAAS;AAExB,QAAM,MAAM,0BAA0B,KAAK,UAAU;AACrD,MAAI,QAAQ,IAAI,cAAc,OAAO;AAAA,IACnC,UAAU;AAAA,IACV,MAAM;AAAA,IACN,UAAU;AAAA,IACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,IACjC,QAAQ;AAAA,EACV,CAAC;AACD,SAAO;AACT;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aACE;AAAA,MACF,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,mDAAmD,WAAW,YAAY;AAAA,MACxG;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -13,6 +13,7 @@ import { runCustomRouteAfterInterceptors } from "@open-mercato/shared/lib/crud/c
|
|
|
13
13
|
import { sanitizeRedirectPath } from "@open-mercato/core/modules/auth/lib/safeRedirect";
|
|
14
14
|
import { getAppBaseUrl, isCrossSiteBrowserRequest } from "@open-mercato/shared/lib/url";
|
|
15
15
|
import { handleAuthRouteError } from "@open-mercato/core/modules/auth/api/routeError";
|
|
16
|
+
import { isStaffTenantActive } from "@open-mercato/core/modules/auth/lib/tenantEligibility";
|
|
16
17
|
const loginRateLimitConfig = readEndpointRateLimitConfig("LOGIN", {
|
|
17
18
|
points: 5,
|
|
18
19
|
duration: 60,
|
|
@@ -117,9 +118,11 @@ async function handleLoginRequest(req) {
|
|
|
117
118
|
user = users.length === 1 ? users[0] : null;
|
|
118
119
|
}
|
|
119
120
|
const ok = await auth.verifyPassword(user, parsed.data.password);
|
|
120
|
-
|
|
121
|
+
const tenantActive = user ? await isStaffTenantActive(container.resolve("em"), user.tenantId) : false;
|
|
122
|
+
if (!user || !ok || user.isConfirmed === false || !tenantActive) {
|
|
121
123
|
let reason;
|
|
122
124
|
if (user && user.isConfirmed === false) reason = "account_deactivated";
|
|
125
|
+
else if (user && !tenantActive) reason = "tenant_unavailable";
|
|
123
126
|
else if (user?.passwordHash) reason = "invalid_password";
|
|
124
127
|
else reason = "invalid_credentials";
|
|
125
128
|
void emitAuthEvent("auth.login.failed", { email: parsed.data.email, reason }).catch(() => void 0);
|
|
@@ -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'\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 })\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 if (!user || !ok || user.isConfirmed === false) {\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?.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 const { session: loginSession, token: sessionRefreshToken } = await auth.createSession(user, sessionExpiresAt)\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 void emitAuthEvent('auth.login.success', { id: String(user.id), email: user.email, tenantId: resolvedTenantId, organizationId: user.organizationId ? String(user.organizationId) : null }).catch(() => undefined)\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 return NextResponse.json(interceptedResponse.body, { status: interceptedResponse.statusCode })\n }\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;
|
|
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 { isStaffTenantActive } from '@open-mercato/core/modules/auth/lib/tenantEligibility'\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 })\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 const { session: loginSession, token: sessionRefreshToken } = await auth.createSession(user, sessionExpiresAt)\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 void emitAuthEvent('auth.login.success', { id: String(user.id), email: user.email, tenantId: resolvedTenantId, organizationId: user.organizationId ? String(user.organizationId) : null }).catch(() => undefined)\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 return NextResponse.json(interceptedResponse.body, { status: interceptedResponse.statusCode })\n }\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,2BAA2B;AAEpC,MAAM,uBAAuB,4BAA4B,SAAS;AAAA,EAChE,QAAQ;AAAA,EAAG,UAAU;AAAA,EAAI,eAAe;AAAA,EAAI,WAAW;AACzD,CAAC;AACD,MAAM,yBAAyB,4BAA4B,YAAY;AAAA,EACrE,QAAQ;AAAA,EAAI,UAAU;AAAA,EAAI,eAAe;AAAA,EAAI,WAAW;AAC1D,CAAC;AAEM,MAAM,WAAW,EAAE,aAAa,MAAM;AAa7C,SAAS,mBAAmB,UAA4B;AACtD,SAAO,SACJ,MAAM,GAAG,EACT,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAC3B,OAAO,OAAO;AACnB;AAEA,eAAe,eAAe,KAAwC;AACpE,QAAM,iBAAiB,IAAI,QAAQ,IAAI,cAAc,KAAK;AAC1D,QAAM,cAAc,eAAe,MAAM,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,YAAY;AAEpE,MAAI;AACF,QAAI,gBAAgB,qCAAqC;AACvD,YAAM,OAAO,MAAM,IAA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AW;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
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
2
2
|
import { RoleAcl, Session, User, UserAcl, UserRole } from "@open-mercato/core/modules/auth/data/entities";
|
|
3
|
+
import { isStaffTenantActive } from "@open-mercato/core/modules/auth/lib/tenantEligibility";
|
|
3
4
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
4
5
|
const INVALID_SCOPE = /* @__PURE__ */ Symbol("invalid-scope");
|
|
5
6
|
function normalizeScopeId(value) {
|
|
@@ -54,6 +55,7 @@ async function resolveCanonicalStaffAuthContext(em, auth) {
|
|
|
54
55
|
if (currentTenantId === INVALID_SCOPE || currentOrganizationId === INVALID_SCOPE || currentTenantId !== actorTenantId || currentOrganizationId !== actorOrganizationId) {
|
|
55
56
|
return null;
|
|
56
57
|
}
|
|
58
|
+
if (!await isStaffTenantActive(em, currentTenantId)) return null;
|
|
57
59
|
const linksPromise = currentTenantId ? findWithDecryption(
|
|
58
60
|
em,
|
|
59
61
|
UserRole,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/auth/lib/sessionIntegrity.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Role, RoleAcl, Session, User, UserAcl, UserRole } from '@open-mercato/core/modules/auth/data/entities'\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\nconst INVALID_SCOPE = Symbol('invalid-scope')\n\ntype NormalizedScopeId = string | null | typeof INVALID_SCOPE\n\nfunction normalizeScopeId(value: unknown): NormalizedScopeId {\n if (value === null || value === undefined) return null\n if (typeof value !== 'string') return INVALID_SCOPE\n const trimmed = value.trim()\n if (!trimmed) return null\n return UUID_RE.test(trimmed) ? trimmed : INVALID_SCOPE\n}\n\nfunction resolveActorTenantId(auth: NonNullable<AuthContext>): NormalizedScopeId {\n const actorTenantId = (auth as { actorTenantId?: unknown }).actorTenantId\n return normalizeScopeId(actorTenantId ?? auth.tenantId ?? null)\n}\n\nfunction resolveActorOrganizationId(auth: NonNullable<AuthContext>): NormalizedScopeId {\n const actorOrgId = (auth as { actorOrgId?: unknown }).actorOrgId\n return normalizeScopeId(actorOrgId ?? auth.orgId ?? null)\n}\n\nexport async function resolveCanonicalStaffAuthContext(\n em: EntityManager,\n auth: AuthContext,\n): Promise<AuthContext> {\n if (!auth) return null\n if (auth.isApiKey) return auth\n\n const subjectId = normalizeScopeId(auth.sub)\n const actorTenantId = resolveActorTenantId(auth)\n const actorOrganizationId = resolveActorOrganizationId(auth)\n if (\n subjectId === INVALID_SCOPE ||\n actorTenantId === INVALID_SCOPE ||\n actorOrganizationId === INVALID_SCOPE\n ) {\n return null\n }\n\n // Session binding: when the JWT carries an `sid` claim, require the referenced session to\n // still exist (not soft-deleted, not expired). This is what makes logout / password-reset\n // actually invalidate an already-issued JWT.\n //\n // Legacy tokens (pre-migration, without `sid`) are allowed through during the grace period so\n // that rolling deployments don't force-logout every user. `verifyJwt` owns that window: it only\n // marks a payload `_legacyToken` while the token's own `iat` is within JWT_LEGACY_GRACE_MINUTES\n // and before JWT_LEGACY_CUTOVER_AT, so an aged or post-cutover raw-secret token fails\n // verification before reaching this point and every remaining token must carry a live `sid`.\n const sessionId = normalizeScopeId(typeof auth.sid === 'string' ? auth.sid : null)\n if (sessionId === INVALID_SCOPE) return null\n if (sessionId === null) {\n // Legacy token without sid \u2014 allow only if it was verified via the legacy fallback path.\n // The `_legacyToken` flag is set by `verifyJwt` when a token passes raw-secret verification\n // but fails audience-derived verification. Without this flag, reject.\n if ((auth as Record<string, unknown>)._legacyToken === true) {\n // Allow through without session validation \u2014 the token will expire naturally\n } else {\n return null\n }\n }\n // The session-revocation check and the user load are independent (neither reads\n // the other's result), so they run concurrently to collapse two sequential DB\n // round-trips into one. The `em` here is a fresh request-scoped EntityManager\n // (resolved per request, never inside an explicit transaction), so concurrent\n // reads on it are safe.\n //\n // The session lookup is bound to the token subject (`user: subjectId`) so the\n // referenced session must actually belong to the JWT's subject. Without this\n // binding, a forged-but-otherwise-valid token could pair `sub` for one user with\n // a still-live `sid` belonging to another, evading per-user session revocation\n // (logout / deleteAllUserSessions / password reset).\n const sessionPromise = sessionId !== null\n ? findOneWithDecryption(em, Session, { id: sessionId, user: subjectId, deletedAt: null })\n : Promise.resolve(null)\n const userPromise = findOneWithDecryption(\n em,\n User,\n { id: subjectId, deletedAt: null },\n undefined,\n { tenantId: actorTenantId, organizationId: actorOrganizationId },\n )\n const [session, user] = await Promise.all([sessionPromise, userPromise])\n\n if (sessionId !== null) {\n if (!session) return null\n if (resolveSessionUserId(session) !== subjectId) return null\n if (session.expiresAt.getTime() < Date.now()) return null\n }\n\n if (!user || user.isConfirmed === false) return null\n\n const currentTenantId = normalizeScopeId(user.tenantId ?? null)\n const currentOrganizationId = normalizeScopeId(user.organizationId ?? null)\n if (\n currentTenantId === INVALID_SCOPE ||\n currentOrganizationId === INVALID_SCOPE ||\n currentTenantId !== actorTenantId ||\n currentOrganizationId !== actorOrganizationId\n ) {\n return null\n }\n\n // Role links and the per-user super-admin flag are likewise independent, so they\n // run concurrently. The role-level super-admin lookup depends on the resolved\n // role ids, so it stays sequential after the links resolve (and is skipped\n // entirely when the per-user flag already grants super-admin).\n const linksPromise = currentTenantId\n ? findWithDecryption(\n em,\n UserRole,\n {\n user: user.id,\n deletedAt: null,\n role: { tenantId: currentTenantId, deletedAt: null } as unknown as Role,\n } as never,\n { populate: ['role'] },\n { tenantId: currentTenantId, organizationId: currentOrganizationId },\n )\n : Promise.resolve([] as UserRole[])\n const userAclSuperAdminPromise = currentTenantId\n ? userAclGrantsSuperAdmin(em, user.id, currentTenantId, currentOrganizationId)\n : Promise.resolve(false)\n const [links, userAclSuperAdmin] = await Promise.all([linksPromise, userAclSuperAdminPromise])\n\n const linkedRoles = links\n .map((link) => link.role)\n .filter((role): role is Role => !!role)\n\n const roles = linkedRoles\n .map((role) => role.name)\n .filter((name): name is string => typeof name === 'string' && name.trim().length > 0)\n\n const isSuperAdmin = currentTenantId\n ? userAclSuperAdmin || (await roleAclGrantsSuperAdmin(em, linkedRoles, currentTenantId, currentOrganizationId))\n : false\n\n return {\n ...auth,\n sub: user.id,\n tenantId: currentTenantId,\n orgId: currentOrganizationId,\n roles,\n isSuperAdmin,\n }\n}\n\nfunction resolveSessionUserId(session: Session): string | null {\n const owner = (session as { user?: unknown }).user\n if (typeof owner === 'string') return owner\n if (owner && typeof owner === 'object') {\n const ownerId = (owner as { id?: unknown }).id\n if (typeof ownerId === 'string') return ownerId\n }\n return null\n}\n\nasync function userAclGrantsSuperAdmin(\n em: EntityManager,\n userId: string,\n tenantId: string,\n organizationId: string | null,\n): Promise<boolean> {\n const userAcl = await findOneWithDecryption(\n em,\n UserAcl,\n {\n user: userId,\n tenantId,\n isSuperAdmin: true,\n deletedAt: null,\n } as never,\n undefined,\n { tenantId, organizationId },\n )\n return !!(userAcl && (userAcl as { isSuperAdmin?: boolean }).isSuperAdmin === true)\n}\n\nasync function roleAclGrantsSuperAdmin(\n em: EntityManager,\n linkedRoles: Role[],\n tenantId: string,\n organizationId: string | null,\n): Promise<boolean> {\n const roleIds = Array.from(\n new Set(\n linkedRoles\n .map((role) => (role?.id ? String(role.id) : null))\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n if (!roleIds.length) return false\n\n const roleAcl = await findOneWithDecryption(\n em,\n RoleAcl,\n {\n tenantId,\n isSuperAdmin: true,\n deletedAt: null,\n role: { $in: roleIds },\n } as never,\n undefined,\n { tenantId, organizationId },\n )\n return !!(roleAcl && (roleAcl as { isSuperAdmin?: boolean }).isSuperAdmin === true)\n}\n\nexport async function isAuthContextValid(\n em: EntityManager,\n auth: AuthContext,\n): Promise<boolean> {\n return (await resolveCanonicalStaffAuthContext(em, auth)) !== null\n}\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,uBAAuB,0BAA0B;AAC1D,SAAe,SAAS,SAAS,MAAM,SAAS,gBAAgB;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Role, RoleAcl, Session, User, UserAcl, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport { isStaffTenantActive } from '@open-mercato/core/modules/auth/lib/tenantEligibility'\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\nconst INVALID_SCOPE = Symbol('invalid-scope')\n\ntype NormalizedScopeId = string | null | typeof INVALID_SCOPE\n\nfunction normalizeScopeId(value: unknown): NormalizedScopeId {\n if (value === null || value === undefined) return null\n if (typeof value !== 'string') return INVALID_SCOPE\n const trimmed = value.trim()\n if (!trimmed) return null\n return UUID_RE.test(trimmed) ? trimmed : INVALID_SCOPE\n}\n\nfunction resolveActorTenantId(auth: NonNullable<AuthContext>): NormalizedScopeId {\n const actorTenantId = (auth as { actorTenantId?: unknown }).actorTenantId\n return normalizeScopeId(actorTenantId ?? auth.tenantId ?? null)\n}\n\nfunction resolveActorOrganizationId(auth: NonNullable<AuthContext>): NormalizedScopeId {\n const actorOrgId = (auth as { actorOrgId?: unknown }).actorOrgId\n return normalizeScopeId(actorOrgId ?? auth.orgId ?? null)\n}\n\nexport async function resolveCanonicalStaffAuthContext(\n em: EntityManager,\n auth: AuthContext,\n): Promise<AuthContext> {\n if (!auth) return null\n if (auth.isApiKey) return auth\n\n const subjectId = normalizeScopeId(auth.sub)\n const actorTenantId = resolveActorTenantId(auth)\n const actorOrganizationId = resolveActorOrganizationId(auth)\n if (\n subjectId === INVALID_SCOPE ||\n actorTenantId === INVALID_SCOPE ||\n actorOrganizationId === INVALID_SCOPE\n ) {\n return null\n }\n\n // Session binding: when the JWT carries an `sid` claim, require the referenced session to\n // still exist (not soft-deleted, not expired). This is what makes logout / password-reset\n // actually invalidate an already-issued JWT.\n //\n // Legacy tokens (pre-migration, without `sid`) are allowed through during the grace period so\n // that rolling deployments don't force-logout every user. `verifyJwt` owns that window: it only\n // marks a payload `_legacyToken` while the token's own `iat` is within JWT_LEGACY_GRACE_MINUTES\n // and before JWT_LEGACY_CUTOVER_AT, so an aged or post-cutover raw-secret token fails\n // verification before reaching this point and every remaining token must carry a live `sid`.\n const sessionId = normalizeScopeId(typeof auth.sid === 'string' ? auth.sid : null)\n if (sessionId === INVALID_SCOPE) return null\n if (sessionId === null) {\n // Legacy token without sid \u2014 allow only if it was verified via the legacy fallback path.\n // The `_legacyToken` flag is set by `verifyJwt` when a token passes raw-secret verification\n // but fails audience-derived verification. Without this flag, reject.\n if ((auth as Record<string, unknown>)._legacyToken === true) {\n // Allow through without session validation \u2014 the token will expire naturally\n } else {\n return null\n }\n }\n // The session-revocation check and the user load are independent (neither reads\n // the other's result), so they run concurrently to collapse two sequential DB\n // round-trips into one. The `em` here is a fresh request-scoped EntityManager\n // (resolved per request, never inside an explicit transaction), so concurrent\n // reads on it are safe.\n //\n // The session lookup is bound to the token subject (`user: subjectId`) so the\n // referenced session must actually belong to the JWT's subject. Without this\n // binding, a forged-but-otherwise-valid token could pair `sub` for one user with\n // a still-live `sid` belonging to another, evading per-user session revocation\n // (logout / deleteAllUserSessions / password reset).\n const sessionPromise = sessionId !== null\n ? findOneWithDecryption(em, Session, { id: sessionId, user: subjectId, deletedAt: null })\n : Promise.resolve(null)\n const userPromise = findOneWithDecryption(\n em,\n User,\n { id: subjectId, deletedAt: null },\n undefined,\n { tenantId: actorTenantId, organizationId: actorOrganizationId },\n )\n const [session, user] = await Promise.all([sessionPromise, userPromise])\n\n if (sessionId !== null) {\n if (!session) return null\n if (resolveSessionUserId(session) !== subjectId) return null\n if (session.expiresAt.getTime() < Date.now()) return null\n }\n\n if (!user || user.isConfirmed === false) return null\n\n const currentTenantId = normalizeScopeId(user.tenantId ?? null)\n const currentOrganizationId = normalizeScopeId(user.organizationId ?? null)\n if (\n currentTenantId === INVALID_SCOPE ||\n currentOrganizationId === INVALID_SCOPE ||\n currentTenantId !== actorTenantId ||\n currentOrganizationId !== actorOrganizationId\n ) {\n return null\n }\n if (!(await isStaffTenantActive(em, currentTenantId))) return null\n\n // Role links and the per-user super-admin flag are likewise independent, so they\n // run concurrently. The role-level super-admin lookup depends on the resolved\n // role ids, so it stays sequential after the links resolve (and is skipped\n // entirely when the per-user flag already grants super-admin).\n const linksPromise = currentTenantId\n ? findWithDecryption(\n em,\n UserRole,\n {\n user: user.id,\n deletedAt: null,\n role: { tenantId: currentTenantId, deletedAt: null } as unknown as Role,\n } as never,\n { populate: ['role'] },\n { tenantId: currentTenantId, organizationId: currentOrganizationId },\n )\n : Promise.resolve([] as UserRole[])\n const userAclSuperAdminPromise = currentTenantId\n ? userAclGrantsSuperAdmin(em, user.id, currentTenantId, currentOrganizationId)\n : Promise.resolve(false)\n const [links, userAclSuperAdmin] = await Promise.all([linksPromise, userAclSuperAdminPromise])\n\n const linkedRoles = links\n .map((link) => link.role)\n .filter((role): role is Role => !!role)\n\n const roles = linkedRoles\n .map((role) => role.name)\n .filter((name): name is string => typeof name === 'string' && name.trim().length > 0)\n\n const isSuperAdmin = currentTenantId\n ? userAclSuperAdmin || (await roleAclGrantsSuperAdmin(em, linkedRoles, currentTenantId, currentOrganizationId))\n : false\n\n return {\n ...auth,\n sub: user.id,\n tenantId: currentTenantId,\n orgId: currentOrganizationId,\n roles,\n isSuperAdmin,\n }\n}\n\nfunction resolveSessionUserId(session: Session): string | null {\n const owner = (session as { user?: unknown }).user\n if (typeof owner === 'string') return owner\n if (owner && typeof owner === 'object') {\n const ownerId = (owner as { id?: unknown }).id\n if (typeof ownerId === 'string') return ownerId\n }\n return null\n}\n\nasync function userAclGrantsSuperAdmin(\n em: EntityManager,\n userId: string,\n tenantId: string,\n organizationId: string | null,\n): Promise<boolean> {\n const userAcl = await findOneWithDecryption(\n em,\n UserAcl,\n {\n user: userId,\n tenantId,\n isSuperAdmin: true,\n deletedAt: null,\n } as never,\n undefined,\n { tenantId, organizationId },\n )\n return !!(userAcl && (userAcl as { isSuperAdmin?: boolean }).isSuperAdmin === true)\n}\n\nasync function roleAclGrantsSuperAdmin(\n em: EntityManager,\n linkedRoles: Role[],\n tenantId: string,\n organizationId: string | null,\n): Promise<boolean> {\n const roleIds = Array.from(\n new Set(\n linkedRoles\n .map((role) => (role?.id ? String(role.id) : null))\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n if (!roleIds.length) return false\n\n const roleAcl = await findOneWithDecryption(\n em,\n RoleAcl,\n {\n tenantId,\n isSuperAdmin: true,\n deletedAt: null,\n role: { $in: roleIds },\n } as never,\n undefined,\n { tenantId, organizationId },\n )\n return !!(roleAcl && (roleAcl as { isSuperAdmin?: boolean }).isSuperAdmin === true)\n}\n\nexport async function isAuthContextValid(\n em: EntityManager,\n auth: AuthContext,\n): Promise<boolean> {\n return (await resolveCanonicalStaffAuthContext(em, auth)) !== null\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,uBAAuB,0BAA0B;AAC1D,SAAe,SAAS,SAAS,MAAM,SAAS,gBAAgB;AAChE,SAAS,2BAA2B;AAEpC,MAAM,UAAU;AAChB,MAAM,gBAAgB,uBAAO,eAAe;AAI5C,SAAS,iBAAiB,OAAmC;AAC3D,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,QAAQ,KAAK,OAAO,IAAI,UAAU;AAC3C;AAEA,SAAS,qBAAqB,MAAmD;AAC/E,QAAM,gBAAiB,KAAqC;AAC5D,SAAO,iBAAiB,iBAAiB,KAAK,YAAY,IAAI;AAChE;AAEA,SAAS,2BAA2B,MAAmD;AACrF,QAAM,aAAc,KAAkC;AACtD,SAAO,iBAAiB,cAAc,KAAK,SAAS,IAAI;AAC1D;AAEA,eAAsB,iCACpB,IACA,MACsB;AACtB,MAAI,CAAC,KAAM,QAAO;AAClB,MAAI,KAAK,SAAU,QAAO;AAE1B,QAAM,YAAY,iBAAiB,KAAK,GAAG;AAC3C,QAAM,gBAAgB,qBAAqB,IAAI;AAC/C,QAAM,sBAAsB,2BAA2B,IAAI;AAC3D,MACE,cAAc,iBACd,kBAAkB,iBAClB,wBAAwB,eACxB;AACA,WAAO;AAAA,EACT;AAWA,QAAM,YAAY,iBAAiB,OAAO,KAAK,QAAQ,WAAW,KAAK,MAAM,IAAI;AACjF,MAAI,cAAc,cAAe,QAAO;AACxC,MAAI,cAAc,MAAM;AAItB,QAAK,KAAiC,iBAAiB,MAAM;A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CAAC,OAAqB,OAAO,OAAO,YAAY,GAAG,SAAS,CAAC;AAAA,IACzE;AAAA,EACF;AACA,MAAI,CAAC,QAAQ,OAAQ,QAAO;AAE5B,QAAM,UAAU,MAAM;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,MACE;AAAA,MACA,cAAc;AAAA,MACd,WAAW;AAAA,MACX,MAAM,EAAE,KAAK,QAAQ;AAAA,IACvB;AAAA,IACA;AAAA,IACA,EAAE,UAAU,eAAe;AAAA,EAC7B;AACA,SAAO,CAAC,EAAE,WAAY,QAAuC,iBAAiB;AAChF;AAEA,eAAsB,mBACpB,IACA,MACkB;AAClB,SAAQ,MAAM,iCAAiC,IAAI,IAAI,MAAO;AAChE;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Tenant } from "@open-mercato/core/modules/directory/data/entities";
|
|
2
|
+
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
3
|
+
async function isStaffTenantActive(em, tenantId) {
|
|
4
|
+
if (tenantId == null) return true;
|
|
5
|
+
const tenant = await findOneWithDecryption(
|
|
6
|
+
em,
|
|
7
|
+
Tenant,
|
|
8
|
+
{ id: tenantId, isActive: true, deletedAt: null },
|
|
9
|
+
{ fields: ["id"], refresh: true }
|
|
10
|
+
);
|
|
11
|
+
return tenant !== null;
|
|
12
|
+
}
|
|
13
|
+
export {
|
|
14
|
+
isStaffTenantActive
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=tenantEligibility.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/auth/lib/tenantEligibility.ts"],
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Tenant } from '@open-mercato/core/modules/directory/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nexport async function isStaffTenantActive(\n em: EntityManager,\n tenantId: string | null | undefined,\n): Promise<boolean> {\n if (tenantId == null) return true\n const tenant = await findOneWithDecryption(\n em,\n Tenant,\n { id: tenantId, isActive: true, deletedAt: null },\n { fields: ['id'], refresh: true },\n )\n return tenant !== null\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,cAAc;AACvB,SAAS,6BAA6B;AAEtC,eAAsB,oBACpB,IACA,UACkB;AAClB,MAAI,YAAY,KAAM,QAAO;AAC7B,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA,EAAE,IAAI,UAAU,UAAU,MAAM,WAAW,KAAK;AAAA,IAChD,EAAE,QAAQ,CAAC,IAAI,GAAG,SAAS,KAAK;AAAA,EAClC;AACA,SAAO,WAAW;AACpB;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -3,6 +3,7 @@ import { User, UserRole, Session, PasswordReset } from "@open-mercato/core/modul
|
|
|
3
3
|
import { emailHashLookupValues } from "@open-mercato/core/modules/auth/lib/emailHash";
|
|
4
4
|
import { generateAuthToken, hashAuthToken } from "@open-mercato/core/modules/auth/lib/tokenHash";
|
|
5
5
|
import { findWithDecryption, findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
6
|
+
import { isStaffTenantActive } from "@open-mercato/core/modules/auth/lib/tenantEligibility";
|
|
6
7
|
const TIMING_EQUALIZER_PASSWORD_HASH = "$2b$10$OcZrhmZpIzJOjkfwUrk7d.Nl0eHNzOvalBcBlt5Ran.4lj8R3HZg6";
|
|
7
8
|
class AuthService {
|
|
8
9
|
constructor(em) {
|
|
@@ -68,6 +69,9 @@ class AuthService {
|
|
|
68
69
|
return links.map((l) => l.role).filter((role) => !!role).map((role) => role.name).filter((name) => typeof name === "string" && name.trim().length > 0);
|
|
69
70
|
}
|
|
70
71
|
async createSession(user, expiresAt) {
|
|
72
|
+
if (!await isStaffTenantActive(this.em, user.tenantId)) {
|
|
73
|
+
throw new Error("[internal] Tenant is not available for authentication");
|
|
74
|
+
}
|
|
71
75
|
const rawToken = generateAuthToken();
|
|
72
76
|
const tokenHash = hashAuthToken(rawToken);
|
|
73
77
|
const sess = this.em.create(Session, { user, token: tokenHash, expiresAt, createdAt: /* @__PURE__ */ new Date() });
|
|
@@ -97,6 +101,7 @@ class AuthService {
|
|
|
97
101
|
if (!sess || sess.expiresAt <= now) return null;
|
|
98
102
|
const user = await findOneWithDecryption(this.em, User, { id: sess.user.id, deletedAt: null });
|
|
99
103
|
if (!user) return null;
|
|
104
|
+
if (!await isStaffTenantActive(this.em, user.tenantId)) return null;
|
|
100
105
|
const roles = await this.getUserRoles(user, user.tenantId ?? null);
|
|
101
106
|
return { user, roles, session: sess };
|
|
102
107
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/auth/services/authService.ts"],
|
|
4
|
-
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport { compare, hash } from 'bcryptjs'\nimport { User, Role, UserRole, Session, PasswordReset } from '@open-mercato/core/modules/auth/data/entities'\nimport { emailHashLookupValues } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { generateAuthToken, hashAuthToken } from '@open-mercato/core/modules/auth/lib/tokenHash'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\n// A fixed, valid bcrypt hash (cost 10) of a throwaway value no real password\n// can match. verifyPassword compares against it whenever the user is missing or\n// has no password hash, so a failed login spends the same bcrypt CPU time\n// regardless of whether the account exists \u2014 closing the timing side channel\n// for account enumeration (issue #2242).\nconst TIMING_EQUALIZER_PASSWORD_HASH = '$2b$10$OcZrhmZpIzJOjkfwUrk7d.Nl0eHNzOvalBcBlt5Ran.4lj8R3HZg6'\n\nexport class AuthService {\n constructor(private em: EntityManager) {}\n\n async findUserByEmail(email: string) {\n const emailHashes = emailHashLookupValues(email)\n return findOneWithDecryption(this.em, User, {\n deletedAt: null,\n $or: [\n { email },\n { emailHash: { $in: emailHashes } },\n ],\n } as any)\n }\n\n async findUsersByEmail(email: string) {\n const emailHashes = emailHashLookupValues(email)\n return findWithDecryption(this.em, User, {\n deletedAt: null,\n $or: [\n { email },\n { emailHash: { $in: emailHashes } },\n ],\n } as any)\n }\n\n async findUserByEmailAndTenant(email: string, tenantId: string) {\n const emailHashes = emailHashLookupValues(email)\n return findOneWithDecryption(\n this.em,\n User,\n {\n tenantId,\n deletedAt: null,\n $or: [\n { email },\n { emailHash: { $in: emailHashes } },\n ],\n } as any,\n undefined,\n { tenantId },\n )\n }\n\n async verifyPassword(user: User | null, password: string) {\n const storedHash = user?.passwordHash ?? null\n // Always run a bcrypt comparison \u2014 against a fixed dummy hash when the user\n // is absent or has no password \u2014 so login latency does not reveal whether\n // the account exists (timing-based enumeration, issue #2242).\n const matched = await compare(password, storedHash ?? TIMING_EQUALIZER_PASSWORD_HASH)\n return storedHash !== null && matched\n }\n\n async updateLastLoginAt(user: User) {\n const now = new Date()\n // Use native update to avoid flushing unrelated entities that might be pending in this EM\n await this.em.nativeUpdate(User, { id: user.id }, { lastLoginAt: now })\n user.lastLoginAt = now\n }\n\n async getUserRoles(user: User, tenantId?: string | null): Promise<string[]> {\n const resolvedTenantId = tenantId ?? user.tenantId ?? null\n if (!resolvedTenantId) return []\n const links = await findWithDecryption(\n this.em,\n UserRole,\n { user, deletedAt: null, role: { tenantId: resolvedTenantId, deletedAt: null } as any },\n { populate: ['role'] },\n { tenantId: resolvedTenantId, organizationId: user.organizationId ?? null },\n )\n // A populated `role` can still be null when the link points at a soft-deleted\n // role (the Role soft-delete filter suppresses hydration), e.g. an admin link\n // orphaned by a re-seed during interrupted-provisioning recovery. Dropping such\n // links keeps role resolution from throwing on the login / session-refresh hot\n // path, mirroring resolveCanonicalStaffAuthContext in lib/sessionIntegrity.ts.\n return links\n .map((l) => l.role)\n .filter((role): role is Role => !!role)\n .map((role) => role.name)\n .filter((name): name is string => typeof name === 'string' && name.trim().length > 0)\n }\n\n\n async createSession(user: User, expiresAt: Date): Promise<{ session: Session; token: string }> {\n const rawToken = generateAuthToken()\n const tokenHash = hashAuthToken(rawToken)\n const sess = this.em.create(Session as any, { user, token: tokenHash, expiresAt, createdAt: new Date() } as any)\n await this.em.persist(sess).flush()\n return { session: sess as Session, token: rawToken }\n }\n\n async deleteSessionByToken(token: string) {\n const hashedToken = hashAuthToken(token)\n await this.em.nativeDelete(Session, { token: hashedToken })\n }\n\n async deleteSessionById(sessionId: string) {\n await this.em.nativeDelete(Session, { id: sessionId })\n }\n\n async findActiveSessionById(sessionId: string): Promise<Session | null> {\n const session = await this.em.findOne(Session, { id: sessionId, deletedAt: null })\n if (!session) return null\n if (session.expiresAt.getTime() < Date.now()) return null\n return session\n }\n\n async deleteAllUserSessions(userId: string) {\n await this.em.nativeDelete(Session, { user: userId })\n }\n\n async refreshFromSessionToken(token: string) {\n const now = new Date()\n const hashedToken = hashAuthToken(token)\n const sess = await this.em.findOne(Session, { token: hashedToken })\n if (!sess || sess.expiresAt <= now) return null\n const user = await findOneWithDecryption(this.em, User, { id: sess.user.id, deletedAt: null })\n if (!user) return null\n const roles = await this.getUserRoles(user, user.tenantId ?? null)\n return { user, roles, session: sess }\n }\n\n async requestPasswordReset(email: string) {\n const user = await this.findUserByEmail(email)\n if (!user) return null\n const rawToken = generateAuthToken()\n const tokenHash = hashAuthToken(rawToken)\n const expiresAt = new Date(Date.now() + 60 * 60 * 1000)\n const row = this.em.create(PasswordReset as any, { user, token: tokenHash, expiresAt, createdAt: new Date() } as any)\n await this.em.persist(row).flush()\n return { user, token: rawToken }\n }\n\n private async findUnconsumedPasswordReset(token: string): Promise<PasswordReset | null> {\n const now = new Date()\n const hashedToken = hashAuthToken(token)\n const row = await this.em.findOne(PasswordReset, { token: hashedToken })\n if (!row) return null\n if (row.usedAt && row.usedAt <= now) return null\n if (row.expiresAt <= now) return null\n return row\n }\n\n async isPasswordResetTokenValid(token: string): Promise<boolean> {\n const row = await this.findUnconsumedPasswordReset(token)\n if (!row) return false\n const user = await findOneWithDecryption(this.em, User, { id: row.user.id, deletedAt: null })\n return user != null\n }\n\n async confirmPasswordReset(token: string, newPassword: string): Promise<User | null> {\n const now = new Date()\n const row = await this.findUnconsumedPasswordReset(token)\n if (!row) return null\n\n // Atomic compare-and-set: only mark used if still unused \u2014 prevents token replay under concurrency\n const affected = await this.em.nativeUpdate(\n PasswordReset,\n { id: row.id, usedAt: null },\n { usedAt: now },\n )\n if (affected === 0) return null\n\n const user = await findOneWithDecryption(this.em, User, { id: row.user.id, deletedAt: null })\n if (!user) return null\n user.passwordHash = await hash(newPassword, 10)\n await this.em.flush()\n await this.deleteAllUserSessions(String(user.id))\n return user\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,SAAS,YAAY;AAC9B,SAAS,MAAY,UAAU,SAAS,qBAAqB;AAC7D,SAAS,6BAA6B;AACtC,SAAS,mBAAmB,qBAAqB;AACjD,SAAS,oBAAoB,6BAA6B;
|
|
4
|
+
"sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport { compare, hash } from 'bcryptjs'\nimport { User, Role, UserRole, Session, PasswordReset } from '@open-mercato/core/modules/auth/data/entities'\nimport { emailHashLookupValues } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { generateAuthToken, hashAuthToken } from '@open-mercato/core/modules/auth/lib/tokenHash'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isStaffTenantActive } from '@open-mercato/core/modules/auth/lib/tenantEligibility'\n\n// A fixed, valid bcrypt hash (cost 10) of a throwaway value no real password\n// can match. verifyPassword compares against it whenever the user is missing or\n// has no password hash, so a failed login spends the same bcrypt CPU time\n// regardless of whether the account exists \u2014 closing the timing side channel\n// for account enumeration (issue #2242).\nconst TIMING_EQUALIZER_PASSWORD_HASH = '$2b$10$OcZrhmZpIzJOjkfwUrk7d.Nl0eHNzOvalBcBlt5Ran.4lj8R3HZg6'\n\nexport class AuthService {\n constructor(private em: EntityManager) {}\n\n async findUserByEmail(email: string) {\n const emailHashes = emailHashLookupValues(email)\n return findOneWithDecryption(this.em, User, {\n deletedAt: null,\n $or: [\n { email },\n { emailHash: { $in: emailHashes } },\n ],\n } as any)\n }\n\n async findUsersByEmail(email: string) {\n const emailHashes = emailHashLookupValues(email)\n return findWithDecryption(this.em, User, {\n deletedAt: null,\n $or: [\n { email },\n { emailHash: { $in: emailHashes } },\n ],\n } as any)\n }\n\n async findUserByEmailAndTenant(email: string, tenantId: string) {\n const emailHashes = emailHashLookupValues(email)\n return findOneWithDecryption(\n this.em,\n User,\n {\n tenantId,\n deletedAt: null,\n $or: [\n { email },\n { emailHash: { $in: emailHashes } },\n ],\n } as any,\n undefined,\n { tenantId },\n )\n }\n\n async verifyPassword(user: User | null, password: string) {\n const storedHash = user?.passwordHash ?? null\n // Always run a bcrypt comparison \u2014 against a fixed dummy hash when the user\n // is absent or has no password \u2014 so login latency does not reveal whether\n // the account exists (timing-based enumeration, issue #2242).\n const matched = await compare(password, storedHash ?? TIMING_EQUALIZER_PASSWORD_HASH)\n return storedHash !== null && matched\n }\n\n async updateLastLoginAt(user: User) {\n const now = new Date()\n // Use native update to avoid flushing unrelated entities that might be pending in this EM\n await this.em.nativeUpdate(User, { id: user.id }, { lastLoginAt: now })\n user.lastLoginAt = now\n }\n\n async getUserRoles(user: User, tenantId?: string | null): Promise<string[]> {\n const resolvedTenantId = tenantId ?? user.tenantId ?? null\n if (!resolvedTenantId) return []\n const links = await findWithDecryption(\n this.em,\n UserRole,\n { user, deletedAt: null, role: { tenantId: resolvedTenantId, deletedAt: null } as any },\n { populate: ['role'] },\n { tenantId: resolvedTenantId, organizationId: user.organizationId ?? null },\n )\n // A populated `role` can still be null when the link points at a soft-deleted\n // role (the Role soft-delete filter suppresses hydration), e.g. an admin link\n // orphaned by a re-seed during interrupted-provisioning recovery. Dropping such\n // links keeps role resolution from throwing on the login / session-refresh hot\n // path, mirroring resolveCanonicalStaffAuthContext in lib/sessionIntegrity.ts.\n return links\n .map((l) => l.role)\n .filter((role): role is Role => !!role)\n .map((role) => role.name)\n .filter((name): name is string => typeof name === 'string' && name.trim().length > 0)\n }\n\n\n async createSession(user: User, expiresAt: Date): Promise<{ session: Session; token: string }> {\n if (!(await isStaffTenantActive(this.em, user.tenantId))) {\n throw new Error('[internal] Tenant is not available for authentication')\n }\n const rawToken = generateAuthToken()\n const tokenHash = hashAuthToken(rawToken)\n const sess = this.em.create(Session as any, { user, token: tokenHash, expiresAt, createdAt: new Date() } as any)\n await this.em.persist(sess).flush()\n return { session: sess as Session, token: rawToken }\n }\n\n async deleteSessionByToken(token: string) {\n const hashedToken = hashAuthToken(token)\n await this.em.nativeDelete(Session, { token: hashedToken })\n }\n\n async deleteSessionById(sessionId: string) {\n await this.em.nativeDelete(Session, { id: sessionId })\n }\n\n async findActiveSessionById(sessionId: string): Promise<Session | null> {\n const session = await this.em.findOne(Session, { id: sessionId, deletedAt: null })\n if (!session) return null\n if (session.expiresAt.getTime() < Date.now()) return null\n return session\n }\n\n async deleteAllUserSessions(userId: string) {\n await this.em.nativeDelete(Session, { user: userId })\n }\n\n async refreshFromSessionToken(token: string) {\n const now = new Date()\n const hashedToken = hashAuthToken(token)\n const sess = await this.em.findOne(Session, { token: hashedToken })\n if (!sess || sess.expiresAt <= now) return null\n const user = await findOneWithDecryption(this.em, User, { id: sess.user.id, deletedAt: null })\n if (!user) return null\n if (!(await isStaffTenantActive(this.em, user.tenantId))) return null\n const roles = await this.getUserRoles(user, user.tenantId ?? null)\n return { user, roles, session: sess }\n }\n\n async requestPasswordReset(email: string) {\n const user = await this.findUserByEmail(email)\n if (!user) return null\n const rawToken = generateAuthToken()\n const tokenHash = hashAuthToken(rawToken)\n const expiresAt = new Date(Date.now() + 60 * 60 * 1000)\n const row = this.em.create(PasswordReset as any, { user, token: tokenHash, expiresAt, createdAt: new Date() } as any)\n await this.em.persist(row).flush()\n return { user, token: rawToken }\n }\n\n private async findUnconsumedPasswordReset(token: string): Promise<PasswordReset | null> {\n const now = new Date()\n const hashedToken = hashAuthToken(token)\n const row = await this.em.findOne(PasswordReset, { token: hashedToken })\n if (!row) return null\n if (row.usedAt && row.usedAt <= now) return null\n if (row.expiresAt <= now) return null\n return row\n }\n\n async isPasswordResetTokenValid(token: string): Promise<boolean> {\n const row = await this.findUnconsumedPasswordReset(token)\n if (!row) return false\n const user = await findOneWithDecryption(this.em, User, { id: row.user.id, deletedAt: null })\n return user != null\n }\n\n async confirmPasswordReset(token: string, newPassword: string): Promise<User | null> {\n const now = new Date()\n const row = await this.findUnconsumedPasswordReset(token)\n if (!row) return null\n\n // Atomic compare-and-set: only mark used if still unused \u2014 prevents token replay under concurrency\n const affected = await this.em.nativeUpdate(\n PasswordReset,\n { id: row.id, usedAt: null },\n { usedAt: now },\n )\n if (affected === 0) return null\n\n const user = await findOneWithDecryption(this.em, User, { id: row.user.id, deletedAt: null })\n if (!user) return null\n user.passwordHash = await hash(newPassword, 10)\n await this.em.flush()\n await this.deleteAllUserSessions(String(user.id))\n return user\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,SAAS,YAAY;AAC9B,SAAS,MAAY,UAAU,SAAS,qBAAqB;AAC7D,SAAS,6BAA6B;AACtC,SAAS,mBAAmB,qBAAqB;AACjD,SAAS,oBAAoB,6BAA6B;AAC1D,SAAS,2BAA2B;AAOpC,MAAM,iCAAiC;AAEhC,MAAM,YAAY;AAAA,EACvB,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,gBAAgB,OAAe;AACnC,UAAM,cAAc,sBAAsB,KAAK;AAC/C,WAAO,sBAAsB,KAAK,IAAI,MAAM;AAAA,MAC1C,WAAW;AAAA,MACX,KAAK;AAAA,QACH,EAAE,MAAM;AAAA,QACR,EAAE,WAAW,EAAE,KAAK,YAAY,EAAE;AAAA,MACpC;AAAA,IACF,CAAQ;AAAA,EACV;AAAA,EAEA,MAAM,iBAAiB,OAAe;AACpC,UAAM,cAAc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AACjC,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,0BAA0B,OAAiC;AAC/D,UAAM,MAAM,MAAM,KAAK,4BAA4B,KAAK;AACxD,QAAI,CAAC,IAAK,QAAO;AACjB,UAAM,OAAO,MAAM,sBAAsB,KAAK,IAAI,MAAM,EAAE,IAAI,IAAI,KAAK,IAAI,WAAW,KAAK,CAAC;AAC5F,WAAO,QAAQ;AAAA,EACjB;AAAA,EAEA,MAAM,qBAAqB,OAAe,aAA2C;AACnF,UAAM,MAAM,oBAAI,KAAK;AACrB,UAAM,MAAM,MAAM,KAAK,4BAA4B,KAAK;AACxD,QAAI,CAAC,IAAK,QAAO;AAGjB,UAAM,WAAW,MAAM,KAAK,GAAG;AAAA,MAC7B;AAAA,MACA,EAAE,IAAI,IAAI,IAAI,QAAQ,KAAK;AAAA,MAC3B,EAAE,QAAQ,IAAI;AAAA,IAChB;AACA,QAAI,aAAa,EAAG,QAAO;AAE3B,UAAM,OAAO,MAAM,sBAAsB,KAAK,IAAI,MAAM,EAAE,IAAI,IAAI,KAAK,IAAI,WAAW,KAAK,CAAC;AAC5F,QAAI,CAAC,KAAM,QAAO;AAClB,SAAK,eAAe,MAAM,KAAK,aAAa,EAAE;AAC9C,UAAM,KAAK,GAAG,MAAM;AACpB,UAAM,KAAK,sBAAsB,OAAO,KAAK,EAAE,CAAC;AAChD,WAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -15,15 +15,15 @@ async function POST(req, ctx) {
|
|
|
15
15
|
if (!auth || !auth.tenantId) return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
|
16
16
|
const container = await createRequestContainer();
|
|
17
17
|
const rbac = container.resolve("rbacService");
|
|
18
|
-
const allowed = await rbac.userHasAllFeatures(auth.sub, [FEATURE], {
|
|
19
|
-
tenantId: auth.tenantId,
|
|
20
|
-
organizationId: auth.orgId
|
|
21
|
-
});
|
|
22
|
-
if (!allowed) return NextResponse.json({ ok: false, error: "Forbidden" }, { status: 403 });
|
|
23
18
|
const { id } = await ctx.params;
|
|
24
19
|
const service = container.resolve("domainMappingService");
|
|
25
20
|
const record = await service.findById(id, { tenantId: auth.tenantId });
|
|
26
21
|
if (!record) return NextResponse.json({ ok: false, error: "Not found" }, { status: 404 });
|
|
22
|
+
const allowed = await rbac.userHasAllFeatures(auth.sub, [FEATURE], {
|
|
23
|
+
tenantId: auth.tenantId,
|
|
24
|
+
organizationId: record.organizationId
|
|
25
|
+
});
|
|
26
|
+
if (!allowed) return NextResponse.json({ ok: false, error: "Forbidden" }, { status: 403 });
|
|
27
27
|
const guardResult = await validateCrudMutationGuard(container, {
|
|
28
28
|
tenantId: auth.tenantId,
|
|
29
29
|
organizationId: record.organizationId,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customer_accounts/api/admin/domain-mappings/%5Bid%5D/health-check.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport {\n validateCrudMutationGuard,\n runCrudMutationGuardAfterSuccess,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { DomainMappingService } from '@open-mercato/core/modules/customer_accounts/services/domainMappingService'\n\nconst FEATURE = 'customer_accounts.domain.manage'\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: [FEATURE] },\n}\n\nexport async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) return NextResponse.json({ ok: false, error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const rbac = container.resolve('rbacService') as RbacService\n const
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,UAAU;AAET,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,OAAO,EAAE;AACxD;AAEA,eAAsB,KAAK,KAAc,KAA0C;AACjF,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,SAAU,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAE3G,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,UAAU,QAAQ,aAAa;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport {\n validateCrudMutationGuard,\n runCrudMutationGuardAfterSuccess,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { DomainMappingService } from '@open-mercato/core/modules/customer_accounts/services/domainMappingService'\n\nconst FEATURE = 'customer_accounts.domain.manage'\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: [FEATURE] },\n}\n\nexport async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) return NextResponse.json({ ok: false, error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const rbac = container.resolve('rbacService') as RbacService\n\n const { id } = await ctx.params\n const service = container.resolve('domainMappingService') as DomainMappingService\n const record = await service.findById(id, { tenantId: auth.tenantId })\n if (!record) return NextResponse.json({ ok: false, error: 'Not found' }, { status: 404 })\n const allowed = await rbac.userHasAllFeatures(auth.sub, [FEATURE], {\n tenantId: auth.tenantId,\n organizationId: record.organizationId,\n })\n if (!allowed) return NextResponse.json({ ok: false, error: 'Forbidden' }, { status: 403 })\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: record.organizationId,\n userId: auth.sub,\n resourceKind: 'customer_accounts.domain_mapping',\n resourceId: id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n let updated\n try {\n updated = await service.healthCheck(id)\n } catch (err) {\n return NextResponse.json(\n { ok: false, error: err instanceof Error ? err.message : 'Health check failed' },\n { status: 500 },\n )\n }\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: record.organizationId,\n userId: auth.sub,\n resourceKind: 'customer_accounts.domain_mapping',\n resourceId: id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({\n ok: true,\n domainMapping: {\n id: updated.id,\n hostname: updated.hostname,\n status: updated.status,\n tlsRetryCount: updated.tlsRetryCount,\n tlsFailureReason: updated.tlsFailureReason ?? null,\n },\n })\n}\n\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'CustomerAccounts',\n summary: 'TLS health check for a custom domain mapping',\n methods: {\n POST: {\n summary: 'Trigger TLS health check',\n description:\n 'Runs an HTTPS probe to verify Traefik has provisioned a certificate. On success: transitions the mapping to active.',\n responses: [\n {\n status: 200,\n description: 'OK',\n schema: z.object({\n ok: z.literal(true),\n domainMapping: z.object({\n id: z.string().uuid(),\n hostname: z.string(),\n status: z.string(),\n tlsRetryCount: z.number().int().nonnegative(),\n tlsFailureReason: z.string().nullable(),\n }),\n }),\n },\n ],\n errors: [\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Forbidden', schema: errorSchema },\n { status: 404, description: 'Not found', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,UAAU;AAET,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,OAAO,EAAE;AACxD;AAEA,eAAsB,KAAK,KAAc,KAA0C;AACjF,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,SAAU,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAE3G,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,UAAU,QAAQ,aAAa;AAE5C,QAAM,EAAE,GAAG,IAAI,MAAM,IAAI;AACzB,QAAM,UAAU,UAAU,QAAQ,sBAAsB;AACxD,QAAM,SAAS,MAAM,QAAQ,SAAS,IAAI,EAAE,UAAU,KAAK,SAAS,CAAC;AACrE,MAAI,CAAC,OAAQ,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;AACxF,QAAM,UAAU,MAAM,KAAK,mBAAmB,KAAK,KAAK,CAAC,OAAO,GAAG;AAAA,IACjE,UAAU,KAAK;AAAA,IACf,gBAAgB,OAAO;AAAA,EACzB,CAAC;AACD,MAAI,CAAC,QAAS,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;AAEzF,QAAM,cAAc,MAAM,0BAA0B,WAAW;AAAA,IAC7D,UAAU,KAAK;AAAA,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J,SAAS;AAAA,MACT,aACE;AAAA,MACF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,IAAI,EAAE,QAAQ,IAAI;AAAA,YAClB,eAAe,EAAE,OAAO;AAAA,cACtB,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,cACpB,UAAU,EAAE,OAAO;AAAA,cACnB,QAAQ,EAAE,OAAO;AAAA,cACjB,eAAe,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA,cAC5C,kBAAkB,EAAE,OAAO,EAAE,SAAS;AAAA,YACxC,CAAC;AAAA,UACH,CAAC;AAAA,QACH;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,QAChE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,YAAY;AAAA,QAC7D,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,YAAY;AAAA,MAC/D;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -15,15 +15,15 @@ async function POST(req, ctx) {
|
|
|
15
15
|
if (!auth || !auth.tenantId) return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
|
16
16
|
const container = await createRequestContainer();
|
|
17
17
|
const rbac = container.resolve("rbacService");
|
|
18
|
-
const allowed = await rbac.userHasAllFeatures(auth.sub, [FEATURE], {
|
|
19
|
-
tenantId: auth.tenantId,
|
|
20
|
-
organizationId: auth.orgId
|
|
21
|
-
});
|
|
22
|
-
if (!allowed) return NextResponse.json({ ok: false, error: "Forbidden" }, { status: 403 });
|
|
23
18
|
const { id } = await ctx.params;
|
|
24
19
|
const service = container.resolve("domainMappingService");
|
|
25
20
|
const record = await service.findById(id, { tenantId: auth.tenantId });
|
|
26
21
|
if (!record) return NextResponse.json({ ok: false, error: "Not found" }, { status: 404 });
|
|
22
|
+
const allowed = await rbac.userHasAllFeatures(auth.sub, [FEATURE], {
|
|
23
|
+
tenantId: auth.tenantId,
|
|
24
|
+
organizationId: record.organizationId
|
|
25
|
+
});
|
|
26
|
+
if (!allowed) return NextResponse.json({ ok: false, error: "Forbidden" }, { status: 403 });
|
|
27
27
|
const guardResult = await validateCrudMutationGuard(container, {
|
|
28
28
|
tenantId: auth.tenantId,
|
|
29
29
|
organizationId: record.organizationId,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customer_accounts/api/admin/domain-mappings/%5Bid%5D/verify.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport {\n validateCrudMutationGuard,\n runCrudMutationGuardAfterSuccess,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { DomainMappingService } from '@open-mercato/core/modules/customer_accounts/services/domainMappingService'\n\nconst FEATURE = 'customer_accounts.domain.manage'\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: [FEATURE] },\n}\n\nexport async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) return NextResponse.json({ ok: false, error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const rbac = container.resolve('rbacService') as RbacService\n const
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,UAAU;AAET,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,OAAO,EAAE;AACxD;AAEA,eAAsB,KAAK,KAAc,KAA0C;AACjF,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,SAAU,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAE3G,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,UAAU,QAAQ,aAAa;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport {\n validateCrudMutationGuard,\n runCrudMutationGuardAfterSuccess,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { DomainMappingService } from '@open-mercato/core/modules/customer_accounts/services/domainMappingService'\n\nconst FEATURE = 'customer_accounts.domain.manage'\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: [FEATURE] },\n}\n\nexport async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) return NextResponse.json({ ok: false, error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const rbac = container.resolve('rbacService') as RbacService\n\n const { id } = await ctx.params\n const service = container.resolve('domainMappingService') as DomainMappingService\n const record = await service.findById(id, { tenantId: auth.tenantId })\n if (!record) return NextResponse.json({ ok: false, error: 'Not found' }, { status: 404 })\n const allowed = await rbac.userHasAllFeatures(auth.sub, [FEATURE], {\n tenantId: auth.tenantId,\n organizationId: record.organizationId,\n })\n if (!allowed) return NextResponse.json({ ok: false, error: 'Forbidden' }, { status: 403 })\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: record.organizationId,\n userId: auth.sub,\n resourceKind: 'customer_accounts.domain_mapping',\n resourceId: id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n let result\n try {\n result = await service.verify(id)\n } catch (err) {\n return NextResponse.json(\n { ok: false, error: err instanceof Error ? err.message : 'DNS verification failed' },\n { status: 500 },\n )\n }\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: record.organizationId,\n userId: auth.sub,\n resourceKind: 'customer_accounts.domain_mapping',\n resourceId: id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({\n ok: true,\n domainMapping: {\n id: result.domainMapping.id,\n hostname: result.domainMapping.hostname,\n status: result.domainMapping.status,\n verifiedAt: result.domainMapping.verifiedAt?.toISOString() ?? null,\n lastDnsCheckAt: result.domainMapping.lastDnsCheckAt?.toISOString() ?? null,\n dnsFailureReason: result.domainMapping.dnsFailureReason ?? null,\n },\n diagnostics: result.diagnostics ?? null,\n })\n}\n\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'CustomerAccounts',\n summary: 'Verify a custom domain mapping (DNS check)',\n methods: {\n POST: {\n summary: 'Trigger DNS verification',\n description:\n 'Runs DNS verification (CNAME \u2192 A \u2192 reverse-resolve fallback) for the domain mapping. Returns diagnostics on failure.',\n responses: [\n {\n status: 200,\n description: 'OK \u2014 see status',\n schema: z.object({\n ok: z.literal(true),\n domainMapping: z.object({\n id: z.string().uuid(),\n hostname: z.string(),\n status: z.string(),\n verifiedAt: z.string().nullable(),\n lastDnsCheckAt: z.string().nullable(),\n dnsFailureReason: z.string().nullable(),\n }),\n diagnostics: z.unknown().nullable(),\n }),\n },\n ],\n errors: [\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Forbidden', schema: errorSchema },\n { status: 404, description: 'Not found', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,UAAU;AAET,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,OAAO,EAAE;AACxD;AAEA,eAAsB,KAAK,KAAc,KAA0C;AACjF,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,SAAU,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAE3G,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,UAAU,QAAQ,aAAa;AAE5C,QAAM,EAAE,GAAG,IAAI,MAAM,IAAI;AACzB,QAAM,UAAU,UAAU,QAAQ,sBAAsB;AACxD,QAAM,SAAS,MAAM,QAAQ,SAAS,IAAI,EAAE,UAAU,KAAK,SAAS,CAAC;AACrE,MAAI,CAAC,OAAQ,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;AACxF,QAAM,UAAU,MAAM,KAAK,mBAAmB,KAAK,KAAK,CAAC,OAAO,GAAG;AAAA,IACjE,UAAU,KAAK;AAAA,IACf,gBAAgB,OAAO;AAAA,EACzB,CAAC;AACD,MAAI,CAAC,QAAS,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;AAEzF,QAAM,cAAc,MAAM,0BAA0B,WAAW;AAAA,IAC7D,UAAU,KAAK;AAAA,IACf,gBAA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