@nifrajs/core 2.14.1 → 3.1.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.
Files changed (138) hide show
  1. package/README.md +4 -0
  2. package/dist/assurance.d.ts +16 -8
  3. package/dist/assurance.d.ts.map +1 -1
  4. package/dist/assurance.js +33 -0
  5. package/dist/assurance.js.map +1 -1
  6. package/dist/edge-kit.d.ts +27 -0
  7. package/dist/edge-kit.d.ts.map +1 -0
  8. package/dist/edge-kit.js +24 -0
  9. package/dist/edge-kit.js.map +1 -0
  10. package/dist/errors.d.ts +1 -1
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/internal/route-execution.d.ts +11 -5
  18. package/dist/internal/route-execution.d.ts.map +1 -1
  19. package/dist/internal/route-execution.js +2 -1
  20. package/dist/internal/route-execution.js.map +1 -1
  21. package/dist/response-observer.d.ts +25 -0
  22. package/dist/response-observer.d.ts.map +1 -0
  23. package/dist/response-observer.js +40 -0
  24. package/dist/response-observer.js.map +1 -0
  25. package/dist/security/baseline.d.ts +68 -0
  26. package/dist/security/baseline.d.ts.map +1 -0
  27. package/dist/security/baseline.js +118 -0
  28. package/dist/security/baseline.js.map +1 -0
  29. package/dist/server/bare-error-lane.d.ts +26 -0
  30. package/dist/server/bare-error-lane.d.ts.map +1 -0
  31. package/dist/server/bare-error-lane.js +60 -0
  32. package/dist/server/bare-error-lane.js.map +1 -0
  33. package/dist/server/body.d.ts +7 -0
  34. package/dist/server/body.d.ts.map +1 -1
  35. package/dist/server/body.js +7 -0
  36. package/dist/server/body.js.map +1 -1
  37. package/dist/server/bridge-markers.d.ts +25 -0
  38. package/dist/server/bridge-markers.d.ts.map +1 -0
  39. package/dist/server/bridge-markers.js +25 -0
  40. package/dist/server/bridge-markers.js.map +1 -0
  41. package/dist/server/context.d.ts +6 -1
  42. package/dist/server/context.d.ts.map +1 -1
  43. package/dist/server/header-case.d.ts.map +1 -1
  44. package/dist/server/header-case.js +2 -1
  45. package/dist/server/header-case.js.map +1 -1
  46. package/dist/server/http.d.ts +36 -3
  47. package/dist/server/http.d.ts.map +1 -1
  48. package/dist/server/http.js +49 -3
  49. package/dist/server/http.js.map +1 -1
  50. package/dist/server/install.d.ts +6 -8
  51. package/dist/server/install.d.ts.map +1 -1
  52. package/dist/server/install.js +7 -0
  53. package/dist/server/install.js.map +1 -1
  54. package/dist/server/node-outcome-hook.d.ts +2 -1
  55. package/dist/server/node-outcome-hook.d.ts.map +1 -1
  56. package/dist/server/node-outcome-hook.js.map +1 -1
  57. package/dist/server/node-outcome.d.ts +17 -2
  58. package/dist/server/node-outcome.d.ts.map +1 -1
  59. package/dist/server/node-outcome.js +37 -3
  60. package/dist/server/node-outcome.js.map +1 -1
  61. package/dist/server/query.d.ts +7 -1
  62. package/dist/server/query.d.ts.map +1 -1
  63. package/dist/server/query.js +8 -3
  64. package/dist/server/query.js.map +1 -1
  65. package/dist/server/request-context.d.ts +17 -4
  66. package/dist/server/request-context.d.ts.map +1 -1
  67. package/dist/server/request-context.js +63 -29
  68. package/dist/server/request-context.js.map +1 -1
  69. package/dist/server/respond.d.ts.map +1 -1
  70. package/dist/server/respond.js +19 -2
  71. package/dist/server/respond.js.map +1 -1
  72. package/dist/server/response-contract-lane.d.ts.map +1 -1
  73. package/dist/server/response-contract-lane.js +5 -2
  74. package/dist/server/response-contract-lane.js.map +1 -1
  75. package/dist/server/response-observer-runtime.d.ts +20 -0
  76. package/dist/server/response-observer-runtime.d.ts.map +1 -0
  77. package/dist/server/response-observer-runtime.js +95 -0
  78. package/dist/server/response-observer-runtime.js.map +1 -0
  79. package/dist/server/runtime-core.d.ts +60 -0
  80. package/dist/server/runtime-core.d.ts.map +1 -1
  81. package/dist/server/runtime-core.js +65 -1
  82. package/dist/server/runtime-core.js.map +1 -1
  83. package/dist/server/server-types.d.ts +3 -1
  84. package/dist/server/server-types.d.ts.map +1 -1
  85. package/dist/server/server.d.ts +52 -39
  86. package/dist/server/server.d.ts.map +1 -1
  87. package/dist/server/server.js +267 -271
  88. package/dist/server/server.js.map +1 -1
  89. package/dist/server/websocket.d.ts +20 -4
  90. package/dist/server/websocket.d.ts.map +1 -1
  91. package/dist/server/websocket.js +81 -11
  92. package/dist/server/websocket.js.map +1 -1
  93. package/dist/server/ws-bun.d.ts +1 -1
  94. package/dist/server/ws-bun.d.ts.map +1 -1
  95. package/dist/server/ws-bun.js +12 -8
  96. package/dist/server/ws-bun.js.map +1 -1
  97. package/dist/server.d.ts +2 -1
  98. package/dist/server.d.ts.map +1 -1
  99. package/dist/server.js +2 -1
  100. package/dist/server.js.map +1 -1
  101. package/dist/single-copy-register.d.ts +2 -0
  102. package/dist/single-copy-register.d.ts.map +1 -0
  103. package/dist/single-copy-register.js +24 -0
  104. package/dist/single-copy-register.js.map +1 -0
  105. package/dist/single-copy.d.ts +156 -0
  106. package/dist/single-copy.d.ts.map +1 -0
  107. package/dist/single-copy.js +470 -0
  108. package/dist/single-copy.js.map +1 -0
  109. package/package.json +24 -2
  110. package/src/assurance.ts +58 -1
  111. package/src/edge-kit.ts +27 -0
  112. package/src/errors.ts +1 -0
  113. package/src/index.ts +1 -1
  114. package/src/internal/route-execution.ts +23 -16
  115. package/src/response-observer.ts +64 -0
  116. package/src/security/baseline.ts +172 -0
  117. package/src/server/bare-error-lane.ts +76 -0
  118. package/src/server/body.ts +8 -0
  119. package/src/server/bridge-markers.ts +24 -0
  120. package/src/server/context.ts +6 -1
  121. package/src/server/header-case.ts +3 -1
  122. package/src/server/http.ts +53 -3
  123. package/src/server/install.ts +14 -0
  124. package/src/server/node-outcome-hook.ts +2 -1
  125. package/src/server/node-outcome.ts +44 -3
  126. package/src/server/query.ts +10 -4
  127. package/src/server/request-context.ts +85 -33
  128. package/src/server/respond.ts +26 -1
  129. package/src/server/response-contract-lane.ts +6 -2
  130. package/src/server/response-observer-runtime.ts +135 -0
  131. package/src/server/runtime-core.ts +98 -1
  132. package/src/server/server-types.ts +3 -1
  133. package/src/server/server.ts +436 -367
  134. package/src/server/websocket.ts +127 -17
  135. package/src/server/ws-bun.ts +26 -7
  136. package/src/server.ts +2 -1
  137. package/src/single-copy-register.ts +24 -0
  138. package/src/single-copy.ts +524 -0
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Edge kit - the moat-neutral free functions a compact fetch-handler server needs to enforce the
3
+ * SAME request trust boundary the full `Server` does, without pulling in the full builder.
4
+ *
5
+ * A minimal edge entrypoint (`@nifrajs/edge`) is not allowed to re-derive the body lane: the assembly
6
+ * order of the content-type dispatch, the bounded read, the Content-Length pre-reject, and the
7
+ * prototype-poisoning guard is a security contract, and a second copy of it would drift. This subpath
8
+ * exposes the one lane the fused body runner already calls, so a compact server reuses it verbatim:
9
+ *
10
+ * - {@link readBodyFramed} read + cap + proto-guard + content-type framing (JSON / urlencoded / 415)
11
+ * - {@link toResponse} render a {@link ResponseResult} (e.g. a 413 / 415 rejection) to a `Response`
12
+ * - {@link plainError} the structured rejection envelope the lane returns
13
+ * - {@link queryObjectOf} / {@link searchOf} query parse without a full WHATWG URL construction
14
+ *
15
+ * Everything here carries only structure - bytes, guards, and envelopes - never routing, lifecycle,
16
+ * or app state. It is the interface, not the framework.
17
+ */
18
+
19
+ export { plainError } from "./server/http.ts"
20
+ export type { ProtoPoisoning } from "./server/proto-guard.ts"
21
+ export { type QueryValue, queryObjectOf, searchOf } from "./server/query.ts"
22
+ export { readBodyFramed } from "./server/request-context.ts"
23
+ export { toResponse } from "./server/respond.ts"
24
+ export type { ResponseResult } from "./server/runtime-core.ts"
25
+ export { EMPTY_RESPONSE_CONTROLS } from "./server/runtime-core.ts"
26
+ export type { CtxSet, MaybePromise, RequestSource } from "./server/server.ts"
27
+ export { plainValidationError } from "./server/server.ts"
package/src/errors.ts CHANGED
@@ -26,6 +26,7 @@ export type RouteConfigErrorCode =
26
26
  | "INVALID_METHOD"
27
27
  | "INVALID_ASSURANCE"
28
28
  | "INVALID_IDEMPOTENCY"
29
+ | "INVALID_WS_SEND_VALIDATION"
29
30
  | "INVALID_BODY_LIMIT"
30
31
 
31
32
  /**
package/src/index.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * read its own package.json at runtime. `scripts/version.ts` rewrites it on every release bump and
11
11
  * `check:publish` asserts it equals `@nifrajs/core`'s package version.
12
12
  */
13
- export const VERSION = "2.14.1" as const
13
+ export const VERSION = "3.1.0" as const
14
14
 
15
15
  export type Version = typeof VERSION
16
16
 
@@ -19,6 +19,7 @@
19
19
  import type { RequestBudget } from "../budget.ts"
20
20
  import type { RequestLedger } from "../ledger.ts"
21
21
  import type { StandardSchemaV1 } from "../schema/standard.ts"
22
+ import { UNLIMITED_BODY_BYTES } from "../server/body.ts"
22
23
  import type { Platform, RouteSchema } from "../server/context.ts"
23
24
  import type { ResolvedIdempotency } from "../server/idempotency-lane.ts"
24
25
  import type { EffectLedgerRuntime, ResolvedEffectLedger } from "../server/ledger-lane.ts"
@@ -26,7 +27,7 @@ import type { ProtoPoisoning } from "../server/proto-guard.ts"
26
27
  import type { Registry } from "../server/registry.ts"
27
28
  import { RequestContext } from "../server/request-context.ts"
28
29
  import type { ResponseContractRuntime } from "../server/response-contract-lane.ts"
29
- import type { HandlerResult } from "../server/runtime-core.ts"
30
+ import type { HandlerResult, ResponseResult } from "../server/runtime-core.ts"
30
31
  import type { CtxSet, MaybePromise, RawContext, RequestSource, Server } from "../server/server.ts"
31
32
 
32
33
  export type InternalHandler = (ctx: RawContext) => MaybePromise<HandlerResult>
@@ -49,7 +50,7 @@ export type RouteExecutionRunner = <T, R extends Registry, Ctx>(
49
50
  platform: Platform | undefined,
50
51
  nativeContext: boolean,
51
52
  finalize: (result: unknown, set: CtxSet) => T,
52
- wrapResponse: (response: Response) => T,
53
+ wrapResponse: (response: Response | ResponseResult) => T,
53
54
  ) => MaybePromise<T>
54
55
 
55
56
  export type ContextRouteRunner = <T, R extends Registry, Ctx>(
@@ -58,7 +59,7 @@ export type ContextRouteRunner = <T, R extends Registry, Ctx>(
58
59
  source: RequestSource,
59
60
  ctx: RawContext,
60
61
  finalize: (result: unknown, set: CtxSet) => T,
61
- wrapResponse: (response: Response) => T,
62
+ wrapResponse: (response: Response | ResponseResult) => T,
62
63
  ) => MaybePromise<T>
63
64
 
64
65
  /** The kernel's private execution surface, mirrored structurally. The runner methods are private on
@@ -76,66 +77,66 @@ interface RouteExecutionRuntime {
76
77
  budget: RequestBudget,
77
78
  platform: Platform | undefined,
78
79
  finalize: (result: unknown, set: CtxSet) => T,
79
- wrapResponse: (response: Response) => T,
80
+ wrapResponse: (response: Response | ResponseResult) => T,
80
81
  ): MaybePromise<T>
81
82
  runBare<T>(
82
83
  entry: RouteEntry,
83
84
  ctx: RawContext,
84
85
  finalize: (result: unknown, set: CtxSet) => T,
85
- wrapResponse: (response: Response) => T,
86
+ wrapResponse: (response: Response | ResponseResult) => T,
86
87
  ): MaybePromise<T>
87
88
  runBodyOnly<T>(
88
89
  entry: RouteEntry,
89
90
  source: RequestSource,
90
91
  ctx: RawContext,
91
92
  finalize: (result: unknown, set: CtxSet) => T,
92
- wrapResponse: (response: Response) => T,
93
+ wrapResponse: (response: Response | ResponseResult) => T,
93
94
  ): MaybePromise<T>
94
95
  runQueryOnly<T>(
95
96
  entry: RouteEntry,
96
97
  ctx: RawContext,
97
98
  finalize: (result: unknown, set: CtxSet) => T,
98
- wrapResponse: (response: Response) => T,
99
+ wrapResponse: (response: Response | ResponseResult) => T,
99
100
  ): MaybePromise<T>
100
101
  runLifecycleHooks<T>(
101
102
  entry: RouteEntry,
102
103
  ctx: RawContext,
103
104
  finalize: (result: unknown, set: CtxSet) => T,
104
- wrapResponse: (response: Response) => T,
105
+ wrapResponse: (response: Response | ResponseResult) => T,
105
106
  ): MaybePromise<T>
106
107
  runLifecycleQuery<T>(
107
108
  entry: RouteEntry,
108
109
  ctx: RawContext,
109
110
  finalize: (result: unknown, set: CtxSet) => T,
110
- wrapResponse: (response: Response) => T,
111
+ wrapResponse: (response: Response | ResponseResult) => T,
111
112
  ): MaybePromise<T>
112
113
  runLifecycleBody<T>(
113
114
  entry: RouteEntry,
114
115
  source: RequestSource,
115
116
  ctx: RawContext,
116
117
  finalize: (result: unknown, set: CtxSet) => T,
117
- wrapResponse: (response: Response) => T,
118
+ wrapResponse: (response: Response | ResponseResult) => T,
118
119
  ): MaybePromise<T>
119
120
  runLifecycleBodyQuery<T>(
120
121
  entry: RouteEntry,
121
122
  source: RequestSource,
122
123
  ctx: RawContext,
123
124
  finalize: (result: unknown, set: CtxSet) => T,
124
- wrapResponse: (response: Response) => T,
125
+ wrapResponse: (response: Response | ResponseResult) => T,
125
126
  ): MaybePromise<T>
126
127
  runLifecycle<T>(
127
128
  entry: RouteEntry,
128
129
  source: RequestSource,
129
130
  ctx: RawContext,
130
131
  finalize: (result: unknown, set: CtxSet) => T,
131
- wrapResponse: (response: Response) => T,
132
+ wrapResponse: (response: Response | ResponseResult) => T,
132
133
  ): MaybePromise<T>
133
134
  runWithAround<T>(
134
135
  entry: RouteEntry,
135
136
  ctx: RawContext,
136
137
  run: () => MaybePromise<T>,
137
138
  finalize: (result: unknown, set: CtxSet) => T,
138
- wrapResponse: (response: Response) => T,
139
+ wrapResponse: (response: Response | ResponseResult) => T,
139
140
  ): MaybePromise<T>
140
141
  readonly maxBodyBytes: number
141
142
  readonly protoPoisoning: ProtoPoisoning
@@ -295,7 +296,7 @@ export function compileRouteExecutionPlan(options: {
295
296
  wrapResponse,
296
297
  ) => {
297
298
  const server = runtime as unknown as RouteExecutionRuntime
298
- const maxBodyBytes = entry.bodyLimit ?? server.maxBodyBytes
299
+ const maxBodyBytes = entry.bodyLimit ?? UNLIMITED_BODY_BYTES
299
300
  const ctx = nativeContext
300
301
  ? RequestContext.native(source, params, search, maxBodyBytes, platform, server.protoPoisoning)
301
302
  : new RequestContext(
@@ -346,7 +347,13 @@ export interface RouteExecutionPlan {
346
347
  export interface RouteEntry {
347
348
  readonly handler: InternalHandler
348
349
  readonly schema: RouteSchema | undefined
349
- /** Effective transport body cap; `undefined` is an explicit streaming/upload exemption. */
350
+ /**
351
+ * Effective transport body cap, already resolved at registration: the route's own
352
+ * `schema.bodyLimit` when it declared one, the server's `maxBodyBytes` otherwise. `undefined` is
353
+ * an explicit streaming/upload exemption (`bodyLimit: "unlimited"`) and means NO cap - readers
354
+ * must fall back to {@link UNLIMITED_BODY_BYTES}, never to the server default, which would be a
355
+ * tighter bound than the route asked for.
356
+ */
350
357
  readonly bodyLimit: number | undefined
351
358
  /** Resolved idempotency config; `undefined` = off (the dedupe lane is never entered). */
352
359
  readonly idempotent: ResolvedIdempotency | undefined
@@ -399,5 +406,5 @@ export type FusedBodyRunner = <T>(
399
406
  platform: Platform | undefined,
400
407
  nativeContext: boolean,
401
408
  finalize: (result: unknown, set: CtxSet, ctx: RawContext) => T,
402
- wrapResponse: (response: Response) => T,
409
+ wrapResponse: (response: Response | ResponseResult) => T,
403
410
  ) => MaybePromise<T>
@@ -0,0 +1,64 @@
1
+ import { INSTALL_RESPONSE_OBSERVER } from "./server/install.ts"
2
+ import {
3
+ createResponseObserverRuntime,
4
+ type ResponseObserverRuntime,
5
+ } from "./server/response-observer-runtime.ts"
6
+ import type { AnyServer } from "./server/server.ts"
7
+
8
+ export type {
9
+ ResponseBodyHook,
10
+ ResponseHeadersHook,
11
+ ResponseObserverMethods,
12
+ ResponseObserverRuntime,
13
+ } from "./server/response-observer-runtime.ts"
14
+
15
+ /** A server shape with the opt-in response observation methods installed. */
16
+ export type ResponseObserverServer<S extends AnyServer> = S &
17
+ import("./server/response-observer-runtime.ts").ResponseObserverMethods
18
+
19
+ /** A plugin that enables response header, body, and raw-response observation methods. */
20
+ export type ResponseObserverPlugin = (<S extends AnyServer>(
21
+ app: S,
22
+ ) => ResponseObserverServer<S>) & { readonly pluginName?: string }
23
+
24
+ /**
25
+ * Enable the response observation methods on a server.
26
+ *
27
+ * The default server does not carry the header, body, or raw-response observation adapters. Apply
28
+ * this plugin before using those methods:
29
+ *
30
+ * ```ts
31
+ * import { responseObserver } from "@nifrajs/core/response-observer"
32
+ * const app = server().use(responseObserver()).onResponseHeaders((headers) => {
33
+ * headers.set("cache-control", "no-store")
34
+ * })
35
+ * ```
36
+ */
37
+ export function responseObserver(): ResponseObserverPlugin {
38
+ const apply = <S extends AnyServer>(app: S): ResponseObserverServer<S> => {
39
+ const install = (app as unknown as Record<symbol, unknown>)[INSTALL_RESPONSE_OBSERVER]
40
+ if (typeof install !== "function") {
41
+ throw new TypeError("[nifra] responseObserver() requires a compatible Server")
42
+ }
43
+ const methods = (install as (runtime: ResponseObserverRuntime) => unknown).call(
44
+ app,
45
+ createResponseObserverRuntime(),
46
+ )
47
+ if (methods === null || typeof methods !== "object") {
48
+ throw new TypeError("[nifra] responseObserver() failed to install its methods")
49
+ }
50
+ Object.assign(app, methods)
51
+ return app as ResponseObserverServer<S>
52
+ }
53
+ return Object.assign(apply, { pluginName: "nifra:response-observer" })
54
+ }
55
+
56
+ /** Attach the opt-in observer runtime to a middleware bundle that uses response observation. */
57
+ export function withResponseObserver<T extends object>(middleware: T): T {
58
+ Object.defineProperty(middleware, INSTALL_RESPONSE_OBSERVER, {
59
+ value: createResponseObserverRuntime(),
60
+ enumerable: false,
61
+ configurable: false,
62
+ })
63
+ return middleware
64
+ }
@@ -0,0 +1,172 @@
1
+ import type { AssurancePolicy, AssuranceRule } from "../assurance.ts"
2
+ import { NIFRA_ASSURANCE_IDS } from "../internal/route-assurance.ts"
3
+
4
+ /**
5
+ * How much a {@link securityBaseline} demands. Each level is a superset of the one before it, so
6
+ * raising the level only ever adds findings.
7
+ *
8
+ * - `"essential"` - the invariants that hold for ANY app and never false-positive on a reasonable
9
+ * one: a body read must be bounded, an unlimited body may never claim to be bounded, an agent tool
10
+ * ingress must be bounded, and an authenticated state change must prove CSRF. Every required piece
11
+ * of evidence here is either published by the core from the route schema or only demanded when the
12
+ * route already opted into the risk (CSRF is required only where authentication is present). Safe to
13
+ * adopt on day one.
14
+ * - `"standard"` (default) - essential, plus: a route the app itself classified as `pii` or higher
15
+ * must be authenticated, whether it reads or writes. High signal, low noise - it fires only on
16
+ * routes the application already labelled sensitive.
17
+ * - `"strict"` - standard, plus the opinionated, higher-friction requirements: every route must carry
18
+ * a response contract, every read must carry security headers, and every mutation must be rate
19
+ * limited. These need middleware the app has to install, so they are opt-in rather than default.
20
+ */
21
+ export type SecurityBaselineLevel = "essential" | "standard" | "strict"
22
+
23
+ /** Tuning for {@link securityBaseline}. Every knob only ever tightens the policy. */
24
+ export interface SecurityBaselineOptions {
25
+ /** How much the baseline demands. Default `"standard"`. See {@link SecurityBaselineLevel}. */
26
+ readonly level?: SecurityBaselineLevel
27
+ /**
28
+ * How to treat a route no rule matched. Default `"ignore"` so the baseline is purely additive - it
29
+ * asserts the invariants below and stays silent on everything else, which lets a project adopt it
30
+ * without first classifying its whole route table. Set `"error"` to make an unclassified route a
31
+ * finding, turning the baseline into a closed allow-list (recommended once the table is covered).
32
+ */
33
+ readonly unmatched?: "error" | "ignore"
34
+ /**
35
+ * Require that a matched route's evidence was installed by runtime enforcement (middleware/plugin
36
+ * or framework policy) rather than asserted inline on `schema.assurance`. Default `true`: an author
37
+ * label is not proof, and a security baseline that accepts labels is theater. Set `false` only to
38
+ * stage adoption before guards emit runtime evidence.
39
+ */
40
+ readonly requireRuntimeProvenance?: boolean
41
+ }
42
+
43
+ const MUTATING = ["POST", "PUT", "PATCH", "DELETE"] as const
44
+ const READING = ["GET", "HEAD"] as const
45
+ /** The classification threshold above which the baseline demands authentication. */
46
+ const SENSITIVE = "pii" as const
47
+
48
+ /**
49
+ * A first-match-wins security policy that turns the recurring audit finding classes into machine
50
+ * checked route invariants. Composed only from the public assurance engine, so it inherits its
51
+ * fail-closed evaluation, provenance checks, and selector validation - no bespoke evaluator.
52
+ *
53
+ * The rules are ordered most-specific-first because assurance evaluation is first-match-wins: each
54
+ * route is owned by exactly one rule, so that rule carries the FULL requirement bundle for its class
55
+ * (a body-carrying mutation proves bounded-body AND CSRF in one rule, not two). Raising the `level`
56
+ * widens those bundles; it never reorders them.
57
+ *
58
+ * Coverage by level (see {@link SecurityBaselineLevel} for the rationale):
59
+ *
60
+ * | invariant | essential | standard | strict |
61
+ * | --- | :-: | :-: | :-: |
62
+ * | unlimited body can never be "bounded" (F-001) | ✓ | ✓ | ✓ |
63
+ * | every body read is bounded | ✓ | ✓ | ✓ |
64
+ * | agent tool ingress is bounded | ✓ | ✓ | ✓ |
65
+ * | authenticated mutation proves CSRF | ✓ | ✓ | ✓ |
66
+ * | pii+ route is authenticated | | ✓ | ✓ |
67
+ * | every route carries a response contract | | | ✓ |
68
+ * | every read carries security headers | | | ✓ |
69
+ * | every mutation is rate limited | | | ✓ |
70
+ *
71
+ * The baseline deliberately does not select on `access`/`zone` capabilities: those selectors require
72
+ * capability definitions and would make the preset refuse an app that declares none. Extend the
73
+ * returned policy's `rules` for capability- or path-specific requirements; put more specific rules
74
+ * before these so they own their routes first.
75
+ */
76
+ export function securityBaseline(options: SecurityBaselineOptions = {}): AssurancePolicy {
77
+ const level = options.level ?? "standard"
78
+ const strict = level === "strict"
79
+ const authSensitive = level !== "essential"
80
+ const provenance = options.requireRuntimeProvenance === false ? "any" : "runtime"
81
+
82
+ const A = NIFRA_ASSURANCE_IDS
83
+ // Evidence the app must install middleware for, gated to the levels that assume that cost.
84
+ const contract = strict ? [A.RESPONSE_CONTRACT] : []
85
+ const headers = strict ? [A.SECURITY_HEADERS] : []
86
+ const rateLimit = strict ? [A.RATE_LIMITED] : []
87
+ const authed = authSensitive ? [A.AUTHENTICATED] : []
88
+
89
+ const rules: AssuranceRule[] = [
90
+ // The static twin of the config-time rejection: a schema route that opted into `bodyLimit:
91
+ // "unlimited"` can never carry `nifra.body-bounded` (the core withholds it), so requiring it is a
92
+ // standing ban. Owns the unlimited case before any body rule below can soften it. (F-001.)
93
+ {
94
+ name: "banned-unlimited-body",
95
+ match: { hasBody: true, bodyLimit: "unlimited" },
96
+ require: [A.BODY_BOUNDED],
97
+ },
98
+ // Agent tool ingress buffers attacker-influenced arguments; it must be bounded. Not CSRF-guarded:
99
+ // tool calls are token-authenticated machine traffic, not ambient-cookie browser posts.
100
+ {
101
+ name: "tool-ingress-bounded",
102
+ match: { tools: true, hasBody: true },
103
+ require: [A.BODY_BOUNDED, ...contract],
104
+ requireProvenance: provenance,
105
+ },
106
+ ]
107
+
108
+ // Sensitive mutations, split by body shape so bounded-body is required only where a body exists.
109
+ // Emitted only when a level adds a requirement beyond the generic mutation rules, otherwise they
110
+ // would be redundant duplicates that only slow evaluation.
111
+ if (authSensitive || strict) {
112
+ rules.push(
113
+ {
114
+ name: "sensitive-mutation-body",
115
+ match: { methods: [...MUTATING], hasBody: true, classificationAtLeast: SENSITIVE },
116
+ require: [A.BODY_BOUNDED, ...authed, ...contract, ...rateLimit],
117
+ requireCsrfWithAuthenticated: true,
118
+ requireProvenance: provenance,
119
+ },
120
+ {
121
+ name: "sensitive-mutation",
122
+ match: { methods: [...MUTATING], classificationAtLeast: SENSITIVE },
123
+ require: [...authed, ...contract, ...rateLimit],
124
+ requireCsrfWithAuthenticated: true,
125
+ requireProvenance: provenance,
126
+ },
127
+ )
128
+ }
129
+
130
+ rules.push(
131
+ {
132
+ name: "mutation-body",
133
+ match: { methods: [...MUTATING], hasBody: true },
134
+ require: [A.BODY_BOUNDED, ...contract, ...rateLimit],
135
+ requireCsrfWithAuthenticated: true,
136
+ requireProvenance: provenance,
137
+ },
138
+ {
139
+ name: "mutation",
140
+ match: { methods: [...MUTATING] },
141
+ require: [...contract, ...rateLimit],
142
+ requireCsrfWithAuthenticated: true,
143
+ requireProvenance: provenance,
144
+ },
145
+ )
146
+
147
+ if (authSensitive || strict) {
148
+ rules.push({
149
+ name: "sensitive-read",
150
+ match: { methods: [...READING], classificationAtLeast: SENSITIVE },
151
+ require: [...authed, ...contract, ...headers],
152
+ requireProvenance: provenance,
153
+ })
154
+ }
155
+
156
+ // The catch-all read rule. At essential/standard its requirement bundle is empty, so it is a pure
157
+ // classification that simply marks reads as covered - which matters only under `unmatched: "error"`,
158
+ // where an unowned route would otherwise fail. At strict it demands the response + header contract.
159
+ rules.push({
160
+ name: "read",
161
+ match: { methods: [...READING] },
162
+ require: [...contract, ...headers],
163
+ ...(strict ? { requireProvenance: provenance } : {}),
164
+ })
165
+
166
+ return {
167
+ rules,
168
+ unmatched: options.unmatched ?? "ignore",
169
+ // A wrong import reflecting zero routes must fail, not silently pass a security gate.
170
+ allowEmpty: false,
171
+ }
172
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The bare lane's ERROR rendering, as free functions the kernel delegates to.
3
+ *
4
+ * ## Why this is a lane module and not methods on `Server`
5
+ *
6
+ * These are the cold half of the bare request lane: what happens when a handler (or a `derive`)
7
+ * throws, rather than returns. The success half stays on the class - it reads request-lifecycle
8
+ * state and is the async-frame-skip hot path - but the error half needs none of that class state:
9
+ * `renderBareError` is pure control-flow routing, and `emitRequestErrorLog` needs only the logger
10
+ * and the detail policy, both of which are config fixed at construction. Passing those two in keeps
11
+ * this file free of any runtime dependency back on `server.ts`, so there is no import cycle: the
12
+ * `RawContext`/`CtxSet` imports are type-only and erased (the same shape `edge.ts` already relies on).
13
+ *
14
+ * A single source of truth for the thrown-value contract matters because it is a security surface:
15
+ * an unhandled throw must render as a 500 with no caller-controlled body, and the amount of the
16
+ * error's own text that reaches the log sink is the app's `errorLogDetail` call, not an accident of
17
+ * which lane caught it. Both the generic bare lane and the fused body runner route here, so that
18
+ * decision lives in exactly one place.
19
+ */
20
+ import { pathnameOf, plainError } from "./http.ts"
21
+ import type { Logger } from "./logger.ts"
22
+ import { isResponseResult, type ResponseResult } from "./runtime-core.ts"
23
+ import type { CtxSet, RawContext } from "./server.ts"
24
+
25
+ /** How much of a thrown error's own text reaches the log sink. Mirrors `Server`'s option. */
26
+ export type ErrorLogDetail = "full" | "message" | "none"
27
+
28
+ /**
29
+ * Render a value thrown on the bare lane. Three shapes, in the order the lane means them:
30
+ * - a bare `Response` is the app answering directly - passed through untouched;
31
+ * - a thrown `status(...)` is control flow, still plain data: rendered through the same `finalize`
32
+ * a RETURNED one takes, with the request's `c.set`, so it costs what the return costs;
33
+ * - anything else is a real fault: logged once, then a bodyless 500 (never the caller's error text).
34
+ *
35
+ * `responseSet` and `logError` are injected rather than imported so this file keeps no runtime edge
36
+ * back to `server.ts` (`responseSet` reaches into the context's set symbol; `logError` closes over the
37
+ * server's logger). Both run only on the throw path, so the closures cost nothing on the hot lane.
38
+ */
39
+ export function renderBareError<T>(
40
+ err: unknown,
41
+ ctx: RawContext,
42
+ finalize: (result: unknown, set: CtxSet, ctx: RawContext) => T,
43
+ wrapResponse: (response: Response | ResponseResult) => T,
44
+ responseSet: (ctx: RawContext) => CtxSet,
45
+ logError: (err: unknown, ctx: RawContext) => void,
46
+ ): T {
47
+ if (err instanceof Response) return wrapResponse(err)
48
+ if (isResponseResult(err)) return finalize(err, responseSet(ctx), ctx)
49
+ logError(err, ctx)
50
+ return wrapResponse(plainError(500, "internal_error"))
51
+ }
52
+
53
+ /**
54
+ * Write an unhandled request error to the log. An error's own text can quote the input that produced
55
+ * it, so how much of it reaches the sink is the app's call (`detail`). The default keeps it: a 500
56
+ * with no message and no stack is an incident nobody can diagnose, and the framework already ships
57
+ * the narrower instrument for the leak - a redacting logger with `valuePatterns`. `"none"` is there
58
+ * for an untrusted sink.
59
+ */
60
+ export function emitRequestErrorLog(
61
+ logger: Logger,
62
+ detail: ErrorLogDetail,
63
+ err: unknown,
64
+ ctx: RawContext,
65
+ ): void {
66
+ logger.error("unhandled request error", {
67
+ method: ctx.req.method,
68
+ path: pathnameOf(ctx.req.url),
69
+ name: err instanceof Error ? err.name : "Error",
70
+ // `detail`, not `message`: the logger uses `message` for its own first argument, so a field of
71
+ // that name is silently overwritten and the thrown error's own text never reaches the sink. It
72
+ // survived only incidentally inside `stack`, and was lost outright for a non-Error throw.
73
+ ...(detail === "none" ? {} : { detail: err instanceof Error ? err.message : String(err) }),
74
+ ...(detail === "full" && err instanceof Error ? { stack: err.stack } : {}),
75
+ })
76
+ }
@@ -37,6 +37,14 @@ export function rawBodySourceOf<T extends BodySource>(req: T): T {
37
37
  return ((req as { [RAW_BODY_READERS]?: T })[RAW_BODY_READERS] as T | undefined) ?? req
38
38
  }
39
39
 
40
+ /**
41
+ * The byte cap a route that declared `bodyLimit: "unlimited"` reads under. It is a real number, not
42
+ * `Infinity` or a skipped check: every bounded reader keeps its single `> maxBytes` enforcement
43
+ * point (and its `assertByteLimit` guard) rather than growing an uncapped branch that a future
44
+ * caller could reach by accident. No HTTP body reaches 2^53-1 bytes, so this is unlimited in fact.
45
+ */
46
+ export const UNLIMITED_BODY_BYTES = Number.MAX_SAFE_INTEGER
47
+
40
48
  /** Security/resource limits must be finite byte counts. Invalid values otherwise make `> maxBytes`
41
49
  * comparisons fail open (notably for `NaN`) and can re-enable unbounded buffering. */
42
50
  export function assertByteLimit(value: number, name = "maxBytes"): void {
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Wire marker keys shared between @nifrajs/core and the @nifrajs/node adapter.
3
+ *
4
+ * Each entry names a symbol looked up with `Symbol.for(...)`, so the two packages agree ONLY by the
5
+ * string. A rename on one side and not the other is a silent protocol break - no type error, just a
6
+ * symbol that never matches and a body that stops taking the direct-write lane. This module is the
7
+ * single source: core defines its own symbols from these literals, and `scripts/gen-node-outcome.ts`
8
+ * copies the map verbatim into the adapter's generated contract, so @nifrajs/node reads the identical
9
+ * strings without a runtime dependency on core (the same deployment shape the generated outcome type
10
+ * preserves).
11
+ *
12
+ * Keep this module import-free: every core file that owns one of these symbols imports it, so a cycle
13
+ * here would reach most of the response path.
14
+ */
15
+ export const NODE_BRIDGE_MARKER_KEYS = {
16
+ /** A `Response` carrying its already-serialized bytes, so the Node writer emits them without a drain. */
17
+ responseBody: "nifra.response.body",
18
+ /** A plain-data response-result carrier the node lane renders without building a `Response`. */
19
+ responseResult: "nifra.response.result",
20
+ /** Proof that a header record's names are already the lowercase wire spelling. */
21
+ lowercaseHeaderKeys: "nifra.headers.lowercase",
22
+ /** A mounted handler's node-direct resolver entry point. */
23
+ resolveNodeMount: "@nifrajs/core/resolve-node-mount",
24
+ } as const
@@ -64,7 +64,12 @@ export type Params<Path extends string> = Prettify<RawParams<Path>>
64
64
  export interface RouteSchema {
65
65
  /** Transport body cap for this route. Defaults to the server's maxBodyBytes. Use a finite
66
66
  * smaller/larger limit for a specific endpoint. The 'unlimited' value is an explicit
67
- * streaming/upload exemption and requires a non-empty bodyLimitReason for auditability. */
67
+ * streaming/upload exemption and requires a non-empty bodyLimitReason for auditability.
68
+ *
69
+ * 'unlimited' is legal only for schema-less streaming/upload routes. It is rejected with `body` or
70
+ * `idempotency`, because those lanes buffer the body before user code can apply a protocol-specific
71
+ * bound. Read an unlimited route from `c.req.body` as a stream and bound it by the protocol it speaks;
72
+ * `nifra.body-bounded` is deliberately NOT published for an unlimited route. */
68
73
  readonly bodyLimit?: number | "unlimited"
69
74
  /** Required explanation when bodyLimit is 'unlimited' (for example, a streaming upload is
70
75
  * bounded by an upstream object-store protocol). */
@@ -1,3 +1,5 @@
1
+ import { NODE_BRIDGE_MARKER_KEYS } from "./bridge-markers.ts"
2
+
1
3
  /**
2
4
  * The all-lowercase header-name proof: one answer, computed once per request, read by everyone who
3
5
  * would otherwise re-derive it.
@@ -23,7 +25,7 @@
23
25
  * Declared with `Symbol.for` so the `@nifrajs/node` adapter can read it by key rather than importing
24
26
  * across the package boundary - the same cross-package convention as the body and result marks.
25
27
  */
26
- const LOWERCASE_HEADER_KEYS = Symbol.for("nifra.headers.lowercase")
28
+ const LOWERCASE_HEADER_KEYS = Symbol.for(NODE_BRIDGE_MARKER_KEYS.lowercaseHeaderKeys)
27
29
 
28
30
  /** True when the name contains an ASCII `A`-`Z`, i.e. is not already the wire spelling. */
29
31
  export function hasUpperAscii(name: string): boolean {
@@ -1,8 +1,37 @@
1
1
  /**
2
- * Dependency-free HTTP helpers shared by the kernel and the opt-in request lanes (idempotency,
3
- * effect-ledger). Kept in a leaf module so a lane can reuse them without importing the server, and so
4
- * the server can reuse them without pulling a lane's feature code into the base bundle.
2
+ * HTTP helpers shared by the kernel and the opt-in request lanes (idempotency, effect-ledger). Kept
3
+ * in a leaf module (runtime-core aside, itself a leaf) so a lane can reuse them without importing the
4
+ * server, and so the server can reuse them without pulling a lane's feature code into the base bundle.
5
5
  */
6
+ import { type ResponseResult, status as statusResult } from "./runtime-core.ts"
7
+
8
+ /**
9
+ * Is `value` a destination that stays on this origin?
10
+ *
11
+ * True only for an absolute path: one leading `/`, never `//` (protocol-relative → another origin),
12
+ * and free of any character a URL parser turns into an origin escape. A leading `/` alone is not
13
+ * enough: under a special scheme `\` parses as `/`, and tab/CR/LF are STRIPPED before parsing, so
14
+ * `/\evil.example` and `/<TAB>/evil.example` both resolve to the external host `evil.example` while
15
+ * passing a `//` test. Rejecting CR/LF here also keeps a validated destination out of the
16
+ * response-splitting sink it usually flows into.
17
+ *
18
+ * One implementation, because every caller is the same open-redirect gate: `redirect()` in
19
+ * `@nifrajs/web`, the `redirectTo` of the `@nifrajs/auth` and `@nifrajs/better-auth` guards. Three
20
+ * copies of a security predicate is three chances for one of them to be hardened alone.
21
+ *
22
+ * It answers about a PATH, not a URL: an absolute `https://this.host/x` is false even for the
23
+ * current origin, because the whole point is that the value never got to name a host.
24
+ */
25
+ export function isSameOriginPath(value: string): boolean {
26
+ if (!value.startsWith("/") || value.startsWith("//")) return false
27
+ // Scanned by character code rather than matched by regex: no control characters have to be written
28
+ // into a pattern, and the check is a single pass over a short string.
29
+ for (let i = 1; i < value.length; i++) {
30
+ const code = value.charCodeAt(i)
31
+ if (code === 0x5c /* \ */ || code <= 0x1f || code === 0x7f) return false
32
+ }
33
+ return true
34
+ }
6
35
 
7
36
  /** A uniform JSON error envelope: `{ ok: false, error }` at the given status. */
8
37
  export function jsonError(
@@ -16,6 +45,27 @@ export function jsonError(
16
45
  )
17
46
  }
18
47
 
48
+ /**
49
+ * The same envelope as {@link jsonError}, as plain data rather than a built `Response`.
50
+ *
51
+ * This is what the framework's own renders - 404, 405, 422, the body caps, the timeouts, 500 - answer
52
+ * with wherever the value flows into a lane's response wrapper, so an error costs what a handler's
53
+ * plain return costs. Building the `Response` was measured as the dominant cost of answering early
54
+ * (see `PlainRender`), and on the Node lane an error `Response` is worse still: it is untagged, so
55
+ * the adapter cannot recognize its body and drains it through a Web stream, which is also why an
56
+ * error answered chunked while an ordinary return carries a `content-length`.
57
+ *
58
+ * `jsonError` stays for the callers that genuinely need a `Response` object (mount bridges, the
59
+ * lanes' own typed returns).
60
+ */
61
+ export function plainError(
62
+ status: number,
63
+ error: string,
64
+ headers?: Record<string, string>,
65
+ ): ResponseResult {
66
+ return statusResult(status, { ok: false, error }, headers !== undefined ? { headers } : undefined)
67
+ }
68
+
19
69
  export interface UrlParts {
20
70
  readonly pathname: string
21
71
  readonly search: string