@oneaddress/partner-sdk 1.2.0 → 1.3.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,482 @@
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
+ ---
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.3.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, verified name, known-names, 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 per-partner `loa_encrypted` — the signed Letter of Authority, encrypted with the SAME scheme + key as the address envelope (`{ session_envelope, session_key_share }`).
49
+
50
+ > **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).
51
+
52
+ Decrypt via `decryptSession`:
53
+
54
+ ```typescript
55
+ import { decryptSession } from '@oneaddress/partner-sdk';
56
+
57
+ const data = await decryptSession(
58
+ body.session_key_share,
59
+ body.session_envelope,
60
+ myPrivateKeyForKeyId, // looked up by share.key_id from your key store
61
+ body.partner_id, // your partner UUID, used in HKDF info binding
62
+ );
63
+
64
+ // data.new_address.street, data.account_number, data.verified_name, etc.
65
+ ```
66
+
67
+ `decryptSession` handles **both** wrap schemes transparently — it routes on `share.alg` and you just supply the private key matching `share.key_id`:
68
+
69
+ - **`ECDH-ES+HKDF-SHA256+A256GCM`** (default) — your key is ECDH P-256; supply your P-256 PKCS#8 private key.
70
+ - **`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.
71
+ - **`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.
72
+
73
+ In all schemes the `session_envelope` is identical (AES-256-GCM under SK<sub>n</sub>) — only the SK<sub>n</sub> wrap differs.
74
+
75
+ ### Decrypting + verifying the Letter of Authority
76
+
77
+ 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:
78
+
79
+ ```typescript
80
+ import { decryptLoaEncrypted, verifyD5LOA, d5LoaRef, fetchLoaPublicKey } from '@oneaddress/partner-sdk';
81
+
82
+ const loa = await decryptLoaEncrypted(body.loa_encrypted, myPrivateKeyForKeyId, body.partner_id);
83
+ const loaKey = await fetchLoaPublicKey(); // cache this
84
+ if (!(await verifyD5LOA(loa, loaKey))) throw new Error('LOA signature invalid');
85
+
86
+ // Echo the ref in your /api/confirm POST so OneAddress can confirm you decrypted
87
+ // a valid signed consent. It carries no name in the clear.
88
+ await fetch(confirmUrl, { method: 'POST', /* …auth… */,
89
+ body: JSON.stringify({ dispatch_id, partner_id, status: 'confirmed', loa_ref: d5LoaRef(loa) }) });
90
+ ```
91
+
92
+ 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).
93
+
94
+ > **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.
95
+
96
+ ### Key versioning + retention obligations
97
+
98
+ 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.
99
+
100
+ **Your contractual obligations:**
101
+
102
+ 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.
103
+ 2. **Retain** the `session_key_share` object alongside the update record until `key_share_expiry`. After that date OneAddress will not request reconstruction.
104
+ 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.
105
+
106
+ See `docs/PARTNER_INTEGRATION.md` for the full integration spec.
107
+
108
+ ### Legacy ECDH still supported
109
+
110
+ 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`:
111
+
112
+ ```typescript
113
+ if (body.session_envelope) {
114
+ const data = await decryptSession(body.session_key_share, body.session_envelope, myKey, body.partner_id);
115
+ } else {
116
+ const data = await decryptAddress(body.address_encrypted, myKey, body.partner_id);
117
+ }
118
+ ```
119
+
120
+ The legacy helper is deprecated and will be removed in v1.3.x after all OneAddress dispatches have migrated to D5.
121
+
122
+ ---
123
+
124
+ ## Blind-index matching (zero-plaintext record matching)
125
+
126
+ > **Superseded by the "no cleartext" mandate.** OneAddress no longer emits a
127
+ > cleartext `customer` block **or** a `customer_match` block on `address.updated`
128
+ > dispatches — identity now travels only inside the encrypted `session_envelope`.
129
+ > The `computeBlindIndex` / `normalizeForBlindIndex` helpers remain exported for
130
+ > partners who still use blind indexes for their own internal matching, but the
131
+ > dispatch payload no longer carries `customer_match`. Match on the decrypted
132
+ > `verified_name` / `known_names` / `account_number` instead. The section below
133
+ > is retained for historical reference.
134
+
135
+ By default each webhook carries a cleartext `customer` block (`name` / `email` /
136
+ `account_number` / `known_names`) so you can locate your record before
137
+ decrypting the address. If you enable **blind-index matching** in the partner
138
+ portal, OneAddress sends a `customer_match` block **instead** — each value is
139
+ `base64url(HMAC-SHA256(yourBlindIndexSecret, normalize(field)))`. No plaintext
140
+ name/email/account crosses the wire, and you can still match **without
141
+ decrypting** the envelope.
142
+
143
+ ```typescript
144
+ import { computeBlindIndex } from '@oneaddress/partner-sdk';
145
+
146
+ // One-time: backfill a blind-index column on your records.
147
+ // email_bidx = computeBlindIndex(secret, 'email', record.email)
148
+ // Then, on each webhook:
149
+ async function onUpdate(event) {
150
+ const m = event.customer_match; // present when blind-index is enabled
151
+ if (m) {
152
+ const emailIdx = await computeBlindIndex(process.env.OA_BLIND_INDEX_SECRET!, 'email', '' /* n/a — you query by index */);
153
+ const record =
154
+ m.email ? await db.findByEmailBidx(m.email)
155
+ : m.account_number ? await db.findByAccountBidx(m.account_number)
156
+ : await db.findByAnyNameBidx(m.names); // match if ANY name index hits
157
+ // ... then decryptSession(...) to get the new address.
158
+ } else {
159
+ // Cleartext path (default): match on event.customer.
160
+ }
161
+ }
162
+ ```
163
+
164
+ **The blind-index secret** is generated and shown in the portal (Encryption Key →
165
+ Blind-index matching). It is distinct from your webhook/confirm/setup secrets.
166
+
167
+ **Normalisation is part of the contract** — always compute indexes with the
168
+ SDK's `computeBlindIndex` (or `normalizeForBlindIndex`), never by hand:
169
+
170
+ | Field | Normalisation |
171
+ | --- | --- |
172
+ | `email` | NFKC · trim · lowercase |
173
+ | `name` | NFKC · trim · lowercase · collapse internal whitespace |
174
+ | `account_number` | NFKC · trim · remove all whitespace · **case preserved** |
175
+
176
+ `customer_match.names` holds one index per name (legal name + each known-name
177
+ alias); match if **any** of your stored name indexes appears in it.
178
+
179
+ ---
180
+
181
+ ## Idempotency — handling retries
182
+
183
+ 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:
184
+
185
+ ```typescript
186
+ async onUpdate(event) {
187
+ if (event.dispatchId) {
188
+ const seen = await db.dispatches.exists({ dispatchId: event.dispatchId });
189
+ if (seen) return; // idempotent no-op
190
+ }
191
+
192
+ await db.updateAddress({ email: event.customer.email, ...event.address });
193
+
194
+ if (event.dispatchId) {
195
+ await db.dispatches.insert({ dispatchId: event.dispatchId });
196
+ }
197
+ }
198
+ ```
199
+
200
+ `dispatchId` falls back to `''` (empty string) if the header is absent — always guard before using it as a key.
201
+
202
+ > **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.
203
+ >
204
+ > **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.
205
+
206
+ ---
207
+
208
+ ## Identity verification attestation
209
+
210
+ 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:
211
+
212
+ ```typescript
213
+ async onUpdate(event) {
214
+ if (event.id_verification) {
215
+ // The outer block confirms the update was IDV-authorised, but carries
216
+ // no identifying reference. It is safe to log for audit/compliance.
217
+ logger.info('IDV-authorised dispatch', {
218
+ method: event.id_verification.method, // 'identity_document'
219
+ verified_at: event.id_verification.verified_at,
220
+ });
221
+ }
222
+ }
223
+ ```
224
+
225
+ | Field | Description |
226
+ |---|---|
227
+ | `method` | `identity_document` when the customer completed a document + biometric check; `mock` in sandbox builds. Carries no underlying-provider identity. |
228
+ | `verified_at` | ISO-8601 timestamp the verification was completed. |
229
+ | `verified` | Always `true` when the block is present. |
230
+ | `platform` | Format tag — currently `oneaddress/v1`. |
231
+
232
+ The block is absent on `BYPASS_STRIPE` test flows where no IDV credit was consumed. Production dispatches always include it.
233
+
234
+ ### The verification reference lives inside the encrypted envelope
235
+
236
+ 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`:
237
+
238
+ ```typescript
239
+ import { decryptSession, type SessionData } from '@oneaddress/partner-sdk';
240
+
241
+ const session = await decryptSession(
242
+ event.raw.session_key_share,
243
+ event.raw.session_envelope,
244
+ process.env.OA_PRIVATE_KEY_PEM!,
245
+ process.env.OA_PARTNER_ID!,
246
+ ) as SessionData;
247
+
248
+ // Persist the ref against your record of the update — it never travels
249
+ // in the clear and is only computable after you decrypt the envelope.
250
+ await db.updateAddress({
251
+ ...event.address,
252
+ verification_ref: session.id_verification_ref,
253
+ });
254
+ ```
255
+
256
+ ---
257
+
258
+ ## Secret rotation grace window
259
+
260
+ 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:
261
+
262
+ ```typescript
263
+ export const handler = createOneAddressHandler({
264
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
265
+ previousWebhookSecret: process.env.OA_PREVIOUS_WEBHOOK_SECRET,
266
+ webhookSecretGraceUntil: process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL, // ISO-8601
267
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
268
+ async onUpdate(event) { /* ... */ },
269
+ });
270
+ ```
271
+
272
+ Once `webhookSecretGraceUntil` passes, the previous secret is ignored automatically. You can then remove those two env vars.
273
+
274
+ ### Standalone `verifyWithGrace`
275
+
276
+ If you're not using the handler factory, use `verifyWithGrace` directly instead of calling `verifySignature` twice:
277
+
278
+ ```typescript
279
+ import { verifyWithGrace, isFreshTimestamp } from '@oneaddress/partner-sdk';
280
+
281
+ // Replay check first — before signature verify
282
+ if (!isFreshTimestamp(req.headers['x-oneaddress-timestamp'])) {
283
+ return res.status(400).json({ error: 'Stale timestamp' });
284
+ }
285
+
286
+ const ok = verifyWithGrace(
287
+ rawBody,
288
+ req.headers['x-oneaddress-timestamp'],
289
+ req.headers['x-oneaddress-signature'],
290
+ process.env.OA_WEBHOOK_SECRET!,
291
+ process.env.OA_PREVIOUS_WEBHOOK_SECRET,
292
+ process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL,
293
+ );
294
+ if (!ok) return res.status(401).json({ error: 'Invalid signature' });
295
+ ```
296
+
297
+ ---
298
+
299
+ ## Address verification events
300
+
301
+ Implement `onVerify` to respond to consumer address-match checks:
302
+
303
+ ```typescript
304
+ export const handler = createOneAddressHandler({
305
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
306
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
307
+
308
+ async onUpdate(event) { /* ... */ },
309
+
310
+ async onVerify(event) {
311
+ const stored = await db.getAddress({ email: event.customer.email });
312
+ const match = stored?.street === event.address.street &&
313
+ stored?.postcode === event.address.postcode;
314
+ return { match, note: match ? undefined : 'Address does not match our records' };
315
+ },
316
+ });
317
+ ```
318
+
319
+ ---
320
+
321
+ ## Account verification (pre-payment, guest flow)
322
+
323
+ 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.
324
+
325
+ 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.
326
+
327
+ ```typescript
328
+ export const handler = createOneAddressHandler({
329
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
330
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
331
+
332
+ async onUpdate(event) { /* ... */ },
333
+
334
+ async onAccountVerify(event) {
335
+ // event.customer = { email, name, known_names, account_number }
336
+ const row = await db.findCustomer({
337
+ accountNumber: event.customer.account_number,
338
+ email: event.customer.email,
339
+ });
340
+
341
+ if (!row) return { status: 'no_account' };
342
+
343
+ const nameOk = row.full_name.toLowerCase() === event.customer.name.toLowerCase()
344
+ || event.customer.known_names.some(
345
+ (alias) => row.full_name.toLowerCase() === alias.toLowerCase(),
346
+ );
347
+
348
+ return nameOk ? { status: 'match' } : { status: 'no_match' };
349
+ },
350
+ });
351
+ ```
352
+
353
+ The three statuses surface to the consumer as:
354
+
355
+ | Returned | Consumer sees |
356
+ |----------|--------------|
357
+ | `{ status: 'match' }` | ✓ Account found |
358
+ | `{ status: 'no_match' }` | ⚠ Couldn't verify — check your account number (editable, retriable) |
359
+ | `{ status: 'no_account' }` | ✗ No account found (editable, retriable) |
360
+
361
+ 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.
362
+
363
+ 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.
364
+
365
+ ---
366
+
367
+ ## Edge runtime (Cloudflare Workers, Next.js Edge)
368
+
369
+ ```typescript
370
+ import { createOneAddressHandler } from '@oneaddress/partner-sdk/edge';
371
+ ```
372
+
373
+ All exports are available on the `/edge` path. No Node.js-specific APIs are used.
374
+
375
+ ---
376
+
377
+ ## Standalone utilities
378
+
379
+ ```typescript
380
+ import {
381
+ verifySignature, // single-secret HMAC verify
382
+ verifyWithGrace, // two-secret grace-window verify
383
+ decryptAddress, // ECDH + HKDF + AES-GCM decryption (legacy blob)
384
+ decryptSession, // D5 session-envelope decryption
385
+ transformAddress, // decrypt legacy blob then re-encrypt to a different public key (e.g. KMS)
386
+ transformSession, // decrypt D5 session then re-encrypt to a different public key (e.g. KMS)
387
+ isFreshTimestamp, // ±5-minute replay-window check
388
+ CURRENT_VERSION, // '2026.1'
389
+ SUPPORTED_VERSIONS, // ['2026.1']
390
+ } from '@oneaddress/partner-sdk';
391
+ ```
392
+
393
+ ### `verifySignature(rawBody, signature, timestamp, secret)`
394
+
395
+ Returns `true` if the HMAC-SHA256 signature is valid. Signing formula: `HMAC-SHA256("${timestamp}.${rawBody}")`.
396
+
397
+ ### `isFreshTimestamp(timestamp, toleranceSecs?)`
398
+
399
+ 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.
400
+
401
+ ### `decryptAddress(payload, privateKeyPem, partnerId)`
402
+
403
+ Decrypts the `address_encrypted` blob using your PKCS#8 ECDH P-256 private key.
404
+
405
+ ### `transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem)`
406
+
407
+ 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.
408
+
409
+ ```typescript
410
+ import { transformAddress } from '@oneaddress/partner-sdk';
411
+
412
+ async onUpdate(event) {
413
+ // Re-encrypt to your KMS key — plaintext never leaves this function
414
+ const kmsBlob = await transformAddress(
415
+ event.raw.address_encrypted as EncryptedPayload,
416
+ process.env.OA_PRIVATE_KEY_PEM!,
417
+ event.partner_id,
418
+ process.env.KMS_PUBLIC_KEY_SPKI_PEM!, // your KMS/HSM SPKI PEM public key
419
+ );
420
+ await db.storeEncryptedAddress(event.customer.email, kmsBlob);
421
+ }
422
+ ```
423
+
424
+ Each call generates a fresh ephemeral key pair and random HKDF salt — full forward secrecy, no shared state between calls.
425
+
426
+ ### `transformSession(share, envelopeB64, privateKeyPem, partnerId, recipientSpkiPem)`
427
+
428
+ 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.
429
+
430
+ Use this for the current dispatch path (session envelopes); use `transformAddress` for the legacy single-blob `address_encrypted` path.
431
+
432
+ ```typescript
433
+ import { transformSession } from '@oneaddress/partner-sdk';
434
+
435
+ async onUpdate(event) {
436
+ const body = event.raw; // the full webhook body
437
+ const myPrivateKey = keyStore.get(body.session_key_share.key_id);
438
+
439
+ // Re-encrypt to your KMS key — the address never leaves this function in plaintext
440
+ const kmsBlob = await transformSession(
441
+ body.session_key_share,
442
+ body.session_envelope,
443
+ myPrivateKey,
444
+ body.partner_id,
445
+ process.env.KMS_PUBLIC_KEY_SPKI_PEM!, // your KMS/HSM SPKI PEM public key
446
+ );
447
+ await db.storeEncryptedAddress(body.customer.email, kmsBlob);
448
+ }
449
+ ```
450
+
451
+ > **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.
452
+
453
+ ---
454
+
455
+ ## Protocol versioning
456
+
457
+ The SDK warns (but does not reject) if it receives a protocol version it doesn't recognise:
458
+
459
+ ```
460
+ [OneAddress SDK] Unrecognised protocol version "2027.1".
461
+ Supported: 2026.1. Update @oneaddress/partner-sdk to the latest version.
462
+ ```
463
+
464
+ This ensures you keep receiving events while updating your SDK. See `SUPPORTED_VERSIONS` to check which versions the installed SDK build supports.
465
+
466
+ ---
467
+
468
+ ## Testing your integration
469
+
470
+ **Quick smoke test** — send a single test webhook from the Partner Portal (Profile → Test Webhook).
471
+
472
+ **Full conformance suite** — run 10 checks against your endpoint using real crypto, no mocks:
473
+
474
+ ```bash
475
+ # Against a live endpoint
476
+ npx @oneaddress/conformance test https://your-endpoint.com/webhook --secret whsec_...
477
+
478
+ # Against a local server (run from the machine where the server is running)
479
+ npx @oneaddress/conformance test http://localhost:3001/webhook
480
+ ```
481
+
482
+ Or use the **Integration Conformance** card in the Partner Portal to run the same checks against your configured webhook URL from within the portal.