@oneaddress/partner-sdk 1.8.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,58 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.0.0] - 2026-09-16
11
+
12
+ A major version because `OneAddressUpdateEvent.address` is now optional (see
13
+ Changed below): a TypeScript integration that dereferences it without
14
+ narrowing stops compiling on upgrade, and that is the intended outcome.
15
+ Runtime behaviour for an integration that declares nothing is unchanged.
16
+
17
+ ### Added
18
+
19
+ - **`acceptedUpdateTypes`: the receiver declares, in code, which kinds of
20
+ changed detail it can handle** (`address`, `phone`, `email`; default
21
+ address-only). The declaration rides every authenticated 2xx acknowledgement
22
+ as `accepted_update_types`, so the conformance run can read it, probe each
23
+ declared kind, probe an undeclared one and require a refusal, and fail the
24
+ run when the partner portal promises a kind the code did not declare. It is
25
+ withheld from a 401, so an unsigned caller learns nothing.
26
+ - **`contact.updated` is handled**, routed to the same `onUpdate` as
27
+ `address.updated`. The relay has sent it for a phone-only or email-only
28
+ dispatch since 14 Aug 2026, and every SDK build before this one acknowledged
29
+ it as an unknown event with `200 { ok: true, skipped: true }`, storing
30
+ nothing. `HANDLED_EVENTS` extended to match.
31
+ - `OneAddressUpdateEvent` gains `update_types` (literal; absent means
32
+ `['address']`), `new_phone` (E.164) and `new_email` (lowercased).
33
+
34
+ ### Changed
35
+
36
+ - **`OneAddressUpdateEvent.address` is now optional.** A contact-only update
37
+ genuinely has none. A TypeScript integration that dereferences
38
+ `event.address` without narrowing stops compiling on upgrade, which is the
39
+ intended outcome: that is exactly the code that would throw on its first
40
+ `contact.updated`. An integration that declares nothing never receives the
41
+ absent case at runtime. Versioning note for whoever cuts the release: this
42
+ is a type-level breaking change.
43
+ - A kind the envelope names that this build does not know is refused with
44
+ `422 invalid_update_types` rather than dropped. A kind the receiver did not
45
+ declare is refused with `422 update_type_not_accepted` before `onUpdate`
46
+ runs, leaving the idempotency claim incomplete so the retry after widening
47
+ the declaration is reprocessed. A declared kind whose value is missing from
48
+ the envelope is a fault (500, retried), not an update with a hole in it.
49
+
50
+ ### Security
51
+
52
+ - **`sendVerifyResult` pins the callback host to `oneaddress.io` and its
53
+ subdomains.** `isSafeWebhookUrl` refused SSRF targets but permitted any
54
+ public host, and `callback_url` arrives on the wire, so a leaked webhook
55
+ secret let a forged `address.verify` make the partner's own server POST the
56
+ callback token, batch id and match result to a host the attacker controls.
57
+ Every generated scaffold already pinned the host; the SDK's own `onVerify`
58
+ path did not, so delegating to the SDK was a silent downgrade. Near-miss
59
+ hostnames are refused. `OA_CALLBACK_HOST_ALLOWLIST` and `allowedCallbackHosts`
60
+ exist for staging and self-hosted relays only.
61
+
10
62
  ## [1.8.0] - 2026-08-25
11
63
 
12
64
  ### Added
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 OneAddress Pty Ltd
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -31,6 +31,11 @@ export const handler = createOneAddressHandler({
31
31
  webhookSecret: process.env.OA_WEBHOOK_SECRET!,
32
32
  privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
33
33
 
34
+ // Which kinds of changed detail THIS CODE can handle. Address only is the
35
+ // default. Declare phone or email only once onUpdate stores them; see
36
+ // "Phone and email updates" below.
37
+ acceptedUpdateTypes: ['address'],
38
+
34
39
  async onUpdate(event) {
35
40
  // event.address is already decrypted. event.customer.email is always ''
36
41
  // on this event (OneAddress never learns a consumer's email for a
@@ -96,6 +101,75 @@ export { handler as POST };
96
101
 
97
102
  ---
98
103
 
104
+ ## Phone and email updates
105
+
106
+ *Available from 2.0.0.*
107
+
108
+ A OneAddress dispatch can carry a new **postal address**, a new **telephone
109
+ number** or a new **email address**, alone or together. Two things decide what
110
+ you receive:
111
+
112
+ 1. **Consent**, ticked by a person in the partner portal (`accepted_update_types`).
113
+ 2. **Capability**, declared by this code with `acceptedUpdateTypes`.
114
+
115
+ A kind is dispatched to you only where BOTH hold, and the conformance run is
116
+ what ties them together: it reads your declaration off your first
117
+ acknowledgement, sends a real contact-only envelope for every kind you declared,
118
+ sends one kind you did NOT declare and requires you to refuse it, and fails the
119
+ run if the portal promises a kind this code has not declared.
120
+
121
+ ```typescript
122
+ export const handler = createOneAddressHandler({
123
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
124
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
125
+ acceptedUpdateTypes: ['address', 'phone', 'email'],
126
+
127
+ async onUpdate(event) {
128
+ const account = event.customer?.account_number;
129
+ if (!account) throw new Error('Dispatch carried no account number to match on');
130
+
131
+ // `update_types` says what is inside; read it rather than probing fields.
132
+ // A phone-only change arrives as ['phone'] with NO address at all.
133
+ if (event.address) await db.updateAddress(account, event.address);
134
+ if (event.new_phone) await db.updatePhone(account, event.new_phone); // E.164
135
+ if (event.new_email) await db.updateEmail(account, event.new_email); // lowercased
136
+ },
137
+ });
138
+ ```
139
+
140
+ What the handler guarantees:
141
+
142
+ | Situation | Response | `onUpdate` |
143
+ |---|---|---|
144
+ | Every kind in the envelope is declared | `200 { ok: true, accepted_update_types }` | runs |
145
+ | A kind you did not declare | `422 update_type_not_accepted` | never runs |
146
+ | A kind name this SDK build does not know | `422 invalid_update_types` | never runs |
147
+ | `contact.updated` without a session envelope | `400 missing_session_envelope` | never runs |
148
+
149
+ - **`address.updated` vs `contact.updated`.** A dispatch carrying an address is
150
+ `address.updated` exactly as before, whether or not a contact detail rides
151
+ beside it. One carrying no address is `contact.updated`. Both reach the same
152
+ `onUpdate`; route on `update_types`, not on the event name.
153
+ - **`event.address` is optional now.** Every dispatch that existed before
154
+ September 2026 has one, and if you declare nothing you will never see the
155
+ absent case, but TypeScript will ask you to narrow: bind it to a local and
156
+ check it, or test it with `if` as the example does.
157
+ - **`update_types` is literal.** `['phone']` means the phone number changed and
158
+ nothing else. It is never widened to include `address`.
159
+ - **Refusal is deliberate.** Acknowledging a kind you cannot store would look
160
+ identical to success on both sides while the consumer has already paid. The
161
+ 422 leaves the dispatch incomplete in your idempotency store, so once you
162
+ widen `acceptedUpdateTypes` OneAddress's retry is processed rather than
163
+ dismissed as a duplicate.
164
+ - **`accepted_update_types` rides every authenticated 2xx.** It is how the
165
+ conformance run discovers what you declared. It is never included in a 401,
166
+ so an unsigned caller learns nothing about your receiver.
167
+ - **Declare a kind only once you store it.** The conformance run can prove your
168
+ code ACCEPTED a phone-only envelope. It cannot see whether your outbox has a
169
+ column for the number.
170
+
171
+ ---
172
+
99
173
  ## D5 — session-envelope decryption (added in v1.3.0)
100
174
 
101
175
  OneAddress is rolling out a new dispatch architecture (D5 + D1 + D2 in the design doc) where each `address.updated` webhook carries:
@@ -628,6 +702,20 @@ await sendVerifyResult({
628
702
  (OneAddress skips the dispatch) and `match: false → 'mismatch' + address_match false`
629
703
  (the update proceeds). It throws if the callback POST returns a non-2xx status.
630
704
 
705
+ ### The callback host is pinned
706
+
707
+ `callback_url` arrives on the wire, so it is only as trustworthy as the webhook
708
+ secret. The SDK has always refused SSRF targets (loopback, private ranges, cloud
709
+ metadata) but would POST to any public host, which meant a leaked secret let an
710
+ attacker forge an `address.verify` and have your server send the callback token,
711
+ batch id and match result wherever they liked. `sendVerifyResult` now posts only
712
+ to `https://oneaddress.io` or a subdomain of it, and near-miss hostnames
713
+ (`notoneaddress.io`, `evil-oneaddress.io`, `oneaddress.io.evil.com`) are
714
+ refused. For a staging or self-hosted relay, name the extra host in
715
+ `OA_CALLBACK_HOST_ALLOWLIST` (comma-separated) or pass `allowedCallbackHosts` to
716
+ `sendVerifyResult` or `createOneAddressHandler`. Every host you add is a host a
717
+ forged request could reach, so keep it empty in production.
718
+
631
719
  ---
632
720
 
633
721
  ## Account verification (pre-payment, guest flow)
@@ -670,7 +758,7 @@ The three statuses surface to the consumer as:
670
758
  | Returned | Consumer sees |
671
759
  |----------|--------------|
672
760
  | `{ status: 'match' }` | ✓ Account found |
673
- | `{ status: 'no_match' }` | ⚠ Couldn't verify — check your account number (editable, retriable) |
761
+ | `{ status: 'no_match' }` | Couldn't verify — check your account number (editable, retriable) |
674
762
  | `{ status: 'no_account' }` | ✗ No account found (editable, retriable) |
675
763
 
676
764
  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.
@@ -822,3 +910,13 @@ npx @oneaddress/conformance test http://localhost:3001/webhook
822
910
  ```
823
911
 
824
912
  Or use the **Integration Conformance** card in the Partner Portal to run the same checks against your configured webhook URL from within the portal.
913
+
914
+ ## Licence
915
+
916
+ Apache License 2.0. See [LICENSE](./LICENSE).
917
+
918
+ Apache-2.0 rather than MIT deliberately: it carries an **express patent grant**,
919
+ bounded to this package. OneAddress holds a pending patent application over the
920
+ address-change notification architecture, and this SDK is the recipient half of
921
+ it. Partners using it is the entire point, so an explicit, bounded grant is
922
+ clearer for you than MIT's silence on patents.
@@ -3178,6 +3178,64 @@ function isSafeWebhookUrl(url, opts2 = {}) {
3178
3178
  return { ok: true };
3179
3179
  }
3180
3180
 
3181
+ // ../crypto/src/endpoint-health.ts
3182
+ var ENDPOINT_FAILURE_THRESHOLD = 3;
3183
+ var MISSING_STATUSES = /* @__PURE__ */ new Set([404, 405, 410]);
3184
+ function classifyEndpointProbe(input) {
3185
+ const status = typeof input.httpStatus === "number" && Number.isFinite(input.httpStatus) ? input.httpStatus : null;
3186
+ if (status === null || status === 0) {
3187
+ const detail = input.error ? `: ${input.error}` : "";
3188
+ return {
3189
+ health: "unreachable",
3190
+ dispatchable: false,
3191
+ summary: `No response from the endpoint${detail}. Check the host is running and reachable.`
3192
+ };
3193
+ }
3194
+ if (status >= 200 && status < 300) {
3195
+ return {
3196
+ health: "healthy",
3197
+ dispatchable: true,
3198
+ summary: `Receiver accepted a signed test request (HTTP ${status}).`
3199
+ };
3200
+ }
3201
+ if (status === 401 || status === 403) {
3202
+ return {
3203
+ health: "auth",
3204
+ dispatchable: false,
3205
+ summary: `Receiver rejected our signature (HTTP ${status}). Check the signing secret matches on both sides.`
3206
+ };
3207
+ }
3208
+ if (MISSING_STATUSES.has(status)) {
3209
+ return {
3210
+ health: "missing",
3211
+ dispatchable: false,
3212
+ summary: `Host answered but no receiver is listening at this path (HTTP ${status}). A stopped tunnel or a stale URL looks exactly like this.`
3213
+ };
3214
+ }
3215
+ if (status === 429) {
3216
+ return {
3217
+ health: "throttled",
3218
+ dispatchable: false,
3219
+ summary: `Receiver is up and rate-limiting us (HTTP 429). Back off and retry, or raise the ceiling; nothing is wrong with the URL.`
3220
+ };
3221
+ }
3222
+ if (status >= 500) {
3223
+ return {
3224
+ health: "degraded",
3225
+ dispatchable: false,
3226
+ summary: `Receiver is present but erroring (HTTP ${status}).`
3227
+ };
3228
+ }
3229
+ return {
3230
+ health: "rejected",
3231
+ dispatchable: false,
3232
+ summary: `Receiver refused the request (HTTP ${status}).`
3233
+ };
3234
+ }
3235
+ function countsAsFailure(verdict) {
3236
+ return !verdict.dispatchable;
3237
+ }
3238
+
3181
3239
  // ../crypto/src/partner-key-attestation.ts
3182
3240
  var PARTNER_KEY_ATTESTATION_V1 = "oneaddress-partner-key-attestation:v1";
3183
3241
  var PARTNER_KEY_ATTESTATION_ALG = "ECDSA-P256";
@@ -3259,6 +3317,8 @@ async function verifyPartnerKeyAttestationWithRoots(input, signatureHex, rootKey
3259
3317
 
3260
3318
  // ../crypto/src/registry-head.ts
3261
3319
  var REGISTRY_HEAD_V1 = "oneaddress-partner-key-registry-head:v1";
3320
+ var REGISTRY_HEAD_V2 = "oneaddress-partner-key-registry-head:v2";
3321
+ var KNOWN_VERSIONS = /* @__PURE__ */ new Set([REGISTRY_HEAD_V1, REGISTRY_HEAD_V2]);
3262
3322
  var REGISTRY_HEAD_ALG = "ECDSA-P256";
3263
3323
  function assertNoLineBreak(field, value) {
3264
3324
  if (typeof value !== "string" || value.length === 0) {
@@ -3275,6 +3335,9 @@ function assertMapSafe(field, value) {
3275
3335
  }
3276
3336
  }
3277
3337
  function buildRegistryHeadStatement(payload) {
3338
+ if (!KNOWN_VERSIONS.has(payload.version)) {
3339
+ throw new Error(`[registry-head] unknown head version: ${String(payload.version)}`);
3340
+ }
3278
3341
  assertNoLineBreak("issued_at", payload.issued_at);
3279
3342
  assertNoLineBreak("expires_at", payload.expires_at);
3280
3343
  assertMapSafe("root_key_id", payload.root_key_id);
@@ -3291,14 +3354,42 @@ function buildRegistryHeadStatement(payload) {
3291
3354
  }
3292
3355
  seen.add(partnerId);
3293
3356
  }
3294
- return [
3295
- REGISTRY_HEAD_V1,
3357
+ const lines = [
3358
+ payload.version,
3296
3359
  `issued_at:${payload.issued_at}`,
3297
3360
  `expires_at:${payload.expires_at}`,
3298
3361
  `root_key_id:${payload.root_key_id}`,
3299
3362
  `heads:${entries.length}`,
3300
3363
  ...entries.map(([partnerId, keyId]) => `${partnerId}:${keyId}`)
3301
- ].join("\n");
3364
+ ];
3365
+ if (payload.version === REGISTRY_HEAD_V1) {
3366
+ if (payload.staged && Object.keys(payload.staged).length > 0) {
3367
+ throw new Error("[registry-head] v1 statement cannot carry staged entries");
3368
+ }
3369
+ return lines.join("\n");
3370
+ }
3371
+ const stagedEntries = Object.entries(payload.staged ?? {}).map(([partnerId, entry]) => {
3372
+ assertMapSafe("staged partner_id", partnerId);
3373
+ assertMapSafe("staged key_id", entry?.key_id);
3374
+ assertMapSafe("staged key_sha256", entry?.key_sha256);
3375
+ if (!/^[0-9a-f]{64}$/i.test(entry.key_sha256)) {
3376
+ throw new Error(`[registry-head] staged key_sha256 must be 64 hex chars: ${partnerId}`);
3377
+ }
3378
+ return [partnerId.toLowerCase(), entry.key_id.toLowerCase(), entry.key_sha256.toLowerCase()];
3379
+ });
3380
+ stagedEntries.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
3381
+ const stagedSeen = /* @__PURE__ */ new Set();
3382
+ for (const [partnerId] of stagedEntries) {
3383
+ if (stagedSeen.has(partnerId)) {
3384
+ throw new Error(`[registry-head] duplicate partner_id in staged: ${partnerId}`);
3385
+ }
3386
+ stagedSeen.add(partnerId);
3387
+ }
3388
+ lines.push(`staged:${stagedEntries.length}`);
3389
+ for (const [partnerId, keyId, digest] of stagedEntries) {
3390
+ lines.push(`${partnerId}:${keyId}:${digest}`);
3391
+ }
3392
+ return lines.join("\n");
3302
3393
  }
3303
3394
  function b64ToBytes2(b64) {
3304
3395
  const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
@@ -3319,7 +3410,7 @@ function hexToBytes4(hex) {
3319
3410
  }
3320
3411
  async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date()) {
3321
3412
  try {
3322
- if (doc?.version !== REGISTRY_HEAD_V1) return "malformed";
3413
+ if (!doc || !KNOWN_VERSIONS.has(doc.version)) return "malformed";
3323
3414
  if (doc.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
3324
3415
  if (typeof doc.signature !== "string" || !/^[0-9a-f]{128}$/i.test(doc.signature)) return "malformed";
3325
3416
  if (!doc.heads || typeof doc.heads !== "object") return "malformed";
@@ -3334,7 +3425,14 @@ async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date())
3334
3425
  issued_at: doc.issued_at,
3335
3426
  expires_at: doc.expires_at,
3336
3427
  root_key_id: doc.root_key_id,
3337
- heads: doc.heads
3428
+ heads: doc.heads,
3429
+ // Passed through rather than dropped: the staged map is part of what the
3430
+ // root signed on a v2 head, so omitting it here would rebuild different
3431
+ // bytes and report `bad-signature` on a perfectly good document. On a v1
3432
+ // head the builder REFUSES a non-empty map, which lands here as
3433
+ // `malformed` — the right answer for a document claiming staged keys its
3434
+ // signature does not cover.
3435
+ staged: doc.staged
3338
3436
  });
3339
3437
  const rootKey = await crypto.subtle.importKey(
3340
3438
  "spki",
@@ -3360,6 +3458,27 @@ function headNamesKey(doc, partnerId, keyId) {
3360
3458
  const named = doc.heads?.[partnerId.toLowerCase()];
3361
3459
  return typeof named === "string" && named.toLowerCase() === keyId.toLowerCase();
3362
3460
  }
3461
+ function headNamesPartner(doc, partnerId) {
3462
+ return typeof doc.heads?.[partnerId.toLowerCase()] === "string";
3463
+ }
3464
+ async function partnerKeyFingerprint(publicKeyB64) {
3465
+ const digest = await crypto.subtle.digest(
3466
+ "SHA-256",
3467
+ b64ToBytes2(publicKeyB64)
3468
+ );
3469
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
3470
+ }
3471
+ async function headNamesStagedKey(doc, partnerId, keyId, publicKeyB64) {
3472
+ try {
3473
+ const entry = doc.staged?.[partnerId.toLowerCase()];
3474
+ if (!entry || typeof entry.key_id !== "string" || typeof entry.key_sha256 !== "string") return false;
3475
+ if (entry.key_id.toLowerCase() !== keyId.toLowerCase()) return false;
3476
+ if (!/^[0-9a-f]{64}$/i.test(entry.key_sha256)) return false;
3477
+ return await partnerKeyFingerprint(publicKeyB64) === entry.key_sha256.toLowerCase();
3478
+ } catch {
3479
+ return false;
3480
+ }
3481
+ }
3363
3482
 
3364
3483
  // ../crypto/src/index.ts
3365
3484
  function b64ToBytes3(b64) {
@@ -3381,7 +3500,15 @@ function keyB64ToBytes(key) {
3381
3500
  function bytesToB64(bytes) {
3382
3501
  return btoa(String.fromCodePoint(...bytes));
3383
3502
  }
3384
- var subtle = () => globalThis.crypto.subtle;
3503
+ var subtle = () => {
3504
+ const webcrypto = globalThis.crypto;
3505
+ if (!webcrypto?.subtle) {
3506
+ throw new Error(
3507
+ "Web Crypto is unavailable in this runtime, so no encryption or key operation can run. In Node this needs version 19 or later, where globalThis.crypto is enabled by default (Node 18 has it behind --experimental-global-webcrypto, and is itself end-of-life). Check with `node -v` and upgrade, or re-run with NODE_OPTIONS=--experimental-global-webcrypto as a one-off."
3508
+ );
3509
+ }
3510
+ return webcrypto.subtle;
3511
+ };
3385
3512
  async function importP256PublicKey(keyBytes) {
3386
3513
  if (keyBytes.length === 65 && keyBytes[0] === 4) {
3387
3514
  return subtle().importKey(
@@ -3761,13 +3888,18 @@ async function encryptSessionForAll(partners) {
3761
3888
  );
3762
3889
  return Object.fromEntries(results.map((r) => [r.partner_id, r]));
3763
3890
  }
3764
- async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3891
+ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expectedAlg) {
3765
3892
  if (share.alg !== "ECDH-ES+HKDF-SHA256+A256GCM" && share.alg !== "RSA-OAEP-256+A256GCM" && share.alg !== "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3766
3893
  throw new Error(`decryptSession: unsupported alg ${share.alg}`);
3767
3894
  }
3768
3895
  if (share.v !== 2) {
3769
3896
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
3770
3897
  }
3898
+ if (expectedAlg && share.alg !== expectedAlg) {
3899
+ throw new Error(
3900
+ `decryptSession: algorithm downgrade - the dispatch wraps SK_n as ${share.alg}, but this key is provisioned for ${expectedAlg}. Refusing rather than attempting a different wrap than the recipient chose.`
3901
+ );
3902
+ }
3771
3903
  const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
3772
3904
  if (ops) {
3773
3905
  if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
@@ -4001,6 +4133,9 @@ export {
4001
4133
  isFreshTimestamp,
4002
4134
  isIpLiteralHost,
4003
4135
  isSafeWebhookUrl,
4136
+ ENDPOINT_FAILURE_THRESHOLD,
4137
+ classifyEndpointProbe,
4138
+ countsAsFailure,
4004
4139
  PARTNER_KEY_ATTESTATION_V1,
4005
4140
  PARTNER_KEY_ATTESTATION_ALG,
4006
4141
  buildPartnerKeyAttestation,
@@ -4009,10 +4144,14 @@ export {
4009
4144
  verifyPartnerKeyAttestation,
4010
4145
  verifyPartnerKeyAttestationWithRoots,
4011
4146
  REGISTRY_HEAD_V1,
4147
+ REGISTRY_HEAD_V2,
4012
4148
  REGISTRY_HEAD_ALG,
4013
4149
  buildRegistryHeadStatement,
4014
4150
  verifyRegistryHead,
4015
4151
  headNamesKey,
4152
+ headNamesPartner,
4153
+ partnerKeyFingerprint,
4154
+ headNamesStagedKey,
4016
4155
  normaliseAddress,
4017
4156
  generatePartnerKeyPair,
4018
4157
  generateHybridPartnerKeyPair,