@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,86 @@
1
+ /**
2
+ * 網站主機金鑰(server key)的共用契約:main、public-sites Worker 與 SDK 讀同一份。
3
+ *
4
+ * 主機金鑰是用途為「網站主機用」的服務帳號金鑰(`knr_sa_`)。站主自建前端的伺服器帶著它代訪客寫入
5
+ * (送表單、顧客登入、回報爬蟲),邊緣驗過後才採信它宣稱的訪客 IP。它打不開 Management API。
6
+ * 設計見 docs/platform/decisions/0002-operation-context.md「修訂一」。
7
+ */
8
+ /** 主機帶金鑰的標頭 */
9
+ export declare const SERVER_KEY_HEADER = "X-Kanorio-Server-Key";
10
+ /** 主機轉述的訪客 IP;只在金鑰驗過時採信 */
11
+ export declare const SERVER_KEY_VISITOR_IP_HEADER = "X-Kanorio-Visitor-IP";
12
+ /**
13
+ * Worker → main:這個請求帶著驗過的主機金鑰(值是金鑰 id)。main 只在它與 Worker 金鑰(X-API-Key)俱全時
14
+ * 才採信 `x-kanorio-client-ip` 裡主機轉述的訪客 IP(apps/main/lib/utils/ip-address.ts)。
15
+ */
16
+ export declare const SERVER_KEY_ID_FORWARD_HEADER = "x-kanorio-server-key-id";
17
+ /**
18
+ * 服務帳號授予與金鑰 scopes 裡的機器專用標記。不在「人的權限目錄」(`ALL_PERMISSIONS`)裡:
19
+ * 沒有任何團隊角色持有它、角色編輯器不會出現、PAT 與 OAuth 選不到。建立這種服務帳號只需要 `developer:manage`。
20
+ */
21
+ export declare const STOREFRONT_SERVER_SCOPE = "storefront:server";
22
+ export declare const SERVER_KEY_PREFIX = "knr_sa_";
23
+ export declare function isServerKeyFormat(raw: string): boolean;
24
+ /**
25
+ * 外部視角探針用的假金鑰(格式正確、永遠不存在):監控每輪拿它 POST 一個站,確認假金鑰會被拒。
26
+ * 邊緣認得它,照常驗證與拒絕,但不計入該站的「主機金鑰驗證失敗」異常訊號(那是我們自己的探針,不是有人在試)。
27
+ */
28
+ export declare const PROBE_FAKE_SERVER_KEY: string;
29
+ /** 服務帳號的用途:由授予是否帶 `STOREFRONT_SERVER_SCOPE` 決定,建立後不可改 */
30
+ export type ServiceAccountPurpose = "management" | "storefront_server";
31
+ export declare function purposeOfGrant(permissions: readonly string[]): ServiceAccountPurpose;
32
+ /** 環境變數的慣用名稱(後台的一次性顯示、CLI `--write-env`、文件都用這個) */
33
+ export declare const SERVER_KEY_ENV_NAME = "KANORIO_SERVER_KEY";
34
+ /** Worker → main 驗證端點的回應 */
35
+ export interface ServerKeyVerifyResponse {
36
+ valid: boolean;
37
+ tokenId?: string;
38
+ /** ISO 時間;null=不過期 */
39
+ expiresAt?: string | null;
40
+ /** 來源限制(空陣列=不限制);比對的是實際連線 IP 與 ASN */
41
+ allowedCidrs?: string[];
42
+ allowedAsns?: number[];
43
+ }
44
+ export interface ParsedIp {
45
+ version: 4 | 6;
46
+ bytes: number[];
47
+ }
48
+ /** 解析 IP;`::ffff:a.b.c.d` 視為 IPv4。不合法回 null */
49
+ export declare function parseIp(raw: string): ParsedIp | null;
50
+ export declare function isPublicIp(ip: ParsedIp): boolean;
51
+ /**
52
+ * 主機轉述的訪客 IP:必須是合法的公開位址,否則視為沒帶(回 null)。
53
+ * 設錯的反向代理會把 10.x 這類內網位址轉過來,照收的話全站訪客會共用一個限流桶。
54
+ */
55
+ export declare function normalizeVisitorIp(raw: string | null | undefined): string | null;
56
+ /** 限流桶的鍵:IPv4 用整個位址,IPv6 用 /64(同一個用戶端通常拿到整段 /64) */
57
+ export declare function rateLimitKeyForIp(ip: string): string;
58
+ export interface ParsedCidr {
59
+ version: 4 | 6;
60
+ bytes: number[];
61
+ bits: number;
62
+ /** 正規化後的寫法(網路位址+前綴長度) */
63
+ text: string;
64
+ }
65
+ /**
66
+ * 解析來源限制的一筆 IP 或 CIDR。單一 IP 視為 /32(IPv6 為 /128)。
67
+ * 拒收:格式錯、非公開網段、前綴過寬。
68
+ */
69
+ export declare function parseAllowedCidr(raw: string): ParsedCidr | null;
70
+ export declare function ipInCidr(ip: string, cidr: ParsedCidr): boolean;
71
+ export declare const MAX_ALLOWED_CIDRS = 20;
72
+ export declare const MAX_ALLOWED_ASNS = 10;
73
+ export interface SourcePolicy {
74
+ allowedCidrs: readonly string[];
75
+ allowedAsns: readonly number[];
76
+ }
77
+ export declare function hasSourcePolicy(policy: SourcePolicy): boolean;
78
+ /**
79
+ * 來源限制判定(比照 Stripe 存取政策):設了哪一類條件,那一類就必須符合;兩類都設就兩類都要符合。
80
+ * 比對的是 Cloudflare 給的實際連線 IP 與 ASN,不是主機轉述的訪客 IP。
81
+ * 有 ASN 條件但拿不到 ASN(本機開發、邊緣沒帶)時視為不符合。
82
+ */
83
+ export declare function isSourceAllowed(policy: SourcePolicy, source: {
84
+ ip: string | null;
85
+ asn: number | null;
86
+ }): boolean;
@@ -0,0 +1,252 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * 網站主機金鑰(server key)的共用契約:main、public-sites Worker 與 SDK 讀同一份。
4
+ *
5
+ * 主機金鑰是用途為「網站主機用」的服務帳號金鑰(`knr_sa_`)。站主自建前端的伺服器帶著它代訪客寫入
6
+ * (送表單、顧客登入、回報爬蟲),邊緣驗過後才採信它宣稱的訪客 IP。它打不開 Management API。
7
+ * 設計見 docs/platform/decisions/0002-operation-context.md「修訂一」。
8
+ */
9
+ /** 主機帶金鑰的標頭 */
10
+ export const SERVER_KEY_HEADER = "X-Kanorio-Server-Key";
11
+ /** 主機轉述的訪客 IP;只在金鑰驗過時採信 */
12
+ export const SERVER_KEY_VISITOR_IP_HEADER = "X-Kanorio-Visitor-IP";
13
+ /**
14
+ * Worker → main:這個請求帶著驗過的主機金鑰(值是金鑰 id)。main 只在它與 Worker 金鑰(X-API-Key)俱全時
15
+ * 才採信 `x-kanorio-client-ip` 裡主機轉述的訪客 IP(apps/main/lib/utils/ip-address.ts)。
16
+ */
17
+ export const SERVER_KEY_ID_FORWARD_HEADER = "x-kanorio-server-key-id";
18
+ /**
19
+ * 服務帳號授予與金鑰 scopes 裡的機器專用標記。不在「人的權限目錄」(`ALL_PERMISSIONS`)裡:
20
+ * 沒有任何團隊角色持有它、角色編輯器不會出現、PAT 與 OAuth 選不到。建立這種服務帳號只需要 `developer:manage`。
21
+ */
22
+ export const STOREFRONT_SERVER_SCOPE = "storefront:server";
23
+ export const SERVER_KEY_PREFIX = "knr_sa_";
24
+ /** `knr_sa_` + 43 字元 base64url(32 bytes)。格式不符就不必回源查 */
25
+ const SERVER_KEY_PATTERN = /^knr_sa_[A-Za-z0-9_-]{43}$/;
26
+ export function isServerKeyFormat(raw) {
27
+ return SERVER_KEY_PATTERN.test(raw);
28
+ }
29
+ /**
30
+ * 外部視角探針用的假金鑰(格式正確、永遠不存在):監控每輪拿它 POST 一個站,確認假金鑰會被拒。
31
+ * 邊緣認得它,照常驗證與拒絕,但不計入該站的「主機金鑰驗證失敗」異常訊號(那是我們自己的探針,不是有人在試)。
32
+ */
33
+ export const PROBE_FAKE_SERVER_KEY = `${SERVER_KEY_PREFIX}${"0".repeat(43)}`;
34
+ export function purposeOfGrant(permissions) {
35
+ return permissions.includes(STOREFRONT_SERVER_SCOPE) ? "storefront_server" : "management";
36
+ }
37
+ /** 環境變數的慣用名稱(後台的一次性顯示、CLI `--write-env`、文件都用這個) */
38
+ export const SERVER_KEY_ENV_NAME = "KANORIO_SERVER_KEY";
39
+ // ─── IP 工具(Worker 與 main 共用;不依賴 node:net,Workers 也能跑) ───
40
+ function parseIpv4(value) {
41
+ const parts = value.split(".");
42
+ if (parts.length !== 4)
43
+ return null;
44
+ const out = [];
45
+ for (const part of parts) {
46
+ if (!/^\d{1,3}$/.test(part))
47
+ return null;
48
+ const n = Number(part);
49
+ if (n > 255)
50
+ return null;
51
+ out.push(n);
52
+ }
53
+ return out;
54
+ }
55
+ /** IPv6 → 16 bytes;支援 `::` 壓縮與結尾的 IPv4(`::ffff:1.2.3.4`)。不收 zone id */
56
+ function parseIpv6(value) {
57
+ if (!value.includes(":") || value.includes("%"))
58
+ return null;
59
+ let head = value;
60
+ let tailV4 = null;
61
+ const lastColon = value.lastIndexOf(":");
62
+ const maybeV4 = value.slice(lastColon + 1);
63
+ if (maybeV4.includes(".")) {
64
+ tailV4 = parseIpv4(maybeV4);
65
+ if (!tailV4)
66
+ return null;
67
+ head = `${value.slice(0, lastColon)}:0:0`;
68
+ }
69
+ const doubleColon = head.indexOf("::");
70
+ if (doubleColon !== head.lastIndexOf("::"))
71
+ return null;
72
+ let groups;
73
+ if (doubleColon >= 0) {
74
+ const left = head.slice(0, doubleColon).split(":").filter(Boolean);
75
+ const right = head.slice(doubleColon + 2).split(":").filter(Boolean);
76
+ const missing = 8 - left.length - right.length;
77
+ if (missing < 1)
78
+ return null;
79
+ groups = [...left, ...Array(missing).fill("0"), ...right];
80
+ }
81
+ else {
82
+ groups = head.split(":");
83
+ }
84
+ if (groups.length !== 8)
85
+ return null;
86
+ const bytes = [];
87
+ for (const group of groups) {
88
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group))
89
+ return null;
90
+ const n = parseInt(group, 16);
91
+ bytes.push(n >> 8, n & 0xff);
92
+ }
93
+ if (tailV4)
94
+ bytes.splice(12, 4, ...tailV4);
95
+ return bytes;
96
+ }
97
+ /** 解析 IP;`::ffff:a.b.c.d` 視為 IPv4。不合法回 null */
98
+ export function parseIp(raw) {
99
+ const value = raw.trim();
100
+ if (!value || value.length > 45)
101
+ return null;
102
+ const v4 = parseIpv4(value);
103
+ if (v4)
104
+ return { version: 4, bytes: v4 };
105
+ const v6 = parseIpv6(value);
106
+ if (!v6)
107
+ return null;
108
+ const mapped = v6.slice(0, 10).every((b) => b === 0) && v6[10] === 0xff && v6[11] === 0xff;
109
+ if (mapped)
110
+ return { version: 4, bytes: v6.slice(12) };
111
+ return { version: 6, bytes: v6 };
112
+ }
113
+ function inPrefix(bytes, prefix, bits) {
114
+ const full = Math.floor(bits / 8);
115
+ for (let i = 0; i < full; i++)
116
+ if (bytes[i] !== prefix[i])
117
+ return false;
118
+ const rest = bits % 8;
119
+ if (rest === 0)
120
+ return true;
121
+ const mask = (0xff << (8 - rest)) & 0xff;
122
+ return ((bytes[full] ?? 0) & mask) === ((prefix[full] ?? 0) & mask);
123
+ }
124
+ /** 不可路由到公網的位址:私有、loopback、link-local、CGNAT、文件用、多播與保留網段 */
125
+ const NON_PUBLIC_V4 = [
126
+ [[0, 0, 0, 0], 8],
127
+ [[10, 0, 0, 0], 8],
128
+ [[100, 64, 0, 0], 10],
129
+ [[127, 0, 0, 0], 8],
130
+ [[169, 254, 0, 0], 16],
131
+ [[172, 16, 0, 0], 12],
132
+ [[192, 0, 0, 0], 24],
133
+ [[192, 0, 2, 0], 24],
134
+ [[192, 168, 0, 0], 16],
135
+ [[198, 18, 0, 0], 15],
136
+ [[198, 51, 100, 0], 24],
137
+ [[203, 0, 113, 0], 24],
138
+ [[224, 0, 0, 0], 3],
139
+ ];
140
+ const NON_PUBLIC_V6 = [
141
+ // ::/127(未指定與 loopback)
142
+ [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 127],
143
+ // fc00::/7 unique local
144
+ [[0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 7],
145
+ // fe80::/10 link-local
146
+ [[0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 10],
147
+ // ff00::/8 多播
148
+ [[0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 8],
149
+ // 2001:db8::/32 文件用
150
+ [[0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 32],
151
+ ];
152
+ export function isPublicIp(ip) {
153
+ const table = ip.version === 4 ? NON_PUBLIC_V4 : NON_PUBLIC_V6;
154
+ return !table.some(([prefix, bits]) => inPrefix(ip.bytes, prefix, bits));
155
+ }
156
+ function formatIp(ip) {
157
+ if (ip.version === 4)
158
+ return ip.bytes.join(".");
159
+ const groups = [];
160
+ for (let i = 0; i < 16; i += 2)
161
+ groups.push((((ip.bytes[i] ?? 0) << 8) | (ip.bytes[i + 1] ?? 0)).toString(16));
162
+ return groups.join(":");
163
+ }
164
+ /**
165
+ * 主機轉述的訪客 IP:必須是合法的公開位址,否則視為沒帶(回 null)。
166
+ * 設錯的反向代理會把 10.x 這類內網位址轉過來,照收的話全站訪客會共用一個限流桶。
167
+ */
168
+ export function normalizeVisitorIp(raw) {
169
+ if (!raw)
170
+ return null;
171
+ const parsed = parseIp(raw);
172
+ if (!parsed || !isPublicIp(parsed))
173
+ return null;
174
+ return formatIp(parsed);
175
+ }
176
+ /** 限流桶的鍵:IPv4 用整個位址,IPv6 用 /64(同一個用戶端通常拿到整段 /64) */
177
+ export function rateLimitKeyForIp(ip) {
178
+ const parsed = parseIp(ip);
179
+ if (!parsed)
180
+ return ip;
181
+ if (parsed.version === 4)
182
+ return formatIp(parsed);
183
+ return `${formatIp({ version: 6, bytes: [...parsed.bytes.slice(0, 8), 0, 0, 0, 0, 0, 0, 0, 0] })}/64`;
184
+ }
185
+ /** 最寬只收到 IPv4 /8、IPv6 /16:再寬就等於沒限制 */
186
+ const MIN_PREFIX_BITS = { 4: 8, 6: 16 };
187
+ /**
188
+ * 解析來源限制的一筆 IP 或 CIDR。單一 IP 視為 /32(IPv6 為 /128)。
189
+ * 拒收:格式錯、非公開網段、前綴過寬。
190
+ */
191
+ export function parseAllowedCidr(raw) {
192
+ const value = raw.trim();
193
+ const slash = value.indexOf("/");
194
+ const ip = parseIp(slash >= 0 ? value.slice(0, slash) : value);
195
+ if (!ip)
196
+ return null;
197
+ const maxBits = ip.version === 4 ? 32 : 128;
198
+ let bits = maxBits;
199
+ if (slash >= 0) {
200
+ const text = value.slice(slash + 1);
201
+ if (!/^\d{1,3}$/.test(text))
202
+ return null;
203
+ bits = Number(text);
204
+ if (bits > maxBits || bits < MIN_PREFIX_BITS[ip.version])
205
+ return null;
206
+ }
207
+ if (!isPublicIp(ip))
208
+ return null;
209
+ const network = ip.bytes.map((byte, index) => {
210
+ const start = index * 8;
211
+ if (start + 8 <= bits)
212
+ return byte;
213
+ if (start >= bits)
214
+ return 0;
215
+ return byte & ((0xff << (8 - (bits - start))) & 0xff);
216
+ });
217
+ return { version: ip.version, bytes: network, bits, text: `${formatIp({ version: ip.version, bytes: network })}/${bits}` };
218
+ }
219
+ export function ipInCidr(ip, cidr) {
220
+ const parsed = parseIp(ip);
221
+ if (!parsed || parsed.version !== cidr.version)
222
+ return false;
223
+ return inPrefix(parsed.bytes, cidr.bytes, cidr.bits);
224
+ }
225
+ export const MAX_ALLOWED_CIDRS = 20;
226
+ export const MAX_ALLOWED_ASNS = 10;
227
+ export function hasSourcePolicy(policy) {
228
+ return policy.allowedCidrs.length > 0 || policy.allowedAsns.length > 0;
229
+ }
230
+ /**
231
+ * 來源限制判定(比照 Stripe 存取政策):設了哪一類條件,那一類就必須符合;兩類都設就兩類都要符合。
232
+ * 比對的是 Cloudflare 給的實際連線 IP 與 ASN,不是主機轉述的訪客 IP。
233
+ * 有 ASN 條件但拿不到 ASN(本機開發、邊緣沒帶)時視為不符合。
234
+ */
235
+ export function isSourceAllowed(policy, source) {
236
+ if (policy.allowedCidrs.length > 0) {
237
+ const ip = source.ip;
238
+ if (!ip)
239
+ return false;
240
+ const matched = policy.allowedCidrs.some((raw) => {
241
+ const cidr = parseAllowedCidr(raw);
242
+ return cidr ? ipInCidr(ip, cidr) : false;
243
+ });
244
+ if (!matched)
245
+ return false;
246
+ }
247
+ if (policy.allowedAsns.length > 0) {
248
+ if (source.asn === null || !policy.allowedAsns.includes(source.asn))
249
+ return false;
250
+ }
251
+ return true;
252
+ }
@@ -0,0 +1,14 @@
1
+ import type { RegistryAttributionWire } from "./types.js";
2
+ /** 登記資料的來源(是哪個登記,不是從哪條路徑取得) */
3
+ export type RegistrySource = "fia_tax_registration" | "gcis_company";
4
+ /**
5
+ * 政府開放資料的來源標示。授權條件(政府資料開放授權條款-第 1 版)要求使用時標示提供機關,
6
+ * 所以回應、自動帶入的畫面與文件都要帶這一份。
7
+ */
8
+ export declare const REGISTRY_ATTRIBUTION: Record<RegistrySource, RegistryAttributionWire>;
9
+ export declare function registryAttribution(source: RegistrySource, dataDate?: string): RegistryAttributionWire;
10
+ /**
11
+ * 顯示來源標示時用哪個機關名稱:中文介面用原文,其餘語系用英文名稱。
12
+ * 結帳、顧客中心、表單與後台都用這一份,不各自判斷語系。
13
+ */
14
+ export declare function registryProviderName(attribution: Pick<RegistryAttributionWire, "provider" | "providerEn">, locale: string | null | undefined): string;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * 政府開放資料的來源標示。授權條件(政府資料開放授權條款-第 1 版)要求使用時標示提供機關,
3
+ * 所以回應、自動帶入的畫面與文件都要帶這一份。
4
+ */
5
+ export const REGISTRY_ATTRIBUTION = {
6
+ fia_tax_registration: {
7
+ provider: "財政部財政資訊中心",
8
+ providerEn: "Fiscal Information Agency, Ministry of Finance (Taiwan)",
9
+ license: "OGDL-TW-1.0",
10
+ licenseUrl: "https://data.gov.tw/license",
11
+ },
12
+ gcis_company: {
13
+ provider: "經濟部商業發展署",
14
+ providerEn: "Administration of Commerce, Ministry of Economic Affairs (Taiwan)",
15
+ license: "OGDL-TW-1.0",
16
+ licenseUrl: "https://data.gov.tw/license",
17
+ },
18
+ };
19
+ export function registryAttribution(source, dataDate) {
20
+ return dataDate ? { ...REGISTRY_ATTRIBUTION[source], dataDate } : REGISTRY_ATTRIBUTION[source];
21
+ }
22
+ /**
23
+ * 顯示來源標示時用哪個機關名稱:中文介面用原文,其餘語系用英文名稱。
24
+ * 結帳、顧客中心、表單與後台都用這一份,不各自判斷語系。
25
+ */
26
+ export function registryProviderName(attribution, locale) {
27
+ return locale?.toLowerCase().startsWith("zh") ? attribution.provider : attribution.providerEn;
28
+ }
@@ -0,0 +1,3 @@
1
+ import type { TaxIdFormatDefinition } from "./types.js";
2
+ /** 宣告一個稅號格式。只做型別收斂;登錄在 registry.ts */
3
+ export declare function defineTaxIdFormat(definition: TaxIdFormatDefinition): TaxIdFormatDefinition;
@@ -0,0 +1,4 @@
1
+ /** 宣告一個稅號格式。只做型別收斂;登錄在 registry.ts */
2
+ export function defineTaxIdFormat(definition) {
3
+ return definition;
4
+ }
@@ -0,0 +1,2 @@
1
+ export declare const EU_VAT_COUNTRIES: readonly string[];
2
+ export declare const euVat: import("../types.js").TaxIdFormatDefinition;
@@ -0,0 +1,54 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ import { defineTaxIdFormat } from "../define.js";
3
+ import { stripSeparators } from "../normalize.js";
4
+ /**
5
+ * 歐盟 VAT 識別號:會員國前綴+各國格式。希臘的前綴是 EL(國碼是 GR)。
6
+ * 各國格式依歐盟 VIES 的公開說明整理,尚未逐國對照官方文件核實,所以只警示、不擋;
7
+ * 各國的檢查碼也還沒做。使用者只打號碼沒打前綴時補上前綴。
8
+ */
9
+ const EU_VAT = {
10
+ AT: { prefix: "AT", pattern: /^ATU\d{8}$/, example: "ATU12345678" },
11
+ BE: { prefix: "BE", pattern: /^BE[01]\d{9}$/, example: "BE0123456789" },
12
+ BG: { prefix: "BG", pattern: /^BG\d{9,10}$/, example: "BG123456789" },
13
+ CY: { prefix: "CY", pattern: /^CY\d{8}[A-Z]$/, example: "CY12345678Z" },
14
+ CZ: { prefix: "CZ", pattern: /^CZ\d{8,10}$/, example: "CZ12345678" },
15
+ DE: { prefix: "DE", pattern: /^DE\d{9}$/, example: "DE123456789" },
16
+ DK: { prefix: "DK", pattern: /^DK\d{8}$/, example: "DK12345678" },
17
+ EE: { prefix: "EE", pattern: /^EE\d{9}$/, example: "EE123456789" },
18
+ GR: { prefix: "EL", pattern: /^EL\d{9}$/, example: "EL123456789" },
19
+ ES: { prefix: "ES", pattern: /^ES[A-Z0-9]\d{7}[A-Z0-9]$/, example: "ESA1234567Z" },
20
+ FI: { prefix: "FI", pattern: /^FI\d{8}$/, example: "FI12345678" },
21
+ FR: { prefix: "FR", pattern: /^FR[A-HJ-NP-Z0-9]{2}\d{9}$/, example: "FRAB123456789" },
22
+ HR: { prefix: "HR", pattern: /^HR\d{11}$/, example: "HR12345678912" },
23
+ HU: { prefix: "HU", pattern: /^HU\d{8}$/, example: "HU12345678" },
24
+ IE: { prefix: "IE", pattern: /^IE(\d{7}[A-Z]{1,2}|\d[A-Z+*]\d{5}[A-Z])$/, example: "IE1234567AB" },
25
+ IT: { prefix: "IT", pattern: /^IT\d{11}$/, example: "IT12345678912" },
26
+ LT: { prefix: "LT", pattern: /^LT(\d{9}|\d{12})$/, example: "LT123456789" },
27
+ LU: { prefix: "LU", pattern: /^LU\d{8}$/, example: "LU12345678" },
28
+ LV: { prefix: "LV", pattern: /^LV\d{11}$/, example: "LV12345678912" },
29
+ MT: { prefix: "MT", pattern: /^MT\d{8}$/, example: "MT12345678" },
30
+ NL: { prefix: "NL", pattern: /^NL\d{9}B\d{2}$/, example: "NL123456789B01" },
31
+ PL: { prefix: "PL", pattern: /^PL\d{10}$/, example: "PL1234567890" },
32
+ PT: { prefix: "PT", pattern: /^PT\d{9}$/, example: "PT123456789" },
33
+ RO: { prefix: "RO", pattern: /^RO\d{2,10}$/, example: "RO1234567891" },
34
+ SE: { prefix: "SE", pattern: /^SE\d{12}$/, example: "SE123456789123" },
35
+ SI: { prefix: "SI", pattern: /^SI\d{8}$/, example: "SI12345678" },
36
+ SK: { prefix: "SK", pattern: /^SK\d{10}$/, example: "SK1234567891" },
37
+ };
38
+ export const EU_VAT_COUNTRIES = Object.keys(EU_VAT);
39
+ export const euVat = defineTaxIdFormat({
40
+ type: "eu_vat",
41
+ countries: EU_VAT_COUNTRIES,
42
+ stripeType: "eu_vat",
43
+ normalize: (cleaned, country) => {
44
+ const value = stripSeparators(cleaned);
45
+ const rule = EU_VAT[country];
46
+ return rule && value && !value.startsWith(rule.prefix) ? `${rule.prefix}${value}` : value;
47
+ },
48
+ validate: (normalized, country) => (EU_VAT[country]?.pattern.test(normalized) ? null : "FORMAT"),
49
+ enforcement: "warn",
50
+ hasChecksum: false,
51
+ example: (country) => EU_VAT[country]?.example ?? "",
52
+ maxLength: 20,
53
+ inputMode: "text",
54
+ });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * 香港商業登記號碼:8 碼數字(2023-12 起同時是「唯一業務識別碼」的號碼部分)。
3
+ * 商業登記證上的完整號碼是「8 碼-分行 3 碼-…」,貼上整串時只取前 8 碼。官方沒有公開檢查碼。
4
+ */
5
+ export declare const hkBr: import("../types.js").TaxIdFormatDefinition;
@@ -0,0 +1,23 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ import { defineTaxIdFormat } from "../define.js";
3
+ import { stripSeparators } from "../normalize.js";
4
+ /**
5
+ * 香港商業登記號碼:8 碼數字(2023-12 起同時是「唯一業務識別碼」的號碼部分)。
6
+ * 商業登記證上的完整號碼是「8 碼-分行 3 碼-…」,貼上整串時只取前 8 碼。官方沒有公開檢查碼。
7
+ */
8
+ export const hkBr = defineTaxIdFormat({
9
+ type: "hk_br",
10
+ countries: ["HK"],
11
+ stripeType: "hk_br",
12
+ normalize: (cleaned) => {
13
+ const digits = stripSeparators(cleaned);
14
+ // 完整的登記證號碼:8 碼+分行 3 碼+年月等,共 16 碼
15
+ return /^\d{16}$/.test(digits) && /\D/.test(cleaned) ? digits.slice(0, 8) : digits;
16
+ },
17
+ validate: (normalized) => (/^\d{8}$/.test(normalized) ? null : "FORMAT"),
18
+ enforcement: "block",
19
+ hasChecksum: false,
20
+ example: () => "12345678",
21
+ maxLength: 24,
22
+ inputMode: "numeric",
23
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 日本適格請求書發行事業者登錄番號:「T」+13 碼數字(國稅廳)。
3
+ * 法人是 T+法人番號(有檢查碼);個人事業者是另外配發的 13 碼,官方沒有說明它是否滿足法人番號的檢查碼,
4
+ * 所以這裡只驗格式,不驗檢查碼。只打 13 碼數字時補上 T。
5
+ */
6
+ export declare const jpTrn: import("../types.js").TaxIdFormatDefinition;
@@ -0,0 +1,23 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ import { defineTaxIdFormat } from "../define.js";
3
+ import { stripSeparators } from "../normalize.js";
4
+ /**
5
+ * 日本適格請求書發行事業者登錄番號:「T」+13 碼數字(國稅廳)。
6
+ * 法人是 T+法人番號(有檢查碼);個人事業者是另外配發的 13 碼,官方沒有說明它是否滿足法人番號的檢查碼,
7
+ * 所以這裡只驗格式,不驗檢查碼。只打 13 碼數字時補上 T。
8
+ */
9
+ export const jpTrn = defineTaxIdFormat({
10
+ type: "jp_trn",
11
+ countries: ["JP"],
12
+ stripeType: "jp_trn",
13
+ normalize: (cleaned) => {
14
+ const value = stripSeparators(cleaned);
15
+ return /^\d{13}$/.test(value) ? `T${value}` : value;
16
+ },
17
+ validate: (normalized) => (/^T\d{13}$/.test(normalized) ? null : "FORMAT"),
18
+ enforcement: "block",
19
+ hasChecksum: false,
20
+ example: () => "T1234567890123",
21
+ maxLength: 20,
22
+ inputMode: "text",
23
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 韓國事業者登錄番號:10 碼數字(常寫成 XXX-XX-XXXXX)+檢查碼。
3
+ * 前 9 碼乘上權重 [1,3,7,1,3,7,1,3,5] 加總,再加上「第 9 碼 × 5」的十位數;(10 − 總和 % 10) % 10 要等於第 10 碼。
4
+ */
5
+ export declare function isValidKrBrn(normalized: string): boolean;
6
+ export declare const krBrn: import("../types.js").TaxIdFormatDefinition;
@@ -0,0 +1,30 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ import { defineTaxIdFormat } from "../define.js";
3
+ import { stripSeparators } from "../normalize.js";
4
+ const WEIGHTS = [1, 3, 7, 1, 3, 7, 1, 3, 5];
5
+ /**
6
+ * 韓國事業者登錄番號:10 碼數字(常寫成 XXX-XX-XXXXX)+檢查碼。
7
+ * 前 9 碼乘上權重 [1,3,7,1,3,7,1,3,5] 加總,再加上「第 9 碼 × 5」的十位數;(10 − 總和 % 10) % 10 要等於第 10 碼。
8
+ */
9
+ export function isValidKrBrn(normalized) {
10
+ if (!/^\d{10}$/.test(normalized))
11
+ return false;
12
+ const digits = normalized.split("").map(Number);
13
+ let sum = 0;
14
+ for (let i = 0; i < 9; i++)
15
+ sum += digits[i] * WEIGHTS[i];
16
+ sum += Math.floor((digits[8] * 5) / 10);
17
+ return (10 - (sum % 10)) % 10 === digits[9];
18
+ }
19
+ export const krBrn = defineTaxIdFormat({
20
+ type: "kr_brn",
21
+ countries: ["KR"],
22
+ stripeType: "kr_brn",
23
+ normalize: (cleaned) => stripSeparators(cleaned),
24
+ validate: (normalized) => (!/^\d{10}$/.test(normalized) ? "FORMAT" : isValidKrBrn(normalized) ? null : "CHECKSUM"),
25
+ enforcement: "block",
26
+ hasChecksum: true,
27
+ example: () => "220-81-62517",
28
+ maxLength: 14,
29
+ inputMode: "numeric",
30
+ });
@@ -0,0 +1,7 @@
1
+ /**
2
+ * 馬來西亞稅號。兩種都依公開範例整理、尚未對照 LHDN 與關稅局的官方文件核實,只警示不擋。
3
+ * - my_itn:所得稅號(TIN),類別字母 1–2 碼+數字(如 C 1234567890);電子發票(MyInvois)用的就是它
4
+ * - my_sst:銷售與服務稅登記號(如 A12-3456-78912345)
5
+ */
6
+ export declare const myItn: import("../types.js").TaxIdFormatDefinition;
7
+ export declare const mySst: import("../types.js").TaxIdFormatDefinition;
@@ -0,0 +1,32 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ import { defineTaxIdFormat } from "../define.js";
3
+ import { stripSeparators } from "../normalize.js";
4
+ /**
5
+ * 馬來西亞稅號。兩種都依公開範例整理、尚未對照 LHDN 與關稅局的官方文件核實,只警示不擋。
6
+ * - my_itn:所得稅號(TIN),類別字母 1–2 碼+數字(如 C 1234567890);電子發票(MyInvois)用的就是它
7
+ * - my_sst:銷售與服務稅登記號(如 A12-3456-78912345)
8
+ */
9
+ export const myItn = defineTaxIdFormat({
10
+ type: "my_itn",
11
+ countries: ["MY"],
12
+ stripeType: "my_itn",
13
+ normalize: (cleaned) => stripSeparators(cleaned),
14
+ validate: (normalized) => (/^[A-Z]{1,2}\d{8,11}$/.test(normalized) ? null : "FORMAT"),
15
+ enforcement: "warn",
16
+ hasChecksum: false,
17
+ example: () => "C1234567890",
18
+ maxLength: 16,
19
+ inputMode: "text",
20
+ });
21
+ export const mySst = defineTaxIdFormat({
22
+ type: "my_sst",
23
+ countries: ["MY"],
24
+ stripeType: "my_sst",
25
+ normalize: (cleaned) => stripSeparators(cleaned),
26
+ validate: (normalized) => (/^[A-Z]\d{14}$/.test(normalized) ? null : "FORMAT"),
27
+ enforcement: "warn",
28
+ hasChecksum: false,
29
+ example: () => "A12-3456-78912345",
30
+ maxLength: 20,
31
+ inputMode: "text",
32
+ });
@@ -0,0 +1 @@
1
+ export declare const sgUen: import("../types.js").TaxIdFormatDefinition;
@@ -0,0 +1,21 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ import { defineTaxIdFormat } from "../define.js";
3
+ import { stripSeparators } from "../normalize.js";
4
+ /**
5
+ * 新加坡 UEN:三種格式——商號(8 碼數字+字母)、本地公司(西元年 4 碼+5 碼數字+字母)、
6
+ * 其他實體(T/S/R+年 2 碼+類別 2 字母+4 碼數字+字母)。
7
+ * 結尾的檢查字母演算法官方沒有公開,這裡只驗格式;格式依 ACRA 的公開說明整理、尚未逐條核實,只警示不擋。
8
+ */
9
+ const SG_UEN = [/^\d{8}[A-Z]$/, /^(18|19|20)\d{2}\d{5}[A-Z]$/, /^[TSR]\d{2}[A-Z]{2}\d{4}[A-Z]$/];
10
+ export const sgUen = defineTaxIdFormat({
11
+ type: "sg_uen",
12
+ countries: ["SG"],
13
+ stripeType: "sg_uen",
14
+ normalize: (cleaned) => stripSeparators(cleaned),
15
+ validate: (normalized) => (SG_UEN.some((re) => re.test(normalized)) ? null : "FORMAT"),
16
+ enforcement: "warn",
17
+ hasChecksum: false,
18
+ example: () => "201912345K",
19
+ maxLength: 12,
20
+ inputMode: "text",
21
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * 台灣統一編號:8 碼數字+檢查碼(財政部 112 年 4 月新制)。
3
+ *
4
+ * 各位數乘上權重 [1,2,1,2,1,2,4,1],乘積為兩位數時取十位+個位,加總後能被 5 整除即有效
5
+ * (舊制是被 10 整除;財政部為擴增號碼空間放寬,新制配發的 04595252、10458570、62176616 在舊制會被誤判)。
6
+ * 例外:第 7 碼是 7 時(乘積 28 可視為 10 或 1),總和加 1 能被 5 整除也有效。
7
+ * 來源:財政部財政資訊中心「營利事業統一編號檢查碼邏輯修正說明」。
8
+ */
9
+ export declare function isValidTwVat(normalized: string): boolean;
10
+ export declare const twVat: import("../types.js").TaxIdFormatDefinition;