@dudousxd/nestjs-catalog-dashboard 0.1.0

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.
@@ -0,0 +1,271 @@
1
+ import { DynamicModule, CanActivate, ExecutionContext, StreamableFile } from '@nestjs/common';
2
+
3
+ /** The session user the host `login` hook returns to mint a cookie. */
4
+ interface DashboardSessionUser {
5
+ id: string;
6
+ name?: string;
7
+ roles?: string[];
8
+ }
9
+
10
+ /** Host hook for Mode A — validates the host's own auth on the raw request. */
11
+ type SessionHook = (request: unknown) => Promise<DashboardSessionUser | null> | DashboardSessionUser | null;
12
+ /** Host hook for Mode B — validates submitted credentials from the built-in login page. */
13
+ type LoginHook = (username: string, password: string) => Promise<DashboardSessionUser | null> | DashboardSessionUser | null;
14
+ /**
15
+ * Re-checks a LIVE session when the cookie is slid forward. Runs at most once per `ttl/2` per
16
+ * session, so a DB round-trip here is cheap — this holds even under concurrent traffic: N parallel
17
+ * requests carrying the same past-half-life cookie share ONE call (see `revalidateOnce` in
18
+ * `session-cookie-io.ts`), not N. Return `false` to revoke (the cookie is cleared and the request
19
+ * denied). Distinct from `session`: that hook reads the host's auth off a fresh request, which a
20
+ * console XHR does not carry — this one receives the already-minted session.
21
+ */
22
+ type RevalidateHook = (session: DashboardSessionUser) => Promise<boolean> | boolean;
23
+ /** What `unauthenticatedPage` receives. An object (not positional args) so fields can be added later. */
24
+ interface UnauthenticatedPageContext {
25
+ /**
26
+ * The platform-native request — Express' `Request`, Fastify's `FastifyRequest`. Typed `unknown`
27
+ * for the same reason `SessionHook`'s is: this package refuses to depend on either platform.
28
+ * Cast it to whatever your app actually runs on.
29
+ */
30
+ request: unknown;
31
+ /**
32
+ * The platform-native response. The hook OWNS it: it must write AND end it (`res.render(...)`,
33
+ * `res.status(401).send(...)`, an Inertia render, ...). If the hook returns without writing, the
34
+ * library falls back to its own built-in page rather than leaving the request hanging.
35
+ */
36
+ response: unknown;
37
+ /** Where this console is mounted (e.g. `/catalog`) — useful for a "back to the console" link. */
38
+ basePath: string;
39
+ }
40
+ /**
41
+ * Host-owned page for an unauthenticated full-page navigation to the console.
42
+ *
43
+ * The built-in page cannot know who hosts the console, so it can only say "open this console from
44
+ * your application" in the abstract — it can't name the launcher, link to it, or look like the rest
45
+ * of the host's product. This hook hands the whole response to the host instead: render through
46
+ * your own template engine, your own Inertia page, whatever. The page is served AT the console's
47
+ * own URL, so `/catalog` stays `/catalog`.
48
+ *
49
+ * Deliberately NOT a replacement for Mode B's built-in login form. A host that wants its own login
50
+ * UI uses Mode A plus this hook, and posts to `<basePath>/session` from its own page — the mint
51
+ * endpoint is the supported primitive for that.
52
+ *
53
+ * Fail-closed by construction: it only ever runs on a request that has ALREADY been denied. A hook
54
+ * that throws, or that returns without writing, falls back to the built-in page — it cannot let
55
+ * anyone in.
56
+ */
57
+ type UnauthenticatedPageHook = (context: UnauthenticatedPageContext) => void | Promise<void>;
58
+ type AuthMode = 'session' | 'login';
59
+ /**
60
+ * Author-facing `dashboardAuth` option on `CatalogDashboardModule.forRoot`/`forRootAsync`. Gates
61
+ * BOTH the SPA (a full-page navigation redirected to a server-rendered login page) and the JSON
62
+ * API (a plain `401`) behind a signed session cookie, mirroring `@dudousxd/nestjs-telescope`'s
63
+ * `dashboardAuth` mechanism (same HMAC-SHA256 cookie, same fail-closed validation). Two ways to
64
+ * mint that cookie: Mode A (`session`) — the host frontend, already carrying its own auth, POSTs
65
+ * to `<basePath>/session` and the host hook decides; or Mode B (`login`) — the built-in,
66
+ * dependency-free server-rendered login page (`GET <basePath>/login`). At least one of the two is
67
+ * required so an un-mintable gate is a boot error, not a silently-open (or silently-stuck) console.
68
+ */
69
+ interface DashboardAuthOptions {
70
+ /** REQUIRED HMAC-SHA256 signing key. Missing/empty => boot error (fail closed). */
71
+ secret: string;
72
+ /** Cookie TTL as a duration string (`'8h'`, `'30m'`, `'7d'`). Default `'8h'`. */
73
+ ttl?: string;
74
+ /** Mode A: validates the host's own auth on the raw request POSTed to `<basePath>/session`;
75
+ * return the session user, or `null` to deny. Thrown errors are treated as a denial (logged
76
+ * once, never surfaced to the client). */
77
+ session?: SessionHook;
78
+ /** Mode B: validates submitted username/password from the built-in login page; return the
79
+ * session user, or `null` to deny. Thrown errors are treated as a denial (logged once, never
80
+ * surfaced to the client). */
81
+ login?: LoginHook;
82
+ /** Re-checks a live session on sliding renewal; see `RevalidateHook`. Not a mode — it cannot
83
+ * mint a session, only revoke one already minted by `session`/`login`. */
84
+ revalidate?: RevalidateHook;
85
+ /** Renders the host's own page for an unauthenticated navigation, in place of the built-in
86
+ * "open this console from your application" card; see `UnauthenticatedPageHook`. */
87
+ unauthenticatedPage?: UnauthenticatedPageHook;
88
+ }
89
+ /** Resolved, validated `dashboardAuth` config shared by the guards, auth controller, and login page. */
90
+ interface ResolvedDashboardAuth {
91
+ secret: string;
92
+ ttlMs: number;
93
+ modes: AuthMode[];
94
+ session?: SessionHook;
95
+ login?: LoginHook;
96
+ revalidate?: RevalidateHook;
97
+ unauthenticatedPage?: UnauthenticatedPageHook;
98
+ }
99
+ /** DI token carrying the resolved `dashboardAuth` config (`ResolvedDashboardAuth | null`). */
100
+ declare const DASHBOARD_AUTH: unique symbol;
101
+
102
+ interface LoginBody {
103
+ username?: unknown;
104
+ password?: unknown;
105
+ returnTo?: unknown;
106
+ }
107
+ /**
108
+ * Mints/clears the `dashboardAuth` session cookie and serves the built-in login page. Mounted
109
+ * under `basePath` alongside `CatalogUiController` (see `CatalogDashboardModule.forRoot`), but on
110
+ * a SEPARATE controller so it is never itself behind `CatalogUiSessionGuard` — these endpoints
111
+ * CREATE the session that guard checks for. `@Optional()` on both injections: this controller is
112
+ * only registered when `dashboardAuth` might be configured (a static `forRoot({ dashboardAuth })`
113
+ * or any `forRootAsync`), but the resolved value can still be `null` at runtime for the async case
114
+ * — every handler below re-checks it and 404s rather than assuming it is set.
115
+ */
116
+ declare class CatalogAuthController {
117
+ private readonly auth;
118
+ private readonly basePath;
119
+ private readonly logger;
120
+ /** Warn once per hook kind so a throwing hook doesn't spam logs on every failed attempt. */
121
+ private readonly warnedHooks;
122
+ constructor(auth: ResolvedDashboardAuth | null, basePath: string);
123
+ loginPage(): string;
124
+ login(body: LoginBody, request: unknown, response: unknown): Promise<{
125
+ redirectTo: string;
126
+ }>;
127
+ session(request: unknown, response: unknown): Promise<void>;
128
+ logout(request: unknown, response: unknown): void;
129
+ private requireAuth;
130
+ /**
131
+ * Run a host hook (`login` or `session`) defensively: a throw is treated as a denial (uniform
132
+ * failure) and warn-logged once PER KIND, so a buggy hook never 500s the endpoint into a
133
+ * stack-trace leak nor floods the logs on repeated bad attempts.
134
+ */
135
+ private runHook;
136
+ }
137
+
138
+ interface CatalogDashboardOptions {
139
+ /**
140
+ * Where the console is served. Default `/catalog`.
141
+ *
142
+ * Not under the host's API prefix: this serves HTML and assets, and a host
143
+ * that sets a global `/api` prefix has to exclude these paths from it — see
144
+ * {@link catalogDashboardMountPaths}.
145
+ */
146
+ path?: string;
147
+ /**
148
+ * Where the catalog's JSON API lives, baked into the SPA so it knows what to
149
+ * call. Default `/api/catalog-service`.
150
+ *
151
+ * A separate option because the console does NOT proxy the API — unlike some
152
+ * Aviary dashboards, the catalog's HTTP surface is already mounted by
153
+ * `CatalogModule` and `CatalogPipelineModule`, and a second copy behind this
154
+ * console would be a second set of routes to keep authorised.
155
+ */
156
+ apiPath?: string;
157
+ /**
158
+ * How a visitor is authenticated.
159
+ *
160
+ * **Omit it and the console is open.** That is a real decision, not a
161
+ * default to drift into: this console can rewrite a catalog's model and run
162
+ * its connectors. A host with any notion of users should pass this, and a
163
+ * host that means to leave it open should say so where someone will read it.
164
+ */
165
+ auth?: DashboardAuthOptions;
166
+ }
167
+ /**
168
+ * The catalog console, as a mountable module.
169
+ *
170
+ * Serves the SPA and the session endpoints; nothing else. The screens come from
171
+ * `@dudousxd/nestjs-catalog-react` and the data from the catalog's own API, so
172
+ * this package is the mount, the auth and the asset serving — the three things a
173
+ * component library cannot do for itself.
174
+ */
175
+ declare class CatalogDashboardModule {
176
+ static forRoot(options?: CatalogDashboardOptions): DynamicModule;
177
+ }
178
+ /**
179
+ * The paths a host must exclude from its global API prefix.
180
+ *
181
+ * Without this, a host calling `setGlobalPrefix('api')` moves the console to
182
+ * `/api/catalog` while the SPA still asks for `/catalog/assets/...`, and the
183
+ * console loads as a blank page with 404s in the network tab — which reads as a
184
+ * broken build rather than a routing mistake.
185
+ *
186
+ * Derived from the same defaulting `forRoot` uses, so the two cannot drift.
187
+ */
188
+ declare function catalogDashboardMountPaths(options?: Pick<CatalogDashboardOptions, 'path'>): Array<{
189
+ path: string;
190
+ method: number;
191
+ }>;
192
+
193
+ /**
194
+ * Gates `CatalogUiController` (the SPA shell + assets, a full-page browser navigation) on a valid
195
+ * `dashboardAuth` session cookie. A no-op (always `true`) when `dashboardAuth` was not configured
196
+ * — see `CatalogDashboardModule.forRoot`'s `dashboardAuth` doc. Missing/invalid/expired session,
197
+ * when Mode B (`login`) is configured, gets a `302` to the built-in login page carrying
198
+ * `?returnTo=<original url>`, via `DashboardLoginRedirectException` (see that file for why a guard
199
+ * can't just call `response.redirect()` and return `false`). When only Mode A (`session`) is
200
+ * configured there is no login page to redirect to — the host mints the session itself — so it
201
+ * instead throws `DashboardSessionRequiredException`, rendering a small instruction page.
202
+ *
203
+ * Auth is mount-level and role-agnostic: this guard has no notion of control-plane vs tenant
204
+ * (see the catalog dashboard's topology note in `dashboard.service.ts`) — it only ever answers
205
+ * "is there a valid dashboard session", nothing role-specific changes here.
206
+ */
207
+ declare class CatalogUiSessionGuard implements CanActivate {
208
+ private readonly auth;
209
+ private readonly basePath;
210
+ constructor(auth: ResolvedDashboardAuth | null, basePath: string);
211
+ canActivate(context: ExecutionContext): Promise<boolean>;
212
+ /**
213
+ * A revoked session (the host's `revalidate` hook says no) is denied exactly like an absent
214
+ * one — by design, there is nothing left to distinguish "never had a session" from "had one,
215
+ * then lost it" once the cookie is cleared, so both get the same Mode-aware treatment.
216
+ *
217
+ * Takes `auth` explicitly rather than reading `this.auth`: `canActivate`'s `!this.auth` early
218
+ * return narrows the field within that method only — TS doesn't carry it across a method call
219
+ * — so callers pass the already-narrowed value instead of this method re-deriving (or
220
+ * asserting away) the nullability.
221
+ */
222
+ private denyUnauthenticated;
223
+ }
224
+ /**
225
+ * Gates `CatalogApiController` (the JSON API the SPA fetches) on a valid `dashboardAuth` session
226
+ * cookie. A no-op (always `true`) when `dashboardAuth` was not configured. Missing/invalid/expired
227
+ * session => a plain `401` (the API is called via `fetch`, never a browser navigation, so a
228
+ * redirect would just fail the request anyway — the caller reads the status code, not HTML).
229
+ *
230
+ * Mount-level and role-agnostic, same as `CatalogUiSessionGuard` above.
231
+ */
232
+ declare class CatalogApiSessionGuard implements CanActivate {
233
+ private readonly auth;
234
+ constructor(auth: ResolvedDashboardAuth | null);
235
+ canActivate(context: ExecutionContext): Promise<boolean>;
236
+ /**
237
+ * A bare 401 body carrying `{ auth: { modes } }` — mirrors `@dudousxd/nestjs-telescope`'s
238
+ * dashboardAuth 401. The API is fetched (never navigated), so this is the ONLY way the console
239
+ * SPA (`catalog-client.ts`) learns which auth surface to send the operator to on a mid-session
240
+ * 401; `CatalogUiSessionGuard`'s redirect/session-required exceptions above don't reach it.
241
+ */
242
+ private unauthorized;
243
+ }
244
+
245
+ /** DI token carrying the UI mount base (e.g. `/catalog`). */
246
+ declare const DASHBOARD_BASE_PATH: unique symbol;
247
+ /** DI token carrying the JSON API base the SPA fetches from (e.g. `/api/catalog`). */
248
+ declare const DASHBOARD_API_PATH: unique symbol;
249
+ /**
250
+ * Serves the bundled control-plane SPA at the configured base (+ hashed assets at `<base>/assets`).
251
+ * The path comes from `RouterModule` (set by `CatalogDashboardModule.forRoot({ basePath })`), so the
252
+ * controller routes are relative.
253
+ *
254
+ * `@UseFilters(DashboardLoginRedirectFilter, DashboardSessionRequiredFilter)` is permanent (present
255
+ * regardless of whether `dashboardAuth` is configured): each only ever activates for its own
256
+ * exception type, which `CatalogUiSessionGuard` only throws when it is ALSO stamped on this
257
+ * controller (see `CatalogDashboardModule.forRoot`) — so leaving them decorated here is inert, not
258
+ * a behavior change, when `dashboardAuth` is absent. The guard picks between the two exceptions
259
+ * based on which mode is configured (Mode B => redirect to the login page; Mode A only => render
260
+ * the session-required instruction page in place, since there is no login page to redirect to).
261
+ */
262
+ declare class CatalogUiController {
263
+ private readonly basePath;
264
+ private readonly apiBasePath;
265
+ private readonly dir;
266
+ constructor(basePath: string, apiBasePath: string);
267
+ index(): string;
268
+ asset(file: string): StreamableFile;
269
+ }
270
+
271
+ export { CatalogApiSessionGuard, CatalogAuthController, CatalogDashboardModule, type CatalogDashboardOptions, CatalogUiController, CatalogUiSessionGuard, DASHBOARD_API_PATH, DASHBOARD_AUTH, DASHBOARD_BASE_PATH, type DashboardAuthOptions, type DashboardSessionUser, type UnauthenticatedPageContext, type UnauthenticatedPageHook, catalogDashboardMountPaths };