@t3foundry/tasra-sdk 0.3.1-next.1 → 0.4.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 +1067 -28
- package/README.md +15 -0
- package/dist/app/approvals.d.ts +66 -4
- package/dist/app/approvals.js +153 -16
- package/dist/app/authorization.d.ts +1 -1
- package/dist/app/authorization.js +1 -1
- package/dist/app/browser.d.ts +63 -0
- package/dist/app/browser.js +242 -0
- package/dist/app/client.d.ts +114 -13
- package/dist/app/client.js +302 -76
- package/dist/app/identity.js +21 -9
- package/dist/app/index.d.ts +28 -3
- package/dist/app/index.js +16 -1
- package/dist/app/memory-store.d.ts +7 -0
- package/dist/app/memory-store.js +55 -0
- package/dist/app/node.d.ts +34 -6
- package/dist/app/node.js +387 -64
- package/dist/app/paid-allowance.d.ts +325 -0
- package/dist/app/paid-allowance.js +1290 -0
- package/dist/app/paid-approval.d.ts +122 -0
- package/dist/app/paid-approval.js +379 -0
- package/dist/app/paid-journal.d.ts +51 -0
- package/dist/app/paid-journal.js +117 -0
- package/dist/app/paid-keys.d.ts +12 -0
- package/dist/app/paid-keys.js +20 -0
- package/dist/app/paid-operation.d.ts +821 -0
- package/dist/app/paid-operation.js +1720 -0
- package/dist/app/paid-reservation.d.ts +157 -0
- package/dist/app/paid-reservation.js +323 -0
- package/dist/app/paid-session.d.ts +147 -0
- package/dist/app/paid-session.js +578 -0
- package/dist/app/payer-queue.d.ts +11 -0
- package/dist/app/payer-queue.js +27 -0
- package/dist/app/policy-bootstrap.d.ts +342 -0
- package/dist/app/policy-bootstrap.js +365 -0
- package/dist/app/policy-operation.d.ts +47 -0
- package/dist/app/policy-operation.js +101 -0
- package/dist/app/ready-slot.d.ts +12 -0
- package/dist/app/ready-slot.js +5 -2
- package/dist/app/rotation-lock.d.ts +38 -0
- package/dist/app/rotation-lock.js +42 -0
- package/dist/app/session-decrypt.d.ts +135 -0
- package/dist/app/session-decrypt.js +335 -0
- package/dist/app/session-grants.d.ts +349 -0
- package/dist/app/session-grants.js +811 -0
- package/dist/app/signing-intents.d.ts +78 -0
- package/dist/app/signing-intents.js +95 -0
- package/dist/app/store-commit.d.ts +63 -0
- package/dist/app/store-commit.js +126 -0
- package/dist/app/store-errors.d.ts +8 -0
- package/dist/app/store-errors.js +11 -0
- package/dist/app/tasra-client.d.ts +2 -0
- package/dist/app/tasra-client.js +1 -1
- package/dist/app/wallet.js +4 -1
- package/dist/auth/holderProof.d.ts +3 -0
- package/dist/auth/holderProof.js +8 -7
- package/dist/auth/verifier.d.ts +4 -2
- package/dist/auth/verifier.js +5 -2
- package/dist/chain/abis/index.d.ts +6178 -4101
- package/dist/chain/abis/index.js +3 -0
- package/dist/chain/abis/keyRegistry.d.ts +256 -0
- package/dist/chain/abis/keyRegistry.js +333 -0
- package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
- package/dist/chain/abis/prepaidFaultOracle.js +413 -0
- package/dist/chain/abis/settlement.d.ts +2203 -703
- package/dist/chain/abis/settlement.js +2685 -764
- package/dist/chain/allowance.d.ts +358 -0
- package/dist/chain/allowance.js +800 -0
- package/dist/chain/billing.d.ts +85 -0
- package/dist/chain/billing.js +197 -0
- package/dist/chain/chainId.d.ts +13 -0
- package/dist/chain/chainId.js +26 -0
- package/dist/chain/client.d.ts +15 -1
- package/dist/chain/client.js +57 -1
- package/dist/chain/commitmentRecovery.d.ts +51 -0
- package/dist/chain/commitmentRecovery.js +38 -0
- package/dist/chain/committeeClient.d.ts +17 -10
- package/dist/chain/committeeClient.js +64 -16
- package/dist/chain/committeeDraw.d.ts +12 -0
- package/dist/chain/committeeDraw.js +56 -0
- package/dist/chain/custodyHealth.d.ts +212 -0
- package/dist/chain/custodyHealth.js +365 -0
- package/dist/chain/deployments.js +2 -0
- package/dist/chain/events.js +2 -0
- package/dist/chain/headFollower.d.ts +77 -0
- package/dist/chain/headFollower.js +219 -0
- package/dist/chain/headPrefetch.d.ts +23 -0
- package/dist/chain/headPrefetch.js +67 -0
- package/dist/chain/index.d.ts +50 -8
- package/dist/chain/index.js +28 -3
- package/dist/chain/keeperExecution.d.ts +44 -0
- package/dist/chain/keeperExecution.js +127 -0
- package/dist/chain/keeperRecovery.d.ts +78 -0
- package/dist/chain/keeperRecovery.js +91 -0
- package/dist/chain/node.d.ts +24 -1
- package/dist/chain/node.js +88 -43
- package/dist/chain/offchain.d.ts +2 -0
- package/dist/chain/paidAgentTransport.d.ts +38 -0
- package/dist/chain/paidAgentTransport.js +1 -0
- package/dist/chain/paidEpoch.d.ts +66 -0
- package/dist/chain/paidEpoch.js +139 -0
- package/dist/chain/paidPacing.d.ts +81 -0
- package/dist/chain/paidPacing.js +136 -0
- package/dist/chain/pinnedReads.d.ts +49 -0
- package/dist/chain/pinnedReads.js +218 -0
- package/dist/chain/prepaid.d.ts +383 -0
- package/dist/chain/prepaid.js +1046 -0
- package/dist/chain/prepaidEscape.d.ts +274 -0
- package/dist/chain/prepaidEscape.js +432 -0
- package/dist/chain/prepaidFault.d.ts +94 -0
- package/dist/chain/prepaidFault.js +148 -0
- package/dist/chain/receipt.d.ts +24 -0
- package/dist/chain/receipt.js +82 -0
- package/dist/chain/registeredAgent.d.ts +68 -3
- package/dist/chain/registeredAgent.js +143 -42
- package/dist/chain/registeredOperation.d.ts +10 -1
- package/dist/chain/registeredOperation.js +18 -3
- package/dist/chain/registeredPaidAgent.d.ts +254 -0
- package/dist/chain/registeredPaidAgent.js +889 -0
- package/dist/chain/registeredRelay.d.ts +31 -1
- package/dist/chain/registeredRelay.js +164 -43
- package/dist/chain/relayVoucher.d.ts +64 -0
- package/dist/chain/relayVoucher.js +69 -0
- package/dist/chain/reservation.d.ts +239 -0
- package/dist/chain/reservation.js +746 -0
- package/dist/chain/reshareRoster.d.ts +64 -0
- package/dist/chain/reshareRoster.js +85 -0
- package/dist/chain/revertReason.d.ts +8 -0
- package/dist/chain/revertReason.js +2 -1
- package/dist/chain/rotationLock.d.ts +130 -0
- package/dist/chain/rotationLock.js +168 -0
- package/dist/chain/serviceRequestPolicy.d.ts +47 -0
- package/dist/chain/serviceRequestPolicy.js +86 -0
- package/dist/chain/services.d.ts +7 -0
- package/dist/chain/services.js +44 -4
- package/dist/chain/slotClient.js +11 -2
- package/dist/chain/slotHandoff.d.ts +81 -0
- package/dist/chain/slotHandoff.js +166 -0
- package/dist/chain/slotSeed.d.ts +47 -5
- package/dist/chain/slotSeed.js +173 -42
- package/dist/chain/verifierSnapshot.d.ts +36 -0
- package/dist/chain/verifierSnapshot.js +197 -0
- package/dist/chain/write.d.ts +111 -21
- package/dist/chain/write.js +378 -146
- package/dist/committee/blsSharing.d.ts +53 -0
- package/dist/committee/blsSharing.js +90 -0
- package/dist/committee/client.d.ts +62 -23
- package/dist/committee/client.js +288 -72
- package/dist/committee/dual-operation.d.ts +165 -0
- package/dist/committee/dual-operation.js +229 -0
- package/dist/committee/dual-sign.d.ts +26 -1
- package/dist/committee/dual-sign.js +85 -7
- package/dist/committee/ecdsa.d.ts +38 -0
- package/dist/committee/ecdsa.js +87 -15
- package/dist/committee/evidence.d.ts +30 -0
- package/dist/committee/evidence.js +65 -0
- package/dist/committee/execution.d.ts +414 -0
- package/dist/committee/execution.js +446 -0
- package/dist/committee/extraction.js +33 -26
- package/dist/committee/index.d.ts +30 -7
- package/dist/committee/index.js +18 -6
- package/dist/committee/keeperExecution.d.ts +37 -0
- package/dist/committee/keeperExecution.js +141 -0
- package/dist/committee/oauth.d.ts +14 -4
- package/dist/committee/oauth.js +17 -5
- package/dist/committee/payment.d.ts +369 -0
- package/dist/committee/payment.js +339 -0
- package/dist/committee/recovery.d.ts +136 -0
- package/dist/committee/recovery.js +204 -0
- package/dist/committee/recoveryJson.d.ts +2 -0
- package/dist/committee/recoveryJson.js +87 -0
- package/dist/committee/request.d.ts +63 -27
- package/dist/committee/request.js +77 -66
- package/dist/committee/session-grant.d.ts +320 -0
- package/dist/committee/session-grant.js +397 -0
- package/dist/committee/status-refresh.d.ts +257 -0
- package/dist/committee/status-refresh.js +619 -0
- package/dist/committee/token.d.ts +163 -15
- package/dist/committee/token.js +247 -10
- package/dist/crypto/bn254.d.ts +70 -0
- package/dist/crypto/bn254.js +222 -0
- package/dist/crypto/ibe.d.ts +32 -0
- package/dist/crypto/ibe.js +56 -8
- package/dist/crypto/index.d.ts +1 -1
- package/dist/crypto/index.js +1 -1
- package/dist/crypto/kem.d.ts +31 -0
- package/dist/crypto/kem.js +113 -7
- package/dist/crypto/recipient.d.ts +75 -0
- package/dist/crypto/recipient.js +107 -0
- package/dist/decryption/client.d.ts +10 -16
- package/dist/decryption/client.js +8 -76
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/decryption/sealed.d.ts +72 -0
- package/dist/decryption/sealed.js +147 -0
- package/dist/decryption/session.d.ts +115 -0
- package/dist/decryption/session.js +358 -0
- package/dist/errors.d.ts +406 -1
- package/dist/errors.js +400 -5
- package/dist/index.d.ts +9 -2
- package/dist/index.js +6 -1
- package/dist/internal/bounded.d.ts +66 -0
- package/dist/internal/bounded.js +126 -0
- package/dist/internal/network.d.ts +4 -0
- package/dist/internal/network.js +40 -0
- package/dist/internal/retryAfter.d.ts +8 -0
- package/dist/internal/retryAfter.js +28 -0
- package/dist/internal/sleep.d.ts +6 -0
- package/dist/internal/sleep.js +15 -0
- package/dist/internal/typedData.d.ts +13 -0
- package/dist/internal/typedData.js +77 -0
- package/dist/internal/viemErrors.d.ts +26 -0
- package/dist/internal/viemErrors.js +49 -0
- package/dist/oid4vp/binding.d.ts +27 -1
- package/dist/oid4vp/binding.js +36 -1
- package/dist/oid4vp/jose.d.ts +4 -2
- package/dist/oid4vp/jose.js +39 -7
- package/dist/oid4vp/request-object.d.ts +61 -4
- package/dist/oid4vp/request-object.js +140 -5
- package/dist/oid4vp/verifier-agent.d.ts +18 -8
- package/dist/oid4vp/verifier-agent.js +48 -6
- package/dist/oid4vp/wallet.d.ts +2 -4
- package/dist/oid4vp/wallet.js +1 -0
- package/dist/retry.d.ts +78 -0
- package/dist/retry.js +137 -0
- package/dist/signing/frost.d.ts +1 -1
- package/dist/verifier-agent/index.d.ts +41 -5
- package/dist/verifier-agent/index.js +124 -9
- package/dist/verifier-agent/payment.d.ts +7 -0
- package/dist/verifier-agent/payment.js +17 -0
- package/docs/api.md +8 -2
- package/docs/application-api.md +25 -2
- package/docs/chain.md +155 -9
- package/docs/consumer-migrations.md +61 -0
- package/docs/encrypted-notes.md +3 -2
- package/docs/encryption.md +4 -2
- package/docs/errors.md +14 -1
- package/docs/flows.md +2 -2
- package/docs/funding.md +902 -0
- package/docs/native-approvals.md +63 -0
- package/docs/reference/README.md +9 -8
- package/docs/reference/app-browser.md +232 -0
- package/docs/reference/app-node.md +38 -8
- package/docs/reference/app.md +4621 -805
- package/docs/reference/chain-node.md +74 -16
- package/docs/reference/chain.md +6740 -1592
- package/docs/reference/committee.md +5630 -987
- package/docs/reference/main.md +1439 -140
- package/docs/reference/oid4vp.md +297 -144
- package/docs/reference/verifier-agent.md +77 -35
- package/docs/signing.md +6 -0
- package/examples/encrypted-notes.ts +21 -6
- package/examples/getting-started.ts +2 -7
- package/examples/live-config.ts +24 -17
- package/package.json +17 -5
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
// Status refresh for an already-issued committee grant (`keykeeper/committee-status-refresh/v1`).
|
|
2
|
+
//
|
|
3
|
+
// A drawn verifier re-attests the holder's credential status for the SAME token, from its own
|
|
4
|
+
// durable issuance record: a fresh `keykeeper/committee-status-attestation/v1` statement over the
|
|
5
|
+
// unchanged token hash. No new token, session, payment or keeper stage exists afterwards; keepers
|
|
6
|
+
// accept the refreshed attestation exactly like the original one.
|
|
7
|
+
//
|
|
8
|
+
// refresh_hash = keccak256("keykeeper/committee-status-refresh/v1"
|
|
9
|
+
// || chain_id (u64 BE) || token_hash (32)
|
|
10
|
+
// || payment_hash (32; all-zero when unpaid)
|
|
11
|
+
// || principal_kind (u8: 1 holder_key, 2 client_execution)
|
|
12
|
+
// || seq (u64 BE) || issued_at (i64 BE))
|
|
13
|
+
//
|
|
14
|
+
// The principal is the one the verifier recorded at issuance: the creator-certified client
|
|
15
|
+
// EXECUTION key of a paid grant (`client_execution`, a 0x-hex Ed25519 signature over the hash),
|
|
16
|
+
// or the holder key (`holder_key`, a compact JWS `typ: keykeeper-status-refresh+jwt` with payload
|
|
17
|
+
// `{"refresh":"0x<hash>"}` and the public key in the header `jwk`).
|
|
18
|
+
//
|
|
19
|
+
// ⚠ NOTHING A REFRESH RETURNS IS TRUSTED UNSIGNED. Every attestation is verified here under the
|
|
20
|
+
// ORIGINAL roster key of a verifier whose signature over the ORIGINAL token verifies; anything
|
|
21
|
+
// else is dropped. Each attestation must sit inside every hard cap of the grant minus the keeper
|
|
22
|
+
// skew (`status_until + 5 <= cap`). The merge keeps, per verifier index, the later `status_until`;
|
|
23
|
+
// a refresh succeeds only when the MERGED set (new attestations plus, in direct mode, the
|
|
24
|
+
// still-eligible originals) meets the keeper rule: the quorum-th largest `status_until` is fresh.
|
|
25
|
+
//
|
|
26
|
+
// ⚠ EVERY OUTCOME IS CLASSIFIED BEFORE ANYTHING IS MERGED (the same rule as the verifier-agent
|
|
27
|
+
// relay and the CLI): ANY verifier's `status_refresh_refused` (an explicit, current revocation)
|
|
28
|
+
// refuses the whole refresh - still-fresh original attestations never outvote it; another typed
|
|
29
|
+
// negative outcome ({@link withdrawsOriginal}) makes THAT verifier's original attestation
|
|
30
|
+
// ineligible for the merged result.
|
|
31
|
+
//
|
|
32
|
+
// ⚠ A refresh is never sent automatically and never retried here. One proof (one `seq`) may fan out
|
|
33
|
+
// to the original signers only; a new attempt needs a new, larger `seq` (each verifier keeps its own
|
|
34
|
+
// counter and answers 409 `status_refresh_replayed` otherwise).
|
|
35
|
+
import { keccak_256 } from '@noble/hashes/sha3';
|
|
36
|
+
import { concatBytes } from '@noble/hashes/utils';
|
|
37
|
+
import { sha256 } from '@noble/hashes/sha256';
|
|
38
|
+
import { ed25519 } from '@noble/curves/ed25519';
|
|
39
|
+
import { p256 } from '@noble/curves/p256';
|
|
40
|
+
import { bytesToHex, hexToBytes } from '../crypto/hex.js';
|
|
41
|
+
import { isStatusRefreshError, StatusRefreshError } from '../errors.js';
|
|
42
|
+
import { parseRetryAfter } from '../internal/retryAfter.js';
|
|
43
|
+
import { b64url } from '../oid4vp/jose.js';
|
|
44
|
+
import { assertStatusAttestationsWire, compoundTokenHash, decodeCompoundToken, signersThatVerify, verifyStatusAttestation, verifyStatusAttestations, STATUS_SKEW_SECS, } from './token.js';
|
|
45
|
+
/** Domain separator of the status-refresh proof (new name, `/v1`). */
|
|
46
|
+
export const STATUS_REFRESH_DOMAIN = 'keykeeper/committee-status-refresh/v1';
|
|
47
|
+
/** JOSE `typ` of a `holder_key` refresh proof. */
|
|
48
|
+
export const STATUS_REFRESH_JWT_TYP = 'keykeeper-status-refresh+jwt';
|
|
49
|
+
/** Verifier route (direct mode). */
|
|
50
|
+
export const STATUS_REFRESH_PATH = '/v1/committee/status-refresh';
|
|
51
|
+
/** Largest request body a verifier accepts, in bytes. */
|
|
52
|
+
export const MAX_STATUS_REFRESH_BODY_BYTES = 4096;
|
|
53
|
+
/** A verifier accepts `|issued_at - now| <= 30 s`. */
|
|
54
|
+
export const STATUS_REFRESH_FRESHNESS_SECS = 30;
|
|
55
|
+
/** Default deadline of one refresh HTTP exchange, ms. */
|
|
56
|
+
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
57
|
+
/** Largest response body read, bytes. */
|
|
58
|
+
const MAX_RESPONSE_BYTES = 64 * 1024;
|
|
59
|
+
const DOMAIN_BYTES = new TextEncoder().encode(STATUS_REFRESH_DOMAIN);
|
|
60
|
+
const U64_MAX = (1n << 64n) - 1n;
|
|
61
|
+
const HASH_HEX = /^0x[0-9a-fA-F]{64}$/;
|
|
62
|
+
const SIGNATURE_HEX = /^(?:0x)?[0-9a-fA-F]{128}$/;
|
|
63
|
+
const PRINCIPAL_KIND = { holder_key: 1, client_execution: 2 };
|
|
64
|
+
function u64(value, name, min) {
|
|
65
|
+
if (typeof value === 'number' && !Number.isSafeInteger(value))
|
|
66
|
+
throw new Error(`status refresh ${name} must be an integer`);
|
|
67
|
+
if (typeof value !== 'number' && typeof value !== 'bigint')
|
|
68
|
+
throw new Error(`status refresh ${name} must be an integer`);
|
|
69
|
+
const n = BigInt(value);
|
|
70
|
+
if (n < min || n > U64_MAX)
|
|
71
|
+
throw new Error(`status refresh ${name} is out of range`);
|
|
72
|
+
const b = new Uint8Array(8);
|
|
73
|
+
new DataView(b.buffer).setBigUint64(0, n, false);
|
|
74
|
+
return b;
|
|
75
|
+
}
|
|
76
|
+
function i64(value, name) {
|
|
77
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value))
|
|
78
|
+
throw new Error(`status refresh ${name} must be a safe integer`);
|
|
79
|
+
const b = new Uint8Array(8);
|
|
80
|
+
new DataView(b.buffer).setBigInt64(0, BigInt(value), false);
|
|
81
|
+
return b;
|
|
82
|
+
}
|
|
83
|
+
function bytes32(value, name) {
|
|
84
|
+
if (!(value instanceof Uint8Array) || value.length !== 32)
|
|
85
|
+
throw new Error(`status refresh ${name} must be 32 bytes`);
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The 32-byte digest a refresh proof signs:
|
|
90
|
+
* `keccak256(DOMAIN || chainId(u64 BE) || tokenHash || paymentHash|zero32 || principalKind(u8)
|
|
91
|
+
* || seq(u64 BE) || issuedAt(i64 BE))`.
|
|
92
|
+
*
|
|
93
|
+
* @param input - Chain, token hash, original payment hash (paid only), principal, seq and issue time.
|
|
94
|
+
*/
|
|
95
|
+
export function statusRefreshHash(input) {
|
|
96
|
+
const kind = PRINCIPAL_KIND[input.principal];
|
|
97
|
+
if (kind === undefined)
|
|
98
|
+
throw new Error('status refresh principal must be holder_key or client_execution');
|
|
99
|
+
return keccak_256(concatBytes(DOMAIN_BYTES, u64(input.chainId, 'chain_id', 0n), bytes32(input.tokenHash, 'token hash'), input.paymentHash === undefined ? new Uint8Array(32) : bytes32(input.paymentHash, 'payment hash'), Uint8Array.of(kind), u64(input.seq, 'seq', 1n), i64(input.issuedAt, 'issued_at')));
|
|
100
|
+
}
|
|
101
|
+
function bareJwk(jwk) {
|
|
102
|
+
return jwk.kty === 'EC' ? { kty: 'EC', crv: jwk.crv, x: jwk.x, y: jwk.y } : { kty: 'OKP', crv: jwk.crv, x: jwk.x };
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* A {@link StatusRefreshHolderSigner} over a local holder key (P-256 signs ES256, Ed25519 signs EdDSA).
|
|
106
|
+
* The returned signer keeps a reference to `holder.privateKey`; the caller owns its lifetime.
|
|
107
|
+
*
|
|
108
|
+
* @param holder - Holder key the credential was bound to at issuance.
|
|
109
|
+
*/
|
|
110
|
+
export function statusRefreshHolderSigner(holder) {
|
|
111
|
+
const okp = holder.publicJwk.kty === 'OKP', key = holder.privateKey;
|
|
112
|
+
return {
|
|
113
|
+
alg: okp ? 'EdDSA' : 'ES256',
|
|
114
|
+
publicJwk: bareJwk(holder.publicJwk),
|
|
115
|
+
sign: input => okp ? ed25519.sign(input, key) : p256.sign(sha256(input), key).toCompactRawBytes(),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Sign one refresh proof. `client_execution` signs the hash with the execution key
|
|
120
|
+
* (`0x`-hex Ed25519); `holder_key` signs a compact JWS (`typ: keykeeper-status-refresh+jwt`,
|
|
121
|
+
* header `jwk`, payload `{"refresh":"0x<hash>"}`).
|
|
122
|
+
*
|
|
123
|
+
* @param opts - Chain, token hash, original payment hash, seq, issue time and prover.
|
|
124
|
+
*/
|
|
125
|
+
export async function createStatusRefreshProof(opts) {
|
|
126
|
+
if (!Number.isSafeInteger(opts.seq) || opts.seq < 1)
|
|
127
|
+
throw new Error('status refresh seq must be a positive safe integer');
|
|
128
|
+
const issuedAt = opts.issuedAt ?? Math.floor(Date.now() / 1000);
|
|
129
|
+
const prover = opts.prover;
|
|
130
|
+
const hash = statusRefreshHash({ chainId: opts.chainId, tokenHash: opts.tokenHash, paymentHash: opts.paymentHash,
|
|
131
|
+
principal: prover.kind, seq: opts.seq, issuedAt });
|
|
132
|
+
if (prover.kind === 'client_execution') {
|
|
133
|
+
const signature = await prover.signer.sign(hash);
|
|
134
|
+
if (!(signature instanceof Uint8Array) || signature.length !== 64
|
|
135
|
+
|| !ed25519.verify(signature, hash, prover.signer.publicKey, { zip215: false }))
|
|
136
|
+
throw new Error('execution signer produced an invalid status refresh signature');
|
|
137
|
+
return { kind: 'client_execution', seq: opts.seq, issued_at: issuedAt, signature: bytesToHex(signature) };
|
|
138
|
+
}
|
|
139
|
+
if (prover.kind !== 'holder_key')
|
|
140
|
+
throw new Error('status refresh prover must be client_execution or holder_key');
|
|
141
|
+
const signer = prover.signer;
|
|
142
|
+
if ((signer.alg === 'EdDSA') !== (signer.publicJwk.kty === 'OKP') || (signer.alg !== 'EdDSA' && signer.alg !== 'ES256')) {
|
|
143
|
+
throw new Error('holder signer algorithm does not match its key type');
|
|
144
|
+
}
|
|
145
|
+
const header = { alg: signer.alg, typ: STATUS_REFRESH_JWT_TYP, jwk: bareJwk(signer.publicJwk) };
|
|
146
|
+
const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify({ refresh: bytesToHex(hash) }))}`;
|
|
147
|
+
const signature = await signer.sign(new TextEncoder().encode(input));
|
|
148
|
+
if (!(signature instanceof Uint8Array) || signature.length !== 64)
|
|
149
|
+
throw new Error('holder signer produced an invalid JWS signature');
|
|
150
|
+
return { kind: 'holder_key', seq: opts.seq, issued_at: issuedAt, signature: `${input}.${b64url(signature)}` };
|
|
151
|
+
}
|
|
152
|
+
function assertProofWire(proof) {
|
|
153
|
+
if (!proof || typeof proof !== 'object' || (proof.kind !== 'holder_key' && proof.kind !== 'client_execution')
|
|
154
|
+
|| !Number.isSafeInteger(proof.seq) || proof.seq < 1 || !Number.isSafeInteger(proof.issued_at)
|
|
155
|
+
|| typeof proof.signature !== 'string' || !proof.signature)
|
|
156
|
+
throw new Error('Invalid status refresh proof');
|
|
157
|
+
if (proof.kind === 'client_execution' && !/^0x[0-9a-fA-F]{128}$/.test(proof.signature))
|
|
158
|
+
throw new Error('Invalid client_execution refresh signature');
|
|
159
|
+
return { kind: proof.kind, seq: proof.seq, issued_at: proof.issued_at, signature: proof.signature };
|
|
160
|
+
}
|
|
161
|
+
function encodeBody(value) {
|
|
162
|
+
const body = new TextEncoder().encode(JSON.stringify(value));
|
|
163
|
+
if (body.length > MAX_STATUS_REFRESH_BODY_BYTES)
|
|
164
|
+
throw new Error(`status refresh body exceeds ${MAX_STATUS_REFRESH_BODY_BYTES} bytes`);
|
|
165
|
+
return body;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The exact verifier request body `{chain_id, token_hash, proof}` (≤ 4096 bytes).
|
|
169
|
+
*
|
|
170
|
+
* @param chainId - Chain ID (a JavaScript safe integer).
|
|
171
|
+
* @param tokenHash - 32-byte canonical token hash.
|
|
172
|
+
* @param proof - Signed proof.
|
|
173
|
+
*/
|
|
174
|
+
export function statusRefreshRequestBody(chainId, tokenHash, proof) {
|
|
175
|
+
if (!Number.isSafeInteger(chainId) || chainId < 0)
|
|
176
|
+
throw new Error('status refresh chain_id must be a safe non-negative integer');
|
|
177
|
+
return encodeBody({ chain_id: chainId, token_hash: bytesToHex(bytes32(tokenHash, 'token hash')), proof: assertProofWire(proof) });
|
|
178
|
+
}
|
|
179
|
+
const invalid = (message, verifierIndex) => ({ ...(verifierIndex !== undefined ? { verifierIndex } : {}), code: 'status_refresh_invalid_response', message });
|
|
180
|
+
/**
|
|
181
|
+
* Strictly validate an untrusted verifier refresh reply. Throws {@link StatusRefreshError}
|
|
182
|
+
* (`status_refresh_invalid_response`). Validates the SHAPE only; the signature is checked against
|
|
183
|
+
* the original roster by the refresh functions.
|
|
184
|
+
*
|
|
185
|
+
* @param raw - Parsed JSON reply.
|
|
186
|
+
*/
|
|
187
|
+
export function parseStatusRefreshReply(raw) {
|
|
188
|
+
const fail = (message) => new StatusRefreshError({ code: 'status_refresh_invalid_response', message: `status refresh reply ${message}` });
|
|
189
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
190
|
+
throw fail('is not an object');
|
|
191
|
+
const r = raw;
|
|
192
|
+
const keys = Object.keys(r);
|
|
193
|
+
if (keys.length !== 4 || !['token_hash', 'verifier_index', 'status_until', 'status_signature'].every(k => Object.hasOwn(r, k))) {
|
|
194
|
+
throw fail('is not exactly {token_hash, verifier_index, status_until, status_signature}');
|
|
195
|
+
}
|
|
196
|
+
const tokenHash = r.token_hash, index = r.verifier_index, until = r.status_until, signature = r.status_signature;
|
|
197
|
+
if (typeof tokenHash !== 'string' || !HASH_HEX.test(tokenHash))
|
|
198
|
+
throw fail('token_hash is not 0x + 32 bytes of hex');
|
|
199
|
+
if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0 || index > 0xffff_ffff)
|
|
200
|
+
throw fail('verifier_index is not a u32');
|
|
201
|
+
if (typeof until !== 'number' || !Number.isSafeInteger(until))
|
|
202
|
+
throw fail('status_until is not a safe integer');
|
|
203
|
+
if (typeof signature !== 'string' || !SIGNATURE_HEX.test(signature))
|
|
204
|
+
throw fail('status_signature is not 64 bytes of hex');
|
|
205
|
+
return { token_hash: tokenHash, verifier_index: index, status_until: until, status_signature: signature };
|
|
206
|
+
}
|
|
207
|
+
// HTTP status → the codes a server may send with it (the code must agree with the status).
|
|
208
|
+
const CODES_BY_STATUS = {
|
|
209
|
+
401: ['status_refresh_unauthenticated'],
|
|
210
|
+
403: ['status_refresh_unauthenticated', 'status_refresh_refused'],
|
|
211
|
+
404: ['status_refresh_unknown'],
|
|
212
|
+
409: ['status_refresh_unavailable', 'status_refresh_replayed', 'status_refresh_context_changed'],
|
|
213
|
+
410: ['status_refresh_expired'],
|
|
214
|
+
429: ['status_refresh_rate_limited'],
|
|
215
|
+
503: ['status_refresh_unavailable_status', 'status_refresh_quorum_unmet'],
|
|
216
|
+
};
|
|
217
|
+
// A status whose meaning is unambiguous without a code.
|
|
218
|
+
const FALLBACK_BY_STATUS = {
|
|
219
|
+
401: 'status_refresh_unauthenticated', 404: 'status_refresh_unknown', 410: 'status_refresh_expired', 429: 'status_refresh_rate_limited',
|
|
220
|
+
};
|
|
221
|
+
const KNOWN_CODES = new Set(Object.values(CODES_BY_STATUS).flatMap(codes => codes ?? []));
|
|
222
|
+
function findCode(body) {
|
|
223
|
+
try {
|
|
224
|
+
const parsed = JSON.parse(body);
|
|
225
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
226
|
+
const code = parsed.code;
|
|
227
|
+
if (typeof code === 'string' && KNOWN_CODES.has(code))
|
|
228
|
+
return code;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
catch { /* not JSON: search the text */ }
|
|
232
|
+
// Maximal `[a-z_]+` runs, so `status_refresh_unavailable_status` never reads as `..._unavailable`.
|
|
233
|
+
for (const match of body.matchAll(/status_refresh_[a-z_]+/g))
|
|
234
|
+
if (KNOWN_CODES.has(match[0]))
|
|
235
|
+
return match[0];
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Classify a non-200 refresh answer by its HTTP status and the stable code in its body. A code
|
|
240
|
+
* that does not belong to the status is ignored; an unclassified answer is `status_refresh_http`.
|
|
241
|
+
*
|
|
242
|
+
* @param status - HTTP status.
|
|
243
|
+
* @param body - Response body text.
|
|
244
|
+
*/
|
|
245
|
+
export function classifyStatusRefreshResponse(status, body) {
|
|
246
|
+
const found = findCode(body.slice(0, MAX_RESPONSE_BYTES));
|
|
247
|
+
if (found !== undefined && CODES_BY_STATUS[status]?.includes(found))
|
|
248
|
+
return found;
|
|
249
|
+
return FALLBACK_BY_STATUS[status] ?? 'status_refresh_http';
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Whether a verifier's typed refresh outcome withdraws its ORIGINAL attestation from the merged
|
|
253
|
+
* result: the verifier, answering for this token, said its status statement does not stand now
|
|
254
|
+
* (revoked, past a cap, the principal does not verify, its context moved, it cannot read status,
|
|
255
|
+
* or the proof replays). Transport, unknown or malformed outcomes withdraw nothing.
|
|
256
|
+
*
|
|
257
|
+
* @param code - A failure's code.
|
|
258
|
+
*/
|
|
259
|
+
export function withdrawsOriginal(code) {
|
|
260
|
+
return code === 'status_refresh_refused' || code === 'status_refresh_expired' || code === 'status_refresh_unauthenticated'
|
|
261
|
+
|| code === 'status_refresh_context_changed' || code === 'status_refresh_unavailable_status' || code === 'status_refresh_replayed';
|
|
262
|
+
}
|
|
263
|
+
function prepareGrant(grant) {
|
|
264
|
+
const token = decodeCompoundToken(grant.token);
|
|
265
|
+
if (!Number.isSafeInteger(grant.quorum) || grant.quorum < 1)
|
|
266
|
+
throw new Error('status refresh quorum must be a positive integer');
|
|
267
|
+
const counted = signersThatVerify(token, grant.set);
|
|
268
|
+
if (counted.length < grant.quorum)
|
|
269
|
+
throw new Error(`original grant carries ${counted.length} verified signatures under the supplied roster, need ${grant.quorum}`);
|
|
270
|
+
let cap = Number(token.exp);
|
|
271
|
+
for (const c of grant.caps ?? []) {
|
|
272
|
+
if (!Number.isSafeInteger(c))
|
|
273
|
+
throw new Error('status refresh caps must be Unix seconds');
|
|
274
|
+
cap = Math.min(cap, c);
|
|
275
|
+
}
|
|
276
|
+
return { wire: grant.token, tokenHash: compoundTokenHash(token), counted, set: grant.set, quorum: grant.quorum, cap };
|
|
277
|
+
}
|
|
278
|
+
/** Local check before anything is sent: the grant still has a usable window under its caps. */
|
|
279
|
+
function assertRefreshable(p, now) {
|
|
280
|
+
if (p.cap - STATUS_SKEW_SECS <= now) {
|
|
281
|
+
throw new StatusRefreshError({ code: 'status_refresh_expired',
|
|
282
|
+
message: `status refresh not sent: a hard cap of the grant (${p.cap}) minus the ${STATUS_SKEW_SECS} s keeper skew has passed` });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
function aggregateFailure(failures, got, need) {
|
|
286
|
+
const retryAfter = failures.reduce((max, f) => f.retryAfterMs === undefined ? max : Math.max(max ?? 0, f.retryAfterMs), undefined);
|
|
287
|
+
const detail = failures.map(f => `${f.verifierIndex !== undefined ? `#${f.verifierIndex} ` : ''}${f.code}`).join('; ');
|
|
288
|
+
const message = `status refresh: ${got} of ${need} required fresh attestations${detail ? ` (${detail})` : ''}`;
|
|
289
|
+
// `status_refresh_refused` never reaches here: acceptRefresh refuses on it before any merge.
|
|
290
|
+
// Every original signer failed the same way: that code is the answer. Otherwise the quorum is unmet.
|
|
291
|
+
const first = failures[0];
|
|
292
|
+
if (got === 0 && first && failures.every(f => f.code === first.code)) {
|
|
293
|
+
return new StatusRefreshError({ code: first.code, httpStatus: first.httpStatus, message, reasons: failures, retryAfterMs: retryAfter });
|
|
294
|
+
}
|
|
295
|
+
const transient = failures.some(f => ['status_refresh_rate_limited', 'status_refresh_unavailable_status', 'status_refresh_unreachable', 'status_refresh_quorum_unmet'].includes(f.code)
|
|
296
|
+
|| (f.code === 'status_refresh_http' && f.httpStatus !== undefined && (f.httpStatus >= 500 || f.httpStatus === 429)));
|
|
297
|
+
return new StatusRefreshError({ code: 'status_refresh_quorum_unmet', message, reasons: failures, retryAfterMs: retryAfter, retryable: transient });
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* The relay's and the CLI's order, exactly: (1) classify - any revocation refusal refuses the whole
|
|
301
|
+
* refresh, another typed negative outcome withdraws that verifier's original; (2) accept new
|
|
302
|
+
* attestations only from original verified signers, verified under their original keys, fresh and
|
|
303
|
+
* capped; (3) merge per index with the still-eligible originals (`mergeExisting`, direct mode: each
|
|
304
|
+
* original re-verified and capped the same way; a relay answer is already the whole set); (4) judge
|
|
305
|
+
* the MERGED set by the keeper rule (quorum-th largest `status_until`, fresh at `now`). The number
|
|
306
|
+
* of NEW attestations alone is never the judge: one fresh reply beside a still-fresh eligible
|
|
307
|
+
* original can meet the quorum.
|
|
308
|
+
*/
|
|
309
|
+
function acceptRefresh(p, candidates, failures, now, mergeExisting) {
|
|
310
|
+
const refused = failures.filter(f => f.code === 'status_refresh_refused');
|
|
311
|
+
if (refused.length) {
|
|
312
|
+
const detail = refused.map(f => `${f.verifierIndex !== undefined ? `#${f.verifierIndex} ` : ''}${f.code}`).join('; ');
|
|
313
|
+
throw new StatusRefreshError({ code: 'status_refresh_refused', httpStatus: 403, reasons: failures,
|
|
314
|
+
message: `status refresh: the holder's credential status is refused now (${detail}); do not send this grant` });
|
|
315
|
+
}
|
|
316
|
+
const ineligible = new Set(failures.flatMap(f => f.verifierIndex !== undefined && withdrawsOriginal(f.code) ? [f.verifierIndex] : []));
|
|
317
|
+
const accepted = new Map();
|
|
318
|
+
for (const a of candidates) {
|
|
319
|
+
const index = a.verifierIndex;
|
|
320
|
+
if (!p.counted.includes(index)) {
|
|
321
|
+
failures.push(invalid('attestation from a verifier that did not verifiably sign the original token', index));
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
const pubkey = p.set.pubkeys.get(index);
|
|
325
|
+
if (!pubkey || !verifyStatusAttestation(pubkey, p.tokenHash, a)) {
|
|
326
|
+
failures.push(invalid('attestation does not verify under the original roster key', index));
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (a.statusUntil + STATUS_SKEW_SECS > p.cap) {
|
|
330
|
+
failures.push(invalid(`status_until ${a.statusUntil} + ${STATUS_SKEW_SECS} s passes the grant cap ${p.cap}`, index));
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (now > a.statusUntil + STATUS_SKEW_SECS) {
|
|
334
|
+
failures.push(invalid(`attestation is already stale (status_until ${a.statusUntil})`, index));
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
const prior = accepted.get(index);
|
|
338
|
+
if (!prior || a.statusUntil > prior.statusUntil)
|
|
339
|
+
accepted.set(index, a);
|
|
340
|
+
}
|
|
341
|
+
// The journaled list, filtered to what a keeper would count (a bad counted entry would refuse
|
|
342
|
+
// the whole grant) and to the grant caps (as the CLI's `authenticate_all`), then merged per
|
|
343
|
+
// index: the later deadline wins. A stale original stays in the list; the judge below does not
|
|
344
|
+
// count it.
|
|
345
|
+
const merged = new Map();
|
|
346
|
+
let existing = [];
|
|
347
|
+
if (mergeExisting && p.wire.status_attestations != null) {
|
|
348
|
+
try {
|
|
349
|
+
existing = assertStatusAttestationsWire(p.wire.status_attestations, p.wire.verifier_indexes.length);
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
existing = [];
|
|
353
|
+
} // a malformed journaled list contributes nothing (the CLI's `.ok().flatten()`)
|
|
354
|
+
}
|
|
355
|
+
for (const w of existing) {
|
|
356
|
+
if (ineligible.has(w.verifier_index))
|
|
357
|
+
continue; // withdrawn by that verifier's own negative outcome
|
|
358
|
+
const a = { verifierIndex: w.verifier_index, statusUntil: w.status_until, signature: hexToBytes(w.signature) };
|
|
359
|
+
const pubkey = p.set.pubkeys.get(a.verifierIndex);
|
|
360
|
+
if (!p.counted.includes(a.verifierIndex) || !pubkey || !verifyStatusAttestation(pubkey, p.tokenHash, a))
|
|
361
|
+
continue;
|
|
362
|
+
if (a.statusUntil + STATUS_SKEW_SECS > p.cap)
|
|
363
|
+
continue;
|
|
364
|
+
merged.set(a.verifierIndex, a);
|
|
365
|
+
}
|
|
366
|
+
// A relay's set is its whole answer: every original signer it left out stays out.
|
|
367
|
+
if (!mergeExisting)
|
|
368
|
+
for (const i of p.counted)
|
|
369
|
+
if (!accepted.has(i))
|
|
370
|
+
ineligible.add(i);
|
|
371
|
+
for (const [index, a] of accepted) {
|
|
372
|
+
const prior = merged.get(index);
|
|
373
|
+
if (!prior || a.statusUntil > prior.statusUntil)
|
|
374
|
+
merged.set(index, a);
|
|
375
|
+
}
|
|
376
|
+
const list = [...merged.values()].sort((x, y) => x.verifierIndex - y.verifierIndex);
|
|
377
|
+
// The keeper rule on the MERGED set is the only judge; below it, this refresh's quorum is unmet.
|
|
378
|
+
let statusUntil;
|
|
379
|
+
try {
|
|
380
|
+
statusUntil = verifyStatusAttestations({ tokenHash: p.tokenHash, attestations: list, counted: p.counted, set: p.set, quorum: p.quorum, now });
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
throw aggregateFailure(failures, list.filter(a => now <= a.statusUntil + STATUS_SKEW_SECS).length, p.quorum);
|
|
384
|
+
}
|
|
385
|
+
const statusAttestations = list.map(a => ({ verifier_index: a.verifierIndex, status_until: a.statusUntil, signature: bytesToHex(a.signature) }));
|
|
386
|
+
return { token: { ...structuredClone(p.wire), status_attestations: structuredClone(statusAttestations) }, statusAttestations,
|
|
387
|
+
refreshed: [...accepted.keys()].sort((x, y) => x - y), statusUntil, failures, ineligible: [...ineligible].sort((x, y) => x - y) };
|
|
388
|
+
}
|
|
389
|
+
const text = (body) => typeof body === 'string' ? body : new TextDecoder().decode(body);
|
|
390
|
+
function failureOf(response, verifierIndex) {
|
|
391
|
+
const body = text(response.body);
|
|
392
|
+
return { ...(verifierIndex !== undefined ? { verifierIndex } : {}), code: classifyStatusRefreshResponse(response.status, body), httpStatus: response.status,
|
|
393
|
+
...(response.retryAfterMs !== undefined ? { retryAfterMs: response.retryAfterMs } : {}),
|
|
394
|
+
message: `HTTP ${response.status}${body ? `: ${body.slice(0, 200)}` : ''}` };
|
|
395
|
+
}
|
|
396
|
+
const oversize = (status, detail) => new StatusRefreshError({ code: 'status_refresh_invalid_response', httpStatus: status,
|
|
397
|
+
message: `status refresh response ${detail} exceeds ${MAX_RESPONSE_BYTES} bytes` });
|
|
398
|
+
/**
|
|
399
|
+
* Read at most {@link MAX_RESPONSE_BYTES} of a response body, whatever its status. An advertised
|
|
400
|
+
* `Content-Length` over the cap is refused without reading (skipped under a `Content-Encoding`,
|
|
401
|
+
* where it counts encoded bytes); otherwise the stream is read chunk by chunk and cancelled as soon
|
|
402
|
+
* as the running total passes the cap, so a lying or absent length never buffers more than one
|
|
403
|
+
* chunk past it. Throws {@link StatusRefreshError} `status_refresh_invalid_response`.
|
|
404
|
+
*/
|
|
405
|
+
async function readBoundedBody(res) {
|
|
406
|
+
const advertised = res.headers?.get('content-length');
|
|
407
|
+
if (advertised && !res.headers.get('content-encoding') && /^\d+$/.test(advertised) && Number(advertised) > MAX_RESPONSE_BYTES) {
|
|
408
|
+
void res.body?.cancel().catch(() => { });
|
|
409
|
+
throw oversize(res.status, `Content-Length ${advertised}`);
|
|
410
|
+
}
|
|
411
|
+
if (!res.body)
|
|
412
|
+
return '';
|
|
413
|
+
const reader = res.body.getReader();
|
|
414
|
+
const decoder = new TextDecoder();
|
|
415
|
+
let size = 0, out = '';
|
|
416
|
+
try {
|
|
417
|
+
for (;;) {
|
|
418
|
+
const { done, value } = await reader.read();
|
|
419
|
+
if (done)
|
|
420
|
+
break;
|
|
421
|
+
size += value.length;
|
|
422
|
+
if (size > MAX_RESPONSE_BYTES)
|
|
423
|
+
throw oversize(res.status, 'body');
|
|
424
|
+
out += decoder.decode(value, { stream: true });
|
|
425
|
+
}
|
|
426
|
+
return out + decoder.decode();
|
|
427
|
+
}
|
|
428
|
+
finally {
|
|
429
|
+
// Also on the cap refusal. Initiate cancellation without waiting on a hostile body's cancel hook.
|
|
430
|
+
void reader.cancel().catch(() => { });
|
|
431
|
+
reader.releaseLock();
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
async function post(fetchImpl, url, body, signal, bearer) {
|
|
435
|
+
const res = await fetchImpl(url, { method: 'POST', redirect: 'error', signal, body: new TextDecoder().decode(body),
|
|
436
|
+
headers: { 'Content-Type': 'application/json', ...(bearer !== undefined ? { Authorization: `Bearer ${bearer}` } : {}) } });
|
|
437
|
+
const raw = await readBoundedBody(res);
|
|
438
|
+
const retryAfterMs = parseRetryAfter(res.headers?.get('retry-after'));
|
|
439
|
+
return { status: res.status, body: raw, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) };
|
|
440
|
+
}
|
|
441
|
+
function endpoint(url, allowHttp) {
|
|
442
|
+
let parsed;
|
|
443
|
+
try {
|
|
444
|
+
parsed = new URL(url);
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
throw new Error('Invalid status refresh endpoint');
|
|
448
|
+
}
|
|
449
|
+
if (parsed.protocol !== 'https:' && !(allowHttp && parsed.protocol === 'http:'))
|
|
450
|
+
throw new Error('Status refresh endpoints must use https');
|
|
451
|
+
if (parsed.username || parsed.password || parsed.search || parsed.hash)
|
|
452
|
+
throw new Error('Invalid status refresh endpoint');
|
|
453
|
+
return parsed.origin + parsed.pathname.replace(/\/+$/, '');
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Refresh a grant's status directly at its original signers' verifiers
|
|
457
|
+
* (`POST /v1/committee/status-refresh`), verify every reply under the original roster, and merge.
|
|
458
|
+
* Sends the one proof once per original signer; never retries.
|
|
459
|
+
*
|
|
460
|
+
* @param opts - Grant, roster, quorum, caps, chain, proof and verifier endpoints.
|
|
461
|
+
* @returns The merged grant and its new effective deadline.
|
|
462
|
+
* @throws StatusRefreshError when fewer than a quorum of fresh, valid, capped attestations arrive.
|
|
463
|
+
*/
|
|
464
|
+
export async function refreshStatusDirect(opts) {
|
|
465
|
+
const p = prepareGrant(opts);
|
|
466
|
+
assertRefreshable(p, Math.floor(Date.now() / 1000));
|
|
467
|
+
const body = statusRefreshRequestBody(opts.chainId, p.tokenHash, opts.proof);
|
|
468
|
+
const fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
469
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
470
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000)
|
|
471
|
+
throw new Error('Invalid status refresh timeout');
|
|
472
|
+
const urls = new Map();
|
|
473
|
+
for (const v of opts.verifiers) {
|
|
474
|
+
if (!p.counted.includes(v.index))
|
|
475
|
+
continue; // never fan out beyond the original verified signers
|
|
476
|
+
if (urls.has(v.index))
|
|
477
|
+
throw new Error(`Duplicate status refresh endpoint for verifier #${v.index}`);
|
|
478
|
+
urls.set(v.index, endpoint(v.url, opts.allowHttp === true) + STATUS_REFRESH_PATH);
|
|
479
|
+
}
|
|
480
|
+
const failures = p.counted.filter(i => !urls.has(i))
|
|
481
|
+
.map(i => ({ verifierIndex: i, code: 'status_refresh_unreachable', message: 'no endpoint supplied for this original signer' }));
|
|
482
|
+
const tokenHashHex = bytesToHex(p.tokenHash);
|
|
483
|
+
const candidates = [];
|
|
484
|
+
await Promise.all([...urls].map(async ([index, url]) => {
|
|
485
|
+
const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(opts.signal ? [opts.signal] : [])]);
|
|
486
|
+
let response;
|
|
487
|
+
try {
|
|
488
|
+
response = await post(fetchImpl, url, body, signal);
|
|
489
|
+
}
|
|
490
|
+
catch (error) {
|
|
491
|
+
if (isStatusRefreshError(error)) { // an oversized answer: typed, not a transport failure
|
|
492
|
+
failures.push({ verifierIndex: index, code: error.code, ...(error.httpStatus !== undefined ? { httpStatus: error.httpStatus } : {}), message: error.message.slice(0, 200) });
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
failures.push({ verifierIndex: index, code: 'status_refresh_unreachable', message: error instanceof Error ? error.message.slice(0, 200) : 'no answer' });
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
if (response.status !== 200) {
|
|
499
|
+
failures.push(failureOf(response, index));
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
let reply;
|
|
503
|
+
try {
|
|
504
|
+
reply = parseStatusRefreshReply(JSON.parse(text(response.body)));
|
|
505
|
+
}
|
|
506
|
+
catch (error) {
|
|
507
|
+
failures.push(invalid(error instanceof Error ? error.message : 'unparseable reply', index));
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
if (reply.verifier_index !== index) {
|
|
511
|
+
failures.push(invalid(`reply names verifier #${reply.verifier_index}`, index));
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
if (reply.token_hash.toLowerCase() !== tokenHashHex) {
|
|
515
|
+
failures.push(invalid('reply is for another token', index));
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
candidates.push({ verifierIndex: index, statusUntil: reply.status_until, signature: hexToBytes(reply.status_signature) });
|
|
519
|
+
}));
|
|
520
|
+
opts.signal?.throwIfAborted();
|
|
521
|
+
return acceptRefresh(p, candidates, failures, Math.floor(Date.now() / 1000), true);
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Verify a verifier-agent relay answer (`POST /v1/sessions/:id/status-refresh`). A 200 body must
|
|
525
|
+
* be exactly `{token_hash, status_attestations}`; each attestation is re-verified here under the
|
|
526
|
+
* original roster (the agent is not trusted). A non-200 answer becomes a typed
|
|
527
|
+
* {@link StatusRefreshError}, with the relay's per-index `reasons` when it sent them.
|
|
528
|
+
*
|
|
529
|
+
* @param grant - Grant, original roster, quorum and caps.
|
|
530
|
+
* @param response - The relay's bounded HTTP answer.
|
|
531
|
+
*/
|
|
532
|
+
export function acceptStatusRefreshRelay(grant, response) {
|
|
533
|
+
const p = prepareGrant(grant);
|
|
534
|
+
const bodyText = text(response.body);
|
|
535
|
+
if (response.status !== 200) {
|
|
536
|
+
const failure = failureOf(response);
|
|
537
|
+
const reasons = [];
|
|
538
|
+
try {
|
|
539
|
+
const parsed = JSON.parse(bodyText);
|
|
540
|
+
if (Array.isArray(parsed.reasons)) {
|
|
541
|
+
for (const entry of parsed.reasons.slice(0, 64)) {
|
|
542
|
+
if (!entry || typeof entry !== 'object')
|
|
543
|
+
continue;
|
|
544
|
+
const e = entry, index = e.verifier_index, rawCode = e.code ?? e.error;
|
|
545
|
+
const code = typeof rawCode === 'string' ? rawCode : '';
|
|
546
|
+
if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0)
|
|
547
|
+
continue;
|
|
548
|
+
reasons.push({ verifierIndex: index, code: KNOWN_CODES.has(code) ? code : 'status_refresh_http', message: code.slice(0, 200) });
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
catch { /* no structured reasons */ }
|
|
553
|
+
throw new StatusRefreshError({ code: failure.code, httpStatus: response.status, retryAfterMs: response.retryAfterMs,
|
|
554
|
+
message: `status refresh relay: ${failure.message}`, reasons: [failure, ...reasons] });
|
|
555
|
+
}
|
|
556
|
+
const fail = (message) => new StatusRefreshError({ code: 'status_refresh_invalid_response', httpStatus: 200, message: `status refresh relay reply ${message}` });
|
|
557
|
+
let parsed;
|
|
558
|
+
try {
|
|
559
|
+
parsed = JSON.parse(bodyText);
|
|
560
|
+
}
|
|
561
|
+
catch {
|
|
562
|
+
throw fail('is not JSON');
|
|
563
|
+
}
|
|
564
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
565
|
+
throw fail('is not an object');
|
|
566
|
+
const r = parsed;
|
|
567
|
+
if (Object.keys(r).length !== 2 || !Object.hasOwn(r, 'token_hash') || !Object.hasOwn(r, 'status_attestations'))
|
|
568
|
+
throw fail('is not exactly {token_hash, status_attestations}');
|
|
569
|
+
if (typeof r.token_hash !== 'string' || r.token_hash.toLowerCase() !== bytesToHex(p.tokenHash))
|
|
570
|
+
throw fail('is for another token');
|
|
571
|
+
let list;
|
|
572
|
+
try {
|
|
573
|
+
list = assertStatusAttestationsWire(r.status_attestations, p.wire.verifier_indexes.length);
|
|
574
|
+
}
|
|
575
|
+
catch (error) {
|
|
576
|
+
throw fail(error instanceof Error ? error.message : 'carries malformed attestations');
|
|
577
|
+
}
|
|
578
|
+
const candidates = list.map(w => ({ verifierIndex: w.verifier_index, statusUntil: w.status_until, signature: hexToBytes(w.signature) }));
|
|
579
|
+
return acceptRefresh(p, candidates, [], Math.floor(Date.now() / 1000), false);
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Refresh a grant's status through the verifier-agent relay. The agent fans the proof out to the
|
|
583
|
+
* original signers; its answer is re-verified here exactly as in {@link refreshStatusDirect}.
|
|
584
|
+
*
|
|
585
|
+
* @param opts - Grant, roster, quorum, caps, agent session and proof.
|
|
586
|
+
* @throws StatusRefreshError on a typed refusal, an unsigned or forged reply, or no fresh quorum.
|
|
587
|
+
*/
|
|
588
|
+
export async function refreshStatusViaAgent(opts) {
|
|
589
|
+
const p = prepareGrant(opts);
|
|
590
|
+
assertRefreshable(p, Math.floor(Date.now() / 1000));
|
|
591
|
+
if (typeof opts.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(opts.sessionId))
|
|
592
|
+
throw new Error('Invalid verifier-agent session id');
|
|
593
|
+
if (typeof opts.pollSecret !== 'string' || !/^[A-Za-z0-9_-]{16,256}$/.test(opts.pollSecret))
|
|
594
|
+
throw new Error('Invalid verifier-agent session secret');
|
|
595
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
596
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000)
|
|
597
|
+
throw new Error('Invalid status refresh timeout');
|
|
598
|
+
const url = `${endpoint(opts.agentUrl, opts.allowHttp === true)}/v1/sessions/${opts.sessionId}/status-refresh`;
|
|
599
|
+
const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(opts.signal ? [opts.signal] : [])]);
|
|
600
|
+
let response;
|
|
601
|
+
try {
|
|
602
|
+
response = await post(opts.fetch ?? globalThis.fetch, url, encodeBody({ proof: assertProofWire(opts.proof) }), signal, opts.pollSecret);
|
|
603
|
+
}
|
|
604
|
+
catch (error) {
|
|
605
|
+
opts.signal?.throwIfAborted();
|
|
606
|
+
if (isStatusRefreshError(error))
|
|
607
|
+
throw error; // an oversized answer stays `status_refresh_invalid_response`
|
|
608
|
+
throw new StatusRefreshError({ code: 'status_refresh_unreachable', message: 'status refresh relay did not answer', cause: error });
|
|
609
|
+
}
|
|
610
|
+
return acceptStatusRefreshRelay(opts, response);
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* The relay request body `{proof}` (for a caller-owned transport).
|
|
614
|
+
*
|
|
615
|
+
* @param proof - Refresh proof, validated before it is encoded.
|
|
616
|
+
*/
|
|
617
|
+
export function statusRefreshRelayBody(proof) {
|
|
618
|
+
return encodeBody({ proof: assertProofWire(proof) });
|
|
619
|
+
}
|