@rexezuge/http 1.10.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +182 -12
  2. package/dist/ErrorMapper.d.ts +65 -10
  3. package/dist/ErrorMapper.d.ts.map +1 -1
  4. package/dist/ErrorMapper.js +1 -1
  5. package/dist/ErrorMapper.js.map +3 -3
  6. package/dist/errorClassification.d.ts +44 -0
  7. package/dist/errorClassification.d.ts.map +1 -0
  8. package/dist/errorClassification.js +1 -0
  9. package/dist/errorClassification.js.map +7 -0
  10. package/dist/hono/FamilyRoute.d.ts +56 -0
  11. package/dist/hono/FamilyRoute.d.ts.map +1 -0
  12. package/dist/hono/FamilyRoute.js +1 -0
  13. package/dist/hono/FamilyRoute.js.map +7 -0
  14. package/dist/hono/auth.d.ts +91 -0
  15. package/dist/hono/auth.d.ts.map +1 -0
  16. package/dist/hono/auth.js +1 -0
  17. package/dist/hono/auth.js.map +7 -0
  18. package/dist/hono/bookmarks.d.ts +63 -0
  19. package/dist/hono/bookmarks.d.ts.map +1 -0
  20. package/dist/hono/bookmarks.js +1 -0
  21. package/dist/hono/bookmarks.js.map +7 -0
  22. package/dist/hono/contracts.d.ts +44 -0
  23. package/dist/hono/contracts.d.ts.map +1 -0
  24. package/dist/hono/contracts.js +1 -0
  25. package/dist/hono/contracts.js.map +7 -0
  26. package/dist/hono/createApiApp.d.ts +93 -0
  27. package/dist/hono/createApiApp.d.ts.map +1 -0
  28. package/dist/hono/createApiApp.js +1 -0
  29. package/dist/hono/createApiApp.js.map +7 -0
  30. package/dist/hono/docs.d.ts +41 -0
  31. package/dist/hono/docs.d.ts.map +1 -0
  32. package/dist/hono/docs.js +1 -0
  33. package/dist/hono/docs.js.map +7 -0
  34. package/dist/hono/errorHandler.d.ts +25 -0
  35. package/dist/hono/errorHandler.d.ts.map +1 -0
  36. package/dist/hono/errorHandler.js +1 -0
  37. package/dist/hono/errorHandler.js.map +7 -0
  38. package/dist/hono/hardening.d.ts +51 -0
  39. package/dist/hono/hardening.d.ts.map +1 -0
  40. package/dist/hono/hardening.js +1 -0
  41. package/dist/hono/hardening.js.map +7 -0
  42. package/dist/hono/index.d.ts +37 -0
  43. package/dist/hono/index.d.ts.map +1 -0
  44. package/dist/hono/index.js +1 -0
  45. package/dist/hono/index.js.map +7 -0
  46. package/dist/hono/rateLimits.d.ts +63 -0
  47. package/dist/hono/rateLimits.d.ts.map +1 -0
  48. package/dist/hono/rateLimits.js +1 -0
  49. package/dist/hono/rateLimits.js.map +7 -0
  50. package/dist/hono/requestContext.d.ts +28 -0
  51. package/dist/hono/requestContext.d.ts.map +1 -0
  52. package/dist/hono/requestContext.js +1 -0
  53. package/dist/hono/requestContext.js.map +7 -0
  54. package/dist/hono/types.d.ts +69 -0
  55. package/dist/hono/types.d.ts.map +1 -0
  56. package/dist/hono/types.js +1 -0
  57. package/dist/hono/types.js.map +7 -0
  58. package/dist/index.d.ts +20 -4
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +1 -1
  61. package/dist/index.js.map +3 -3
  62. package/dist/openApiErrors.d.ts +63 -0
  63. package/dist/openApiErrors.d.ts.map +1 -0
  64. package/dist/openApiErrors.js +1 -0
  65. package/dist/openApiErrors.js.map +7 -0
  66. package/dist/requestGuards.d.ts +52 -0
  67. package/dist/requestGuards.d.ts.map +1 -0
  68. package/dist/requestGuards.js +1 -0
  69. package/dist/requestGuards.js.map +7 -0
  70. package/dist/routeBase.d.ts.map +1 -1
  71. package/dist/routeBase.js +1 -1
  72. package/dist/routeBase.js.map +3 -3
  73. package/package.json +13 -5
@@ -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,E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AC,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};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/auth.ts"],
4
+ "sourcesContent": ["/**\n * The two authenticated surfaces, as Hono middleware.\n *\n * - `accessAuth` for `/user/*`: Cloudflare Access, through the kit's\n * `authenticateAccess` — resolution order, the single 401 message and the\n * `email_verified` refusal are the kit's and not options. Replaces the\n * `MiddlewareHandlers.userAuthentication()` copies (Mail-Bee, Mail-Meow,\n * Mail-Otter, Durable-DAV, Edge-Git, Image-Host, AWS-AccessBridge).\n * - `apiKeyAuth` for `/api/*`: PATs, HMAC signatures and path keys are\n * app-specific, so verification is a **port**. The kit owns what happens\n * around it: an absent principal is a 401, and the principal lands on the\n * same two variables `accessAuth` sets, so downstream code (and the\n * identity-keyed rate limiter) never asks which surface it is on.\n *\n * Both **throw** on failure, so the rejection leaves through `app.onError` in\n * the family envelope with the security headers and request id attached.\n */\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { UnauthorizedError } from '@rexezuge/errors';\nimport { authenticateAccess } from '../accessAuth.ts';\nimport type { AccessBinding, AccessJwtVerifier } from '../accessAuth.ts';\nimport { resolveFromEnv } from './types.ts';\nimport type { FamilyEnv, FromEnv } from './types.ts';\n\n/**\n * The account an address resolved to. A bare string is the id; an object may\n * also carry the account's **current** address, which wins over the sign-in one\n * (identity convergence: an account outlives the address it was created with).\n */\ntype ResolvedUser = string | { id: string; email?: string };\n\ninterface AccessAuthMiddlewareOptions<E extends object, V extends object> {\n /**\n `https://<team>.cloudflareaccess.com`. Usually `(env) => env.TEAM_DOMAIN`.\n */\n teamDomain: FromEnv<E, string | undefined>;\n /**\n The Access application's audience tag. Usually `(env) => env.POLICY_AUD`.\n */\n policyAud: FromEnv<E, string | undefined>;\n /**\n The `ACCESS` binding. Defaults to `env.ACCESS`; its absence is a 401, never an open door.\n */\n binding?: (env: E) => AccessBinding | undefined;\n /**\n * The development bypass. `allowed` is an **allow-list** decision (derive it\n * from an explicit var, never from `environment !== 'production'`); it also\n * gates `demo`.\n */\n devBypass?: FromEnv<E, { allowed: boolean; email?: string }>;\n /**\n The demo user, honoured only while `devBypass.allowed`.\n */\n demo?: FromEnv<E, { enabled: boolean; email?: string }>;\n /**\n Map the verified address to the account (`UserIdentityService.resolveAccountId`, an upsert, …).\n */\n resolveUserId(email: string, c: Context<FamilyEnv<E, V>>): Promise<ResolvedUser>;\n /**\n JWT verification seam for tests. The default (`jose`) refuses `email_verified: false`.\n */\n verifier?: AccessJwtVerifier;\n}\n\nfunction publish(c: Context<FamilyEnv<object, object>>, resolved: ResolvedUser, signInEmail: string): void {\n const id = typeof resolved === 'string' ? resolved : resolved.id;\n if (id.trim() === '') throw new UnauthorizedError('Cloudflare Access authentication failed.');\n const email = typeof resolved === 'string' ? signInEmail : (resolved.email ?? signInEmail);\n c.set('AuthenticatedUserId', id);\n c.set('AuthenticatedUserEmailAddress', email.trim().toLowerCase());\n}\n\nfunction accessAuth<E extends object, V extends object = object>(\n options: AccessAuthMiddlewareOptions<E, V>,\n): MiddlewareHandler<FamilyEnv<E, V>> {\n return async (c, next): Promise<void> => {\n const bypass = options.devBypass === undefined ? undefined : resolveFromEnv(options.devBypass, c.env);\n const demo = options.demo === undefined ? undefined : resolveFromEnv(options.demo, c.env);\n const binding = options.binding ? options.binding(c.env) : (c.env as { ACCESS?: AccessBinding }).ACCESS;\n const email = await authenticateAccess(c.req.raw, binding, {\n bypassAllowed: bypass?.allowed === true,\n devAuthEmail: bypass?.email ?? null,\n isDemoMode: demo?.enabled === true,\n demoUserEmail: demo?.email ?? null,\n teamDomain: resolveFromEnv(options.teamDomain, c.env) ?? null,\n policyAud: resolveFromEnv(options.policyAud, c.env) ?? null,\n verifier: options.verifier,\n });\n publish(c as unknown as Context<FamilyEnv<object, object>>, await options.resolveUserId(email, c), email);\n await next();\n };\n}\n\n/**\nWhat an API credential authenticates as.\n*/\ninterface ApiPrincipal {\n userId: string;\n email: string;\n}\n\ninterface ApiKeyAuthOptions<E extends object, V extends object> {\n /**\n * Verify the request's credential (PAT header, HMAC signature, path key).\n * `null` means \"no valid credential\" and answers 401; a thrown `ServiceError`\n * (403, 429) answers itself.\n */\n verify(c: Context<FamilyEnv<E, V>>): Promise<ApiPrincipal | null>;\n /**\n The 401 message. Defaults to a fixed sentence that says nothing about why.\n */\n message?: string;\n}\n\nfunction apiKeyAuth<E extends object, V extends object = object>(options: ApiKeyAuthOptions<E, V>): MiddlewareHandler<FamilyEnv<E, V>> {\n return async (c, next): Promise<void> => {\n const principal = await options.verify(c);\n if (principal === null) throw new UnauthorizedError(options.message ?? 'A valid API credential is required.');\n publish(c as unknown as Context<FamilyEnv<object, object>>, { id: principal.userId, email: principal.email }, principal.email);\n await next();\n };\n}\n\nexport { accessAuth, apiKeyAuth };\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser };\n"],
5
+ "mappings": "+EAkBA,OAAS,qBAAAA,MAAyB,mBAClC,OAAS,sBAAAC,MAA0B,mBAEnC,OAAS,kBAAAC,MAAsB,aA2C/B,SAASC,EAAQC,EAAuCC,EAAwBC,EAAmB,CACjG,MAAMC,EAAK,OAAOF,GAAa,SAAWA,EAAWA,EAAS,GAC9D,GAAIE,EAAG,KAAI,IAAO,GAAI,MAAM,IAAIP,EAAkB,0CAA0C,EAC5F,MAAMQ,EAAQ,OAAOH,GAAa,SAAWC,EAAeD,EAAS,OAASC,EAC9EF,EAAE,IAAI,sBAAuBG,CAAE,EAC/BH,EAAE,IAAI,gCAAiCI,EAAM,KAAI,EAAG,YAAW,CAAE,CACnE,CANSC,EAAAN,EAAA,WAQT,SAASO,EACPC,EAA0C,CAE1C,MAAO,OAAOP,EAAGQ,IAAuB,CACtC,MAAMC,EAASF,EAAQ,YAAc,OAAY,OAAYT,EAAeS,EAAQ,UAAWP,EAAE,GAAG,EAC9FU,EAAOH,EAAQ,OAAS,OAAY,OAAYT,EAAeS,EAAQ,KAAMP,EAAE,GAAG,EAClFW,EAAUJ,EAAQ,QAAUA,EAAQ,QAAQP,EAAE,GAAG,EAAKA,EAAE,IAAmC,OAC3FI,EAAQ,MAAMP,EAAmBG,EAAE,IAAI,IAAKW,EAAS,CACzD,cAAeF,GAAQ,UAAY,GACnC,aAAcA,GAAQ,OAAS,KAC/B,WAAYC,GAAM,UAAY,GAC9B,cAAeA,GAAM,OAAS,KAC9B,WAAYZ,EAAeS,EAAQ,WAAYP,EAAE,GAAG,GAAK,KACzD,UAAWF,EAAeS,EAAQ,UAAWP,EAAE,GAAG,GAAK,KACvD,SAAUO,EAAQ,SACnB,EACDR,EAAQC,EAAoD,MAAMO,EAAQ,cAAcH,EAAOJ,CAAC,EAAGI,CAAK,EACxG,MAAMI,EAAI,CACZ,CACF,CAnBSH,EAAAC,EAAA,cA0CT,SAASM,EAAwDL,EAAgC,CAC/F,MAAO,OAAOP,EAAGQ,IAAuB,CACtC,MAAMK,EAAY,MAAMN,EAAQ,OAAOP,CAAC,EACxC,GAAIa,IAAc,KAAM,MAAM,IAAIjB,EAAkBW,EAAQ,SAAW,qCAAqC,EAC5GR,EAAQC,EAAoD,CAAE,GAAIa,EAAU,OAAQ,MAAOA,EAAU,KAAK,EAAIA,EAAU,KAAK,EAC7H,MAAML,EAAI,CACZ,CACF,CAPSH,EAAAO,EAAA",
6
+ "names": ["UnauthorizedError", "authenticateAccess", "resolveFromEnv", "publish", "c", "resolved", "signInEmail", "id", "email", "__name", "accessAuth", "options", "next", "bypass", "demo", "binding", "apiKeyAuth", "principal"]
7
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The D1 Sessions bookmark middleware.
3
+ *
4
+ * Converged from the `onRequest` blocks in Mail-Otter, Mail-Bee, Mail-Meow,
5
+ * AWS-AccessBridge and CalDAV-Bridge that open a session from `x-d1-bookmark`,
6
+ * hand the app a copied `env`, and stamp the latest bookmark on the way out.
7
+ *
8
+ * `@rexezuge/d1` owns the primitives (`readBookmark` / `openSession` /
9
+ * `withBookmark`); `http` may not depend on `d1`, so they come in through a
10
+ * structural port. The d1 module itself satisfies it:
11
+ *
12
+ * ```ts
13
+ * import { openSession, readBookmark, withBookmark } from '@rexezuge/d1';
14
+ * createApiApp({ d1: { binding: 'DB', bookmarks: { openSession, readBookmark, withBookmark } } });
15
+ * ```
16
+ */
17
+ import type { MiddlewareHandler } from 'hono';
18
+ /**
19
+ A session, structurally: a real `D1DatabaseSession` satisfies it.
20
+ */
21
+ interface BookmarkSession {
22
+ getBookmark(): string | null;
23
+ }
24
+ /**
25
+ A binding that opens sessions: a real `D1Database` satisfies it.
26
+ */
27
+ interface BookmarkSource {
28
+ withSession(constraintOrBookmark?: string): BookmarkSession;
29
+ }
30
+ /**
31
+ The three `@rexezuge/d1` primitives, as the middleware calls them.
32
+ */
33
+ interface BookmarkPort {
34
+ readBookmark(request: Request): string | null;
35
+ openSession(db: BookmarkSource, bookmark: string | null): BookmarkSession;
36
+ withBookmark(response: Response, session: BookmarkSession): Response;
37
+ }
38
+ interface D1BookmarkOptions {
39
+ /**
40
+ The `env` key of the D1 binding the app reads (`'DB'`).
41
+ */
42
+ binding: string;
43
+ bookmarks: BookmarkPort;
44
+ /**
45
+ Where a session is opened. Defaults to every path (`['*']`).
46
+ */
47
+ paths?: readonly string[];
48
+ }
49
+ /**
50
+ * Replace `env[binding]` with a session for the rest of the chain, then stamp
51
+ * its bookmark on the response. The incoming `env` object is never mutated:
52
+ * Workers reuse it across requests, so writing the session into it would hand
53
+ * one request's session to the next.
54
+ *
55
+ * A missing or session-less binding is a **configuration** error and fails the
56
+ * request (a masked 500) rather than silently serving without consistency.
57
+ */
58
+ declare function d1Bookmarks<E extends object>(options: D1BookmarkOptions): MiddlewareHandler<{
59
+ Bindings: E;
60
+ }>;
61
+ export { d1Bookmarks };
62
+ export type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions };
63
+ //# sourceMappingURL=bookmarks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bookmarks.d.ts","sourceRoot":"","sources":["../../src/hono/bookmarks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAE9C;;EAEE;AACF,UAAU,eAAe;IACvB,WAAW,IAAI,MAAM,GAAG,IAAI,CAAC;CAC9B;AAED;;EAEE;AACF,UAAU,cAAc;IACtB,WAAW,CAAC,oBAAoB,CAAC,EAAE,MAAM,GAAG,eAAe,CAAC;CAC7D;AAED;;EAEE;AACF,UAAU,YAAY;IACpB,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAAC;IAC9C,WAAW,CAAC,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,eAAe,CAAC;IAC1E,YAAY,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,eAAe,GAAG,QAAQ,CAAC;CACtE;AAED,UAAU,iBAAiB;IACzB;;MAEE;IACF,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,YAAY,CAAC;IACxB;;MAEE;IACF,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3B;AAMD;;;;;;;;GAQG;AACH,iBAAS,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAYrG;AAED,OAAO,EAAE,WAAW,EAAE,CAAC;AACvB,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var k=Object.defineProperty;var r=(n,e)=>k(n,"name",{value:e,configurable:!0});function a(n){return typeof n=="object"&&n!==null&&typeof n.withSession=="function"}r(a,"isBookmarkSource");function b(n){return async(e,t)=>{const o=e.env[n.binding];if(!a(o))throw new TypeError(`createApiApp: env.${n.binding} is not a D1 binding with withSession().`);const i=n.bookmarks.openSession(o,n.bookmarks.readBookmark(e.req.raw));e.env={...e.env,[n.binding]:i},await t();const s=n.bookmarks.withBookmark(e.res,i);s!==e.res&&(e.res=s)}}r(b,"d1Bookmarks");export{b as d1Bookmarks};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/bookmarks.ts"],
4
+ "sourcesContent": ["/**\n * The D1 Sessions bookmark middleware.\n *\n * Converged from the `onRequest` blocks in Mail-Otter, Mail-Bee, Mail-Meow,\n * AWS-AccessBridge and CalDAV-Bridge that open a session from `x-d1-bookmark`,\n * hand the app a copied `env`, and stamp the latest bookmark on the way out.\n *\n * `@rexezuge/d1` owns the primitives (`readBookmark` / `openSession` /\n * `withBookmark`); `http` may not depend on `d1`, so they come in through a\n * structural port. The d1 module itself satisfies it:\n *\n * ```ts\n * import { openSession, readBookmark, withBookmark } from '@rexezuge/d1';\n * createApiApp({ d1: { binding: 'DB', bookmarks: { openSession, readBookmark, withBookmark } } });\n * ```\n */\nimport type { MiddlewareHandler } from 'hono';\n\n/**\nA session, structurally: a real `D1DatabaseSession` satisfies it.\n*/\ninterface BookmarkSession {\n getBookmark(): string | null;\n}\n\n/**\nA binding that opens sessions: a real `D1Database` satisfies it.\n*/\ninterface BookmarkSource {\n withSession(constraintOrBookmark?: string): BookmarkSession;\n}\n\n/**\nThe three `@rexezuge/d1` primitives, as the middleware calls them.\n*/\ninterface BookmarkPort {\n readBookmark(request: Request): string | null;\n openSession(db: BookmarkSource, bookmark: string | null): BookmarkSession;\n withBookmark(response: Response, session: BookmarkSession): Response;\n}\n\ninterface D1BookmarkOptions {\n /**\n The `env` key of the D1 binding the app reads (`'DB'`).\n */\n binding: string;\n bookmarks: BookmarkPort;\n /**\n Where a session is opened. Defaults to every path (`['*']`).\n */\n paths?: readonly string[];\n}\n\nfunction isBookmarkSource(value: unknown): value is BookmarkSource {\n return typeof value === 'object' && value !== null && typeof (value as { withSession?: unknown }).withSession === 'function';\n}\n\n/**\n * Replace `env[binding]` with a session for the rest of the chain, then stamp\n * its bookmark on the response. The incoming `env` object is never mutated:\n * Workers reuse it across requests, so writing the session into it would hand\n * one request's session to the next.\n *\n * A missing or session-less binding is a **configuration** error and fails the\n * request (a masked 500) rather than silently serving without consistency.\n */\nfunction d1Bookmarks<E extends object>(options: D1BookmarkOptions): MiddlewareHandler<{ Bindings: E }> {\n return async (c, next): Promise<void> => {\n const db = (c.env as Record<string, unknown>)[options.binding];\n if (!isBookmarkSource(db)) {\n throw new TypeError(`createApiApp: env.${options.binding} is not a D1 binding with withSession().`);\n }\n const session = options.bookmarks.openSession(db, options.bookmarks.readBookmark(c.req.raw));\n c.env = { ...c.env, [options.binding]: session };\n await next();\n const stamped = options.bookmarks.withBookmark(c.res, session);\n if (stamped !== c.res) c.res = stamped;\n };\n}\n\nexport { d1Bookmarks };\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions };\n"],
5
+ "mappings": "+EAqDA,SAASA,EAAiBC,EAAc,CACtC,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,OAAQA,EAAoC,aAAgB,UACpH,CAFSC,EAAAF,EAAA,oBAaT,SAASG,EAA8BC,EAA0B,CAC/D,MAAO,OAAOC,EAAGC,IAAuB,CACtC,MAAMC,EAAMF,EAAE,IAAgCD,EAAQ,OAAO,EAC7D,GAAI,CAACJ,EAAiBO,CAAE,EACtB,MAAM,IAAI,UAAU,qBAAqBH,EAAQ,OAAO,0CAA0C,EAEpG,MAAMI,EAAUJ,EAAQ,UAAU,YAAYG,EAAIH,EAAQ,UAAU,aAAaC,EAAE,IAAI,GAAG,CAAC,EAC3FA,EAAE,IAAM,CAAE,GAAGA,EAAE,IAAK,CAACD,EAAQ,OAAO,EAAGI,CAAO,EAC9C,MAAMF,EAAI,EACV,MAAMG,EAAUL,EAAQ,UAAU,aAAaC,EAAE,IAAKG,CAAO,EACzDC,IAAYJ,EAAE,MAAKA,EAAE,IAAMI,EACjC,CACF,CAZSP,EAAAC,EAAA",
6
+ "names": ["isBookmarkSource", "value", "__name", "d1Bookmarks", "options", "c", "next", "db", "session", "stamped"]
7
+ }
@@ -0,0 +1,44 @@
1
+ import type { OpenAPIRoute, OpenAPIRouteSchema } from 'chanfana';
2
+ import type { Contract, ContractEndpoints, Endpoint, EndpointResult, EndpointServerInput } from '@rexezuge/contracts';
3
+ import type { ApiApp } from './createApiApp.ts';
4
+ import type { RouteResult } from './FamilyRoute.ts';
5
+ import type { FamilyContext } from './types.ts';
6
+ /**
7
+ * Your implementation of one endpoint. `input` is the validated request (zod
8
+ * output), and the return value is the response schema's input, `null` for a
9
+ * `204` endpoint, or a `Response` you built yourself.
10
+ */
11
+ type EndpointHandler<EP extends Endpoint, E extends object = object, V extends object = object> = (input: EndpointServerInput<EP>, c: FamilyContext<E, V>) => Promise<RouteResult<EndpointResult<EP>>>;
12
+ /**
13
+ One handler per contract endpoint, by name. A missing key is a compile error.
14
+ */
15
+ type ContractHandlers<C extends ContractEndpoints, E extends object = object, V extends object = object> = {
16
+ [K in keyof C]: EndpointHandler<C[K], E, V>;
17
+ };
18
+ /**
19
+ * A route class, in the type chanfana's `app.get(path, Route)` accepts. It is
20
+ * constructed once, at registration.
21
+ */
22
+ type EndpointRoute = typeof OpenAPIRoute<any>;
23
+ /**
24
+ * The chanfana schema for an endpoint: request, success and error responses.
25
+ */
26
+ declare function schemaFromEndpoint(endpoint: Endpoint): OpenAPIRouteSchema;
27
+ /**
28
+ * One endpoint as a route class: `app.get(endpoint.path, routeFromEndpoint(endpoint, handler))`.
29
+ * Prefer `registerContract`, which also checks the method and path for you.
30
+ */
31
+ declare function routeFromEndpoint<EP extends Endpoint, E extends object = object, V extends object = object>(endpoint: EP, handler: EndpointHandler<EP, E, V>): EndpointRoute;
32
+ /**
33
+ * Register every endpoint of a contract. `handlers` must name exactly the
34
+ * contract's endpoints: the type requires every key, and a missing or an extra
35
+ * key also throws a `TypeError` here, at startup.
36
+ *
37
+ * ```ts
38
+ * createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, { getItem, listItems, renameItem }) });
39
+ * ```
40
+ */
41
+ declare function registerContract<E extends object, V extends object, C extends ContractEndpoints>(app: ApiApp<E, V>, contract: Contract<C>, handlers: ContractHandlers<C, E, V>): void;
42
+ export { registerContract, routeFromEndpoint, schemaFromEndpoint };
43
+ export type { ContractHandlers, EndpointHandler, EndpointRoute };
44
+ //# sourceMappingURL=contracts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/hono/contracts.ts"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAiC,MAAM,UAAU,CAAC;AAEhG,OAAO,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,QAAQ,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAEtH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;GAIG;AACH,KAAK,eAAe,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,CAChG,KAAK,EAAE,mBAAmB,CAAC,EAAE,CAAC,EAC9B,CAAC,EAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,KACnB,OAAO,CAAC,WAAW,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAE9C;;EAEE;AACF,KAAK,gBAAgB,CAAC,CAAC,SAAS,iBAAiB,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI;KACxG,CAAC,IAAI,MAAM,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AAEH,KAAK,aAAa,GAAG,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC;AAE9C;;GAEG;AACH,iBAAS,kBAAkB,CAAC,QAAQ,EAAE,QAAQ,GAAG,kBAAkB,CAwBlE;AAED;;;GAGG;AACH,iBAAS,iBAAiB,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAClG,QAAQ,EAAE,EAAE,EACZ,OAAO,EAAE,eAAe,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,GACjC,aAAa,CAyBf;AAID;;;;;;;;GAQG;AACH,iBAAS,gBAAgB,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,iBAAiB,EACvF,GAAG,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EACjB,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,EACrB,QAAQ,EAAE,gBAAgB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAClC,IAAI,CAaN;AAED,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,CAAC;AACnE,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var h=Object.defineProperty;var i=(e,r)=>h(e,"name",{value:r,configurable:!0});import{contentJson as y}from"chanfana";import{UnauthorizedError as b}from"@rexezuge/errors";import{errorResponses as g}from"../openApiErrors.js";import{FamilyRoute as w}from"./FamilyRoute.js";function l(e){const r={};e.params!==void 0&&(r.params=e.params),e.query!==void 0&&(r.query=e.query),e.body!==void 0&&(r.body=y(e.body));const o=e.response===null?{204:{description:"No Content"}}:{200:{description:e.summary??"OK",...y(e.response)}},a=Object.assign({},...e.errorResponses.map(({status:t,description:u})=>g(u===null?[t]:{[t]:u})));return{...e.summary!==void 0&&{summary:e.summary},...e.description!==void 0&&{description:e.description},...e.tags!==void 0&&{tags:[...e.tags]},request:r,responses:{...o,...a}}}i(l,"schemaFromEndpoint");function d(e,r){const o=l(e),a=e.auth!=="public";class t extends w{static{i(this,"ContractRoute")}schema=o;async handleRequest(f,s){if(a&&!s.get("AuthenticatedUserId"))throw new b;const n=f,c={};e.params!==void 0&&(c.params=n.params),e.query!==void 0&&(c.query=n.query),e.body!==void 0&&(c.body=n.body);const m=await r(c,s);return e.response===null&&!(m instanceof Response)?null:m}}return Object.defineProperty(t,"name",{value:`${e.method} ${e.path}`}),t}i(d,"routeFromEndpoint");function p(e,r,o){const a=Object.keys(r),t=a.filter(s=>typeof o[s]!="function");if(t.length>0)throw new TypeError(`registerContract: no handler for ${t.join(", ")}`);const u=Object.keys(o).filter(s=>!Object.hasOwn(r,s));if(u.length>0)throw new TypeError(`registerContract: ${u.join(", ")} is not in the contract`);const f=e;for(const s of a){const n=r[s],c=o[s];f[n.method.toLowerCase()]?.call(e,n.path,d(n,c))}}i(p,"registerContract");export{p as registerContract,d as routeFromEndpoint,l as schemaFromEndpoint};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/contracts.ts"],
4
+ "sourcesContent": ["/**\n * The backend half of `@rexezuge/contracts`: an endpoint becomes a chanfana\n * route on the family app.\n *\n * ## Why here, and why `http` depends on `contracts`\n *\n * The adapter needs chanfana (`contentJson`, `OpenAPIRoute`), and the kit's rule\n * is that `hono`/`chanfana` are imported under `packages/http/src/hono/` and\n * nowhere else. So the adapter lives in `/hono`, and `http` takes a dependency on\n * `contracts`, a framework-free package that depends on neither `http` nor\n * `web`. The graph stays acyclic: `errors`/`shared` → `contracts` → `http` →\n * `web`. The other direction (a `/hono` subpath inside `contracts`) would have\n * put a second framework package in the kit.\n *\n * ## Closed\n *\n * - The route's chanfana `schema` is **derived** from the endpoint: request\n * `params`/`query`/`body`, the success response (`200` + the response schema,\n * or `204`), and every documented error as the kit's `{Exception}` envelope\n * (`errorResponses`). There is no second hand-written schema to drift.\n * - The route is a `FamilyRoute`, so validation, result shaping and error\n * mapping are the kit's `@final` `handle()`.\n * - **Fail-closed auth.** An `access`/`apiKey` endpoint answers `401` when no\n * auth middleware set `AuthenticatedUserId`, so forgetting to mount\n * `accessAuth` on a path does not publish an authenticated route.\n * - `registerContract` refuses a missing or an unknown handler at startup.\n *\n * ## Open\n *\n * The handler, the app (`E`, `V`), and `schemaFromEndpoint` for a hand-written\n * `FamilyRoute` subclass that needs `errorMapping()` or a raw `Response`.\n */\nimport { contentJson } from 'chanfana';\nimport type { OpenAPIRoute, OpenAPIRouteSchema, ResponseConfig, ValidatedData } from 'chanfana';\nimport { UnauthorizedError } from '@rexezuge/errors';\nimport type { Contract, ContractEndpoints, Endpoint, EndpointResult, EndpointServerInput } from '@rexezuge/contracts';\nimport { errorResponses } from '../openApiErrors.ts';\nimport type { ApiApp } from './createApiApp.ts';\nimport { FamilyRoute } from './FamilyRoute.ts';\nimport type { RouteResult } from './FamilyRoute.ts';\nimport type { FamilyContext } from './types.ts';\n\n/**\n * Your implementation of one endpoint. `input` is the validated request (zod\n * output), and the return value is the response schema's input, `null` for a\n * `204` endpoint, or a `Response` you built yourself.\n */\ntype EndpointHandler<EP extends Endpoint, E extends object = object, V extends object = object> = (\n input: EndpointServerInput<EP>,\n c: FamilyContext<E, V>,\n) => Promise<RouteResult<EndpointResult<EP>>>;\n\n/**\nOne handler per contract endpoint, by name. A missing key is a compile error.\n*/\ntype ContractHandlers<C extends ContractEndpoints, E extends object = object, V extends object = object> = {\n [K in keyof C]: EndpointHandler<C[K], E, V>;\n};\n\n/**\n * A route class, in the type chanfana's `app.get(path, Route)` accepts. It is\n * constructed once, at registration.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- chanfana's own registration parameter type\ntype EndpointRoute = typeof OpenAPIRoute<any>;\n\n/**\n * The chanfana schema for an endpoint: request, success and error responses.\n */\nfunction schemaFromEndpoint(endpoint: Endpoint): OpenAPIRouteSchema {\n const request: NonNullable<OpenAPIRouteSchema['request']> = {};\n if (endpoint.params !== undefined) request.params = endpoint.params;\n if (endpoint.query !== undefined) request.query = endpoint.query;\n if (endpoint.body !== undefined) request.body = contentJson(endpoint.body);\n\n const success: Record<string, ResponseConfig> =\n endpoint.response === null\n ? { '204': { description: 'No Content' } }\n : { '200': { description: endpoint.summary ?? 'OK', ...contentJson(endpoint.response) } };\n const errors = Object.assign(\n {},\n ...endpoint.errorResponses.map(({ status, description }) =>\n errorResponses(description === null ? [status] : { [status]: description }),\n ),\n ) as ReturnType<typeof errorResponses>;\n\n return {\n ...(endpoint.summary !== undefined && { summary: endpoint.summary }),\n ...(endpoint.description !== undefined && { description: endpoint.description }),\n ...(endpoint.tags !== undefined && { tags: [...endpoint.tags] }),\n request,\n responses: { ...success, ...errors },\n };\n}\n\n/**\n * One endpoint as a route class: `app.get(endpoint.path, routeFromEndpoint(endpoint, handler))`.\n * Prefer `registerContract`, which also checks the method and path for you.\n */\nfunction routeFromEndpoint<EP extends Endpoint, E extends object = object, V extends object = object>(\n endpoint: EP,\n handler: EndpointHandler<EP, E, V>,\n): EndpointRoute {\n const schema = schemaFromEndpoint(endpoint);\n const authenticated = endpoint.auth !== 'public';\n\n class ContractRoute extends FamilyRoute<OpenAPIRouteSchema, E, V> {\n public override schema = schema;\n\n protected async handleRequest(input: ValidatedData<OpenAPIRouteSchema>, c: FamilyContext<E, V>): Promise<RouteResult<unknown>> {\n // Read loosely on purpose: the variable is typed as always present, and\n // this is the check that it really is.\n if (authenticated && !(c.get('AuthenticatedUserId') as string | undefined)) throw new UnauthorizedError();\n const validated = input as { params?: unknown; query?: unknown; body?: unknown };\n const slots: Record<string, unknown> = {};\n if (endpoint.params !== undefined) slots.params = validated.params;\n if (endpoint.query !== undefined) slots.query = validated.query;\n if (endpoint.body !== undefined) slots.body = validated.body;\n const result = await handler(slots as EndpointServerInput<EP>, c);\n // A 204 endpoint answers 204 whatever the handler returned, unless it\n // built its own Response.\n if (endpoint.response === null && !(result instanceof Response)) return null;\n return result;\n }\n }\n Object.defineProperty(ContractRoute, 'name', { value: `${endpoint.method} ${endpoint.path}` });\n return ContractRoute;\n}\n\ntype Register = (path: string, route: unknown) => unknown;\n\n/**\n * Register every endpoint of a contract. `handlers` must name exactly the\n * contract's endpoints: the type requires every key, and a missing or an extra\n * key also throws a `TypeError` here, at startup.\n *\n * ```ts\n * createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, { getItem, listItems, renameItem }) });\n * ```\n */\nfunction registerContract<E extends object, V extends object, C extends ContractEndpoints>(\n app: ApiApp<E, V>,\n contract: Contract<C>,\n handlers: ContractHandlers<C, E, V>,\n): void {\n const names = Object.keys(contract);\n const missing = names.filter((name) => typeof (handlers as Record<string, unknown>)[name] !== 'function');\n if (missing.length > 0) throw new TypeError(`registerContract: no handler for ${missing.join(', ')}`);\n const unknown = Object.keys(handlers).filter((name) => !Object.hasOwn(contract, name));\n if (unknown.length > 0) throw new TypeError(`registerContract: ${unknown.join(', ')} is not in the contract`);\n\n const router = app as unknown as Record<string, Register>;\n for (const name of names) {\n const endpoint = contract[name] as Endpoint;\n const handler = (handlers as Record<string, EndpointHandler<Endpoint, E, V>>)[name];\n router[endpoint.method.toLowerCase()]?.call(app, endpoint.path, routeFromEndpoint(endpoint, handler));\n }\n}\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint };\nexport type { ContractHandlers, EndpointHandler, EndpointRoute };\n"],
5
+ "mappings": "+EAgCA,OAAS,eAAAA,MAAmB,WAE5B,OAAS,qBAAAC,MAAyB,mBAElC,OAAS,kBAAAC,MAAsB,sBAE/B,OAAS,eAAAC,MAAmB,mBA+B5B,SAASC,EAAmBC,EAAkB,CAC5C,MAAMC,EAAsD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AS,SAAWe,EAAM,KAAOD,EAAU,MACxD,MAAME,EAAS,MAAMR,EAAQO,EAAkCF,CAAC,EAGhE,OAAIb,EAAS,WAAa,MAAQ,EAAEgB,aAAkB,UAAkB,KACjEA,CACT,EAEF,cAAO,eAAeL,EAAe,OAAQ,CAAE,MAAO,GAAGX,EAAS,MAAM,IAAIA,EAAS,IAAI,EAAE,CAAE,EACtFW,CACT,CA5BSL,EAAAC,EAAA,qBAyCT,SAASU,EACPC,EACAC,EACAC,EAAmC,CAEnC,MAAMC,EAAQ,OAAO,KAAKF,CAAQ,EAC5BG,EAAUD,EAAM,OAAQE,GAAS,OAAQH,EAAqCG,CAAI,GAAM,UAAU,EACxG,GAAID,EAAQ,OAAS,EAAG,MAAM,IAAI,UAAU,oCAAoCA,EAAQ,KAAK,IAAI,CAAC,EAAE,EACpG,MAAME,EAAU,OAAO,KAAKJ,CAAQ,EAAE,OAAQG,GAAS,CAAC,OAAO,OAAOJ,EAAUI,CAAI,CAAC,EACrF,GAAIC,EAAQ,OAAS,EAAG,MAAM,IAAI,UAAU,qBAAqBA,EAAQ,KAAK,IAAI,CAAC,yBAAyB,EAE5G,MAAMC,EAASP,EACf,UAAWK,KAAQF,EAAO,CACxB,MAAMrB,EAAWmB,EAASI,CAAI,EACxBf,EAAWY,EAA6DG,CAAI,EAClFE,EAAOzB,EAAS,OAAO,YAAW,CAAE,GAAG,KAAKkB,EAAKlB,EAAS,KAAMO,EAAkBP,EAAUQ,CAAO,CAAC,CACtG,CACF,CAjBSF,EAAAW,EAAA",
6
+ "names": ["contentJson", "UnauthorizedError", "errorResponses", "FamilyRoute", "schemaFromEndpoint", "endpoint", "request", "success", "errors", "status", "description", "__name", "routeFromEndpoint", "handler", "schema", "authenticated", "ContractRoute", "input", "c", "validated", "slots", "result", "registerContract", "app", "contract", "handlers", "names", "missing", "name", "unknown", "router"]
7
+ }
@@ -0,0 +1,93 @@
1
+ import type { HonoOpenAPIRouterType } from 'chanfana';
2
+ import type { MiddlewareHandler } from 'hono';
3
+ import { cors } from 'hono/cors';
4
+ import type { ErrorMapperOptions } from '../ErrorMapper.ts';
5
+ import type { D1BookmarkOptions } from './bookmarks.ts';
6
+ import type { HardeningOptions } from './hardening.ts';
7
+ import type { RateLimitRule } from './rateLimits.ts';
8
+ import type { RequestContextOptions } from './requestContext.ts';
9
+ import type { FamilyEnv } from './types.ts';
10
+ type ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;
11
+ type CorsOptions = NonNullable<Parameters<typeof cors>[0]>;
12
+ interface DocsOptions {
13
+ /**
14
+ Defaults to `/docs`.
15
+ */
16
+ url?: string;
17
+ /**
18
+ Defaults to `/openapi.json`.
19
+ */
20
+ openapiUrl?: string;
21
+ /**
22
+ The OpenAPI document's `info`.
23
+ */
24
+ info?: {
25
+ title: string;
26
+ version: string;
27
+ description?: string;
28
+ };
29
+ }
30
+ interface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {
31
+ /**
32
+ * The paths whose responses get `Cache-Control: no-store`. Defaults to
33
+ * `['/user/', '/api/']`: both surfaces carry credentials or account data.
34
+ */
35
+ sensitivePaths?: readonly string[];
36
+ /**
37
+ Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.
38
+ */
39
+ cors?: CorsOptions;
40
+ /**
41
+ Tunes the hardening slot. The guards themselves are not optional.
42
+ */
43
+ hardening?: HardeningOptions<E>;
44
+ /**
45
+ Open a D1 session per request and round-trip its bookmark.
46
+ */
47
+ d1?: D1BookmarkOptions;
48
+ /**
49
+ Rate-limit rules; each rule's `key` decides its slot (6 or 9).
50
+ */
51
+ rateLimits?: readonly RateLimitRule<E>[];
52
+ /**
53
+ * The authenticated surfaces: a path pattern → its auth middleware, e.g.
54
+ * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.
55
+ */
56
+ auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;
57
+ /**
58
+ Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).
59
+ */
60
+ hooks?: {
61
+ beforeAuth?: readonly AppHook<E, V>[];
62
+ afterAuth?: readonly AppHook<E, V>[];
63
+ };
64
+ /**
65
+ Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`).
66
+ */
67
+ errors?: ErrorMapperOptions;
68
+ /**
69
+ `/docs` and `/openapi.json`. Pass `false` to serve neither.
70
+ */
71
+ docs?: DocsOptions | false;
72
+ /**
73
+ Register your routes. Runs last, after every kit slot.
74
+ */
75
+ routes?: (app: ApiApp<E, V>) => void;
76
+ }
77
+ type AppHook<E extends object, V extends object> = MiddlewareHandler<FamilyEnv<E, V>> | {
78
+ path: string;
79
+ handler: MiddlewareHandler<FamilyEnv<E, V>>;
80
+ };
81
+ /**
82
+ The context key `FamilyRoute` reads the app's mapper options from.
83
+ */
84
+ declare const ERROR_OPTIONS_KEY = "errorMapperOptions";
85
+ /**
86
+ * Build the app. The returned value is the chanfana router: register routes on
87
+ * it (or in `routes`), and hand `app.fetch` the request from your entrypoint's
88
+ * `onRequest`.
89
+ */
90
+ declare function createApiApp<E extends object, V extends object = object>(options?: ApiAppOptions<E, V>): ApiApp<E, V>;
91
+ export { createApiApp, ERROR_OPTIONS_KEY };
92
+ export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions };
93
+ //# sourceMappingURL=createApiApp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createApiApp.d.ts","sourceRoot":"","sources":["../../src/hono/createApiApp.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,qBAAqB,EAAiB,MAAM,UAAU,CAAC;AAErE,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAG5D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAG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ono as m}from"chanfana";import{Hono as p}from"hono";import{cors as h}from"hono/cors";import{securityHeaders as y,sensitivePaths as _}from"../securityHeaders.js";import{d1Bookmarks as T}from"./bookmarks.js";import{DOCS_CONTENT_SECURITY_POLICY as O,isDocsPath as E}from"./docs.js";import{createErrorHandler as H,createNotFoundHandler as P}from"./errorHandler.js";import{bodyLimitGuard as R,contentTypeGuard as k,methodGuard as A,originGuard as C}from"./hardening.js";import{rateLimitRule as i}from"./rateLimits.js";import{requestContext as N}from"./requestContext.js";const c="errorMapperOptions",S=["/user/*"],g=["/user/*","/api/*"];function f(e,r){for(const s of r??[])typeof s=="function"?e.use("*",s):e.use(s.path,s.handler)}n(f,"mountHooks");function w(e){return e===!1?{docs_url:null,openapi_url:null,redoc_url:null,raiseOnError:!0}:{docs_url:e?.url??"/docs",openapi_url:e?.openapiUrl??"/openapi.json",redoc_url:null,raiseOnError:!0,...e?.info&&{schema:{info:e.info}}}}n(w,"routerOptions");function x(e,r){e.use("*",N(r)),e.use("*",async(t,o)=>{t.set(c,r.errors??{}),await o()});const s=y(_(...r.sensitivePaths??["/user/","/api/"])),a=r.docs===!1?null:r.docs?.url??"/docs";if(e.use("*",async(t,o)=>{await s(t,o),a!==null&&E(t.req.path,a)&&(t.res.headers.get("content-type")??"").includes("text/html")&&t.header("Content-Security-Policy",O)}),r.cors){const t=[...new Set([...r.cors.exposeHeaders??[],"X-Request-Id"])];e.use("*",h({...r.cors,exposeHeaders:t}))}const u=r.hardening??{};e.use("*",A(u.methods)),e.use("*",R(u.maxBodyBytes));for(const t of u.contentType?.paths??g)e.use(t,k(u.contentType?.allowed));for(const t of u.origin?.paths??S)e.use(t,C(u.origin));if(r.d1)for(const t of r.d1.paths??["*"])e.use(t,T(r.d1))}n(x,"mountPlatform");function I(e={}){const r=new p;r.onError(H(e.errors)),r.notFound(P()),x(r,e);const s=e.rateLimits??[],a=s.filter(o=>o.key==="ip"),u=s.filter(o=>o.key!=="ip");for(const o of a)r.use(o.path,i(o));f(r,e.hooks?.beforeAuth);for(const[o,l]of Object.entries(e.auth??{}))r.use(o,l);for(const o of u)r.use(o.path,i(o));f(r,e.hooks?.afterAuth);const t=m(r,w(e.docs));return e.routes?.(t),t}n(I,"createApiApp");export{c as ERROR_OPTIONS_KEY,I as createApiApp};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/createApiApp.ts"],
4
+ "sourcesContent": ["/**\n * `createApiApp` — the family API worker's Hono + chanfana app, pre-wired.\n *\n * Every family worker hand-assembled the same stack in its constructor, and each\n * assembly had its own ordering bug: a limiter installed before auth (per-IP\n * buckets for an office NAT), security headers registered after a middleware\n * that returns early (no headers on the 401), no `onError` (a text 500 the SPA\n * cannot parse), a D1 session opened by mutating the shared `env`. The order is\n * the kit's now, and it is **closed**:\n *\n * | # | Slot | Why here |\n * | -- | ----------------------- | ---------------------------------------------------------------- |\n * | 1 | request id + logger | everything after can log and correlate |\n * | 2 | security headers | wraps the rest, so a 401/404/500 leaves with them |\n * | 3 | CORS (option) | a preflight answers before any guard or auth |\n * | 4 | hardening | method, body size, JSON content type, origin guard: cheap, no I/O |\n * | 5 | D1 bookmarks (option) | auth's account lookup already reads through the session |\n * | 6 | `ip` rate limits | throttle before the auth step spends D1 on an anonymous caller |\n * | 7 | `beforeAuth` hooks | your middleware that must see the request unauthenticated |\n * | 8 | auth surfaces | `accessAuth` on `/user/*`, `apiKeyAuth` on `/api/*`, … |\n * | 9 | `identity` rate limits | keyed on the account, which only exists after 8 |\n * | 10 | `afterAuth` hooks | your middleware that needs the account (request scope, audit) |\n * | 11 | `routes(app)` | your routes |\n *\n * plus `onError` (the kit mapper → `{Exception:{Type,Message}}`), `notFound` (the\n * same envelope) and `/docs` + `/openapi.json` (option).\n */\nimport { fromHono } from 'chanfana';\nimport type { HonoOpenAPIRouterType, RouterOptions } from 'chanfana';\nimport { Hono } from 'hono';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { cors } from 'hono/cors';\nimport { securityHeaders, sensitivePaths } from '../securityHeaders.ts';\nimport type { ErrorMapperOptions } from '../ErrorMapper.ts';\nimport { d1Bookmarks } from './bookmarks.ts';\nimport { DOCS_CONTENT_SECURITY_POLICY, isDocsPath } from './docs.ts';\nimport type { D1BookmarkOptions } from './bookmarks.ts';\nimport { createErrorHandler, createNotFoundHandler } from './errorHandler.ts';\nimport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nimport type { HardeningOptions } from './hardening.ts';\nimport { rateLimitRule } from './rateLimits.ts';\nimport type { RateLimitRule } from './rateLimits.ts';\nimport { requestContext } from './requestContext.ts';\nimport type { RequestContextOptions } from './requestContext.ts';\nimport type { FamilyEnv } from './types.ts';\n\ntype ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;\n\ntype CorsOptions = NonNullable<Parameters<typeof cors>[0]>;\n\ninterface DocsOptions {\n /**\n Defaults to `/docs`.\n */\n url?: string;\n /**\n Defaults to `/openapi.json`.\n */\n openapiUrl?: string;\n /**\n The OpenAPI document's `info`.\n */\n info?: { title: string; version: string; description?: string };\n}\n\ninterface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {\n /**\n * The paths whose responses get `Cache-Control: no-store`. Defaults to\n * `['/user/', '/api/']`: both surfaces carry credentials or account data.\n */\n sensitivePaths?: readonly string[];\n /**\n Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.\n */\n cors?: CorsOptions;\n /**\n Tunes the hardening slot. The guards themselves are not optional.\n */\n hardening?: HardeningOptions<E>;\n /**\n Open a D1 session per request and round-trip its bookmark.\n */\n d1?: D1BookmarkOptions;\n /**\n Rate-limit rules; each rule's `key` decides its slot (6 or 9).\n */\n rateLimits?: readonly RateLimitRule<E>[];\n /**\n * The authenticated surfaces: a path pattern → its auth middleware, e.g.\n * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.\n */\n auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;\n /**\n Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).\n */\n hooks?: {\n beforeAuth?: readonly AppHook<E, V>[];\n afterAuth?: readonly AppHook<E, V>[];\n };\n /**\n Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`).\n */\n errors?: ErrorMapperOptions;\n /**\n `/docs` and `/openapi.json`. Pass `false` to serve neither.\n */\n docs?: DocsOptions | false;\n /**\n Register your routes. Runs last, after every kit slot.\n */\n routes?: (app: ApiApp<E, V>) => void;\n}\n\ntype AppHook<E extends object, V extends object> =\n MiddlewareHandler<FamilyEnv<E, V>> | { path: string; handler: MiddlewareHandler<FamilyEnv<E, V>> };\n\n/**\nThe context key `FamilyRoute` reads the app's mapper options from.\n*/\nconst ERROR_OPTIONS_KEY = 'errorMapperOptions';\n\nconst DEFAULT_ORIGIN_PATHS: readonly string[] = ['/user/*'];\nconst DEFAULT_CONTENT_TYPE_PATHS: readonly string[] = ['/user/*', '/api/*'];\n\nfunction mountHooks<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, hooks: readonly AppHook<E, V>[] | undefined): void {\n for (const hook of hooks ?? []) {\n if (typeof hook === 'function') hono.use('*', hook);\n else hono.use(hook.path, hook.handler);\n }\n}\n\nfunction routerOptions(docs: DocsOptions | false | undefined): RouterOptions {\n if (docs === false) return { docs_url: null, openapi_url: null, redoc_url: null, raiseOnError: true };\n return {\n docs_url: docs?.url ?? '/docs',\n openapi_url: docs?.openapiUrl ?? '/openapi.json',\n redoc_url: null,\n raiseOnError: true,\n ...(docs?.info && { schema: { info: docs.info } }),\n };\n}\n\n/**\n * Slots 1–5: identity of the request, headers, CORS, the guards, the session.\n */\nfunction mountPlatform<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, options: ApiAppOptions<E, V>): void {\n hono.use('*', requestContext<E, V>(options));\n hono.use('*', async (c, next) => {\n (c as unknown as Context).set(ERROR_OPTIONS_KEY, options.errors ?? {});\n await next();\n });\n const headers = securityHeaders(sensitivePaths(...(options.sensitivePaths ?? ['/user/', '/api/']))) as unknown as MiddlewareHandler;\n const docsUrl = options.docs === false ? null : (options.docs?.url ?? '/docs');\n hono.use('*', async (c, next) => {\n await headers(c, next);\n // Closed: the docs page (and only it) gets the policy that admits the\n // Swagger UI assets. Every other HTML response keeps the strict one.\n if (docsUrl !== null && isDocsPath(c.req.path, docsUrl) && (c.res.headers.get('content-type') ?? '').includes('text/html')) {\n c.header('Content-Security-Policy', DOCS_CONTENT_SECURITY_POLICY);\n }\n });\n if (options.cors) {\n const exposeHeaders = [...new Set([...(options.cors.exposeHeaders ?? []), 'X-Request-Id'])];\n hono.use('*', cors({ ...options.cors, exposeHeaders }));\n }\n\n const hardening = options.hardening ?? {};\n hono.use('*', methodGuard(hardening.methods));\n hono.use('*', bodyLimitGuard(hardening.maxBodyBytes));\n for (const path of hardening.contentType?.paths ?? DEFAULT_CONTENT_TYPE_PATHS) {\n hono.use(path, contentTypeGuard(hardening.contentType?.allowed));\n }\n for (const path of hardening.origin?.paths ?? DEFAULT_ORIGIN_PATHS) {\n hono.use(path, originGuard<E>(hardening.origin));\n }\n\n if (options.d1) {\n for (const path of options.d1.paths ?? ['*']) hono.use(path, d1Bookmarks<E>(options.d1));\n }\n}\n\n/**\n * Build the app. The returned value is the chanfana router: register routes on\n * it (or in `routes`), and hand `app.fetch` the request from your entrypoint's\n * `onRequest`.\n */\nfunction createApiApp<E extends object, V extends object = object>(options: ApiAppOptions<E, V> = {}): ApiApp<E, V> {\n const hono = new Hono<FamilyEnv<E, V>>();\n hono.onError(createErrorHandler(options.errors));\n hono.notFound(createNotFoundHandler());\n\n mountPlatform(hono, options);\n\n const rules = options.rateLimits ?? [];\n const ipRules = rules.filter((entry) => entry.key === 'ip');\n const identityRules = rules.filter((entry) => entry.key !== 'ip');\n for (const rule of ipRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.beforeAuth);\n for (const [path, middleware] of Object.entries(options.auth ?? {})) hono.use(path, middleware);\n for (const rule of identityRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.afterAuth);\n\n const app = fromHono(hono, routerOptions(options.docs)) as ApiApp<E, V>;\n options.routes?.(app);\n return app;\n}\n\nexport { createApiApp, ERROR_OPTIONS_KEY };\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions };\n"],
5
+ "mappings": "+EA2BA,OAAS,YAAAA,MAAgB,WAEzB,OAAS,QAAAC,MAAY,OAErB,OAAS,QAAAC,MAAY,YACrB,OAAS,mBAAAC,EAAiB,kBAAAC,MAAsB,wBAEhD,OAAS,eAAAC,MAAmB,iBAC5B,OAAS,gCAAAC,EAA8B,cAAAC,MAAkB,YAEzD,OAAS,sBAAAC,EAAoB,yBAAAC,MAA6B,oBAC1D,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,MAAmB,iBAE3E,OAAS,iBAAAC,MAAqB,kBAE9B,OAAS,kBAAAC,MAAsB,sBA6E/B,MAAMC,EAAoB,qBAEpBC,EAA0C,CAAC,SAAS,EACpDC,EAAgD,CAAC,UAAW,QAAQ,EAE1E,SAASC,EAA+CC,EAA6BC,EAA2C,CAC9H,UAAWC,KAAQD,GAAS,CAAA,EACtB,OAAOC,GAAS,WAAYF,EAAK,IAAI,IAAKE,CAAI,EAC7CF,EAAK,IAAIE,EAAK,KAAMA,EAAK,OAAO,CAEzC,CALSC,EAAAJ,EAAA,cAOT,SAASK,EAAcC,EAAqC,CAC1D,OAAIA,IAAS,GAAc,CAAE,SAAU,KAAM,YAAa,KAAM,UAAW,KAAM,aAAc,EAAI,EAC5F,CACL,SAAUA,GAAM,KAAO,QACvB,YAAaA,GAAM,YAAc,gBACjC,UAAW,KACX,aAAc,GACd,GAAIA,GAAM,MAAQ,CAAE,OAAQ,CAAE,KAAMA,EAAK,IAAI,CAAE,EAEnD,CATSF,EAAAC,EAAA,iBAcT,SAASE,EAAkDN,EAA6BO,EAA4B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GAAG,EAAGP,EAAK,IAAIc,EAAM7B,EAAesB,EAAQ,EAAE,CAAC,CAE3F,CAlCSJ,EAAAG,EAAA,iBAyCT,SAASS,EAA0DR,EAA+B,CAAA,EAAE,CAClG,MAAMP,EAAO,IAAInB,EACjBmB,EAAK,QAAQZ,EAAmBmB,EAAQ,MAAM,CAAC,EAC/CP,EAAK,SAASX,EAAqB,CAAE,EAErCiB,EAAcN,EAAMO,CAAO,EAE3B,MAAMS,EAAQT,EAAQ,YAAc,CAAA,EAC9BU,EAAUD,EAAM,OAAQE,GAAUA,EAAM,MAAQ,IAAI,EACpDC,EAAgBH,EAAM,OAAQE,GAAUA,EAAM,MAAQ,IAAI,EAChE,UAAWE,KAAQH,EAASjB,EAAK,IAAIoB,EAAK,KAAM1B,EAAiB0B,CAAI,CAAC,EACtErB,EAAWC,EAAMO,EAAQ,OAAO,UAAU,EAC1C,SAAW,CAACO,EAAMO,CAAU,IAAK,OAAO,QAAQd,EAAQ,MAAQ,CAAA,CAAE,EAAGP,EAAK,IAAIc,EAAMO,CAAU,EAC9F,UAAWD,KAAQD,EAAenB,EAAK,IAAIoB,EAAK,KAAM1B,EAAiB0B,CAAI,CAAC,EAC5ErB,EAAWC,EAAMO,EAAQ,OAAO,SAAS,EAEzC,MAAMe,EAAM1C,EAASoB,EAAMI,EAAcG,EAAQ,IAAI,CAAC,EACtD,OAAAA,EAAQ,SAASe,CAAG,EACbA,CACT,CAnBSnB,EAAAY,EAAA",
6
+ "names": ["fromHono", "Hono", "cors", "securityHeaders", "sensitivePaths", "d1Bookmarks", "DOCS_CONTENT_SECURITY_POLICY", "isDocsPath", "createErrorHandler", "createNotFoundHandler", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "rateLimitRule", "requestContext", "ERROR_OPTIONS_KEY", "DEFAULT_ORIGIN_PATHS", "DEFAULT_CONTENT_TYPE_PATHS", "mountHooks", "hono", "hooks", "hook", "__name", "routerOptions", "docs", "mountPlatform", "options", "c", "next", "headers", "docsUrl", "exposeHeaders", "hardening", "path", "createApiApp", "rules", "ipRules", "entry", "identityRules", "rule", "middleware", "app"]
7
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The Content-Security-Policy for the Swagger UI page `createApiApp` serves.
3
+ *
4
+ * chanfana's `/docs` page is an HTML shell that loads Swagger UI's script and
5
+ * stylesheet from jsDelivr. The kit's strict HTML policy
6
+ * (`CONTENT_SECURITY_POLICY`, `script-src 'self'`) blocks both, so the page
7
+ * rendered blank: the boundary was doing its job on a page the kit itself served.
8
+ *
9
+ * The fix is a **second, narrower** policy, applied by `createApiApp` to the docs
10
+ * path and nothing else:
11
+ *
12
+ * - The only extra source is the exact Swagger UI asset directory chanfana
13
+ * references (`swagger-ui-dist@<version>/`), a CSP path source, not the whole
14
+ * CDN. A different package on the same CDN is still refused.
15
+ * - It is **closed**. There is no option to pass a policy, and the public
16
+ * `securityHeaders` middleware is unchanged. A consumer cannot loosen the CSP
17
+ * for its own pages through this door. The docs page is the kit's page, so the
18
+ * policy for it is the kit's too.
19
+ *
20
+ * The suite parses chanfana's own `getSwaggerUI` output and asserts every
21
+ * external asset is covered, so a chanfana bump that moves the Swagger UI
22
+ * version fails the test rather than blanking `/docs` again.
23
+ */
24
+ /**
25
+ The Swagger UI asset directory chanfana 3.4's `getSwaggerUI` loads from.
26
+ */
27
+ declare const SWAGGER_UI_ASSET_SOURCE = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/";
28
+ /**
29
+ * The strict HTML policy, plus the Swagger UI directory for scripts and styles.
30
+ * `'unsafe-inline'` was already in the base policy: chanfana's page boots Swagger
31
+ * UI from one inline script.
32
+ */
33
+ declare const DOCS_CONTENT_SECURITY_POLICY: string;
34
+ /**
35
+ * Whether `pathname` is the docs page. An exact match, with or without one
36
+ * trailing slash: the policy must not reach a route that merely starts with
37
+ * `/docs`.
38
+ */
39
+ declare function isDocsPath(pathname: string, docsUrl: string): boolean;
40
+ export { DOCS_CONTENT_SECURITY_POLICY, isDocsPath, SWAGGER_UI_ASSET_SOURCE };
41
+ //# sourceMappingURL=docs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docs.d.ts","sourceRoot":"","sources":["../../src/hono/docs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;EAEE;AACF,QAAA,MAAM,uBAAuB,0DAA0D,CAAC;AAExF;;;;GAIG;AACH,QAAA,MAAM,4BAA4B,QAUtB,CAAC;AAEb;;;;GAIG;AACH,iBAAS,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAG9D;AAED,OAAO,EAAE,4BAA4B,EAAE,UAAU,EAAE,uBAAuB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var r=(s,n)=>c(s,"name",{value:n,configurable:!0});const i="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/",l=["default-src 'self'","img-src 'self' data:",`style-src 'self' 'unsafe-inline' ${i}`,`script-src 'self' 'unsafe-inline' ${i}`,"object-src 'none'","form-action 'self'","base-uri 'self'","frame-ancestors 'none'","upgrade-insecure-requests"].join("; ");function o(s,n){const t=r(e=>e.length>1&&e.endsWith("/")?e.slice(0,-1):e,"normalize");return t(s)===t(n)}r(o,"isDocsPath");export{l as DOCS_CONTENT_SECURITY_POLICY,i as SWAGGER_UI_ASSET_SOURCE,o as isDocsPath};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/docs.ts"],
4
+ "sourcesContent": ["/**\n * The Content-Security-Policy for the Swagger UI page `createApiApp` serves.\n *\n * chanfana's `/docs` page is an HTML shell that loads Swagger UI's script and\n * stylesheet from jsDelivr. The kit's strict HTML policy\n * (`CONTENT_SECURITY_POLICY`, `script-src 'self'`) blocks both, so the page\n * rendered blank: the boundary was doing its job on a page the kit itself served.\n *\n * The fix is a **second, narrower** policy, applied by `createApiApp` to the docs\n * path and nothing else:\n *\n * - The only extra source is the exact Swagger UI asset directory chanfana\n * references (`swagger-ui-dist@<version>/`), a CSP path source, not the whole\n * CDN. A different package on the same CDN is still refused.\n * - It is **closed**. There is no option to pass a policy, and the public\n * `securityHeaders` middleware is unchanged. A consumer cannot loosen the CSP\n * for its own pages through this door. The docs page is the kit's page, so the\n * policy for it is the kit's too.\n *\n * The suite parses chanfana's own `getSwaggerUI` output and asserts every\n * external asset is covered, so a chanfana bump that moves the Swagger UI\n * version fails the test rather than blanking `/docs` again.\n */\n\n/**\nThe Swagger UI asset directory chanfana 3.4's `getSwaggerUI` loads from.\n*/\nconst SWAGGER_UI_ASSET_SOURCE = 'https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/';\n\n/**\n * The strict HTML policy, plus the Swagger UI directory for scripts and styles.\n * `'unsafe-inline'` was already in the base policy: chanfana's page boots Swagger\n * UI from one inline script.\n */\nconst DOCS_CONTENT_SECURITY_POLICY = [\n \"default-src 'self'\",\n \"img-src 'self' data:\",\n `style-src 'self' 'unsafe-inline' ${SWAGGER_UI_ASSET_SOURCE}`,\n `script-src 'self' 'unsafe-inline' ${SWAGGER_UI_ASSET_SOURCE}`,\n \"object-src 'none'\",\n \"form-action 'self'\",\n \"base-uri 'self'\",\n \"frame-ancestors 'none'\",\n 'upgrade-insecure-requests',\n].join('; ');\n\n/**\n * Whether `pathname` is the docs page. An exact match, with or without one\n * trailing slash: the policy must not reach a route that merely starts with\n * `/docs`.\n */\nfunction isDocsPath(pathname: string, docsUrl: string): boolean {\n const normalize = (path: string): string => (path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path);\n return normalize(pathname) === normalize(docsUrl);\n}\n\nexport { DOCS_CONTENT_SECURITY_POLICY, isDocsPath, SWAGGER_UI_ASSET_SOURCE };\n"],
5
+ "mappings": "+EA2BA,MAAMA,EAA0B,wDAO1BC,EAA+B,CACnC,qBACA,uBACA,oCAAoCD,CAAuB,GAC3D,qCAAqCA,CAAuB,GAC5D,oBACA,qBACA,kBACA,yBACA,6BACA,KAAK,IAAI,EAOX,SAASE,EAAWC,EAAkBC,EAAe,CACnD,MAAMC,EAAYC,EAACC,GAA0BA,EAAK,OAAS,GAAKA,EAAK,SAAS,GAAG,EAAIA,EAAK,MAAM,EAAG,EAAE,EAAIA,EAAvF,aAClB,OAAOF,EAAUF,CAAQ,IAAME,EAAUD,CAAO,CAClD,CAHSE,EAAAJ,EAAA",
6
+ "names": ["SWAGGER_UI_ASSET_SOURCE", "DOCS_CONTENT_SECURITY_POLICY", "isDocsPath", "pathname", "docsUrl", "normalize", "__name", "path"]
7
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The app-level error boundary: `app.onError` and `app.notFound`.
3
+ *
4
+ * Every family worker ended its chain in one of two broken places: the
5
+ * entrypoint's catch-all (a bare `Internal Error` *text* 500 the SPA cannot
6
+ * parse), or Hono's default `onError` (the same, plus a `console.error` of the
7
+ * caught value). This boundary answers the `{Exception:{Type,Message}}` envelope
8
+ * for anything that escapes a route or a middleware — including a throwing
9
+ * `beforeAuth` hook — through the kit mapper, so a failure answers identically
10
+ * whichever layer caught it.
11
+ */
12
+ import type { Context, ErrorHandler, NotFoundHandler } from 'hono';
13
+ import type { ErrorMapperOptions } from '../ErrorMapper.ts';
14
+ /**
15
+ * Map, log and answer one failure on a Hono context. Shared by `onError` and
16
+ * `FamilyRoute`, so both produce byte-identical envelopes.
17
+ */
18
+ declare function respondWithError(c: Context, error: unknown, options?: ErrorMapperOptions): Response;
19
+ declare function createErrorHandler(options?: ErrorMapperOptions): ErrorHandler;
20
+ /**
21
+ A miss is a `404 NotFound` envelope, never Hono's `404 Not Found` text.
22
+ */
23
+ declare function createNotFoundHandler(): NotFoundHandler;
24
+ export { createErrorHandler, createNotFoundHandler, respondWithError };
25
+ //# sourceMappingURL=errorHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errorHandler.d.ts","sourceRoot":"","sources":["../../src/hono/errorHandler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAGnE,OAAO,KAAK,EAAE,kBAAkB,EAAe,MAAM,mBAAmB,CAAC;AAkBzE;;;GAGG;AACH,iBAAS,gBAAgB,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,GAAE,kBAAuB,GAAG,QAAQ,CAKhG;AAED,iBAAS,kBAAkB,CAAC,OAAO,GAAE,kBAAuB,GAAG,YAAY,CAE1E;AAED;;EAEE;AACF,iBAAS,qBAAqB,IAAI,eAAe,CAGhD;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var s=(r,e)=>a(r,"name",{value:e,configurable:!0});import{NotFoundError as d}from"@rexezuge/errors";import{mapError as i}from"../ErrorMapper.js";function f(r,e,o){if(!r)return;const t={type:e.error.type,status:e.status,requestId:o};e.status>=500?r.error("Request failed with a server error",t):r.warn("Request rejected",t)}s(f,"logMapped");function n(r,e,o={}){const t=i(e,o),u=o.toResponse?.(t.error,t.status);return f(r.get("logger"),t,r.get("requestId")),u??Response.json(t.body,{status:t.status,headers:t.headers})}s(n,"respondWithError");function c(r={}){return(e,o)=>n(o,e,r)}s(c,"createErrorHandler");function p(){return r=>n(r,new d(`No route matches ${r.req.method} ${new URL(r.req.url).pathname}.`))}s(p,"createNotFoundHandler");export{c as createErrorHandler,p as createNotFoundHandler,n as respondWithError};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/errorHandler.ts"],
4
+ "sourcesContent": ["/**\n * The app-level error boundary: `app.onError` and `app.notFound`.\n *\n * Every family worker ended its chain in one of two broken places: the\n * entrypoint's catch-all (a bare `Internal Error` *text* 500 the SPA cannot\n * parse), or Hono's default `onError` (the same, plus a `console.error` of the\n * caught value). This boundary answers the `{Exception:{Type,Message}}` envelope\n * for anything that escapes a route or a middleware — including a throwing\n * `beforeAuth` hook — through the kit mapper, so a failure answers identically\n * whichever layer caught it.\n */\nimport type { Context, ErrorHandler, NotFoundHandler } from 'hono';\nimport { NotFoundError } from '@rexezuge/errors';\nimport { mapError } from '../ErrorMapper.ts';\nimport type { ErrorMapperOptions, MappedError } from '../ErrorMapper.ts';\nimport type { HttpLogger } from './types.ts';\n\n/**\n * Log one mapped failure. Static message, plain fields: the caught value and its\n * message never reach the sink (a D1 message names tables; an upstream body can\n * carry a token).\n */\nfunction logMapped(logger: HttpLogger | undefined, mapped: MappedError, requestId: string | undefined): void {\n if (!logger) return;\n const fields = { type: mapped.error.type, status: mapped.status, requestId };\n if (mapped.status >= 500) {\n logger.error('Request failed with a server error', fields);\n } else {\n logger.warn('Request rejected', fields);\n }\n}\n\n/**\n * Map, log and answer one failure on a Hono context. Shared by `onError` and\n * `FamilyRoute`, so both produce byte-identical envelopes.\n */\nfunction respondWithError(c: Context, error: unknown, options: ErrorMapperOptions = {}): Response {\n const mapped = mapError(error, options);\n const custom = options.toResponse?.(mapped.error, mapped.status);\n logMapped(c.get('logger') as HttpLogger | undefined, mapped, c.get('requestId') as string | undefined);\n return custom ?? Response.json(mapped.body, { status: mapped.status, headers: mapped.headers });\n}\n\nfunction createErrorHandler(options: ErrorMapperOptions = {}): ErrorHandler {\n return (error: unknown, c: Context): Response => respondWithError(c, error, options);\n}\n\n/**\nA miss is a `404 NotFound` envelope, never Hono's `404 Not Found` text.\n*/\nfunction createNotFoundHandler(): NotFoundHandler {\n return (c: Context): Response =>\n respondWithError(c, new NotFoundError(`No route matches ${c.req.method} ${new URL(c.req.url).pathname}.`));\n}\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError };\n"],
5
+ "mappings": "+EAYA,OAAS,iBAAAA,MAAqB,mBAC9B,OAAS,YAAAC,MAAgB,oBASzB,SAASC,EAAUC,EAAgCC,EAAqBC,EAA6B,CACnG,GAAI,CAACF,EAAQ,OACb,MAAMG,EAAS,CAAE,KAAMF,EAAO,MAAM,KAAM,OAAQA,EAAO,OAAQ,UAAAC,CAAS,EACtED,EAAO,QAAU,IACnBD,EAAO,MAAM,qCAAsCG,CAAM,EAEzDH,EAAO,KAAK,mBAAoBG,CAAM,CAE1C,CARSC,EAAAL,EAAA,aAcT,SAASM,EAAiBC,EAAYC,EAAgBC,EAA8B,CAAA,EAAE,CACpF,MAAMP,EAASH,EAASS,EAAOC,CAAO,EAChCC,EAASD,EAAQ,aAAaP,EAAO,MAAOA,EAAO,MAAM,EAC/D,OAAAF,EAAUO,EAAE,IAAI,QAAQ,EAA6BL,EAAQK,EAAE,IAAI,WAAW,CAAuB,EAC9FG,GAAU,SAAS,KAAKR,EAAO,KAAM,CAAE,OAAQA,EAAO,OAAQ,QAASA,EAAO,OAAO,CAAE,CAChG,CALSG,EAAAC,EAAA,oBAOT,SAASK,EAAmBF,EAA8B,CAAA,EAAE,CAC1D,MAAO,CAACD,EAAgBD,IAAyBD,EAAiBC,EAAGC,EAAOC,CAAO,CACrF,CAFSJ,EAAAM,EAAA,sBAOT,SAASC,GAAqB,CAC5B,OAAQL,GACND,EAAiBC,EAAG,IAAIT,EAAc,oBAAoBS,EAAE,IAAI,MAAM,IAAI,IAAI,IAAIA,EAAE,IAAI,GAAG,EAAE,QAAQ,GAAG,CAAC,CAC7G,CAHSF,EAAAO,EAAA",
6
+ "names": ["NotFoundError", "mapError", "logMapped", "logger", "mapped", "requestId", "fields", "__name", "respondWithError", "c", "error", "options", "custom", "createErrorHandler", "createNotFoundHandler"]
7
+ }
@@ -0,0 +1,51 @@
1
+ import type { MiddlewareHandler } from 'hono';
2
+ import type { FromEnv } from './types.ts';
3
+ interface OriginPolicy<E> {
4
+ /**
5
+ The cookie-authenticated surfaces to guard. Defaults to `['/user/*']`.
6
+ */
7
+ paths?: readonly string[];
8
+ /**
9
+ Origins trusted besides the request's own (a Pages origin, a custom domain).
10
+ */
11
+ allowedOrigins?: FromEnv<E, readonly string[]>;
12
+ /**
13
+ Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.
14
+ */
15
+ allowMissingOrigin?: boolean;
16
+ }
17
+ interface ContentTypePolicy {
18
+ /**
19
+ Where JSON mutations are enforced. Defaults to `['/user/*', '/api/*']`.
20
+ */
21
+ paths?: readonly string[];
22
+ /**
23
+ The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.
24
+ */
25
+ allowed?: readonly string[];
26
+ }
27
+ interface HardeningOptions<E> {
28
+ /**
29
+ The methods the app answers. Defaults to {@link DEFAULT_ALLOWED_METHODS}.
30
+ */
31
+ methods?: readonly string[];
32
+ /**
33
+ The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB.
34
+ */
35
+ maxBodyBytes?: number;
36
+ contentType?: ContentTypePolicy;
37
+ origin?: OriginPolicy<E>;
38
+ }
39
+ declare function methodGuard(methods?: readonly string[]): MiddlewareHandler;
40
+ /**
41
+ * The declared-length check first (cheap, no read), then Hono's streaming cap
42
+ * for a chunked body that declares nothing.
43
+ */
44
+ declare function bodyLimitGuard(maxBytes?: number): MiddlewareHandler;
45
+ declare function contentTypeGuard(allowed?: readonly string[]): MiddlewareHandler;
46
+ declare function originGuard<E extends object>(policy?: OriginPolicy<E>): MiddlewareHandler<{
47
+ Bindings: E;
48
+ }>;
49
+ export { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard };
50
+ export type { ContentTypePolicy, HardeningOptions, OriginPolicy };
51
+ //# sourceMappingURL=hardening.d.ts.map