@solobrand/http 0.0.0-stage → 0.1.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/README.md +148 -2
- package/dist/context/body.d.ts +21 -0
- package/dist/context/body.d.ts.map +1 -0
- package/dist/context/body.js +113 -0
- package/dist/context/body.js.map +1 -0
- package/dist/context/context.d.ts +44 -0
- package/dist/context/context.d.ts.map +1 -0
- package/dist/context/context.js +59 -0
- package/dist/context/context.js.map +1 -0
- package/dist/context/test-principal.d.ts +67 -0
- package/dist/context/test-principal.d.ts.map +1 -0
- package/dist/context/test-principal.js +193 -0
- package/dist/context/test-principal.js.map +1 -0
- package/dist/contracts.d.ts +109 -0
- package/dist/contracts.d.ts.map +1 -0
- package/dist/contracts.js +16 -0
- package/dist/contracts.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/kernel/errors.d.ts +17 -0
- package/dist/kernel/errors.d.ts.map +1 -0
- package/dist/kernel/errors.js +111 -0
- package/dist/kernel/errors.js.map +1 -0
- package/dist/kernel/form-request.d.ts +43 -0
- package/dist/kernel/form-request.d.ts.map +1 -0
- package/dist/kernel/form-request.js +103 -0
- package/dist/kernel/form-request.js.map +1 -0
- package/dist/kernel/kernel.d.ts +3 -0
- package/dist/kernel/kernel.d.ts.map +1 -0
- package/dist/kernel/kernel.js +220 -0
- package/dist/kernel/kernel.js.map +1 -0
- package/dist/kernel/keys.d.ts +20 -0
- package/dist/kernel/keys.d.ts.map +1 -0
- package/dist/kernel/keys.js +10 -0
- package/dist/kernel/keys.js.map +1 -0
- package/dist/kernel/messages.d.ts +10 -0
- package/dist/kernel/messages.d.ts.map +1 -0
- package/dist/kernel/messages.js +59 -0
- package/dist/kernel/messages.js.map +1 -0
- package/dist/kernel/pipeline.d.ts +3 -0
- package/dist/kernel/pipeline.d.ts.map +1 -0
- package/dist/kernel/pipeline.js +28 -0
- package/dist/kernel/pipeline.js.map +1 -0
- package/dist/kernel/registry.d.ts +63 -0
- package/dist/kernel/registry.d.ts.map +1 -0
- package/dist/kernel/registry.js +95 -0
- package/dist/kernel/registry.js.map +1 -0
- package/dist/kernel/throttle.d.ts +6 -0
- package/dist/kernel/throttle.d.ts.map +1 -0
- package/dist/kernel/throttle.js +27 -0
- package/dist/kernel/throttle.js.map +1 -0
- package/dist/kernel/tokens.d.ts +3 -0
- package/dist/kernel/tokens.d.ts.map +1 -0
- package/dist/kernel/tokens.js +6 -0
- package/dist/kernel/tokens.js.map +1 -0
- package/dist/router/path.d.ts +32 -0
- package/dist/router/path.d.ts.map +1 -0
- package/dist/router/path.js +198 -0
- package/dist/router/path.js.map +1 -0
- package/dist/router/router.d.ts +52 -0
- package/dist/router/router.d.ts.map +1 -0
- package/dist/router/router.js +163 -0
- package/dist/router/router.js.map +1 -0
- package/dist/security/body-limit.d.ts +14 -0
- package/dist/security/body-limit.d.ts.map +1 -0
- package/dist/security/body-limit.js +73 -0
- package/dist/security/body-limit.js.map +1 -0
- package/dist/security/cors.d.ts +18 -0
- package/dist/security/cors.d.ts.map +1 -0
- package/dist/security/cors.js +86 -0
- package/dist/security/cors.js.map +1 -0
- package/dist/security/csrf.d.ts +62 -0
- package/dist/security/csrf.d.ts.map +1 -0
- package/dist/security/csrf.js +108 -0
- package/dist/security/csrf.js.map +1 -0
- package/dist/security/d1-compat.d.ts +4 -0
- package/dist/security/d1-compat.d.ts.map +1 -0
- package/dist/security/d1-compat.js +4 -0
- package/dist/security/d1-compat.js.map +1 -0
- package/dist/security/fake-context.test-helper.d.ts +8 -0
- package/dist/security/fake-context.test-helper.d.ts.map +1 -0
- package/dist/security/fake-context.test-helper.js +24 -0
- package/dist/security/fake-context.test-helper.js.map +1 -0
- package/dist/security/headers.d.ts +37 -0
- package/dist/security/headers.d.ts.map +1 -0
- package/dist/security/headers.js +104 -0
- package/dist/security/headers.js.map +1 -0
- package/dist/security/index.d.ts +21 -0
- package/dist/security/index.d.ts.map +1 -0
- package/dist/security/index.js +14 -0
- package/dist/security/index.js.map +1 -0
- package/dist/security/messages.d.ts +22 -0
- package/dist/security/messages.d.ts.map +1 -0
- package/dist/security/messages.js +21 -0
- package/dist/security/messages.js.map +1 -0
- package/dist/security/migrations.d.ts +15 -0
- package/dist/security/migrations.d.ts.map +1 -0
- package/dist/security/migrations.js +27 -0
- package/dist/security/migrations.js.map +1 -0
- package/dist/security/rate-limit.d.ts +109 -0
- package/dist/security/rate-limit.d.ts.map +1 -0
- package/dist/security/rate-limit.js +232 -0
- package/dist/security/rate-limit.js.map +1 -0
- package/dist/security/sliding-window.d.ts +60 -0
- package/dist/security/sliding-window.d.ts.map +1 -0
- package/dist/security/sliding-window.js +134 -0
- package/dist/security/sliding-window.js.map +1 -0
- package/dist/security/util.d.ts +20 -0
- package/dist/security/util.d.ts.map +1 -0
- package/dist/security/util.js +57 -0
- package/dist/security/util.js.map +1 -0
- package/package.json +35 -4
package/README.md
CHANGED
|
@@ -1,3 +1,149 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @solobrand/http
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Router, FormRequest, responses, secure headers, CORS, CSRF, rate limiting for Workers.
|
|
4
|
+
|
|
5
|
+
Part of the [SoloBrand framework](../../README.md). Public API: `src/contracts.ts` (frozen, see CONTRIBUTING.md).
|
|
6
|
+
|
|
7
|
+
## Routing + kernel (F1 http, routing/kernel sub-front)
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createKernel, throttle, secureHeaders, D1RateLimitStore, FormRequest } from '@solobrand/http';
|
|
11
|
+
|
|
12
|
+
class StoreReserva extends FormRequest {
|
|
13
|
+
override readonly status = 201;
|
|
14
|
+
override rules() { return { email: 'required|email', guests: 'required|integer' }; }
|
|
15
|
+
override authorize(ctx) { return ctx.user !== null; } // default is FALSE
|
|
16
|
+
handle(ctx, input) { return { id: 1, ...input }; } // → { data: … } with 201
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export default createKernel({
|
|
20
|
+
app,
|
|
21
|
+
global: ['headers'],
|
|
22
|
+
middleware: { headers: secureHeaders(), throttle: throttle(new D1RateLimitStore(env.DB)) },
|
|
23
|
+
limiters: { login: { max: 5, perSeconds: 60 } },
|
|
24
|
+
routes: (r) => {
|
|
25
|
+
r.group({ prefix: '/api', middleware: ['auth'], name: 'api.' }, (api) => {
|
|
26
|
+
api.resource('reservas', { index: IndexReserva, show: ShowReserva, store: StoreReserva });
|
|
27
|
+
api.get('/reservas/:id(\\d+)/pdf', pdf).name('reservas.pdf');
|
|
28
|
+
});
|
|
29
|
+
r.post('/login', Login).throttle('login');
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- **Paths**: `:id` matches one segment (URI-decoded); `:id(\d+)` is anchored as a whole.
|
|
35
|
+
Static beats constrained beats plain, whatever the registration order. Trailing slash ignored.
|
|
36
|
+
- **Groups** stack prefix, middleware and name prefix. **Resources**: `GET /x` index,
|
|
37
|
+
`POST /x` store, `GET /x/:id` show, `PUT|PATCH /x/:id` update, `DELETE /x/:id` destroy,
|
|
38
|
+
named `x.index` … `x.destroy`. `router.url(name, params)` checks constraints; extra
|
|
39
|
+
params become the query string.
|
|
40
|
+
- **Pipeline**: global (around routing, so 404/405/500 get security headers too) → group →
|
|
41
|
+
route, onion-style; `next()` runs at most once. Whatever an inner step throws comes back
|
|
42
|
+
from `next()` already rendered, so outer middleware (`secureHeaders`) decorates every error
|
|
43
|
+
(SEC-008, fixed).
|
|
44
|
+
- **Build at boot**: routes and middleware are resolved once, on the first request, after
|
|
45
|
+
`app.boot()` (so providers have registered). An unknown middleware / limiter / `prefix:`,
|
|
46
|
+
a duplicate route or a name with two owners is a configuration error: every request is a
|
|
47
|
+
logged 500 and nothing is routed unguarded.
|
|
48
|
+
- **KernelRegistry** (providers contribute without the app wiring them):
|
|
49
|
+
`kernelRegistry(app)` (bound at `kernelRegistryToken`) → `routes(fn)` (runs after the
|
|
50
|
+
app's `routes`), `middleware(name, mw)`, `middlewareFactory('scope', arg => mw)` for
|
|
51
|
+
`scope:<arg>` (built once per name), `global(name)` (appended after the app's `global`;
|
|
52
|
+
if the app lists the name, the app's position wins — that is how the app orders
|
|
53
|
+
`session` before `csrf`), `limiter(name, limit)`. A name owned twice (registry and
|
|
54
|
+
`KernelOptions`) is refused, never overridden. Sealed once the kernel reads it.
|
|
55
|
+
- **FormRequest**: `authorize()` must return exactly `true` (else 403) → body parsed once
|
|
56
|
+
(JSON / urlencoded / multipart, `maxBody` default 1 MiB, counted on the stream) →
|
|
57
|
+
validated (query + body, only ruled fields pass, frozen) with the validator bound at
|
|
58
|
+
`validatorToken` (= `validationTokens.validator`, same symbol), else the stock
|
|
59
|
+
`createValidator()`, given the lookup bound at `validationLookupToken` when there is one
|
|
60
|
+
(`unique` / `exists` count rows through it; `databaseLookup(db)` builds it over a
|
|
61
|
+
`Database`; the app template binds it next to `dbTokens.database` — http never imports db,
|
|
62
|
+
AUD-33) → `handle`. Data → `{ data }` with
|
|
63
|
+
`status` (204 → empty body); a `Response` passes through.
|
|
64
|
+
*Authorize runs before validation* (unlike the brief's order): `authorize(ctx)` never sees
|
|
65
|
+
the input, and validating first would let an unauthorized caller probe `unique` rules.
|
|
66
|
+
- **HEAD** runs GET without a body; **OPTIONS** → 204 with `Allow` (CORS preflights are
|
|
67
|
+
answered earlier by `cors()`); **405** with `Allow`; unknown verbs (PROPFIND, TRACE…) never
|
|
68
|
+
routed, but their 404/405 runs inside the global middleware like any other (security
|
|
69
|
+
headers, CORS; AUD-36).
|
|
70
|
+
- **Errors**: a 4xx `AppError` → `{ data: null, message, errors? }` translated by
|
|
71
|
+
`Accept-Language` (es/en), error `headers` (e.g. `RateLimitError`) copied. **Every 5xx**
|
|
72
|
+
(`AppError('internal' | 'unavailable')` or anything thrown) → `{ data: null, message }` with
|
|
73
|
+
the generic `errors.internal` only — never its key, params or `errors` (AUD-32); those, and
|
|
74
|
+
the stack, go to `app.logger` (`http.unhandled`).
|
|
75
|
+
- **Per request**: `app.scope()` container with `httpTokens.context` and `httpTokens.router`;
|
|
76
|
+
`ctx.ip` = `CF-Connecting-IP` only; `ctx.locals.get(routeKey)` = matched route.
|
|
77
|
+
- **Throttle**: `route.throttle('login')` runs the middleware named `throttle` with
|
|
78
|
+
`ctx.locals.get(throttleKey)` = `{ name, limit }`; `throttle(store)` is the adapter over
|
|
79
|
+
`rateLimit`. A route with a limit and no `throttle` middleware is a boot error.
|
|
80
|
+
- `createContext({ request, app, … })` builds a context without a kernel (middleware tests).
|
|
81
|
+
- **actingAs hook**: `readTestPrincipal(request, env)` (+ `testPrincipalMiddleware`,
|
|
82
|
+
`encodeTestPrincipal`, `generateTestKey`, `testHookEnabled`, header/env names) moved here
|
|
83
|
+
from `@solobrand/testing`; honoured only with `SOLOBRAND_TESTING === '1'` and a
|
|
84
|
+
`SOLOBRAND_TEST_KEY` that looks like ≥ 32 random bytes (`testKeyAcceptable`: 64 hex or
|
|
85
|
+
≥ 43 base64url chars, not repeated / patterned / a placeholder), matched in constant time.
|
|
86
|
+
The kernel warns once at boot (`http.test_hook_enabled`) when the flag is on outside a
|
|
87
|
+
local origin (SEC-013). Auth guards read it first.
|
|
88
|
+
- Defaults for `errors.*`, `validation.*` and `security.*` keys (es/en) are added only where
|
|
89
|
+
the app has no translation of its own.
|
|
90
|
+
|
|
91
|
+
### Status
|
|
92
|
+
|
|
93
|
+
- **Implemented**: everything above (`src/router`, `src/kernel`, `src/context`, `src/index.ts`,
|
|
94
|
+
which also re-exports `src/security`). Integrator decisions applied: KernelRegistry,
|
|
95
|
+
`readTestPrincipal` moved, `validatorToken` = `validationTokens.validator`, SEC-008 and
|
|
96
|
+
SEC-013 fixed.
|
|
97
|
+
- **Tested**: `src/**/*.test.ts` — path matching/constraints/escaping/decoding, specificity,
|
|
98
|
+
groups/resources/names/url, duplicates and late registration; body parsing, `__proto__`
|
|
99
|
+
keys, Content-Length and streamed caps, `CF-Connecting-IP` vs spoofed `X-Forwarded-For`;
|
|
100
|
+
kernel order of middleware, 404/405/HEAD/OPTIONS, authorize-false/truthy-non-boolean → 403,
|
|
101
|
+
authorize before validate, only validated fields reach `handle`, 413/422, no stack or
|
|
102
|
+
message leak on 500, broken translator, boot once / retry after failed boot, request
|
|
103
|
+
scope, throttle wiring fail-closed and 429 with `Retry-After` over `MemoryRateLimitStore`,
|
|
104
|
+
errors from inner global/route middleware decorated by outer ones (SEC-008, plus
|
|
105
|
+
`security/tests/http/kernel.test.ts`), configuration errors → 500 at boot; registry:
|
|
106
|
+
provider routes/middleware/globals/limiters, `scope:*` factories, ordering, duplicate
|
|
107
|
+
owners, bad names, sealing, foreign binding; the actingAs hook (flag, key, malformed
|
|
108
|
+
principal), SEC-013 (weak/patterned/placeholder keys refused, generated keys accepted,
|
|
109
|
+
never authenticates outside testing, boot warning without the key); one run on the real
|
|
110
|
+
`createApplication`.
|
|
111
|
+
- **Left** (owned by others): `@solobrand/testing` still has its own copy of the hook in
|
|
112
|
+
`src/hook.ts` — its owner switches it to a re-export of `@solobrand/http` (its
|
|
113
|
+
`test-app.test.ts` mocks `@solobrand/core` wholesale, so the switch needs that mock to
|
|
114
|
+
keep `token`, and its copy still checks the key by length only); the token guard reading
|
|
115
|
+
the hook by default is F3 auth's to turn off (defence in depth); a DB `lookup` for
|
|
116
|
+
`unique`/`exists` comes from whoever binds the validator; locale from the user's profile
|
|
117
|
+
(only `Accept-Language` today).
|
|
118
|
+
|
|
119
|
+
TERMINADO 2026-11-28
|
|
120
|
+
|
|
121
|
+
## Security middleware (F1 http, security sub-front)
|
|
122
|
+
|
|
123
|
+
`src/security/` — details and integration notes in [`src/security/README.md`](src/security/README.md).
|
|
124
|
+
|
|
125
|
+
### Status
|
|
126
|
+
|
|
127
|
+
- **Implemented**: `secureHeaders()` + `cspNonce()` (nonce CSP, HSTS, nosniff,
|
|
128
|
+
Referrer-Policy, Permissions-Policy, COOP/CORP, frame-ancestors none), `cors()`
|
|
129
|
+
(exact allowlist, credentials only with explicit origins, preflight), `csrf()`
|
|
130
|
+
(Origin / `Sec-Fetch-Site` check, `X-CSRF-Token` or `_token` form field compared in
|
|
131
|
+
constant time against a `CsrfTokenSource`, Bearer exempt, 419), `rateLimit()` with
|
|
132
|
+
`MemoryRateLimitStore` and `D1RateLimitStore` (fixed window, one atomic upsert,
|
|
133
|
+
`X-RateLimit-*`, `Retry-After`, 429), `slidingRateLimit()` with
|
|
134
|
+
`MemorySlidingRateLimitStore` / `D1SlidingRateLimitStore` (weighted two-window counter,
|
|
135
|
+
no 2 × max boundary burst), `bodyLimit()` / `readLimited()` (Content-Length
|
|
136
|
+
and streamed counting, 413), `securityMessages` (es/en, `{param}` as core interpolates).
|
|
137
|
+
- **Tested**: `src/security/*.test.ts`, 94 threat-oriented tests — cross-origin and
|
|
138
|
+
look-alike origins, `null` origin, missing/empty/wrong token, token replay across
|
|
139
|
+
sessions, duplicated headers and repeated `_token` fields, Bearer scheme case, CORS
|
|
140
|
+
wildcard+credentials refused at boot, handler-added CORS grants stripped, CSP
|
|
141
|
+
injection, oversized chunked and lying-length bodies, limiter key collisions,
|
|
142
|
+
50 concurrent hits counted atomically on real SQLite, sliding window closing the
|
|
143
|
+
boundary burst with an exact `Retry-After`, lagging isolate clocks never resetting a
|
|
144
|
+
window, messages through core's
|
|
145
|
+
translator. No red-team finding in `security/FINDINGS.md` is open against this
|
|
146
|
+
sub-front (SEC-008 belongs to the kernel).
|
|
147
|
+
- **Left**: nothing here; `throttle()` (kernel) still uses the fixed window.
|
|
148
|
+
|
|
149
|
+
TERMINADO 2026-11-28
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Body parsing with a hard size cap. The stream is counted as it is read, so
|
|
3
|
+
* a lying or missing Content-Length cannot get past the limit.
|
|
4
|
+
*/
|
|
5
|
+
import { AppError } from '@solobrand/core';
|
|
6
|
+
import type { Input } from '@solobrand/validation';
|
|
7
|
+
/** Defines an own property: `__proto__` from a form is a key, never a prototype. */
|
|
8
|
+
/**
|
|
9
|
+
* 415: a body in a media type the kernel does not read (AUD-38). Core's error codes have no
|
|
10
|
+
* 415 (proposed in CONTRACT-CHANGES.md), so the code stays `validation_failed` and the
|
|
11
|
+
* status says 415; the renderer honours it.
|
|
12
|
+
*/
|
|
13
|
+
export declare class UnsupportedMediaTypeError extends AppError {
|
|
14
|
+
constructor(type: string);
|
|
15
|
+
}
|
|
16
|
+
export declare function setOwn(target: Record<string, unknown>, key: string, value: unknown): void;
|
|
17
|
+
export declare function readCapped(request: Request, max: number): Promise<Uint8Array>;
|
|
18
|
+
/** Repeated keys (and `key[]`) collect into arrays. */
|
|
19
|
+
export declare function entriesToInput(entries: Iterable<[string, unknown]>): Record<string, unknown>;
|
|
20
|
+
export declare function parseBody(request: Request, max: number): Promise<Input>;
|
|
21
|
+
//# sourceMappingURL=body.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"body.d.ts","sourceRoot":"","sources":["../../src/context/body.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAEnD,oFAAoF;AACpF;;;;GAIG;AACH,qBAAa,yBAA0B,SAAQ,QAAQ;gBACzC,IAAI,EAAE,MAAM;CAIzB;AAED,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEzF;AAED,wBAAsB,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CA2BnF;AAMD,uDAAuD;AACvD,wBAAgB,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAY5F;AAED,wBAAsB,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAkC7E"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Body parsing with a hard size cap. The stream is counted as it is read, so
|
|
3
|
+
* a lying or missing Content-Length cannot get past the limit.
|
|
4
|
+
*/
|
|
5
|
+
import { AppError } from '@solobrand/core';
|
|
6
|
+
/** Defines an own property: `__proto__` from a form is a key, never a prototype. */
|
|
7
|
+
/**
|
|
8
|
+
* 415: a body in a media type the kernel does not read (AUD-38). Core's error codes have no
|
|
9
|
+
* 415 (proposed in CONTRACT-CHANGES.md), so the code stays `validation_failed` and the
|
|
10
|
+
* status says 415; the renderer honours it.
|
|
11
|
+
*/
|
|
12
|
+
export class UnsupportedMediaTypeError extends AppError {
|
|
13
|
+
constructor(type) {
|
|
14
|
+
super('validation_failed', 'errors.unsupported_media_type', { params: { type } });
|
|
15
|
+
Object.defineProperty(this, 'status', { value: 415, enumerable: true });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function setOwn(target, key, value) {
|
|
19
|
+
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
|
|
20
|
+
}
|
|
21
|
+
export async function readCapped(request, max) {
|
|
22
|
+
const declared = request.headers.get('content-length');
|
|
23
|
+
if (declared !== null && declared.trim() !== '') {
|
|
24
|
+
const n = Number(declared);
|
|
25
|
+
if (Number.isFinite(n) && n > max)
|
|
26
|
+
throw new AppError('payload_too_large', 'errors.payload_too_large', { params: { max } });
|
|
27
|
+
}
|
|
28
|
+
if (!request.body)
|
|
29
|
+
return new Uint8Array(0);
|
|
30
|
+
const reader = request.body.getReader();
|
|
31
|
+
const chunks = [];
|
|
32
|
+
let total = 0;
|
|
33
|
+
for (;;) {
|
|
34
|
+
const { done, value } = await reader.read();
|
|
35
|
+
if (done)
|
|
36
|
+
break;
|
|
37
|
+
total += value.byteLength;
|
|
38
|
+
if (total > max) {
|
|
39
|
+
await reader.cancel().catch(() => undefined);
|
|
40
|
+
throw new AppError('payload_too_large', 'errors.payload_too_large', { params: { max } });
|
|
41
|
+
}
|
|
42
|
+
chunks.push(value);
|
|
43
|
+
}
|
|
44
|
+
const out = new Uint8Array(total);
|
|
45
|
+
let offset = 0;
|
|
46
|
+
for (const c of chunks) {
|
|
47
|
+
out.set(c, offset);
|
|
48
|
+
offset += c.byteLength;
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
function mediaType(request) {
|
|
53
|
+
return (request.headers.get('content-type') ?? '').split(';')[0]?.trim().toLowerCase() ?? '';
|
|
54
|
+
}
|
|
55
|
+
/** Repeated keys (and `key[]`) collect into arrays. */
|
|
56
|
+
export function entriesToInput(entries) {
|
|
57
|
+
const out = {};
|
|
58
|
+
for (const [rawKey, value] of entries) {
|
|
59
|
+
const isList = rawKey.endsWith('[]');
|
|
60
|
+
const key = isList ? rawKey.slice(0, -2) : rawKey;
|
|
61
|
+
const has = Object.prototype.hasOwnProperty.call(out, key);
|
|
62
|
+
const current = has ? out[key] : undefined;
|
|
63
|
+
if (Array.isArray(current))
|
|
64
|
+
current.push(value);
|
|
65
|
+
else if (has)
|
|
66
|
+
setOwn(out, key, [current, value]);
|
|
67
|
+
else
|
|
68
|
+
setOwn(out, key, isList ? [value] : value);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
export async function parseBody(request, max) {
|
|
73
|
+
if (request.method === 'GET' || request.method === 'HEAD')
|
|
74
|
+
return {};
|
|
75
|
+
const bytes = await readCapped(request, max);
|
|
76
|
+
if (bytes.byteLength === 0)
|
|
77
|
+
return {};
|
|
78
|
+
const type = mediaType(request);
|
|
79
|
+
if (type === 'application/json' || type.endsWith('+json')) {
|
|
80
|
+
let value;
|
|
81
|
+
try {
|
|
82
|
+
value = JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bytes));
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
throw new AppError('validation_failed', 'errors.invalid_json');
|
|
86
|
+
}
|
|
87
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
88
|
+
throw new AppError('validation_failed', 'errors.invalid_json');
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
91
|
+
if (type === 'application/x-www-form-urlencoded') {
|
|
92
|
+
let text;
|
|
93
|
+
try {
|
|
94
|
+
text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bytes);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw new AppError('validation_failed', 'errors.invalid_body');
|
|
98
|
+
}
|
|
99
|
+
return entriesToInput(new URLSearchParams(text));
|
|
100
|
+
}
|
|
101
|
+
if (type === 'multipart/form-data') {
|
|
102
|
+
let form;
|
|
103
|
+
try {
|
|
104
|
+
form = await new Response(bytes, { headers: { 'content-type': request.headers.get('content-type') ?? '' } }).formData();
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
throw new AppError('validation_failed', 'errors.invalid_body');
|
|
108
|
+
}
|
|
109
|
+
return entriesToInput(form.entries());
|
|
110
|
+
}
|
|
111
|
+
throw new UnsupportedMediaTypeError(type || 'none');
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=body.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"body.js","sourceRoot":"","sources":["../../src/context/body.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAG3C,oFAAoF;AACpF;;;;GAIG;AACH,MAAM,OAAO,yBAA0B,SAAQ,QAAQ;IACrD,YAAY,IAAY;QACtB,KAAK,CAAC,mBAAmB,EAAE,+BAA+B,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,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M,CAAC,CAAC;AACtD,CAAC"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Application, Container } from '@solobrand/core';
|
|
2
|
+
import type { Input } from '@solobrand/validation';
|
|
3
|
+
import type { HttpContext, Method, Principal } from '../contracts.js';
|
|
4
|
+
export declare const DEFAULT_MAX_BODY: number;
|
|
5
|
+
export declare const METHODS: readonly Method[];
|
|
6
|
+
export declare function isMethod(value: string): value is Method;
|
|
7
|
+
export interface CreateContextOptions {
|
|
8
|
+
readonly request: Request;
|
|
9
|
+
readonly app: Application;
|
|
10
|
+
/** Defaults to `app.scope()`. */
|
|
11
|
+
readonly container?: Container;
|
|
12
|
+
readonly execution?: ExecutionContext;
|
|
13
|
+
readonly params?: Readonly<Record<string, string>>;
|
|
14
|
+
/** Body cap in bytes (default 1 MiB). */
|
|
15
|
+
readonly maxBody?: number;
|
|
16
|
+
readonly user?: Principal | null;
|
|
17
|
+
/**
|
|
18
|
+
* Accept a verb outside `Method` (PROPFIND, a made-up one). The kernel sets it so an
|
|
19
|
+
* unknown verb still runs the GLOBAL middleware (security headers, CORS) before its
|
|
20
|
+
* 404/405 (AUD-36); such a context never reaches a route. `ctx.method` is then the
|
|
21
|
+
* verb as sent, upper-cased.
|
|
22
|
+
*/
|
|
23
|
+
readonly allowUnknownMethod?: boolean;
|
|
24
|
+
}
|
|
25
|
+
export declare class Context implements HttpContext {
|
|
26
|
+
readonly request: Request;
|
|
27
|
+
readonly url: URL;
|
|
28
|
+
readonly method: Method;
|
|
29
|
+
/** Set by the kernel once the route matched. */
|
|
30
|
+
params: Readonly<Record<string, string>>;
|
|
31
|
+
readonly query: URLSearchParams;
|
|
32
|
+
readonly app: Application;
|
|
33
|
+
readonly container: Container;
|
|
34
|
+
readonly execution: ExecutionContext;
|
|
35
|
+
user: Principal | null;
|
|
36
|
+
readonly locals: Map<string | symbol, unknown>;
|
|
37
|
+
readonly ip: string | null;
|
|
38
|
+
private readonly maxBody;
|
|
39
|
+
private parsed;
|
|
40
|
+
constructor(options: CreateContextOptions);
|
|
41
|
+
body(): Promise<Input>;
|
|
42
|
+
}
|
|
43
|
+
export declare function createContext(options: CreateContextOptions): HttpContext;
|
|
44
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/context/context.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAGtE,eAAO,MAAM,gBAAgB,QAAc,CAAC;AAE5C,eAAO,MAAM,OAAO,EAAE,SAAS,MAAM,EAAiE,CAAC;AAEvG,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,MAAM,CAEvD;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,GAAG,EAAE,WAAW,CAAC;IAC1B,iCAAiC;IACjC,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC;IAC/B,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,CAAC;IACtC,QAAQ,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,yCAAyC;IACzC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,GAAG,IAAI,CAAC;IACjC;;;;;OAKG;IACH,QAAQ,CAAC,kBAAkB,CAAC,EAAE,OAAO,CAAC;CACvC;AAOD,qBAAa,OAAQ,YAAW,WAAW;IACzC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC;IAClB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,gDAAgD;IAChD,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACzC,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC;IAChC,QAAQ,CAAC,GAAG,EAAE,WAAW,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,gBAAgB,CAAC;IACrC,IAAI,EAAE,SAAS,GAAG,IAAI,CAAC;IACvB,QAAQ,CAAC,MAAM,gCAAuC;IACtD,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,MAAM,CAA+B;gBAEjC,OAAO,EAAE,oBAAoB;IAqBzC,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC;CAIvB;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,WAAW,CAExE"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-request HttpContext. `createContext` is public so middleware
|
|
3
|
+
* (and the security sub-front's tests) can build one without a kernel.
|
|
4
|
+
*/
|
|
5
|
+
import { AppError } from '@solobrand/core';
|
|
6
|
+
import { parseBody } from './body.js';
|
|
7
|
+
export const DEFAULT_MAX_BODY = 1024 * 1024;
|
|
8
|
+
export const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
9
|
+
export function isMethod(value) {
|
|
10
|
+
return METHODS.includes(value);
|
|
11
|
+
}
|
|
12
|
+
const noopExecution = {
|
|
13
|
+
waitUntil() { },
|
|
14
|
+
passThroughOnException() { },
|
|
15
|
+
};
|
|
16
|
+
export class Context {
|
|
17
|
+
request;
|
|
18
|
+
url;
|
|
19
|
+
method;
|
|
20
|
+
/** Set by the kernel once the route matched. */
|
|
21
|
+
params;
|
|
22
|
+
query;
|
|
23
|
+
app;
|
|
24
|
+
container;
|
|
25
|
+
execution;
|
|
26
|
+
user;
|
|
27
|
+
locals = new Map();
|
|
28
|
+
ip;
|
|
29
|
+
maxBody;
|
|
30
|
+
parsed = null;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
const method = options.request.method.toUpperCase();
|
|
33
|
+
if (!isMethod(method) && options.allowUnknownMethod !== true) {
|
|
34
|
+
throw new AppError('internal', 'errors.method_unsupported', { params: { method } });
|
|
35
|
+
}
|
|
36
|
+
this.request = options.request;
|
|
37
|
+
this.url = new URL(options.request.url);
|
|
38
|
+
// Only an unrouted context (allowUnknownMethod) holds a verb outside Method.
|
|
39
|
+
this.method = method;
|
|
40
|
+
this.params = options.params ?? {};
|
|
41
|
+
this.query = this.url.searchParams;
|
|
42
|
+
this.app = options.app;
|
|
43
|
+
this.container = options.container ?? options.app.scope();
|
|
44
|
+
this.execution = options.execution ?? noopExecution;
|
|
45
|
+
this.user = options.user ?? null;
|
|
46
|
+
this.maxBody = options.maxBody ?? DEFAULT_MAX_BODY;
|
|
47
|
+
// Only Cloudflare's header: X-Forwarded-For / X-Real-IP are client-controlled.
|
|
48
|
+
const ip = options.request.headers.get('cf-connecting-ip');
|
|
49
|
+
this.ip = ip && ip.trim() !== '' ? ip.trim() : null;
|
|
50
|
+
}
|
|
51
|
+
body() {
|
|
52
|
+
this.parsed ??= parseBody(this.request, this.maxBody);
|
|
53
|
+
return this.parsed;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
export function createContext(options) {
|
|
57
|
+
return new Context(options);
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/context/context.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,Q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AC,GAAG,CAAC,CAAC;QACxC,6EAA6E;QAC7E,IAAI,CAAC,MAAM,GAAG,MAAgB,CAAC;QAC/B,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;QACnC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC;QACnC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;QAC1D,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,aAAa,CAAC;QACpD,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC;QACjC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,gBAAgB,CAAC;QACnD,+EAA+E;QAC/E,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;QAC3D,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACtD,CAAC;IAED,IAAI;QACF,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACtD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AAED,MAAM,UAAU,aAAa,CAAC,OAA6B;IACzD,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;AAC9B,CAAC"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `actingAs()` test hook — Workers-safe, no dependencies (moved here from
|
|
3
|
+
* @solobrand/testing, which re-exports it, so the auth guards can read it).
|
|
4
|
+
*
|
|
5
|
+
* `TestApp.actingAs(user)` sends two headers:
|
|
6
|
+
*
|
|
7
|
+
* X-SoloBrand-Test-Principal: base64url(JSON principal)
|
|
8
|
+
* X-SoloBrand-Test-Key: the per-test-app random key
|
|
9
|
+
*
|
|
10
|
+
* A guard honours them ONLY when BOTH hold:
|
|
11
|
+
* 1. `env.SOLOBRAND_TESTING === '1'` (exactly the string '1'), and
|
|
12
|
+
* 2. `env.SOLOBRAND_TEST_KEY` looks like ≥ 32 random bytes (`generateTestKey()`:
|
|
13
|
+
* 64 hex chars; or ≥ 43 base64url chars) and is not trivial (one repeated
|
|
14
|
+
* character, a short repeating pattern, few distinct characters, a known
|
|
15
|
+
* placeholder such as «changeme»), and the key header equals it in
|
|
16
|
+
* constant time. `createTestApp` generates a fresh random key per app.
|
|
17
|
+
* 3. the request — and `env.APP_URL` when set — is on a local origin
|
|
18
|
+
* (localhost, loopback, `*.localhost`, `.test`): never on a deployed host.
|
|
19
|
+
* Anything else — flag missing or different, key missing, short, weak or wrong,
|
|
20
|
+
* a non-local origin, a malformed principal — and the hook returns null.
|
|
21
|
+
* Deploys never set these vars, so in production the headers are inert noise;
|
|
22
|
+
* the kernel logs a warning at boot when the flag is on outside a local origin
|
|
23
|
+
* (SEC-013).
|
|
24
|
+
*/
|
|
25
|
+
import type { Middleware, Principal } from '../contracts.js';
|
|
26
|
+
export declare const TEST_PRINCIPAL_HEADER = "x-solobrand-test-principal";
|
|
27
|
+
export declare const TEST_KEY_HEADER = "x-solobrand-test-key";
|
|
28
|
+
export declare const TESTING_FLAG = "SOLOBRAND_TESTING";
|
|
29
|
+
export declare const TESTING_KEY = "SOLOBRAND_TEST_KEY";
|
|
30
|
+
/**
|
|
31
|
+
* A random key for `env.SOLOBRAND_TEST_KEY` (32 bytes, hex) that `testKeyAcceptable` takes.
|
|
32
|
+
* About 1 random key in 140 000 contains a placeholder run (`123456`, `abcdef`): drawn again.
|
|
33
|
+
*/
|
|
34
|
+
export declare function generateTestKey(): string;
|
|
35
|
+
/** The header value for a principal (what `actingAs` sends). */
|
|
36
|
+
export declare function encodeTestPrincipal(principal: Principal): string;
|
|
37
|
+
/**
|
|
38
|
+
* True when `key` can gate the hook: the shape of ≥ 32 random bytes and not a
|
|
39
|
+
* memorable or patterned value. A random `generateTestKey()` always passes
|
|
40
|
+
* (P(< 8 distinct hex digits in 64) is negligible).
|
|
41
|
+
*/
|
|
42
|
+
export declare function testKeyAcceptable(key: unknown): key is string;
|
|
43
|
+
/** True only when the env enables the hook: flag exactly '1' and an acceptable key. */
|
|
44
|
+
export declare function testHookEnabled(env: Readonly<Record<string, unknown>>): boolean;
|
|
45
|
+
/** localhost, loopback, `*.localhost` and the reserved `.test` TLD (createTestApp's origin). */
|
|
46
|
+
export declare function isLocalOrigin(url: string): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* What the kernel says at boot about the hook (null: nothing to say). The flag
|
|
49
|
+
* on outside a local origin is a warning even when the key is weak (the hook
|
|
50
|
+
* then stays off, which is also worth knowing).
|
|
51
|
+
*/
|
|
52
|
+
export declare function testHookWarning(env: Readonly<Record<string, unknown>>, requestUrl: string): {
|
|
53
|
+
message: string;
|
|
54
|
+
context: Record<string, unknown>;
|
|
55
|
+
} | null;
|
|
56
|
+
/**
|
|
57
|
+
* The principal a test asked for, or null. Guards call this first and fall back
|
|
58
|
+
* to their real credential check when it returns null.
|
|
59
|
+
*/
|
|
60
|
+
export declare function readTestPrincipal(request: Request, env: Readonly<Record<string, unknown>>): Principal | null;
|
|
61
|
+
/**
|
|
62
|
+
* The hook as a global middleware, for kernels that want it before the auth
|
|
63
|
+
* guards run: sets `ctx.user` from the hook when it is enabled and no user is
|
|
64
|
+
* set yet. Harmless in production (the hook is off there).
|
|
65
|
+
*/
|
|
66
|
+
export declare const testPrincipalMiddleware: Middleware;
|
|
67
|
+
//# sourceMappingURL=test-principal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"test-principal.d.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