@verivyx/paywall-hono 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -17,6 +17,31 @@ function pathMatchesAny(pathname, patterns) {
17
17
  return new RegExp("^" + regexStr + "$").test(pathname);
18
18
  });
19
19
  }
20
+ function publicUrl(req, trustProxy) {
21
+ if (!trustProxy) return req.url;
22
+ const u = new URL(req.url);
23
+ const fwdProto = req.headers.get("x-forwarded-proto");
24
+ if (fwdProto) {
25
+ const p = fwdProto.split(",")[0];
26
+ if (p !== void 0) u.protocol = p.trim() + ":";
27
+ }
28
+ const fwdHost = req.headers.get("x-forwarded-host") ?? req.headers.get("host");
29
+ if (fwdHost) {
30
+ const h = fwdHost.split(",")[0];
31
+ if (h !== void 0) {
32
+ const trimmed = h.trim();
33
+ const colonIdx = trimmed.lastIndexOf(":");
34
+ if (colonIdx !== -1) {
35
+ u.hostname = trimmed.slice(0, colonIdx);
36
+ u.port = trimmed.slice(colonIdx + 1);
37
+ } else {
38
+ u.hostname = trimmed;
39
+ u.port = "";
40
+ }
41
+ }
42
+ }
43
+ return u.toString();
44
+ }
20
45
  function lastPathSegment(pathname) {
21
46
  const segments = pathname.split("/").filter((s) => s.length > 0);
22
47
  const last = segments[segments.length - 1];
@@ -63,15 +88,16 @@ function verivyxHono(opts) {
63
88
  function buildCoreRequest(c) {
64
89
  const raw = c.req.raw;
65
90
  const ip = resolveIp(c, trustProxy);
91
+ const url = publicUrl(raw, trustProxy);
66
92
  if (ip !== void 0) {
67
93
  const headers = new Headers(raw.headers);
68
94
  headers.set("x-real-ip", ip);
69
- return new Request(raw, { headers });
95
+ return new Request(url, { method: raw.method, headers });
70
96
  } else {
71
97
  const headers = new Headers(raw.headers);
72
98
  headers.delete("x-real-ip");
73
99
  headers.delete("x-forwarded-for");
74
- return new Request(raw, { headers });
100
+ return new Request(url, { method: raw.method, headers });
75
101
  }
76
102
  }
77
103
  return {
@@ -86,7 +112,7 @@ function verivyxHono(opts) {
86
112
  const isPreviewCandidate = decision.reason === "crawler" || decision.reason === "human-unverified";
87
113
  if (isPreviewCandidate && o?.seoPreview !== void 0) {
88
114
  return withAdvertiseHeaders(
89
- paywall.buildSeoPreviewResponse(slug, raw.url, o.seoPreview),
115
+ paywall.buildSeoPreviewResponse(slug, publicUrl(raw, trustProxy), o.seoPreview),
90
116
  opts?.advertise
91
117
  );
92
118
  }
@@ -119,7 +145,7 @@ function verivyxHono(opts) {
119
145
  const isPreviewCandidate = decision.reason === "crawler" || decision.reason === "human-unverified";
120
146
  if (isPreviewCandidate && opts?.seoPreview !== void 0) {
121
147
  return withAdvertiseHeaders(
122
- paywall.buildSeoPreviewResponse(slug, c.req.raw.url, opts.seoPreview),
148
+ paywall.buildSeoPreviewResponse(slug, publicUrl(c.req.raw, trustProxy), opts.seoPreview),
123
149
  opts.advertise
124
150
  );
125
151
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["rslLinkHeader","contentUsageHeader","verivyx","createSearchCrawlerVerifier","buildSeoPreviewResponse","attachPaymentResponse"],"mappings":";;;;;AAiGA,SAAS,SAAS,GAAA,EAAoD;AACpE,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,GAAA,KAAQ,MAAA,IAAa,QAAQ,EAAA,EAAI;AACnD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAC9B,EAAA,OAAO,KAAA,KAAU,MAAA,GAAY,KAAA,CAAM,IAAA,MAAU,MAAA,GAAY,MAAA;AAC3D;AAOA,SAAS,cAAA,CAAe,UAAkB,QAAA,EAA6B;AACrE,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,CAAC,OAAA,KAAY;AAEhC,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,CAAQ,mBAAA,EAAqB,MAAM,C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AAG,CAAA;AACtC,YAAA,CAAA,CAAE,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,kBAAA,EAAoB,SAAS,eAAe,CAAA;AAAA,UAChE;AACA,UAAA;AAAA,QACF;AAIA,QAAA,MAAM,kBAAA,GACJ,QAAA,CAAS,MAAA,KAAW,SAAA,IAAa,SAAS,MAAA,KAAW,kBAAA;AACvD,QAAA,IAAI,kBAAA,IAAsB,IAAA,EAAM,UAAA,KAAe,MAAA,EAAW;AACxD,UAAA,OAAO,oBAAA;AAAA,YACLD,gCAAwB,IAAA,EAAM,CAAA,CAAE,IAAI,GAAA,CAAI,GAAA,EAAK,KAAK,UAAU,CAAA;AAAA,YAC5D,IAAA,CAAK;AAAA,WACP;AAAA,QACF;AACA,QAAA,OAAO,oBAAA,CAAqB,QAAA,CAAS,QAAA,EAAS,EAAG,MAAM,SAAS,CAAA;AAAA,MAClE,CAAA;AAAA,IACF;AAAA,GACF;AACF;AAeO,SAAS,sBAAsB,IAAA,EAA8C;AAClF,EAAA,OAAO,WAAA,CAAY,IAAI,CAAA,CAAE,UAAA,EAAW;AACtC","file":"index.cjs","sourcesContent":["/**\n * @verivyx/paywall-hono\n *\n * Hono adapter for the Verivyx paywall SDK (Cloudflare Workers / Vercel Edge).\n *\n * Thin layer — all gate logic lives in @verivyx/paywall core.\n * This module handles:\n * 1. IP resolution from Cloudflare / proxy headers (CF-Connecting-IP first).\n * 2. Cloning the Web `Request` with the resolved IP in `x-real-ip`.\n * 3. Calling core `protect()` (decision overload).\n * 4. Returning `decision.response()` when denied (handler NOT called).\n * 5. Attaching `PAYMENT-RESPONSE` header when a settlement receipt exists.\n *\n * Edge-portable: NO `node:*` imports. Uses only Web Platform APIs and Hono types.\n *\n * @example\n * ```ts\n * import { verivyxHono } from \"@verivyx/paywall-hono\";\n * const vx = verivyxHono({ domain: \"example.com\", token: process.env.VX_TOKEN });\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\n * ```\n */\n\nimport {\n verivyx,\n createSearchCrawlerVerifier,\n buildSeoPreviewResponse,\n attachPaymentResponse,\n rslLinkHeader,\n contentUsageHeader,\n} from \"@verivyx/paywall\";\nimport type { VerivyxOptions, Verivyx, DiscoveryOptions } from \"@verivyx/paywall\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the Hono adapter.\n * Extends core VerivyxOptions with edge-specific controls.\n */\nexport interface HonoAdapterOptions extends VerivyxOptions {\n /**\n * When true (default), read the client IP from Cloudflare / proxy headers:\n * CF-Connecting-IP → X-Forwarded-For first hop → X-Real-IP.\n * Set to false if running without a trusted proxy.\n */\n trustProxy?: boolean;\n\n /**\n * Override the reverse-DNS search-crawler verifier injected into the core.\n * When omitted, `createSearchCrawlerVerifier()` is used.\n */\n verifyCrawlerDns?: (ip: string, ua: string) => Promise<boolean>;\n\n /**\n * Override the Web Bot Auth verifier injected into the core.\n * When omitted, the core's bundled RFC 9421 verifier is used.\n */\n verifyWebBotAuth?: (req: Request) => Promise<boolean>;\n\n /**\n * @internal\n * Inject a pre-built `Verivyx` core instance. Used in tests via\n * `verivyx.mock({...})` to avoid any network access. Production code\n * should never set this; omit it and the adapter constructs the real core.\n */\n _core?: Verivyx;\n\n /**\n * When set, attach RSL `Link` and AIPREF `Content-Usage` headers to both\n * the denied (402) and allowed handler responses.\n * Default undefined = OFF (no headers added; existing behavior unchanged).\n */\n advertise?: DiscoveryOptions;\n\n /**\n * When set, unverified humans and search crawlers (reason: \"human-unverified\"\n * or \"crawler\") receive a 200 HTML teaser page instead of a bare 402.\n * Bots / agents (reason: \"bot-unpaid\") still get the 402 x402 response.\n *\n * Used by both `protect()` (when set on the factory opts) and `middleware()`.\n * `protect()` also accepts `seoPreview` in its per-call options `o`; if both\n * are set, the per-call value takes precedence.\n */\n seoPreview?: (ctx: { slug: string }) => { title: string; excerpt: string };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the first (client-most) hop from an `X-Forwarded-For` header value.\n * The header may contain a comma-separated list; the leftmost is the client.\n */\nfunction firstHop(xff: string | null | undefined): string | undefined {\n if (xff === null || xff === undefined || xff === \"\") {\n return undefined;\n }\n const first = xff.split(\",\")[0];\n return first !== undefined ? first.trim() || undefined : undefined;\n}\n\n/**\n * Return true when `pathname` matches any of the `patterns`.\n * Supports `*` (single-segment wildcard) and `**` (multi-segment wildcard).\n * Performs an anchored full-path match.\n */\nfunction pathMatchesAny(pathname: string, patterns: string[]): boolean {\n return patterns.some((pattern) => {\n // Escape regex metacharacters except * which we handle specially.\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Replace ** before * so the two-step substitution is order-safe.\n const regexStr = escaped\n .replace(/\\*\\*/g, \"\u0001\") // placeholder for **\n .replace(/\\*/g, \"[^/]*\") // single-segment wildcard\n .replace(/\u0001/g, \".*\"); // multi-segment wildcard\n return new RegExp(\"^\" + regexStr + \"$\").test(pathname);\n });\n}\n\n/**\n * Extract the last non-empty path segment from a URL pathname.\n * Used as a fallback slug when `c.req.param(\"slug\")` is unavailable.\n */\nfunction lastPathSegment(pathname: string): string {\n const segments = pathname.split(\"/\").filter((s) => s.length > 0);\n const last = segments[segments.length - 1];\n if (last === undefined) {\n return \"\";\n }\n try {\n return decodeURIComponent(last);\n } catch {\n return last;\n }\n}\n\n/**\n * Resolve the trusted client IP from Hono context headers.\n *\n * Precedence (Cloudflare Workers best-practice order):\n * 1. CF-Connecting-IP — set by Cloudflare edge (single trusted value).\n * 2. X-Forwarded-For first hop — set by other proxies / Vercel.\n * 3. X-Real-IP — generic proxy header.\n * Returns undefined when trustProxy === false or no header is present.\n */\nfunction resolveIp(c: Context, trustProxy: boolean): string | undefined {\n if (!trustProxy) {\n return undefined;\n }\n const cfIp = c.req.header(\"cf-connecting-ip\");\n if (cfIp !== undefined && cfIp !== \"\") {\n return cfIp;\n }\n const xff = c.req.header(\"x-forwarded-for\");\n const hop = firstHop(xff);\n if (hop !== undefined) {\n return hop;\n }\n const xri = c.req.header(\"x-real-ip\");\n return xri !== undefined && xri !== \"\" ? xri : undefined;\n}\n\n/**\n * Attach RSL + AIPREF discovery headers to a Web Response by cloning it.\n * Appends to any existing `Link` (preserves prior values); sets `Content-Usage`.\n * Returns the same Response unchanged when `advertise` is undefined.\n */\nfunction withAdvertiseHeaders(res: Response, advertise: DiscoveryOptions | undefined): Response {\n if (advertise === undefined) {\n return res;\n }\n const headers = new Headers(res.headers);\n headers.append(\"Link\", rslLinkHeader(advertise));\n headers.set(\"Content-Usage\", contentUsageHeader(advertise));\n return new Response(res.body, { status: res.status, statusText: res.statusText, headers });\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Verivyx Hono adapter.\n *\n * Returns an object with `protect(handler)` (per-route gate) and\n * `middleware()` (whole-app settling gate).\n *\n * ```ts\n * const vx = verivyxHono({ domain: \"example.com\", token: \"...\" });\n * // Per-route:\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\n * // Whole-app:\n * app.use(\"*\", vx.middleware());\n * ```\n */\nexport function verivyxHono(opts?: HonoAdapterOptions): {\n protect(\n handler: (c: Context) => Response | Promise<Response>,\n o?: { seoPreview?: (c: { slug: string }) => { title: string; excerpt: string } },\n ): MiddlewareHandler;\n middleware(): MiddlewareHandler;\n} {\n // Resolve the core: use the injected `_core` (tests) or build the real one.\n // Only pass `verifyWebBotAuth` to the core deps when the caller overrode it;\n // the core bundled default is correct otherwise.\n const vx: Verivyx =\n opts?._core ??\n verivyx(opts, {\n verifyCrawlerDns:\n opts?.verifyCrawlerDns ?? createSearchCrawlerVerifier(),\n ...(opts?.verifyWebBotAuth !== undefined\n ? { verifyWebBotAuth: opts.verifyWebBotAuth }\n : {}),\n });\n\n const trustProxy = opts?.trustProxy !== false; // default true\n\n /**\n * Build a core-compatible `Request` from a Hono context.\n * Resolves the trusted client IP (CF/proxy headers) and sets `x-real-ip`\n * on the cloned request, or strips forwarding headers when trustProxy:false.\n *\n * Security invariant: a client can never inject a fake IP into the core\n * classifier — either CF/proxy value wins, or no IP is seen at all.\n */\n function buildCoreRequest(c: Context): Request {\n const raw = c.req.raw;\n const ip = resolveIp(c, trustProxy);\n if (ip !== undefined) {\n const headers = new Headers(raw.headers);\n headers.set(\"x-real-ip\", ip);\n return new Request(raw, { headers });\n } else {\n // trustProxy === false: strip forwarding headers so the client cannot\n // inject a spoofed IP into the core.\n const headers = new Headers(raw.headers);\n headers.delete(\"x-real-ip\");\n headers.delete(\"x-forwarded-for\");\n return new Request(raw, { headers });\n }\n }\n\n return {\n protect(\n handler: (c: Context) => Response | Promise<Response>,\n o?: { seoPreview?: (c: { slug: string }) => { title: string; excerpt: string } },\n ): MiddlewareHandler {\n return async function verivyxHonoGuard(c): Promise<Response> {\n // 1. Build a core-compatible request (IP resolution + header hygiene).\n const coreReq = buildCoreRequest(c);\n const raw = c.req.raw;\n\n // 2. Resolve slug.\n // Priority: Hono named param \"slug\" > last URL path segment.\n const paramSlug: string | undefined = c.req.param(\"slug\");\n const slug: string =\n (paramSlug !== undefined && paramSlug !== \"\")\n ? paramSlug\n : lastPathSegment(new URL(raw.url).pathname);\n\n // 3. Ask the core to evaluate the request (decision overload).\n const decision = await vx.protect(coreReq, { slug });\n\n // 4. Denied — check if this is a crawler/human-unverified that we can\n // serve an SEO preview to instead of a bare 402. Handler NOT called.\n if (!decision.allowed) {\n const isPreviewCandidate =\n decision.reason === \"crawler\" || decision.reason === \"human-unverified\";\n if (isPreviewCandidate && o?.seoPreview !== undefined) {\n return withAdvertiseHeaders(\n buildSeoPreviewResponse(slug, raw.url, o.seoPreview),\n opts?.advertise,\n );\n }\n return withAdvertiseHeaders(decision.response(), opts?.advertise);\n }\n\n // 5. Allowed — call the original Hono handler.\n const res = await handler(c);\n\n // 6. Attach the settlement receipt header when a payment was processed,\n // then attach discovery headers (single clone when both apply).\n return withAdvertiseHeaders(\n attachPaymentResponse(res, decision.paymentResponse),\n opts?.advertise,\n );\n };\n },\n\n middleware(): MiddlewareHandler {\n return async (c, next) => {\n // 1. Path-match filter: when match is set, skip non-matching paths.\n const pathname = c.req.path;\n if (opts?.match !== undefined && opts.match.length > 0 && !pathMatchesAny(pathname, opts.match)) {\n return next();\n }\n\n // 2. Build a core-compatible request (IP resolution + header hygiene).\n const coreReq = buildCoreRequest(c);\n\n // 3. Slug = last path segment (middleware has no named :slug param).\n const slug = pathname.split(\"/\").filter(Boolean).pop() ?? \"\";\n\n // 4. Gate decision.\n const decision = await vx.protect(coreReq, { slug });\n\n if (decision.allowed) {\n // 5a. Allowed — run downstream handlers first.\n await next();\n // 5b. Attach settlement receipt on the outbound response.\n // After next(), c.res holds the downstream Response.\n // Reassign to a mutable clone so we can set the header.\n if (decision.paymentResponse !== undefined) {\n c.res = new Response(c.res.body, c.res);\n c.res.headers.set(\"PAYMENT-RESPONSE\", decision.paymentResponse);\n }\n return;\n }\n\n // 5c. Blocked — check if this is a crawler/human-unverified that we can\n // serve an SEO preview to instead of a bare 402. next() is NOT called.\n const isPreviewCandidate =\n decision.reason === \"crawler\" || decision.reason === \"human-unverified\";\n if (isPreviewCandidate && opts?.seoPreview !== undefined) {\n return withAdvertiseHeaders(\n buildSeoPreviewResponse(slug, c.req.raw.url, opts.seoPreview),\n opts.advertise,\n );\n }\n return withAdvertiseHeaders(decision.response(), opts?.advertise);\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Top-level convenience export\n// ---------------------------------------------------------------------------\n\n/**\n * Whole-app Hono middleware that gates every matched route behind the\n * Verivyx settling paywall.\n *\n * ```ts\n * import { verivyxHonoMiddleware } from \"@verivyx/paywall-hono\";\n * app.use(\"*\", verivyxHonoMiddleware({ domain: \"example.com\", token: \"...\" }));\n * ```\n */\nexport function verivyxHonoMiddleware(opts?: HonoAdapterOptions): MiddlewareHandler {\n return verivyxHono(opts).middleware();\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":["rslLinkHeader","contentUsageHeader","verivyx","createSearchCrawlerVerifier","buildSeoPreviewResponse","attachPaymentResponse"],"mappings":";;;;;AAiGA,SAAS,SAAS,GAAA,EAAoD;AACpE,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,GAAA,KAAQ,MAAA,IAAa,QAAQ,EAAA,EAAI;AACnD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAC9B,EAAA,OAAO,KAAA,KAAU,MAAA,GAAY,KAAA,CAAM,IAAA,MAAU,MAAA,GAAY,MAAA;AAC3D;AAOA,SAAS,cAAA,CAAe,UAAkB,QAAA,EAA6B;AACrE,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,CAAC,OAAA,KAAY;AAEhC,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,CAAQ,mBAAA,EAAqB,MAAM,CAAA;AAE3D,IAAA,MAAM,QAAA,GAAW,OAAA,CACd,OAAA,CAAQ,OAAA,EAAS,GAAG,CAAA,CACpB,OAAA,CAAQ,KAAA,EAAO,OAAO,CAAA,CACtB,OAAA,CAAQ,IAAA,EAAM,IAAI,CAAA;AACrB,IAAA,OAAO,IAAI,MAAA,CAAO,GAAA,GAAM,WAAW,GAAG,CAAA,CAAE,KAAK,QAAQ,CAAA;AAAA,EACvD,CAAC,CAAA;AACH;AASA,SAAS,SAAA,CAAU,KAAc,UAAA,EAA6B;AAC5D,EAAA,IAAI,CAAC,UAAA,EAAY,OAAO,GAAA,CAAI,GAAA;AAC5B,EAAA,MAAM,CAAA,GAAI,IAAI,GAAA,CAAI,GAAA,CAAI,GAAG,CAAA;AACzB,EAAA,MAAM,QAAA,GAAW,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,mBAAmB,CAAA;AACpD,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,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,YAC/E,IAAA,CAAK;AAAA,WACP;AAAA,QACF;AACA,QAAA,OAAO,oBAAA,CAAqB,QAAA,CAAS,QAAA,EAAS,EAAG,MAAM,SAAS,CAAA;AAAA,MAClE,CAAA;AAAA,IACF;AAAA,GACF;AACF;AAeO,SAAS,sBAAsB,IAAA,EAA8C;AAClF,EAAA,OAAO,WAAA,CAAY,IAAI,CAAA,CAAE,UAAA,EAAW;AACtC","file":"index.cjs","sourcesContent":["/**\n * @verivyx/paywall-hono\n *\n * Hono adapter for the Verivyx paywall SDK (Cloudflare Workers / Vercel Edge).\n *\n * Thin layer — all gate logic lives in @verivyx/paywall core.\n * This module handles:\n * 1. IP resolution from Cloudflare / proxy headers (CF-Connecting-IP first).\n * 2. Cloning the Web `Request` with the resolved IP in `x-real-ip`.\n * 3. Calling core `protect()` (decision overload).\n * 4. Returning `decision.response()` when denied (handler NOT called).\n * 5. Attaching `PAYMENT-RESPONSE` header when a settlement receipt exists.\n *\n * Edge-portable: NO `node:*` imports. Uses only Web Platform APIs and Hono types.\n *\n * @example\n * ```ts\n * import { verivyxHono } from \"@verivyx/paywall-hono\";\n * const vx = verivyxHono({ domain: \"example.com\", token: process.env.VX_TOKEN });\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\n * ```\n */\n\nimport {\n verivyx,\n createSearchCrawlerVerifier,\n buildSeoPreviewResponse,\n attachPaymentResponse,\n rslLinkHeader,\n contentUsageHeader,\n} from \"@verivyx/paywall\";\nimport type { VerivyxOptions, Verivyx, DiscoveryOptions } from \"@verivyx/paywall\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the Hono adapter.\n * Extends core VerivyxOptions with edge-specific controls.\n */\nexport interface HonoAdapterOptions extends VerivyxOptions {\n /**\n * When true (default), read the client IP from Cloudflare / proxy headers:\n * CF-Connecting-IP → X-Forwarded-For first hop → X-Real-IP.\n * Set to false if running without a trusted proxy.\n */\n trustProxy?: boolean;\n\n /**\n * Override the reverse-DNS search-crawler verifier injected into the core.\n * When omitted, `createSearchCrawlerVerifier()` is used.\n */\n verifyCrawlerDns?: (ip: string, ua: string) => Promise<boolean>;\n\n /**\n * Override the Web Bot Auth verifier injected into the core.\n * When omitted, the core's bundled RFC 9421 verifier is used.\n */\n verifyWebBotAuth?: (req: Request) => Promise<boolean>;\n\n /**\n * @internal\n * Inject a pre-built `Verivyx` core instance. Used in tests via\n * `verivyx.mock({...})` to avoid any network access. Production code\n * should never set this; omit it and the adapter constructs the real core.\n */\n _core?: Verivyx;\n\n /**\n * When set, attach RSL `Link` and AIPREF `Content-Usage` headers to both\n * the denied (402) and allowed handler responses.\n * Default undefined = OFF (no headers added; existing behavior unchanged).\n */\n advertise?: DiscoveryOptions;\n\n /**\n * When set, unverified humans and search crawlers (reason: \"human-unverified\"\n * or \"crawler\") receive a 200 HTML teaser page instead of a bare 402.\n * Bots / agents (reason: \"bot-unpaid\") still get the 402 x402 response.\n *\n * Used by both `protect()` (when set on the factory opts) and `middleware()`.\n * `protect()` also accepts `seoPreview` in its per-call options `o`; if both\n * are set, the per-call value takes precedence.\n */\n seoPreview?: (ctx: { slug: string }) => { title: string; excerpt: string };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the first (client-most) hop from an `X-Forwarded-For` header value.\n * The header may contain a comma-separated list; the leftmost is the client.\n */\nfunction firstHop(xff: string | null | undefined): string | undefined {\n if (xff === null || xff === undefined || xff === \"\") {\n return undefined;\n }\n const first = xff.split(\",\")[0];\n return first !== undefined ? first.trim() || undefined : undefined;\n}\n\n/**\n * Return true when `pathname` matches any of the `patterns`.\n * Supports `*` (single-segment wildcard) and `**` (multi-segment wildcard).\n * Performs an anchored full-path match.\n */\nfunction pathMatchesAny(pathname: string, patterns: string[]): boolean {\n return patterns.some((pattern) => {\n // Escape regex metacharacters except * which we handle specially.\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Replace ** before * so the two-step substitution is order-safe.\n const regexStr = escaped\n .replace(/\\*\\*/g, \"\u0001\") // placeholder for **\n .replace(/\\*/g, \"[^/]*\") // single-segment wildcard\n .replace(/\u0001/g, \".*\"); // multi-segment wildcard\n return new RegExp(\"^\" + regexStr + \"$\").test(pathname);\n });\n}\n\n/**\n * Rebuild the absolute request URL using `X-Forwarded-Host` / `X-Forwarded-Proto`\n * when `trustProxy` is enabled, so the x402 resource URL reflects the public host\n * rather than the internal address assigned by a reverse proxy.\n *\n * When `trustProxy` is false the raw request URL is returned unchanged.\n */\nfunction publicUrl(req: Request, trustProxy: boolean): string {\n if (!trustProxy) return req.url;\n const u = new URL(req.url);\n const fwdProto = req.headers.get(\"x-forwarded-proto\");\n if (fwdProto) {\n const p = fwdProto.split(\",\")[0];\n if (p !== undefined) u.protocol = p.trim() + \":\";\n }\n const fwdHost = req.headers.get(\"x-forwarded-host\") ?? req.headers.get(\"host\");\n if (fwdHost) {\n const h = fwdHost.split(\",\")[0];\n if (h !== undefined) {\n const trimmed = h.trim();\n // If the forwarded host includes a port (\"host:port\"), split it.\n // Otherwise clear any internal port so we only expose the public host.\n const colonIdx = trimmed.lastIndexOf(\":\");\n if (colonIdx !== -1) {\n u.hostname = trimmed.slice(0, colonIdx);\n u.port = trimmed.slice(colonIdx + 1);\n } else {\n u.hostname = trimmed;\n u.port = \"\";\n }\n }\n }\n return u.toString();\n}\n\n/**\n * Extract the last non-empty path segment from a URL pathname.\n * Used as a fallback slug when `c.req.param(\"slug\")` is unavailable.\n */\nfunction lastPathSegment(pathname: string): string {\n const segments = pathname.split(\"/\").filter((s) => s.length > 0);\n const last = segments[segments.length - 1];\n if (last === undefined) {\n return \"\";\n }\n try {\n return decodeURIComponent(last);\n } catch {\n return last;\n }\n}\n\n/**\n * Resolve the trusted client IP from Hono context headers.\n *\n * Precedence (Cloudflare Workers best-practice order):\n * 1. CF-Connecting-IP — set by Cloudflare edge (single trusted value).\n * 2. X-Forwarded-For first hop — set by other proxies / Vercel.\n * 3. X-Real-IP — generic proxy header.\n * Returns undefined when trustProxy === false or no header is present.\n */\nfunction resolveIp(c: Context, trustProxy: boolean): string | undefined {\n if (!trustProxy) {\n return undefined;\n }\n const cfIp = c.req.header(\"cf-connecting-ip\");\n if (cfIp !== undefined && cfIp !== \"\") {\n return cfIp;\n }\n const xff = c.req.header(\"x-forwarded-for\");\n const hop = firstHop(xff);\n if (hop !== undefined) {\n return hop;\n }\n const xri = c.req.header(\"x-real-ip\");\n return xri !== undefined && xri !== \"\" ? xri : undefined;\n}\n\n/**\n * Attach RSL + AIPREF discovery headers to a Web Response by cloning it.\n * Appends to any existing `Link` (preserves prior values); sets `Content-Usage`.\n * Returns the same Response unchanged when `advertise` is undefined.\n */\nfunction withAdvertiseHeaders(res: Response, advertise: DiscoveryOptions | undefined): Response {\n if (advertise === undefined) {\n return res;\n }\n const headers = new Headers(res.headers);\n headers.append(\"Link\", rslLinkHeader(advertise));\n headers.set(\"Content-Usage\", contentUsageHeader(advertise));\n return new Response(res.body, { status: res.status, statusText: res.statusText, headers });\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Verivyx Hono adapter.\n *\n * Returns an object with `protect(handler)` (per-route gate) and\n * `middleware()` (whole-app settling gate).\n *\n * ```ts\n * const vx = verivyxHono({ domain: \"example.com\", token: \"...\" });\n * // Per-route:\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\n * // Whole-app:\n * app.use(\"*\", vx.middleware());\n * ```\n */\nexport function verivyxHono(opts?: HonoAdapterOptions): {\n protect(\n handler: (c: Context) => Response | Promise<Response>,\n o?: { seoPreview?: (c: { slug: string }) => { title: string; excerpt: string } },\n ): MiddlewareHandler;\n middleware(): MiddlewareHandler;\n} {\n // Resolve the core: use the injected `_core` (tests) or build the real one.\n // Only pass `verifyWebBotAuth` to the core deps when the caller overrode it;\n // the core bundled default is correct otherwise.\n const vx: Verivyx =\n opts?._core ??\n verivyx(opts, {\n verifyCrawlerDns:\n opts?.verifyCrawlerDns ?? createSearchCrawlerVerifier(),\n ...(opts?.verifyWebBotAuth !== undefined\n ? { verifyWebBotAuth: opts.verifyWebBotAuth }\n : {}),\n });\n\n const trustProxy = opts?.trustProxy !== false; // default true\n\n /**\n * Build a core-compatible `Request` from a Hono context.\n * Resolves the trusted client IP (CF/proxy headers) and sets `x-real-ip`\n * on the cloned request, or strips forwarding headers when trustProxy:false.\n *\n * Security invariant: a client can never inject a fake IP into the core\n * classifier — either CF/proxy value wins, or no IP is seen at all.\n */\n function buildCoreRequest(c: Context): Request {\n const raw = c.req.raw;\n const ip = resolveIp(c, trustProxy);\n const url = publicUrl(raw, trustProxy);\n if (ip !== undefined) {\n const headers = new Headers(raw.headers);\n headers.set(\"x-real-ip\", ip);\n return new Request(url, { method: raw.method, headers });\n } else {\n // trustProxy === false: strip forwarding headers so the client cannot\n // inject a spoofed IP into the core.\n const headers = new Headers(raw.headers);\n headers.delete(\"x-real-ip\");\n headers.delete(\"x-forwarded-for\");\n return new Request(url, { method: raw.method, headers });\n }\n }\n\n return {\n protect(\n handler: (c: Context) => Response | Promise<Response>,\n o?: { seoPreview?: (c: { slug: string }) => { title: string; excerpt: string } },\n ): MiddlewareHandler {\n return async function verivyxHonoGuard(c): Promise<Response> {\n // 1. Build a core-compatible request (IP resolution + header hygiene).\n const coreReq = buildCoreRequest(c);\n const raw = c.req.raw;\n\n // 2. Resolve slug.\n // Priority: Hono named param \"slug\" > last URL path segment.\n const paramSlug: string | undefined = c.req.param(\"slug\");\n const slug: string =\n (paramSlug !== undefined && paramSlug !== \"\")\n ? paramSlug\n : lastPathSegment(new URL(raw.url).pathname);\n\n // 3. Ask the core to evaluate the request (decision overload).\n const decision = await vx.protect(coreReq, { slug });\n\n // 4. Denied — check if this is a crawler/human-unverified that we can\n // serve an SEO preview to instead of a bare 402. Handler NOT called.\n if (!decision.allowed) {\n const isPreviewCandidate =\n decision.reason === \"crawler\" || decision.reason === \"human-unverified\";\n if (isPreviewCandidate && o?.seoPreview !== undefined) {\n return withAdvertiseHeaders(\n buildSeoPreviewResponse(slug, publicUrl(raw, trustProxy), o.seoPreview),\n opts?.advertise,\n );\n }\n return withAdvertiseHeaders(decision.response(), opts?.advertise);\n }\n\n // 5. Allowed — call the original Hono handler.\n const res = await handler(c);\n\n // 6. Attach the settlement receipt header when a payment was processed,\n // then attach discovery headers (single clone when both apply).\n return withAdvertiseHeaders(\n attachPaymentResponse(res, decision.paymentResponse),\n opts?.advertise,\n );\n };\n },\n\n middleware(): MiddlewareHandler {\n return async (c, next) => {\n // 1. Path-match filter: when match is set, skip non-matching paths.\n const pathname = c.req.path;\n if (opts?.match !== undefined && opts.match.length > 0 && !pathMatchesAny(pathname, opts.match)) {\n return next();\n }\n\n // 2. Build a core-compatible request (IP resolution + header hygiene).\n const coreReq = buildCoreRequest(c);\n\n // 3. Slug = last path segment (middleware has no named :slug param).\n const slug = pathname.split(\"/\").filter(Boolean).pop() ?? \"\";\n\n // 4. Gate decision.\n const decision = await vx.protect(coreReq, { slug });\n\n if (decision.allowed) {\n // 5a. Allowed — run downstream handlers first.\n await next();\n // 5b. Attach settlement receipt on the outbound response.\n // After next(), c.res holds the downstream Response.\n // Reassign to a mutable clone so we can set the header.\n if (decision.paymentResponse !== undefined) {\n c.res = new Response(c.res.body, c.res);\n c.res.headers.set(\"PAYMENT-RESPONSE\", decision.paymentResponse);\n }\n return;\n }\n\n // 5c. Blocked — check if this is a crawler/human-unverified that we can\n // serve an SEO preview to instead of a bare 402. next() is NOT called.\n const isPreviewCandidate =\n decision.reason === \"crawler\" || decision.reason === \"human-unverified\";\n if (isPreviewCandidate && opts?.seoPreview !== undefined) {\n return withAdvertiseHeaders(\n buildSeoPreviewResponse(slug, publicUrl(c.req.raw, trustProxy), opts.seoPreview),\n opts.advertise,\n );\n }\n return withAdvertiseHeaders(decision.response(), opts?.advertise);\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Top-level convenience export\n// ---------------------------------------------------------------------------\n\n/**\n * Whole-app Hono middleware that gates every matched route behind the\n * Verivyx settling paywall.\n *\n * ```ts\n * import { verivyxHonoMiddleware } from \"@verivyx/paywall-hono\";\n * app.use(\"*\", verivyxHonoMiddleware({ domain: \"example.com\", token: \"...\" }));\n * ```\n */\nexport function verivyxHonoMiddleware(opts?: HonoAdapterOptions): MiddlewareHandler {\n return verivyxHono(opts).middleware();\n}\n"]}
package/dist/index.js CHANGED
@@ -15,6 +15,31 @@ function pathMatchesAny(pathname, patterns) {
15
15
  return new RegExp("^" + regexStr + "$").test(pathname);
16
16
  });
17
17
  }
18
+ function publicUrl(req, trustProxy) {
19
+ if (!trustProxy) return req.url;
20
+ const u = new URL(req.url);
21
+ const fwdProto = req.headers.get("x-forwarded-proto");
22
+ if (fwdProto) {
23
+ const p = fwdProto.split(",")[0];
24
+ if (p !== void 0) u.protocol = p.trim() + ":";
25
+ }
26
+ const fwdHost = req.headers.get("x-forwarded-host") ?? req.headers.get("host");
27
+ if (fwdHost) {
28
+ const h = fwdHost.split(",")[0];
29
+ if (h !== void 0) {
30
+ const trimmed = h.trim();
31
+ const colonIdx = trimmed.lastIndexOf(":");
32
+ if (colonIdx !== -1) {
33
+ u.hostname = trimmed.slice(0, colonIdx);
34
+ u.port = trimmed.slice(colonIdx + 1);
35
+ } else {
36
+ u.hostname = trimmed;
37
+ u.port = "";
38
+ }
39
+ }
40
+ }
41
+ return u.toString();
42
+ }
18
43
  function lastPathSegment(pathname) {
19
44
  const segments = pathname.split("/").filter((s) => s.length > 0);
20
45
  const last = segments[segments.length - 1];
@@ -61,15 +86,16 @@ function verivyxHono(opts) {
61
86
  function buildCoreRequest(c) {
62
87
  const raw = c.req.raw;
63
88
  const ip = resolveIp(c, trustProxy);
89
+ const url = publicUrl(raw, trustProxy);
64
90
  if (ip !== void 0) {
65
91
  const headers = new Headers(raw.headers);
66
92
  headers.set("x-real-ip", ip);
67
- return new Request(raw, { headers });
93
+ return new Request(url, { method: raw.method, headers });
68
94
  } else {
69
95
  const headers = new Headers(raw.headers);
70
96
  headers.delete("x-real-ip");
71
97
  headers.delete("x-forwarded-for");
72
- return new Request(raw, { headers });
98
+ return new Request(url, { method: raw.method, headers });
73
99
  }
74
100
  }
75
101
  return {
@@ -84,7 +110,7 @@ function verivyxHono(opts) {
84
110
  const isPreviewCandidate = decision.reason === "crawler" || decision.reason === "human-unverified";
85
111
  if (isPreviewCandidate && o?.seoPreview !== void 0) {
86
112
  return withAdvertiseHeaders(
87
- buildSeoPreviewResponse(slug, raw.url, o.seoPreview),
113
+ buildSeoPreviewResponse(slug, publicUrl(raw, trustProxy), o.seoPreview),
88
114
  opts?.advertise
89
115
  );
90
116
  }
@@ -117,7 +143,7 @@ function verivyxHono(opts) {
117
143
  const isPreviewCandidate = decision.reason === "crawler" || decision.reason === "human-unverified";
118
144
  if (isPreviewCandidate && opts?.seoPreview !== void 0) {
119
145
  return withAdvertiseHeaders(
120
- buildSeoPreviewResponse(slug, c.req.raw.url, opts.seoPreview),
146
+ buildSeoPreviewResponse(slug, publicUrl(c.req.raw, trustProxy), opts.seoPreview),
121
147
  opts.advertise
122
148
  );
123
149
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAiGA,SAAS,SAAS,GAAA,EAAoD;AACpE,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,GAAA,KAAQ,MAAA,IAAa,QAAQ,EAAA,EAAI;AACnD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAC9B,EAAA,OAAO,KAAA,KAAU,MAAA,GAAY,KAAA,CAAM,IAAA,MAAU,MAAA,GAAY,MAAA;AAC3D;AAOA,SAAS,cAAA,CAAe,UAAkB,QAAA,EAA6B;AAC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AAA,IAAI,QAAA,CAAS,oBAAoB,MAAA,EAAW;AAC1C,YAAA,CAAA,CAAE,MAAM,IAAI,QAAA,CAAS,EAAE,GAAA,CAAI,IAAA,EAAM,EAAE,GAAG,CAAA;AACtC,YAAA,CAAA,CAAE,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,kBAAA,EAAoB,SAAS,eAAe,CAAA;AAAA,UAChE;AACA,UAAA;AAAA,QACF;AAIA,QAAA,MAAM,kBAAA,GACJ,QAAA,CAAS,MAAA,KAAW,SAAA,IAAa,SAAS,MAAA,KAAW,kBAAA;AACvD,QAAA,IAAI,kBAAA,IAAsB,IAAA,EAAM,UAAA,KAAe,MAAA,EAAW;AACxD,UAAA,OAAO,oBAAA;AAAA,YACL,wBAAwB,IAAA,EAAM,CAAA,CAAE,IAAI,GAAA,CAAI,GAAA,EAAK,KAAK,UAAU,CAAA;AAAA,YAC5D,IAAA,CAAK;AAAA,WACP;AAAA,QACF;AACA,QAAA,OAAO,oBAAA,CAAqB,QAAA,CAAS,QAAA,EAAS,EAAG,MAAM,SAAS,CAAA;AAAA,MAClE,CAAA;AAAA,IACF;AAAA,GACF;AACF;AAeO,SAAS,sBAAsB,IAAA,EAA8C;AAClF,EAAA,OAAO,WAAA,CAAY,IAAI,CAAA,CAAE,UAAA,EAAW;AACtC","file":"index.js","sourcesContent":["/**\n * @verivyx/paywall-hono\n *\n * Hono adapter for the Verivyx paywall SDK (Cloudflare Workers / Vercel Edge).\n *\n * Thin layer — all gate logic lives in @verivyx/paywall core.\n * This module handles:\n * 1. IP resolution from Cloudflare / proxy headers (CF-Connecting-IP first).\n * 2. Cloning the Web `Request` with the resolved IP in `x-real-ip`.\n * 3. Calling core `protect()` (decision overload).\n * 4. Returning `decision.response()` when denied (handler NOT called).\n * 5. Attaching `PAYMENT-RESPONSE` header when a settlement receipt exists.\n *\n * Edge-portable: NO `node:*` imports. Uses only Web Platform APIs and Hono types.\n *\n * @example\n * ```ts\n * import { verivyxHono } from \"@verivyx/paywall-hono\";\n * const vx = verivyxHono({ domain: \"example.com\", token: process.env.VX_TOKEN });\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\n * ```\n */\n\nimport {\n verivyx,\n createSearchCrawlerVerifier,\n buildSeoPreviewResponse,\n attachPaymentResponse,\n rslLinkHeader,\n contentUsageHeader,\n} from \"@verivyx/paywall\";\nimport type { VerivyxOptions, Verivyx, DiscoveryOptions } from \"@verivyx/paywall\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the Hono adapter.\n * Extends core VerivyxOptions with edge-specific controls.\n */\nexport interface HonoAdapterOptions extends VerivyxOptions {\n /**\n * When true (default), read the client IP from Cloudflare / proxy headers:\n * CF-Connecting-IP → X-Forwarded-For first hop → X-Real-IP.\n * Set to false if running without a trusted proxy.\n */\n trustProxy?: boolean;\n\n /**\n * Override the reverse-DNS search-crawler verifier injected into the core.\n * When omitted, `createSearchCrawlerVerifier()` is used.\n */\n verifyCrawlerDns?: (ip: string, ua: string) => Promise<boolean>;\n\n /**\n * Override the Web Bot Auth verifier injected into the core.\n * When omitted, the core's bundled RFC 9421 verifier is used.\n */\n verifyWebBotAuth?: (req: Request) => Promise<boolean>;\n\n /**\n * @internal\n * Inject a pre-built `Verivyx` core instance. Used in tests via\n * `verivyx.mock({...})` to avoid any network access. Production code\n * should never set this; omit it and the adapter constructs the real core.\n */\n _core?: Verivyx;\n\n /**\n * When set, attach RSL `Link` and AIPREF `Content-Usage` headers to both\n * the denied (402) and allowed handler responses.\n * Default undefined = OFF (no headers added; existing behavior unchanged).\n */\n advertise?: DiscoveryOptions;\n\n /**\n * When set, unverified humans and search crawlers (reason: \"human-unverified\"\n * or \"crawler\") receive a 200 HTML teaser page instead of a bare 402.\n * Bots / agents (reason: \"bot-unpaid\") still get the 402 x402 response.\n *\n * Used by both `protect()` (when set on the factory opts) and `middleware()`.\n * `protect()` also accepts `seoPreview` in its per-call options `o`; if both\n * are set, the per-call value takes precedence.\n */\n seoPreview?: (ctx: { slug: string }) => { title: string; excerpt: string };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the first (client-most) hop from an `X-Forwarded-For` header value.\n * The header may contain a comma-separated list; the leftmost is the client.\n */\nfunction firstHop(xff: string | null | undefined): string | undefined {\n if (xff === null || xff === undefined || xff === \"\") {\n return undefined;\n }\n const first = xff.split(\",\")[0];\n return first !== undefined ? first.trim() || undefined : undefined;\n}\n\n/**\n * Return true when `pathname` matches any of the `patterns`.\n * Supports `*` (single-segment wildcard) and `**` (multi-segment wildcard).\n * Performs an anchored full-path match.\n */\nfunction pathMatchesAny(pathname: string, patterns: string[]): boolean {\n return patterns.some((pattern) => {\n // Escape regex metacharacters except * which we handle specially.\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Replace ** before * so the two-step substitution is order-safe.\n const regexStr = escaped\n .replace(/\\*\\*/g, \"\u0001\") // placeholder for **\n .replace(/\\*/g, \"[^/]*\") // single-segment wildcard\n .replace(/\u0001/g, \".*\"); // multi-segment wildcard\n return new RegExp(\"^\" + regexStr + \"$\").test(pathname);\n });\n}\n\n/**\n * Extract the last non-empty path segment from a URL pathname.\n * Used as a fallback slug when `c.req.param(\"slug\")` is unavailable.\n */\nfunction lastPathSegment(pathname: string): string {\n const segments = pathname.split(\"/\").filter((s) => s.length > 0);\n const last = segments[segments.length - 1];\n if (last === undefined) {\n return \"\";\n }\n try {\n return decodeURIComponent(last);\n } catch {\n return last;\n }\n}\n\n/**\n * Resolve the trusted client IP from Hono context headers.\n *\n * Precedence (Cloudflare Workers best-practice order):\n * 1. CF-Connecting-IP — set by Cloudflare edge (single trusted value).\n * 2. X-Forwarded-For first hop — set by other proxies / Vercel.\n * 3. X-Real-IP — generic proxy header.\n * Returns undefined when trustProxy === false or no header is present.\n */\nfunction resolveIp(c: Context, trustProxy: boolean): string | undefined {\n if (!trustProxy) {\n return undefined;\n }\n const cfIp = c.req.header(\"cf-connecting-ip\");\n if (cfIp !== undefined && cfIp !== \"\") {\n return cfIp;\n }\n const xff = c.req.header(\"x-forwarded-for\");\n const hop = firstHop(xff);\n if (hop !== undefined) {\n return hop;\n }\n const xri = c.req.header(\"x-real-ip\");\n return xri !== undefined && xri !== \"\" ? xri : undefined;\n}\n\n/**\n * Attach RSL + AIPREF discovery headers to a Web Response by cloning it.\n * Appends to any existing `Link` (preserves prior values); sets `Content-Usage`.\n * Returns the same Response unchanged when `advertise` is undefined.\n */\nfunction withAdvertiseHeaders(res: Response, advertise: DiscoveryOptions | undefined): Response {\n if (advertise === undefined) {\n return res;\n }\n const headers = new Headers(res.headers);\n headers.append(\"Link\", rslLinkHeader(advertise));\n headers.set(\"Content-Usage\", contentUsageHeader(advertise));\n return new Response(res.body, { status: res.status, statusText: res.statusText, headers });\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Verivyx Hono adapter.\n *\n * Returns an object with `protect(handler)` (per-route gate) and\n * `middleware()` (whole-app settling gate).\n *\n * ```ts\n * const vx = verivyxHono({ domain: \"example.com\", token: \"...\" });\n * // Per-route:\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\n * // Whole-app:\n * app.use(\"*\", vx.middleware());\n * ```\n */\nexport function verivyxHono(opts?: HonoAdapterOptions): {\n protect(\n handler: (c: Context) => Response | Promise<Response>,\n o?: { seoPreview?: (c: { slug: string }) => { title: string; excerpt: string } },\n ): MiddlewareHandler;\n middleware(): MiddlewareHandler;\n} {\n // Resolve the core: use the injected `_core` (tests) or build the real one.\n // Only pass `verifyWebBotAuth` to the core deps when the caller overrode it;\n // the core bundled default is correct otherwise.\n const vx: Verivyx =\n opts?._core ??\n verivyx(opts, {\n verifyCrawlerDns:\n opts?.verifyCrawlerDns ?? createSearchCrawlerVerifier(),\n ...(opts?.verifyWebBotAuth !== undefined\n ? { verifyWebBotAuth: opts.verifyWebBotAuth }\n : {}),\n });\n\n const trustProxy = opts?.trustProxy !== false; // default true\n\n /**\n * Build a core-compatible `Request` from a Hono context.\n * Resolves the trusted client IP (CF/proxy headers) and sets `x-real-ip`\n * on the cloned request, or strips forwarding headers when trustProxy:false.\n *\n * Security invariant: a client can never inject a fake IP into the core\n * classifier — either CF/proxy value wins, or no IP is seen at all.\n */\n function buildCoreRequest(c: Context): Request {\n const raw = c.req.raw;\n const ip = resolveIp(c, trustProxy);\n if (ip !== undefined) {\n const headers = new Headers(raw.headers);\n headers.set(\"x-real-ip\", ip);\n return new Request(raw, { headers });\n } else {\n // trustProxy === false: strip forwarding headers so the client cannot\n // inject a spoofed IP into the core.\n const headers = new Headers(raw.headers);\n headers.delete(\"x-real-ip\");\n headers.delete(\"x-forwarded-for\");\n return new Request(raw, { headers });\n }\n }\n\n return {\n protect(\n handler: (c: Context) => Response | Promise<Response>,\n o?: { seoPreview?: (c: { slug: string }) => { title: string; excerpt: string } },\n ): MiddlewareHandler {\n return async function verivyxHonoGuard(c): Promise<Response> {\n // 1. Build a core-compatible request (IP resolution + header hygiene).\n const coreReq = buildCoreRequest(c);\n const raw = c.req.raw;\n\n // 2. Resolve slug.\n // Priority: Hono named param \"slug\" > last URL path segment.\n const paramSlug: string | undefined = c.req.param(\"slug\");\n const slug: string =\n (paramSlug !== undefined && paramSlug !== \"\")\n ? paramSlug\n : lastPathSegment(new URL(raw.url).pathname);\n\n // 3. Ask the core to evaluate the request (decision overload).\n const decision = await vx.protect(coreReq, { slug });\n\n // 4. Denied — check if this is a crawler/human-unverified that we can\n // serve an SEO preview to instead of a bare 402. Handler NOT called.\n if (!decision.allowed) {\n const isPreviewCandidate =\n decision.reason === \"crawler\" || decision.reason === \"human-unverified\";\n if (isPreviewCandidate && o?.seoPreview !== undefined) {\n return withAdvertiseHeaders(\n buildSeoPreviewResponse(slug, raw.url, o.seoPreview),\n opts?.advertise,\n );\n }\n return withAdvertiseHeaders(decision.response(), opts?.advertise);\n }\n\n // 5. Allowed — call the original Hono handler.\n const res = await handler(c);\n\n // 6. Attach the settlement receipt header when a payment was processed,\n // then attach discovery headers (single clone when both apply).\n return withAdvertiseHeaders(\n attachPaymentResponse(res, decision.paymentResponse),\n opts?.advertise,\n );\n };\n },\n\n middleware(): MiddlewareHandler {\n return async (c, next) => {\n // 1. Path-match filter: when match is set, skip non-matching paths.\n const pathname = c.req.path;\n if (opts?.match !== undefined && opts.match.length > 0 && !pathMatchesAny(pathname, opts.match)) {\n return next();\n }\n\n // 2. Build a core-compatible request (IP resolution + header hygiene).\n const coreReq = buildCoreRequest(c);\n\n // 3. Slug = last path segment (middleware has no named :slug param).\n const slug = pathname.split(\"/\").filter(Boolean).pop() ?? \"\";\n\n // 4. Gate decision.\n const decision = await vx.protect(coreReq, { slug });\n\n if (decision.allowed) {\n // 5a. Allowed — run downstream handlers first.\n await next();\n // 5b. Attach settlement receipt on the outbound response.\n // After next(), c.res holds the downstream Response.\n // Reassign to a mutable clone so we can set the header.\n if (decision.paymentResponse !== undefined) {\n c.res = new Response(c.res.body, c.res);\n c.res.headers.set(\"PAYMENT-RESPONSE\", decision.paymentResponse);\n }\n return;\n }\n\n // 5c. Blocked — check if this is a crawler/human-unverified that we can\n // serve an SEO preview to instead of a bare 402. next() is NOT called.\n const isPreviewCandidate =\n decision.reason === \"crawler\" || decision.reason === \"human-unverified\";\n if (isPreviewCandidate && opts?.seoPreview !== undefined) {\n return withAdvertiseHeaders(\n buildSeoPreviewResponse(slug, c.req.raw.url, opts.seoPreview),\n opts.advertise,\n );\n }\n return withAdvertiseHeaders(decision.response(), opts?.advertise);\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Top-level convenience export\n// ---------------------------------------------------------------------------\n\n/**\n * Whole-app Hono middleware that gates every matched route behind the\n * Verivyx settling paywall.\n *\n * ```ts\n * import { verivyxHonoMiddleware } from \"@verivyx/paywall-hono\";\n * app.use(\"*\", verivyxHonoMiddleware({ domain: \"example.com\", token: \"...\" }));\n * ```\n */\nexport function verivyxHonoMiddleware(opts?: HonoAdapterOptions): MiddlewareHandler {\n return verivyxHono(opts).middleware();\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAiGA,SAAS,SAAS,GAAA,EAAoD;AACpE,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,GAAA,KAAQ,MAAA,IAAa,QAAQ,EAAA,EAAI;AACnD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAC9B,EAAA,OAAO,KAAA,KAAU,MAAA,GAAY,KAAA,CAAM,IAAA,MAAU,MAAA,GAAY,MAAA;AAC3D;AAOA,SAAS,cAAA,CAAe,UAAkB,QAAA,EAA6B;AACrE,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,CAAC,OAAA,KAAY;AAEhC,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,CAAQ,mBAAA,EAAqB,MAAM,CAAA;AAE3D,IAAA,MAAM,QAAA,GAAW,OAAA,CACd,OAAA,CAAQ,OAAA,EAAS,GAAG,CAAA,CACpB,OAAA,CAAQ,KAAA,EAAO,OAAO,CAAA,CACtB,OAAA,CAAQ,IAAA,EAAM,IAAI,CAAA;AACrB,IAAA,OAAO,IAAI,MAAA,CAAO,GAAA,GAAM,WAAW,GAAG,CAAA,CAAE,KAAK,QAAQ,CAAA;AAAA,EACvD,CAAC,CAAA;AACH;AASA,SAAS,SAAA,CAAU,KAAc,UAAA,EAA6B;AAC5D,EAAA,IAAI,CAAC,UAAA,EAAY,OAAO,GAAA,CAAI,GAAA;AAC5B,EAAA,MAAM,CAAA,GAAI,IAAI,GAAA,CAAI,GAAA,CAAI,GAAG,CAAA;AACzB,EAAA,MAAM,QAAA,GAAW,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,mBAA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U,CAAA,EAAG,IAAA,CAAK,UAAU,CAAA;AAAA,YAC/E,IAAA,CAAK;AAAA,WACP;AAAA,QACF;AACA,QAAA,OAAO,oBAAA,CAAqB,QAAA,CAAS,QAAA,EAAS,EAAG,MAAM,SAAS,CAAA;AAAA,MAClE,CAAA;AAAA,IACF;AAAA,GACF;AACF;AAeO,SAAS,sBAAsB,IAAA,EAA8C;AAClF,EAAA,OAAO,WAAA,CAAY,IAAI,CAAA,CAAE,UAAA,EAAW;AACtC","file":"index.js","sourcesContent":["/**\n * @verivyx/paywall-hono\n *\n * Hono adapter for the Verivyx paywall SDK (Cloudflare Workers / Vercel Edge).\n *\n * Thin layer — all gate logic lives in @verivyx/paywall core.\n * This module handles:\n * 1. IP resolution from Cloudflare / proxy headers (CF-Connecting-IP first).\n * 2. Cloning the Web `Request` with the resolved IP in `x-real-ip`.\n * 3. Calling core `protect()` (decision overload).\n * 4. Returning `decision.response()` when denied (handler NOT called).\n * 5. Attaching `PAYMENT-RESPONSE` header when a settlement receipt exists.\n *\n * Edge-portable: NO `node:*` imports. Uses only Web Platform APIs and Hono types.\n *\n * @example\n * ```ts\n * import { verivyxHono } from \"@verivyx/paywall-hono\";\n * const vx = verivyxHono({ domain: \"example.com\", token: process.env.VX_TOKEN });\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\n * ```\n */\n\nimport {\n verivyx,\n createSearchCrawlerVerifier,\n buildSeoPreviewResponse,\n attachPaymentResponse,\n rslLinkHeader,\n contentUsageHeader,\n} from \"@verivyx/paywall\";\nimport type { VerivyxOptions, Verivyx, DiscoveryOptions } from \"@verivyx/paywall\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the Hono adapter.\n * Extends core VerivyxOptions with edge-specific controls.\n */\nexport interface HonoAdapterOptions extends VerivyxOptions {\n /**\n * When true (default), read the client IP from Cloudflare / proxy headers:\n * CF-Connecting-IP → X-Forwarded-For first hop → X-Real-IP.\n * Set to false if running without a trusted proxy.\n */\n trustProxy?: boolean;\n\n /**\n * Override the reverse-DNS search-crawler verifier injected into the core.\n * When omitted, `createSearchCrawlerVerifier()` is used.\n */\n verifyCrawlerDns?: (ip: string, ua: string) => Promise<boolean>;\n\n /**\n * Override the Web Bot Auth verifier injected into the core.\n * When omitted, the core's bundled RFC 9421 verifier is used.\n */\n verifyWebBotAuth?: (req: Request) => Promise<boolean>;\n\n /**\n * @internal\n * Inject a pre-built `Verivyx` core instance. Used in tests via\n * `verivyx.mock({...})` to avoid any network access. Production code\n * should never set this; omit it and the adapter constructs the real core.\n */\n _core?: Verivyx;\n\n /**\n * When set, attach RSL `Link` and AIPREF `Content-Usage` headers to both\n * the denied (402) and allowed handler responses.\n * Default undefined = OFF (no headers added; existing behavior unchanged).\n */\n advertise?: DiscoveryOptions;\n\n /**\n * When set, unverified humans and search crawlers (reason: \"human-unverified\"\n * or \"crawler\") receive a 200 HTML teaser page instead of a bare 402.\n * Bots / agents (reason: \"bot-unpaid\") still get the 402 x402 response.\n *\n * Used by both `protect()` (when set on the factory opts) and `middleware()`.\n * `protect()` also accepts `seoPreview` in its per-call options `o`; if both\n * are set, the per-call value takes precedence.\n */\n seoPreview?: (ctx: { slug: string }) => { title: string; excerpt: string };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the first (client-most) hop from an `X-Forwarded-For` header value.\n * The header may contain a comma-separated list; the leftmost is the client.\n */\nfunction firstHop(xff: string | null | undefined): string | undefined {\n if (xff === null || xff === undefined || xff === \"\") {\n return undefined;\n }\n const first = xff.split(\",\")[0];\n return first !== undefined ? first.trim() || undefined : undefined;\n}\n\n/**\n * Return true when `pathname` matches any of the `patterns`.\n * Supports `*` (single-segment wildcard) and `**` (multi-segment wildcard).\n * Performs an anchored full-path match.\n */\nfunction pathMatchesAny(pathname: string, patterns: string[]): boolean {\n return patterns.some((pattern) => {\n // Escape regex metacharacters except * which we handle specially.\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Replace ** before * so the two-step substitution is order-safe.\n const regexStr = escaped\n .replace(/\\*\\*/g, \"\u0001\") // placeholder for **\n .replace(/\\*/g, \"[^/]*\") // single-segment wildcard\n .replace(/\u0001/g, \".*\"); // multi-segment wildcard\n return new RegExp(\"^\" + regexStr + \"$\").test(pathname);\n });\n}\n\n/**\n * Rebuild the absolute request URL using `X-Forwarded-Host` / `X-Forwarded-Proto`\n * when `trustProxy` is enabled, so the x402 resource URL reflects the public host\n * rather than the internal address assigned by a reverse proxy.\n *\n * When `trustProxy` is false the raw request URL is returned unchanged.\n */\nfunction publicUrl(req: Request, trustProxy: boolean): string {\n if (!trustProxy) return req.url;\n const u = new URL(req.url);\n const fwdProto = req.headers.get(\"x-forwarded-proto\");\n if (fwdProto) {\n const p = fwdProto.split(\",\")[0];\n if (p !== undefined) u.protocol = p.trim() + \":\";\n }\n const fwdHost = req.headers.get(\"x-forwarded-host\") ?? req.headers.get(\"host\");\n if (fwdHost) {\n const h = fwdHost.split(\",\")[0];\n if (h !== undefined) {\n const trimmed = h.trim();\n // If the forwarded host includes a port (\"host:port\"), split it.\n // Otherwise clear any internal port so we only expose the public host.\n const colonIdx = trimmed.lastIndexOf(\":\");\n if (colonIdx !== -1) {\n u.hostname = trimmed.slice(0, colonIdx);\n u.port = trimmed.slice(colonIdx + 1);\n } else {\n u.hostname = trimmed;\n u.port = \"\";\n }\n }\n }\n return u.toString();\n}\n\n/**\n * Extract the last non-empty path segment from a URL pathname.\n * Used as a fallback slug when `c.req.param(\"slug\")` is unavailable.\n */\nfunction lastPathSegment(pathname: string): string {\n const segments = pathname.split(\"/\").filter((s) => s.length > 0);\n const last = segments[segments.length - 1];\n if (last === undefined) {\n return \"\";\n }\n try {\n return decodeURIComponent(last);\n } catch {\n return last;\n }\n}\n\n/**\n * Resolve the trusted client IP from Hono context headers.\n *\n * Precedence (Cloudflare Workers best-practice order):\n * 1. CF-Connecting-IP — set by Cloudflare edge (single trusted value).\n * 2. X-Forwarded-For first hop — set by other proxies / Vercel.\n * 3. X-Real-IP — generic proxy header.\n * Returns undefined when trustProxy === false or no header is present.\n */\nfunction resolveIp(c: Context, trustProxy: boolean): string | undefined {\n if (!trustProxy) {\n return undefined;\n }\n const cfIp = c.req.header(\"cf-connecting-ip\");\n if (cfIp !== undefined && cfIp !== \"\") {\n return cfIp;\n }\n const xff = c.req.header(\"x-forwarded-for\");\n const hop = firstHop(xff);\n if (hop !== undefined) {\n return hop;\n }\n const xri = c.req.header(\"x-real-ip\");\n return xri !== undefined && xri !== \"\" ? xri : undefined;\n}\n\n/**\n * Attach RSL + AIPREF discovery headers to a Web Response by cloning it.\n * Appends to any existing `Link` (preserves prior values); sets `Content-Usage`.\n * Returns the same Response unchanged when `advertise` is undefined.\n */\nfunction withAdvertiseHeaders(res: Response, advertise: DiscoveryOptions | undefined): Response {\n if (advertise === undefined) {\n return res;\n }\n const headers = new Headers(res.headers);\n headers.append(\"Link\", rslLinkHeader(advertise));\n headers.set(\"Content-Usage\", contentUsageHeader(advertise));\n return new Response(res.body, { status: res.status, statusText: res.statusText, headers });\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Verivyx Hono adapter.\n *\n * Returns an object with `protect(handler)` (per-route gate) and\n * `middleware()` (whole-app settling gate).\n *\n * ```ts\n * const vx = verivyxHono({ domain: \"example.com\", token: \"...\" });\n * // Per-route:\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\n * // Whole-app:\n * app.use(\"*\", vx.middleware());\n * ```\n */\nexport function verivyxHono(opts?: HonoAdapterOptions): {\n protect(\n handler: (c: Context) => Response | Promise<Response>,\n o?: { seoPreview?: (c: { slug: string }) => { title: string; excerpt: string } },\n ): MiddlewareHandler;\n middleware(): MiddlewareHandler;\n} {\n // Resolve the core: use the injected `_core` (tests) or build the real one.\n // Only pass `verifyWebBotAuth` to the core deps when the caller overrode it;\n // the core bundled default is correct otherwise.\n const vx: Verivyx =\n opts?._core ??\n verivyx(opts, {\n verifyCrawlerDns:\n opts?.verifyCrawlerDns ?? createSearchCrawlerVerifier(),\n ...(opts?.verifyWebBotAuth !== undefined\n ? { verifyWebBotAuth: opts.verifyWebBotAuth }\n : {}),\n });\n\n const trustProxy = opts?.trustProxy !== false; // default true\n\n /**\n * Build a core-compatible `Request` from a Hono context.\n * Resolves the trusted client IP (CF/proxy headers) and sets `x-real-ip`\n * on the cloned request, or strips forwarding headers when trustProxy:false.\n *\n * Security invariant: a client can never inject a fake IP into the core\n * classifier — either CF/proxy value wins, or no IP is seen at all.\n */\n function buildCoreRequest(c: Context): Request {\n const raw = c.req.raw;\n const ip = resolveIp(c, trustProxy);\n const url = publicUrl(raw, trustProxy);\n if (ip !== undefined) {\n const headers = new Headers(raw.headers);\n headers.set(\"x-real-ip\", ip);\n return new Request(url, { method: raw.method, headers });\n } else {\n // trustProxy === false: strip forwarding headers so the client cannot\n // inject a spoofed IP into the core.\n const headers = new Headers(raw.headers);\n headers.delete(\"x-real-ip\");\n headers.delete(\"x-forwarded-for\");\n return new Request(url, { method: raw.method, headers });\n }\n }\n\n return {\n protect(\n handler: (c: Context) => Response | Promise<Response>,\n o?: { seoPreview?: (c: { slug: string }) => { title: string; excerpt: string } },\n ): MiddlewareHandler {\n return async function verivyxHonoGuard(c): Promise<Response> {\n // 1. Build a core-compatible request (IP resolution + header hygiene).\n const coreReq = buildCoreRequest(c);\n const raw = c.req.raw;\n\n // 2. Resolve slug.\n // Priority: Hono named param \"slug\" > last URL path segment.\n const paramSlug: string | undefined = c.req.param(\"slug\");\n const slug: string =\n (paramSlug !== undefined && paramSlug !== \"\")\n ? paramSlug\n : lastPathSegment(new URL(raw.url).pathname);\n\n // 3. Ask the core to evaluate the request (decision overload).\n const decision = await vx.protect(coreReq, { slug });\n\n // 4. Denied — check if this is a crawler/human-unverified that we can\n // serve an SEO preview to instead of a bare 402. Handler NOT called.\n if (!decision.allowed) {\n const isPreviewCandidate =\n decision.reason === \"crawler\" || decision.reason === \"human-unverified\";\n if (isPreviewCandidate && o?.seoPreview !== undefined) {\n return withAdvertiseHeaders(\n buildSeoPreviewResponse(slug, publicUrl(raw, trustProxy), o.seoPreview),\n opts?.advertise,\n );\n }\n return withAdvertiseHeaders(decision.response(), opts?.advertise);\n }\n\n // 5. Allowed — call the original Hono handler.\n const res = await handler(c);\n\n // 6. Attach the settlement receipt header when a payment was processed,\n // then attach discovery headers (single clone when both apply).\n return withAdvertiseHeaders(\n attachPaymentResponse(res, decision.paymentResponse),\n opts?.advertise,\n );\n };\n },\n\n middleware(): MiddlewareHandler {\n return async (c, next) => {\n // 1. Path-match filter: when match is set, skip non-matching paths.\n const pathname = c.req.path;\n if (opts?.match !== undefined && opts.match.length > 0 && !pathMatchesAny(pathname, opts.match)) {\n return next();\n }\n\n // 2. Build a core-compatible request (IP resolution + header hygiene).\n const coreReq = buildCoreRequest(c);\n\n // 3. Slug = last path segment (middleware has no named :slug param).\n const slug = pathname.split(\"/\").filter(Boolean).pop() ?? \"\";\n\n // 4. Gate decision.\n const decision = await vx.protect(coreReq, { slug });\n\n if (decision.allowed) {\n // 5a. Allowed — run downstream handlers first.\n await next();\n // 5b. Attach settlement receipt on the outbound response.\n // After next(), c.res holds the downstream Response.\n // Reassign to a mutable clone so we can set the header.\n if (decision.paymentResponse !== undefined) {\n c.res = new Response(c.res.body, c.res);\n c.res.headers.set(\"PAYMENT-RESPONSE\", decision.paymentResponse);\n }\n return;\n }\n\n // 5c. Blocked — check if this is a crawler/human-unverified that we can\n // serve an SEO preview to instead of a bare 402. next() is NOT called.\n const isPreviewCandidate =\n decision.reason === \"crawler\" || decision.reason === \"human-unverified\";\n if (isPreviewCandidate && opts?.seoPreview !== undefined) {\n return withAdvertiseHeaders(\n buildSeoPreviewResponse(slug, publicUrl(c.req.raw, trustProxy), opts.seoPreview),\n opts.advertise,\n );\n }\n return withAdvertiseHeaders(decision.response(), opts?.advertise);\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Top-level convenience export\n// ---------------------------------------------------------------------------\n\n/**\n * Whole-app Hono middleware that gates every matched route behind the\n * Verivyx settling paywall.\n *\n * ```ts\n * import { verivyxHonoMiddleware } from \"@verivyx/paywall-hono\";\n * app.use(\"*\", verivyxHonoMiddleware({ domain: \"example.com\", token: \"...\" }));\n * ```\n */\nexport function verivyxHonoMiddleware(opts?: HonoAdapterOptions): MiddlewareHandler {\n return verivyxHono(opts).middleware();\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verivyx/paywall-hono",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Hono adapter for the Verivyx paywall SDK (Cloudflare Workers / Vercel Edge)",
5
5
  "type": "module",
6
6
  "license": "MIT",