@verivyx/paywall-hono 0.2.0 → 0.3.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 +7 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -116,6 +116,13 @@ function verivyxHono(opts) {
|
|
|
116
116
|
}
|
|
117
117
|
return;
|
|
118
118
|
}
|
|
119
|
+
const isPreviewCandidate = decision.reason === "crawler" || decision.reason === "human-unverified";
|
|
120
|
+
if (isPreviewCandidate && opts?.seoPreview !== void 0) {
|
|
121
|
+
return withAdvertiseHeaders(
|
|
122
|
+
paywall.buildSeoPreviewResponse(slug, c.req.raw.url, opts.seoPreview),
|
|
123
|
+
opts.advertise
|
|
124
|
+
);
|
|
125
|
+
}
|
|
119
126
|
return withAdvertiseHeaders(decision.response(), opts?.advertise);
|
|
120
127
|
};
|
|
121
128
|
}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["rslLinkHeader","contentUsageHeader","verivyx","createSearchCrawlerVerifier","buildSeoPreviewResponse","attachPaymentResponse"],"mappings":";;;;;AAsFA,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,OA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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;AAGA,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// ---------------------------------------------------------------------------\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 — short-circuit; next() is NOT called.\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,QA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A,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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -58,6 +58,21 @@ interface HonoAdapterOptions extends VerivyxOptions {
|
|
|
58
58
|
* Default undefined = OFF (no headers added; existing behavior unchanged).
|
|
59
59
|
*/
|
|
60
60
|
advertise?: DiscoveryOptions;
|
|
61
|
+
/**
|
|
62
|
+
* When set, unverified humans and search crawlers (reason: "human-unverified"
|
|
63
|
+
* or "crawler") receive a 200 HTML teaser page instead of a bare 402.
|
|
64
|
+
* Bots / agents (reason: "bot-unpaid") still get the 402 x402 response.
|
|
65
|
+
*
|
|
66
|
+
* Used by both `protect()` (when set on the factory opts) and `middleware()`.
|
|
67
|
+
* `protect()` also accepts `seoPreview` in its per-call options `o`; if both
|
|
68
|
+
* are set, the per-call value takes precedence.
|
|
69
|
+
*/
|
|
70
|
+
seoPreview?: (ctx: {
|
|
71
|
+
slug: string;
|
|
72
|
+
}) => {
|
|
73
|
+
title: string;
|
|
74
|
+
excerpt: string;
|
|
75
|
+
};
|
|
61
76
|
}
|
|
62
77
|
/**
|
|
63
78
|
* Create a Verivyx Hono adapter.
|
package/dist/index.d.ts
CHANGED
|
@@ -58,6 +58,21 @@ interface HonoAdapterOptions extends VerivyxOptions {
|
|
|
58
58
|
* Default undefined = OFF (no headers added; existing behavior unchanged).
|
|
59
59
|
*/
|
|
60
60
|
advertise?: DiscoveryOptions;
|
|
61
|
+
/**
|
|
62
|
+
* When set, unverified humans and search crawlers (reason: "human-unverified"
|
|
63
|
+
* or "crawler") receive a 200 HTML teaser page instead of a bare 402.
|
|
64
|
+
* Bots / agents (reason: "bot-unpaid") still get the 402 x402 response.
|
|
65
|
+
*
|
|
66
|
+
* Used by both `protect()` (when set on the factory opts) and `middleware()`.
|
|
67
|
+
* `protect()` also accepts `seoPreview` in its per-call options `o`; if both
|
|
68
|
+
* are set, the per-call value takes precedence.
|
|
69
|
+
*/
|
|
70
|
+
seoPreview?: (ctx: {
|
|
71
|
+
slug: string;
|
|
72
|
+
}) => {
|
|
73
|
+
title: string;
|
|
74
|
+
excerpt: string;
|
|
75
|
+
};
|
|
61
76
|
}
|
|
62
77
|
/**
|
|
63
78
|
* Create a Verivyx Hono adapter.
|
package/dist/index.js
CHANGED
|
@@ -114,6 +114,13 @@ function verivyxHono(opts) {
|
|
|
114
114
|
}
|
|
115
115
|
return;
|
|
116
116
|
}
|
|
117
|
+
const isPreviewCandidate = decision.reason === "crawler" || decision.reason === "human-unverified";
|
|
118
|
+
if (isPreviewCandidate && opts?.seoPreview !== void 0) {
|
|
119
|
+
return withAdvertiseHeaders(
|
|
120
|
+
buildSeoPreviewResponse(slug, c.req.raw.url, opts.seoPreview),
|
|
121
|
+
opts.advertise
|
|
122
|
+
);
|
|
123
|
+
}
|
|
117
124
|
return withAdvertiseHeaders(decision.response(), opts?.advertise);
|
|
118
125
|
};
|
|
119
126
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAsFA,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,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ACF;AAGA,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// ---------------------------------------------------------------------------\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 — short-circuit; next() is NOT called.\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;AAMA,SAAS,gBAAgB,QAAA,EAA0B;AACjD,EAAA,MAAM,QAAA,GAAW,QAAA,CA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AI,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"]}
|