@kanorio/sdk 0.0.0-stage → 1.0.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 +116 -0
  7. package/dist/delivery.d.ts +35 -0
  8. package/dist/delivery.js +49 -0
  9. package/dist/edge.d.ts +104 -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 +2380 -0
  15. package/dist/generated/management.d.ts +38248 -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 +86 -0
  39. package/dist/shared/api/server-key.js +252 -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 +67 -0
  79. package/dist/shared/utils/redirect-matching.js +148 -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`:Next.js Draft Mode 與 Astro 預覽權杖(`knr_pv_`)輔助(Stage F3)。
3
+ *
4
+ * - `previewHeaders(token)`:組裝 `X-Kanorio-Preview: knr_pv_...` 標頭,配合 `?preview=1` 讀取未發布草稿。
5
+ * - `tokenFromCookieHeader(cookieHeader)`:從 `Request` 的 `Cookie` 標頭安全取出 `kanorio_preview` 權杖。
6
+ * - `createPreviewRouteHandler({ siteUrl, enableDraftMode })`:一行掛在 Next.js `app/api/preview/route.ts` 或 Astro endpoint,
7
+ * 驗證 `knr_pv_` 格式、(當提供 `siteUrl` 時)向 Kanorio Delivery API 驗證簽章與時效、阻擋 open redirect,
8
+ * 寫入 `kanorio_preview` HttpOnly cookie 並 307 導向目標頁。
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
+ // 形狀是 `knr_pv_{siteId}.{expiresAtSec}.{jti}.{sig}`;jti 與 sig 都是 base64url,可能含 `-` 與 `_`。
14
+ // jti 一段必須接受 `-`:不接受時約六分之一的合法權杖會被判成格式錯誤(預覽路由回 401、cookie 讀不出來)。
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
+ /** 僅允許以單一 `/` 開頭的站內路徑,阻擋 `//evil.com` 或 `https://evil.com` open redirect */
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
+ /** 從 HTTP `Cookie` 標頭提取並驗證 `kanorio_preview` 權杖;不存在或格式不符時回傳 `null` */
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
+ // 上游網路暫時異常時不誤擋格式合法的權杖
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
+ * 人機驗證(表單、顧客登入共用):把 `GET /api/v1/forms/{id}/challenge` 或 `GET /api/v1/customer/auth/protection`
3
+ * 回的題目變成送出時要帶的防護欄位。
4
+ *
5
+ * - `provider: "kanorio"`:內建的 ALTCHA 工作量證明,這裡直接解(Web Crypto,瀏覽器與 Node 20 都能跑),payload 放 `_tk`。
6
+ * - 第三方(Turnstile、reCAPTCHA、hCaptcha):用回傳的 `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,
7
+ * 把 widget 給的 token 交給這裡,放 `captchaToken`。提供者由網站設定決定,伺服器依設定驗。
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:把驗證畫出來(網站登入量異常時) */
30
+ visible?: boolean;
31
+ /** 只有表單:附件上傳票用(第三方 token 是一次性的,留給送出) */
32
+ uploadToken?: string;
33
+ };
34
+ /** 送出時帶的防護欄位(`_hp`、`_wp`、`_co` 是蜜罐,一律空字串) */
35
+ export interface ProtectionFields {
36
+ _hp: "";
37
+ _wp: "";
38
+ _co: "";
39
+ /** 畫面顯示的時間(Unix 毫秒) */
40
+ _ts: number;
41
+ /** 內建:解完的 ALTCHA payload */
42
+ _tk?: string;
43
+ /** 題目綁的對象:表單 id,或 `customer-login:{siteId}` */
44
+ _ctx?: string;
45
+ /** 第三方:widget 給的 token */
46
+ captchaToken?: string;
47
+ }
48
+ /**
49
+ * 解內建題目:找出 `SHA-256(salt + n) === challenge` 的 n,回 ALTCHA payload(base64 JSON)。
50
+ * 中階手機約 0.5~1 秒;`signal` 可在使用者離開頁面時中止。
51
+ */
52
+ export declare function solveAltchaChallenge(challenge: AltchaChallenge, options?: {
53
+ signal?: AbortSignal;
54
+ }): Promise<string>;
55
+ /**
56
+ * 題目 → 防護欄位。內建題目在這裡解;第三方要先畫 widget 拿到 token,再以 `captchaToken` 傳進來。
57
+ *
58
+ * @param context 題目綁的對象:表單 id,或 `customer-login:{siteId}`(內建題目才用)
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
+ * 附件上傳票的防護欄位:內建時就是送出用的那份(同一個解、上傳不消費);第三方時用 challenge 的 `uploadToken`,
68
+ * widget token 留給送出。
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
+ * 人機驗證(表單、顧客登入共用):把 `GET /api/v1/forms/{id}/challenge` 或 `GET /api/v1/customer/auth/protection`
3
+ * 回的題目變成送出時要帶的防護欄位。
4
+ *
5
+ * - `provider: "kanorio"`:內建的 ALTCHA 工作量證明,這裡直接解(Web Crypto,瀏覽器與 Node 20 都能跑),payload 放 `_tk`。
6
+ * - 第三方(Turnstile、reCAPTCHA、hCaptcha):用回傳的 `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,
7
+ * 把 widget 給的 token 交給這裡,放 `captchaToken`。提供者由網站設定決定,伺服器依設定驗。
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
+ * 解內建題目:找出 `SHA-256(salt + n) === challenge` 的 n,回 ALTCHA payload(base64 JSON)。
20
+ * 中階手機約 0.5~1 秒;`signal` 可在使用者離開頁面時中止。
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
+ * 題目 → 防護欄位。內建題目在這裡解;第三方要先畫 widget 拿到 token,再以 `captchaToken` 傳進來。
43
+ *
44
+ * @param context 題目綁的對象:表單 id,或 `customer-login:{siteId}`(內建題目才用)
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
+ * 附件上傳票的防護欄位:內建時就是送出用的那份(同一個解、上傳不消費);第三方時用 challenge 的 `uploadToken`,
59
+ * widget token 留給送出。
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 驗章與 Next.js / Astro On-Demand ISR `revalidateTag` 處理器(階段 6)。
3
+ *
4
+ * 契約與伺服器端 `lib/notifications/team/adapters/webhook.ts` 及 docs/infrastructure/webhooks/README.md 一致:
5
+ * - `X-Kanorio-Signature: t=<unix 秒>,v1=<hex>[,v1=<hex>]`,`v1` 是以端點簽章金鑰對 `${t}.${rawBody}` 計算的 HMAC-SHA256
6
+ * - 金鑰輪替並行期內會同時附新舊兩個 `v1=`,任一相符即通過
7
+ * - `X-Kanorio-Event` 為事件鍵、`X-Kanorio-Delivery` 為投遞 id(重試與重送間不變,可去重)
8
+ * - 使用 Web Crypto API(`crypto.subtle`),於 Node 20+、Cloudflare Workers、Vercel Edge 皆零依賴可用
9
+ * - 從 payload 的 `data.cacheTags` 取出標籤、加上命名空間(預設 `kanorio:`,與 `frameworkCacheTags` 同一套)後呼叫 `revalidateTag`;
10
+ * 事件只列出真的變了的標籤(單筆內容的事件不帶 `site:<id>`,別的頁不動),不再自動補整站標籤
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
+ /** `X-Kanorio-Signature` 標頭原值(`t=<unix>,v1=<hex>[,v1=<hex>]`) */
19
+ signatureHeader: string | null | undefined;
20
+ signingSecret: string;
21
+ /** 允許的時間偏移秒數(預設 300 秒) */
22
+ toleranceSeconds?: number;
23
+ nowMs?: number;
24
+ }
25
+ export interface ParsedWebhookSignature {
26
+ timestamp: number;
27
+ signatures: string[];
28
+ }
29
+ /** 解析 `t=<unix>,v1=<hex>[,v1=<hex>]`;格式不符回 null */
30
+ export declare function parseWebhookSignatureHeader(header: string | null | undefined): ParsedWebhookSignature | null;
31
+ /** 計算單一 `v1` 值(hex);多把金鑰請各呼叫一次再以 `t=…,v1=…,v1=…` 組合 */
32
+ export declare function computeWebhookSignature(signingSecret: string, timestamp: number | string, rawBody: string): Promise<string>;
33
+ /** 產生與伺服器相同格式的 `X-Kanorio-Signature` 值(測試或本機模擬投遞用) */
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
+ /** 通用 JSON webhook payload(`formatGenericWebhook`,version 1) */
37
+ export interface WebhookEnvelope {
38
+ version?: string;
39
+ /** 與 `X-Kanorio-Delivery` 相同,重試與重送時不變 */
40
+ id?: string;
41
+ /** 事件鍵,例如 `collections.item.published`、`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
+ /** 事件要清的標籤(原始字串,不含命名空間);事件本身已列出該清的全部標籤 */
59
+ export declare function extractWebhookCacheTags(payload: WebhookEnvelope): string[];
60
+ export interface RevalidateHandlerOptions {
61
+ /** Webhook 端點的簽章金鑰(`whsec_...`) */
62
+ signingSecret: string;
63
+ /** Next.js `revalidateTag` 或自訂快取失效函式 */
64
+ revalidateTag: (tag: string) => void | Promise<void>;
65
+ /**
66
+ * 交給 `revalidateTag` 前加的命名空間(預設 `kanorio:`),要與讀取時 `frameworkCacheTags()`/`cacheTags.*` 打在快取上的標籤一致;
67
+ * 傳 `""` 用原始標籤
68
+ */
69
+ tagPrefix?: string;
70
+ toleranceSeconds?: number;
71
+ onEvent?: (payload: WebhookEnvelope, revalidatedTags: string[]) => void | Promise<void>;
72
+ }
73
+ /**
74
+ * 建立標準 `POST` Route Handler(直接 export 於 Next.js `app/api/revalidate/route.ts` 或 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 驗章與 Next.js / Astro On-Demand ISR `revalidateTag` 處理器(階段 6)。
3
+ *
4
+ * 契約與伺服器端 `lib/notifications/team/adapters/webhook.ts` 及 docs/infrastructure/webhooks/README.md 一致:
5
+ * - `X-Kanorio-Signature: t=<unix 秒>,v1=<hex>[,v1=<hex>]`,`v1` 是以端點簽章金鑰對 `${t}.${rawBody}` 計算的 HMAC-SHA256
6
+ * - 金鑰輪替並行期內會同時附新舊兩個 `v1=`,任一相符即通過
7
+ * - `X-Kanorio-Event` 為事件鍵、`X-Kanorio-Delivery` 為投遞 id(重試與重送間不變,可去重)
8
+ * - 使用 Web Crypto API(`crypto.subtle`),於 Node 20+、Cloudflare Workers、Vercel Edge 皆零依賴可用
9
+ * - 從 payload 的 `data.cacheTags` 取出標籤、加上命名空間(預設 `kanorio:`,與 `frameworkCacheTags` 同一套)後呼叫 `revalidateTag`;
10
+ * 事件只列出真的變了的標籤(單筆內容的事件不帶 `site:<id>`,別的頁不動),不再自動補整站標籤
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
+ /** 解析 `t=<unix>,v1=<hex>[,v1=<hex>]`;格式不符回 null */
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
+ /** 計算單一 `v1` 值(hex);多把金鑰請各呼叫一次再以 `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
+ /** 產生與伺服器相同格式的 `X-Kanorio-Signature` 值(測試或本機模擬投遞用) */
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
+ // 輪替期內伺服器會附新舊兩個 v1;接收端只持有其中一把,任一相符即通過
86
+ return parsed.signatures.some((sig) => constantTimeEqual(sig, expected));
87
+ }
88
+ /** 事件要清的標籤(原始字串,不含命名空間);事件本身已列出該清的全部標籤 */
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
+ * 建立標準 `POST` Route Handler(直接 export 於 Next.js `app/api/revalidate/route.ts` 或 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
+ * Headless SEO/AEO 衍生檔與 JSON-LD 輔助工具(階段 6/PR-4h):
3
+ * - `seoRewrites({ siteUrl, framework })`:回傳可直接展開進 `next.config` `rewrites()` 或 `astro.config` 的規則陣列/映射
4
+ * - `fetchDeliveryJsonLd({ siteUrl, path })`:抓取指定路徑的 Schema.org JSON-LD `@graph` 與安全轉義後的 `<script>` 字串
5
+ * - `fetchSitemapEntries({ siteUrl })`:`sitemap.xml` 的資料版,給自己組 sitemap 的前端合併用
6
+ * - `listingRobots(site, key)`:依 `/api/v1/site` 的 `listings` 決定列表頁的 robots 值
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
+ /** 站台系統網址或自訂網域(例如 `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
+ /** 已將 `<`、`>`、`&` 轉義為 Unicode escape 的 JSON 字串,可安全放入 `<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
+ /** 一筆 sitemap 項目(`GET /api/v1/seo/sitemap`) */
43
+ export interface SitemapEntry {
44
+ url: string;
45
+ /** 站內路徑,以 `/` 開頭 */
46
+ path: string;
47
+ /** YYYY-MM-DD */
48
+ lastModified: string;
49
+ changeFrequency: string;
50
+ priority: number;
51
+ /** 這個網址是什麼: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
+ * Kanorio 管的網址清單(與 `/api/v1/seo/sitemap.xml` 同一份,資料格式)。
66
+ * 只有部分內容在 Kanorio 的站,在自己的 sitemap 產生器把這份清單和自己的網址合在一起:
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
+ * 回源失敗回 null,由呼叫端決定要不要只輸出自己的網址。
77
+ */
78
+ export declare function fetchSitemapEntries(options: {
79
+ siteUrl: string;
80
+ fetch?: typeof globalThis.fetch;
81
+ }): Promise<SitemapEntriesResult | null>;
82
+ /**
83
+ * 列表頁(部落格首頁、文章分類頁、商店首頁…)該輸出的 robots 值,與 Kanorio 的 sitemap/IndexNow 同一套判斷:
84
+ * - `live` → `"index, follow"`
85
+ * - `empty`(還沒有內容)→ `"noindex, follow"`,頁面照常渲染
86
+ * - `off`(站主隱藏,或沒有在 externalListings 宣告)→ `null`:這頁不該對外提供,請回 404
87
+ *
88
+ * `site` 是 `GET /api/v1/site` 的回應。缺 `listings` 只會發生在升級前就快取的舊回應;SDK 端沒有內容
89
+ * 旗標可推導,退回 `live` 以維持升級前的行為,不是正式語意。
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
+ /** 多語網站一頁的 canonical 與 hreflang(`locales.alternates`) */
117
+ readonly alternates: typeof buildAlternates;
118
+ readonly languageSwitcher: typeof languageSwitcher;
119
+ readonly create: typeof createSeoHelpers;
120
+ };