@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/CHANGELOG.md +238 -0
- package/README.md +714 -350
- package/dist/chunk-CE6M64CX.mjs +916 -0
- package/dist/chunk-TAZD6PFZ.mjs +4019 -0
- package/dist/edge.d.mts +1 -3
- package/dist/edge.d.ts +1 -3
- package/dist/edge.js +4628 -71
- package/dist/edge.mjs +29 -3
- package/dist/index.d.mts +757 -38
- package/dist/index.d.ts +757 -38
- package/dist/index.js +4339 -161
- package/dist/index.mjs +35 -3
- package/dist/src-ESYTJ2EY.mjs +72 -0
- package/package.json +53 -38
- package/dist/chunk-EHR6T6MA.mjs +0 -436
- package/dist/chunk-TGLIJMGK.mjs +0 -498
- package/dist/src-NUBMOPDK.mjs +0 -30
|
@@ -0,0 +1,916 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isFreshTimestamp,
|
|
3
|
+
isSafeWebhookUrl
|
|
4
|
+
} from "./chunk-TAZD6PFZ.mjs";
|
|
5
|
+
|
|
6
|
+
// src/index.ts
|
|
7
|
+
import crypto from "crypto";
|
|
8
|
+
|
|
9
|
+
// ../protocol/src/types.ts
|
|
10
|
+
var CURRENT_VERSION = "2026.1";
|
|
11
|
+
var SUPPORTED_VERSIONS = ["2026.1"];
|
|
12
|
+
|
|
13
|
+
// ../name-match/src/index.ts
|
|
14
|
+
function isEmailLike(value) {
|
|
15
|
+
return value.includes("@");
|
|
16
|
+
}
|
|
17
|
+
function stripDiacritics(s) {
|
|
18
|
+
return s.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
|
19
|
+
}
|
|
20
|
+
function norm(s) {
|
|
21
|
+
return stripDiacritics(s).toLowerCase().replaceAll(".", "").trim().replaceAll(/\s+/g, " ");
|
|
22
|
+
}
|
|
23
|
+
function tokenize(name) {
|
|
24
|
+
return norm(name).split(" ").filter(Boolean);
|
|
25
|
+
}
|
|
26
|
+
function surnameVariants(token) {
|
|
27
|
+
if (!token.includes("-")) return [token];
|
|
28
|
+
return [token, ...token.split("-").filter(Boolean)];
|
|
29
|
+
}
|
|
30
|
+
function namePoolMatches(providedNames, storedName) {
|
|
31
|
+
if (isEmailLike(storedName)) return false;
|
|
32
|
+
const provided = providedNames.filter((n) => Boolean(n) && !isEmailLike(n));
|
|
33
|
+
const primary = tokenize(provided[0] ?? "");
|
|
34
|
+
if (primary.length === 0) return false;
|
|
35
|
+
const surnames = new Set(surnameVariants(primary[primary.length - 1]));
|
|
36
|
+
for (let i = 1; i < provided.length; i++) {
|
|
37
|
+
const t = tokenize(provided[i]);
|
|
38
|
+
if (t.length >= 2) for (const v of surnameVariants(t[t.length - 1])) surnames.add(v);
|
|
39
|
+
}
|
|
40
|
+
const all = /* @__PURE__ */ new Set();
|
|
41
|
+
for (const n of provided) for (const t of tokenize(n)) all.add(t);
|
|
42
|
+
const given = [...all].filter((t) => !surnames.has(t));
|
|
43
|
+
const stored = tokenize(storedName);
|
|
44
|
+
if (stored.length === 0) return false;
|
|
45
|
+
const storedSurname = stored[stored.length - 1];
|
|
46
|
+
const storedGiven = stored.slice(0, -1);
|
|
47
|
+
if (!surnameVariants(storedSurname).some((v) => surnames.has(v))) return false;
|
|
48
|
+
const covered = (tok) => given.includes(tok) || tok.length === 1 && given.some((g) => g[0] === tok) || given.some((g) => g.length === 1 && g === tok[0]);
|
|
49
|
+
return storedGiven.every(covered);
|
|
50
|
+
}
|
|
51
|
+
function findMatchingStoredName(providedNames, storedCandidates) {
|
|
52
|
+
return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/index.ts
|
|
56
|
+
function createSqlIdempotencyStore(opts) {
|
|
57
|
+
const table = opts.table ?? "oneaddress_dispatches";
|
|
58
|
+
const ph = opts.placeholder ?? ((n) => `$${n}`);
|
|
59
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
|
|
60
|
+
throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
|
|
61
|
+
}
|
|
62
|
+
const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
|
|
63
|
+
return {
|
|
64
|
+
async claim(dispatchId) {
|
|
65
|
+
const inserted = await opts.query(
|
|
66
|
+
`INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
|
|
67
|
+
[dispatchId]
|
|
68
|
+
);
|
|
69
|
+
if (inserted.length > 0) return "fresh";
|
|
70
|
+
const rows = await opts.query(
|
|
71
|
+
`SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
|
|
72
|
+
[dispatchId]
|
|
73
|
+
);
|
|
74
|
+
return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
|
|
75
|
+
},
|
|
76
|
+
async complete(dispatchId) {
|
|
77
|
+
await opts.query(
|
|
78
|
+
`UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
|
|
79
|
+
[dispatchId]
|
|
80
|
+
);
|
|
81
|
+
},
|
|
82
|
+
// Legacy surface, implemented over the same table so a store built here
|
|
83
|
+
// still satisfies callers (or SDK versions) that only know has/set.
|
|
84
|
+
async has(dispatchId) {
|
|
85
|
+
const rows = await opts.query(
|
|
86
|
+
`SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
|
|
87
|
+
[dispatchId]
|
|
88
|
+
);
|
|
89
|
+
return rows.length > 0 && Boolean(completedOf(rows[0]));
|
|
90
|
+
},
|
|
91
|
+
async set(dispatchId) {
|
|
92
|
+
await opts.query(
|
|
93
|
+
`INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
|
|
94
|
+
[dispatchId]
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function verifySignature(rawBody, signature, timestamp, secret) {
|
|
100
|
+
if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
|
|
101
|
+
const sigPayload = `${timestamp}.${rawBody}`;
|
|
102
|
+
const expected = crypto.createHmac("sha256", secret).update(sigPayload).digest("hex");
|
|
103
|
+
const sigBuffer = Buffer.from(signature, "hex");
|
|
104
|
+
const expBuffer = Buffer.from(expected, "hex");
|
|
105
|
+
if (sigBuffer.length !== expBuffer.length) return false;
|
|
106
|
+
return crypto.timingSafeEqual(sigBuffer, expBuffer);
|
|
107
|
+
}
|
|
108
|
+
function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
|
|
109
|
+
if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
|
|
110
|
+
if (previousSecret && previousSecret !== currentSecret && graceUntil) {
|
|
111
|
+
const until = typeof graceUntil === "number" ? graceUntil : Date.parse(graceUntil);
|
|
112
|
+
if (!Number.isNaN(until) && Date.now() < until) {
|
|
113
|
+
return verifySignature(rawBody, signature, timestamp, previousSecret);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
function base64urlToBuffer(b64) {
|
|
119
|
+
return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
120
|
+
}
|
|
121
|
+
function pemToBase64(pem) {
|
|
122
|
+
const begin = pem.indexOf("-----BEGIN");
|
|
123
|
+
if (begin === -1) return pem.replace(/\s/g, "");
|
|
124
|
+
const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
|
|
125
|
+
if (armourEnd === -1) return pem.replace(/\s/g, "");
|
|
126
|
+
const bodyStart = armourEnd + "-----".length;
|
|
127
|
+
const end = pem.indexOf("-----END", bodyStart);
|
|
128
|
+
return (end === -1 ? pem.slice(bodyStart) : pem.slice(bodyStart, end)).replace(/\s/g, "");
|
|
129
|
+
}
|
|
130
|
+
function pemToBuffer(pem) {
|
|
131
|
+
return Buffer.from(pemToBase64(pem), "base64");
|
|
132
|
+
}
|
|
133
|
+
async function decryptAddress(payload, privateKeyPem, partnerId) {
|
|
134
|
+
const { ephemeralPublicKey, iv, ciphertext, hkdfSalt } = payload;
|
|
135
|
+
const privateKey = await crypto.subtle.importKey(
|
|
136
|
+
"pkcs8",
|
|
137
|
+
pemToBuffer(privateKeyPem),
|
|
138
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
139
|
+
false,
|
|
140
|
+
["deriveBits"]
|
|
141
|
+
);
|
|
142
|
+
const ephemeralKey = await crypto.subtle.importKey(
|
|
143
|
+
"raw",
|
|
144
|
+
base64urlToBuffer(ephemeralPublicKey),
|
|
145
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
146
|
+
false,
|
|
147
|
+
[]
|
|
148
|
+
);
|
|
149
|
+
const sharedBits = await crypto.subtle.deriveBits(
|
|
150
|
+
{ name: "ECDH", public: ephemeralKey },
|
|
151
|
+
privateKey,
|
|
152
|
+
256
|
|
153
|
+
);
|
|
154
|
+
const hkdfKey = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
|
|
155
|
+
let salt;
|
|
156
|
+
if (hkdfSalt) {
|
|
157
|
+
const saltBytes = base64urlToBuffer(hkdfSalt);
|
|
158
|
+
if (saltBytes.byteLength !== 32) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
`[OneAddress SDK] hkdfSalt must be 32 bytes, received ${saltBytes.byteLength}. This may indicate a protocol version mismatch or a tampered payload.`
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
salt = saltBytes;
|
|
164
|
+
} else {
|
|
165
|
+
salt = new Uint8Array(32);
|
|
166
|
+
}
|
|
167
|
+
const info = new TextEncoder().encode(`oneaddress:${partnerId}`);
|
|
168
|
+
const aesKeyBits = await crypto.subtle.deriveBits(
|
|
169
|
+
{ name: "HKDF", hash: "SHA-256", salt, info },
|
|
170
|
+
hkdfKey,
|
|
171
|
+
256
|
|
172
|
+
);
|
|
173
|
+
const aesKey = await crypto.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["decrypt"]);
|
|
174
|
+
const plaintext = await crypto.subtle.decrypt(
|
|
175
|
+
{ name: "AES-GCM", iv: base64urlToBuffer(iv), tagLength: 128 },
|
|
176
|
+
aesKey,
|
|
177
|
+
base64urlToBuffer(ciphertext)
|
|
178
|
+
);
|
|
179
|
+
return JSON.parse(new TextDecoder().decode(plaintext));
|
|
180
|
+
}
|
|
181
|
+
async function decryptSession(share, envelopeB64, privateKeyPem, partnerId) {
|
|
182
|
+
const { decryptSession: decryptSessionCrypto } = await import("./src-ESYTJ2EY.mjs");
|
|
183
|
+
return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
|
|
184
|
+
}
|
|
185
|
+
async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
|
|
186
|
+
const plaintext = await decryptAddress(payload, privateKeyPem, partnerId);
|
|
187
|
+
const plaintextBytes = new TextEncoder().encode(JSON.stringify(plaintext));
|
|
188
|
+
return reEncryptForRecipient(
|
|
189
|
+
plaintextBytes,
|
|
190
|
+
recipientSpkiPem,
|
|
191
|
+
new TextEncoder().encode(`oneaddress:transform:${partnerId}`)
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
async function reEncryptForRecipient(plaintextBytes, recipientSpkiPem, info) {
|
|
195
|
+
const recipientKey = await crypto.subtle.importKey(
|
|
196
|
+
"spki",
|
|
197
|
+
pemToBuffer(recipientSpkiPem),
|
|
198
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
199
|
+
false,
|
|
200
|
+
[]
|
|
201
|
+
);
|
|
202
|
+
const ephemeralPair = await crypto.subtle.generateKey(
|
|
203
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
204
|
+
true,
|
|
205
|
+
["deriveBits"]
|
|
206
|
+
);
|
|
207
|
+
const sharedBits = await crypto.subtle.deriveBits(
|
|
208
|
+
{ name: "ECDH", public: recipientKey },
|
|
209
|
+
ephemeralPair.privateKey,
|
|
210
|
+
256
|
|
211
|
+
);
|
|
212
|
+
const hkdfSaltBytes = crypto.getRandomValues(new Uint8Array(32));
|
|
213
|
+
const hkdfKey = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
|
|
214
|
+
const aesKeyBits = await crypto.subtle.deriveBits(
|
|
215
|
+
{ name: "HKDF", hash: "SHA-256", salt: hkdfSaltBytes, info },
|
|
216
|
+
hkdfKey,
|
|
217
|
+
256
|
|
218
|
+
);
|
|
219
|
+
const aesKey = await crypto.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["encrypt"]);
|
|
220
|
+
const ivBytes = crypto.getRandomValues(new Uint8Array(12));
|
|
221
|
+
const ciphertextBuf = await crypto.subtle.encrypt(
|
|
222
|
+
{ name: "AES-GCM", iv: ivBytes, tagLength: 128 },
|
|
223
|
+
aesKey,
|
|
224
|
+
plaintextBytes
|
|
225
|
+
);
|
|
226
|
+
const ephemeralPublicKeyRaw = await crypto.subtle.exportKey("raw", ephemeralPair.publicKey);
|
|
227
|
+
return {
|
|
228
|
+
ephemeralPublicKey: Buffer.from(ephemeralPublicKeyRaw).toString("base64"),
|
|
229
|
+
iv: Buffer.from(ivBytes).toString("base64"),
|
|
230
|
+
ciphertext: Buffer.from(ciphertextBuf).toString("base64"),
|
|
231
|
+
hkdfSalt: Buffer.from(hkdfSaltBytes).toString("base64")
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
async function transformSession(share, envelopeB64, privateKeyPem, partnerId, recipientSpkiPem) {
|
|
235
|
+
const sessionData = await decryptSession(share, envelopeB64, privateKeyPem, partnerId);
|
|
236
|
+
const plaintextBytes = new TextEncoder().encode(JSON.stringify(sessionData));
|
|
237
|
+
return reEncryptForRecipient(
|
|
238
|
+
plaintextBytes,
|
|
239
|
+
recipientSpkiPem,
|
|
240
|
+
new TextEncoder().encode(`oneaddress:transform-session:${partnerId}`)
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
var OA_APP_BASE_URL = "https://oneaddress.io";
|
|
244
|
+
async function confirmUpdate(opts) {
|
|
245
|
+
const {
|
|
246
|
+
partnerId,
|
|
247
|
+
secret,
|
|
248
|
+
dispatchId,
|
|
249
|
+
status = "confirmed",
|
|
250
|
+
note,
|
|
251
|
+
loaRef,
|
|
252
|
+
memberName,
|
|
253
|
+
appBaseUrl = OA_APP_BASE_URL,
|
|
254
|
+
fetchImpl = fetch
|
|
255
|
+
} = opts;
|
|
256
|
+
if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
|
|
257
|
+
if (!secret) return { ok: false, status: 0, error: "secret is required" };
|
|
258
|
+
const id = typeof dispatchId === "string" ? Number(dispatchId) : dispatchId;
|
|
259
|
+
if (!Number.isInteger(id) || id <= 0) {
|
|
260
|
+
return {
|
|
261
|
+
ok: false,
|
|
262
|
+
status: 0,
|
|
263
|
+
error: `dispatchId must be a positive integer, received ${JSON.stringify(dispatchId)} \u2014 it comes from the X-OneAddress-Dispatch header on the webhook you are confirming`
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
const body = JSON.stringify({
|
|
267
|
+
dispatch_id: id,
|
|
268
|
+
partner_id: partnerId,
|
|
269
|
+
status,
|
|
270
|
+
...note !== void 0 ? { note } : {},
|
|
271
|
+
...loaRef !== void 0 ? { loa_ref: loaRef } : {},
|
|
272
|
+
...memberName !== void 0 ? { member_name: memberName } : {}
|
|
273
|
+
});
|
|
274
|
+
const timestamp = String(Math.floor(Date.now() / 1e3));
|
|
275
|
+
const signature = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
|
|
276
|
+
let base = appBaseUrl;
|
|
277
|
+
while (base.endsWith("/")) base = base.slice(0, -1);
|
|
278
|
+
let res;
|
|
279
|
+
try {
|
|
280
|
+
res = await fetchImpl(`${base}/api/confirm`, {
|
|
281
|
+
method: "POST",
|
|
282
|
+
headers: {
|
|
283
|
+
"Content-Type": "application/json",
|
|
284
|
+
"Authorization": `Bearer ${secret}`,
|
|
285
|
+
"X-OneAddress-Timestamp": timestamp,
|
|
286
|
+
"X-OneAddress-Signature": signature
|
|
287
|
+
},
|
|
288
|
+
// The SAME string that was signed. Not an object, and not re-stringified.
|
|
289
|
+
body
|
|
290
|
+
});
|
|
291
|
+
} catch (err) {
|
|
292
|
+
return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
|
|
293
|
+
}
|
|
294
|
+
if (res.ok) return { ok: true, status: res.status };
|
|
295
|
+
let error;
|
|
296
|
+
try {
|
|
297
|
+
const parsed = await res.json();
|
|
298
|
+
if (typeof parsed?.error === "string") error = parsed.error;
|
|
299
|
+
} catch {
|
|
300
|
+
}
|
|
301
|
+
return { ok: false, status: res.status, error };
|
|
302
|
+
}
|
|
303
|
+
function allowedLoaHosts() {
|
|
304
|
+
const hosts = ["oneaddress.io", "app.oneaddress.io"];
|
|
305
|
+
if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
|
|
306
|
+
hosts.push("localhost", "127.0.0.1");
|
|
307
|
+
}
|
|
308
|
+
return new Set(hosts);
|
|
309
|
+
}
|
|
310
|
+
async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
|
|
311
|
+
let parsedBase;
|
|
312
|
+
try {
|
|
313
|
+
parsedBase = new URL(appBaseUrl);
|
|
314
|
+
} catch {
|
|
315
|
+
throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
|
|
316
|
+
}
|
|
317
|
+
const allowedHosts = allowedLoaHosts();
|
|
318
|
+
if (!allowedHosts.has(parsedBase.hostname)) {
|
|
319
|
+
throw new Error(
|
|
320
|
+
`[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
|
|
324
|
+
const res = await fetch(url);
|
|
325
|
+
if (!res.ok) {
|
|
326
|
+
throw new Error(`[OneAddress SDK] Failed to fetch LOA public key: HTTP ${res.status}`);
|
|
327
|
+
}
|
|
328
|
+
return res.text();
|
|
329
|
+
}
|
|
330
|
+
async function verifyLOA(loa, publicKeyPem) {
|
|
331
|
+
if (loa.algorithm !== "ECDSA-P256") {
|
|
332
|
+
console.warn(
|
|
333
|
+
// NOSONAR — intentional SDK diagnostic, not user-controlled data
|
|
334
|
+
"[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."
|
|
335
|
+
);
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
try {
|
|
339
|
+
const key = await crypto.subtle.importKey(
|
|
340
|
+
"spki",
|
|
341
|
+
pemToBuffer(publicKeyPem),
|
|
342
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
343
|
+
false,
|
|
344
|
+
["verify"]
|
|
345
|
+
);
|
|
346
|
+
const sigBytes = Buffer.from(loa.signature, "hex");
|
|
347
|
+
const textBytes = new TextEncoder().encode(loa.text);
|
|
348
|
+
return await crypto.subtle.verify(
|
|
349
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
350
|
+
key,
|
|
351
|
+
sigBytes,
|
|
352
|
+
textBytes
|
|
353
|
+
);
|
|
354
|
+
} catch {
|
|
355
|
+
return false;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
function canonicalD5LoaForm(loa) {
|
|
359
|
+
return [
|
|
360
|
+
loa.consumer_name,
|
|
361
|
+
loa.authorisation_date,
|
|
362
|
+
loa.scope,
|
|
363
|
+
loa.update_uid,
|
|
364
|
+
loa.oneaddress_acn
|
|
365
|
+
].join("|");
|
|
366
|
+
}
|
|
367
|
+
function toB64Url(buf) {
|
|
368
|
+
return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
369
|
+
}
|
|
370
|
+
function d5LoaRef(loa) {
|
|
371
|
+
return toB64Url(crypto.createHash("sha256").update(canonicalD5LoaForm(loa), "utf8").digest());
|
|
372
|
+
}
|
|
373
|
+
async function verifyD5LOA(loa, publicKeyPem) {
|
|
374
|
+
if (loa.signature_algorithm !== "ECDSA-P256") {
|
|
375
|
+
console.warn(
|
|
376
|
+
// NOSONAR — intentional SDK diagnostic, not user-controlled data
|
|
377
|
+
"[OneAddress SDK] D5 LOA algorithm is HMAC-SHA256 (deprecated) \u2014 cannot be verified by partners."
|
|
378
|
+
);
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
const key = await crypto.subtle.importKey(
|
|
383
|
+
"spki",
|
|
384
|
+
pemToBuffer(publicKeyPem),
|
|
385
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
386
|
+
false,
|
|
387
|
+
["verify"]
|
|
388
|
+
);
|
|
389
|
+
return await crypto.subtle.verify(
|
|
390
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
391
|
+
key,
|
|
392
|
+
Buffer.from(loa.oneaddress_signature, "hex"),
|
|
393
|
+
new TextEncoder().encode(canonicalD5LoaForm(loa))
|
|
394
|
+
);
|
|
395
|
+
} catch {
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
|
|
400
|
+
const data = await decryptSession(
|
|
401
|
+
loaEncrypted.session_key_share,
|
|
402
|
+
loaEncrypted.session_envelope,
|
|
403
|
+
privateKeyPem,
|
|
404
|
+
partnerId
|
|
405
|
+
);
|
|
406
|
+
return data;
|
|
407
|
+
}
|
|
408
|
+
var ADDRESS_REQUIRED_FIELDS = [
|
|
409
|
+
"street",
|
|
410
|
+
"suburb",
|
|
411
|
+
"state",
|
|
412
|
+
"postcode",
|
|
413
|
+
"country"
|
|
414
|
+
];
|
|
415
|
+
function validateAddress(raw) {
|
|
416
|
+
if (typeof raw !== "object" || raw === null) {
|
|
417
|
+
throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
|
|
418
|
+
}
|
|
419
|
+
const obj = raw;
|
|
420
|
+
for (const field of ADDRESS_REQUIRED_FIELDS) {
|
|
421
|
+
if (typeof obj[field] !== "string" || obj[field] === "") {
|
|
422
|
+
throw new Error(
|
|
423
|
+
`[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return obj;
|
|
428
|
+
}
|
|
429
|
+
var ADDRESS_ALIASES = {
|
|
430
|
+
line1: ["line1", "address_line1", "street", "streetAddress"],
|
|
431
|
+
suburb: ["suburb", "city", "locality", "town"],
|
|
432
|
+
state: ["state", "region", "province"],
|
|
433
|
+
postcode: ["postcode", "postalCode", "postal_code", "zip"],
|
|
434
|
+
country: ["country"]
|
|
435
|
+
};
|
|
436
|
+
function readAddressParts(raw) {
|
|
437
|
+
const a = raw && typeof raw === "object" ? raw : {};
|
|
438
|
+
const read = (part) => {
|
|
439
|
+
for (const key of ADDRESS_ALIASES[part]) {
|
|
440
|
+
const v = a[key];
|
|
441
|
+
if (typeof v === "string" && v.trim() !== "") return v.trim();
|
|
442
|
+
if (typeof v === "number" && Number.isFinite(v)) return String(v);
|
|
443
|
+
}
|
|
444
|
+
return "";
|
|
445
|
+
};
|
|
446
|
+
return {
|
|
447
|
+
line1: read("line1"),
|
|
448
|
+
suburb: read("suburb"),
|
|
449
|
+
state: read("state"),
|
|
450
|
+
postcode: read("postcode"),
|
|
451
|
+
country: read("country") || "AU"
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function formatAddressParts(parts) {
|
|
455
|
+
return [parts.line1, parts.suburb, parts.state, parts.postcode].filter(Boolean).join(", ");
|
|
456
|
+
}
|
|
457
|
+
var STREET_SUFFIX_MAP = {
|
|
458
|
+
st: "street",
|
|
459
|
+
str: "street",
|
|
460
|
+
rd: "road",
|
|
461
|
+
ave: "avenue",
|
|
462
|
+
av: "avenue",
|
|
463
|
+
blvd: "boulevard",
|
|
464
|
+
dr: "drive",
|
|
465
|
+
ct: "court",
|
|
466
|
+
cres: "crescent",
|
|
467
|
+
cr: "crescent",
|
|
468
|
+
pl: "place",
|
|
469
|
+
ln: "lane",
|
|
470
|
+
hwy: "highway",
|
|
471
|
+
pde: "parade",
|
|
472
|
+
pkwy: "parkway",
|
|
473
|
+
ter: "terrace",
|
|
474
|
+
cl: "close"
|
|
475
|
+
};
|
|
476
|
+
function expandSuffixes(line) {
|
|
477
|
+
return line.split(/\s+/).map((tok) => {
|
|
478
|
+
const lower = tok.toLowerCase().replace(/[.,]$/, "");
|
|
479
|
+
return STREET_SUFFIX_MAP[lower] ?? tok.replace(/[.,]$/, "").toLowerCase();
|
|
480
|
+
}).join(" ");
|
|
481
|
+
}
|
|
482
|
+
function normaliseLine(value) {
|
|
483
|
+
if (!value) return "";
|
|
484
|
+
const collapsed = value.toLowerCase().trim().replace(/\s+/g, " ");
|
|
485
|
+
return expandSuffixes(collapsed);
|
|
486
|
+
}
|
|
487
|
+
function normaliseToken(value) {
|
|
488
|
+
return (value ?? "").toLowerCase().trim().replace(/\s+/g, " ");
|
|
489
|
+
}
|
|
490
|
+
function normalisePostcode(value) {
|
|
491
|
+
const trimmed = (value ?? "").trim();
|
|
492
|
+
if (!trimmed) return "";
|
|
493
|
+
if (/^\d{1,4}$/.test(trimmed)) return trimmed.padStart(4, "0");
|
|
494
|
+
return trimmed.toLowerCase();
|
|
495
|
+
}
|
|
496
|
+
function compareAddresses(a, b) {
|
|
497
|
+
const aStreet = normaliseLine(a.street ?? a.address_line1);
|
|
498
|
+
const bStreet = normaliseLine(b.street ?? b.address_line1);
|
|
499
|
+
if (!aStreet || !bStreet || aStreet !== bStreet) return false;
|
|
500
|
+
const aSuburb = normaliseToken(a.suburb);
|
|
501
|
+
const bSuburb = normaliseToken(b.suburb);
|
|
502
|
+
if (!aSuburb || !bSuburb || aSuburb !== bSuburb) return false;
|
|
503
|
+
const aState = normaliseToken(a.state);
|
|
504
|
+
const bState = normaliseToken(b.state);
|
|
505
|
+
if (!aState || !bState || aState !== bState) return false;
|
|
506
|
+
const aPost = normalisePostcode(a.postcode);
|
|
507
|
+
const bPost = normalisePostcode(b.postcode);
|
|
508
|
+
if (!aPost || !bPost || aPost !== bPost) return false;
|
|
509
|
+
const aCountry = normaliseToken(a.country);
|
|
510
|
+
const bCountry = normaliseToken(b.country);
|
|
511
|
+
if (aCountry && bCountry && aCountry !== bCountry) return false;
|
|
512
|
+
return true;
|
|
513
|
+
}
|
|
514
|
+
async function sendVerifyResult(params) {
|
|
515
|
+
const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
|
|
516
|
+
const safe = isSafeWebhookUrl(callbackUrl);
|
|
517
|
+
if (!safe.ok) {
|
|
518
|
+
throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
|
|
519
|
+
}
|
|
520
|
+
const res = await fetch(callbackUrl, {
|
|
521
|
+
method: "POST",
|
|
522
|
+
headers: { "Content-Type": "application/json" },
|
|
523
|
+
body: JSON.stringify({
|
|
524
|
+
batch_id: batchId,
|
|
525
|
+
partner_id: partnerId,
|
|
526
|
+
result: match ? "match" : "mismatch",
|
|
527
|
+
address_match: match,
|
|
528
|
+
...note ? { note } : {},
|
|
529
|
+
token: callbackToken
|
|
530
|
+
})
|
|
531
|
+
});
|
|
532
|
+
if (!res.ok) {
|
|
533
|
+
throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
|
|
537
|
+
var warnedUnhandledEvents = /* @__PURE__ */ new Set();
|
|
538
|
+
function createOneAddressHandler(options) {
|
|
539
|
+
const {
|
|
540
|
+
webhookSecret,
|
|
541
|
+
previousWebhookSecret,
|
|
542
|
+
webhookSecretGraceUntil,
|
|
543
|
+
privateKeyPem,
|
|
544
|
+
loaPublicKeyPem,
|
|
545
|
+
onUpdate,
|
|
546
|
+
onVerify,
|
|
547
|
+
onAccountVerify,
|
|
548
|
+
onTest,
|
|
549
|
+
timestampToleranceSecs = 300,
|
|
550
|
+
idempotencyStore
|
|
551
|
+
} = options;
|
|
552
|
+
async function buildD5Pieces(body, partnerId) {
|
|
553
|
+
const share = body.session_key_share;
|
|
554
|
+
const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId);
|
|
555
|
+
const address = validateAddress({
|
|
556
|
+
street: data.new_address?.street,
|
|
557
|
+
suburb: data.new_address?.suburb,
|
|
558
|
+
state: data.new_address?.state,
|
|
559
|
+
postcode: data.new_address?.postcode,
|
|
560
|
+
country: data.new_address?.country,
|
|
561
|
+
updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
|
|
562
|
+
});
|
|
563
|
+
const customer = {
|
|
564
|
+
email: "",
|
|
565
|
+
name: data.verified_name ?? "",
|
|
566
|
+
account_number: data.account_number ?? null,
|
|
567
|
+
known_names: Array.isArray(data.known_names) ? data.known_names : []
|
|
568
|
+
};
|
|
569
|
+
let loa;
|
|
570
|
+
let loa_ref;
|
|
571
|
+
if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
|
|
572
|
+
loa = await decryptLoaEncrypted(
|
|
573
|
+
body.loa_encrypted,
|
|
574
|
+
privateKeyPem,
|
|
575
|
+
partnerId
|
|
576
|
+
);
|
|
577
|
+
loa_ref = d5LoaRef(loa);
|
|
578
|
+
if (loaPublicKeyPem) {
|
|
579
|
+
const valid = await verifyD5LOA(loa, loaPublicKeyPem);
|
|
580
|
+
if (!valid) throw new Error("D5 LOA signature verification failed");
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return { address, customer, loa, loa_ref, raw: data };
|
|
584
|
+
}
|
|
585
|
+
function isD5Body(body) {
|
|
586
|
+
return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
|
|
587
|
+
}
|
|
588
|
+
return async function handler(req) {
|
|
589
|
+
const rawBody = await req.text();
|
|
590
|
+
const sig = req.headers.get("x-oneaddress-signature") ?? "";
|
|
591
|
+
const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
|
|
592
|
+
if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
|
|
593
|
+
return new Response(JSON.stringify({ error: "Request timestamp out of tolerance" }), {
|
|
594
|
+
status: 400,
|
|
595
|
+
headers: { "Content-Type": "application/json" }
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
if (!verifyWithGrace(rawBody, tsHeader, sig, webhookSecret, previousWebhookSecret, webhookSecretGraceUntil)) {
|
|
599
|
+
return new Response(JSON.stringify({ error: "Invalid signature" }), {
|
|
600
|
+
status: 401,
|
|
601
|
+
headers: { "Content-Type": "application/json" }
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
let body;
|
|
605
|
+
try {
|
|
606
|
+
body = JSON.parse(rawBody);
|
|
607
|
+
} catch {
|
|
608
|
+
return new Response(JSON.stringify({ error: "Invalid JSON" }), {
|
|
609
|
+
status: 400,
|
|
610
|
+
headers: { "Content-Type": "application/json" }
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
const payloadVersion = body.oneaddress_version ?? body.version ?? "";
|
|
614
|
+
if (payloadVersion && !SUPPORTED_VERSIONS.includes(payloadVersion)) {
|
|
615
|
+
console.warn(
|
|
616
|
+
// NOSONAR — intentional SDK diagnostic, not user-controlled data
|
|
617
|
+
`[OneAddress SDK] Unrecognised protocol version "${payloadVersion}". Supported: ${SUPPORTED_VERSIONS.join(", ")}. Update @oneaddress/partner-sdk to the latest version.`
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
const partnerId = body.partner_id ?? "";
|
|
621
|
+
const tsNum = Number(tsHeader);
|
|
622
|
+
const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
|
|
623
|
+
if (dispatchId) {
|
|
624
|
+
if (!idempotencyStore) {
|
|
625
|
+
if (process.env.NODE_ENV === "test") {
|
|
626
|
+
throw new Error(
|
|
627
|
+
"[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
} else if (idempotencyStore.claim) {
|
|
631
|
+
const claim = await idempotencyStore.claim(dispatchId);
|
|
632
|
+
if (claim === "duplicate") {
|
|
633
|
+
return new Response(JSON.stringify({ ok: true, duplicate: true }), {
|
|
634
|
+
status: 200,
|
|
635
|
+
headers: { "Content-Type": "application/json" }
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
} else {
|
|
639
|
+
const alreadySeen = await idempotencyStore.has(dispatchId);
|
|
640
|
+
if (alreadySeen) {
|
|
641
|
+
return new Response(JSON.stringify({ ok: true, duplicate: true }), {
|
|
642
|
+
status: 200,
|
|
643
|
+
headers: { "Content-Type": "application/json" }
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
try {
|
|
649
|
+
if (body.event === "address.updated") {
|
|
650
|
+
let event;
|
|
651
|
+
if (isD5Body(body)) {
|
|
652
|
+
const d5 = await buildD5Pieces(body, partnerId);
|
|
653
|
+
event = {
|
|
654
|
+
event: "address.updated",
|
|
655
|
+
version: body.oneaddress_version ?? body.version ?? "2.0",
|
|
656
|
+
id: body.id ?? "",
|
|
657
|
+
timestamp: tsNum,
|
|
658
|
+
partner_id: partnerId,
|
|
659
|
+
dispatchId,
|
|
660
|
+
customer: d5.customer,
|
|
661
|
+
address: d5.address,
|
|
662
|
+
loa: d5.loa,
|
|
663
|
+
loa_ref: d5.loa_ref,
|
|
664
|
+
id_verification: body.id_verification,
|
|
665
|
+
raw: d5.raw
|
|
666
|
+
};
|
|
667
|
+
} else {
|
|
668
|
+
if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
|
|
669
|
+
return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
|
|
670
|
+
status: 400,
|
|
671
|
+
headers: { "Content-Type": "application/json" }
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
const encrypted = body.address_encrypted;
|
|
675
|
+
const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
|
|
676
|
+
let loa;
|
|
677
|
+
let loa_ref;
|
|
678
|
+
if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
|
|
679
|
+
loa = await decryptLoaEncrypted(
|
|
680
|
+
body.loa_encrypted,
|
|
681
|
+
privateKeyPem,
|
|
682
|
+
partnerId
|
|
683
|
+
);
|
|
684
|
+
loa_ref = d5LoaRef(loa);
|
|
685
|
+
if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
|
|
686
|
+
throw new Error("D5 LOA signature verification failed");
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
const customer = {
|
|
690
|
+
email: "",
|
|
691
|
+
name: rawAddress.fullName ?? "",
|
|
692
|
+
account_number: rawAddress.accountReference ?? null,
|
|
693
|
+
known_names: Array.isArray(rawAddress.knownNames) ? rawAddress.knownNames : []
|
|
694
|
+
};
|
|
695
|
+
event = {
|
|
696
|
+
event: "address.updated",
|
|
697
|
+
version: body.oneaddress_version ?? body.version ?? "1",
|
|
698
|
+
id: body.id ?? "",
|
|
699
|
+
timestamp: tsNum,
|
|
700
|
+
partner_id: partnerId,
|
|
701
|
+
dispatchId,
|
|
702
|
+
customer,
|
|
703
|
+
address: validateAddress(rawAddress),
|
|
704
|
+
loa,
|
|
705
|
+
loa_ref,
|
|
706
|
+
id_verification: body.id_verification,
|
|
707
|
+
raw: rawAddress
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
const result = await onUpdate(event);
|
|
711
|
+
if (dispatchId && idempotencyStore) {
|
|
712
|
+
const record = idempotencyStore.complete ? idempotencyStore.complete(dispatchId) : idempotencyStore.set(dispatchId);
|
|
713
|
+
await record.catch(
|
|
714
|
+
(err) => console.error("[OneAddress SDK] idempotency completion failed:", err)
|
|
715
|
+
// NOSONAR
|
|
716
|
+
);
|
|
717
|
+
}
|
|
718
|
+
return new Response(JSON.stringify({ ok: true, ...result }), {
|
|
719
|
+
status: 200,
|
|
720
|
+
headers: { "Content-Type": "application/json" }
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
if (body.event === "address.verify" && onVerify) {
|
|
724
|
+
if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
|
|
725
|
+
return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
|
|
726
|
+
status: 400,
|
|
727
|
+
headers: { "Content-Type": "application/json" }
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
const encrypted = body.address_encrypted;
|
|
731
|
+
const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
|
|
732
|
+
const event = {
|
|
733
|
+
event: "address.verify",
|
|
734
|
+
version: body.oneaddress_version ?? body.version ?? "1",
|
|
735
|
+
id: body.id ?? "",
|
|
736
|
+
timestamp: tsNum,
|
|
737
|
+
partner_id: partnerId,
|
|
738
|
+
dispatchId,
|
|
739
|
+
batch_id: body.batch_id ?? 0,
|
|
740
|
+
user_id: body.user_id ?? "",
|
|
741
|
+
customer: body.customer,
|
|
742
|
+
customer_match: body.customer_match,
|
|
743
|
+
address: validateAddress(rawAddress),
|
|
744
|
+
loa: body.loa,
|
|
745
|
+
id_verification: body.id_verification,
|
|
746
|
+
raw: rawAddress
|
|
747
|
+
};
|
|
748
|
+
const result = await onVerify(event);
|
|
749
|
+
const matched = result && typeof result.match === "boolean" ? result.match : void 0;
|
|
750
|
+
const callbackUrl = typeof body.callback_url === "string" ? body.callback_url : "";
|
|
751
|
+
const callbackToken = typeof body.callback_token === "string" ? body.callback_token : "";
|
|
752
|
+
if (matched === void 0) {
|
|
753
|
+
console.error("[OneAddress SDK] onVerify must return { match: boolean } to close the verify loop; result dropped.");
|
|
754
|
+
} else if (!callbackUrl || !callbackToken) {
|
|
755
|
+
console.error("[OneAddress SDK] address.verify webhook is missing callback_url/callback_token; cannot report the result.");
|
|
756
|
+
} else {
|
|
757
|
+
try {
|
|
758
|
+
await sendVerifyResult({
|
|
759
|
+
callbackUrl,
|
|
760
|
+
callbackToken,
|
|
761
|
+
batchId: body.batch_id ?? 0,
|
|
762
|
+
partnerId,
|
|
763
|
+
match: matched,
|
|
764
|
+
note: result && typeof result.note === "string" ? result.note : void 0
|
|
765
|
+
});
|
|
766
|
+
} catch (err) {
|
|
767
|
+
console.error("[OneAddress SDK] verify-result callback failed:", err);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
return new Response(JSON.stringify({ ok: true, match: matched }), {
|
|
771
|
+
status: 200,
|
|
772
|
+
headers: { "Content-Type": "application/json" }
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
if (body.event === "account.verify" && onAccountVerify) {
|
|
776
|
+
let customer;
|
|
777
|
+
if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
|
|
778
|
+
const raw = await decryptAddress(
|
|
779
|
+
body.customer_encrypted,
|
|
780
|
+
privateKeyPem,
|
|
781
|
+
partnerId
|
|
782
|
+
);
|
|
783
|
+
customer = {
|
|
784
|
+
email: raw.email ?? "",
|
|
785
|
+
name: raw.name ?? "",
|
|
786
|
+
account_number: raw.account_number ?? null,
|
|
787
|
+
known_names: Array.isArray(raw.known_names) ? raw.known_names : []
|
|
788
|
+
};
|
|
789
|
+
} else {
|
|
790
|
+
customer = body.customer ?? {};
|
|
791
|
+
}
|
|
792
|
+
const event = {
|
|
793
|
+
event: "account.verify",
|
|
794
|
+
version: body.oneaddress_version ?? body.version ?? "1",
|
|
795
|
+
id: body.id ?? "",
|
|
796
|
+
timestamp: tsNum,
|
|
797
|
+
partner_id: partnerId,
|
|
798
|
+
dispatchId,
|
|
799
|
+
user_id: body.user_id ?? "",
|
|
800
|
+
customer,
|
|
801
|
+
raw: body
|
|
802
|
+
};
|
|
803
|
+
const result = await onAccountVerify(event);
|
|
804
|
+
return new Response(JSON.stringify({ ok: true, ...result }), {
|
|
805
|
+
status: 200,
|
|
806
|
+
headers: { "Content-Type": "application/json" }
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
if (body.event === "address.test" && onTest) {
|
|
810
|
+
if (!isD5Body(body)) {
|
|
811
|
+
return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
|
|
812
|
+
status: 400,
|
|
813
|
+
headers: { "Content-Type": "application/json" }
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
const d5 = await buildD5Pieces(body, partnerId);
|
|
817
|
+
await onTest({
|
|
818
|
+
event: "address.test",
|
|
819
|
+
index: typeof body.index === "number" ? body.index : void 0,
|
|
820
|
+
total: typeof body.total === "number" ? body.total : void 0,
|
|
821
|
+
verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
|
|
822
|
+
timestamp: tsNum,
|
|
823
|
+
partner_id: partnerId,
|
|
824
|
+
customer: d5.customer,
|
|
825
|
+
address: d5.address,
|
|
826
|
+
raw: d5.raw
|
|
827
|
+
});
|
|
828
|
+
return new Response(JSON.stringify({ ok: true, test: true }), {
|
|
829
|
+
status: 200,
|
|
830
|
+
headers: { "Content-Type": "application/json" }
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
const evt = typeof body.event === "string" ? body.event : "(none)";
|
|
834
|
+
if (!warnedUnhandledEvents.has(evt)) {
|
|
835
|
+
warnedUnhandledEvents.add(evt);
|
|
836
|
+
console.warn(
|
|
837
|
+
`[OneAddress SDK] Event "${evt}" is not handled by this build and was SKIPPED. It was acknowledged with 200 so OneAddress does not retry, but your onUpdate callback did NOT run. This build handles: ${HANDLED_EVENTS.join(", ")}. If you expected this event to be processed, update @oneaddress/partner-sdk.`
|
|
838
|
+
// NOSONAR
|
|
839
|
+
);
|
|
840
|
+
}
|
|
841
|
+
return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
|
|
842
|
+
status: 200,
|
|
843
|
+
headers: { "Content-Type": "application/json" }
|
|
844
|
+
});
|
|
845
|
+
} catch (err) {
|
|
846
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
847
|
+
console.error("[OneAddress SDK] Handler error:", msg);
|
|
848
|
+
return new Response(JSON.stringify({ error: "Internal handler error" }), {
|
|
849
|
+
status: 500,
|
|
850
|
+
headers: { "Content-Type": "application/json" }
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
function toExpressHandler(handler) {
|
|
856
|
+
return async function expressHandler(req, res) {
|
|
857
|
+
const raw = req.body;
|
|
858
|
+
const isBuffer = typeof raw === "object" && raw !== null && typeof raw.copy === "function" && typeof raw.toString === "function";
|
|
859
|
+
if (!isBuffer && typeof raw !== "string") {
|
|
860
|
+
const detail = raw === void 0 ? "the body was not read at all" : `the body arrived as ${raw === null ? "null" : typeof raw}, already parsed`;
|
|
861
|
+
console.error(
|
|
862
|
+
`[OneAddress SDK] toExpressHandler: raw request body required, but ${detail}. Add express.raw({ type: 'application/json' }) to THIS route, before the handler, and make sure no global express.json() runs first. The webhook signature is computed over the raw bytes, so a parsed body cannot be verified.`
|
|
863
|
+
// NOSONAR
|
|
864
|
+
);
|
|
865
|
+
res.status(500).send(JSON.stringify({ error: "Receiver misconfigured: raw body required" }));
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
const text = typeof raw === "string" ? raw : String(raw);
|
|
869
|
+
const fetchLike = {
|
|
870
|
+
text: async () => text,
|
|
871
|
+
headers: {
|
|
872
|
+
get(name) {
|
|
873
|
+
const v = req.headers[name.toLowerCase()];
|
|
874
|
+
if (v === void 0) return null;
|
|
875
|
+
return Array.isArray(v) ? v.join(", ") : v;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
const out = await handler(fetchLike);
|
|
880
|
+
const bodyText = await out.text();
|
|
881
|
+
res.status(out.status);
|
|
882
|
+
out.headers.forEach((value, key) => {
|
|
883
|
+
res.setHeader(key, value);
|
|
884
|
+
});
|
|
885
|
+
res.send(bodyText);
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
export {
|
|
890
|
+
CURRENT_VERSION,
|
|
891
|
+
SUPPORTED_VERSIONS,
|
|
892
|
+
isEmailLike,
|
|
893
|
+
namePoolMatches,
|
|
894
|
+
findMatchingStoredName,
|
|
895
|
+
createSqlIdempotencyStore,
|
|
896
|
+
verifySignature,
|
|
897
|
+
verifyWithGrace,
|
|
898
|
+
decryptAddress,
|
|
899
|
+
decryptSession,
|
|
900
|
+
transformAddress,
|
|
901
|
+
transformSession,
|
|
902
|
+
confirmUpdate,
|
|
903
|
+
fetchLoaPublicKey,
|
|
904
|
+
verifyLOA,
|
|
905
|
+
canonicalD5LoaForm,
|
|
906
|
+
d5LoaRef,
|
|
907
|
+
verifyD5LOA,
|
|
908
|
+
decryptLoaEncrypted,
|
|
909
|
+
validateAddress,
|
|
910
|
+
readAddressParts,
|
|
911
|
+
formatAddressParts,
|
|
912
|
+
compareAddresses,
|
|
913
|
+
sendVerifyResult,
|
|
914
|
+
createOneAddressHandler,
|
|
915
|
+
toExpressHandler
|
|
916
|
+
};
|