@rexezuge/http 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +146 -12
- package/dist/ErrorMapper.d.ts +65 -10
- package/dist/ErrorMapper.d.ts.map +1 -1
- package/dist/ErrorMapper.js +1 -1
- package/dist/ErrorMapper.js.map +3 -3
- package/dist/errorClassification.d.ts +44 -0
- package/dist/errorClassification.d.ts.map +1 -0
- package/dist/errorClassification.js +1 -0
- package/dist/errorClassification.js.map +7 -0
- package/dist/hono/FamilyRoute.d.ts +56 -0
- package/dist/hono/FamilyRoute.d.ts.map +1 -0
- package/dist/hono/FamilyRoute.js +1 -0
- package/dist/hono/FamilyRoute.js.map +7 -0
- package/dist/hono/auth.d.ts +91 -0
- package/dist/hono/auth.d.ts.map +1 -0
- package/dist/hono/auth.js +1 -0
- package/dist/hono/auth.js.map +7 -0
- package/dist/hono/bookmarks.d.ts +63 -0
- package/dist/hono/bookmarks.d.ts.map +1 -0
- package/dist/hono/bookmarks.js +1 -0
- package/dist/hono/bookmarks.js.map +7 -0
- package/dist/hono/createApiApp.d.ts +93 -0
- package/dist/hono/createApiApp.d.ts.map +1 -0
- package/dist/hono/createApiApp.js +1 -0
- package/dist/hono/createApiApp.js.map +7 -0
- package/dist/hono/errorHandler.d.ts +25 -0
- package/dist/hono/errorHandler.d.ts.map +1 -0
- package/dist/hono/errorHandler.js +1 -0
- package/dist/hono/errorHandler.js.map +7 -0
- package/dist/hono/hardening.d.ts +51 -0
- package/dist/hono/hardening.d.ts.map +1 -0
- package/dist/hono/hardening.js +1 -0
- package/dist/hono/hardening.js.map +7 -0
- package/dist/hono/index.d.ts +33 -0
- package/dist/hono/index.d.ts.map +1 -0
- package/dist/hono/index.js +1 -0
- package/dist/hono/index.js.map +7 -0
- package/dist/hono/rateLimits.d.ts +63 -0
- package/dist/hono/rateLimits.d.ts.map +1 -0
- package/dist/hono/rateLimits.js +1 -0
- package/dist/hono/rateLimits.js.map +7 -0
- package/dist/hono/requestContext.d.ts +28 -0
- package/dist/hono/requestContext.d.ts.map +1 -0
- package/dist/hono/requestContext.js +1 -0
- package/dist/hono/requestContext.js.map +7 -0
- package/dist/hono/types.d.ts +69 -0
- package/dist/hono/types.d.ts.map +1 -0
- package/dist/hono/types.js +1 -0
- package/dist/hono/types.js.map +7 -0
- package/dist/index.d.ts +20 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/openApiErrors.d.ts +63 -0
- package/dist/openApiErrors.d.ts.map +1 -0
- package/dist/openApiErrors.js +1 -0
- package/dist/openApiErrors.js.map +7 -0
- package/dist/requestGuards.d.ts +52 -0
- package/dist/requestGuards.d.ts.map +1 -0
- package/dist/requestGuards.js +1 -0
- package/dist/requestGuards.js.map +7 -0
- package/dist/routeBase.d.ts.map +1 -1
- package/dist/routeBase.js +1 -1
- package/dist/routeBase.js.map +3 -3
- package/package.json +12 -5
package/README.md
CHANGED
|
@@ -15,21 +15,32 @@ So this is the one package that is framework-shaped, deliberately. Nothing in th
|
|
|
15
15
|
other eight imports it, so a repo that wants the framework-free core can keep
|
|
16
16
|
taking only that.
|
|
17
17
|
|
|
18
|
-
It
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
It has two entry points:
|
|
19
|
+
|
|
20
|
+
- **`@rexezuge/http`** (the root barrel) is **framework-free**. Every entry point
|
|
21
|
+
takes a structural context type (see below), so a bare-`Request` dispatcher (a
|
|
22
|
+
Durable Object, a route-table loop) can use it without Hono installed.
|
|
23
|
+
- **`@rexezuge/http/hono`** is the Hono + chanfana app kernel: `createApiApp`,
|
|
24
|
+
`FamilyRoute`, `accessAuth` / `apiKeyAuth` and the hardening middleware.
|
|
25
|
+
Everything that imports `hono` or `chanfana` lives here, and nowhere else.
|
|
26
|
+
|
|
27
|
+
`hono` and `chanfana` are **optional peer dependencies**: not needed for the root
|
|
28
|
+
barrel, **required if you import `@rexezuge/http/hono`**. The app brings its own
|
|
29
|
+
copy, and this package never pins or duplicates it. The only third-party runtime
|
|
30
|
+
dependency is `jose` (Cloudflare Access JWT verification).
|
|
23
31
|
|
|
24
32
|
## What converged here
|
|
25
33
|
|
|
26
|
-
| Module | From
|
|
27
|
-
| ----------------- |
|
|
28
|
-
| `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header
|
|
29
|
-
| `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument
|
|
30
|
-
| `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute
|
|
31
|
-
| `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience
|
|
32
|
-
| `routeBase` | All three incompatible shapes, with their shared parts converged
|
|
34
|
+
| Module | From |
|
|
35
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------------- |
|
|
36
|
+
| `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |
|
|
37
|
+
| `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |
|
|
38
|
+
| `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |
|
|
39
|
+
| `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |
|
|
40
|
+
| `routeBase` | All three incompatible shapes, with their shared parts converged |
|
|
41
|
+
| `requestGuards` | `HttpHardening.ts` ×4, AWS-AccessBridge `RequestGuards.ts`, Image-Host's CSRF guard, Pigeongram's `origin.ts` |
|
|
42
|
+
| `openApiErrors` | AWS-AccessBridge's `exceptionResponses.ts` |
|
|
43
|
+
| `/hono` | Each API worker's constructor stack, the seven `IBaseRoute.ts` copies, the `userAuthentication` middleware |
|
|
33
44
|
|
|
34
45
|
## The three decisions worth knowing
|
|
35
46
|
|
|
@@ -72,6 +83,129 @@ A surface with its own wire envelope (Subsonic, CalDAV) supplies `onThrottled`
|
|
|
72
83
|
and `toResponse`; everything else gets the canonical `{Exception:{Type,Message}}`
|
|
73
84
|
dialect every SPA in the family decodes.
|
|
74
85
|
|
|
86
|
+
## `@rexezuge/http/hono`: the app kernel
|
|
87
|
+
|
|
88
|
+
A complete API worker. The entrypoint extends `AbstractEntrypointWorker`; its
|
|
89
|
+
`onRequest` delegates to the app `createApiApp` built once in the constructor.
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import { AbstractEntrypointWorker, createLogger } from '@rexezuge/runtime';
|
|
93
|
+
import { isD1DailyLimitError, openSession, readBookmark, withBookmark } from '@rexezuge/d1';
|
|
94
|
+
import { errorResponses } from '@rexezuge/http';
|
|
95
|
+
import { accessAuth, apiKeyAuth, createApiApp, FamilyRoute } from '@rexezuge/http/hono';
|
|
96
|
+
import type { ApiApp, FamilyContext, RouteResult } from '@rexezuge/http/hono';
|
|
97
|
+
import { contentJson } from 'chanfana';
|
|
98
|
+
import type { ValidatedData } from 'chanfana';
|
|
99
|
+
import { z } from 'zod';
|
|
100
|
+
|
|
101
|
+
const RenameVolume = {
|
|
102
|
+
request: { params: z.object({ id: z.string() }), body: contentJson(z.object({ name: z.string().min(1) })) },
|
|
103
|
+
responses: { '200': { description: 'Renamed' }, ...errorResponses({ 400: 'Invalid name', 404: 'No such volume' }) },
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
class RenameVolumeRoute extends FamilyRoute<typeof RenameVolume, Env> {
|
|
107
|
+
public override schema = RenameVolume;
|
|
108
|
+
|
|
109
|
+
protected async handleRequest(input: ValidatedData<typeof RenameVolume>, c: FamilyContext<Env>): Promise<RouteResult<{ id: string }>> {
|
|
110
|
+
await new VolumeDAO(c.env.DB).rename(c.get('AuthenticatedUserId'), input.params.id, input.body.name);
|
|
111
|
+
return { id: input.params.id };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
class ApiWorker extends AbstractEntrypointWorker {
|
|
116
|
+
private readonly app: ApiApp<Env> = createApiApp<Env>({
|
|
117
|
+
logger: (env) => createLogger('api', 'Owner/Repo', env),
|
|
118
|
+
d1: { binding: 'DB', bookmarks: { openSession, readBookmark, withBookmark } },
|
|
119
|
+
errors: { dailyLimit: isD1DailyLimitError },
|
|
120
|
+
auth: {
|
|
121
|
+
'/user/*': accessAuth<Env>({
|
|
122
|
+
teamDomain: (env) => env.TEAM_DOMAIN,
|
|
123
|
+
policyAud: (env) => env.POLICY_AUD,
|
|
124
|
+
devBypass: (env) => ({ allowed: env.DEV_AUTH_EMAIL !== undefined, email: env.DEV_AUTH_EMAIL }),
|
|
125
|
+
resolveUserId: (email, c) => new UserIdentityService(deps(c.env)).resolveAccountId(email),
|
|
126
|
+
}),
|
|
127
|
+
'/api/*': apiKeyAuth<Env>({ verify: (c) => new PatService(c.env).principalFor(c.req.header('Authorization')) }),
|
|
128
|
+
},
|
|
129
|
+
rateLimits: [
|
|
130
|
+
{ path: '/api/*', keyPrefix: 'api', windowMs: 60_000, max: 120, key: 'ip', binding: (env) => env.API_RATE_LIMITER },
|
|
131
|
+
{ path: '/user/*', keyPrefix: 'user', windowMs: 60_000, max: 300 },
|
|
132
|
+
],
|
|
133
|
+
routes: (app) => {
|
|
134
|
+
app.put('/user/volumes/:id', RenameVolumeRoute);
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
protected onRequest(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
139
|
+
return Promise.resolve(this.app.fetch(request, env, ctx));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export default ApiWorker;
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### The fixed order (closed)
|
|
147
|
+
|
|
148
|
+
| # | Slot | Notes |
|
|
149
|
+
| --- | ----------------------- | ------------------------------------------------------------------------------------- |
|
|
150
|
+
| 1 | request id + logger | `X-Request-Id` on every response; `c.get('logger')` |
|
|
151
|
+
| 2 | security headers | wraps everything, so a 401/404/500 carries them; `/user/` and `/api/` `no-store` |
|
|
152
|
+
| 3 | CORS | only with `cors`; `X-Request-Id` always exposed |
|
|
153
|
+
| 4 | hardening | method allow-list (405), body ceiling (413), JSON mutations (415), origin guard (403) |
|
|
154
|
+
| 5 | D1 bookmarks | `env[binding]` becomes the session for the rest of the chain |
|
|
155
|
+
| 6 | `key: 'ip'` rate limits | before auth, so the auth step itself is throttled |
|
|
156
|
+
| 7 | `beforeAuth` hooks | yours |
|
|
157
|
+
| 8 | auth surfaces | `accessAuth` (Access, `email_verified` always enforced), `apiKeyAuth` (a port) |
|
|
158
|
+
| 9 | identity rate limits | keyed on the account; native `ratelimits` binding when configured |
|
|
159
|
+
| 10 | `afterAuth` hooks | yours: request scope, audit |
|
|
160
|
+
| 11 | `routes(app)` | yours |
|
|
161
|
+
|
|
162
|
+
Anything that throws — a route, a guard, a hook — reaches `app.onError`, which
|
|
163
|
+
maps it through the kit mapper to the `{Exception:{Type,Message}}` envelope: 4xx
|
|
164
|
+
messages kept, 5xx masked, zod/chanfana validation → 400, a retryable
|
|
165
|
+
`DatabaseError` → 503, a spent D1 allowance → 503 + `Retry-After`. The log line
|
|
166
|
+
is a static message with `type`, `status` and `requestId` — never the caught value.
|
|
167
|
+
An unmatched path is the `404 NotFound` envelope. `/docs` and `/openapi.json` are
|
|
168
|
+
served unless `docs: false`.
|
|
169
|
+
|
|
170
|
+
`FamilyVariables` is the typed context: `AuthenticatedUserEmailAddress`,
|
|
171
|
+
`AuthenticatedUserId`, `requestId`, `logger`. Add your own with the second type
|
|
172
|
+
parameter: `createApiApp<Env, { RequestScope: Scope }>()`.
|
|
173
|
+
|
|
174
|
+
### `FamilyRoute`
|
|
175
|
+
|
|
176
|
+
The converged chanfana route base. `handle()` is `@final`: it validates through
|
|
177
|
+
the route's own `schema` (`getValidatedData`), calls `handleRequest(input, c)`,
|
|
178
|
+
and shapes the result (a `Response` passes through, `null` is `204`, anything
|
|
179
|
+
else is JSON). A failure goes through the same mapper as `onError`. A subclass
|
|
180
|
+
that redeclares `handle` or `execute` is **refused at registration**
|
|
181
|
+
(`assertFinalMembers` from `@rexezuge/shared`): chanfana constructs each route
|
|
182
|
+
once when it is registered.
|
|
183
|
+
|
|
184
|
+
## Extending
|
|
185
|
+
|
|
186
|
+
| You want | Door |
|
|
187
|
+
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
|
188
|
+
| Your own routes | `routes(app)`, or register on the returned app; `FamilyRoute.handleRequest` |
|
|
189
|
+
| Middleware before / after authentication | `hooks.beforeAuth` / `hooks.afterAuth` (a handler, or `{ path, handler }`) |
|
|
190
|
+
| Another authenticated surface | `auth: { '/partner/*': apiKeyAuth({ verify }) }` |
|
|
191
|
+
| Your PAT / HMAC / path-key scheme | `apiKeyAuth({ verify })` — return a principal or `null`; throw a `ServiceError` for 403 |
|
|
192
|
+
| Map a verified address to your account | `accessAuth({ resolveUserId })` |
|
|
193
|
+
| Extra trusted origins (Pages, custom host) | `hardening.origin.allowedOrigins` (a list, or `(env) => list`) |
|
|
194
|
+
| Uploads | `hardening.contentType.allowed: ['application/json', 'multipart/form-data']`, `hardening.maxBodyBytes` |
|
|
195
|
+
| Your logger / redacting sink | `logger: (env, requestId) => createLogger(…, sink)` |
|
|
196
|
+
| A protocol dialect (Subsonic, WebDAV) | `errors.toResponse` app-wide, or `FamilyRoute.errorMapping()` per route |
|
|
197
|
+
| More context variables | the `V` type parameter |
|
|
198
|
+
|
|
199
|
+
Closed, with no flag: the slot order, the error envelope and its masking, log
|
|
200
|
+
redaction, `email_verified` enforcement, the origin guard on `/user/*`, the
|
|
201
|
+
`@final` route `handle()`.
|
|
202
|
+
|
|
203
|
+
## Renamed: `toErrorResponse` → `errorResponseFromUnknown`
|
|
204
|
+
|
|
205
|
+
The free function collided with `ServiceError#toErrorResponse()` in
|
|
206
|
+
`@rexezuge/errors`. `toErrorResponse` stays as a `@deprecated` alias and is removed
|
|
207
|
+
in 2.0; the kit codemod rewrites imports from `@rexezuge/http` (and only those).
|
|
208
|
+
|
|
75
209
|
## Test seams
|
|
76
210
|
|
|
77
211
|
The limiter's buckets are module-global. Suites reset and inspect them through the
|
package/dist/ErrorMapper.d.ts
CHANGED
|
@@ -30,8 +30,25 @@
|
|
|
30
30
|
* `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code
|
|
31
31
|
* for absence (Subsonic's `code=70`) supplies its own mapper; this one does not
|
|
32
32
|
* second-guess the taxonomy into something a client can misread.
|
|
33
|
+
*
|
|
34
|
+
* ## What else converged here
|
|
35
|
+
*
|
|
36
|
+
* Zod and chanfana validation failures (a 400 naming the first issue), raw `D1_`
|
|
37
|
+
* errors (a masked `DatabaseError`), a retryable `DatabaseError` (503) and a spent
|
|
38
|
+
* D1 daily allowance (503 + `Retry-After`, through the {@link DailyLimitDetector}
|
|
39
|
+
* port) — the union of Edge-Git, Edge-Sonic, Durable-DAV-Router and Mail-Meow's
|
|
40
|
+
* boundary mappers. See `errorClassification.ts`.
|
|
33
41
|
*/
|
|
34
42
|
import { ServiceError } from '@rexezuge/errors';
|
|
43
|
+
import type { Clock } from '@rexezuge/shared';
|
|
44
|
+
/**
|
|
45
|
+
* A D1 daily-allowance detector, structurally: `@rexezuge/d1`'s
|
|
46
|
+
* `isD1DailyLimitError` satisfies it. A port rather than an import because
|
|
47
|
+
* `http` may only depend on `errors` and `shared`.
|
|
48
|
+
*/
|
|
49
|
+
type DailyLimitDetector = (error: unknown) => {
|
|
50
|
+
readonly resetsAt: number;
|
|
51
|
+
} | null;
|
|
35
52
|
interface ErrorMapperOptions {
|
|
36
53
|
/**
|
|
37
54
|
* The HTTP status when the error carries none it should publish. Defaults to
|
|
@@ -46,15 +63,35 @@ interface ErrorMapperOptions {
|
|
|
46
63
|
Adds headers to the response (e.g. `Retry-After` on a 429).
|
|
47
64
|
*/
|
|
48
65
|
headers?(status: number, error: ServiceError): Record<string, string>;
|
|
66
|
+
/**
|
|
67
|
+
* Recognise a spent D1 daily allowance (pass `isD1DailyLimitError` from
|
|
68
|
+
* `@rexezuge/d1`). Such a failure answers `503 ServiceUnavailable` with a
|
|
69
|
+
* `Retry-After` until the reset, so a client does not retry straight into it.
|
|
70
|
+
*/
|
|
71
|
+
dailyLimit?: DailyLimitDetector;
|
|
72
|
+
/**
|
|
73
|
+
The clock `Retry-After` is computed against. Defaults to the system clock.
|
|
74
|
+
*/
|
|
75
|
+
clock?: Clock;
|
|
49
76
|
}
|
|
50
|
-
declare const INTERNAL_SERVER_MESSAGE = "The server encountered an internal error and was unable to complete your request.";
|
|
51
77
|
/**
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
78
|
+
What a caught value becomes on the wire, before any framework writes it.
|
|
79
|
+
*/
|
|
80
|
+
interface MappedError {
|
|
81
|
+
status: number;
|
|
82
|
+
body: {
|
|
83
|
+
Exception: {
|
|
84
|
+
Type: string;
|
|
85
|
+
Message: string;
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
headers: Record<string, string>;
|
|
89
|
+
/**
|
|
90
|
+
The taxonomy error the body was built from — for logging its `type`, never its message.
|
|
91
|
+
*/
|
|
92
|
+
error: ServiceError;
|
|
93
|
+
}
|
|
94
|
+
declare const INTERNAL_SERVER_MESSAGE = "The server encountered an internal error and was unable to complete your request.";
|
|
58
95
|
/**
|
|
59
96
|
* The canonical wire body.
|
|
60
97
|
*
|
|
@@ -68,14 +105,32 @@ declare function errorBody(error: ServiceError): {
|
|
|
68
105
|
Message: string;
|
|
69
106
|
};
|
|
70
107
|
};
|
|
108
|
+
/**
|
|
109
|
+
* Map a caught value to its status, envelope and headers, framework-free.
|
|
110
|
+
*
|
|
111
|
+
* The one decision table behind `errorResponseFromUnknown`, the `/hono`
|
|
112
|
+
* `onError` handler and `FamilyRoute`, so a failure answers identically
|
|
113
|
+
* whichever layer caught it.
|
|
114
|
+
*/
|
|
115
|
+
declare function mapError(error: unknown, options?: ErrorMapperOptions): MappedError;
|
|
71
116
|
/**
|
|
72
117
|
* Map a caught value to a `Response`.
|
|
73
118
|
*
|
|
74
119
|
* The `json`-shaped callback is injected rather than imported from Hono so this
|
|
75
120
|
* module stays free of the `Context` generic: a caller passes its own `c.json`,
|
|
76
121
|
* which is what makes it usable from a bare-`Request` dispatcher as well.
|
|
122
|
+
*
|
|
123
|
+
* Named for what it accepts: `ServiceError#toErrorResponse()` in
|
|
124
|
+
* `@rexezuge/errors` is a different function (a payload, not a `Response`).
|
|
125
|
+
*/
|
|
126
|
+
declare function errorResponseFromUnknown(error: unknown, json: (body: unknown, status: number, headers?: Record<string, string>) => Response, options?: ErrorMapperOptions): Response;
|
|
127
|
+
/**
|
|
128
|
+
* @deprecated Renamed to {@link errorResponseFromUnknown}: the old name collides
|
|
129
|
+
* with `ServiceError#toErrorResponse` in `@rexezuge/errors`. Removed in 2.0; the
|
|
130
|
+
* kit codemod rewrites imports from `@rexezuge/http`.
|
|
77
131
|
*/
|
|
78
|
-
declare
|
|
79
|
-
export { errorBody,
|
|
80
|
-
export
|
|
132
|
+
declare const toErrorResponse: typeof errorResponseFromUnknown;
|
|
133
|
+
export { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, INTERNAL_SERVER_MESSAGE };
|
|
134
|
+
export { toServiceError } from './errorClassification.ts';
|
|
135
|
+
export type { DailyLimitDetector, ErrorMapperOptions, MappedError };
|
|
81
136
|
//# sourceMappingURL=ErrorMapper.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ErrorMapper.d.ts","sourceRoot":"","sources":["../src/ErrorMapper.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"ErrorMapper.d.ts","sourceRoot":"","sources":["../src/ErrorMapper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,OAAO,EAAiB,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAE/D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAG9C;;;;GAIG;AACH,KAAK,kBAAkB,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC;AAEnF,UAAU,kBAAkB;IAC1B;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;MAEE;IACF,UAAU,CAAC,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC;IACvE;;MAEE;IACF,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtE;;;;OAIG;IACH,UAAU,CAAC,EAAE,kBAAkB,CAAC;IAChC;;MAEE;IACF,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAED;;EAEE;AACF,UAAU,WAAW;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE;QAAE,SAAS,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;IACvD,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC;;MAEE;IACF,KAAK,EAAE,YAAY,CAAC;CACrB;AAED,QAAA,MAAM,uBAAuB,sFAAsF,CAAC;AAEpH;;;;;;GAMG;AACH,iBAAS,SAAS,CAAC,KAAK,EAAE,YAAY,GAAG;IAAE,SAAS,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAOxF;AA2BD;;;;;;GAMG;AACH,iBAAS,QAAQ,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,GAAE,kBAAuB,GAAG,WAAW,CAO/E;AAED;;;;;;;;;GASG;AACH,iBAAS,wBAAwB,CAC/B,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,QAAQ,EACnF,OAAO,GAAE,kBAAuB,GAC/B,QAAQ,CAKV;AAED;;;;GAIG;AACH,QAAA,MAAM,eAAe,EAAE,OAAO,wBAAmD,CAAC;AAElF,OAAO,EAAE,SAAS,EAAE,wBAAwB,EAAE,QAAQ,EAAE,eAAe,EAAE,uBAAuB,EAAE,CAAC;AACnG,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,YAAY,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,CAAC"}
|
package/dist/ErrorMapper.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var o=(e,t)=>m(e,"name",{value:t,configurable:!0});import{DatabaseError as p}from"@rexezuge/errors";import{SYSTEM_CLOCK as y}from"@rexezuge/shared";import{catalogMessageFor as S,MappedServiceError as c,toServiceError as d}from"./errorClassification.js";const l="The server encountered an internal error and was unable to complete your request.";function u(e){return{Exception:{Type:e.type,Message:e.expose?e.message:l}}}o(u,"errorBody");function b(e,t,n){const r=n.dailyLimit?.(e)??null;if(r!==null){const a=(n.clock??y).now();return{error:new c(503,"ServiceUnavailable",S("ServiceUnavailable"),{cause:e,expose:!0}),retryAfter:Math.max(1,Math.ceil((r.resetsAt-a)/1e3))}}return t instanceof p&&t.retryable?{error:new c(503,"ServiceUnavailable",t.message,{cause:e}),retryAfter:null}:{error:t,retryAfter:null}}o(b,"refine");function i(e,t={}){const n=b(e,d(e),t),r=n.error,a=r.status||t.fallbackStatus||500,s={...t.headers?.(a,r)};return n.retryAfter!==null&&(s["Retry-After"]=String(n.retryAfter)),{status:a,body:u(r),headers:s,error:r}}o(i,"mapError");function f(e,t,n={}){const r=i(e,n),a=n.toResponse?.(r.error,r.status);return a||t(r.body,r.status,r.headers)}o(f,"errorResponseFromUnknown");const E=f;import{toServiceError as w}from"./errorClassification.js";export{l as INTERNAL_SERVER_MESSAGE,u as errorBody,f as errorResponseFromUnknown,i as mapError,E as toErrorResponse,w as toServiceError};
|
package/dist/ErrorMapper.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/ErrorMapper.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Error → response mapping at the HTTP boundary.\n *\n * Converged from `errors/ErrorMapper.ts` in Durable-DAV-Router, Edge-Git and\n * Edge-Sonic. Edge-Sonic's split is the one that survived, because it is the\n * only one that states **why** it splits: by surface, not by convenience.\n *\n * ## One surface, one dialect\n *\n * The `{Exception:{Type,Message}}` envelope is the family's established wire\n * format and the one the SPAs decode. A protocol surface with its own envelope —\n * Subsonic, WebDAV, CalDAV — must answer in *that* envelope, because a client\n * parsing that surface has no way to interpret anything else: a 401 carrying an\n * unrecognized body renders as \"server error\" and the client retries.\n *\n * So the split is by surface, and a caller declares which one it is on rather\n * than each handler deciding for itself. A surface that has its own dialect\n * supplies {@link ErrorMapperOptions.toResponse}; everything else gets the\n * canonical envelope.\n *\n * ## A 5xx never carries its own message\n *\n * `expose` in `@rexezuge/errors` already decides this, and this mapper is where\n * that decision becomes bytes. A D1 error names tables and columns; an upstream\n * body can carry a stack. The substitution lives here once rather than in every\n * boundary mapper.\n *\n * ## A 404 is a 404\n *\n * `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code\n * for absence (Subsonic's `code=70`) supplies its own mapper; this one does not\n * second-guess the taxonomy into something a client can misread.\n */\nimport { ServiceError } from '@rexezuge/errors';\n\ninterface ErrorMapperOptions {\n /**\n * The HTTP status when the error carries none it should publish. Defaults to\n * 500 — a non-`ServiceError` that reached the boundary is an unknown failure.\n */\n fallbackStatus?: number;\n /**\n A surface-specific dialect. Returns `undefined` to fall through to the default.\n */\n toResponse?(error: ServiceError, status: number): Response | undefined;\n /**\n Adds headers to the response (e.g. `Retry-After` on a 429).\n */\n headers?(status: number, error: ServiceError): Record<string, string>;\n
|
|
5
|
-
"mappings": "+
|
|
6
|
-
"names": ["
|
|
4
|
+
"sourcesContent": ["/**\n * Error → response mapping at the HTTP boundary.\n *\n * Converged from `errors/ErrorMapper.ts` in Durable-DAV-Router, Edge-Git and\n * Edge-Sonic. Edge-Sonic's split is the one that survived, because it is the\n * only one that states **why** it splits: by surface, not by convenience.\n *\n * ## One surface, one dialect\n *\n * The `{Exception:{Type,Message}}` envelope is the family's established wire\n * format and the one the SPAs decode. A protocol surface with its own envelope —\n * Subsonic, WebDAV, CalDAV — must answer in *that* envelope, because a client\n * parsing that surface has no way to interpret anything else: a 401 carrying an\n * unrecognized body renders as \"server error\" and the client retries.\n *\n * So the split is by surface, and a caller declares which one it is on rather\n * than each handler deciding for itself. A surface that has its own dialect\n * supplies {@link ErrorMapperOptions.toResponse}; everything else gets the\n * canonical envelope.\n *\n * ## A 5xx never carries its own message\n *\n * `expose` in `@rexezuge/errors` already decides this, and this mapper is where\n * that decision becomes bytes. A D1 error names tables and columns; an upstream\n * body can carry a stack. The substitution lives here once rather than in every\n * boundary mapper.\n *\n * ## A 404 is a 404\n *\n * `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code\n * for absence (Subsonic's `code=70`) supplies its own mapper; this one does not\n * second-guess the taxonomy into something a client can misread.\n *\n * ## What else converged here\n *\n * Zod and chanfana validation failures (a 400 naming the first issue), raw `D1_`\n * errors (a masked `DatabaseError`), a retryable `DatabaseError` (503) and a spent\n * D1 daily allowance (503 + `Retry-After`, through the {@link DailyLimitDetector}\n * port) — the union of Edge-Git, Edge-Sonic, Durable-DAV-Router and Mail-Meow's\n * boundary mappers. See `errorClassification.ts`.\n */\nimport { DatabaseError, ServiceError } from '@rexezuge/errors';\nimport { SYSTEM_CLOCK } from '@rexezuge/shared';\nimport type { Clock } from '@rexezuge/shared';\nimport { catalogMessageFor, MappedServiceError, toServiceError } from './errorClassification.ts';\n\n/**\n * A D1 daily-allowance detector, structurally: `@rexezuge/d1`'s\n * `isD1DailyLimitError` satisfies it. A port rather than an import because\n * `http` may only depend on `errors` and `shared`.\n */\ntype DailyLimitDetector = (error: unknown) => { readonly resetsAt: number } | null;\n\ninterface ErrorMapperOptions {\n /**\n * The HTTP status when the error carries none it should publish. Defaults to\n * 500 — a non-`ServiceError` that reached the boundary is an unknown failure.\n */\n fallbackStatus?: number;\n /**\n A surface-specific dialect. Returns `undefined` to fall through to the default.\n */\n toResponse?(error: ServiceError, status: number): Response | undefined;\n /**\n Adds headers to the response (e.g. `Retry-After` on a 429).\n */\n headers?(status: number, error: ServiceError): Record<string, string>;\n /**\n * Recognise a spent D1 daily allowance (pass `isD1DailyLimitError` from\n * `@rexezuge/d1`). Such a failure answers `503 ServiceUnavailable` with a\n * `Retry-After` until the reset, so a client does not retry straight into it.\n */\n dailyLimit?: DailyLimitDetector;\n /**\n The clock `Retry-After` is computed against. Defaults to the system clock.\n */\n clock?: Clock;\n}\n\n/**\nWhat a caught value becomes on the wire, before any framework writes it.\n*/\ninterface MappedError {\n status: number;\n body: { Exception: { Type: string; Message: string } };\n headers: Record<string, string>;\n /**\n The taxonomy error the body was built from — for logging its `type`, never its message.\n */\n error: ServiceError;\n}\n\nconst INTERNAL_SERVER_MESSAGE = 'The server encountered an internal error and was unable to complete your request.';\n\n/**\n * The canonical wire body.\n *\n * A 4xx keeps its message; a 5xx is masked. This is the `{Exception:{…}}`\n * envelope every SPA in the family decodes, and the one a surface with no\n * dialect of its own should answer in.\n */\nfunction errorBody(error: ServiceError): { Exception: { Type: string; Message: string } } {\n return {\n Exception: {\n Type: error.type,\n Message: error.expose ? error.message : INTERNAL_SERVER_MESSAGE,\n },\n };\n}\n\n/**\n * A transient D1 failure is a 503, not a 500: `retryable` already says a retry\n * is meaningful, and a 500 tells a client the opposite. A spent daily allowance\n * is a 503 with a known wait.\n */\nfunction refine(\n error: unknown,\n serviceError: ServiceError,\n options: ErrorMapperOptions,\n): { error: ServiceError; retryAfter: number | null } {\n const limit = options.dailyLimit?.(error) ?? null;\n if (limit !== null) {\n const now = (options.clock ?? SYSTEM_CLOCK).now();\n const unavailable = new MappedServiceError(503, 'ServiceUnavailable', catalogMessageFor('ServiceUnavailable'), {\n cause: error,\n expose: true,\n });\n return { error: unavailable, retryAfter: Math.max(1, Math.ceil((limit.resetsAt - now) / 1000)) };\n }\n if (serviceError instanceof DatabaseError && serviceError.retryable) {\n return { error: new MappedServiceError(503, 'ServiceUnavailable', serviceError.message, { cause: error }), retryAfter: null };\n }\n return { error: serviceError, retryAfter: null };\n}\n\n/**\n * Map a caught value to its status, envelope and headers, framework-free.\n *\n * The one decision table behind `errorResponseFromUnknown`, the `/hono`\n * `onError` handler and `FamilyRoute`, so a failure answers identically\n * whichever layer caught it.\n */\nfunction mapError(error: unknown, options: ErrorMapperOptions = {}): MappedError {\n const refined = refine(error, toServiceError(error), options);\n const serviceError = refined.error;\n const status = serviceError.status || options.fallbackStatus || 500;\n const headers = { ...options.headers?.(status, serviceError) };\n if (refined.retryAfter !== null) headers['Retry-After'] = String(refined.retryAfter);\n return { status, body: errorBody(serviceError), headers, error: serviceError };\n}\n\n/**\n * Map a caught value to a `Response`.\n *\n * The `json`-shaped callback is injected rather than imported from Hono so this\n * module stays free of the `Context` generic: a caller passes its own `c.json`,\n * which is what makes it usable from a bare-`Request` dispatcher as well.\n *\n * Named for what it accepts: `ServiceError#toErrorResponse()` in\n * `@rexezuge/errors` is a different function (a payload, not a `Response`).\n */\nfunction errorResponseFromUnknown(\n error: unknown,\n json: (body: unknown, status: number, headers?: Record<string, string>) => Response,\n options: ErrorMapperOptions = {},\n): Response {\n const mapped = mapError(error, options);\n const custom = options.toResponse?.(mapped.error, mapped.status);\n if (custom) return custom;\n return json(mapped.body, mapped.status, mapped.headers);\n}\n\n/**\n * @deprecated Renamed to {@link errorResponseFromUnknown}: the old name collides\n * with `ServiceError#toErrorResponse` in `@rexezuge/errors`. Removed in 2.0; the\n * kit codemod rewrites imports from `@rexezuge/http`.\n */\nconst toErrorResponse: typeof errorResponseFromUnknown = errorResponseFromUnknown;\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, INTERNAL_SERVER_MESSAGE };\nexport { toServiceError } from './errorClassification.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, MappedError };\n"],
|
|
5
|
+
"mappings": "+EAyCA,OAAS,iBAAAA,MAAmC,mBAC5C,OAAS,gBAAAC,MAAoB,mBAE7B,OAAS,qBAAAC,EAAmB,sBAAAC,EAAoB,kBAAAC,MAAsB,2BAgDtE,MAAMC,EAA0B,oFAShC,SAASC,EAAUC,EAAmB,CACpC,MAAO,CACL,UAAW,CACT,KAAMA,EAAM,KACZ,QAASA,EAAM,OAASA,EAAM,QAAUF,GAG9C,CAPSG,EAAAF,EAAA,aAcT,SAASG,EACPF,EACAG,EACAC,EAA2B,CAE3B,MAAMC,EAAQD,EAAQ,aAAaJ,CAAK,GAAK,KAC7C,GAAIK,IAAU,KAAM,CAClB,MAAMC,GAAOF,EAAQ,OAASV,GAAc,IAAG,EAK/C,MAAO,CAAE,MAJW,IAAIE,EAAmB,IAAK,qBAAsBD,EAAkB,oBAAoB,EAAG,CAC7G,MAAOK,EACP,OAAQ,GACT,EAC4B,WAAY,KAAK,IAAI,EAAG,KAAK,MAAMK,EAAM,SAAWC,GAAO,GAAI,CAAC,CAAC,CAChG,CACA,OAAIH,aAAwBV,GAAiBU,EAAa,UACjD,CAAE,MAAO,IAAIP,EAAmB,IAAK,qBAAsBO,EAAa,QAAS,CAAE,MAAOH,CAAK,CAAE,EAAG,WAAY,IAAI,EAEtH,CAAE,MAAOG,EAAc,WAAY,IAAI,CAChD,CAlBSF,EAAAC,EAAA,UA2BT,SAASK,EAASP,EAAgBI,EAA8B,CAAA,EAAE,CAChE,MAAMI,EAAUN,EAAOF,EAAOH,EAAeG,CAAK,EAAGI,CAAO,EACtDD,EAAeK,EAAQ,MACvBC,EAASN,EAAa,QAAUC,EAAQ,gBAAkB,IAC1DM,EAAU,CAAE,GAAGN,EAAQ,UAAUK,EAAQN,CAAY,CAAC,EAC5D,OAAIK,EAAQ,aAAe,OAAME,EAAQ,aAAa,EAAI,OAAOF,EAAQ,UAAU,GAC5E,CAAE,OAAAC,EAAQ,KAAMV,EAAUI,CAAY,EAAG,QAAAO,EAAS,MAAOP,CAAY,CAC9E,CAPSF,EAAAM,EAAA,YAmBT,SAASI,EACPX,EACAY,EACAR,EAA8B,CAAA,EAAE,CAEhC,MAAMS,EAASN,EAASP,EAAOI,CAAO,EAChCU,EAASV,EAAQ,aAAaS,EAAO,MAAOA,EAAO,MAAM,EAC/D,OAAIC,GACGF,EAAKC,EAAO,KAAMA,EAAO,OAAQA,EAAO,OAAO,CACxD,CATSZ,EAAAU,EAAA,4BAgBT,MAAMI,EAAmDJ,EAGzD,OAAS,kBAAAd,MAAsB",
|
|
6
|
+
"names": ["DatabaseError", "SYSTEM_CLOCK", "catalogMessageFor", "MappedServiceError", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorBody", "error", "__name", "refine", "serviceError", "options", "limit", "now", "mapError", "refined", "status", "headers", "errorResponseFromUnknown", "json", "mapped", "custom", "toErrorResponse"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recognise the thrown values a Hono/chanfana app produces that are not
|
|
3
|
+
* `ServiceError`s, and translate each into the taxonomy — structurally, so the
|
|
4
|
+
* framework-free barrel never imports `zod` or `chanfana`.
|
|
5
|
+
*
|
|
6
|
+
* Converged from the boundary mappers in Edge-Git, Edge-Sonic and
|
|
7
|
+
* Durable-DAV-Router (`backend-services/src/errors/ErrorMapper.ts`), Mail-Meow's
|
|
8
|
+
* `apps/api/src/errors/errorResponse.ts` and the `validateRequestInput` →
|
|
9
|
+
* `BadRequestError` step every `IBaseRoute` copy performs by hand. Each copy
|
|
10
|
+
* handled a different subset; the union is here:
|
|
11
|
+
*
|
|
12
|
+
* | Thrown value | Becomes |
|
|
13
|
+
* | ---------------------------------------------- | ---------------------------------------- |
|
|
14
|
+
* | `ServiceError` | itself |
|
|
15
|
+
* | `ZodError` (`name === 'ZodError'`, `issues[]`) | `400 BadRequest`, first issue named |
|
|
16
|
+
* | chanfana `ApiException` / `MultiException` | its status; a 400 names the first issue |
|
|
17
|
+
* | Hono `HTTPException` (`status`, `getResponse`) | its status, catalog type |
|
|
18
|
+
* | an `Error` whose message starts `D1_` | `500 DatabaseError`, masked |
|
|
19
|
+
* | anything else | `500 InternalError`, masked |
|
|
20
|
+
*/
|
|
21
|
+
import { ServiceError } from '@rexezuge/errors';
|
|
22
|
+
/**
|
|
23
|
+
A catalog-typed error built from a status the caller already decided.
|
|
24
|
+
*/
|
|
25
|
+
declare class MappedServiceError extends ServiceError {
|
|
26
|
+
constructor(status: number, type: string, message: string, options?: {
|
|
27
|
+
cause?: unknown;
|
|
28
|
+
expose?: boolean;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
The catalog name for a status, or `InternalServerError` for one it does not list.
|
|
33
|
+
*/
|
|
34
|
+
declare function catalogTypeFor(status: number): string;
|
|
35
|
+
declare function catalogMessageFor(type: string): string;
|
|
36
|
+
/**
|
|
37
|
+
* Normalize an unknown catch value into the taxonomy.
|
|
38
|
+
*
|
|
39
|
+
* Re-wrapping a `ServiceError` would bury its context, so it passes through
|
|
40
|
+
* untouched and the caller can rely on `instanceof` downstream.
|
|
41
|
+
*/
|
|
42
|
+
declare function toServiceError(error: unknown): ServiceError;
|
|
43
|
+
export { catalogMessageFor, catalogTypeFor, MappedServiceError, toServiceError };
|
|
44
|
+
//# sourceMappingURL=errorClassification.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errorClassification.d.ts","sourceRoot":"","sources":["../src/errorClassification.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAW,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEzD;;EAEE;AACF,cAAM,kBAAmB,SAAQ,YAAY;gBACxB,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAC;QAAC,MAAM,CAAC,EAAE,OAAO,CAAA;KAAE;CAGlH;AAOD;;EAEE;AACF,iBAAS,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAK9C;AAED,iBAAS,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAI/C;AAkCD;;;;;GAKG;AACH,iBAAS,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,CA4BpD;AAED,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,kBAAkB,EAAE,cAAc,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var p=Object.defineProperty;var a=(s,e)=>p(s,"name",{value:e,configurable:!0});import{CATALOG as c,ServiceError as o}from"@rexezuge/errors";class i extends o{static{a(this,"MappedServiceError")}constructor(e,t,n,u){super(e,t,n,u)}}function f(s){for(const[e,t]of Object.entries(c))if(t.status===s)return e;return s<500?"BadRequest":"InternalServerError"}a(f,"catalogTypeFor");function r(s){return c[s]?.defaultMessage??c.InternalServerError.defaultMessage}a(r,"catalogMessageFor");function l(s){if(!s)return"Invalid request.";const e=Array.isArray(s.path)&&s.path.length>0?`${s.path.map(String).join(".")}: `:"",t=typeof s.message=="string"&&s.message!==""?s.message:"Invalid value";return`Invalid request: ${e}${t}`}a(l,"describeIssue");function g(s){if(!(s instanceof Error)||s.name!=="ZodError")return null;const e=s.issues;return Array.isArray(e)?e:null}a(g,"zodIssues");function m(s){if(!(s instanceof Error))return null;const e=s;if(typeof e.buildResponse!="function"||typeof e.status!="number")return null;const t=Array.isArray(e.errors)?e.errors:[],n=t.length>0?t:[{path:e.path,message:s.message}];return{status:e.status,visible:e.isVisible!==!1,issues:n,message:s.message}}a(m,"chanfanaException");function d(s){if(s instanceof o)return s;const e=g(s);if(e!==null)return new i(400,"BadRequest",l(e[0]),{cause:s});const t=m(s);if(t!==null){const n=f(t.status),u=t.status===400?l(t.issues[0]):t.message||r(n);return new i(t.status,n,t.visible?u:r(n),{cause:s})}if(s instanceof Error&&typeof s.getResponse=="function"){const n=s.status;if(typeof n=="number"&&n>=400&&n<600){const u=f(n);return new i(n,u,s.message||r(u),{cause:s})}}return s instanceof Error&&s.message.startsWith("D1_")?new i(500,"DatabaseError",s.message,{cause:s}):o.from(s)}a(d,"toServiceError");export{i as MappedServiceError,r as catalogMessageFor,f as catalogTypeFor,d as toServiceError};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/errorClassification.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Recognise the thrown values a Hono/chanfana app produces that are not\n * `ServiceError`s, and translate each into the taxonomy — structurally, so the\n * framework-free barrel never imports `zod` or `chanfana`.\n *\n * Converged from the boundary mappers in Edge-Git, Edge-Sonic and\n * Durable-DAV-Router (`backend-services/src/errors/ErrorMapper.ts`), Mail-Meow's\n * `apps/api/src/errors/errorResponse.ts` and the `validateRequestInput` →\n * `BadRequestError` step every `IBaseRoute` copy performs by hand. Each copy\n * handled a different subset; the union is here:\n *\n * | Thrown value | Becomes |\n * | ---------------------------------------------- | ---------------------------------------- |\n * | `ServiceError` | itself |\n * | `ZodError` (`name === 'ZodError'`, `issues[]`) | `400 BadRequest`, first issue named |\n * | chanfana `ApiException` / `MultiException` | its status; a 400 names the first issue |\n * | Hono `HTTPException` (`status`, `getResponse`) | its status, catalog type |\n * | an `Error` whose message starts `D1_` | `500 DatabaseError`, masked |\n * | anything else | `500 InternalError`, masked |\n */\nimport { CATALOG, ServiceError } from '@rexezuge/errors';\n\n/**\nA catalog-typed error built from a status the caller already decided.\n*/\nclass MappedServiceError extends ServiceError {\n public constructor(status: number, type: string, message: string, options?: { cause?: unknown; expose?: boolean }) {\n super(status, type, message, options);\n }\n}\n\ninterface ValidationIssueLike {\n path?: readonly (string | number)[] | null;\n message?: string;\n}\n\n/**\nThe catalog name for a status, or `InternalServerError` for one it does not list.\n*/\nfunction catalogTypeFor(status: number): string {\n for (const [type, definition] of Object.entries(CATALOG)) {\n if (definition.status === status) return type;\n }\n return status < 500 ? 'BadRequest' : 'InternalServerError';\n}\n\nfunction catalogMessageFor(type: string): string {\n return (\n (CATALOG as Record<string, { defaultMessage: string } | undefined>)[type]?.defaultMessage ?? CATALOG.InternalServerError.defaultMessage\n );\n}\n\n/**\n * `Invalid request: body.name: Required`. The first issue only: a list of every\n * failure is a diagnostics dump, and the SPA renders one sentence.\n */\nfunction describeIssue(issue: ValidationIssueLike | undefined): string {\n if (!issue) return 'Invalid request.';\n const path = Array.isArray(issue.path) && issue.path.length > 0 ? `${issue.path.map(String).join('.')}: ` : '';\n const message = typeof issue.message === 'string' && issue.message !== '' ? issue.message : 'Invalid value';\n return `Invalid request: ${path}${message}`;\n}\n\nfunction zodIssues(error: unknown): readonly ValidationIssueLike[] | null {\n if (!(error instanceof Error) || error.name !== 'ZodError') return null;\n const issues = (error as unknown as { issues?: unknown }).issues;\n return Array.isArray(issues) ? (issues as ValidationIssueLike[]) : null;\n}\n\n/**\n * chanfana's exception family: an `Error` with a numeric `status` and a\n * `buildResponse()` method. `MultiException` carries `errors[]`.\n */\nfunction chanfanaException(\n error: unknown,\n): { status: number; visible: boolean; issues: readonly ValidationIssueLike[]; message: string } | null {\n if (!(error instanceof Error)) return null;\n const candidate = error as unknown as Record<string, unknown>;\n if (typeof candidate['buildResponse'] !== 'function' || typeof candidate['status'] !== 'number') return null;\n const nested = Array.isArray(candidate['errors']) ? (candidate['errors'] as ValidationIssueLike[]) : [];\n const issues = nested.length > 0 ? nested : [{ path: candidate['path'] as ValidationIssueLike['path'], message: error.message }];\n return { status: candidate['status'], visible: candidate['isVisible'] !== false, issues, message: error.message };\n}\n\n/**\n * Normalize an unknown catch value into the taxonomy.\n *\n * Re-wrapping a `ServiceError` would bury its context, so it passes through\n * untouched and the caller can rely on `instanceof` downstream.\n */\nfunction toServiceError(error: unknown): ServiceError {\n if (error instanceof ServiceError) return error;\n\n const issues = zodIssues(error);\n if (issues !== null) return new MappedServiceError(400, 'BadRequest', describeIssue(issues[0]), { cause: error });\n\n const chanfana = chanfanaException(error);\n if (chanfana !== null) {\n const type = catalogTypeFor(chanfana.status);\n const message = chanfana.status === 400 ? describeIssue(chanfana.issues[0]) : chanfana.message || catalogMessageFor(type);\n return new MappedServiceError(chanfana.status, type, chanfana.visible ? message : catalogMessageFor(type), { cause: error });\n }\n\n if (error instanceof Error && typeof (error as unknown as Record<string, unknown>)['getResponse'] === 'function') {\n const status = (error as unknown as { status?: unknown }).status;\n if (typeof status === 'number' && status >= 400 && status < 600) {\n const type = catalogTypeFor(status);\n return new MappedServiceError(status, type, error.message || catalogMessageFor(type), { cause: error });\n }\n }\n\n // A raw D1 failure that never went through a DAO's retry wrapper. Its message\n // names tables and columns, so it is typed (operators can find it) and masked.\n if (error instanceof Error && error.message.startsWith('D1_')) {\n return new MappedServiceError(500, 'DatabaseError', error.message, { cause: error });\n }\n\n return ServiceError.from(error);\n}\n\nexport { catalogMessageFor, catalogTypeFor, MappedServiceError, toServiceError };\n"],
|
|
5
|
+
"mappings": "+EAoBA,OAAS,WAAAA,EAAS,gBAAAC,MAAoB,mBAKtC,MAAMC,UAA2BD,CAAY,CAzB7C,MAyB6C,CAAAE,EAAA,2BAC3C,YAAmBC,EAAgBC,EAAcC,EAAiBC,EAA+C,CAC/G,MAAMH,EAAQC,EAAMC,EAASC,CAAO,CACtC,EAWF,SAASC,EAAeJ,EAAc,CACpC,SAAW,CAACC,EAAMI,CAAU,IAAK,OAAO,QAAQT,CAAO,EACrD,GAAIS,EAAW,SAAWL,EAAQ,OAAOC,EAE3C,OAAOD,EAAS,IAAM,aAAe,qBACvC,CALSD,EAAAK,EAAA,kBAOT,SAASE,EAAkBL,EAAY,CACrC,OACGL,EAAmEK,CAAI,GAAG,gBAAkBL,EAAQ,oBAAoB,cAE7H,CAJSG,EAAAO,EAAA,qBAUT,SAASC,EAAcC,EAAsC,CAC3D,GAAI,CAACA,EAAO,MAAO,mBACnB,MAAMC,EAAO,MAAM,QAAQD,EAAM,IAAI,GAAKA,EAAM,KAAK,OAAS,EAAI,GAAGA,EAAM,KAAK,IAAI,MAAM,EAAE,KAAK,GAAG,CAAC,KAAO,GACtGN,EAAU,OAAOM,EAAM,SAAY,UAAYA,EAAM,UAAY,GAAKA,EAAM,QAAU,gBAC5F,MAAO,oBAAoBC,CAAI,GAAGP,CAAO,EAC3C,CALSH,EAAAQ,EAAA,iBAOT,SAASG,EAAUC,EAAc,CAC/B,GAAI,EAAEA,aAAiB,QAAUA,EAAM,OAAS,WAAY,OAAO,KACnE,MAAMC,EAAUD,EAA0C,OAC1D,OAAO,MAAM,QAAQC,CAAM,EAAKA,EAAmC,IACrE,CAJSb,EAAAW,EAAA,aAUT,SAASG,EACPF,EAAc,CAEd,GAAI,EAAEA,aAAiB,OAAQ,OAAO,KACtC,MAAMG,EAAYH,EAClB,GAAI,OAAOG,EAAU,eAAqB,YAAc,OAAOA,EAAU,QAAc,SAAU,OAAO,KACxG,MAAMC,EAAS,MAAM,QAAQD,EAAU,MAAS,EAAKA,EAAU,OAAsC,CAAA,EAC/FF,EAASG,EAAO,OAAS,EAAIA,EAAS,CAAC,CAAE,KAAMD,EAAU,KAAwC,QAASH,EAAM,OAAO,CAAE,EAC/H,MAAO,CAAE,OAAQG,EAAU,OAAW,QAASA,EAAU,YAAiB,GAAO,OAAAF,EAAQ,QAASD,EAAM,OAAO,CACjH,CATSZ,EAAAc,EAAA,qBAiBT,SAASG,EAAeL,EAAc,CACpC,GAAIA,aAAiBd,EAAc,OAAOc,EAE1C,MAAMC,EAASF,EAAUC,CAAK,EAC9B,GAAIC,IAAW,KAAM,OAAO,IAAId,EAAmB,IAAK,aAAcS,EAAcK,EAAO,CAAC,CAAC,EAAG,CAAE,MAAOD,CAAK,CAAE,EAEhH,MAAMM,EAAWJ,EAAkBF,CAAK,EACxC,GAAIM,IAAa,KAAM,CACrB,MAAMhB,EAAOG,EAAea,EAAS,MAAM,EACrCf,EAAUe,EAAS,SAAW,IAAMV,EAAcU,EAAS,OAAO,CAAC,CAAC,EAAIA,EAAS,SAAWX,EAAkBL,CAAI,EACxH,OAAO,IAAIH,EAAmBmB,EAAS,OAAQhB,EAAMgB,EAAS,QAAUf,EAAUI,EAAkBL,CAAI,EAAG,CAAE,MAAOU,CAAK,CAAE,CAC7H,CAEA,GAAIA,aAAiB,OAAS,OAAQA,EAA6C,aAAmB,WAAY,CAChH,MAAMX,EAAUW,EAA0C,OAC1D,GAAI,OAAOX,GAAW,UAAYA,GAAU,KAAOA,EAAS,IAAK,CAC/D,MAAMC,EAAOG,EAAeJ,CAAM,EAClC,OAAO,IAAIF,EAAmBE,EAAQC,EAAMU,EAAM,SAAWL,EAAkBL,CAAI,EAAG,CAAE,MAAOU,CAAK,CAAE,CACxG,CACF,CAIA,OAAIA,aAAiB,OAASA,EAAM,QAAQ,WAAW,KAAK,EACnD,IAAIb,EAAmB,IAAK,gBAAiBa,EAAM,QAAS,CAAE,MAAOA,CAAK,CAAE,EAG9Ed,EAAa,KAAKc,CAAK,CAChC,CA5BSZ,EAAAiB,EAAA",
|
|
6
|
+
"names": ["CATALOG", "ServiceError", "MappedServiceError", "__name", "status", "type", "message", "options", "catalogTypeFor", "definition", "catalogMessageFor", "describeIssue", "issue", "path", "zodIssues", "error", "issues", "chanfanaException", "candidate", "nested", "toServiceError", "chanfana"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The converged chanfana route base.
|
|
3
|
+
*
|
|
4
|
+
* Converged from the seven `apps/api/src/endpoints/IBaseRoute.ts` copies
|
|
5
|
+
* (ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Bee,
|
|
6
|
+
* Mail-Meow, Mail-Otter), and the answer to the "unconverged" note in
|
|
7
|
+
* `../routeBase.ts`. Every copy did the same four things by hand and each got a
|
|
8
|
+
* different one wrong:
|
|
9
|
+
*
|
|
10
|
+
* 1. **Parse and validate.** The Mail-* copies parsed the body themselves and
|
|
11
|
+
* validated against a path-keyed registry (`validateRequestInput`) that failed
|
|
12
|
+
* *open* for a route nobody registered. Here the route's own chanfana `schema`
|
|
13
|
+
* validates — the same object that documents it — so there is no second
|
|
14
|
+
* registry to forget.
|
|
15
|
+
* 2. **Run the handler** — the only open step: {@link FamilyRoute.handleRequest}.
|
|
16
|
+
* 3. **Shape the response.** A `Response` passes through; a value is JSON; `null`
|
|
17
|
+
* is `204`.
|
|
18
|
+
* 4. **Map the failure** through the kit mapper (`respondWithError`), never a
|
|
19
|
+
* hand-built envelope: two copies shipped a 5xx's raw message.
|
|
20
|
+
*
|
|
21
|
+
* Steps 1, 3 and 4 are closed. `handle` and chanfana's `execute` are `@final`
|
|
22
|
+
* and **refused at construction** (`assertFinalMembers`) — chanfana constructs a
|
|
23
|
+
* route once at registration, so an override fails the app at startup.
|
|
24
|
+
*/
|
|
25
|
+
import { OpenAPIRoute } from 'chanfana';
|
|
26
|
+
import type { OpenAPIRouteSchema, RouteOptions, ValidatedData } from 'chanfana';
|
|
27
|
+
import type { Context } from 'hono';
|
|
28
|
+
import type { ErrorMapperOptions } from '../ErrorMapper.ts';
|
|
29
|
+
import type { FamilyEnv } from './types.ts';
|
|
30
|
+
/**
|
|
31
|
+
* Open: what the route returns. A `Response` is sent as-is (redirects, streams,
|
|
32
|
+
* a non-JSON body); `null` is `204 No Content`; anything else is JSON with 200.
|
|
33
|
+
*/
|
|
34
|
+
type RouteResult<T> = T | Response | null;
|
|
35
|
+
declare abstract class FamilyRoute<S extends OpenAPIRouteSchema = OpenAPIRouteSchema, E extends object = object, V extends object = object, TOutput = unknown> extends OpenAPIRoute<[Context<FamilyEnv<E, V>>]> {
|
|
36
|
+
constructor(params: RouteOptions);
|
|
37
|
+
/**
|
|
38
|
+
* @final Validate → `handleRequest` → shape, with every failure mapped to the
|
|
39
|
+
* family envelope. Extend through {@link handleRequest} and {@link errorMapping}.
|
|
40
|
+
*/
|
|
41
|
+
handle(c: Context<FamilyEnv<E, V>>): Promise<Response>;
|
|
42
|
+
/**
|
|
43
|
+
* The route's domain work. `input` is chanfana's validated `{ params, query,
|
|
44
|
+
* headers, body }` for this route's `schema`; `c` is the typed family context
|
|
45
|
+
* (bindings, `AuthenticatedUserId`, `logger`, …).
|
|
46
|
+
*/
|
|
47
|
+
protected abstract handleRequest(input: ValidatedData<S>, c: Context<FamilyEnv<E, V>>): Promise<RouteResult<TOutput>>;
|
|
48
|
+
/**
|
|
49
|
+
* Open: per-route mapper options, merged over the app's. The hook for a
|
|
50
|
+
* protocol surface with its own dialect (`toResponse`) or extra headers.
|
|
51
|
+
*/
|
|
52
|
+
protected errorMapping(): ErrorMapperOptions;
|
|
53
|
+
}
|
|
54
|
+
export { FamilyRoute };
|
|
55
|
+
export type { RouteResult };
|
|
56
|
+
//# sourceMappingURL=FamilyRoute.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FamilyRoute.d.ts","sourceRoot":"","sources":["../../src/hono/FamilyRoute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAChF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C;;;GAGG;AACH,KAAK,WAAW,CAAC,CAAC,IAAI,CAAC,GAAG,QAAQ,GAAG,IAAI,CAAC;AAE1C,uBAAe,WAAW,CACxB,CAAC,SAAS,kBAAkB,GAAG,kBAAkB,EACjD,CAAC,SAAS,MAAM,GAAG,MAAM,EACzB,CAAC,SAAS,MAAM,GAAG,MAAM,EACzB,OAAO,GAAG,OAAO,CACjB,SAAQ,YAAY,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC7B,MAAM,EAAE,YAAY;IAKvC;;;OAGG;IACU,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC;IAanE;;;;OAIG;IACH,SAAS,CAAC,QAAQ,CAAC,aAAa,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAErH;;;OAGG;IACH,SAAS,CAAC,YAAY,IAAI,kBAAkB;CAG7C;AAED,OAAO,EAAE,WAAW,EAAE,CAAC;AACvB,YAAY,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var o=(s,r)=>a(s,"name",{value:r,configurable:!0});import{OpenAPIRoute as i}from"chanfana";import{assertFinalMembers as p}from"@rexezuge/shared";import{respondWithError as u}from"./errorHandler.js";class n extends i{static{o(this,"FamilyRoute")}constructor(r){super(r),p(this,n,["handle","execute"])}async handle(r){try{const e=await this.getValidatedData(),t=await this.handleRequest(e,r);return t instanceof Response?t:t===null?r.body(null,204):r.json(t)}catch(e){const t=r.get("errorMapperOptions");return u(r,e,{...t,...this.errorMapping()})}}errorMapping(){return{}}}export{n as FamilyRoute};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hono/FamilyRoute.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * The converged chanfana route base.\n *\n * Converged from the seven `apps/api/src/endpoints/IBaseRoute.ts` copies\n * (ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Bee,\n * Mail-Meow, Mail-Otter), and the answer to the \"unconverged\" note in\n * `../routeBase.ts`. Every copy did the same four things by hand and each got a\n * different one wrong:\n *\n * 1. **Parse and validate.** The Mail-* copies parsed the body themselves and\n * validated against a path-keyed registry (`validateRequestInput`) that failed\n * *open* for a route nobody registered. Here the route's own chanfana `schema`\n * validates — the same object that documents it — so there is no second\n * registry to forget.\n * 2. **Run the handler** — the only open step: {@link FamilyRoute.handleRequest}.\n * 3. **Shape the response.** A `Response` passes through; a value is JSON; `null`\n * is `204`.\n * 4. **Map the failure** through the kit mapper (`respondWithError`), never a\n * hand-built envelope: two copies shipped a 5xx's raw message.\n *\n * Steps 1, 3 and 4 are closed. `handle` and chanfana's `execute` are `@final`\n * and **refused at construction** (`assertFinalMembers`) — chanfana constructs a\n * route once at registration, so an override fails the app at startup.\n */\nimport { OpenAPIRoute } from 'chanfana';\nimport type { OpenAPIRouteSchema, RouteOptions, ValidatedData } from 'chanfana';\nimport type { Context } from 'hono';\nimport { assertFinalMembers } from '@rexezuge/shared';\nimport type { ErrorMapperOptions } from '../ErrorMapper.ts';\nimport { respondWithError } from './errorHandler.ts';\nimport type { FamilyEnv } from './types.ts';\n\n/**\n * Open: what the route returns. A `Response` is sent as-is (redirects, streams,\n * a non-JSON body); `null` is `204 No Content`; anything else is JSON with 200.\n */\ntype RouteResult<T> = T | Response | null;\n\nabstract class FamilyRoute<\n S extends OpenAPIRouteSchema = OpenAPIRouteSchema,\n E extends object = object,\n V extends object = object,\n TOutput = unknown,\n> extends OpenAPIRoute<[Context<FamilyEnv<E, V>>]> {\n public constructor(params: RouteOptions) {\n super(params);\n assertFinalMembers(this, FamilyRoute, ['handle', 'execute']);\n }\n\n /**\n * @final Validate → `handleRequest` → shape, with every failure mapped to the\n * family envelope. Extend through {@link handleRequest} and {@link errorMapping}.\n */\n public async handle(c: Context<FamilyEnv<E, V>>): Promise<Response> {\n try {\n const input = await this.getValidatedData<S>();\n const result = await this.handleRequest(input, c);\n if (result instanceof Response) return result;\n if (result === null) return c.body(null, 204);\n return c.json(result as object);\n } catch (error: unknown) {\n const appOptions = c.get('errorMapperOptions' as never) as ErrorMapperOptions | undefined;\n return respondWithError(c, error, { ...appOptions, ...this.errorMapping() });\n }\n }\n\n /**\n * The route's domain work. `input` is chanfana's validated `{ params, query,\n * headers, body }` for this route's `schema`; `c` is the typed family context\n * (bindings, `AuthenticatedUserId`, `logger`, …).\n */\n protected abstract handleRequest(input: ValidatedData<S>, c: Context<FamilyEnv<E, V>>): Promise<RouteResult<TOutput>>;\n\n /**\n * Open: per-route mapper options, merged over the app's. The hook for a\n * protocol surface with its own dialect (`toResponse`) or extra headers.\n */\n protected errorMapping(): ErrorMapperOptions {\n return {};\n }\n}\n\nexport { FamilyRoute };\nexport type { RouteResult };\n"],
|
|
5
|
+
"mappings": "+EAwBA,OAAS,gBAAAA,MAAoB,WAG7B,OAAS,sBAAAC,MAA0B,mBAEnC,OAAS,oBAAAC,MAAwB,oBASjC,MAAeC,UAKLH,CAAwC,CA3ClD,MA2CkD,CAAAI,EAAA,oBAChD,YAAmBC,EAAoB,CACrC,MAAMA,CAAM,EACZJ,EAAmB,KAAME,EAAa,CAAC,SAAU,SAAS,CAAC,CAC7D,CAMO,MAAM,OAAOG,EAA2B,CAC7C,GAAI,CACF,MAAMC,EAAQ,MAAM,KAAK,iBAAgB,EACnCC,EAAS,MAAM,KAAK,cAAcD,EAAOD,CAAC,EAChD,OAAIE,aAAkB,SAAiBA,EACnCA,IAAW,KAAaF,EAAE,KAAK,KAAM,GAAG,EACrCA,EAAE,KAAKE,CAAgB,CAChC,OAASC,EAAgB,CACvB,MAAMC,EAAaJ,EAAE,IAAI,oBAA6B,EACtD,OAAOJ,EAAiBI,EAAGG,EAAO,CAAE,GAAGC,EAAY,GAAG,KAAK,aAAY,CAAE,CAAE,CAC7E,CACF,CAaU,cAAY,CACpB,MAAO,CAAA,CACT",
|
|
6
|
+
"names": ["OpenAPIRoute", "assertFinalMembers", "respondWithError", "FamilyRoute", "__name", "params", "c", "input", "result", "error", "appOptions"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two authenticated surfaces, as Hono middleware.
|
|
3
|
+
*
|
|
4
|
+
* - `accessAuth` for `/user/*`: Cloudflare Access, through the kit's
|
|
5
|
+
* `authenticateAccess` — resolution order, the single 401 message and the
|
|
6
|
+
* `email_verified` refusal are the kit's and not options. Replaces the
|
|
7
|
+
* `MiddlewareHandlers.userAuthentication()` copies (Mail-Bee, Mail-Meow,
|
|
8
|
+
* Mail-Otter, Durable-DAV, Edge-Git, Image-Host, AWS-AccessBridge).
|
|
9
|
+
* - `apiKeyAuth` for `/api/*`: PATs, HMAC signatures and path keys are
|
|
10
|
+
* app-specific, so verification is a **port**. The kit owns what happens
|
|
11
|
+
* around it: an absent principal is a 401, and the principal lands on the
|
|
12
|
+
* same two variables `accessAuth` sets, so downstream code (and the
|
|
13
|
+
* identity-keyed rate limiter) never asks which surface it is on.
|
|
14
|
+
*
|
|
15
|
+
* Both **throw** on failure, so the rejection leaves through `app.onError` in
|
|
16
|
+
* the family envelope with the security headers and request id attached.
|
|
17
|
+
*/
|
|
18
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
19
|
+
import type { AccessBinding, AccessJwtVerifier } from '../accessAuth.ts';
|
|
20
|
+
import type { FamilyEnv, FromEnv } from './types.ts';
|
|
21
|
+
/**
|
|
22
|
+
* The account an address resolved to. A bare string is the id; an object may
|
|
23
|
+
* also carry the account's **current** address, which wins over the sign-in one
|
|
24
|
+
* (identity convergence: an account outlives the address it was created with).
|
|
25
|
+
*/
|
|
26
|
+
type ResolvedUser = string | {
|
|
27
|
+
id: string;
|
|
28
|
+
email?: string;
|
|
29
|
+
};
|
|
30
|
+
interface AccessAuthMiddlewareOptions<E extends object, V extends object> {
|
|
31
|
+
/**
|
|
32
|
+
`https://<team>.cloudflareaccess.com`. Usually `(env) => env.TEAM_DOMAIN`.
|
|
33
|
+
*/
|
|
34
|
+
teamDomain: FromEnv<E, string | undefined>;
|
|
35
|
+
/**
|
|
36
|
+
The Access application's audience tag. Usually `(env) => env.POLICY_AUD`.
|
|
37
|
+
*/
|
|
38
|
+
policyAud: FromEnv<E, string | undefined>;
|
|
39
|
+
/**
|
|
40
|
+
The `ACCESS` binding. Defaults to `env.ACCESS`; its absence is a 401, never an open door.
|
|
41
|
+
*/
|
|
42
|
+
binding?: (env: E) => AccessBinding | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* The development bypass. `allowed` is an **allow-list** decision (derive it
|
|
45
|
+
* from an explicit var, never from `environment !== 'production'`); it also
|
|
46
|
+
* gates `demo`.
|
|
47
|
+
*/
|
|
48
|
+
devBypass?: FromEnv<E, {
|
|
49
|
+
allowed: boolean;
|
|
50
|
+
email?: string;
|
|
51
|
+
}>;
|
|
52
|
+
/**
|
|
53
|
+
The demo user, honoured only while `devBypass.allowed`.
|
|
54
|
+
*/
|
|
55
|
+
demo?: FromEnv<E, {
|
|
56
|
+
enabled: boolean;
|
|
57
|
+
email?: string;
|
|
58
|
+
}>;
|
|
59
|
+
/**
|
|
60
|
+
Map the verified address to the account (`UserIdentityService.resolveAccountId`, an upsert, …).
|
|
61
|
+
*/
|
|
62
|
+
resolveUserId(email: string, c: Context<FamilyEnv<E, V>>): Promise<ResolvedUser>;
|
|
63
|
+
/**
|
|
64
|
+
JWT verification seam for tests. The default (`jose`) refuses `email_verified: false`.
|
|
65
|
+
*/
|
|
66
|
+
verifier?: AccessJwtVerifier;
|
|
67
|
+
}
|
|
68
|
+
declare function accessAuth<E extends object, V extends object = object>(options: AccessAuthMiddlewareOptions<E, V>): MiddlewareHandler<FamilyEnv<E, V>>;
|
|
69
|
+
/**
|
|
70
|
+
What an API credential authenticates as.
|
|
71
|
+
*/
|
|
72
|
+
interface ApiPrincipal {
|
|
73
|
+
userId: string;
|
|
74
|
+
email: string;
|
|
75
|
+
}
|
|
76
|
+
interface ApiKeyAuthOptions<E extends object, V extends object> {
|
|
77
|
+
/**
|
|
78
|
+
* Verify the request's credential (PAT header, HMAC signature, path key).
|
|
79
|
+
* `null` means "no valid credential" and answers 401; a thrown `ServiceError`
|
|
80
|
+
* (403, 429) answers itself.
|
|
81
|
+
*/
|
|
82
|
+
verify(c: Context<FamilyEnv<E, V>>): Promise<ApiPrincipal | null>;
|
|
83
|
+
/**
|
|
84
|
+
The 401 message. Defaults to a fixed sentence that says nothing about why.
|
|
85
|
+
*/
|
|
86
|
+
message?: string;
|
|
87
|
+
}
|
|
88
|
+
declare function apiKeyAuth<E extends object, V extends object = object>(options: ApiKeyAuthOptions<E, V>): MiddlewareHandler<FamilyEnv<E, V>>;
|
|
89
|
+
export { accessAuth, apiKeyAuth };
|
|
90
|
+
export type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser };
|
|
91
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/hono/auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAGvD,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAEzE,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErD;;;;GAIG;AACH,KAAK,YAAY,GAAG,MAAM,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAE5D,UAAU,2BAA2B,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM;IACtE;;MAEE;IACF,UAAU,EAAE,OAAO,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IAC3C;;MAEE;IACF,SAAS,EAAE,OAAO,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IAC1C;;MAEE;IACF,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,aAAa,GAAG,SAAS,CAAC;IAChD;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC7D;;MAEE;IACF,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD;;MAEE;IACF,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;IACjF;;MAEE;IACF,QAAQ,CAAC,EAAE,iBAAiB,CAAC;CAC9B;AAUD,iBAAS,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAC7D,OAAO,EAAE,2BAA2B,CAAC,CAAC,EAAE,CAAC,CAAC,GACzC,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAiBpC;AAED;;EAEE;AACF,UAAU,YAAY;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf;AAED,UAAU,iBAAiB,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM;IAC5D;;;;OAIG;IACH,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC;IAClE;;MAEE;IACF,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,iBAAS,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,OAAO,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAOrI;AAED,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC;AAClC,YAAY,EAAE,2BAA2B,EAAE,iBAAiB,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=Object.defineProperty;var r=(i,e)=>f(i,"name",{value:e,configurable:!0});import{UnauthorizedError as u}from"@rexezuge/errors";import{authenticateAccess as o}from"../accessAuth.js";import{resolveFromEnv as d}from"./types.js";function m(i,e,n){const a=typeof e=="string"?e:e.id;if(a.trim()==="")throw new u("Cloudflare Access authentication failed.");const t=typeof e=="string"?n:e.email??n;i.set("AuthenticatedUserId",a),i.set("AuthenticatedUserEmailAddress",t.trim().toLowerCase())}r(m,"publish");function c(i){return async(e,n)=>{const a=i.devBypass===void 0?void 0:d(i.devBypass,e.env),t=i.demo===void 0?void 0:d(i.demo,e.env),s=i.binding?i.binding(e.env):e.env.ACCESS,l=await o(e.req.raw,s,{bypassAllowed:a?.allowed===!0,devAuthEmail:a?.email??null,isDemoMode:t?.enabled===!0,demoUserEmail:t?.email??null,teamDomain:d(i.teamDomain,e.env)??null,policyAud:d(i.policyAud,e.env)??null,verifier:i.verifier});m(e,await i.resolveUserId(l,e),l),await n()}}r(c,"accessAuth");function A(i){return async(e,n)=>{const a=await i.verify(e);if(a===null)throw new u(i.message??"A valid API credential is required.");m(e,{id:a.userId,email:a.email},a.email),await n()}}r(A,"apiKeyAuth");export{c as accessAuth,A as apiKeyAuth};
|