@dokebi/web 0.4.2 → 0.4.3

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.
Files changed (46) hide show
  1. package/AI.md +248 -39
  2. package/README.md +31 -10
  3. package/dist/app-routes.d.ts +20 -0
  4. package/dist/app-routes.js +137 -0
  5. package/dist/before-hijack.d.ts +24 -0
  6. package/dist/before-hijack.js +73 -0
  7. package/dist/body.d.ts +14 -0
  8. package/dist/body.js +30 -0
  9. package/dist/cluster-ready.d.ts +67 -0
  10. package/dist/cluster-ready.js +123 -0
  11. package/dist/compilers.d.ts +16 -0
  12. package/dist/compilers.js +25 -0
  13. package/dist/compression.d.ts +40 -0
  14. package/dist/compression.js +435 -0
  15. package/dist/connections.d.ts +44 -0
  16. package/dist/connections.js +282 -0
  17. package/dist/define-errors.d.ts +76 -0
  18. package/dist/define-errors.js +161 -0
  19. package/dist/describe.d.ts +37 -0
  20. package/dist/describe.js +96 -0
  21. package/dist/errors.d.ts +1 -1
  22. package/dist/errors.js +24 -3
  23. package/dist/forms.d.ts +23 -7
  24. package/dist/forms.js +53 -13
  25. package/dist/index.d.ts +134 -4
  26. package/dist/index.js +1518 -91
  27. package/dist/options.d.ts +56 -0
  28. package/dist/options.js +320 -1
  29. package/dist/points.d.ts +159 -0
  30. package/dist/points.js +162 -1
  31. package/dist/responses.d.ts +31 -6
  32. package/dist/responses.js +68 -6
  33. package/dist/route-config.d.ts +38 -0
  34. package/dist/route-config.js +222 -0
  35. package/dist/route-hooks.d.ts +75 -0
  36. package/dist/route-hooks.js +118 -0
  37. package/dist/route-table.d.ts +55 -0
  38. package/dist/route-table.js +142 -0
  39. package/dist/seal.d.ts +49 -1
  40. package/dist/seal.js +259 -24
  41. package/dist/security-headers.d.ts +121 -0
  42. package/dist/security-headers.js +298 -0
  43. package/dist/transient-log.d.ts +42 -0
  44. package/dist/transient-log.js +95 -0
  45. package/options.schema.json +488 -1
  46. package/package.json +22 -9
package/dist/seal.js CHANGED
@@ -1,8 +1,63 @@
1
1
  import { diagnostics } from '@dokebi/core/libraries';
2
+ import { bodyFollows } from './body.js';
2
3
  import { WebError } from './errors.js';
4
+ import { FORM_SUBMISSION_HEADER } from './responses.js';
3
5
  /** Response header naming the path a sealed response was sealed with (after a redirect it is the final one). */
4
6
  export const SEALED_PATH_HEADER = 'x-dokebi-sealed-path';
7
+ /**
8
+ * Response header of a redirect answered to a sealed form (`x-dokebi-form: 1`, D-0092 §1.2): the
9
+ * 3xx becomes 204 with the `Location` here, and the forms module navigates to it.
10
+ */
11
+ export const SEALED_LOCATION_HEADER = 'x-dokebi-location';
5
12
  const JSON_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json$/;
13
+ /**
14
+ * The refusal of a body stamped before the codec's nonce store lost its nonces (dokebi-seal
15
+ * `nonces-lost`, R4-SEAL-4): retryable 503 SEAL_NONCES_LOST with the codec's `retryAfterMs`.
16
+ */
17
+ const LOST = 'nonces-lost';
18
+ /**
19
+ * On a refusal this layer already recorded (the warn `SEAL_BODY_REFUSED`, once per window): the
20
+ * error answer writes no record of its own.
21
+ */
22
+ export const RECORDED = Symbol('dokebi.web.seal.recorded');
23
+ /**
24
+ * True when a codec failure was caused by a store error of `storeCode` from a plugin whose store
25
+ * logged it itself (`STORE_PLUGINS`): dokebi-seal's `TimedNonceStore` creates every
26
+ * `NONCE_STORE_UNAVAILABLE` through its `onFailure`, which logs it at error once per window; the
27
+ * in-process stores log `NONCE_STORE_FULL` once per window. Matched by shape, the cause chain at
28
+ * most four deep.
29
+ */
30
+ function storeRecorded(error, storeCode) {
31
+ let current = error;
32
+ for (let depth = 0; depth < 4; depth++) {
33
+ if (current === null || typeof current !== 'object')
34
+ return false;
35
+ const { plugin, code, cause } = current;
36
+ if (STORE_PLUGINS.has(plugin) && code === storeCode)
37
+ return true;
38
+ current = cause;
39
+ }
40
+ return false;
41
+ }
42
+ /**
43
+ * The plugins whose nonce stores record their own failures: dokebi-seal (its `TimedNonceStore`
44
+ * logs `NONCE_STORE_UNAVAILABLE`, its `MemoryNonceStore` `NONCE_STORE_FULL`) and websocket-hub (its
45
+ * local store `NONCE_STORE_FULL`); both are given the plugin's logger.
46
+ */
47
+ const STORE_PLUGINS = new Set(['dokebi-seal', 'dokebi-websocket-hub']);
48
+ /** A refusal reason a codec may give (lower case words); anything else is logged as `unknown`. */
49
+ const REASON = /^[a-z][a-z-]{0,31}$/;
50
+ /**
51
+ * The refusals that prove the body bad (dokebi-seal `SealReject`): answered 400. Every other
52
+ * failure — `capacity`, `unavailable`, or none of these — means the server could not check it.
53
+ */
54
+ const CLIENT_REASONS = new Set([
55
+ 'no-prefix',
56
+ 'plain-rejected',
57
+ 'drift',
58
+ 'replay',
59
+ 'open-failed',
60
+ ]);
6
61
  /** The media type of a Content-Type value: lower case, without parameters. */
7
62
  export function mediaType(value) {
8
63
  return (String(Array.isArray(value) ? value[0] : (value ?? ''))
@@ -10,19 +65,35 @@ export function mediaType(value) {
10
65
  ?.trim()
11
66
  .toLowerCase() ?? '');
12
67
  }
13
- /** A request carries a body when it says so (Content-Length above 0 or Transfer-Encoding). */
14
- function hasBody(headers) {
15
- if (headers['transfer-encoding'] !== undefined)
16
- return true;
17
- const length = headers['content-length'];
18
- return length !== undefined && length !== '0';
68
+ /**
69
+ * Ends a body stream an onSend step replaces: Fastify sends the new payload and never touches the
70
+ * old one, so a file stream kept its descriptor open for the life of the process.
71
+ */
72
+ export function discardPayload(payload, logger) {
73
+ if (payload === null || typeof payload !== 'object' || Buffer.isBuffer(payload))
74
+ return;
75
+ const node = payload;
76
+ if (typeof node.destroy === 'function') {
77
+ if (!node.destroyed)
78
+ node.destroy();
79
+ return;
80
+ }
81
+ const web = payload;
82
+ if (typeof web.cancel === 'function' && !web.locked)
83
+ web
84
+ .cancel()
85
+ .then(undefined, (error) => diagnostics.logError(logger, 'A replaced response body stream failed to cancel', 'WEB_BODY_DISCARD_FAILED', error));
19
86
  }
20
87
  /** `/a/b?c` → `/a/b`. */
21
88
  export function pathOf(url) {
22
89
  const end = url.search(/[?#]/);
23
90
  return end === -1 ? url : url.slice(0, end);
24
91
  }
25
- /** A host without its port, lower case; IPv6 literals keep their brackets (as `location.hostname`). */
92
+ /**
93
+ * A host without its port, lower case, as the browser's `location.hostname` (the other key
94
+ * input): IPv6 literals keep their brackets and a trailing dot stays (`a.test.`), even where a
95
+ * host decision treats `a.test.` as `a.test`.
96
+ */
26
97
  function withoutPort(host) {
27
98
  const raw = host.toLowerCase();
28
99
  if (raw.startsWith('['))
@@ -39,6 +110,55 @@ export function checkSealSetting(value) {
39
110
  return value;
40
111
  throw new WebError('INVALID_ROUTE', 'Route seal must be a boolean or a function of the request');
41
112
  }
113
+ /** The urlencoded media type: refused on a sealed request with its own message (D-0092 §1.4). */
114
+ const FORM_TYPE = 'application/x-www-form-urlencoded';
115
+ /**
116
+ * The refusal of a request that carries the seal forms marker (`x-dokebi-form`) wrongly, or
117
+ * undefined: the value must be `1`, and a body must be sealed (`sealedType`, the provider's
118
+ * media type) or multipart (a file upload of a sealed form). A body-less request with the marker
119
+ * passes (a redirect a proxy answered, followed by the browser). `body`: `bodyFollows(request)`.
120
+ */
121
+ export function formMarkerRefusal(headers, sealedType, body) {
122
+ const value = headers[FORM_SUBMISSION_HEADER];
123
+ if (value === undefined)
124
+ return undefined;
125
+ if (value !== '1')
126
+ return new WebError('FORM_BODY_INVALID', 'The x-dokebi-form header must be 1');
127
+ if (!body)
128
+ return undefined;
129
+ const type = mediaType(headers['content-type']);
130
+ if (type === 'multipart/form-data' || (sealedType !== undefined && type === sealedType))
131
+ return undefined;
132
+ return new WebError('FORM_BODY_INVALID', 'A request with x-dokebi-form must carry a sealed or multipart body');
133
+ }
134
+ /**
135
+ * The opened body of a sealed form (D-0092 §1.3), checked to have the shape the urlencoded parser
136
+ * gives — an object of strings, a repeated name an array of strings — and returned like it: an
137
+ * object without a prototype (`__proto__` is an ordinary key), at most `maxFields` values.
138
+ */
139
+ export function sealedFormBody(value, maxFields) {
140
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
141
+ throw new WebError('FORM_BODY_INVALID', 'A sealed form body must be an object');
142
+ const body = Object.create(null);
143
+ let fields = 0;
144
+ for (const [name, field] of Object.entries(value)) {
145
+ if (typeof field === 'string') {
146
+ fields++;
147
+ body[name] = field;
148
+ }
149
+ else if (Array.isArray(field) &&
150
+ field.length > 1 &&
151
+ field.every((item) => typeof item === 'string')) {
152
+ fields += field.length;
153
+ body[name] = [...field];
154
+ }
155
+ else
156
+ throw new WebError('FORM_BODY_INVALID', 'A sealed form field must be a string or an array of two or more strings', { data: { field: name.slice(0, 100) } });
157
+ if (fields > maxFields)
158
+ throw new WebError('FORM_BODY_TOO_MANY_FIELDS', `A form body may carry at most ${maxFields} fields`, { data: { maxFields } });
159
+ }
160
+ return body;
161
+ }
42
162
  /**
43
163
  * The seal slot of one web server. Requests are sealed by their route (`seal`) or by a
44
164
  * registered predicate (dokebi-app: hosts with `seal: true`); health routes, `seal: false`
@@ -57,11 +177,15 @@ export class WebSealing {
57
177
  #decided = new WeakMap();
58
178
  /** Replies this layer answered itself (415, refused body): sent plain so any client can read them. */
59
179
  #plain = new WeakSet();
60
- #repeats = new diagnostics.Repeats();
180
+ #repeats;
181
+ /** `data` of a retryable seal refusal: the body and `Retry-After` (seconds) say when to retry. */
182
+ #retry;
61
183
  constructor(logger, options, requestHost) {
62
184
  this.logger = logger;
63
185
  this.options = options;
64
186
  this.requestHost = requestHost;
187
+ this.#repeats = new diagnostics.Repeats({ intervalMs: options.logRepeatWindowMs ?? 10_000 });
188
+ this.#retry = Object.freeze({ retryable: true, retryAfterMs: options.retryAfterMs ?? 1_000 });
65
189
  }
66
190
  get provider() {
67
191
  return this.#provider;
@@ -173,7 +297,9 @@ export class WebSealing {
173
297
  method: request.method,
174
298
  path: sealer.path.slice(0, 200),
175
299
  });
176
- if (!hasBody(request.headers))
300
+ // Over HTTP/2 the headers alone never say it: a plain body without Content-Length got
301
+ // through to the parsers (audit r4 step 2).
302
+ if (!bodyFollows(request))
177
303
  return undefined;
178
304
  const type = mediaType(request.headers['content-type']);
179
305
  const provider = this.#provider;
@@ -193,24 +319,39 @@ export class WebSealing {
193
319
  ...(repeated ? { repeated } : {}),
194
320
  });
195
321
  this.#plain.add(request);
322
+ // A native form post: the page was sent without its seal forms module (D-0092 §1.4). The
323
+ // answer is the same 415 (an HTML page for a browser, JSON for a script) with its own words.
324
+ if (type === FORM_TYPE)
325
+ return new WebError('SEAL_REQUIRED', 'This page needs its seal script to send forms', {
326
+ hint: 'Reload the page and send the form again.',
327
+ fix: `This host is sealed: a form is sent sealed by the @dokebi/seal/forms module. Write <%- data.seal.head %> in the <head> of the EJS layout (dokebi-app), or send the body sealed as ${provider.contentType} with sealedFetch. Webhooks and server-to-server routes set seal: false or are listed in dokebi-web sealExclude.`,
328
+ });
196
329
  return new WebError('SEAL_REQUIRED', 'A sealed route got a plain request body', {
197
- fix: `This route is sealed (a seal host): send the body sealed as ${provider.contentType} with @dokebi/seal (sealedFetch, or the Inertia bridge sealInertia). File uploads use multipart/form-data; webhooks and server-to-server routes set seal: false or are listed in dokebi-web sealExclude.`,
330
+ fix: `This route is sealed (a seal host): send the body sealed as ${provider.contentType} with @dokebi/seal (sealedFetch, the Inertia bridge sealInertia, or the forms module @dokebi/seal/forms). File uploads use multipart/form-data; webhooks and server-to-server routes set seal: false or are listed in dokebi-web sealExclude.`,
198
331
  });
199
332
  }
200
- /** The body parser of the sealed media type: opens, then parses JSON. Refusals are 400. */
333
+ /**
334
+ * The body parser of the sealed media type: opens, then parses JSON. A body proven bad (no
335
+ * prefix, plain, drift, replay, does not open) is 400; a body the server could not check (a full
336
+ * nonce store, a failing or slow store, any failure without a known client reason) is a
337
+ * retryable 503 (D-0075, D-0096 §2), never a client error.
338
+ */
201
339
  async parse(request, body) {
202
340
  let plain;
203
341
  try {
204
342
  plain = await this.#codec(request).codec.decode(body);
205
343
  }
206
344
  catch (error) {
207
- const reason = typeof error?.reason === 'string'
208
- ? String(error.reason)
209
- : 'unknown';
345
+ const given = error?.reason;
346
+ const reason = typeof given === 'string' && REASON.test(given) ? given : 'unknown';
210
347
  const route = request.routeOptions.url ?? 'unmatched';
211
- const repeated = this.#repeats.take(`open ${route} ${reason}`);
348
+ this.#plain.add(request);
349
+ const checked = CLIENT_REASONS.has(reason) || reason === LOST;
350
+ const repeated = checked || reason === 'capacity'
351
+ ? this.#repeats.take(`open ${route} ${reason}`)
352
+ : undefined;
212
353
  // The reason goes to the log only: telling the client drift from replay is an oracle.
213
- if (repeated !== undefined)
354
+ if (repeated !== undefined && checked)
214
355
  this.logger.log('warn', 'Sealed request body refused', {
215
356
  code: 'SEAL_BODY_REFUSED',
216
357
  reason,
@@ -218,25 +359,92 @@ export class WebSealing {
218
359
  route,
219
360
  ...(repeated ? { repeated } : {}),
220
361
  });
221
- this.#plain.add(request);
222
- // A full replay nonce store (D-0075, fail closed) is the server's state, not the body's:
223
- // 503, so the client may retry. It says nothing about drift or replay.
224
- if (reason === 'capacity')
225
- throw new WebError('SEAL_BUSY', 'Sealed request body refused: server busy', {
362
+ if (CLIENT_REASONS.has(reason))
363
+ throw new WebError('SEAL_BODY_REFUSED', 'Sealed request body refused', { cause: error });
364
+ // The server's state, not the body's: 503 with Retry-After, and nothing about drift or
365
+ // replay. A full nonce store (D-0075, fail closed) is SEAL_BUSY; a store that failed or
366
+ // was too slow, or a failure without a known reason, was not checked at all (D-0096 §2):
367
+ // no warn here: the error with the whole cause is dokebi-seal's SEAL_NONCE_STORE_UNAVAILABLE
368
+ // for its shared stores, else web's WEB_REQUEST_FAILED.
369
+ // A body stamped before the provider's nonce store lost its nonces (dokebi-seal
370
+ // `nonces-lost`): still refused, but the store's state, with the wait the provider gives.
371
+ if (reason === LOST) {
372
+ const given = error.retryAfterMs;
373
+ const retryAfterMs = typeof given === 'number' && Number.isFinite(given) && given > 0
374
+ ? given
375
+ : this.#retry.retryAfterMs;
376
+ const lost = new WebError('SEAL_NONCES_LOST', 'Sealed request body refused: the nonces were lost', {
226
377
  cause: error,
378
+ data: { retryable: true, retryAfterMs },
227
379
  });
228
- throw new WebError('SEAL_BODY_REFUSED', 'Sealed request body refused', { cause: error });
380
+ // An expected, bounded state after a store loss, recorded once per window by the warn
381
+ // above: the error answer adds no record of its own (one layer, D-0047; audit r4 step 2).
382
+ Object.defineProperty(lost, RECORDED, { value: true });
383
+ throw lost;
384
+ }
385
+ if (reason === 'capacity') {
386
+ const busy = new WebError('SEAL_BUSY', 'Sealed request body refused: server busy', {
387
+ cause: error,
388
+ data: this.#retry,
389
+ });
390
+ // A full nonce store is a capacity refusal with a fix (nonces.max), not a fault: one warn
391
+ // record (D-0075 §4; decision of audit r4 step 2). The official stores write it themselves
392
+ // (NONCE_STORE_FULL, with max, live and the count); for any other store web writes the
393
+ // same level, once per route and window, the rest counted. The error answer adds none.
394
+ if (repeated !== undefined && !storeRecorded(error, 'NONCE_STORE_FULL'))
395
+ this.logger.log('warn', 'Sealed request body refused: the replay nonce store is full', {
396
+ code: 'SEAL_BUSY',
397
+ reason,
398
+ method: request.method,
399
+ route,
400
+ fix: busy.fix,
401
+ ...(repeated ? { repeated } : {}),
402
+ });
403
+ Object.defineProperty(busy, RECORDED, { value: true });
404
+ throw busy;
405
+ }
406
+ // The codec's wait when it names one (dokebi-seal: a @dokebi/redis error's retryAfterMs, so
407
+ // one Redis outage answers one Retry-After from every plugin), else sealRetryAfterMs.
408
+ const wait = error?.retryAfterMs;
409
+ const unavailable = new WebError('SEAL_NONCE_STORE_UNAVAILABLE', 'Sealed request body not checked: the replay nonce store is unavailable', {
410
+ cause: error,
411
+ data: typeof wait === 'number' && Number.isFinite(wait) && wait > 0
412
+ ? { retryable: true, retryAfterMs: wait }
413
+ : this.#retry,
414
+ });
415
+ // dokebi-seal's shared store logged this failure itself (error SEAL_NONCE_STORE_UNAVAILABLE
416
+ // once per window, with its cause): no second record here. Any other failure (a codec
417
+ // failure without a known reason) has web's error record only.
418
+ if (storeRecorded(error, 'NONCE_STORE_UNAVAILABLE'))
419
+ Object.defineProperty(unavailable, RECORDED, { value: true });
420
+ throw unavailable;
229
421
  }
422
+ const form = request.headers[FORM_SUBMISSION_HEADER] === '1';
230
423
  if (plain === '')
231
- return undefined;
424
+ return form ? Object.create(null) : undefined;
425
+ let value;
232
426
  try {
233
- return JSON.parse(plain);
427
+ value = JSON.parse(plain);
234
428
  }
235
429
  catch (error) {
236
430
  throw new WebError('SEAL_BODY_NOT_JSON', 'Sealed request body is not JSON', {
237
431
  cause: error,
238
432
  });
239
433
  }
434
+ if (!form)
435
+ return value;
436
+ // A sealed form is a form body (D-0092 §1.3): `formBody` decides as for urlencoded, and the
437
+ // handler gets the shape the urlencoded parser gives, whatever the client sent.
438
+ if (!this.options.formBody)
439
+ throw new WebError('FORM_BODY_DISABLED', 'Form bodies are not enabled');
440
+ const fields = sealedFormBody(value, this.options.formMaxFields);
441
+ if (this.logger.isEnabled('debug'))
442
+ this.logger.log('debug', 'Sealed form body opened', {
443
+ method: request.method,
444
+ route: request.routeOptions.url ?? 'unmatched',
445
+ fields: Object.keys(fields).length,
446
+ });
447
+ return fields;
240
448
  }
241
449
  /** onSend: seals the JSON response of a sealed request (other types pass unchanged). */
242
450
  onSend(request, reply, payload) {
@@ -273,7 +481,34 @@ export class WebSealing {
273
481
  });
274
482
  reply.code(500).header('content-type', 'application/json; charset=utf-8');
275
483
  reply.removeHeader(SEALED_PATH_HEADER);
484
+ discardPayload(payload, this.logger);
276
485
  return '{"error":"INTERNAL_SERVER_ERROR"}';
277
486
  }
278
487
  }
279
488
  }
489
+ /**
490
+ * onSend of a redirect answered to a sealed form (D-0092 §1.2): 204 with the target in
491
+ * `x-dokebi-location` instead of the 3xx, so the browser's fetch does not follow it (it would
492
+ * render the next page — and take its session flash — for an answer the forms module throws
493
+ * away, and a redirect to another origin would fail as a CORS request). Returns the payload.
494
+ */
495
+ export function sealedFormRedirect(request, reply, logger, payload) {
496
+ discardPayload(payload, logger);
497
+ const location = reply.getHeader('location');
498
+ const target = String(Array.isArray(location) ? location[0] : location);
499
+ const status = reply.statusCode;
500
+ reply.code(204);
501
+ reply.removeHeader('location');
502
+ reply.removeHeader('content-type');
503
+ reply.removeHeader('content-length');
504
+ reply.header(SEALED_LOCATION_HEADER, target);
505
+ reply.header('cache-control', 'no-store');
506
+ if (logger.isEnabled('debug'))
507
+ logger.log('debug', 'Sealed form redirect told', {
508
+ method: request.method,
509
+ route: request.routeOptions.url ?? 'unmatched',
510
+ status,
511
+ target: target.split('?', 1)[0]?.slice(0, 200),
512
+ });
513
+ return '';
514
+ }
@@ -0,0 +1,121 @@
1
+ /** The CSP of an HTML page unless options or the route change it (decision §3). */
2
+ export declare const DEFAULT_DIRECTIVES: Readonly<Record<string, readonly string[]>>;
3
+ /** A CSP directive name: lower case letters and `-`. */
4
+ export declare const DIRECTIVE: RegExp;
5
+ /** One CSP source or keyword: no white space, `;` or `,` (they would end it). */
6
+ export declare const SOURCE: RegExp;
7
+ export type FrameOptions = 'DENY' | 'SAMEORIGIN';
8
+ export type ReferrerPolicy = 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';
9
+ export type OpenerPolicy = 'same-origin' | 'same-origin-allow-popups' | 'unsafe-none';
10
+ export type ResourcePolicy = 'same-origin' | 'same-site' | 'cross-origin';
11
+ /** The CSP part of the options or of a route override. */
12
+ export interface CspSetting {
13
+ /** Changes to the default directives: a list replaces that directive, `false` removes it. */
14
+ readonly directives?: Readonly<Record<string, readonly string[] | false>>;
15
+ /** `Content-Security-Policy-Report-Only` instead: the browser reports and does not block. */
16
+ readonly reportOnly?: boolean;
17
+ }
18
+ /** One route's `config.securityHeaders` (or `false`: no security header at all). */
19
+ export interface WebSecurityHeadersRoute {
20
+ readonly contentSecurityPolicy?: CspSetting | false;
21
+ readonly strictTransportSecurity?: false;
22
+ readonly frameOptions?: FrameOptions | false;
23
+ readonly referrerPolicy?: ReferrerPolicy | false;
24
+ readonly crossOriginOpenerPolicy?: OpenerPolicy | false;
25
+ readonly crossOriginResourcePolicy?: ResourcePolicy | false;
26
+ readonly contentTypeOptions?: boolean;
27
+ }
28
+ /** `options.dokebi-web.securityHeaders`, parsed. */
29
+ export interface SecurityHeadersOptions {
30
+ readonly enabled: boolean;
31
+ readonly contentSecurityPolicy: false | {
32
+ readonly directives: Readonly<Record<string, readonly string[] | false>>;
33
+ readonly reportOnly: boolean;
34
+ };
35
+ readonly strictTransportSecurity: false | {
36
+ readonly maxAgeSec: number;
37
+ readonly includeSubDomains: boolean;
38
+ readonly preload: boolean;
39
+ };
40
+ readonly frameOptions: FrameOptions | false;
41
+ readonly referrerPolicy: ReferrerPolicy | false;
42
+ readonly crossOriginOpenerPolicy: OpenerPolicy | false;
43
+ readonly crossOriginResourcePolicy: ResourcePolicy | false;
44
+ readonly contentTypeOptions: boolean;
45
+ }
46
+ /** Sources a plugin adds to the policy (`web.contentSecurityPolicy`, setup only). */
47
+ export interface WebCspContribution {
48
+ /** The plugin, named in logs and describe. */
49
+ readonly plugin: string;
50
+ /** Sources appended to each directive (`{ 'connect-src': ['ws://*:5173'] }`). */
51
+ readonly directives: Readonly<Record<string, readonly string[]>>;
52
+ }
53
+ /** The problem of a route's `config.securityHeaders` value, or undefined (checked at start). */
54
+ export declare function securityHeadersProblem(value: unknown): string | undefined;
55
+ /** The problem of a `web.contentSecurityPolicy` contribution, or undefined. */
56
+ export declare function contributionProblem(value: unknown): string | undefined;
57
+ type HeaderList = readonly (readonly [string, string])[];
58
+ /** The headers of one policy (the options merged with a route's override). */
59
+ interface Built {
60
+ /** Every answer: nosniff. */
61
+ readonly always: HeaderList;
62
+ /** An HTML document: the rest after `always`. */
63
+ readonly document: HeaderList;
64
+ /** The HSTS value for HTTPS requests, or undefined. */
65
+ readonly hsts: string | undefined;
66
+ /**
67
+ * Cross-Origin-Opener-Policy of HTML documents, HTTPS only: browsers ignore it on an origin
68
+ * that is not potentially trustworthy and log a console error for it (seen in Chromium).
69
+ */
70
+ readonly opener: string | undefined;
71
+ }
72
+ /** The serialized CSP: `name sources; …` in the order of the merged directives. */
73
+ export declare function serializePolicy(directives: Readonly<Record<string, readonly string[]>>): string;
74
+ /** The merged directives: defaults, then the changes (options, then route), then contributions. */
75
+ export declare function mergeDirectives(changes: readonly (Readonly<Record<string, readonly string[] | false>> | undefined)[], contributions: readonly WebCspContribution[]): Record<string, readonly string[]>;
76
+ /** The answer of one route: the policy built at its first answer after the start. */
77
+ export declare class RouteSecurity {
78
+ #private;
79
+ readonly owner: SecurityHeaders;
80
+ readonly override: WebSecurityHeadersRoute | false | undefined;
81
+ constructor(owner: SecurityHeaders, override: WebSecurityHeadersRoute | false | undefined);
82
+ get built(): Built;
83
+ }
84
+ /** A reply as the onSend step uses it. */
85
+ interface HeaderReply {
86
+ getHeader(name: string): unknown;
87
+ hasHeader(name: string): boolean;
88
+ header(name: string, value: string): unknown;
89
+ }
90
+ export declare class SecurityHeaders {
91
+ #private;
92
+ /** Bumped by `update`: every route builds its headers again at its next answer. */
93
+ generation: number;
94
+ /** The policy of routes without an override and of answers without a route (404). */
95
+ readonly defaults: RouteSecurity;
96
+ constructor(options: SecurityHeadersOptions);
97
+ get enabled(): boolean;
98
+ /**
99
+ * D-0154: reloaded header values. `enabled` stays as it was at start (the route steps exist
100
+ * only when it was on); the headers of every route are built again at their next answer.
101
+ */
102
+ update(options: SecurityHeadersOptions): void;
103
+ /** Setup only (web freezes it at start). */
104
+ contribute(contribution: WebCspContribution): void;
105
+ /** At start: contributions are final, policies may be built. */
106
+ freeze(): void;
107
+ get frozen(): boolean;
108
+ get contributions(): readonly WebCspContribution[];
109
+ /** The policy of a route (its `config.securityHeaders`, already checked). */
110
+ route(override: unknown): RouteSecurity;
111
+ /** The headers of the options with a route override. */
112
+ build(override: WebSecurityHeadersRoute | false | undefined): Built;
113
+ /**
114
+ * The onSend step: the headers of `policy` that the reply does not have yet. `request.protocol`
115
+ * (it follows trustProxy) is read only for HSTS and only when it is on.
116
+ */
117
+ apply(policy: RouteSecurity, request: {
118
+ readonly protocol: string;
119
+ }, reply: HeaderReply): void;
120
+ }
121
+ export {};