@t3foundry/tasra-sdk 0.3.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
|
@@ -98,12 +98,69 @@ export declare function verifyRequestObject(jwt: string, opts?: VerifyRequestObj
|
|
|
98
98
|
* @param ro - Verified request claims containing optional recipient encryption keys.
|
|
99
99
|
*/
|
|
100
100
|
export declare function responseEncryptionKey(ro: Pick<VerifiedRequestObject, 'claims'>): EcJwk | undefined;
|
|
101
|
+
/**
|
|
102
|
+
* The `error` message of the verifier-agent's HTTP 503 meaning "the paid exchange this request
|
|
103
|
+
* started is still running; repeating this same request joins it and never sends or pays again".
|
|
104
|
+
* It must equal the agent's text byte for byte. Any other 503 (for example an uncertain paid
|
|
105
|
+
* outcome awaiting reconciliation) is final.
|
|
106
|
+
*/
|
|
107
|
+
export declare const REQUEST_OBJECT_IN_PROGRESS = "paid verifier exchange in progress; it will not be sent again - retry this request";
|
|
108
|
+
/**
|
|
109
|
+
* The `error` message of the verifier-agent's HTTP 503 meaning "this agent is at its paid-exchange
|
|
110
|
+
* capacity": the request was refused before anything was dispatched, sent or billed, and the
|
|
111
|
+
* approval stands, so repeating the same request is safe. It must equal the agent's text byte for byte.
|
|
112
|
+
*/
|
|
113
|
+
export declare const REQUEST_OBJECT_AT_CAPACITY = "paid verifier exchange capacity saturated on this agent; nothing was sent or billed and the approval stands - retry this request";
|
|
114
|
+
/**
|
|
115
|
+
* Limits for repeating the identical `request_uri` GET while the verifier-agent reports work in progress
|
|
116
|
+
* or that it is at capacity.
|
|
117
|
+
*
|
|
118
|
+
* The default budget is 120 s because the agent's detached paid exchange may legitimately run up to
|
|
119
|
+
* about 118 s (its deadline is the earlier of the session authority's expiry and dispatch + 120 s,
|
|
120
|
+
* less 2 s). The budget ends at the earliest of `maxTotalMs`, `notAfterMs` and the caller's
|
|
121
|
+
* `AbortSignal`; pass the session's (authority's) expiry as `notAfterMs` when you know it.
|
|
122
|
+
*/
|
|
123
|
+
export interface RequestObjectRetryPolicy {
|
|
124
|
+
/** Total GETs including the first, 1..256 (default 64; 120 s at the agent's 2 s hint is 60). 1 disables the retry. */
|
|
125
|
+
maxAttempts?: number;
|
|
126
|
+
/** Wall-clock budget from the first GET in ms, 0..300000 (default 120000). Every GET and body read is bounded; zero sends nothing. */
|
|
127
|
+
maxTotalMs?: number;
|
|
128
|
+
/** Absolute end of the budget in Unix ms, such as the session's expiry; the earlier of this and `maxTotalMs` applies. */
|
|
129
|
+
notAfterMs?: number;
|
|
130
|
+
/** Shortest wait in ms, 100..5000 (default 500). A smaller `Retry-After` is raised to it. */
|
|
131
|
+
minDelayMs?: number;
|
|
132
|
+
/** Longest wait in ms, `minDelayMs`..10000 (default 5000). A larger `Retry-After` is lowered to it. */
|
|
133
|
+
maxDelayMs?: number;
|
|
134
|
+
}
|
|
135
|
+
/** Request verification, transport, cancellation and retry options for {@link fetchRequestObject}. */
|
|
136
|
+
export interface FetchRequestObjectOpts extends VerifyRequestObjectOpts {
|
|
137
|
+
/** HTTP transport override; defaults to the global fetch implementation. */
|
|
138
|
+
fetchImpl?: typeof fetch;
|
|
139
|
+
/** Cancels an in-flight GET and any wait between GETs; the promise rejects with the signal's reason. */
|
|
140
|
+
signal?: AbortSignal;
|
|
141
|
+
/** Limits for the in-progress and at-capacity retry; see {@link RequestObjectRetryPolicy}. */
|
|
142
|
+
inProgressRetry?: RequestObjectRetryPolicy;
|
|
143
|
+
}
|
|
101
144
|
/**
|
|
102
145
|
* Fetch a JAR from `request_uri` (`Accept: application/oauth-authz-req+jwt`) and verify it.
|
|
103
146
|
*
|
|
147
|
+
* While a paid verifier exchange that this request started is still running, the verifier-agent
|
|
148
|
+
* answers HTTP 503 with the exact {@link REQUEST_OBJECT_IN_PROGRESS} message and `Retry-After`.
|
|
149
|
+
* When it is at its paid-exchange capacity it refuses before sending or billing anything with the
|
|
150
|
+
* exact {@link REQUEST_OBJECT_AT_CAPACITY} message. Only these two answers are retried, in any mix
|
|
151
|
+
* and under one shared budget, by repeating the identical GET (same URL and headers; nothing is
|
|
152
|
+
* posted, presented or paid). The wait follows `Retry-After` (delta-seconds or HTTP-date; 2 s when
|
|
153
|
+
* absent or malformed) clamped to `minDelayMs`..`maxDelayMs` (default 0.5..5 s), within
|
|
154
|
+
* `maxAttempts` (default 64) and a wall-clock budget (default 120 s, which covers the agent's
|
|
155
|
+
* longest detached exchange) that ends early at `notAfterMs`. A repeated GET still running at the
|
|
156
|
+
* end of the budget is aborted. `signal` cancels the in-flight GET or the wait at once. When the
|
|
157
|
+
* budget or attempts run out, the last 503 is thrown; the paid work may still complete on the agent.
|
|
158
|
+
* Authorization refusals, any other 503 (including an uncertain paid outcome), other statuses, a
|
|
159
|
+
* reply from a redirected URL and network errors are final. Every GET, including the first and
|
|
160
|
+
* its response body, shares that deadline and cancellation signal. An expired budget sends
|
|
161
|
+
* nothing. A 200 is verified exactly as before.
|
|
162
|
+
*
|
|
104
163
|
* @param requestUri - URL from the OpenID4VP request_uri parameter.
|
|
105
|
-
* @param opts - Request signature verification settings and
|
|
164
|
+
* @param opts - Request signature verification settings, fetch implementation, cancellation and retry limits.
|
|
106
165
|
*/
|
|
107
|
-
export declare function fetchRequestObject(requestUri: string, opts?:
|
|
108
|
-
fetchImpl?: typeof fetch;
|
|
109
|
-
}): Promise<VerifiedRequestObject>;
|
|
166
|
+
export declare function fetchRequestObject(requestUri: string, opts?: FetchRequestObjectOpts): Promise<VerifiedRequestObject>;
|
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
// binding rides in the `nonce`, which the wallet copies into its KB-JWT without interpreting it.
|
|
6
6
|
import { resolveDidWeb, verificationKey } from './did-web.js';
|
|
7
7
|
import { decodeJson, jwkFromDid, verifyCompactJws } from './jose.js';
|
|
8
|
+
import { parseRetryAfter } from '../internal/retryAfter.js';
|
|
9
|
+
import { sleep } from '../internal/sleep.js';
|
|
8
10
|
/** JOSE type identifier for a signed authorization request object. */
|
|
9
11
|
export const REQUEST_OBJECT_TYP = 'oauth-authz-req+jwt';
|
|
10
12
|
/** OpenID4VP client identifier prefix for a DID-based verifier. */
|
|
@@ -81,16 +83,149 @@ export function responseEncryptionKey(ro) {
|
|
|
81
83
|
const k = ro.claims.client_metadata?.jwks?.keys?.[0];
|
|
82
84
|
return k && k.kty === 'EC' && k.crv === 'P-256' ? k : undefined;
|
|
83
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* The `error` message of the verifier-agent's HTTP 503 meaning "the paid exchange this request
|
|
88
|
+
* started is still running; repeating this same request joins it and never sends or pays again".
|
|
89
|
+
* It must equal the agent's text byte for byte. Any other 503 (for example an uncertain paid
|
|
90
|
+
* outcome awaiting reconciliation) is final.
|
|
91
|
+
*/
|
|
92
|
+
export const REQUEST_OBJECT_IN_PROGRESS = 'paid verifier exchange in progress; it will not be sent again - retry this request';
|
|
93
|
+
/**
|
|
94
|
+
* The `error` message of the verifier-agent's HTTP 503 meaning "this agent is at its paid-exchange
|
|
95
|
+
* capacity": the request was refused before anything was dispatched, sent or billed, and the
|
|
96
|
+
* approval stands, so repeating the same request is safe. It must equal the agent's text byte for byte.
|
|
97
|
+
*/
|
|
98
|
+
export const REQUEST_OBJECT_AT_CAPACITY = 'paid verifier exchange capacity saturated on this agent; nothing was sent or billed and the approval stands - retry this request';
|
|
99
|
+
/** The only 503 messages that make the identical `request_uri` GET worth repeating. */
|
|
100
|
+
const RETRYABLE_503_MESSAGES = new Set([REQUEST_OBJECT_IN_PROGRESS, REQUEST_OBJECT_AT_CAPACITY]);
|
|
101
|
+
/** Wait used when a retryable 503 carries no usable `Retry-After` (the agent's own value). */
|
|
102
|
+
const IN_PROGRESS_DEFAULT_DELAY_MS = 2_000;
|
|
103
|
+
/** A retryable 503 is a short JSON object; a larger body is not one. */
|
|
104
|
+
const IN_PROGRESS_MAX_BODY = 4_096;
|
|
105
|
+
function requestObjectRetryLimits(policy = {}) {
|
|
106
|
+
const value = (v, fallback, min, max, name) => {
|
|
107
|
+
const n = v ?? fallback;
|
|
108
|
+
if (!Number.isSafeInteger(n) || n < min || n > max)
|
|
109
|
+
throw new Error(`invalid inProgressRetry.${name}`);
|
|
110
|
+
return n;
|
|
111
|
+
};
|
|
112
|
+
const minDelayMs = value(policy.minDelayMs, 500, 100, 5_000, 'minDelayMs');
|
|
113
|
+
const limits = { maxAttempts: value(policy.maxAttempts, 64, 1, 256, 'maxAttempts'), maxTotalMs: value(policy.maxTotalMs, 120_000, 0, 300_000, 'maxTotalMs'),
|
|
114
|
+
minDelayMs, maxDelayMs: value(policy.maxDelayMs, Math.max(5_000, minDelayMs), minDelayMs, 10_000, 'maxDelayMs') };
|
|
115
|
+
if (policy.notAfterMs === undefined)
|
|
116
|
+
return limits;
|
|
117
|
+
if (!Number.isFinite(policy.notAfterMs))
|
|
118
|
+
throw new Error('invalid inProgressRetry.notAfterMs');
|
|
119
|
+
return { ...limits, notAfterMs: policy.notAfterMs };
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* True only for the verifier-agent's explicit in-progress or at-capacity answer: HTTP 503, served
|
|
123
|
+
* by the requested URL itself (no redirect), with a JSON body whose `error` is exactly
|
|
124
|
+
* {@link REQUEST_OBJECT_IN_PROGRESS} or {@link REQUEST_OBJECT_AT_CAPACITY}. Every other reply is final.
|
|
125
|
+
*/
|
|
126
|
+
function isRetryable503(res, requestUri, body) {
|
|
127
|
+
if (res.status !== 503 || res.redirected === true)
|
|
128
|
+
return false;
|
|
129
|
+
if (typeof res.url === 'string' && res.url !== '') {
|
|
130
|
+
let requested;
|
|
131
|
+
try {
|
|
132
|
+
requested = new URL(requestUri).href;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
if (res.url !== requested)
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
if (body.length > IN_PROGRESS_MAX_BODY)
|
|
141
|
+
return false;
|
|
142
|
+
let parsed;
|
|
143
|
+
try {
|
|
144
|
+
parsed = JSON.parse(body);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) && RETRYABLE_503_MESSAGES.has(parsed.error);
|
|
150
|
+
}
|
|
84
151
|
/**
|
|
85
152
|
* Fetch a JAR from `request_uri` (`Accept: application/oauth-authz-req+jwt`) and verify it.
|
|
86
153
|
*
|
|
154
|
+
* While a paid verifier exchange that this request started is still running, the verifier-agent
|
|
155
|
+
* answers HTTP 503 with the exact {@link REQUEST_OBJECT_IN_PROGRESS} message and `Retry-After`.
|
|
156
|
+
* When it is at its paid-exchange capacity it refuses before sending or billing anything with the
|
|
157
|
+
* exact {@link REQUEST_OBJECT_AT_CAPACITY} message. Only these two answers are retried, in any mix
|
|
158
|
+
* and under one shared budget, by repeating the identical GET (same URL and headers; nothing is
|
|
159
|
+
* posted, presented or paid). The wait follows `Retry-After` (delta-seconds or HTTP-date; 2 s when
|
|
160
|
+
* absent or malformed) clamped to `minDelayMs`..`maxDelayMs` (default 0.5..5 s), within
|
|
161
|
+
* `maxAttempts` (default 64) and a wall-clock budget (default 120 s, which covers the agent's
|
|
162
|
+
* longest detached exchange) that ends early at `notAfterMs`. A repeated GET still running at the
|
|
163
|
+
* end of the budget is aborted. `signal` cancels the in-flight GET or the wait at once. When the
|
|
164
|
+
* budget or attempts run out, the last 503 is thrown; the paid work may still complete on the agent.
|
|
165
|
+
* Authorization refusals, any other 503 (including an uncertain paid outcome), other statuses, a
|
|
166
|
+
* reply from a redirected URL and network errors are final. Every GET, including the first and
|
|
167
|
+
* its response body, shares that deadline and cancellation signal. An expired budget sends
|
|
168
|
+
* nothing. A 200 is verified exactly as before.
|
|
169
|
+
*
|
|
87
170
|
* @param requestUri - URL from the OpenID4VP request_uri parameter.
|
|
88
|
-
* @param opts - Request signature verification settings and
|
|
171
|
+
* @param opts - Request signature verification settings, fetch implementation, cancellation and retry limits.
|
|
89
172
|
*/
|
|
90
173
|
export async function fetchRequestObject(requestUri, opts = {}) {
|
|
91
174
|
const f = opts.fetchImpl ?? fetch;
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
175
|
+
const limits = requestObjectRetryLimits(opts.inProgressRetry);
|
|
176
|
+
const signal = opts.signal;
|
|
177
|
+
const headers = { Accept: `application/${REQUEST_OBJECT_TYP}` };
|
|
178
|
+
const deadline = Math.min(Date.now() + limits.maxTotalMs, limits.notAfterMs ?? Number.POSITIVE_INFINITY);
|
|
179
|
+
for (let attempt = 1;; attempt++) {
|
|
180
|
+
signal?.throwIfAborted();
|
|
181
|
+
const { res, body } = await boundedGet();
|
|
182
|
+
if (res.ok)
|
|
183
|
+
return verifyRequestObject(body.trim(), opts);
|
|
184
|
+
const failure = new Error(`request_uri ${requestUri} → HTTP ${res.status}: ${body.slice(0, 200)}`);
|
|
185
|
+
if (!isRetryable503(res, requestUri, body) || attempt >= limits.maxAttempts)
|
|
186
|
+
throw failure;
|
|
187
|
+
const hinted = parseRetryAfter(res.headers?.get('retry-after')) ?? IN_PROGRESS_DEFAULT_DELAY_MS;
|
|
188
|
+
const delay = Math.min(Math.max(hinted, limits.minDelayMs), limits.maxDelayMs);
|
|
189
|
+
if (Date.now() + delay >= deadline)
|
|
190
|
+
throw failure;
|
|
191
|
+
await sleep(delay, signal);
|
|
192
|
+
}
|
|
193
|
+
// Deadline admission precedes every dispatch, including the first. The race also
|
|
194
|
+
// bounds custom transports that do not honour AbortSignal themselves.
|
|
195
|
+
async function boundedGet() {
|
|
196
|
+
const ended = () => new Error(`request_uri ${requestUri} → still unavailable when the retry budget ended`);
|
|
197
|
+
if (Date.now() >= deadline)
|
|
198
|
+
throw ended();
|
|
199
|
+
const budget = new AbortController();
|
|
200
|
+
const combined = signal ? AbortSignal.any([signal, budget.signal]) : budget.signal;
|
|
201
|
+
const timer = setTimeout(() => budget.abort(ended()), deadline - Date.now());
|
|
202
|
+
let onAbort;
|
|
203
|
+
try {
|
|
204
|
+
const cancelled = new Promise((_, reject) => {
|
|
205
|
+
onAbort = () => reject(combined.reason);
|
|
206
|
+
combined.addEventListener('abort', onAbort, { once: true });
|
|
207
|
+
if (combined.aborted)
|
|
208
|
+
onAbort();
|
|
209
|
+
});
|
|
210
|
+
const response = (async () => {
|
|
211
|
+
combined.throwIfAborted();
|
|
212
|
+
const res = await f(requestUri, { headers, signal: combined });
|
|
213
|
+
const body = res.ok ? await res.text() : await res.text().catch(() => '');
|
|
214
|
+
combined.throwIfAborted();
|
|
215
|
+
return { res, body };
|
|
216
|
+
})();
|
|
217
|
+
return await Promise.race([response, cancelled]);
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
signal?.throwIfAborted();
|
|
221
|
+
if (budget.signal.aborted)
|
|
222
|
+
throw new Error(`request_uri ${requestUri} → still unavailable when the retry budget ended`, { cause: error });
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
finally {
|
|
226
|
+
clearTimeout(timer);
|
|
227
|
+
if (onAbort)
|
|
228
|
+
combined.removeEventListener('abort', onAbort);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
96
231
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { type DecryptionBindingWire } from '../crypto/recipient.js';
|
|
2
|
+
import { type PaymentIntentWire } from '../committee/payment.js';
|
|
1
3
|
import type { CompoundTokenWire } from '../committee/token.js';
|
|
2
4
|
import type { VerifierProof } from '../committee/client.js';
|
|
3
5
|
import { type CreateSessionResult, type PresentationDelegation, type PresentationOperation, type WaitOpts, type SessionStatusResult } from '../verifier-agent/index.js';
|
|
@@ -57,6 +59,8 @@ export interface TypedDataSigner {
|
|
|
57
59
|
}
|
|
58
60
|
/** Slot operation, payload context and authorization lifetime used to construct EIP-712 typed data. */
|
|
59
61
|
export interface OperationInput {
|
|
62
|
+
/** Public recipient and epoch metadata bound into the operation digest before creator authorization. */
|
|
63
|
+
decryption?: DecryptionBindingWire;
|
|
60
64
|
/** EVM chain identifier. */
|
|
61
65
|
chainId: number;
|
|
62
66
|
/** The KeyRegistry address - the EIP-712 `verifyingContract`. */
|
|
@@ -91,6 +95,10 @@ export declare function presentationOperationTypedData(input: OperationInput): {
|
|
|
91
95
|
};
|
|
92
96
|
/** Operation, signing wallet and verifier-agent endpoint for opening a presentation session. */
|
|
93
97
|
export interface OpenVerifierAgentSessionOpts extends OperationInput {
|
|
98
|
+
/** Already reserved creator payment, fixed before opening the session. */
|
|
99
|
+
payment?: PaymentIntentWire;
|
|
100
|
+
/** Random committed in payment.session_commitment. Required with payment. */
|
|
101
|
+
random?: string;
|
|
94
102
|
/** Verifier-agent HTTP base URL for the selected network. */
|
|
95
103
|
verifierAgentUrl: string;
|
|
96
104
|
/** The slot creator's key, or a delegate's (with `delegation`). */
|
|
@@ -100,6 +108,8 @@ export interface OpenVerifierAgentSessionOpts extends OperationInput {
|
|
|
100
108
|
}
|
|
101
109
|
/** Opened wallet session with its signed operation and expected request-binding hash. */
|
|
102
110
|
export interface OpenedVerifierAgentSession extends CreateSessionResult {
|
|
111
|
+
/** Expected payment commitment; a result may not change or discard it. */
|
|
112
|
+
paymentHash?: string;
|
|
103
113
|
/** Signed operation details presented for authorization. */
|
|
104
114
|
operation: PresentationOperation;
|
|
105
115
|
/** The binding hash the token will carry - compare with the token's `request_hash`. */
|
|
@@ -115,6 +125,12 @@ export interface OpenedVerifierAgentSession extends CreateSessionResult {
|
|
|
115
125
|
export declare function openVerifierAgentSession(opts: OpenVerifierAgentSessionOpts): Promise<OpenedVerifierAgentSession>;
|
|
116
126
|
/** Compound committee token with optional request preimage and verifier membership proofs. */
|
|
117
127
|
export interface VerifierAgentResult {
|
|
128
|
+
/**
|
|
129
|
+
* Sealed presentation ciphertext the token's `evidence_hash` binds, when the committee
|
|
130
|
+
* sealed one: retain it and forward it unchanged to every keeper call (`evidenceCt`); a keeper
|
|
131
|
+
* with `require_committee_evidence` refuses the token without it.
|
|
132
|
+
*/
|
|
133
|
+
evidenceCt?: string;
|
|
118
134
|
/** Compound committee authorization token. */
|
|
119
135
|
token: CompoundTokenWire;
|
|
120
136
|
/** Operation context used to derive the request-binding hash. */
|
|
@@ -125,12 +141,6 @@ export interface VerifierAgentResult {
|
|
|
125
141
|
* (`api.require_verifier_proofs`) refuses a committee request without them.
|
|
126
142
|
*/
|
|
127
143
|
verifierProofs?: VerifierProof[];
|
|
128
|
-
/**
|
|
129
|
-
* the sealed presentation the token's `evidence_hash` binds, when the committee
|
|
130
|
-
* sealed one — hand it to every keeper call (`evidenceCt`); a keeper with
|
|
131
|
-
* `require_committee_evidence` refuses the token without it.
|
|
132
|
-
*/
|
|
133
|
-
evidenceCt?: string;
|
|
134
144
|
}
|
|
135
145
|
/**
|
|
136
146
|
* The verifier-agent's `verifier_proofs` DTO (`{verifier_index, operator, pubkey, proof}`) to the SDK shape.
|
|
@@ -148,7 +158,7 @@ export declare function verifierAgentVerifierProofs(raw: unknown): VerifierProof
|
|
|
148
158
|
* @param session - Opened session credentials and expected request-binding hash.
|
|
149
159
|
* @param opts - Polling intervals, timeout, cancellation and progress callback.
|
|
150
160
|
*/
|
|
151
|
-
export declare function awaitVerifierAgentResult(session: Pick<OpenedVerifierAgentSession, 'verifierAgentUrl' | 'sessionId' | 'pollSecret' | 'requestHash'>, opts?: {
|
|
161
|
+
export declare function awaitVerifierAgentResult(session: Pick<OpenedVerifierAgentSession, 'verifierAgentUrl' | 'sessionId' | 'pollSecret' | 'requestHash' | 'paymentHash'>, opts?: {
|
|
152
162
|
intervalMs?: number;
|
|
153
163
|
timeoutMs?: number;
|
|
154
164
|
} & WaitOpts): Promise<VerifierAgentResult>;
|
|
@@ -158,4 +168,4 @@ export declare function awaitVerifierAgentResult(session: Pick<OpenedVerifierAge
|
|
|
158
168
|
* @param session - Session identifier and expected request-binding hash.
|
|
159
169
|
* @param r - Completed session status to validate and decode.
|
|
160
170
|
*/
|
|
161
|
-
export declare function verifierAgentResult(session: Pick<OpenedVerifierAgentSession, 'sessionId' | 'requestHash'>, r: SessionStatusResult): VerifierAgentResult;
|
|
171
|
+
export declare function verifierAgentResult(session: Pick<OpenedVerifierAgentSession, 'sessionId' | 'requestHash' | 'paymentHash'>, r: SessionStatusResult): VerifierAgentResult;
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { recipientPayloadDigest } from '../crypto/recipient.js';
|
|
2
|
+
import { sha256 } from '@noble/hashes/sha256';
|
|
3
|
+
import { evidenceBody } from '../committee/evidence.js';
|
|
1
4
|
// The RELYING PARTY half against the Verifier Agent: the app that wants an authorization
|
|
2
5
|
// signs the operation tuple with the slot creator's EVM key (EIP-712 `PresentationOperation`),
|
|
3
6
|
// opens a session, hands the `openid4vp://` payload to a wallet as a QR or deep link, and later
|
|
@@ -5,9 +8,11 @@
|
|
|
5
8
|
//
|
|
6
9
|
// Adds EIP-712 operation signing and action-specific payload binding to the session client.
|
|
7
10
|
import { bytesToHex, hexToBytes } from '../crypto/hex.js';
|
|
8
|
-
import {
|
|
11
|
+
import { paymentIntentHash } from '../committee/payment.js';
|
|
12
|
+
import { assertCompoundTokenWire, VerifierAgentSessionError, createOid4vpSession, waitForSession } from '../verifier-agent/index.js';
|
|
9
13
|
import { payloadDigestFor, requestHash } from './binding.js';
|
|
10
14
|
import { utf8 } from './jose.js';
|
|
15
|
+
import { sessionPaymentFields } from '../verifier-agent/payment.js';
|
|
11
16
|
export { createOid4vpSession, pollOid4vpSession, waitForSession, payloadDigest, nextPollDelay, assertCompoundTokenWire, VerifierAgentSessionError } from '../verifier-agent/index.js';
|
|
12
17
|
/** EIP-712 domain name for creator-signed presentation operations. */
|
|
13
18
|
export const PRESENTATION_EIP712_NAME = 'Keykeeper Presentation';
|
|
@@ -34,7 +39,28 @@ export function presentationOperationTypedData(input) {
|
|
|
34
39
|
if (slot.length !== 32)
|
|
35
40
|
throw new Error('slotId must be 32 bytes');
|
|
36
41
|
const messageBytes = input.action === 'ibe-extract' ? (input.identity !== undefined ? utf8(input.identity) : undefined) : input.message;
|
|
37
|
-
|
|
42
|
+
let digest;
|
|
43
|
+
if (input.action === 'decrypt' || input.action === 'ibe-extract') {
|
|
44
|
+
const d = input.decryption;
|
|
45
|
+
if (!d)
|
|
46
|
+
throw new Error('Recipient binding required before decryption authorization');
|
|
47
|
+
if (input.action === 'ibe-extract' && input.identity === undefined)
|
|
48
|
+
throw new Error('IBE requires identity');
|
|
49
|
+
const content = input.action === 'ibe-extract' ? sha256(utf8(input.identity)) : hexToBytes(d.content_digest ?? '');
|
|
50
|
+
if (input.action === 'ibe-extract' && d.content_digest !== undefined) {
|
|
51
|
+
const supplied = hexToBytes(d.content_digest);
|
|
52
|
+
if (supplied.length !== 32 || !content.every((b, i) => b === supplied[i]))
|
|
53
|
+
throw new Error('IBE content digest differs from identity');
|
|
54
|
+
}
|
|
55
|
+
digest = recipientPayloadDigest(content, d.ciphertext_epoch, d.recipient);
|
|
56
|
+
if (input.payloadDigest && (input.payloadDigest.length !== 32 || !digest.every((b, i) => b === input.payloadDigest[i])))
|
|
57
|
+
throw new Error('Supplied digest differs from recipient binding');
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
if (input.decryption)
|
|
61
|
+
throw new Error('Recipient binding only applies to decryption');
|
|
62
|
+
digest = payloadDigestFor(input.action, { message: input.message, identity: input.identity, payloadDigest: input.payloadDigest });
|
|
63
|
+
}
|
|
38
64
|
// The verifier-agent requires `message_hex` and, for sign / ibe-extract, derives the digest from it; for the
|
|
39
65
|
// other actions the digest is taken as signed, so the digest itself is the message it stores.
|
|
40
66
|
const messageHex = bytesToHex(messageBytes ?? digest);
|
|
@@ -66,10 +92,15 @@ export function presentationOperationTypedData(input) {
|
|
|
66
92
|
*/
|
|
67
93
|
export async function openVerifierAgentSession(opts) {
|
|
68
94
|
const { typedData, operation, messageHex, payloadDigest } = presentationOperationTypedData(opts);
|
|
69
|
-
const
|
|
70
|
-
const
|
|
95
|
+
const payment = opts.payment && structuredClone(opts.payment), random = opts.random;
|
|
96
|
+
const delegation = opts.delegation && structuredClone(opts.delegation), verifierAgentUrl = opts.verifierAgentUrl;
|
|
97
|
+
sessionPaymentFields({ operation, operationSig: '0x', messageHex, payment, random });
|
|
98
|
+
const paymentHash = payment && paymentIntentHash(payment);
|
|
71
99
|
const slot = typeof opts.slotId === 'string' ? hexToBytes(opts.slotId) : opts.slotId;
|
|
72
|
-
|
|
100
|
+
const expectedRequestHash = requestHash(opts.chainId, slot, opts.action, payloadDigest);
|
|
101
|
+
const operationSig = await opts.signer.signTypedData(typedData);
|
|
102
|
+
const session = await createOid4vpSession(verifierAgentUrl, { operation, operationSig, delegation, messageHex, payment, random, decryption: opts.decryption });
|
|
103
|
+
return { ...session, operation, ...(paymentHash ? { paymentHash } : {}), requestHash: expectedRequestHash, verifierAgentUrl };
|
|
73
104
|
}
|
|
74
105
|
/**
|
|
75
106
|
* The verifier-agent's `verifier_proofs` DTO (`{verifier_index, operator, pubkey, proof}`) to the SDK shape.
|
|
@@ -116,11 +147,22 @@ export async function awaitVerifierAgentResult(session, opts = {}) {
|
|
|
116
147
|
export function verifierAgentResult(session, r) {
|
|
117
148
|
if (r.status !== 'done' || !r.compoundToken)
|
|
118
149
|
throw new VerifierAgentSessionError('refused', session.sessionId, `presentation ${r.status}: ${r.error ?? 'no token'}`);
|
|
119
|
-
const token = r.compoundToken;
|
|
150
|
+
const token = assertCompoundTokenWire(r.compoundToken, session.sessionId);
|
|
151
|
+
try {
|
|
152
|
+
evidenceBody(token, r.evidenceCt);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
throw new VerifierAgentSessionError('protocol', session.sessionId, 'the token lacks its bound sealed evidence');
|
|
156
|
+
}
|
|
120
157
|
const rh = token.request_hash;
|
|
121
158
|
if (!rh || rh.replace(/^0x/, '').toLowerCase() !== bytesToHex(session.requestHash).replace(/^0x/, '').toLowerCase()) {
|
|
122
159
|
throw new VerifierAgentSessionError('protocol', session.sessionId, 'the token does not bind the request this session opened');
|
|
123
160
|
}
|
|
161
|
+
const actualPayment = token.payment_hash?.replace(/^0x/, '').toLowerCase();
|
|
162
|
+
const expectedPayment = session.paymentHash?.replace(/^0x/, '').toLowerCase();
|
|
163
|
+
if (actualPayment !== expectedPayment || (expectedPayment && !token.payment)) {
|
|
164
|
+
throw new VerifierAgentSessionError('protocol', session.sessionId, 'the token does not bind the payment this session opened');
|
|
165
|
+
}
|
|
124
166
|
let verifierProofs;
|
|
125
167
|
try {
|
|
126
168
|
verifierProofs = verifierAgentVerifierProofs(r.verifierProofs);
|
package/dist/oid4vp/wallet.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type CredentialView, type Query } from '../auth/oid4vp.js';
|
|
2
2
|
import { type JweEnc } from './jwe.js';
|
|
3
3
|
import type { HolderKey } from './jose.js';
|
|
4
|
-
import { type VerifiedRequestObject, type
|
|
4
|
+
import { type VerifiedRequestObject, type FetchRequestObjectOpts } from './request-object.js';
|
|
5
5
|
import { type ParsedSdJwt } from './sd-jwt.js';
|
|
6
6
|
/** A credential the wallet holds. */
|
|
7
7
|
export interface HeldSdJwt {
|
|
@@ -91,9 +91,7 @@ export declare function submitResponse(ro: Pick<VerifiedRequestObject, 'claims'>
|
|
|
91
91
|
redirectUri?: string;
|
|
92
92
|
}>;
|
|
93
93
|
/** Request verification, credential selection and disclosure options for a wallet presentation. */
|
|
94
|
-
export interface PresentOpts extends
|
|
95
|
-
/** HTTP transport override; defaults to the global fetch implementation. */
|
|
96
|
-
fetchImpl?: typeof fetch;
|
|
94
|
+
export interface PresentOpts extends FetchRequestObjectOpts {
|
|
97
95
|
/** Pick among the candidates (default: the evaluator's choice). Return `undefined` to abort. */
|
|
98
96
|
choose?: (plan: PresentationPlan) => PresentationCandidate | undefined | Promise<PresentationCandidate | undefined>;
|
|
99
97
|
/** Claim names to disclose, or all; defaults to the selected query's requested claims. */
|
package/dist/oid4vp/wallet.js
CHANGED
|
@@ -100,6 +100,7 @@ export async function presentToRequestUri(requestUriOrOpenid4vp, held, holder, o
|
|
|
100
100
|
const ro = await fetchRequestObject(requestUri, opts);
|
|
101
101
|
const plan = planPresentation(ro, held, opts.nowSecs);
|
|
102
102
|
const candidate = opts.choose ? await opts.choose(plan) : plan.chosen;
|
|
103
|
+
opts.signal?.throwIfAborted();
|
|
103
104
|
if (!candidate)
|
|
104
105
|
throw new Error(plan.unmatched.length ? `no held credential answers: ${plan.unmatched.join(', ')}` : 'presentation declined');
|
|
105
106
|
const built = buildResponse({ ro, candidate, holder, disclose: opts.disclose, nowSecs: opts.nowSecs });
|
package/dist/retry.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { parseRetryAfter } from './internal/retryAfter.js';
|
|
2
|
+
export { parseRetryAfter };
|
|
3
|
+
/** Limits for one retried request. Every field is optional and bounded. */
|
|
4
|
+
export interface RetryPolicy {
|
|
5
|
+
/** Total sends including the first, 1..10 (default 4). */
|
|
6
|
+
maxAttempts?: number;
|
|
7
|
+
/** First backoff when the service gives no `Retry-After`, in ms (default 250). */
|
|
8
|
+
baseDelayMs?: number;
|
|
9
|
+
/** Largest single wait in ms (default 10000). A longer `Retry-After` ends retrying. */
|
|
10
|
+
maxDelayMs?: number;
|
|
11
|
+
/** Largest sum of all waits in ms (default 30000, at most 600000). */
|
|
12
|
+
maxTotalWaitMs?: number;
|
|
13
|
+
/** Source of uniform randomness in [0, 1) for jitter; defaults to Math.random. */
|
|
14
|
+
random?: () => number;
|
|
15
|
+
}
|
|
16
|
+
/** Classification of one failed attempt. */
|
|
17
|
+
export interface RetryDecision {
|
|
18
|
+
/** Whether sending the same request again may succeed. */
|
|
19
|
+
retry: boolean;
|
|
20
|
+
/** Service-requested minimum wait in ms, when it sent one. */
|
|
21
|
+
retryAfterMs?: number;
|
|
22
|
+
}
|
|
23
|
+
/** HTTP statuses that mean "not now" and are retried even without a header. */
|
|
24
|
+
export declare const RETRY_STATUSES: readonly number[];
|
|
25
|
+
/** HTTP statuses retried only when the service explicitly sends `Retry-After`. */
|
|
26
|
+
export declare const RETRY_AFTER_ONLY_STATUSES: readonly number[];
|
|
27
|
+
/**
|
|
28
|
+
* The wait before the next attempt, or undefined when the policy says to stop.
|
|
29
|
+
* A service `Retry-After` is a floor: the wait adds up to 20% (max 1 s) of jitter on top so
|
|
30
|
+
* that refused clients do not return in lockstep, and it is never shortened. A requested wait
|
|
31
|
+
* above `maxDelayMs` or beyond the remaining total budget stops retrying instead.
|
|
32
|
+
* Without a header the wait is full-jitter exponential backoff from `baseDelayMs`.
|
|
33
|
+
* @param attempt Zero-based index of the attempt that just failed.
|
|
34
|
+
* @param retryAfterMs Service-requested wait, when any.
|
|
35
|
+
* @param policy Retry limits.
|
|
36
|
+
* @param waitedMs Sum of the waits already spent on this request.
|
|
37
|
+
*/
|
|
38
|
+
export declare function retryDelayMs(attempt: number, retryAfterMs: number | undefined, policy?: RetryPolicy, waitedMs?: number): number | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Default classification for an idempotent request: retry 425/429/503, a 409/410/422 only
|
|
41
|
+
* when the service sent `Retry-After`, other 5xx and unreachable endpoints with backoff.
|
|
42
|
+
* Authorization refusals and other 4xx are final.
|
|
43
|
+
* @param error Failure thrown by one attempt.
|
|
44
|
+
*/
|
|
45
|
+
export declare function classifyRetry(error: unknown): RetryDecision;
|
|
46
|
+
/**
|
|
47
|
+
* Retry only explicit "not now" refusals: 425/429/503, or 409/410/422 carrying
|
|
48
|
+
* `Retry-After`. Generic 5xx and transport failures are final. Suits requests whose
|
|
49
|
+
* repetition is harmless but whose callers expect a prompt failure otherwise.
|
|
50
|
+
* @param error Failure thrown by one attempt.
|
|
51
|
+
*/
|
|
52
|
+
export declare function classifyRefusal(error: unknown): RetryDecision;
|
|
53
|
+
/**
|
|
54
|
+
* Classification for a write whose refusal proves it was not processed: only HTTP 429, which
|
|
55
|
+
* the verifier uses for SP-11 capacity refusals before it stores anything. A 5xx or lost reply
|
|
56
|
+
* may follow processing, so it is final here.
|
|
57
|
+
* @param error Failure thrown by one attempt.
|
|
58
|
+
*/
|
|
59
|
+
export declare function classifyRefusedWrite(error: unknown): RetryDecision;
|
|
60
|
+
/**
|
|
61
|
+
* Send one idempotent request, waiting between attempts as the service and policy allow.
|
|
62
|
+
* The last failure is rethrown unchanged when the policy is exhausted, the classification says
|
|
63
|
+
* stop, or the requested wait is longer than allowed. Only wrap a request that is safe to send
|
|
64
|
+
* again; this function cannot tell.
|
|
65
|
+
* @param work Sends the identical request; receives the zero-based attempt number.
|
|
66
|
+
* @param options Policy, cancellation and an optional classifier (default {@link classifyRetry}).
|
|
67
|
+
*/
|
|
68
|
+
export declare function retryIdempotent<T>(work: (attempt: number) => Promise<T>, options?: {
|
|
69
|
+
policy?: RetryPolicy;
|
|
70
|
+
signal?: AbortSignal;
|
|
71
|
+
classify?: (error: unknown) => RetryDecision;
|
|
72
|
+
/** Observe each scheduled wait (for logging or UI); never called for the final failure. */
|
|
73
|
+
onRetry?: (event: {
|
|
74
|
+
attempt: number;
|
|
75
|
+
delayMs: number;
|
|
76
|
+
error: unknown;
|
|
77
|
+
}) => void;
|
|
78
|
+
}): Promise<T>;
|
package/dist/retry.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Bounded, jittered waits for requests that are safe to send again.
|
|
2
|
+
//
|
|
3
|
+
// Services answer load and capacity refusals with a status and, often, a `Retry-After`
|
|
4
|
+
// header: the verifier's nonce and renewal stores (429, SP-11), the relayer's busy lanes,
|
|
5
|
+
// full journal and unavailable shared budget (422 `rejected`), and generic 503s. This
|
|
6
|
+
// module turns that header into a wait the caller can bound.
|
|
7
|
+
//
|
|
8
|
+
// ⚠ It never decides that a request is safe to repeat. Callers wrap only a request that is
|
|
9
|
+
// idempotent, or one whose refusal proves it was not processed (an HTTP 429 capacity refusal,
|
|
10
|
+
// an identical signed relay request whose nonce the chain spends once). A paid flow, a
|
|
11
|
+
// reservation or any other write with an uncertain outcome must be reconciled, never retried.
|
|
12
|
+
import { TasraError, TasraHttpError, NodeUnreachableError } from './errors.js';
|
|
13
|
+
import { parseRetryAfter } from './internal/retryAfter.js';
|
|
14
|
+
import { sleep } from './internal/sleep.js';
|
|
15
|
+
export { parseRetryAfter };
|
|
16
|
+
/** HTTP statuses that mean "not now" and are retried even without a header. */
|
|
17
|
+
export const RETRY_STATUSES = Object.freeze([425, 429, 503]);
|
|
18
|
+
/** HTTP statuses retried only when the service explicitly sends `Retry-After`. */
|
|
19
|
+
export const RETRY_AFTER_ONLY_STATUSES = Object.freeze([409, 410, 422]);
|
|
20
|
+
function limits(policy = {}) {
|
|
21
|
+
const value = (v, fallback, min, max, name) => {
|
|
22
|
+
const n = v ?? fallback;
|
|
23
|
+
if (!Number.isSafeInteger(n) || n < min || n > max)
|
|
24
|
+
throw new TasraError(`Invalid retry policy ${name}`);
|
|
25
|
+
return n;
|
|
26
|
+
};
|
|
27
|
+
const maxDelayMs = value(policy.maxDelayMs, 10_000, 1, 600_000, 'maxDelayMs');
|
|
28
|
+
const random = policy.random ?? Math.random;
|
|
29
|
+
if (typeof random !== 'function')
|
|
30
|
+
throw new TasraError('Invalid retry policy random');
|
|
31
|
+
return { maxAttempts: value(policy.maxAttempts, 4, 1, 10, 'maxAttempts'), baseDelayMs: value(policy.baseDelayMs, 250, 1, maxDelayMs, 'baseDelayMs'),
|
|
32
|
+
maxDelayMs, maxTotalWaitMs: value(policy.maxTotalWaitMs, 30_000, 0, 600_000, 'maxTotalWaitMs'), random };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The wait before the next attempt, or undefined when the policy says to stop.
|
|
36
|
+
* A service `Retry-After` is a floor: the wait adds up to 20% (max 1 s) of jitter on top so
|
|
37
|
+
* that refused clients do not return in lockstep, and it is never shortened. A requested wait
|
|
38
|
+
* above `maxDelayMs` or beyond the remaining total budget stops retrying instead.
|
|
39
|
+
* Without a header the wait is full-jitter exponential backoff from `baseDelayMs`.
|
|
40
|
+
* @param attempt Zero-based index of the attempt that just failed.
|
|
41
|
+
* @param retryAfterMs Service-requested wait, when any.
|
|
42
|
+
* @param policy Retry limits.
|
|
43
|
+
* @param waitedMs Sum of the waits already spent on this request.
|
|
44
|
+
*/
|
|
45
|
+
export function retryDelayMs(attempt, retryAfterMs, policy = {}, waitedMs = 0) {
|
|
46
|
+
const p = limits(policy);
|
|
47
|
+
if (!Number.isSafeInteger(attempt) || attempt < 0 || !Number.isSafeInteger(waitedMs) || waitedMs < 0)
|
|
48
|
+
throw new TasraError('Invalid retry state');
|
|
49
|
+
if (attempt + 1 >= p.maxAttempts)
|
|
50
|
+
return undefined;
|
|
51
|
+
const remaining = p.maxTotalWaitMs - waitedMs;
|
|
52
|
+
const r = Math.min(Math.max(p.random(), 0), 0.999_999);
|
|
53
|
+
let delay;
|
|
54
|
+
if (retryAfterMs !== undefined) {
|
|
55
|
+
if (!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0)
|
|
56
|
+
throw new TasraError('Invalid Retry-After');
|
|
57
|
+
if (retryAfterMs > p.maxDelayMs || retryAfterMs > remaining)
|
|
58
|
+
return undefined;
|
|
59
|
+
const jitter = Math.floor(r * Math.min(1000, retryAfterMs * 0.2, p.maxDelayMs - retryAfterMs, remaining - retryAfterMs));
|
|
60
|
+
delay = retryAfterMs + Math.max(0, jitter);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
const ceiling = Math.min(p.maxDelayMs, p.baseDelayMs * 2 ** Math.min(attempt, 20));
|
|
64
|
+
delay = Math.floor(r * ceiling);
|
|
65
|
+
if (delay > remaining)
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
return delay;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Default classification for an idempotent request: retry 425/429/503, a 409/410/422 only
|
|
72
|
+
* when the service sent `Retry-After`, other 5xx and unreachable endpoints with backoff.
|
|
73
|
+
* Authorization refusals and other 4xx are final.
|
|
74
|
+
* @param error Failure thrown by one attempt.
|
|
75
|
+
*/
|
|
76
|
+
export function classifyRetry(error) {
|
|
77
|
+
if (error instanceof TasraHttpError) {
|
|
78
|
+
const after = error.retryAfterMs;
|
|
79
|
+
if (RETRY_STATUSES.includes(error.status))
|
|
80
|
+
return { retry: true, retryAfterMs: after };
|
|
81
|
+
if (RETRY_AFTER_ONLY_STATUSES.includes(error.status))
|
|
82
|
+
return after === undefined ? { retry: false } : { retry: true, retryAfterMs: after };
|
|
83
|
+
return { retry: error.status >= 500 && error.status !== 501, retryAfterMs: after };
|
|
84
|
+
}
|
|
85
|
+
return { retry: error instanceof NodeUnreachableError };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Retry only explicit "not now" refusals: 425/429/503, or 409/410/422 carrying
|
|
89
|
+
* `Retry-After`. Generic 5xx and transport failures are final. Suits requests whose
|
|
90
|
+
* repetition is harmless but whose callers expect a prompt failure otherwise.
|
|
91
|
+
* @param error Failure thrown by one attempt.
|
|
92
|
+
*/
|
|
93
|
+
export function classifyRefusal(error) {
|
|
94
|
+
const decision = classifyRetry(error);
|
|
95
|
+
return error instanceof TasraHttpError && (RETRY_STATUSES.includes(error.status) || RETRY_AFTER_ONLY_STATUSES.includes(error.status))
|
|
96
|
+
? decision : { retry: false };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Classification for a write whose refusal proves it was not processed: only HTTP 429, which
|
|
100
|
+
* the verifier uses for SP-11 capacity refusals before it stores anything. A 5xx or lost reply
|
|
101
|
+
* may follow processing, so it is final here.
|
|
102
|
+
* @param error Failure thrown by one attempt.
|
|
103
|
+
*/
|
|
104
|
+
export function classifyRefusedWrite(error) {
|
|
105
|
+
return error instanceof TasraHttpError && error.status === 429 ? { retry: true, retryAfterMs: error.retryAfterMs } : { retry: false };
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Send one idempotent request, waiting between attempts as the service and policy allow.
|
|
109
|
+
* The last failure is rethrown unchanged when the policy is exhausted, the classification says
|
|
110
|
+
* stop, or the requested wait is longer than allowed. Only wrap a request that is safe to send
|
|
111
|
+
* again; this function cannot tell.
|
|
112
|
+
* @param work Sends the identical request; receives the zero-based attempt number.
|
|
113
|
+
* @param options Policy, cancellation and an optional classifier (default {@link classifyRetry}).
|
|
114
|
+
*/
|
|
115
|
+
export async function retryIdempotent(work, options = {}) {
|
|
116
|
+
const policy = { ...options.policy }, classify = options.classify ?? classifyRetry;
|
|
117
|
+
limits(policy);
|
|
118
|
+
let waited = 0;
|
|
119
|
+
for (let attempt = 0;; attempt++) {
|
|
120
|
+
options.signal?.throwIfAborted();
|
|
121
|
+
try {
|
|
122
|
+
return await work(attempt);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
options.signal?.throwIfAborted();
|
|
126
|
+
const decision = classify(error);
|
|
127
|
+
if (!decision.retry)
|
|
128
|
+
throw error;
|
|
129
|
+
const delay = retryDelayMs(attempt, decision.retryAfterMs, policy, waited);
|
|
130
|
+
if (delay === undefined)
|
|
131
|
+
throw error;
|
|
132
|
+
options.onRetry?.({ attempt, delayMs: delay, error });
|
|
133
|
+
await sleep(delay, options.signal);
|
|
134
|
+
waited += delay;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|