@dudousxd/nestjs-catalog-dashboard 0.7.0 → 0.7.2
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/dist/server/index.cjs +12 -18
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.js +12 -18
- package/dist/server/index.js.map +1 -1
- package/dist/spa/assets/index-BrkRcRNu.css +1 -0
- package/dist/spa/assets/index-DzT3XvKC.js +781 -0
- package/dist/spa/index.html +2 -2
- package/package.json +2 -2
- package/dist/spa/assets/index-C6AeB3m3.css +0 -1
- package/dist/spa/assets/index-VMZkXHwi.js +0 -582
package/dist/server/index.cjs
CHANGED
|
@@ -53,30 +53,24 @@ function durationToMs(ttl) {
|
|
|
53
53
|
return Number(match[1]) * unit;
|
|
54
54
|
}
|
|
55
55
|
__name(durationToMs, "durationToMs");
|
|
56
|
+
function assertOptionalHook(value, name) {
|
|
57
|
+
if (value !== void 0 && typeof value !== "function") {
|
|
58
|
+
throw new Error(`CatalogDashboardModule: dashboardAuth.${name} must be a function.`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
__name(assertOptionalHook, "assertOptionalHook");
|
|
56
62
|
function resolveDashboardAuth(options) {
|
|
57
63
|
if (options === void 0) return null;
|
|
58
64
|
if (typeof options.secret !== "string" || options.secret === "") {
|
|
59
65
|
throw new Error("CatalogDashboardModule: dashboardAuth.secret is required and must be a non-empty string (HMAC-SHA256 signing key, 32+ bytes recommended). Failing closed.");
|
|
60
66
|
}
|
|
67
|
+
assertOptionalHook(options.session, "session");
|
|
68
|
+
assertOptionalHook(options.login, "login");
|
|
69
|
+
assertOptionalHook(options.revalidate, "revalidate");
|
|
70
|
+
assertOptionalHook(options.unauthenticatedPage, "unauthenticatedPage");
|
|
61
71
|
const modes = [];
|
|
62
|
-
if (options.session !== void 0)
|
|
63
|
-
|
|
64
|
-
throw new Error("CatalogDashboardModule: dashboardAuth.session must be a function.");
|
|
65
|
-
}
|
|
66
|
-
modes.push("session");
|
|
67
|
-
}
|
|
68
|
-
if (options.login !== void 0) {
|
|
69
|
-
if (typeof options.login !== "function") {
|
|
70
|
-
throw new Error("CatalogDashboardModule: dashboardAuth.login must be a function.");
|
|
71
|
-
}
|
|
72
|
-
modes.push("login");
|
|
73
|
-
}
|
|
74
|
-
if (options.revalidate !== void 0 && typeof options.revalidate !== "function") {
|
|
75
|
-
throw new Error("CatalogDashboardModule: dashboardAuth.revalidate must be a function.");
|
|
76
|
-
}
|
|
77
|
-
if (options.unauthenticatedPage !== void 0 && typeof options.unauthenticatedPage !== "function") {
|
|
78
|
-
throw new Error("CatalogDashboardModule: dashboardAuth.unauthenticatedPage must be a function.");
|
|
79
|
-
}
|
|
72
|
+
if (options.session !== void 0) modes.push("session");
|
|
73
|
+
if (options.login !== void 0) modes.push("login");
|
|
80
74
|
if (modes.length === 0) {
|
|
81
75
|
throw new Error("CatalogDashboardModule: dashboardAuth needs at least one of `session` or `login` (otherwise the cookie can never be minted). Failing closed.");
|
|
82
76
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/index.ts","../../src/server/auth/dashboard-auth-config.ts","../../src/server/auth/cookie-header.ts","../../src/server/auth/request.ts","../../src/server/auth/response.ts","../../src/server/auth/session-cookie.ts","../../src/server/auth/session-cookie-io.ts","../../src/server/catalog-auth.controller.ts","../../src/server/auth/login-page.ts","../../src/server/catalog-ui.controller.ts","../../src/server/auth/login-redirect.exception.ts","../../src/server/auth/session-required.exception.ts","../../src/server/catalog-dashboard.module.ts","../../src/server/catalog-session.guard.ts"],"sourcesContent":["export type {\n DashboardAuthOptions,\n // What `DASHBOARD_AUTH` actually carries. A host reading the session off a\n // request injects that token and needs a name for what comes out.\n ResolvedDashboardAuth,\n UnauthenticatedPageContext,\n UnauthenticatedPageHook,\n} from './auth/dashboard-auth-config.js';\nexport { DASHBOARD_AUTH } from './auth/dashboard-auth-config.js';\nexport type { DashboardSession, DashboardSessionUser } from './auth/session-cookie.js';\n/**\n * Read and verify the console's session off a request.\n *\n * Exported because this package deliberately does NOT proxy the catalog's API —\n * that surface is mounted by `CatalogModule` and guarded by whatever the host\n * put in front of it. Which leaves a gap the host cannot close on its own: the\n * console SPA fetches that API from a browser, carrying this cookie and no\n * bearer token, so a host whose API guard only understands its own token\n * answers 401 to every screen while the console shell loads perfectly. The\n * symptom reads as a broken API, not as two auth systems that were never\n * introduced.\n *\n * So the host's own resolver can ask this: given a request, is there a valid\n * console session on it, and whose? Signature and expiry are checked here;\n * `revalidate` is not run, because that is renewal and belongs to the guard\n * that owns the cookie's lifetime.\n */\nexport { readSessionFromRequest as readCatalogConsoleSession } from './auth/session-cookie-io.js';\nexport { CatalogAuthController } from './catalog-auth.controller.js';\nexport {\n CatalogDashboardModule,\n catalogDashboardMountPaths,\n type CatalogDashboardAsyncOptions,\n type CatalogDashboardOptions,\n} from './catalog-dashboard.module.js';\nexport {\n CatalogApiSessionGuard,\n CatalogUiSessionGuard,\n} from './catalog-session.guard.js';\nexport {\n CatalogUiController,\n DASHBOARD_API_PATH,\n DASHBOARD_BASE_PATH,\n} from './catalog-ui.controller.js';\n","import type { DashboardSessionUser } from './session-cookie.js';\n\n/** Host hook for Mode A — validates the host's own auth on the raw request. */\nexport type SessionHook = (\n request: unknown,\n) => Promise<DashboardSessionUser | null> | DashboardSessionUser | null;\n\n/** Host hook for Mode B — validates submitted credentials from the built-in login page. */\nexport type LoginHook = (\n username: string,\n password: string,\n) => Promise<DashboardSessionUser | null> | DashboardSessionUser | null;\n\n/**\n * Re-checks a LIVE session when the cookie is slid forward. Runs at most once per `ttl/2` per\n * session, so a DB round-trip here is cheap — this holds even under concurrent traffic: N parallel\n * requests carrying the same past-half-life cookie share ONE call (see `revalidateOnce` in\n * `session-cookie-io.ts`), not N. Return `false` to revoke (the cookie is cleared and the request\n * denied). Distinct from `session`: that hook reads the host's auth off a fresh request, which a\n * console XHR does not carry — this one receives the already-minted session.\n */\nexport type RevalidateHook = (session: DashboardSessionUser) => Promise<boolean> | boolean;\n\n/** What `unauthenticatedPage` receives. An object (not positional args) so fields can be added later. */\nexport interface UnauthenticatedPageContext {\n /**\n * The platform-native request — Express' `Request`, Fastify's `FastifyRequest`. Typed `unknown`\n * for the same reason `SessionHook`'s is: this package refuses to depend on either platform.\n * Cast it to whatever your app actually runs on.\n */\n request: unknown;\n /**\n * The platform-native response. The hook OWNS it: it must write AND end it (`res.render(...)`,\n * `res.status(401).send(...)`, an Inertia render, ...). If the hook returns without writing, the\n * library falls back to its own built-in page rather than leaving the request hanging.\n */\n response: unknown;\n /** Where this console is mounted (e.g. `/catalog`) — useful for a \"back to the console\" link. */\n basePath: string;\n}\n\n/**\n * Host-owned page for an unauthenticated full-page navigation to the console.\n *\n * The built-in page cannot know who hosts the console, so it can only say \"open this console from\n * your application\" in the abstract — it can't name the launcher, link to it, or look like the rest\n * of the host's product. This hook hands the whole response to the host instead: render through\n * your own template engine, your own Inertia page, whatever. The page is served AT the console's\n * own URL, so `/catalog` stays `/catalog`.\n *\n * Deliberately NOT a replacement for Mode B's built-in login form. A host that wants its own login\n * UI uses Mode A plus this hook, and posts to `<basePath>/session` from its own page — the mint\n * endpoint is the supported primitive for that.\n *\n * Fail-closed by construction: it only ever runs on a request that has ALREADY been denied. A hook\n * that throws, or that returns without writing, falls back to the built-in page — it cannot let\n * anyone in.\n */\nexport type UnauthenticatedPageHook = (context: UnauthenticatedPageContext) => void | Promise<void>;\n\nexport type AuthMode = 'session' | 'login';\n\n/**\n * Author-facing `dashboardAuth` option on `CatalogDashboardModule.forRoot`/`forRootAsync`. Gates\n * BOTH the SPA (a full-page navigation redirected to a server-rendered login page) and the JSON\n * API (a plain `401`) behind a signed session cookie, mirroring `@dudousxd/nestjs-telescope`'s\n * `dashboardAuth` mechanism (same HMAC-SHA256 cookie, same fail-closed validation). Two ways to\n * mint that cookie: Mode A (`session`) — the host frontend, already carrying its own auth, POSTs\n * to `<basePath>/session` and the host hook decides; or Mode B (`login`) — the built-in,\n * dependency-free server-rendered login page (`GET <basePath>/login`). At least one of the two is\n * required so an un-mintable gate is a boot error, not a silently-open (or silently-stuck) console.\n */\nexport interface DashboardAuthOptions {\n /** REQUIRED HMAC-SHA256 signing key. Missing/empty => boot error (fail closed). */\n secret: string;\n /** Cookie TTL as a duration string (`'8h'`, `'30m'`, `'7d'`). Default `'8h'`. */\n ttl?: string;\n /** Mode A: validates the host's own auth on the raw request POSTed to `<basePath>/session`;\n * return the session user, or `null` to deny. Thrown errors are treated as a denial (logged\n * once, never surfaced to the client). */\n session?: SessionHook;\n /** Mode B: validates submitted username/password from the built-in login page; return the\n * session user, or `null` to deny. Thrown errors are treated as a denial (logged once, never\n * surfaced to the client). */\n login?: LoginHook;\n /** Re-checks a live session on sliding renewal; see `RevalidateHook`. Not a mode — it cannot\n * mint a session, only revoke one already minted by `session`/`login`. */\n revalidate?: RevalidateHook;\n /** Renders the host's own page for an unauthenticated navigation, in place of the built-in\n * \"open this console from your application\" card; see `UnauthenticatedPageHook`. */\n unauthenticatedPage?: UnauthenticatedPageHook;\n}\n\n/** Resolved, validated `dashboardAuth` config shared by the guards, auth controller, and login page. */\nexport interface ResolvedDashboardAuth {\n secret: string;\n ttlMs: number;\n modes: AuthMode[];\n session?: SessionHook;\n login?: LoginHook;\n revalidate?: RevalidateHook;\n unauthenticatedPage?: UnauthenticatedPageHook;\n}\n\n/** DI token carrying the resolved `dashboardAuth` config (`ResolvedDashboardAuth | null`). */\nexport const DASHBOARD_AUTH = Symbol('DASHBOARD_AUTH');\n\nconst DEFAULT_TTL = '8h';\nconst DEFAULT_TTL_MS = 8 * 60 * 60 * 1000;\nconst DURATION_UNITS: Record<string, number> = {\n s: 1000,\n m: 60 * 1000,\n h: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n};\n\n/** Parse a `'<number><s|m|h|d>'` duration to ms; falls back to the 8h default on a bad value. */\nfunction durationToMs(ttl: string): number {\n const match = /^(\\d+)([smhd])$/.exec(ttl.trim());\n if (!match) return DEFAULT_TTL_MS;\n const unit = DURATION_UNITS[match[2] ?? ''];\n if (unit === undefined) return DEFAULT_TTL_MS;\n return Number(match[1]) * unit;\n}\n\n/**\n * Validate + resolve the `dashboardAuth` option. Returns `null` when unconfigured (today's\n * unauthenticated behavior, unchanged). Throws at boot (fail closed) when configured but missing a\n * secret, or missing both a `session` and a `login` hook — the host learns immediately rather than\n * shipping an un-mintable gate.\n */\nexport function resolveDashboardAuth(\n options: DashboardAuthOptions | undefined,\n): ResolvedDashboardAuth | null {\n if (options === undefined) return null;\n if (typeof options.secret !== 'string' || options.secret === '') {\n throw new Error(\n 'CatalogDashboardModule: dashboardAuth.secret is required and must be a non-empty string ' +\n '(HMAC-SHA256 signing key, 32+ bytes recommended). Failing closed.',\n );\n }\n const modes: AuthMode[] = [];\n if (options.session !== undefined) {\n if (typeof options.session !== 'function') {\n throw new Error('CatalogDashboardModule: dashboardAuth.session must be a function.');\n }\n modes.push('session');\n }\n if (options.login !== undefined) {\n if (typeof options.login !== 'function') {\n throw new Error('CatalogDashboardModule: dashboardAuth.login must be a function.');\n }\n modes.push('login');\n }\n if (options.revalidate !== undefined && typeof options.revalidate !== 'function') {\n throw new Error('CatalogDashboardModule: dashboardAuth.revalidate must be a function.');\n }\n if (\n options.unauthenticatedPage !== undefined &&\n typeof options.unauthenticatedPage !== 'function'\n ) {\n throw new Error(\n 'CatalogDashboardModule: dashboardAuth.unauthenticatedPage must be a function.',\n );\n }\n if (modes.length === 0) {\n throw new Error(\n 'CatalogDashboardModule: dashboardAuth needs at least one of `session` or `login` ' +\n '(otherwise the cookie can never be minted). Failing closed.',\n );\n }\n return {\n secret: options.secret,\n ttlMs: durationToMs(options.ttl ?? DEFAULT_TTL),\n modes,\n ...(options.session !== undefined ? { session: options.session } : {}),\n ...(options.login !== undefined ? { login: options.login } : {}),\n ...(options.revalidate !== undefined ? { revalidate: options.revalidate } : {}),\n ...(options.unauthenticatedPage !== undefined\n ? { unauthenticatedPage: options.unauthenticatedPage }\n : {}),\n };\n}\n","/**\n * Parse a raw `Cookie` request header into a name→value map. Dependency-free so it works on raw\n * Express AND Fastify requests without `cookie-parser`. Values are URL-decoded; malformed\n * segments are skipped, never thrown.\n */\nexport function parseCookieHeader(header: string | undefined): Record<string, string> {\n const cookies: Record<string, string> = {};\n if (typeof header !== 'string' || header === '') return cookies;\n for (const segment of header.split(';')) {\n const eq = segment.indexOf('=');\n if (eq <= 0) continue;\n const name = segment.slice(0, eq).trim();\n if (name === '') continue;\n let rawValue = segment.slice(eq + 1).trim();\n // Strip a single pair of wrapping double-quotes (RFC 6265 quoted form).\n if (rawValue.length >= 2 && rawValue.startsWith('\"') && rawValue.endsWith('\"')) {\n rawValue = rawValue.slice(1, -1);\n }\n // First occurrence wins; don't clobber an earlier value with a later dup.\n if (name in cookies) continue;\n try {\n cookies[name] = decodeURIComponent(rawValue);\n } catch {\n cookies[name] = rawValue;\n }\n }\n return cookies;\n}\n\nexport interface SetCookieOptions {\n /** Cookie `Path`. The dashboard scopes its session cookie to `/` — see `session-cookie-io.ts`\n * for why (the UI mount and the JSON API mount can be configured to live at unrelated paths). */\n path: string;\n /** Cookie lifetime in seconds. Ignored (and forced to 0) when `clear` is set. */\n maxAgeSeconds: number;\n /** Add `Secure` when the request is https. */\n secure: boolean;\n /** Clear the cookie: empty value + `Max-Age=0` (and `Expires` in the past). */\n clear?: boolean;\n}\n\n/**\n * Serialize a `Set-Cookie` header value. Always `HttpOnly` + `SameSite=Lax` (Lax blocks\n * cross-site `POST`s carrying the cookie — CSRF coverage for the login/logout endpoints).\n * Platform-agnostic: just a string.\n */\nexport function serializeSetCookie(name: string, value: string, options: SetCookieOptions): string {\n const parts = [`${name}=${options.clear ? '' : encodeURIComponent(value)}`];\n parts.push(`Path=${options.path}`);\n parts.push('HttpOnly');\n parts.push('SameSite=Lax');\n if (options.secure) parts.push('Secure');\n if (options.clear) {\n parts.push('Max-Age=0');\n parts.push('Expires=Thu, 01 Jan 1970 00:00:00 GMT');\n } else {\n parts.push(`Max-Age=${options.maxAgeSeconds}`);\n }\n return parts.join('; ');\n}\n","function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction readHeaders(request: unknown): Record<string, unknown> {\n if (!isRecord(request)) return {};\n const headers = request.headers;\n return isRecord(headers) ? headers : {};\n}\n\n/** Coerce a single header (string or string[]) to a string, else undefined. */\nfunction headerToString(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value) && value.every((part) => typeof part === 'string')) {\n return value.join(',');\n }\n return undefined;\n}\n\n/** Read the raw `Cookie` request header (Express and Fastify both expose `headers`). */\nexport function readCookieHeader(request: unknown): string | undefined {\n return headerToString(readHeaders(request).cookie);\n}\n\n/**\n * Decide whether the cookie should carry `Secure`. True when the request is https directly\n * (`request.protocol === 'https'`) OR a proxy forwarded https (`x-forwarded-proto` includes\n * 'https'). Defensive structural reads — never throws, defaults to insecure (works on plain http\n * in dev).\n */\nexport function isHttpsRequest(request: unknown): boolean {\n if (isRecord(request) && request.protocol === 'https') return true;\n const forwarded = headerToString(readHeaders(request)['x-forwarded-proto']);\n if (forwarded === undefined) return false;\n return forwarded\n .split(',')\n .map((proto) => proto.trim().toLowerCase())\n .includes('https');\n}\n\n/** The path + query a browser navigated to (Express's `originalUrl`, else the generic `url`). */\nexport function originalRequestUrl(request: unknown): string {\n if (!isRecord(request)) return '/';\n if (typeof request.originalUrl === 'string' && request.originalUrl !== '') {\n return request.originalUrl;\n }\n if (typeof request.url === 'string' && request.url !== '') return request.url;\n return '/';\n}\n\n/**\n * Guard a client-supplied redirect target against an open redirect: it must be a same-origin,\n * root-relative path (`/catalog/foo`), never a protocol-relative (`//evil.com`) or absolute\n * (`https://evil.com`) URL. Falls back to `fallback` (typically the dashboard's own `basePath`)\n * for anything else, including a missing/non-string value.\n */\nexport function sanitizeReturnTo(candidate: unknown, fallback: string): string {\n if (typeof candidate !== 'string') return fallback;\n if (!candidate.startsWith('/')) return fallback;\n if (candidate.startsWith('//')) return fallback;\n if (candidate.includes('://')) return fallback;\n return candidate;\n}\n","function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\ninterface RawCookieResponse {\n getHeader(name: string): number | string | string[] | undefined;\n setHeader(name: string, value: string | string[]): unknown;\n}\n\nfunction isRawCookieResponse(value: unknown): value is RawCookieResponse {\n return (\n isRecord(value) &&\n typeof value.getHeader === 'function' &&\n typeof value.setHeader === 'function'\n );\n}\n\n/**\n * Resolve the writable Node `ServerResponse` from a platform response. Express' response IS the\n * Node response; Fastify's reply wraps it on `.raw`. Returns the outer response when it already\n * exposes get/setHeader (Express), otherwise the unwrapped `.raw` (Fastify) — so a single write\n * path serves both without a platform-specific dependency.\n */\nfunction resolveCookieResponse(response: unknown): RawCookieResponse | null {\n if (isRawCookieResponse(response)) return response;\n if (isRecord(response) && isRawCookieResponse(response.raw)) return response.raw;\n return null;\n}\n\nfunction existingSetCookies(response: RawCookieResponse): string[] {\n const current = response.getHeader('set-cookie');\n if (Array.isArray(current)) return current;\n if (typeof current === 'string') return [current];\n return [];\n}\n\n/**\n * Append a `Set-Cookie` header to the response WITHOUT clobbering any cookies already queued by\n * the host. Platform-agnostic raw write — no-ops gracefully if the response can't be unwrapped.\n */\nexport function appendSetCookie(response: unknown, cookie: string): void {\n const raw = resolveCookieResponse(response);\n if (!raw) return;\n raw.setHeader('set-cookie', [...existingSetCookies(raw), cookie]);\n}\n\ninterface RawRedirectResponse extends RawCookieResponse {\n statusCode: number;\n end(chunk?: string): unknown;\n}\n\nfunction isRawRedirectResponse(value: unknown): value is RawRedirectResponse {\n return (\n isRecord(value) &&\n typeof value.getHeader === 'function' &&\n typeof value.setHeader === 'function' &&\n typeof value.end === 'function'\n );\n}\n\nfunction resolveRedirectResponse(response: unknown): RawRedirectResponse | null {\n if (isRawRedirectResponse(response)) return response;\n if (isRecord(response) && isRawRedirectResponse(response.raw)) return response.raw;\n return null;\n}\n\n/**\n * Write a redirect directly on the raw response and END it. Used from the `DashboardLoginRedirect`\n * exception filter (guards can't use `@Redirect()` — that decorator only applies to a controller\n * handler's return value) and by the manual, non-passthrough logout handler. Bypassing Nest's\n * normal \"send the handler's return value\" pipeline this way is only safe when NOTHING downstream\n * (a filter, or Nest itself) will also try to write to the same response — both call sites here\n * are the terminal step of their request (an exception filter, or a `@Res()` non-passthrough\n * handler), so there is no second writer to race.\n */\nexport function redirectRaw(response: unknown, location: string, status = 302): void {\n const raw = resolveRedirectResponse(response);\n if (!raw) return;\n raw.statusCode = status;\n raw.setHeader('location', location);\n raw.end();\n}\n\n/**\n * Did something already write to this response?\n *\n * Used to decide whether a host's `unauthenticatedPage` hook actually produced a page. A hook that\n * returns without writing (an early `return`, a forgotten `await`, a template that resolved to\n * nothing) would otherwise leave the request hanging forever — the browser spins until it times\n * out, with no error anywhere. Checking this lets the caller fall back to the built-in page.\n *\n * Reads the Node `ServerResponse.headersSent` through the same Express/Fastify unwrapping as the\n * writers above; Fastify's own `reply.sent` is not consulted because `.raw.headersSent` is true in\n * every case that matters here (the reply has been flushed to the socket).\n */\nexport function responseAlreadyWritten(response: unknown): boolean {\n const raw = resolveRedirectResponse(response) as\n | (RawRedirectResponse & { headersSent?: boolean })\n | null;\n return raw?.headersSent === true;\n}\n\n/**\n * Write a full HTML page directly on the raw response and END it. Used by\n * `DashboardSessionRequiredFilter` (the Mode-A-only instruction page a guard renders in place of a\n * login redirect that no longer exists) — same raw-response bypass, and the same reason it's safe:\n * an exception filter is the terminal step of the request, so there's no second writer to race.\n */\nexport function writeHtmlRaw(response: unknown, html: string, status = 200): void {\n const raw = resolveRedirectResponse(response);\n if (!raw) return;\n raw.statusCode = status;\n raw.setHeader('content-type', 'text/html; charset=utf-8');\n // Same as the auth controller's `@Header('Cache-Control', ...)` on the sibling login page: this\n // page reflects live session state, so it must never be served stale from a cache.\n raw.setHeader('cache-control', 'no-store, must-revalidate');\n raw.end(html);\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\n\n/** Clock-skew grace applied to `exp` so a marginally-late clock doesn't bounce a valid cookie. */\nconst EXP_GRACE_MS = 30_000;\n\n/** The validated dashboard session attached to a request once its cookie verifies. */\nexport interface DashboardSession {\n /** Stable user id (the session user's `id`). */\n sub: string;\n /** Optional display name. */\n name?: string;\n /** Free-form role strings; the dashboard does not interpret them. */\n roles: string[];\n /** Issued-at, epoch milliseconds. */\n iat: number;\n /** Expiry, epoch milliseconds. */\n exp: number;\n}\n\n/** The session user the host `login` hook returns to mint a cookie. */\nexport interface DashboardSessionUser {\n id: string;\n name?: string;\n roles?: string[];\n}\n\nexport interface SignOptions {\n secret: string;\n ttlMs: number;\n /** Injectable clock (epoch ms) for deterministic tests. Defaults to `Date.now()`. */\n now?: number;\n}\n\nexport interface VerifyOptions {\n secret: string;\n /** Injectable clock (epoch ms) for deterministic tests. Defaults to `Date.now()`. */\n now?: number;\n}\n\nfunction base64urlEncode(value: string): string {\n return Buffer.from(value, 'utf8').toString('base64url');\n}\n\nfunction base64urlDecode(value: string): string {\n return Buffer.from(value, 'base64url').toString('utf8');\n}\n\nfunction hmac(secret: string, payload: string): string {\n return createHmac('sha256', secret).update(payload).digest('base64url');\n}\n\n/**\n * Sign a session into the cookie value `base64url(payload).base64url(hmac)`. Stateless\n * HMAC-SHA256, no store, `node:crypto` only — no JWT dependency. Mirrors\n * `@dudousxd/nestjs-telescope`'s `dashboardAuth` cookie mechanism so the behavior is familiar\n * across the aviary consoles.\n */\nexport function signSessionCookie(user: DashboardSessionUser, options: SignOptions): string {\n const issuedAt = options.now ?? Date.now();\n const session: DashboardSession = {\n sub: user.id,\n ...(user.name !== undefined ? { name: user.name } : {}),\n roles: user.roles ?? [],\n iat: issuedAt,\n exp: issuedAt + options.ttlMs,\n };\n const encodedPayload = base64urlEncode(JSON.stringify(session));\n const signature = hmac(options.secret, encodedPayload);\n return `${encodedPayload}.${signature}`;\n}\n\n/** Type guard for the decoded payload shape — defends against tampered/legacy payloads. */\nfunction isSessionPayload(value: unknown): value is DashboardSession {\n if (typeof value !== 'object' || value === null) return false;\n const record: Record<string, unknown> = { ...value };\n if (typeof record.sub !== 'string') return false;\n if (record.name !== undefined && typeof record.name !== 'string') return false;\n if (!Array.isArray(record.roles)) return false;\n if (!record.roles.every((role) => typeof role === 'string')) return false;\n if (typeof record.iat !== 'number' || !Number.isFinite(record.iat)) return false;\n if (typeof record.exp !== 'number' || !Number.isFinite(record.exp)) return false;\n return true;\n}\n\n/**\n * Verify a cookie value and return the session, or `null` for anything that's tampered,\n * malformed, or expired (past `exp` + a 30s grace). Constant-time signature comparison. NEVER\n * throws — any parse failure yields `null`.\n */\nexport function verifySessionCookie(\n value: string,\n options: VerifyOptions,\n): DashboardSession | null {\n try {\n const dot = value.indexOf('.');\n if (dot <= 0 || dot === value.length - 1) return null;\n const encodedPayload = value.slice(0, dot);\n const providedSignature = value.slice(dot + 1);\n const expectedSignature = hmac(options.secret, encodedPayload);\n const provided = Buffer.from(providedSignature, 'base64url');\n const expected = Buffer.from(expectedSignature, 'base64url');\n // timingSafeEqual throws on a length mismatch — guard it so a wrong-length (tampered)\n // signature returns null instead of throwing.\n if (provided.length !== expected.length) return null;\n if (!timingSafeEqual(provided, expected)) return null;\n const decoded: unknown = JSON.parse(base64urlDecode(encodedPayload));\n if (!isSessionPayload(decoded)) return null;\n const now = options.now ?? Date.now();\n if (now > decoded.exp + EXP_GRACE_MS) return null;\n const session: DashboardSession = {\n sub: decoded.sub,\n ...(decoded.name !== undefined ? { name: decoded.name } : {}),\n roles: decoded.roles,\n iat: decoded.iat,\n exp: decoded.exp,\n };\n return session;\n } catch {\n return null;\n }\n}\n","import { parseCookieHeader, serializeSetCookie } from './cookie-header.js';\nimport type { ResolvedDashboardAuth } from './dashboard-auth-config.js';\nimport { isHttpsRequest, readCookieHeader } from './request.js';\nimport { appendSetCookie } from './response.js';\nimport {\n type DashboardSession,\n type DashboardSessionUser,\n signSessionCookie,\n verifySessionCookie,\n} from './session-cookie.js';\n\n/** Cookie name carrying the signed dashboard session. */\nexport const SESSION_COOKIE_NAME = 'catalog_dashboard_session';\n\n/**\n * `Path=/`, deliberately not scoped to `basePath`/`apiBasePath`: the two mounts are independently\n * configurable (`CatalogDashboardModule.forRoot({ basePath, apiBasePath })`) and can live at\n * unrelated paths (e.g. a `/catalog` UI + an `/api/catalog-service` API) — a cookie scoped to either one alone\n * would not reach the other. The cookie is `HttpOnly` + signed + short-lived, so the broader scope\n * is a reasonable trade for correctness across any mount configuration.\n */\nconst COOKIE_PATH = '/';\n\n/**\n * Sign a fresh session for `user` and append it as a `Set-Cookie` on the response, `Secure` when\n * the request is https.\n */\nexport function issueSessionCookie(\n user: DashboardSessionUser,\n context: {\n auth: ResolvedDashboardAuth;\n request: unknown;\n response: unknown;\n now?: number;\n },\n): void {\n const value = signSessionCookie(user, {\n secret: context.auth.secret,\n ttlMs: context.auth.ttlMs,\n ...(context.now !== undefined ? { now: context.now } : {}),\n });\n const cookie = serializeSetCookie(SESSION_COOKIE_NAME, value, {\n path: COOKIE_PATH,\n maxAgeSeconds: Math.floor(context.auth.ttlMs / 1000),\n secure: isHttpsRequest(context.request),\n });\n appendSetCookie(context.response, cookie);\n}\n\n/** Append a cookie-clearing `Set-Cookie` (Max-Age=0). */\nexport function clearSessionCookie(context: { request: unknown; response: unknown }): void {\n const cookie = serializeSetCookie(SESSION_COOKIE_NAME, '', {\n path: COOKIE_PATH,\n maxAgeSeconds: 0,\n secure: isHttpsRequest(context.request),\n clear: true,\n });\n appendSetCookie(context.response, cookie);\n}\n\n/** Read + verify the session cookie on `request`, or `null` when absent/tampered/expired. */\nexport function readSessionFromRequest(\n auth: ResolvedDashboardAuth,\n request: unknown,\n): DashboardSession | null {\n const cookieValue = parseCookieHeader(readCookieHeader(request))[SESSION_COOKIE_NAME];\n if (cookieValue === undefined) return null;\n return verifySessionCookie(cookieValue, { secret: auth.secret });\n}\n\n/**\n * In-flight `revalidate` calls, keyed by `<secret>:<sub>` (the secret disambiguates two\n * `dashboardAuth` configs that happen to share a process, e.g. tests) — joined, not repeated, by\n * every concurrent renewal of the SAME session. Entries are removed the moment their call settles\n * (`finally`, below), so this only ever holds calls genuinely in flight right now: it can't grow\n * without bound, and a throwing hook can't wedge a session's future renewals.\n */\nconst inFlightRevalidations = new Map<string, Promise<boolean>>();\n\n/**\n * Run `auth.revalidate` for `user`, joining an already-in-flight call for the same session instead\n * of starting a second one. This is what makes the `RevalidateHook` doc's \"runs at most once per\n * `ttl/2` per session\" true under real traffic: a single console page load fires several parallel\n * API calls, and without this every one of them carrying the same past-half-life cookie would\n * independently call the host's hook before the first renewal's fresh cookie lands. Every caller\n * still awaits the SAME outcome and applies it to its OWN request/response — only the host round\n * trip is shared.\n */\nfunction revalidateOnce(auth: ResolvedDashboardAuth, user: DashboardSessionUser): Promise<boolean> {\n const revalidate = auth.revalidate;\n if (!revalidate) return Promise.resolve(true);\n const key = `${auth.secret}:${user.id}`;\n const inFlight = inFlightRevalidations.get(key);\n if (inFlight) return inFlight;\n const call = Promise.resolve()\n .then(() => revalidate(user))\n // Fail closed: a throwing hook revokes rather than silently extending the session.\n .catch(() => false)\n .finally(() => {\n // Cleared on BOTH outcomes (the `.catch` above means this only ever sees a resolution, never\n // a rejection) so a later, non-concurrent renewal cycle calls the hook fresh rather than\n // reusing a stale result — and so the map never accumulates settled entries.\n inFlightRevalidations.delete(key);\n });\n inFlightRevalidations.set(key, call);\n return call;\n}\n\n/**\n * Sliding renewal + revalidation. When a valid cookie is past 50% of its TTL, re-issue a fresh one\n * so an active session never expires mid-use — but first give the host's `revalidate` hook a say,\n * so a deactivated or demoted user loses access instead of riding a self-renewing cookie forever.\n * Concurrent renewals of the same session share one `revalidate` call (see `revalidateOnce`).\n *\n * Returns `false` when the session was revoked (the clearing `Set-Cookie` is already queued and the\n * caller must deny the request); `true` otherwise, including when no renewal was due.\n */\nexport async function maybeRenewSession(\n auth: ResolvedDashboardAuth,\n session: DashboardSession,\n request: unknown,\n response: unknown,\n now: number = Date.now(),\n): Promise<boolean> {\n if (now - session.iat <= auth.ttlMs / 2) return true;\n const user: DashboardSessionUser = {\n id: session.sub,\n ...(session.name !== undefined ? { name: session.name } : {}),\n roles: session.roles,\n };\n const allowed = await revalidateOnce(auth, user);\n if (!allowed) {\n clearSessionCookie({ request, response });\n return false;\n }\n issueSessionCookie(user, { auth, request, response, now });\n return true;\n}\n","import {\n BadRequestException,\n Body,\n Controller,\n Get,\n Header,\n HttpCode,\n Inject,\n Logger,\n NotFoundException,\n Optional,\n Post,\n Req,\n Res,\n UnauthorizedException,\n} from '@nestjs/common';\nimport { DASHBOARD_AUTH, type ResolvedDashboardAuth } from './auth/dashboard-auth-config.js';\nimport { renderLoginPage } from './auth/login-page.js';\nimport { sanitizeReturnTo } from './auth/request.js';\nimport { redirectRaw } from './auth/response.js';\nimport { clearSessionCookie, issueSessionCookie } from './auth/session-cookie-io.js';\nimport type { DashboardSessionUser } from './auth/session-cookie.js';\nimport { DASHBOARD_BASE_PATH } from './catalog-ui.controller.js';\n\ninterface LoginBody {\n username?: unknown;\n password?: unknown;\n returnTo?: unknown;\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n/**\n * Mints/clears the `dashboardAuth` session cookie and serves the built-in login page. Mounted\n * under `basePath` alongside `CatalogUiController` (see `CatalogDashboardModule.forRoot`), but on\n * a SEPARATE controller so it is never itself behind `CatalogUiSessionGuard` — these endpoints\n * CREATE the session that guard checks for. `@Optional()` on both injections: this controller is\n * only registered when `dashboardAuth` might be configured (a static `forRoot({ dashboardAuth })`\n * or any `forRootAsync`), but the resolved value can still be `null` at runtime for the async case\n * — every handler below re-checks it and 404s rather than assuming it is set.\n */\n@Controller()\nexport class CatalogAuthController {\n private readonly logger = new Logger(CatalogAuthController.name);\n /** Warn once per hook kind so a throwing hook doesn't spam logs on every failed attempt. */\n private readonly warnedHooks = new Set<string>();\n\n constructor(\n @Optional() @Inject(DASHBOARD_AUTH) private readonly auth: ResolvedDashboardAuth | null,\n @Inject(DASHBOARD_BASE_PATH) private readonly basePath: string,\n ) {}\n\n // The login page reads `returnTo`/`error` from `location.search` client-side (see\n // `login-page.ts`), so this response never varies per request and needs no templating beyond\n // the developer-controlled `basePath`.\n @Get('login')\n @Header('Content-Type', 'text/html; charset=utf-8')\n @Header('Cache-Control', 'no-store, must-revalidate')\n loginPage(): string {\n const auth = this.requireAuth();\n if (!auth.modes.includes('login')) throw new NotFoundException();\n return renderLoginPage(this.basePath);\n }\n\n // Called by the login page's own fetch (JSON, not a classic form POST — see `login-page.ts` for\n // why: it keeps the login page working with no host-configured body parser beyond the\n // JSON one Nest wires in by default on both Express and Fastify). Uniform `401` on any failure\n // (unknown user, wrong password, throwing hook) — no user-enumeration.\n @Post('login')\n @HttpCode(200)\n async login(\n @Body() body: LoginBody,\n @Req() request: unknown,\n @Res({ passthrough: true }) response: unknown,\n ): Promise<{ redirectTo: string }> {\n const auth = this.requireAuth();\n if (!auth.modes.includes('login')) throw new NotFoundException();\n if (!isString(body?.username) || !isString(body?.password)) {\n throw new BadRequestException('Body must include string `username` and `password`.');\n }\n const { username, password } = body;\n const user = await this.runHook('login', () => auth.login?.(username, password) ?? null);\n if (!user) throw new UnauthorizedException({ message: 'Invalid username or password.' });\n issueSessionCookie(user, { auth, request, response });\n return { redirectTo: sanitizeReturnTo(body.returnTo, this.basePath) };\n }\n\n // Mode A: the host frontend (carrying its own auth) POSTs here; the host hook validates the raw\n // request and returns the session user, or `null` to deny. This is the SSO path — the host's own\n // guard decides, and no credential ever reaches this library.\n @Post('session')\n @HttpCode(204)\n async session(\n @Req() request: unknown,\n @Res({ passthrough: true }) response: unknown,\n ): Promise<void> {\n const auth = this.requireAuth();\n // Mode A not configured => the endpoint does not exist for this host.\n if (!auth.modes.includes('session')) throw new NotFoundException();\n const user = await this.runHook('session', () => auth.session?.(request) ?? null);\n if (!user) throw new UnauthorizedException();\n issueSessionCookie(user, { auth, request, response });\n }\n\n // Plain `GET` (not `POST`): logging out only ever destroys the CALLER's own session, so it's\n // safe/idempotent from the caller's perspective — a simple `<a href>` (no JS, no CSRF token)\n // works. Non-passthrough `@Res()`: this handler owns the response outright (clears the cookie,\n // then redirects), so Nest must not also try to send a return value afterwards.\n @Get('logout')\n logout(@Req() request: unknown, @Res() response: unknown): void {\n // Best-effort: even without dashboardAuth configured, clearing is harmless.\n clearSessionCookie({ request, response });\n // Only bounce to the login page when Mode B is actually configured — under Mode A (only), that\n // page 404s (see loginPage()); redirecting to basePath instead lands back on the guarded UI,\n // which renders the Mode-A session-required instruction page.\n redirectRaw(\n response,\n this.auth?.modes.includes('login') ? `${this.basePath}/login` : this.basePath,\n );\n }\n\n private requireAuth(): ResolvedDashboardAuth {\n // login()/session()/logout() only reach a real request when dashboardAuth is configured — this\n // is a defensive guard (matching loginPage()'s 404), not a reachable runtime path in practice.\n if (!this.auth) throw new NotFoundException();\n return this.auth;\n }\n\n /**\n * Run a host hook (`login` or `session`) defensively: a throw is treated as a denial (uniform\n * failure) and warn-logged once PER KIND, so a buggy hook never 500s the endpoint into a\n * stack-trace leak nor floods the logs on repeated bad attempts.\n */\n private async runHook(\n kind: string,\n run: () => Promise<DashboardSessionUser | null> | DashboardSessionUser | null,\n ): Promise<DashboardSessionUser | null> {\n try {\n return (await run()) ?? null;\n } catch (error) {\n if (!this.warnedHooks.has(kind)) {\n this.warnedHooks.add(kind);\n this.logger.warn(\n `dashboardAuth ${kind} hook threw; treating as denial. ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return null;\n }\n }\n}\n","/**\n * Shared HTML shell for the `dashboardAuth` server-rendered pages (the Mode B login page below and\n * `renderSessionRequiredPage`'s Mode A instruction page) — same dark zinc card, mono type, emerald\n * accent as `@dudousxd/nestjs-agent`'s dashboard login page, so every auth-adjacent page in this\n * family looks like one product. `content` is placed inside the `.card` div verbatim, so a caller\n * needing its own `<script>` (see `renderLoginPage`) can simply include it in `content` — a\n * `<script>` renders identically whether it's the div's last child or a body-level sibling.\n *\n * `content` is always caller-controlled static markup, never user input reflected into the page,\n * so this sidesteps HTML-escaping entirely.\n */\nfunction page(content: string, title = 'Catalog'): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<meta name=\"robots\" content=\"noindex, nofollow\" />\n<title>${title}</title>\n<style>\n :root { color-scheme: dark; }\n * { box-sizing: border-box; }\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: #09090b;\n color: #e4e4e7;\n font: 14px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n padding: 16px;\n }\n .card {\n width: 100%;\n max-width: 384px;\n border: 1px solid #27272a;\n background: #18181b;\n border-radius: 8px;\n padding: 32px;\n box-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.5);\n }\n .brand {\n margin: 0 0 24px;\n text-align: center;\n font-size: 18px;\n font-weight: 600;\n color: #34d399;\n }\n h1 {\n margin: 0 0 12px;\n font-size: 16px;\n font-weight: 600;\n color: #f4f4f5;\n }\n p { margin: 0 0 16px; color: #a1a1aa; }\n form { display: flex; flex-direction: column; gap: 16px; }\n label { display: flex; flex-direction: column; gap: 6px; }\n .field-label {\n font-size: 11px;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: #71717a;\n }\n input {\n border-radius: 4px;\n border: 1px solid #3f3f46;\n background: #09090b;\n color: #f4f4f5;\n padding: 8px 12px;\n font: inherit;\n outline: none;\n }\n input:focus { border-color: rgb(52 211 153 / 0.6); }\n #error {\n display: none;\n margin: 0;\n font-size: 12px;\n color: #fb7185;\n }\n button, .button {\n margin-top: 8px;\n border-radius: 4px;\n border: 1px solid rgb(52 211 153 / 0.4);\n background: rgb(52 211 153 / 0.1);\n color: #6ee7b7;\n padding: 8px 12px;\n font: inherit;\n font-size: 12px;\n font-weight: 500;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n cursor: pointer;\n display: inline-block;\n text-align: center;\n text-decoration: none;\n box-sizing: border-box;\n }\n button:hover:not(:disabled), .button:hover { background: rgb(52 211 153 / 0.2); }\n button:disabled { opacity: 0.6; cursor: default; }\n</style>\n</head>\n<body>\n <div class=\"card\">\n ${content}\n </div>\n</body>\n</html>`;\n}\n\n/**\n * The built-in `dashboardAuth` login page (`GET <basePath>/login`, Mode B). Deliberately a small,\n * dependency-free, hand-authored HTML page — NOT part of the bundled React SPA — so gating the\n * dashboard shell doesn't require rebuilding or extending the Vite bundle with a new route/screen.\n *\n * `returnTo` and any error state are read CLIENT-SIDE from `location.search` (never server-echoed\n * into the HTML), so this function's only per-request-ish input is `basePath` — a developer-\n * controlled config value, not user input — and the page body is otherwise a static template.\n *\n * The submit flow (this page POSTs JSON via `fetch` and follows the JSON `redirectTo` it gets\n * back, rather than a classic form POST + server redirect) is why the markup keeps its own\n * `<script>` rather than adopting agent-dashboard's plain `<form method=\"post\">`.\n */\nexport function renderLoginPage(basePath: string): string {\n const loginAction = `${basePath}/login`;\n const defaultReturnTo = basePath;\n return page(\n `<p class=\"brand\">Catalog</p>\n <form id=\"login-form\" autocomplete=\"on\">\n <label>\n <span class=\"field-label\">Username</span>\n <input id=\"username\" name=\"username\" type=\"text\" autocomplete=\"username\" required autofocus />\n </label>\n <label>\n <span class=\"field-label\">Password</span>\n <input id=\"password\" name=\"password\" type=\"password\" autocomplete=\"current-password\" />\n </label>\n <p id=\"error\" role=\"alert\">Invalid username or password.</p>\n <button id=\"submit\" type=\"submit\">Sign in</button>\n </form>\n<script>\n(function () {\n var LOGIN_ACTION = ${JSON.stringify(loginAction)};\n var DEFAULT_RETURN_TO = ${JSON.stringify(defaultReturnTo)};\n var params = new URLSearchParams(window.location.search);\n var errorBox = document.getElementById('error');\n if (params.get('error')) errorBox.style.display = 'block';\n\n function sameOriginReturnTo(value) {\n if (typeof value !== 'string' || value === '') return DEFAULT_RETURN_TO;\n if (value.charAt(0) !== '/' || value.charAt(1) === '/' || value.indexOf('://') !== -1) {\n return DEFAULT_RETURN_TO;\n }\n return value;\n }\n\n var form = document.getElementById('login-form');\n var submitButton = document.getElementById('submit');\n form.addEventListener('submit', function (event) {\n event.preventDefault();\n submitButton.disabled = true;\n errorBox.style.display = 'none';\n var returnTo = sameOriginReturnTo(params.get('returnTo'));\n fetch(LOGIN_ACTION, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n credentials: 'same-origin',\n body: JSON.stringify({\n username: document.getElementById('username').value,\n password: document.getElementById('password').value,\n returnTo: returnTo,\n }),\n })\n .then(function (response) {\n if (!response.ok) throw new Error('unauthorized');\n return response.json();\n })\n .then(function (data) {\n window.location.href = data.redirectTo || DEFAULT_RETURN_TO;\n })\n .catch(function () {\n errorBox.style.display = 'block';\n submitButton.disabled = false;\n });\n });\n})();\n</script>`,\n 'Sign in — Catalog',\n );\n}\n\n/**\n * Mode-A-only shell (`GET <basePath>/login` never renders under Mode A — this is what the page\n * guard serves in its place, see `session-required.exception.ts`): there is no form here because\n * the host mints the session. Mirrors `renderLoginPage`'s markup so the two pages look like one\n * product. `basePath` drives the Retry link's `href` — a plain `<a>` back to the guarded mount\n * (which re-runs the check once the host has minted a session), keeping this page free of any\n * inline `<script>`, unlike `renderLoginPage`'s fetch-driven form.\n */\nexport function renderSessionRequiredPage(basePath: string): string {\n return page(\n `<h1>Open this console from your application</h1>\n <p>Your session is minted by the host app. Use its console launcher to sign in, then reload.</p>\n <a class=\"button\" href=\"${basePath}\">Retry</a>`,\n );\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { basename, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n Controller,\n Get,\n Header,\n Inject,\n NotFoundException,\n Optional,\n Param,\n StreamableFile,\n UseFilters,\n} from '@nestjs/common';\nimport { DASHBOARD_AUTH } from './auth/dashboard-auth-config.js';\nimport { DashboardLoginRedirectFilter } from './auth/login-redirect.exception.js';\nimport { DashboardSessionRequiredFilter } from './auth/session-required.exception.js';\n\n/** DI token carrying the UI mount base (e.g. `/catalog`). */\nexport const DASHBOARD_BASE_PATH = Symbol('DASHBOARD_BASE_PATH');\n/** DI token carrying the JSON API base the SPA fetches from (e.g. `/api/catalog`). */\nexport const DASHBOARD_API_PATH = Symbol('DASHBOARD_API_PATH');\n\n/** The base the SPA bundle was built with (Vite `base`); rewritten to the configured base at serve time. */\nconst BUILD_BASE = '/catalog';\n\n/** dist/server/catalog-ui.controller.js -> ../spa (the Vite build output). */\nfunction spaDir(): string {\n return fileURLToPath(new URL('../spa', import.meta.url));\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.json': 'application/json; charset=utf-8',\n '.woff2': 'font/woff2',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Serves the bundled control-plane SPA at the configured base (+ hashed assets at `<base>/assets`).\n * The path comes from `RouterModule` (set by `CatalogDashboardModule.forRoot({ basePath })`), so the\n * controller routes are relative.\n *\n * `@UseFilters(DashboardLoginRedirectFilter, DashboardSessionRequiredFilter)` is permanent (present\n * regardless of whether `dashboardAuth` is configured): each only ever activates for its own\n * exception type, which `CatalogUiSessionGuard` only throws when it is ALSO stamped on this\n * controller (see `CatalogDashboardModule.forRoot`) — so leaving them decorated here is inert, not\n * a behavior change, when `dashboardAuth` is absent. The guard picks between the two exceptions\n * based on which mode is configured (Mode B => redirect to the login page; Mode A only => render\n * the session-required instruction page in place, since there is no login page to redirect to).\n */\n@UseFilters(DashboardLoginRedirectFilter, DashboardSessionRequiredFilter)\n@Controller()\nexport class CatalogUiController {\n private readonly dir = spaDir();\n\n constructor(\n @Inject(DASHBOARD_BASE_PATH) private readonly basePath: string,\n @Inject(DASHBOARD_API_PATH) private readonly apiBasePath: string,\n @Optional()\n @Inject(DASHBOARD_AUTH)\n private readonly auth: unknown = null,\n ) {}\n\n // index.html references hash-named bundles, so it MUST NOT be cached (stale bundle = the\n // classic \"stuck loading after a deploy\"). The hashed assets below are immutable.\n @Get()\n @Header('Content-Type', 'text/html; charset=utf-8')\n @Header('Cache-Control', 'no-store, must-revalidate')\n index(): string {\n const indexPath = join(this.dir, 'index.html');\n if (!existsSync(indexPath)) {\n throw new NotFoundException('Dashboard is not built. Run the package build.');\n }\n // The bundle was built with Vite base `/catalog/`; rewrite asset URLs to the configured base so\n // the SPA loads from `<base>/assets` wherever it's mounted, and tell the client its API base.\n const html = readFileSync(indexPath, 'utf8').replaceAll(\n `=\"${BUILD_BASE}/`,\n `=\"${this.basePath}/`,\n );\n // __CATALOG_BASE__ = where assets load; __CATALOG_API__ = where the SPA fetches the JSON API;\n // __CATALOG_HOST_AUTH__ = whether the HOST authenticates, in which case the SPA must not show\n // its own sign-in. A console mounted inside an application that already knows who you are and\n // then asks you to log in again is not a smaller problem than one that lets anybody in.\n const hostAuth = this.auth ? 'true' : 'false';\n const inject = `<script>window.__CATALOG_BASE__='${this.basePath}';window.__CATALOG_API__='${this.apiBasePath}';window.__CATALOG_HOST_AUTH__=${hostAuth};</script>`;\n return html.includes('</head>') ? html.replace('</head>', `${inject}</head>`) : inject + html;\n }\n\n @Get('assets/:file')\n @Header('Cache-Control', 'public, max-age=31536000, immutable')\n asset(@Param('file') file: string): StreamableFile {\n const safe = basename(file);\n if (safe !== file) throw new NotFoundException();\n const root = resolve(this.dir, 'assets');\n const assetPath = resolve(root, safe);\n if (!assetPath.startsWith(root + sep) || !existsSync(assetPath)) {\n throw new NotFoundException();\n }\n const type = CONTENT_TYPES[extname(safe)] ?? 'application/octet-stream';\n return new StreamableFile(readFileSync(assetPath), { type });\n }\n}\n","import type { ArgumentsHost, ExceptionFilter } from '@nestjs/common';\nimport { Catch, HttpException, HttpStatus } from '@nestjs/common';\nimport { redirectRaw } from './response.js';\n\n/**\n * Thrown by `CatalogUiSessionGuard` when a page-level (full-page navigation) request has no valid\n * `dashboardAuth` session — carries the login URL to redirect to. Guards can't use Nest's\n * `@Redirect()` decorator (that only applies to a controller handler's return value), so the\n * guard throws this and a dedicated, controller-scoped `DashboardLoginRedirectFilter` (see below)\n * turns it into a real `302`. This is the ONLY safe way to redirect from a guard: writing directly\n * to the response inside `canActivate` and then returning `false` risks a double-write (Nest still\n * tries to send a `ForbiddenException` response afterwards) — routing through the normal\n * exception-filter pipeline instead guarantees exactly one writer finalizes the response.\n */\nexport class DashboardLoginRedirectException extends HttpException {\n constructor(public readonly location: string) {\n super({ location }, HttpStatus.FOUND);\n }\n}\n\n/** Turns a `DashboardLoginRedirectException` into a real `302 Location: <location>` response. */\n@Catch(DashboardLoginRedirectException)\nexport class DashboardLoginRedirectFilter implements ExceptionFilter {\n catch(exception: DashboardLoginRedirectException, host: ArgumentsHost): void {\n const response = host.switchToHttp().getResponse();\n redirectRaw(response, exception.location);\n }\n}\n","import type { ArgumentsHost, ExceptionFilter } from '@nestjs/common';\nimport { Catch, HttpException, HttpStatus, Inject, Logger, Optional } from '@nestjs/common';\nimport { DASHBOARD_AUTH, type ResolvedDashboardAuth } from './dashboard-auth-config.js';\nimport { renderSessionRequiredPage } from './login-page.js';\nimport { responseAlreadyWritten, writeHtmlRaw } from './response.js';\n\n/**\n * Thrown by `CatalogUiSessionGuard` when a page-level (full-page navigation) request has no valid\n * `dashboardAuth` session AND Mode B (`login`) isn't configured — there is no login page to\n * redirect to (see `DashboardLoginRedirectException`, its Mode-B sibling). Carries `basePath` so\n * the filter below can render the Mode-A instruction page in its place. Same reasoning as the\n * login redirect for why a guard can't just write the response directly and return `false`: a\n * dedicated, controller-scoped `DashboardSessionRequiredFilter` (see below) is the only writer,\n * guaranteeing no double-write race.\n */\nexport class DashboardSessionRequiredException extends HttpException {\n constructor(public readonly basePath: string) {\n super({ basePath }, HttpStatus.UNAUTHORIZED);\n }\n}\n\n/**\n * Renders the Mode-A page for a denied navigation: the host's own `unauthenticatedPage` when one is\n * configured, otherwise the built-in instruction card.\n *\n * `@Optional()` on the injection is load-bearing. This filter is decorated onto\n * `CatalogUiController` unconditionally (see that controller's docblock — it is inert when\n * `dashboardAuth` is absent, because the guard that throws its exception is only stamped on when\n * auth IS configured), so it must still construct in a module where `DASHBOARD_AUTH` was never\n * provided.\n */\n@Catch(DashboardSessionRequiredException)\nexport class DashboardSessionRequiredFilter implements ExceptionFilter {\n private readonly logger = new Logger(DashboardSessionRequiredFilter.name);\n private warned = false;\n\n constructor(\n @Optional()\n @Inject(DASHBOARD_AUTH)\n private readonly auth: ResolvedDashboardAuth | null = null,\n ) {}\n\n async catch(exception: DashboardSessionRequiredException, host: ArgumentsHost): Promise<void> {\n const http = host.switchToHttp();\n const response = http.getResponse();\n const hook = this.auth?.unauthenticatedPage;\n\n if (hook) {\n try {\n await hook({ request: http.getRequest(), response, basePath: exception.basePath });\n // The hook owns the response; if it wrote one, we are done.\n if (responseAlreadyWritten(response)) return;\n // It did not write. Falling through to the built-in page is the only outcome that neither\n // hangs the request forever nor invents a page the host did not ask for — but it is almost\n // certainly a bug in the hook, so say so.\n this.warnOnce(\n 'dashboardAuth.unauthenticatedPage returned without writing a response; falling back to ' +\n 'the built-in page. The hook must write AND end the response it is given.',\n );\n } catch (error) {\n // A broken host page must not turn a denial into a 500, and must never open the console.\n this.warnOnce(\n `dashboardAuth.unauthenticatedPage threw; falling back to the built-in page. ${String(error)}`,\n );\n // It may have written headers before throwing, in which case there is nothing left to do:\n // writing again would raise ERR_HTTP_HEADERS_SENT on top of the original failure.\n if (responseAlreadyWritten(response)) return;\n }\n }\n\n writeHtmlRaw(response, renderSessionRequiredPage(exception.basePath), HttpStatus.UNAUTHORIZED);\n }\n\n /** Once per process, not once per request: a broken hook fires on every denied navigation. */\n private warnOnce(message: string): void {\n if (this.warned) return;\n this.warned = true;\n this.logger.warn(message);\n }\n}\n","import {\n type DynamicModule,\n type FactoryProvider,\n Module,\n type Provider,\n type Type,\n UseGuards,\n} from '@nestjs/common';\nimport { RouterModule } from '@nestjs/core';\nimport {\n DASHBOARD_AUTH,\n type DashboardAuthOptions,\n resolveDashboardAuth,\n} from './auth/dashboard-auth-config.js';\nimport { CatalogAuthController } from './catalog-auth.controller.js';\nimport { CatalogUiSessionGuard } from './catalog-session.guard.js';\nimport {\n CatalogUiController,\n DASHBOARD_API_PATH,\n DASHBOARD_BASE_PATH,\n} from './catalog-ui.controller.js';\n\nexport interface CatalogDashboardOptions {\n /**\n * Where the console is served. Default `/catalog`.\n *\n * Not under the host's API prefix: this serves HTML and assets, and a host\n * that sets a global `/api` prefix has to exclude these paths from it — see\n * {@link catalogDashboardMountPaths}.\n */\n path?: string;\n /**\n * Where the catalog's JSON API lives, baked into the SPA so it knows what to\n * call. Default `/api/catalog-service`.\n *\n * A separate option because the console does NOT proxy the API — unlike some\n * Aviary dashboards, the catalog's HTTP surface is already mounted by\n * `CatalogModule` and `CatalogPipelineModule`, and a second copy behind this\n * console would be a second set of routes to keep authorised.\n */\n apiPath?: string;\n /**\n * How a visitor is authenticated.\n *\n * **Omit it and the console is open.** That is a real decision, not a\n * default to drift into: this console can rewrite a catalog's model and run\n * its connectors. A host with any notion of users should pass this, and a\n * host that means to leave it open should say so where someone will read it.\n */\n auth?: DashboardAuthOptions;\n /**\n * Guards fronting the console's own controllers.\n *\n * Separate from `auth`, and the reason is the failure it prevents: `auth`\n * describes how a session is validated, so a host that has not configured it\n * yet has an OPEN console. A host that would rather be shut than open passes a\n * denying guard here — it needs no secret, no DI and no session to work.\n *\n * Bound at module-definition time, so it cannot come from `forRootAsync`.\n */\n guards?: Type<unknown>[];\n}\n\nexport interface CatalogDashboardAsyncOptions extends Omit<CatalogDashboardOptions, 'auth'> {\n imports?: DynamicModule['imports'];\n inject?: FactoryProvider['inject'];\n /**\n * Builds the auth from DI. See {@link CatalogDashboardModule.forRootAsync}.\n *\n * May return `undefined`, and that is the important case rather than an\n * afterthought: a host whose signing secret is unset has no way to mint a\n * session, and the honest answer is \"no auth mechanism\" — paired with a\n * denying `guards` entry, which is what turns that into a CLOSED console\n * instead of an open one. Forcing a return here would push hosts to invent an\n * auth object around an absent secret, i.e. a cookie signed with nothing.\n */\n useDashboardAuth: (\n ...args: never[]\n ) => DashboardAuthOptions | undefined | Promise<DashboardAuthOptions | undefined>;\n}\n\n/**\n * The catalog console, as a mountable module.\n *\n * Serves the SPA and the session endpoints; nothing else. The screens come from\n * `@dudousxd/nestjs-catalog-react` and the data from the catalog's own API, so\n * this package is the mount, the auth and the asset serving — the three things a\n * component library cannot do for itself.\n */\n@Module({})\nexport class CatalogDashboardModule {\n static forRoot(options: CatalogDashboardOptions = {}): DynamicModule {\n // Resolved, not passed through: `resolveDashboardAuth` derives `modes` from\n // which hooks are present, and every consumer reads that. Handing over the\n // raw options gives a value whose `modes` is undefined, and the endpoints\n // fail with `Cannot read properties of undefined (reading 'includes')` — a\n // 500 where a 401 belongs.\n return build(options, {\n provide: DASHBOARD_AUTH,\n useValue: options.auth ? resolveDashboardAuth(options.auth) : null,\n });\n }\n\n /**\n * Same mount, but the auth is built from DI.\n *\n * Needed whenever validating a session means asking something the host owns —\n * a user store, a session service. `forRoot` cannot express that: `guards` and\n * the router are bound at module-DEFINITION time, before any injector exists,\n * which is why `guards` stays a static option on both forms.\n */\n static forRootAsync(options: CatalogDashboardAsyncOptions): DynamicModule {\n const factory = options.useDashboardAuth;\n const mounted = build(options, {\n provide: DASHBOARD_AUTH,\n // Same resolution as `forRoot`, wrapped around the host's factory so the\n // async path cannot skip it.\n useFactory: async (...args: never[]) => {\n const auth = await factory(...args);\n return auth ? resolveDashboardAuth(auth) : null;\n },\n inject: options.inject ?? [],\n });\n // Appended, not replaced: `build` puts the RouterModule registration in\n // `imports`, and overwriting it would leave the console unrouted.\n return {\n ...mounted,\n imports: [...(mounted.imports ?? []), ...(options.imports ?? [])],\n };\n }\n}\n\n/** See the note where this is set: `UseGuards` appends, and these classes are shared. */\nlet sessionGuardStamped = false;\n\nfunction build(\n options: CatalogDashboardOptions | CatalogDashboardAsyncOptions,\n auth: Provider,\n): DynamicModule {\n const path = normalise(options.path ?? '/catalog');\n const apiPath = normalise(options.apiPath ?? '/api/catalog-service');\n\n // The session guard, on the SPA and its assets.\n //\n // This was missing, and its absence was not visible from anywhere: `auth`\n // configures how a session is minted and validated, the docblocks describe it\n // as the thing that closes an otherwise-open console, and nothing ever stamped\n // the guard that enforces it. A host that configured `auth` correctly still\n // served the console shell to anyone who could reach the URL.\n //\n // NOT on `CatalogAuthController`: that is where a session is obtained, and\n // gating it on already having one locks the door from the inside.\n //\n // The guard is a no-op when `auth` is absent, so this is safe on an\n // intentionally open mount — \"open\" then remains a decision the host made by\n // omitting `auth`, rather than one the module made by forgetting.\n //\n // Stamped once per process, not once per mount. `UseGuards` APPENDS to the\n // controller's metadata and these controller classes are module-level, so a\n // second `forRoot` in the same process would run the guard twice per request.\n if (!sessionGuardStamped) {\n UseGuards(CatalogUiSessionGuard)(CatalogUiController);\n sessionGuardStamped = true;\n }\n\n // Host guards on top, applied to both controllers so a host can shut the whole\n // console — including the way in — without touching the rest of its app.\n // `UseGuards` at definition time is why `guards` cannot come from DI.\n for (const guard of options.guards ?? []) {\n UseGuards(guard)(CatalogUiController);\n UseGuards(guard)(CatalogAuthController);\n }\n\n const providers: Provider[] = [\n { provide: DASHBOARD_BASE_PATH, useValue: path },\n { provide: DASHBOARD_API_PATH, useValue: apiPath },\n auth,\n // Constructed by Nest, so it must be declared here — a guard stamped by\n // `UseGuards` is still resolved from the declaring module's injector.\n CatalogUiSessionGuard,\n ];\n\n return {\n module: CatalogDashboardModule,\n // The controllers are `@Controller()` with no path of their own, and the\n // prefix arrives here instead. That is what lets `path` be configurable at\n // all: a decorator argument is fixed at class-definition time, so a\n // hardcoded one would pin every host to the same mount point.\n //\n // Without this the controllers inherit whatever the host's global prefix is\n // — they answered on `/api` — and the console 404s at its configured path\n // while the module reports itself initialised, which is a confusing pair of\n // symptoms to hold at once.\n imports: [RouterModule.register([{ path, module: CatalogDashboardModule }])],\n controllers: [CatalogUiController, CatalogAuthController],\n providers,\n exports: providers,\n };\n}\n\n/**\n * The paths a host must exclude from its global API prefix.\n *\n * Without this, a host calling `setGlobalPrefix('api')` moves the console to\n * `/api/catalog` while the SPA still asks for `/catalog/assets/...`, and the\n * console loads as a blank page with 404s in the network tab — which reads as a\n * broken build rather than a routing mistake.\n *\n * Derived from the same defaulting `forRoot` uses, so the two cannot drift.\n */\nexport function catalogDashboardMountPaths(\n options: Pick<CatalogDashboardOptions, 'path'> = {},\n): string[] {\n const base = normalise(options.path ?? '/catalog').replace(/^\\//, '');\n // Plain strings with a `{*splat}` wildcard, which is the shape `setGlobalPrefix`'s\n // `exclude` matches and what every other Aviary console helper returns. An\n // object form is accepted by the type but does NOT match here, and the symptom\n // is subtle: the console mounts, logs itself as initialised, and answers on\n // `/api/<path>` while 404ing at `/<path>`.\n return [base, `${base}/{*splat}`];\n}\n\n/** Leading slash, no trailing one — the shape every consumer below assumes. */\nfunction normalise(path: string): string {\n const withLeading = path.startsWith('/') ? path : `/${path}`;\n return withLeading.length > 1 ? withLeading.replace(/\\/+$/, '') : withLeading;\n}\n","import {\n type CanActivate,\n type ExecutionContext,\n Inject,\n Injectable,\n UnauthorizedException,\n} from '@nestjs/common';\nimport { DASHBOARD_AUTH, type ResolvedDashboardAuth } from './auth/dashboard-auth-config.js';\nimport { DashboardLoginRedirectException } from './auth/login-redirect.exception.js';\nimport { originalRequestUrl } from './auth/request.js';\nimport { maybeRenewSession, readSessionFromRequest } from './auth/session-cookie-io.js';\nimport { DashboardSessionRequiredException } from './auth/session-required.exception.js';\nimport { DASHBOARD_BASE_PATH } from './catalog-ui.controller.js';\n\n/**\n * Gates `CatalogUiController` (the SPA shell + assets, a full-page browser navigation) on a valid\n * `dashboardAuth` session cookie. A no-op (always `true`) when `dashboardAuth` was not configured\n * — see `CatalogDashboardModule.forRoot`'s `dashboardAuth` doc. Missing/invalid/expired session,\n * when Mode B (`login`) is configured, gets a `302` to the built-in login page carrying\n * `?returnTo=<original url>`, via `DashboardLoginRedirectException` (see that file for why a guard\n * can't just call `response.redirect()` and return `false`). When only Mode A (`session`) is\n * configured there is no login page to redirect to — the host mints the session itself — so it\n * instead throws `DashboardSessionRequiredException`, rendering a small instruction page.\n *\n * Auth is mount-level and role-agnostic: this guard has no notion of control-plane vs tenant\n * (see the catalog dashboard's topology note in `dashboard.service.ts`) — it only ever answers\n * \"is there a valid dashboard session\", nothing role-specific changes here.\n */\n@Injectable()\nexport class CatalogUiSessionGuard implements CanActivate {\n constructor(\n @Inject(DASHBOARD_AUTH) private readonly auth: ResolvedDashboardAuth | null,\n @Inject(DASHBOARD_BASE_PATH) private readonly basePath: string,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n if (!this.auth) return true;\n const auth = this.auth;\n const http = context.switchToHttp();\n const request = http.getRequest<unknown>();\n const session = readSessionFromRequest(auth, request);\n if (!session) {\n this.denyUnauthenticated(auth, request);\n }\n if (!(await maybeRenewSession(auth, session, request, http.getResponse()))) {\n this.denyUnauthenticated(auth, request);\n }\n return true;\n }\n\n /**\n * A revoked session (the host's `revalidate` hook says no) is denied exactly like an absent\n * one — by design, there is nothing left to distinguish \"never had a session\" from \"had one,\n * then lost it\" once the cookie is cleared, so both get the same Mode-aware treatment.\n *\n * Takes `auth` explicitly rather than reading `this.auth`: `canActivate`'s `!this.auth` early\n * return narrows the field within that method only — TS doesn't carry it across a method call\n * — so callers pass the already-narrowed value instead of this method re-deriving (or\n * asserting away) the nullability.\n */\n private denyUnauthenticated(auth: ResolvedDashboardAuth, request: unknown): never {\n if (!auth.modes.includes('login')) throw new DashboardSessionRequiredException(this.basePath);\n const returnTo = encodeURIComponent(originalRequestUrl(request));\n throw new DashboardLoginRedirectException(`${this.basePath}/login?returnTo=${returnTo}`);\n }\n}\n\n/**\n * Gates `CatalogApiController` (the JSON API the SPA fetches) on a valid `dashboardAuth` session\n * cookie. A no-op (always `true`) when `dashboardAuth` was not configured. Missing/invalid/expired\n * session => a plain `401` (the API is called via `fetch`, never a browser navigation, so a\n * redirect would just fail the request anyway — the caller reads the status code, not HTML).\n *\n * Mount-level and role-agnostic, same as `CatalogUiSessionGuard` above.\n */\n@Injectable()\nexport class CatalogApiSessionGuard implements CanActivate {\n constructor(@Inject(DASHBOARD_AUTH) private readonly auth: ResolvedDashboardAuth | null) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n if (!this.auth) return true;\n const auth = this.auth;\n const http = context.switchToHttp();\n const request = http.getRequest<unknown>();\n const session = readSessionFromRequest(auth, request);\n if (!session) throw this.unauthorized(auth);\n if (!(await maybeRenewSession(auth, session, request, http.getResponse()))) {\n // Revoked mid-session: same treatment as an absent cookie.\n throw this.unauthorized(auth);\n }\n return true;\n }\n\n /**\n * A bare 401 body carrying `{ auth: { modes } }` — mirrors `@dudousxd/nestjs-telescope`'s\n * dashboardAuth 401. The API is fetched (never navigated), so this is the ONLY way the console\n * SPA (`catalog-client.ts`) learns which auth surface to send the operator to on a mid-session\n * 401; `CatalogUiSessionGuard`'s redirect/session-required exceptions above don't reach it.\n */\n private unauthorized(auth: ResolvedDashboardAuth): UnauthorizedException {\n return new UnauthorizedException({ auth: { modes: auth.modes } });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;ACiGO,IAAMA,iBAAiBC,OAAO,gBAAA;AAErC,IAAMC,cAAc;AACpB,IAAMC,iBAAiB,IAAI,KAAK,KAAK;AACrC,IAAMC,iBAAyC;EAC7CC,GAAG;EACHC,GAAG,KAAK;EACRC,GAAG,KAAK,KAAK;EACbC,GAAG,KAAK,KAAK,KAAK;AACpB;AAGA,SAASC,aAAaC,KAAW;AAC/B,QAAMC,QAAQ,kBAAkBC,KAAKF,IAAIG,KAAI,CAAA;AAC7C,MAAI,CAACF,MAAO,QAAOR;AACnB,QAAMW,OAAOV,eAAeO,MAAM,CAAA,KAAM,EAAA;AACxC,MAAIG,SAASC,OAAW,QAAOZ;AAC/B,SAAOa,OAAOL,MAAM,CAAA,CAAE,IAAIG;AAC5B;AANSL;AAcF,SAASQ,qBACdC,SAAyC;AAE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AA;WAASd,QAAQc,WAAW,CAAA;;IAC/D;EACF;AACF;;;;AAGA,IAAIC,sBAAsB;AAE1B,SAASd,MACPD,SACAK,MAAc;AAEd,QAAMW,OAAOC,UAAUjB,QAAQgB,QAAQ,UAAA;AACvC,QAAME,UAAUD,UAAUjB,QAAQkB,WAAW,sBAAA;AAoB7C,MAAI,CAACH,qBAAqB;AACxBI,kCAAUC,qBAAAA,EAAuBC,mBAAAA;AACjCN,0BAAsB;EACxB;AAKA,aAAWO,SAAStB,QAAQuB,UAAU,CAAA,GAAI;AACxCJ,kCAAUG,KAAAA,EAAOD,mBAAAA;AACjBF,kCAAUG,KAAAA,EAAOE,qBAAAA;EACnB;AAEA,QAAMC,YAAwB;IAC5B;MAAEvB,SAASwB;MAAqBtB,UAAUY;IAAK;IAC/C;MAAEd,SAASyB;MAAoBvB,UAAUc;IAAQ;IACjDb;;;IAGAe;;AAGF,SAAO;IACLQ,QAAQ9B;;;;;;;;;;IAURgB,SAAS;MAACe,yBAAaC,SAAS;QAAC;UAAEd;UAAMY,QAAQ9B;QAAuB;OAAE;;IAC1EiC,aAAa;MAACV;MAAqBG;;IACnCC;IACAO,SAASP;EACX;AACF;AA/DSxB;AA2EF,SAASgC,2BACdjC,UAAiD,CAAC,GAAC;AAEnD,QAAMkC,OAAOjB,UAAUjB,QAAQgB,QAAQ,UAAA,EAAYmB,QAAQ,OAAO,EAAA;AAMlE,SAAO;IAACD;IAAM,GAAGA,IAAAA;;AACnB;AAVgBD;AAahB,SAAShB,UAAUD,MAAY;AAC7B,QAAMoB,cAAcpB,KAAKqB,WAAW,GAAA,IAAOrB,OAAO,IAAIA,IAAAA;AACtD,SAAOoB,YAAYE,SAAS,IAAIF,YAAYD,QAAQ,QAAQ,EAAA,IAAMC;AACpE;AAHSnB;","names":["DASHBOARD_AUTH","Symbol","DEFAULT_TTL","DEFAULT_TTL_MS","DURATION_UNITS","s","m","h","d","durationToMs","ttl","match","exec","trim","unit","undefined","Number","resolveDashboardAuth","options","secret","Error","modes","session","push","login","revalidate","unauthenticatedPage","length","ttlMs","parseCookieHeader","header","cookies","segment","split","eq","indexOf","name","slice","trim","rawValue","length","startsWith","endsWith","decodeURIComponent","serializeSetCookie","value","options","parts","clear","encodeURIComponent","push","path","secure","maxAgeSeconds","join","isRecord","value","readHeaders","request","headers","headerToString","Array","isArray","every","part","join","undefined","readCookieHeader","cookie","isHttpsRequest","protocol","forwarded","split","map","proto","trim","toLowerCase","includes","originalRequestUrl","originalUrl","url","sanitizeReturnTo","candidate","fallback","startsWith","isRecord","value","isRawCookieResponse","getHeader","setHeader","resolveCookieResponse","response","raw","existingSetCookies","current","Array","isArray","appendSetCookie","cookie","isRawRedirectResponse","end","resolveRedirectResponse","redirectRaw","location","status","statusCode","responseAlreadyWritten","headersSent","writeHtmlRaw","html","EXP_GRACE_MS","base64urlEncode","value","Buffer","from","toString","base64urlDecode","hmac","secret","payload","createHmac","update","digest","signSessionCookie","user","options","issuedAt","now","Date","session","sub","id","name","undefined","roles","iat","exp","ttlMs","encodedPayload","JSON","stringify","signature","isSessionPayload","record","Array","isArray","every","role","Number","isFinite","verifySessionCookie","dot","indexOf","length","slice","providedSignature","expectedSignature","provided","expected","timingSafeEqual","decoded","parse","SESSION_COOKIE_NAME","COOKIE_PATH","issueSessionCookie","user","context","value","signSessionCookie","secret","auth","ttlMs","now","undefined","cookie","serializeSetCookie","path","maxAgeSeconds","Math","floor","secure","isHttpsRequest","request","appendSetCookie","response","clearSessionCookie","clear","readSessionFromRequest","cookieValue","parseCookieHeader","readCookieHeader","verifySessionCookie","inFlightRevalidations","Map","revalidateOnce","revalidate","Promise","resolve","key","id","inFlight","get","call","then","catch","finally","delete","set","maybeRenewSession","session","Date","iat","sub","name","roles","allowed","import_common","page","content","title","renderLoginPage","basePath","loginAction","defaultReturnTo","JSON","stringify","renderSessionRequiredPage","import_common","DashboardLoginRedirectException","HttpException","location","HttpStatus","FOUND","DashboardLoginRedirectFilter","catch","exception","host","response","switchToHttp","getResponse","redirectRaw","import_common","DashboardSessionRequiredException","HttpException","basePath","HttpStatus","UNAUTHORIZED","DashboardSessionRequiredFilter","logger","Logger","name","warned","auth","catch","exception","host","http","switchToHttp","response","getResponse","hook","unauthenticatedPage","request","getRequest","responseAlreadyWritten","warnOnce","error","String","writeHtmlRaw","renderSessionRequiredPage","message","warn","DASHBOARD_BASE_PATH","Symbol","DASHBOARD_API_PATH","BUILD_BASE","spaDir","fileURLToPath","URL","CONTENT_TYPES","CatalogUiController","dir","basePath","apiBasePath","auth","index","indexPath","join","existsSync","NotFoundException","html","readFileSync","replaceAll","hostAuth","inject","includes","replace","asset","file","safe","basename","root","resolve","assetPath","startsWith","sep","type","extname","StreamableFile","isString","value","CatalogAuthController","logger","Logger","name","warnedHooks","Set","auth","basePath","loginPage","requireAuth","modes","includes","NotFoundException","renderLoginPage","login","body","request","response","username","password","BadRequestException","user","runHook","UnauthorizedException","message","issueSessionCookie","redirectTo","sanitizeReturnTo","returnTo","session","logout","clearSessionCookie","redirectRaw","kind","run","error","has","add","warn","Error","String","passthrough","import_common","import_common","CatalogUiSessionGuard","auth","basePath","canActivate","context","http","switchToHttp","request","getRequest","session","readSessionFromRequest","denyUnauthenticated","maybeRenewSession","getResponse","modes","includes","DashboardSessionRequiredException","returnTo","encodeURIComponent","originalRequestUrl","DashboardLoginRedirectException","CatalogApiSessionGuard","unauthorized","UnauthorizedException","CatalogDashboardModule","forRoot","options","build","provide","DASHBOARD_AUTH","useValue","auth","resolveDashboardAuth","forRootAsync","factory","useDashboardAuth","mounted","useFactory","args","inject","imports","sessionGuardStamped","path","normalise","apiPath","UseGuards","CatalogUiSessionGuard","CatalogUiController","guard","guards","CatalogAuthController","providers","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH","module","RouterModule","register","controllers","exports","catalogDashboardMountPaths","base","replace","withLeading","startsWith","length"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/index.ts","../../src/server/auth/dashboard-auth-config.ts","../../src/server/auth/cookie-header.ts","../../src/server/auth/request.ts","../../src/server/auth/response.ts","../../src/server/auth/session-cookie.ts","../../src/server/auth/session-cookie-io.ts","../../src/server/catalog-auth.controller.ts","../../src/server/auth/login-page.ts","../../src/server/catalog-ui.controller.ts","../../src/server/auth/login-redirect.exception.ts","../../src/server/auth/session-required.exception.ts","../../src/server/catalog-dashboard.module.ts","../../src/server/catalog-session.guard.ts"],"sourcesContent":["export type {\n DashboardAuthOptions,\n // What `DASHBOARD_AUTH` actually carries. A host reading the session off a\n // request injects that token and needs a name for what comes out.\n ResolvedDashboardAuth,\n UnauthenticatedPageContext,\n UnauthenticatedPageHook,\n} from './auth/dashboard-auth-config.js';\nexport { DASHBOARD_AUTH } from './auth/dashboard-auth-config.js';\nexport type { DashboardSession, DashboardSessionUser } from './auth/session-cookie.js';\n/**\n * Read and verify the console's session off a request.\n *\n * Exported because this package deliberately does NOT proxy the catalog's API —\n * that surface is mounted by `CatalogModule` and guarded by whatever the host\n * put in front of it. Which leaves a gap the host cannot close on its own: the\n * console SPA fetches that API from a browser, carrying this cookie and no\n * bearer token, so a host whose API guard only understands its own token\n * answers 401 to every screen while the console shell loads perfectly. The\n * symptom reads as a broken API, not as two auth systems that were never\n * introduced.\n *\n * So the host's own resolver can ask this: given a request, is there a valid\n * console session on it, and whose? Signature and expiry are checked here;\n * `revalidate` is not run, because that is renewal and belongs to the guard\n * that owns the cookie's lifetime.\n */\nexport { readSessionFromRequest as readCatalogConsoleSession } from './auth/session-cookie-io.js';\nexport { CatalogAuthController } from './catalog-auth.controller.js';\nexport {\n CatalogDashboardModule,\n catalogDashboardMountPaths,\n type CatalogDashboardAsyncOptions,\n type CatalogDashboardOptions,\n} from './catalog-dashboard.module.js';\nexport {\n CatalogApiSessionGuard,\n CatalogUiSessionGuard,\n} from './catalog-session.guard.js';\nexport {\n CatalogUiController,\n DASHBOARD_API_PATH,\n DASHBOARD_BASE_PATH,\n} from './catalog-ui.controller.js';\n","import type { DashboardSessionUser } from './session-cookie.js';\n\n/** Host hook for Mode A — validates the host's own auth on the raw request. */\nexport type SessionHook = (\n request: unknown,\n) => Promise<DashboardSessionUser | null> | DashboardSessionUser | null;\n\n/** Host hook for Mode B — validates submitted credentials from the built-in login page. */\nexport type LoginHook = (\n username: string,\n password: string,\n) => Promise<DashboardSessionUser | null> | DashboardSessionUser | null;\n\n/**\n * Re-checks a LIVE session when the cookie is slid forward. Runs at most once per `ttl/2` per\n * session, so a DB round-trip here is cheap — this holds even under concurrent traffic: N parallel\n * requests carrying the same past-half-life cookie share ONE call (see `revalidateOnce` in\n * `session-cookie-io.ts`), not N. Return `false` to revoke (the cookie is cleared and the request\n * denied). Distinct from `session`: that hook reads the host's auth off a fresh request, which a\n * console XHR does not carry — this one receives the already-minted session.\n */\nexport type RevalidateHook = (session: DashboardSessionUser) => Promise<boolean> | boolean;\n\n/** What `unauthenticatedPage` receives. An object (not positional args) so fields can be added later. */\nexport interface UnauthenticatedPageContext {\n /**\n * The platform-native request — Express' `Request`, Fastify's `FastifyRequest`. Typed `unknown`\n * for the same reason `SessionHook`'s is: this package refuses to depend on either platform.\n * Cast it to whatever your app actually runs on.\n */\n request: unknown;\n /**\n * The platform-native response. The hook OWNS it: it must write AND end it (`res.render(...)`,\n * `res.status(401).send(...)`, an Inertia render, ...). If the hook returns without writing, the\n * library falls back to its own built-in page rather than leaving the request hanging.\n */\n response: unknown;\n /** Where this console is mounted (e.g. `/catalog`) — useful for a \"back to the console\" link. */\n basePath: string;\n}\n\n/**\n * Host-owned page for an unauthenticated full-page navigation to the console.\n *\n * The built-in page cannot know who hosts the console, so it can only say \"open this console from\n * your application\" in the abstract — it can't name the launcher, link to it, or look like the rest\n * of the host's product. This hook hands the whole response to the host instead: render through\n * your own template engine, your own Inertia page, whatever. The page is served AT the console's\n * own URL, so `/catalog` stays `/catalog`.\n *\n * Deliberately NOT a replacement for Mode B's built-in login form. A host that wants its own login\n * UI uses Mode A plus this hook, and posts to `<basePath>/session` from its own page — the mint\n * endpoint is the supported primitive for that.\n *\n * Fail-closed by construction: it only ever runs on a request that has ALREADY been denied. A hook\n * that throws, or that returns without writing, falls back to the built-in page — it cannot let\n * anyone in.\n */\nexport type UnauthenticatedPageHook = (context: UnauthenticatedPageContext) => void | Promise<void>;\n\nexport type AuthMode = 'session' | 'login';\n\n/**\n * Author-facing `dashboardAuth` option on `CatalogDashboardModule.forRoot`/`forRootAsync`. Gates\n * BOTH the SPA (a full-page navigation redirected to a server-rendered login page) and the JSON\n * API (a plain `401`) behind a signed session cookie, mirroring `@dudousxd/nestjs-telescope`'s\n * `dashboardAuth` mechanism (same HMAC-SHA256 cookie, same fail-closed validation). Two ways to\n * mint that cookie: Mode A (`session`) — the host frontend, already carrying its own auth, POSTs\n * to `<basePath>/session` and the host hook decides; or Mode B (`login`) — the built-in,\n * dependency-free server-rendered login page (`GET <basePath>/login`). At least one of the two is\n * required so an un-mintable gate is a boot error, not a silently-open (or silently-stuck) console.\n */\nexport interface DashboardAuthOptions {\n /** REQUIRED HMAC-SHA256 signing key. Missing/empty => boot error (fail closed). */\n secret: string;\n /** Cookie TTL as a duration string (`'8h'`, `'30m'`, `'7d'`). Default `'8h'`. */\n ttl?: string;\n /** Mode A: validates the host's own auth on the raw request POSTed to `<basePath>/session`;\n * return the session user, or `null` to deny. Thrown errors are treated as a denial (logged\n * once, never surfaced to the client). */\n session?: SessionHook;\n /** Mode B: validates submitted username/password from the built-in login page; return the\n * session user, or `null` to deny. Thrown errors are treated as a denial (logged once, never\n * surfaced to the client). */\n login?: LoginHook;\n /** Re-checks a live session on sliding renewal; see `RevalidateHook`. Not a mode — it cannot\n * mint a session, only revoke one already minted by `session`/`login`. */\n revalidate?: RevalidateHook;\n /** Renders the host's own page for an unauthenticated navigation, in place of the built-in\n * \"open this console from your application\" card; see `UnauthenticatedPageHook`. */\n unauthenticatedPage?: UnauthenticatedPageHook;\n}\n\n/** Resolved, validated `dashboardAuth` config shared by the guards, auth controller, and login page. */\nexport interface ResolvedDashboardAuth {\n secret: string;\n ttlMs: number;\n modes: AuthMode[];\n session?: SessionHook;\n login?: LoginHook;\n revalidate?: RevalidateHook;\n unauthenticatedPage?: UnauthenticatedPageHook;\n}\n\n/** DI token carrying the resolved `dashboardAuth` config (`ResolvedDashboardAuth | null`). */\nexport const DASHBOARD_AUTH = Symbol('DASHBOARD_AUTH');\n\nconst DEFAULT_TTL = '8h';\nconst DEFAULT_TTL_MS = 8 * 60 * 60 * 1000;\nconst DURATION_UNITS: Record<string, number> = {\n s: 1000,\n m: 60 * 1000,\n h: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n};\n\n/** Parse a `'<number><s|m|h|d>'` duration to ms; falls back to the 8h default on a bad value. */\nfunction durationToMs(ttl: string): number {\n const match = /^(\\d+)([smhd])$/.exec(ttl.trim());\n if (!match) return DEFAULT_TTL_MS;\n const unit = DURATION_UNITS[match[2] ?? ''];\n if (unit === undefined) return DEFAULT_TTL_MS;\n return Number(match[1]) * unit;\n}\n\n/**\n * An optional `dashboardAuth` hook is either absent or callable.\n *\n * One function for all four so the four messages cannot drift apart — a host\n * reading \"dashboardAuth.revalidate must be a function\" and then a differently\n * worded one for `login` has to work out whether the difference means anything.\n * `name` is this package's own literal at every call site, never user input.\n */\nfunction assertOptionalHook(value: unknown, name: string): void {\n if (value !== undefined && typeof value !== 'function') {\n throw new Error(`CatalogDashboardModule: dashboardAuth.${name} must be a function.`);\n }\n}\n\n/**\n * Validate + resolve the `dashboardAuth` option. Returns `null` when unconfigured (today's\n * unauthenticated behavior, unchanged). Throws at boot (fail closed) when configured but missing a\n * secret, or missing both a `session` and a `login` hook — the host learns immediately rather than\n * shipping an un-mintable gate.\n */\nexport function resolveDashboardAuth(\n options: DashboardAuthOptions | undefined,\n): ResolvedDashboardAuth | null {\n if (options === undefined) return null;\n if (typeof options.secret !== 'string' || options.secret === '') {\n throw new Error(\n 'CatalogDashboardModule: dashboardAuth.secret is required and must be a non-empty string ' +\n '(HMAC-SHA256 signing key, 32+ bytes recommended). Failing closed.',\n );\n }\n // Checked in declaration order, so the first thing a misconfigured host is\n // told about is the first thing it got wrong.\n assertOptionalHook(options.session, 'session');\n assertOptionalHook(options.login, 'login');\n assertOptionalHook(options.revalidate, 'revalidate');\n assertOptionalHook(options.unauthenticatedPage, 'unauthenticatedPage');\n\n const modes: AuthMode[] = [];\n if (options.session !== undefined) modes.push('session');\n if (options.login !== undefined) modes.push('login');\n\n if (modes.length === 0) {\n throw new Error(\n 'CatalogDashboardModule: dashboardAuth needs at least one of `session` or `login` ' +\n '(otherwise the cookie can never be minted). Failing closed.',\n );\n }\n return {\n secret: options.secret,\n ttlMs: durationToMs(options.ttl ?? DEFAULT_TTL),\n modes,\n ...(options.session !== undefined ? { session: options.session } : {}),\n ...(options.login !== undefined ? { login: options.login } : {}),\n ...(options.revalidate !== undefined ? { revalidate: options.revalidate } : {}),\n ...(options.unauthenticatedPage !== undefined\n ? { unauthenticatedPage: options.unauthenticatedPage }\n : {}),\n };\n}\n","/**\n * Parse a raw `Cookie` request header into a name→value map. Dependency-free so it works on raw\n * Express AND Fastify requests without `cookie-parser`. Values are URL-decoded; malformed\n * segments are skipped, never thrown.\n */\nexport function parseCookieHeader(header: string | undefined): Record<string, string> {\n const cookies: Record<string, string> = {};\n if (typeof header !== 'string' || header === '') return cookies;\n for (const segment of header.split(';')) {\n const eq = segment.indexOf('=');\n if (eq <= 0) continue;\n const name = segment.slice(0, eq).trim();\n if (name === '') continue;\n let rawValue = segment.slice(eq + 1).trim();\n // Strip a single pair of wrapping double-quotes (RFC 6265 quoted form).\n if (rawValue.length >= 2 && rawValue.startsWith('\"') && rawValue.endsWith('\"')) {\n rawValue = rawValue.slice(1, -1);\n }\n // First occurrence wins; don't clobber an earlier value with a later dup.\n if (name in cookies) continue;\n try {\n cookies[name] = decodeURIComponent(rawValue);\n } catch {\n cookies[name] = rawValue;\n }\n }\n return cookies;\n}\n\nexport interface SetCookieOptions {\n /** Cookie `Path`. The dashboard scopes its session cookie to `/` — see `session-cookie-io.ts`\n * for why (the UI mount and the JSON API mount can be configured to live at unrelated paths). */\n path: string;\n /** Cookie lifetime in seconds. Ignored (and forced to 0) when `clear` is set. */\n maxAgeSeconds: number;\n /** Add `Secure` when the request is https. */\n secure: boolean;\n /** Clear the cookie: empty value + `Max-Age=0` (and `Expires` in the past). */\n clear?: boolean;\n}\n\n/**\n * Serialize a `Set-Cookie` header value. Always `HttpOnly` + `SameSite=Lax` (Lax blocks\n * cross-site `POST`s carrying the cookie — CSRF coverage for the login/logout endpoints).\n * Platform-agnostic: just a string.\n */\nexport function serializeSetCookie(name: string, value: string, options: SetCookieOptions): string {\n const parts = [`${name}=${options.clear ? '' : encodeURIComponent(value)}`];\n parts.push(`Path=${options.path}`);\n parts.push('HttpOnly');\n parts.push('SameSite=Lax');\n if (options.secure) parts.push('Secure');\n if (options.clear) {\n parts.push('Max-Age=0');\n parts.push('Expires=Thu, 01 Jan 1970 00:00:00 GMT');\n } else {\n parts.push(`Max-Age=${options.maxAgeSeconds}`);\n }\n return parts.join('; ');\n}\n","function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction readHeaders(request: unknown): Record<string, unknown> {\n if (!isRecord(request)) return {};\n const headers = request.headers;\n return isRecord(headers) ? headers : {};\n}\n\n/** Coerce a single header (string or string[]) to a string, else undefined. */\nfunction headerToString(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value) && value.every((part) => typeof part === 'string')) {\n return value.join(',');\n }\n return undefined;\n}\n\n/** Read the raw `Cookie` request header (Express and Fastify both expose `headers`). */\nexport function readCookieHeader(request: unknown): string | undefined {\n return headerToString(readHeaders(request).cookie);\n}\n\n/**\n * Decide whether the cookie should carry `Secure`. True when the request is https directly\n * (`request.protocol === 'https'`) OR a proxy forwarded https (`x-forwarded-proto` includes\n * 'https'). Defensive structural reads — never throws, defaults to insecure (works on plain http\n * in dev).\n */\nexport function isHttpsRequest(request: unknown): boolean {\n if (isRecord(request) && request.protocol === 'https') return true;\n const forwarded = headerToString(readHeaders(request)['x-forwarded-proto']);\n if (forwarded === undefined) return false;\n return forwarded\n .split(',')\n .map((proto) => proto.trim().toLowerCase())\n .includes('https');\n}\n\n/** The path + query a browser navigated to (Express's `originalUrl`, else the generic `url`). */\nexport function originalRequestUrl(request: unknown): string {\n if (!isRecord(request)) return '/';\n if (typeof request.originalUrl === 'string' && request.originalUrl !== '') {\n return request.originalUrl;\n }\n if (typeof request.url === 'string' && request.url !== '') return request.url;\n return '/';\n}\n\n/**\n * Guard a client-supplied redirect target against an open redirect: it must be a same-origin,\n * root-relative path (`/catalog/foo`), never a protocol-relative (`//evil.com`) or absolute\n * (`https://evil.com`) URL. Falls back to `fallback` (typically the dashboard's own `basePath`)\n * for anything else, including a missing/non-string value.\n */\nexport function sanitizeReturnTo(candidate: unknown, fallback: string): string {\n if (typeof candidate !== 'string') return fallback;\n if (!candidate.startsWith('/')) return fallback;\n if (candidate.startsWith('//')) return fallback;\n if (candidate.includes('://')) return fallback;\n return candidate;\n}\n","function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\ninterface RawCookieResponse {\n getHeader(name: string): number | string | string[] | undefined;\n setHeader(name: string, value: string | string[]): unknown;\n}\n\nfunction isRawCookieResponse(value: unknown): value is RawCookieResponse {\n return (\n isRecord(value) &&\n typeof value.getHeader === 'function' &&\n typeof value.setHeader === 'function'\n );\n}\n\n/**\n * Resolve the writable Node `ServerResponse` from a platform response. Express' response IS the\n * Node response; Fastify's reply wraps it on `.raw`. Returns the outer response when it already\n * exposes get/setHeader (Express), otherwise the unwrapped `.raw` (Fastify) — so a single write\n * path serves both without a platform-specific dependency.\n */\nfunction resolveCookieResponse(response: unknown): RawCookieResponse | null {\n if (isRawCookieResponse(response)) return response;\n if (isRecord(response) && isRawCookieResponse(response.raw)) return response.raw;\n return null;\n}\n\nfunction existingSetCookies(response: RawCookieResponse): string[] {\n const current = response.getHeader('set-cookie');\n if (Array.isArray(current)) return current;\n if (typeof current === 'string') return [current];\n return [];\n}\n\n/**\n * Append a `Set-Cookie` header to the response WITHOUT clobbering any cookies already queued by\n * the host. Platform-agnostic raw write — no-ops gracefully if the response can't be unwrapped.\n */\nexport function appendSetCookie(response: unknown, cookie: string): void {\n const raw = resolveCookieResponse(response);\n if (!raw) return;\n raw.setHeader('set-cookie', [...existingSetCookies(raw), cookie]);\n}\n\ninterface RawRedirectResponse extends RawCookieResponse {\n statusCode: number;\n end(chunk?: string): unknown;\n}\n\nfunction isRawRedirectResponse(value: unknown): value is RawRedirectResponse {\n return (\n isRecord(value) &&\n typeof value.getHeader === 'function' &&\n typeof value.setHeader === 'function' &&\n typeof value.end === 'function'\n );\n}\n\nfunction resolveRedirectResponse(response: unknown): RawRedirectResponse | null {\n if (isRawRedirectResponse(response)) return response;\n if (isRecord(response) && isRawRedirectResponse(response.raw)) return response.raw;\n return null;\n}\n\n/**\n * Write a redirect directly on the raw response and END it. Used from the `DashboardLoginRedirect`\n * exception filter (guards can't use `@Redirect()` — that decorator only applies to a controller\n * handler's return value) and by the manual, non-passthrough logout handler. Bypassing Nest's\n * normal \"send the handler's return value\" pipeline this way is only safe when NOTHING downstream\n * (a filter, or Nest itself) will also try to write to the same response — both call sites here\n * are the terminal step of their request (an exception filter, or a `@Res()` non-passthrough\n * handler), so there is no second writer to race.\n */\nexport function redirectRaw(response: unknown, location: string, status = 302): void {\n const raw = resolveRedirectResponse(response);\n if (!raw) return;\n raw.statusCode = status;\n raw.setHeader('location', location);\n raw.end();\n}\n\n/**\n * Did something already write to this response?\n *\n * Used to decide whether a host's `unauthenticatedPage` hook actually produced a page. A hook that\n * returns without writing (an early `return`, a forgotten `await`, a template that resolved to\n * nothing) would otherwise leave the request hanging forever — the browser spins until it times\n * out, with no error anywhere. Checking this lets the caller fall back to the built-in page.\n *\n * Reads the Node `ServerResponse.headersSent` through the same Express/Fastify unwrapping as the\n * writers above; Fastify's own `reply.sent` is not consulted because `.raw.headersSent` is true in\n * every case that matters here (the reply has been flushed to the socket).\n */\nexport function responseAlreadyWritten(response: unknown): boolean {\n const raw = resolveRedirectResponse(response) as\n | (RawRedirectResponse & { headersSent?: boolean })\n | null;\n return raw?.headersSent === true;\n}\n\n/**\n * Write a full HTML page directly on the raw response and END it. Used by\n * `DashboardSessionRequiredFilter` (the Mode-A-only instruction page a guard renders in place of a\n * login redirect that no longer exists) — same raw-response bypass, and the same reason it's safe:\n * an exception filter is the terminal step of the request, so there's no second writer to race.\n */\nexport function writeHtmlRaw(response: unknown, html: string, status = 200): void {\n const raw = resolveRedirectResponse(response);\n if (!raw) return;\n raw.statusCode = status;\n raw.setHeader('content-type', 'text/html; charset=utf-8');\n // Same as the auth controller's `@Header('Cache-Control', ...)` on the sibling login page: this\n // page reflects live session state, so it must never be served stale from a cache.\n raw.setHeader('cache-control', 'no-store, must-revalidate');\n raw.end(html);\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\n\n/** Clock-skew grace applied to `exp` so a marginally-late clock doesn't bounce a valid cookie. */\nconst EXP_GRACE_MS = 30_000;\n\n/** The validated dashboard session attached to a request once its cookie verifies. */\nexport interface DashboardSession {\n /** Stable user id (the session user's `id`). */\n sub: string;\n /** Optional display name. */\n name?: string;\n /** Free-form role strings; the dashboard does not interpret them. */\n roles: string[];\n /** Issued-at, epoch milliseconds. */\n iat: number;\n /** Expiry, epoch milliseconds. */\n exp: number;\n}\n\n/** The session user the host `login` hook returns to mint a cookie. */\nexport interface DashboardSessionUser {\n id: string;\n name?: string;\n roles?: string[];\n}\n\nexport interface SignOptions {\n secret: string;\n ttlMs: number;\n /** Injectable clock (epoch ms) for deterministic tests. Defaults to `Date.now()`. */\n now?: number;\n}\n\nexport interface VerifyOptions {\n secret: string;\n /** Injectable clock (epoch ms) for deterministic tests. Defaults to `Date.now()`. */\n now?: number;\n}\n\nfunction base64urlEncode(value: string): string {\n return Buffer.from(value, 'utf8').toString('base64url');\n}\n\nfunction base64urlDecode(value: string): string {\n return Buffer.from(value, 'base64url').toString('utf8');\n}\n\nfunction hmac(secret: string, payload: string): string {\n return createHmac('sha256', secret).update(payload).digest('base64url');\n}\n\n/**\n * Sign a session into the cookie value `base64url(payload).base64url(hmac)`. Stateless\n * HMAC-SHA256, no store, `node:crypto` only — no JWT dependency. Mirrors\n * `@dudousxd/nestjs-telescope`'s `dashboardAuth` cookie mechanism so the behavior is familiar\n * across the aviary consoles.\n */\nexport function signSessionCookie(user: DashboardSessionUser, options: SignOptions): string {\n const issuedAt = options.now ?? Date.now();\n const session: DashboardSession = {\n sub: user.id,\n ...(user.name !== undefined ? { name: user.name } : {}),\n roles: user.roles ?? [],\n iat: issuedAt,\n exp: issuedAt + options.ttlMs,\n };\n const encodedPayload = base64urlEncode(JSON.stringify(session));\n const signature = hmac(options.secret, encodedPayload);\n return `${encodedPayload}.${signature}`;\n}\n\n/** Type guard for the decoded payload shape — defends against tampered/legacy payloads. */\nfunction isSessionPayload(value: unknown): value is DashboardSession {\n if (typeof value !== 'object' || value === null) return false;\n const record: Record<string, unknown> = { ...value };\n if (typeof record.sub !== 'string') return false;\n if (record.name !== undefined && typeof record.name !== 'string') return false;\n if (!Array.isArray(record.roles)) return false;\n if (!record.roles.every((role) => typeof role === 'string')) return false;\n if (typeof record.iat !== 'number' || !Number.isFinite(record.iat)) return false;\n if (typeof record.exp !== 'number' || !Number.isFinite(record.exp)) return false;\n return true;\n}\n\n/**\n * Verify a cookie value and return the session, or `null` for anything that's tampered,\n * malformed, or expired (past `exp` + a 30s grace). Constant-time signature comparison. NEVER\n * throws — any parse failure yields `null`.\n */\nexport function verifySessionCookie(\n value: string,\n options: VerifyOptions,\n): DashboardSession | null {\n try {\n const dot = value.indexOf('.');\n if (dot <= 0 || dot === value.length - 1) return null;\n const encodedPayload = value.slice(0, dot);\n const providedSignature = value.slice(dot + 1);\n const expectedSignature = hmac(options.secret, encodedPayload);\n const provided = Buffer.from(providedSignature, 'base64url');\n const expected = Buffer.from(expectedSignature, 'base64url');\n // timingSafeEqual throws on a length mismatch — guard it so a wrong-length (tampered)\n // signature returns null instead of throwing.\n if (provided.length !== expected.length) return null;\n if (!timingSafeEqual(provided, expected)) return null;\n const decoded: unknown = JSON.parse(base64urlDecode(encodedPayload));\n if (!isSessionPayload(decoded)) return null;\n const now = options.now ?? Date.now();\n if (now > decoded.exp + EXP_GRACE_MS) return null;\n const session: DashboardSession = {\n sub: decoded.sub,\n ...(decoded.name !== undefined ? { name: decoded.name } : {}),\n roles: decoded.roles,\n iat: decoded.iat,\n exp: decoded.exp,\n };\n return session;\n } catch {\n return null;\n }\n}\n","import { parseCookieHeader, serializeSetCookie } from './cookie-header.js';\nimport type { ResolvedDashboardAuth } from './dashboard-auth-config.js';\nimport { isHttpsRequest, readCookieHeader } from './request.js';\nimport { appendSetCookie } from './response.js';\nimport {\n type DashboardSession,\n type DashboardSessionUser,\n signSessionCookie,\n verifySessionCookie,\n} from './session-cookie.js';\n\n/** Cookie name carrying the signed dashboard session. */\nexport const SESSION_COOKIE_NAME = 'catalog_dashboard_session';\n\n/**\n * `Path=/`, deliberately not scoped to `basePath`/`apiBasePath`: the two mounts are independently\n * configurable (`CatalogDashboardModule.forRoot({ basePath, apiBasePath })`) and can live at\n * unrelated paths (e.g. a `/catalog` UI + an `/api/catalog-service` API) — a cookie scoped to either one alone\n * would not reach the other. The cookie is `HttpOnly` + signed + short-lived, so the broader scope\n * is a reasonable trade for correctness across any mount configuration.\n */\nconst COOKIE_PATH = '/';\n\n/**\n * Sign a fresh session for `user` and append it as a `Set-Cookie` on the response, `Secure` when\n * the request is https.\n */\nexport function issueSessionCookie(\n user: DashboardSessionUser,\n context: {\n auth: ResolvedDashboardAuth;\n request: unknown;\n response: unknown;\n now?: number;\n },\n): void {\n const value = signSessionCookie(user, {\n secret: context.auth.secret,\n ttlMs: context.auth.ttlMs,\n ...(context.now !== undefined ? { now: context.now } : {}),\n });\n const cookie = serializeSetCookie(SESSION_COOKIE_NAME, value, {\n path: COOKIE_PATH,\n maxAgeSeconds: Math.floor(context.auth.ttlMs / 1000),\n secure: isHttpsRequest(context.request),\n });\n appendSetCookie(context.response, cookie);\n}\n\n/** Append a cookie-clearing `Set-Cookie` (Max-Age=0). */\nexport function clearSessionCookie(context: { request: unknown; response: unknown }): void {\n const cookie = serializeSetCookie(SESSION_COOKIE_NAME, '', {\n path: COOKIE_PATH,\n maxAgeSeconds: 0,\n secure: isHttpsRequest(context.request),\n clear: true,\n });\n appendSetCookie(context.response, cookie);\n}\n\n/** Read + verify the session cookie on `request`, or `null` when absent/tampered/expired. */\nexport function readSessionFromRequest(\n auth: ResolvedDashboardAuth,\n request: unknown,\n): DashboardSession | null {\n const cookieValue = parseCookieHeader(readCookieHeader(request))[SESSION_COOKIE_NAME];\n if (cookieValue === undefined) return null;\n return verifySessionCookie(cookieValue, { secret: auth.secret });\n}\n\n/**\n * In-flight `revalidate` calls, keyed by `<secret>:<sub>` (the secret disambiguates two\n * `dashboardAuth` configs that happen to share a process, e.g. tests) — joined, not repeated, by\n * every concurrent renewal of the SAME session. Entries are removed the moment their call settles\n * (`finally`, below), so this only ever holds calls genuinely in flight right now: it can't grow\n * without bound, and a throwing hook can't wedge a session's future renewals.\n */\nconst inFlightRevalidations = new Map<string, Promise<boolean>>();\n\n/**\n * Run `auth.revalidate` for `user`, joining an already-in-flight call for the same session instead\n * of starting a second one. This is what makes the `RevalidateHook` doc's \"runs at most once per\n * `ttl/2` per session\" true under real traffic: a single console page load fires several parallel\n * API calls, and without this every one of them carrying the same past-half-life cookie would\n * independently call the host's hook before the first renewal's fresh cookie lands. Every caller\n * still awaits the SAME outcome and applies it to its OWN request/response — only the host round\n * trip is shared.\n */\nfunction revalidateOnce(auth: ResolvedDashboardAuth, user: DashboardSessionUser): Promise<boolean> {\n const revalidate = auth.revalidate;\n if (!revalidate) return Promise.resolve(true);\n const key = `${auth.secret}:${user.id}`;\n const inFlight = inFlightRevalidations.get(key);\n if (inFlight) return inFlight;\n const call = Promise.resolve()\n .then(() => revalidate(user))\n // Fail closed: a throwing hook revokes rather than silently extending the session.\n .catch(() => false)\n .finally(() => {\n // Cleared on BOTH outcomes (the `.catch` above means this only ever sees a resolution, never\n // a rejection) so a later, non-concurrent renewal cycle calls the hook fresh rather than\n // reusing a stale result — and so the map never accumulates settled entries.\n inFlightRevalidations.delete(key);\n });\n inFlightRevalidations.set(key, call);\n return call;\n}\n\n/**\n * Sliding renewal + revalidation. When a valid cookie is past 50% of its TTL, re-issue a fresh one\n * so an active session never expires mid-use — but first give the host's `revalidate` hook a say,\n * so a deactivated or demoted user loses access instead of riding a self-renewing cookie forever.\n * Concurrent renewals of the same session share one `revalidate` call (see `revalidateOnce`).\n *\n * Returns `false` when the session was revoked (the clearing `Set-Cookie` is already queued and the\n * caller must deny the request); `true` otherwise, including when no renewal was due.\n */\nexport async function maybeRenewSession(\n auth: ResolvedDashboardAuth,\n session: DashboardSession,\n request: unknown,\n response: unknown,\n now: number = Date.now(),\n): Promise<boolean> {\n if (now - session.iat <= auth.ttlMs / 2) return true;\n const user: DashboardSessionUser = {\n id: session.sub,\n ...(session.name !== undefined ? { name: session.name } : {}),\n roles: session.roles,\n };\n const allowed = await revalidateOnce(auth, user);\n if (!allowed) {\n clearSessionCookie({ request, response });\n return false;\n }\n issueSessionCookie(user, { auth, request, response, now });\n return true;\n}\n","import {\n BadRequestException,\n Body,\n Controller,\n Get,\n Header,\n HttpCode,\n Inject,\n Logger,\n NotFoundException,\n Optional,\n Post,\n Req,\n Res,\n UnauthorizedException,\n} from '@nestjs/common';\nimport { DASHBOARD_AUTH, type ResolvedDashboardAuth } from './auth/dashboard-auth-config.js';\nimport { renderLoginPage } from './auth/login-page.js';\nimport { sanitizeReturnTo } from './auth/request.js';\nimport { redirectRaw } from './auth/response.js';\nimport { clearSessionCookie, issueSessionCookie } from './auth/session-cookie-io.js';\nimport type { DashboardSessionUser } from './auth/session-cookie.js';\nimport { DASHBOARD_BASE_PATH } from './catalog-ui.controller.js';\n\ninterface LoginBody {\n username?: unknown;\n password?: unknown;\n returnTo?: unknown;\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n/**\n * Mints/clears the `dashboardAuth` session cookie and serves the built-in login page. Mounted\n * under `basePath` alongside `CatalogUiController` (see `CatalogDashboardModule.forRoot`), but on\n * a SEPARATE controller so it is never itself behind `CatalogUiSessionGuard` — these endpoints\n * CREATE the session that guard checks for. `@Optional()` on both injections: this controller is\n * only registered when `dashboardAuth` might be configured (a static `forRoot({ dashboardAuth })`\n * or any `forRootAsync`), but the resolved value can still be `null` at runtime for the async case\n * — every handler below re-checks it and 404s rather than assuming it is set.\n */\n@Controller()\nexport class CatalogAuthController {\n private readonly logger = new Logger(CatalogAuthController.name);\n /** Warn once per hook kind so a throwing hook doesn't spam logs on every failed attempt. */\n private readonly warnedHooks = new Set<string>();\n\n constructor(\n @Optional() @Inject(DASHBOARD_AUTH) private readonly auth: ResolvedDashboardAuth | null,\n @Inject(DASHBOARD_BASE_PATH) private readonly basePath: string,\n ) {}\n\n // The login page reads `returnTo`/`error` from `location.search` client-side (see\n // `login-page.ts`), so this response never varies per request and needs no templating beyond\n // the developer-controlled `basePath`.\n @Get('login')\n @Header('Content-Type', 'text/html; charset=utf-8')\n @Header('Cache-Control', 'no-store, must-revalidate')\n loginPage(): string {\n const auth = this.requireAuth();\n if (!auth.modes.includes('login')) throw new NotFoundException();\n return renderLoginPage(this.basePath);\n }\n\n // Called by the login page's own fetch (JSON, not a classic form POST — see `login-page.ts` for\n // why: it keeps the login page working with no host-configured body parser beyond the\n // JSON one Nest wires in by default on both Express and Fastify). Uniform `401` on any failure\n // (unknown user, wrong password, throwing hook) — no user-enumeration.\n @Post('login')\n @HttpCode(200)\n async login(\n @Body() body: LoginBody,\n @Req() request: unknown,\n @Res({ passthrough: true }) response: unknown,\n ): Promise<{ redirectTo: string }> {\n const auth = this.requireAuth();\n if (!auth.modes.includes('login')) throw new NotFoundException();\n if (!isString(body?.username) || !isString(body?.password)) {\n throw new BadRequestException('Body must include string `username` and `password`.');\n }\n const { username, password } = body;\n const user = await this.runHook('login', () => auth.login?.(username, password) ?? null);\n if (!user) throw new UnauthorizedException({ message: 'Invalid username or password.' });\n issueSessionCookie(user, { auth, request, response });\n return { redirectTo: sanitizeReturnTo(body.returnTo, this.basePath) };\n }\n\n // Mode A: the host frontend (carrying its own auth) POSTs here; the host hook validates the raw\n // request and returns the session user, or `null` to deny. This is the SSO path — the host's own\n // guard decides, and no credential ever reaches this library.\n @Post('session')\n @HttpCode(204)\n async session(\n @Req() request: unknown,\n @Res({ passthrough: true }) response: unknown,\n ): Promise<void> {\n const auth = this.requireAuth();\n // Mode A not configured => the endpoint does not exist for this host.\n if (!auth.modes.includes('session')) throw new NotFoundException();\n const user = await this.runHook('session', () => auth.session?.(request) ?? null);\n if (!user) throw new UnauthorizedException();\n issueSessionCookie(user, { auth, request, response });\n }\n\n // Plain `GET` (not `POST`): logging out only ever destroys the CALLER's own session, so it's\n // safe/idempotent from the caller's perspective — a simple `<a href>` (no JS, no CSRF token)\n // works. Non-passthrough `@Res()`: this handler owns the response outright (clears the cookie,\n // then redirects), so Nest must not also try to send a return value afterwards.\n @Get('logout')\n logout(@Req() request: unknown, @Res() response: unknown): void {\n // Best-effort: even without dashboardAuth configured, clearing is harmless.\n clearSessionCookie({ request, response });\n // Only bounce to the login page when Mode B is actually configured — under Mode A (only), that\n // page 404s (see loginPage()); redirecting to basePath instead lands back on the guarded UI,\n // which renders the Mode-A session-required instruction page.\n redirectRaw(\n response,\n this.auth?.modes.includes('login') ? `${this.basePath}/login` : this.basePath,\n );\n }\n\n private requireAuth(): ResolvedDashboardAuth {\n // login()/session()/logout() only reach a real request when dashboardAuth is configured — this\n // is a defensive guard (matching loginPage()'s 404), not a reachable runtime path in practice.\n if (!this.auth) throw new NotFoundException();\n return this.auth;\n }\n\n /**\n * Run a host hook (`login` or `session`) defensively: a throw is treated as a denial (uniform\n * failure) and warn-logged once PER KIND, so a buggy hook never 500s the endpoint into a\n * stack-trace leak nor floods the logs on repeated bad attempts.\n */\n private async runHook(\n kind: string,\n run: () => Promise<DashboardSessionUser | null> | DashboardSessionUser | null,\n ): Promise<DashboardSessionUser | null> {\n try {\n return (await run()) ?? null;\n } catch (error) {\n if (!this.warnedHooks.has(kind)) {\n this.warnedHooks.add(kind);\n this.logger.warn(\n `dashboardAuth ${kind} hook threw; treating as denial. ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return null;\n }\n }\n}\n","/**\n * Shared HTML shell for the `dashboardAuth` server-rendered pages (the Mode B login page below and\n * `renderSessionRequiredPage`'s Mode A instruction page) — same dark zinc card, mono type, emerald\n * accent as `@dudousxd/nestjs-agent`'s dashboard login page, so every auth-adjacent page in this\n * family looks like one product. `content` is placed inside the `.card` div verbatim, so a caller\n * needing its own `<script>` (see `renderLoginPage`) can simply include it in `content` — a\n * `<script>` renders identically whether it's the div's last child or a body-level sibling.\n *\n * `content` is always caller-controlled static markup, never user input reflected into the page,\n * so this sidesteps HTML-escaping entirely.\n */\nfunction page(content: string, title = 'Catalog'): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<meta name=\"robots\" content=\"noindex, nofollow\" />\n<title>${title}</title>\n<style>\n :root { color-scheme: dark; }\n * { box-sizing: border-box; }\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: #09090b;\n color: #e4e4e7;\n font: 14px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n padding: 16px;\n }\n .card {\n width: 100%;\n max-width: 384px;\n border: 1px solid #27272a;\n background: #18181b;\n border-radius: 8px;\n padding: 32px;\n box-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.5);\n }\n .brand {\n margin: 0 0 24px;\n text-align: center;\n font-size: 18px;\n font-weight: 600;\n color: #34d399;\n }\n h1 {\n margin: 0 0 12px;\n font-size: 16px;\n font-weight: 600;\n color: #f4f4f5;\n }\n p { margin: 0 0 16px; color: #a1a1aa; }\n form { display: flex; flex-direction: column; gap: 16px; }\n label { display: flex; flex-direction: column; gap: 6px; }\n .field-label {\n font-size: 11px;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: #71717a;\n }\n input {\n border-radius: 4px;\n border: 1px solid #3f3f46;\n background: #09090b;\n color: #f4f4f5;\n padding: 8px 12px;\n font: inherit;\n outline: none;\n }\n input:focus { border-color: rgb(52 211 153 / 0.6); }\n #error {\n display: none;\n margin: 0;\n font-size: 12px;\n color: #fb7185;\n }\n button, .button {\n margin-top: 8px;\n border-radius: 4px;\n border: 1px solid rgb(52 211 153 / 0.4);\n background: rgb(52 211 153 / 0.1);\n color: #6ee7b7;\n padding: 8px 12px;\n font: inherit;\n font-size: 12px;\n font-weight: 500;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n cursor: pointer;\n display: inline-block;\n text-align: center;\n text-decoration: none;\n box-sizing: border-box;\n }\n button:hover:not(:disabled), .button:hover { background: rgb(52 211 153 / 0.2); }\n button:disabled { opacity: 0.6; cursor: default; }\n</style>\n</head>\n<body>\n <div class=\"card\">\n ${content}\n </div>\n</body>\n</html>`;\n}\n\n/**\n * The built-in `dashboardAuth` login page (`GET <basePath>/login`, Mode B). Deliberately a small,\n * dependency-free, hand-authored HTML page — NOT part of the bundled React SPA — so gating the\n * dashboard shell doesn't require rebuilding or extending the Vite bundle with a new route/screen.\n *\n * `returnTo` and any error state are read CLIENT-SIDE from `location.search` (never server-echoed\n * into the HTML), so this function's only per-request-ish input is `basePath` — a developer-\n * controlled config value, not user input — and the page body is otherwise a static template.\n *\n * The submit flow (this page POSTs JSON via `fetch` and follows the JSON `redirectTo` it gets\n * back, rather than a classic form POST + server redirect) is why the markup keeps its own\n * `<script>` rather than adopting agent-dashboard's plain `<form method=\"post\">`.\n */\nexport function renderLoginPage(basePath: string): string {\n const loginAction = `${basePath}/login`;\n const defaultReturnTo = basePath;\n return page(\n `<p class=\"brand\">Catalog</p>\n <form id=\"login-form\" autocomplete=\"on\">\n <label>\n <span class=\"field-label\">Username</span>\n <input id=\"username\" name=\"username\" type=\"text\" autocomplete=\"username\" required autofocus />\n </label>\n <label>\n <span class=\"field-label\">Password</span>\n <input id=\"password\" name=\"password\" type=\"password\" autocomplete=\"current-password\" />\n </label>\n <p id=\"error\" role=\"alert\">Invalid username or password.</p>\n <button id=\"submit\" type=\"submit\">Sign in</button>\n </form>\n<script>\n(function () {\n var LOGIN_ACTION = ${JSON.stringify(loginAction)};\n var DEFAULT_RETURN_TO = ${JSON.stringify(defaultReturnTo)};\n var params = new URLSearchParams(window.location.search);\n var errorBox = document.getElementById('error');\n if (params.get('error')) errorBox.style.display = 'block';\n\n function sameOriginReturnTo(value) {\n if (typeof value !== 'string' || value === '') return DEFAULT_RETURN_TO;\n if (value.charAt(0) !== '/' || value.charAt(1) === '/' || value.indexOf('://') !== -1) {\n return DEFAULT_RETURN_TO;\n }\n return value;\n }\n\n var form = document.getElementById('login-form');\n var submitButton = document.getElementById('submit');\n form.addEventListener('submit', function (event) {\n event.preventDefault();\n submitButton.disabled = true;\n errorBox.style.display = 'none';\n var returnTo = sameOriginReturnTo(params.get('returnTo'));\n fetch(LOGIN_ACTION, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n credentials: 'same-origin',\n body: JSON.stringify({\n username: document.getElementById('username').value,\n password: document.getElementById('password').value,\n returnTo: returnTo,\n }),\n })\n .then(function (response) {\n if (!response.ok) throw new Error('unauthorized');\n return response.json();\n })\n .then(function (data) {\n window.location.href = data.redirectTo || DEFAULT_RETURN_TO;\n })\n .catch(function () {\n errorBox.style.display = 'block';\n submitButton.disabled = false;\n });\n });\n})();\n</script>`,\n 'Sign in — Catalog',\n );\n}\n\n/**\n * Mode-A-only shell (`GET <basePath>/login` never renders under Mode A — this is what the page\n * guard serves in its place, see `session-required.exception.ts`): there is no form here because\n * the host mints the session. Mirrors `renderLoginPage`'s markup so the two pages look like one\n * product. `basePath` drives the Retry link's `href` — a plain `<a>` back to the guarded mount\n * (which re-runs the check once the host has minted a session), keeping this page free of any\n * inline `<script>`, unlike `renderLoginPage`'s fetch-driven form.\n */\nexport function renderSessionRequiredPage(basePath: string): string {\n return page(\n `<h1>Open this console from your application</h1>\n <p>Your session is minted by the host app. Use its console launcher to sign in, then reload.</p>\n <a class=\"button\" href=\"${basePath}\">Retry</a>`,\n );\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { basename, extname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n Controller,\n Get,\n Header,\n Inject,\n NotFoundException,\n Optional,\n Param,\n StreamableFile,\n UseFilters,\n} from '@nestjs/common';\nimport { DASHBOARD_AUTH } from './auth/dashboard-auth-config.js';\nimport { DashboardLoginRedirectFilter } from './auth/login-redirect.exception.js';\nimport { DashboardSessionRequiredFilter } from './auth/session-required.exception.js';\n\n/** DI token carrying the UI mount base (e.g. `/catalog`). */\nexport const DASHBOARD_BASE_PATH = Symbol('DASHBOARD_BASE_PATH');\n/** DI token carrying the JSON API base the SPA fetches from (e.g. `/api/catalog`). */\nexport const DASHBOARD_API_PATH = Symbol('DASHBOARD_API_PATH');\n\n/** The base the SPA bundle was built with (Vite `base`); rewritten to the configured base at serve time. */\nconst BUILD_BASE = '/catalog';\n\n/** dist/server/catalog-ui.controller.js -> ../spa (the Vite build output). */\nfunction spaDir(): string {\n return fileURLToPath(new URL('../spa', import.meta.url));\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.json': 'application/json; charset=utf-8',\n '.woff2': 'font/woff2',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Serves the bundled control-plane SPA at the configured base (+ hashed assets at `<base>/assets`).\n * The path comes from `RouterModule` (set by `CatalogDashboardModule.forRoot({ basePath })`), so the\n * controller routes are relative.\n *\n * `@UseFilters(DashboardLoginRedirectFilter, DashboardSessionRequiredFilter)` is permanent (present\n * regardless of whether `dashboardAuth` is configured): each only ever activates for its own\n * exception type, which `CatalogUiSessionGuard` only throws when it is ALSO stamped on this\n * controller (see `CatalogDashboardModule.forRoot`) — so leaving them decorated here is inert, not\n * a behavior change, when `dashboardAuth` is absent. The guard picks between the two exceptions\n * based on which mode is configured (Mode B => redirect to the login page; Mode A only => render\n * the session-required instruction page in place, since there is no login page to redirect to).\n */\n@UseFilters(DashboardLoginRedirectFilter, DashboardSessionRequiredFilter)\n@Controller()\nexport class CatalogUiController {\n private readonly dir = spaDir();\n\n constructor(\n @Inject(DASHBOARD_BASE_PATH) private readonly basePath: string,\n @Inject(DASHBOARD_API_PATH) private readonly apiBasePath: string,\n @Optional()\n @Inject(DASHBOARD_AUTH)\n private readonly auth: unknown = null,\n ) {}\n\n // index.html references hash-named bundles, so it MUST NOT be cached (stale bundle = the\n // classic \"stuck loading after a deploy\"). The hashed assets below are immutable.\n @Get()\n @Header('Content-Type', 'text/html; charset=utf-8')\n @Header('Cache-Control', 'no-store, must-revalidate')\n index(): string {\n const indexPath = join(this.dir, 'index.html');\n if (!existsSync(indexPath)) {\n throw new NotFoundException('Dashboard is not built. Run the package build.');\n }\n // The bundle was built with Vite base `/catalog/`; rewrite asset URLs to the configured base so\n // the SPA loads from `<base>/assets` wherever it's mounted, and tell the client its API base.\n const html = readFileSync(indexPath, 'utf8').replaceAll(\n `=\"${BUILD_BASE}/`,\n `=\"${this.basePath}/`,\n );\n // __CATALOG_BASE__ = where assets load; __CATALOG_API__ = where the SPA fetches the JSON API;\n // __CATALOG_HOST_AUTH__ = whether the HOST authenticates, in which case the SPA must not show\n // its own sign-in. A console mounted inside an application that already knows who you are and\n // then asks you to log in again is not a smaller problem than one that lets anybody in.\n const hostAuth = this.auth ? 'true' : 'false';\n const inject = `<script>window.__CATALOG_BASE__='${this.basePath}';window.__CATALOG_API__='${this.apiBasePath}';window.__CATALOG_HOST_AUTH__=${hostAuth};</script>`;\n return html.includes('</head>') ? html.replace('</head>', `${inject}</head>`) : inject + html;\n }\n\n @Get('assets/:file')\n @Header('Cache-Control', 'public, max-age=31536000, immutable')\n asset(@Param('file') file: string): StreamableFile {\n const safe = basename(file);\n if (safe !== file) throw new NotFoundException();\n const root = resolve(this.dir, 'assets');\n const assetPath = resolve(root, safe);\n if (!assetPath.startsWith(root + sep) || !existsSync(assetPath)) {\n throw new NotFoundException();\n }\n const type = CONTENT_TYPES[extname(safe)] ?? 'application/octet-stream';\n return new StreamableFile(readFileSync(assetPath), { type });\n }\n}\n","import type { ArgumentsHost, ExceptionFilter } from '@nestjs/common';\nimport { Catch, HttpException, HttpStatus } from '@nestjs/common';\nimport { redirectRaw } from './response.js';\n\n/**\n * Thrown by `CatalogUiSessionGuard` when a page-level (full-page navigation) request has no valid\n * `dashboardAuth` session — carries the login URL to redirect to. Guards can't use Nest's\n * `@Redirect()` decorator (that only applies to a controller handler's return value), so the\n * guard throws this and a dedicated, controller-scoped `DashboardLoginRedirectFilter` (see below)\n * turns it into a real `302`. This is the ONLY safe way to redirect from a guard: writing directly\n * to the response inside `canActivate` and then returning `false` risks a double-write (Nest still\n * tries to send a `ForbiddenException` response afterwards) — routing through the normal\n * exception-filter pipeline instead guarantees exactly one writer finalizes the response.\n */\nexport class DashboardLoginRedirectException extends HttpException {\n constructor(public readonly location: string) {\n super({ location }, HttpStatus.FOUND);\n }\n}\n\n/** Turns a `DashboardLoginRedirectException` into a real `302 Location: <location>` response. */\n@Catch(DashboardLoginRedirectException)\nexport class DashboardLoginRedirectFilter implements ExceptionFilter {\n catch(exception: DashboardLoginRedirectException, host: ArgumentsHost): void {\n const response = host.switchToHttp().getResponse();\n redirectRaw(response, exception.location);\n }\n}\n","import type { ArgumentsHost, ExceptionFilter } from '@nestjs/common';\nimport { Catch, HttpException, HttpStatus, Inject, Logger, Optional } from '@nestjs/common';\nimport { DASHBOARD_AUTH, type ResolvedDashboardAuth } from './dashboard-auth-config.js';\nimport { renderSessionRequiredPage } from './login-page.js';\nimport { responseAlreadyWritten, writeHtmlRaw } from './response.js';\n\n/**\n * Thrown by `CatalogUiSessionGuard` when a page-level (full-page navigation) request has no valid\n * `dashboardAuth` session AND Mode B (`login`) isn't configured — there is no login page to\n * redirect to (see `DashboardLoginRedirectException`, its Mode-B sibling). Carries `basePath` so\n * the filter below can render the Mode-A instruction page in its place. Same reasoning as the\n * login redirect for why a guard can't just write the response directly and return `false`: a\n * dedicated, controller-scoped `DashboardSessionRequiredFilter` (see below) is the only writer,\n * guaranteeing no double-write race.\n */\nexport class DashboardSessionRequiredException extends HttpException {\n constructor(public readonly basePath: string) {\n super({ basePath }, HttpStatus.UNAUTHORIZED);\n }\n}\n\n/**\n * Renders the Mode-A page for a denied navigation: the host's own `unauthenticatedPage` when one is\n * configured, otherwise the built-in instruction card.\n *\n * `@Optional()` on the injection is load-bearing. This filter is decorated onto\n * `CatalogUiController` unconditionally (see that controller's docblock — it is inert when\n * `dashboardAuth` is absent, because the guard that throws its exception is only stamped on when\n * auth IS configured), so it must still construct in a module where `DASHBOARD_AUTH` was never\n * provided.\n */\n@Catch(DashboardSessionRequiredException)\nexport class DashboardSessionRequiredFilter implements ExceptionFilter {\n private readonly logger = new Logger(DashboardSessionRequiredFilter.name);\n private warned = false;\n\n constructor(\n @Optional()\n @Inject(DASHBOARD_AUTH)\n private readonly auth: ResolvedDashboardAuth | null = null,\n ) {}\n\n async catch(exception: DashboardSessionRequiredException, host: ArgumentsHost): Promise<void> {\n const http = host.switchToHttp();\n const response = http.getResponse();\n const hook = this.auth?.unauthenticatedPage;\n\n if (hook) {\n try {\n await hook({ request: http.getRequest(), response, basePath: exception.basePath });\n // The hook owns the response; if it wrote one, we are done.\n if (responseAlreadyWritten(response)) return;\n // It did not write. Falling through to the built-in page is the only outcome that neither\n // hangs the request forever nor invents a page the host did not ask for — but it is almost\n // certainly a bug in the hook, so say so.\n this.warnOnce(\n 'dashboardAuth.unauthenticatedPage returned without writing a response; falling back to ' +\n 'the built-in page. The hook must write AND end the response it is given.',\n );\n } catch (error) {\n // A broken host page must not turn a denial into a 500, and must never open the console.\n this.warnOnce(\n `dashboardAuth.unauthenticatedPage threw; falling back to the built-in page. ${String(error)}`,\n );\n // It may have written headers before throwing, in which case there is nothing left to do:\n // writing again would raise ERR_HTTP_HEADERS_SENT on top of the original failure.\n if (responseAlreadyWritten(response)) return;\n }\n }\n\n writeHtmlRaw(response, renderSessionRequiredPage(exception.basePath), HttpStatus.UNAUTHORIZED);\n }\n\n /** Once per process, not once per request: a broken hook fires on every denied navigation. */\n private warnOnce(message: string): void {\n if (this.warned) return;\n this.warned = true;\n this.logger.warn(message);\n }\n}\n","import {\n type DynamicModule,\n type FactoryProvider,\n Module,\n type Provider,\n type Type,\n UseGuards,\n} from '@nestjs/common';\nimport { RouterModule } from '@nestjs/core';\nimport {\n DASHBOARD_AUTH,\n type DashboardAuthOptions,\n resolveDashboardAuth,\n} from './auth/dashboard-auth-config.js';\nimport { CatalogAuthController } from './catalog-auth.controller.js';\nimport { CatalogUiSessionGuard } from './catalog-session.guard.js';\nimport {\n CatalogUiController,\n DASHBOARD_API_PATH,\n DASHBOARD_BASE_PATH,\n} from './catalog-ui.controller.js';\n\nexport interface CatalogDashboardOptions {\n /**\n * Where the console is served. Default `/catalog`.\n *\n * Not under the host's API prefix: this serves HTML and assets, and a host\n * that sets a global `/api` prefix has to exclude these paths from it — see\n * {@link catalogDashboardMountPaths}.\n */\n path?: string;\n /**\n * Where the catalog's JSON API lives, baked into the SPA so it knows what to\n * call. Default `/api/catalog-service`.\n *\n * A separate option because the console does NOT proxy the API — unlike some\n * Aviary dashboards, the catalog's HTTP surface is already mounted by\n * `CatalogModule` and `CatalogPipelineModule`, and a second copy behind this\n * console would be a second set of routes to keep authorised.\n */\n apiPath?: string;\n /**\n * How a visitor is authenticated.\n *\n * **Omit it and the console is open.** That is a real decision, not a\n * default to drift into: this console can rewrite a catalog's model and run\n * its connectors. A host with any notion of users should pass this, and a\n * host that means to leave it open should say so where someone will read it.\n */\n auth?: DashboardAuthOptions;\n /**\n * Guards fronting the console's own controllers.\n *\n * Separate from `auth`, and the reason is the failure it prevents: `auth`\n * describes how a session is validated, so a host that has not configured it\n * yet has an OPEN console. A host that would rather be shut than open passes a\n * denying guard here — it needs no secret, no DI and no session to work.\n *\n * Bound at module-definition time, so it cannot come from `forRootAsync`.\n */\n guards?: Type<unknown>[];\n}\n\nexport interface CatalogDashboardAsyncOptions extends Omit<CatalogDashboardOptions, 'auth'> {\n imports?: DynamicModule['imports'];\n inject?: FactoryProvider['inject'];\n /**\n * Builds the auth from DI. See {@link CatalogDashboardModule.forRootAsync}.\n *\n * May return `undefined`, and that is the important case rather than an\n * afterthought: a host whose signing secret is unset has no way to mint a\n * session, and the honest answer is \"no auth mechanism\" — paired with a\n * denying `guards` entry, which is what turns that into a CLOSED console\n * instead of an open one. Forcing a return here would push hosts to invent an\n * auth object around an absent secret, i.e. a cookie signed with nothing.\n */\n useDashboardAuth: (\n ...args: never[]\n ) => DashboardAuthOptions | undefined | Promise<DashboardAuthOptions | undefined>;\n}\n\n/**\n * The catalog console, as a mountable module.\n *\n * Serves the SPA and the session endpoints; nothing else. The screens come from\n * `@dudousxd/nestjs-catalog-react` and the data from the catalog's own API, so\n * this package is the mount, the auth and the asset serving — the three things a\n * component library cannot do for itself.\n */\n@Module({})\nexport class CatalogDashboardModule {\n static forRoot(options: CatalogDashboardOptions = {}): DynamicModule {\n // Resolved, not passed through: `resolveDashboardAuth` derives `modes` from\n // which hooks are present, and every consumer reads that. Handing over the\n // raw options gives a value whose `modes` is undefined, and the endpoints\n // fail with `Cannot read properties of undefined (reading 'includes')` — a\n // 500 where a 401 belongs.\n return build(options, {\n provide: DASHBOARD_AUTH,\n useValue: options.auth ? resolveDashboardAuth(options.auth) : null,\n });\n }\n\n /**\n * Same mount, but the auth is built from DI.\n *\n * Needed whenever validating a session means asking something the host owns —\n * a user store, a session service. `forRoot` cannot express that: `guards` and\n * the router are bound at module-DEFINITION time, before any injector exists,\n * which is why `guards` stays a static option on both forms.\n */\n static forRootAsync(options: CatalogDashboardAsyncOptions): DynamicModule {\n const factory = options.useDashboardAuth;\n const mounted = build(options, {\n provide: DASHBOARD_AUTH,\n // Same resolution as `forRoot`, wrapped around the host's factory so the\n // async path cannot skip it.\n useFactory: async (...args: never[]) => {\n const auth = await factory(...args);\n return auth ? resolveDashboardAuth(auth) : null;\n },\n inject: options.inject ?? [],\n });\n // Appended, not replaced: `build` puts the RouterModule registration in\n // `imports`, and overwriting it would leave the console unrouted.\n return {\n ...mounted,\n imports: [...(mounted.imports ?? []), ...(options.imports ?? [])],\n };\n }\n}\n\n/** See the note where this is set: `UseGuards` appends, and these classes are shared. */\nlet sessionGuardStamped = false;\n\nfunction build(\n options: CatalogDashboardOptions | CatalogDashboardAsyncOptions,\n auth: Provider,\n): DynamicModule {\n const path = normalise(options.path ?? '/catalog');\n const apiPath = normalise(options.apiPath ?? '/api/catalog-service');\n\n // The session guard, on the SPA and its assets.\n //\n // This was missing, and its absence was not visible from anywhere: `auth`\n // configures how a session is minted and validated, the docblocks describe it\n // as the thing that closes an otherwise-open console, and nothing ever stamped\n // the guard that enforces it. A host that configured `auth` correctly still\n // served the console shell to anyone who could reach the URL.\n //\n // NOT on `CatalogAuthController`: that is where a session is obtained, and\n // gating it on already having one locks the door from the inside.\n //\n // The guard is a no-op when `auth` is absent, so this is safe on an\n // intentionally open mount — \"open\" then remains a decision the host made by\n // omitting `auth`, rather than one the module made by forgetting.\n //\n // Stamped once per process, not once per mount. `UseGuards` APPENDS to the\n // controller's metadata and these controller classes are module-level, so a\n // second `forRoot` in the same process would run the guard twice per request.\n if (!sessionGuardStamped) {\n UseGuards(CatalogUiSessionGuard)(CatalogUiController);\n sessionGuardStamped = true;\n }\n\n // Host guards on top, applied to both controllers so a host can shut the whole\n // console — including the way in — without touching the rest of its app.\n // `UseGuards` at definition time is why `guards` cannot come from DI.\n for (const guard of options.guards ?? []) {\n UseGuards(guard)(CatalogUiController);\n UseGuards(guard)(CatalogAuthController);\n }\n\n const providers: Provider[] = [\n { provide: DASHBOARD_BASE_PATH, useValue: path },\n { provide: DASHBOARD_API_PATH, useValue: apiPath },\n auth,\n // Constructed by Nest, so it must be declared here — a guard stamped by\n // `UseGuards` is still resolved from the declaring module's injector.\n CatalogUiSessionGuard,\n ];\n\n return {\n module: CatalogDashboardModule,\n // The controllers are `@Controller()` with no path of their own, and the\n // prefix arrives here instead. That is what lets `path` be configurable at\n // all: a decorator argument is fixed at class-definition time, so a\n // hardcoded one would pin every host to the same mount point.\n //\n // Without this the controllers inherit whatever the host's global prefix is\n // — they answered on `/api` — and the console 404s at its configured path\n // while the module reports itself initialised, which is a confusing pair of\n // symptoms to hold at once.\n imports: [RouterModule.register([{ path, module: CatalogDashboardModule }])],\n controllers: [CatalogUiController, CatalogAuthController],\n providers,\n exports: providers,\n };\n}\n\n/**\n * The paths a host must exclude from its global API prefix.\n *\n * Without this, a host calling `setGlobalPrefix('api')` moves the console to\n * `/api/catalog` while the SPA still asks for `/catalog/assets/...`, and the\n * console loads as a blank page with 404s in the network tab — which reads as a\n * broken build rather than a routing mistake.\n *\n * Derived from the same defaulting `forRoot` uses, so the two cannot drift.\n */\nexport function catalogDashboardMountPaths(\n options: Pick<CatalogDashboardOptions, 'path'> = {},\n): string[] {\n const base = normalise(options.path ?? '/catalog').replace(/^\\//, '');\n // Plain strings with a `{*splat}` wildcard, which is the shape `setGlobalPrefix`'s\n // `exclude` matches and what every other Aviary console helper returns. An\n // object form is accepted by the type but does NOT match here, and the symptom\n // is subtle: the console mounts, logs itself as initialised, and answers on\n // `/api/<path>` while 404ing at `/<path>`.\n return [base, `${base}/{*splat}`];\n}\n\n/** Leading slash, no trailing one — the shape every consumer below assumes. */\nfunction normalise(path: string): string {\n const withLeading = path.startsWith('/') ? path : `/${path}`;\n return withLeading.length > 1 ? withLeading.replace(/\\/+$/, '') : withLeading;\n}\n","import {\n type CanActivate,\n type ExecutionContext,\n Inject,\n Injectable,\n UnauthorizedException,\n} from '@nestjs/common';\nimport { DASHBOARD_AUTH, type ResolvedDashboardAuth } from './auth/dashboard-auth-config.js';\nimport { DashboardLoginRedirectException } from './auth/login-redirect.exception.js';\nimport { originalRequestUrl } from './auth/request.js';\nimport { maybeRenewSession, readSessionFromRequest } from './auth/session-cookie-io.js';\nimport { DashboardSessionRequiredException } from './auth/session-required.exception.js';\nimport { DASHBOARD_BASE_PATH } from './catalog-ui.controller.js';\n\n/**\n * Gates `CatalogUiController` (the SPA shell + assets, a full-page browser navigation) on a valid\n * `dashboardAuth` session cookie. A no-op (always `true`) when `dashboardAuth` was not configured\n * — see `CatalogDashboardModule.forRoot`'s `dashboardAuth` doc. Missing/invalid/expired session,\n * when Mode B (`login`) is configured, gets a `302` to the built-in login page carrying\n * `?returnTo=<original url>`, via `DashboardLoginRedirectException` (see that file for why a guard\n * can't just call `response.redirect()` and return `false`). When only Mode A (`session`) is\n * configured there is no login page to redirect to — the host mints the session itself — so it\n * instead throws `DashboardSessionRequiredException`, rendering a small instruction page.\n *\n * Auth is mount-level and role-agnostic: this guard has no notion of control-plane vs tenant\n * (see the catalog dashboard's topology note in `dashboard.service.ts`) — it only ever answers\n * \"is there a valid dashboard session\", nothing role-specific changes here.\n */\n@Injectable()\nexport class CatalogUiSessionGuard implements CanActivate {\n constructor(\n @Inject(DASHBOARD_AUTH) private readonly auth: ResolvedDashboardAuth | null,\n @Inject(DASHBOARD_BASE_PATH) private readonly basePath: string,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n if (!this.auth) return true;\n const auth = this.auth;\n const http = context.switchToHttp();\n const request = http.getRequest<unknown>();\n const session = readSessionFromRequest(auth, request);\n if (!session) {\n this.denyUnauthenticated(auth, request);\n }\n if (!(await maybeRenewSession(auth, session, request, http.getResponse()))) {\n this.denyUnauthenticated(auth, request);\n }\n return true;\n }\n\n /**\n * A revoked session (the host's `revalidate` hook says no) is denied exactly like an absent\n * one — by design, there is nothing left to distinguish \"never had a session\" from \"had one,\n * then lost it\" once the cookie is cleared, so both get the same Mode-aware treatment.\n *\n * Takes `auth` explicitly rather than reading `this.auth`: `canActivate`'s `!this.auth` early\n * return narrows the field within that method only — TS doesn't carry it across a method call\n * — so callers pass the already-narrowed value instead of this method re-deriving (or\n * asserting away) the nullability.\n */\n private denyUnauthenticated(auth: ResolvedDashboardAuth, request: unknown): never {\n if (!auth.modes.includes('login')) throw new DashboardSessionRequiredException(this.basePath);\n const returnTo = encodeURIComponent(originalRequestUrl(request));\n throw new DashboardLoginRedirectException(`${this.basePath}/login?returnTo=${returnTo}`);\n }\n}\n\n/**\n * Gates `CatalogApiController` (the JSON API the SPA fetches) on a valid `dashboardAuth` session\n * cookie. A no-op (always `true`) when `dashboardAuth` was not configured. Missing/invalid/expired\n * session => a plain `401` (the API is called via `fetch`, never a browser navigation, so a\n * redirect would just fail the request anyway — the caller reads the status code, not HTML).\n *\n * Mount-level and role-agnostic, same as `CatalogUiSessionGuard` above.\n */\n@Injectable()\nexport class CatalogApiSessionGuard implements CanActivate {\n constructor(@Inject(DASHBOARD_AUTH) private readonly auth: ResolvedDashboardAuth | null) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n if (!this.auth) return true;\n const auth = this.auth;\n const http = context.switchToHttp();\n const request = http.getRequest<unknown>();\n const session = readSessionFromRequest(auth, request);\n if (!session) throw this.unauthorized(auth);\n if (!(await maybeRenewSession(auth, session, request, http.getResponse()))) {\n // Revoked mid-session: same treatment as an absent cookie.\n throw this.unauthorized(auth);\n }\n return true;\n }\n\n /**\n * A bare 401 body carrying `{ auth: { modes } }` — mirrors `@dudousxd/nestjs-telescope`'s\n * dashboardAuth 401. The API is fetched (never navigated), so this is the ONLY way the console\n * SPA (`catalog-client.ts`) learns which auth surface to send the operator to on a mid-session\n * 401; `CatalogUiSessionGuard`'s redirect/session-required exceptions above don't reach it.\n */\n private unauthorized(auth: ResolvedDashboardAuth): UnauthorizedException {\n return new UnauthorizedException({ auth: { modes: au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ASP;EACX;AACF;AA/DSxB;AA2EF,SAASgC,2BACdjC,UAAiD,CAAC,GAAC;AAEnD,QAAMkC,OAAOjB,UAAUjB,QAAQgB,QAAQ,UAAA,EAAYmB,QAAQ,OAAO,EAAA;AAMlE,SAAO;IAACD;IAAM,GAAGA,IAAAA;;AACnB;AAVgBD;AAahB,SAAShB,UAAUD,MAAY;AAC7B,QAAMoB,cAAcpB,KAAKqB,WAAW,GAAA,IAAOrB,OAAO,IAAIA,IAAAA;AACtD,SAAOoB,YAAYE,SAAS,IAAIF,YAAYD,QAAQ,QAAQ,EAAA,IAAMC;AACpE;AAHSnB;","names":["DASHBOARD_AUTH","Symbol","DEFAULT_TTL","DEFAULT_TTL_MS","DURATION_UNITS","s","m","h","d","durationToMs","ttl","match","exec","trim","unit","undefined","Number","assertOptionalHook","value","name","Error","resolveDashboardAuth","options","secret","session","login","revalidate","unauthenticatedPage","modes","push","length","ttlMs","parseCookieHeader","header","cookies","segment","split","eq","indexOf","name","slice","trim","rawValue","length","startsWith","endsWith","decodeURIComponent","serializeSetCookie","value","options","parts","clear","encodeURIComponent","push","path","secure","maxAgeSeconds","join","isRecord","value","readHeaders","request","headers","headerToString","Array","isArray","every","part","join","undefined","readCookieHeader","cookie","isHttpsRequest","protocol","forwarded","split","map","proto","trim","toLowerCase","includes","originalRequestUrl","originalUrl","url","sanitizeReturnTo","candidate","fallback","startsWith","isRecord","value","isRawCookieResponse","getHeader","setHeader","resolveCookieResponse","response","raw","existingSetCookies","current","Array","isArray","appendSetCookie","cookie","isRawRedirectResponse","end","resolveRedirectResponse","redirectRaw","location","status","statusCode","responseAlreadyWritten","headersSent","writeHtmlRaw","html","EXP_GRACE_MS","base64urlEncode","value","Buffer","from","toString","base64urlDecode","hmac","secret","payload","createHmac","update","digest","signSessionCookie","user","options","issuedAt","now","Date","session","sub","id","name","undefined","roles","iat","exp","ttlMs","encodedPayload","JSON","stringify","signature","isSessionPayload","record","Array","isArray","every","role","Number","isFinite","verifySessionCookie","dot","indexOf","length","slice","providedSignature","expectedSignature","provided","expected","timingSafeEqual","decoded","parse","SESSION_COOKIE_NAME","COOKIE_PATH","issueSessionCookie","user","context","value","signSessionCookie","secret","auth","ttlMs","now","undefined","cookie","serializeSetCookie","path","maxAgeSeconds","Math","floor","secure","isHttpsRequest","request","appendSetCookie","response","clearSessionCookie","clear","readSessionFromRequest","cookieValue","parseCookieHeader","readCookieHeader","verifySessionCookie","inFlightRevalidations","Map","revalidateOnce","revalidate","Promise","resolve","key","id","inFlight","get","call","then","catch","finally","delete","set","maybeRenewSession","session","Date","iat","sub","name","roles","allowed","import_common","page","content","title","renderLoginPage","basePath","loginAction","defaultReturnTo","JSON","stringify","renderSessionRequiredPage","import_common","DashboardLoginRedirectException","HttpException","location","HttpStatus","FOUND","DashboardLoginRedirectFilter","catch","exception","host","response","switchToHttp","getResponse","redirectRaw","import_common","DashboardSessionRequiredException","HttpException","basePath","HttpStatus","UNAUTHORIZED","DashboardSessionRequiredFilter","logger","Logger","name","warned","auth","catch","exception","host","http","switchToHttp","response","getResponse","hook","unauthenticatedPage","request","getRequest","responseAlreadyWritten","warnOnce","error","String","writeHtmlRaw","renderSessionRequiredPage","message","warn","DASHBOARD_BASE_PATH","Symbol","DASHBOARD_API_PATH","BUILD_BASE","spaDir","fileURLToPath","URL","CONTENT_TYPES","CatalogUiController","dir","basePath","apiBasePath","auth","index","indexPath","join","existsSync","NotFoundException","html","readFileSync","replaceAll","hostAuth","inject","includes","replace","asset","file","safe","basename","root","resolve","assetPath","startsWith","sep","type","extname","StreamableFile","isString","value","CatalogAuthController","logger","Logger","name","warnedHooks","Set","auth","basePath","loginPage","requireAuth","modes","includes","NotFoundException","renderLoginPage","login","body","request","response","username","password","BadRequestException","user","runHook","UnauthorizedException","message","issueSessionCookie","redirectTo","sanitizeReturnTo","returnTo","session","logout","clearSessionCookie","redirectRaw","kind","run","error","has","add","warn","Error","String","passthrough","import_common","import_common","CatalogUiSessionGuard","auth","basePath","canActivate","context","http","switchToHttp","request","getRequest","session","readSessionFromRequest","denyUnauthenticated","maybeRenewSession","getResponse","modes","includes","DashboardSessionRequiredException","returnTo","encodeURIComponent","originalRequestUrl","DashboardLoginRedirectException","CatalogApiSessionGuard","unauthorized","UnauthorizedException","CatalogDashboardModule","forRoot","options","build","provide","DASHBOARD_AUTH","useValue","auth","resolveDashboardAuth","forRootAsync","factory","useDashboardAuth","mounted","useFactory","args","inject","imports","sessionGuardStamped","path","normalise","apiPath","UseGuards","CatalogUiSessionGuard","CatalogUiController","guard","guards","CatalogAuthController","providers","DASHBOARD_BASE_PATH","DASHBOARD_API_PATH","module","RouterModule","register","controllers","exports","catalogDashboardMountPaths","base","replace","withLeading","startsWith","length"]}
|
package/dist/server/index.js
CHANGED
|
@@ -19,30 +19,24 @@ function durationToMs(ttl) {
|
|
|
19
19
|
return Number(match[1]) * unit;
|
|
20
20
|
}
|
|
21
21
|
__name(durationToMs, "durationToMs");
|
|
22
|
+
function assertOptionalHook(value, name) {
|
|
23
|
+
if (value !== void 0 && typeof value !== "function") {
|
|
24
|
+
throw new Error(`CatalogDashboardModule: dashboardAuth.${name} must be a function.`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
__name(assertOptionalHook, "assertOptionalHook");
|
|
22
28
|
function resolveDashboardAuth(options) {
|
|
23
29
|
if (options === void 0) return null;
|
|
24
30
|
if (typeof options.secret !== "string" || options.secret === "") {
|
|
25
31
|
throw new Error("CatalogDashboardModule: dashboardAuth.secret is required and must be a non-empty string (HMAC-SHA256 signing key, 32+ bytes recommended). Failing closed.");
|
|
26
32
|
}
|
|
33
|
+
assertOptionalHook(options.session, "session");
|
|
34
|
+
assertOptionalHook(options.login, "login");
|
|
35
|
+
assertOptionalHook(options.revalidate, "revalidate");
|
|
36
|
+
assertOptionalHook(options.unauthenticatedPage, "unauthenticatedPage");
|
|
27
37
|
const modes = [];
|
|
28
|
-
if (options.session !== void 0)
|
|
29
|
-
|
|
30
|
-
throw new Error("CatalogDashboardModule: dashboardAuth.session must be a function.");
|
|
31
|
-
}
|
|
32
|
-
modes.push("session");
|
|
33
|
-
}
|
|
34
|
-
if (options.login !== void 0) {
|
|
35
|
-
if (typeof options.login !== "function") {
|
|
36
|
-
throw new Error("CatalogDashboardModule: dashboardAuth.login must be a function.");
|
|
37
|
-
}
|
|
38
|
-
modes.push("login");
|
|
39
|
-
}
|
|
40
|
-
if (options.revalidate !== void 0 && typeof options.revalidate !== "function") {
|
|
41
|
-
throw new Error("CatalogDashboardModule: dashboardAuth.revalidate must be a function.");
|
|
42
|
-
}
|
|
43
|
-
if (options.unauthenticatedPage !== void 0 && typeof options.unauthenticatedPage !== "function") {
|
|
44
|
-
throw new Error("CatalogDashboardModule: dashboardAuth.unauthenticatedPage must be a function.");
|
|
45
|
-
}
|
|
38
|
+
if (options.session !== void 0) modes.push("session");
|
|
39
|
+
if (options.login !== void 0) modes.push("login");
|
|
46
40
|
if (modes.length === 0) {
|
|
47
41
|
throw new Error("CatalogDashboardModule: dashboardAuth needs at least one of `session` or `login` (otherwise the cookie can never be minted). Failing closed.");
|
|
48
42
|
}
|