@oneaddress/partner-sdk 1.2.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,36 +1,68 @@
1
1
  import {
2
2
  CURRENT_VERSION,
3
3
  SUPPORTED_VERSIONS,
4
+ canonicalD5LoaForm,
4
5
  compareAddresses,
6
+ confirmUpdate,
5
7
  createOneAddressHandler,
8
+ createSqlIdempotencyStore,
9
+ d5LoaRef,
6
10
  decryptAddress,
11
+ decryptLoaEncrypted,
7
12
  decryptSession,
8
13
  fetchLoaPublicKey,
14
+ findMatchingStoredName,
15
+ formatAddressParts,
16
+ isEmailLike,
17
+ namePoolMatches,
18
+ readAddressParts,
19
+ sendVerifyResult,
20
+ toExpressHandler,
9
21
  transformAddress,
22
+ transformSession,
10
23
  validateAddress,
24
+ verifyD5LOA,
11
25
  verifyLOA,
12
26
  verifySignature,
13
27
  verifyWithGrace
14
- } from "./chunk-EHR6T6MA.mjs";
28
+ } from "./chunk-CE6M64CX.mjs";
15
29
  import {
16
30
  DEFAULT_REPLAY_WINDOW_SECS,
17
- isFreshTimestamp
18
- } from "./chunk-TGLIJMGK.mjs";
31
+ computeBlindIndex,
32
+ isFreshTimestamp,
33
+ normalizeForBlindIndex
34
+ } from "./chunk-TAZD6PFZ.mjs";
19
35
  export {
20
36
  CURRENT_VERSION,
21
37
  DEFAULT_REPLAY_WINDOW_SECS,
22
38
  SUPPORTED_VERSIONS,
39
+ canonicalD5LoaForm,
23
40
  compareAddresses,
41
+ computeBlindIndex,
42
+ confirmUpdate,
24
43
  createOneAddressHandler,
44
+ createSqlIdempotencyStore,
45
+ d5LoaRef,
25
46
  decryptAddress as decrypt,
26
47
  decryptAddress,
48
+ decryptLoaEncrypted,
27
49
  decryptSession,
28
50
  fetchLoaPublicKey,
51
+ findMatchingStoredName,
52
+ formatAddressParts,
53
+ isEmailLike,
29
54
  isFreshTimestamp,
55
+ namePoolMatches,
56
+ normalizeForBlindIndex,
57
+ readAddressParts,
58
+ sendVerifyResult,
59
+ toExpressHandler,
30
60
  transformAddress as transform,
31
61
  transformAddress,
62
+ transformSession,
32
63
  validateAddress,
33
64
  verifySignature as verify,
65
+ verifyD5LOA,
34
66
  verifyWithGrace as verifyGrace,
35
67
  verifyLOA,
36
68
  verifySignature,
@@ -0,0 +1,72 @@
1
+ import {
2
+ DEFAULT_REPLAY_WINDOW_SECS,
3
+ PARTNER_KEY_ATTESTATION_ALG,
4
+ PARTNER_KEY_ATTESTATION_V1,
5
+ REGISTRY_HEAD_ALG,
6
+ REGISTRY_HEAD_V1,
7
+ buildPartnerKeyAttestation,
8
+ buildRegistryHeadStatement,
9
+ cleanNameAliases,
10
+ computeBlindIndex,
11
+ computeCustomerBlindIndex,
12
+ decryptAddress,
13
+ decryptSession,
14
+ encryptAddressForAll,
15
+ encryptAddressForPartner,
16
+ encryptEnvelopeForPartner,
17
+ encryptPayloadForPartner,
18
+ encryptSessionForAll,
19
+ encryptSessionForPartner,
20
+ generateHybridPartnerKeyPair,
21
+ generatePartnerKeyPair,
22
+ headNamesKey,
23
+ isEmailLike,
24
+ isFreshTimestamp,
25
+ isIpLiteralHost,
26
+ isSafeWebhookUrl,
27
+ normaliseAddress,
28
+ normalizeForBlindIndex,
29
+ rootKeyIdFromSpki,
30
+ rootKeyIdFromSpkiB64,
31
+ signWebhookPayload,
32
+ verifyPartnerKeyAttestation,
33
+ verifyPartnerKeyAttestationWithRoots,
34
+ verifyRegistryHead,
35
+ verifyWebhookSignature
36
+ } from "./chunk-TAZD6PFZ.mjs";
37
+ export {
38
+ DEFAULT_REPLAY_WINDOW_SECS,
39
+ PARTNER_KEY_ATTESTATION_ALG,
40
+ PARTNER_KEY_ATTESTATION_V1,
41
+ REGISTRY_HEAD_ALG,
42
+ REGISTRY_HEAD_V1,
43
+ buildPartnerKeyAttestation,
44
+ buildRegistryHeadStatement,
45
+ cleanNameAliases,
46
+ computeBlindIndex,
47
+ computeCustomerBlindIndex,
48
+ decryptAddress,
49
+ decryptSession,
50
+ encryptAddressForAll,
51
+ encryptAddressForPartner,
52
+ encryptEnvelopeForPartner,
53
+ encryptPayloadForPartner,
54
+ encryptSessionForAll,
55
+ encryptSessionForPartner,
56
+ generateHybridPartnerKeyPair,
57
+ generatePartnerKeyPair,
58
+ headNamesKey,
59
+ isEmailLike,
60
+ isFreshTimestamp,
61
+ isIpLiteralHost,
62
+ isSafeWebhookUrl,
63
+ normaliseAddress,
64
+ normalizeForBlindIndex,
65
+ rootKeyIdFromSpki,
66
+ rootKeyIdFromSpkiB64,
67
+ signWebhookPayload,
68
+ verifyPartnerKeyAttestation,
69
+ verifyPartnerKeyAttestationWithRoots,
70
+ verifyRegistryHead,
71
+ verifyWebhookSignature
72
+ };
package/package.json CHANGED
@@ -1,38 +1,53 @@
1
- {
2
- "name": "@oneaddress/partner-sdk",
3
- "version": "1.2.0",
4
- "description": "Official OneAddress partner integration SDK — webhook verification, address decryption (legacy + D5 session-envelope), LOA validation",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "exports": {
8
- ".": {
9
- "import": "./dist/index.mjs",
10
- "require": "./dist/index.js",
11
- "types": "./dist/index.d.mts"
12
- },
13
- "./edge": {
14
- "import": "./dist/edge.mjs",
15
- "types": "./dist/edge.d.mts"
16
- }
17
- },
18
- "files": ["dist", "README.md"],
19
- "publishConfig": {
20
- "access": "public"
21
- },
22
- "scripts": {
23
- "build": "tsup src/index.ts src/edge.ts --format esm,cjs --dts --clean",
24
- "prepare": "tsup src/index.ts src/edge.ts --format esm,cjs --dts --clean",
25
- "dev": "tsup src/index.ts src/edge.ts --format esm,cjs --dts --watch",
26
- "test": "vitest run"
27
- },
28
- "keywords": ["oneaddress", "address", "partner", "webhook", "sdk"],
29
- "license": "UNLICENSED",
30
- "engines": { "node": ">=18" },
31
- "devDependencies": {
32
- "@oneaddress/crypto": "*",
33
- "@oneaddress/protocol": "^0.1.0",
34
- "tsup": "^8.0.0",
35
- "typescript": "^5.0.0",
36
- "vitest": "^1.0.0"
37
- }
38
- }
1
+ {
2
+ "name": "@oneaddress/partner-sdk",
3
+ "version": "1.6.0",
4
+ "description": "Official OneAddress partner integration SDK — webhook verification, address decryption (legacy + D5 session-envelope), LOA validation",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.mts",
10
+ "import": "./dist/index.mjs",
11
+ "require": "./dist/index.js"
12
+ },
13
+ "./edge": {
14
+ "types": "./dist/edge.d.mts",
15
+ "import": "./dist/edge.mjs"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "CHANGELOG.md"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "scripts": {
27
+ "build": "tsup src/index.ts src/edge.ts --format esm,cjs --dts --dts-resolve --tsconfig tsconfig.build.json --clean",
28
+ "type-check": "tsc --noEmit",
29
+ "prepare": "tsup src/index.ts src/edge.ts --format esm,cjs --dts --dts-resolve --tsconfig tsconfig.build.json --clean",
30
+ "dev": "tsup src/index.ts src/edge.ts --format esm,cjs --dts --dts-resolve --tsconfig tsconfig.build.json --watch",
31
+ "test": "vitest run",
32
+ "test:dist": "vitest run src/dist-exports.test.ts"
33
+ },
34
+ "keywords": [
35
+ "oneaddress",
36
+ "address",
37
+ "partner",
38
+ "webhook",
39
+ "sdk"
40
+ ],
41
+ "license": "UNLICENSED",
42
+ "engines": {
43
+ "node": ">=18"
44
+ },
45
+ "devDependencies": {
46
+ "@oneaddress/crypto": "*",
47
+ "@oneaddress/name-match": "*",
48
+ "@oneaddress/protocol": "^0.1.0",
49
+ "tsup": "^8.0.0",
50
+ "typescript": "^5.0.0",
51
+ "vitest": "^4.1.10"
52
+ }
53
+ }
@@ -1,436 +0,0 @@
1
- import {
2
- isFreshTimestamp
3
- } from "./chunk-TGLIJMGK.mjs";
4
-
5
- // src/index.ts
6
- import crypto from "crypto";
7
-
8
- // ../protocol/src/types.ts
9
- var CURRENT_VERSION = "2026.1";
10
- var SUPPORTED_VERSIONS = ["2026.1"];
11
-
12
- // src/index.ts
13
- function verifySignature(rawBody, signature, timestamp, secret) {
14
- if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
15
- const sigPayload = `${timestamp}.${rawBody}`;
16
- const expected = crypto.createHmac("sha256", secret).update(sigPayload).digest("hex");
17
- const sigBuffer = Buffer.from(signature, "hex");
18
- const expBuffer = Buffer.from(expected, "hex");
19
- if (sigBuffer.length !== expBuffer.length) return false;
20
- return crypto.timingSafeEqual(sigBuffer, expBuffer);
21
- }
22
- function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
23
- if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
24
- if (previousSecret && previousSecret !== currentSecret && graceUntil) {
25
- const until = typeof graceUntil === "number" ? graceUntil : Date.parse(graceUntil);
26
- if (!Number.isNaN(until) && Date.now() < until) {
27
- return verifySignature(rawBody, signature, timestamp, previousSecret);
28
- }
29
- }
30
- return false;
31
- }
32
- function base64urlToBuffer(b64) {
33
- return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
34
- }
35
- function pemToBuffer(pem) {
36
- return Buffer.from(pem.replace(/-----[^-]+-----/g, "").replace(/\s/g, ""), "base64");
37
- }
38
- async function decryptAddress(payload, privateKeyPem, partnerId) {
39
- const { ephemeralPublicKey, iv, ciphertext, hkdfSalt } = payload;
40
- const privateKey = await crypto.subtle.importKey(
41
- "pkcs8",
42
- pemToBuffer(privateKeyPem),
43
- { name: "ECDH", namedCurve: "P-256" },
44
- false,
45
- ["deriveBits"]
46
- );
47
- const ephemeralKey = await crypto.subtle.importKey(
48
- "raw",
49
- base64urlToBuffer(ephemeralPublicKey),
50
- { name: "ECDH", namedCurve: "P-256" },
51
- false,
52
- []
53
- );
54
- const sharedBits = await crypto.subtle.deriveBits(
55
- { name: "ECDH", public: ephemeralKey },
56
- privateKey,
57
- 256
58
- );
59
- const hkdfKey = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
60
- let salt;
61
- if (hkdfSalt) {
62
- const saltBytes = base64urlToBuffer(hkdfSalt);
63
- if (saltBytes.byteLength !== 32) {
64
- throw new Error(
65
- `[OneAddress SDK] hkdfSalt must be 32 bytes, received ${saltBytes.byteLength}. This may indicate a protocol version mismatch or a tampered payload.`
66
- );
67
- }
68
- salt = saltBytes;
69
- } else {
70
- salt = new Uint8Array(32);
71
- }
72
- const info = new TextEncoder().encode(`oneaddress:${partnerId}`);
73
- const aesKeyBits = await crypto.subtle.deriveBits(
74
- { name: "HKDF", hash: "SHA-256", salt, info },
75
- hkdfKey,
76
- 256
77
- );
78
- const aesKey = await crypto.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["decrypt"]);
79
- const plaintext = await crypto.subtle.decrypt(
80
- { name: "AES-GCM", iv: base64urlToBuffer(iv), tagLength: 128 },
81
- aesKey,
82
- base64urlToBuffer(ciphertext)
83
- );
84
- return JSON.parse(new TextDecoder().decode(plaintext));
85
- }
86
- async function decryptSession(share, envelopeB64, privateKeyPem, partnerId) {
87
- const { decryptSession: decryptSessionCrypto } = await import("./src-NUBMOPDK.mjs");
88
- const privateKeyB64 = privateKeyPem.replace(/-----[^-]+-----/g, "").replace(/\s/g, "");
89
- return decryptSessionCrypto(share, envelopeB64, privateKeyB64, partnerId);
90
- }
91
- async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
92
- const plaintext = await decryptAddress(payload, privateKeyPem, partnerId);
93
- const plaintextBytes = new TextEncoder().encode(JSON.stringify(plaintext));
94
- const recipientKey = await crypto.subtle.importKey(
95
- "spki",
96
- pemToBuffer(recipientSpkiPem),
97
- { name: "ECDH", namedCurve: "P-256" },
98
- false,
99
- []
100
- );
101
- const ephemeralPair = await crypto.subtle.generateKey(
102
- { name: "ECDH", namedCurve: "P-256" },
103
- true,
104
- ["deriveBits"]
105
- );
106
- const sharedBits = await crypto.subtle.deriveBits(
107
- { name: "ECDH", public: recipientKey },
108
- ephemeralPair.privateKey,
109
- 256
110
- );
111
- const hkdfSaltBytes = crypto.getRandomValues(new Uint8Array(32));
112
- const hkdfKey = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
113
- const info = new TextEncoder().encode(`oneaddress:transform:${partnerId}`);
114
- const aesKeyBits = await crypto.subtle.deriveBits(
115
- { name: "HKDF", hash: "SHA-256", salt: hkdfSaltBytes, info },
116
- hkdfKey,
117
- 256
118
- );
119
- const aesKey = await crypto.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["encrypt"]);
120
- const ivBytes = crypto.getRandomValues(new Uint8Array(12));
121
- const ciphertextBuf = await crypto.subtle.encrypt(
122
- { name: "AES-GCM", iv: ivBytes, tagLength: 128 },
123
- aesKey,
124
- plaintextBytes
125
- );
126
- const ephemeralPublicKeyRaw = await crypto.subtle.exportKey("raw", ephemeralPair.publicKey);
127
- return {
128
- ephemeralPublicKey: Buffer.from(ephemeralPublicKeyRaw).toString("base64"),
129
- iv: Buffer.from(ivBytes).toString("base64"),
130
- ciphertext: Buffer.from(ciphertextBuf).toString("base64"),
131
- hkdfSalt: Buffer.from(hkdfSaltBytes).toString("base64")
132
- };
133
- }
134
- var OA_APP_BASE_URL = "https://oneaddress.io";
135
- var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["oneaddress.io", "app.oneaddress.io", "localhost", "127.0.0.1"]);
136
- async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
137
- let parsedBase;
138
- try {
139
- parsedBase = new URL(appBaseUrl);
140
- } catch {
141
- throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
142
- }
143
- if (!ALLOWED_LOA_HOSTS.has(parsedBase.hostname)) {
144
- throw new Error(
145
- `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...ALLOWED_LOA_HOSTS].join(", ")}`
146
- );
147
- }
148
- const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
149
- const res = await fetch(url);
150
- if (!res.ok) {
151
- throw new Error(`[OneAddress SDK] Failed to fetch LOA public key: HTTP ${res.status}`);
152
- }
153
- return res.text();
154
- }
155
- async function verifyLOA(loa, publicKeyPem) {
156
- if (loa.algorithm !== "ECDSA-P256") {
157
- console.warn(
158
- // NOSONAR — intentional SDK diagnostic, not user-controlled data
159
- "[OneAddress SDK] LOA algorithm is HMAC-SHA256 (deprecated). Verification is not possible without the OneAddress HMAC key. Contact support@oneaddress.io if you are seeing this on recent webhooks."
160
- );
161
- return false;
162
- }
163
- try {
164
- const key = await crypto.subtle.importKey(
165
- "spki",
166
- pemToBuffer(publicKeyPem),
167
- { name: "ECDSA", namedCurve: "P-256" },
168
- false,
169
- ["verify"]
170
- );
171
- const sigBytes = Buffer.from(loa.signature, "hex");
172
- const textBytes = new TextEncoder().encode(loa.text);
173
- return await crypto.subtle.verify(
174
- { name: "ECDSA", hash: "SHA-256" },
175
- key,
176
- sigBytes,
177
- textBytes
178
- );
179
- } catch {
180
- return false;
181
- }
182
- }
183
- var ADDRESS_REQUIRED_FIELDS = [
184
- "street",
185
- "suburb",
186
- "state",
187
- "postcode",
188
- "country"
189
- ];
190
- function validateAddress(raw) {
191
- if (typeof raw !== "object" || raw === null) {
192
- throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
193
- }
194
- const obj = raw;
195
- for (const field of ADDRESS_REQUIRED_FIELDS) {
196
- if (typeof obj[field] !== "string" || obj[field] === "") {
197
- throw new Error(
198
- `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
199
- );
200
- }
201
- }
202
- return obj;
203
- }
204
- var STREET_SUFFIX_MAP = {
205
- st: "street",
206
- str: "street",
207
- rd: "road",
208
- ave: "avenue",
209
- av: "avenue",
210
- blvd: "boulevard",
211
- dr: "drive",
212
- ct: "court",
213
- cres: "crescent",
214
- cr: "crescent",
215
- pl: "place",
216
- ln: "lane",
217
- hwy: "highway",
218
- pde: "parade",
219
- pkwy: "parkway",
220
- ter: "terrace",
221
- cl: "close"
222
- };
223
- function expandSuffixes(line) {
224
- return line.split(/\s+/).map((tok) => {
225
- const lower = tok.toLowerCase().replace(/[.,]$/, "");
226
- return STREET_SUFFIX_MAP[lower] ?? tok.replace(/[.,]$/, "").toLowerCase();
227
- }).join(" ");
228
- }
229
- function normaliseLine(value) {
230
- if (!value) return "";
231
- const collapsed = value.toLowerCase().trim().replace(/\s+/g, " ");
232
- return expandSuffixes(collapsed);
233
- }
234
- function normaliseToken(value) {
235
- return (value ?? "").toLowerCase().trim().replace(/\s+/g, " ");
236
- }
237
- function normalisePostcode(value) {
238
- const trimmed = (value ?? "").trim();
239
- if (!trimmed) return "";
240
- if (/^\d{1,4}$/.test(trimmed)) return trimmed.padStart(4, "0");
241
- return trimmed.toLowerCase();
242
- }
243
- function compareAddresses(a, b) {
244
- const aStreet = normaliseLine(a.street ?? a.address_line1);
245
- const bStreet = normaliseLine(b.street ?? b.address_line1);
246
- if (!aStreet || !bStreet || aStreet !== bStreet) return false;
247
- const aSuburb = normaliseToken(a.suburb);
248
- const bSuburb = normaliseToken(b.suburb);
249
- if (!aSuburb || !bSuburb || aSuburb !== bSuburb) return false;
250
- const aState = normaliseToken(a.state);
251
- const bState = normaliseToken(b.state);
252
- if (!aState || !bState || aState !== bState) return false;
253
- const aPost = normalisePostcode(a.postcode);
254
- const bPost = normalisePostcode(b.postcode);
255
- if (!aPost || !bPost || aPost !== bPost) return false;
256
- const aCountry = normaliseToken(a.country);
257
- const bCountry = normaliseToken(b.country);
258
- if (aCountry && bCountry && aCountry !== bCountry) return false;
259
- return true;
260
- }
261
- function createOneAddressHandler(options) {
262
- const {
263
- webhookSecret,
264
- previousWebhookSecret,
265
- webhookSecretGraceUntil,
266
- privateKeyPem,
267
- onUpdate,
268
- onVerify,
269
- onAccountVerify,
270
- timestampToleranceSecs = 300,
271
- idempotencyStore
272
- } = options;
273
- return async function handler(req) {
274
- const rawBody = await req.text();
275
- const sig = req.headers.get("x-oneaddress-signature") ?? "";
276
- const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
277
- if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
278
- return new Response(JSON.stringify({ error: "Request timestamp out of tolerance" }), {
279
- status: 400,
280
- headers: { "Content-Type": "application/json" }
281
- });
282
- }
283
- if (!verifyWithGrace(rawBody, tsHeader, sig, webhookSecret, previousWebhookSecret, webhookSecretGraceUntil)) {
284
- return new Response(JSON.stringify({ error: "Invalid signature" }), {
285
- status: 401,
286
- headers: { "Content-Type": "application/json" }
287
- });
288
- }
289
- let body;
290
- try {
291
- body = JSON.parse(rawBody);
292
- } catch {
293
- return new Response(JSON.stringify({ error: "Invalid JSON" }), {
294
- status: 400,
295
- headers: { "Content-Type": "application/json" }
296
- });
297
- }
298
- const payloadVersion = body.oneaddress_version ?? body.version ?? "";
299
- if (payloadVersion && !SUPPORTED_VERSIONS.includes(payloadVersion)) {
300
- console.warn(
301
- // NOSONAR — intentional SDK diagnostic, not user-controlled data
302
- `[OneAddress SDK] Unrecognised protocol version "${payloadVersion}". Supported: ${SUPPORTED_VERSIONS.join(", ")}. Update @oneaddress/partner-sdk to the latest version.`
303
- );
304
- }
305
- const partnerId = body.partner_id ?? "";
306
- const tsNum = Number(tsHeader);
307
- const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
308
- if (dispatchId) {
309
- if (!idempotencyStore) {
310
- if (process.env.NODE_ENV === "test") {
311
- throw new Error(
312
- "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
313
- );
314
- }
315
- } else {
316
- const alreadySeen = await idempotencyStore.has(dispatchId);
317
- if (alreadySeen) {
318
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
319
- status: 200,
320
- headers: { "Content-Type": "application/json" }
321
- });
322
- }
323
- }
324
- }
325
- try {
326
- if (body.event === "address.updated") {
327
- if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
328
- return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
329
- status: 400,
330
- headers: { "Content-Type": "application/json" }
331
- });
332
- }
333
- const encrypted = body.address_encrypted;
334
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
335
- const event = {
336
- event: "address.updated",
337
- version: body.oneaddress_version ?? body.version ?? "1",
338
- id: body.id ?? "",
339
- timestamp: tsNum,
340
- partner_id: partnerId,
341
- dispatchId,
342
- customer: body.customer,
343
- address: validateAddress(rawAddress),
344
- loa: body.loa,
345
- id_verification: body.id_verification,
346
- raw: rawAddress
347
- };
348
- const result = await onUpdate(event);
349
- if (dispatchId && idempotencyStore) {
350
- await idempotencyStore.set(dispatchId).catch(
351
- (err) => console.error("[OneAddress SDK] idempotencyStore.set failed:", err)
352
- // NOSONAR
353
- );
354
- }
355
- return new Response(JSON.stringify({ ok: true, ...result }), {
356
- status: 200,
357
- headers: { "Content-Type": "application/json" }
358
- });
359
- }
360
- if (body.event === "address.verify" && onVerify) {
361
- if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
362
- return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
363
- status: 400,
364
- headers: { "Content-Type": "application/json" }
365
- });
366
- }
367
- const encrypted = body.address_encrypted;
368
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
369
- const event = {
370
- event: "address.verify",
371
- version: body.oneaddress_version ?? body.version ?? "1",
372
- id: body.id ?? "",
373
- timestamp: tsNum,
374
- partner_id: partnerId,
375
- dispatchId,
376
- batch_id: body.batch_id ?? 0,
377
- user_id: body.user_id ?? "",
378
- customer: body.customer ?? {},
379
- address: validateAddress(rawAddress),
380
- loa: body.loa,
381
- id_verification: body.id_verification,
382
- raw: rawAddress
383
- };
384
- const result = await onVerify(event);
385
- return new Response(JSON.stringify({ ok: true, ...result }), {
386
- status: 200,
387
- headers: { "Content-Type": "application/json" }
388
- });
389
- }
390
- if (body.event === "account.verify" && onAccountVerify) {
391
- const event = {
392
- event: "account.verify",
393
- version: body.oneaddress_version ?? body.version ?? "1",
394
- id: body.id ?? "",
395
- timestamp: tsNum,
396
- partner_id: partnerId,
397
- dispatchId,
398
- user_id: body.user_id ?? "",
399
- customer: body.customer ?? {},
400
- raw: body
401
- };
402
- const result = await onAccountVerify(event);
403
- return new Response(JSON.stringify({ ok: true, ...result }), {
404
- status: 200,
405
- headers: { "Content-Type": "application/json" }
406
- });
407
- }
408
- return new Response(JSON.stringify({ ok: true, skipped: true }), {
409
- status: 200,
410
- headers: { "Content-Type": "application/json" }
411
- });
412
- } catch (err) {
413
- const msg = err instanceof Error ? err.message : String(err);
414
- console.error("[OneAddress SDK] Handler error:", msg);
415
- return new Response(JSON.stringify({ error: "Internal handler error" }), {
416
- status: 500,
417
- headers: { "Content-Type": "application/json" }
418
- });
419
- }
420
- };
421
- }
422
-
423
- export {
424
- CURRENT_VERSION,
425
- SUPPORTED_VERSIONS,
426
- verifySignature,
427
- verifyWithGrace,
428
- decryptAddress,
429
- decryptSession,
430
- transformAddress,
431
- fetchLoaPublicKey,
432
- verifyLOA,
433
- validateAddress,
434
- compareAddresses,
435
- createOneAddressHandler
436
- };