@dokebi/web 0.1.2 → 0.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.
package/AI.md CHANGED
@@ -1,4 +1,4 @@
1
- # AI 작업 안내 — @dokebi/web 0.1.2
1
+ # AI 작업 안내 — @dokebi/web 0.2.0
2
2
 
3
3
  Fastify 5 HTTP 서버를 앱이 소유하게 하는 플러그인이다. 준비 전·종료 중 요청 차단(503), health 경로, 진행 요청을 기다리는 drain, cluster 워커의 무중단 교체, 신뢰 프락시를 맡는다. 라우터·컨트롤러·뷰·DB는 필수가 아니다. Node >=24.0.0, core ^0.2.0. 세부는 [README](README.md)다.
4
4
 
@@ -16,6 +16,8 @@ dokebi-web:
16
16
  requestTimeout: 30000 # 요청 수신 제한(업무 실행 제한이 아님)
17
17
  healthRoutes: { live: /health/live, ready: /health/ready } # false면 등록 안 함
18
18
  trustProxy: [127.0.0.1, "::1"] # 정확한 IP만, 최대 64개
19
+ sealDriftMs: 60000 # 봉인 호스트(D-0062): 봉인 본문 ts 허용 오차
20
+ sealExclude: [/webhooks] # 봉인 호스트에서도 평문인 경로 접두
19
21
  ```
20
22
 
21
23
  TLS·HTTP2·임의 Fastify 생성 옵션은 아직 공개하지 않는다(앞단 프락시에서 TLS).
@@ -44,6 +46,8 @@ http.route({ method: 'POST', url: '/import', handler: async (request, reply) =>
44
46
  | `constraint(strategy)` | 라우트 제약 전략 추가(@dokebi/app의 `dokebiApp`). 그 제약을 쓰는 라우트보다 먼저, setup 중에만 |
45
47
  | `track(() => work)` | HTTP 응답과 수명이 다른 업무를 drain이 기다리게 함 |
46
48
  | `requestHost(request)` | 신뢰 프락시 규칙을 적용한 요청 호스트(소문자, 포트 유지) |
49
+ | `route({ ..., seal })` | `seal: false`면 봉인 호스트에서도 평문(웹훅·서버 사이), `true`·함수면 어느 호스트든 봉인(D-0062) |
50
+ | `sealCodec(provider)`·`sealRequests(predicate)`·`sealOf(request)`·`sealing` | HTTP 봉인 자리(D-0062). 제공자는 @dokebi/seal, 판단은 @dokebi/app이 등록한다. 직접 부를 일은 드물다 |
47
51
  | `address` | listen 뒤 실제 주소(그 전 undefined). cluster 워커에서는 core `ready` 뒤에 정해지므로 다른 플러그인은 `ready`에서 읽는다 |
48
52
 
49
53
  ## 3. 시작과 요청 차단
@@ -52,6 +56,10 @@ http.route({ method: 'POST', url: '/import', handler: async (request, reply) =>
52
56
  - 앱 start 완료와 health ready 전에는 업무 요청에 503 `{ error: 'SERVICE_UNAVAILABLE', reason }`(reason: `STARTING`·`NOT_READY`·`DRAINING`).
53
57
  - health 경로: live 200/503, ready 200/503(앱 상태와 health check). 앱마다 독립이고 cluster 전체 집계가 아니다.
54
58
 
59
+ ## 3-1. 봉인 호스트의 HTTP(D-0062)
60
+
61
+ @dokebi/seal과 @dokebi/app이 있으면 seal 호스트의 요청은 이렇게 된다: JSON 응답(4xx 포함)은 `E:<ts>:<b64>` 본문과 `Content-Type: application/vnd.dokebi-seal`·`x-dokebi-sealed-path`로 나가고, 요청 본문은 봉인 형식이어야 한다. 평문 JSON·urlencoded·text 본문은 처리기 전에 **415 `SEAL_REQUIRED`**(multipart 업로드는 통과). 브라우저는 `@dokebi/seal/http`의 `sealedFetch`·`sealInertia`를 쓴다. 웹훅처럼 봉인할 수 없는 라우트는 `seal: false`나 `sealExclude`로 뺀다. HTML 응답(EJS)은 그대로다. 제공자 없이 봉인을 원하면 시작 실패 `SEAL_PROVIDER_MISSING`. seal은 난독화·재전송 방지이고 기밀성은 TLS다.
62
+
55
63
  ## 4. 종료(drain)
56
64
 
57
65
  - 단일 프로세스: 새 요청을 503으로 막고 진행 응답·handler Promise·요청 훅·`track` 업무를 기다린다. core drain 기한(기본 20초)이 지나거나 `stop({ force: true })`면 남은 연결을 끊고 반환한다(core가 `DRAIN_TIMEOUT` 기록). 모든 drain 성공 뒤 cleanup에서 `Fastify.close`(onClose 실행).
@@ -66,7 +74,7 @@ http.route({ method: 'POST', url: '/import', handler: async (request, reply) =>
66
74
 
67
75
  ## 6. 오류
68
76
 
69
- `WebError`(`INVALID_OPTIONS`·`FROZEN`·`CLOSED`). 기본 오류 응답은 내부 메시지를 숨긴다. 500은 `error` 로그 `HTTP request failed`(`code: WEB_REQUEST_FAILED`·`requestId`·`method`·`route`(라우트 패턴, 쿼리 없음)·`error`(이름·전체 메시지·스택·`Caused by:` 원인, URL 인증 정보만 `//***@`로 지우고 16KB 넘으면 잘라 표시))를 남기고, 같은 라우트·오류 이름은 10초에 한 번만 남기며 사이 횟수는 다음 로그의 `repeated`로 알린다(D-0047). 4xx는 debug `HTTP request rejected`(`status`·`route`·`error` 전체 글·Fastify 코드 `errorCode`). 사용자 오류 처리기를 등록하면 그 보안 책임도 사용자에게 있다.
77
+ `WebError`(`INVALID_OPTIONS`·`FROZEN`·`CLOSED`). 봉인: `SEAL_PROVIDER_MISSING`(start)·`SEAL_PROVIDER_INVALID`, 요청 415 `SEAL_REQUIRED`·400 `SEAL_BODY_REFUSED`/`SEAL_BODY_NOT_JSON`, 응답 500 `SEAL_STREAM_UNSUPPORTED`·`SEAL_ENCODE_FAILED`(error 로그). 기본 오류 응답은 내부 메시지를 숨긴다. 500은 `error` 로그 `HTTP request failed`(`code: WEB_REQUEST_FAILED`·`requestId`·`method`·`route`(라우트 패턴, 쿼리 없음)·`error`(이름·전체 메시지·스택·`Caused by:` 원인, URL 인증 정보만 `//***@`로 지우고 16KB 넘으면 잘라 표시))를 남기고, 같은 라우트·오류 이름은 10초에 한 번만 남기며 사이 횟수는 다음 로그의 `repeated`로 알린다(D-0047). 4xx는 debug `HTTP request rejected`(`status`·`route`·`error` 전체 글·Fastify 코드 `errorCode`). 사용자 오류 처리기를 등록하면 그 보안 책임도 사용자에게 있다.
70
78
 
71
79
  debug 로그(`DOKEBI_LOG_LEVEL=debug`): `Web server configured`(옵션, trustProxy는 개수만)·`Web routes frozen`·`Web server listening`(주소·ms)·`Web drain started`·`Web worker stopped listening`·`Web drain cut connections`·`Web drain finished`·`Web server closed`, 요청마다는 `HTTP request refused`(이유·메서드·쿼리 뺀 경로; debug가 켜졌을 때만 만든다).
72
80
 
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @dokebi/web 0.1.2
1
+ # @dokebi/web 0.2.0
2
2
 
3
3
  Node >=24.0.0, core ^0.2.0의 선택 패키지다(npm 공개). Fastify 5.12.7로 HTTP 서버를 소유하며 DB·라우터·컨트롤러·뷰는 필수가 아니다.
4
4
 
@@ -64,6 +64,30 @@ Application 전체 start 완료 및 선택 health.ready 전에는 업무 요청
64
64
 
65
65
  진입 파일을 가진 플러그인은 생성 코드의 manifest 의존 검사에서 제외되므로 CLI 경로에서도 진입 파일의 `requires`를 쓸 수 있다(같은 생성 코드 규칙을 2026-10-14 controller·module 진입 파일로 실행 확인, [ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-04). 진입 파일로 더한 의존은 CLI의 remove·doctor 판단에 보이지 않으며 빠지면 실행 시 `MISSING_DEPENDENCY`로 드러난다.
66
66
 
67
+ ## 봉인 호스트의 HTTP (D-0062, 0.2.0)
68
+
69
+ seal 호스트(@dokebi/app `domains.<host>.seal: true`)나 `seal: true` 라우트의 HTTP 데이터를 봉인하는 **자리**를 가진다. 알고리즘은 @dokebi/seal이 `sealCodec(provider)`로 채운다(이 패키지는 seal을 import하지 않는다). [D-0062](../../docs/decisions/D-0062-http-seal.md).
70
+
71
+ - 판단(요청마다 한 번): health → 평문, 라우트 `seal: false` → 평문, `seal: true`·`seal(request)` → 봉인, `sealExclude` 접두(`/` 경계) → 평문, `sealRequests(predicate)` 중 하나가 참 → 봉인. `seal`은 `route()`·Fastify `register` 범위·router `mount` 어디서 줘도 `config.dokebiSeal`이 된다.
72
+ - 봉인 요청의 본문: 형식이 제공자의 `contentType`(`application/vnd.dokebi-seal`)이면 파서가 열어 JSON으로 `request.body`에 둔다(drift·재전송·변조는 400, 이유는 warn `SEAL_BODY_REFUSED`에만). 본문이 있는데 봉인 형식도 `multipart/form-data`도 아니면 **파서 전에** `415 { error: 'SEAL_REQUIRED', fix }`(warn `SEAL_REQUIRED`, 라우트당 10초에 한 번).
73
+ - 봉인 요청의 JSON 응답(`application/json`·`+json`, 4xx·5xx 포함)은 `onSend`에서 봉인되고 `Content-Type: application/vnd.dokebi-seal`·`x-dokebi-sealed-path`(봉인에 쓴 경로, 리다이렉트 뒤의 최종 경로)가 붙는다. HTML·파일·hijack 응답은 그대로다. 스트림 JSON은 봉인할 수 없어 500(평문을 내보내지 않는다).
74
+ - 스스로 본문을 쓰는 코드(Inertia 첫 화면, SSE)는 `sealOf(request)`로 `{ path, encode }`를 받는다.
75
+ - 무언가 봉인을 원하는데(판단 등록·봉인 라우트) 제공자가 없으면 start에서 `SEAL_PROVIDER_MISSING`.
76
+
77
+ ```yaml
78
+ options:
79
+ dokebi-web:
80
+ sealDriftMs: 60000 # 봉인 본문 ts 허용 오차(1000..600000), nonce는 그 두 배 보관
81
+ sealExclude: [/webhooks] # seal 호스트에서도 평문인 경로 접두(최대 64)
82
+ ```
83
+
84
+ | API | 뜻 |
85
+ |---|---|
86
+ | `sealCodec(provider)` | HTTP 봉인 자리 채우기(setup, 한 번). dokebi-seal이 부른다 |
87
+ | `sealRequests(predicate)` | 이 판단이 참인 요청을 봉인(setup). dokebi-app이 seal 도메인으로 부른다 |
88
+ | `sealOf(request)` | 봉인 요청이면 `{ path, encode(text) }`, 아니면 undefined |
89
+ | `sealing` | 제공자가 등록됐는가 |
90
+
67
91
  ## 라우트 제약 전략 (D-0030)
68
92
 
69
93
  `constraint(strategy)`는 setup 단계에서 Fastify 라우트 제약 전략(`addConstraintStrategy`)을 더한다. 그 제약을 쓰는 라우트보다 먼저 호출한다. @dokebi/app이 Host → 앱 선택(`dokebiApp`)에 쓰며, 같은 경로를 여러 라우트가 제약 값별로 나눠 가질 수 있다. start 이후 호출은 `FROZEN`이다.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,15 @@
1
1
  import { type Awaitable, type Plugin, type PluginDependency } from '@dokebi/core';
2
- import { type FastifyInstance, type FastifyPluginAsync, type FastifyPluginCallback, type FastifyPluginOptions, type FastifyRegisterOptions, type RawReplyDefaultExpression, type RawRequestDefaultExpression, type RawServerDefault, type RouteGenericInterface, type RouteOptions } from 'fastify';
3
- export type WebRoute<T extends RouteGenericInterface = RouteGenericInterface> = RouteOptions<RawServerDefault, RawRequestDefaultExpression<RawServerDefault>, RawReplyDefaultExpression<RawServerDefault>, T>;
2
+ import { type FastifyInstance, type FastifyPluginAsync, type FastifyPluginCallback, type FastifyPluginOptions, type FastifyRegisterOptions, type FastifyRequest, type RawReplyDefaultExpression, type RawRequestDefaultExpression, type RawServerDefault, type RouteGenericInterface, type RouteOptions } from 'fastify';
3
+ import { type WebSealCodecProvider, type WebSealer, type WebSealSetting } from './seal.js';
4
+ export { SEALED_PATH_HEADER, type WebSealCodec, type WebSealCodecProvider, type WebSealer, type WebSealRequest, type WebSealSetting, } from './seal.js';
5
+ export type WebRoute<T extends RouteGenericInterface = RouteGenericInterface> = RouteOptions<RawServerDefault, RawRequestDefaultExpression<RawServerDefault>, RawReplyDefaultExpression<RawServerDefault>, T> & {
6
+ /**
7
+ * Sealing of this route (D-0062): `false` keeps it plain on a seal host (webhooks,
8
+ * server-to-server), `true` or a function returning true seals it on any host. Unset: the host
9
+ * decides (dokebi-app `domains.<host>.seal`). Stored as `config.dokebiSeal`.
10
+ */
11
+ readonly seal?: WebSealSetting;
12
+ };
4
13
  export interface WebHealth {
5
14
  readonly ready: boolean;
6
15
  readonly live: boolean;
@@ -21,6 +30,23 @@ export interface WebApi {
21
30
  * `trustProxy`, otherwise `Host`. Lower case, port kept. Takes a raw or Fastify request.
22
31
  */
23
32
  requestHost(request: WebRequestLike): string;
33
+ /**
34
+ * Fills the HTTP seal slot (D-0062); the dokebi-seal plugin calls it. Setup only, once. Sealed
35
+ * request bodies of `provider.contentType` are opened before routing reaches the handler.
36
+ */
37
+ sealCodec(provider: WebSealCodecProvider): void;
38
+ /**
39
+ * Seals every request the predicate accepts (dokebi-app: hosts with `seal: true`), except
40
+ * health routes, `seal: false` routes and `sealExclude` prefixes. Setup only.
41
+ */
42
+ sealRequests(predicate: (request: FastifyRequest) => boolean): void;
43
+ /**
44
+ * The sealing of a request, or undefined when it is plain: for code that writes its own body
45
+ * (the Inertia first page, SSE event data). JSON responses are sealed by dokebi-web itself.
46
+ */
47
+ sealOf(request: FastifyRequest): WebSealer | undefined;
48
+ /** True once a seal codec is registered. */
49
+ readonly sealing: boolean;
24
50
  }
25
51
  export interface WebRequestLike {
26
52
  readonly headers: Readonly<Record<string, string | string[] | undefined>>;
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@ import { setTimeout as delay, setImmediate as immediate } from 'node:timers/prom
4
4
  import { types } from 'node:util';
5
5
  import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
6
6
  import Fastify, {} from 'fastify';
7
+ import { checkSealSetting, sealExclude, WebSealing, } from './seal.js';
8
+ export { SEALED_PATH_HEADER, } from './seal.js';
7
9
  export class WebError extends Error {
8
10
  code;
9
11
  constructor(code) {
@@ -128,10 +130,12 @@ function normalize(input) {
128
130
  'requestTimeout',
129
131
  'healthRoutes',
130
132
  'trustProxy',
133
+ 'sealDriftMs',
134
+ 'sealExclude',
131
135
  ]);
132
136
  if (!value)
133
137
  throw new WebError('INVALID_OPTIONS');
134
- const host = value.host === undefined ? '127.0.0.1' : value.host, port = value.port === undefined ? 0 : value.port, bodyLimit = value.bodyLimit === undefined ? 1048576 : value.bodyLimit, requestTimeout = value.requestTimeout === undefined ? 30000 : value.requestTimeout;
138
+ const host = value.host === undefined ? '127.0.0.1' : value.host, port = value.port === undefined ? 0 : value.port, bodyLimit = value.bodyLimit === undefined ? 1048576 : value.bodyLimit, requestTimeout = value.requestTimeout === undefined ? 30000 : value.requestTimeout, sealDriftMs = value.sealDriftMs === undefined ? 60000 : value.sealDriftMs, exclude = sealExclude(value.sealExclude);
135
139
  if (typeof host !== 'string' ||
136
140
  !host ||
137
141
  host.length > 253 ||
@@ -146,7 +150,12 @@ function normalize(input) {
146
150
  typeof requestTimeout !== 'number' ||
147
151
  !Number.isSafeInteger(requestTimeout) ||
148
152
  requestTimeout < 1 ||
149
- requestTimeout > 2147483647)
153
+ requestTimeout > 2147483647 ||
154
+ typeof sealDriftMs !== 'number' ||
155
+ !Number.isSafeInteger(sealDriftMs) ||
156
+ sealDriftMs < 1000 ||
157
+ sealDriftMs > 600000 ||
158
+ !exclude)
150
159
  throw new WebError('INVALID_OPTIONS');
151
160
  return {
152
161
  host,
@@ -155,6 +164,8 @@ function normalize(input) {
155
164
  requestTimeout,
156
165
  healthRoutes: healthRoutes(value.healthRoutes),
157
166
  trustProxy: trustProxy(value.trustProxy),
167
+ sealDriftMs,
168
+ sealExclude: exclude,
158
169
  };
159
170
  }
160
171
  const hooks = new Map([
@@ -179,6 +190,7 @@ class WebOwner {
179
190
  #frozen = false;
180
191
  #draining = false;
181
192
  #address;
193
+ #sealing;
182
194
  api;
183
195
  constructor(context, options, health) {
184
196
  this.context = context;
@@ -199,6 +211,8 @@ class WebOwner {
199
211
  requestTimeout: options.requestTimeout,
200
212
  healthRoutes: options.healthRoutes ? { ...options.healthRoutes } : false,
201
213
  trustProxy: options.trustProxy.length,
214
+ sealDriftMs: options.sealDriftMs,
215
+ sealExclude: options.sealExclude.length,
202
216
  health: health !== undefined,
203
217
  cluster: cluster.isWorker ? 'worker' : 'none',
204
218
  });
@@ -286,8 +300,33 @@ class WebOwner {
286
300
  reply.header('connection', 'close');
287
301
  return payload;
288
302
  });
303
+ // D-0062: the seal slot. Both hooks do nothing until something asks for sealing.
304
+ const sealing = new WebSealing(context.logger, { driftMs: options.sealDriftMs, exclude: options.sealExclude }, (request) => this.api.requestHost(request), errorText);
305
+ this.#sealing = sealing;
306
+ this.server.addHook('onRequest', async (request, reply) => {
307
+ if (!sealing.provider)
308
+ return;
309
+ return sealing.onRequest(request, reply);
310
+ });
311
+ this.server.addHook('onSend', async (request, reply, payload) => {
312
+ if (!sealing.provider)
313
+ return payload;
314
+ return sealing.onSend(request, reply, payload);
315
+ });
289
316
  this.server.addHook('onRoute', (route) => {
290
- if (route.config?.dokebiHealth === true)
317
+ // `seal` on a route given to Fastify directly (a register() scope, @dokebi/router mount)
318
+ // becomes `config.dokebiSeal` too, so every way of adding a route can opt out (D-0062).
319
+ const options = route;
320
+ if (options.seal !== undefined) {
321
+ options.config = {
322
+ ...route.config,
323
+ dokebiSeal: checkSealSetting(options.seal),
324
+ };
325
+ delete options.seal;
326
+ }
327
+ const config = route.config;
328
+ sealing.route(checkSealSetting(config?.dokebiSeal));
329
+ if (config?.dokebiHealth === true)
291
330
  return;
292
331
  const original = route.handler;
293
332
  route.handler = function (request, reply) {
@@ -324,7 +363,14 @@ class WebOwner {
324
363
  },
325
364
  route: (route) => {
326
365
  this.#assertMutable();
327
- this.server.route(route);
366
+ const { seal, ...rest } = route;
367
+ if (seal === undefined)
368
+ this.server.route(rest);
369
+ else
370
+ this.server.route({
371
+ ...rest,
372
+ config: { ...rest.config, dokebiSeal: checkSealSetting(seal) },
373
+ });
328
374
  },
329
375
  register: (plugin, options) => {
330
376
  this.#assertMutable();
@@ -348,6 +394,20 @@ class WebOwner {
348
394
  .trim()
349
395
  .toLowerCase();
350
396
  },
397
+ sealCodec: (provider) => {
398
+ this.#assertMutable();
399
+ sealing.setProvider(provider);
400
+ // Registered on the root before any plugin scope exists, so every route inherits it.
401
+ this.server.addContentTypeParser(provider.contentType, { parseAs: 'string', bodyLimit: options.bodyLimit }, (request, body) => sealing.parse(request, String(body)));
402
+ },
403
+ sealRequests: (predicate) => {
404
+ this.#assertMutable();
405
+ sealing.addPredicate(predicate);
406
+ },
407
+ sealOf: (request) => sealing.sealOf(request),
408
+ get sealing() {
409
+ return sealing.provider !== undefined;
410
+ },
351
411
  });
352
412
  }
353
413
  #assertMutable() {
@@ -429,6 +489,8 @@ class WebOwner {
429
489
  this.#frozen = true;
430
490
  const started = performance.now();
431
491
  await this.server.ready();
492
+ // After every setup (routes and the seal provider are all known): fail closed (D-0062).
493
+ this.#sealing.check();
432
494
  this.context.logger.log('debug', 'Web routes frozen', {
433
495
  ms: Math.round(performance.now() - started),
434
496
  });
@@ -581,7 +643,7 @@ class WebRuntime {
581
643
  }
582
644
  export const createPlugin = definePlugin({
583
645
  name: 'dokebi-web',
584
- version: '0.1.2',
646
+ version: '0.2.0',
585
647
  core: '^0.2.0',
586
648
  options: normalize,
587
649
  entry: parseEntry,
@@ -599,6 +661,6 @@ export const createPlugin = definePlugin({
599
661
  export const dependency = providerDependency({
600
662
  name: 'dokebi-web',
601
663
  packageName: '@dokebi/web',
602
- version: '^0.1.0',
664
+ version: '^0.2.0',
603
665
  load: () => import('./index.js'),
604
666
  });
package/dist/seal.d.ts ADDED
@@ -0,0 +1,82 @@
1
+ import type { Logger } from '@dokebi/core';
2
+ import type { FastifyReply, FastifyRequest } from 'fastify';
3
+ /** A route's own seal setting: true seals it on every host, false keeps it plain on seal hosts. */
4
+ export type WebSealSetting = boolean | ((request: FastifyRequest) => boolean);
5
+ /** What a codec provider is told about one sealed request. */
6
+ export interface WebSealRequest {
7
+ /** The request host without port, lower case (`requestHost`, so trustProxy applies). */
8
+ readonly host: string;
9
+ /** The request path as the browser sent it, without the query. */
10
+ readonly path: string;
11
+ readonly userAgent: string;
12
+ /** Accepted clock difference of a sealed body (`sealDriftMs`). */
13
+ readonly driftMs: number;
14
+ }
15
+ /** Seals and opens the bodies of one request. Its errors never reach the client. */
16
+ export interface WebSealCodec {
17
+ /** Opens a sealed request body; rejects (with a `reason` such as `drift` or `replay`) to refuse it. */
18
+ decode(body: string): Promise<string>;
19
+ /** Seals one response text (`E:<ts>:<base64>`). */
20
+ encode(text: string): string;
21
+ }
22
+ /** The shape the dokebi-seal plugin provides (structural; never imported). */
23
+ export interface WebSealCodecProvider {
24
+ /** Media type of sealed bodies, both ways (for example `application/vnd.dokebi-seal`). */
25
+ readonly contentType: string;
26
+ /** The codec of one request. Replay nonces are the provider's (the hub's `nonces()`). */
27
+ forRequest(request: WebSealRequest): WebSealCodec;
28
+ }
29
+ /** The sealing of one sealed request, for code that writes its own body (Inertia page, SSE). */
30
+ export interface WebSealer {
31
+ /** The path the request was sealed with (the key input), also sent as `x-dokebi-sealed-path`. */
32
+ readonly path: string;
33
+ /** Seals one text with this request's key. */
34
+ encode(text: string): string;
35
+ }
36
+ /** Response header naming the path a sealed response was sealed with (after a redirect it is the final one). */
37
+ export declare const SEALED_PATH_HEADER = "x-dokebi-sealed-path";
38
+ /** The media type of a Content-Type value: lower case, without parameters. */
39
+ export declare function mediaType(value: unknown): string;
40
+ /** `/a/b?c` → `/a/b`. */
41
+ export declare function pathOf(url: string): string;
42
+ /** Validates `sealExclude`: path prefixes, matched at a segment boundary. */
43
+ export declare function sealExclude(input: unknown): readonly string[] | undefined;
44
+ export declare function checkSealSetting(value: unknown): WebSealSetting | undefined;
45
+ export interface SealingOptions {
46
+ readonly driftMs: number;
47
+ readonly exclude: readonly string[];
48
+ }
49
+ /**
50
+ * The seal slot of one web server. Requests are sealed by their route (`seal`) or by a
51
+ * registered predicate (dokebi-app: hosts with `seal: true`); health routes, `seal: false`
52
+ * routes and `sealExclude` prefixes stay plain. A sealed request's body must be sealed (or
53
+ * multipart), and its JSON responses are sealed on the way out.
54
+ */
55
+ export declare class WebSealing {
56
+ #private;
57
+ readonly logger: Logger;
58
+ readonly options: SealingOptions;
59
+ readonly requestHost: (request: FastifyRequest) => string;
60
+ /** The full text of a caught value for the `error` log field (D-0047). */
61
+ readonly errorText: (error: unknown) => string;
62
+ constructor(logger: Logger, options: SealingOptions, requestHost: (request: FastifyRequest) => string,
63
+ /** The full text of a caught value for the `error` log field (D-0047). */
64
+ errorText: (error: unknown) => string);
65
+ get provider(): WebSealCodecProvider | undefined;
66
+ /** True when anything may be sealed: a predicate or a sealing route. */
67
+ get wanted(): boolean;
68
+ setProvider(provider: WebSealCodecProvider): void;
69
+ addPredicate(predicate: (request: FastifyRequest) => boolean): void;
70
+ /** Counts a route whose own setting may seal it (for the missing provider check). */
71
+ route(setting: WebSealSetting | undefined): void;
72
+ /** Fail closed at start: something wants sealing but no provider will seal it. */
73
+ check(): void;
74
+ /** The sealer of a request, decided once; undefined for a plain request. */
75
+ sealOf(request: FastifyRequest): WebSealer | undefined;
76
+ /** onRequest: decides the request and refuses a plain body on a sealed one (415). */
77
+ onRequest(request: FastifyRequest, reply: FastifyReply): Promise<unknown>;
78
+ /** The body parser of the sealed media type: opens, then parses JSON. Refusals are 400. */
79
+ parse(request: FastifyRequest, body: string): Promise<unknown>;
80
+ /** onSend: seals the JSON response of a sealed request (other types pass unchanged). */
81
+ onSend(request: FastifyRequest, reply: FastifyReply, payload: unknown): unknown;
82
+ }
package/dist/seal.js ADDED
@@ -0,0 +1,303 @@
1
+ /** Response header naming the path a sealed response was sealed with (after a redirect it is the final one). */
2
+ export const SEALED_PATH_HEADER = 'x-dokebi-sealed-path';
3
+ const PATH = /^\/[^?#\s]{0,2047}$/;
4
+ const REPEAT_INTERVAL_MS = 10_000;
5
+ const JSON_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json$/;
6
+ /** The media type of a Content-Type value: lower case, without parameters. */
7
+ export function mediaType(value) {
8
+ return (String(Array.isArray(value) ? value[0] : (value ?? ''))
9
+ .split(';', 1)[0]
10
+ ?.trim()
11
+ .toLowerCase() ?? '');
12
+ }
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';
19
+ }
20
+ /** `/a/b?c` → `/a/b`. */
21
+ export function pathOf(url) {
22
+ const end = url.search(/[?#]/);
23
+ return end === -1 ? url : url.slice(0, end);
24
+ }
25
+ /** A host without its port, lower case; IPv6 literals keep their brackets (as `location.hostname`). */
26
+ function withoutPort(host) {
27
+ const raw = host.toLowerCase();
28
+ if (raw.startsWith('['))
29
+ return raw.slice(0, raw.indexOf(']') + 1);
30
+ const colon = raw.lastIndexOf(':');
31
+ return colon === -1 ? raw : raw.slice(0, colon);
32
+ }
33
+ /** Validates `sealExclude`: path prefixes, matched at a segment boundary. */
34
+ export function sealExclude(input) {
35
+ if (input === undefined)
36
+ return Object.freeze([]);
37
+ if (!Array.isArray(input) ||
38
+ input.length > 64 ||
39
+ !input.every((item) => typeof item === 'string' && PATH.test(item)))
40
+ return undefined;
41
+ return Object.freeze([...new Set(input.map((item) => item.replace(/(.)\/+$/, '$1')))]);
42
+ }
43
+ export function checkSealSetting(value) {
44
+ if (value === undefined || typeof value === 'boolean' || typeof value === 'function')
45
+ return value;
46
+ throw new TypeError('Route seal must be a boolean or a function of the request');
47
+ }
48
+ class Repeats {
49
+ #keys = new Map();
50
+ take(key, now = Date.now()) {
51
+ const entry = this.#keys.get(key);
52
+ if (entry && now < entry.until) {
53
+ entry.repeated++;
54
+ return undefined;
55
+ }
56
+ if (!entry && this.#keys.size >= 256)
57
+ this.#keys.clear();
58
+ this.#keys.set(key, { until: now + REPEAT_INTERVAL_MS, repeated: 0 });
59
+ return entry?.repeated ?? 0;
60
+ }
61
+ }
62
+ function coded(message, code, statusCode, cause) {
63
+ return Object.assign(new Error(message, cause === undefined ? undefined : { cause }), {
64
+ code,
65
+ statusCode,
66
+ });
67
+ }
68
+ /**
69
+ * The seal slot of one web server. Requests are sealed by their route (`seal`) or by a
70
+ * registered predicate (dokebi-app: hosts with `seal: true`); health routes, `seal: false`
71
+ * routes and `sealExclude` prefixes stay plain. A sealed request's body must be sealed (or
72
+ * multipart), and its JSON responses are sealed on the way out.
73
+ */
74
+ export class WebSealing {
75
+ logger;
76
+ options;
77
+ requestHost;
78
+ errorText;
79
+ #provider;
80
+ #predicates = [];
81
+ /** Routes that may seal (`seal: true` or a function): they need a provider. */
82
+ #routes = 0;
83
+ /** The sealer of every decided request (null: plain). */
84
+ #decided = new WeakMap();
85
+ /** Replies this layer answered itself (415, refused body): sent plain so any client can read them. */
86
+ #plain = new WeakSet();
87
+ #repeats = new Repeats();
88
+ constructor(logger, options, requestHost,
89
+ /** The full text of a caught value for the `error` log field (D-0047). */
90
+ errorText) {
91
+ this.logger = logger;
92
+ this.options = options;
93
+ this.requestHost = requestHost;
94
+ this.errorText = errorText;
95
+ }
96
+ get provider() {
97
+ return this.#provider;
98
+ }
99
+ /** True when anything may be sealed: a predicate or a sealing route. */
100
+ get wanted() {
101
+ return this.#predicates.length > 0 || this.#routes > 0;
102
+ }
103
+ setProvider(provider) {
104
+ if (this.#provider)
105
+ throw new TypeError('A seal codec is already registered');
106
+ if (provider === null ||
107
+ typeof provider !== 'object' ||
108
+ typeof provider.forRequest !== 'function' ||
109
+ typeof provider.contentType !== 'string' ||
110
+ !/^[a-z]+\/[a-z0-9.+-]{1,100}$/.test(provider.contentType))
111
+ throw Object.assign(new TypeError('Invalid seal codec provider'), {
112
+ code: 'SEAL_PROVIDER_INVALID',
113
+ });
114
+ this.#provider = provider;
115
+ this.logger.log('debug', 'Web seal codec registered', {
116
+ contentType: provider.contentType,
117
+ driftMs: this.options.driftMs,
118
+ exclude: [...this.options.exclude],
119
+ });
120
+ }
121
+ addPredicate(predicate) {
122
+ if (typeof predicate !== 'function')
123
+ throw new TypeError('Seal predicate must be a function');
124
+ this.#predicates.push(predicate);
125
+ this.logger.log('debug', 'Web seal predicate registered', {
126
+ predicates: this.#predicates.length,
127
+ });
128
+ }
129
+ /** Counts a route whose own setting may seal it (for the missing provider check). */
130
+ route(setting) {
131
+ if (setting === true || typeof setting === 'function')
132
+ this.#routes++;
133
+ }
134
+ /** Fail closed at start: something wants sealing but no provider will seal it. */
135
+ check() {
136
+ this.logger.log('debug', 'Web sealing', {
137
+ provider: this.#provider !== undefined,
138
+ predicates: this.#predicates.length,
139
+ routes: this.#routes,
140
+ exclude: this.options.exclude.length,
141
+ });
142
+ if (this.wanted && !this.#provider)
143
+ throw Object.assign(new Error('Requests are sealed (a seal host or a route with seal) but no seal codec is registered; register the dokebi-seal plugin'), { code: 'SEAL_PROVIDER_MISSING' });
144
+ }
145
+ #sealedRequest(request) {
146
+ const config = (request.routeOptions?.config ?? {});
147
+ if (config.dokebiHealth === true)
148
+ return false;
149
+ const own = config.dokebiSeal;
150
+ if (own === false)
151
+ return false;
152
+ if (own === true || (typeof own === 'function' && own(request) === true))
153
+ return true;
154
+ if (!this.#predicates.length)
155
+ return false;
156
+ const path = pathOf(request.url);
157
+ for (const prefix of this.options.exclude)
158
+ if (path === prefix || path.startsWith(prefix === '/' ? prefix : `${prefix}/`))
159
+ return false;
160
+ return this.#predicates.some((predicate) => predicate(request) === true);
161
+ }
162
+ #codec(request) {
163
+ const path = pathOf(request.url);
164
+ const agent = request.headers['user-agent'];
165
+ const codec = this.#provider.forRequest({
166
+ host: withoutPort(this.requestHost(request)),
167
+ path,
168
+ userAgent: typeof agent === 'string' ? agent : '',
169
+ driftMs: this.options.driftMs,
170
+ });
171
+ return { codec, path };
172
+ }
173
+ /** The sealer of a request, decided once; undefined for a plain request. */
174
+ sealOf(request) {
175
+ const known = this.#decided.get(request);
176
+ if (known !== undefined)
177
+ return known ?? undefined;
178
+ let sealer = null;
179
+ if (this.#provider && this.#sealedRequest(request)) {
180
+ let codec;
181
+ const path = pathOf(request.url);
182
+ sealer = Object.freeze({
183
+ path,
184
+ encode: (text) => {
185
+ codec ??= this.#codec(request).codec;
186
+ return codec.encode(text);
187
+ },
188
+ });
189
+ }
190
+ this.#decided.set(request, sealer);
191
+ return sealer ?? undefined;
192
+ }
193
+ /** onRequest: decides the request and refuses a plain body on a sealed one (415). */
194
+ async onRequest(request, reply) {
195
+ const sealer = this.sealOf(request);
196
+ const debug = this.logger.isEnabled('debug');
197
+ if (!sealer)
198
+ return undefined;
199
+ if (debug)
200
+ this.logger.log('debug', 'HTTP request sealed', {
201
+ method: request.method,
202
+ path: sealer.path.slice(0, 200),
203
+ });
204
+ if (!hasBody(request.headers))
205
+ return undefined;
206
+ const type = mediaType(request.headers['content-type']);
207
+ const provider = this.#provider;
208
+ // Only a sealed body, or an upload (multipart/form-data: files are not sealed), gets through.
209
+ // Every other type is refused before any parser runs, so no parser can let plain text in.
210
+ if (type === provider.contentType || type === 'multipart/form-data')
211
+ return undefined;
212
+ const route = request.routeOptions.url ?? 'unmatched';
213
+ const repeated = this.#repeats.take(`plain ${request.method} ${route}`);
214
+ if (repeated !== undefined)
215
+ this.logger.log('warn', 'Plain request body refused on a sealed route', {
216
+ code: 'SEAL_REQUIRED',
217
+ reason: 'plain-body',
218
+ method: request.method,
219
+ route,
220
+ contentType: type.slice(0, 100) || null,
221
+ ...(repeated ? { repeated } : {}),
222
+ });
223
+ this.#plain.add(request);
224
+ return reply
225
+ .code(415)
226
+ .type('application/json; charset=utf-8')
227
+ .send({
228
+ error: 'SEAL_REQUIRED',
229
+ 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.`,
230
+ });
231
+ }
232
+ /** The body parser of the sealed media type: opens, then parses JSON. Refusals are 400. */
233
+ async parse(request, body) {
234
+ let plain;
235
+ try {
236
+ plain = await this.#codec(request).codec.decode(body);
237
+ }
238
+ catch (error) {
239
+ const reason = typeof error?.reason === 'string'
240
+ ? String(error.reason)
241
+ : 'unknown';
242
+ const route = request.routeOptions.url ?? 'unmatched';
243
+ const repeated = this.#repeats.take(`open ${route} ${reason}`);
244
+ // The reason goes to the log only: telling the client drift from replay is an oracle.
245
+ if (repeated !== undefined)
246
+ this.logger.log('warn', 'Sealed request body refused', {
247
+ code: 'SEAL_BODY_REFUSED',
248
+ reason,
249
+ method: request.method,
250
+ route,
251
+ ...(repeated ? { repeated } : {}),
252
+ });
253
+ this.#plain.add(request);
254
+ throw coded('Sealed request body refused', 'SEAL_BODY_REFUSED', 400, error);
255
+ }
256
+ if (plain === '')
257
+ return undefined;
258
+ try {
259
+ return JSON.parse(plain);
260
+ }
261
+ catch (error) {
262
+ throw coded('Sealed request body is not JSON', 'SEAL_BODY_NOT_JSON', 400, error);
263
+ }
264
+ }
265
+ /** onSend: seals the JSON response of a sealed request (other types pass unchanged). */
266
+ onSend(request, reply, payload) {
267
+ const sealer = this.#decided.get(request);
268
+ if (!sealer || this.#plain.has(request) || payload === null || payload === undefined)
269
+ return payload;
270
+ if (!JSON_TYPE.test(mediaType(reply.getHeader('content-type'))))
271
+ return payload;
272
+ const provider = this.#provider;
273
+ try {
274
+ let text;
275
+ if (typeof payload === 'string')
276
+ text = payload;
277
+ else if (Buffer.isBuffer(payload))
278
+ text = payload.toString('utf8');
279
+ else
280
+ throw coded('A streamed JSON response cannot be sealed', 'SEAL_STREAM_UNSUPPORTED', 500);
281
+ const sealed = sealer.encode(text);
282
+ reply.header('content-type', provider.contentType);
283
+ reply.header(SEALED_PATH_HEADER, sealer.path);
284
+ return sealed;
285
+ }
286
+ catch (error) {
287
+ // Fail closed: no plain JSON leaves a sealed request.
288
+ const route = request.routeOptions.url ?? 'unmatched';
289
+ const repeated = this.#repeats.take(`encode ${route}`);
290
+ if (repeated !== undefined)
291
+ this.logger.log('error', 'Sealing a response failed', {
292
+ code: error.code ?? 'SEAL_ENCODE_FAILED',
293
+ method: request.method,
294
+ route,
295
+ error: this.errorText(error),
296
+ ...(repeated ? { repeated } : {}),
297
+ });
298
+ reply.code(500).header('content-type', 'application/json; charset=utf-8');
299
+ reply.removeHeader(SEALED_PATH_HEADER);
300
+ return '{"error":"INTERNAL_SERVER_ERROR"}';
301
+ }
302
+ }
303
+ }
@@ -66,6 +66,24 @@
66
66
  },
67
67
  "default": [],
68
68
  "description": "Proxy addresses whose X-Forwarded-Host/For/Proto are trusted, e.g. [127.0.0.1, ::1] for a local tunnel"
69
+ },
70
+ "sealDriftMs": {
71
+ "type": "integer",
72
+ "minimum": 1000,
73
+ "maximum": 600000,
74
+ "default": 60000,
75
+ "description": "Seal hosts (D-0062): accepted clock difference of a sealed request body in ms; replay nonces are kept twice as long"
76
+ },
77
+ "sealExclude": {
78
+ "type": "array",
79
+ "maxItems": 64,
80
+ "uniqueItems": true,
81
+ "items": {
82
+ "type": "string",
83
+ "pattern": "^/[^?#\\s]{0,2047}$"
84
+ },
85
+ "default": [],
86
+ "description": "Seal hosts (D-0062): path prefixes that stay plain (webhooks, server-to-server), matched at a / boundary"
69
87
  }
70
88
  }
71
89
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/web",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "MIT",