@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/README.md CHANGED
@@ -1,350 +1,714 @@
1
- # @oneaddress/partner-sdk
2
-
3
- Official Node.js SDK for OneAddress partner webhook integrations.
4
-
5
- Handles signature verification, replay-window enforcement, ECDH address decryption, and secret-rotation grace windows in a single call.
6
-
7
- ---
8
-
9
- ## Installation
10
-
11
- ```bash
12
- npm install @oneaddress/partner-sdk
13
- ```
14
-
15
- ---
16
-
17
- ## Quick start
18
-
19
- ```typescript
20
- import { createOneAddressHandler } from '@oneaddress/partner-sdk';
21
-
22
- export const handler = createOneAddressHandler({
23
- webhookSecret: process.env.OA_WEBHOOK_SECRET!,
24
- privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
25
-
26
- async onUpdate(event) {
27
- // event.address is already decrypted
28
- console.log(`Address updated for ${event.customer.email}:`, event.address);
29
- await db.updateAddress({ email: event.customer.email, ...event.address });
30
- },
31
- });
32
-
33
- // Next.js App Router
34
- export { handler as POST };
35
-
36
- // Express (requires express.raw middleware on this route)
37
- // app.post('/webhook/oneaddress', express.raw({ type: 'application/json' }), handler);
38
- ```
39
-
40
- ---
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
-
94
- ## Idempotency — handling retries
95
-
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:
97
-
98
- ```typescript
99
- async onUpdate(event) {
100
- if (event.dispatchId) {
101
- const seen = await db.dispatches.exists({ dispatchId: event.dispatchId });
102
- if (seen) return; // idempotent no-op
103
- }
104
-
105
- await db.updateAddress({ email: event.customer.email, ...event.address });
106
-
107
- if (event.dispatchId) {
108
- await db.dispatches.insert({ dispatchId: event.dispatchId });
109
- }
110
- }
111
- ```
112
-
113
- `dispatchId` falls back to `''` (empty string) if the header is absent — always guard before using it as a key.
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
-
153
- ---
154
-
155
- ## Secret rotation grace window
156
-
157
- After rotating your webhook secret in the Partner Portal, OneAddress keeps dispatching webhooks signed with the **old** secret for up to 24 hours to cover in-flight requests. Pass both secrets to the handler during the transition:
158
-
159
- ```typescript
160
- export const handler = createOneAddressHandler({
161
- webhookSecret: process.env.OA_WEBHOOK_SECRET!,
162
- previousWebhookSecret: process.env.OA_PREVIOUS_WEBHOOK_SECRET,
163
- webhookSecretGraceUntil: process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL, // ISO-8601
164
- privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
165
- async onUpdate(event) { /* ... */ },
166
- });
167
- ```
168
-
169
- Once `webhookSecretGraceUntil` passes, the previous secret is ignored automatically. You can then remove those two env vars.
170
-
171
- ### Standalone `verifyWithGrace`
172
-
173
- If you're not using the handler factory, use `verifyWithGrace` directly instead of calling `verifySignature` twice:
174
-
175
- ```typescript
176
- import { verifyWithGrace, isFreshTimestamp } from '@oneaddress/partner-sdk';
177
-
178
- // Replay check first — before signature verify
179
- if (!isFreshTimestamp(req.headers['x-oneaddress-timestamp'])) {
180
- return res.status(400).json({ error: 'Stale timestamp' });
181
- }
182
-
183
- const ok = verifyWithGrace(
184
- rawBody,
185
- req.headers['x-oneaddress-timestamp'],
186
- req.headers['x-oneaddress-signature'],
187
- process.env.OA_WEBHOOK_SECRET!,
188
- process.env.OA_PREVIOUS_WEBHOOK_SECRET,
189
- process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL,
190
- );
191
- if (!ok) return res.status(401).json({ error: 'Invalid signature' });
192
- ```
193
-
194
- ---
195
-
196
- ## Address verification events
197
-
198
- Implement `onVerify` to respond to consumer address-match checks:
199
-
200
- ```typescript
201
- export const handler = createOneAddressHandler({
202
- webhookSecret: process.env.OA_WEBHOOK_SECRET!,
203
- privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
204
-
205
- async onUpdate(event) { /* ... */ },
206
-
207
- async onVerify(event) {
208
- const stored = await db.getAddress({ email: event.customer.email });
209
- const match = stored?.street === event.address.street &&
210
- stored?.postcode === event.address.postcode;
211
- return { match, note: match ? undefined : 'Address does not match our records' };
212
- },
213
- });
214
- ```
215
-
216
- ---
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
-
264
- ## Edge runtime (Cloudflare Workers, Next.js Edge)
265
-
266
- ```typescript
267
- import { createOneAddressHandler } from '@oneaddress/partner-sdk/edge';
268
- ```
269
-
270
- All exports are available on the `/edge` path. No Node.js-specific APIs are used.
271
-
272
- ---
273
-
274
- ## Standalone utilities
275
-
276
- ```typescript
277
- import {
278
- verifySignature, // single-secret HMAC verify
279
- verifyWithGrace, // two-secret grace-window verify
280
- decryptAddress, // ECDH + HKDF + AES-GCM decryption
281
- transformAddress, // decrypt then re-encrypt to a different public key (e.g. KMS)
282
- isFreshTimestamp, // ±5-minute replay-window check
283
- CURRENT_VERSION, // '2026.1'
284
- SUPPORTED_VERSIONS, // ['2026.1']
285
- } from '@oneaddress/partner-sdk';
286
- ```
287
-
288
- ### `verifySignature(rawBody, signature, timestamp, secret)`
289
-
290
- Returns `true` if the HMAC-SHA256 signature is valid. Signing formula: `HMAC-SHA256("${timestamp}.${rawBody}")`.
291
-
292
- ### `isFreshTimestamp(timestamp, toleranceSecs?)`
293
-
294
- Returns `true` if `timestamp` (Unix seconds string) is within `toleranceSecs` of now. Default tolerance: 300 seconds (±5 minutes). **Always check freshness before signature** — a stale-timestamp check is cheap; a signature verify is not.
295
-
296
- ### `decryptAddress(payload, privateKeyPem, partnerId)`
297
-
298
- Decrypts the `address_encrypted` blob using your PKCS#8 ECDH P-256 private key.
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
-
321
- ---
322
-
323
- ## Protocol versioning
324
-
325
- The SDK warns (but does not reject) if it receives a protocol version it doesn't recognise:
326
-
327
- ```
328
- [OneAddress SDK] Unrecognised protocol version "2027.1".
329
- Supported: 2026.1. Update @oneaddress/partner-sdk to the latest version.
330
- ```
331
-
332
- This ensures you keep receiving events while updating your SDK. See `SUPPORTED_VERSIONS` to check which versions the installed SDK build supports.
333
-
334
- ---
335
-
336
- ## Testing your integration
337
-
338
- **Quick smoke test** — send a single test webhook from the Partner Portal (Profile → Test Webhook).
339
-
340
- **Full conformance suite** — run 10 checks against your endpoint using real crypto, no mocks:
341
-
342
- ```bash
343
- # Against a live endpoint
344
- npx @oneaddress/conformance test https://your-endpoint.com/webhook --secret whsec_...
345
-
346
- # Against a local server (run from the machine where the server is running)
347
- npx @oneaddress/conformance test http://localhost:3001/webhook
348
- ```
349
-
350
- Or use the **Integration Conformance** card in the Partner Portal to run the same checks against your configured webhook URL from within the portal.
1
+ # @oneaddress/partner-sdk
2
+
3
+ Official Node.js SDK for OneAddress partner webhook integrations.
4
+
5
+ Handles signature verification, replay-window enforcement, ECDH address decryption, and secret-rotation grace windows in a single call.
6
+
7
+ > **Not using Node?** You do not need this SDK. The full wire protocol is documented in the
8
+ > [OneAddress partner protocol specification](../../docs/integrations/partner-protocol-spec.md) —
9
+ > headers, signing, replay rules, all three key-unwrap procedures with exact HKDF parameters and
10
+ > byte layouts, both callbacks, and an implementation checklist. It is written so a conforming
11
+ > receiver can be built on any platform with no OneAddress code at all. This SDK is the fast path,
12
+ > not the only path.
13
+
14
+ ---
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @oneaddress/partner-sdk
20
+ ```
21
+
22
+ ---
23
+
24
+ ## Quick start
25
+
26
+ ```typescript
27
+ import { createOneAddressHandler, namePoolMatches } from '@oneaddress/partner-sdk';
28
+
29
+ export const handler = createOneAddressHandler({
30
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
31
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
32
+
33
+ async onUpdate(event) {
34
+ // event.address is already decrypted. event.customer.email is always ''
35
+ // on this event (OneAddress never learns a consumer's email for a
36
+ // dispatch it isn't sent for) - match on account_number and/or name.
37
+ const providedNames = [event.customer.name, ...event.customer.known_names];
38
+ const record = await db.findByAccountNumber(event.customer.account_number);
39
+ if (!record || !namePoolMatches(providedNames, record.fullName)) {
40
+ throw new Error('No matching customer for this dispatch');
41
+ }
42
+ await db.updateAddress({ id: record.id, ...event.address });
43
+ },
44
+ // Connection-verification test records. OneAddress sends five of these
45
+ // before you go live: real signed, encrypted dispatches carrying FABRICATED
46
+ // identities, which you decrypt and relay back.
47
+ //
48
+ // Deliberately NOT routed through onUpdate - the names and addresses are
49
+ // fictitious, and writing them into real customer records is exactly what a
50
+ // separate event type exists to prevent.
51
+ //
52
+ // Leave it out and address.test is acknowledged with 200, skipped, and
53
+ // logged as skipped. You will not be able to complete connection
54
+ // verification through the SDK.
55
+ async onTest(event) {
56
+ console.log(`test record ${event.index}/${event.total}`,
57
+ event.customer.name, event.address);
58
+ },
59
+ });
60
+
61
+ // Next.js App Router
62
+ export { handler as POST };
63
+
64
+ // Express — wrap with toExpressHandler. The handler itself is Fetch-shaped
65
+ // (it reads req.text() and returns a Response), which is what lets the same
66
+ // code run on App Router, Workers, Deno and Bun. Express gives neither, so it
67
+ // needs the adapter — passing `handler` straight in throws
68
+ // "req.text is not a function" on your first delivery.
69
+ //
70
+ // import { createOneAddressHandler, toExpressHandler } from '@oneaddress/partner-sdk';
71
+ //
72
+ // app.post(
73
+ // '/webhook/oneaddress',
74
+ // express.raw({ type: 'application/json' }), // required, see below
75
+ // toExpressHandler(handler),
76
+ // );
77
+ //
78
+ // express.raw on THIS route is not optional and not merely a body-parser
79
+ // preference: the signature is an HMAC over the raw request bytes, so if
80
+ // express.json() has already parsed the body those bytes are gone and no
81
+ // re-serialisation reproduces them. toExpressHandler refuses a parsed body
82
+ // with a named error rather than letting it become a confusing 401.
83
+ ```
84
+
85
+ ---
86
+
87
+ ## D5 — session-envelope decryption (added in v1.3.0)
88
+
89
+ OneAddress is rolling out a new dispatch architecture (D5 + D1 + D2 in the design doc) where each `address.updated` webhook carries:
90
+
91
+ - A per-partner `session_envelope` — AES-256-GCM ciphertext of the new address, account number, IDV reference, verified name, known-names, etc., encrypted under a fresh session key SK<sub>n</sub>.
92
+ - 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`.
93
+ - A per-partner `loa_encrypted` — the signed Letter of Authority, encrypted with the SAME scheme + key as the address envelope (`{ session_envelope, session_key_share }`).
94
+
95
+ > **No cleartext customer identity.** As of the "no cleartext" mandate the webhook carries **no** cleartext `customer` block, **no** `customer_match` blind-index block, and **no** cleartext `letter_of_authority`. The consumer's name, known-names, and your account number are recoverable **only** by decrypting the `session_envelope`; the signed consent only by decrypting `loa_encrypted`. Nothing about the consumer is knowable before you decrypt. If you use `createOneAddressHandler`, `event.customer` is populated for you from the decrypted envelope (with `email: ''` — match on name / known_names / account_number).
96
+
97
+ Decrypt via `decryptSession`:
98
+
99
+ ```typescript
100
+ import { decryptSession } from '@oneaddress/partner-sdk';
101
+
102
+ const data = await decryptSession(
103
+ body.session_key_share,
104
+ body.session_envelope,
105
+ myPrivateKeyForKeyId, // looked up by share.key_id from your key store
106
+ body.partner_id, // your partner UUID, used in HKDF info binding
107
+ );
108
+
109
+ // data.new_address.street, data.account_number, data.verified_name, etc.
110
+ ```
111
+
112
+ `decryptSession` handles **both** wrap schemes transparently — it routes on `share.alg` and you just supply the private key matching `share.key_id`:
113
+
114
+ - **`ECDH-ES+HKDF-SHA256+A256GCM`** (default) — your key is ECDH P-256; supply your P-256 PKCS#8 private key.
115
+ - **`RSA-OAEP-256+A256GCM`** — your key is RSA (e.g. a KMS/HSM that only exposes RSA); supply your RSA PKCS#8 private key. Register the RSA public key via the **Encryption Key → “Use your own RSA key (KMS / HSM)”** option in the partner portal. In this scheme there is no ephemeral key (`share.epk` is absent); the session key SK<sub>n</sub> is RSA-OAEP-encrypted directly to your RSA public key.
116
+ - **`MLKEM768X25519+HKDF-SHA256+A256GCM`** — **post-quantum hybrid** (X-Wing = ML-KEM-768 + X25519, per `draft-connolly-cfrg-xwing-kem`). Protects SK<sub>n</sub> against “harvest now, decrypt later” — an adversary who records the wire cannot recover it even with a future quantum computer, because that requires breaking **both** ML-KEM-768 and X25519. Supply your **32-byte X-Wing secret** (base64). `share.epk` carries the X-Wing KEM ciphertext. Register the X-Wing public key via the **Encryption Key → “Post-quantum (ML-KEM-768 + X25519)”** option in the partner portal.
117
+
118
+ In all schemes the `session_envelope` is identical (AES-256-GCM under SK<sub>n</sub>) — only the SK<sub>n</sub> wrap differs.
119
+
120
+ ### Decrypting + verifying the Letter of Authority
121
+
122
+ The signed LOA travels as `loa_encrypted` (same `{ session_envelope, session_key_share }` shape, wrapped to the same `key_id`). Decrypt it, verify the signature, and echo the reference back in your confirm callback:
123
+
124
+ ```typescript
125
+ import {
126
+ decryptLoaEncrypted, verifyD5LOA, d5LoaRef, fetchLoaPublicKey, confirmUpdate,
127
+ } from '@oneaddress/partner-sdk';
128
+
129
+ const loa = await decryptLoaEncrypted(body.loa_encrypted, myPrivateKeyForKeyId, body.partner_id);
130
+ const loaKey = await fetchLoaPublicKey(); // cache this
131
+ if (!(await verifyD5LOA(loa, loaKey))) throw new Error('LOA signature invalid');
132
+
133
+ // Echo the ref in your confirm callback so OneAddress can confirm you decrypted
134
+ // a valid signed consent. It carries no name in the clear.
135
+ await confirmUpdate({
136
+ partnerId, secret: process.env.OA_CONFIRM_SECRET!,
137
+ dispatchId: event.dispatch_id,
138
+ status: 'confirmed', loaRef: d5LoaRef(loa),
139
+ });
140
+ ```
141
+
142
+ If you use `createOneAddressHandler`, this is done for you: pass `loaPublicKeyPem` and the handler decrypts + verifies + rejects on failure, and exposes `event.loa` (the decrypted LOA) and `event.loa_ref` (echo it in your confirm callback).
143
+
144
+ > **Post-quantum SDK availability.** The X-Wing (`MLKEM768X25519+…`) scheme is supported today in the **TypeScript** (this package) and **Go** SDKs. Python, Java, and C# X-Wing decapsulation is **available on request** — X-Wing is a 2024 draft without a mature drop-in library in those languages yet, so we build it per-SDK on demand (verified against the canonical `session_pq` test vector). Contact OneAddress engineering if you need a Python/Java/C# post-quantum build. ECDH-ES and RSA-OAEP are supported in all five SDKs.
145
+
146
+ ### Key versioning + retention obligations
147
+
148
+ Under D5 your `partner_keys` registry holds your **active** key plus zero-or-more **retired** keys still within their retention window (your configured retention period, minimum 14 days; the authoritative horizon for each key is its `destroy_after` date, not a fixed number of days). Each envelope you receive tells you (via `session_key_share.key_id`) which retained key OneAddress used to wrap it.
149
+
150
+ **Your contractual obligations:**
151
+
152
+ 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.
153
+ 2. **Retain** the `session_key_share` object alongside the update record until `key_share_expiry`. After that date OneAddress will not request reconstruction.
154
+ 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.
155
+
156
+ See the partner portal documentation at partners.oneaddress.io for the full integration spec.
157
+
158
+ ### Legacy ECDH still supported
159
+
160
+ 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`:
161
+
162
+ ```typescript
163
+ if (body.session_envelope) {
164
+ const data = await decryptSession(body.session_key_share, body.session_envelope, myKey, body.partner_id);
165
+ } else {
166
+ const data = await decryptAddress(body.address_encrypted, myKey, body.partner_id);
167
+ }
168
+ ```
169
+
170
+ The legacy helper is deprecated and will be removed in a future major version once all OneAddress dispatches have migrated to D5 - no removal is scheduled yet.
171
+
172
+ ---
173
+
174
+ ## Blind-index matching (zero-plaintext record matching)
175
+
176
+ > **Superseded by the "no cleartext" mandate: no event type carries
177
+ > `customer_match` any more.** OneAddress emits neither a cleartext `customer`
178
+ > block nor a `customer_match` block on any dispatch or verification webhook:
179
+ > identity travels only inside the encrypted payload (`session_envelope` on
180
+ > `address.updated`; `address_encrypted` on `address.verify`;
181
+ > `customer_encrypted` on `account.verify`). `event.customer_match` is always
182
+ > `undefined`. Match on the decrypted `verified_name` / `known_names` /
183
+ > `account_number` instead; if you use `createOneAddressHandler`,
184
+ > `event.customer` is populated for you after decryption. The section below is
185
+ > retained for partners who adopted blind indexes while the feature was live
186
+ > and still use them for their **own internal** matching columns; nothing in it
187
+ > arrives on the wire.
188
+
189
+ The `computeBlindIndex` / `normalizeForBlindIndex` helpers remain exported.
190
+ Each index is `base64url(HMAC-SHA256(yourBlindIndexSecret, normalize(field)))`,
191
+ and if you keep blind-index columns on your own records the normalisation
192
+ contract below still governs how they must be computed.
193
+
194
+ **Normalisation is part of the contract**: always compute indexes with the
195
+ SDK's `computeBlindIndex` (or `normalizeForBlindIndex`), never by hand:
196
+
197
+ | Field | Normalisation |
198
+ | --- | --- |
199
+ | `email` | NFKC · trim · lowercase |
200
+ | `name` | NFKC · trim · lowercase · collapse internal whitespace |
201
+ | `account_number` | NFKC · trim · remove all whitespace · **case preserved** |
202
+
203
+ (Historical note: while the wire feature was live, `customer_match.names` held
204
+ one index per name (legal name plus each known-name alias) and a record
205
+ matched if any stored name index appeared in it. No event carries that block
206
+ today.)
207
+
208
+ ---
209
+
210
+ ## Name matching (added in v1.4.0)
211
+
212
+ Once you've decrypted the envelope (or resolved a blind-index hit), you still
213
+ need to confirm the customer's name matches your stored record before
214
+ accepting an address change. **Don't write this comparison yourself.** A naive
215
+ approach - substring or prefix matching on whitespace-split tokens - treats an
216
+ email address as just another name token, and an email's local part can
217
+ satisfy that comparison against an unrelated customer's first name. That's a
218
+ real failure mode we found and fixed in our own systems: it lets a stray email
219
+ address stored in a name-shaped field act as a false-positive match.
220
+
221
+ The SDK re-exports the same component-aware matcher OneAddress's own
222
+ reference receivers run:
223
+
224
+ ```typescript
225
+ import { namePoolMatches } from '@oneaddress/partner-sdk';
226
+
227
+ const data = await decryptSession(/* ... */);
228
+ const providedNames = [data.verified_name, ...(data.known_names ?? [])];
229
+
230
+ const record = await db.findAccount(/* by account_number, etc. */);
231
+ if (!namePoolMatches(providedNames, record.name)) {
232
+ // Names don't line up - do not apply the address change.
233
+ }
234
+ ```
235
+
236
+ `namePoolMatches(providedNames, storedName)` returns `true` when `storedName`'s
237
+ surname is one of the surnames implied by `providedNames`, and every one of
238
+ `storedName`'s given-name tokens is explained by the pool (an exact token, or a
239
+ single-letter initial matching a pool token). It rejects email-shaped entries
240
+ on **both** sides outright - an email can never satisfy the match, however
241
+ permissive the rest of the pool is. `findMatchingStoredName(providedNames,
242
+ candidates)` does the same over a list of candidate stored names and returns
243
+ the first match, if any.
244
+
245
+ Note: `namePoolMatches` assumes given-name-then-surname ordering (it treats the
246
+ *last* token as the surname). If your customer base includes surname-first
247
+ naming conventions, verify this assumption holds before relying on it.
248
+
249
+ ---
250
+
251
+ ## Confirming back — `confirmUpdate`
252
+
253
+ **Receiving a dispatch is only half the protocol.** Until you call back, the consumer's dashboard shows your business stuck on "dispatched" indefinitely — no matter how correctly you applied the change.
254
+
255
+ ```typescript
256
+ import { confirmUpdate } from '@oneaddress/partner-sdk';
257
+
258
+ const res = await confirmUpdate({
259
+ partnerId: process.env.OA_PARTNER_ID!,
260
+ secret: process.env.OA_CONFIRM_SECRET!, // see "which secret" below
261
+ dispatchId: event.dispatch_id, // from X-OneAddress-Dispatch
262
+ status: 'confirmed',
263
+ note: 'Address updated in CRM',
264
+ });
265
+
266
+ if (!res.ok) console.error('[oneaddress] confirm failed', res.status, res.error);
267
+ ```
268
+
269
+ ### The three statuses mean different things
270
+
271
+ | Status | Meaning |
272
+ | --- | --- |
273
+ | `confirmed` | You applied the change. |
274
+ | `already_current` | You already held that address; nothing to write. **Not a failure** — return it honestly rather than reporting `confirmed`. |
275
+ | `failed` | You could not apply it. Send a `note` saying why. |
276
+
277
+ ### Which secret
278
+
279
+ If you have minted a **confirm secret** in the Partner Portal, use that one — once it exists it is the only secret `/api/confirm` accepts, so that a leaked webhook secret cannot forge confirmations. If you have not, use your webhook signing secret. The same secret authenticates the request and signs the body.
280
+
281
+ ### Why this helper exists
282
+
283
+ The endpoint requires a Bearer token, a fresh unix-**seconds** timestamp, and an HMAC-SHA256 over `` `${timestamp}.${rawBody}` ``. Hand-rolling that has three failure modes which all surface as an indistinguishable `401`:
284
+
285
+ - **Signing a string and then sending a re-serialised object.** A byte of whitespace or a different key order breaks the signature. `confirmUpdate` serialises once and sends exactly what it signed.
286
+ - **Milliseconds instead of seconds.** That is outside the ±300s replay window by a factor of a thousand, and the error reads "stale or future request", which sounds like an auth problem.
287
+ - **Clock drift on your host.** Same error, same confusion. If confirms fail and nothing else has changed, check your clock.
288
+
289
+ `confirmUpdate` never throws on an HTTP status — it returns `{ ok, status, error }`. **Log that result.** If a confirm fails and nothing inspects it, the update looks applied on your side and the consumer never sees it land: the same silent-success shape as an unhandled event, in the other direction.
290
+
291
+ It also refuses a missing or non-numeric `dispatchId` **before** sending, because `/api/confirm` treats an absent `dispatch_id` as a no-op for the dispatch record — so posting one would return `200` having closed no loop at all.
292
+
293
+ ---
294
+
295
+ ## Idempotency — handling retries
296
+
297
+ 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:
298
+
299
+ ```typescript
300
+ async onUpdate(event) {
301
+ if (event.dispatchId) {
302
+ const seen = await db.dispatches.exists({ dispatchId: event.dispatchId });
303
+ if (seen) return; // idempotent no-op
304
+ }
305
+
306
+ await db.updateAddress({ accountNumber: event.customer.account_number, ...event.address });
307
+
308
+ if (event.dispatchId) {
309
+ await db.dispatches.insert({ dispatchId: event.dispatchId });
310
+ }
311
+ }
312
+ ```
313
+
314
+ `dispatchId` falls back to `''` (empty string) if the header is absent — always guard before using it as a key.
315
+
316
+ > **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.
317
+ >
318
+ > **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.
319
+
320
+ ### Let the handler do it — `createSqlIdempotencyStore`
321
+
322
+ Rather than hand-rolling the above, pass an `idempotencyStore` and the handler manages
323
+ deduplication for you. The SDK ships a SQL-backed implementation that works over whatever driver
324
+ you already use — it takes a `query` function, so the SDK stays dependency-free and you reuse
325
+ your existing pool and credentials:
326
+
327
+ ```sql
328
+ CREATE TABLE oneaddress_dispatches (
329
+ dispatch_id TEXT PRIMARY KEY,
330
+ received_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
331
+ completed_at TIMESTAMP
332
+ );
333
+ ```
334
+
335
+ ```typescript
336
+ import { createOneAddressHandler, createSqlIdempotencyStore } from '@oneaddress/partner-sdk';
337
+
338
+ export const handler = createOneAddressHandler({
339
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
340
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
341
+
342
+ idempotencyStore: createSqlIdempotencyStore({
343
+ // Postgres (node-postgres). For MySQL/SQLite/SQL Server add `placeholder: () => '?'`.
344
+ query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
345
+ }),
346
+
347
+ async onUpdate(event) {
348
+ await db.updateAddress({ accountNumber: event.customer.account_number, ...event.address });
349
+ },
350
+ });
351
+ ```
352
+
353
+ **Why a `claim`, not a `has`/`set` pair.** The older two-method interface still works, but it
354
+ cannot be made correct under concurrency: `has` and `set` are separate round-trips, so two
355
+ retries arriving at once both observe "not seen" and both apply the update. `claim` is a single
356
+ atomic `INSERT … ON CONFLICT DO NOTHING` and has no such window.
357
+
358
+ It also distinguishes three states rather than two, and the third is the one that matters:
359
+
360
+ | Claim | Meaning | Handler does |
361
+ |---|---|---|
362
+ | `fresh` | Never seen | Process it |
363
+ | `retry-after-incomplete` | Seen, but the previous attempt never reported completion | **Process it again** |
364
+ | `duplicate` | Seen and completed | Skip, respond `200 { duplicate: true }` |
365
+
366
+ A store that only knows "seen / not seen" has to guess at the middle row. Guess "duplicate" and
367
+ you lose a paid address update permanently the first time a process dies mid-write — with your
368
+ side and ours both reporting success.
369
+
370
+ > **Do not use an in-memory `Set`** beyond local development. It is per-process (so it does
371
+ > nothing behind a load balancer), unbounded (so it leaks), and lost on restart (so it re-opens
372
+ > the duplicate window on every deploy).
373
+
374
+ ---
375
+
376
+ ## Identity verification attestation
377
+
378
+ Every production dispatch carries a **cleartext** `id_verification` block — a server-built attestation that the customer completed identity verification (Global Data DVS + biometric) before the dispatch was authorised. Under the zero-knowledge dispatch rules this outer block carries **no customer identity** — only the fact and format of the verification:
379
+
380
+ ```typescript
381
+ async onUpdate(event) {
382
+ if (event.id_verification) {
383
+ // The outer block confirms the update was IDV-authorised, but carries
384
+ // no identifying reference. It is safe to log for audit/compliance.
385
+ logger.info('IDV-authorised dispatch', {
386
+ method: event.id_verification.method, // 'identity_document'
387
+ verified_at: event.id_verification.verified_at,
388
+ });
389
+ }
390
+ }
391
+ ```
392
+
393
+ | Field | Description |
394
+ |---|---|
395
+ | `method` | `identity_document` when the customer completed a document + biometric check; `mock` in sandbox builds. Carries no underlying-provider identity. |
396
+ | `verified_at` | ISO-8601 timestamp the verification was completed. |
397
+ | `verified` | Always `true` when the block is present. |
398
+ | `platform` | Format tag — currently `oneaddress/v1`. |
399
+
400
+ The block is absent on `BYPASS_STRIPE` test flows where no IDV credit was consumed. Production dispatches always include it.
401
+
402
+ ### The verification reference lives inside the encrypted envelope
403
+
404
+ The immutable IDV handle — the `verification_ref` UUID you quote back to OneAddress support to trace an update to its underlying verification — is **not** in this cleartext block. Per the zero-knowledge dispatch rules, customer identity (including the IDV reference) stays inside the encrypted `session_envelope`. After you decrypt it (via `decryptSession`, or automatically inside `createOneAddressHandler`), read it from the decrypted [`SessionData`](#d5--session-envelope-decryption-added-in-v130) as `id_verification_ref`:
405
+
406
+ ```typescript
407
+ import { decryptSession, type SessionData } from '@oneaddress/partner-sdk';
408
+
409
+ const session = await decryptSession(
410
+ event.raw.session_key_share,
411
+ event.raw.session_envelope,
412
+ process.env.OA_PRIVATE_KEY_PEM!,
413
+ process.env.OA_PARTNER_ID!,
414
+ ) as SessionData;
415
+
416
+ // Persist the ref against your record of the update — it never travels
417
+ // in the clear and is only computable after you decrypt the envelope.
418
+ await db.updateAddress({
419
+ ...event.address,
420
+ verification_ref: session.id_verification_ref,
421
+ });
422
+ ```
423
+
424
+ ---
425
+
426
+ ## Secret rotation grace window
427
+
428
+ After rotating your webhook secret in the Partner Portal, OneAddress keeps dispatching webhooks signed with the **old** secret for up to 24 hours to cover in-flight requests. Pass both secrets to the handler during the transition:
429
+
430
+ ```typescript
431
+ export const handler = createOneAddressHandler({
432
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
433
+ previousWebhookSecret: process.env.OA_PREVIOUS_WEBHOOK_SECRET,
434
+ webhookSecretGraceUntil: process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL, // ISO-8601
435
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
436
+ async onUpdate(event) { /* ... */ },
437
+ });
438
+ ```
439
+
440
+ Once `webhookSecretGraceUntil` passes, the previous secret is ignored automatically. You can then remove those two env vars.
441
+
442
+ ### Standalone `verifyWithGrace`
443
+
444
+ If you're not using the handler factory, use `verifyWithGrace` directly instead of calling `verifySignature` twice:
445
+
446
+ ```typescript
447
+ import { verifyWithGrace, isFreshTimestamp } from '@oneaddress/partner-sdk';
448
+
449
+ // Replay check first — before signature verify
450
+ if (!isFreshTimestamp(req.headers['x-oneaddress-timestamp'])) {
451
+ return res.status(400).json({ error: 'Stale timestamp' });
452
+ }
453
+
454
+ const ok = verifyWithGrace(
455
+ rawBody,
456
+ req.headers['x-oneaddress-timestamp'],
457
+ req.headers['x-oneaddress-signature'],
458
+ process.env.OA_WEBHOOK_SECRET!,
459
+ process.env.OA_PREVIOUS_WEBHOOK_SECRET,
460
+ process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL,
461
+ );
462
+ if (!ok) return res.status(401).json({ error: 'Invalid signature' });
463
+ ```
464
+
465
+ ---
466
+
467
+ ## Address verification events
468
+
469
+ `address.verify` asks whether a consumer's **new** address already matches what you
470
+ hold on file. On a **match**, OneAddress marks the service "already in sync" and
471
+ **skips the `address.updated` dispatch** — there is nothing to update. On a
472
+ **mismatch**, the normal `address.updated` event follows after the check.
473
+
474
+ The address travels encrypted as `address_encrypted` (per-partner ECDH, no
475
+ cleartext); `createOneAddressHandler` decrypts it into `event.address` for you.
476
+ Return `{ match }` and the SDK reports the result back to OneAddress for you —
477
+ use the `compareAddresses` helper for a strict baseline comparison:
478
+
479
+ ```typescript
480
+ import { createOneAddressHandler, compareAddresses } from '@oneaddress/partner-sdk';
481
+
482
+ export const handler = createOneAddressHandler({
483
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
484
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
485
+
486
+ async onUpdate(event) { /* ... */ },
487
+
488
+ async onVerify(event) {
489
+ const stored = await db.getStoredAddress(event); // look up by your account reference
490
+ if (!stored) return { match: false, note: 'No address on file' };
491
+ return { match: compareAddresses(stored, event.address) };
492
+ },
493
+ });
494
+ ```
495
+
496
+ **How the loop closes.** Unlike `account.verify` (which OneAddress reads from your
497
+ synchronous HTTP response), `address.verify` results are ingested from a **callback**
498
+ the SDK POSTs to the webhook's `callback_url` (`/api/verify-result`), carrying
499
+ `{ batch_id, partner_id, result, address_match, token }`. `createOneAddressHandler`
500
+ sends this **automatically** whenever you provide `onVerify`. Simply returning from
501
+ the handler without this callback would leave the verify batch to time out.
502
+
503
+ If you handle `address.verify` **without** the SDK handler, call `sendVerifyResult`
504
+ yourself after verifying the HMAC signature and decrypting the address:
505
+
506
+ ```typescript
507
+ import { sendVerifyResult, compareAddresses, decryptAddress } from '@oneaddress/partner-sdk';
508
+
509
+ const address = await decryptAddress(body.address_encrypted, privateKeyPem, partnerId);
510
+ const match = compareAddresses(await db.getStoredAddress(body), address);
511
+
512
+ await sendVerifyResult({
513
+ callbackUrl: body.callback_url,
514
+ callbackToken: body.callback_token,
515
+ batchId: body.batch_id,
516
+ partnerId,
517
+ match,
518
+ });
519
+ ```
520
+
521
+ `sendVerifyResult` maps `match: true → result 'match' + address_match true`
522
+ (OneAddress skips the dispatch) and `match: false → 'mismatch' + address_match false`
523
+ (the update proceeds). It throws if the callback POST returns a non-2xx status.
524
+
525
+ ---
526
+
527
+ ## Account verification (pre-payment, guest flow)
528
+
529
+ 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.
530
+
531
+ The payload carries **no address** — only the customer identity block (name / known-names / account number), and it travels **encrypted** as `customer_encrypted` (per-partner ECDH, same scheme as the address payload), never in cleartext. `createOneAddressHandler` decrypts it for you and populates `event.customer`. The consumer is waiting for your response, so reply synchronously within 10 seconds.
532
+
533
+ ```typescript
534
+ export const handler = createOneAddressHandler({
535
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
536
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
537
+
538
+ async onUpdate(event) { /* ... */ },
539
+
540
+ async onAccountVerify(event) {
541
+ // event.customer = { email, name, known_names, account_number }
542
+ const row = await db.findCustomer({
543
+ accountNumber: event.customer.account_number,
544
+ email: event.customer.email,
545
+ });
546
+
547
+ if (!row) return { status: 'no_account' };
548
+
549
+ // Use namePoolMatches, not a naive string comparison - see "Name matching" above.
550
+ const providedNames = [event.customer.name, ...event.customer.known_names];
551
+ const nameOk = namePoolMatches(providedNames, row.full_name);
552
+
553
+ return nameOk ? { status: 'match' } : { status: 'no_match' };
554
+ },
555
+ });
556
+ ```
557
+
558
+ The three statuses surface to the consumer as:
559
+
560
+ | Returned | Consumer sees |
561
+ |----------|--------------|
562
+ | `{ status: 'match' }` | ✓ Account found |
563
+ | `{ status: 'no_match' }` | ⚠ Couldn't verify — check your account number (editable, retriable) |
564
+ | `{ status: 'no_account' }` | ✗ No account found (editable, retriable) |
565
+
566
+ 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.
567
+
568
+ 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.
569
+
570
+ ---
571
+
572
+ ## Edge runtime (Cloudflare Workers, Next.js Edge)
573
+
574
+ ```typescript
575
+ import { createOneAddressHandler } from '@oneaddress/partner-sdk/edge';
576
+ ```
577
+
578
+ All exports are available on the `/edge` path. No Node.js-specific APIs are used.
579
+
580
+ ---
581
+
582
+ ## Standalone utilities
583
+
584
+ ```typescript
585
+ import {
586
+ verifySignature, // single-secret HMAC verify
587
+ verifyWithGrace, // two-secret grace-window verify
588
+ decryptAddress, // ECDH + HKDF + AES-GCM decryption (legacy blob)
589
+ decryptSession, // D5 session-envelope decryption
590
+ transformAddress, // decrypt legacy blob then re-encrypt to a different public key (e.g. KMS)
591
+ transformSession, // decrypt D5 session then re-encrypt to a different public key (e.g. KMS)
592
+ readAddressParts, // tolerant address field reader (street/line1/address_line1/…)
593
+ formatAddressParts, // one-line summary of the parts above, for logs + notes
594
+ isFreshTimestamp, // ±5-minute replay-window check
595
+ CURRENT_VERSION, // '2026.1'
596
+ SUPPORTED_VERSIONS, // ['2026.1']
597
+ } from '@oneaddress/partner-sdk';
598
+ ```
599
+
600
+ ### `readAddressParts(raw)` / `formatAddressParts(parts)`
601
+
602
+ Pulls `line1` / `suburb` / `state` / `postcode` / `country` out of a decrypted address regardless
603
+ of which field-name spelling it carries — `street`, `address_line1`, `streetAddress`; `city`,
604
+ `locality`, `town`; `region`, `province`; `postalCode`, `postal_code`, `zip`. Missing parts come
605
+ back as `''` (`country` defaults to `'AU'`), so you can `||` straight into a fallback:
606
+
607
+ ```typescript
608
+ const parts = readAddressParts(data.new_address);
609
+ await db.updateAddress({
610
+ id: row.id,
611
+ line1: parts.line1 || row.line1,
612
+ suburb: parts.suburb || row.suburb,
613
+ postcode: parts.postcode || row.postcode,
614
+ });
615
+ console.log(formatAddressParts(parts)); // "42 Collins Street, Melbourne, VIC, 3000"
616
+ ```
617
+
618
+ This is a **tolerant reader**, not a schema declaration: it describes what the helper accepts and
619
+ says nothing about what OneAddress guarantees to send. Use it instead of hand-rolling the
620
+ `?? ?? ??` ladder — we did that in three receivers and a fix to one silently left the others
621
+ behind.
622
+
623
+ ### `verifySignature(rawBody, signature, timestamp, secret)`
624
+
625
+ Returns `true` if the HMAC-SHA256 signature is valid. Signing formula: `HMAC-SHA256("${timestamp}.${rawBody}")`.
626
+
627
+ ### `isFreshTimestamp(timestamp, toleranceSecs?)`
628
+
629
+ Returns `true` if `timestamp` (Unix seconds string) is within `toleranceSecs` of now. Default tolerance: 300 seconds (±5 minutes). **Always check freshness before signature** — a stale-timestamp check is cheap; a signature verify is not.
630
+
631
+ ### `decryptAddress(payload, privateKeyPem, partnerId)`
632
+
633
+ Decrypts the `address_encrypted` blob using your PKCS#8 ECDH P-256 private key.
634
+
635
+ ### `transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem)`
636
+
637
+ 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.
638
+
639
+ ```typescript
640
+ import { transformAddress } from '@oneaddress/partner-sdk';
641
+
642
+ async onUpdate(event) {
643
+ // Re-encrypt to your KMS key — plaintext never leaves this function
644
+ const kmsBlob = await transformAddress(
645
+ event.raw.address_encrypted as EncryptedPayload,
646
+ process.env.OA_PRIVATE_KEY_PEM!,
647
+ event.partner_id,
648
+ process.env.KMS_PUBLIC_KEY_SPKI_PEM!, // your KMS/HSM SPKI PEM public key
649
+ );
650
+ await db.storeEncryptedAddress(event.customer.account_number, kmsBlob);
651
+ }
652
+ ```
653
+
654
+ Each call generates a fresh ephemeral key pair and random HKDF salt — full forward secrecy, no shared state between calls.
655
+
656
+ ### `transformSession(share, envelopeB64, privateKeyPem, partnerId, recipientSpkiPem)`
657
+
658
+ The **D5 session-envelope** counterpart to `transformAddress`. Decrypts a `session_envelope` (via `decryptSession`) and immediately re-encrypts the recovered `SessionData` to a different ECDH P-256 public key — for example, your internal KMS or HSM. The decrypted session is held in memory only for the duration of the call and is never returned to the caller.
659
+
660
+ Use this for the current dispatch path (session envelopes); use `transformAddress` for the legacy single-blob `address_encrypted` path.
661
+
662
+ ```typescript
663
+ import { transformSession } from '@oneaddress/partner-sdk';
664
+
665
+ async onUpdate(event) {
666
+ const body = event.raw; // the full webhook body
667
+ const myPrivateKey = keyStore.get(body.session_key_share.key_id);
668
+
669
+ // Re-encrypt to your KMS key — the address never leaves this function in plaintext
670
+ const kmsBlob = await transformSession(
671
+ body.session_key_share,
672
+ body.session_envelope,
673
+ myPrivateKey,
674
+ body.partner_id,
675
+ process.env.KMS_PUBLIC_KEY_SPKI_PEM!, // your KMS/HSM SPKI PEM public key
676
+ );
677
+ // Use event.customer (decrypted by the handler), not body.customer - under
678
+ // D5 the raw webhook body carries no cleartext customer block at all.
679
+ await db.storeEncryptedAddress(event.customer.account_number, kmsBlob);
680
+ }
681
+ ```
682
+
683
+ > **Zero plaintext in your app tier.** If your KMS/HSM exposes an ECDH P-256 public key, you can register *that* key as your OneAddress encryption key directly — then the consumer's browser encrypts straight to your KMS and you never need `transformSession` at all. `transformSession` is the bridge for when your OneAddress key and your KMS key differ. The HKDF `info` string differs from `transformAddress` (`oneaddress:transform-session:<partnerId>`) so the two paths never derive the same key.
684
+
685
+ ---
686
+
687
+ ## Protocol versioning
688
+
689
+ The SDK warns (but does not reject) if it receives a protocol version it doesn't recognise:
690
+
691
+ ```
692
+ [OneAddress SDK] Unrecognised protocol version "2027.1".
693
+ Supported: 2026.1. Update @oneaddress/partner-sdk to the latest version.
694
+ ```
695
+
696
+ This ensures you keep receiving events while updating your SDK. See `SUPPORTED_VERSIONS` to check which versions the installed SDK build supports.
697
+
698
+ ---
699
+
700
+ ## Testing your integration
701
+
702
+ **Quick smoke test** — send a single test webhook from the Partner Portal (Profile → Test Webhook).
703
+
704
+ **Full conformance suite** — run 10 checks against your endpoint using real crypto, no mocks:
705
+
706
+ ```bash
707
+ # Against a live endpoint
708
+ npx @oneaddress/conformance test https://your-endpoint.com/webhook --secret whsec_...
709
+
710
+ # Against a local server (run from the machine where the server is running)
711
+ npx @oneaddress/conformance test http://localhost:3001/webhook
712
+ ```
713
+
714
+ Or use the **Integration Conformance** card in the Partner Portal to run the same checks against your configured webhook URL from within the portal.