@kanorio/sdk 1.0.0 → 1.2.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 (81) hide show
  1. package/README.md +41 -2
  2. package/dist/customer-oauth.d.ts +21 -21
  3. package/dist/customer-oauth.js +12 -12
  4. package/dist/customer.d.ts +22 -22
  5. package/dist/customer.js +20 -11
  6. package/dist/delivery.d.ts +9 -9
  7. package/dist/delivery.js +6 -6
  8. package/dist/edge.d.ts +25 -21
  9. package/dist/edge.js +36 -20
  10. package/dist/forms.d.ts +33 -14
  11. package/dist/forms.js +20 -14
  12. package/dist/generated/delivery.d.ts +564 -13
  13. package/dist/generated/management.d.ts +790 -81
  14. package/dist/http.d.ts +13 -13
  15. package/dist/http.js +8 -8
  16. package/dist/image.d.ts +77 -0
  17. package/dist/image.js +78 -0
  18. package/dist/index.d.ts +2 -1
  19. package/dist/index.js +4 -3
  20. package/dist/locales.d.ts +22 -22
  21. package/dist/locales.js +12 -12
  22. package/dist/management.d.ts +5 -5
  23. package/dist/management.js +3 -3
  24. package/dist/next.d.ts +66 -0
  25. package/dist/next.js +58 -0
  26. package/dist/paginate.d.ts +3 -3
  27. package/dist/paginate.js +3 -3
  28. package/dist/preview.d.ts +13 -13
  29. package/dist/preview.js +11 -11
  30. package/dist/protection.d.ts +18 -18
  31. package/dist/protection.js +11 -11
  32. package/dist/revalidate.d.ts +22 -22
  33. package/dist/revalidate.js +14 -14
  34. package/dist/seo.d.ts +137 -21
  35. package/dist/seo.js +113 -21
  36. package/dist/server-key.d.ts +2 -2
  37. package/dist/server-key.js +2 -2
  38. package/dist/shared/api/delivery/cache-tags.d.ts +41 -39
  39. package/dist/shared/api/delivery/cache-tags.js +36 -34
  40. package/dist/shared/api/server-key.d.ts +32 -28
  41. package/dist/shared/api/server-key.js +41 -33
  42. package/dist/shared/business-registry/attribution.d.ts +5 -5
  43. package/dist/shared/business-registry/attribution.js +4 -4
  44. package/dist/shared/business-registry/define.d.ts +1 -1
  45. package/dist/shared/business-registry/define.js +1 -1
  46. package/dist/shared/business-registry/formats/eu-vat.js +4 -4
  47. package/dist/shared/business-registry/formats/hk-br.d.ts +2 -2
  48. package/dist/shared/business-registry/formats/hk-br.js +4 -4
  49. package/dist/shared/business-registry/formats/jp-trn.d.ts +3 -3
  50. package/dist/shared/business-registry/formats/jp-trn.js +4 -4
  51. package/dist/shared/business-registry/formats/kr-brn.d.ts +2 -2
  52. package/dist/shared/business-registry/formats/kr-brn.js +3 -3
  53. package/dist/shared/business-registry/formats/my.d.ts +3 -3
  54. package/dist/shared/business-registry/formats/my.js +4 -4
  55. package/dist/shared/business-registry/formats/sg-uen.js +4 -4
  56. package/dist/shared/business-registry/formats/tw-vat.d.ts +5 -5
  57. package/dist/shared/business-registry/formats/tw-vat.js +6 -6
  58. package/dist/shared/business-registry/index.js +1 -1
  59. package/dist/shared/business-registry/lookup-wire.d.ts +9 -9
  60. package/dist/shared/business-registry/lookup-wire.js +4 -4
  61. package/dist/shared/business-registry/normalize.d.ts +3 -3
  62. package/dist/shared/business-registry/normalize.js +4 -4
  63. package/dist/shared/business-registry/registry.d.ts +9 -9
  64. package/dist/shared/business-registry/registry.js +13 -13
  65. package/dist/shared/business-registry/types.d.ts +20 -20
  66. package/dist/shared/business-registry/types.js +6 -6
  67. package/dist/shared/localization/locale-path.d.ts +18 -18
  68. package/dist/shared/localization/locale-path.js +18 -18
  69. package/dist/shared/localization/request-locale.d.ts +16 -16
  70. package/dist/shared/localization/request-locale.js +13 -13
  71. package/dist/shared/seo/alternates.d.ts +26 -26
  72. package/dist/shared/seo/alternates.js +18 -18
  73. package/dist/shared/types/forms-logic.d.ts +28 -28
  74. package/dist/shared/types/forms-logic.js +27 -27
  75. package/dist/shared/types/number-input.d.ts +2 -2
  76. package/dist/shared/types/number-input.js +3 -3
  77. package/dist/shared/utils/redirect-matching.d.ts +33 -24
  78. package/dist/shared/utils/redirect-matching.js +73 -40
  79. package/dist/typed.d.ts +5 -5
  80. package/dist/typed.js +3 -3
  81. package/package.json +15 -10
@@ -1,6 +1,6 @@
1
1
  /**
2
- * 三套 API 的列表都回同一個信封 `{ data, hasMore, nextCursor }`(ADR-0006 決定 2-2)。
3
- * `paginate` 依 `nextCursor` 一頁一頁取,逐筆 yield;呼叫端只要把 cursor 放進自己的查詢。
2
+ * Lists in all three APIs return the same envelope `{ data, hasMore, nextCursor }`.
3
+ * `paginate` follows `nextCursor` page by page and yields item by item; the caller only puts the cursor into its own query.
4
4
  *
5
5
  * ```ts
6
6
  * for await (const post of paginate((cursor) => client.get("/collections/{key}/items", { params: { key: "blog" }, query: { cursor } }))) {
@@ -14,5 +14,5 @@ export interface ListPage<T> {
14
14
  nextCursor: string | null;
15
15
  }
16
16
  export declare function paginate<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): AsyncGenerator<T, void, undefined>;
17
- /** 取完所有頁並回傳陣列(小清單用;大清單請用 {@link paginate} 逐筆處理) */
17
+ /** Fetches every page and returns an array (for small lists; use {@link paginate} to process large ones item by item) */
18
18
  export declare function listAll<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): Promise<T[]>;
package/dist/paginate.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * 三套 API 的列表都回同一個信封 `{ data, hasMore, nextCursor }`(ADR-0006 決定 2-2)。
3
- * `paginate` 依 `nextCursor` 一頁一頁取,逐筆 yield;呼叫端只要把 cursor 放進自己的查詢。
2
+ * Lists in all three APIs return the same envelope `{ data, hasMore, nextCursor }`.
3
+ * `paginate` follows `nextCursor` page by page and yields item by item; the caller only puts the cursor into its own query.
4
4
  *
5
5
  * ```ts
6
6
  * for await (const post of paginate((cursor) => client.get("/collections/{key}/items", { params: { key: "blog" }, query: { cursor } }))) {
@@ -18,7 +18,7 @@ export async function* paginate(fetchPage) {
18
18
  cursor = page.nextCursor;
19
19
  }
20
20
  }
21
- /** 取完所有頁並回傳陣列(小清單用;大清單請用 {@link paginate} 逐筆處理) */
21
+ /** Fetches every page and returns an array (for small lists; use {@link paginate} to process large ones item by item) */
22
22
  export async function listAll(fetchPage) {
23
23
  const out = [];
24
24
  for await (const item of paginate(fetchPage))
package/dist/preview.d.ts CHANGED
@@ -1,30 +1,30 @@
1
1
  /**
2
- * `@kanorio/sdk/preview`:Next.js Draft Mode 與 Astro 預覽權杖(`knr_pv_`)輔助(Stage F3)。
2
+ * `@kanorio/sdk/preview`: helpers for Next.js Draft Mode and Astro with preview tokens (`knr_pv_`).
3
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 導向目標頁。
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
9
  */
10
10
  export declare const PREVIEW_TOKEN_PREFIX = "knr_pv_";
11
11
  export declare const PREVIEW_COOKIE_NAME = "kanorio_preview";
12
12
  export declare function isValidPreviewTokenFormat(token: string | null | undefined): token is string;
13
- /** 僅允許以單一 `/` 開頭的站內路徑,阻擋 `//evil.com` 或 `https://evil.com` open redirect */
13
+ /** Only in-site paths starting with a single `/` are allowed, which blocks `//evil.com` and `https://evil.com` open redirects */
14
14
  export declare function sanitizePreviewRedirectPath(raw: string | null | undefined): string;
15
15
  export declare function previewHeaders(token: string): Record<string, string>;
16
- /** 從 HTTP `Cookie` 標頭提取並驗證 `kanorio_preview` 權杖;不存在或格式不符時回傳 `null` */
16
+ /** Extracts and validates the `kanorio_preview` token from an HTTP `Cookie` header; `null` when absent or malformed */
17
17
  export declare function tokenFromCookieHeader(cookieHeader: string | null | undefined): string | null;
18
18
  export interface PreviewRouteHandlerOptions {
19
19
  /**
20
- * 選填:傳入 Kanorio 系統或服務網址(如 `https://s-xxx.kanorio.com`)時,
21
- * 會在啟用 Draft Mode 前先向 `GET {siteUrl}/api/v1/site?preview=1` 驗證權杖簽章與有效期限,
22
- * 防止偽造或過期的權杖讓瀏覽器進入失敗的預覽狀態。
20
+ * Optional: with a Kanorio system or service URL (for example `https://s-xxx.kanorio.com`),
21
+ * the token's signature and expiry are verified against `GET {siteUrl}/api/v1/site?preview=1` before Draft Mode is enabled,
22
+ * so a forged or expired token cannot leave the browser in a broken preview state.
23
23
  */
24
24
  siteUrl?: string;
25
- /** Next.js App Router 傳入 `async () => (await draftMode()).enable()` */
25
+ /** In the Next.js App Router, pass `async () => (await draftMode()).enable()` */
26
26
  enableDraftMode?: (token: string) => void | Promise<void>;
27
- /** Cookie 存活秒數(預設 3600 秒) */
27
+ /** Cookie lifetime in seconds (3600 by default) */
28
28
  cookieMaxAgeSeconds?: number;
29
29
  fetch?: typeof globalThis.fetch;
30
30
  }
package/dist/preview.js CHANGED
@@ -1,17 +1,17 @@
1
1
  /**
2
- * `@kanorio/sdk/preview`:Next.js Draft Mode 與 Astro 預覽權杖(`knr_pv_`)輔助(Stage F3)。
2
+ * `@kanorio/sdk/preview`: helpers for Next.js Draft Mode and Astro with preview tokens (`knr_pv_`).
3
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 導向目標頁。
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
9
  */
10
10
  import { DELIVERY_PREVIEW_HEADER, deliveryBaseUrl } from "./delivery.js";
11
11
  export const PREVIEW_TOKEN_PREFIX = "knr_pv_";
12
12
  export const PREVIEW_COOKIE_NAME = "kanorio_preview";
13
- // 形狀是 `knr_pv_{siteId}.{expiresAtSec}.{jti}.{sig}`;jti 與 sig 都是 base64url,可能含 `-` 與 `_`。
14
- // jti 一段必須接受 `-`:不接受時約六分之一的合法權杖會被判成格式錯誤(預覽路由回 401、cookie 讀不出來)。
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
15
  const PREVIEW_TOKEN_RE = /^knr_pv_[a-z0-9]+\.\d+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/i;
16
16
  export function isValidPreviewTokenFormat(token) {
17
17
  if (!token || typeof token !== "string")
@@ -19,7 +19,7 @@ export function isValidPreviewTokenFormat(token) {
19
19
  const trimmed = token.trim();
20
20
  return trimmed.length <= 256 && PREVIEW_TOKEN_RE.test(trimmed);
21
21
  }
22
- /** 僅允許以單一 `/` 開頭的站內路徑,阻擋 `//evil.com` 或 `https://evil.com` open redirect */
22
+ /** Only in-site paths starting with a single `/` are allowed, which blocks `//evil.com` and `https://evil.com` open redirects */
23
23
  export function sanitizePreviewRedirectPath(raw) {
24
24
  if (!raw || typeof raw !== "string")
25
25
  return "/";
@@ -34,7 +34,7 @@ export function previewHeaders(token) {
34
34
  [DELIVERY_PREVIEW_HEADER]: token.trim(),
35
35
  };
36
36
  }
37
- /** 從 HTTP `Cookie` 標頭提取並驗證 `kanorio_preview` 權杖;不存在或格式不符時回傳 `null` */
37
+ /** Extracts and validates the `kanorio_preview` token from an HTTP `Cookie` header; `null` when absent or malformed */
38
38
  export function tokenFromCookieHeader(cookieHeader) {
39
39
  if (!cookieHeader)
40
40
  return null;
@@ -95,7 +95,7 @@ export function createPreviewRouteHandler(options = {}) {
95
95
  }
96
96
  }
97
97
  catch {
98
- // 上游網路暫時異常時不誤擋格式合法的權杖
98
+ // Do not reject a well-formed token when the upstream network is temporarily failing
99
99
  }
100
100
  }
101
101
  await options.enableDraftMode?.(token);
@@ -1,10 +1,10 @@
1
1
  /**
2
- * 人機驗證(表單、顧客登入共用):把 `GET /api/v1/forms/{id}/challenge` 或 `GET /api/v1/customer/auth/protection`
3
- * 回的題目變成送出時要帶的防護欄位。
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
4
  *
5
- * - `provider: "kanorio"`:內建的 ALTCHA 工作量證明,這裡直接解(Web Crypto,瀏覽器與 Node 20 都能跑),payload 放 `_tk`。
6
- * - 第三方(Turnstile、reCAPTCHA、hCaptcha):用回傳的 `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,
7
- * 把 widget 給的 token 交給這裡,放 `captchaToken`。提供者由網站設定決定,伺服器依設定驗。
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
8
  */
9
9
  export type ProtectionProvider = "kanorio" | "turnstile" | "recaptcha" | "hcaptcha";
10
10
  export interface AltchaChallenge {
@@ -26,36 +26,36 @@ export type ProtectionChallenge = {
26
26
  action: string;
27
27
  cData: string | null;
28
28
  recaptchaVersion: "v2" | "v3" | null;
29
- /** true:把驗證畫出來(網站登入量異常時) */
29
+ /** true: show the verification (when sign-in volume on the site is unusual) */
30
30
  visible?: boolean;
31
- /** 只有表單:附件上傳票用(第三方 token 是一次性的,留給送出) */
31
+ /** Forms only: for attachment upload tickets (a third-party token is single-use and is kept for the submit) */
32
32
  uploadToken?: string;
33
33
  };
34
- /** 送出時帶的防護欄位(`_hp`、`_wp`、`_co` 是蜜罐,一律空字串) */
34
+ /** Protection fields sent on submit (`_hp`, `_wp` and `_co` are honeypots, always empty strings) */
35
35
  export interface ProtectionFields {
36
36
  _hp: "";
37
37
  _wp: "";
38
38
  _co: "";
39
- /** 畫面顯示的時間(Unix 毫秒) */
39
+ /** When the screen was shown (Unix milliseconds) */
40
40
  _ts: number;
41
- /** 內建:解完的 ALTCHA payload */
41
+ /** Built-in: the solved ALTCHA payload */
42
42
  _tk?: string;
43
- /** 題目綁的對象:表單 id,或 `customer-login:{siteId}` */
43
+ /** What the challenge is bound to: the form id, or `customer-login:{siteId}` */
44
44
  _ctx?: string;
45
- /** 第三方:widget 給的 token */
45
+ /** Third party: the token from the widget */
46
46
  captchaToken?: string;
47
47
  }
48
48
  /**
49
- * 解內建題目:找出 `SHA-256(salt + n) === challenge` 的 n,回 ALTCHA payload(base64 JSON)。
50
- * 中階手機約 0.5~1 秒;`signal` 可在使用者離開頁面時中止。
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
51
  */
52
52
  export declare function solveAltchaChallenge(challenge: AltchaChallenge, options?: {
53
53
  signal?: AbortSignal;
54
54
  }): Promise<string>;
55
55
  /**
56
- * 題目 → 防護欄位。內建題目在這裡解;第三方要先畫 widget 拿到 token,再以 `captchaToken` 傳進來。
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
57
  *
58
- * @param context 題目綁的對象:表單 id,或 `customer-login:{siteId}`(內建題目才用)
58
+ * @param context What the challenge is bound to: the form id, or `customer-login:{siteId}` (built-in challenge only)
59
59
  */
60
60
  export declare function protectionFromChallenge(challenge: ProtectionChallenge, options: {
61
61
  context: string;
@@ -64,8 +64,8 @@ export declare function protectionFromChallenge(challenge: ProtectionChallenge,
64
64
  signal?: AbortSignal;
65
65
  }): Promise<ProtectionFields>;
66
66
  /**
67
- * 附件上傳票的防護欄位:內建時就是送出用的那份(同一個解、上傳不消費);第三方時用 challenge 的 `uploadToken`,
68
- * widget token 留給送出。
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
69
  */
70
70
  export declare function uploadProtectionFromChallenge(challenge: ProtectionChallenge, options: {
71
71
  context: string;
@@ -1,10 +1,10 @@
1
1
  /**
2
- * 人機驗證(表單、顧客登入共用):把 `GET /api/v1/forms/{id}/challenge` 或 `GET /api/v1/customer/auth/protection`
3
- * 回的題目變成送出時要帶的防護欄位。
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
4
  *
5
- * - `provider: "kanorio"`:內建的 ALTCHA 工作量證明,這裡直接解(Web Crypto,瀏覽器與 Node 20 都能跑),payload 放 `_tk`。
6
- * - 第三方(Turnstile、reCAPTCHA、hCaptcha):用回傳的 `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,
7
- * 把 widget 給的 token 交給這裡,放 `captchaToken`。提供者由網站設定決定,伺服器依設定驗。
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
8
  */
9
9
  const DEFAULT_MAX_NUMBER = 1_000_000;
10
10
  function toHex(buffer) {
@@ -16,8 +16,8 @@ function toBase64(text) {
16
16
  return Buffer.from(text, "utf8").toString("base64");
17
17
  }
18
18
  /**
19
- * 解內建題目:找出 `SHA-256(salt + n) === challenge` 的 n,回 ALTCHA payload(base64 JSON)。
20
- * 中階手機約 0.5~1 秒;`signal` 可在使用者離開頁面時中止。
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
21
  */
22
22
  export async function solveAltchaChallenge(challenge, options = {}) {
23
23
  if (challenge.algorithm !== "SHA-256")
@@ -39,9 +39,9 @@ export async function solveAltchaChallenge(challenge, options = {}) {
39
39
  throw new Error("ALTCHA challenge has no solution within maxnumber.");
40
40
  }
41
41
  /**
42
- * 題目 → 防護欄位。內建題目在這裡解;第三方要先畫 widget 拿到 token,再以 `captchaToken` 傳進來。
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
43
  *
44
- * @param context 題目綁的對象:表單 id,或 `customer-login:{siteId}`(內建題目才用)
44
+ * @param context What the challenge is bound to: the form id, or `customer-login:{siteId}` (built-in challenge only)
45
45
  */
46
46
  export async function protectionFromChallenge(challenge, options) {
47
47
  const base = { _hp: "", _wp: "", _co: "", _ts: options.renderedAt };
@@ -55,8 +55,8 @@ export async function protectionFromChallenge(challenge, options) {
55
55
  return { ...base, captchaToken: options.captchaToken, _ctx: options.context };
56
56
  }
57
57
  /**
58
- * 附件上傳票的防護欄位:內建時就是送出用的那份(同一個解、上傳不消費);第三方時用 challenge 的 `uploadToken`,
59
- * widget token 留給送出。
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
60
  */
61
61
  export function uploadProtectionFromChallenge(challenge, options) {
62
62
  const base = { _hp: "", _wp: "", _co: "", _ts: options.renderedAt };
@@ -1,13 +1,13 @@
1
1
  /**
2
- * Kanorio Webhook 驗章與 Next.js / Astro On-Demand ISR `revalidateTag` 處理器(階段 6)。
2
+ * Kanorio webhook signature verification and an on-demand `revalidateTag` handler for Next.js and Astro.
3
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>`,別的頁不動),不再自動補整站標籤
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
11
  */
12
12
  export declare const WEBHOOK_SIGNATURE_HEADER = "x-kanorio-signature";
13
13
  export declare const WEBHOOK_DELIVERY_HEADER = "x-kanorio-delivery";
@@ -15,10 +15,10 @@ export declare const WEBHOOK_EVENT_HEADER = "x-kanorio-event";
15
15
  export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
16
16
  export interface VerifyWebhookSignatureOptions {
17
17
  rawBody: string;
18
- /** `X-Kanorio-Signature` 標頭原值(`t=<unix>,v1=<hex>[,v1=<hex>]`) */
18
+ /** The raw `X-Kanorio-Signature` header (`t=<unix>,v1=<hex>[,v1=<hex>]`) */
19
19
  signatureHeader: string | null | undefined;
20
20
  signingSecret: string;
21
- /** 允許的時間偏移秒數(預設 300 秒) */
21
+ /** Allowed clock difference in seconds (300 by default) */
22
22
  toleranceSeconds?: number;
23
23
  nowMs?: number;
24
24
  }
@@ -26,19 +26,19 @@ export interface ParsedWebhookSignature {
26
26
  timestamp: number;
27
27
  signatures: string[];
28
28
  }
29
- /** 解析 `t=<unix>,v1=<hex>[,v1=<hex>]`;格式不符回 null */
29
+ /** Parses `t=<unix>,v1=<hex>[,v1=<hex>]`; null when malformed */
30
30
  export declare function parseWebhookSignatureHeader(header: string | null | undefined): ParsedWebhookSignature | null;
31
- /** 計算單一 `v1` 值(hex);多把金鑰請各呼叫一次再以 `t=…,v1=…,v1=…` 組合 */
31
+ /** Computes one `v1` value (hex); for several secrets, call once each and join as `t=...,v1=...,v1=...` */
32
32
  export declare function computeWebhookSignature(signingSecret: string, timestamp: number | string, rawBody: string): Promise<string>;
33
- /** 產生與伺服器相同格式的 `X-Kanorio-Signature` 值(測試或本機模擬投遞用) */
33
+ /** Builds an `X-Kanorio-Signature` value in the server's format (for tests or simulating a delivery locally) */
34
34
  export declare function buildWebhookSignatureHeader(signingSecrets: string | readonly string[], rawBody: string, timestamp: number): Promise<string>;
35
35
  export declare function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<boolean>;
36
- /** 通用 JSON webhook payload(`formatGenericWebhook`,version 1) */
36
+ /** The generic JSON webhook payload (version 1) */
37
37
  export interface WebhookEnvelope {
38
38
  version?: string;
39
- /** 與 `X-Kanorio-Delivery` 相同,重試與重送時不變 */
39
+ /** Same as `X-Kanorio-Delivery`; unchanged on retries and resends */
40
40
  id?: string;
41
- /** 事件鍵,例如 `collections.item.published`、`content.site.published` */
41
+ /** Event key, for example `collections.item.published` or `content.site.published` */
42
42
  event?: string;
43
43
  occurredAt?: string;
44
44
  websiteId?: string;
@@ -55,23 +55,23 @@ export interface WebhookEnvelope {
55
55
  };
56
56
  actionUrl?: string | null;
57
57
  }
58
- /** 事件要清的標籤(原始字串,不含命名空間);事件本身已列出該清的全部標籤 */
58
+ /** The tags an event asks to clear (raw strings, no namespace); the event already lists every tag to clear */
59
59
  export declare function extractWebhookCacheTags(payload: WebhookEnvelope): string[];
60
60
  export interface RevalidateHandlerOptions {
61
- /** Webhook 端點的簽章金鑰(`whsec_...`) */
61
+ /** The webhook endpoint's signing secret (`whsec_...`) */
62
62
  signingSecret: string;
63
- /** Next.js `revalidateTag` 或自訂快取失效函式 */
63
+ /** Next.js `revalidateTag` or your own cache invalidation function */
64
64
  revalidateTag: (tag: string) => void | Promise<void>;
65
65
  /**
66
- * 交給 `revalidateTag` 前加的命名空間(預設 `kanorio:`),要與讀取時 `frameworkCacheTags()`/`cacheTags.*` 打在快取上的標籤一致;
67
- * 傳 `""` 用原始標籤
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
68
  */
69
69
  tagPrefix?: string;
70
70
  toleranceSeconds?: number;
71
71
  onEvent?: (payload: WebhookEnvelope, revalidatedTags: string[]) => void | Promise<void>;
72
72
  }
73
73
  /**
74
- * 建立標準 `POST` Route Handler(直接 export 於 Next.js `app/api/revalidate/route.ts` 或 Astro endpoint)。
74
+ * Creates a standard `POST` route handler (export it from Next.js `app/api/revalidate/route.ts` or an Astro endpoint).
75
75
  */
76
76
  export declare function createRevalidateHandler(options: RevalidateHandlerOptions): (request: Request) => Promise<Response>;
77
77
  export declare const revalidate: {
@@ -1,13 +1,13 @@
1
1
  /**
2
- * Kanorio Webhook 驗章與 Next.js / Astro On-Demand ISR `revalidateTag` 處理器(階段 6)。
2
+ * Kanorio webhook signature verification and an on-demand `revalidateTag` handler for Next.js and Astro.
3
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>`,別的頁不動),不再自動補整站標籤
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
11
  */
12
12
  import { DEFAULT_CACHE_TAG_PREFIX, prefixCacheTags } from "./shared/api/delivery/cache-tags.js";
13
13
  export const WEBHOOK_SIGNATURE_HEADER = "x-kanorio-signature";
@@ -30,7 +30,7 @@ function constantTimeEqual(a, b) {
30
30
  }
31
31
  return diff === 0;
32
32
  }
33
- /** 解析 `t=<unix>,v1=<hex>[,v1=<hex>]`;格式不符回 null */
33
+ /** Parses `t=<unix>,v1=<hex>[,v1=<hex>]`; null when malformed */
34
34
  export function parseWebhookSignatureHeader(header) {
35
35
  if (!header)
36
36
  return null;
@@ -55,14 +55,14 @@ export function parseWebhookSignatureHeader(header) {
55
55
  return null;
56
56
  return { timestamp, signatures };
57
57
  }
58
- /** 計算單一 `v1` 值(hex);多把金鑰請各呼叫一次再以 `t=…,v1=…,v1=…` 組合 */
58
+ /** Computes one `v1` value (hex); for several secrets, call once each and join as `t=...,v1=...,v1=...` */
59
59
  export async function computeWebhookSignature(signingSecret, timestamp, rawBody) {
60
60
  const enc = new TextEncoder();
61
61
  const key = await crypto.subtle.importKey("raw", enc.encode(signingSecret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
62
62
  const sig = await crypto.subtle.sign("HMAC", key, enc.encode(`${timestamp}.${rawBody}`));
63
63
  return bytesToHex(new Uint8Array(sig));
64
64
  }
65
- /** 產生與伺服器相同格式的 `X-Kanorio-Signature` 值(測試或本機模擬投遞用) */
65
+ /** Builds an `X-Kanorio-Signature` value in the server's format (for tests or simulating a delivery locally) */
66
66
  export async function buildWebhookSignatureHeader(signingSecrets, rawBody, timestamp) {
67
67
  const list = typeof signingSecrets === "string" ? [signingSecrets] : signingSecrets;
68
68
  const parts = [];
@@ -82,10 +82,10 @@ export async function verifyWebhookSignature(options) {
82
82
  if (Math.abs(nowSeconds - parsed.timestamp) > tolerance)
83
83
  return false;
84
84
  const expected = await computeWebhookSignature(options.signingSecret, parsed.timestamp, options.rawBody);
85
- // 輪替期內伺服器會附新舊兩個 v1;接收端只持有其中一把,任一相符即通過
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
86
  return parsed.signatures.some((sig) => constantTimeEqual(sig, expected));
87
87
  }
88
- /** 事件要清的標籤(原始字串,不含命名空間);事件本身已列出該清的全部標籤 */
88
+ /** The tags an event asks to clear (raw strings, no namespace); the event already lists every tag to clear */
89
89
  export function extractWebhookCacheTags(payload) {
90
90
  const tags = new Set();
91
91
  if (Array.isArray(payload.data?.cacheTags)) {
@@ -97,7 +97,7 @@ export function extractWebhookCacheTags(payload) {
97
97
  return [...tags];
98
98
  }
99
99
  /**
100
- * 建立標準 `POST` Route Handler(直接 export 於 Next.js `app/api/revalidate/route.ts` 或 Astro endpoint)。
100
+ * Creates a standard `POST` route handler (export it from Next.js `app/api/revalidate/route.ts` or an Astro endpoint).
101
101
  */
102
102
  export function createRevalidateHandler(options) {
103
103
  return async function POST(request) {