@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,1074 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/server/auth/dashboard-auth-config.ts
5
+ var DASHBOARD_AUTH = Symbol("DASHBOARD_AUTH");
6
+ var DEFAULT_TTL_MS = 8 * 60 * 60 * 1e3;
7
+ var DURATION_UNITS = {
8
+ s: 1e3,
9
+ m: 60 * 1e3,
10
+ h: 60 * 60 * 1e3,
11
+ d: 24 * 60 * 60 * 1e3
12
+ };
13
+
14
+ // src/server/catalog-auth.controller.ts
15
+ import { BadRequestException, Body, Controller as Controller2, Get as Get2, Header as Header2, HttpCode, Inject as Inject3, Logger as Logger2, NotFoundException as NotFoundException2, Optional as Optional2, Post, Req, Res, UnauthorizedException } from "@nestjs/common";
16
+
17
+ // src/server/auth/login-page.ts
18
+ function page(content, title = "Catalog") {
19
+ return `<!doctype html>
20
+ <html lang="en">
21
+ <head>
22
+ <meta charset="utf-8" />
23
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
24
+ <meta name="robots" content="noindex, nofollow" />
25
+ <title>${title}</title>
26
+ <style>
27
+ :root { color-scheme: dark; }
28
+ * { box-sizing: border-box; }
29
+ body {
30
+ margin: 0;
31
+ min-height: 100vh;
32
+ display: flex;
33
+ align-items: center;
34
+ justify-content: center;
35
+ background: #09090b;
36
+ color: #e4e4e7;
37
+ font: 14px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
38
+ padding: 16px;
39
+ }
40
+ .card {
41
+ width: 100%;
42
+ max-width: 384px;
43
+ border: 1px solid #27272a;
44
+ background: #18181b;
45
+ border-radius: 8px;
46
+ padding: 32px;
47
+ box-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.5);
48
+ }
49
+ .brand {
50
+ margin: 0 0 24px;
51
+ text-align: center;
52
+ font-size: 18px;
53
+ font-weight: 600;
54
+ color: #34d399;
55
+ }
56
+ h1 {
57
+ margin: 0 0 12px;
58
+ font-size: 16px;
59
+ font-weight: 600;
60
+ color: #f4f4f5;
61
+ }
62
+ p { margin: 0 0 16px; color: #a1a1aa; }
63
+ form { display: flex; flex-direction: column; gap: 16px; }
64
+ label { display: flex; flex-direction: column; gap: 6px; }
65
+ .field-label {
66
+ font-size: 11px;
67
+ text-transform: uppercase;
68
+ letter-spacing: 0.05em;
69
+ color: #71717a;
70
+ }
71
+ input {
72
+ border-radius: 4px;
73
+ border: 1px solid #3f3f46;
74
+ background: #09090b;
75
+ color: #f4f4f5;
76
+ padding: 8px 12px;
77
+ font: inherit;
78
+ outline: none;
79
+ }
80
+ input:focus { border-color: rgb(52 211 153 / 0.6); }
81
+ #error {
82
+ display: none;
83
+ margin: 0;
84
+ font-size: 12px;
85
+ color: #fb7185;
86
+ }
87
+ button, .button {
88
+ margin-top: 8px;
89
+ border-radius: 4px;
90
+ border: 1px solid rgb(52 211 153 / 0.4);
91
+ background: rgb(52 211 153 / 0.1);
92
+ color: #6ee7b7;
93
+ padding: 8px 12px;
94
+ font: inherit;
95
+ font-size: 12px;
96
+ font-weight: 500;
97
+ text-transform: uppercase;
98
+ letter-spacing: 0.05em;
99
+ cursor: pointer;
100
+ display: inline-block;
101
+ text-align: center;
102
+ text-decoration: none;
103
+ box-sizing: border-box;
104
+ }
105
+ button:hover:not(:disabled), .button:hover { background: rgb(52 211 153 / 0.2); }
106
+ button:disabled { opacity: 0.6; cursor: default; }
107
+ </style>
108
+ </head>
109
+ <body>
110
+ <div class="card">
111
+ ${content}
112
+ </div>
113
+ </body>
114
+ </html>`;
115
+ }
116
+ __name(page, "page");
117
+ function renderLoginPage(basePath) {
118
+ const loginAction = `${basePath}/login`;
119
+ const defaultReturnTo = basePath;
120
+ return page(`<p class="brand">Catalog</p>
121
+ <form id="login-form" autocomplete="on">
122
+ <label>
123
+ <span class="field-label">Username</span>
124
+ <input id="username" name="username" type="text" autocomplete="username" required autofocus />
125
+ </label>
126
+ <label>
127
+ <span class="field-label">Password</span>
128
+ <input id="password" name="password" type="password" autocomplete="current-password" />
129
+ </label>
130
+ <p id="error" role="alert">Invalid username or password.</p>
131
+ <button id="submit" type="submit">Sign in</button>
132
+ </form>
133
+ <script>
134
+ (function () {
135
+ var LOGIN_ACTION = ${JSON.stringify(loginAction)};
136
+ var DEFAULT_RETURN_TO = ${JSON.stringify(defaultReturnTo)};
137
+ var params = new URLSearchParams(window.location.search);
138
+ var errorBox = document.getElementById('error');
139
+ if (params.get('error')) errorBox.style.display = 'block';
140
+
141
+ function sameOriginReturnTo(value) {
142
+ if (typeof value !== 'string' || value === '') return DEFAULT_RETURN_TO;
143
+ if (value.charAt(0) !== '/' || value.charAt(1) === '/' || value.indexOf('://') !== -1) {
144
+ return DEFAULT_RETURN_TO;
145
+ }
146
+ return value;
147
+ }
148
+
149
+ var form = document.getElementById('login-form');
150
+ var submitButton = document.getElementById('submit');
151
+ form.addEventListener('submit', function (event) {
152
+ event.preventDefault();
153
+ submitButton.disabled = true;
154
+ errorBox.style.display = 'none';
155
+ var returnTo = sameOriginReturnTo(params.get('returnTo'));
156
+ fetch(LOGIN_ACTION, {
157
+ method: 'POST',
158
+ headers: { 'content-type': 'application/json' },
159
+ credentials: 'same-origin',
160
+ body: JSON.stringify({
161
+ username: document.getElementById('username').value,
162
+ password: document.getElementById('password').value,
163
+ returnTo: returnTo,
164
+ }),
165
+ })
166
+ .then(function (response) {
167
+ if (!response.ok) throw new Error('unauthorized');
168
+ return response.json();
169
+ })
170
+ .then(function (data) {
171
+ window.location.href = data.redirectTo || DEFAULT_RETURN_TO;
172
+ })
173
+ .catch(function () {
174
+ errorBox.style.display = 'block';
175
+ submitButton.disabled = false;
176
+ });
177
+ });
178
+ })();
179
+ </script>`, "Sign in \u2014 Catalog");
180
+ }
181
+ __name(renderLoginPage, "renderLoginPage");
182
+ function renderSessionRequiredPage(basePath) {
183
+ return page(`<h1>Open this console from your application</h1>
184
+ <p>Your session is minted by the host app. Use its console launcher to sign in, then reload.</p>
185
+ <a class="button" href="${basePath}">Retry</a>`);
186
+ }
187
+ __name(renderSessionRequiredPage, "renderSessionRequiredPage");
188
+
189
+ // src/server/auth/request.ts
190
+ function isRecord(value) {
191
+ return typeof value === "object" && value !== null;
192
+ }
193
+ __name(isRecord, "isRecord");
194
+ function readHeaders(request) {
195
+ if (!isRecord(request)) return {};
196
+ const headers = request.headers;
197
+ return isRecord(headers) ? headers : {};
198
+ }
199
+ __name(readHeaders, "readHeaders");
200
+ function headerToString(value) {
201
+ if (typeof value === "string") return value;
202
+ if (Array.isArray(value) && value.every((part) => typeof part === "string")) {
203
+ return value.join(",");
204
+ }
205
+ return void 0;
206
+ }
207
+ __name(headerToString, "headerToString");
208
+ function readCookieHeader(request) {
209
+ return headerToString(readHeaders(request).cookie);
210
+ }
211
+ __name(readCookieHeader, "readCookieHeader");
212
+ function isHttpsRequest(request) {
213
+ if (isRecord(request) && request.protocol === "https") return true;
214
+ const forwarded = headerToString(readHeaders(request)["x-forwarded-proto"]);
215
+ if (forwarded === void 0) return false;
216
+ return forwarded.split(",").map((proto) => proto.trim().toLowerCase()).includes("https");
217
+ }
218
+ __name(isHttpsRequest, "isHttpsRequest");
219
+ function originalRequestUrl(request) {
220
+ if (!isRecord(request)) return "/";
221
+ if (typeof request.originalUrl === "string" && request.originalUrl !== "") {
222
+ return request.originalUrl;
223
+ }
224
+ if (typeof request.url === "string" && request.url !== "") return request.url;
225
+ return "/";
226
+ }
227
+ __name(originalRequestUrl, "originalRequestUrl");
228
+ function sanitizeReturnTo(candidate, fallback) {
229
+ if (typeof candidate !== "string") return fallback;
230
+ if (!candidate.startsWith("/")) return fallback;
231
+ if (candidate.startsWith("//")) return fallback;
232
+ if (candidate.includes("://")) return fallback;
233
+ return candidate;
234
+ }
235
+ __name(sanitizeReturnTo, "sanitizeReturnTo");
236
+
237
+ // src/server/auth/response.ts
238
+ function isRecord2(value) {
239
+ return typeof value === "object" && value !== null;
240
+ }
241
+ __name(isRecord2, "isRecord");
242
+ function isRawCookieResponse(value) {
243
+ return isRecord2(value) && typeof value.getHeader === "function" && typeof value.setHeader === "function";
244
+ }
245
+ __name(isRawCookieResponse, "isRawCookieResponse");
246
+ function resolveCookieResponse(response) {
247
+ if (isRawCookieResponse(response)) return response;
248
+ if (isRecord2(response) && isRawCookieResponse(response.raw)) return response.raw;
249
+ return null;
250
+ }
251
+ __name(resolveCookieResponse, "resolveCookieResponse");
252
+ function existingSetCookies(response) {
253
+ const current = response.getHeader("set-cookie");
254
+ if (Array.isArray(current)) return current;
255
+ if (typeof current === "string") return [
256
+ current
257
+ ];
258
+ return [];
259
+ }
260
+ __name(existingSetCookies, "existingSetCookies");
261
+ function appendSetCookie(response, cookie) {
262
+ const raw = resolveCookieResponse(response);
263
+ if (!raw) return;
264
+ raw.setHeader("set-cookie", [
265
+ ...existingSetCookies(raw),
266
+ cookie
267
+ ]);
268
+ }
269
+ __name(appendSetCookie, "appendSetCookie");
270
+ function isRawRedirectResponse(value) {
271
+ return isRecord2(value) && typeof value.getHeader === "function" && typeof value.setHeader === "function" && typeof value.end === "function";
272
+ }
273
+ __name(isRawRedirectResponse, "isRawRedirectResponse");
274
+ function resolveRedirectResponse(response) {
275
+ if (isRawRedirectResponse(response)) return response;
276
+ if (isRecord2(response) && isRawRedirectResponse(response.raw)) return response.raw;
277
+ return null;
278
+ }
279
+ __name(resolveRedirectResponse, "resolveRedirectResponse");
280
+ function redirectRaw(response, location, status = 302) {
281
+ const raw = resolveRedirectResponse(response);
282
+ if (!raw) return;
283
+ raw.statusCode = status;
284
+ raw.setHeader("location", location);
285
+ raw.end();
286
+ }
287
+ __name(redirectRaw, "redirectRaw");
288
+ function responseAlreadyWritten(response) {
289
+ const raw = resolveRedirectResponse(response);
290
+ return raw?.headersSent === true;
291
+ }
292
+ __name(responseAlreadyWritten, "responseAlreadyWritten");
293
+ function writeHtmlRaw(response, html, status = 200) {
294
+ const raw = resolveRedirectResponse(response);
295
+ if (!raw) return;
296
+ raw.statusCode = status;
297
+ raw.setHeader("content-type", "text/html; charset=utf-8");
298
+ raw.setHeader("cache-control", "no-store, must-revalidate");
299
+ raw.end(html);
300
+ }
301
+ __name(writeHtmlRaw, "writeHtmlRaw");
302
+
303
+ // src/server/auth/cookie-header.ts
304
+ function parseCookieHeader(header) {
305
+ const cookies = {};
306
+ if (typeof header !== "string" || header === "") return cookies;
307
+ for (const segment of header.split(";")) {
308
+ const eq = segment.indexOf("=");
309
+ if (eq <= 0) continue;
310
+ const name = segment.slice(0, eq).trim();
311
+ if (name === "") continue;
312
+ let rawValue = segment.slice(eq + 1).trim();
313
+ if (rawValue.length >= 2 && rawValue.startsWith('"') && rawValue.endsWith('"')) {
314
+ rawValue = rawValue.slice(1, -1);
315
+ }
316
+ if (name in cookies) continue;
317
+ try {
318
+ cookies[name] = decodeURIComponent(rawValue);
319
+ } catch {
320
+ cookies[name] = rawValue;
321
+ }
322
+ }
323
+ return cookies;
324
+ }
325
+ __name(parseCookieHeader, "parseCookieHeader");
326
+ function serializeSetCookie(name, value, options) {
327
+ const parts = [
328
+ `${name}=${options.clear ? "" : encodeURIComponent(value)}`
329
+ ];
330
+ parts.push(`Path=${options.path}`);
331
+ parts.push("HttpOnly");
332
+ parts.push("SameSite=Lax");
333
+ if (options.secure) parts.push("Secure");
334
+ if (options.clear) {
335
+ parts.push("Max-Age=0");
336
+ parts.push("Expires=Thu, 01 Jan 1970 00:00:00 GMT");
337
+ } else {
338
+ parts.push(`Max-Age=${options.maxAgeSeconds}`);
339
+ }
340
+ return parts.join("; ");
341
+ }
342
+ __name(serializeSetCookie, "serializeSetCookie");
343
+
344
+ // src/server/auth/session-cookie.ts
345
+ import { createHmac, timingSafeEqual } from "node:crypto";
346
+ var EXP_GRACE_MS = 3e4;
347
+ function base64urlEncode(value) {
348
+ return Buffer.from(value, "utf8").toString("base64url");
349
+ }
350
+ __name(base64urlEncode, "base64urlEncode");
351
+ function base64urlDecode(value) {
352
+ return Buffer.from(value, "base64url").toString("utf8");
353
+ }
354
+ __name(base64urlDecode, "base64urlDecode");
355
+ function hmac(secret, payload) {
356
+ return createHmac("sha256", secret).update(payload).digest("base64url");
357
+ }
358
+ __name(hmac, "hmac");
359
+ function signSessionCookie(user, options) {
360
+ const issuedAt = options.now ?? Date.now();
361
+ const session = {
362
+ sub: user.id,
363
+ ...user.name !== void 0 ? {
364
+ name: user.name
365
+ } : {},
366
+ roles: user.roles ?? [],
367
+ iat: issuedAt,
368
+ exp: issuedAt + options.ttlMs
369
+ };
370
+ const encodedPayload = base64urlEncode(JSON.stringify(session));
371
+ const signature = hmac(options.secret, encodedPayload);
372
+ return `${encodedPayload}.${signature}`;
373
+ }
374
+ __name(signSessionCookie, "signSessionCookie");
375
+ function isSessionPayload(value) {
376
+ if (typeof value !== "object" || value === null) return false;
377
+ const record = {
378
+ ...value
379
+ };
380
+ if (typeof record.sub !== "string") return false;
381
+ if (record.name !== void 0 && typeof record.name !== "string") return false;
382
+ if (!Array.isArray(record.roles)) return false;
383
+ if (!record.roles.every((role) => typeof role === "string")) return false;
384
+ if (typeof record.iat !== "number" || !Number.isFinite(record.iat)) return false;
385
+ if (typeof record.exp !== "number" || !Number.isFinite(record.exp)) return false;
386
+ return true;
387
+ }
388
+ __name(isSessionPayload, "isSessionPayload");
389
+ function verifySessionCookie(value, options) {
390
+ try {
391
+ const dot = value.indexOf(".");
392
+ if (dot <= 0 || dot === value.length - 1) return null;
393
+ const encodedPayload = value.slice(0, dot);
394
+ const providedSignature = value.slice(dot + 1);
395
+ const expectedSignature = hmac(options.secret, encodedPayload);
396
+ const provided = Buffer.from(providedSignature, "base64url");
397
+ const expected = Buffer.from(expectedSignature, "base64url");
398
+ if (provided.length !== expected.length) return null;
399
+ if (!timingSafeEqual(provided, expected)) return null;
400
+ const decoded = JSON.parse(base64urlDecode(encodedPayload));
401
+ if (!isSessionPayload(decoded)) return null;
402
+ const now = options.now ?? Date.now();
403
+ if (now > decoded.exp + EXP_GRACE_MS) return null;
404
+ const session = {
405
+ sub: decoded.sub,
406
+ ...decoded.name !== void 0 ? {
407
+ name: decoded.name
408
+ } : {},
409
+ roles: decoded.roles,
410
+ iat: decoded.iat,
411
+ exp: decoded.exp
412
+ };
413
+ return session;
414
+ } catch {
415
+ return null;
416
+ }
417
+ }
418
+ __name(verifySessionCookie, "verifySessionCookie");
419
+
420
+ // src/server/auth/session-cookie-io.ts
421
+ var SESSION_COOKIE_NAME = "catalog_dashboard_session";
422
+ var COOKIE_PATH = "/";
423
+ function issueSessionCookie(user, context) {
424
+ const value = signSessionCookie(user, {
425
+ secret: context.auth.secret,
426
+ ttlMs: context.auth.ttlMs,
427
+ ...context.now !== void 0 ? {
428
+ now: context.now
429
+ } : {}
430
+ });
431
+ const cookie = serializeSetCookie(SESSION_COOKIE_NAME, value, {
432
+ path: COOKIE_PATH,
433
+ maxAgeSeconds: Math.floor(context.auth.ttlMs / 1e3),
434
+ secure: isHttpsRequest(context.request)
435
+ });
436
+ appendSetCookie(context.response, cookie);
437
+ }
438
+ __name(issueSessionCookie, "issueSessionCookie");
439
+ function clearSessionCookie(context) {
440
+ const cookie = serializeSetCookie(SESSION_COOKIE_NAME, "", {
441
+ path: COOKIE_PATH,
442
+ maxAgeSeconds: 0,
443
+ secure: isHttpsRequest(context.request),
444
+ clear: true
445
+ });
446
+ appendSetCookie(context.response, cookie);
447
+ }
448
+ __name(clearSessionCookie, "clearSessionCookie");
449
+ function readSessionFromRequest(auth, request) {
450
+ const cookieValue = parseCookieHeader(readCookieHeader(request))[SESSION_COOKIE_NAME];
451
+ if (cookieValue === void 0) return null;
452
+ return verifySessionCookie(cookieValue, {
453
+ secret: auth.secret
454
+ });
455
+ }
456
+ __name(readSessionFromRequest, "readSessionFromRequest");
457
+ var inFlightRevalidations = /* @__PURE__ */ new Map();
458
+ function revalidateOnce(auth, user) {
459
+ const revalidate = auth.revalidate;
460
+ if (!revalidate) return Promise.resolve(true);
461
+ const key = `${auth.secret}:${user.id}`;
462
+ const inFlight = inFlightRevalidations.get(key);
463
+ if (inFlight) return inFlight;
464
+ const call = Promise.resolve().then(() => revalidate(user)).catch(() => false).finally(() => {
465
+ inFlightRevalidations.delete(key);
466
+ });
467
+ inFlightRevalidations.set(key, call);
468
+ return call;
469
+ }
470
+ __name(revalidateOnce, "revalidateOnce");
471
+ async function maybeRenewSession(auth, session, request, response, now = Date.now()) {
472
+ if (now - session.iat <= auth.ttlMs / 2) return true;
473
+ const user = {
474
+ id: session.sub,
475
+ ...session.name !== void 0 ? {
476
+ name: session.name
477
+ } : {},
478
+ roles: session.roles
479
+ };
480
+ const allowed = await revalidateOnce(auth, user);
481
+ if (!allowed) {
482
+ clearSessionCookie({
483
+ request,
484
+ response
485
+ });
486
+ return false;
487
+ }
488
+ issueSessionCookie(user, {
489
+ auth,
490
+ request,
491
+ response,
492
+ now
493
+ });
494
+ return true;
495
+ }
496
+ __name(maybeRenewSession, "maybeRenewSession");
497
+
498
+ // src/server/catalog-ui.controller.ts
499
+ import { existsSync, readFileSync } from "node:fs";
500
+ import { basename, extname, join, resolve, sep } from "node:path";
501
+ import { fileURLToPath } from "node:url";
502
+ import { Controller, Get, Header, Inject as Inject2, NotFoundException, Param, StreamableFile, UseFilters } from "@nestjs/common";
503
+
504
+ // src/server/auth/login-redirect.exception.ts
505
+ import { Catch, HttpException, HttpStatus } from "@nestjs/common";
506
+ function _ts_decorate(decorators, target, key, desc) {
507
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
508
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
509
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
510
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
511
+ }
512
+ __name(_ts_decorate, "_ts_decorate");
513
+ var DashboardLoginRedirectException = class extends HttpException {
514
+ static {
515
+ __name(this, "DashboardLoginRedirectException");
516
+ }
517
+ location;
518
+ constructor(location) {
519
+ super({
520
+ location
521
+ }, HttpStatus.FOUND), this.location = location;
522
+ }
523
+ };
524
+ var DashboardLoginRedirectFilter = class {
525
+ static {
526
+ __name(this, "DashboardLoginRedirectFilter");
527
+ }
528
+ catch(exception, host) {
529
+ const response = host.switchToHttp().getResponse();
530
+ redirectRaw(response, exception.location);
531
+ }
532
+ };
533
+ DashboardLoginRedirectFilter = _ts_decorate([
534
+ Catch(DashboardLoginRedirectException)
535
+ ], DashboardLoginRedirectFilter);
536
+
537
+ // src/server/auth/session-required.exception.ts
538
+ import { Catch as Catch2, HttpException as HttpException2, HttpStatus as HttpStatus2, Inject, Logger, Optional } from "@nestjs/common";
539
+ function _ts_decorate2(decorators, target, key, desc) {
540
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
541
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
542
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
543
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
544
+ }
545
+ __name(_ts_decorate2, "_ts_decorate");
546
+ function _ts_metadata(k, v) {
547
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
548
+ }
549
+ __name(_ts_metadata, "_ts_metadata");
550
+ function _ts_param(paramIndex, decorator) {
551
+ return function(target, key) {
552
+ decorator(target, key, paramIndex);
553
+ };
554
+ }
555
+ __name(_ts_param, "_ts_param");
556
+ var DashboardSessionRequiredException = class extends HttpException2 {
557
+ static {
558
+ __name(this, "DashboardSessionRequiredException");
559
+ }
560
+ basePath;
561
+ constructor(basePath) {
562
+ super({
563
+ basePath
564
+ }, HttpStatus2.UNAUTHORIZED), this.basePath = basePath;
565
+ }
566
+ };
567
+ var DashboardSessionRequiredFilter = class _DashboardSessionRequiredFilter {
568
+ static {
569
+ __name(this, "DashboardSessionRequiredFilter");
570
+ }
571
+ auth;
572
+ logger = new Logger(_DashboardSessionRequiredFilter.name);
573
+ warned = false;
574
+ constructor(auth = null) {
575
+ this.auth = auth;
576
+ }
577
+ async catch(exception, host) {
578
+ const http = host.switchToHttp();
579
+ const response = http.getResponse();
580
+ const hook = this.auth?.unauthenticatedPage;
581
+ if (hook) {
582
+ try {
583
+ await hook({
584
+ request: http.getRequest(),
585
+ response,
586
+ basePath: exception.basePath
587
+ });
588
+ if (responseAlreadyWritten(response)) return;
589
+ this.warnOnce("dashboardAuth.unauthenticatedPage returned without writing a response; falling back to the built-in page. The hook must write AND end the response it is given.");
590
+ } catch (error) {
591
+ this.warnOnce(`dashboardAuth.unauthenticatedPage threw; falling back to the built-in page. ${String(error)}`);
592
+ if (responseAlreadyWritten(response)) return;
593
+ }
594
+ }
595
+ writeHtmlRaw(response, renderSessionRequiredPage(exception.basePath), HttpStatus2.UNAUTHORIZED);
596
+ }
597
+ /** Once per process, not once per request: a broken hook fires on every denied navigation. */
598
+ warnOnce(message) {
599
+ if (this.warned) return;
600
+ this.warned = true;
601
+ this.logger.warn(message);
602
+ }
603
+ };
604
+ DashboardSessionRequiredFilter = _ts_decorate2([
605
+ Catch2(DashboardSessionRequiredException),
606
+ _ts_param(0, Optional()),
607
+ _ts_param(0, Inject(DASHBOARD_AUTH)),
608
+ _ts_metadata("design:type", Function),
609
+ _ts_metadata("design:paramtypes", [
610
+ Object
611
+ ])
612
+ ], DashboardSessionRequiredFilter);
613
+
614
+ // src/server/catalog-ui.controller.ts
615
+ function _ts_decorate3(decorators, target, key, desc) {
616
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
617
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
618
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
619
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
620
+ }
621
+ __name(_ts_decorate3, "_ts_decorate");
622
+ function _ts_metadata2(k, v) {
623
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
624
+ }
625
+ __name(_ts_metadata2, "_ts_metadata");
626
+ function _ts_param2(paramIndex, decorator) {
627
+ return function(target, key) {
628
+ decorator(target, key, paramIndex);
629
+ };
630
+ }
631
+ __name(_ts_param2, "_ts_param");
632
+ var DASHBOARD_BASE_PATH = Symbol("DASHBOARD_BASE_PATH");
633
+ var DASHBOARD_API_PATH = Symbol("DASHBOARD_API_PATH");
634
+ var BUILD_BASE = "/catalog";
635
+ function spaDir() {
636
+ return fileURLToPath(new URL("../spa", import.meta.url));
637
+ }
638
+ __name(spaDir, "spaDir");
639
+ var CONTENT_TYPES = {
640
+ ".js": "text/javascript; charset=utf-8",
641
+ ".css": "text/css; charset=utf-8",
642
+ ".map": "application/json; charset=utf-8",
643
+ ".svg": "image/svg+xml",
644
+ ".json": "application/json; charset=utf-8",
645
+ ".woff2": "font/woff2",
646
+ ".ico": "image/x-icon"
647
+ };
648
+ var CatalogUiController = class {
649
+ static {
650
+ __name(this, "CatalogUiController");
651
+ }
652
+ basePath;
653
+ apiBasePath;
654
+ dir = spaDir();
655
+ constructor(basePath, apiBasePath) {
656
+ this.basePath = basePath;
657
+ this.apiBasePath = apiBasePath;
658
+ }
659
+ // index.html references hash-named bundles, so it MUST NOT be cached (stale bundle = the
660
+ // classic "stuck loading after a deploy"). The hashed assets below are immutable.
661
+ index() {
662
+ const indexPath = join(this.dir, "index.html");
663
+ if (!existsSync(indexPath)) {
664
+ throw new NotFoundException("Dashboard is not built. Run the package build.");
665
+ }
666
+ const html = readFileSync(indexPath, "utf8").replaceAll(`="${BUILD_BASE}/`, `="${this.basePath}/`);
667
+ const inject = `<script>window.__DURABLE_BASE__='${this.basePath}';window.__DURABLE_API__='${this.apiBasePath}';</script>`;
668
+ return html.includes("</head>") ? html.replace("</head>", `${inject}</head>`) : inject + html;
669
+ }
670
+ asset(file) {
671
+ const safe = basename(file);
672
+ if (safe !== file) throw new NotFoundException();
673
+ const root = resolve(this.dir, "assets");
674
+ const assetPath = resolve(root, safe);
675
+ if (!assetPath.startsWith(root + sep) || !existsSync(assetPath)) {
676
+ throw new NotFoundException();
677
+ }
678
+ const type = CONTENT_TYPES[extname(safe)] ?? "application/octet-stream";
679
+ return new StreamableFile(readFileSync(assetPath), {
680
+ type
681
+ });
682
+ }
683
+ };
684
+ _ts_decorate3([
685
+ Get(),
686
+ Header("Content-Type", "text/html; charset=utf-8"),
687
+ Header("Cache-Control", "no-store, must-revalidate"),
688
+ _ts_metadata2("design:type", Function),
689
+ _ts_metadata2("design:paramtypes", []),
690
+ _ts_metadata2("design:returntype", String)
691
+ ], CatalogUiController.prototype, "index", null);
692
+ _ts_decorate3([
693
+ Get("assets/:file"),
694
+ Header("Cache-Control", "public, max-age=31536000, immutable"),
695
+ _ts_param2(0, Param("file")),
696
+ _ts_metadata2("design:type", Function),
697
+ _ts_metadata2("design:paramtypes", [
698
+ String
699
+ ]),
700
+ _ts_metadata2("design:returntype", typeof StreamableFile === "undefined" ? Object : StreamableFile)
701
+ ], CatalogUiController.prototype, "asset", null);
702
+ CatalogUiController = _ts_decorate3([
703
+ UseFilters(DashboardLoginRedirectFilter, DashboardSessionRequiredFilter),
704
+ Controller(),
705
+ _ts_param2(0, Inject2(DASHBOARD_BASE_PATH)),
706
+ _ts_param2(1, Inject2(DASHBOARD_API_PATH)),
707
+ _ts_metadata2("design:type", Function),
708
+ _ts_metadata2("design:paramtypes", [
709
+ String,
710
+ String
711
+ ])
712
+ ], CatalogUiController);
713
+
714
+ // src/server/catalog-auth.controller.ts
715
+ function _ts_decorate4(decorators, target, key, desc) {
716
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
717
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
718
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
719
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
720
+ }
721
+ __name(_ts_decorate4, "_ts_decorate");
722
+ function _ts_metadata3(k, v) {
723
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
724
+ }
725
+ __name(_ts_metadata3, "_ts_metadata");
726
+ function _ts_param3(paramIndex, decorator) {
727
+ return function(target, key) {
728
+ decorator(target, key, paramIndex);
729
+ };
730
+ }
731
+ __name(_ts_param3, "_ts_param");
732
+ function isString(value) {
733
+ return typeof value === "string";
734
+ }
735
+ __name(isString, "isString");
736
+ var CatalogAuthController = class _CatalogAuthController {
737
+ static {
738
+ __name(this, "CatalogAuthController");
739
+ }
740
+ auth;
741
+ basePath;
742
+ logger = new Logger2(_CatalogAuthController.name);
743
+ /** Warn once per hook kind so a throwing hook doesn't spam logs on every failed attempt. */
744
+ warnedHooks = /* @__PURE__ */ new Set();
745
+ constructor(auth, basePath) {
746
+ this.auth = auth;
747
+ this.basePath = basePath;
748
+ }
749
+ // The login page reads `returnTo`/`error` from `location.search` client-side (see
750
+ // `login-page.ts`), so this response never varies per request and needs no templating beyond
751
+ // the developer-controlled `basePath`.
752
+ loginPage() {
753
+ const auth = this.requireAuth();
754
+ if (!auth.modes.includes("login")) throw new NotFoundException2();
755
+ return renderLoginPage(this.basePath);
756
+ }
757
+ // Called by the login page's own fetch (JSON, not a classic form POST — see `login-page.ts` for
758
+ // why: it keeps the login page working with no host-configured body parser beyond the
759
+ // JSON one Nest wires in by default on both Express and Fastify). Uniform `401` on any failure
760
+ // (unknown user, wrong password, throwing hook) — no user-enumeration.
761
+ async login(body, request, response) {
762
+ const auth = this.requireAuth();
763
+ if (!auth.modes.includes("login")) throw new NotFoundException2();
764
+ if (!isString(body?.username) || !isString(body?.password)) {
765
+ throw new BadRequestException("Body must include string `username` and `password`.");
766
+ }
767
+ const { username, password } = body;
768
+ const user = await this.runHook("login", () => auth.login?.(username, password) ?? null);
769
+ if (!user) throw new UnauthorizedException({
770
+ message: "Invalid username or password."
771
+ });
772
+ issueSessionCookie(user, {
773
+ auth,
774
+ request,
775
+ response
776
+ });
777
+ return {
778
+ redirectTo: sanitizeReturnTo(body.returnTo, this.basePath)
779
+ };
780
+ }
781
+ // Mode A: the host frontend (carrying its own auth) POSTs here; the host hook validates the raw
782
+ // request and returns the session user, or `null` to deny. This is the SSO path — the host's own
783
+ // guard decides, and no credential ever reaches this library.
784
+ async session(request, response) {
785
+ const auth = this.requireAuth();
786
+ if (!auth.modes.includes("session")) throw new NotFoundException2();
787
+ const user = await this.runHook("session", () => auth.session?.(request) ?? null);
788
+ if (!user) throw new UnauthorizedException();
789
+ issueSessionCookie(user, {
790
+ auth,
791
+ request,
792
+ response
793
+ });
794
+ }
795
+ // Plain `GET` (not `POST`): logging out only ever destroys the CALLER's own session, so it's
796
+ // safe/idempotent from the caller's perspective — a simple `<a href>` (no JS, no CSRF token)
797
+ // works. Non-passthrough `@Res()`: this handler owns the response outright (clears the cookie,
798
+ // then redirects), so Nest must not also try to send a return value afterwards.
799
+ logout(request, response) {
800
+ clearSessionCookie({
801
+ request,
802
+ response
803
+ });
804
+ redirectRaw(response, this.auth?.modes.includes("login") ? `${this.basePath}/login` : this.basePath);
805
+ }
806
+ requireAuth() {
807
+ if (!this.auth) throw new NotFoundException2();
808
+ return this.auth;
809
+ }
810
+ /**
811
+ * Run a host hook (`login` or `session`) defensively: a throw is treated as a denial (uniform
812
+ * failure) and warn-logged once PER KIND, so a buggy hook never 500s the endpoint into a
813
+ * stack-trace leak nor floods the logs on repeated bad attempts.
814
+ */
815
+ async runHook(kind, run) {
816
+ try {
817
+ return await run() ?? null;
818
+ } catch (error) {
819
+ if (!this.warnedHooks.has(kind)) {
820
+ this.warnedHooks.add(kind);
821
+ this.logger.warn(`dashboardAuth ${kind} hook threw; treating as denial. ${error instanceof Error ? error.message : String(error)}`);
822
+ }
823
+ return null;
824
+ }
825
+ }
826
+ };
827
+ _ts_decorate4([
828
+ Get2("login"),
829
+ Header2("Content-Type", "text/html; charset=utf-8"),
830
+ Header2("Cache-Control", "no-store, must-revalidate"),
831
+ _ts_metadata3("design:type", Function),
832
+ _ts_metadata3("design:paramtypes", []),
833
+ _ts_metadata3("design:returntype", String)
834
+ ], CatalogAuthController.prototype, "loginPage", null);
835
+ _ts_decorate4([
836
+ Post("login"),
837
+ HttpCode(200),
838
+ _ts_param3(0, Body()),
839
+ _ts_param3(1, Req()),
840
+ _ts_param3(2, Res({
841
+ passthrough: true
842
+ })),
843
+ _ts_metadata3("design:type", Function),
844
+ _ts_metadata3("design:paramtypes", [
845
+ typeof LoginBody === "undefined" ? Object : LoginBody,
846
+ Object,
847
+ Object
848
+ ]),
849
+ _ts_metadata3("design:returntype", Promise)
850
+ ], CatalogAuthController.prototype, "login", null);
851
+ _ts_decorate4([
852
+ Post("session"),
853
+ HttpCode(204),
854
+ _ts_param3(0, Req()),
855
+ _ts_param3(1, Res({
856
+ passthrough: true
857
+ })),
858
+ _ts_metadata3("design:type", Function),
859
+ _ts_metadata3("design:paramtypes", [
860
+ Object,
861
+ Object
862
+ ]),
863
+ _ts_metadata3("design:returntype", Promise)
864
+ ], CatalogAuthController.prototype, "session", null);
865
+ _ts_decorate4([
866
+ Get2("logout"),
867
+ _ts_param3(0, Req()),
868
+ _ts_param3(1, Res()),
869
+ _ts_metadata3("design:type", Function),
870
+ _ts_metadata3("design:paramtypes", [
871
+ Object,
872
+ Object
873
+ ]),
874
+ _ts_metadata3("design:returntype", void 0)
875
+ ], CatalogAuthController.prototype, "logout", null);
876
+ CatalogAuthController = _ts_decorate4([
877
+ Controller2(),
878
+ _ts_param3(0, Optional2()),
879
+ _ts_param3(0, Inject3(DASHBOARD_AUTH)),
880
+ _ts_param3(1, Inject3(DASHBOARD_BASE_PATH)),
881
+ _ts_metadata3("design:type", Function),
882
+ _ts_metadata3("design:paramtypes", [
883
+ Object,
884
+ String
885
+ ])
886
+ ], CatalogAuthController);
887
+
888
+ // src/server/catalog-dashboard.module.ts
889
+ import { Module } from "@nestjs/common";
890
+ function _ts_decorate5(decorators, target, key, desc) {
891
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
892
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
893
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
894
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
895
+ }
896
+ __name(_ts_decorate5, "_ts_decorate");
897
+ var CatalogDashboardModule = class _CatalogDashboardModule {
898
+ static {
899
+ __name(this, "CatalogDashboardModule");
900
+ }
901
+ static forRoot(options = {}) {
902
+ const path = normalise(options.path ?? "/catalog");
903
+ const apiPath = normalise(options.apiPath ?? "/api/catalog-service");
904
+ const providers = [
905
+ {
906
+ provide: DASHBOARD_BASE_PATH,
907
+ useValue: path
908
+ },
909
+ {
910
+ provide: DASHBOARD_API_PATH,
911
+ useValue: apiPath
912
+ },
913
+ {
914
+ provide: DASHBOARD_AUTH,
915
+ useValue: options.auth ?? null
916
+ }
917
+ ];
918
+ return {
919
+ module: _CatalogDashboardModule,
920
+ controllers: [
921
+ CatalogUiController,
922
+ CatalogAuthController
923
+ ],
924
+ providers,
925
+ exports: providers
926
+ };
927
+ }
928
+ };
929
+ CatalogDashboardModule = _ts_decorate5([
930
+ Module({})
931
+ ], CatalogDashboardModule);
932
+ function catalogDashboardMountPaths(options = {}) {
933
+ const base = normalise(options.path ?? "/catalog").replace(/^\//, "");
934
+ return [
935
+ {
936
+ path: base,
937
+ method: 7
938
+ },
939
+ {
940
+ path: `${base}/{*path}`,
941
+ method: 7
942
+ }
943
+ ];
944
+ }
945
+ __name(catalogDashboardMountPaths, "catalogDashboardMountPaths");
946
+ function normalise(path) {
947
+ const withLeading = path.startsWith("/") ? path : `/${path}`;
948
+ return withLeading.length > 1 ? withLeading.replace(/\/+$/, "") : withLeading;
949
+ }
950
+ __name(normalise, "normalise");
951
+
952
+ // src/server/catalog-session.guard.ts
953
+ import { Inject as Inject4, Injectable, UnauthorizedException as UnauthorizedException2 } from "@nestjs/common";
954
+ function _ts_decorate6(decorators, target, key, desc) {
955
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
956
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
957
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
958
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
959
+ }
960
+ __name(_ts_decorate6, "_ts_decorate");
961
+ function _ts_metadata4(k, v) {
962
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
963
+ }
964
+ __name(_ts_metadata4, "_ts_metadata");
965
+ function _ts_param4(paramIndex, decorator) {
966
+ return function(target, key) {
967
+ decorator(target, key, paramIndex);
968
+ };
969
+ }
970
+ __name(_ts_param4, "_ts_param");
971
+ var CatalogUiSessionGuard = class {
972
+ static {
973
+ __name(this, "CatalogUiSessionGuard");
974
+ }
975
+ auth;
976
+ basePath;
977
+ constructor(auth, basePath) {
978
+ this.auth = auth;
979
+ this.basePath = basePath;
980
+ }
981
+ async canActivate(context) {
982
+ if (!this.auth) return true;
983
+ const auth = this.auth;
984
+ const http = context.switchToHttp();
985
+ const request = http.getRequest();
986
+ const session = readSessionFromRequest(auth, request);
987
+ if (!session) {
988
+ this.denyUnauthenticated(auth, request);
989
+ }
990
+ if (!await maybeRenewSession(auth, session, request, http.getResponse())) {
991
+ this.denyUnauthenticated(auth, request);
992
+ }
993
+ return true;
994
+ }
995
+ /**
996
+ * A revoked session (the host's `revalidate` hook says no) is denied exactly like an absent
997
+ * one — by design, there is nothing left to distinguish "never had a session" from "had one,
998
+ * then lost it" once the cookie is cleared, so both get the same Mode-aware treatment.
999
+ *
1000
+ * Takes `auth` explicitly rather than reading `this.auth`: `canActivate`'s `!this.auth` early
1001
+ * return narrows the field within that method only — TS doesn't carry it across a method call
1002
+ * — so callers pass the already-narrowed value instead of this method re-deriving (or
1003
+ * asserting away) the nullability.
1004
+ */
1005
+ denyUnauthenticated(auth, request) {
1006
+ if (!auth.modes.includes("login")) throw new DashboardSessionRequiredException(this.basePath);
1007
+ const returnTo = encodeURIComponent(originalRequestUrl(request));
1008
+ throw new DashboardLoginRedirectException(`${this.basePath}/login?returnTo=${returnTo}`);
1009
+ }
1010
+ };
1011
+ CatalogUiSessionGuard = _ts_decorate6([
1012
+ Injectable(),
1013
+ _ts_param4(0, Inject4(DASHBOARD_AUTH)),
1014
+ _ts_param4(1, Inject4(DASHBOARD_BASE_PATH)),
1015
+ _ts_metadata4("design:type", Function),
1016
+ _ts_metadata4("design:paramtypes", [
1017
+ Object,
1018
+ String
1019
+ ])
1020
+ ], CatalogUiSessionGuard);
1021
+ var CatalogApiSessionGuard = class {
1022
+ static {
1023
+ __name(this, "CatalogApiSessionGuard");
1024
+ }
1025
+ auth;
1026
+ constructor(auth) {
1027
+ this.auth = auth;
1028
+ }
1029
+ async canActivate(context) {
1030
+ if (!this.auth) return true;
1031
+ const auth = this.auth;
1032
+ const http = context.switchToHttp();
1033
+ const request = http.getRequest();
1034
+ const session = readSessionFromRequest(auth, request);
1035
+ if (!session) throw this.unauthorized(auth);
1036
+ if (!await maybeRenewSession(auth, session, request, http.getResponse())) {
1037
+ throw this.unauthorized(auth);
1038
+ }
1039
+ return true;
1040
+ }
1041
+ /**
1042
+ * A bare 401 body carrying `{ auth: { modes } }` — mirrors `@dudousxd/nestjs-telescope`'s
1043
+ * dashboardAuth 401. The API is fetched (never navigated), so this is the ONLY way the console
1044
+ * SPA (`catalog-client.ts`) learns which auth surface to send the operator to on a mid-session
1045
+ * 401; `CatalogUiSessionGuard`'s redirect/session-required exceptions above don't reach it.
1046
+ */
1047
+ unauthorized(auth) {
1048
+ return new UnauthorizedException2({
1049
+ auth: {
1050
+ modes: auth.modes
1051
+ }
1052
+ });
1053
+ }
1054
+ };
1055
+ CatalogApiSessionGuard = _ts_decorate6([
1056
+ Injectable(),
1057
+ _ts_param4(0, Inject4(DASHBOARD_AUTH)),
1058
+ _ts_metadata4("design:type", Function),
1059
+ _ts_metadata4("design:paramtypes", [
1060
+ Object
1061
+ ])
1062
+ ], CatalogApiSessionGuard);
1063
+ export {
1064
+ CatalogApiSessionGuard,
1065
+ CatalogAuthController,
1066
+ CatalogDashboardModule,
1067
+ CatalogUiController,
1068
+ CatalogUiSessionGuard,
1069
+ DASHBOARD_API_PATH,
1070
+ DASHBOARD_AUTH,
1071
+ DASHBOARD_BASE_PATH,
1072
+ catalogDashboardMountPaths
1073
+ };
1074
+ //# sourceMappingURL=index.js.map