@dokebi/web 0.2.0 → 0.4.1

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,88 +1,237 @@
1
- # AI 작업 안내 — @dokebi/web 0.2.0
1
+ # AI guide — @dokebi/web 0.4.1
2
2
 
3
- Fastify 5 HTTP 서버를 앱이 소유하게 하는 플러그인이다. 준비 전·종료 중 요청 차단(503), health 경로, 진행 요청을 기다리는 drain, cluster 워커의 무중단 교체, 신뢰 프락시를 맡는다. 라우터·컨트롤러·뷰·DB는 필수가 아니다. Node >=24.0.0, core ^0.2.0. 세부는 [README](README.md)다.
3
+ A plugin through which the app owns a Fastify 5 HTTP server. It blocks requests before the app is ready and while it shuts down (503), serves health routes, drains requests in progress, swaps cluster workers without downtime and handles trusted proxies. Routers, controllers, views and DBs are not required. Node >=24.0.0, core ^0.4.0. Details are in the [README](README.md).
4
4
 
5
- ## 1. 설치와 설정
5
+ ## 1. Install and configure
6
6
 
7
7
  ```sh
8
- npx dokebi add @dokebi/web # src/infra/web/requires.ts(onClose에서 쓰는 자원 목록)
8
+ npx dokebi add @dokebi/web # src/infra/web/extension.ts (the requires list + an empty AppWeb extension)
9
9
  ```
10
10
 
11
+ > `npx dokebi` is the @dokebi/cli installed in the project (`dokebi init` adds it to devDependencies). The npm package `dokebi` is not this CLI, so never use `npx -y dokebi`. Without an installed CLI use `npx -y @dokebi/cli …`.
12
+
11
13
  ```yaml
12
14
  dokebi-web:
13
- host: 127.0.0.1 # 기본. 외부에서 받으려면 0.0.0.0(앞단 프락시 권장)
14
- port: 3000 # 기본 0(임시 포트), 0..65535
15
- bodyLimit: 1048576 # 1 B..64 MiB
16
- requestTimeout: 30000 # 요청 수신 제한(업무 실행 제한이 아님)
17
- healthRoutes: { live: /health/live, ready: /health/ready } # false면 등록 안 함
18
- trustProxy: [127.0.0.1, "::1"] # 정확한 IP만, 최대 64개
19
- sealDriftMs: 60000 # 봉인 호스트(D-0062): 봉인 본문 ts 허용 오차
20
- sealExclude: [/webhooks] # 봉인 호스트에서도 평문인 경로 접두
15
+ host: 127.0.0.1 # default; 0.0.0.0 to accept outside traffic (a front proxy is recommended)
16
+ port: 3000 # default 0 (an ephemeral port), 0..65535
17
+ maxBodyBytes: 1048576 # 1 B..64 MiB (named bodyLimit before 0.4.0)
18
+ requestTimeoutMs: 30000 # limit for receiving a request, not for running the work (named requestTimeout before 0.4.0)
19
+ healthRoutes: { live: /health/live, ready: /health/ready } # false registers none
20
+ trustProxy: [127.0.0.1, "::1"] # exact IPs only, up to 64
21
+ sealDriftMs: 60000 # seal hosts (D-0062): allowed ts drift of sealed bodies
22
+ sealExclude: [/webhooks] # path prefixes that stay plain on seal hosts
23
+ formBody: true # HTML forms (application/x-www-form-urlencoded) into request.body; default false
24
+ formMaxFields: 1000 # field limit per form, 1..10000; above it 413 FORM_BODY_TOO_MANY_FIELDS
25
+ developmentErrors: true # outside production (NODE_ENV=production) error bodies also carry fix and details; false always answers like production
21
26
  ```
22
27
 
23
- TLS·HTTP2·임의 Fastify 생성 옵션은 아직 공개하지 않는다(앞단 프락시에서 TLS).
28
+ | Key | Type | Default | Description |
29
+ |---|---|---|---|
30
+ | `host` | string | `127.0.0.1` | listen address |
31
+ | `port` | integer | 0 | 0..65535; 0 picks an ephemeral port |
32
+ | `maxBodyBytes` | integer | 1048576 | request body limit, 1 B..64 MiB |
33
+ | `bodyLimit` | integer | — | deprecated name of `maxBodyBytes` (D-0071): warns `OPTION_DEPRECATED`; setting both is `INVALID_OPTIONS` |
34
+ | `requestTimeoutMs` | integer | 30000 | time to receive a request, 1..2147483647 ms; not a limit on the work |
35
+ | `requestTimeout` | integer | — | deprecated name of `requestTimeoutMs` (D-0071) |
36
+ | `healthRoutes` | `{ live?, ready? }` or `false` | `{ live: /health/live, ready: /health/ready }` | missing keys use the default path; paths start with `/`, have no `?`, `#` or spaces, and differ; `false` registers neither |
37
+ | `trustProxy` | string[] | `[]` | exact IPv4/IPv6 proxy addresses (up to 64) whose `X-Forwarded-*` headers are trusted |
38
+ | `sealDriftMs` | integer | 60000 | allowed timestamp drift of sealed bodies, 1000..600000; nonces are kept twice as long |
39
+ | `sealExclude` | string[] | `[]` | path prefixes (with a `/` boundary) that stay plain on seal hosts, up to 64 |
40
+ | `formBody` | boolean | false | parse `application/x-www-form-urlencoded` bodies |
41
+ | `formMaxFields` | integer | 1000 | field limit per form, 1..10000 |
42
+ | `developmentErrors` | boolean | true | outside production, error bodies carry `fix` and `details`; false answers like production everywhere |
24
43
 
25
- ## 2. 사용
44
+ **To accept HTML forms set `formBody: true`** (off by default, D-0068). While off, a form request gets 415 `{ error: 'FORM_BODY_DISABLED', fix }` before the handler, and the `fix` and a warn log (`HTTP form body refused`, `code: FORM_BODY_DISABLED`, once per route every 10 seconds) name this option. When on, the body is decoded with `node:querystring` into `request.body`: an object without a prototype, repeated names become arrays, `+` and `%XX` are decoded, and `maxBodyBytes` applies. It is off by default because a form POST is a request other sites can send without a preflight (a CORS simple request): cookie-authenticated apps keep the session cookie `SameSite=Lax` (the @dokebi/session default) or `Strict`, or check a CSRF token. Seal hosts still refuse forms with 415 `SEAL_REQUIRED` when it is on (§3.1).
26
45
 
27
- 보통은 @dokebi/app·module·router가 web 위에 라우트를 만든다. 직접 쓸 때:
46
+ `dokebi verify` starts the app with `DOKEBI_VERIFY_TOKEN` (random), and only when that variable is set does this plugin add the header `x-dokebi-verify: <token>` to every response. verify counts only answers with the right header, so another app on the same port is never mistaken for yours (D-0065 §11). Without the variable (normal runs and production) the hook does not exist. A malformed value is ignored with warn `VERIFY_TOKEN_INVALID`.
28
47
 
29
- ```ts
48
+ `dokebi start` gives the app a random per-start `DOKEBI_INSTANCE_TOKEN` (D-0073). While that variable is set, a request carrying a challenge in the header `x-dokebi-instance` (16–128 characters of `A-Za-z0-9_-`) is answered at once with `204` and `x-dokebi-instance: <base64url HMAC-SHA256(token, challenge)>`; no route or app code runs, and the token itself never goes on the wire. Requests without that header are served as usual. `dokebi stop` and `status` use it to prove a recorded pid is this app where `ps` is blocked. A malformed token is ignored with warn `INSTANCE_TOKEN_INVALID`; without the variable no hook exists.
49
+
50
+ Fastify construction options such as HTTPS, HTTP/2, `serverFactory` or the query-string parser are not dokebi.yaml options; give them through the extension hook `fastifyOptions` (§8). Usually TLS ends at a front proxy.
51
+
52
+ ## 2. Usage
53
+
54
+ Usually @dokebi/app, module and router build routes on top of web. To use it directly:
55
+
56
+ ```ts snippet
30
57
  import cors from '@fastify/cors';
31
58
  import { dependency as web } from '@dokebi/web';
32
- // dependencies/requires에 web을 넣고 setup에서:
59
+ // put web into dependencies/requires, then in setup:
33
60
  const http = context.getDependency(web);
34
61
  http.route({ method: 'GET', url: '/ping', handler: async () => ({ ok: true }) });
35
- http.register(cors, { origin: ['https://a.com'] }); // Fastify 확장(옵션 필수, 없으면 {})
62
+ http.register(cors, { origin: ['https://a.com'] }); // Fastify plugin (options required; {} when none)
36
63
  http.route({ method: 'POST', url: '/import', handler: async (request, reply) => {
37
- void http.track(() => importLater(request.body)); // 응답 뒤 계속되는 업무는 track으로 drain 대상에
64
+ void http.track(() => importLater(request.body)); // work that outlives the response joins the drain via track
38
65
  return reply.code(202).send({ accepted: true });
39
66
  }});
40
67
  ```
41
68
 
42
- | API | 뜻 |
69
+ | API | Meaning |
43
70
  |---|---|
44
- | `route(options)` | Fastify RouteOptions(타입·schema 유지). setup 중에만, 이후 `FROZEN` |
45
- | `register(plugin, options)` | Fastify async·callback 플러그인(scope·decorator·hook 유지). setup 중에만 |
46
- | `constraint(strategy)` | 라우트 제약 전략 추가(@dokebi/app의 `dokebiApp`). 그 제약을 쓰는 라우트보다 먼저, setup 중에만 |
47
- | `track(() => work)` | HTTP 응답과 수명이 다른 업무를 drain이 기다리게 함 |
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이 등록한다. 직접 부를 일은 드물다 |
51
- | `address` | listen 뒤 실제 주소(그 전 undefined). cluster 워커에서는 core `ready` 뒤에 정해지므로 다른 플러그인은 `ready`에서 읽는다 |
71
+ | `route(options)` | Fastify RouteOptions (types and schema kept). Setup only; afterwards `FROZEN` |
72
+ | `register(plugin, options)` | a Fastify async or callback plugin (scope, decorators and hooks kept). Setup only |
73
+ | `constraint(strategy)` | adds a route constraint strategy (`dokebiApp` of @dokebi/app). Setup only, before the routes that use it |
74
+ | `track(() => work)` | makes drain wait for work whose lifetime differs from the HTTP response |
75
+ | `requestHost(request)` | the request host under the trusted-proxy rules (lower case, port kept) |
76
+ | `route({ ..., seal })` | `seal: false` stays plain even on a seal host (webhooks, server to server); `true` or a function seals on any host (D-0062) |
77
+ | `sealCodec(provider)` · `sealRequests(predicate)` · `sealOf(request)` · `sealing` | the HTTP seal slot (D-0062). @dokebi/seal provides the codec and @dokebi/app registers the decision; you rarely call them yourself |
78
+ | `errorResponder(responder)` | adds an error responder (D-0074, §6): asked before web writes an error answer, the last added first; `(response) => boolean \| Promise<boolean>`, true when it sent the answer itself. @dokebi/app (HTML form redirect, error views) and template-inertia (validation redirect, error page) use it. Setup only |
79
+ | `address` | the real address after listen (undefined before). In a cluster worker it is set after core `ready`, so other plugins read it in `ready`. A process with `runtime.serving` false (a migration tool and so on) never listens, so it stays undefined |
80
+
81
+ - `dependency` of `@dokebi/web/dependency` (also exported from the root) is the provider descriptor for plugins and app code that always install web (D-0063 §6; a small module that does not load Fastify).
82
+ - `@dokebi/web/points` exports the contribution points `viewEngines` (`dokebi-web:view-engine`) and `realtime` (`dokebi-web:realtime`) and their value types (`WebViewEngine`, `WebRealtimeTransport`, `WebRealtimeScope`): template-ejs and template-inertia contribute view engines, websocket and sse contribute realtime transports, and @dokebi/app collects them.
83
+ - web also contributes Fastify `inject` to the `inject` slot of `@dokebi/core/testing` (`dokebi-testing:inject`), so `await inject('/health/live')` runs without a socket.
84
+ - Other exports: `options` (the `defineOptions` declaration) and `WebOptions`, `WebError`, `validationError` and `WebValidationError` (§6), `errorFormat` and the responder types (`WebErrorResponder`, `WebErrorResponse`, `WebErrorFormat`, `WebFieldError`), the form helpers `isFormSubmission`, `formFieldErrors`, `formOldInput`, `formBackTarget` and their types `WebFormRequest`, `WebFormValue` (0.4.1, §6), `WebExtension` and its types, `SEALED_PATH_HEADER` (`x-dokebi-sealed-path`) and the seal types.
85
+
86
+ ## 3. Start and request blocking
87
+
88
+ - web listens in its start, after every setup. **A cluster worker (`context.runtime.role === 'worker'`) listens in the core `ready` hook** (D-0034), so only workers whose whole app is ready get connections. With `runtime.serving` false it never listens (D-0063 §4).
89
+ - Until the app has started and health is ready, business requests get 503 `{ error: 'SERVICE_UNAVAILABLE', reason }` (reason `STARTING`, `NOT_READY` or `DRAINING`); a browser page (§6 format rule) gets the same as a small HTML page. The status, headers (`retry-after` and so on) and body can be changed with the extension hook `unavailable` (§8); a hook body of the error shape (`{ error, … }`) is still drawn as a page for a browser. The request is refused either way, so drain stays correct. Error responders are not asked for these refusals (the app is starting or draining).
90
+ - Health routes: live 200/503, ready 200/503 (app state and the health checks). `dokebi-health` is an optional dependency: when registered it is connected automatically, otherwise only the app state counts. Health is per app, not a cluster-wide aggregate.
91
+
92
+ ### 3.1 HTTP on seal hosts (D-0062)
93
+
94
+ With @dokebi/seal and @dokebi/app, requests to a seal host behave like this: JSON responses (4xx included) go out as an `E:<ts>:<b64>` body with `Content-Type: application/vnd.dokebi-seal` and `x-dokebi-sealed-path`, and request bodies must be sealed. Plain JSON, urlencoded and text bodies get **415 `SEAL_REQUIRED`** before the handler (multipart uploads pass). Browsers use `sealedFetch` and `sealInertia` of `@dokebi/seal/http`. Routes that cannot be sealed, such as webhooks, opt out with `seal: false` or `sealExclude`. HTML responses (EJS) stay as they are. Asking for sealing without a provider fails the start with `SEAL_PROVIDER_MISSING`. Sealing is obfuscation and replay protection; confidentiality comes from TLS.
95
+
96
+ ## 4. Shutdown (drain)
97
+
98
+ - Single process: new requests get 503, and drain waits for responses in progress, handler Promises (including the part that continues after the response was sent), request hooks, after-response hooks (`onResponse`, `onError`, `onTimeout`, `onRequestAbort`) and `track` work. When a client disconnects first, drain still waits for that request's hooks and handler (D-0023). Requests are counted without a Promise each (D-0068). When the core drain deadline (default 20 s) passes or on `stop({ force: true })`, remaining connections are cut and drain returns (core records `DRAIN_TIMEOUT`). After every drain succeeded, cleanup calls `Fastify.close` (onClose runs).
99
+ - Cluster worker (D-0036): the listen socket closes first so the primary sends new connections to other workers; requests on open keep-alive connections are served and then closed with `Connection: close`. The worker stays up at least 100 ms. A request sent at the moment an idle keep-alive connection closes can get `ECONNRESET` (inherent to HTTP); non-browser clients retry an idempotent request on a reused socket once.
52
100
 
53
- ## 3. 시작과 요청 차단
101
+ ## 5. Ownership rules (important)
54
102
 
55
- - 모든 setup 뒤 web start에서 listen한다. **cluster 워커는 core `ready` 훅에서 listen**한다(D-0034). 앱 전체가 준비된 워커만 연결을 받게 하기 위해서다.
56
- - 앱 start 완료와 health ready 전에는 업무 요청에 503 `{ error: 'SERVICE_UNAVAILABLE', reason }`(reason: `STARTING`·`NOT_READY`·`DRAINING`).
57
- - health 경로: live 200/503, ready 200/503(앱 상태와 health check). 앱마다 독립이고 cluster 전체 집계가 아니다.
103
+ - **Put every Dokebi resource that a Fastify `onClose` hook uses into `entry.requires`** (in a CLI project, `requires` of `src/infra/web/extension.ts`). Cleanup runs in reverse initialisation order, so web must depend on the resource for the resource to close after Fastify.close. Entries are plugin instances (converted with core `dependencyOf`) or `PluginDependency` descriptors. Putting a `dokebi-health` instance there makes it required instead of optional.
104
+ - Never close a borrowed DB pool or similar in a handler.
105
+ - For callback hooks the end is done or the end of the response; for async hooks it is the returned Promise. Do not mix async and done. Work that continues in raw streams, timers or outside events must be awaited with `track` or the owning plugin's drain.
106
+ - Calling `listen`/`close` directly, overwriting root hooks or bypassing the reserved `dokebiHealth` config are outside the contract.
58
107
 
59
- ## 3-1. 봉인 호스트의 HTTP(D-0062)
108
+ ## 6. Errors
60
109
 
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다.
110
+ **Response mapping (D-0063 §1).** Errors thrown by handlers and hooks are answered like this.
62
111
 
63
- ## 4. 종료(drain)
112
+ | Thrown | Status | Body |
113
+ |---|---|---|
114
+ | a Dokebi error (`DokebiError`, or that shape with a `plugin`) with `status` | that `status` | `{ error: code, message, hint?, data? }` |
115
+ | a Dokebi error without `status` | Fastify's 4xx `statusCode` if any, else 500 | the same |
116
+ | a refused route schema of the body or the query string (D-0074) | 422 | `{ error: 'VALIDATION_FAILED', message, hint, fields: [{ field, message }], errors: { field: message } }` |
117
+ | `throw validationError({ name: 'Already taken' })` from a handler (D-0074) | 422 | the same shape (`fields`, `errors`) |
118
+ | an unknown route (D-0074) | 404 | `{ error: 'NOT_FOUND', message, hint }` |
119
+ | any other 4xx (malformed JSON, media type, size, a `params` or `headers` schema) | Fastify's value | `{ error: 'INVALID_REQUEST' }` (plus Fastify's `message` in development) |
120
+ | anything else (unknown errors, errno and so on) | 500 | `{ error: 'INTERNAL_SERVER_ERROR' }` |
64
121
 
65
- - 단일 프로세스: 새 요청을 503으로 막고 진행 응답·handler Promise·요청 훅·`track` 업무를 기다린다. core drain 기한(기본 20초)이 지나거나 `stop({ force: true })`면 남은 연결을 끊고 반환한다(core가 `DRAIN_TIMEOUT` 기록). 모든 drain 성공 뒤 cleanup에서 `Fastify.close`(onClose 실행).
66
- - cluster 워커(D-0036): listen 소켓부터 닫아 primary가 새 연결을 다른 워커로 보내게 하고, 열린 keep-alive 연결의 요청은 처리한 뒤 `Connection: close`로 닫는다. 최소 100ms 살아 있는다. 쉬는 keep-alive가 닫히는 순간 보낸 요청은 `ECONNRESET`일 수 있다(HTTP 본질). 브라우저가 아닌 클라이언트는 재사용 소켓의 멱등 요청을 한 번 재시도한다.
122
+ - **Production** (`NODE_ENV=production` or `developmentErrors: false`) never carries `fix`, `details` or stacks, and a 5xx `message` becomes a generic sentence (`Internal Server Error`, `Service Unavailable` and so on). `code`, `hint`, `data`, `fields` and `errors` are sent in production too. **Development** also sends `fix` and `details` (when they fit in 16 KB of JSON).
123
+ - The body is a flat object extending the old `{ error: '<CODE>' }` shape (`error` is the code). Clients branch on `body.error`.
124
+ - The extension hook `errorBody` can change status and body (§8). In production web removes `fix`, `details` and `stack` whatever the hook returns.
67
125
 
68
- ## 5. 소유권 규칙(중요)
126
+ **Validation errors (D-0074).** A field is the property path without `body/`: `name`, `address.city`, `items.0.name`; a missing property is named itself (`required` → `name`: `is required`); a query string field is `query.page`; a body that is wrong as a whole is `_body`. Fastify stops at the first failing rule (Ajv `allErrors: false`, its safe default), so a schema answer usually names one field. Refuse input in handler code the same way, so clients see one shape:
69
127
 
70
- - **Fastify `onClose`에서 쓰는 Dokebi 자원은 `entry.requires`(CLI 프로젝트는 `src/infra/web/requires.ts`의 `requires`)에 넣는다.** cleanup은 초기화 역순이라, web이 그 자원에 의존해야 Fastify.close 뒤에 자원이 닫힌다.
71
- - 빌린 DB 풀 등을 handler에서 닫지 않는다.
72
- - callback 훅은 done 또는 응답 종료, async 훅은 반환 Promise가 완료 경계다. async와 done을 섞지 않는다. raw stream·타이머·외부 이벤트로 이어지는 작업은 `track`이나 소유 플러그인 drain으로 기다린다.
73
- - `listen`·`close` 직접 호출, 루트 훅 덮어쓰기, `dokebiHealth` 예약 config 우회는 계약 밖이다.
128
+ ```ts snippet
129
+ import { validationError } from '@dokebi/web';
130
+ if (await users.exists(body.name)) throw validationError({ name: 'This name is taken' });
131
+ // or a list: validationError([{ field: 'name', message: '…' }], { message, hint, data })
132
+ ```
133
+
134
+ Do not answer validation with your own `reply.code(422).send(…)`: template-inertia only turns a `VALIDATION_FAILED` answer into the Inertia validation redirect. `fields` keeps every message in order; `errors` is the first message per field (the shape of Inertia `useForm().errors`).
135
+
136
+ **JSON or HTML (D-0074, `errorFormat(headers, sealed)`).** One rule for every error answer (thrown errors, refused schemas, unknown routes, 413/415 bodies, seal errors, the 503 refusals):
137
+
138
+ - **JSON** when any of: `X-Inertia` is present; `X-Requested-With: XMLHttpRequest`; `Authorization: Bearer …`; the request body is JSON (`Content-Type` `application/json` or `+json`: a script sent it); the request is sealed (D-0062: only sealed JSON leaves a seal host); `Accept` prefers JSON or is `*/*` (`fetch()`).
139
+ - **HTML** (a small page with the code, message, hint, the refused fields and, in development, `fix`) only otherwise and only when `Accept` prefers `text/html`: a browser navigation or an HTML form post.
74
140
 
75
- ## 6. 오류
141
+ | Client \ error | 404 route | 400 bad JSON | 413 | 415 form off | 422 schema | 422 `validationError` | 401/403 | 500 | 503 refused |
142
+ |---|---|---|---|---|---|---|---|---|---|
143
+ | browser navigation (GET, `Accept: text/html`) | HTML | – | – | – | HTML (query) | HTML | HTML | HTML | HTML |
144
+ | HTML form post (urlencoded, `formBody` on) | HTML | – | HTML | HTML | HTML | HTML | HTML | HTML | HTML |
145
+ | `fetch` with JSON | JSON | JSON | JSON | – | JSON | JSON | JSON | JSON | JSON |
146
+ | XHR (`X-Requested-With`) | JSON | JSON | JSON | JSON | JSON | JSON | JSON | JSON | JSON |
147
+ | Bearer API | JSON | – | – | – | JSON (query) | JSON | JSON | JSON | JSON |
148
+ | Inertia visit (GET, `X-Inertia`) | JSON | – | – | – | JSON | JSON | JSON | JSON | JSON |
149
+ | Inertia POST | JSON | JSON | JSON | – | JSON | JSON | JSON | JSON | JSON |
150
+ | sealed request (seal host) | JSON (sealed) | – | JSON (sealed) | 415 `SEAL_REQUIRED` JSON (plain) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) |
76
151
 
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`). 사용자 오류 처리기를 등록하면 그 보안 책임도 사용자에게 있다.
152
+ (`–`: that client cannot send that request. The table is `tests/error-matrix.test.ts`.) With @dokebi/template-inertia an Inertia request refused with 422 goes back instead (303, `errors` in the session flash); with @dokebi/app 0.4.1 and @dokebi/session an HTML form post refused with 422 goes back the same way (`data.errors`, `data.old` in the app's views); and an app's error views or Inertia error page may draw the HTML answer: all through error responders.
78
153
 
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가 켜졌을 때만 만든다).
154
+ **Error responders (D-0074).** `web.errorResponder((response) => …)` (setup only) is asked before web writes an error answer, the last added first. `response` is `{ request, reply, error, status, body, format, production, sealed }` with the final status and body (after `errorBody`, production-cut). Return true after sending the answer yourself (`reply.redirect`, a rendered view), false to pass. A responder that throws (or returns true without sending) is logged once per route and interval as `error` `Web error responder failed` (`code: WEB_ERROR_RESPONDER_FAILED`, `status`, `errorCode`, `error`) and web sends its own answer. @dokebi/app answers an app's hosts with the HTML form redirect and its error views; template-inertia does the Inertia validation redirect and the error page. Responders are not asked for the 503 refusals.
155
+
156
+ **Form helpers (0.4.1, D-0074 addendum 1).** The pieces of the validation redirect, shared by template-inertia and @dokebi/app, for a responder of your own:
157
+
158
+ | Function | Returns |
159
+ |---|---|
160
+ | `isFormSubmission(headers)` | true for a body of `application/x-www-form-urlencoded` or `multipart/form-data` (a browser `<form method="post">`) |
161
+ | `formFieldErrors(body)` | the `errors` (`{ field: message }`) of a 422 `VALIDATION_FAILED` body, else undefined |
162
+ | `formOldInput(body)` | the request body's top-level strings, numbers, booleans and nulls without password-like fields (`password`, `token`, `secret`, `api_key`, `card`, `cvc`, `otp`, `pin`…); undefined when nothing is left or it is over 8 KB as JSON |
163
+ | `formBackTarget(request, host, fallback?)` | the path and query of the `Referer` when it is `host` (`web.requestHost(request)`; another origin is never followed), else `fallback` for a POST/PUT/PATCH/DELETE, else undefined; a GET or HEAD never goes back to itself (no redirect loop) |
80
164
 
81
- ## 7. 주의 사항
165
+ dokebi-web knows no session: the caller flashes `errors` and `old` and answers `reply.redirect(target, 303)`.
166
+
167
+ <!-- docs-check: complete-error-codes WebErrorCode -->
168
+ `WebError` (`plugin: 'dokebi-web'`, always a `fix`; request errors also have `status` and `hint`):
169
+
170
+ | Code | When |
171
+ |---|---|
172
+ | `INVALID_ENTRY` | the entry module exports something other than `requires` and `default`, or exports the extension class under a name (the cause of `INVALID_PLUGIN_INPUT`) |
173
+ | `INVALID_ROUTE` | a route's `seal` is neither boolean nor function |
174
+ | `INVALID_HOOK` | an async Fastify hook takes the done argument |
175
+ | `INVALID_ARGUMENT` | `sealRequests` or `errorResponder` got something other than a function, or `validationError` got no field or a non-string message |
176
+ | `INVALID_EXTENSION_RESULT` | an extension hook returned the wrong shape (`fastifyOptions` fails setup; `errorBody` and `unavailable` fall back to the default answer plus error log `WEB_EXTENSION_FAILED`) |
177
+ | `FROZEN` | `route`, `register`, `constraint`, `errorResponder` or a seal setting after setup |
178
+ | `CLOSED` | `track` after close |
179
+ | `FORM_BODY_DISABLED` | 415, form bodies are off (`fix` says how to turn them on; warn log) |
180
+ | `FORM_BODY_TOO_MANY_FIELDS` | 413, `data.maxFields` |
181
+ | `SEAL_PROVIDER_MISSING` | start: sealing is wanted but there is no provider |
182
+ | `SEAL_PROVIDER_INVALID` | the provider has the wrong shape or was registered twice |
183
+ | `SEAL_REQUIRED` | 415, a plain body on a sealed request (answered in plain text) |
184
+ | `SEAL_BODY_REFUSED` | 400, a sealed body could not be opened (the reason is only in the warn log) |
185
+ | `SEAL_BODY_NOT_JSON` | 400, the opened body is not JSON |
186
+ | `SEAL_STREAM_UNSUPPORTED` | 500, JSON for a sealed request was sent as a stream (error log) |
187
+ | `VALIDATION_FAILED` | 422, a refused body or query string schema, or `validationError()`; `fields` and `errors` in the body |
188
+ | `NOT_FOUND` | 404, no route for the method and path |
189
+
190
+ Option errors are core `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS` with paths such as `trustProxy[0]` in `details.issues`). A 500 leaves the `error` log `HTTP request failed` (`code: WEB_REQUEST_FAILED`, `requestId`, `method`, `route` (the route pattern, no query), `status`, `errorCode`, `error` (name, full message, stack and `Caused by:` causes; only URL credentials are removed as `//***@`, cut above 16 KB)). The same route and error is logged once per 10 seconds and the count in between appears as `repeated` in the next record (D-0047). A 4xx is debug `HTTP request rejected` (`status`, `route`, the full `error` text, `errorCode`). If you register your own error handler, its security is your responsibility.
191
+
192
+ The info log `Web server listening` (`address`, `urls` (every bound address; `localhost` means 127.0.0.1 and ::1), `host`, `ms`) is what `dokebi start` reads to show the address. Debug logs (`DOKEBI_LOG_LEVEL=debug`): `Web server configured` (options, only the number of trustProxy entries, and `schemaCompilers`: `lazy` loads Fastify's default validation and serialization compilers when the first route with a schema appears — about 15 ms faster startup with the same behaviour, header schema names still case-insensitive; `extension` when the extension's `fastifyOptions` supplies a `schemaController`, D-0070), `Web routes frozen`, `Web drain started` (`pending`: requests, handlers, hooks and track work in progress at that moment), `Web worker stopped listening`, `Web drain cut connections`, `Web drain finished`, `Web server closed`; per request `HTTP request refused` (reason, method and path without the query; built only when debug is on), and when a client leaves before the response `HTTP client left before the response` and `HTTP request without client finished`.
193
+
194
+ ## 7. Cautions
195
+
196
+ - Behind a proxy, list **only the proxy addresses** in `trustProxy`; never trust Host or X-Forwarded-* headers yourself, use `requestHost(request)`.
197
+ - Authentication, rate limiting, CORS and security headers are Fastify plugins the app chooses (none are built in).
198
+ - `requestTimeoutMs` is not a limit on the work. Send long work to job.
199
+ - Do not treat the end of a response or a client disconnect as the work being done.
200
+
201
+ ## 8. Extension (D-0064 §9)
202
+
203
+ When the default export of `src/infra/web/extension.ts` (created by `dokebi add @dokebi/web`) extends `WebExtension`, only the overridden hooks are called. Left empty, it costs nothing per request. There are three hooks, all synchronous. No constructor parameters, and hooks do not call each other (`INVALID_EXTENSION`).
204
+
205
+ ```ts
206
+ import {
207
+ type WebErrorAnswer,
208
+ type WebErrorContext,
209
+ WebExtension,
210
+ type WebFastifyOptions,
211
+ type WebUnavailableAnswer,
212
+ type WebUnavailableContext,
213
+ } from '@dokebi/web';
214
+
215
+ export const requires = [] as const;
216
+
217
+ export default class AppWeb extends WebExtension {
218
+ // Fastify construction options (https, http2, serverFactory, routerOptions and so on). return503OnClosing and forceCloseConnections cannot change.
219
+ protected override fastifyOptions(defaults: WebFastifyOptions): WebFastifyOptions {
220
+ return { ...defaults, requestIdHeader: 'x-request-id' };
221
+ }
222
+ // Status and body of error responses (in production web removes fix, details and stack).
223
+ protected override errorBody(error: unknown, context: WebErrorContext): WebErrorAnswer {
224
+ void error;
225
+ return { status: context.answer.status, body: { ...context.answer.body, requestId: context.request.id } };
226
+ }
227
+ // Status, headers and body of refusals before ready and during drain (the request is refused either way).
228
+ protected override unavailable(context: WebUnavailableContext): WebUnavailableAnswer {
229
+ return { ...context.answer, headers: { 'retry-after': '5' } };
230
+ }
231
+ }
232
+ ```
82
233
 
83
- - 프락시 뒤에서는 `trustProxy`에 **프락시 주소만** 적고, Host·X-Forwarded-* 헤더를 직접 믿지 말고 `requestHost(request)`를 쓴다.
84
- - 인증·rate limit·CORS·보안 헤더는 앱이 Fastify 확장으로 고른다(기본 제공 없음).
85
- - `requestTimeout`은 업무 시간 제한이 아니다. 긴 작업은 job으로 보낸다.
86
- - 응답 종료·클라이언트 연결 끊김을 업무 완료로 보지 않는다.
234
+ - Projects created before 0.4.0 keep `src/infra/web/requires.ts` as their entry (upgrade does not move it). Add `export default class AppWeb extends WebExtension {}` to that file.
235
+ - The extension surface (hook signatures and their types) is fingerprinted in `scripts/release/extensions.json`.
87
236
 
88
- 근거: `examples/22-web`(API·HTML), `examples/12-cluster`·`24-template-inertia --cluster`(순차 교체), `examples/21-db`(DB와 drain), `examples/25-playground`, D-0034·D-0036.
237
+ References: `examples/29-extension` (errorBody, unavailable), `examples/22-web` (API and HTML), `examples/12-cluster` and `24-template-inertia --cluster` (rolling replacement), `examples/21-db` (DB and drain), `examples/25-playground`, D-0034, D-0036, D-0062, D-0068, D-0071.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
- # @dokebi/web 0.2.0
1
+ # @dokebi/web 0.4.1
2
2
 
3
- Node >=24.0.0, core ^0.2.0의 선택 패키지다(npm 공개). Fastify 5.12.7로 HTTP 서버를 소유하며 DB·라우터·컨트롤러·뷰는 필수가 아니다.
3
+ An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). It owns an HTTP server built on Fastify 5.12.7; DBs, routers, controllers and views are not required.
4
4
 
5
- ## 공개 계약
5
+ ## Public contract
6
6
 
7
- 플러그인 계약 v2([D-0028](../../docs/decisions/D-0028-plugin-contract-v2.md))를 따른다. `createPlugin({ app, options?, entry? })` → `app.register(plugin)` → `app.start()` → `app.get(plugin)` 순서로 사용한다. `app`(Application의 `app.view`)은 필수다. `options`를 생략하면 `app.config['dokebi-web']`을, 그것도 없으면 `{}`를 쓴다. 플러그인 인스턴스는 Application마다 새로 만든다. 예전 `health`·`requires`·`dependencies` 입력은 없다.
7
+ It follows plugin contract v2 ([D-0028](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0028-plugin-contract-v2.md)): `createPlugin({ app, options?, entry? })` → `app.register(plugin)` → `app.start()` → `app.get(plugin)`. `app` (the Application's `app.view`) is required. Without `options` it uses `app.config['dokebi-web']`, or `{}` when that is missing too. Create a new plugin instance per Application. The old `health`, `requires` and `dependencies` inputs are gone.
8
8
 
9
- ```ts
9
+ ```ts snippet
10
10
  import { Application } from '@dokebi/core';
11
11
  import { createPlugin as createWeb } from '@dokebi/web';
12
12
 
@@ -15,83 +15,85 @@ const web = createWeb({ app: app.view, entry: { requires: [sessionStore] } });
15
15
  app.register(web);
16
16
  ```
17
17
 
18
- - 의존성: `dokebi-health`는 선택 의존성(`optionalDependency`)이다. 같은 앱에 health가 등록되어 있으면 자동으로 연결되고 없으면 앱 상태만으로 판단한다. 직접 지정하려면 `app.register(createHealth({ app: app.view }))`처럼 같은 이름으로 먼저 등록한다.
19
- - `entry.requires`: Fastify `onClose`에서 쓰는 Dokebi 자원 목록이다. 플러그인 인스턴스(core `dependencyOf`로 변환) 또는 `PluginDependency` descriptor를 넣는다. 아래 "시작·종료와 소유권"을 본다. `dokebi-health`를 인스턴스로 넣으면 선택 의존성 대신 그 인스턴스를 필수로 쓴다.
20
- - 다른 플러그인용 descriptor: `import { dependency } from '@dokebi/web'`. 공급자가 없으면 이 패키지에서 web을 만든다. 공식 소비자(router·template-inertia)는 자기 패키지에서 같은 descriptor를 직접 만든다.
18
+ - Dependencies: `dokebi-health` is an optional dependency (`optionalDependency`). When health is registered in the same app it is connected automatically; otherwise only the app state counts. To choose the instance, register it under the same name first, as in `app.register(createHealth({ app: app.view }))`.
19
+ - `entry.requires`: the Dokebi resources that Fastify `onClose` hooks use. Entries are plugin instances (converted with core `dependencyOf`) or `PluginDependency` descriptors. See "Start, shutdown and ownership" below. A `dokebi-health` instance there is used as a required dependency instead of the optional one.
20
+ - Descriptor for other plugins: `import { dependency } from '@dokebi/web/dependency'` (also exported from the root). When no provider is registered, web is created from this package.
21
21
 
22
- - `route<T>(options)`: Fastify RouteOptions와 Params/Body/Reply 타입을 유지한다. setup에서 등록한다.
23
- - `register(plugin, options)`: Fastify async 또는 callback 플러그인과 옵션을 전달한다. 옵션이 없으면 `{}`를 전달한다. 네이티브 플러그인의 scope/decorator/schema/hook을 보존한다.
24
- - `address`: listen 이후 실제 주소이며 그 전에는 undefined다. node:cluster 워커에서는 core `ready` 이후에야 정해진다(D-0034). 다른 플러그인은 `start`가 아니라 `ready`에서 읽는다. 종료 후에는 마지막 주소가 남으므로 가용 상태로 사용하지 않는다.
25
- - `track(() => work)`: HTTP 응답과 수명이 다른 명시 업무를 drain 대상에 넣고 Promise를 반환한다. 호출자는 실패를 처리하고 새 작업 유입을 멈춰야 한다.
22
+ - `route<T>(options)`: keeps Fastify RouteOptions and the Params/Body/Reply types. Register during setup.
23
+ - `register(plugin, options)`: passes a Fastify async or callback plugin and its options (`{}` when none). Native plugins keep their scope, decorators, schemas and hooks.
24
+ - `address`: the real address after listen, undefined before. In a node:cluster worker it is set only after core `ready` (D-0034); other plugins read it in `ready`, not `start`. After shutdown the last address remains, so do not take it as a sign of availability.
25
+ - `track(() => work)`: puts explicit work whose lifetime differs from the HTTP response into drain and returns a Promise. The caller handles its failure and stops accepting new work.
26
26
 
27
- 모든 Dokebi setup 이후 web.start에서 ready/listen한다. 단 `node:cluster` 워커에서는 core `ready` 훅에서 listen한다([D-0034](../../docs/decisions/D-0034-ready-before-traffic.md)). primary는 listen한 워커에 바로 연결을 나눠 주기 때문에, 앱 전체가 준비된 워커만 연결을 받게 하려는 것이다. 이후 route/register는 FROZEN이다. Fastify 등록 함수 안에서는 전달받은 scope에 라우트를 등록한다. 실행 중 확장 추가는 지원하지 않는다.
27
+ web becomes ready and listens in its start, after every Dokebi setup. In a `node:cluster` worker it listens in the core `ready` hook instead ([D-0034](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0034-ready-before-traffic.md)): the primary hands connections to a worker as soon as it listens, so only workers whose whole app is ready should take them. After that, `route` and `register` are FROZEN. Inside a Fastify registration function, register routes on the scope you were given. Adding plugins while running is not supported.
28
28
 
29
- ## YAML 옵션
29
+ ## YAML options
30
30
 
31
31
  ```yaml
32
32
  options:
33
33
  dokebi-web:
34
34
  host: 127.0.0.1
35
35
  port: 3000
36
- bodyLimit: 1048576
37
- requestTimeout: 30000
38
- healthRoutes: # false면 health 라우트를 등록하지 않는다
36
+ maxBodyBytes: 1048576
37
+ requestTimeoutMs: 30000
38
+ healthRoutes: # false registers no health routes
39
39
  live: /health/live
40
40
  ready: /health/ready
41
41
  ```
42
42
 
43
- 기본 host는 127.0.0.1, port는 0(임시 포트), bodyLimit는 1 MiB, requestTimeout은 30초다. port 0..65535, bodyLimit 1..64 MiB, requestTimeout 1..2147483647ms를 허용한다. requestTimeout은 요청 수신 제한이며 업무 실행 시간 제한이나 DB 취소가 아니다. TLS/HTTP2/임의 Fastify 생성 옵션을 아직 공개하지 않는다.
43
+ The defaults are host 127.0.0.1, port 0 (an ephemeral port), maxBodyBytes 1 MiB and requestTimeoutMs 30 seconds. Allowed are port 0..65535, maxBodyBytes 1..64 MiB and requestTimeoutMs 1..2147483647 ms. `requestTimeoutMs` limits receiving a request; it is not a limit on running the work and does not cancel DB calls. Before 0.4.0 the keys were `bodyLimit` and `requestTimeout`; those names are still accepted with an `OPTION_DEPRECATED` warning, and setting old and new together is an error ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)). Fastify construction options such as HTTPS, HTTP/2 and `serverFactory` go through the extension hook `fastifyOptions` (AI.md §8).
44
44
 
45
- `healthRoutes`의 기본값은 `{ live: '/health/live', ready: '/health/ready' }`다. 객체에서 빠진 키는 기본 경로를 쓴다. 경로는 `/`로 시작하고 `?`·`#`·공백이 없어야 하며 live와 ready가 같으면 안 된다. `false`면 두 라우트를 모두 등록하지 않는다(외부 health 서버를 쓸 때). 잘못된 옵션은 팩토리에서 `CoreError('INVALID_PLUGIN_OPTIONS')`(cause는 `WebError('INVALID_OPTIONS')`)로 실패한다.
45
+ `healthRoutes` defaults to `{ live: '/health/live', ready: '/health/ready' }`. Keys missing from the object use the default path. Paths start with `/`, contain no `?`, `#` or spaces, and live and ready must differ. `false` registers neither route (when an external health server is used). The options are one `defineOptions` declaration in `src/options.ts`, which is the parser, and the build writes `options.schema.json` from it (D-0063 §3). Invalid options fail in the factory with `CoreError('INVALID_PLUGIN_OPTIONS')` (cause: core `INVALID_OPTIONS`, with paths in `details.issues`).
46
46
 
47
- ## 시작·종료와 소유권
47
+ Other options: `trustProxy` (below), `sealDriftMs` and `sealExclude` (seal hosts), `formBody` and `formMaxFields` (HTML form bodies, off by default), `developmentErrors` (error details outside production). The [AI guide](AI.md) has the full table.
48
48
 
49
- Application 전체 start 완료 및 선택 health.ready 전에는 업무 요청에 503을 반환한다. 본문은 `{ error: 'SERVICE_UNAVAILABLE', reason }`이고 reason은 `DRAINING`·`STARTING`·`NOT_READY` 중 하나다. 같은 이유를 debug 로그 `HTTP request refused`에도 남긴다. health 라우트(기본 `/health/live`, `/health/ready`)는 예약 경로이며 각각 200/503을 반환한다. health는 앱마다 독립적이고 부모 cluster 전체 집계가 아니다.
49
+ ## Start, shutdown and ownership
50
50
 
51
- **node:cluster 워커**(D-0036)에서는 drain을 시작하면 listen 소켓을 먼저 닫아 primary가 새 연결을 다른 워커로 보내게 한다. 이미 열린 keep-alive 연결로 오는 요청은 503 대신 처리하고 `Connection: close`로 닫는다. listen을 닫은 뒤 최소 100ms는 살아 있어, primary가 넘기던 연결이 버려지지 않게 한다. 쉬는 keep-alive 연결이 닫히는 순간 그 연결로 보낸 요청은 `ECONNRESET`을 받을 수 있다. HTTP의 본질적 경합이므로 브라우저가 아닌 클라이언트는 재사용 소켓의 멱등 요청을 한 번 재시도한다(Node 문서 권고). 단일 프로세스는 아래처럼 listen을 유지하고 503을 준다(로드밸런서가 health로 뺀다).
51
+ Until the whole Application has started and the optional health is ready, business requests get 503 with the body `{ error: 'SERVICE_UNAVAILABLE', reason }`, where reason is one of `DRAINING`, `STARTING` and `NOT_READY`. A browser page gets the same as a small HTML page (D-0074). The same reason goes to the debug log `HTTP request refused`. The health routes (default `/health/live`, `/health/ready`) are reserved paths and answer 200/503. Health is per app, not an aggregate over the parent cluster.
52
52
 
53
- 단일 프로세스의 drain은 새 요청을 503으로 차단한 뒤 응답, handler Promise, 등록한 요청 생명주기 훅, track 업무를 기다린다. core의 drain 기한(`shutdown.drainTimeoutMs`, 기본 20초)이 지나거나 `stop({ force: true })`로 `context.drainSignal`이 abort되면 기다림을 멈추고 `server.closeAllConnections()`로 남은 연결을 끊은 뒤 반환한다. 이때 core가 `DRAIN_TIMEOUT`을 기록한다. 클라이언트 연결 해제로 handler/hook 업무를 완료 처리하지 않는다. 전체 플러그인의 drain이 성공한 뒤에만 deferred cleanup에서 Fastify.close를 호출한다. 네이티브 onClose도 그때 실행된다. 종료 실패·지연을 감추거나 미완료 업무보다 먼저 DB를 닫지 않는다. cluster의 최종 강제 종료는 프로세스 정책이며 정상 drain 성공이 아니다.
53
+ In a **node:cluster worker** (D-0036), drain first closes the listen socket so the primary sends new connections to other workers. Requests arriving on already open keep-alive connections are served instead of refused and the connection is then closed with `Connection: close`. The worker stays up at least 100 ms after closing listen so connections the primary was handing over are not dropped. A request sent on an idle keep-alive connection at the moment it closes can get `ECONNRESET`. This is an inherent HTTP race, so non-browser clients retry an idempotent request on a reused socket once (as the Node docs recommend). A single process keeps listening and answers 503, as below (the load balancer takes it out through health).
54
54
 
55
- **규칙: Fastify `onClose`에서 쓰는 Dokebi 자원은 반드시 `entry.requires`에 넣는다.** 예: `createWeb({ app: app.view, entry: { requires: [dbPlugin] } })`. cleanup은 초기화 역순이므로 web이 그 자원에 의존해야 Fastify.close 이후에 자원이 정리된다. 반대로 자원 쪽이 web에 의존하면 자원이 먼저 닫힌다. 업무 모듈은 자신이 사용하는 web/router/controller/DB를 직접 requires로 선언한다. 빌린 풀을 임의로 close하지 않는다.
55
+ In a single process, drain refuses new requests with 503 and then waits for responses, handler Promises, registered request lifecycle hooks and track work. When the core drain deadline (`shutdown.drainTimeoutMs`, default 20 seconds) passes or `stop({ force: true })` aborts `context.drainSignal`, it stops waiting, cuts the remaining connections with `server.closeAllConnections()` and returns; core then records `DRAIN_TIMEOUT`. A client disconnect never marks handler or hook work as done. Fastify.close runs in the deferred cleanup only after every plugin's drain succeeded, and native onClose hooks run then. Shutdown failures and delays are never hidden, and the DB is never closed before unfinished work. A final forced kill in a cluster is a process policy, not a successful drain.
56
56
 
57
- 네이티브 callback 훅은 done 또는 정상 응답 종료가 업무 완료 경계다. async 훅은 반환 Promise까지 기다린다. 응답을 보낸 뒤에도 계속되는 작업, 사용자 raw stream·parser·custom error handler·타이머·외부 이벤트의 비동기 작업은 자동 추적을 가정하지 말고 track 또는 소유 플러그인의 drain으로 기다린다. hook에서 async와 done을 혼용하지 않는다. `listen/close`, 루트 훅 덮어쓰기, `dokebiHealth` 예약 config 우회는 확장 계약 밖이다.
57
+ **Rule: put every Dokebi resource a Fastify `onClose` hook uses into `entry.requires`.** For example `createWeb({ app: app.view, entry: { requires: [dbPlugin] } })`. Cleanup runs in reverse initialisation order, so web must depend on the resource for the resource to be cleaned up after Fastify.close. If the resource depends on web instead, the resource closes first. Business modules declare the web, router, controller and DB they use in their own requires. Never close a borrowed pool on your own.
58
58
 
59
- 기본 오류 응답은 내부 메시지를 숨기며 500은 최소 로거에 requestId만 남긴다. 사용자 오류 처리기를 등록하면 그 보안 책임도 사용자에게 있다. HTTP 인증·rate limit·CORS 등은 앱이 필요한 Fastify 확장으로 선택한다.
59
+ For native callback hooks, done or the normal end of the response marks the end of the work; async hooks are awaited until their returned Promise settles. Work that continues after the response, and async work in user raw streams, parsers, custom error handlers, timers or outside events, is not tracked automatically: wait for it with track or the owning plugin's drain. Do not mix async and done in a hook. `listen`/`close`, overwriting root hooks and bypassing the reserved `dokebiHealth` config are outside the extension contract.
60
60
 
61
- ## 설치·실행
61
+ Error responses follow the D-0063 §1 mapping: a Dokebi error answers with its `status` and `{ error: code, message, hint?, data? }` (plus `fix` and `details` in development); an unknown error answers 500 `{ error: 'INTERNAL_SERVER_ERROR' }`. In production (`NODE_ENV=production` or `developmentErrors: false`) `fix` and `details` are left out and 5xx messages become generic sentences. One rule picks the format ([D-0074](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0074-error-responses.md)): Inertia requests, XHR, Bearer API clients, JSON request bodies, sealed requests and `fetch()` get JSON; only a browser page (a navigation, an HTML form post) gets the same content as a small HTML page. A refused body or query string schema is 422 `{ error: 'VALIDATION_FAILED', message, hint, fields: [{ field, message }], errors: { field: message } }`, and `throw validationError({ name: 'Already taken' })` from a handler gives the same answer; an unknown route is 404 `NOT_FOUND` in the same shape. Error responders (`web.errorResponder`) let @dokebi/app draw an app's error views and send a refused HTML form back to its page, and @dokebi/template-inertia answer Inertia requests (validation redirect, error page). The pieces of that redirect are exported for your own responders (0.4.1): `isFormSubmission`, `formFieldErrors`, `formOldInput` and `formBackTarget` (AI.md §6). A 500 leaves the error log `WEB_REQUEST_FAILED` (with the full error text). The table is in [AI.md](AI.md) §6. If you register your own error handler, its security is your responsibility. HTTP authentication, rate limiting, CORS and so on are Fastify plugins the app chooses.
62
62
 
63
- `dokebi add`는 정적 설치 선언으로 진입 파일 `src/infra/web/requires.ts`(`export const requires = [] as const;`)를 만든다. 생성 코드가 이 모듈을 `entry`로 넘긴다. 사용자 main에서 직접 조합할 때 자동 생성 파일을 편집하거나 같은 ID를 중복 등록하지 않는다. 저장소 실행 예제는 examples/22-web/main.ts, 실제 DB/cluster 예제는 examples/21-db/main.ts다.
63
+ ## Install and run
64
64
 
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`로 드러난다.
65
+ `dokebi add` creates the entry file `src/infra/web/extension.ts` (`export const requires = [] as const;` and an empty `export default class AppWeb extends WebExtension {}`) through the install module (`dist/install.js`). In projects created before 0.4.0, `src/infra/web/requires.ts` stays the entry after upgrade. The generated code passes this module as `entry`. When you compose the app in your own main, do not edit generated files or register the same ID twice. The repository's runnable example is `examples/22-web/main.ts`; the real DB and cluster example is `examples/21-db/main.ts`.
66
66
 
67
- ## 봉인 호스트의 HTTP (D-0062, 0.2.0)
67
+ Plugins with an entry file are left out of the generated code's manifest dependency check, so the entry file's `requires` works on the CLI path too (the same generated-code rule was run with controller and module entry files on 2026-10-14, [ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-04). Dependencies added through an entry file are invisible to the CLI's remove and doctor decisions; a missing one shows up at run time as `MISSING_DEPENDENCY`.
68
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).
69
+ ## HTTP on seal hosts (D-0062, 0.2.0)
70
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`.
71
+ web owns the **slot** that seals HTTP data of seal hosts (@dokebi/app `domains.<host>.seal: true`) and of `seal: true` routes. @dokebi/seal fills in the algorithm with `sealCodec(provider)` (this package never imports seal). See [D-0062](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0062-http-seal.md).
72
+
73
+ - The decision (once per request): health → plain, route `seal: false` → plain, `seal: true` or `seal(request)` → sealed, a `sealExclude` prefix (`/` boundary) → plain, any `sealRequests(predicate)` true → sealed. `seal` becomes `config.dokebiSeal` whether given to `route()`, a Fastify `register` scope or a router `mount`.
74
+ - Bodies of sealed requests: when the content type is the provider's `contentType` (`application/vnd.dokebi-seal`), the parser opens it and puts the JSON into `request.body` (drift, replay and tampering are 400, with the reason only in warn `SEAL_BODY_REFUSED`). A body that is neither sealed nor `multipart/form-data` gets `415 { error: 'SEAL_REQUIRED', fix }` **before the parser** (warn `SEAL_REQUIRED`, once per route every 10 seconds).
75
+ - JSON responses of sealed requests (`application/json`, `+json`, 4xx and 5xx included) are sealed in `onSend` and get `Content-Type: application/vnd.dokebi-seal` and `x-dokebi-sealed-path` (the path used for sealing; the final path after redirects). HTML, file and hijacked responses stay as they are. Streamed JSON cannot be sealed and becomes a 500 (plain text is never sent).
76
+ - Code that writes its own body (the Inertia first page, SSE) gets `{ path, encode }` from `sealOf(request)`.
77
+ - When something wants sealing (a registered decision or a sealed route) but no provider exists, start fails with `SEAL_PROVIDER_MISSING`.
76
78
 
77
79
  ```yaml
78
80
  options:
79
81
  dokebi-web:
80
- sealDriftMs: 60000 # 봉인 본문 ts 허용 오차(1000..600000), nonce는 그 두 배 보관
81
- sealExclude: [/webhooks] # seal 호스트에서도 평문인 경로 접두(최대 64)
82
+ sealDriftMs: 60000 # allowed ts drift of sealed bodies (1000..600000); nonces are kept twice as long
83
+ sealExclude: [/webhooks] # path prefixes that stay plain on seal hosts (up to 64)
82
84
  ```
83
85
 
84
- | API | 뜻 |
86
+ | API | Meaning |
85
87
  |---|---|
86
- | `sealCodec(provider)` | HTTP 봉인 자리 채우기(setup, 한 번). dokebi-seal이 부른다 |
87
- | `sealRequests(predicate)` | 이 판단이 참인 요청을 봉인(setup). dokebi-app이 seal 도메인으로 부른다 |
88
- | `sealOf(request)` | 봉인 요청이면 `{ path, encode(text) }`, 아니면 undefined |
89
- | `sealing` | 제공자가 등록됐는가 |
88
+ | `sealCodec(provider)` | fills the HTTP seal slot (setup, once). dokebi-seal calls it |
89
+ | `sealRequests(predicate)` | seals the requests this predicate accepts (setup). dokebi-app calls it for seal domains |
90
+ | `sealOf(request)` | `{ path, encode(text) }` for a sealed request, otherwise undefined |
91
+ | `sealing` | whether a provider is registered |
90
92
 
91
- ## 라우트 제약 전략 (D-0030)
93
+ ## Route constraint strategies (D-0030)
92
94
 
93
- `constraint(strategy)`는 setup 단계에서 Fastify 라우트 제약 전략(`addConstraintStrategy`)을 더한다. 그 제약을 쓰는 라우트보다 먼저 호출한다. @dokebi/app이 Host → 앱 선택(`dokebiApp`)에 쓰며, 같은 경로를 여러 라우트가 제약 값별로 나눠 가질 수 있다. start 이후 호출은 `FROZEN`이다.
95
+ `constraint(strategy)` adds a Fastify route constraint strategy (`addConstraintStrategy`) during setup. Call it before the routes that use the constraint. @dokebi/app uses it to pick the app by Host (`dokebiApp`), so several routes can share one path, split by constraint value. A call after start is `FROZEN`.
94
96
 
95
- ## 신뢰 프락시 (2026-10-14)
97
+ ## Trusted proxies (2026-10-14)
96
98
 
97
- `trustProxy: [주소...]`(정확한 IPv4·IPv6 주소, 최대 64개)에서 온 요청만 `X-Forwarded-Host`(·For·Proto)를 믿는다. Fastify `trustProxy`에도 같은 목록을 넘긴다. `requestHost(request)`는 그 규칙으로 요청이 원한 호스트를 소문자로 돌려준다(포트 유지). @dokebi/app의 도메인 판단과 @dokebi/websocket의 Origin 검사가 이를 쓴다. 예: 같은 컴퓨터의 Cloudflare 터널은 `[127.0.0.1, ::1]`([ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-20).
99
+ Only requests from `trustProxy: [address...]` (exact IPv4 and IPv6 addresses, up to 64) have their `X-Forwarded-Host` (and For and Proto) trusted. The same list goes to Fastify's `trustProxy`. `requestHost(request)` returns the host the request asked for under that rule, in lower case with the port kept. @dokebi/app's domain decision and @dokebi/websocket's Origin check use it. Example: a Cloudflare tunnel on the same machine is `[127.0.0.1, ::1]` ([ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-20).
@@ -0,0 +1,9 @@
1
+ import type { FastifyInstance, FastifyServerOptions } from 'fastify';
2
+ export type SchemaControllerOptions = NonNullable<FastifyServerOptions['schemaController']>;
3
+ /** A fresh controller option for one Fastify instance (each instance has its own pools). */
4
+ export declare function lazyCompilers(): SchemaControllerOptions;
5
+ /**
6
+ * After `fastify()`: when the server uses `controller` (not an extension's own), mark its compilers
7
+ * as the defaults again so header schemas keep Fastify's case-insensitive names.
8
+ */
9
+ export declare function restoreDefaultCompilers(server: FastifyInstance, given: unknown, controller: SchemaControllerOptions): boolean;