@verivyx/paywall-hono 0.1.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 +53 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -3
- package/dist/index.d.ts +32 -3
- package/dist/index.js +53 -13
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -10,6 +10,13 @@ function firstHop(xff) {
|
|
|
10
10
|
const first = xff.split(",")[0];
|
|
11
11
|
return first !== void 0 ? first.trim() || void 0 : void 0;
|
|
12
12
|
}
|
|
13
|
+
function pathMatchesAny(pathname, patterns) {
|
|
14
|
+
return patterns.some((pattern) => {
|
|
15
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
16
|
+
const regexStr = escaped.replace(/\*\*/g, "").replace(/\*/g, "[^/]*").replace(//g, ".*");
|
|
17
|
+
return new RegExp("^" + regexStr + "$").test(pathname);
|
|
18
|
+
});
|
|
19
|
+
}
|
|
13
20
|
function lastPathSegment(pathname) {
|
|
14
21
|
const segments = pathname.split("/").filter((s) => s.length > 0);
|
|
15
22
|
const last = segments[segments.length - 1];
|
|
@@ -53,22 +60,25 @@ function verivyxHono(opts) {
|
|
|
53
60
|
...opts?.verifyWebBotAuth !== void 0 ? { verifyWebBotAuth: opts.verifyWebBotAuth } : {}
|
|
54
61
|
});
|
|
55
62
|
const trustProxy = opts?.trustProxy !== false;
|
|
63
|
+
function buildCoreRequest(c) {
|
|
64
|
+
const raw = c.req.raw;
|
|
65
|
+
const ip = resolveIp(c, trustProxy);
|
|
66
|
+
if (ip !== void 0) {
|
|
67
|
+
const headers = new Headers(raw.headers);
|
|
68
|
+
headers.set("x-real-ip", ip);
|
|
69
|
+
return new Request(raw, { headers });
|
|
70
|
+
} else {
|
|
71
|
+
const headers = new Headers(raw.headers);
|
|
72
|
+
headers.delete("x-real-ip");
|
|
73
|
+
headers.delete("x-forwarded-for");
|
|
74
|
+
return new Request(raw, { headers });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
56
77
|
return {
|
|
57
78
|
protect(handler, o) {
|
|
58
79
|
return async function verivyxHonoGuard(c) {
|
|
80
|
+
const coreReq = buildCoreRequest(c);
|
|
59
81
|
const raw = c.req.raw;
|
|
60
|
-
const ip = resolveIp(c, trustProxy);
|
|
61
|
-
let coreReq;
|
|
62
|
-
if (ip !== void 0) {
|
|
63
|
-
const headers = new Headers(raw.headers);
|
|
64
|
-
headers.set("x-real-ip", ip);
|
|
65
|
-
coreReq = new Request(raw, { headers });
|
|
66
|
-
} else {
|
|
67
|
-
const headers = new Headers(raw.headers);
|
|
68
|
-
headers.delete("x-real-ip");
|
|
69
|
-
headers.delete("x-forwarded-for");
|
|
70
|
-
coreReq = new Request(raw, { headers });
|
|
71
|
-
}
|
|
72
82
|
const paramSlug = c.req.param("slug");
|
|
73
83
|
const slug = paramSlug !== void 0 && paramSlug !== "" ? paramSlug : lastPathSegment(new URL(raw.url).pathname);
|
|
74
84
|
const decision = await vx.protect(coreReq, { slug });
|
|
@@ -88,10 +98,41 @@ function verivyxHono(opts) {
|
|
|
88
98
|
opts?.advertise
|
|
89
99
|
);
|
|
90
100
|
};
|
|
101
|
+
},
|
|
102
|
+
middleware() {
|
|
103
|
+
return async (c, next) => {
|
|
104
|
+
const pathname = c.req.path;
|
|
105
|
+
if (opts?.match !== void 0 && opts.match.length > 0 && !pathMatchesAny(pathname, opts.match)) {
|
|
106
|
+
return next();
|
|
107
|
+
}
|
|
108
|
+
const coreReq = buildCoreRequest(c);
|
|
109
|
+
const slug = pathname.split("/").filter(Boolean).pop() ?? "";
|
|
110
|
+
const decision = await vx.protect(coreReq, { slug });
|
|
111
|
+
if (decision.allowed) {
|
|
112
|
+
await next();
|
|
113
|
+
if (decision.paymentResponse !== void 0) {
|
|
114
|
+
c.res = new Response(c.res.body, c.res);
|
|
115
|
+
c.res.headers.set("PAYMENT-RESPONSE", decision.paymentResponse);
|
|
116
|
+
}
|
|
117
|
+
return;
|
|
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
|
+
}
|
|
126
|
+
return withAdvertiseHeaders(decision.response(), opts?.advertise);
|
|
127
|
+
};
|
|
91
128
|
}
|
|
92
129
|
};
|
|
93
130
|
}
|
|
131
|
+
function verivyxHonoMiddleware(opts) {
|
|
132
|
+
return verivyxHono(opts).middleware();
|
|
133
|
+
}
|
|
94
134
|
|
|
95
135
|
exports.verivyxHono = verivyxHono;
|
|
136
|
+
exports.verivyxHonoMiddleware = verivyxHonoMiddleware;
|
|
96
137
|
//# sourceMappingURL=index.cjs.map
|
|
97
138
|
//# sourceMappingURL=index.cjs.map
|
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;AAMA,SAAS,gBAAgB,QAAA,EAA0B;AACjD,EAAA,MAAM,QAAA,GAAW,QAAA,CAAS,KAAA,C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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 * 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 a single `protect(handler)` method that wraps a\n * Hono route handler behind the Verivyx paywall gate.\n *\n * ```ts\n * const vx = verivyxHono({ domain: \"example.com\", token: \"...\" });\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\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} {\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 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. Get the raw Web Request from Hono context.\n const raw = c.req.raw;\n\n // 2. Resolve trusted client IP and inject into a cloned request so the\n // core classifier reads a reliable address regardless of edge hop.\n //\n // Security invariant:\n // trustProxy !== false → resolve IP from CF/proxy headers and set\n // x-real-ip on the cloned request (overrides any client value).\n // trustProxy === false → no socket IP is available in edge runtimes;\n // strip both x-real-ip and x-forwarded-for so a client cannot\n // spoof an IP into the core classifier (core sees no IP → safe).\n const ip = resolveIp(c, trustProxy);\n let coreReq: Request;\n if (ip !== undefined) {\n const headers = new Headers(raw.headers);\n headers.set(\"x-real-ip\", ip);\n // Clone the Request with updated headers. For GET/HEAD this is safe;\n // the core classify path reads headers only — body stays with raw.\n coreReq = 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 coreReq = new Request(raw, { headers });\n }\n\n // 3. 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 // 4. Ask the core to evaluate the request (decision overload).\n const decision = await vx.protect(coreReq, { slug });\n\n // 5. 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 // 6. Allowed — call the original Hono handler.\n const res = await handler(c);\n\n // 7. 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}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["rslLinkHeader","contentUsageHeader","verivyx","createSearchCrawlerVerifier","buildSe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tC","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,16 +58,34 @@ 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.
|
|
64
79
|
*
|
|
65
|
-
* Returns an object with
|
|
66
|
-
*
|
|
80
|
+
* Returns an object with `protect(handler)` (per-route gate) and
|
|
81
|
+
* `middleware()` (whole-app settling gate).
|
|
67
82
|
*
|
|
68
83
|
* ```ts
|
|
69
84
|
* const vx = verivyxHono({ domain: "example.com", token: "..." });
|
|
85
|
+
* // Per-route:
|
|
70
86
|
* app.get("/articles/:slug", vx.protect(async (c) => c.json({ content: "..." })));
|
|
87
|
+
* // Whole-app:
|
|
88
|
+
* app.use("*", vx.middleware());
|
|
71
89
|
* ```
|
|
72
90
|
*/
|
|
73
91
|
declare function verivyxHono(opts?: HonoAdapterOptions): {
|
|
@@ -79,6 +97,17 @@ declare function verivyxHono(opts?: HonoAdapterOptions): {
|
|
|
79
97
|
excerpt: string;
|
|
80
98
|
};
|
|
81
99
|
}): MiddlewareHandler;
|
|
100
|
+
middleware(): MiddlewareHandler;
|
|
82
101
|
};
|
|
102
|
+
/**
|
|
103
|
+
* Whole-app Hono middleware that gates every matched route behind the
|
|
104
|
+
* Verivyx settling paywall.
|
|
105
|
+
*
|
|
106
|
+
* ```ts
|
|
107
|
+
* import { verivyxHonoMiddleware } from "@verivyx/paywall-hono";
|
|
108
|
+
* app.use("*", verivyxHonoMiddleware({ domain: "example.com", token: "..." }));
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
declare function verivyxHonoMiddleware(opts?: HonoAdapterOptions): MiddlewareHandler;
|
|
83
112
|
|
|
84
|
-
export { type HonoAdapterOptions, verivyxHono };
|
|
113
|
+
export { type HonoAdapterOptions, verivyxHono, verivyxHonoMiddleware };
|
package/dist/index.d.ts
CHANGED
|
@@ -58,16 +58,34 @@ 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.
|
|
64
79
|
*
|
|
65
|
-
* Returns an object with
|
|
66
|
-
*
|
|
80
|
+
* Returns an object with `protect(handler)` (per-route gate) and
|
|
81
|
+
* `middleware()` (whole-app settling gate).
|
|
67
82
|
*
|
|
68
83
|
* ```ts
|
|
69
84
|
* const vx = verivyxHono({ domain: "example.com", token: "..." });
|
|
85
|
+
* // Per-route:
|
|
70
86
|
* app.get("/articles/:slug", vx.protect(async (c) => c.json({ content: "..." })));
|
|
87
|
+
* // Whole-app:
|
|
88
|
+
* app.use("*", vx.middleware());
|
|
71
89
|
* ```
|
|
72
90
|
*/
|
|
73
91
|
declare function verivyxHono(opts?: HonoAdapterOptions): {
|
|
@@ -79,6 +97,17 @@ declare function verivyxHono(opts?: HonoAdapterOptions): {
|
|
|
79
97
|
excerpt: string;
|
|
80
98
|
};
|
|
81
99
|
}): MiddlewareHandler;
|
|
100
|
+
middleware(): MiddlewareHandler;
|
|
82
101
|
};
|
|
102
|
+
/**
|
|
103
|
+
* Whole-app Hono middleware that gates every matched route behind the
|
|
104
|
+
* Verivyx settling paywall.
|
|
105
|
+
*
|
|
106
|
+
* ```ts
|
|
107
|
+
* import { verivyxHonoMiddleware } from "@verivyx/paywall-hono";
|
|
108
|
+
* app.use("*", verivyxHonoMiddleware({ domain: "example.com", token: "..." }));
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
declare function verivyxHonoMiddleware(opts?: HonoAdapterOptions): MiddlewareHandler;
|
|
83
112
|
|
|
84
|
-
export { type HonoAdapterOptions, verivyxHono };
|
|
113
|
+
export { type HonoAdapterOptions, verivyxHono, verivyxHonoMiddleware };
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,13 @@ function firstHop(xff) {
|
|
|
8
8
|
const first = xff.split(",")[0];
|
|
9
9
|
return first !== void 0 ? first.trim() || void 0 : void 0;
|
|
10
10
|
}
|
|
11
|
+
function pathMatchesAny(pathname, patterns) {
|
|
12
|
+
return patterns.some((pattern) => {
|
|
13
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
14
|
+
const regexStr = escaped.replace(/\*\*/g, "").replace(/\*/g, "[^/]*").replace(//g, ".*");
|
|
15
|
+
return new RegExp("^" + regexStr + "$").test(pathname);
|
|
16
|
+
});
|
|
17
|
+
}
|
|
11
18
|
function lastPathSegment(pathname) {
|
|
12
19
|
const segments = pathname.split("/").filter((s) => s.length > 0);
|
|
13
20
|
const last = segments[segments.length - 1];
|
|
@@ -51,22 +58,25 @@ function verivyxHono(opts) {
|
|
|
51
58
|
...opts?.verifyWebBotAuth !== void 0 ? { verifyWebBotAuth: opts.verifyWebBotAuth } : {}
|
|
52
59
|
});
|
|
53
60
|
const trustProxy = opts?.trustProxy !== false;
|
|
61
|
+
function buildCoreRequest(c) {
|
|
62
|
+
const raw = c.req.raw;
|
|
63
|
+
const ip = resolveIp(c, trustProxy);
|
|
64
|
+
if (ip !== void 0) {
|
|
65
|
+
const headers = new Headers(raw.headers);
|
|
66
|
+
headers.set("x-real-ip", ip);
|
|
67
|
+
return new Request(raw, { headers });
|
|
68
|
+
} else {
|
|
69
|
+
const headers = new Headers(raw.headers);
|
|
70
|
+
headers.delete("x-real-ip");
|
|
71
|
+
headers.delete("x-forwarded-for");
|
|
72
|
+
return new Request(raw, { headers });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
54
75
|
return {
|
|
55
76
|
protect(handler, o) {
|
|
56
77
|
return async function verivyxHonoGuard(c) {
|
|
78
|
+
const coreReq = buildCoreRequest(c);
|
|
57
79
|
const raw = c.req.raw;
|
|
58
|
-
const ip = resolveIp(c, trustProxy);
|
|
59
|
-
let coreReq;
|
|
60
|
-
if (ip !== void 0) {
|
|
61
|
-
const headers = new Headers(raw.headers);
|
|
62
|
-
headers.set("x-real-ip", ip);
|
|
63
|
-
coreReq = new Request(raw, { headers });
|
|
64
|
-
} else {
|
|
65
|
-
const headers = new Headers(raw.headers);
|
|
66
|
-
headers.delete("x-real-ip");
|
|
67
|
-
headers.delete("x-forwarded-for");
|
|
68
|
-
coreReq = new Request(raw, { headers });
|
|
69
|
-
}
|
|
70
80
|
const paramSlug = c.req.param("slug");
|
|
71
81
|
const slug = paramSlug !== void 0 && paramSlug !== "" ? paramSlug : lastPathSegment(new URL(raw.url).pathname);
|
|
72
82
|
const decision = await vx.protect(coreReq, { slug });
|
|
@@ -86,10 +96,40 @@ function verivyxHono(opts) {
|
|
|
86
96
|
opts?.advertise
|
|
87
97
|
);
|
|
88
98
|
};
|
|
99
|
+
},
|
|
100
|
+
middleware() {
|
|
101
|
+
return async (c, next) => {
|
|
102
|
+
const pathname = c.req.path;
|
|
103
|
+
if (opts?.match !== void 0 && opts.match.length > 0 && !pathMatchesAny(pathname, opts.match)) {
|
|
104
|
+
return next();
|
|
105
|
+
}
|
|
106
|
+
const coreReq = buildCoreRequest(c);
|
|
107
|
+
const slug = pathname.split("/").filter(Boolean).pop() ?? "";
|
|
108
|
+
const decision = await vx.protect(coreReq, { slug });
|
|
109
|
+
if (decision.allowed) {
|
|
110
|
+
await next();
|
|
111
|
+
if (decision.paymentResponse !== void 0) {
|
|
112
|
+
c.res = new Response(c.res.body, c.res);
|
|
113
|
+
c.res.headers.set("PAYMENT-RESPONSE", decision.paymentResponse);
|
|
114
|
+
}
|
|
115
|
+
return;
|
|
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
|
+
}
|
|
124
|
+
return withAdvertiseHeaders(decision.response(), opts?.advertise);
|
|
125
|
+
};
|
|
89
126
|
}
|
|
90
127
|
};
|
|
91
128
|
}
|
|
129
|
+
function verivyxHonoMiddleware(opts) {
|
|
130
|
+
return verivyxHono(opts).middleware();
|
|
131
|
+
}
|
|
92
132
|
|
|
93
|
-
export { verivyxHono };
|
|
133
|
+
export { verivyxHono, verivyxHonoMiddleware };
|
|
94
134
|
//# sourceMappingURL=index.js.map
|
|
95
135
|
//# sourceMappingURL=index.js.map
|
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;AAMA,SAAS,gBAAgB,QAAA,EAA0B;AACjD,EAAA,MAAM,QAAA,GAAW,QAAA,CAAS,KAAA,CAAM,GAAG,CAAA,CAAE,OAAO,CAAC,CAAA,KAAM,CAAA,CAAE,MAAA,GAAS,CAAC,CAAA;AAC/D,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,QAAA,CAAS,MAAA,GAAS,CAAC,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AA,EAAK,EAAE,SAAS,CAAA;AAAA,QACxC;AAIA,QAAA,MAAM,SAAA,GAAgC,CAAA,CAAE,GAAA,CAAI,KAAA,CAAM,MAAM,CAAA;AACxD,QAAA,MAAM,IAAA,GACH,SAAA,KAAc,MAAA,IAAa,SAAA,KAAc,EAAA,GACtC,SAAA,GACA,eAAA,CAAgB,IAAI,GAAA,CAAI,GAAA,CAAI,GAAG,CAAA,CAAE,QAAQ,CAAA;AAG/C,QAAA,MAAM,WAAW,MAAM,EAAA,CAAG,QAAQ,OAAA,EAAS,EAAE,MAAM,CAAA;AAInD,QAAA,IAAI,CAAC,SAAS,OAAA,EAAS;AACrB,UAAA,MAAM,kBAAA,GACJ,QAAA,CAAS,MAAA,KAAW,SAAA,IAAa,SAAS,MAAA,KAAW,kBAAA;AACvD,UAAA,IAAI,kBAAA,IAAsB,CAAA,EAAG,UAAA,KAAe,MAAA,EAAW;AACrD,YAAA,OAAO,oBAAA;AAAA,cACL,uBAAA,CAAwB,IAAA,EAAM,GAAA,CAAI,GAAA,EAAK,EAAE,UAAU,CAAA;AAAA,cACnD,IAAA,EAAM;AAAA,aACR;AAAA,UACF;AACA,UAAA,OAAO,oBAAA,CAAqB,QAAA,CAAS,QAAA,EAAS,EAAG,MAAM,SAAS,CAAA;AAAA,QAClE;AAGA,QAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,CAAC,CAAA;AAI3B,QAAA,OAAO,oBAAA;AAAA,UACL,qBAAA,CAAsB,GAAA,EAAK,QAAA,CAAS,eAAe,CAAA;AAAA,UACnD,IAAA,EAAM;AAAA,SACR;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACF;AACF","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 * 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 a single `protect(handler)` method that wraps a\n * Hono route handler behind the Verivyx paywall gate.\n *\n * ```ts\n * const vx = verivyxHono({ domain: \"example.com\", token: \"...\" });\n * app.get(\"/articles/:slug\", vx.protect(async (c) => c.json({ content: \"...\" })));\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} {\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 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. Get the raw Web Request from Hono context.\n const raw = c.req.raw;\n\n // 2. Resolve trusted client IP and inject into a cloned request so the\n // core classifier reads a reliable address regardless of edge hop.\n //\n // Security invariant:\n // trustProxy !== false → resolve IP from CF/proxy headers and set\n // x-real-ip on the cloned request (overrides any client value).\n // trustProxy === false → no socket IP is available in edge runtimes;\n // strip both x-real-ip and x-forwarded-for so a client cannot\n // spoof an IP into the core classifier (core sees no IP → safe).\n const ip = resolveIp(c, trustProxy);\n let coreReq: Request;\n if (ip !== undefined) {\n const headers = new Headers(raw.headers);\n headers.set(\"x-real-ip\", ip);\n // Clone the Request with updated headers. For GET/HEAD this is safe;\n // the core classify path reads headers only — body stays with raw.\n coreReq = 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 coreReq = new Request(raw, { headers });\n }\n\n // 3. 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 // 4. Ask the core to evaluate the request (decision overload).\n const decision = await vx.protect(coreReq, { slug });\n\n // 5. 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 // 6. Allowed — call the original Hono handler.\n const res = await handler(c);\n\n // 7. 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}\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,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,IAAK,EAAA;AAG1D,QAAA,MAAM,WAAW,MAAM,EAAA,CAAG,QAAQ,OAAA,EAAS,EAAE,MAAM,CAAA;AAEnD,QAAA,IAAI,SAAS,OAAA,EAAS;AAEpB,UAAA,MAAM,IAAA,EAAK;AAIX,UAAA,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"]}
|