@oneaddress/partner-sdk 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,6 +39,58 @@ export { handler as POST };
39
39
 
40
40
  ---
41
41
 
42
+ ## D5 — session-envelope decryption (added in v1.2.0)
43
+
44
+ OneAddress is rolling out a new dispatch architecture (D5 + D1 + D2 in the design doc) where each `address.updated` webhook carries:
45
+
46
+ - A per-partner `session_envelope` — AES-256-GCM ciphertext of the new address, account number, IDV reference, etc., encrypted under a fresh session key SK<sub>n</sub>.
47
+ - A structured `session_key_share` block — ECDH-ES wrap of SK<sub>n</sub> under your specific registered key, identified by a stable `key_id`.
48
+ - A reduced `letter_of_authority` — no address inside, just attestation fields.
49
+ - A cleartext `customer` block — name, email, your account_number, known_names (for record-matching only).
50
+
51
+ Decrypt via `decryptSession`:
52
+
53
+ ```typescript
54
+ import { decryptSession } from '@oneaddress/partner-sdk';
55
+
56
+ const data = await decryptSession(
57
+ body.session_key_share,
58
+ body.session_envelope,
59
+ myPrivateKeyForKeyId, // looked up by share.key_id from your key store
60
+ body.partner_id, // your partner UUID, used in HKDF info binding
61
+ );
62
+
63
+ // data.new_address.street, data.account_number, data.verified_name, etc.
64
+ ```
65
+
66
+ ### Key versioning + retention obligations
67
+
68
+ Under D5 your `partner_keys` registry holds your **active** key plus zero-or-more **retired** keys still within their 90-day retention window. Each envelope you receive tells you (via `session_key_share.key_id`) which retained key OneAddress used to wrap it.
69
+
70
+ **Your contractual obligations:**
71
+
72
+ 1. **Retain** the private key for any `key_id` whose paired public key has a `destroy_after` date in the future. You may destroy the private key on or after `destroy_after` — the corresponding session ciphertext on OneAddress's side has been purged by then.
73
+ 2. **Retain** the `session_key_share` object alongside the update record until `key_share_expiry`. After that date OneAddress will not request reconstruction.
74
+ 3. **Cooperate** in good faith with OneAddress reconstruction requests for in-window envelopes citing a legitimate `reason_code` — by decrypting the relevant share and returning SK<sub>n</sub> over the mutually-authenticated reconstruction channel.
75
+
76
+ See `docs/PARTNER_INTEGRATION.md` for the full integration spec.
77
+
78
+ ### Legacy ECDH still supported
79
+
80
+ The pre-D5 `decryptAddress` helper is unchanged and still works for any webhook carrying the legacy `address_encrypted` field. A webhook will carry **either** the legacy shape **or** the D5 shape — never both. Detect by checking for `session_envelope`:
81
+
82
+ ```typescript
83
+ if (body.session_envelope) {
84
+ const data = await decryptSession(body.session_key_share, body.session_envelope, myKey, body.partner_id);
85
+ } else {
86
+ const data = await decryptAddress(body.address_encrypted, myKey, body.partner_id);
87
+ }
88
+ ```
89
+
90
+ The legacy helper is deprecated and will be removed in v1.3.x after all OneAddress dispatches have migrated to D5.
91
+
92
+ ---
93
+
42
94
  ## Idempotency — handling retries
43
95
 
44
96
  If your handler takes longer than ~10 seconds OneAddress will time out and retry the webhook. Your `onUpdate` can be called more than once for the same address change. Use `event.dispatchId` (from the `X-OneAddress-Dispatch` header) as an idempotency key:
@@ -60,6 +112,44 @@ async onUpdate(event) {
60
112
 
61
113
  `dispatchId` falls back to `''` (empty string) if the header is absent — always guard before using it as a key.
62
114
 
115
+ > **At-least-once delivery:** The dispatch ID is recorded *after* `onUpdate` succeeds. This means if your process crashes between a successful `onUpdate` and the ID being stored, the same event will be delivered again on retry. This is intentional — the alternative (recording before processing) risks silently dropping updates if `onUpdate` fails.
116
+ >
117
+ > **Recommendation:** Make your database write idempotent (e.g. `INSERT … ON CONFLICT DO UPDATE`) rather than relying solely on the dispatchId check. That way a duplicate delivery is harmless even if the ID was never recorded.
118
+
119
+ ---
120
+
121
+ ## Identity verification attestation
122
+
123
+ Every production dispatch carries an `id_verification` block — a server-built attestation that the customer completed identity verification (Global Data DVS + biometric) before the dispatch was authorised:
124
+
125
+ ```typescript
126
+ async onUpdate(event) {
127
+ if (event.id_verification) {
128
+ // Persist the verification_ref alongside your record of the update.
129
+ // It is the immutable handle for the IDV credit consumed by this
130
+ // dispatch — quote it back to OneAddress support to trace an update
131
+ // back to the underlying verification.
132
+ await db.updateAddress({
133
+ email: event.customer.email,
134
+ ...event.address,
135
+ verification_ref: event.id_verification.verification_ref,
136
+ verified_at: event.id_verification.verified_at,
137
+ });
138
+ }
139
+ }
140
+ ```
141
+
142
+ | Field | Description |
143
+ |---|---|
144
+ | `verification_ref` | UUID — immutable handle for the IDV credit. Survives partner key rotations and IDV table rewrites. |
145
+ | `method` | `global_data_idpass` for production, `mock` in sandbox builds. |
146
+ | `verified_at` | ISO-8601 timestamp the verification was completed. |
147
+ | `certificate_id` | Global Data `api_reference` (provider certificate id). May be `null` on legacy rows. |
148
+ | `verified` | Always `true` when the block is present. |
149
+ | `platform` | Format tag — currently `oneaddress/v1`. |
150
+
151
+ The block is absent on `BYPASS_STRIPE` test flows where no IDV credit was consumed. Production dispatches always include it.
152
+
63
153
  ---
64
154
 
65
155
  ## Secret rotation grace window
@@ -125,6 +215,52 @@ export const handler = createOneAddressHandler({
125
215
 
126
216
  ---
127
217
 
218
+ ## Account verification (pre-payment, guest flow)
219
+
220
+ OneAddress runs an optional pre-payment existence check during the guest checkout flow. Implement `onAccountVerify` to participate — partners that don't implement it are silently skipped, the consumer is allowed to continue, and the regular `address.updated` event still arrives after payment.
221
+
222
+ The payload carries **no encrypted address** — just a cleartext customer block — and the consumer is waiting for your response, so reply synchronously within 10 seconds.
223
+
224
+ ```typescript
225
+ export const handler = createOneAddressHandler({
226
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
227
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
228
+
229
+ async onUpdate(event) { /* ... */ },
230
+
231
+ async onAccountVerify(event) {
232
+ // event.customer = { email, name, known_names, account_number }
233
+ const row = await db.findCustomer({
234
+ accountNumber: event.customer.account_number,
235
+ email: event.customer.email,
236
+ });
237
+
238
+ if (!row) return { status: 'no_account' };
239
+
240
+ const nameOk = row.full_name.toLowerCase() === event.customer.name.toLowerCase()
241
+ || event.customer.known_names.some(
242
+ (alias) => row.full_name.toLowerCase() === alias.toLowerCase(),
243
+ );
244
+
245
+ return nameOk ? { status: 'match' } : { status: 'no_match' };
246
+ },
247
+ });
248
+ ```
249
+
250
+ The three statuses surface to the consumer as:
251
+
252
+ | Returned | Consumer sees |
253
+ |----------|--------------|
254
+ | `{ status: 'match' }` | ✓ Account found |
255
+ | `{ status: 'no_match' }` | ⚠ Couldn't verify — check your account number (editable, retriable) |
256
+ | `{ status: 'no_account' }` | ✗ No account found (editable, retriable) |
257
+
258
+ Any other 2xx response — including the default behaviour when you don't supply `onAccountVerify` at all — surfaces as "—" (skipped). The consumer can still pay and dispatch.
259
+
260
+ Failure mode: `no_match` and `no_account` are **informational only**. The consumer is told and may correct their input, but the wizard does not block them from paying. After payment your usual `onUpdate` handler still fires — apply the same matching rules you would for an account-flow update.
261
+
262
+ ---
263
+
128
264
  ## Edge runtime (Cloudflare Workers, Next.js Edge)
129
265
 
130
266
  ```typescript
@@ -142,6 +278,7 @@ import {
142
278
  verifySignature, // single-secret HMAC verify
143
279
  verifyWithGrace, // two-secret grace-window verify
144
280
  decryptAddress, // ECDH + HKDF + AES-GCM decryption
281
+ transformAddress, // decrypt then re-encrypt to a different public key (e.g. KMS)
145
282
  isFreshTimestamp, // ±5-minute replay-window check
146
283
  CURRENT_VERSION, // '2026.1'
147
284
  SUPPORTED_VERSIONS, // ['2026.1']
@@ -160,6 +297,27 @@ Returns `true` if `timestamp` (Unix seconds string) is within `toleranceSecs` of
160
297
 
161
298
  Decrypts the `address_encrypted` blob using your PKCS#8 ECDH P-256 private key.
162
299
 
300
+ ### `transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem)`
301
+
302
+ Decrypts a OneAddress payload and immediately re-encrypts it to a different ECDH P-256 public key — for example, your internal KMS or HSM. The plaintext address is held in memory only for the duration of the call and is never returned to the caller.
303
+
304
+ ```typescript
305
+ import { transformAddress } from '@oneaddress/partner-sdk';
306
+
307
+ async onUpdate(event) {
308
+ // Re-encrypt to your KMS key — plaintext never leaves this function
309
+ const kmsBlob = await transformAddress(
310
+ event.raw.address_encrypted as EncryptedPayload,
311
+ process.env.OA_PRIVATE_KEY_PEM!,
312
+ event.partner_id,
313
+ process.env.KMS_PUBLIC_KEY_SPKI_PEM!, // your KMS/HSM SPKI PEM public key
314
+ );
315
+ await db.storeEncryptedAddress(event.customer.email, kmsBlob);
316
+ }
317
+ ```
318
+
319
+ Each call generates a fresh ephemeral key pair and random HKDF salt — full forward secrecy, no shared state between calls.
320
+
163
321
  ---
164
322
 
165
323
  ## Protocol versioning
@@ -1,23 +1,17 @@
1
+ import {
2
+ isFreshTimestamp
3
+ } from "./chunk-TGLIJMGK.mjs";
4
+
1
5
  // src/index.ts
2
6
  import crypto from "crypto";
3
7
 
4
- // ../crypto/src/replay-window.ts
5
- var DEFAULT_REPLAY_WINDOW_SECS = 300;
6
- function isFreshTimestamp(timestampHeader, toleranceSecs = DEFAULT_REPLAY_WINDOW_SECS, nowSecs) {
7
- if (typeof timestampHeader !== "string" || timestampHeader.length === 0) return false;
8
- if (!/^\d+$/.test(timestampHeader)) return false;
9
- const ts = Number(timestampHeader);
10
- if (!Number.isFinite(ts) || ts < 0) return false;
11
- const now = typeof nowSecs === "number" ? nowSecs : Math.floor(Date.now() / 1e3);
12
- return Math.abs(now - ts) <= toleranceSecs;
13
- }
14
-
15
8
  // ../protocol/src/types.ts
16
9
  var CURRENT_VERSION = "2026.1";
17
10
  var SUPPORTED_VERSIONS = ["2026.1"];
18
11
 
19
12
  // src/index.ts
20
13
  function verifySignature(rawBody, signature, timestamp, secret) {
14
+ if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
21
15
  const sigPayload = `${timestamp}.${rawBody}`;
22
16
  const expected = crypto.createHmac("sha256", secret).update(sigPayload).digest("hex");
23
17
  const sigBuffer = Buffer.from(signature, "hex");
@@ -27,7 +21,7 @@ function verifySignature(rawBody, signature, timestamp, secret) {
27
21
  }
28
22
  function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
29
23
  if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
30
- if (previousSecret && graceUntil) {
24
+ if (previousSecret && previousSecret !== currentSecret && graceUntil) {
31
25
  const until = typeof graceUntil === "number" ? graceUntil : Date.parse(graceUntil);
32
26
  if (!Number.isNaN(until) && Date.now() < until) {
33
27
  return verifySignature(rawBody, signature, timestamp, previousSecret);
@@ -63,7 +57,18 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
63
57
  256
64
58
  );
65
59
  const hkdfKey = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
66
- const salt = hkdfSalt ? base64urlToBuffer(hkdfSalt) : new Uint8Array(0);
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
+ }
67
72
  const info = new TextEncoder().encode(`oneaddress:${partnerId}`);
68
73
  const aesKeyBits = await crypto.subtle.deriveBits(
69
74
  { name: "HKDF", hash: "SHA-256", salt, info },
@@ -78,6 +83,11 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
78
83
  );
79
84
  return JSON.parse(new TextDecoder().decode(plaintext));
80
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
+ }
81
91
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
82
92
  const plaintext = await decryptAddress(payload, privateKeyPem, partnerId);
83
93
  const plaintextBytes = new TextEncoder().encode(JSON.stringify(plaintext));
@@ -100,7 +110,7 @@ async function transformAddress(payload, privateKeyPem, partnerId, recipientSpki
100
110
  );
101
111
  const hkdfSaltBytes = crypto.getRandomValues(new Uint8Array(32));
102
112
  const hkdfKey = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
103
- const info = new TextEncoder().encode(`oneaddress:transform`);
113
+ const info = new TextEncoder().encode(`oneaddress:transform:${partnerId}`);
104
114
  const aesKeyBits = await crypto.subtle.deriveBits(
105
115
  { name: "HKDF", hash: "SHA-256", salt: hkdfSaltBytes, info },
106
116
  hkdfKey,
@@ -121,8 +131,8 @@ async function transformAddress(payload, privateKeyPem, partnerId, recipientSpki
121
131
  hkdfSalt: Buffer.from(hkdfSaltBytes).toString("base64")
122
132
  };
123
133
  }
124
- var OA_APP_BASE_URL = "https://app.oneaddress.io";
125
- var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["app.oneaddress.io", "localhost", "127.0.0.1"]);
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"]);
126
136
  async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
127
137
  let parsedBase;
128
138
  try {
@@ -191,6 +201,63 @@ function validateAddress(raw) {
191
201
  }
192
202
  return obj;
193
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
+ }
194
261
  function createOneAddressHandler(options) {
195
262
  const {
196
263
  webhookSecret,
@@ -199,6 +266,7 @@ function createOneAddressHandler(options) {
199
266
  privateKeyPem,
200
267
  onUpdate,
201
268
  onVerify,
269
+ onAccountVerify,
202
270
  timestampToleranceSecs = 300,
203
271
  idempotencyStore
204
272
  } = options;
@@ -274,6 +342,7 @@ function createOneAddressHandler(options) {
274
342
  customer: body.customer,
275
343
  address: validateAddress(rawAddress),
276
344
  loa: body.loa,
345
+ id_verification: body.id_verification,
277
346
  raw: rawAddress
278
347
  };
279
348
  const result = await onUpdate(event);
@@ -309,6 +378,7 @@ function createOneAddressHandler(options) {
309
378
  customer: body.customer ?? {},
310
379
  address: validateAddress(rawAddress),
311
380
  loa: body.loa,
381
+ id_verification: body.id_verification,
312
382
  raw: rawAddress
313
383
  };
314
384
  const result = await onVerify(event);
@@ -317,6 +387,24 @@ function createOneAddressHandler(options) {
317
387
  headers: { "Content-Type": "application/json" }
318
388
  });
319
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
+ }
320
408
  return new Response(JSON.stringify({ ok: true, skipped: true }), {
321
409
  status: 200,
322
410
  headers: { "Content-Type": "application/json" }
@@ -333,16 +421,16 @@ function createOneAddressHandler(options) {
333
421
  }
334
422
 
335
423
  export {
336
- DEFAULT_REPLAY_WINDOW_SECS,
337
- isFreshTimestamp,
338
424
  CURRENT_VERSION,
339
425
  SUPPORTED_VERSIONS,
340
426
  verifySignature,
341
427
  verifyWithGrace,
342
428
  decryptAddress,
429
+ decryptSession,
343
430
  transformAddress,
344
431
  fetchLoaPublicKey,
345
432
  verifyLOA,
346
433
  validateAddress,
434
+ compareAddresses,
347
435
  createOneAddressHandler
348
436
  };