@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.
Files changed (65) hide show
  1. package/README.md +146 -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/createApiApp.d.ts +93 -0
  23. package/dist/hono/createApiApp.d.ts.map +1 -0
  24. package/dist/hono/createApiApp.js +1 -0
  25. package/dist/hono/createApiApp.js.map +7 -0
  26. package/dist/hono/errorHandler.d.ts +25 -0
  27. package/dist/hono/errorHandler.d.ts.map +1 -0
  28. package/dist/hono/errorHandler.js +1 -0
  29. package/dist/hono/errorHandler.js.map +7 -0
  30. package/dist/hono/hardening.d.ts +51 -0
  31. package/dist/hono/hardening.d.ts.map +1 -0
  32. package/dist/hono/hardening.js +1 -0
  33. package/dist/hono/hardening.js.map +7 -0
  34. package/dist/hono/index.d.ts +33 -0
  35. package/dist/hono/index.d.ts.map +1 -0
  36. package/dist/hono/index.js +1 -0
  37. package/dist/hono/index.js.map +7 -0
  38. package/dist/hono/rateLimits.d.ts +63 -0
  39. package/dist/hono/rateLimits.d.ts.map +1 -0
  40. package/dist/hono/rateLimits.js +1 -0
  41. package/dist/hono/rateLimits.js.map +7 -0
  42. package/dist/hono/requestContext.d.ts +28 -0
  43. package/dist/hono/requestContext.d.ts.map +1 -0
  44. package/dist/hono/requestContext.js +1 -0
  45. package/dist/hono/requestContext.js.map +7 -0
  46. package/dist/hono/types.d.ts +69 -0
  47. package/dist/hono/types.d.ts.map +1 -0
  48. package/dist/hono/types.js +1 -0
  49. package/dist/hono/types.js.map +7 -0
  50. package/dist/index.d.ts +20 -4
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +1 -1
  53. package/dist/index.js.map +3 -3
  54. package/dist/openApiErrors.d.ts +63 -0
  55. package/dist/openApiErrors.d.ts.map +1 -0
  56. package/dist/openApiErrors.js +1 -0
  57. package/dist/openApiErrors.js.map +7 -0
  58. package/dist/requestGuards.d.ts +52 -0
  59. package/dist/requestGuards.d.ts.map +1 -0
  60. package/dist/requestGuards.js +1 -0
  61. package/dist/requestGuards.js.map +7 -0
  62. package/dist/routeBase.d.ts.map +1 -1
  63. package/dist/routeBase.js +1 -1
  64. package/dist/routeBase.js.map +3 -3
  65. package/package.json +12 -5
@@ -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,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":"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"}
@@ -0,0 +1 @@
1
+ var p=Object.defineProperty;var u=(r,e)=>p(r,"name",{value:e,configurable:!0});import{fromHono as m}from"chanfana";import{Hono as d}from"hono";import{cors as h}from"hono/cors";import{securityHeaders as _,sensitivePaths as y}from"../securityHeaders.js";import{d1Bookmarks as T}from"./bookmarks.js";import{createErrorHandler as E,createNotFoundHandler as H}from"./errorHandler.js";import{bodyLimitGuard as O,contentTypeGuard as k,methodGuard as A,originGuard as R}from"./hardening.js";import{rateLimitRule as i}from"./rateLimits.js";import{requestContext as P}from"./requestContext.js";const f="errorMapperOptions",g=["/user/*"],w=["/user/*","/api/*"];function c(r,e){for(const t of e??[])typeof t=="function"?r.use("*",t):r.use(t.path,t.handler)}u(c,"mountHooks");function x(r){return r===!1?{docs_url:null,openapi_url:null,redoc_url:null,raiseOnError:!0}:{docs_url:r?.url??"/docs",openapi_url:r?.openapiUrl??"/openapi.json",redoc_url:null,raiseOnError:!0,...r?.info&&{schema:{info:r.info}}}}u(x,"routerOptions");function G(r,e){if(r.use("*",P(e)),r.use("*",async(o,n)=>{o.set(f,e.errors??{}),await n()}),r.use("*",_(y(...e.sensitivePaths??["/user/","/api/"]))),e.cors){const o=[...new Set([...e.cors.exposeHeaders??[],"X-Request-Id"])];r.use("*",h({...e.cors,exposeHeaders:o}))}const t=e.hardening??{};r.use("*",A(t.methods)),r.use("*",O(t.maxBodyBytes));for(const o of t.contentType?.paths??w)r.use(o,k(t.contentType?.allowed));for(const o of t.origin?.paths??g)r.use(o,R(t.origin));if(e.d1)for(const o of e.d1.paths??["*"])r.use(o,T(e.d1))}u(G,"mountPlatform");function L(r={}){const e=new d;e.onError(E(r.errors)),e.notFound(H()),G(e,r);const t=r.rateLimits??[],o=t.filter(s=>s.key==="ip"),n=t.filter(s=>s.key!=="ip");for(const s of o)e.use(s.path,i(s));c(e,r.hooks?.beforeAuth);for(const[s,l]of Object.entries(r.auth??{}))e.use(s,l);for(const s of n)e.use(s.path,i(s));c(e,r.hooks?.afterAuth);const a=m(e,x(r.docs));return r.routes?.(a),a}u(L,"createApiApp");export{f as ERROR_OPTIONS_KEY,L 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 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 hono.use('*', securityHeaders(sensitivePaths(...(options.sensitivePaths ?? ['/user/', '/api/']))) as unknown as MiddlewareHandler);\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": "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",
6
+ "names": ["fromHono", "Hono", "cors", "securityHeaders", "sensitivePaths", "d1Bookmarks", "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", "exposeHeaders", "hardening", "path", "createApiApp", "rules", "ipRules", "entry", "identityRules", "rule", "middleware", "app"]
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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hardening.d.ts","sourceRoot":"","sources":["../../src/hono/hardening.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAW9C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,UAAU,YAAY,CAAC,CAAC;IACtB;;MAEE;IACF,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B;;MAEE;IACF,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;IAC/C;;MAEE;IACF,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,UAAU,iBAAiB;IACzB;;MAEE;IACF,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B;;MAEE;IACF,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7B;AAED,UAAU,gBAAgB,CAAC,CAAC;IAC1B;;MAEE;IACF,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B;;MAEE;IACF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,MAAM,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;CAC1B;AAED,iBAAS,WAAW,CAAC,OAAO,GAAE,SAAS,MAAM,EAA4B,GAAG,iBAAiB,CAM5F;AAED;;;GAGG;AACH,iBAAS,cAAc,CAAC,QAAQ,GAAE,MAA+B,GAAG,iBAAiB,CAepF;AAED,iBAAS,gBAAgB,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,iBAAiB,CAMxE;AAED,iBAAS,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,GAAE,YAAY,CAAC,CAAC,CAAM,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAOvG;AAED,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC;AACtE,YAAY,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var i=(r,n)=>a(r,"name",{value:n,configurable:!0});import{bodyLimit as c}from"hono/body-limit";import{PayloadTooLargeError as s}from"@rexezuge/errors";import{checkContentLength as w,checkContentType as d,checkMethod as u,checkOrigin as f,DEFAULT_ALLOWED_METHODS as g,DEFAULT_MAX_BODY_BYTES as h}from"../requestGuards.js";import{resolveFromEnv as m}from"./types.js";function l(r=g){return async(n,e)=>{const o=u(n.req.method,r);if(o)throw o;await e()}}i(l,"methodGuard");function E(r=h){if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Invalid maxBodyBytes: ${String(r)} (must be a positive integer)`);const n=c({maxSize:r,onError:i(()=>{throw new s},"onError")});return async(e,o)=>{const t=w(e.req.raw,r);if(t)throw t;return n(e,o)}}i(E,"bodyLimitGuard");function O(r){return async(n,e)=>{const o=d(n.req.raw,r);if(o)throw o;await e()}}i(O,"contentTypeGuard");function L(r={}){return async(n,e)=>{const o=r.allowedOrigins===void 0?[]:m(r.allowedOrigins,n.env),t=f(n.req.raw,{allowedOrigins:o,allowMissingOrigin:r.allowMissingOrigin});if(t)throw t;await e()}}i(L,"originGuard");export{E as bodyLimitGuard,O as contentTypeGuard,l as methodGuard,L as originGuard};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/hardening.ts"],
4
+ "sourcesContent": ["/**\n * The request-hardening middleware: the Hono form of `../requestGuards.ts`.\n *\n * Converged from `apps/api/src/middleware/HttpHardening.ts` (Mail-Bee, Mail-Meow,\n * Mail-Otter, Pigeongram), AWS-AccessBridge's `RequestGuards.ts`, Image-Host's\n * `csrfProtectionHandler` and Pigeongram's `session/origin.ts`. Each guard\n * **throws** its `ServiceError` rather than answering, so the rejection reaches\n * `app.onError` and leaves in the same envelope (and with the same security\n * headers and request id) as every other failure.\n */\nimport { bodyLimit } from 'hono/body-limit';\nimport type { MiddlewareHandler } from 'hono';\nimport { PayloadTooLargeError } from '@rexezuge/errors';\nimport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from '../requestGuards.ts';\nimport { resolveFromEnv } from './types.ts';\nimport type { FromEnv } from './types.ts';\n\ninterface OriginPolicy<E> {\n /**\n The cookie-authenticated surfaces to guard. Defaults to `['/user/*']`.\n */\n paths?: readonly string[];\n /**\n Origins trusted besides the request's own (a Pages origin, a custom domain).\n */\n allowedOrigins?: FromEnv<E, readonly string[]>;\n /**\n Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.\n */\n allowMissingOrigin?: boolean;\n}\n\ninterface ContentTypePolicy {\n /**\n Where JSON mutations are enforced. Defaults to `['/user/*', '/api/*']`.\n */\n paths?: readonly string[];\n /**\n The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.\n */\n allowed?: readonly string[];\n}\n\ninterface HardeningOptions<E> {\n /**\n The methods the app answers. Defaults to {@link DEFAULT_ALLOWED_METHODS}.\n */\n methods?: readonly string[];\n /**\n The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB.\n */\n maxBodyBytes?: number;\n contentType?: ContentTypePolicy;\n origin?: OriginPolicy<E>;\n}\n\nfunction methodGuard(methods: readonly string[] = DEFAULT_ALLOWED_METHODS): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkMethod(c.req.method, methods);\n if (rejection) throw rejection;\n await next();\n };\n}\n\n/**\n * The declared-length check first (cheap, no read), then Hono's streaming cap\n * for a chunked body that declares nothing.\n */\nfunction bodyLimitGuard(maxBytes: number = DEFAULT_MAX_BODY_BYTES): MiddlewareHandler {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new Error(`Invalid maxBodyBytes: ${String(maxBytes)} (must be a positive integer)`);\n }\n const streamed = bodyLimit({\n maxSize: maxBytes,\n onError: (): never => {\n throw new PayloadTooLargeError();\n },\n });\n return async (c, next): Promise<Response | void> => {\n const rejection = checkContentLength(c.req.raw, maxBytes);\n if (rejection) throw rejection;\n return streamed(c, next);\n };\n}\n\nfunction contentTypeGuard(allowed?: readonly string[]): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkContentType(c.req.raw, allowed);\n if (rejection) throw rejection;\n await next();\n };\n}\n\nfunction originGuard<E extends object>(policy: OriginPolicy<E> = {}): MiddlewareHandler<{ Bindings: E }> {\n return async (c, next): Promise<void> => {\n const allowedOrigins = policy.allowedOrigins === undefined ? [] : resolveFromEnv(policy.allowedOrigins, c.env);\n const rejection = checkOrigin(c.req.raw, { allowedOrigins, allowMissingOrigin: policy.allowMissingOrigin });\n if (rejection) throw rejection;\n await next();\n };\n}\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard };\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy };\n"],
5
+ "mappings": "+EAUA,OAAS,aAAAA,MAAiB,kBAE1B,OAAS,wBAAAC,MAA4B,mBACrC,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,sBACP,OAAS,kBAAAC,MAAsB,aA0C/B,SAASC,EAAYC,EAA6BJ,EAAuB,CACvE,MAAO,OAAOK,EAAGC,IAAuB,CACtC,MAAMC,EAAYT,EAAYO,EAAE,IAAI,OAAQD,CAAO,EACnD,GAAIG,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAL,EAAA,eAYT,SAASM,EAAeC,EAAmBT,EAAsB,CAC/D,GAAI,CAAC,OAAO,cAAcS,CAAQ,GAAKA,GAAY,EACjD,MAAM,IAAI,MAAM,yBAAyB,OAAOA,CAAQ,CAAC,+BAA+B,EAE1F,MAAMC,EAAWjB,EAAU,CACzB,QAASgB,EACT,QAASF,EAAA,IAAY,CACnB,MAAM,IAAIb,CACZ,EAFS,WAGV,EACD,MAAO,OAAOU,EAAGC,IAAkC,CACjD,MAAMC,EAAYX,EAAmBS,EAAE,IAAI,IAAKK,CAAQ,EACxD,GAAIH,EAAW,MAAMA,EACrB,OAAOI,EAASN,EAAGC,CAAI,CACzB,CACF,CAfSE,EAAAC,EAAA,kBAiBT,SAASG,EAAiBC,EAA2B,CACnD,MAAO,OAAOR,EAAGC,IAAuB,CACtC,MAAMC,EAAYV,EAAiBQ,EAAE,IAAI,IAAKQ,CAAO,EACrD,GAAIN,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAI,EAAA,oBAQT,SAASE,EAA8BC,EAA0B,CAAA,EAAE,CACjE,MAAO,OAAOV,EAAGC,IAAuB,CACtC,MAAMU,EAAiBD,EAAO,iBAAmB,OAAY,CAAA,EAAKb,EAAea,EAAO,eAAgBV,EAAE,GAAG,EACvGE,EAAYR,EAAYM,EAAE,IAAI,IAAK,CAAE,eAAAW,EAAgB,mBAAoBD,EAAO,kBAAkB,CAAE,EAC1G,GAAIR,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CAPSE,EAAAM,EAAA",
6
+ "names": ["bodyLimit", "PayloadTooLargeError", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "resolveFromEnv", "methodGuard", "methods", "c", "next", "rejection", "__name", "bodyLimitGuard", "maxBytes", "streamed", "contentTypeGuard", "allowed", "originGuard", "policy", "allowedOrigins"]
7
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `@rexezuge/http/hono` — the Hono + chanfana app kernel.
3
+ *
4
+ * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,
5
+ * so the root barrel stays framework-free. `hono` and `chanfana` are optional
6
+ * peers of the package and **required** by a repo that imports this subpath.
7
+ *
8
+ * | Export | Replaces |
9
+ * | ------------------------------- | ------------------------------------------------------------------------ |
10
+ * | `createApiApp` | each API worker's hand-assembled constructor stack |
11
+ * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |
12
+ * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |
13
+ * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |
14
+ * | `d1Bookmarks` | the `onRequest` D1-session blocks |
15
+ * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |
16
+ */
17
+ export { createApiApp } from './createApiApp.ts';
18
+ export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';
19
+ export { FamilyRoute } from './FamilyRoute.ts';
20
+ export type { RouteResult } from './FamilyRoute.ts';
21
+ export { accessAuth, apiKeyAuth } from './auth.ts';
22
+ export type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';
23
+ export { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';
24
+ export type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';
25
+ export { d1Bookmarks } from './bookmarks.ts';
26
+ export type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';
27
+ export { rateLimitRule } from './rateLimits.ts';
28
+ export type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';
29
+ export { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';
30
+ export { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';
31
+ export type { RequestContextOptions } from './requestContext.ts';
32
+ export type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hono/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElG,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACnD,YAAY,EAAE,2BAA2B,EAAE,iBAAiB,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5G,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC5F,YAAY,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAExF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEvG,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEhG,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACvF,YAAY,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAEjE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1 @@
1
+ import{createApiApp as e}from"./createApiApp.js";import{FamilyRoute as a}from"./FamilyRoute.js";import{accessAuth as m,apiKeyAuth as d}from"./auth.js";import{bodyLimitGuard as u,contentTypeGuard as n,methodGuard as x,originGuard as f}from"./hardening.js";import{d1Bookmarks as s}from"./bookmarks.js";import{rateLimitRule as l}from"./rateLimits.js";import{createErrorHandler as h,createNotFoundHandler as y,respondWithError as G}from"./errorHandler.js";import{consoleLogger as g,requestContext as H,REQUEST_ID_HEADER as L}from"./requestContext.js";export{a as FamilyRoute,L as REQUEST_ID_HEADER,m as accessAuth,d as apiKeyAuth,u as bodyLimitGuard,g as consoleLogger,n as contentTypeGuard,e as createApiApp,h as createErrorHandler,y as createNotFoundHandler,s as d1Bookmarks,x as methodGuard,f as originGuard,l as rateLimitRule,H as requestContext,G as respondWithError};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/index.ts"],
4
+ "sourcesContent": ["/**\n * `@rexezuge/http/hono` — the Hono + chanfana app kernel.\n *\n * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,\n * so the root barrel stays framework-free. `hono` and `chanfana` are optional\n * peers of the package and **required** by a repo that imports this subpath.\n *\n * | Export | Replaces |\n * | ------------------------------- | ------------------------------------------------------------------------ |\n * | `createApiApp` | each API worker's hand-assembled constructor stack |\n * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |\n * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |\n * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |\n * | `d1Bookmarks` | the `onRequest` D1-session blocks |\n * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |\n */\nexport { createApiApp } from './createApiApp.ts';\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { RouteResult } from './FamilyRoute.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
5
+ "mappings": "AAgBA,OAAS,gBAAAA,MAAoB,oBAG7B,OAAS,eAAAC,MAAmB,mBAG5B,OAAS,cAAAC,EAAY,cAAAC,MAAkB,YAGvC,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,MAAmB,iBAG3E,OAAS,eAAAC,MAAmB,iBAG5B,OAAS,iBAAAC,MAAqB,kBAG9B,OAAS,sBAAAC,EAAoB,yBAAAC,EAAuB,oBAAAC,MAAwB,oBAE5E,OAAS,iBAAAC,EAAe,kBAAAC,EAAgB,qBAAAC,MAAyB",
6
+ "names": ["createApiApp", "FamilyRoute", "accessAuth", "apiKeyAuth", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "d1Bookmarks", "rateLimitRule", "createErrorHandler", "createNotFoundHandler", "respondWithError", "consoleLogger", "requestContext", "REQUEST_ID_HEADER"]
7
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Rate-limit rules: the native `ratelimits` binding where configured, the kit's
3
+ * in-isolate limiter as the fallback (RFC 0001, backend conventions).
4
+ *
5
+ * Converged from the per-surface limiters in the four `HttpHardening.ts` copies
6
+ * and AWS-AccessBridge's `rateLimitHandler` (native binding, IP-keyed, before
7
+ * auth). The two disagreed about *when* a limiter runs, and both were right for
8
+ * their surface — so a rule declares its key and the key decides the slot:
9
+ *
10
+ * - `key: 'ip'` runs **before** auth. It protects the auth step itself (a PAT
11
+ * lookup per request is a D1 spend an anonymous caller controls).
12
+ * - `key: 'identity'` (the default) runs **after** auth, keyed on
13
+ * `AuthenticatedUserEmailAddress`. Installed before auth it would see no
14
+ * identity and put every operator behind one NAT in a shared bucket.
15
+ */
16
+ import type { MiddlewareHandler } from 'hono';
17
+ import type { RateLimitContext } from '../rateLimit.ts';
18
+ /**
19
+ The native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).
20
+ */
21
+ interface NativeRateLimiter {
22
+ limit(options: {
23
+ key: string;
24
+ }): Promise<{
25
+ success: boolean;
26
+ }>;
27
+ }
28
+ interface RateLimitRule<E> {
29
+ /**
30
+ The Hono path pattern the rule guards (`'/user/*'`).
31
+ */
32
+ path: string;
33
+ /**
34
+ The bucket namespace; two rules never share one.
35
+ */
36
+ keyPrefix: string;
37
+ /**
38
+ The in-isolate window. Mirror the binding's `period` when one is configured.
39
+ */
40
+ windowMs: number;
41
+ /**
42
+ The in-isolate budget, or a per-request resolver (`env` is not known at construction).
43
+ */
44
+ max: number | ((c: RateLimitContext) => number);
45
+ /**
46
+ What the bucket is keyed on, and therefore which slot the rule runs in.
47
+ */
48
+ key?: 'identity' | 'ip';
49
+ /**
50
+ The native binding, when configured. Absent → the in-isolate limiter answers.
51
+ */
52
+ binding?: (env: E) => NativeRateLimiter | undefined;
53
+ }
54
+ /**
55
+ * One rule's middleware. A native limiter that throws **fails open**, like the
56
+ * in-isolate limiter: a broken limiter must not become an outage.
57
+ */
58
+ declare function rateLimitRule<E extends object>(rule: RateLimitRule<E>): MiddlewareHandler<{
59
+ Bindings: E;
60
+ }>;
61
+ export { rateLimitRule };
62
+ export type { NativeRateLimiter, RateLimitRule };
63
+ //# sourceMappingURL=rateLimits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rateLimits.d.ts","sourceRoot":"","sources":["../../src/hono/rateLimits.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAE9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD;;EAEE;AACF,UAAU,iBAAiB;IACzB,KAAK,CAAC,OAAO,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAChE;AAED,UAAU,aAAa,CAAC,CAAC;IACvB;;MAEE;IACF,IAAI,EAAE,MAAM,CAAC;IACb;;MAEE;IACF,SAAS,EAAE,MAAM,CAAC;IAClB;;MAEE;IACF,QAAQ,EAAE,MAAM,CAAC;IACjB;;MAEE;IACF,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,gBAAgB,KAAK,MAAM,CAAC,CAAC;IAChD;;MAEE;IACF,GAAG,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;IACxB;;MAEE;IACF,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,GAAG,SAAS,CAAC;CACrD;AAMD;;;GAGG;AACH,iBAAS,aAAa,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAkBnG;AAED,OAAO,EAAE,aAAa,EAAE,CAAC;AACzB,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var f=Object.defineProperty;var r=(t,i)=>f(t,"name",{value:i,configurable:!0});import{clientIp as m,rateLimit as w}from"../rateLimit.js";function p(t){return{Exception:{Type:"RateLimited",Message:`Too many requests. Retry after ${t}s.`}}}r(p,"throttledBody");function u(t){const i=w({windowMs:t.windowMs,max:t.max,keyPrefix:t.keyPrefix}),a=Math.max(1,Math.ceil(t.windowMs/1e3));return async(e,s)=>{const o=t.binding?.(e.env);if(!o)return i(e,s);const d=t.key==="ip"?void 0:e.get("AuthenticatedUserEmailAddress"),y=`${t.keyPrefix}:${d??`ip:${m(c=>e.req.header(c))}`}`;let n=!0;try{n=(await o.limit({key:y})).success}catch{n=!0}if(!n)return e.json(p(a),429,{"Retry-After":String(a)});await s()}}r(u,"rateLimitRule");export{u as rateLimitRule};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/rateLimits.ts"],
4
+ "sourcesContent": ["/**\n * Rate-limit rules: the native `ratelimits` binding where configured, the kit's\n * in-isolate limiter as the fallback (RFC 0001, backend conventions).\n *\n * Converged from the per-surface limiters in the four `HttpHardening.ts` copies\n * and AWS-AccessBridge's `rateLimitHandler` (native binding, IP-keyed, before\n * auth). The two disagreed about *when* a limiter runs, and both were right for\n * their surface — so a rule declares its key and the key decides the slot:\n *\n * - `key: 'ip'` runs **before** auth. It protects the auth step itself (a PAT\n * lookup per request is a D1 spend an anonymous caller controls).\n * - `key: 'identity'` (the default) runs **after** auth, keyed on\n * `AuthenticatedUserEmailAddress`. Installed before auth it would see no\n * identity and put every operator behind one NAT in a shared bucket.\n */\nimport type { MiddlewareHandler } from 'hono';\nimport { clientIp, rateLimit } from '../rateLimit.ts';\nimport type { RateLimitContext } from '../rateLimit.ts';\n\n/**\nThe native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).\n*/\ninterface NativeRateLimiter {\n limit(options: { key: string }): Promise<{ success: boolean }>;\n}\n\ninterface RateLimitRule<E> {\n /**\n The Hono path pattern the rule guards (`'/user/*'`).\n */\n path: string;\n /**\n The bucket namespace; two rules never share one.\n */\n keyPrefix: string;\n /**\n The in-isolate window. Mirror the binding's `period` when one is configured.\n */\n windowMs: number;\n /**\n The in-isolate budget, or a per-request resolver (`env` is not known at construction).\n */\n max: number | ((c: RateLimitContext) => number);\n /**\n What the bucket is keyed on, and therefore which slot the rule runs in.\n */\n key?: 'identity' | 'ip';\n /**\n The native binding, when configured. Absent → the in-isolate limiter answers.\n */\n binding?: (env: E) => NativeRateLimiter | undefined;\n}\n\nfunction throttledBody(retryAfter: number): { Exception: { Type: string; Message: string } } {\n return { Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } };\n}\n\n/**\n * One rule's middleware. A native limiter that throws **fails open**, like the\n * in-isolate limiter: a broken limiter must not become an outage.\n */\nfunction rateLimitRule<E extends object>(rule: RateLimitRule<E>): MiddlewareHandler<{ Bindings: E }> {\n const fallback = rateLimit({ windowMs: rule.windowMs, max: rule.max, keyPrefix: rule.keyPrefix });\n const retryAfter = Math.max(1, Math.ceil(rule.windowMs / 1000));\n return async (c, next): Promise<Response | void> => {\n const native = rule.binding?.(c.env);\n if (!native) return fallback(c, next);\n\n const identity = rule.key === 'ip' ? undefined : (c.get('AuthenticatedUserEmailAddress' as never) as string | undefined);\n const key = `${rule.keyPrefix}:${identity ?? `ip:${clientIp((name) => c.req.header(name))}`}`;\n let allowed = true;\n try {\n allowed = (await native.limit({ key })).success;\n } catch {\n allowed = true;\n }\n if (!allowed) return c.json(throttledBody(retryAfter), 429, { 'Retry-After': String(retryAfter) });\n await next();\n };\n}\n\nexport { rateLimitRule };\nexport type { NativeRateLimiter, RateLimitRule };\n"],
5
+ "mappings": "+EAgBA,OAAS,YAAAA,EAAU,aAAAC,MAAiB,kBAqCpC,SAASC,EAAcC,EAAkB,CACvC,MAAO,CAAE,UAAW,CAAE,KAAM,cAAe,QAAS,kCAAkCA,CAAU,IAAI,CAAE,CACxG,CAFSC,EAAAF,EAAA,iBAQT,SAASG,EAAgCC,EAAsB,CAC7D,MAAMC,EAAWN,EAAU,CAAE,SAAUK,EAAK,SAAU,IAAKA,EAAK,IAAK,UAAWA,EAAK,SAAS,CAAE,EAC1FH,EAAa,KAAK,IAAI,EAAG,KAAK,KAAKG,EAAK,SAAW,GAAI,CAAC,EAC9D,MAAO,OAAOE,EAAGC,IAAkC,CACjD,MAAMC,EAASJ,EAAK,UAAUE,EAAE,GAAG,EACnC,GAAI,CAACE,EAAQ,OAAOH,EAASC,EAAGC,CAAI,EAEpC,MAAME,EAAWL,EAAK,MAAQ,KAAO,OAAaE,EAAE,IAAI,+BAAwC,EAC1FI,EAAM,GAAGN,EAAK,SAAS,IAAIK,GAAY,MAAMX,EAAUa,GAASL,EAAE,IAAI,OAAOK,CAAI,CAAC,CAAC,EAAE,GAC3F,IAAIC,EAAU,GACd,GAAI,CACFA,GAAW,MAAMJ,EAAO,MAAM,CAAE,IAAAE,CAAG,CAAE,GAAG,OAC1C,MAAQ,CACNE,EAAU,EACZ,CACA,GAAI,CAACA,EAAS,OAAON,EAAE,KAAKN,EAAcC,CAAU,EAAG,IAAK,CAAE,cAAe,OAAOA,CAAU,CAAC,CAAE,EACjG,MAAMM,EAAI,CACZ,CACF,CAlBSL,EAAAC,EAAA",
6
+ "names": ["clientIp", "rateLimit", "throttledBody", "retryAfter", "__name", "rateLimitRule", "rule", "fallback", "c", "next", "native", "identity", "key", "name", "allowed"]
7
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The first middleware: a correlation id and a request-scoped logger.
3
+ *
4
+ * The id is minted here rather than read from the client: an incoming
5
+ * `X-Request-Id` is caller-controlled, and a log line keyed on it lets a caller
6
+ * splice their requests into someone else's trace. A repo that sits behind a
7
+ * proxy it trusts supplies `requestId` and reads the header itself.
8
+ */
9
+ import type { MiddlewareHandler } from 'hono';
10
+ import type { FamilyEnv, HttpLogger } from './types.ts';
11
+ declare const REQUEST_ID_HEADER = "X-Request-Id";
12
+ interface RequestContextOptions<E extends object> {
13
+ /**
14
+ Mint this request's id. Defaults to `crypto.randomUUID()`.
15
+ */
16
+ requestId?: (request: Request) => string;
17
+ /**
18
+ * Build the request-scoped logger. Pass `@rexezuge/runtime`'s `createLogger`:
19
+ * `logger: (env) => createLogger('api', 'Owner/Repo', env)`. Defaults to a
20
+ * console logger prefixed with the request id.
21
+ */
22
+ logger?: (env: E, requestId: string) => HttpLogger;
23
+ }
24
+ declare function consoleLogger(requestId: string): HttpLogger;
25
+ declare function requestContext<E extends object, V extends object>(options?: RequestContextOptions<E>): MiddlewareHandler<FamilyEnv<E, V>>;
26
+ export { consoleLogger, requestContext, REQUEST_ID_HEADER };
27
+ export type { RequestContextOptions };
28
+ //# sourceMappingURL=requestContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestContext.d.ts","sourceRoot":"","sources":["../../src/hono/requestContext.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExD,QAAA,MAAM,iBAAiB,iBAAiB,CAAC;AAEzC,UAAU,qBAAqB,CAAC,CAAC,SAAS,MAAM;IAC9C;;MAEE;IACF,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,CAAC;IACzC;;;;OAIG;IACH,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,SAAS,EAAE,MAAM,KAAK,UAAU,CAAC;CACpD;AAED,iBAAS,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,UAAU,CAQpD;AAED,iBAAS,cAAc,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,EAAE,OAAO,GAAE,qBAAqB,CAAC,CAAC,CAAM,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CActI;AAED,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,CAAC;AAC5D,YAAY,EAAE,qBAAqB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var o=(n,r)=>a(n,"name",{value:r,configurable:!0});const c="X-Request-Id";function u(n){const r=`[${n}]`;return{debug:o((...e)=>console.debug(r,...e),"debug"),info:o((...e)=>console.info(r,...e),"info"),warn:o((...e)=>console.warn(r,...e),"warn"),error:o((...e)=>console.error(r,...e),"error")}}o(u,"consoleLogger");function d(n={}){return async(r,e)=>{const t=r,s=n.requestId?.(t.req.raw)??crypto.randomUUID();t.set("requestId",s),t.set("logger",n.logger?.(t.env,s)??u(s)),await e();try{t.res.headers.set(c,s)}catch{}}}o(d,"requestContext");export{c as REQUEST_ID_HEADER,u as consoleLogger,d as requestContext};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/requestContext.ts"],
4
+ "sourcesContent": ["/**\n * The first middleware: a correlation id and a request-scoped logger.\n *\n * The id is minted here rather than read from the client: an incoming\n * `X-Request-Id` is caller-controlled, and a log line keyed on it lets a caller\n * splice their requests into someone else's trace. A repo that sits behind a\n * proxy it trusts supplies `requestId` and reads the header itself.\n */\nimport type { Context, MiddlewareHandler } from 'hono';\nimport type { FamilyEnv, HttpLogger } from './types.ts';\n\nconst REQUEST_ID_HEADER = 'X-Request-Id';\n\ninterface RequestContextOptions<E extends object> {\n /**\n Mint this request's id. Defaults to `crypto.randomUUID()`.\n */\n requestId?: (request: Request) => string;\n /**\n * Build the request-scoped logger. Pass `@rexezuge/runtime`'s `createLogger`:\n * `logger: (env) => createLogger('api', 'Owner/Repo', env)`. Defaults to a\n * console logger prefixed with the request id.\n */\n logger?: (env: E, requestId: string) => HttpLogger;\n}\n\nfunction consoleLogger(requestId: string): HttpLogger {\n const prefix = `[${requestId}]`;\n return {\n debug: (...args: unknown[]): void => console.debug(prefix, ...args),\n info: (...args: unknown[]): void => console.info(prefix, ...args),\n warn: (...args: unknown[]): void => console.warn(prefix, ...args),\n error: (...args: unknown[]): void => console.error(prefix, ...args),\n };\n}\n\nfunction requestContext<E extends object, V extends object>(options: RequestContextOptions<E> = {}): MiddlewareHandler<FamilyEnv<E, V>> {\n return async (context, next): Promise<void> => {\n // Narrowed to the kit's own variables: the caller's `V` cannot redeclare them.\n const c = context as unknown as Context<FamilyEnv<E>>;\n const id = options.requestId?.(c.req.raw) ?? crypto.randomUUID();\n c.set('requestId', id);\n c.set('logger', options.logger?.(c.env, id) ?? consoleLogger(id));\n await next();\n try {\n c.res.headers.set(REQUEST_ID_HEADER, id);\n } catch {\n // An immutable response (a pass-through `fetch`) keeps its own headers.\n }\n };\n}\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER };\nexport type { RequestContextOptions };\n"],
5
+ "mappings": "+EAWA,MAAMA,EAAoB,eAe1B,SAASC,EAAcC,EAAiB,CACtC,MAAMC,EAAS,IAAID,CAAS,IAC5B,MAAO,CACL,MAAOE,EAAA,IAAIC,IAA0B,QAAQ,MAAMF,EAAQ,GAAGE,CAAI,EAA3D,SACP,KAAMD,EAAA,IAAIC,IAA0B,QAAQ,KAAKF,EAAQ,GAAGE,CAAI,EAA1D,QACN,KAAMD,EAAA,IAAIC,IAA0B,QAAQ,KAAKF,EAAQ,GAAGE,CAAI,EAA1D,QACN,MAAOD,EAAA,IAAIC,IAA0B,QAAQ,MAAMF,EAAQ,GAAGE,CAAI,EAA3D,SAEX,CARSD,EAAAH,EAAA,iBAUT,SAASK,EAAmDC,EAAoC,CAAA,EAAE,CAChG,MAAO,OAAOC,EAASC,IAAuB,CAE5C,MAAMC,EAAIF,EACJG,EAAKJ,EAAQ,YAAYG,EAAE,IAAI,GAAG,GAAK,OAAO,WAAU,EAC9DA,EAAE,IAAI,YAAaC,CAAE,EACrBD,EAAE,IAAI,SAAUH,EAAQ,SAASG,EAAE,IAAKC,CAAE,GAAKV,EAAcU,CAAE,CAAC,EAChE,MAAMF,EAAI,EACV,GAAI,CACFC,EAAE,IAAI,QAAQ,IAAIV,EAAmBW,CAAE,CACzC,MAAQ,CAER,CACF,CACF,CAdSP,EAAAE,EAAA",
6
+ "names": ["REQUEST_ID_HEADER", "consoleLogger", "requestId", "prefix", "__name", "args", "requestContext", "options", "context", "next", "c", "id"]
7
+ }