@steve31415/baselib 5.1.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
1
+ /**
2
+ * - `shown`: a type a browser shows in a tab or plays — PDF, raster images,
3
+ * audio, video — answered as that type, `inline`.
4
+ * - `text`: declared as plain text (or a plain-text file name), valid UTF-8
5
+ * with no NUL — `text/plain; charset=utf-8`, `inline`.
6
+ * - `embedded`: SVG — `image/svg+xml`, `attachment`. An `<img>` ignores the
7
+ * disposition and never runs an SVG's script; a document load downloads.
8
+ * - `download`: everything else — `application/octet-stream`, `attachment`.
9
+ */
10
+ export type OutsideClass = 'shown' | 'text' | 'embedded' | 'download';
11
+ export interface OutsideType {
12
+ contentType: string;
13
+ disposition: 'inline' | 'attachment';
14
+ class: OutsideClass;
15
+ }
16
+ /** The leading bytes `decideOutsideType` needs for every class but text. */
17
+ export declare const OUTSIDE_SNIFF_BYTES = 4096;
18
+ /** Above this the text check is not run and the file downloads. */
19
+ export declare const TEXT_CHECK_MAX_BYTES: number;
20
+ /**
21
+ * Decide how bytes an outsider chose may be answered. `bytes` must be the
22
+ * whole file for the text class (a file of at most TEXT_CHECK_MAX_BYTES);
23
+ * the other classes need only the first OUTSIDE_SNIFF_BYTES, and a prefix
24
+ * of a text file decides `download`. `declaredType` and `filename` are the
25
+ * sender's and only ever narrow the answer: a label never makes bytes
26
+ * `shown`.
27
+ */
28
+ export declare function decideOutsideType(bytes: Uint8Array, declaredType?: string, filename?: string): OutsideType;
29
+ /**
30
+ * A `Content-Disposition` value. The file name (the sender's) goes in an
31
+ * ASCII `filename` with every risky character replaced, plus the exact name
32
+ * percent-encoded in `filename*` (RFC 6266), so no name can add a parameter
33
+ * or end the header.
34
+ */
35
+ export declare function contentDisposition(disposition: 'inline' | 'attachment', filename?: string | null): string;
36
+ /** What a signer must sign: a read of `bucket`/`key` valid from
37
+ * `accessibleAt` to `expires`, whose response carries `responseType` and
38
+ * `responseDisposition` whatever the object says. */
39
+ export interface LinkSignRequest {
40
+ bucket: string;
41
+ key: string;
42
+ accessibleAt: Date;
43
+ expires: Date;
44
+ responseType: string;
45
+ responseDisposition: string;
46
+ }
47
+ export type LinkSigner = (request: LinkSignRequest) => Promise<string>;
48
+ /** The part of `@google-cloud/storage`'s `Storage` a GCS signer needs. */
49
+ export interface GcsSignerStorage {
50
+ bucket(name: string): {
51
+ file(name: string): {
52
+ getSignedUrl(config: {
53
+ version: 'v4';
54
+ action: 'read';
55
+ accessibleAt: Date;
56
+ expires: Date;
57
+ responseType: string;
58
+ responseDisposition: string;
59
+ }): Promise<[string] | string[]>;
60
+ };
61
+ };
62
+ }
63
+ /**
64
+ * V4 signed links through `@google-cloud/storage`. On Cloud Run there is no
65
+ * key on disk: the library signs through IAM `signBlob`, which needs the
66
+ * service account to hold `roles/iam.serviceAccountTokenCreator` on itself
67
+ * (PW docs/SECURITY.md, "Signed storage URLs").
68
+ */
69
+ export declare function gcsLinkSigner(storage: GcsSignerStorage): LinkSigner;
70
+ export interface SignedLink {
71
+ url: string;
72
+ expiresAt: Date;
73
+ /** For the redirect's `Cache-Control: private, max-age=`: the link's
74
+ * remaining life less a ten-minute margin, never negative. */
75
+ maxAgeSeconds: number;
76
+ }
77
+ export interface MintRequest {
78
+ bucket: string;
79
+ key: string;
80
+ /** The decided type (`decideOutsideType`), recorded when the object was
81
+ * stored. Required: a link is never minted for an undecided type. */
82
+ type: OutsideType;
83
+ /** The sender's file name, for the disposition. */
84
+ filename?: string | null;
85
+ /** `attachment` whatever the class (a Download button). */
86
+ download?: boolean;
87
+ }
88
+ export interface SignedLinkMinterOptions {
89
+ sign: LinkSigner;
90
+ now?: () => number;
91
+ /** Mints inside one window share `accessibleAt` and so give one URL. */
92
+ windowMs?: number;
93
+ /** A link lives this long from its window's start. */
94
+ lifetimeMs?: number;
95
+ /** Cached links kept per instance before stale windows are dropped. */
96
+ maxCached?: number;
97
+ }
98
+ export declare const SIGNED_LINK_WINDOW_MS: number;
99
+ export declare const SIGNED_LINK_LIFETIME_MS: number;
100
+ export interface SignedLinkMinter {
101
+ mint(request: MintRequest): Promise<SignedLink>;
102
+ }
103
+ /**
104
+ * Links that live `lifetimeMs` (12 h) from the start of the current
105
+ * `windowMs` (1 h) window: `accessibleAt` is the window start, so V4's
106
+ * `X-Goog-Date` and `X-Goog-Expires` — both in the URL — are the same for
107
+ * every mint in the window, and a link always has at least
108
+ * `lifetimeMs - windowMs` left. Cached per instance, so most mints skip the
109
+ * signing call.
110
+ */
111
+ export declare function createSignedLinkMinter(opts: SignedLinkMinterOptions): SignedLinkMinter;
112
+ export interface MemoryLinkCheck {
113
+ bucket: string;
114
+ key: string;
115
+ responseType: string;
116
+ responseDisposition: string;
117
+ }
118
+ export interface MemoryLinkSigner {
119
+ sign: LinkSigner;
120
+ /** The signed request a URL carries, or null when its signature is wrong
121
+ * or it is outside its validity. The app's dev route answers the object
122
+ * with exactly these type and disposition. */
123
+ check(url: string | URL): MemoryLinkCheck | null;
124
+ }
125
+ /**
126
+ * Signed links for tests and local dev, where there is no storage site and
127
+ * no signing key: URLs under `baseUrl` + `path` (a route the app mounts only
128
+ * with its in-memory store, public like a real signed link), HMAC-signed
129
+ * with a per-process key so a holder can change neither the object, the
130
+ * validity, nor the pinned type and disposition.
131
+ */
132
+ export declare function createMemoryLinkSigner(opts: {
133
+ baseUrl: string;
134
+ path: string;
135
+ now?: () => number;
136
+ }): MemoryLinkSigner;
@@ -0,0 +1,275 @@
1
+ // Outside bytes: files an outsider chose (an email attachment, a Slack or
2
+ // WhatsApp file, an upload, a fetched page). PW docs/SECURITY.md
3
+ // browser-facing rule 5: such bytes never load as a document from an app
4
+ // origin; they reach the browser through a signed Cloud Storage link whose
5
+ // type and disposition are pinned (PW plans/outside-bytes-and-radar-
6
+ // attachments.md). Since 5.2.0.
7
+ //
8
+ // - `decideOutsideType` decides how bytes may be answered, from the bytes
9
+ // themselves; the sender's label and file name only ever narrow it.
10
+ // - `contentDisposition` builds a header value whose file name cannot break
11
+ // out of it.
12
+ // - `createSignedLinkMinter` mints links that live `lifetimeMs` from the
13
+ // start of a `windowMs` window, so every mint of one object inside a
14
+ // window gives the same URL (a browser can cache it), and caches them per
15
+ // instance. It requires a decided type, and pins it and the disposition
16
+ // in the signature.
17
+ // - `gcsLinkSigner` signs with `@google-cloud/storage` (structurally typed:
18
+ // baselib does not depend on it). `createMemoryLinkSigner` is the fake for
19
+ // tests and local dev: HMAC-signed URLs under a dev route of the app's own.
20
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
21
+ /** The leading bytes `decideOutsideType` needs for every class but text. */
22
+ export const OUTSIDE_SNIFF_BYTES = 4096;
23
+ /** Above this the text check is not run and the file downloads. */
24
+ export const TEXT_CHECK_MAX_BYTES = 1024 * 1024;
25
+ const OCTET = { contentType: 'application/octet-stream', disposition: 'attachment', class: 'download' };
26
+ const shown = (contentType) => ({ contentType, disposition: 'inline', class: 'shown' });
27
+ function startsWith(bytes, sig, offset = 0) {
28
+ if (bytes.length < offset + sig.length)
29
+ return false;
30
+ for (let i = 0; i < sig.length; i++)
31
+ if (bytes[offset + i] !== sig[i])
32
+ return false;
33
+ return true;
34
+ }
35
+ function ascii(bytes, start, end) {
36
+ let s = '';
37
+ for (let i = start; i < Math.min(end, bytes.length); i++)
38
+ s += String.fromCharCode(bytes[i]);
39
+ return s;
40
+ }
41
+ const MP4_BRANDS = ['isom', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'mp41', 'mp42', 'avc1', 'dash', 'M4V ', 'mp71'];
42
+ /** ISO base media file (`ftyp` box): the major brand says what it is. */
43
+ function isoBmffType(bytes) {
44
+ if (ascii(bytes, 4, 8) !== 'ftyp')
45
+ return null;
46
+ const major = ascii(bytes, 8, 12);
47
+ if (major === 'avif' || major === 'avis')
48
+ return 'image/avif';
49
+ if (major === 'M4A ' || major === 'M4B ')
50
+ return 'audio/mp4';
51
+ if (major === 'qt ')
52
+ return 'video/quicktime';
53
+ // HEIC and other image brands are not shown by browsers: download.
54
+ if (MP4_BRANDS.includes(major))
55
+ return 'video/mp4';
56
+ return null;
57
+ }
58
+ /** The type of a binary format a browser shows, from its signature. */
59
+ function binaryType(bytes) {
60
+ if (startsWith(bytes, [0x25, 0x50, 0x44, 0x46, 0x2d]))
61
+ return 'application/pdf'; // %PDF-
62
+ if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
63
+ return 'image/png';
64
+ if (startsWith(bytes, [0xff, 0xd8, 0xff]))
65
+ return 'image/jpeg';
66
+ const head6 = ascii(bytes, 0, 6);
67
+ if (head6 === 'GIF87a' || head6 === 'GIF89a')
68
+ return 'image/gif';
69
+ if (ascii(bytes, 0, 4) === 'RIFF') {
70
+ const form = ascii(bytes, 8, 12);
71
+ if (form === 'WEBP')
72
+ return 'image/webp';
73
+ if (form === 'WAVE')
74
+ return 'audio/wav';
75
+ return null;
76
+ }
77
+ if (ascii(bytes, 0, 4) === 'OggS')
78
+ return 'audio/ogg';
79
+ if (ascii(bytes, 0, 3) === 'ID3')
80
+ return 'audio/mpeg';
81
+ if (bytes.length >= 2 && bytes[0] === 0xff) {
82
+ // ADTS AAC: sync 0xFFF, layer 00. MPEG audio: sync 0xFFE, layer != 00.
83
+ if ((bytes[1] & 0xf6) === 0xf0)
84
+ return 'audio/aac';
85
+ if ((bytes[1] & 0xe0) === 0xe0 && (bytes[1] & 0x06) !== 0)
86
+ return 'audio/mpeg';
87
+ }
88
+ if (startsWith(bytes, [0x1a, 0x45, 0xdf, 0xa3])) {
89
+ // EBML: WebM only (Matroska in general is not shown).
90
+ return ascii(bytes, 0, 64).includes('webm') ? 'video/webm' : null;
91
+ }
92
+ return isoBmffType(bytes);
93
+ }
94
+ const SVG_ROOT = /^\uFEFF?\s*(<\?xml[^>]*\?>\s*)?((<!--[\s\S]*?-->|<!DOCTYPE[^>]*>)\s*)*<svg[\s>/]/i;
95
+ function looksLikeSvg(bytes) {
96
+ // The root element is near the start; the non-fatal decoder drops a
97
+ // multi-byte character cut at the end of the slice.
98
+ return SVG_ROOT.test(new TextDecoder('utf-8').decode(bytes.subarray(0, OUTSIDE_SNIFF_BYTES)));
99
+ }
100
+ const TEXT_EXTENSIONS = /\.(txt|md|csv|log)$/i;
101
+ /** Declared text types never shown as text: markup, and calendar invites
102
+ * (`.ics` downloads). */
103
+ const NOT_SHOWN_AS_TEXT = /^text\/(html|xml|xsl|vtt|javascript|ecmascript|css|calendar)\b/i;
104
+ function declaredText(declaredType, filename) {
105
+ const t = declaredType.trim().toLowerCase();
106
+ if (t.startsWith('text/'))
107
+ return !NOT_SHOWN_AS_TEXT.test(t);
108
+ return TEXT_EXTENSIONS.test(filename);
109
+ }
110
+ function isUtf8(bytes) {
111
+ try {
112
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes);
113
+ return true;
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ /**
120
+ * Decide how bytes an outsider chose may be answered. `bytes` must be the
121
+ * whole file for the text class (a file of at most TEXT_CHECK_MAX_BYTES);
122
+ * the other classes need only the first OUTSIDE_SNIFF_BYTES, and a prefix
123
+ * of a text file decides `download`. `declaredType` and `filename` are the
124
+ * sender's and only ever narrow the answer: a label never makes bytes
125
+ * `shown`.
126
+ */
127
+ export function decideOutsideType(bytes, declaredType = '', filename = '') {
128
+ const binary = binaryType(bytes);
129
+ if (binary)
130
+ return shown(binary);
131
+ if (looksLikeSvg(bytes))
132
+ return { contentType: 'image/svg+xml', disposition: 'attachment', class: 'embedded' };
133
+ if (declaredText(declaredType, filename) && bytes.length <= TEXT_CHECK_MAX_BYTES && !bytes.includes(0) && isUtf8(bytes)) {
134
+ return { contentType: 'text/plain; charset=utf-8', disposition: 'inline', class: 'text' };
135
+ }
136
+ return OCTET;
137
+ }
138
+ // ---- Content-Disposition ----
139
+ /**
140
+ * A `Content-Disposition` value. The file name (the sender's) goes in an
141
+ * ASCII `filename` with every risky character replaced, plus the exact name
142
+ * percent-encoded in `filename*` (RFC 6266), so no name can add a parameter
143
+ * or end the header.
144
+ */
145
+ export function contentDisposition(disposition, filename) {
146
+ const name = (filename ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim();
147
+ if (!name)
148
+ return disposition;
149
+ const fallback = name.replace(/[^\x20-\x7e]|["\\;%]/g, '_');
150
+ const encoded = encodeURIComponent(name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
151
+ return `${disposition}; filename="${fallback}"; filename*=UTF-8''${encoded}`;
152
+ }
153
+ /**
154
+ * V4 signed links through `@google-cloud/storage`. On Cloud Run there is no
155
+ * key on disk: the library signs through IAM `signBlob`, which needs the
156
+ * service account to hold `roles/iam.serviceAccountTokenCreator` on itself
157
+ * (PW docs/SECURITY.md, "Signed storage URLs").
158
+ */
159
+ export function gcsLinkSigner(storage) {
160
+ return async (r) => {
161
+ const [url] = await storage.bucket(r.bucket).file(r.key).getSignedUrl({
162
+ version: 'v4',
163
+ action: 'read',
164
+ accessibleAt: r.accessibleAt,
165
+ expires: r.expires,
166
+ responseType: r.responseType,
167
+ responseDisposition: r.responseDisposition,
168
+ });
169
+ return url;
170
+ };
171
+ }
172
+ export const SIGNED_LINK_WINDOW_MS = 60 * 60 * 1000;
173
+ export const SIGNED_LINK_LIFETIME_MS = 12 * 60 * 60 * 1000;
174
+ const MAX_AGE_MARGIN_S = 600;
175
+ /**
176
+ * Links that live `lifetimeMs` (12 h) from the start of the current
177
+ * `windowMs` (1 h) window: `accessibleAt` is the window start, so V4's
178
+ * `X-Goog-Date` and `X-Goog-Expires` — both in the URL — are the same for
179
+ * every mint in the window, and a link always has at least
180
+ * `lifetimeMs - windowMs` left. Cached per instance, so most mints skip the
181
+ * signing call.
182
+ */
183
+ export function createSignedLinkMinter(opts) {
184
+ const now = opts.now ?? Date.now;
185
+ const windowMs = opts.windowMs ?? SIGNED_LINK_WINDOW_MS;
186
+ const lifetimeMs = opts.lifetimeMs ?? SIGNED_LINK_LIFETIME_MS;
187
+ const maxCached = opts.maxCached ?? 2000;
188
+ if (!(lifetimeMs > windowMs))
189
+ throw new Error('signed link lifetime must exceed its window');
190
+ const cache = new Map();
191
+ return {
192
+ async mint(request) {
193
+ const { type } = request;
194
+ if (!type || !type.contentType || !type.class)
195
+ throw new Error('signed link needs a decided type');
196
+ const disposition = contentDisposition(request.download ? 'attachment' : type.disposition, request.filename);
197
+ const at = now();
198
+ const windowStart = Math.floor(at / windowMs) * windowMs;
199
+ const expires = windowStart + lifetimeMs;
200
+ const cacheKey = [request.bucket, request.key, type.contentType, disposition].join('\n');
201
+ let entry = cache.get(cacheKey);
202
+ if (!entry || entry.windowStart !== windowStart) {
203
+ const url = await opts.sign({
204
+ bucket: request.bucket,
205
+ key: request.key,
206
+ accessibleAt: new Date(windowStart),
207
+ expires: new Date(expires),
208
+ responseType: type.contentType,
209
+ responseDisposition: disposition,
210
+ });
211
+ entry = { windowStart, url };
212
+ if (cache.size >= maxCached) {
213
+ for (const [k, v] of cache)
214
+ if (v.windowStart !== windowStart)
215
+ cache.delete(k);
216
+ if (cache.size >= maxCached)
217
+ cache.clear();
218
+ }
219
+ cache.set(cacheKey, entry);
220
+ }
221
+ return {
222
+ url: entry.url,
223
+ expiresAt: new Date(expires),
224
+ maxAgeSeconds: Math.max(0, Math.floor((expires - at) / 1000) - MAX_AGE_MARGIN_S),
225
+ };
226
+ },
227
+ };
228
+ }
229
+ /**
230
+ * Signed links for tests and local dev, where there is no storage site and
231
+ * no signing key: URLs under `baseUrl` + `path` (a route the app mounts only
232
+ * with its in-memory store, public like a real signed link), HMAC-signed
233
+ * with a per-process key so a holder can change neither the object, the
234
+ * validity, nor the pinned type and disposition.
235
+ */
236
+ export function createMemoryLinkSigner(opts) {
237
+ const secret = randomBytes(32);
238
+ const now = opts.now ?? Date.now;
239
+ const base = `${opts.baseUrl.replace(/\/+$/, '')}${opts.path}`;
240
+ const fields = ['bucket', 'key', 'from', 'until', 'type', 'disposition'];
241
+ const mac = (params) => createHmac('sha256', secret).update(fields.map((f) => params.get(f) ?? '').join('\n')).digest('hex');
242
+ return {
243
+ async sign(r) {
244
+ const params = new URLSearchParams({
245
+ bucket: r.bucket,
246
+ key: r.key,
247
+ from: String(r.accessibleAt.getTime()),
248
+ until: String(r.expires.getTime()),
249
+ type: r.responseType,
250
+ disposition: r.responseDisposition,
251
+ });
252
+ params.set('sig', mac(params));
253
+ return `${base}?${params}`;
254
+ },
255
+ check(url) {
256
+ const parsed = new URL(url, opts.baseUrl);
257
+ if (parsed.pathname !== new URL(base).pathname)
258
+ return null;
259
+ const params = parsed.searchParams;
260
+ const sig = Buffer.from(params.get('sig') ?? '', 'hex');
261
+ const expected = Buffer.from(mac(params), 'hex');
262
+ if (sig.length !== expected.length || !timingSafeEqual(sig, expected))
263
+ return null;
264
+ const at = now();
265
+ if (at < Number(params.get('from')) || at >= Number(params.get('until')))
266
+ return null;
267
+ return {
268
+ bucket: params.get('bucket') ?? '',
269
+ key: params.get('key') ?? '',
270
+ responseType: params.get('type') ?? '',
271
+ responseDisposition: params.get('disposition') ?? '',
272
+ };
273
+ },
274
+ };
275
+ }
@@ -17,6 +17,14 @@
17
17
  // says so in its own CSP's frame-ancestors, and then gets no
18
18
  // X-Frame-Options: framing is an explicit per-page decision, never a
19
19
  // weaker default.
20
+ // - Since 5.2.0, on anything that is not a page, script, style, JSON,
21
+ // wasm, audio or video and has no CSP of its own:
22
+ // `Content-Security-Policy: sandbox` — the backstop of PW
23
+ // docs/SECURITY.md browser-facing rule 5: an SVG or XML file an app
24
+ // serves by mistake gets no script and an opaque origin when opened as
25
+ // a document. An `<img>` ignores it, and a raster image opened in a tab
26
+ // still shows; audio and video are exempt because a browser's own media
27
+ // page stops playing under `sandbox` (Chromium, checked 2026-12-03).
20
28
  //
21
29
  // `contentSecurityPolicy()` builds the full policy an app shell carries. It
22
30
  // is opt-in per app: a wrong policy breaks a page.
@@ -27,6 +35,9 @@ export const DEFAULT_HUB_URL = 'https://hub.apps.snewman.net';
27
35
  /** Where the browser logger and RUM post their events. */
28
36
  export const DEFAULT_LOG_URL = 'https://api.axiom.co';
29
37
  export const HSTS_VALUE = 'max-age=31536000';
38
+ /** Types the sandbox backstop leaves alone: pages (which get their own
39
+ * framing policy), scripts, styles, JSON, wasm, and audio and video. */
40
+ const NOT_SANDBOXED = /^\s*((text\/(html|css|javascript)|application\/(javascript|ecmascript|wasm|json|[\w.-]+\+json))\s*($|;)|(audio|video)\/)/i;
30
41
  /** The headers `response` lacks of the defaults for `request`. */
31
42
  export function missingSecurityHeaders(request, headers) {
32
43
  const out = [];
@@ -38,7 +49,10 @@ export function missingSecurityHeaders(request, headers) {
38
49
  add('referrer-policy', 'strict-origin-when-cross-origin');
39
50
  if (servedOverHttps(request))
40
51
  add('strict-transport-security', HSTS_VALUE);
41
- if (/^\s*text\/html\b/i.test(headers.get('content-type') ?? '')) {
52
+ const contentType = headers.get('content-type') ?? '';
53
+ if (contentType && !NOT_SANDBOXED.test(contentType))
54
+ add('content-security-policy', 'sandbox');
55
+ if (/^\s*text\/html\b/i.test(contentType)) {
42
56
  const ownPolicy = headers.get('content-security-policy');
43
57
  if (ownPolicy === null)
44
58
  add('content-security-policy', "frame-ancestors 'none'");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "5.1.0",
3
+ "version": "5.2.0",
4
4
  "description": "Plasticine new-world shared platform library: logging, auth, service-to-service auth, db, HTTP, sync, app updates",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -53,6 +53,10 @@
53
53
  "types": "./dist/rum.d.ts",
54
54
  "default": "./dist/rum.js"
55
55
  },
56
+ "./outside-bytes": {
57
+ "types": "./dist/outside-bytes.d.ts",
58
+ "default": "./dist/outside-bytes.js"
59
+ },
56
60
  "./slow-fetch": {
57
61
  "types": "./dist/slow-fetch.d.ts",
58
62
  "default": "./dist/slow-fetch.js"