@fonderie/adapter-hono 6.0.1 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,6 +17,8 @@ function requireFeature(key: string): MiddlewareHandler
17
17
 
18
18
  function mount(hono: Hono<BlankEnv, BlankSchema, "/">, fonderie: FonderieApp): Hono<BlankEnv, BlankSchema, "/">
19
19
 
20
+ function cors(options?: CorsOptions | undefined): MiddlewareHandler
21
+
20
22
  const OPERATIONS: { readonly CREATE: "create"; readonly READ: "read"; readonly UPDATE: "update"; readonly DELETE: "delete"; }
21
23
 
22
24
  type FonderieVariables = {
package/dist/index.cjs CHANGED
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  OPERATIONS: () => import_core.OPERATIONS,
34
34
  adapt: () => adapt,
35
35
  bridge: () => bridge,
36
+ cors: () => cors,
36
37
  mount: () => mount,
37
38
  requireAuth: () => requireAuth,
38
39
  requireFeature: () => requireFeature,
@@ -62,6 +63,9 @@ function bridge(fonderie, options = {}) {
62
63
  const ctx = await fonderie.buildContext(c.req.raw);
63
64
  const early = ctx.meta["pipelineResponse"];
64
65
  if (early instanceof Response) return early;
66
+ if (ctx.request !== c.req.raw) {
67
+ c.req.raw = ctx.request;
68
+ }
65
69
  const socketIp = c.env?.incoming?.socket?.remoteAddress;
66
70
  const headerIp = options.ipHeader ? c.req.raw.headers.get(options.ipHeader) ?? void 0 : void 0;
67
71
  const clientIp = (0, import_middlewares.resolveClientIp)(headerIp ?? socketIp ?? void 0, c.req.raw.headers);
@@ -136,11 +140,25 @@ function mount(hono, fonderie) {
136
140
  });
137
141
  return hono;
138
142
  }
143
+ function cors(options) {
144
+ const resolved = (0, import_middlewares.resolveCorsOptions)(options);
145
+ return async (c, next) => {
146
+ const corsHeaders = (0, import_middlewares.corsHeadersFor)(resolved, c.req.header("origin") ?? "");
147
+ if (c.req.method === "OPTIONS") {
148
+ return c.body(null, 204, corsHeaders);
149
+ }
150
+ await next();
151
+ for (const [k, v] of Object.entries(corsHeaders)) {
152
+ c.res.headers.set(k, v);
153
+ }
154
+ };
155
+ }
139
156
  // Annotate the CommonJS export names for ESM import in node:
140
157
  0 && (module.exports = {
141
158
  OPERATIONS,
142
159
  adapt,
143
160
  bridge,
161
+ cors,
144
162
  mount,
145
163
  requireAuth,
146
164
  requireFeature,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Context, MiddlewareHandler } from 'hono';\nimport type { Hono } from 'hono';\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport { requireAuth as _requireAuth, resolveClientIp } from '@fonderie/core/middlewares';\n// Optional peers: type-only imports (erased at runtime). The guard factories\n// below load them lazily so installing this adapter never requires\n// @fonderie/workspaces, @fonderie/permissions, or @fonderie/billing unless\n// the corresponding guard is actually used.\nimport type { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport type { requirePermission as _requirePermission } from '@fonderie/permissions';\n\nexport { OPERATIONS } from '@fonderie/core';\n\nasync function loadOptionalPeer<T>(load: () => Promise<T>, pkg: string, api: string): Promise<T> {\n\ttry {\n\t\treturn await load();\n\t} catch (err) {\n\t\tconst e = err as { code?: string; message?: string } | undefined;\n\t\tconst notFound = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND';\n\t\t// Only claim the peer is missing when the unresolved specifier IS the\n\t\t// peer — a transitive failure inside an installed peer must surface\n\t\t// as-is, not as a misleading install hint.\n\t\tconst missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? '')?.[1] : undefined;\n\t\tif (missing === pkg || missing?.startsWith(pkg + '/')) {\n\t\t\tthrow new Error(\n\t\t\t\t`[fonderie] ${api} requires the optional peer dependency \"${pkg}\". Install it: npm install ${pkg}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// Augment Hono's ContextVariableMap so c.get('_fonderie') is typed.\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t_fonderie: IFonderieContext;\n\t}\n}\n\n// Re-export for consumers who want to type their Hono app:\n// const hono = new Hono<{ Variables: FonderieVariables }>()\nexport type FonderieVariables = {\n\t_fonderie: IFonderieContext;\n};\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Global middleware. Runs fonderie's session + billing global stack so that\n// ctx.user and ctx.meta['billing'] are available in every route handler.\n// Must be registered before any fonderie-aware route middleware.\n//\n// hono.use('*', bridge(fonderie))\n\nexport interface IBridgeOptions {\n\t/**\n\t * Name of the header that carries the PLATFORM-VERIFIED client IP — e.g.\n\t * 'cf-connecting-ip' on Cloudflare, 'x-real-ip' behind an nginx that sets\n\t * it. This is an explicit opt-in: request headers are attacker-settable,\n\t * so trusting one by default would let any client spoof its IP and dodge\n\t * per-IP rate limits (auth brute-force limiters key on this). Only set it\n\t * when your platform/proxy STRIPS the header from client requests and\n\t * injects its own value.\n\t */\n\tipHeader?: string;\n}\n\nexport function bridge(fonderie: FonderieApp, options: IBridgeOptions = {}): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// No clone(): teeing a request and fully reading ONE branch while the\n\t\t// other sits unread stalls once the body crosses the stream's\n\t\t// high-water mark (undici's tee applies backpressure from the slower\n\t\t// consumer). buildContext consumes the body and core's parser\n\t\t// re-materializes ctx.request from the buffered bytes, so mount() and\n\t\t// app routes read from THAT instead of the spent raw request.\n\t\tconst ctx = await fonderie.buildContext(c.req.raw);\n\t\t// A global middleware short-circuited while building context (e.g. the\n\t\t// body parser's 413) — that response must reach the client, not be\n\t\t// swallowed by context-building.\n\t\tconst early = ctx.meta['pipelineResponse'];\n\t\tif (early instanceof Response) return early;\n\t\t// Client IP, spoof-safe by default (mirrors core's trustProxy model):\n\t\t// 1. The real socket address when the runtime exposes one\n\t\t// (@hono/node-server puts the node request on c.env.incoming).\n\t\t// 2. A platform header ONLY when explicitly configured via ipHeader.\n\t\t// 3. X-Forwarded-For only per core's TRUST_PROXY hop count.\n\t\t// Previously cf-connecting-ip/x-real-ip were trusted UNCONDITIONALLY,\n\t\t// which let any direct client forge its IP (fresh rate-limit bucket per\n\t\t// request) or omit it (limiter skipped) on self-hosted deployments.\n\t\tconst socketIp = (\n\t\t\tc.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined\n\t\t)?.incoming?.socket?.remoteAddress;\n\t\tconst headerIp = options.ipHeader\n\t\t\t? (c.req.raw.headers.get(options.ipHeader) ?? undefined)\n\t\t\t: undefined;\n\t\tconst clientIp = resolveClientIp(headerIp ?? socketIp ?? undefined, c.req.raw.headers);\n\t\tif (clientIp) ctx.meta.clientIp = clientIp;\n\t\tc.set('_fonderie', ctx);\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Hono\n// MiddlewareHandler. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\nexport function adapt(middleware: Middleware): MiddlewareHandler {\n\treturn async (c: Context, next) => {\n\t\tconst ctx = c.get('_fonderie');\n\t\tif (!ctx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(ctx, async () => {\n\t\t\tcontinued = true;\n\t\t\treturn new Response();\n\t\t});\n\n\t\tif (continued) {\n\t\t\tawait next();\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ── Pre-adapted middleware ────────────────────────────────────────\n//\n// Drop-in replacements for the fonderie middleware functions — no adapt()\n// needed. Import directly from this package instead of from the source\n// packages, and use them as native Hono middleware.\n//\n// hono.get('/jobs', requireAuth, withWorkspace(store), ...)\n\nexport const requireAuth: MiddlewareHandler = adapt(_requireAuth);\n\n// The three guards below wrap OPTIONAL peers, so the peer is imported lazily\n// on first request — not at module load. MiddlewareHandler is async either\n// way, so the extra await changes nothing for callers.\n\nexport function withWorkspace(store: Parameters<typeof _withWorkspace>[0]): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/workspaces'),\n\t\t\t\t'@fonderie/workspaces',\n\t\t\t\t'withWorkspace()',\n\t\t\t);\n\t\t\tinner = adapt(mod.withWorkspace(store));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/permissions'),\n\t\t\t\t'@fonderie/permissions',\n\t\t\t\t'requirePermission()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requirePermission(operation, permissionKey));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requireFeature(key: string): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/billing'),\n\t\t\t\t'@fonderie/billing',\n\t\t\t\t'requireFeature()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requireFeature(key));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Hono app. Returns the same app so you can add\n// routes after mount() — fonderie infra is the notFound handler, so\n// user routes always take priority:\n//\n// const api = mount(hono, fonderie)\n// api.get('/v1/todos', requireAuth, handler)\n// export default hono\n\n// mount() wires fonderie's infrastructure routes as the notFound fallback so\n// user routes always take priority. Call bridge() yourself before your routes\n// to ensure _fonderie is populated for them.\nexport function mount(hono: Hono, fonderie: FonderieApp): Hono {\n\thono.notFound((c) => {\n\t\t// bridge() consumed the raw body (see its no-clone note) and core's\n\t\t// parser re-materialized ctx.request with the buffered bytes — route\n\t\t// fonderie's handling through THAT. Without bridge (no ctx), the raw\n\t\t// request is untouched and safe to hand over directly.\n\t\tconst ctx = c.get('_fonderie') as IFonderieContext | undefined;\n\t\treturn fonderie.handle(ctx?.request ?? c.req.raw);\n\t});\n\treturn hono;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,yBAA6D;AAQ7D,kBAA2B;AAE3B,eAAe,iBAAoB,MAAwB,KAAa,KAAyB;AAChG,MAAI;AACH,WAAO,MAAM,KAAK;AAAA,EACnB,SAAS,KAAK;AACb,UAAM,IAAI;AACV,UAAM,WAAW,GAAG,SAAS,0BAA0B,GAAG,SAAS;AAInE,UAAM,UAAU,WAAW,2CAA2C,KAAK,GAAG,WAAW,EAAE,IAAI,CAAC,IAAI;AACpG,QAAI,YAAY,OAAO,SAAS,WAAW,MAAM,GAAG,GAAG;AACtD,YAAM,IAAI;AAAA,QACT,cAAc,GAAG,2CAA2C,GAAG,8BAA8B,GAAG;AAAA,MACjG;AAAA,IACD;AACA,UAAM;AAAA,EACP;AACD;AAoCO,SAAS,OAAO,UAAuB,UAA0B,CAAC,GAAsB;AAC9F,SAAO,OAAO,GAAG,SAAS;AAOzB,UAAM,MAAM,MAAM,SAAS,aAAa,EAAE,IAAI,GAAG;AAIjD,UAAM,QAAQ,IAAI,KAAK,kBAAkB;AACzC,QAAI,iBAAiB,SAAU,QAAO;AAStC,UAAM,WACL,EAAE,KACA,UAAU,QAAQ;AACrB,UAAM,WAAW,QAAQ,WACrB,EAAE,IAAI,IAAI,QAAQ,IAAI,QAAQ,QAAQ,KAAK,SAC5C;AACH,UAAM,eAAW,oCAAgB,YAAY,YAAY,QAAW,EAAE,IAAI,IAAI,OAAO;AACrF,QAAI,SAAU,KAAI,KAAK,WAAW;AAClC,MAAE,IAAI,aAAa,GAAG;AACtB,UAAM,KAAK;AAAA,EACZ;AACD;A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A,EACrB;AACD;AAeO,SAAS,MAAM,MAAY,UAA6B;AAC9D,OAAK,SAAS,CAAC,MAAM;AAKpB,UAAM,MAAM,EAAE,IAAI,WAAW;AAC7B,WAAO,SAAS,OAAO,KAAK,WAAW,EAAE,IAAI,GAAG;AAAA,EACjD,CAAC;AACD,SAAO;AACR;","names":["_requireAuth"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Context, MiddlewareHandler } from 'hono';\nimport type { Hono } from 'hono';\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport {\n\trequireAuth as _requireAuth,\n\tresolveClientIp,\n\tresolveCorsOptions,\n\tcorsHeadersFor,\n\ttype CorsOptions,\n} from '@fonderie/core/middlewares';\n// Optional peers: type-only imports (erased at runtime). The guard factories\n// below load them lazily so installing this adapter never requires\n// @fonderie/workspaces, @fonderie/permissions, or @fonderie/billing unless\n// the corresponding guard is actually used.\nimport type { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport type { requirePermission as _requirePermission } from '@fonderie/permissions';\n\nexport { OPERATIONS } from '@fonderie/core';\n\nasync function loadOptionalPeer<T>(load: () => Promise<T>, pkg: string, api: string): Promise<T> {\n\ttry {\n\t\treturn await load();\n\t} catch (err) {\n\t\tconst e = err as { code?: string; message?: string } | undefined;\n\t\tconst notFound = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND';\n\t\t// Only claim the peer is missing when the unresolved specifier IS the\n\t\t// peer — a transitive failure inside an installed peer must surface\n\t\t// as-is, not as a misleading install hint.\n\t\tconst missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? '')?.[1] : undefined;\n\t\tif (missing === pkg || missing?.startsWith(pkg + '/')) {\n\t\t\tthrow new Error(\n\t\t\t\t`[fonderie] ${api} requires the optional peer dependency \"${pkg}\". Install it: npm install ${pkg}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// Augment Hono's ContextVariableMap so c.get('_fonderie') is typed.\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t_fonderie: IFonderieContext;\n\t}\n}\n\n// Re-export for consumers who want to type their Hono app:\n// const hono = new Hono<{ Variables: FonderieVariables }>()\nexport type FonderieVariables = {\n\t_fonderie: IFonderieContext;\n};\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Global middleware. Runs fonderie's session + billing global stack so that\n// ctx.user and ctx.meta['billing'] are available in every route handler.\n// Must be registered before any fonderie-aware route middleware.\n//\n// hono.use('*', bridge(fonderie))\n\nexport interface IBridgeOptions {\n\t/**\n\t * Name of the header that carries the PLATFORM-VERIFIED client IP — e.g.\n\t * 'cf-connecting-ip' on Cloudflare, 'x-real-ip' behind an nginx that sets\n\t * it. This is an explicit opt-in: request headers are attacker-settable,\n\t * so trusting one by default would let any client spoof its IP and dodge\n\t * per-IP rate limits (auth brute-force limiters key on this). Only set it\n\t * when your platform/proxy STRIPS the header from client requests and\n\t * injects its own value.\n\t */\n\tipHeader?: string;\n}\n\nexport function bridge(fonderie: FonderieApp, options: IBridgeOptions = {}): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// No clone(): teeing a request and fully reading ONE branch while the\n\t\t// other sits unread stalls once the body crosses the stream's\n\t\t// high-water mark (undici's tee applies backpressure from the slower\n\t\t// consumer). buildContext consumes the body and core's parser\n\t\t// re-materializes ctx.request from the buffered bytes, so mount() and\n\t\t// app routes read from THAT instead of the spent raw request.\n\t\tconst ctx = await fonderie.buildContext(c.req.raw);\n\t\t// A global middleware short-circuited while building context (e.g. the\n\t\t// body parser's 413) — that response must reach the client, not be\n\t\t// swallowed by context-building.\n\t\tconst early = ctx.meta['pipelineResponse'];\n\t\tif (early instanceof Response) return early;\n\t\t// buildContext CONSUMED c.req.raw's body (no clone — a tee stalls on\n\t\t// large bodies). Core's parser re-materialized ctx.request from the\n\t\t// buffered bytes; point Hono's request at it so the app's OWN native\n\t\t// handlers (c.req.json()/text()/parseBody()) still read the body —\n\t\t// otherwise they'd hit a drained stream. For content-types the parser\n\t\t// leaves untouched (multipart), ctx.request === the original, so this\n\t\t// is a no-op. bodyCache is empty here (nothing read yet).\n\t\tif (ctx.request !== c.req.raw) {\n\t\t\t(c.req as { raw: Request }).raw = ctx.request;\n\t\t}\n\t\t// Client IP, spoof-safe by default (mirrors core's trustProxy model):\n\t\t// 1. The real socket address when the runtime exposes one\n\t\t// (@hono/node-server puts the node request on c.env.incoming).\n\t\t// 2. A platform header ONLY when explicitly configured via ipHeader.\n\t\t// 3. X-Forwarded-For only per core's TRUST_PROXY hop count.\n\t\t// Previously cf-connecting-ip/x-real-ip were trusted UNCONDITIONALLY,\n\t\t// which let any direct client forge its IP (fresh rate-limit bucket per\n\t\t// request) or omit it (limiter skipped) on self-hosted deployments.\n\t\tconst socketIp = (\n\t\t\tc.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined\n\t\t)?.incoming?.socket?.remoteAddress;\n\t\tconst headerIp = options.ipHeader\n\t\t\t? (c.req.raw.headers.get(options.ipHeader) ?? undefined)\n\t\t\t: undefined;\n\t\tconst clientIp = resolveClientIp(headerIp ?? socketIp ?? undefined, c.req.raw.headers);\n\t\tif (clientIp) ctx.meta.clientIp = clientIp;\n\t\tc.set('_fonderie', ctx);\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Hono\n// MiddlewareHandler. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\nexport function adapt(middleware: Middleware): MiddlewareHandler {\n\treturn async (c: Context, next) => {\n\t\tconst ctx = c.get('_fonderie');\n\t\tif (!ctx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(ctx, async () => {\n\t\t\tcontinued = true;\n\t\t\treturn new Response();\n\t\t});\n\n\t\tif (continued) {\n\t\t\tawait next();\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ── Pre-adapted middleware ────────────────────────────────────────\n//\n// Drop-in replacements for the fonderie middleware functions — no adapt()\n// needed. Import directly from this package instead of from the source\n// packages, and use them as native Hono middleware.\n//\n// hono.get('/jobs', requireAuth, withWorkspace(store), ...)\n\nexport const requireAuth: MiddlewareHandler = adapt(_requireAuth);\n\n// The three guards below wrap OPTIONAL peers, so the peer is imported lazily\n// on first request — not at module load. MiddlewareHandler is async either\n// way, so the extra await changes nothing for callers.\n\nexport function withWorkspace(store: Parameters<typeof _withWorkspace>[0]): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/workspaces'),\n\t\t\t\t'@fonderie/workspaces',\n\t\t\t\t'withWorkspace()',\n\t\t\t);\n\t\t\tinner = adapt(mod.withWorkspace(store));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/permissions'),\n\t\t\t\t'@fonderie/permissions',\n\t\t\t\t'requirePermission()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requirePermission(operation, permissionKey));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requireFeature(key: string): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/billing'),\n\t\t\t\t'@fonderie/billing',\n\t\t\t\t'requireFeature()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requireFeature(key));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Hono app. Returns the same app so you can add\n// routes after mount() — fonderie infra is the notFound handler, so\n// user routes always take priority:\n//\n// const api = mount(hono, fonderie)\n// api.get('/v1/todos', requireAuth, handler)\n// export default hono\n\n// mount() wires fonderie's infrastructure routes as the notFound fallback so\n// user routes always take priority. Call bridge() yourself before your routes\n// to ensure _fonderie is populated for them.\nexport function mount(hono: Hono, fonderie: FonderieApp): Hono {\n\thono.notFound((c) => {\n\t\t// bridge() consumed the raw body (see its no-clone note) and core's\n\t\t// parser re-materialized ctx.request with the buffered bytes — route\n\t\t// fonderie's handling through THAT. Without bridge (no ctx), the raw\n\t\t// request is untouched and safe to hand over directly.\n\t\tconst ctx = c.get('_fonderie') as IFonderieContext | undefined;\n\t\treturn fonderie.handle(ctx?.request ?? c.req.raw);\n\t});\n\treturn hono;\n}\n\n// ── App-level CORS ────────────────────────────────────────────────\n//\n// Native Hono middleware speaking core's CORS contract — same options and\n// defaults as withCors, so the headers @fonderie/client sends are allowed out\n// of the box (unlike hono/cors, whose defaults know nothing about them).\n// Register it on the Hono app itself so it covers EVERY route, including\n// ones outside the fonderie pipeline: fonderie.use(withCors()) only guards\n// the mounted basePath.\n//\n// app.use('*', cors({ credentials: true, origin: process.env.FRONTEND_URL! }))\n\nexport function cors(options?: CorsOptions): MiddlewareHandler {\n\tconst resolved = resolveCorsOptions(options);\n\treturn async (c, next) => {\n\t\tconst corsHeaders = corsHeadersFor(resolved, c.req.header('origin') ?? '');\n\t\t// Preflight — respond immediately, skip the pipeline\n\t\tif (c.req.method === 'OPTIONS') {\n\t\t\treturn c.body(null, 204, corsHeaders);\n\t\t}\n\t\tawait next();\n\t\tfor (const [k, v] of Object.entries(corsHeaders)) {\n\t\t\tc.res.headers.set(k, v);\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AA,EACjD,CAAC;AACD,SAAO;AACR;AAaO,SAAS,KAAK,SAA0C;AAC9D,QAAM,eAAW,uCAAmB,OAAO;AAC3C,SAAO,OAAO,GAAG,SAAS;AACzB,UAAM,kBAAc,mCAAe,UAAU,EAAE,IAAI,OAAO,QAAQ,KAAK,EAAE;AAEzE,QAAI,EAAE,IAAI,WAAW,WAAW;AAC/B,aAAO,EAAE,KAAK,MAAM,KAAK,WAAW;AAAA,IACrC;AACA,UAAM,KAAK;AACX,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,WAAW,GAAG;AACjD,QAAE,IAAI,QAAQ,IAAI,GAAG,CAAC;AAAA,IACvB;AAAA,EACD;AACD;","names":["_requireAuth"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { MiddlewareHandler, Hono } from 'hono';
2
2
  import { IFonderieContext, Middleware, FonderieApp } from '@fonderie/core';
3
3
  export { OPERATIONS } from '@fonderie/core';
4
+ import { CorsOptions } from '@fonderie/core/middlewares';
4
5
  import { withWorkspace as withWorkspace$1 } from '@fonderie/workspaces';
5
6
  import { requirePermission as requirePermission$1 } from '@fonderie/permissions';
6
7
 
@@ -31,5 +32,6 @@ declare function withWorkspace(store: Parameters<typeof withWorkspace$1>[0]): Mi
31
32
  declare function requirePermission(operation: Parameters<typeof requirePermission$1>[0], permissionKey: Parameters<typeof requirePermission$1>[1]): MiddlewareHandler;
32
33
  declare function requireFeature(key: string): MiddlewareHandler;
33
34
  declare function mount(hono: Hono, fonderie: FonderieApp): Hono;
35
+ declare function cors(options?: CorsOptions): MiddlewareHandler;
34
36
 
35
- export { type FonderieVariables, type IBridgeOptions, adapt, bridge, mount, requireAuth, requireFeature, requirePermission, withWorkspace };
37
+ export { type FonderieVariables, type IBridgeOptions, adapt, bridge, cors, mount, requireAuth, requireFeature, requirePermission, withWorkspace };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { MiddlewareHandler, Hono } from 'hono';
2
2
  import { IFonderieContext, Middleware, FonderieApp } from '@fonderie/core';
3
3
  export { OPERATIONS } from '@fonderie/core';
4
+ import { CorsOptions } from '@fonderie/core/middlewares';
4
5
  import { withWorkspace as withWorkspace$1 } from '@fonderie/workspaces';
5
6
  import { requirePermission as requirePermission$1 } from '@fonderie/permissions';
6
7
 
@@ -31,5 +32,6 @@ declare function withWorkspace(store: Parameters<typeof withWorkspace$1>[0]): Mi
31
32
  declare function requirePermission(operation: Parameters<typeof requirePermission$1>[0], permissionKey: Parameters<typeof requirePermission$1>[1]): MiddlewareHandler;
32
33
  declare function requireFeature(key: string): MiddlewareHandler;
33
34
  declare function mount(hono: Hono, fonderie: FonderieApp): Hono;
35
+ declare function cors(options?: CorsOptions): MiddlewareHandler;
34
36
 
35
- export { type FonderieVariables, type IBridgeOptions, adapt, bridge, mount, requireAuth, requireFeature, requirePermission, withWorkspace };
37
+ export { type FonderieVariables, type IBridgeOptions, adapt, bridge, cors, mount, requireAuth, requireFeature, requirePermission, withWorkspace };
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
1
  // src/index.ts
2
- import { requireAuth as _requireAuth, resolveClientIp } from "@fonderie/core/middlewares";
2
+ import {
3
+ requireAuth as _requireAuth,
4
+ resolveClientIp,
5
+ resolveCorsOptions,
6
+ corsHeadersFor
7
+ } from "@fonderie/core/middlewares";
3
8
  import { OPERATIONS } from "@fonderie/core";
4
9
  async function loadOptionalPeer(load, pkg, api) {
5
10
  try {
@@ -21,6 +26,9 @@ function bridge(fonderie, options = {}) {
21
26
  const ctx = await fonderie.buildContext(c.req.raw);
22
27
  const early = ctx.meta["pipelineResponse"];
23
28
  if (early instanceof Response) return early;
29
+ if (ctx.request !== c.req.raw) {
30
+ c.req.raw = ctx.request;
31
+ }
24
32
  const socketIp = c.env?.incoming?.socket?.remoteAddress;
25
33
  const headerIp = options.ipHeader ? c.req.raw.headers.get(options.ipHeader) ?? void 0 : void 0;
26
34
  const clientIp = resolveClientIp(headerIp ?? socketIp ?? void 0, c.req.raw.headers);
@@ -95,10 +103,24 @@ function mount(hono, fonderie) {
95
103
  });
96
104
  return hono;
97
105
  }
106
+ function cors(options) {
107
+ const resolved = resolveCorsOptions(options);
108
+ return async (c, next) => {
109
+ const corsHeaders = corsHeadersFor(resolved, c.req.header("origin") ?? "");
110
+ if (c.req.method === "OPTIONS") {
111
+ return c.body(null, 204, corsHeaders);
112
+ }
113
+ await next();
114
+ for (const [k, v] of Object.entries(corsHeaders)) {
115
+ c.res.headers.set(k, v);
116
+ }
117
+ };
118
+ }
98
119
  export {
99
120
  OPERATIONS,
100
121
  adapt,
101
122
  bridge,
123
+ cors,
102
124
  mount,
103
125
  requireAuth,
104
126
  requireFeature,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Context, MiddlewareHandler } from 'hono';\nimport type { Hono } from 'hono';\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport { requireAuth as _requireAuth, resolveClientIp } from '@fonderie/core/middlewares';\n// Optional peers: type-only imports (erased at runtime). The guard factories\n// below load them lazily so installing this adapter never requires\n// @fonderie/workspaces, @fonderie/permissions, or @fonderie/billing unless\n// the corresponding guard is actually used.\nimport type { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport type { requirePermission as _requirePermission } from '@fonderie/permissions';\n\nexport { OPERATIONS } from '@fonderie/core';\n\nasync function loadOptionalPeer<T>(load: () => Promise<T>, pkg: string, api: string): Promise<T> {\n\ttry {\n\t\treturn await load();\n\t} catch (err) {\n\t\tconst e = err as { code?: string; message?: string } | undefined;\n\t\tconst notFound = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND';\n\t\t// Only claim the peer is missing when the unresolved specifier IS the\n\t\t// peer — a transitive failure inside an installed peer must surface\n\t\t// as-is, not as a misleading install hint.\n\t\tconst missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? '')?.[1] : undefined;\n\t\tif (missing === pkg || missing?.startsWith(pkg + '/')) {\n\t\t\tthrow new Error(\n\t\t\t\t`[fonderie] ${api} requires the optional peer dependency \"${pkg}\". Install it: npm install ${pkg}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// Augment Hono's ContextVariableMap so c.get('_fonderie') is typed.\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t_fonderie: IFonderieContext;\n\t}\n}\n\n// Re-export for consumers who want to type their Hono app:\n// const hono = new Hono<{ Variables: FonderieVariables }>()\nexport type FonderieVariables = {\n\t_fonderie: IFonderieContext;\n};\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Global middleware. Runs fonderie's session + billing global stack so that\n// ctx.user and ctx.meta['billing'] are available in every route handler.\n// Must be registered before any fonderie-aware route middleware.\n//\n// hono.use('*', bridge(fonderie))\n\nexport interface IBridgeOptions {\n\t/**\n\t * Name of the header that carries the PLATFORM-VERIFIED client IP — e.g.\n\t * 'cf-connecting-ip' on Cloudflare, 'x-real-ip' behind an nginx that sets\n\t * it. This is an explicit opt-in: request headers are attacker-settable,\n\t * so trusting one by default would let any client spoof its IP and dodge\n\t * per-IP rate limits (auth brute-force limiters key on this). Only set it\n\t * when your platform/proxy STRIPS the header from client requests and\n\t * injects its own value.\n\t */\n\tipHeader?: string;\n}\n\nexport function bridge(fonderie: FonderieApp, options: IBridgeOptions = {}): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// No clone(): teeing a request and fully reading ONE branch while the\n\t\t// other sits unread stalls once the body crosses the stream's\n\t\t// high-water mark (undici's tee applies backpressure from the slower\n\t\t// consumer). buildContext consumes the body and core's parser\n\t\t// re-materializes ctx.request from the buffered bytes, so mount() and\n\t\t// app routes read from THAT instead of the spent raw request.\n\t\tconst ctx = await fonderie.buildContext(c.req.raw);\n\t\t// A global middleware short-circuited while building context (e.g. the\n\t\t// body parser's 413) — that response must reach the client, not be\n\t\t// swallowed by context-building.\n\t\tconst early = ctx.meta['pipelineResponse'];\n\t\tif (early instanceof Response) return early;\n\t\t// Client IP, spoof-safe by default (mirrors core's trustProxy model):\n\t\t// 1. The real socket address when the runtime exposes one\n\t\t// (@hono/node-server puts the node request on c.env.incoming).\n\t\t// 2. A platform header ONLY when explicitly configured via ipHeader.\n\t\t// 3. X-Forwarded-For only per core's TRUST_PROXY hop count.\n\t\t// Previously cf-connecting-ip/x-real-ip were trusted UNCONDITIONALLY,\n\t\t// which let any direct client forge its IP (fresh rate-limit bucket per\n\t\t// request) or omit it (limiter skipped) on self-hosted deployments.\n\t\tconst socketIp = (\n\t\t\tc.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined\n\t\t)?.incoming?.socket?.remoteAddress;\n\t\tconst headerIp = options.ipHeader\n\t\t\t? (c.req.raw.headers.get(options.ipHeader) ?? undefined)\n\t\t\t: undefined;\n\t\tconst clientIp = resolveClientIp(headerIp ?? socketIp ?? undefined, c.req.raw.headers);\n\t\tif (clientIp) ctx.meta.clientIp = clientIp;\n\t\tc.set('_fonderie', ctx);\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Hono\n// MiddlewareHandler. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\nexport function adapt(middleware: Middleware): MiddlewareHandler {\n\treturn async (c: Context, next) => {\n\t\tconst ctx = c.get('_fonderie');\n\t\tif (!ctx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(ctx, async () => {\n\t\t\tcontinued = true;\n\t\t\treturn new Response();\n\t\t});\n\n\t\tif (continued) {\n\t\t\tawait next();\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ── Pre-adapted middleware ────────────────────────────────────────\n//\n// Drop-in replacements for the fonderie middleware functions — no adapt()\n// needed. Import directly from this package instead of from the source\n// packages, and use them as native Hono middleware.\n//\n// hono.get('/jobs', requireAuth, withWorkspace(store), ...)\n\nexport const requireAuth: MiddlewareHandler = adapt(_requireAuth);\n\n// The three guards below wrap OPTIONAL peers, so the peer is imported lazily\n// on first request — not at module load. MiddlewareHandler is async either\n// way, so the extra await changes nothing for callers.\n\nexport function withWorkspace(store: Parameters<typeof _withWorkspace>[0]): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/workspaces'),\n\t\t\t\t'@fonderie/workspaces',\n\t\t\t\t'withWorkspace()',\n\t\t\t);\n\t\t\tinner = adapt(mod.withWorkspace(store));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/permissions'),\n\t\t\t\t'@fonderie/permissions',\n\t\t\t\t'requirePermission()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requirePermission(operation, permissionKey));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requireFeature(key: string): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/billing'),\n\t\t\t\t'@fonderie/billing',\n\t\t\t\t'requireFeature()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requireFeature(key));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Hono app. Returns the same app so you can add\n// routes after mount() — fonderie infra is the notFound handler, so\n// user routes always take priority:\n//\n// const api = mount(hono, fonderie)\n// api.get('/v1/todos', requireAuth, handler)\n// export default hono\n\n// mount() wires fonderie's infrastructure routes as the notFound fallback so\n// user routes always take priority. Call bridge() yourself before your routes\n// to ensure _fonderie is populated for them.\nexport function mount(hono: Hono, fonderie: FonderieApp): Hono {\n\thono.notFound((c) => {\n\t\t// bridge() consumed the raw body (see its no-clone note) and core's\n\t\t// parser re-materialized ctx.request with the buffered bytes — route\n\t\t// fonderie's handling through THAT. Without bridge (no ctx), the raw\n\t\t// request is untouched and safe to hand over directly.\n\t\tconst ctx = c.get('_fonderie') as IFonderieContext | undefined;\n\t\treturn fonderie.handle(ctx?.request ?? c.req.raw);\n\t});\n\treturn hono;\n}\n"],"mappings":";AAIA,SAAS,eAAe,cAAc,uBAAuB;AAQ7D,SAAS,kBAAkB;AAE3B,eAAe,iBAAoB,MAAwB,KAAa,KAAyB;AAChG,MAAI;AACH,WAAO,MAAM,KAAK;AAAA,EACnB,SAAS,KAAK;AACb,UAAM,IAAI;AACV,UAAM,WAAW,GAAG,SAAS,0BAA0B,GAAG,SAAS;AAInE,UAAM,UAAU,WAAW,2CAA2C,KAAK,GAAG,WAAW,EAAE,IAAI,CAAC,IAAI;AACpG,QAAI,YAAY,OAAO,SAAS,WAAW,MAAM,GAAG,GAAG;AACtD,YAAM,IAAI;AAAA,QACT,cAAc,GAAG,2CAA2C,GAAG,8BAA8B,GAAG;AAAA,MACjG;AAAA,IACD;AACA,UAAM;AAAA,EACP;AACD;AAoCO,SAAS,OAAO,UAAuB,UAA0B,CAAC,GAAsB;AAC9F,SAAO,OAAO,GAAG,SAAS;AAOzB,UAAM,MAAM,MAAM,SAAS,aAAa,EAAE,IAAI,GAAG;AAIjD,UAAM,QAAQ,IAAI,KAAK,kBAAkB;AACzC,QAAI,iBAAiB,SAAU,QAAO;AAStC,UAAM,WACL,EAAE,KACA,UAAU,QAAQ;AACrB,UAAM,WAAW,QAAQ,WACrB,EAAE,IAAI,IAAI,QAAQ,IAAI,QAAQ,QAAQ,KAAK,SAC5C;AACH,UAAM,WAAW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ACjB,MAAM,OAAO,mBAAmB;AAAA,QAChC;AAAA,QACA;AAAA,MACD;AACA,cAAQ,MAAM,IAAI,eAAe,GAAG,CAAC;AAAA,IACtC;AACA,WAAO,MAAM,GAAG,IAAI;AAAA,EACrB;AACD;AAeO,SAAS,MAAM,MAAY,UAA6B;AAC9D,OAAK,SAAS,CAAC,MAAM;AAKpB,UAAM,MAAM,EAAE,IAAI,WAAW;AAC7B,WAAO,SAAS,OAAO,KAAK,WAAW,EAAE,IAAI,GAAG;AAAA,EACjD,CAAC;AACD,SAAO;AACR;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Context, MiddlewareHandler } from 'hono';\nimport type { Hono } from 'hono';\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport {\n\trequireAuth as _requireAuth,\n\tresolveClientIp,\n\tresolveCorsOptions,\n\tcorsHeadersFor,\n\ttype CorsOptions,\n} from '@fonderie/core/middlewares';\n// Optional peers: type-only imports (erased at runtime). The guard factories\n// below load them lazily so installing this adapter never requires\n// @fonderie/workspaces, @fonderie/permissions, or @fonderie/billing unless\n// the corresponding guard is actually used.\nimport type { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport type { requirePermission as _requirePermission } from '@fonderie/permissions';\n\nexport { OPERATIONS } from '@fonderie/core';\n\nasync function loadOptionalPeer<T>(load: () => Promise<T>, pkg: string, api: string): Promise<T> {\n\ttry {\n\t\treturn await load();\n\t} catch (err) {\n\t\tconst e = err as { code?: string; message?: string } | undefined;\n\t\tconst notFound = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND';\n\t\t// Only claim the peer is missing when the unresolved specifier IS the\n\t\t// peer — a transitive failure inside an installed peer must surface\n\t\t// as-is, not as a misleading install hint.\n\t\tconst missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? '')?.[1] : undefined;\n\t\tif (missing === pkg || missing?.startsWith(pkg + '/')) {\n\t\t\tthrow new Error(\n\t\t\t\t`[fonderie] ${api} requires the optional peer dependency \"${pkg}\". Install it: npm install ${pkg}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// Augment Hono's ContextVariableMap so c.get('_fonderie') is typed.\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t_fonderie: IFonderieContext;\n\t}\n}\n\n// Re-export for consumers who want to type their Hono app:\n// const hono = new Hono<{ Variables: FonderieVariables }>()\nexport type FonderieVariables = {\n\t_fonderie: IFonderieContext;\n};\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Global middleware. Runs fonderie's session + billing global stack so that\n// ctx.user and ctx.meta['billing'] are available in every route handler.\n// Must be registered before any fonderie-aware route middleware.\n//\n// hono.use('*', bridge(fonderie))\n\nexport interface IBridgeOptions {\n\t/**\n\t * Name of the header that carries the PLATFORM-VERIFIED client IP — e.g.\n\t * 'cf-connecting-ip' on Cloudflare, 'x-real-ip' behind an nginx that sets\n\t * it. This is an explicit opt-in: request headers are attacker-settable,\n\t * so trusting one by default would let any client spoof its IP and dodge\n\t * per-IP rate limits (auth brute-force limiters key on this). Only set it\n\t * when your platform/proxy STRIPS the header from client requests and\n\t * injects its own value.\n\t */\n\tipHeader?: string;\n}\n\nexport function bridge(fonderie: FonderieApp, options: IBridgeOptions = {}): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// No clone(): teeing a request and fully reading ONE branch while the\n\t\t// other sits unread stalls once the body crosses the stream's\n\t\t// high-water mark (undici's tee applies backpressure from the slower\n\t\t// consumer). buildContext consumes the body and core's parser\n\t\t// re-materializes ctx.request from the buffered bytes, so mount() and\n\t\t// app routes read from THAT instead of the spent raw request.\n\t\tconst ctx = await fonderie.buildContext(c.req.raw);\n\t\t// A global middleware short-circuited while building context (e.g. the\n\t\t// body parser's 413) — that response must reach the client, not be\n\t\t// swallowed by context-building.\n\t\tconst early = ctx.meta['pipelineResponse'];\n\t\tif (early instanceof Response) return early;\n\t\t// buildContext CONSUMED c.req.raw's body (no clone — a tee stalls on\n\t\t// large bodies). Core's parser re-materialized ctx.request from the\n\t\t// buffered bytes; point Hono's request at it so the app's OWN native\n\t\t// handlers (c.req.json()/text()/parseBody()) still read the body —\n\t\t// otherwise they'd hit a drained stream. For content-types the parser\n\t\t// leaves untouched (multipart), ctx.request === the original, so this\n\t\t// is a no-op. bodyCache is empty here (nothing read yet).\n\t\tif (ctx.request !== c.req.raw) {\n\t\t\t(c.req as { raw: Request }).raw = ctx.request;\n\t\t}\n\t\t// Client IP, spoof-safe by default (mirrors core's trustProxy model):\n\t\t// 1. The real socket address when the runtime exposes one\n\t\t// (@hono/node-server puts the node request on c.env.incoming).\n\t\t// 2. A platform header ONLY when explicitly configured via ipHeader.\n\t\t// 3. X-Forwarded-For only per core's TRUST_PROXY hop count.\n\t\t// Previously cf-connecting-ip/x-real-ip were trusted UNCONDITIONALLY,\n\t\t// which let any direct client forge its IP (fresh rate-limit bucket per\n\t\t// request) or omit it (limiter skipped) on self-hosted deployments.\n\t\tconst socketIp = (\n\t\t\tc.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined\n\t\t)?.incoming?.socket?.remoteAddress;\n\t\tconst headerIp = options.ipHeader\n\t\t\t? (c.req.raw.headers.get(options.ipHeader) ?? undefined)\n\t\t\t: undefined;\n\t\tconst clientIp = resolveClientIp(headerIp ?? socketIp ?? undefined, c.req.raw.headers);\n\t\tif (clientIp) ctx.meta.clientIp = clientIp;\n\t\tc.set('_fonderie', ctx);\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Hono\n// MiddlewareHandler. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\nexport function adapt(middleware: Middleware): MiddlewareHandler {\n\treturn async (c: Context, next) => {\n\t\tconst ctx = c.get('_fonderie');\n\t\tif (!ctx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(ctx, async () => {\n\t\t\tcontinued = true;\n\t\t\treturn new Response();\n\t\t});\n\n\t\tif (continued) {\n\t\t\tawait next();\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ── Pre-adapted middleware ────────────────────────────────────────\n//\n// Drop-in replacements for the fonderie middleware functions — no adapt()\n// needed. Import directly from this package instead of from the source\n// packages, and use them as native Hono middleware.\n//\n// hono.get('/jobs', requireAuth, withWorkspace(store), ...)\n\nexport const requireAuth: MiddlewareHandler = adapt(_requireAuth);\n\n// The three guards below wrap OPTIONAL peers, so the peer is imported lazily\n// on first request — not at module load. MiddlewareHandler is async either\n// way, so the extra await changes nothing for callers.\n\nexport function withWorkspace(store: Parameters<typeof _withWorkspace>[0]): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/workspaces'),\n\t\t\t\t'@fonderie/workspaces',\n\t\t\t\t'withWorkspace()',\n\t\t\t);\n\t\t\tinner = adapt(mod.withWorkspace(store));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/permissions'),\n\t\t\t\t'@fonderie/permissions',\n\t\t\t\t'requirePermission()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requirePermission(operation, permissionKey));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requireFeature(key: string): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/billing'),\n\t\t\t\t'@fonderie/billing',\n\t\t\t\t'requireFeature()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requireFeature(key));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Hono app. Returns the same app so you can add\n// routes after mount() — fonderie infra is the notFound handler, so\n// user routes always take priority:\n//\n// const api = mount(hono, fonderie)\n// api.get('/v1/todos', requireAuth, handler)\n// export default hono\n\n// mount() wires fonderie's infrastructure routes as the notFound fallback so\n// user routes always take priority. Call bridge() yourself before your routes\n// to ensure _fonderie is populated for them.\nexport function mount(hono: Hono, fonderie: FonderieApp): Hono {\n\thono.notFound((c) => {\n\t\t// bridge() consumed the raw body (see its no-clone note) and core's\n\t\t// parser re-materialized ctx.request with the buffered bytes — route\n\t\t// fonderie's handling through THAT. Without bridge (no ctx), the raw\n\t\t// request is untouched and safe to hand over directly.\n\t\tconst ctx = c.get('_fonderie') as IFonderieContext | undefined;\n\t\treturn fonderie.handle(ctx?.request ?? c.req.raw);\n\t});\n\treturn hono;\n}\n\n// ── App-level CORS ────────────────────────────────────────────────\n//\n// Native Hono middleware speaking core's CORS contract — same options and\n// defaults as withCors, so the headers @fonderie/client sends are allowed out\n// of the box (unlike hono/cors, whose defaults know nothing about them).\n// Register it on the Hono app itself so it covers EVERY route, including\n// ones outside the fonderie pipeline: fonderie.use(withCors()) only guards\n// the mounted basePath.\n//\n// app.use('*', cors({ credentials: true, origin: process.env.FRONTEND_URL! }))\n\nexport function cors(options?: CorsOptions): MiddlewareHandler {\n\tconst resolved = resolveCorsOptions(options);\n\treturn async (c, next) => {\n\t\tconst corsHeaders = corsHeadersFor(resolved, c.req.header('origin') ?? '');\n\t\t// Preflight — respond immediately, skip the pipeline\n\t\tif (c.req.method === 'OPTIONS') {\n\t\t\treturn c.body(null, 204, corsHeaders);\n\t\t}\n\t\tawait next();\n\t\tfor (const [k, v] of Object.entries(corsHeaders)) {\n\t\t\tc.res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EAAE,IAAI,WAAW;AAC7B,WAAO,SAAS,OAAO,KAAK,WAAW,EAAE,IAAI,GAAG;AAAA,EACjD,CAAC;AACD,SAAO;AACR;AAaO,SAAS,KAAK,SAA0C;AAC9D,QAAM,WAAW,mBAAmB,OAAO;AAC3C,SAAO,OAAO,GAAG,SAAS;AACzB,UAAM,cAAc,eAAe,UAAU,EAAE,IAAI,OAAO,QAAQ,KAAK,EAAE;AAEzE,QAAI,EAAE,IAAI,WAAW,WAAW;AAC/B,aAAO,EAAE,KAAK,MAAM,KAAK,WAAW;AAAA,IACrC;AACA,UAAM,KAAK;AACX,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,WAAW,GAAG;AACjD,QAAE,IAAI,QAAQ,IAAI,GAAG,CAAC;AAAA,IACvB;AAAA,EACD;AACD;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@fonderie/adapter-hono",
3
- "version": "6.0.1",
3
+ "version": "6.1.0",
4
+ "fonderie": { "stability": "stable" },
4
5
  "description": "Hono adapter for fonderiejs \u2014 bridge(), adapt(), mount() to use fonderie middleware in native Hono routes.",
5
6
  "keywords": [
6
7
  "fonderiejs",
@@ -35,7 +36,7 @@
35
36
  "check": "biome check --write src"
36
37
  },
37
38
  "peerDependencies": {
38
- "@fonderie/core": "^0.10.1",
39
+ "@fonderie/core": "^0.11.0",
39
40
  "@fonderie/workspaces": "^6.0.0",
40
41
  "@fonderie/permissions": "^5.0.0",
41
42
  "@fonderie/billing": "^9.0.0",