@oneaddress/partner-sdk 2.9.0 → 2.11.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,7 +7,70 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ## [2.9.0] - unreleased (repo bump only, not published)
10
+ ## [2.11.0] - 2026-11-30
11
+
12
+ ### Fixed: what the docs say happens to a confirm `note`
13
+
14
+ - The `note` on `confirmUpdate`, the `onUpdate` result and `sendVerifyResult` is kept only when it is a short code such as `crm_updated`, and the consumer sees a kept code beside the result. Any other text is replaced by OneAddress's own sentence for the status. The docs had said the note was free text for OneAddress support and never shown to the consumer. Documentation only.
15
+
16
+ ### Fixed: the LOA key fetch no longer follows redirects
17
+
18
+ - `fetchLoaPublicKey` (and so `cachedLoaPublicKey` and the handler's default key lookup) refuses a redirect rather than following it, and gives up after 10 seconds. The host allowlist is checked on the URL asked for, so a followed redirect could have served the key that consent proofs are verified against from another host. The Java and C# SDKs already refused redirects.
19
+
20
+
21
+ ### Added: `isIsoDate`
22
+
23
+ - The `YYYY-MM-DD` check the handler applies to a body's `effective_date`, exported so code that calls `decryptSession` itself refuses the same values before calling `assertEffectiveDateBound`.
24
+
25
+ ### Added: the account check for RSA-OAEP and X-Wing keys
26
+
27
+ - `account.verify` now opens `customer_encrypted` in either shape. An ECDH key still receives the single blob opened with `decryptAddress`. An RSA-OAEP or X-Wing key receives the shape `loa_encrypted` uses (`session_envelope` and `session_key_share`), opened with `decryptSession`, so it also works through a `PrivateKeyOperations` delegate. Until now OneAddress could not seal an account check to an RSA-OAEP or X-Wing key at all. Vectors: `account_check_sealed`.
28
+
29
+ ## [2.10.0] - 2026-11-06
30
+
31
+ ### Added: the confirm names the SDK version
32
+
33
+ - Every confirm sends `X-OneAddress-Client: partner-sdk-ts/<version>`. Software name and version only, outside the signature. OneAddress records it after the confirm verifies and the partner portal shows whether an update exists.
34
+
35
+ ### Added: a read-only update check
36
+
37
+ - `startUpdateCheck()`, `checkForUpdate()` and `updateCheckMetric()`: ask the public registry, at most once a day, whether a newer SDK is published, and log one line, `update available: X -> Y, see <guide URL>`, when it is. Opt-in (nothing runs unless you start it), sends no identifying data, never installs anything, and `ONEADDRESS_UPDATE_CHECK=off` stops it.
38
+
39
+ ### Added: a signed answer to the connection verification
40
+
41
+ - **An indexed `address.test` / `address.test-dispatch` is answered with
42
+ `commitment`** beside `verification: true`: lowercase hex HMAC-SHA256, keyed
43
+ with the webhook secret that verified the request (the previous one inside a
44
+ rotation grace window), over one canonical string of the verification id,
45
+ the record index and the DECRYPTED name and structured address. OneAddress
46
+ recomputes it over the record it sent and records the verification itself,
47
+ so going live no longer rests on a bare `verification: true` and nobody has
48
+ to paste a block from the logs. Automatic when `onTest` is wired. A health
49
+ probe (no index) gets no commitment.
50
+ - **`computeVerificationCommitment`**, **`verificationCommitmentString`**,
51
+ **`normaliseCommitmentField`** and **`VERIFICATION_COMMITMENT_VERSION`**, for a
52
+ receiver that answers `address.test` without the handler. Checked against the
53
+ `verification_commitment` vectors the Python, Go, Java and C# SDKs share.
54
+ - **`matchingWebhookSecret`**: which secret verified a request, or null.
55
+ `verifyWithGrace` is now a wrapper over it and answers exactly as before.
56
+
57
+ ### Added: `product` on product-line accounts
58
+
59
+ - **`OneAddressUpdateEvent.product`** (`{ id, code, name }` or `null`), the partner
60
+ product line the customer's account sits under, sealed in the envelope beside
61
+ `account_number`. Route on `code`. `null` for a plain account and on legacy dispatches.
62
+ - **`SessionData.product`**, the same value from `decryptSession`, plus
63
+ `readSessionProduct` and `PRODUCT_CODE_PATTERN`.
64
+ - **Read tolerantly.** A `product` that is not an object, lacks a string `id` or
65
+ `code`, or has a `code` outside `^[a-z0-9][a-z0-9_-]{0,39}$` reads as `null` with a
66
+ warning, and the update is still handled. A missing `name` reads as the `code`.
67
+ Validated against the shared `session_product` vectors.
68
+
69
+ ## [2.9.0] - 2026-10-31
70
+
71
+ Published at registry timestamp `2026-10-31T17:14:06.672Z`. The tarball carries the heading this line
72
+ replaced, "unreleased (repo bump only, not published)", because the record is written after
73
+ the publish.
11
74
 
12
75
  ### Added: `effective_date` on scheduled moves
13
76
 
package/README.md CHANGED
@@ -482,7 +482,7 @@ const res = await confirmUpdate({
482
482
  secret: process.env.OA_CONFIRM_SECRET!, // see "which secret" below
483
483
  dispatchId: event.dispatchId, // from X-OneAddress-Dispatch
484
484
  status: 'confirmed',
485
- note: 'Applied to CRM record', // never the address itself
485
+ note: 'crm_updated', // a short code, never the address
486
486
  });
487
487
 
488
488
  if (!res.ok) console.error('[oneaddress] confirm failed', res.status, res.error);
@@ -494,7 +494,7 @@ if (!res.ok) console.error('[oneaddress] confirm failed', res.status, res.error)
494
494
  | --- | --- |
495
495
  | `confirmed` | You applied the change. |
496
496
  | `already_current` | You already held that address; nothing to write. **Not a failure** — return it honestly rather than reporting `confirmed`. |
497
- | `failed` | Your system could not apply it. OneAddress retries, and a run of these makes the update our fault and refunds the consumer. Send a `note` saying why (what happened, never the address). |
497
+ | `failed` | Your system could not apply it. OneAddress retries, and a run of these makes the update our fault and refunds the consumer. Send a `note` code saying why (what happened, never the address). |
498
498
  | `no_match` | You looked, and this person is not a customer of yours. Nothing is broken and retrying cannot help, so the consumer is told to check their account reference with you. No refund is triggered. |
499
499
 
500
500
  The last two cost different people money. `failed` for a stranger bills a refund against a receiver that behaved correctly; `no_match` during a real outage tells a genuine customer to fix an account number that was never wrong. **If you cannot tell the two apart, send `failed`**, which is the one that is safe to be wrong about.
@@ -507,7 +507,7 @@ A dispatch can carry an address together with a new phone number or email addres
507
507
 
508
508
  **The first confirmation for a dispatch is the one that counts.** All four statuses resolve to a terminal record, and a later confirm for the same `dispatchId` cannot move it. That guard is deliberate, so a retry or a replay cannot turn a recorded success into a failure — but it also means two calls cannot report two kinds separately. The second is a no-op on what the consumer sees, not a correction.
509
509
 
510
- `note` is free text and is kept, so it can say what did not apply. Nothing is driven off it: the consumer's dashboard reads the status alone.
510
+ `note` is optional. OneAddress keeps it only when it is a short code such as `crm_updated`: a letter first, then letters, digits or `_ . : -`, up to 64 characters, with no run of five or more digits. Any other text is replaced by OneAddress's own sentence for the status. A kept code is shown to the consumer beside the result, on their dashboard and in their Transmission Report. Nothing is driven off it: the status alone decides what happens next.
511
511
 
512
512
  ### Which secret
513
513
 
@@ -545,15 +545,16 @@ What each response status means to us:
545
545
  |---|---|---|
546
546
  | `2xx` (and no `ok: false`) | delivered, awaiting your confirm | Wait for `confirmUpdate`. |
547
547
  | `400` | partner error | Retry on the backoff. A malformed request cannot be fixed by retrying, but the class of problem (a stale timestamp, a body that is not JSON) usually clears on the next attempt. |
548
- | `401` or `403` | **auth failed** | **Not retried.** See the warning below. |
548
+ | `401` | **auth failed** | **Not retried.** See the warning below. |
549
+ | `403` | partner error | Retry on the backoff. A WAF or proxy in front of your receiver answers 403 for its own rules (rate, geography, a bot check), which usually clears. |
549
550
  | `422` | partner error | Retry. The handler sends this for a kind you have not declared in `acceptedUpdateTypes`; once you widen the declaration the retry is processed. |
550
551
  | `500` | partner error | Retry. This is what the handler answers for a decrypt failure, a missing or invalid consent proof, or a throwing `onUpdate`, and it is the right answer for anything you want retried. |
551
552
  | no response / timeout | unreachable | Retry. |
552
553
 
553
- > **A 401 or 403 ends the delivery. It is not retried, and this README said the
554
+ > **A 401 ends the delivery. It is not retried, and this README said the
554
555
  > opposite until 5 October 2026.**
555
556
  >
556
- > Those two statuses are the only ones we read as a **rejected signature**, and
557
+ > That status is the only one we read as a **rejected signature**, and
557
558
  > a rejected signature does not fix itself: nothing about waiting and sending
558
559
  > the same bytes again makes them verify. So the dispatch is parked in the
559
560
  > `auth_failed` state and the retry cron excludes it from its candidate set.
@@ -571,7 +572,7 @@ What each response status means to us:
571
572
  > broken signing deploy or an unsynced secret - and worth telling us about
572
573
  > rather than waiting out.
573
574
 
574
- Every 4xx EXCEPT 401 and 403 is filed as "partner error" and retried; 401 and 403 are filed as "auth failed" and are not. Either way a 4xx you send deliberately reads, to the consumer, as a problem between you and OneAddress. Prefer a 500 for "try again" and a confirm of `no_match` for "not my customer".
575
+ Every 4xx EXCEPT 401 is filed as "partner error" and retried; a 401 is filed as "auth failed" and is not. A 403 was filed with 401 until 13 November 2026. Either way a 4xx you send deliberately reads, to the consumer, as a problem between you and OneAddress. Prefer a 500 for "try again" and a confirm of `no_match` for "not my customer".
575
576
 
576
577
  ---
577
578
 
@@ -840,6 +841,20 @@ The customer's device also seals the move date inside the envelope. The handler
840
841
 
841
842
  Rehearse it with `buildSignedTestWebhook({ ..., effectiveDate: '2026-12-07' })`, which puts the date in the body and seals it in the session.
842
843
 
844
+ ## Product lines and `product`
845
+
846
+ If you set up product lines in the partner portal (home and car insurance, say), the customer picks one when they add their account, and it is sealed in the envelope beside the account number. Route on its `code`, which is your own key and survives a rename:
847
+
848
+ ```ts
849
+ onUpdate: async (event) => {
850
+ // null for a plain account.
851
+ const queue = event.product?.code ?? 'default';
852
+ await queues[queue].push(event.customer, event.address);
853
+ },
854
+ ```
855
+
856
+ `event.product` is `{ id, code, name }` or `null`. A malformed sealed value is read as `null` (and logged as a warning), never as a refusal, so a sender fault cannot lose a change of address. `decryptSession` exposes the same field as `session.product`.
857
+
843
858
  ## Secret rotation grace window
844
859
 
845
860
  **Rotate with an overlap.** Staging a new secret in the Partner Portal does **not** change what we sign with: we keep using your current secret until you press *Switch over*. So the safe sequence is stage, deploy the new secret alongside the current one, verify with both, then switch. At every point the secret we sign with is one your receiver already holds.
@@ -973,7 +988,7 @@ forged request could reach, so keep it empty in production.
973
988
 
974
989
  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.
975
990
 
976
- 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.
991
+ The payload carries **no address**, only the customer identity block (name / known-names / account number), and it travels **encrypted** as `customer_encrypted`, never in cleartext: the legacy ECDH blob for an ECDH key, or the shape `loa_encrypted` uses (`session_envelope` and `session_key_share`) for an RSA-OAEP or X-Wing key. `createOneAddressHandler` decrypts it for you and populates `event.customer`. The consumer is waiting for your response, so reply synchronously within 10 seconds.
977
992
 
978
993
  ```typescript
979
994
  export const handler = createOneAddressHandler({
@@ -1213,7 +1228,7 @@ The address is encrypted to you and to nobody else. Four ways to undo that, each
1213
1228
 
1214
1229
  - **Never log the plaintext address**, at any level, in any format. A log line is a copy at rest with no retention policy and a wider audience than your database.
1215
1230
  - **Never persist the plaintext address anywhere but the record it belongs to.** Not a debug table, not a queue payload, not a crash dump. `transformSession` exists so an outbox can hold it re-encrypted to your own key.
1216
- - **Never put the address in a confirm `note`.** The note travels back to OneAddress in the clear and is stored there. Say what happened, not what the address was.
1231
+ - **Never put the address in a confirm `note`.** The note travels back to OneAddress in the clear, and a code in it is shown to the consumer. Say what happened, not what the address was.
1217
1232
  - **Never route a test record to `onUpdate`.** `address.test` and `address.test-dispatch` carry fabricated identities and go to `onTest`; the handler keeps them apart, and so must anything you build beside it.
1218
1233
  - **Never skip the idempotency store in production.** Retries are normal (28 over 48 hours); without a store each one applies the update again. The handler will tell you once, in the log, and then keep going.
1219
1234
 
@@ -1367,6 +1382,27 @@ npx @oneaddress/conformance test http://localhost:3001/webhook
1367
1382
 
1368
1383
  Or use the **Integration Conformance** card in the Partner Portal to run the same checks against your configured webhook URL from within the portal.
1369
1384
 
1385
+ ## Update check
1386
+
1387
+ Call it once at startup and the SDK tells you when a newer version is published. It never installs anything: a receiver holds your decryption key, so updating stays a change you review and deploy.
1388
+
1389
+ ```ts
1390
+ import { startUpdateCheck } from '@oneaddress/partner-sdk';
1391
+
1392
+ const updates = startUpdateCheck(); // logs one line via console.warn
1393
+ // in /metrics: updateCheckMetric(updates.current())
1394
+ ```
1395
+
1396
+ - Asks npm (`registry.npmjs.org/@oneaddress/partner-sdk/latest`) for one version number, at most once a day, in the background.
1397
+ - Sends a plain GET with no partner id and no identifying header.
1398
+ - When behind, logs one line: `update available: X -> Y, see https://partners.oneaddress.io/#updating-safely`.
1399
+ - A refused connection or a proxy 403 logs nothing.
1400
+ - `ONEADDRESS_UPDATE_CHECK=off` stops it. It does not run unless you start it.
1401
+
1402
+ Each confirm also sends `X-OneAddress-Client: partner-sdk-ts/<version>`, which names this SDK and its version and nothing about you or your customers. The partner portal's Webhook screen uses it to show when an update exists.
1403
+
1404
+ We recommend against auto-updating a receiver. The guide linked above covers upgrading and rolling back.
1405
+
1370
1406
  ## Licence
1371
1407
 
1372
1408
  Apache License 2.0. See [LICENSE](./LICENSE).
@@ -3901,6 +3901,11 @@ function isFreshTimestamp(timestampHeader, toleranceSecs = DEFAULT_REPLAY_WINDOW
3901
3901
  return Math.abs(now - ts) <= toleranceSecs;
3902
3902
  }
3903
3903
 
3904
+ // ../crypto/src/refund-review-notify.ts
3905
+ function refundReviewNotifySigningString(timestamp, rawBody) {
3906
+ return `oneaddress.refund-review-notify.v1.${timestamp}.${rawBody}`;
3907
+ }
3908
+
3904
3909
  // ../crypto/src/safe-url.ts
3905
3910
  var BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
3906
3911
  "localhost",
@@ -4137,11 +4142,18 @@ function classifyEndpointProbe(input) {
4137
4142
  summary: `Receiver accepted a signed test request (HTTP ${status}).`
4138
4143
  };
4139
4144
  }
4140
- if (status === 401 || status === 403) {
4145
+ if (status === 401) {
4141
4146
  return {
4142
4147
  health: "auth",
4143
4148
  dispatchable: false,
4144
- summary: `Receiver rejected our signature (HTTP ${status}). Check the signing secret matches on both sides.`
4149
+ summary: `Receiver rejected our signature (HTTP 401). Check the signing secret matches on both sides.`
4150
+ };
4151
+ }
4152
+ if (status === 403) {
4153
+ return {
4154
+ health: "rejected",
4155
+ dispatchable: false,
4156
+ summary: `Something in front of the receiver refused the request (HTTP 403), usually a firewall rule on rate, location or bots. Our signature is refused with a 401, not this.`
4145
4157
  };
4146
4158
  }
4147
4159
  if (MISSING_STATUSES.has(status)) {
@@ -4258,18 +4270,49 @@ async function verifyPartnerKeyAttestationWithRoots(input, signatureHex, rootKey
4258
4270
  }
4259
4271
 
4260
4272
  // ../crypto/src/registry-root-pin.ts
4261
- var PINNED_REGISTRY_ROOTS = Object.freeze([
4262
- Object.freeze({
4263
- root_key_id: "rk1_251368ec9b0a84ae",
4264
- spki_sha256: "251368ec9b0a84ae9881533bd1687efb7d439edd927aef47c1bb3bb069b3dc1d"
4265
- })
4273
+ var PRODUCTION_REGISTRY_HOSTS = Object.freeze([
4274
+ "oneaddress.io",
4275
+ "www.oneaddress.io",
4276
+ "app.oneaddress.io"
4266
4277
  ]);
4278
+ function registryEnvironmentForOrigin(origin) {
4279
+ let o = origin ?? "";
4280
+ if (!o) {
4281
+ const loc = globalThis.location;
4282
+ o = loc?.origin ?? "";
4283
+ }
4284
+ if (!o) return "preview";
4285
+ try {
4286
+ const host = new URL(o).hostname.toLowerCase().replace(/\.$/, "");
4287
+ return PRODUCTION_REGISTRY_HOSTS.includes(host) ? "production" : "preview";
4288
+ } catch {
4289
+ return "preview";
4290
+ }
4291
+ }
4292
+ var PRODUCTION_ROOT = Object.freeze({
4293
+ root_key_id: "rk1_251368ec9b0a84ae",
4294
+ spki_sha256: "251368ec9b0a84ae9881533bd1687efb7d439edd927aef47c1bb3bb069b3dc1d"
4295
+ });
4296
+ var REGISTRY_ROOT_PINS = Object.freeze({
4297
+ production: Object.freeze([PRODUCTION_ROOT]),
4298
+ preview: Object.freeze([
4299
+ Object.freeze({
4300
+ root_key_id: "rk1_4690d67464893d48",
4301
+ spki_sha256: "4690d67464893d48ebb335bcd29f3203fbacefbc69afd8a047b639521296bfab"
4302
+ })
4303
+ ])
4304
+ });
4305
+ var PINNED_REGISTRY_ROOTS = REGISTRY_ROOT_PINS.production;
4267
4306
  var overrideForTests = null;
4268
4307
  function __setPinnedRegistryRootsForTests(pins) {
4269
4308
  overrideForTests = pins;
4270
4309
  }
4271
- function pinnedRegistryRoots() {
4272
- return overrideForTests ?? PINNED_REGISTRY_ROOTS;
4310
+ function pinnedRegistryRoots(env = "production") {
4311
+ if (overrideForTests) {
4312
+ if (Array.isArray(overrideForTests)) return overrideForTests;
4313
+ return overrideForTests[env] ?? [];
4314
+ }
4315
+ return REGISTRY_ROOT_PINS[env];
4273
4316
  }
4274
4317
  function b64ToBytes2(b64) {
4275
4318
  const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
@@ -4282,20 +4325,20 @@ async function spkiSha256HexFromB64(spkiB64) {
4282
4325
  const digest = await crypto.subtle.digest("SHA-256", b64ToBytes2(spkiB64));
4283
4326
  return bytesToHex3(new Uint8Array(digest));
4284
4327
  }
4285
- async function rootIsPinned(root) {
4328
+ async function rootIsPinned(root, env = "production") {
4286
4329
  try {
4287
4330
  const digest = await spkiSha256HexFromB64(root.public_key_b64);
4288
- return pinnedRegistryRoots().some(
4331
+ return pinnedRegistryRoots(env).some(
4289
4332
  (p) => p.root_key_id === root.root_key_id && p.spki_sha256 === digest
4290
4333
  );
4291
4334
  } catch {
4292
4335
  return false;
4293
4336
  }
4294
4337
  }
4295
- async function unpinnedRootIds(roots) {
4338
+ async function unpinnedRootIds(roots, env = "production") {
4296
4339
  const out = [];
4297
4340
  for (const root of roots) {
4298
- if (!await rootIsPinned(root)) out.push(String(root?.root_key_id ?? "(no id)"));
4341
+ if (!await rootIsPinned(root, env)) out.push(String(root?.root_key_id ?? "(no id)"));
4299
4342
  }
4300
4343
  return out;
4301
4344
  }
@@ -4482,6 +4525,30 @@ async function headNamesStagedKey(doc, partnerId, keyId, publicKeyB64) {
4482
4525
  // ../crypto/src/verify-partner-keys.ts
4483
4526
  var ACCEPTABLE = /* @__PURE__ */ new Set(["ok", "exempt"]);
4484
4527
  var EMPTY_BOUND = /* @__PURE__ */ new Set();
4528
+ function localStorageHeadHighWater(key = "oa-registry-head-issued-at") {
4529
+ return {
4530
+ read() {
4531
+ try {
4532
+ return globalThis.localStorage?.getItem(key) ?? null;
4533
+ } catch {
4534
+ return null;
4535
+ }
4536
+ },
4537
+ write(issuedAt) {
4538
+ try {
4539
+ globalThis.localStorage?.setItem(key, issuedAt);
4540
+ } catch {
4541
+ }
4542
+ }
4543
+ };
4544
+ }
4545
+ function isOlderThan(candidate, mark) {
4546
+ if (!mark) return false;
4547
+ const m = Date.parse(mark);
4548
+ const c = Date.parse(candidate);
4549
+ if (Number.isNaN(m)) return false;
4550
+ return Number.isNaN(c) || c < m;
4551
+ }
4485
4552
  async function saysRootNotConfigured(res) {
4486
4553
  if (res.status !== 503) return false;
4487
4554
  try {
@@ -4517,19 +4584,61 @@ async function crossoverOutcomeFor(partnerId, crossover, reg) {
4517
4584
  if (!reg.head) return "head-unusable";
4518
4585
  return await headNamesStagedKey(reg.head, partnerId, crossover.key_id, crossover.public_key_b64) ? "ok" : "not-authorised";
4519
4586
  }
4587
+ function refuseAll(keys, outcome) {
4588
+ const blocked = {};
4589
+ const crossoverBlocked = {};
4590
+ try {
4591
+ for (const [partnerId, key] of Object.entries(keys ?? {})) {
4592
+ blocked[partnerId] = outcome;
4593
+ if (key?.crossover) crossoverBlocked[partnerId] = "head-unusable";
4594
+ }
4595
+ } catch {
4596
+ }
4597
+ return { blocked, crossoverBlocked };
4598
+ }
4520
4599
  function createPartnerKeyVerifier(env = {}) {
4521
4600
  const baseUrl = env.baseUrl ?? "";
4522
- const report = env.report ?? (() => {
4523
- });
4601
+ const report = (context, detail) => {
4602
+ try {
4603
+ env.report?.(context, detail);
4604
+ } catch {
4605
+ }
4606
+ };
4524
4607
  let registryPromise = null;
4525
4608
  function worthCaching(load) {
4526
4609
  return load.ok && load.registry.head !== null;
4527
4610
  }
4611
+ async function readMark() {
4612
+ try {
4613
+ const v = await env.headHighWater?.read();
4614
+ return typeof v === "string" ? v : null;
4615
+ } catch {
4616
+ return null;
4617
+ }
4618
+ }
4619
+ async function writeMark(issuedAt) {
4620
+ try {
4621
+ await env.headHighWater?.write(issuedAt);
4622
+ } catch {
4623
+ }
4624
+ }
4625
+ async function judgeHead(headRes, roots) {
4626
+ if (!headRes.ok) return { head: null, headVerdict: "absent" };
4627
+ let head;
4628
+ try {
4629
+ head = await headRes.json();
4630
+ } catch {
4631
+ return { head: null, headVerdict: "unreadable" };
4632
+ }
4633
+ const headVerdict = await verifyRegistryHead(head, roots);
4634
+ return headVerdict === "ok" ? { head, headVerdict } : { head: null, headVerdict };
4635
+ }
4528
4636
  async function loadRegistry() {
4529
4637
  try {
4638
+ const headUrl = baseUrl + "/.well-known/oneaddress-key-registry-head.json";
4530
4639
  const [rootsRes, headRes] = await Promise.all([
4531
4640
  fetch(baseUrl + "/.well-known/oneaddress-key-registry.json", { cache: "no-cache" }),
4532
- fetch(baseUrl + "/.well-known/oneaddress-key-registry-head.json", { cache: "no-cache" })
4641
+ fetch(headUrl, { cache: "no-cache" })
4533
4642
  ]);
4534
4643
  if (!rootsRes.ok) {
4535
4644
  const configured = await saysRootNotConfigured(rootsRes);
@@ -4551,16 +4660,30 @@ function createPartnerKeyVerifier(env = {}) {
4551
4660
  if (roots.length === 0) {
4552
4661
  return { ok: false, failure: { reason: "roots-empty", status: rootsRes.status } };
4553
4662
  }
4554
- const unpinnedRoots = await unpinnedRootIds(roots);
4663
+ const unpinnedRoots = await unpinnedRootIds(roots, registryEnvironmentForOrigin(baseUrl));
4555
4664
  if (unpinnedRoots.length > 0) {
4556
4665
  return { ok: true, registry: { roots: [], head: null, headVerdict: "root-unpinned", unpinnedRoots } };
4557
4666
  }
4558
- let head = null;
4559
- let headVerdict = "absent";
4560
- if (headRes.ok) {
4561
- head = await headRes.json();
4562
- headVerdict = await verifyRegistryHead(head, roots);
4563
- if (headVerdict !== "ok" && headVerdict !== "expired") head = null;
4667
+ let { head, headVerdict } = await judgeHead(headRes, roots);
4668
+ if (head) {
4669
+ const mark = await readMark();
4670
+ if (isOlderThan(head.issued_at, mark)) {
4671
+ let fresh = { head: null, headVerdict: "absent" };
4672
+ try {
4673
+ fresh = await judgeHead(
4674
+ await fetch(`${headUrl}?fresh=${Date.now()}`, { cache: "reload" }),
4675
+ roots
4676
+ );
4677
+ } catch {
4678
+ }
4679
+ if (fresh.head && !isOlderThan(fresh.head.issued_at, mark)) {
4680
+ ({ head, headVerdict } = fresh);
4681
+ } else {
4682
+ head = null;
4683
+ headVerdict = "rolled-back";
4684
+ }
4685
+ }
4686
+ if (head && head.issued_at !== mark) await writeMark(head.issued_at);
4564
4687
  }
4565
4688
  return { ok: true, registry: { roots, head, headVerdict, unpinnedRoots: [] } };
4566
4689
  } catch {
@@ -4573,8 +4696,8 @@ function createPartnerKeyVerifier(env = {}) {
4573
4696
  const load = await pending;
4574
4697
  if (!worthCaching(load)) registryPromise = null;
4575
4698
  if (!load.ok) {
4576
- report(context, { registry: "unavailable", enforced: false, ...load.failure });
4577
- return { blocked: {}, crossoverBlocked: {} };
4699
+ report(context, { registry: "unavailable", enforced: true, ...load.failure });
4700
+ return refuseAll(keys, "registry-unavailable");
4578
4701
  }
4579
4702
  const reg = load.registry;
4580
4703
  let bound = EMPTY_BOUND;
@@ -4595,6 +4718,7 @@ function createPartnerKeyVerifier(env = {}) {
4595
4718
  "not-in-head": [],
4596
4719
  "head-unusable": [],
4597
4720
  "root-unpinned": [],
4721
+ "registry-unavailable": [],
4598
4722
  "error": []
4599
4723
  };
4600
4724
  const blocked = {};
@@ -4646,8 +4770,8 @@ function createPartnerKeyVerifier(env = {}) {
4646
4770
  }
4647
4771
  return { blocked, crossoverBlocked };
4648
4772
  } catch {
4649
- report(context, { registry: "verifier-error", enforced: false });
4650
- return { blocked: {}, crossoverBlocked: {} };
4773
+ report(context, { registry: "verifier-error", enforced: true });
4774
+ return refuseAll(keys, "error");
4651
4775
  }
4652
4776
  }
4653
4777
  function __resetRegistryCacheForTests() {
@@ -5021,6 +5145,13 @@ async function encryptPayloadForPartner(payload, partner) {
5021
5145
  hkdfSalt: bytesToB64(hkdfSaltBytes)
5022
5146
  };
5023
5147
  }
5148
+ async function encryptAccountCheckForPartner(payload, partner) {
5149
+ if (isRsaScheme(partner.algorithm) || isHybridScheme(partner.algorithm)) {
5150
+ const { session_envelope, session_key_share } = await encryptEnvelopeForPartner(payload, partner);
5151
+ return { session_envelope, session_key_share };
5152
+ }
5153
+ return encryptPayloadForPartner(payload, { partnerId: partner.partner_id, publicKeyB64: partner.public_key_b64 });
5154
+ }
5024
5155
  async function encryptAddressForAll(address, partners) {
5025
5156
  const results = await Promise.all(
5026
5157
  partners.map((p) => encryptAddressForPartner(address, p))
@@ -5461,6 +5592,7 @@ async function verifyWebhookSignature(payload, signature, secret) {
5461
5592
  export {
5462
5593
  DEFAULT_REPLAY_WINDOW_SECS,
5463
5594
  isFreshTimestamp,
5595
+ refundReviewNotifySigningString,
5464
5596
  isIpLiteralHost,
5465
5597
  isSafeWebhookUrl,
5466
5598
  blockedPublicKeyReason,
@@ -5477,6 +5609,9 @@ export {
5477
5609
  rootKeyIdFromSpkiB64,
5478
5610
  verifyPartnerKeyAttestation,
5479
5611
  verifyPartnerKeyAttestationWithRoots,
5612
+ PRODUCTION_REGISTRY_HOSTS,
5613
+ registryEnvironmentForOrigin,
5614
+ REGISTRY_ROOT_PINS,
5480
5615
  PINNED_REGISTRY_ROOTS,
5481
5616
  __setPinnedRegistryRootsForTests,
5482
5617
  pinnedRegistryRoots,
@@ -5492,6 +5627,7 @@ export {
5492
5627
  headNamesPartner,
5493
5628
  partnerKeyFingerprint,
5494
5629
  headNamesStagedKey,
5630
+ localStorageHeadHighWater,
5495
5631
  createPartnerKeyVerifier,
5496
5632
  PARTNER_KEY_REFUSED_MESSAGE,
5497
5633
  SENDER_HELD_KEY_ALGORITHM,
@@ -5510,6 +5646,7 @@ export {
5510
5646
  generateHybridPartnerKeyPair,
5511
5647
  encryptAddressForPartner,
5512
5648
  encryptPayloadForPartner,
5649
+ encryptAccountCheckForPartner,
5513
5650
  encryptAddressForAll,
5514
5651
  decryptAddress,
5515
5652
  encryptSessionForPartner,