@kanorio/sdk 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -2
  3. package/dist/customer-oauth.d.ts +86 -0
  4. package/dist/customer-oauth.js +112 -0
  5. package/dist/customer.d.ts +176 -0
  6. package/dist/customer.js +125 -0
  7. package/dist/delivery.d.ts +35 -0
  8. package/dist/delivery.js +49 -0
  9. package/dist/edge.d.ts +108 -0
  10. package/dist/edge.js +287 -0
  11. package/dist/forms.d.ts +123 -0
  12. package/dist/forms.js +130 -0
  13. package/dist/generated/customer.d.ts +3157 -0
  14. package/dist/generated/delivery.d.ts +2408 -0
  15. package/dist/generated/management.d.ts +38333 -0
  16. package/dist/http.d.ts +73 -0
  17. package/dist/http.js +162 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.js +17 -0
  20. package/dist/locales.d.ts +80 -0
  21. package/dist/locales.js +81 -0
  22. package/dist/management.d.ts +19 -0
  23. package/dist/management.js +22 -0
  24. package/dist/paginate.d.ts +18 -0
  25. package/dist/paginate.js +27 -0
  26. package/dist/preview.d.ts +40 -0
  27. package/dist/preview.js +131 -0
  28. package/dist/protection.d.ts +74 -0
  29. package/dist/protection.js +68 -0
  30. package/dist/revalidate.d.ts +84 -0
  31. package/dist/revalidate.js +143 -0
  32. package/dist/seo.d.ts +120 -0
  33. package/dist/seo.js +125 -0
  34. package/dist/server-key.d.ts +71 -0
  35. package/dist/server-key.js +103 -0
  36. package/dist/shared/api/delivery/cache-tags.d.ts +142 -0
  37. package/dist/shared/api/delivery/cache-tags.js +212 -0
  38. package/dist/shared/api/server-key.d.ts +90 -0
  39. package/dist/shared/api/server-key.js +260 -0
  40. package/dist/shared/business-registry/attribution.d.ts +14 -0
  41. package/dist/shared/business-registry/attribution.js +28 -0
  42. package/dist/shared/business-registry/define.d.ts +3 -0
  43. package/dist/shared/business-registry/define.js +4 -0
  44. package/dist/shared/business-registry/formats/eu-vat.d.ts +2 -0
  45. package/dist/shared/business-registry/formats/eu-vat.js +54 -0
  46. package/dist/shared/business-registry/formats/hk-br.d.ts +5 -0
  47. package/dist/shared/business-registry/formats/hk-br.js +23 -0
  48. package/dist/shared/business-registry/formats/jp-trn.d.ts +6 -0
  49. package/dist/shared/business-registry/formats/jp-trn.js +23 -0
  50. package/dist/shared/business-registry/formats/kr-brn.d.ts +6 -0
  51. package/dist/shared/business-registry/formats/kr-brn.js +30 -0
  52. package/dist/shared/business-registry/formats/my.d.ts +7 -0
  53. package/dist/shared/business-registry/formats/my.js +32 -0
  54. package/dist/shared/business-registry/formats/sg-uen.d.ts +1 -0
  55. package/dist/shared/business-registry/formats/sg-uen.js +21 -0
  56. package/dist/shared/business-registry/formats/tw-vat.d.ts +10 -0
  57. package/dist/shared/business-registry/formats/tw-vat.js +32 -0
  58. package/dist/shared/business-registry/index.d.ts +9 -0
  59. package/dist/shared/business-registry/index.js +10 -0
  60. package/dist/shared/business-registry/lookup-wire.d.ts +33 -0
  61. package/dist/shared/business-registry/lookup-wire.js +8 -0
  62. package/dist/shared/business-registry/normalize.d.ts +7 -0
  63. package/dist/shared/business-registry/normalize.js +12 -0
  64. package/dist/shared/business-registry/registry.d.ts +26 -0
  65. package/dist/shared/business-registry/registry.js +67 -0
  66. package/dist/shared/business-registry/types.d.ts +60 -0
  67. package/dist/shared/business-registry/types.js +10 -0
  68. package/dist/shared/localization/locale-path.d.ts +38 -0
  69. package/dist/shared/localization/locale-path.js +76 -0
  70. package/dist/shared/localization/request-locale.d.ts +42 -0
  71. package/dist/shared/localization/request-locale.js +61 -0
  72. package/dist/shared/seo/alternates.d.ts +61 -0
  73. package/dist/shared/seo/alternates.js +71 -0
  74. package/dist/shared/types/forms-logic.d.ts +96 -0
  75. package/dist/shared/types/forms-logic.js +209 -0
  76. package/dist/shared/types/number-input.d.ts +5 -0
  77. package/dist/shared/types/number-input.js +16 -0
  78. package/dist/shared/utils/redirect-matching.d.ts +76 -0
  79. package/dist/shared/utils/redirect-matching.js +181 -0
  80. package/dist/tax-id.d.ts +7 -0
  81. package/dist/tax-id.js +6 -0
  82. package/dist/typed.d.ts +85 -0
  83. package/dist/typed.js +28 -0
  84. package/package.json +86 -3
@@ -0,0 +1,131 @@
1
+ /**
2
+ * `@kanorio/sdk/preview`: helpers for Next.js Draft Mode and Astro with preview tokens (`knr_pv_`).
3
+ *
4
+ * - `previewHeaders(token)`: builds the `X-Kanorio-Preview: knr_pv_...` header, used with `?preview=1` to read unpublished drafts.
5
+ * - `tokenFromCookieHeader(cookieHeader)`: safely reads the `kanorio_preview` token from a `Request`'s `Cookie` header.
6
+ * - `createPreviewRouteHandler({ siteUrl, enableDraftMode })`: one line in Next.js `app/api/preview/route.ts` or an Astro endpoint;
7
+ * it validates the `knr_pv_` format, verifies signature and expiry with the Kanorio Delivery API (when `siteUrl` is given), blocks open redirects,
8
+ * sets the `kanorio_preview` HttpOnly cookie and redirects 307 to the target page.
9
+ */
10
+ import { DELIVERY_PREVIEW_HEADER, deliveryBaseUrl } from "./delivery.js";
11
+ export const PREVIEW_TOKEN_PREFIX = "knr_pv_";
12
+ export const PREVIEW_COOKIE_NAME = "kanorio_preview";
13
+ // The shape is `knr_pv_{siteId}.{expiresAtSec}.{jti}.{sig}`; jti and sig are base64url and may contain `-` and `_`.
14
+ // The jti segment must accept `-`: otherwise about one in six valid tokens is treated as malformed (the preview route answers 401 and the cookie cannot be read).
15
+ const PREVIEW_TOKEN_RE = /^knr_pv_[a-z0-9]+\.\d+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/i;
16
+ export function isValidPreviewTokenFormat(token) {
17
+ if (!token || typeof token !== "string")
18
+ return false;
19
+ const trimmed = token.trim();
20
+ return trimmed.length <= 256 && PREVIEW_TOKEN_RE.test(trimmed);
21
+ }
22
+ /** Only in-site paths starting with a single `/` are allowed, which blocks `//evil.com` and `https://evil.com` open redirects */
23
+ export function sanitizePreviewRedirectPath(raw) {
24
+ if (!raw || typeof raw !== "string")
25
+ return "/";
26
+ const trimmed = raw.trim();
27
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//") || trimmed.includes("\\")) {
28
+ return "/";
29
+ }
30
+ return trimmed;
31
+ }
32
+ export function previewHeaders(token) {
33
+ return {
34
+ [DELIVERY_PREVIEW_HEADER]: token.trim(),
35
+ };
36
+ }
37
+ /** Extracts and validates the `kanorio_preview` token from an HTTP `Cookie` header; `null` when absent or malformed */
38
+ export function tokenFromCookieHeader(cookieHeader) {
39
+ if (!cookieHeader)
40
+ return null;
41
+ for (const part of cookieHeader.split(";")) {
42
+ const eq = part.indexOf("=");
43
+ if (eq === -1)
44
+ continue;
45
+ const name = part.slice(0, eq).trim();
46
+ if (name !== PREVIEW_COOKIE_NAME)
47
+ continue;
48
+ try {
49
+ const value = decodeURIComponent(part.slice(eq + 1).trim());
50
+ return isValidPreviewTokenFormat(value) ? value : null;
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ }
56
+ return null;
57
+ }
58
+ export function createPreviewRouteHandler(options = {}) {
59
+ const maxAge = Math.max(60, options.cookieMaxAgeSeconds ?? 3600);
60
+ const f = options.fetch ?? globalThis.fetch;
61
+ return async function handlePreviewRequest(request) {
62
+ const url = new URL(request.url);
63
+ const token = url.searchParams.get("token") ?? url.searchParams.get("kp");
64
+ if (!isValidPreviewTokenFormat(token)) {
65
+ return new Response(JSON.stringify({
66
+ error: {
67
+ code: "INVALID_PREVIEW_TOKEN",
68
+ message: "Missing or malformed knr_pv_ preview token.",
69
+ },
70
+ }), {
71
+ status: 401,
72
+ headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" },
73
+ });
74
+ }
75
+ if (options.siteUrl) {
76
+ const apiBase = deliveryBaseUrl(options.siteUrl);
77
+ try {
78
+ const verifyRes = await f(`${apiBase}/site?preview=1`, {
79
+ headers: {
80
+ Accept: "application/json",
81
+ [DELIVERY_PREVIEW_HEADER]: token.trim(),
82
+ },
83
+ cache: "no-store",
84
+ });
85
+ if (verifyRes.status === 401 || verifyRes.status === 403) {
86
+ return new Response(JSON.stringify({
87
+ error: {
88
+ code: "PREVIEW_TOKEN_REJECTED",
89
+ message: "Preview token is expired, revoked, or invalid for this site.",
90
+ },
91
+ }), {
92
+ status: 401,
93
+ headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" },
94
+ });
95
+ }
96
+ }
97
+ catch {
98
+ // Do not reject a well-formed token when the upstream network is temporarily failing
99
+ }
100
+ }
101
+ await options.enableDraftMode?.(token);
102
+ const redirectPath = sanitizePreviewRedirectPath(url.searchParams.get("redirect") ?? url.searchParams.get("path") ?? "/");
103
+ const location = new URL(redirectPath, url.origin).toString();
104
+ const isHttps = url.protocol === "https:";
105
+ const cookie = [
106
+ `${PREVIEW_COOKIE_NAME}=${encodeURIComponent(token)}`,
107
+ "Path=/",
108
+ `Max-Age=${maxAge}`,
109
+ "HttpOnly",
110
+ "SameSite=Lax",
111
+ ...(isHttps ? ["Secure"] : []),
112
+ ].join("; ");
113
+ return new Response(null, {
114
+ status: 307,
115
+ headers: {
116
+ Location: location,
117
+ "Set-Cookie": cookie,
118
+ "Cache-Control": "no-store",
119
+ },
120
+ });
121
+ };
122
+ }
123
+ export const preview = {
124
+ headers: previewHeaders,
125
+ tokenFromCookieHeader,
126
+ isValidTokenFormat: isValidPreviewTokenFormat,
127
+ sanitizeRedirectPath: sanitizePreviewRedirectPath,
128
+ createRouteHandler: createPreviewRouteHandler,
129
+ COOKIE_NAME: PREVIEW_COOKIE_NAME,
130
+ TOKEN_PREFIX: PREVIEW_TOKEN_PREFIX,
131
+ };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Bot protection (shared by forms and customer sign-in): turns the challenge from `GET /api/v1/forms/{id}/challenge` or `GET /api/v1/customer/auth/protection`
3
+ * into the protection fields to send on submit.
4
+ *
5
+ * - `provider: "kanorio"`: the built-in ALTCHA proof of work, solved here (Web Crypto; runs in browsers and Node 20), with the payload in `_tk`.
6
+ * - Third parties (Turnstile, reCAPTCHA, hCaptcha): render that widget with the returned `siteKey` and `action` (Turnstile also has `cData`),
7
+ * then pass the widget's token here to be sent as `captchaToken`. The provider is a site setting, and the server verifies accordingly.
8
+ */
9
+ export type ProtectionProvider = "kanorio" | "turnstile" | "recaptcha" | "hcaptcha";
10
+ export interface AltchaChallenge {
11
+ algorithm: string;
12
+ challenge: string;
13
+ maxnumber?: number;
14
+ salt: string;
15
+ signature: string;
16
+ }
17
+ export type ProtectionChallenge = {
18
+ provider: "kanorio";
19
+ entry: string;
20
+ altcha: AltchaChallenge;
21
+ visible?: boolean;
22
+ } | {
23
+ provider: Exclude<ProtectionProvider, "kanorio">;
24
+ entry: string;
25
+ siteKey: string;
26
+ action: string;
27
+ cData: string | null;
28
+ recaptchaVersion: "v2" | "v3" | null;
29
+ /** true: show the verification (when sign-in volume on the site is unusual) */
30
+ visible?: boolean;
31
+ /** Forms only: for attachment upload tickets (a third-party token is single-use and is kept for the submit) */
32
+ uploadToken?: string;
33
+ };
34
+ /** Protection fields sent on submit (`_hp`, `_wp` and `_co` are honeypots, always empty strings) */
35
+ export interface ProtectionFields {
36
+ _hp: "";
37
+ _wp: "";
38
+ _co: "";
39
+ /** When the screen was shown (Unix milliseconds) */
40
+ _ts: number;
41
+ /** Built-in: the solved ALTCHA payload */
42
+ _tk?: string;
43
+ /** What the challenge is bound to: the form id, or `customer-login:{siteId}` */
44
+ _ctx?: string;
45
+ /** Third party: the token from the widget */
46
+ captchaToken?: string;
47
+ }
48
+ /**
49
+ * Solves the built-in challenge: finds n where `SHA-256(salt + n) === challenge` and returns the ALTCHA payload (base64 JSON).
50
+ * About 0.5 to 1 second on a mid-range phone; `signal` can abort it when the user leaves the page.
51
+ */
52
+ export declare function solveAltchaChallenge(challenge: AltchaChallenge, options?: {
53
+ signal?: AbortSignal;
54
+ }): Promise<string>;
55
+ /**
56
+ * Challenge to protection fields. The built-in challenge is solved here; for a third party, render the widget first and pass its token in as `captchaToken`.
57
+ *
58
+ * @param context What the challenge is bound to: the form id, or `customer-login:{siteId}` (built-in challenge only)
59
+ */
60
+ export declare function protectionFromChallenge(challenge: ProtectionChallenge, options: {
61
+ context: string;
62
+ renderedAt: number;
63
+ captchaToken?: string;
64
+ signal?: AbortSignal;
65
+ }): Promise<ProtectionFields>;
66
+ /**
67
+ * Protection fields for an attachment upload ticket: with the built-in challenge they are the ones used for submitting (same solution; uploads do not consume it); with a third party, use the challenge's `uploadToken`
68
+ * and keep the widget token for the submit.
69
+ */
70
+ export declare function uploadProtectionFromChallenge(challenge: ProtectionChallenge, options: {
71
+ context: string;
72
+ renderedAt: number;
73
+ solved?: ProtectionFields;
74
+ }): ProtectionFields | null;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Bot protection (shared by forms and customer sign-in): turns the challenge from `GET /api/v1/forms/{id}/challenge` or `GET /api/v1/customer/auth/protection`
3
+ * into the protection fields to send on submit.
4
+ *
5
+ * - `provider: "kanorio"`: the built-in ALTCHA proof of work, solved here (Web Crypto; runs in browsers and Node 20), with the payload in `_tk`.
6
+ * - Third parties (Turnstile, reCAPTCHA, hCaptcha): render that widget with the returned `siteKey` and `action` (Turnstile also has `cData`),
7
+ * then pass the widget's token here to be sent as `captchaToken`. The provider is a site setting, and the server verifies accordingly.
8
+ */
9
+ const DEFAULT_MAX_NUMBER = 1_000_000;
10
+ function toHex(buffer) {
11
+ return Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, "0")).join("");
12
+ }
13
+ function toBase64(text) {
14
+ if (typeof btoa === "function")
15
+ return btoa(unescape(encodeURIComponent(text)));
16
+ return Buffer.from(text, "utf8").toString("base64");
17
+ }
18
+ /**
19
+ * Solves the built-in challenge: finds n where `SHA-256(salt + n) === challenge` and returns the ALTCHA payload (base64 JSON).
20
+ * About 0.5 to 1 second on a mid-range phone; `signal` can abort it when the user leaves the page.
21
+ */
22
+ export async function solveAltchaChallenge(challenge, options = {}) {
23
+ if (challenge.algorithm !== "SHA-256")
24
+ throw new Error(`Unsupported ALTCHA algorithm: ${challenge.algorithm}`);
25
+ const subtle = globalThis.crypto?.subtle;
26
+ if (!subtle)
27
+ throw new Error("Web Crypto is not available in this environment.");
28
+ const encoder = new TextEncoder();
29
+ const max = challenge.maxnumber ?? DEFAULT_MAX_NUMBER;
30
+ const started = Date.now();
31
+ for (let n = 0; n <= max; n += 1) {
32
+ if (options.signal?.aborted)
33
+ throw new Error("ALTCHA solving aborted.");
34
+ const digest = await subtle.digest("SHA-256", encoder.encode(`${challenge.salt}${n}`));
35
+ if (toHex(digest) === challenge.challenge) {
36
+ return toBase64(JSON.stringify({ algorithm: challenge.algorithm, challenge: challenge.challenge, number: n, salt: challenge.salt, signature: challenge.signature, took: Date.now() - started }));
37
+ }
38
+ }
39
+ throw new Error("ALTCHA challenge has no solution within maxnumber.");
40
+ }
41
+ /**
42
+ * Challenge to protection fields. The built-in challenge is solved here; for a third party, render the widget first and pass its token in as `captchaToken`.
43
+ *
44
+ * @param context What the challenge is bound to: the form id, or `customer-login:{siteId}` (built-in challenge only)
45
+ */
46
+ export async function protectionFromChallenge(challenge, options) {
47
+ const base = { _hp: "", _wp: "", _co: "", _ts: options.renderedAt };
48
+ if (challenge.provider === "kanorio") {
49
+ const payload = await solveAltchaChallenge(challenge.altcha, { signal: options.signal });
50
+ return { ...base, _tk: payload, _ctx: options.context };
51
+ }
52
+ if (!options.captchaToken) {
53
+ throw new Error(`This site uses ${challenge.provider}: render its widget with siteKey and action, then pass the widget token as captchaToken.`);
54
+ }
55
+ return { ...base, captchaToken: options.captchaToken, _ctx: options.context };
56
+ }
57
+ /**
58
+ * Protection fields for an attachment upload ticket: with the built-in challenge they are the ones used for submitting (same solution; uploads do not consume it); with a third party, use the challenge's `uploadToken`
59
+ * and keep the widget token for the submit.
60
+ */
61
+ export function uploadProtectionFromChallenge(challenge, options) {
62
+ const base = { _hp: "", _wp: "", _co: "", _ts: options.renderedAt };
63
+ if (challenge.provider === "kanorio")
64
+ return options.solved ?? null;
65
+ if (!challenge.uploadToken)
66
+ return null;
67
+ return { ...base, _tk: challenge.uploadToken, _ctx: options.context };
68
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Kanorio webhook signature verification and an on-demand `revalidateTag` handler for Next.js and Astro.
3
+ *
4
+ * The contract matches the server and the webhook documentation:
5
+ * - `X-Kanorio-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>]`, where `v1` is the HMAC-SHA256 of `${t}.${rawBody}` with the endpoint's signing secret
6
+ * - While a secret is being rotated, both the new and the old `v1=` are sent; a match on either passes
7
+ * - `X-Kanorio-Event` is the event key and `X-Kanorio-Delivery` is the delivery id (unchanged across retries and resends, so it can deduplicate)
8
+ * - Uses the Web Crypto API (`crypto.subtle`), with no dependencies on Node 20+, Cloudflare Workers and Vercel Edge
9
+ * - Takes the tags from the payload's `data.cacheTags`, adds the namespace (`kanorio:` by default, the same as `frameworkCacheTags`) and calls `revalidateTag`;
10
+ * an event lists only the tags that really changed (a single record's event does not carry `site:<id>`, so other pages stay cached), and no site-wide tag is added
11
+ */
12
+ export declare const WEBHOOK_SIGNATURE_HEADER = "x-kanorio-signature";
13
+ export declare const WEBHOOK_DELIVERY_HEADER = "x-kanorio-delivery";
14
+ export declare const WEBHOOK_EVENT_HEADER = "x-kanorio-event";
15
+ export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
16
+ export interface VerifyWebhookSignatureOptions {
17
+ rawBody: string;
18
+ /** The raw `X-Kanorio-Signature` header (`t=<unix>,v1=<hex>[,v1=<hex>]`) */
19
+ signatureHeader: string | null | undefined;
20
+ signingSecret: string;
21
+ /** Allowed clock difference in seconds (300 by default) */
22
+ toleranceSeconds?: number;
23
+ nowMs?: number;
24
+ }
25
+ export interface ParsedWebhookSignature {
26
+ timestamp: number;
27
+ signatures: string[];
28
+ }
29
+ /** Parses `t=<unix>,v1=<hex>[,v1=<hex>]`; null when malformed */
30
+ export declare function parseWebhookSignatureHeader(header: string | null | undefined): ParsedWebhookSignature | null;
31
+ /** Computes one `v1` value (hex); for several secrets, call once each and join as `t=...,v1=...,v1=...` */
32
+ export declare function computeWebhookSignature(signingSecret: string, timestamp: number | string, rawBody: string): Promise<string>;
33
+ /** Builds an `X-Kanorio-Signature` value in the server's format (for tests or simulating a delivery locally) */
34
+ export declare function buildWebhookSignatureHeader(signingSecrets: string | readonly string[], rawBody: string, timestamp: number): Promise<string>;
35
+ export declare function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<boolean>;
36
+ /** The generic JSON webhook payload (version 1) */
37
+ export interface WebhookEnvelope {
38
+ version?: string;
39
+ /** Same as `X-Kanorio-Delivery`; unchanged on retries and resends */
40
+ id?: string;
41
+ /** Event key, for example `collections.item.published` or `content.site.published` */
42
+ event?: string;
43
+ occurredAt?: string;
44
+ websiteId?: string;
45
+ title?: string;
46
+ summary?: string;
47
+ fields?: Array<{
48
+ label: string;
49
+ value: string;
50
+ }>;
51
+ data?: {
52
+ publicVersion?: string | null;
53
+ cacheTags?: string[];
54
+ [key: string]: unknown;
55
+ };
56
+ actionUrl?: string | null;
57
+ }
58
+ /** The tags an event asks to clear (raw strings, no namespace); the event already lists every tag to clear */
59
+ export declare function extractWebhookCacheTags(payload: WebhookEnvelope): string[];
60
+ export interface RevalidateHandlerOptions {
61
+ /** The webhook endpoint's signing secret (`whsec_...`) */
62
+ signingSecret: string;
63
+ /** Next.js `revalidateTag` or your own cache invalidation function */
64
+ revalidateTag: (tag: string) => void | Promise<void>;
65
+ /**
66
+ * Namespace added before calling `revalidateTag` (`kanorio:` by default); it must match the tags that `frameworkCacheTags()` and `cacheTags.*` put on the cache when reading.
67
+ * Pass `""` to use the raw tags
68
+ */
69
+ tagPrefix?: string;
70
+ toleranceSeconds?: number;
71
+ onEvent?: (payload: WebhookEnvelope, revalidatedTags: string[]) => void | Promise<void>;
72
+ }
73
+ /**
74
+ * Creates a standard `POST` route handler (export it from Next.js `app/api/revalidate/route.ts` or an Astro endpoint).
75
+ */
76
+ export declare function createRevalidateHandler(options: RevalidateHandlerOptions): (request: Request) => Promise<Response>;
77
+ export declare const revalidate: {
78
+ readonly handler: typeof createRevalidateHandler;
79
+ readonly verifySignature: typeof verifyWebhookSignature;
80
+ readonly computeSignature: typeof computeWebhookSignature;
81
+ readonly buildSignatureHeader: typeof buildWebhookSignatureHeader;
82
+ readonly parseSignatureHeader: typeof parseWebhookSignatureHeader;
83
+ readonly extractCacheTags: typeof extractWebhookCacheTags;
84
+ };
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Kanorio webhook signature verification and an on-demand `revalidateTag` handler for Next.js and Astro.
3
+ *
4
+ * The contract matches the server and the webhook documentation:
5
+ * - `X-Kanorio-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>]`, where `v1` is the HMAC-SHA256 of `${t}.${rawBody}` with the endpoint's signing secret
6
+ * - While a secret is being rotated, both the new and the old `v1=` are sent; a match on either passes
7
+ * - `X-Kanorio-Event` is the event key and `X-Kanorio-Delivery` is the delivery id (unchanged across retries and resends, so it can deduplicate)
8
+ * - Uses the Web Crypto API (`crypto.subtle`), with no dependencies on Node 20+, Cloudflare Workers and Vercel Edge
9
+ * - Takes the tags from the payload's `data.cacheTags`, adds the namespace (`kanorio:` by default, the same as `frameworkCacheTags`) and calls `revalidateTag`;
10
+ * an event lists only the tags that really changed (a single record's event does not carry `site:<id>`, so other pages stay cached), and no site-wide tag is added
11
+ */
12
+ import { DEFAULT_CACHE_TAG_PREFIX, prefixCacheTags } from "./shared/api/delivery/cache-tags.js";
13
+ export const WEBHOOK_SIGNATURE_HEADER = "x-kanorio-signature";
14
+ export const WEBHOOK_DELIVERY_HEADER = "x-kanorio-delivery";
15
+ export const WEBHOOK_EVENT_HEADER = "x-kanorio-event";
16
+ export const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
17
+ function bytesToHex(bytes) {
18
+ let out = "";
19
+ for (let i = 0; i < bytes.length; i++) {
20
+ out += bytes[i].toString(16).padStart(2, "0");
21
+ }
22
+ return out;
23
+ }
24
+ function constantTimeEqual(a, b) {
25
+ if (a.length !== b.length)
26
+ return false;
27
+ let diff = 0;
28
+ for (let i = 0; i < a.length; i++) {
29
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
30
+ }
31
+ return diff === 0;
32
+ }
33
+ /** Parses `t=<unix>,v1=<hex>[,v1=<hex>]`; null when malformed */
34
+ export function parseWebhookSignatureHeader(header) {
35
+ if (!header)
36
+ return null;
37
+ let timestamp = null;
38
+ const signatures = [];
39
+ for (const part of header.split(",")) {
40
+ const idx = part.indexOf("=");
41
+ if (idx <= 0)
42
+ continue;
43
+ const key = part.slice(0, idx).trim();
44
+ const value = part.slice(idx + 1).trim();
45
+ if (key === "t") {
46
+ const n = Number(value);
47
+ if (Number.isFinite(n) && n > 0)
48
+ timestamp = n;
49
+ }
50
+ else if (key === "v1" && /^[0-9a-f]+$/i.test(value)) {
51
+ signatures.push(value.toLowerCase());
52
+ }
53
+ }
54
+ if (timestamp === null || signatures.length === 0)
55
+ return null;
56
+ return { timestamp, signatures };
57
+ }
58
+ /** Computes one `v1` value (hex); for several secrets, call once each and join as `t=...,v1=...,v1=...` */
59
+ export async function computeWebhookSignature(signingSecret, timestamp, rawBody) {
60
+ const enc = new TextEncoder();
61
+ const key = await crypto.subtle.importKey("raw", enc.encode(signingSecret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
62
+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(`${timestamp}.${rawBody}`));
63
+ return bytesToHex(new Uint8Array(sig));
64
+ }
65
+ /** Builds an `X-Kanorio-Signature` value in the server's format (for tests or simulating a delivery locally) */
66
+ export async function buildWebhookSignatureHeader(signingSecrets, rawBody, timestamp) {
67
+ const list = typeof signingSecrets === "string" ? [signingSecrets] : signingSecrets;
68
+ const parts = [];
69
+ for (const secret of list) {
70
+ parts.push(`v1=${await computeWebhookSignature(secret, timestamp, rawBody)}`);
71
+ }
72
+ return [`t=${timestamp}`, ...parts].join(",");
73
+ }
74
+ export async function verifyWebhookSignature(options) {
75
+ if (!options.signingSecret)
76
+ return false;
77
+ const parsed = parseWebhookSignatureHeader(options.signatureHeader);
78
+ if (!parsed)
79
+ return false;
80
+ const tolerance = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
81
+ const nowSeconds = Math.floor((options.nowMs ?? Date.now()) / 1000);
82
+ if (Math.abs(nowSeconds - parsed.timestamp) > tolerance)
83
+ return false;
84
+ const expected = await computeWebhookSignature(options.signingSecret, parsed.timestamp, options.rawBody);
85
+ // During a rotation the server sends both the new and the old v1; the receiver holds one of the secrets, and a match on either passes
86
+ return parsed.signatures.some((sig) => constantTimeEqual(sig, expected));
87
+ }
88
+ /** The tags an event asks to clear (raw strings, no namespace); the event already lists every tag to clear */
89
+ export function extractWebhookCacheTags(payload) {
90
+ const tags = new Set();
91
+ if (Array.isArray(payload.data?.cacheTags)) {
92
+ for (const tag of payload.data.cacheTags) {
93
+ if (typeof tag === "string" && tag.trim())
94
+ tags.add(tag.trim());
95
+ }
96
+ }
97
+ return [...tags];
98
+ }
99
+ /**
100
+ * Creates a standard `POST` route handler (export it from Next.js `app/api/revalidate/route.ts` or an Astro endpoint).
101
+ */
102
+ export function createRevalidateHandler(options) {
103
+ return async function POST(request) {
104
+ const rawBody = await request.text().catch(() => "");
105
+ const valid = await verifyWebhookSignature({
106
+ rawBody,
107
+ signatureHeader: request.headers.get(WEBHOOK_SIGNATURE_HEADER),
108
+ signingSecret: options.signingSecret,
109
+ toleranceSeconds: options.toleranceSeconds,
110
+ });
111
+ if (!valid) {
112
+ return new Response(JSON.stringify({ ok: false, error: "Invalid webhook signature" }), { status: 401, headers: { "content-type": "application/json" } });
113
+ }
114
+ let payload;
115
+ try {
116
+ payload = JSON.parse(rawBody);
117
+ }
118
+ catch {
119
+ return new Response(JSON.stringify({ ok: false, error: "Invalid JSON payload" }), { status: 400, headers: { "content-type": "application/json" } });
120
+ }
121
+ const tags = prefixCacheTags(extractWebhookCacheTags(payload), options.tagPrefix ?? DEFAULT_CACHE_TAG_PREFIX);
122
+ for (const tag of tags) {
123
+ await options.revalidateTag(tag);
124
+ }
125
+ if (options.onEvent) {
126
+ await options.onEvent(payload, tags);
127
+ }
128
+ return new Response(JSON.stringify({
129
+ ok: true,
130
+ deliveryId: payload.id ?? request.headers.get(WEBHOOK_DELIVERY_HEADER) ?? null,
131
+ revalidated: tags,
132
+ publicVersion: payload.data?.publicVersion ?? null,
133
+ }), { status: 200, headers: { "content-type": "application/json" } });
134
+ };
135
+ }
136
+ export const revalidate = {
137
+ handler: createRevalidateHandler,
138
+ verifySignature: verifyWebhookSignature,
139
+ computeSignature: computeWebhookSignature,
140
+ buildSignatureHeader: buildWebhookSignatureHeader,
141
+ parseSignatureHeader: parseWebhookSignatureHeader,
142
+ extractCacheTags: extractWebhookCacheTags,
143
+ };
package/dist/seo.d.ts ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Helpers for headless SEO and AEO files and JSON-LD:
3
+ * - `seoRewrites({ siteUrl, framework })`: rules to spread into `next.config` `rewrites()`, or a map for `astro.config`
4
+ * - `fetchDeliveryJsonLd({ siteUrl, path })`: fetches a path's Schema.org JSON-LD `@graph` and a safely escaped `<script>` string
5
+ * - `fetchSitemapEntries({ siteUrl })`: `sitemap.xml` as data, for front ends that build their own sitemap and merge it in
6
+ * - `listingRobots(site, key)`: the robots value of a list page, from `listings` in `/api/v1/site`
7
+ */
8
+ import type { components as DeliveryComponents } from "./generated/delivery.js";
9
+ import { buildAlternates, languageSwitcher } from "./locales.js";
10
+ export type ListingState = DeliveryComponents["schemas"]["ListingState"];
11
+ export type ListingKey = keyof NonNullable<DeliveryComponents["schemas"]["SiteMeta"]["listings"]>;
12
+ export type SeoRewriteFramework = "next" | "astro";
13
+ export interface NextSeoRewriteRule {
14
+ source: string;
15
+ destination: string;
16
+ }
17
+ export interface SeoRewritesOptions {
18
+ /** The site's system URL or custom domain (for example `https://s-k4m9x2p7q8w3.kanorio.com`) */
19
+ siteUrl: string;
20
+ framework: SeoRewriteFramework;
21
+ }
22
+ export declare function seoRewrites(options: {
23
+ siteUrl: string;
24
+ framework: "next";
25
+ }): NextSeoRewriteRule[];
26
+ export declare function seoRewrites(options: {
27
+ siteUrl: string;
28
+ framework: "astro";
29
+ }): Record<string, string>;
30
+ export declare function seoRewrites(options: SeoRewritesOptions): NextSeoRewriteRule[] | Record<string, string>;
31
+ export interface DeliveryJsonLdResult {
32
+ jsonLd: Record<string, unknown>;
33
+ /** A JSON string with `<`, `>` and `&` escaped as Unicode escapes, safe inside `<script type="application/ld+json">` */
34
+ scriptJson: string;
35
+ cacheTags: string[];
36
+ }
37
+ export declare function fetchDeliveryJsonLd(options: {
38
+ siteUrl: string;
39
+ path?: string;
40
+ fetch?: typeof globalThis.fetch;
41
+ }): Promise<DeliveryJsonLdResult | null>;
42
+ /** One sitemap entry (`GET /api/v1/seo/sitemap`) */
43
+ export interface SitemapEntry {
44
+ url: string;
45
+ /** In-site path, starting with `/` */
46
+ path: string;
47
+ /** YYYY-MM-DD */
48
+ lastModified: string;
49
+ changeFrequency: string;
50
+ priority: number;
51
+ /** What the URL is: page, blog-post, product, collection-item, ... */
52
+ kind: string;
53
+ locale?: string;
54
+ alternates?: Array<{
55
+ hreflang: string;
56
+ href: string;
57
+ }>;
58
+ }
59
+ export interface SitemapEntriesResult {
60
+ siteUrl: string;
61
+ urls: SitemapEntry[];
62
+ cacheTags: string[];
63
+ }
64
+ /**
65
+ * The URLs Kanorio manages (the same list as `/api/v1/seo/sitemap.xml`, as data).
66
+ * A site with only part of its content on Kanorio merges this list with its own URLs in its sitemap generator:
67
+ *
68
+ * ```ts
69
+ * // app/sitemap.ts (Next.js)
70
+ * export default async function sitemap() {
71
+ * const kanorio = await fetchSitemapEntries({ siteUrl });
72
+ * return [...ownUrls, ...(kanorio?.urls ?? []).map((u) => ({ url: u.url, lastModified: u.lastModified }))];
73
+ * }
74
+ * ```
75
+ *
76
+ * Returns null when the origin fetch fails, so the caller can decide whether to output only its own URLs.
77
+ */
78
+ export declare function fetchSitemapEntries(options: {
79
+ siteUrl: string;
80
+ fetch?: typeof globalThis.fetch;
81
+ }): Promise<SitemapEntriesResult | null>;
82
+ /**
83
+ * The robots value a list page (blog index, post category page, shop index, ...) should output, by the same rules as Kanorio's sitemap and IndexNow:
84
+ * - `live` → `"index, follow"`
85
+ * - `empty` (no content yet): `"noindex, follow"`, and the page renders as usual
86
+ * - `off` (hidden by the owner, or not declared in externalListings): `null`; the page should not be served, so answer 404
87
+ *
88
+ * `site` is the `GET /api/v1/site` response. `listings` is missing only in responses cached before the upgrade; the SDK has no content
89
+ * flags to derive it from, so it falls back to `live` to keep the earlier behavior. That fallback is not a defined meaning.
90
+ */
91
+ export declare function listingRobots(site: {
92
+ listings?: Partial<Record<ListingKey, ListingState>> | null;
93
+ }, key: ListingKey): "index, follow" | "noindex, follow" | null;
94
+ export interface SeoHelpers {
95
+ rewrites(options: {
96
+ framework: "next";
97
+ }): NextSeoRewriteRule[];
98
+ rewrites(options: {
99
+ framework: "astro";
100
+ }): Record<string, string>;
101
+ rewrites(options: {
102
+ framework: SeoRewriteFramework;
103
+ }): NextSeoRewriteRule[] | Record<string, string>;
104
+ jsonLd(path?: string): Promise<DeliveryJsonLdResult | null>;
105
+ sitemapEntries(): Promise<SitemapEntriesResult | null>;
106
+ }
107
+ export declare function createSeoHelpers(options: {
108
+ siteUrl: string;
109
+ fetch?: typeof globalThis.fetch;
110
+ }): SeoHelpers;
111
+ export declare const seo: {
112
+ readonly rewrites: typeof seoRewrites;
113
+ readonly jsonLd: typeof fetchDeliveryJsonLd;
114
+ readonly sitemapEntries: typeof fetchSitemapEntries;
115
+ readonly listingRobots: typeof listingRobots;
116
+ /** A page's canonical and hreflang on multilingual sites (`locales.alternates`) */
117
+ readonly alternates: typeof buildAlternates;
118
+ readonly languageSwitcher: typeof languageSwitcher;
119
+ readonly create: typeof createSeoHelpers;
120
+ };