nish-ui 1.4.1 → 1.6.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.
@@ -1,5 +1,5 @@
1
- import { Context, Handler, Env, Hono, ErrorHandler, MiddlewareHandler } from 'hono';
2
- import { InboxActionCall, InboxData, SessionAuth, Limiter, SpaOptions } from './index.js';
1
+ import { Context, MiddlewareHandler, Handler, Env, Hono, ErrorHandler } from 'hono';
2
+ import { InboxActionCall, InboxData, SessionAuth, Limiter, ManagedServiceTokens, CrossSiteOptions, SpaOptions } from './index.js';
3
3
 
4
4
  /** Node socket peer from @hono/node-server's c.env.incoming, else undefined. */
5
5
  declare function remoteAddressOf(c: Context): string | undefined;
@@ -35,6 +35,11 @@ declare function loginHandler(o: LoginOptions): Handler;
35
35
  declare function mountSessionRoutes<E extends Env>(app: Hono<E>, o: LoginOptions & {
36
36
  base?: string;
37
37
  }): void;
38
+ /** app.use('*', crossSiteGuard()): isCrossSiteWrite -> 403 { error: message } (default
39
+ * 'Cross-site request refused.'), before any route or login runs; everything else goes on. */
40
+ declare function crossSiteGuard(opts?: CrossSiteOptions & {
41
+ message?: string;
42
+ }): MiddlewareHandler;
38
43
  /** app.get('*', serveSpa(...)): createSpaHandler(o) on c.req.raw. */
39
44
  declare function serveSpa(o: SpaOptions): Handler;
40
45
  /** app.onError(...): an error with a getResponse() function (HTTPException) returns that response;
@@ -65,6 +70,16 @@ interface InboxActionRouteOptions {
65
70
  * else run, log `inbox action <actionId> on <dedupeKey>: <status>`, answer c.json(body, status).
66
71
  * Mount before any login middleware covering the path. */
67
72
  declare function mountInboxAction<E extends Env>(app: Hono<E>, o: InboxActionRouteOptions): void;
73
+ interface ServiceTokenRouteOptions {
74
+ tokens: ManagedServiceTokens;
75
+ base?: string;
76
+ log?: (line: string) => void;
77
+ }
78
+ /** GET <base> -> 200 { tokens: views() } with Cache-Control: no-store.
79
+ * POST <base>/:id/revoke -> 200 { tokens: views() } after revoke, logs
80
+ * `service token <id> revoked`; 404 { error: 'No service token with that id.' } when unknown.
81
+ * Mount behind the app's login (requireSession) and its cross-site write guard. */
82
+ declare function mountServiceTokenRoutes<E extends Env>(app: Hono<E>, o: ServiceTokenRouteOptions): void;
68
83
 
69
- export { clientIpOf, endSession, isAuthed, loginHandler, mountInboxAction, mountSessionRoutes, onErrorHandler, remoteAddressOf, requireSession, serveSpa, startSession };
70
- export type { InboxActionRouteOptions, LoginOptions };
84
+ export { clientIpOf, crossSiteGuard, endSession, isAuthed, loginHandler, mountInboxAction, mountServiceTokenRoutes, mountSessionRoutes, onErrorHandler, remoteAddressOf, requireSession, serveSpa, startSession };
85
+ export type { InboxActionRouteOptions, LoginOptions, ServiceTokenRouteOptions };
@@ -18,6 +18,32 @@ function clientIp(get, remoteAddress) {
18
18
  return "local";
19
19
  }
20
20
 
21
+ // src/server/cross-site.ts
22
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
23
+ function originOf(value) {
24
+ try {
25
+ const url = new URL(value);
26
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ function isCrossSiteWrite(method, header, opts = {}) {
32
+ if (SAFE_METHODS.has(method.toUpperCase())) return false;
33
+ const site = header("sec-fetch-site")?.toLowerCase() || void 0;
34
+ if (site === "same-origin" || site === "none") return false;
35
+ const rawOrigin = header("origin") || void 0;
36
+ if (rawOrigin === void 0) return site !== void 0;
37
+ const origin = originOf(rawOrigin);
38
+ if (origin === null) return true;
39
+ for (const allowed of opts.allowedOrigins ?? []) {
40
+ if (originOf(allowed) === origin) return false;
41
+ }
42
+ if (site !== void 0) return true;
43
+ const host = header("host")?.toLowerCase();
44
+ return host === void 0 || new URL(origin).host !== host;
45
+ }
46
+
21
47
  // src/server/inbox/action.ts
22
48
  import { createHash, randomBytes, timingSafeEqual } from "crypto";
23
49
  var INBOX_ACTION_PATH = "/api/inbox/action";
@@ -225,6 +251,13 @@ function mountSessionRoutes(app, o) {
225
251
  return c.json({ authed: false });
226
252
  });
227
253
  }
254
+ function crossSiteGuard(opts) {
255
+ const message = opts?.message ?? "Cross-site request refused.";
256
+ return async (c, next) => {
257
+ if (isCrossSiteWrite(c.req.method, (name) => c.req.header(name), opts)) return c.json({ error: message }, 403);
258
+ await next();
259
+ };
260
+ }
228
261
  function serveSpa(o) {
229
262
  const handle = createSpaHandler(o);
230
263
  return (c) => handle(c.req.raw);
@@ -260,12 +293,29 @@ function mountInboxAction(app, o) {
260
293
  return c.json(result.body, result.status);
261
294
  });
262
295
  }
296
+ function mountServiceTokenRoutes(app, o) {
297
+ const base = (o.base ?? "/api/service-tokens").replace(/\/+$/, "");
298
+ const log = o.log ?? ((line) => console.log(line));
299
+ app.get(base, (c) => {
300
+ c.header("Cache-Control", "no-store");
301
+ return c.json({ tokens: o.tokens.views() });
302
+ });
303
+ app.post(`${base}/:id/revoke`, (c) => {
304
+ const id = c.req.param("id");
305
+ c.header("Cache-Control", "no-store");
306
+ if (!o.tokens.revoke(id)) return c.json({ error: "No service token with that id." }, 404);
307
+ log(`service token ${id} revoked`);
308
+ return c.json({ tokens: o.tokens.views() });
309
+ });
310
+ }
263
311
  export {
264
312
  clientIpOf,
313
+ crossSiteGuard,
265
314
  endSession,
266
315
  isAuthed,
267
316
  loginHandler,
268
317
  mountInboxAction,
318
+ mountServiceTokenRoutes,
269
319
  mountSessionRoutes,
270
320
  onErrorHandler,
271
321
  remoteAddressOf,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server/client-ip.ts","../../src/server/inbox/action.ts","../../src/server/process.ts","../../src/server/session.ts","../../src/server/spa.ts","../../src/server/hono.ts"],"sourcesContent":["// Which key a rate limiter should use for a request. Framework-free: pass a header getter.\n\n/** 127.0.0.0/8, ::1 and ::ffff:127.x. */\nexport function isLoopback(address: string | null | undefined): boolean {\n if (!address) return false;\n const a = address.trim().toLowerCase();\n return a === '::1' || /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(a) || a.startsWith('::ffff:127.');\n}\n\n/** The key a limiter should use for this request. cf-connecting-ip (trimmed, at most 64 chars,\n * no comma) first; else the rightmost X-Forwarded-For entry that is not loopback (127.0.0.0/8,\n * ::1, ::ffff:127.x) and not empty; else remoteAddress when it is not loopback; else 'local'. */\nexport function clientIp(get: (name: string) => string | null | undefined, remoteAddress?: string | null): string {\n const cf = get('cf-connecting-ip')?.trim();\n if (cf && cf.length <= 64 && !cf.includes(',')) return cf;\n const xff = get('x-forwarded-for');\n if (xff) {\n const entries = xff.split(',').map((e) => e.trim());\n for (let i = entries.length - 1; i >= 0; i--) {\n if (entries[i] !== '' && !isLoopback(entries[i])) return entries[i];\n }\n }\n if (remoteAddress && !isLoopback(remoteAddress)) return remoteAddress;\n return 'local';\n}\n","// The guard and tokens for inbox action targets: what an app's POST /api/inbox/action route checks\n// before it runs anything. Framework-free; the Hono route is in @nish/ui/server/hono.\nimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto';\nimport { isInboxActionTarget } from './client';\nimport type { InboxAction, InboxActionCall, InboxData } from './types';\n\nexport const INBOX_ACTION_PATH = '/api/inbox/action';\nexport const ACTION_TOKEN_FIELD = 'actionToken';\nexport const inboxActionTarget = (port: number, path?: string) => `http://127.0.0.1:${port}${path ?? INBOX_ACTION_PATH}`;\n\nexport type HeaderBag = Headers | Record<string, string | string[] | undefined>;\n\nconst LOOPBACK_PEERS = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);\nconst FORBIDDEN_HEADERS = ['forwarded', 'via', 'x-real-ip', 'true-client-ip', 'cdn-loop', 'origin'];\nconst FORBIDDEN_PREFIXES = ['x-forwarded-', 'cf-'];\nconst ACTION_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;\nconst HASH_RE = /^[0-9a-f]{64}$/;\n\nfunction headerNames(headers: HeaderBag): string[] {\n if (typeof (headers as Headers).forEach === 'function' && typeof (headers as Headers).get === 'function') {\n const names: string[] = [];\n (headers as Headers).forEach((_v, k) => names.push(k.toLowerCase()));\n return names;\n }\n return Object.entries(headers as Record<string, string | string[] | undefined>)\n .filter(([, v]) => v !== undefined)\n .map(([k]) => k.toLowerCase());\n}\n\nfunction headerValue(headers: HeaderBag, name: string): string | undefined {\n if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name) ?? undefined;\n for (const [k, v] of Object.entries(headers as Record<string, string | string[] | undefined>)) {\n if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;\n }\n return undefined;\n}\n\n/** True only when every rule holds:\n * remoteAddress is 127.0.0.1, ::1 or ::ffff:127.0.0.1; header host === `127.0.0.1:${port}`;\n * none of these headers is present: forwarded, via, x-real-ip, true-client-ip, cdn-loop, origin, and any name\n * starting with x-forwarded- or cf-; no sec-fetch-* header (site, dest, user: browsers only) except\n * sec-fetch-mode with the exact value 'cors', which Node's own fetch (undici) always sends;\n * header x-inbox-action === '1'.\n * Header names compared lowercase; Headers and Node IncomingHttpHeaders both accepted. */\nexport function isInboxCall(req: { headers: HeaderBag; remoteAddress: string | null | undefined; port: number }): boolean {\n if (!req.remoteAddress || !LOOPBACK_PEERS.has(req.remoteAddress)) return false;\n if (headerValue(req.headers, 'host') !== `127.0.0.1:${req.port}`) return false;\n for (const name of headerNames(req.headers)) {\n if (FORBIDDEN_HEADERS.includes(name)) return false;\n if (FORBIDDEN_PREFIXES.some((p) => name.startsWith(p))) return false;\n if (name.startsWith('sec-fetch-') && !(name === 'sec-fetch-mode' && headerValue(req.headers, name) === 'cors')) return false;\n }\n return headerValue(req.headers, 'x-inbox-action') === '1';\n}\n\n/** The body as an InboxActionCall for `source`, or null: itemId a positive safe integer, actionId\n * matching /^[a-z0-9][a-z0-9-]{0,31}$/, source === `source`, kind a string, dedupeKey string or null,\n * data a plain object. */\nexport function parseInboxActionCall(body: unknown, source: string): (InboxActionCall & { data: InboxData }) | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const b = body as Record<string, unknown>;\n if (typeof b.itemId !== 'number' || !Number.isSafeInteger(b.itemId) || b.itemId <= 0) return null;\n if (typeof b.actionId !== 'string' || !ACTION_ID_RE.test(b.actionId)) return null;\n if (b.source !== source) return null;\n if (typeof b.kind !== 'string') return null;\n if (b.dedupeKey !== null && typeof b.dedupeKey !== 'string') return null;\n const data = b.data;\n if (typeof data !== 'object' || data === null || Array.isArray(data)) return null;\n return {\n itemId: b.itemId,\n actionId: b.actionId,\n source,\n kind: b.kind,\n dedupeKey: b.dedupeKey as string | null,\n data: data as InboxData,\n };\n}\n\n/** 32 random bytes, base64url. */\nexport function newActionToken(): string {\n return randomBytes(32).toString('base64url');\n}\n\n/** sha256 hex (utf8). */\nexport function hashActionToken(token: string): string {\n return createHash('sha256').update(token, 'utf8').digest('hex');\n}\n\n/** Constant time. False when token is not a string of 1..128 chars, or storedHash is not 64 lowercase hex. */\nexport function actionTokenMatches(token: unknown, storedHash: string | null | undefined): boolean {\n if (typeof token !== 'string' || token.length < 1 || token.length > 128) return false;\n if (typeof storedHash !== 'string' || !HASH_RE.test(storedHash)) return false;\n return timingSafeEqual(Buffer.from(hashActionToken(token), 'hex'), Buffer.from(storedHash, 'hex'));\n}\n\n/** An action button; throws Error(`not an inbox action target: ${target}`) when isInboxActionTarget fails. */\nexport function inboxAction(id: string, label: string, target: string): InboxAction {\n if (!isInboxActionTarget(target)) throw new Error(`not an inbox action target: ${target}`);\n return { id, label, method: 'POST', target };\n}\n","// Process-level safety nets for a long-running server: crash logging and graceful shutdown.\n\nexport interface ProcessHandlerOptions {\n name: string;\n log?: (line: string) => void; // default: console.error(`[${iso}] ${name}: ${line}`)\n server?: { close(cb?: (err?: Error) => void): unknown; closeAllConnections?: () => void };\n onShutdown?: () => void | Promise<void>;\n graceMs?: number; // 5000\n exit?: (code: number) => void; // default process.exit, for tests\n}\n\ntype Handle = { shutdown(signal: string): Promise<void> };\nlet installed: Handle | null = null;\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? (err.stack ?? err.message) : String(err);\n}\n\n/** Installs once per process (a second call returns the first handle):\n * - unhandledRejection: log `unhandled rejection: <stack or String(reason)>`, keep running.\n * - uncaughtException: log `uncaught exception: <stack>`, then exit(1) (the supervisor restarts).\n * - SIGINT, SIGTERM: shutdown(signal). Not SIGBREAK: a task stop sends CTRL+BREAK and the\n * supervisor reads the child's 0xC000013A exit as \"stopping\"; a graceful exit 0 would be restarted.\n * shutdown: runs once; logs `got <signal>, shutting down`; server.close(); closeAllConnections?.();\n * awaits onShutdown (errors logged as `shutdown hook failed: <msg>`); exit(0). A graceMs timer\n * (unref'd) logs `forced exit after <graceMs> ms` and exits 0 if that has not finished. */\nexport function installProcessHandlers(o: ProcessHandlerOptions): Handle {\n if (installed) return installed;\n const log = o.log ?? ((line: string) => console.error(`[${new Date().toISOString()}] ${o.name}: ${line}`));\n const exit = o.exit ?? ((code: number) => process.exit(code));\n const graceMs = o.graceMs ?? 5000;\n let shuttingDown: Promise<void> | null = null;\n\n const shutdown = (signal: string): Promise<void> => {\n if (shuttingDown) return shuttingDown;\n shuttingDown = (async () => {\n log(`got ${signal}, shutting down`);\n const timer = setTimeout(() => {\n log(`forced exit after ${graceMs} ms`);\n exit(0);\n }, graceMs);\n timer.unref();\n try {\n o.server?.close();\n o.server?.closeAllConnections?.();\n } catch (err) {\n log(`shutdown hook failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n try {\n await o.onShutdown?.();\n } catch (err) {\n log(`shutdown hook failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n clearTimeout(timer);\n exit(0);\n })();\n return shuttingDown;\n };\n\n process.on('unhandledRejection', (reason) => {\n log(`unhandled rejection: ${describe(reason)}`);\n });\n process.on('uncaughtException', (err) => {\n log(`uncaught exception: ${describe(err)}`);\n exit(1);\n });\n process.on('SIGINT', () => void shutdown('SIGINT'));\n process.on('SIGTERM', () => void shutdown('SIGTERM'));\n\n installed = { shutdown };\n return installed;\n}\n\n/** For any framework's error hook: logs `<method> <path> failed: <stack>` and returns the generic\n * body. Never puts err.message in the response. */\nexport function errorResponse(\n err: unknown,\n req: { method: string; path: string },\n log: (line: string) => void = (line) => console.error(line),\n): { status: 500; body: { error: string } } {\n log(`${req.method} ${req.path} failed: ${describe(err)}`);\n return { status: 500, body: { error: 'Something went wrong.' } };\n}\n","// Session tokens, cookies and password checks shared by every app. Node only, no framework types.\nimport { createHmac, createHash, randomBytes, timingSafeEqual } from 'node:crypto';\n\nexport const SESSION_DAYS = 30;\n\nconst COOKIE_NAME_RE = /^[A-Za-z0-9_-]+$/;\nconst NONCE_RE = /^[0-9a-f]{24}$/;\nconst HEX_RE = /^[0-9a-f]+$/;\n\nfunction equalStrings(a: string, b: string): boolean {\n const x = Buffer.from(a);\n const y = Buffer.from(b);\n return x.length === y.length && timingSafeEqual(x, y);\n}\n\n/** `v1.<expires s>.<24 hex nonce>.<base64url hmac-sha256 of the first three parts>` */\nexport function createSessionToken(secret: string, now: number = Date.now(), days: number = SESSION_DAYS): string {\n if (secret === '') throw new Error('session secret is empty');\n const expires = Math.floor(now / 1000) + Math.round(days * 86400);\n const body = `v1.${expires}.${randomBytes(12).toString('hex')}`;\n const sig = createHmac('sha256', secret).update(body).digest('base64url');\n return `${body}.${sig}`;\n}\n\nexport interface VerifyOptions {\n now?: number;\n legacyHex?: boolean;\n}\n\n/** v1 as above. With legacyHex also job-apps' `v1.<exp>.<hex hmac>` (3 parts) and\n * `v2.<exp>.<nonce>.<hex hmac>`; hex hmac is over every part but the last joined by '.'.\n * False for: empty secret, missing token, wrong part count or prefix, non-finite or past expiry,\n * signature length mismatch. Constant-time compare (timingSafeEqual on equal-length buffers). */\nexport function verifySessionToken(secret: string, token: string | null | undefined, opts: VerifyOptions = {}): boolean {\n if (!secret || !token || typeof token !== 'string') return false;\n const now = opts.now ?? Date.now();\n const parts = token.split('.');\n let signed: string;\n let sig: string;\n let encoding: 'base64url' | 'hex';\n if (parts.length === 4 && parts[0] === 'v1' && NONCE_RE.test(parts[2])) {\n signed = parts.slice(0, 3).join('.');\n sig = parts[3];\n encoding = 'base64url';\n } else if (opts.legacyHex && ((parts.length === 3 && parts[0] === 'v1') || (parts.length === 4 && parts[0] === 'v2'))) {\n signed = parts.slice(0, -1).join('.');\n sig = parts[parts.length - 1];\n encoding = 'hex';\n if (!HEX_RE.test(sig)) return false;\n } else {\n return false;\n }\n const expires = Number(parts[1]);\n if (!parts[1] || !Number.isFinite(expires) || expires * 1000 <= now) return false;\n const expected = createHmac('sha256', secret).update(signed).digest(encoding);\n return equalStrings(expected, sig);\n}\n\n/** sha256 both sides, timingSafeEqual. caseInsensitive (default true) trims and lowercases both.\n * Always false when expected is ''. */\nexport function passwordMatches(expected: string, provided: string, opts: { caseInsensitive?: boolean } = {}): boolean {\n if (typeof expected !== 'string' || typeof provided !== 'string' || expected === '') return false;\n const fold = opts.caseInsensitive ?? true;\n const a = fold ? expected.trim().toLowerCase() : expected;\n const b = fold ? provided.trim().toLowerCase() : provided;\n const ha = createHash('sha256').update(a).digest();\n const hb = createHash('sha256').update(b).digest();\n return timingSafeEqual(ha, hb);\n}\n\n/** Value of cookie `name` in a Cookie header, or undefined. Splits on ';', trims, first match wins,\n * decodeURIComponent in try/catch (raw value on failure). */\nexport function readCookie(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const piece of header.split(';')) {\n const part = piece.trim();\n const eq = part.indexOf('=');\n if (eq < 0) continue;\n if (part.slice(0, eq).trim() !== name) continue;\n const raw = part.slice(eq + 1).trim();\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n }\n return undefined;\n}\n\nexport interface SessionAuth {\n readonly cookieName: string;\n readonly days: number;\n issue(now?: number): string;\n verify(token: string | null | undefined, now?: number): boolean;\n /** Reads the cookie from a Cookie header and verifies it. */\n isAuthed(cookieHeader: string | null | undefined, now?: number): boolean;\n /** A full Set-Cookie value with a fresh token:\n * `<name>=<token>; Max-Age=<days*86400>; Path=/; HttpOnly; SameSite=Lax` plus `; Secure` when secure. */\n setCookie(secure: boolean, now?: number): string;\n /** `<name>=; Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax` */\n clearCookie(): string;\n}\n\nexport function createSessionAuth(o: { cookieName: string; secret: string | (() => string); days?: number; legacyHex?: boolean }): SessionAuth {\n if (!COOKIE_NAME_RE.test(o.cookieName)) throw new Error(`invalid cookie name: ${o.cookieName}`);\n const days = o.days ?? SESSION_DAYS;\n const secret = (): string => (typeof o.secret === 'function' ? o.secret() : o.secret);\n const auth: SessionAuth = {\n cookieName: o.cookieName,\n days,\n issue: (now) => createSessionToken(secret(), now, days),\n verify: (token, now) => verifySessionToken(secret(), token, { now, legacyHex: o.legacyHex }),\n isAuthed: (header, now) => auth.verify(readCookie(header, o.cookieName), now),\n setCookie: (secure, now) =>\n `${o.cookieName}=${auth.issue(now)}; Max-Age=${Math.round(days * 86400)}; Path=/; HttpOnly; SameSite=Lax${secure ? '; Secure' : ''}`,\n clearCookie: () => `${o.cookieName}=; Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax`,\n };\n return auth;\n}\n","// A static single-page-app file handler on web-standard Request and Response.\nimport { readFile, stat } from 'node:fs/promises';\nimport { resolve, sep } from 'node:path';\n\nexport interface SpaOptions {\n dir: string; // absolute path of the built UI, e.g. <root>/dist/public\n index?: string; // 'index.html'\n immutable?: string[]; // URL path prefixes cached for a year: ['/assets/']\n maxAge?: number; // seconds for other static files: 3600\n notBuilt?: string; // 'UI not built: run npm run build'\n}\n\nconst TYPES: Record<string, string> = {\n html: 'text/html; charset=utf-8',\n js: 'text/javascript; charset=utf-8',\n mjs: 'text/javascript; charset=utf-8',\n css: 'text/css; charset=utf-8',\n json: 'application/json; charset=utf-8',\n map: 'application/json; charset=utf-8',\n webmanifest: 'application/manifest+json',\n svg: 'image/svg+xml',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n ico: 'image/x-icon',\n woff2: 'font/woff2',\n woff: 'font/woff',\n txt: 'text/plain; charset=utf-8',\n xml: 'application/xml',\n};\n\nfunction contentType(file: string): string {\n const dot = file.lastIndexOf('.');\n const ext = dot < 0 ? '' : file.slice(dot + 1).toLowerCase();\n return TYPES[ext] ?? 'application/octet-stream';\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\nconst text = (body: string, status: number): Response =>\n new Response(body, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8' } });\n\nexport function createSpaHandler(o: SpaOptions): (req: Request) => Promise<Response> {\n const dir = resolve(o.dir);\n const indexName = o.index ?? 'index.html';\n const immutable = o.immutable ?? [];\n const maxAge = o.maxAge ?? 3600;\n const notBuilt = o.notBuilt ?? 'UI not built: run npm run build';\n const indexPath = resolve(dir, indexName);\n\n const send = async (file: string, cache: string, head: boolean): Promise<Response> => {\n const body = head ? null : await readFile(file);\n return new Response(body, { status: 200, headers: { 'Content-Type': contentType(file), 'Cache-Control': cache } });\n };\n\n return async (req) => {\n const head = req.method === 'HEAD';\n if (req.method !== 'GET' && !head) return text('Not found.', 404);\n\n let pathname: string;\n try {\n pathname = decodeURIComponent(new URL(req.url).pathname);\n } catch {\n return text('Bad request.', 400);\n }\n if (pathname.includes('\\0') || pathname.includes('\\\\')) return text('Not found.', 404);\n const segments = pathname.split('/');\n if (segments.some((s) => s.startsWith('.') && s !== '.well-known')) return text('Not found.', 404);\n // NTFS aliases: 8.3 short names (ENV~1) and stream suffixes (name:$DATA) would bypass the dotfile rule.\n if (segments.some((s) => /~[0-9]|:/.test(s))) return text('Not found.', 404);\n\n const target = resolve(dir, '.' + pathname);\n if (target !== dir && !target.startsWith(dir + sep)) return text('Not found.', 404);\n\n if (target !== dir && (await isFile(target))) {\n let cache = `public, max-age=${maxAge}`;\n if (immutable.some((p) => pathname.startsWith(p))) cache = 'public, max-age=31536000, immutable';\n else if (target === indexPath) cache = 'no-cache';\n return send(target, cache, head);\n }\n\n if (/\\.[A-Za-z0-9]{1,8}$/.test(segments[segments.length - 1] ?? '')) return text('Not found.', 404);\n\n if (!(await isFile(indexPath))) return text(notBuilt, 503);\n return send(indexPath, 'no-cache', head);\n };\n}\n","// @nish/ui/server/hono: Hono adapters over the framework-free @nish/ui/server code.\n// Imports only types from 'hono', so there is no runtime dependency on it.\nimport type { Context, Env, ErrorHandler, Handler, Hono, MiddlewareHandler } from 'hono';\nimport { clientIp } from './client-ip';\nimport { INBOX_ACTION_PATH, isInboxCall, parseInboxActionCall } from './inbox/action';\nimport type { InboxActionCall, InboxData } from './inbox/types';\nimport type { Limiter } from './limiter';\nimport { errorResponse } from './process';\nimport type { SessionAuth } from './session';\nimport { passwordMatches } from './session';\nimport { createSpaHandler, type SpaOptions } from './spa';\n\n/** Node socket peer from @hono/node-server's c.env.incoming, else undefined. */\nexport function remoteAddressOf(c: Context): string | undefined {\n const env = c.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined;\n const address = env?.incoming?.socket?.remoteAddress;\n return typeof address === 'string' ? address : undefined;\n}\n\nexport function clientIpOf(c: Context): string {\n return clientIp((name) => c.req.header(name), remoteAddressOf(c));\n}\n\nexport function isAuthed(c: Context, auth: SessionAuth): boolean {\n return auth.isAuthed(c.req.header('cookie'));\n}\n\nexport function startSession(c: Context, auth: SessionAuth, secure: boolean): void {\n c.header('Set-Cookie', auth.setCookie(secure), { append: true });\n}\n\nexport function endSession(c: Context, auth: SessionAuth): void {\n c.header('Set-Cookie', auth.clearCookie(), { append: true });\n}\n\n/** 401 `{ error: message }` (default 'Log in to see this.') unless authed. */\nexport function requireSession(auth: SessionAuth, opts?: { message?: string }): MiddlewareHandler {\n const message = opts?.message ?? 'Log in to see this.';\n return async (c, next) => {\n if (!isAuthed(c, auth)) return c.json({ error: message }, 401);\n await next();\n };\n}\n\nexport interface LoginOptions {\n auth: SessionAuth;\n password: string | (() => string);\n limiter: Limiter;\n secure: boolean | ((c: Context) => boolean);\n caseInsensitive?: boolean; // true\n failDelayMs?: number; // 0\n messages?: { tooMany?: string; wrong?: string }; // 'Too many tries. Wait a minute and try again.' / 'That password is not right.'\n /** Body of the 429 and 401 answers. Default (kind, message) => ({ error: message }). */\n errorBody?: (kind: 'tooMany' | 'wrong', message: string) => Record<string, unknown>;\n /** Default c.json({ authed: true }). */\n onSuccess?: (c: Context) => Response | Promise<Response>;\n}\n\n/** POST handler: limiter key clientIpOf(c); not allowed -> 429; body via c.req.json() (failure = {});\n * password must be a string of at most 1024 chars and match, else limiter.fail, wait failDelayMs, 401;\n * success -> limiter.reset, startSession, onSuccess. */\nexport function loginHandler(o: LoginOptions): Handler {\n const tooMany = o.messages?.tooMany ?? 'Too many tries. Wait a minute and try again.';\n const wrong = o.messages?.wrong ?? 'That password is not right.';\n const errorBody = o.errorBody ?? ((_kind, message) => ({ error: message }));\n return async (c) => {\n const key = clientIpOf(c);\n if (!o.limiter.allowed(key)) return c.json(errorBody('tooMany', tooMany), 429);\n let body: unknown = {};\n try {\n body = await c.req.json();\n } catch {\n body = {};\n }\n const provided = body && typeof body === 'object' ? (body as { password?: unknown }).password : undefined;\n const expected = typeof o.password === 'function' ? o.password() : o.password;\n const ok =\n typeof provided === 'string' &&\n provided.length <= 1024 &&\n passwordMatches(expected, provided, { caseInsensitive: o.caseInsensitive ?? true });\n if (!ok) {\n o.limiter.fail(key);\n const delay = o.failDelayMs ?? 0;\n if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));\n return c.json(errorBody('wrong', wrong), 401);\n }\n o.limiter.reset(key);\n startSession(c, o.auth, typeof o.secure === 'function' ? o.secure(c) : o.secure);\n return o.onSuccess ? o.onSuccess(c) : c.json({ authed: true });\n };\n}\n\n/** GET <base>/me -> { authed }, POST <base>/login -> loginHandler, POST <base>/logout -> endSession + { authed: false }. base default '/api'. */\nexport function mountSessionRoutes<E extends Env>(app: Hono<E>, o: LoginOptions & { base?: string }): void {\n const base = o.base ?? '/api';\n app.get(`${base}/me`, (c) => c.json({ authed: isAuthed(c, o.auth) }));\n app.post(`${base}/login`, loginHandler(o));\n app.post(`${base}/logout`, (c) => {\n endSession(c, o.auth);\n return c.json({ authed: false });\n });\n}\n\n/** app.get('*', serveSpa(...)): createSpaHandler(o) on c.req.raw. */\nexport function serveSpa(o: SpaOptions): Handler {\n const handle = createSpaHandler(o);\n return (c) => handle(c.req.raw);\n}\n\n/** app.onError(...): an error with a getResponse() function (HTTPException) returns that response;\n * anything else -> errorResponse(...) as JSON 500. */\nexport function onErrorHandler(log?: (line: string) => void): ErrorHandler {\n return (err, c) => {\n const withResponse = err as { getResponse?: unknown };\n if (typeof withResponse.getResponse === 'function') return (withResponse.getResponse as () => Response).call(err);\n const out = errorResponse(err, { method: c.req.method, path: c.req.path }, log);\n return c.json(out.body, out.status);\n };\n}\n\nexport interface InboxActionRouteOptions {\n port: number;\n source: string;\n path?: string; // INBOX_ACTION_PATH\n verify(call: InboxActionCall & { data: InboxData }): boolean | Promise<boolean>;\n run(call: InboxActionCall & { data: InboxData }): { status: number; body: unknown } | Promise<{ status: number; body: unknown }>;\n log(line: string): void;\n refused?: Record<string, unknown>; // { error: 'Log in to see this.' }\n}\n\n/** POST <path>: not isInboxCall -> 401 refused (body unread); parseInboxActionCall null -> 400\n * { error: `Not an inbox action from ${source}.` }; verify false -> log\n * `inbox action <actionId> on <dedupeKey>: refused (no current action token)` and 401 refused;\n * else run, log `inbox action <actionId> on <dedupeKey>: <status>`, answer c.json(body, status).\n * Mount before any login middleware covering the path. */\nexport function mountInboxAction<E extends Env>(app: Hono<E>, o: InboxActionRouteOptions): void {\n const refused = o.refused ?? { error: 'Log in to see this.' };\n app.post(o.path ?? INBOX_ACTION_PATH, async (c) => {\n if (!isInboxCall({ headers: c.req.raw.headers, remoteAddress: remoteAddressOf(c), port: o.port })) {\n return c.json(refused, 401);\n }\n let body: unknown = null;\n try {\n body = await c.req.json();\n } catch {\n body = null;\n }\n const call = parseInboxActionCall(body, o.source);\n if (!call) return c.json({ error: `Not an inbox action from ${o.source}.` }, 400);\n if (!(await o.verify(call))) {\n o.log(`inbox action ${call.actionId} on ${call.dedupeKey}: refused (no current action token)`);\n return c.json(refused, 401);\n }\n const result = await o.run(call);\n o.log(`inbox action ${call.actionId} on ${call.dedupeKey}: ${result.status}`);\n return c.json(result.body as never, result.status as never);\n });\n}\n"],"mappings":";AAGO,SAAS,WAAW,SAA6C;AACtE,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,IAAI,QAAQ,KAAK,EAAE,YAAY;AACrC,SAAO,MAAM,SAAS,mCAAmC,KAAK,CAAC,KAAK,EAAE,WAAW,aAAa;AAChG;AAKO,SAAS,SAAS,KAAkD,eAAuC;AAChH,QAAM,KAAK,IAAI,kBAAkB,GAAG,KAAK;AACzC,MAAI,MAAM,GAAG,UAAU,MAAM,CAAC,GAAG,SAAS,GAAG,EAAG,QAAO;AACvD,QAAM,MAAM,IAAI,iBAAiB;AACjC,MAAI,KAAK;AACP,UAAM,UAAU,IAAI,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC;AAClD,aAAS,IAAI,QAAQ,SAAS,GAAG,KAAK,GAAG,KAAK;AAC5C,UAAI,QAAQ,CAAC,MAAM,MAAM,CAAC,WAAW,QAAQ,CAAC,CAAC,EAAG,QAAO,QAAQ,CAAC;AAAA,IACpE;AAAA,EACF;AACA,MAAI,iBAAiB,CAAC,WAAW,aAAa,EAAG,QAAO;AACxD,SAAO;AACT;;;ACtBA,SAAS,YAAY,aAAa,uBAAuB;AAIlD,IAAM,oBAAoB;AAMjC,IAAM,iBAAiB,oBAAI,IAAI,CAAC,aAAa,OAAO,kBAAkB,CAAC;AACvE,IAAM,oBAAoB,CAAC,aAAa,OAAO,aAAa,kBAAkB,YAAY,QAAQ;AAClG,IAAM,qBAAqB,CAAC,gBAAgB,KAAK;AACjD,IAAM,eAAe;AAGrB,SAAS,YAAY,SAA8B;AACjD,MAAI,OAAQ,QAAoB,YAAY,cAAc,OAAQ,QA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afeEqual","createHash","timingSafeEqual","resolve"]}
1
+ {"version":3,"sources":["../../src/server/client-ip.ts","../../src/server/cross-site.ts","../../src/server/inbox/action.ts","../../src/server/process.ts","../../src/server/session.ts","../../src/server/spa.ts","../../src/server/hono.ts"],"sourcesContent":["// Which key a rate limiter should use for a request. Framework-free: pass a header getter.\n\n/** 127.0.0.0/8, ::1 and ::ffff:127.x. */\nexport function isLoopback(address: string | null | undefined): boolean {\n if (!address) return false;\n const a = address.trim().toLowerCase();\n return a === '::1' || /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(a) || a.startsWith('::ffff:127.');\n}\n\n/** The key a limiter should use for this request. cf-connecting-ip (trimmed, at most 64 chars,\n * no comma) first; else the rightmost X-Forwarded-For entry that is not loopback (127.0.0.0/8,\n * ::1, ::ffff:127.x) and not empty; else remoteAddress when it is not loopback; else 'local'. */\nexport function clientIp(get: (name: string) => string | null | undefined, remoteAddress?: string | null): string {\n const cf = get('cf-connecting-ip')?.trim();\n if (cf && cf.length <= 64 && !cf.includes(',')) return cf;\n const xff = get('x-forwarded-for');\n if (xff) {\n const entries = xff.split(',').map((e) => e.trim());\n for (let i = entries.length - 1; i >= 0; i--) {\n if (entries[i] !== '' && !isLoopback(entries[i])) return entries[i];\n }\n }\n if (remoteAddress && !isLoopback(remoteAddress)) return remoteAddress;\n return 'local';\n}\n","// Refuses state-changing requests a browser sends from another origin. Node or edge, no framework types.\n\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);\n\nexport interface CrossSiteOptions {\n /** Origins besides the request's own that may send writes, like 'https://start.nish.software'. */\n allowedOrigins?: Iterable<string>;\n}\n\nfunction originOf(value: string): string | null {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:' ? url.origin : null;\n } catch {\n return null;\n }\n}\n\n/** True when a POST, PUT, PATCH or DELETE (any method but GET, HEAD and OPTIONS) came from a page on\n * another origin. Another *.nish.software subdomain counts: SameSite=Lax session cookies ride along\n * from those, so the cookie alone does not stop them.\n * - `Sec-Fetch-Site: same-origin` or `none` passes; `same-site` or `cross-site` passes only with an\n * Origin in allowedOrigins.\n * - No Sec-Fetch-Site (an older browser): an Origin must match the Host header or allowedOrigins.\n * - Neither header: not a browser page (curl, a server, the inbox and MCP callers), so it passes. */\nexport function isCrossSiteWrite(\n method: string,\n header: (name: string) => string | null | undefined,\n opts: CrossSiteOptions = {},\n): boolean {\n if (SAFE_METHODS.has(method.toUpperCase())) return false;\n const site = header('sec-fetch-site')?.toLowerCase() || undefined;\n if (site === 'same-origin' || site === 'none') return false;\n const rawOrigin = header('origin') || undefined;\n if (rawOrigin === undefined) return site !== undefined;\n const origin = originOf(rawOrigin);\n if (origin === null) return true;\n for (const allowed of opts.allowedOrigins ?? []) {\n if (originOf(allowed) === origin) return false;\n }\n if (site !== undefined) return true;\n const host = header('host')?.toLowerCase();\n return host === undefined || new URL(origin).host !== host;\n}\n","// The guard and tokens for inbox action targets: what an app's POST /api/inbox/action route checks\n// before it runs anything. Framework-free; the Hono route is in @nish/ui/server/hono.\nimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto';\nimport { isInboxActionTarget } from './client';\nimport type { InboxAction, InboxActionCall, InboxData } from './types';\n\nexport const INBOX_ACTION_PATH = '/api/inbox/action';\nexport const ACTION_TOKEN_FIELD = 'actionToken';\nexport const inboxActionTarget = (port: number, path?: string) => `http://127.0.0.1:${port}${path ?? INBOX_ACTION_PATH}`;\n\nexport type HeaderBag = Headers | Record<string, string | string[] | undefined>;\n\nconst LOOPBACK_PEERS = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);\nconst FORBIDDEN_HEADERS = ['forwarded', 'via', 'x-real-ip', 'true-client-ip', 'cdn-loop', 'origin'];\nconst FORBIDDEN_PREFIXES = ['x-forwarded-', 'cf-'];\nconst ACTION_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;\nconst HASH_RE = /^[0-9a-f]{64}$/;\n\nfunction headerNames(headers: HeaderBag): string[] {\n if (typeof (headers as Headers).forEach === 'function' && typeof (headers as Headers).get === 'function') {\n const names: string[] = [];\n (headers as Headers).forEach((_v, k) => names.push(k.toLowerCase()));\n return names;\n }\n return Object.entries(headers as Record<string, string | string[] | undefined>)\n .filter(([, v]) => v !== undefined)\n .map(([k]) => k.toLowerCase());\n}\n\nfunction headerValue(headers: HeaderBag, name: string): string | undefined {\n if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name) ?? undefined;\n for (const [k, v] of Object.entries(headers as Record<string, string | string[] | undefined>)) {\n if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;\n }\n return undefined;\n}\n\n/** True only when every rule holds:\n * remoteAddress is 127.0.0.1, ::1 or ::ffff:127.0.0.1; header host === `127.0.0.1:${port}`;\n * none of these headers is present: forwarded, via, x-real-ip, true-client-ip, cdn-loop, origin, and any name\n * starting with x-forwarded- or cf-; no sec-fetch-* header (site, dest, user: browsers only) except\n * sec-fetch-mode with the exact value 'cors', which Node's own fetch (undici) always sends;\n * header x-inbox-action === '1'.\n * Header names compared lowercase; Headers and Node IncomingHttpHeaders both accepted. */\nexport function isInboxCall(req: { headers: HeaderBag; remoteAddress: string | null | undefined; port: number }): boolean {\n if (!req.remoteAddress || !LOOPBACK_PEERS.has(req.remoteAddress)) return false;\n if (headerValue(req.headers, 'host') !== `127.0.0.1:${req.port}`) return false;\n for (const name of headerNames(req.headers)) {\n if (FORBIDDEN_HEADERS.includes(name)) return false;\n if (FORBIDDEN_PREFIXES.some((p) => name.startsWith(p))) return false;\n if (name.startsWith('sec-fetch-') && !(name === 'sec-fetch-mode' && headerValue(req.headers, name) === 'cors')) return false;\n }\n return headerValue(req.headers, 'x-inbox-action') === '1';\n}\n\n/** The body as an InboxActionCall for `source`, or null: itemId a positive safe integer, actionId\n * matching /^[a-z0-9][a-z0-9-]{0,31}$/, source === `source`, kind a string, dedupeKey string or null,\n * data a plain object. */\nexport function parseInboxActionCall(body: unknown, source: string): (InboxActionCall & { data: InboxData }) | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const b = body as Record<string, unknown>;\n if (typeof b.itemId !== 'number' || !Number.isSafeInteger(b.itemId) || b.itemId <= 0) return null;\n if (typeof b.actionId !== 'string' || !ACTION_ID_RE.test(b.actionId)) return null;\n if (b.source !== source) return null;\n if (typeof b.kind !== 'string') return null;\n if (b.dedupeKey !== null && typeof b.dedupeKey !== 'string') return null;\n const data = b.data;\n if (typeof data !== 'object' || data === null || Array.isArray(data)) return null;\n return {\n itemId: b.itemId,\n actionId: b.actionId,\n source,\n kind: b.kind,\n dedupeKey: b.dedupeKey as string | null,\n data: data as InboxData,\n };\n}\n\n/** 32 random bytes, base64url. */\nexport function newActionToken(): string {\n return randomBytes(32).toString('base64url');\n}\n\n/** sha256 hex (utf8). */\nexport function hashActionToken(token: string): string {\n return createHash('sha256').update(token, 'utf8').digest('hex');\n}\n\n/** Constant time. False when token is not a string of 1..128 chars, or storedHash is not 64 lowercase hex. */\nexport function actionTokenMatches(token: unknown, storedHash: string | null | undefined): boolean {\n if (typeof token !== 'string' || token.length < 1 || token.length > 128) return false;\n if (typeof storedHash !== 'string' || !HASH_RE.test(storedHash)) return false;\n return timingSafeEqual(Buffer.from(hashActionToken(token), 'hex'), Buffer.from(storedHash, 'hex'));\n}\n\n/** An action button; throws Error(`not an inbox action target: ${target}`) when isInboxActionTarget fails. */\nexport function inboxAction(id: string, label: string, target: string): InboxAction {\n if (!isInboxActionTarget(target)) throw new Error(`not an inbox action target: ${target}`);\n return { id, label, method: 'POST', target };\n}\n","// Process-level safety nets for a long-running server: crash logging and graceful shutdown.\n\nexport interface ProcessHandlerOptions {\n name: string;\n log?: (line: string) => void; // default: console.error(`[${iso}] ${name}: ${line}`)\n server?: { close(cb?: (err?: Error) => void): unknown; closeAllConnections?: () => void };\n onShutdown?: () => void | Promise<void>;\n graceMs?: number; // 5000\n exit?: (code: number) => void; // default process.exit, for tests\n}\n\ntype Handle = { shutdown(signal: string): Promise<void> };\nlet installed: Handle | null = null;\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? (err.stack ?? err.message) : String(err);\n}\n\n/** Installs once per process (a second call returns the first handle):\n * - unhandledRejection: log `unhandled rejection: <stack or String(reason)>`, keep running.\n * - uncaughtException: log `uncaught exception: <stack>`, then exit(1) (the supervisor restarts).\n * - SIGINT, SIGTERM: shutdown(signal). Not SIGBREAK: a task stop sends CTRL+BREAK and the\n * supervisor reads the child's 0xC000013A exit as \"stopping\"; a graceful exit 0 would be restarted.\n * shutdown: runs once; logs `got <signal>, shutting down`; server.close(); closeAllConnections?.();\n * awaits onShutdown (errors logged as `shutdown hook failed: <msg>`); exit(0). A graceMs timer\n * (unref'd) logs `forced exit after <graceMs> ms` and exits 0 if that has not finished. */\nexport function installProcessHandlers(o: ProcessHandlerOptions): Handle {\n if (installed) return installed;\n const log = o.log ?? ((line: string) => console.error(`[${new Date().toISOString()}] ${o.name}: ${line}`));\n const exit = o.exit ?? ((code: number) => process.exit(code));\n const graceMs = o.graceMs ?? 5000;\n let shuttingDown: Promise<void> | null = null;\n\n const shutdown = (signal: string): Promise<void> => {\n if (shuttingDown) return shuttingDown;\n shuttingDown = (async () => {\n log(`got ${signal}, shutting down`);\n const timer = setTimeout(() => {\n log(`forced exit after ${graceMs} ms`);\n exit(0);\n }, graceMs);\n timer.unref();\n try {\n o.server?.close();\n o.server?.closeAllConnections?.();\n } catch (err) {\n log(`shutdown hook failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n try {\n await o.onShutdown?.();\n } catch (err) {\n log(`shutdown hook failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n clearTimeout(timer);\n exit(0);\n })();\n return shuttingDown;\n };\n\n process.on('unhandledRejection', (reason) => {\n log(`unhandled rejection: ${describe(reason)}`);\n });\n process.on('uncaughtException', (err) => {\n log(`uncaught exception: ${describe(err)}`);\n exit(1);\n });\n process.on('SIGINT', () => void shutdown('SIGINT'));\n process.on('SIGTERM', () => void shutdown('SIGTERM'));\n\n installed = { shutdown };\n return installed;\n}\n\n/** For any framework's error hook: logs `<method> <path> failed: <stack>` and returns the generic\n * body. Never puts err.message in the response. */\nexport function errorResponse(\n err: unknown,\n req: { method: string; path: string },\n log: (line: string) => void = (line) => console.error(line),\n): { status: 500; body: { error: string } } {\n log(`${req.method} ${req.path} failed: ${describe(err)}`);\n return { status: 500, body: { error: 'Something went wrong.' } };\n}\n","// Session tokens, cookies and password checks shared by every app. Node only, no framework types.\nimport { createHmac, createHash, randomBytes, timingSafeEqual } from 'node:crypto';\n\nexport const SESSION_DAYS = 30;\n\nconst COOKIE_NAME_RE = /^[A-Za-z0-9_-]+$/;\nconst NONCE_RE = /^[0-9a-f]{24}$/;\nconst HEX_RE = /^[0-9a-f]+$/;\n\nfunction equalStrings(a: string, b: string): boolean {\n const x = Buffer.from(a);\n const y = Buffer.from(b);\n return x.length === y.length && timingSafeEqual(x, y);\n}\n\n/** `v1.<expires s>.<24 hex nonce>.<base64url hmac-sha256 of the first three parts>` */\nexport function createSessionToken(secret: string, now: number = Date.now(), days: number = SESSION_DAYS): string {\n if (secret === '') throw new Error('session secret is empty');\n const expires = Math.floor(now / 1000) + Math.round(days * 86400);\n const body = `v1.${expires}.${randomBytes(12).toString('hex')}`;\n const sig = createHmac('sha256', secret).update(body).digest('base64url');\n return `${body}.${sig}`;\n}\n\nexport interface VerifyOptions {\n now?: number;\n legacyHex?: boolean;\n}\n\n/** v1 as above. With legacyHex also job-apps' `v1.<exp>.<hex hmac>` (3 parts) and\n * `v2.<exp>.<nonce>.<hex hmac>`; hex hmac is over every part but the last joined by '.'.\n * False for: empty secret, missing token, wrong part count or prefix, non-finite or past expiry,\n * signature length mismatch. Constant-time compare (timingSafeEqual on equal-length buffers). */\nexport function verifySessionToken(secret: string, token: string | null | undefined, opts: VerifyOptions = {}): boolean {\n if (!secret || !token || typeof token !== 'string') return false;\n const now = opts.now ?? Date.now();\n const parts = token.split('.');\n let signed: string;\n let sig: string;\n let encoding: 'base64url' | 'hex';\n if (parts.length === 4 && parts[0] === 'v1' && NONCE_RE.test(parts[2])) {\n signed = parts.slice(0, 3).join('.');\n sig = parts[3];\n encoding = 'base64url';\n } else if (opts.legacyHex && ((parts.length === 3 && parts[0] === 'v1') || (parts.length === 4 && parts[0] === 'v2'))) {\n signed = parts.slice(0, -1).join('.');\n sig = parts[parts.length - 1];\n encoding = 'hex';\n if (!HEX_RE.test(sig)) return false;\n } else {\n return false;\n }\n const expires = Number(parts[1]);\n if (!parts[1] || !Number.isFinite(expires) || expires * 1000 <= now) return false;\n const expected = createHmac('sha256', secret).update(signed).digest(encoding);\n return equalStrings(expected, sig);\n}\n\n/** sha256 both sides, timingSafeEqual. caseInsensitive (default true) trims and lowercases both.\n * Always false when expected is ''. */\nexport function passwordMatches(expected: string, provided: string, opts: { caseInsensitive?: boolean } = {}): boolean {\n if (typeof expected !== 'string' || typeof provided !== 'string' || expected === '') return false;\n const fold = opts.caseInsensitive ?? true;\n const a = fold ? expected.trim().toLowerCase() : expected;\n const b = fold ? provided.trim().toLowerCase() : provided;\n const ha = createHash('sha256').update(a).digest();\n const hb = createHash('sha256').update(b).digest();\n return timingSafeEqual(ha, hb);\n}\n\n/** Value of cookie `name` in a Cookie header, or undefined. Splits on ';', trims, first match wins,\n * decodeURIComponent in try/catch (raw value on failure). */\nexport function readCookie(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const piece of header.split(';')) {\n const part = piece.trim();\n const eq = part.indexOf('=');\n if (eq < 0) continue;\n if (part.slice(0, eq).trim() !== name) continue;\n const raw = part.slice(eq + 1).trim();\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n }\n return undefined;\n}\n\nexport interface SessionAuth {\n readonly cookieName: string;\n readonly days: number;\n issue(now?: number): string;\n verify(token: string | null | undefined, now?: number): boolean;\n /** Reads the cookie from a Cookie header and verifies it. */\n isAuthed(cookieHeader: string | null | undefined, now?: number): boolean;\n /** A full Set-Cookie value with a fresh token:\n * `<name>=<token>; Max-Age=<days*86400>; Path=/; HttpOnly; SameSite=Lax` plus `; Secure` when secure. */\n setCookie(secure: boolean, now?: number): string;\n /** `<name>=; Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax` */\n clearCookie(): string;\n}\n\nexport function createSessionAuth(o: { cookieName: string; secret: string | (() => string); days?: number; legacyHex?: boolean }): SessionAuth {\n if (!COOKIE_NAME_RE.test(o.cookieName)) throw new Error(`invalid cookie name: ${o.cookieName}`);\n const days = o.days ?? SESSION_DAYS;\n const secret = (): string => (typeof o.secret === 'function' ? o.secret() : o.secret);\n const auth: SessionAuth = {\n cookieName: o.cookieName,\n days,\n issue: (now) => createSessionToken(secret(), now, days),\n verify: (token, now) => verifySessionToken(secret(), token, { now, legacyHex: o.legacyHex }),\n isAuthed: (header, now) => auth.verify(readCookie(header, o.cookieName), now),\n setCookie: (secure, now) =>\n `${o.cookieName}=${auth.issue(now)}; Max-Age=${Math.round(days * 86400)}; Path=/; HttpOnly; SameSite=Lax${secure ? '; Secure' : ''}`,\n clearCookie: () => `${o.cookieName}=; Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax`,\n };\n return auth;\n}\n","// A static single-page-app file handler on web-standard Request and Response.\nimport { readFile, stat } from 'node:fs/promises';\nimport { resolve, sep } from 'node:path';\n\nexport interface SpaOptions {\n dir: string; // absolute path of the built UI, e.g. <root>/dist/public\n index?: string; // 'index.html'\n immutable?: string[]; // URL path prefixes cached for a year: ['/assets/']\n maxAge?: number; // seconds for other static files: 3600\n notBuilt?: string; // 'UI not built: run npm run build'\n}\n\nconst TYPES: Record<string, string> = {\n html: 'text/html; charset=utf-8',\n js: 'text/javascript; charset=utf-8',\n mjs: 'text/javascript; charset=utf-8',\n css: 'text/css; charset=utf-8',\n json: 'application/json; charset=utf-8',\n map: 'application/json; charset=utf-8',\n webmanifest: 'application/manifest+json',\n svg: 'image/svg+xml',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n ico: 'image/x-icon',\n woff2: 'font/woff2',\n woff: 'font/woff',\n txt: 'text/plain; charset=utf-8',\n xml: 'application/xml',\n};\n\nfunction contentType(file: string): string {\n const dot = file.lastIndexOf('.');\n const ext = dot < 0 ? '' : file.slice(dot + 1).toLowerCase();\n return TYPES[ext] ?? 'application/octet-stream';\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\nconst text = (body: string, status: number): Response =>\n new Response(body, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8' } });\n\nexport function createSpaHandler(o: SpaOptions): (req: Request) => Promise<Response> {\n const dir = resolve(o.dir);\n const indexName = o.index ?? 'index.html';\n const immutable = o.immutable ?? [];\n const maxAge = o.maxAge ?? 3600;\n const notBuilt = o.notBuilt ?? 'UI not built: run npm run build';\n const indexPath = resolve(dir, indexName);\n\n const send = async (file: string, cache: string, head: boolean): Promise<Response> => {\n const body = head ? null : await readFile(file);\n return new Response(body, { status: 200, headers: { 'Content-Type': contentType(file), 'Cache-Control': cache } });\n };\n\n return async (req) => {\n const head = req.method === 'HEAD';\n if (req.method !== 'GET' && !head) return text('Not found.', 404);\n\n let pathname: string;\n try {\n pathname = decodeURIComponent(new URL(req.url).pathname);\n } catch {\n return text('Bad request.', 400);\n }\n if (pathname.includes('\\0') || pathname.includes('\\\\')) return text('Not found.', 404);\n const segments = pathname.split('/');\n if (segments.some((s) => s.startsWith('.') && s !== '.well-known')) return text('Not found.', 404);\n // NTFS aliases: 8.3 short names (ENV~1) and stream suffixes (name:$DATA) would bypass the dotfile rule.\n if (segments.some((s) => /~[0-9]|:/.test(s))) return text('Not found.', 404);\n\n const target = resolve(dir, '.' + pathname);\n if (target !== dir && !target.startsWith(dir + sep)) return text('Not found.', 404);\n\n if (target !== dir && (await isFile(target))) {\n let cache = `public, max-age=${maxAge}`;\n if (immutable.some((p) => pathname.startsWith(p))) cache = 'public, max-age=31536000, immutable';\n else if (target === indexPath) cache = 'no-cache';\n return send(target, cache, head);\n }\n\n if (/\\.[A-Za-z0-9]{1,8}$/.test(segments[segments.length - 1] ?? '')) return text('Not found.', 404);\n\n if (!(await isFile(indexPath))) return text(notBuilt, 503);\n return send(indexPath, 'no-cache', head);\n };\n}\n","// @nish/ui/server/hono: Hono adapters over the framework-free @nish/ui/server code.\n// Imports only types from 'hono', so there is no runtime dependency on it.\nimport type { Context, Env, ErrorHandler, Handler, Hono, MiddlewareHandler } from 'hono';\nimport { clientIp } from './client-ip';\nimport { isCrossSiteWrite, type CrossSiteOptions } from './cross-site';\nimport { INBOX_ACTION_PATH, isInboxCall, parseInboxActionCall } from './inbox/action';\nimport type { InboxActionCall, InboxData } from './inbox/types';\nimport type { Limiter } from './limiter';\nimport { errorResponse } from './process';\nimport type { ManagedServiceTokens } from './service-tokens';\nimport type { SessionAuth } from './session';\nimport { passwordMatches } from './session';\nimport { createSpaHandler, type SpaOptions } from './spa';\n\n/** Node socket peer from @hono/node-server's c.env.incoming, else undefined. */\nexport function remoteAddressOf(c: Context): string | undefined {\n const env = c.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined;\n const address = env?.incoming?.socket?.remoteAddress;\n return typeof address === 'string' ? address : undefined;\n}\n\nexport function clientIpOf(c: Context): string {\n return clientIp((name) => c.req.header(name), remoteAddressOf(c));\n}\n\nexport function isAuthed(c: Context, auth: SessionAuth): boolean {\n return auth.isAuthed(c.req.header('cookie'));\n}\n\nexport function startSession(c: Context, auth: SessionAuth, secure: boolean): void {\n c.header('Set-Cookie', auth.setCookie(secure), { append: true });\n}\n\nexport function endSession(c: Context, auth: SessionAuth): void {\n c.header('Set-Cookie', auth.clearCookie(), { append: true });\n}\n\n/** 401 `{ error: message }` (default 'Log in to see this.') unless authed. */\nexport function requireSession(auth: SessionAuth, opts?: { message?: string }): MiddlewareHandler {\n const message = opts?.message ?? 'Log in to see this.';\n return async (c, next) => {\n if (!isAuthed(c, auth)) return c.json({ error: message }, 401);\n await next();\n };\n}\n\nexport interface LoginOptions {\n auth: SessionAuth;\n password: string | (() => string);\n limiter: Limiter;\n secure: boolean | ((c: Context) => boolean);\n caseInsensitive?: boolean; // true\n failDelayMs?: number; // 0\n messages?: { tooMany?: string; wrong?: string }; // 'Too many tries. Wait a minute and try again.' / 'That password is not right.'\n /** Body of the 429 and 401 answers. Default (kind, message) => ({ error: message }). */\n errorBody?: (kind: 'tooMany' | 'wrong', message: string) => Record<string, unknown>;\n /** Default c.json({ authed: true }). */\n onSuccess?: (c: Context) => Response | Promise<Response>;\n}\n\n/** POST handler: limiter key clientIpOf(c); not allowed -> 429; body via c.req.json() (failure = {});\n * password must be a string of at most 1024 chars and match, else limiter.fail, wait failDelayMs, 401;\n * success -> limiter.reset, startSession, onSuccess. */\nexport function loginHandler(o: LoginOptions): Handler {\n const tooMany = o.messages?.tooMany ?? 'Too many tries. Wait a minute and try again.';\n const wrong = o.messages?.wrong ?? 'That password is not right.';\n const errorBody = o.errorBody ?? ((_kind, message) => ({ error: message }));\n return async (c) => {\n const key = clientIpOf(c);\n if (!o.limiter.allowed(key)) return c.json(errorBody('tooMany', tooMany), 429);\n let body: unknown = {};\n try {\n body = await c.req.json();\n } catch {\n body = {};\n }\n const provided = body && typeof body === 'object' ? (body as { password?: unknown }).password : undefined;\n const expected = typeof o.password === 'function' ? o.password() : o.password;\n const ok =\n typeof provided === 'string' &&\n provided.length <= 1024 &&\n passwordMatches(expected, provided, { caseInsensitive: o.caseInsensitive ?? true });\n if (!ok) {\n o.limiter.fail(key);\n const delay = o.failDelayMs ?? 0;\n if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));\n return c.json(errorBody('wrong', wrong), 401);\n }\n o.limiter.reset(key);\n startSession(c, o.auth, typeof o.secure === 'function' ? o.secure(c) : o.secure);\n return o.onSuccess ? o.onSuccess(c) : c.json({ authed: true });\n };\n}\n\n/** GET <base>/me -> { authed }, POST <base>/login -> loginHandler, POST <base>/logout -> endSession + { authed: false }. base default '/api'. */\nexport function mountSessionRoutes<E extends Env>(app: Hono<E>, o: LoginOptions & { base?: string }): void {\n const base = o.base ?? '/api';\n app.get(`${base}/me`, (c) => c.json({ authed: isAuthed(c, o.auth) }));\n app.post(`${base}/login`, loginHandler(o));\n app.post(`${base}/logout`, (c) => {\n endSession(c, o.auth);\n return c.json({ authed: false });\n });\n}\n\n/** app.use('*', crossSiteGuard()): isCrossSiteWrite -> 403 { error: message } (default\n * 'Cross-site request refused.'), before any route or login runs; everything else goes on. */\nexport function crossSiteGuard(opts?: CrossSiteOptions & { message?: string }): MiddlewareHandler {\n const message = opts?.message ?? 'Cross-site request refused.';\n return async (c, next) => {\n if (isCrossSiteWrite(c.req.method, (name) => c.req.header(name), opts)) return c.json({ error: message }, 403);\n await next();\n };\n}\n\n/** app.get('*', serveSpa(...)): createSpaHandler(o) on c.req.raw. */\nexport function serveSpa(o: SpaOptions): Handler {\n const handle = createSpaHandler(o);\n return (c) => handle(c.req.raw);\n}\n\n/** app.onError(...): an error with a getResponse() function (HTTPException) returns that response;\n * anything else -> errorResponse(...) as JSON 500. */\nexport function onErrorHandler(log?: (line: string) => void): ErrorHandler {\n return (err, c) => {\n const withResponse = err as { getResponse?: unknown };\n if (typeof withResponse.getResponse === 'function') return (withResponse.getResponse as () => Response).call(err);\n const out = errorResponse(err, { method: c.req.method, path: c.req.path }, log);\n return c.json(out.body, out.status);\n };\n}\n\nexport interface InboxActionRouteOptions {\n port: number;\n source: string;\n path?: string; // INBOX_ACTION_PATH\n verify(call: InboxActionCall & { data: InboxData }): boolean | Promise<boolean>;\n run(call: InboxActionCall & { data: InboxData }): { status: number; body: unknown } | Promise<{ status: number; body: unknown }>;\n log(line: string): void;\n refused?: Record<string, unknown>; // { error: 'Log in to see this.' }\n}\n\n/** POST <path>: not isInboxCall -> 401 refused (body unread); parseInboxActionCall null -> 400\n * { error: `Not an inbox action from ${source}.` }; verify false -> log\n * `inbox action <actionId> on <dedupeKey>: refused (no current action token)` and 401 refused;\n * else run, log `inbox action <actionId> on <dedupeKey>: <status>`, answer c.json(body, status).\n * Mount before any login middleware covering the path. */\nexport function mountInboxAction<E extends Env>(app: Hono<E>, o: InboxActionRouteOptions): void {\n const refused = o.refused ?? { error: 'Log in to see this.' };\n app.post(o.path ?? INBOX_ACTION_PATH, async (c) => {\n if (!isInboxCall({ headers: c.req.raw.headers, remoteAddress: remoteAddressOf(c), port: o.port })) {\n return c.json(refused, 401);\n }\n let body: unknown = null;\n try {\n body = await c.req.json();\n } catch {\n body = null;\n }\n const call = parseInboxActionCall(body, o.source);\n if (!call) return c.json({ error: `Not an inbox action from ${o.source}.` }, 400);\n if (!(await o.verify(call))) {\n o.log(`inbox action ${call.actionId} on ${call.dedupeKey}: refused (no current action token)`);\n return c.json(refused, 401);\n }\n const result = await o.run(call);\n o.log(`inbox action ${call.actionId} on ${call.dedupeKey}: ${result.status}`);\n return c.json(result.body as never, result.status as never);\n });\n}\n\nexport interface ServiceTokenRouteOptions {\n tokens: ManagedServiceTokens;\n base?: string; // '/api/service-tokens'\n log?: (line: string) => void; // console.log\n}\n\n/** GET <base> -> 200 { tokens: views() } with Cache-Control: no-store.\n * POST <base>/:id/revoke -> 200 { tokens: views() } after revoke, logs\n * `service token <id> revoked`; 404 { error: 'No service token with that id.' } when unknown.\n * Mount behind the app's login (requireSession) and its cross-site write guard. */\nexport function mountServiceTokenRoutes<E extends Env>(app: Hono<E>, o: ServiceTokenRouteOptions): void {\n const base = (o.base ?? '/api/service-tokens').replace(/\\/+$/, '');\n const log = o.log ?? ((line: string) => console.log(line));\n app.get(base, (c) => {\n c.header('Cache-Control', 'no-store');\n return c.json({ tokens: o.tokens.views() });\n });\n app.post(`${base}/:id/revoke`, (c) => {\n const id = c.req.param('id');\n c.header('Cache-Control', 'no-store');\n if (!o.tokens.revoke(id)) return c.json({ error: 'No service token with that id.' }, 404);\n log(`service token ${id} revoked`);\n return c.json({ tokens: o.tokens.views() });\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AAK,EAAE,IAAI,MAAM,IAAI;AAC3B,MAAE,OAAO,iBAAiB,UAAU;AACpC,QAAI,CAAC,EAAE,OAAO,OAAO,EAAE,EAAG,QAAO,EAAE,KAAK,EAAE,OAAO,iCAAiC,GAAG,GAAG;AACxF,QAAI,iBAAiB,EAAE,UAAU;AACjC,WAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,MAAM,EAAE,CAAC;AAAA,EAC5C,CAAC;AACH;","names":["createHash","randomBytes","timingSafeEqual","createHash","timingSafeEqual","resolve"]}
@@ -1,5 +1,5 @@
1
- import { c as InboxEventInput, d as InboxIngestAction, e as InboxEvent, f as InboxAction, I as InboxActionCall, a as InboxData } from '../spa-EPM1E0Va.js';
2
- export { g as INBOX_ACTION_HEADER, h as INBOX_ACTION_TIMEOUT_MS, i as INBOX_DEFAULT_SETTINGS, j as INBOX_SOURCE_LABELS, k as InboxActionResult, l as InboxItem, m as InboxListResponse, n as InboxSettings, o as InboxSeverity, p as InboxView, L as Limiter, q as SESSION_DAYS, S as SessionAuth, b as SpaOptions, V as VerifyOptions, r as createLimiter, s as createSessionAuth, t as createSessionToken, u as createSpaHandler, v as passwordMatches, w as readCookie, x as verifySessionToken } from '../spa-EPM1E0Va.js';
1
+ import { c as InboxEventInput, d as InboxIngestAction, e as InboxEvent, f as InboxAction, I as InboxActionCall, a as InboxData } from '../spa-DuVB5O7S.js';
2
+ export { C as CrossSiteOptions, g as INBOX_ACTION_HEADER, h as INBOX_ACTION_TIMEOUT_MS, i as INBOX_DEFAULT_SETTINGS, j as INBOX_SOURCE_LABELS, k as InboxActionResult, l as InboxItem, m as InboxListResponse, n as InboxSettings, o as InboxSeverity, p as InboxView, L as Limiter, M as ManagedServiceTokens, R as RevocationStore, q as RevokedToken, r as SESSION_DAYS, s as ServiceTokenEntry, t as ServiceTokenView, u as ServiceTokens, S as SessionAuth, b as SpaOptions, V as VerifyOptions, v as VerifyResult, w as checkServiceRequest, x as createLimiter, y as createServiceTokens, z as createSessionAuth, A as createSessionToken, B as createSpaHandler, D as hashServiceToken, E as isCrossSiteWrite, F as isDirectLoopback, G as jsonRevocationStore, H as loadManagedServiceTokens, J as loadServiceTokens, K as mintServiceToken, N as passwordMatches, O as readCookie, P as verifySessionToken } from '../spa-DuVB5O7S.js';
3
3
 
4
4
  /** 127.0.0.0/8, ::1 and ::ffff:127.x. */
5
5
  declare function isLoopback(address: string | null | undefined): boolean;
@@ -138,55 +138,5 @@ declare function actionTokenMatches(token: unknown, storedHash: string | null |
138
138
  /** An action button; throws Error(`not an inbox action target: ${target}`) when isInboxActionTarget fails. */
139
139
  declare function inboxAction(id: string, label: string, target: string): InboxAction;
140
140
 
141
- interface ServiceTokenEntry {
142
- id: string;
143
- name: string;
144
- scopes: string[];
145
- /** sha256 (hex) of the raw token. */
146
- sha256: string;
147
- created: string;
148
- }
149
- type VerifyResult = {
150
- ok: true;
151
- entry: ServiceTokenEntry;
152
- } | {
153
- ok: false;
154
- status: 401 | 403;
155
- };
156
- interface ServiceTokens {
157
- verify(authorization: string | undefined, scope: string): VerifyResult;
158
- /** The entries without their hashes, for a settings page or a `whoami`. */
159
- list(): Array<Omit<ServiceTokenEntry, 'sha256'>>;
160
- }
161
- declare const hashServiceToken: (token: string) => string;
162
- /** A new raw token for `app` (lowercase letters, digits, dashes). Store only its hash in the app. */
163
- declare function mintServiceToken(app: string): {
164
- token: string;
165
- sha256: string;
166
- };
167
- /**
168
- * Loads entries from `file` (missing file = no entries) and from `env` (the SERVICE_TOKENS value).
169
- * Read once at startup; a deploy restarts the app, which is when the file changes.
170
- */
171
- declare function loadServiceTokens(o?: {
172
- file?: string;
173
- env?: string;
174
- }): ServiceTokens;
175
- declare function createServiceTokens(entries: ServiceTokenEntry[]): ServiceTokens;
176
- /**
177
- * True only for a request made straight to the app on loopback: Host is 127.0.0.1, localhost or
178
- * [::1] with the app's port, there are no proxy headers and no Origin (browsers never get in).
179
- */
180
- declare function isDirectLoopback(get: (name: string) => string | undefined, port: number): boolean;
181
- /** Framework-free check: the status and body a guard should answer with, or null to continue. */
182
- declare function checkServiceRequest(get: (name: string) => string | undefined, o: {
183
- tokens: ServiceTokens;
184
- scope: string;
185
- port: number;
186
- }): {
187
- status: 401 | 403;
188
- error: string;
189
- } | null;
190
-
191
- export { ACTION_TOKEN_FIELD, INBOX_ACTION_PATH, InboxAction, InboxActionCall, InboxData, InboxEvent, InboxEventInput, InboxIngestAction, actionTokenMatches, appRoot, checkServiceRequest, clientIp, createInboxClient, createServiceTokens, envNumber, errorResponse, hashActionToken, hashServiceToken, inboxAction, inboxActionTarget, installProcessHandlers, isDirectLoopback, isInboxActionTarget, isInboxCall, isLoopback, loadAppEnv, loadServiceTokens, mintServiceToken, newActionToken, parseInboxActionCall, parseInboxEvent };
192
- export type { HeaderBag, InboxClient, InboxClientOptions, InboxSendResult, ProcessHandlerOptions, ServiceTokenEntry, ServiceTokens, VerifyResult };
141
+ export { ACTION_TOKEN_FIELD, INBOX_ACTION_PATH, InboxAction, InboxActionCall, InboxData, InboxEvent, InboxEventInput, InboxIngestAction, actionTokenMatches, appRoot, clientIp, createInboxClient, envNumber, errorResponse, hashActionToken, inboxAction, inboxActionTarget, installProcessHandlers, isInboxActionTarget, isInboxCall, isLoopback, loadAppEnv, newActionToken, parseInboxActionCall, parseInboxEvent };
142
+ export type { HeaderBag, InboxClient, InboxClientOptions, InboxSendResult, ProcessHandlerOptions };
@@ -675,7 +675,8 @@ function inboxAction(id, label, target) {
675
675
 
676
676
  // src/server/service-tokens.ts
677
677
  import { createHash as createHash3, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual3 } from "crypto";
678
- import { readFileSync as readFileSync2 } from "fs";
678
+ import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "fs";
679
+ import { dirname as dirname2 } from "path";
679
680
  var TOKEN_RE = /^nish_[a-z][a-z0-9-]*_[A-Za-z0-9_-]{43}$/;
680
681
  var HEX_RE2 = /^[0-9a-f]{64}$/;
681
682
  var hashServiceToken = (token) => createHash3("sha256").update(token, "utf8").digest("hex");
@@ -700,8 +701,8 @@ function parseEntries(raw, where) {
700
701
  }
701
702
  return out;
702
703
  }
703
- function loadServiceTokens(o = {}) {
704
- const entries = [];
704
+ function readSeed(o) {
705
+ const out = [];
705
706
  if (o.file) {
706
707
  let text2 = null;
707
708
  try {
@@ -711,7 +712,7 @@ function loadServiceTokens(o = {}) {
711
712
  }
712
713
  if (text2 !== null) {
713
714
  try {
714
- entries.push(...parseEntries(JSON.parse(text2), o.file));
715
+ for (const entry of parseEntries(JSON.parse(text2), o.file)) out.push({ entry, source: "file" });
715
716
  } catch {
716
717
  console.warn(`[service-tokens] ${o.file}: not valid JSON, ignored`);
717
718
  }
@@ -719,12 +720,104 @@ function loadServiceTokens(o = {}) {
719
720
  }
720
721
  if (o.env && o.env.trim()) {
721
722
  try {
722
- entries.push(...parseEntries(JSON.parse(o.env), "SERVICE_TOKENS"));
723
+ for (const entry of parseEntries(JSON.parse(o.env), "SERVICE_TOKENS")) out.push({ entry, source: "env" });
723
724
  } catch {
724
725
  console.warn("[service-tokens] SERVICE_TOKENS: not valid JSON, ignored");
725
726
  }
726
727
  }
727
- return createServiceTokens(entries);
728
+ return out;
729
+ }
730
+ function loadServiceTokens(o = {}) {
731
+ return createServiceTokens(readSeed(o).map((s) => s.entry));
732
+ }
733
+ function jsonRevocationStore(file) {
734
+ let warned = false;
735
+ const kept = [];
736
+ const warn = (why) => {
737
+ if (warned) return;
738
+ warned = true;
739
+ console.warn(`[service-tokens] ${file}: ${why}, ignored`);
740
+ };
741
+ return {
742
+ load() {
743
+ let text2;
744
+ try {
745
+ text2 = readFileSync2(file, "utf8");
746
+ } catch (err) {
747
+ if (err.code === "ENOENT") return [];
748
+ throw err;
749
+ }
750
+ const setAside = (why) => {
751
+ warn(why);
752
+ renameSync(file, `${file}.bad-${Date.now()}`);
753
+ return [];
754
+ };
755
+ let raw;
756
+ try {
757
+ raw = JSON.parse(text2);
758
+ } catch {
759
+ return setAside("not valid JSON");
760
+ }
761
+ const list = raw?.revoked;
762
+ if (!raw || typeof raw !== "object" || !Array.isArray(list)) return setAside("unexpected shape");
763
+ const out = [];
764
+ for (const r of list) {
765
+ if (r && typeof r === "object" && typeof r.sha256 === "string" && HEX_RE2.test(r.sha256) && typeof r.id === "string" && typeof r.at === "string") {
766
+ out.push({ sha256: r.sha256, id: r.id, at: r.at });
767
+ } else {
768
+ warn("unexpected shape");
769
+ kept.push(r);
770
+ }
771
+ }
772
+ return out;
773
+ },
774
+ save(list) {
775
+ mkdirSync(dirname2(file), { recursive: true });
776
+ const tmp = `${file}.tmp`;
777
+ writeFileSync(tmp, `${JSON.stringify({ version: 1, revoked: [...list, ...kept] }, null, 2)}
778
+ `, "utf8");
779
+ renameSync(tmp, file);
780
+ }
781
+ };
782
+ }
783
+ function loadManagedServiceTokens(o) {
784
+ const seed = readSeed(o);
785
+ const store = typeof o.revocations === "string" ? jsonRevocationStore(o.revocations) : o.revocations;
786
+ const now = o.now ?? (() => /* @__PURE__ */ new Date());
787
+ const revoked = /* @__PURE__ */ new Map();
788
+ for (const r of store.load()) if (!revoked.has(r.sha256)) revoked.set(r.sha256, r);
789
+ const base = createServiceTokens(seed.map((s) => s.entry));
790
+ return {
791
+ verify(authorization, scope) {
792
+ const m = /^Bearer ([^\s]+)$/.exec(authorization ?? "");
793
+ if (m && TOKEN_RE.test(m[1]) && revoked.has(hashServiceToken(m[1]))) return { ok: false, status: 401 };
794
+ return base.verify(authorization, scope);
795
+ },
796
+ list: base.list,
797
+ views() {
798
+ return seed.map(({ entry, source }) => {
799
+ const r = revoked.get(entry.sha256);
800
+ const view = { id: entry.id, name: entry.name, scopes: [...entry.scopes], created: entry.created, source, revoked: !!r };
801
+ if (r) view.revokedAt = r.at;
802
+ return view;
803
+ });
804
+ },
805
+ revoke(id) {
806
+ const matches = seed.filter((s) => s.entry.id === id);
807
+ if (matches.length === 0) return false;
808
+ const at = now().toISOString();
809
+ const added = [];
810
+ for (const { entry } of matches) {
811
+ if (revoked.has(entry.sha256) || added.some((a) => a.sha256 === entry.sha256)) continue;
812
+ added.push({ sha256: entry.sha256, id: entry.id, at });
813
+ }
814
+ if (added.length > 0) {
815
+ store.save([...revoked.values(), ...added]);
816
+ for (const a of added) revoked.set(a.sha256, a);
817
+ }
818
+ return true;
819
+ }
820
+ };
728
821
  }
729
822
  function createServiceTokens(entries) {
730
823
  const byHash = /* @__PURE__ */ new Map();
@@ -755,6 +848,32 @@ function checkServiceRequest(get, o) {
755
848
  if (!r.ok) return { status: r.status, error: r.status === 401 ? "Unauthorized" : "Forbidden" };
756
849
  return null;
757
850
  }
851
+
852
+ // src/server/cross-site.ts
853
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
854
+ function originOf(value) {
855
+ try {
856
+ const url = new URL(value);
857
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : null;
858
+ } catch {
859
+ return null;
860
+ }
861
+ }
862
+ function isCrossSiteWrite(method, header, opts = {}) {
863
+ if (SAFE_METHODS.has(method.toUpperCase())) return false;
864
+ const site = header("sec-fetch-site")?.toLowerCase() || void 0;
865
+ if (site === "same-origin" || site === "none") return false;
866
+ const rawOrigin = header("origin") || void 0;
867
+ if (rawOrigin === void 0) return site !== void 0;
868
+ const origin = originOf(rawOrigin);
869
+ if (origin === null) return true;
870
+ for (const allowed of opts.allowedOrigins ?? []) {
871
+ if (originOf(allowed) === origin) return false;
872
+ }
873
+ if (site !== void 0) return true;
874
+ const host = header("host")?.toLowerCase();
875
+ return host === void 0 || new URL(origin).host !== host;
876
+ }
758
877
  export {
759
878
  ACTION_TOKEN_FIELD,
760
879
  INBOX_ACTION_HEADER,
@@ -780,11 +899,14 @@ export {
780
899
  inboxAction,
781
900
  inboxActionTarget,
782
901
  installProcessHandlers,
902
+ isCrossSiteWrite,
783
903
  isDirectLoopback,
784
904
  isInboxActionTarget,
785
905
  isInboxCall,
786
906
  isLoopback,
907
+ jsonRevocationStore,
787
908
  loadAppEnv,
909
+ loadManagedServiceTokens,
788
910
  loadServiceTokens,
789
911
  mintServiceToken,
790
912
  newActionToken,