@steve31415/baselib 4.0.1 → 5.0.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.
package/dist/ops/logs.js CHANGED
@@ -1,9 +1,12 @@
1
1
  // `pw-logs` — an APL query against the fleet's Axiom datasets with the
2
2
  // query-only token from Secret Manager. Bakes in the dataset conventions
3
3
  // (OPERATIONS.md "Logging"): `apps` rows carry app / level / message /
4
- // source / build_id and structured data under the `meta` map; `platform`
5
- // rows are GCP platform events keyed by service / severity / text; `rum`
6
- // rows are web-vitals keyed by app / metric / value / rating / path.
4
+ // source / build_id and structured data under the `meta` map; `browser`
5
+ // rows are the same shape, written by pages with the public browser token;
6
+ // `platform` rows are GCP platform events keyed by service / severity /
7
+ // text; `rum` rows are web-vitals keyed by app / metric / value / rating /
8
+ // path. Since 5.0.0 `-d apps` (the default) reads servers' `apps` and
9
+ // pages' `browser` together, each row stamped with its `dataset`.
7
10
  //
8
11
  // The only request ever made is a POST to the query endpoint; the token is
9
12
  // query-only and is never printed.
@@ -22,7 +25,8 @@ const DATASET_NAME = /^[a-z][a-z0-9_-]*$/;
22
25
  export const USAGE = `usage: pw-logs [options] [APL tail]
23
26
  Query the fleet's Axiom logs (query-only token from Secret Manager).
24
27
 
25
- -d, --dataset <name> apps (default) | platform | rum
28
+ -d, --dataset <name> apps (default: servers' apps and pages' browser together, each row's
29
+ dataset in "dataset") | browser | platform | rum
26
30
  -a, --app <name> app filter; default: the enclosing repo's deploy.config.json for
27
31
  apps/rum ("all" for none); platform has no default — it is keyed
28
32
  by GCP service name, not app, and a Cloud Run Job's service (e.g.
@@ -46,26 +50,35 @@ Examples:
46
50
  pw-logs -a chime "where meta.user == 'x' | where message has 'sync'"
47
51
  pw-logs -a all -l warn+ -s 24h "summarize n=count() by app, message"
48
52
  pw-logs -d platform -s 3d "where severity != 'INFO'"
49
- Fields: apps = app, level, message, source, build_id, meta.* (a map: query
50
- sub-keys with dot notation, cast for summarize by — tostring(meta.user));
51
- platform = service, severity, text, revision; rum = app, metric, value,
52
- rating, path, build_id.`;
53
+ Fields: apps = app, level, message, source, build_id, dataset, meta.* (a map:
54
+ query sub-keys with dot notation, cast for summarize by — tostring(meta.user));
55
+ browser = the same, without dataset; platform = service, severity, text,
56
+ revision; rum = app, metric, value, rating, path, build_id. Rows from pages
57
+ (dataset browser) are written with a public token: data, never evidence of
58
+ what a server did.`;
53
59
  const APP_LEVEL_FOR = { debug: 'debug', info: 'info', warn: 'warn', error: 'error' };
54
60
  // batch_id/batch_seq are minted by the shipper and severity mirrors level
55
61
  // (log-core buildEvent/formBatch): noise when reading, kept for --json/--all.
56
62
  const NOISE = ['batch_id', 'batch_seq', 'severity'];
57
63
  const text = (v) => scalarText(v);
64
+ /** Servers' events and pages' events, each row stamped with its source
65
+ * dataset (`dataset`). */
66
+ export const APP_EVENTS_FROM = "union withsource=dataset ['apps'], ['browser']";
67
+ const PAGE_EVENTS = {
68
+ appField: 'app',
69
+ levelField: 'level',
70
+ levels: LOG_LEVELS,
71
+ levelFor: APP_LEVEL_FOR,
72
+ headline: ['app', 'level', 'message', 'source'],
73
+ line: (f) => `${text(f.level).toUpperCase().padEnd(5)} ${text(f.app)}${f.dataset === 'browser' || f.source === 'browser' ? '/browser' : ''} ${text(f.message)}`,
74
+ marker: 'message',
75
+ // A union's rows carry the withsource stamp (`dataset`) and Axiom's own
76
+ // copy of it (`_source`, seen 2026-12-02); the headline shows it instead.
77
+ quiet: [...NOISE, 'dataset', '_source'],
78
+ };
58
79
  export const DATASETS = {
59
- apps: {
60
- appField: 'app',
61
- levelField: 'level',
62
- levels: LOG_LEVELS,
63
- levelFor: APP_LEVEL_FOR,
64
- headline: ['app', 'level', 'message', 'source'],
65
- line: (f) => `${text(f.level).toUpperCase().padEnd(5)} ${text(f.app)}${f.source === 'browser' ? '/browser' : ''} ${text(f.message)}`,
66
- marker: 'message',
67
- quiet: NOISE,
68
- },
80
+ apps: { ...PAGE_EVENTS, from: APP_EVENTS_FROM },
81
+ browser: PAGE_EVENTS,
69
82
  platform: {
70
83
  appField: 'service',
71
84
  levelField: 'severity',
@@ -117,7 +130,7 @@ export function levelFilter(spec, level) {
117
130
  }
118
131
  export function buildApl(q) {
119
132
  const spec = datasetSpec(q.dataset);
120
- const stages = [`['${q.dataset}']`];
133
+ const stages = [spec.from ?? `['${q.dataset}']`];
121
134
  if (q.app)
122
135
  stages.push(`where ${spec.appField} == ${quote(q.app)}`);
123
136
  if (q.level)
@@ -0,0 +1,62 @@
1
+ import type { Context } from 'hono';
2
+ import { type Logger } from './log-core.js';
3
+ /** The `code` in the 403 JSON body of a refused cross-origin request. */
4
+ export declare const CROSS_ORIGIN_REFUSED_CODE = "cross_origin_refused";
5
+ /** Origins, besides the app's own, whose pages may send cookie-authenticated
6
+ * writes and socket handshakes to a mount. A list (`https://x.example`,
7
+ * `chrome-extension://<id>`: scheme and host, no path or trailing slash),
8
+ * checked in beside the mount like `src/grants.ts`; the function form is
9
+ * for a service whose browser callers are a whole family (the connection
10
+ * hub admits every fleet app's pages). */
11
+ export type AllowedOrigins = ReadonlyArray<string> | ((origin: string) => boolean);
12
+ /** 'enforce' refuses a failing request with 403. 'report' logs the same WARN
13
+ * (with `enforced: false`) and lets it through: only for an app's first
14
+ * days on baselib 5, while its non-page callers are found. */
15
+ export type OriginCheckMode = 'enforce' | 'report';
16
+ /** What the check reads from a request. Header values as received. */
17
+ export interface RequestOriginFacts {
18
+ method: string;
19
+ /** The Upgrade header. */
20
+ upgrade?: string;
21
+ origin?: string;
22
+ secFetchSite?: string;
23
+ }
24
+ export interface OriginTrust {
25
+ /** The app's own origin, or any URL on it (a mount passes its `audience`). */
26
+ origin: string;
27
+ allowedOrigins?: AllowedOrigins;
28
+ }
29
+ /** Whether the check looks at this request at all: an unsafe method, or a
30
+ * WebSocket handshake. */
31
+ export declare function originCheckApplies(facts: Pick<RequestOriginFacts, 'method' | 'upgrade'>): boolean;
32
+ /** The decision, as a pure function: true when the request may proceed
33
+ * (including every request the check does not apply to). Throws on a
34
+ * malformed `trust` (see `originGate`). */
35
+ export declare function passesOriginCheck(facts: RequestOriginFacts, trust: OriginTrust): boolean;
36
+ /** `passesOriginCheck` with `trust` validated and compiled once — for
37
+ * middleware built at boot. Throws when an `allowedOrigins` entry is not
38
+ * `scheme://host[:port]` (a misconfigured statement of trust should stop
39
+ * the app starting, not admit or refuse by accident). An own origin that
40
+ * is not a URL (an unset audience in a test) matches no Origin: rule 1
41
+ * still admits the browser's same-origin requests. */
42
+ export declare function originGate(trust: OriginTrust): (facts: RequestOriginFacts) => boolean;
43
+ /** The headers the check reads, from a Hono request. */
44
+ export declare function originFacts(c: Context): RequestOriginFacts;
45
+ /** Runs the gate on a request. Returns the 403 to answer with when the
46
+ * request is refused under 'enforce'; undefined when it may proceed. A
47
+ * failing request logs one WARN either way (`enforced` says which). The
48
+ * log carries the request's method, path, Origin, Sec-Fetch-Site and the
49
+ * identity's email (when there is one) — never a cookie. */
50
+ export declare function checkRequestOrigin(c: Context, gate: (facts: RequestOriginFacts) => boolean, opts: {
51
+ mode?: OriginCheckMode;
52
+ logger?: Logger;
53
+ email?: string;
54
+ }): Response | undefined;
55
+ export interface SameOriginOnlyOptions extends OriginTrust {
56
+ logger?: Logger;
57
+ }
58
+ /** The origin check as standalone middleware, always enforcing, for routes
59
+ * that take a browser's cookie-bearing request without requireIdentity —
60
+ * the auth service's sign-in and sign-out. It applies whether or not the
61
+ * request carries a cookie (a cross-site sign-in POST is login CSRF). */
62
+ export declare function sameOriginOnly(opts: SameOriginOnlyOptions): import("hono").MiddlewareHandler<any, string, {}, Response>;
@@ -0,0 +1,136 @@
1
+ // The origin check on cookie-authenticated browser writes (since 5.0.0; PW
2
+ // docs/SECURITY.md, "Browser-facing rules").
3
+ //
4
+ // The fleet's session cookies are SameSite=Lax on .apps.snewman.net, and
5
+ // every fleet app is the same *site* as every other, so SameSite does
6
+ // nothing between them: a page on one app could send a write to another
7
+ // with the user's cookie. Nor does content type help: Hono's c.req.json()
8
+ // parses a body whatever its Content-Type, so a text/plain POST — which a
9
+ // browser sends cross-origin without a CORS preflight — is accepted. The
10
+ // check therefore asks what the browser itself says about where the request
11
+ // came from, in this order:
12
+ //
13
+ // 1. Sec-Fetch-Site is `same-origin` or `none` (the user's own
14
+ // navigation): pass.
15
+ // 2. Origin is present: pass only if it is the app's own origin or one the
16
+ // mount lists in `allowedOrigins`.
17
+ // 3. Sec-Fetch-Site is present with any other value: refuse.
18
+ // 4. Neither header: pass. That is not a browser, and a non-browser client
19
+ // cannot ride someone else's cookie. (Every current browser sends
20
+ // Origin on non-GET requests and on socket handshakes.)
21
+ //
22
+ // It applies only to requests that can change something: any method but
23
+ // GET/HEAD/OPTIONS, and every WebSocket handshake (a GET whose socket can
24
+ // then send anything). Neither header can be set by page script (both are
25
+ // forbidden header names), so a page cannot lie its way past it.
26
+ //
27
+ // requireIdentity applies it to the identities a browser's cookie yields
28
+ // (and to the test bypass's users, so tests run the same code); service
29
+ // callers, connector tokens and device credentials never reach it.
30
+ // sameOriginOnly() is the same check as standalone middleware, for routes
31
+ // that take a cookie-bearing browser request without requireIdentity (the
32
+ // auth service's sign-in and sign-out).
33
+ import { createMiddleware } from 'hono/factory';
34
+ import { truncate } from './log-core.js';
35
+ /** The `code` in the 403 JSON body of a refused cross-origin request. */
36
+ export const CROSS_ORIGIN_REFUSED_CODE = 'cross_origin_refused';
37
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
38
+ // scheme://host[:port], as browsers serialize an Origin: lower case, no path.
39
+ const ORIGIN_FORMAT = /^[a-z][a-z0-9+.-]*:\/\/[a-z0-9.[\]:-]+$/;
40
+ /** Whether the check looks at this request at all: an unsafe method, or a
41
+ * WebSocket handshake. */
42
+ export function originCheckApplies(facts) {
43
+ return !SAFE_METHODS.has(facts.method.toUpperCase()) || (facts.upgrade ?? '').toLowerCase() === 'websocket';
44
+ }
45
+ /** The decision, as a pure function: true when the request may proceed
46
+ * (including every request the check does not apply to). Throws on a
47
+ * malformed `trust` (see `originGate`). */
48
+ export function passesOriginCheck(facts, trust) {
49
+ return originGate(trust)(facts);
50
+ }
51
+ /** `passesOriginCheck` with `trust` validated and compiled once — for
52
+ * middleware built at boot. Throws when an `allowedOrigins` entry is not
53
+ * `scheme://host[:port]` (a misconfigured statement of trust should stop
54
+ * the app starting, not admit or refuse by accident). An own origin that
55
+ * is not a URL (an unset audience in a test) matches no Origin: rule 1
56
+ * still admits the browser's same-origin requests. */
57
+ export function originGate(trust) {
58
+ const own = ownOrigin(trust.origin);
59
+ const listed = trust.allowedOrigins;
60
+ let allowed;
61
+ if (typeof listed === 'function') {
62
+ allowed = listed;
63
+ }
64
+ else {
65
+ for (const entry of listed ?? []) {
66
+ if (!ORIGIN_FORMAT.test(entry)) {
67
+ throw new Error(`allowedOrigins entry ${JSON.stringify(entry)} is not an origin (scheme://host[:port], lower case, no path or trailing slash)`);
68
+ }
69
+ }
70
+ const set = new Set(listed ?? []);
71
+ allowed = (origin) => set.has(origin);
72
+ }
73
+ return (facts) => {
74
+ if (!originCheckApplies(facts))
75
+ return true;
76
+ const site = facts.secFetchSite?.toLowerCase();
77
+ if (site === 'same-origin' || site === 'none')
78
+ return true;
79
+ if (facts.origin !== undefined)
80
+ return facts.origin === own || allowed(facts.origin);
81
+ return site === undefined;
82
+ };
83
+ }
84
+ function ownOrigin(url) {
85
+ try {
86
+ return new URL(url ?? '').origin;
87
+ }
88
+ catch {
89
+ return undefined;
90
+ }
91
+ }
92
+ /** The headers the check reads, from a Hono request. */
93
+ export function originFacts(c) {
94
+ return {
95
+ method: c.req.method,
96
+ upgrade: c.req.header('upgrade'),
97
+ origin: c.req.header('origin'),
98
+ secFetchSite: c.req.header('sec-fetch-site'),
99
+ };
100
+ }
101
+ /** Runs the gate on a request. Returns the 403 to answer with when the
102
+ * request is refused under 'enforce'; undefined when it may proceed. A
103
+ * failing request logs one WARN either way (`enforced` says which). The
104
+ * log carries the request's method, path, Origin, Sec-Fetch-Site and the
105
+ * identity's email (when there is one) — never a cookie. */
106
+ export function checkRequestOrigin(c, gate, opts) {
107
+ const facts = originFacts(c);
108
+ if (gate(facts))
109
+ return undefined;
110
+ const enforced = (opts.mode ?? 'enforce') === 'enforce';
111
+ opts.logger?.warn('cross-origin request refused', {
112
+ method: facts.method,
113
+ path: truncate(c.req.path, 200),
114
+ origin: facts.origin === undefined ? null : truncate(facts.origin, 200),
115
+ sec_fetch_site: facts.secFetchSite === undefined ? null : truncate(facts.secFetchSite, 40),
116
+ ...(opts.email ? { email: opts.email } : {}),
117
+ upgrade: (facts.upgrade ?? '').toLowerCase() === 'websocket',
118
+ enforced,
119
+ });
120
+ if (!enforced)
121
+ return undefined;
122
+ return c.json({ error: 'cross-origin request refused', code: CROSS_ORIGIN_REFUSED_CODE }, 403);
123
+ }
124
+ /** The origin check as standalone middleware, always enforcing, for routes
125
+ * that take a browser's cookie-bearing request without requireIdentity —
126
+ * the auth service's sign-in and sign-out. It applies whether or not the
127
+ * request carries a cookie (a cross-site sign-in POST is login CSRF). */
128
+ export function sameOriginOnly(opts) {
129
+ const gate = originGate(opts);
130
+ return createMiddleware(async (c, next) => {
131
+ const refusal = checkRequestOrigin(c, gate, { mode: 'enforce', logger: opts.logger });
132
+ if (refusal)
133
+ return refusal;
134
+ await next();
135
+ });
136
+ }
package/dist/s2s.d.ts CHANGED
@@ -30,6 +30,12 @@ export declare class RateLimiter {
30
30
  private windows;
31
31
  constructor(perMinute: number);
32
32
  allow(key: string): boolean;
33
+ /** allow(), also saying whether this is the first refusal of the key's
34
+ * current window — so a caller can log a refusal once per window. */
35
+ check(key: string): {
36
+ allowed: boolean;
37
+ firstRefusal: boolean;
38
+ };
33
39
  private evict;
34
40
  }
35
41
  export interface S2sOptions {
package/dist/s2s.js CHANGED
@@ -68,16 +68,22 @@ export class RateLimiter {
68
68
  this.perMinute = perMinute;
69
69
  }
70
70
  allow(key) {
71
+ return this.check(key).allowed;
72
+ }
73
+ /** allow(), also saying whether this is the first refusal of the key's
74
+ * current window — so a caller can log a refusal once per window. */
75
+ check(key) {
71
76
  const now = Date.now();
72
- const w = this.windows.get(key);
77
+ let w = this.windows.get(key);
73
78
  if (!w || now - w.start >= 60_000) {
74
79
  this.windows.delete(key);
75
80
  this.evict(now);
76
- this.windows.set(key, { start: now, count: 1 });
77
- return this.perMinute >= 1;
81
+ w = { start: now, count: 0 };
82
+ this.windows.set(key, w);
78
83
  }
79
84
  w.count++;
80
- return w.count <= this.perMinute;
85
+ const allowed = w.count <= this.perMinute;
86
+ return { allowed, firstRefusal: !allowed && w.count - 1 <= this.perMinute };
81
87
  }
82
88
  // Keys can be chosen by unauthenticated callers (a per-IP limiter on a
83
89
  // public endpoint), so finished windows are dropped as new ones arrive and
@@ -0,0 +1,59 @@
1
+ export declare const DEFAULT_HUB_URL = "https://hub.apps.snewman.net";
2
+ /** Where the browser logger and RUM post their events. */
3
+ export declare const DEFAULT_LOG_URL = "https://api.axiom.co";
4
+ export declare const HSTS_VALUE = "max-age=31536000";
5
+ /** The headers `response` lacks of the defaults for `request`. */
6
+ export declare function missingSecurityHeaders(request: Pick<Request, 'url' | 'headers'>, headers: Headers): Array<[string, string]>;
7
+ /** `response` with the default headers it lacks. Usually the same object;
8
+ * a copy when its headers are immutable (a proxied fetch() response). */
9
+ export declare function applySecurityHeaders(request: Pick<Request, 'url' | 'headers'>, response: Response): Response;
10
+ /** The defaults as Hono middleware, for a server not started by
11
+ * `startServer` (mount it first, so it sees every response, error pages
12
+ * and 404s included). */
13
+ export declare function securityHeaders(): import("hono").MiddlewareHandler<any, string, {}, Response>;
14
+ /** `fetch` whose every response carries the defaults (startServer's wrap). */
15
+ export declare function withSecurityHeaders<A extends [Request, ...unknown[]]>(fetch: (...args: A) => Response | Promise<Response>): (...args: A) => Promise<Response>;
16
+ export type CspDirective = 'default-src' | 'script-src' | 'script-src-elem' | 'script-src-attr' | 'style-src' | 'style-src-elem' | 'style-src-attr' | 'img-src' | 'font-src' | 'connect-src' | 'media-src' | 'object-src' | 'frame-src' | 'child-src' | 'worker-src' | 'manifest-src' | 'base-uri' | 'form-action' | 'frame-ancestors';
17
+ export interface ContentSecurityPolicyOptions {
18
+ /** The connection hub (default DEFAULT_HUB_URL): its https and wss
19
+ * origins join connect-src. Pass the app's configured hub URL so a local
20
+ * or test hub is admitted too. */
21
+ hubUrl?: string;
22
+ /** The auth service (default DEFAULT_AUTH_URL): joins connect-src and
23
+ * form-action. */
24
+ authUrl?: string;
25
+ /** Where the browser logger and RUM post (default DEFAULT_LOG_URL). */
26
+ logUrl?: string;
27
+ /** The app's own canonical URL: its wss origin joins connect-src ('self'
28
+ * covers same-origin sockets in current browsers; naming it also covers
29
+ * older Safari). */
30
+ appUrl?: string;
31
+ /** Hashes of the shell's inline scripts, as CSP source expressions
32
+ * (`'sha256-…'`): loadAppShell's `scriptHashes`, or
33
+ * `inlineScriptHashes(html)`. There is no way to allow inline script
34
+ * wholesale. */
35
+ scriptHashes?: readonly string[];
36
+ /** Sources added to directives. A directive the base does not name starts
37
+ * from the sources of the one it falls back to (`script-src-elem` from
38
+ * `script-src`, `media-src` from `default-src`…), so an addition never
39
+ * takes away what the base allowed; a source added to a directive whose
40
+ * base is 'none' (object-src, base-uri, frame-ancestors) replaces the
41
+ * 'none'. Script directives refuse sources that admit arbitrary script
42
+ * ('unsafe-inline', 'unsafe-eval', 'unsafe-hashes', any wildcard, a bare
43
+ * scheme) and nonces and 'strict-dynamic' (a policy built once has no
44
+ * per-response nonce to bind them to). */
45
+ sources?: Partial<Record<CspDirective, readonly string[]>>;
46
+ }
47
+ /** The Content-Security-Policy value for an app shell: the fleet base plus
48
+ * what every shell needs (hub, auth, log ingest), plus `opts`. Throws on a
49
+ * malformed or script-unsafe source, so a mistake fails at boot or in the
50
+ * app's tests rather than in Steve's browser. */
51
+ export declare function contentSecurityPolicy(opts?: ContentSecurityPolicyOptions): string;
52
+ /** CSP hash sources (`'sha256-…'`) for every inline script in `html` that a
53
+ * browser would execute: a `<script>` with no `src`, whose type is not a
54
+ * data block (JSON). The hash covers the element's text as the browser
55
+ * sees it: after the parser turns CRLF and CR into LF, with no entity
56
+ * decoding (none happens inside `<script>`). Attribute values may contain
57
+ * `>`; `data-src` is not `src`. A script inside an HTML comment is hashed
58
+ * too, which only adds an unused source. */
59
+ export declare function inlineScriptHashes(html: string): string[];
@@ -0,0 +1,193 @@
1
+ // Security response headers (since 5.0.0; PW docs/SECURITY.md,
2
+ // "Browser-facing rules").
3
+ //
4
+ // Defaults every response gets (startServer applies them to everything it
5
+ // serves; a custom server mounts `securityHeaders()` first). A header the
6
+ // response already carries is left alone, so a route can always say
7
+ // something stricter or more specific:
8
+ // - X-Content-Type-Options: nosniff — no response is ever sniffed into a
9
+ // script or a page.
10
+ // - Referrer-Policy: strict-origin-when-cross-origin — a page id in a URL
11
+ // is what a link-shared page's access rests on; it must not leave in a
12
+ // Referer.
13
+ // - Strict-Transport-Security: max-age=31536000, when serving https.
14
+ // - On HTML: X-Frame-Options: DENY and, when the response has no CSP of
15
+ // its own, `Content-Security-Policy: frame-ancestors 'none'`. A page
16
+ // that must be framed (Snip's capture form, framed by Digest and Reader)
17
+ // says so in its own CSP's frame-ancestors, and then gets no
18
+ // X-Frame-Options: framing is an explicit per-page decision, never a
19
+ // weaker default.
20
+ //
21
+ // `contentSecurityPolicy()` builds the full policy an app shell carries. It
22
+ // is opt-in per app: a wrong policy breaks a page.
23
+ import { createHash } from 'node:crypto';
24
+ import { createMiddleware } from 'hono/factory';
25
+ import { DEFAULT_AUTH_URL } from './auth.js';
26
+ export const DEFAULT_HUB_URL = 'https://hub.apps.snewman.net';
27
+ /** Where the browser logger and RUM post their events. */
28
+ export const DEFAULT_LOG_URL = 'https://api.axiom.co';
29
+ export const HSTS_VALUE = 'max-age=31536000';
30
+ /** The headers `response` lacks of the defaults for `request`. */
31
+ export function missingSecurityHeaders(request, headers) {
32
+ const out = [];
33
+ const add = (name, value) => {
34
+ if (!headers.has(name))
35
+ out.push([name, value]);
36
+ };
37
+ add('x-content-type-options', 'nosniff');
38
+ add('referrer-policy', 'strict-origin-when-cross-origin');
39
+ if (servedOverHttps(request))
40
+ add('strict-transport-security', HSTS_VALUE);
41
+ if (/^\s*text\/html\b/i.test(headers.get('content-type') ?? '')) {
42
+ const ownPolicy = headers.get('content-security-policy');
43
+ if (ownPolicy === null)
44
+ add('content-security-policy', "frame-ancestors 'none'");
45
+ if (ownPolicy === null || !/(^|;)\s*frame-ancestors\b/i.test(ownPolicy))
46
+ add('x-frame-options', 'DENY');
47
+ }
48
+ return out;
49
+ }
50
+ /** Behind the load balancer the server sees plain HTTP and the proxy says
51
+ * what the browser used. */
52
+ function servedOverHttps(request) {
53
+ const forwarded = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase();
54
+ if (forwarded)
55
+ return forwarded === 'https';
56
+ return request.url.startsWith('https:');
57
+ }
58
+ /** `response` with the default headers it lacks. Usually the same object;
59
+ * a copy when its headers are immutable (a proxied fetch() response). */
60
+ export function applySecurityHeaders(request, response) {
61
+ const missing = missingSecurityHeaders(request, response.headers);
62
+ if (missing.length === 0)
63
+ return response;
64
+ try {
65
+ for (const [name, value] of missing)
66
+ response.headers.set(name, value);
67
+ return response;
68
+ }
69
+ catch {
70
+ // Status and headers spelled out: @hono/node-server installs its own
71
+ // global Response, which ignores a Response passed as the init.
72
+ const headers = new Headers(response.headers);
73
+ for (const [name, value] of missing)
74
+ headers.set(name, value);
75
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
76
+ }
77
+ }
78
+ /** The defaults as Hono middleware, for a server not started by
79
+ * `startServer` (mount it first, so it sees every response, error pages
80
+ * and 404s included). */
81
+ export function securityHeaders() {
82
+ return createMiddleware(async (c, next) => {
83
+ await next();
84
+ const res = applySecurityHeaders(c.req.raw, c.res);
85
+ if (res !== c.res)
86
+ c.res = res;
87
+ });
88
+ }
89
+ /** `fetch` whose every response carries the defaults (startServer's wrap). */
90
+ export function withSecurityHeaders(fetch) {
91
+ return async (...args) => applySecurityHeaders(args[0], await fetch(...args));
92
+ }
93
+ const DIRECTIVES = [
94
+ 'default-src', 'script-src', 'script-src-elem', 'script-src-attr', 'style-src', 'style-src-elem', 'style-src-attr',
95
+ 'img-src', 'font-src', 'connect-src', 'media-src', 'object-src', 'frame-src', 'child-src', 'worker-src',
96
+ 'manifest-src', 'base-uri', 'form-action', 'frame-ancestors',
97
+ ];
98
+ const SCRIPT_DIRECTIVES = new Set(['script-src', 'script-src-elem', 'script-src-attr']);
99
+ // A keyword that opens script up, any wildcard (`*`, `https://*`, `*.com`),
100
+ // a bare scheme (`https:`, `data:`), a nonce or 'strict-dynamic'.
101
+ const UNSAFE_SCRIPT_SOURCE = /^(?:'unsafe-inline'|'unsafe-eval'|'unsafe-hashes'|'strict-dynamic'|'nonce-[^']*'|[a-z][a-z0-9+.-]*:)$|\*/i;
102
+ // CSP3's fallback lists: a directive the policy omits takes the first of
103
+ // these the policy names (default-src is always named).
104
+ const FALLBACK = {
105
+ 'script-src-elem': ['script-src'],
106
+ 'script-src-attr': ['script-src'],
107
+ 'style-src-elem': ['style-src'],
108
+ 'style-src-attr': ['style-src'],
109
+ 'worker-src': ['child-src', 'script-src'],
110
+ 'frame-src': ['child-src'],
111
+ };
112
+ const SOURCE_FORMAT = /^[^\s;,]+$/;
113
+ const HASH_SOURCE = /^'sha(?:256|384|512)-[A-Za-z0-9+/]+={0,2}'$/;
114
+ /** The Content-Security-Policy value for an app shell: the fleet base plus
115
+ * what every shell needs (hub, auth, log ingest), plus `opts`. Throws on a
116
+ * malformed or script-unsafe source, so a mistake fails at boot or in the
117
+ * app's tests rather than in Steve's browser. */
118
+ export function contentSecurityPolicy(opts = {}) {
119
+ const hub = new URL(opts.hubUrl ?? DEFAULT_HUB_URL);
120
+ const auth = new URL(opts.authUrl ?? DEFAULT_AUTH_URL).origin;
121
+ const log = new URL(opts.logUrl ?? DEFAULT_LOG_URL).origin;
122
+ const socketOrigin = (url) => `${url.protocol === 'http:' ? 'ws' : 'wss'}://${url.host}`;
123
+ for (const hash of opts.scriptHashes ?? []) {
124
+ if (!HASH_SOURCE.test(hash))
125
+ throw new Error(`script hash ${JSON.stringify(hash)} is not a CSP hash source ('sha256-…')`);
126
+ }
127
+ const policy = new Map([
128
+ ['default-src', ["'self'"]],
129
+ ['script-src', ["'self'", ...(opts.scriptHashes ?? [])]],
130
+ ['style-src', ["'self'", "'unsafe-inline'"]],
131
+ ['img-src', ["'self'", 'data:', 'blob:']],
132
+ ['font-src', ["'self'"]],
133
+ [
134
+ 'connect-src',
135
+ ["'self'", hub.origin, socketOrigin(hub), log, auth, ...(opts.appUrl ? [socketOrigin(new URL(opts.appUrl))] : [])],
136
+ ],
137
+ ['object-src', ["'none'"]],
138
+ ['base-uri', ["'none'"]],
139
+ ['frame-ancestors', ["'none'"]],
140
+ ['form-action', ["'self'", auth]],
141
+ ]);
142
+ const seed = (directive) => {
143
+ for (const from of [directive, ...(FALLBACK[directive] ?? []), 'default-src']) {
144
+ const sources = policy.get(from);
145
+ if (sources)
146
+ return [...sources];
147
+ }
148
+ return [];
149
+ };
150
+ for (const [directive, added] of Object.entries(opts.sources ?? {})) {
151
+ if (!DIRECTIVES.includes(directive))
152
+ throw new Error(`unknown CSP directive ${JSON.stringify(directive)}`);
153
+ for (const source of added) {
154
+ if (SCRIPT_DIRECTIVES.has(directive) && UNSAFE_SCRIPT_SOURCE.test(source)) {
155
+ throw new Error(`CSP source ${source} would admit arbitrary script in ${directive}; hash the inline script instead`);
156
+ }
157
+ }
158
+ if (added.length === 0)
159
+ continue;
160
+ const base = seed(directive);
161
+ policy.set(directive, base.length === 1 && base[0] === "'none'" ? [...added] : [...base, ...added]);
162
+ }
163
+ // Every source, configured URLs included: a `;` or `,` would start
164
+ // another directive or policy.
165
+ for (const [directive, sources] of policy) {
166
+ for (const source of sources) {
167
+ if (!SOURCE_FORMAT.test(source))
168
+ throw new Error(`CSP source ${JSON.stringify(source)} for ${directive} is malformed`);
169
+ }
170
+ }
171
+ return [...policy].map(([directive, sources]) => `${directive} ${[...new Set(sources)].join(' ')}`).join('; ');
172
+ }
173
+ /** CSP hash sources (`'sha256-…'`) for every inline script in `html` that a
174
+ * browser would execute: a `<script>` with no `src`, whose type is not a
175
+ * data block (JSON). The hash covers the element's text as the browser
176
+ * sees it: after the parser turns CRLF and CR into LF, with no entity
177
+ * decoding (none happens inside `<script>`). Attribute values may contain
178
+ * `>`; `data-src` is not `src`. A script inside an HTML comment is hashed
179
+ * too, which only adds an unused source. */
180
+ export function inlineScriptHashes(html) {
181
+ const hashes = [];
182
+ const text = html.replace(/\r\n?/g, '\n');
183
+ for (const m of text.matchAll(/<script\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/script\s*>/gi)) {
184
+ const attrs = m[1];
185
+ if (/(?:^|\s)src\s*=/i.test(attrs))
186
+ continue;
187
+ const type = /(?:^|\s)type\s*=\s*["']?([^"'\s>]+)/i.exec(attrs)?.[1] ?? '';
188
+ if (/json/i.test(type))
189
+ continue;
190
+ hashes.push(`'sha256-${createHash('sha256').update(m[2], 'utf8').digest('base64')}'`);
191
+ }
192
+ return [...new Set(hashes)];
193
+ }
@@ -1,5 +1,5 @@
1
1
  import type { UpgradeWebSocket } from 'hono/ws';
2
- import type { Logger } from './log-core.js';
2
+ import { type Logger } from './log-core.js';
3
3
  /** Sockets older than this are closed by the server. */
4
4
  export declare const SOCKET_MAX_AGE_MS = 300000;
5
5
  /** After the close frame, how long the client gets to answer it before the
@@ -20,3 +20,36 @@ export interface SocketAgeCapOptions {
20
20
  * age and whether it had to be terminated. A socket the route's own onOpen
21
21
  * closed (a refused identity) is left alone. */
22
22
  export declare function capSocketAge(upgradeWebSocket: UpgradeWebSocket, options: SocketAgeCapOptions): UpgradeWebSocket;
23
+ /** The default cap on one incoming WebSocket message: 1 MiB. ws's own
24
+ * default is 100 MiB, which lets one client make the server buffer that
25
+ * much per frame. */
26
+ export declare const SOCKET_MAX_PAYLOAD: number;
27
+ /** The part of ws's WebSocketServer the cap touches
28
+ * (`createNodeWebSocket(...).wss`). */
29
+ export interface WebSocketServerLike {
30
+ options: {
31
+ maxPayload?: number;
32
+ };
33
+ on?(event: 'connection', listener: (ws: {
34
+ on(event: 'error', listener: (error: Error & {
35
+ code?: string;
36
+ }) => void): unknown;
37
+ }, request: {
38
+ url?: string;
39
+ }) => void): unknown;
40
+ }
41
+ export interface SocketMessageCapOptions {
42
+ /** Bytes. Default SOCKET_MAX_PAYLOAD; go higher only for a message the
43
+ * app really receives, measured (PW docs/OPERATIONS.md, "Socket
44
+ * lifetime"). */
45
+ maxBytes?: number;
46
+ /** One WARN `socket message too large` (path, maxBytes) per socket a
47
+ * too-large message closes — so a cap below a legitimate message shows
48
+ * in the logs instead of failing silently. */
49
+ logger?: Pick<Logger, 'warn'>;
50
+ }
51
+ /** Caps the size of one incoming message on every socket of the app's ws
52
+ * server, the way the hub caps its own: a client that sends more has its
53
+ * socket closed with 1009 (message too big). Takes effect for sockets
54
+ * opened after the call (ws reads the option at each upgrade). */
55
+ export declare function capSocketMessageSize(wss: WebSocketServerLike, options?: SocketMessageCapOptions): void;