@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
|
@@ -0,0 +1,889 @@
|
|
|
1
|
+
import { verifyEvidenceBinding } from '../committee/evidence.js';
|
|
2
|
+
import { sha256 } from '@noble/hashes/sha256';
|
|
3
|
+
import { concatBytes } from '@noble/hashes/utils';
|
|
4
|
+
import { p256 } from '@noble/curves/p256';
|
|
5
|
+
import { ed25519 } from '@noble/curves/ed25519';
|
|
6
|
+
import { accessTokenHash, jwkThumbprint } from '../auth/dpop.js';
|
|
7
|
+
import { hashTypedData, keccak256, toHex } from 'viem';
|
|
8
|
+
import { approveExecutionRequest, executionBodyHash, executionInitializationTypedData, initializeExecutionSession } from '../committee/execution.js';
|
|
9
|
+
import { paymentIntentHash } from '../committee/payment.js';
|
|
10
|
+
import { protocolHex } from '../committee/receipts.js';
|
|
11
|
+
import { recipientPayloadDigest } from '../crypto/recipient.js';
|
|
12
|
+
import { dpopHtu, platformAudience, isValidSessionId } from '../committee/oauth.js';
|
|
13
|
+
import { BINDING_HOLDER_KEY, assertStatusAttestationsWire, decodeCompoundToken, selectVerifierCommittee, verifierLeaf, verifyCompoundToken, verifyMerkleProof, requireStatusAttestations, compoundTokenHash } from '../committee/token.js';
|
|
14
|
+
import { vpNonceBound, requestHash } from '../oid4vp/binding.js';
|
|
15
|
+
import { MAX_SESSION_SLOTS, decodeSessionGrant, parseSessionKeyJwk, sessionKeyThumbprint, verifySessionGrant } from '../committee/session-grant.js';
|
|
16
|
+
import { b64urlDecode, decodeJson } from '../oid4vp/jose.js';
|
|
17
|
+
import { verifyRequestObject } from '../oid4vp/request-object.js';
|
|
18
|
+
import { parseVerifierAgentSessionStatus } from '../verifier-agent/index.js';
|
|
19
|
+
import { sessionPaymentFields } from '../verifier-agent/payment.js';
|
|
20
|
+
import { readClientExecutionPolicy } from './prepaid.js';
|
|
21
|
+
import { authenticateApprovedService, validateServiceEndpoint } from './serviceIdentity.js';
|
|
22
|
+
import { registerHeadPrefetch } from './headPrefetch.js';
|
|
23
|
+
import { chainIdOf } from './chainId.js';
|
|
24
|
+
import { currentServiceRecord } from './services.js';
|
|
25
|
+
import { PaidBackoff, paidResponseWaitMs, systemPacingClock } from './paidPacing.js';
|
|
26
|
+
/** Manifest capability of an agent that accepts a batch of approvals in one request. */
|
|
27
|
+
export const BATCH_APPROVAL_CAPABILITY = 'execution-approve-batch';
|
|
28
|
+
/** Manifest capability of an agent that holds a proposal listing until one is pending (`?wait_ms=`). */
|
|
29
|
+
export const PROPOSAL_WAIT_CAPABILITY = 'execution-wait';
|
|
30
|
+
/** Longest proposal hold the client asks for (the agent's own cap). */
|
|
31
|
+
export const MAX_PROPOSAL_WAIT_MS = 25_000;
|
|
32
|
+
const HEX32_LOWER = /^0x[0-9a-f]{64}$/;
|
|
33
|
+
/**
|
|
34
|
+
* Validate a session-mode request before anything is signed: KEM decrypt only, a public key, 1..16
|
|
35
|
+
* distinct 32-byte slots naming the session's own slot, positive whole-second lifetimes. Returns
|
|
36
|
+
* the canonical form the create body carries (slots lowercase and ascending, the key re-encoded
|
|
37
|
+
* with exactly its RFC 7638 members), so a retry and a resume send the same signed bytes.
|
|
38
|
+
*/
|
|
39
|
+
function sessionGrantRequest(params) {
|
|
40
|
+
const r = params.sessionGrant;
|
|
41
|
+
if (r === undefined)
|
|
42
|
+
return undefined;
|
|
43
|
+
if (params.operation.action !== 'decrypt')
|
|
44
|
+
throw new Error('A session grant opens only from a KEM decrypt presentation');
|
|
45
|
+
if (!r || typeof r !== 'object' || Object.keys(r).some(k => !['session_key', 'slots', 'access_ttl_secs', 'idle_timeout_secs', 'absolute_ttl_secs'].includes(k)))
|
|
46
|
+
throw new Error('Invalid session grant request');
|
|
47
|
+
const slots = Array.isArray(r.slots) ? r.slots.map(s => typeof s === 'string' ? s.toLowerCase() : '') : [];
|
|
48
|
+
if (slots.length < 1 || slots.length > MAX_SESSION_SLOTS || new Set(slots).size !== slots.length || slots.some(s => !HEX32_LOWER.test(s))
|
|
49
|
+
|| !slots.includes(params.operation.slot_id.toLowerCase()))
|
|
50
|
+
throw new Error('A session grant names 1..16 distinct slots, including the presentation slot');
|
|
51
|
+
for (const n of [r.access_ttl_secs, r.idle_timeout_secs, r.absolute_ttl_secs])
|
|
52
|
+
if (!Number.isSafeInteger(n) || n < 1)
|
|
53
|
+
throw new Error('Session grant lifetimes must be positive whole seconds');
|
|
54
|
+
return { session_key: parseSessionKeyJwk(r.session_key), slots: slots.sort(), access_ttl_secs: r.access_ttl_secs, idle_timeout_secs: r.idle_timeout_secs, absolute_ttl_secs: r.absolute_ttl_secs };
|
|
55
|
+
}
|
|
56
|
+
/** HTTP refusal or consent/recovery wait, with no credential-bearing response text. */
|
|
57
|
+
export class PaidAgentControlError extends Error {
|
|
58
|
+
sessionId;
|
|
59
|
+
httpStatus;
|
|
60
|
+
retryAfterMs;
|
|
61
|
+
constructor(
|
|
62
|
+
/** Original locally derived session identity. */ sessionId,
|
|
63
|
+
/** Observed status; this never authorizes an automatic resend. */ httpStatus,
|
|
64
|
+
/** Agent-requested wait in ms (`Retry-After`), when sent; a polling hint for reads and consent waits. */ retryAfterMs) {
|
|
65
|
+
super(`Paid session control returned HTTP ${httpStatus} (session ${sessionId.slice(0, 12)}…)`);
|
|
66
|
+
this.sessionId = sessionId;
|
|
67
|
+
this.httpStatus = httpStatus;
|
|
68
|
+
this.retryAfterMs = retryAfterMs;
|
|
69
|
+
this.name = 'PaidAgentControlError';
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Smallest attempt budget that fits the agent's 20 s long-poll hold plus network headroom. */
|
|
73
|
+
const HELD_POLL_MIN_BUDGET_MS = 25_000;
|
|
74
|
+
function object(value) {
|
|
75
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
76
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
|
|
77
|
+
throw new Error('Invalid paid agent object');
|
|
78
|
+
const o = value;
|
|
79
|
+
if (Object.getOwnPropertySymbols(o).length || Object.values(Object.getOwnPropertyDescriptors(o)).some(d => !d.enumerable || !Object.hasOwn(d, 'value')))
|
|
80
|
+
throw new Error('Paid agent objects must contain only JSON properties');
|
|
81
|
+
return o;
|
|
82
|
+
}
|
|
83
|
+
function exact(value, fields) {
|
|
84
|
+
if (Object.keys(value).length !== fields.length || fields.some(k => !Object.hasOwn(value, k)))
|
|
85
|
+
throw new Error('Unexpected paid agent fields');
|
|
86
|
+
}
|
|
87
|
+
function decode(bytes) {
|
|
88
|
+
try {
|
|
89
|
+
return object(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
throw new Error('Invalid paid agent reply JSON');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async function bounded(signal, work, timeoutMs = 60_000) {
|
|
96
|
+
const controller = new AbortController(), active = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
97
|
+
const timer = setTimeout(() => controller.abort(new Error('Paid agent operation timed out')), timeoutMs);
|
|
98
|
+
let abort = () => { };
|
|
99
|
+
try {
|
|
100
|
+
active.throwIfAborted();
|
|
101
|
+
return await Promise.race([work(active), new Promise((_, reject) => {
|
|
102
|
+
abort = () => reject(active.reason);
|
|
103
|
+
active.addEventListener('abort', abort, { once: true });
|
|
104
|
+
if (active.aborted)
|
|
105
|
+
abort();
|
|
106
|
+
})]);
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
active.removeEventListener('abort', abort);
|
|
111
|
+
controller.abort();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function id(value) {
|
|
115
|
+
if (typeof value !== 'string' || !/^[0-9a-f]{64}$/.test(value))
|
|
116
|
+
throw new Error('Invalid paid session correlation identity');
|
|
117
|
+
return value;
|
|
118
|
+
}
|
|
119
|
+
function epochBytes(value) {
|
|
120
|
+
const out = new Uint8Array(8);
|
|
121
|
+
new DataView(out.buffer).setBigUint64(0, BigInt(value));
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
function b64(value) {
|
|
125
|
+
return btoa(String.fromCharCode(...value)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
126
|
+
}
|
|
127
|
+
function encryptedKey(value) {
|
|
128
|
+
const key = object(value);
|
|
129
|
+
exact(key, ['kty', 'crv', 'x', 'y', 'alg', 'use', 'kid']);
|
|
130
|
+
if (key.kty !== 'EC' || key.crv !== 'P-256' || key.alg !== 'ECDH-ES' || key.use !== 'enc'
|
|
131
|
+
|| typeof key.kid !== 'string' || !/^[0-9a-f]{32}$/.test(key.kid))
|
|
132
|
+
throw new Error('Invalid public session encryption key');
|
|
133
|
+
const coordinate = (value) => {
|
|
134
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(value))
|
|
135
|
+
throw new Error('Invalid encryption coordinate');
|
|
136
|
+
const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/')), c => c.charCodeAt(0));
|
|
137
|
+
if (bytes.length !== 32 || b64(bytes) !== value)
|
|
138
|
+
throw new Error('Noncanonical encryption coordinate');
|
|
139
|
+
return bytes;
|
|
140
|
+
};
|
|
141
|
+
p256.ProjectivePoint.fromHex(concatBytes(new Uint8Array([4]), coordinate(key.x), coordinate(key.y)));
|
|
142
|
+
return structuredClone(key);
|
|
143
|
+
}
|
|
144
|
+
function presented(value) {
|
|
145
|
+
const o = object(value);
|
|
146
|
+
exact(o, ['holder', 'credentials', 'holder_proof', 'oauth', 'iat']);
|
|
147
|
+
executionBodyHash(o);
|
|
148
|
+
if (typeof value.holder !== 'string' || !Number.isSafeInteger(value.iat) || value.iat < 0
|
|
149
|
+
|| !Array.isArray(value.credentials) || value.credentials.length > 32
|
|
150
|
+
|| value.credentials.some(v => typeof v !== 'string' || !v.length || /\s/.test(v))
|
|
151
|
+
|| (value.holder_proof !== null && typeof value.holder_proof !== 'string'))
|
|
152
|
+
throw new Error('Invalid client-approved presentation');
|
|
153
|
+
if (value.oauth !== null) {
|
|
154
|
+
exact(object(value.oauth), ['access_token', 'dpop_proof', 'session_id']);
|
|
155
|
+
if (value.credentials.length || typeof value.oauth.access_token !== 'string' || typeof value.oauth.dpop_proof !== 'string'
|
|
156
|
+
|| !value.oauth.access_token || !value.oauth.dpop_proof || !isValidSessionId(value.oauth.session_id))
|
|
157
|
+
throw new Error('Invalid OAuth presentation');
|
|
158
|
+
}
|
|
159
|
+
else if (!value.credentials.length)
|
|
160
|
+
throw new Error('Empty wallet presentation');
|
|
161
|
+
return structuredClone(value);
|
|
162
|
+
}
|
|
163
|
+
// Mirrors the agent's signed_jws_expiry reader: only the issuer payload sets
|
|
164
|
+
// this bound, never an SD-JWT disclosure or holder KB-JWT. This is advisory
|
|
165
|
+
// decoding; the drawn verifiers still authenticate the complete evidence.
|
|
166
|
+
function issuerExpiry(credential) {
|
|
167
|
+
const parts = credential.split('~', 1)[0].split('.');
|
|
168
|
+
if (parts.length !== 3)
|
|
169
|
+
return undefined;
|
|
170
|
+
const payload = parts[1].replace(/=+$/, '');
|
|
171
|
+
if (!/^[A-Za-z0-9_-]*$/.test(payload))
|
|
172
|
+
return undefined;
|
|
173
|
+
try {
|
|
174
|
+
const exp = object(decodeJson(payload)).exp;
|
|
175
|
+
if (typeof exp === 'number' && Number.isFinite(exp) && exp >= -(2 ** 63) && exp < 2 ** 63)
|
|
176
|
+
return Math.floor(exp);
|
|
177
|
+
}
|
|
178
|
+
catch { /* Unreadable evidence contributes no bound; verifiers refuse it. */ }
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
// One provider authentication (registry record, manifest, identity challenge, record recheck)
|
|
182
|
+
// serves later sessions to the same approved agent until its own challenge expiry, but only while
|
|
183
|
+
// the registration read at the head (the followed tip when a live follower is attached, otherwise
|
|
184
|
+
// latest by RPC) is field for field the record it authenticated. A head follower also drops it at
|
|
185
|
+
// the first new head where that record differs. The per-request provider check is unchanged.
|
|
186
|
+
// Accepted trade-off (security review P5): within the 25 s challenge lifetime a reused
|
|
187
|
+
// authentication does NOT re-prove that the endpoint holds the registered auth key. What still
|
|
188
|
+
// binds each request to the registered provider: TLS (certificate and host) is validated on every
|
|
189
|
+
// connection, the registered record (auth key, endpoint, owner, revision, manifest, status) is
|
|
190
|
+
// compared field by field at every reuse and before every agent request, and a mismatch drops the
|
|
191
|
+
// reuse at once. A provider that loses its auth key but keeps its TLS endpoint inside that window
|
|
192
|
+
// is not detected until the next full authentication.
|
|
193
|
+
const MAX_REUSED_AUTHENTICATIONS = 16;
|
|
194
|
+
const reusedAuthentications = new WeakMap();
|
|
195
|
+
const RECORD_FIELDS = ['owner', 'pendingOwner', 'authKey', 'serviceType', 'status', 'revision', 'manifestHash', 'endpoint'];
|
|
196
|
+
const sameRecord = (a, b) => RECORD_FIELDS.every(k => typeof a[k] === 'string' && typeof b[k] === 'string' ? a[k].toLowerCase() === b[k].toLowerCase() : a[k] === b[k]);
|
|
197
|
+
const reuseKey = (profile) => {
|
|
198
|
+
const a = profile.approval;
|
|
199
|
+
return [a.chainId, a.registry, a.serviceId, a.owner, a.revision, a.manifestHash, profile.endpoint].join('|').toLowerCase();
|
|
200
|
+
};
|
|
201
|
+
/** Forget the reused authentication of `profile` on `chain` (synchronously: before the caller sends anything else). */
|
|
202
|
+
function dropReusedAuthentication(chain, profile) {
|
|
203
|
+
reusedAuthentications.get(chain.client)?.delete(reuseKey(profile));
|
|
204
|
+
}
|
|
205
|
+
async function reusableAuthentication(chain, profile, authenticate) {
|
|
206
|
+
const a = profile.approval;
|
|
207
|
+
const key = reuseKey(profile);
|
|
208
|
+
let kept = reusedAuthentications.get(chain.client);
|
|
209
|
+
if (!kept)
|
|
210
|
+
reusedAuthentications.set(chain.client, kept = new Map());
|
|
211
|
+
const cached = kept.get(key);
|
|
212
|
+
if (cached && Math.floor(Date.now() / 1000) < cached.expiresAt) {
|
|
213
|
+
const current = await currentServiceRecord(chain, a.serviceId).catch(() => undefined);
|
|
214
|
+
if (current && sameRecord(current, cached.record)
|
|
215
|
+
&& Math.floor(Date.now() / 1000) < cached.expiresAt)
|
|
216
|
+
return cached;
|
|
217
|
+
}
|
|
218
|
+
kept.delete(key);
|
|
219
|
+
const fresh = await authenticate();
|
|
220
|
+
if (!Number.isSafeInteger(fresh.expiresAt))
|
|
221
|
+
return fresh;
|
|
222
|
+
if (kept.size >= MAX_REUSED_AUTHENTICATIONS)
|
|
223
|
+
kept.delete(kept.keys().next().value);
|
|
224
|
+
kept.set(key, fresh);
|
|
225
|
+
const store = kept;
|
|
226
|
+
registerHeadPrefetch(chain.client, `service-auth:${key}`, async () => {
|
|
227
|
+
if (store.get(key) !== fresh)
|
|
228
|
+
return;
|
|
229
|
+
const current = await currentServiceRecord(chain, a.serviceId).catch(() => undefined);
|
|
230
|
+
if (!current || !sameRecord(current, fresh.record))
|
|
231
|
+
store.delete(key);
|
|
232
|
+
}, fresh.expiresAt * 1000);
|
|
233
|
+
return fresh;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Authenticate one approved provider and prepare complete client-signed initialization before HTTP.
|
|
237
|
+
* This function reserves nothing, sends no session POST and keeps the execution signer local.
|
|
238
|
+
* The caller must retain the returned object through uncertain creation/delivery outcomes.
|
|
239
|
+
* @param chain Independently configured trusted RPC/registry client.
|
|
240
|
+
* @param config Approved provider, deployment, drawn Merkle witnesses and client-verified rule/query.
|
|
241
|
+
* @param params Original operation and fixed mined payment, built before contacting the agent.
|
|
242
|
+
* @param consent Creator-certified client key, optional locally retained bearer and consent deadline.
|
|
243
|
+
*/
|
|
244
|
+
export async function prepareRegisteredPaidSession(chain, config, params, consent) {
|
|
245
|
+
params = structuredClone(params);
|
|
246
|
+
// ADR-0090 D7: the fresh session key a session-mode presentation authorizes (its thumbprint is in the nonce).
|
|
247
|
+
const grantRequest = sessionGrantRequest(params);
|
|
248
|
+
const sessionThumbprint = grantRequest ? sessionKeyThumbprint(grantRequest.session_key) : undefined;
|
|
249
|
+
const thumbprintField = sessionThumbprint ? { session_key_thumbprint: toHex(sessionThumbprint) } : {};
|
|
250
|
+
const profile = Object.freeze({ ...config.profile, approval: Object.freeze({ ...config.profile.approval }) });
|
|
251
|
+
const deployment = structuredClone(config.deployment), transport = config.transport;
|
|
252
|
+
const paidRequest = transport.paidAgentRequest.bind(transport);
|
|
253
|
+
const members = structuredClone([...config.members]), ruleHash = protocolHex(config.ruleHash, 32, 'client rule hash');
|
|
254
|
+
executionBodyHash(object(config.dcqlQuery));
|
|
255
|
+
const dcql = structuredClone(config.dcqlQuery), certificate = structuredClone(consent.certificate), signer = consent.signer;
|
|
256
|
+
const allowMissingStatus = config.allowMissingStatusAttestations === true;
|
|
257
|
+
const clock = config.pacing?.clock ?? systemPacingClock, attemptBudgetMs = config.pacing?.attemptBudgetMs ?? 60_000;
|
|
258
|
+
if (typeof clock?.now !== 'function' || typeof clock.sleep !== 'function' || typeof clock.jitter !== 'function'
|
|
259
|
+
|| !Number.isSafeInteger(attemptBudgetMs) || attemptBudgetMs < 1_000 || attemptBudgetMs > 60_000)
|
|
260
|
+
throw new Error('Invalid paid agent pacing');
|
|
261
|
+
const pacing = Object.freeze({ clock, attemptBudgetMs });
|
|
262
|
+
const localPublicKey = signer.publicKey.slice(), localSign = signer.sign.bind(signer);
|
|
263
|
+
const activeSigner = (active) => ({ publicKey: localPublicKey.slice(), sign: async (message) => {
|
|
264
|
+
active.throwIfAborted();
|
|
265
|
+
const signature = await localSign(message);
|
|
266
|
+
active.throwIfAborted();
|
|
267
|
+
return signature;
|
|
268
|
+
} });
|
|
269
|
+
const pollSecret = id(consent.pollSecret ?? toHex(crypto.getRandomValues(new Uint8Array(32))).slice(2));
|
|
270
|
+
if (/^0+$/.test(pollSecret))
|
|
271
|
+
throw new Error('Owner bearer must be nonzero');
|
|
272
|
+
const expires = consent.expires ?? certificate.expires, payment = params.payment, paymentHash = paymentIntentHash(payment);
|
|
273
|
+
// The agent's typed PaymentIntentDto serializes Alloy addresses/bytes32 as
|
|
274
|
+
// lowercase hex. Reconstruct that representation only for returned context
|
|
275
|
+
// and operator bodies. Initialization still signs/sends the original JSON:
|
|
276
|
+
// changing it would change an existing session's identity on recovery.
|
|
277
|
+
const typedPayment = { ...payment };
|
|
278
|
+
for (const field of ['settlement', 'key_registry', 'slot', 'payload_digest', 'session_commitment', 'nonce', 'verification_seed', 'verification_root']) {
|
|
279
|
+
typedPayment[field] = payment[field].toLowerCase();
|
|
280
|
+
}
|
|
281
|
+
const expected = { slot: payment.slot, action: payment.action, payloadDigest: payment.payload_digest };
|
|
282
|
+
validateServiceEndpoint(profile.endpoint);
|
|
283
|
+
if (profile.approval.serviceType !== 1 || profile.approval.chainId !== deployment.chainId
|
|
284
|
+
|| !/^decentralized_identifier:did:web:[a-z0-9.-]+(?:(?:%3A)[0-9]+)?$/.test(profile.clientId)
|
|
285
|
+
|| typeof transport.paidAgentRequest !== 'function')
|
|
286
|
+
throw new Error('Invalid registered paid agent configuration');
|
|
287
|
+
return bounded(consent.signal, async (preparationSignal) => {
|
|
288
|
+
sessionPaymentFields(params, profile.clientId);
|
|
289
|
+
preparationSignal.throwIfAborted();
|
|
290
|
+
// The provider authentication (registry record, manifest, identity challenge, record recheck) and
|
|
291
|
+
// the client execution policy are independent: both only read, and the policy read contacts no
|
|
292
|
+
// agent. Run them together and judge them in the original order: authentication refuses first.
|
|
293
|
+
const [authenticatedRead, policyRead] = await Promise.allSettled([
|
|
294
|
+
reusableAuthentication(chain, profile, () => authenticateApprovedService(chain, profile.approval, { request: (url, opts) => transport.request(url, { ...opts, signal: AbortSignal.any([opts.signal, preparationSignal]) }) })),
|
|
295
|
+
readClientExecutionPolicy(chain.client, deployment, payment, expected)
|
|
296
|
+
]);
|
|
297
|
+
if (authenticatedRead.status === 'rejected')
|
|
298
|
+
throw authenticatedRead.reason;
|
|
299
|
+
const authenticated = authenticatedRead.value;
|
|
300
|
+
if (authenticated.record.endpoint !== profile.endpoint || !authenticated.manifest.capabilities.includes('oid4vp'))
|
|
301
|
+
throw new Error('Paid agent endpoint/capability mismatch');
|
|
302
|
+
preparationSignal.throwIfAborted();
|
|
303
|
+
if (policyRead.status === 'rejected')
|
|
304
|
+
throw policyRead.reason;
|
|
305
|
+
const { policy: originalPolicy } = policyRead.value;
|
|
306
|
+
preparationSignal.throwIfAborted();
|
|
307
|
+
const a = profile.approval, record = authenticated.record;
|
|
308
|
+
const pin = { chainId: a.chainId, registry: a.registry.toLowerCase(), serviceId: a.serviceId.toLowerCase(), serviceType: 1,
|
|
309
|
+
owner: a.owner.toLowerCase(), revision: a.revision.toString(), manifestHash: a.manifestHash.toLowerCase(),
|
|
310
|
+
authKey: record.authKey.toLowerCase(), endpoint: profile.endpoint, clientId: profile.clientId };
|
|
311
|
+
const unsigned = { operation: params.operation, operation_sig: params.operationSig, message_hex: params.messageHex,
|
|
312
|
+
...(params.decryption ? { decryption: params.decryption } : {}),
|
|
313
|
+
...(params.delegation ? { delegation: params.delegation } : {}), payment, random: params.random, poll_secret: pollSecret,
|
|
314
|
+
...(params.kind ? { kind: params.kind } : {}),
|
|
315
|
+
...(grantRequest ? { session_grant: grantRequest } : {}) };
|
|
316
|
+
const initialization = await initializeExecutionSession({ payment, certificate, signer: activeSigner(preparationSignal), policy: originalPolicy,
|
|
317
|
+
expected: { serviceProfile: pin, body: unsigned }, expires });
|
|
318
|
+
preparationSignal.throwIfAborted();
|
|
319
|
+
const sessionId = hashTypedData(executionInitializationTypedData(payment, initialization)).slice(2);
|
|
320
|
+
const requestUri = profile.endpoint + '/v1/request/' + sessionId;
|
|
321
|
+
const rawMessage = params.messageHex.replace(/^0x/, '');
|
|
322
|
+
if (!/^(?:[0-9a-f]{2})+$/i.test(rawMessage))
|
|
323
|
+
throw new Error('Invalid original operation message bytes');
|
|
324
|
+
const message = protocolHex('0x' + rawMessage, rawMessage.length / 2, 'original message');
|
|
325
|
+
// `sign` digests the message itself; `ibe-extract` digests the identity bound to the client
|
|
326
|
+
// recipient (as presentationOperationTypedData builds it and the verifier-agent recomputes it).
|
|
327
|
+
if (params.operation.action === 'sign' && toHex(sha256(message)).toLowerCase() !== params.operation.payload_digest.toLowerCase())
|
|
328
|
+
throw new Error('Original operation does not bind its message');
|
|
329
|
+
if (params.operation.action === 'ibe-extract') {
|
|
330
|
+
const d = params.decryption;
|
|
331
|
+
if (!d)
|
|
332
|
+
throw new Error('Paid IBE extraction requires its client recipient binding');
|
|
333
|
+
const content = sha256(message), bare = (hex) => hex.replace(/^0x/i, '').toLowerCase();
|
|
334
|
+
if (d.content_digest !== undefined && bare(d.content_digest) !== bare(toHex(content)))
|
|
335
|
+
throw new Error('Original operation does not bind its message');
|
|
336
|
+
if (toHex(recipientPayloadDigest(content, d.ciphertext_epoch, d.recipient)).toLowerCase() !== params.operation.payload_digest.toLowerCase())
|
|
337
|
+
throw new Error('Original operation does not bind its message');
|
|
338
|
+
}
|
|
339
|
+
const identity = params.operation.action === 'ibe-extract' ? new TextDecoder('utf-8', { fatal: true }).decode(message) : null;
|
|
340
|
+
if (!['sign', 'decrypt', 'ibe-extract', 'dual-approve'].includes(params.operation.action))
|
|
341
|
+
throw new Error('Unsupported presentation operation');
|
|
342
|
+
const rh = requestHash(payment.chain_id, protocolHex(payment.slot, 32, 'slot'), params.operation.action, protocolHex(payment.payload_digest, 32, 'digest'));
|
|
343
|
+
const drawn = selectVerifierCommittee(protocolHex(payment.slot, 32, 'slot'), payment.verification_epoch, protocolHex(payment.verification_seed, 32, 'seed'), payment.verification_registry_size, payment.verification_committee);
|
|
344
|
+
if (members.length !== drawn.length || new Set(members.map(m => m.index)).size !== members.length
|
|
345
|
+
|| new Set(members.map(m => m.publicKey.toLowerCase())).size !== members.length)
|
|
346
|
+
throw new Error('Incomplete or ambiguous paid verifier witnesses');
|
|
347
|
+
for (const member of members) {
|
|
348
|
+
const point = ed25519.Point.fromHex(protocolHex(member.publicKey, 32, 'member key'), false);
|
|
349
|
+
if (point.isSmallOrder() || !point.isTorsionFree())
|
|
350
|
+
throw new Error('Drawn verifier key must be a prime-order Ed25519 point');
|
|
351
|
+
if (!drawn.includes(member.index) || member.proof.length > 32 || !verifyMerkleProof(verifierLeaf(member.index, protocolHex(member.operator, 20, 'operator'), protocolHex(member.publicKey, 32, 'key')), member.proof.map(p => protocolHex(p, 32, 'proof')), protocolHex(payment.verification_root, 32, 'root')))
|
|
352
|
+
throw new Error('Paid verifier witness differs from the anchored draw');
|
|
353
|
+
}
|
|
354
|
+
const jarIndex = drawn[protocolHex(payment.verification_seed, 32, 'seed')[0] % drawn.length];
|
|
355
|
+
// A session-mode nonce binds THIS client's fresh session key: a holder never presents for a nonce
|
|
356
|
+
// that authorizes another key (every check below compares against this value).
|
|
357
|
+
const nonce = vpNonceBound(rh, protocolHex(params.random, 32, 'random'), { epoch: payment.verification_epoch, snapshotRoot: protocolHex(payment.verification_root, 32, 'root'),
|
|
358
|
+
registrySize: payment.verification_registry_size, committee: payment.verification_committee, quorum: payment.verification_quorum, operationExp: params.operation.exp }, sessionThumbprint);
|
|
359
|
+
const expectedBinding = { chain_id: payment.chain_id, slot_id: params.operation.slot_id, action: params.operation.action,
|
|
360
|
+
message_sha256: toHex(sha256(message)), identity, payload_digest: payment.payload_digest.toLowerCase(), description: params.operation.description,
|
|
361
|
+
operation: params.operation, operation_sig: params.operationSig, payment: typedPayment, delegation: params.delegation ?? null, random: params.random.toLowerCase(),
|
|
362
|
+
request_hash: toHex(rh), nonce, epoch: payment.verification_epoch, seed: payment.verification_seed.toLowerCase(), snapshot_root: payment.verification_root.toLowerCase(),
|
|
363
|
+
committee_count: payment.verification_committee, quorum: payment.verification_quorum, registry_size: payment.verification_registry_size, drawn, jar_signer_index: jarIndex,
|
|
364
|
+
client_id: profile.clientId, service_profile: pin, ...thumbprintField, execution_initialization: initialization, execution_certificate: certificate,
|
|
365
|
+
execution_policy: { chain_id: originalPolicy.chainId, settlement: originalPolicy.settlement.toLowerCase(), key_registry: originalPolicy.keyRegistry.toLowerCase(),
|
|
366
|
+
creator: originalPolicy.creator.toLowerCase(), cost: toHex(originalPolicy.cost, { size: 32 }) } };
|
|
367
|
+
let context;
|
|
368
|
+
let submitted = false;
|
|
369
|
+
const checkContext = (value) => {
|
|
370
|
+
const c = object(value);
|
|
371
|
+
exact(c, ['binding_preimage', 'state', 'enc_public_jwk', 'expires_at']);
|
|
372
|
+
if (executionBodyHash(object(c.binding_preimage)) !== executionBodyHash(expectedBinding)
|
|
373
|
+
|| typeof c.state !== 'string' || !/^[0-9a-f]{64}$/.test(c.state)
|
|
374
|
+
|| typeof c.expires_at !== 'number' || !Number.isSafeInteger(c.expires_at) || c.expires_at <= Math.floor(Date.now() / 1000)
|
|
375
|
+
|| c.expires_at > initialization.expires)
|
|
376
|
+
throw new Error('Paid session context differs from original client intent');
|
|
377
|
+
const next = { state: c.state, key: params.kind === 'oauth' ? null : encryptedKey(c.enc_public_jwk), expires: c.expires_at };
|
|
378
|
+
if (params.kind === 'oauth' && c.enc_public_jwk !== null)
|
|
379
|
+
throw new Error('OAuth session unexpectedly carries an encryption key');
|
|
380
|
+
if (context && executionBodyHash(context) !== executionBodyHash(next))
|
|
381
|
+
throw new Error('Original paid session context changed');
|
|
382
|
+
context = next;
|
|
383
|
+
};
|
|
384
|
+
const ready = () => {
|
|
385
|
+
if (!context)
|
|
386
|
+
throw new Error('Recover original paid session context before approval');
|
|
387
|
+
if (context.expires <= Math.floor(Date.now() / 1000))
|
|
388
|
+
throw new Error('Original paid session context expired');
|
|
389
|
+
return context;
|
|
390
|
+
};
|
|
391
|
+
// Before EVERY agent request: the provider's current registration, read at the latest block (one
|
|
392
|
+
// eth_call; formerly a head-number read and then a call at that number, which is no fresher).
|
|
393
|
+
// The chain ID is the client's (see chainIdOf); only the registry record is read each time.
|
|
394
|
+
const checkProvider = async (signal) => {
|
|
395
|
+
if (chain.addresses.ServiceRegistry?.toLowerCase() !== a.registry.toLowerCase() || await chainIdOf(chain.client) !== a.chainId)
|
|
396
|
+
throw new Error('Paid agent chain or registry changed');
|
|
397
|
+
signal.throwIfAborted();
|
|
398
|
+
// At the followed head when a live follower is attached (the same "latest" registration, without
|
|
399
|
+
// a round trip), otherwise read at latest as before. The check itself is unchanged.
|
|
400
|
+
const current = await currentServiceRecord(chain, a.serviceId);
|
|
401
|
+
signal.throwIfAborted();
|
|
402
|
+
if (current.status > 1 || current.revision < a.revision || current.serviceType !== 1
|
|
403
|
+
|| current.owner.toLowerCase() !== record.owner.toLowerCase() || current.authKey.toLowerCase() !== record.authKey.toLowerCase()
|
|
404
|
+
|| current.pendingOwner.toLowerCase() !== record.pendingOwner.toLowerCase() || current.manifestHash.toLowerCase() !== a.manifestHash.toLowerCase()
|
|
405
|
+
|| current.endpoint !== profile.endpoint) {
|
|
406
|
+
// The authentication this session (and any reuse of it) rests on no longer describes the
|
|
407
|
+
// registered provider: forget it NOW, before this refusal returns, so no later session can
|
|
408
|
+
// reuse it even if the record changes back.
|
|
409
|
+
dropReusedAuthentication(chain, profile);
|
|
410
|
+
throw new Error('Original paid agent provider changed');
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
// One attempt: provider check plus HTTP, cut off at the attempt budget so pacing can count on it.
|
|
414
|
+
const control = (path, method, body, signal, publicRoute = false, oauth) => bounded(signal, async (active) => {
|
|
415
|
+
active.throwIfAborted();
|
|
416
|
+
await checkProvider(active);
|
|
417
|
+
const result = await paidRequest(profile.endpoint + path, { method, body: body instanceof Uint8Array ? body.slice() : body && new TextEncoder().encode(JSON.stringify(body)),
|
|
418
|
+
bearer: publicRoute ? undefined : pollSecret, oauth, maxBytes: 10 * 1024 * 1024, signal: active });
|
|
419
|
+
active.throwIfAborted();
|
|
420
|
+
if (result.body.length > 10 * 1024 * 1024)
|
|
421
|
+
throw new Error('Paid agent response exceeds bound');
|
|
422
|
+
return result;
|
|
423
|
+
}, attemptBudgetMs);
|
|
424
|
+
const BUSY = [429, 503], LIMITED = [429];
|
|
425
|
+
/** The signed session expiry, once the original context is known: the deadline of every paced read. */
|
|
426
|
+
const sessionDeadline = () => context ? context.expires * 1000 : undefined;
|
|
427
|
+
// The creation request has no session yet: its window is the signed payment's remaining time. An
|
|
428
|
+
// already expired payment keeps the single attempt (its refusal is final anyway). 2026-10-31: the
|
|
429
|
+
// agent answered 503 on creation right after a keeper was restored and the SDK gave up at once.
|
|
430
|
+
const creationDeadline = () => payment.expires * 1000 > clock.now() ? payment.expires * 1000 : undefined;
|
|
431
|
+
/**
|
|
432
|
+
* A safely repeatable request: repeated on a status in `retryOn` only while the wait fits before
|
|
433
|
+
* `deadlineMs`, the deadline re-read before EVERY send. No deadline = one attempt (status quo). Any
|
|
434
|
+
* other status is returned for the caller's checks; transport errors propagate and are never repeated.
|
|
435
|
+
*/
|
|
436
|
+
const paced = async (route, send, retryOn, deadlineMs, signal) => {
|
|
437
|
+
if (deadlineMs === undefined)
|
|
438
|
+
return send();
|
|
439
|
+
const backoff = new PaidBackoff(clock, route, deadlineMs, attemptBudgetMs);
|
|
440
|
+
for (;;) {
|
|
441
|
+
signal?.throwIfAborted();
|
|
442
|
+
backoff.readyToSend();
|
|
443
|
+
const response = await send();
|
|
444
|
+
if (!retryOn.includes(response.status))
|
|
445
|
+
return response;
|
|
446
|
+
await backoff.wait(response.status, paidResponseWaitMs(response), signal);
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
const read = (route, path, signal, publicRoute = false) => paced(route, () => control(path, 'GET', undefined, signal, publicRoute), BUSY, sessionDeadline(), signal);
|
|
450
|
+
const ok = (response, statuses) => {
|
|
451
|
+
if (!statuses.includes(response.status))
|
|
452
|
+
throw new PaidAgentControlError(sessionId, response.status, response.retryAfterMs !== undefined && Number.isSafeInteger(response.retryAfterMs) && response.retryAfterMs >= 0 ? response.retryAfterMs : undefined);
|
|
453
|
+
};
|
|
454
|
+
const memberFor = (provided) => {
|
|
455
|
+
const member = members.find(m => m.index === provided.index);
|
|
456
|
+
if (!member || executionBodyHash(member) !== executionBodyHash(provided))
|
|
457
|
+
throw new Error('Approval member differs from independently anchored witnesses');
|
|
458
|
+
return member;
|
|
459
|
+
};
|
|
460
|
+
/** Signs the approval ONCE and returns its exact request body; sends nothing. */
|
|
461
|
+
const signApproval = async (proposed, member, stage, body, signal) => {
|
|
462
|
+
proposed = structuredClone(proposed);
|
|
463
|
+
member = memberFor(structuredClone(member));
|
|
464
|
+
body = structuredClone(body);
|
|
465
|
+
id(proposed.id);
|
|
466
|
+
if (!Number.isSafeInteger(proposed.expires) || proposed.expires <= Math.floor(Date.now() / 1000) || proposed.expires > ready().expires)
|
|
467
|
+
throw new Error('Proposal exceeds the original live session expiry');
|
|
468
|
+
return bounded(signal, async (active) => {
|
|
469
|
+
const { policy } = await readClientExecutionPolicy(chain.client, deployment, payment, expected, member);
|
|
470
|
+
active.throwIfAborted();
|
|
471
|
+
const authorization = await approveExecutionRequest({ payment, certificate, signer: activeSigner(active), policy, expected: { stage, operatorKey: member.publicKey, body },
|
|
472
|
+
proposal: { stage: proposed.stage, operator_key: proposed.operator_key, unsigned_body: proposed.unsigned_body, expires: proposed.expires } });
|
|
473
|
+
active.throwIfAborted();
|
|
474
|
+
return { proposalId: proposed.id, body: JSON.stringify({ authorization }), expires: Math.min(proposed.expires, ready().expires) };
|
|
475
|
+
});
|
|
476
|
+
};
|
|
477
|
+
/** Checks a retained approval (possibly loaded from storage) and returns its exact bytes. */
|
|
478
|
+
const retainedBytes = (approval) => {
|
|
479
|
+
const a = object(approval);
|
|
480
|
+
exact(a, ['proposalId', 'body', 'expires']);
|
|
481
|
+
id(a.proposalId);
|
|
482
|
+
if (typeof a.body !== 'string' || a.body.length > 2 * 1024 * 1024 || !Number.isSafeInteger(a.expires))
|
|
483
|
+
throw new Error('Invalid retained paid approval');
|
|
484
|
+
let parsed;
|
|
485
|
+
try {
|
|
486
|
+
parsed = object(JSON.parse(a.body));
|
|
487
|
+
}
|
|
488
|
+
catch {
|
|
489
|
+
throw new Error('Invalid retained paid approval');
|
|
490
|
+
}
|
|
491
|
+
exact(parsed, ['authorization']);
|
|
492
|
+
object(parsed.authorization);
|
|
493
|
+
if (a.expires <= Math.floor(Date.now() / 1000) || a.expires > ready().expires)
|
|
494
|
+
throw new Error('Retained approval is outside the original live session expiry');
|
|
495
|
+
return new TextEncoder().encode(a.body);
|
|
496
|
+
};
|
|
497
|
+
/** ONE send of the retained bytes; never re-signed, never repeated here. */
|
|
498
|
+
const deliver = async (approval, signal) => {
|
|
499
|
+
const bytes = retainedBytes(approval);
|
|
500
|
+
const response = await control('/v1/sessions/' + sessionId + '/execution/' + approval.proposalId + '/approve', 'POST', bytes, signal);
|
|
501
|
+
if (response.status === 204 && response.body.length)
|
|
502
|
+
throw new Error('Approval reply unexpectedly contains a body');
|
|
503
|
+
return response;
|
|
504
|
+
};
|
|
505
|
+
const batchApprovals = authenticated.manifest.capabilities.includes(BATCH_APPROVAL_CAPABILITY);
|
|
506
|
+
const proposalWait = authenticated.manifest.capabilities.includes(PROPOSAL_WAIT_CAPABILITY);
|
|
507
|
+
/** ONE send of several retained approvals; each entry's authorization is its retained body's, unchanged. */
|
|
508
|
+
const sendRetainedApprovals = async (approvals, signal) => {
|
|
509
|
+
if (!batchApprovals)
|
|
510
|
+
throw new Error('Paid agent does not advertise batch approvals');
|
|
511
|
+
const deliveries = approvals.map(a => a.proposalId);
|
|
512
|
+
if (!approvals.length || approvals.length > 256 || new Set(deliveries).size !== deliveries.length)
|
|
513
|
+
throw new Error('Invalid paid approval batch');
|
|
514
|
+
const authorizations = approvals.map(approval => {
|
|
515
|
+
const parsed = object(JSON.parse(new TextDecoder().decode(retainedBytes(approval))));
|
|
516
|
+
return { delivery: approval.proposalId, authorization: object(parsed.authorization) };
|
|
517
|
+
});
|
|
518
|
+
const response = await control('/v1/sessions/' + sessionId + '/execution/approve', 'POST', { authorizations }, signal);
|
|
519
|
+
if (response.status === 429 || response.status === 503) {
|
|
520
|
+
const hintMs = paidResponseWaitMs(response);
|
|
521
|
+
return { kind: 'busy', httpStatus: response.status, ...(hintMs !== undefined ? { hintMs } : {}) };
|
|
522
|
+
}
|
|
523
|
+
ok(response, [200]);
|
|
524
|
+
const reply = decode(response.body);
|
|
525
|
+
exact(reply, ['results']);
|
|
526
|
+
const values = reply.results;
|
|
527
|
+
if (!Array.isArray(values) || values.length !== deliveries.length)
|
|
528
|
+
throw new Error('Paid approval batch reply does not answer every delivery');
|
|
529
|
+
const results = new Map();
|
|
530
|
+
for (const value of values) {
|
|
531
|
+
const r = object(value);
|
|
532
|
+
exact(r, ['delivery', 'status']);
|
|
533
|
+
if (typeof r.delivery !== 'string' || !deliveries.includes(r.delivery) || results.has(r.delivery) || ![204, 404, 409, 410, 422].includes(r.status))
|
|
534
|
+
throw new Error('Invalid paid approval batch result');
|
|
535
|
+
results.set(r.delivery, r.status);
|
|
536
|
+
}
|
|
537
|
+
return { kind: 'results', results };
|
|
538
|
+
};
|
|
539
|
+
const sendRetainedApproval = async (approval, signal) => {
|
|
540
|
+
const response = await deliver(approval, signal);
|
|
541
|
+
if (response.status === 204)
|
|
542
|
+
return { status: 'accepted' };
|
|
543
|
+
if (response.status === 429 || response.status === 503) {
|
|
544
|
+
const hintMs = paidResponseWaitMs(response);
|
|
545
|
+
return { status: 'busy', httpStatus: response.status, ...(hintMs !== undefined ? { hintMs } : {}) };
|
|
546
|
+
}
|
|
547
|
+
ok(response, [204]);
|
|
548
|
+
throw new Error('unreachable');
|
|
549
|
+
};
|
|
550
|
+
/** The complete body a JAR signer or attester is approved for, built from the original intent. */
|
|
551
|
+
const requestBody = (stage, member) => {
|
|
552
|
+
const c = ready();
|
|
553
|
+
if (params.kind === 'oauth' || (stage === 'presentation_sign' ? member.index !== jarIndex : member.index === jarIndex))
|
|
554
|
+
throw new Error('Incorrect JAR signer or attester');
|
|
555
|
+
return { operation: params.operation, operation_sig: params.operationSig, delegation: params.delegation ?? null,
|
|
556
|
+
session: { response_uri: profile.endpoint + '/v1/response?session=' + sessionId, enc_jwk: c.key, state: c.state, random: params.random.toLowerCase() },
|
|
557
|
+
epoch: payment.verification_epoch, seed: payment.verification_seed.toLowerCase(), committee_count: payment.verification_committee,
|
|
558
|
+
registry_size: payment.verification_registry_size, quorum: payment.verification_quorum, payment: typedPayment, ...thumbprintField };
|
|
559
|
+
};
|
|
560
|
+
/** The complete credential body a drawn verifier is approved for, from the separately accepted presentation. */
|
|
561
|
+
const credentialBody = (accepted) => {
|
|
562
|
+
const approved = presented(accepted), c = ready();
|
|
563
|
+
if ((params.kind === 'oauth') !== (approved.oauth !== null))
|
|
564
|
+
throw new Error('Presentation kind differs from the original session');
|
|
565
|
+
if (approved.oauth !== null && approved.oauth.session_id !== sessionId)
|
|
566
|
+
throw new Error('OAuth presentation differs from the original session');
|
|
567
|
+
let exp = Math.min(approved.iat + 3600, c.expires, params.operation.exp);
|
|
568
|
+
for (const credential of [...approved.credentials, ...(approved.oauth ? [approved.oauth.access_token] : [])]) {
|
|
569
|
+
const expiry = issuerExpiry(credential);
|
|
570
|
+
if (expiry !== undefined)
|
|
571
|
+
exp = Math.min(exp, expiry);
|
|
572
|
+
}
|
|
573
|
+
if (!Number.isSafeInteger(exp) || exp <= Math.floor(Date.now() / 1000))
|
|
574
|
+
throw new Error('Original credential presentation expired');
|
|
575
|
+
return { payment: typedPayment, holder: approved.holder, credentials: approved.credentials,
|
|
576
|
+
...(approved.holder_proof !== null ? { holder_proof: approved.holder_proof } : {}), ...(approved.oauth !== null ? { oauth: approved.oauth, session_id: sessionId } : {}), token_type: 'JWT',
|
|
577
|
+
seed: payment.verification_seed.toLowerCase(), epoch: payment.verification_epoch, slot_id: params.operation.slot_id, registry_size: payment.verification_registry_size,
|
|
578
|
+
committee: payment.verification_committee, quorum: payment.verification_quorum, iat: approved.iat, exp, ...(identity !== null ? { identity } : {}),
|
|
579
|
+
chain_id: payment.chain_id, action: params.operation.action, payload_digest: payment.payload_digest.toLowerCase(), random: params.random.toLowerCase(), client_id: profile.clientId,
|
|
580
|
+
description: params.operation.description, operation_exp: params.operation.exp, operation: params.operation, operation_sig: params.operationSig, ...(params.delegation ? { delegation: params.delegation } : {}), ...thumbprintField };
|
|
581
|
+
};
|
|
582
|
+
// The direct API keeps its single-attempt behaviour: sign once, send once.
|
|
583
|
+
const approve = async (proposed, member, stage, body, signal) => {
|
|
584
|
+
const approval = await signApproval(proposed, member, stage, body, signal);
|
|
585
|
+
ok(await deliver(approval, signal), [204]);
|
|
586
|
+
};
|
|
587
|
+
const callbackId = (approved) => keccak256(concatBytes(new TextEncoder().encode('keykeeper/retained-presentation/v1'), epochBytes(sessionId.length), new TextEncoder().encode(sessionId), protocolHex(executionBodyHash(approved), 32, 'presentation hash'), epochBytes(ready().expires))).slice(2);
|
|
588
|
+
const oauthContext = Object.freeze({ nonce, dpopHtu: dpopHtu(profile.endpoint, sessionId), platformAudience: platformAudience(profile.endpoint, payment.chain_id) });
|
|
589
|
+
const oauthClaims = (accessToken) => {
|
|
590
|
+
if (typeof accessToken !== 'string' || accessToken.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(accessToken))
|
|
591
|
+
throw new Error('Invalid original OAuth access token');
|
|
592
|
+
let claims;
|
|
593
|
+
try {
|
|
594
|
+
claims = object(decodeJson(accessToken.split('.')[1]));
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
throw new Error('Invalid original OAuth access token');
|
|
598
|
+
}
|
|
599
|
+
// A bearer token (no cnf.jkt) is refused by name: only a DPoP-bound token can authorize a paid session.
|
|
600
|
+
if (claims.cnf === null || typeof claims.cnf !== 'object' || Array.isArray(claims.cnf) || typeof claims.cnf.jkt !== 'string')
|
|
601
|
+
throw new Error('OAuth access token is a bearer token (no cnf.jkt): only a DPoP-bound token can authorize a paid session');
|
|
602
|
+
const now = Math.floor(Date.now() / 1000), cnf = object(claims.cnf);
|
|
603
|
+
if (typeof claims.iat !== 'number' || !Number.isSafeInteger(claims.iat) || claims.iat < 0 || claims.iat > now + 60
|
|
604
|
+
|| typeof claims.exp !== 'number' || !Number.isSafeInteger(claims.exp) || claims.exp <= now || claims.exp <= claims.iat
|
|
605
|
+
|| !(typeof claims.aud === 'string' ? claims.aud === oauthContext.platformAudience : Array.isArray(claims.aud) && claims.aud.includes(oauthContext.platformAudience))
|
|
606
|
+
|| typeof cnf.jkt !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(cnf.jkt))
|
|
607
|
+
throw new Error('OAuth token does not bind this original audience, time or DPoP key');
|
|
608
|
+
return claims;
|
|
609
|
+
};
|
|
610
|
+
const checkOAuth = async (approved) => {
|
|
611
|
+
if (params.kind !== 'oauth' || approved.oauth === null || approved.holder !== '' || approved.holder_proof !== null
|
|
612
|
+
|| approved.oauth.session_id !== sessionId)
|
|
613
|
+
throw new Error('Invalid original OAuth presentation');
|
|
614
|
+
const claims = oauthClaims(approved.oauth.access_token), proof = approved.oauth.dpop_proof;
|
|
615
|
+
if (approved.iat !== claims.iat || proof.length > 4 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(proof))
|
|
616
|
+
throw new Error('OAuth presentation changed its original issuance time or proof');
|
|
617
|
+
let header, payload;
|
|
618
|
+
try {
|
|
619
|
+
header = object(decodeJson(proof.split('.')[0]));
|
|
620
|
+
payload = object(decodeJson(proof.split('.')[1]));
|
|
621
|
+
}
|
|
622
|
+
catch {
|
|
623
|
+
throw new Error('Invalid original DPoP proof');
|
|
624
|
+
}
|
|
625
|
+
const jwk = object(header.jwk);
|
|
626
|
+
exact(jwk, ['kty', 'crv', 'x', 'y']);
|
|
627
|
+
if (header.alg !== 'ES256' || header.typ !== 'dpop+jwt' || jwk.kty !== 'EC' || jwk.crv !== 'P-256'
|
|
628
|
+
|| typeof jwk.x !== 'string' || typeof jwk.y !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(jwk.x) || !/^[A-Za-z0-9_-]{43}$/.test(jwk.y)
|
|
629
|
+
|| payload.htm !== 'POST' || payload.htu !== oauthContext.dpopHtu || payload.nonce !== nonce
|
|
630
|
+
|| typeof payload.iat !== 'number' || !Number.isSafeInteger(payload.iat) || Math.abs(payload.iat - Math.floor(Date.now() / 1000)) > 60
|
|
631
|
+
|| typeof payload.jti !== 'string' || !payload.jti || payload.ath !== await accessTokenHash(approved.oauth.access_token)
|
|
632
|
+
|| object(claims.cnf).jkt !== await jwkThumbprint({ kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y }))
|
|
633
|
+
throw new Error('DPoP proof differs from the original token, nonce or target');
|
|
634
|
+
const publicKey = concatBytes(new Uint8Array([4]), b64urlDecode(jwk.x), b64urlDecode(jwk.y));
|
|
635
|
+
if (!p256.verify(b64urlDecode(proof.split('.')[2]), sha256(new TextEncoder().encode(proof.split('.').slice(0, 2).join('.'))), publicKey, { lowS: false }))
|
|
636
|
+
throw new Error('Invalid original DPoP signature');
|
|
637
|
+
};
|
|
638
|
+
/** The creation reply's clamped session parameters: the requested slots and values echoed, each granted value at most the request. */
|
|
639
|
+
const checkGrantParams = (value) => {
|
|
640
|
+
if (!grantRequest) {
|
|
641
|
+
if (value != null)
|
|
642
|
+
throw new Error('Paid creation reply opened a session grant that was never requested');
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
const g = object(value);
|
|
646
|
+
exact(g, ['session_id', 'slots', 'requested', 'granted']);
|
|
647
|
+
if (typeof g.session_id !== 'string' || !HEX32_LOWER.test(g.session_id) || !Array.isArray(g.slots) || g.slots.length !== grantRequest.slots.length
|
|
648
|
+
|| g.slots.some((s, i) => s !== grantRequest.slots[i]))
|
|
649
|
+
throw new Error('Paid creation reply changed the requested session grant');
|
|
650
|
+
const requested = object(g.requested), granted = object(g.granted);
|
|
651
|
+
for (const field of ['access_ttl_secs', 'idle_timeout_secs', 'absolute_ttl_secs']) {
|
|
652
|
+
const value = granted[field];
|
|
653
|
+
if (requested[field] !== grantRequest[field] || typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > grantRequest[field])
|
|
654
|
+
throw new Error('Paid creation reply changed the requested session grant');
|
|
655
|
+
}
|
|
656
|
+
};
|
|
657
|
+
/**
|
|
658
|
+
* A completed session-mode poll: the grant must name THIS chain, this session key, the token's
|
|
659
|
+
* holder, binding, draw and payment slot, and verify against the anchored draw. Anything else is
|
|
660
|
+
* not used (`sdk_grant_invalid`); the compound token still authorizes its one operation.
|
|
661
|
+
*/
|
|
662
|
+
const grantOutcome = (raw, tokenHolder) => {
|
|
663
|
+
if (raw.session_grant == null) {
|
|
664
|
+
const code = typeof raw.session_grant_error === 'string' && /^session_[a-z_]{1,48}$/.test(raw.session_grant_error) ? raw.session_grant_error : 'session_grant_missing';
|
|
665
|
+
return { error: code };
|
|
666
|
+
}
|
|
667
|
+
try {
|
|
668
|
+
if (raw.refresh_seq !== 0)
|
|
669
|
+
throw new Error('an opening grant answers refresh seq 0');
|
|
670
|
+
const wire = structuredClone(raw.session_grant), grant = decodeSessionGrant(wire), p = grant.payload;
|
|
671
|
+
const hex = (b) => toHex(b).toLowerCase(), slot = protocolHex(payment.slot, 32, 'slot');
|
|
672
|
+
if (p.chainId !== BigInt(payment.chain_id) || p.chainId !== BigInt(deployment.chainId) || hex(p.sessionKeyThumbprint) !== hex(sessionThumbprint)
|
|
673
|
+
|| hex(p.holderHash) !== hex(tokenHolder) || p.binding !== BINDING_HOLDER_KEY || p.epoch !== BigInt(payment.verification_epoch)
|
|
674
|
+
|| hex(p.seed) !== payment.verification_seed.toLowerCase() || p.slots.some(s => !grantRequest.slots.includes(hex(s.slotId))))
|
|
675
|
+
throw new Error('grant differs from this session');
|
|
676
|
+
const set = { registrySize: payment.verification_registry_size, pubkeys: new Map(members.map(m => [m.index, protocolHex(m.publicKey, 32, 'key')])) };
|
|
677
|
+
verifySessionGrant({ grant, set, slotId: slot, committee: payment.verification_committee, quorum: payment.verification_quorum, slotRuleHash: ruleHash, seed: protocolHex(payment.verification_seed, 32, 'seed'), now: Math.floor(Date.now() / 1000) });
|
|
678
|
+
return { grant: { session_grant: wire, refresh_seq: 0 } };
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
return { error: 'sdk_grant_invalid' };
|
|
682
|
+
}
|
|
683
|
+
};
|
|
684
|
+
let oauthSubmitted = false;
|
|
685
|
+
const poll = async (signal, options) => {
|
|
686
|
+
// A held poll needs an attempt budget above the agent's 20 s hold.
|
|
687
|
+
const held = options?.wait === true && attemptBudgetMs >= HELD_POLL_MIN_BUDGET_MS;
|
|
688
|
+
const response = await read('GET /v1/sessions/{id}', '/v1/sessions/' + sessionId + (held ? '?wait=1' : ''), signal);
|
|
689
|
+
ok(response, [200]);
|
|
690
|
+
const raw = decode(response.body);
|
|
691
|
+
// A malformed status list is a typed `revocation_status_invalid` preflight refusal, checked
|
|
692
|
+
// before the generic protocol parse would fold it into a session error.
|
|
693
|
+
if (raw.status === 'done' && raw.compound_token && typeof raw.compound_token === 'object') {
|
|
694
|
+
const ct = raw.compound_token;
|
|
695
|
+
if (ct.status_attestations != null)
|
|
696
|
+
assertStatusAttestationsWire(ct.status_attestations, Array.isArray(ct.verifier_indexes) ? ct.verifier_indexes.length : undefined);
|
|
697
|
+
}
|
|
698
|
+
if (raw.execution_context !== undefined)
|
|
699
|
+
checkContext(raw.execution_context);
|
|
700
|
+
if (raw.binding_preimage !== null && raw.binding_preimage !== undefined && executionBodyHash(object(raw.binding_preimage)) !== executionBodyHash(expectedBinding))
|
|
701
|
+
throw new Error('Paid poll operation binding changed');
|
|
702
|
+
const status = parseVerifierAgentSessionStatus(raw, sessionId);
|
|
703
|
+
if ((!grantRequest || status.status !== 'done') && (raw.session_grant != null || raw.refresh_seq != null || raw.session_grant_error != null))
|
|
704
|
+
throw new Error('Paid poll carries a session grant this session cannot have');
|
|
705
|
+
if (status.status === 'done') {
|
|
706
|
+
const token = decodeCompoundToken(status.compoundToken);
|
|
707
|
+
if (toHex(token.slotId).toLowerCase() !== payment.slot.toLowerCase() || toHex(token.seed).toLowerCase() !== payment.verification_seed.toLowerCase()
|
|
708
|
+
|| token.epoch !== payment.verification_epoch || !token.requestHash || toHex(token.requestHash) !== toHex(rh)
|
|
709
|
+
|| !token.paymentHash || toHex(token.paymentHash) !== paymentHash || token.exp > ready().expires
|
|
710
|
+
|| token.exp <= Math.floor(Date.now() / 1000) || token.binding !== BINDING_HOLDER_KEY || token.tokenType !== 'JWT'
|
|
711
|
+
|| (identity === null ? token.identityHash !== undefined : !token.identityHash || toHex(token.identityHash) !== keccak256(toHex(identity))))
|
|
712
|
+
throw new Error('Paid committee result changed its original operation, holder binding or payment');
|
|
713
|
+
const set = { registrySize: payment.verification_registry_size, pubkeys: new Map(members.map(m => [m.index, protocolHex(m.publicKey, 32, 'key')])) }, now = Math.floor(Date.now() / 1000);
|
|
714
|
+
const verified = verifyCompoundToken({ token, set, committee: payment.verification_committee, quorum: payment.verification_quorum, now, leeway: 0, slotRuleHash: ruleHash });
|
|
715
|
+
verifyEvidenceBinding(status.compoundToken, status.evidenceCt, compoundTokenHash(token), set.pubkeys, payment.verification_quorum);
|
|
716
|
+
// Paid preflight: revocation-status attestations sit outside the token hash and are
|
|
717
|
+
// REQUIRED, checked exactly as a keeper will (same keys, counted signers and quorum), so a
|
|
718
|
+
// grant every keeper would refuse never reaches one. Missing (absent, null or empty) is
|
|
719
|
+
// `revocation_status_missing` unless the migration opt-out is set; stale or invalid are
|
|
720
|
+
// always refused. Accepted attestations are carried to the keepers unchanged.
|
|
721
|
+
requireStatusAttestations({ tokenHash: compoundTokenHash(token), attestations: token.statusAttestations,
|
|
722
|
+
counted: verified.verifiedSigners, set, quorum: payment.verification_quorum, now, allowMissing: allowMissingStatus });
|
|
723
|
+
// The signed payment hash already matched; carry its own original preimage to keepers.
|
|
724
|
+
status.compoundToken.payment = structuredClone(payment);
|
|
725
|
+
// Downstream keepers receive the client's anchored witnesses, never unchecked agent proofs.
|
|
726
|
+
status.verifierProofs = drawn.map(index => {
|
|
727
|
+
const member = members.find(m => m.index === index);
|
|
728
|
+
return { verifier_index: index, operator: member.operator.slice(2), pubkey: member.publicKey.slice(2), proof: member.proof.map(p => p.slice(2)) };
|
|
729
|
+
});
|
|
730
|
+
if (grantRequest)
|
|
731
|
+
status.sessionGrant = grantOutcome(raw, token.holderHash);
|
|
732
|
+
}
|
|
733
|
+
return status;
|
|
734
|
+
};
|
|
735
|
+
return Object.freeze({ sessionId, profile, paymentHash, pacing, get initialization() { return structuredClone(initialization); },
|
|
736
|
+
get oauthContext() { ready(); if (params.kind !== 'oauth')
|
|
737
|
+
throw new Error('Wallet session has no OAuth context'); return oauthContext; },
|
|
738
|
+
prepareOAuthPresentation(accessToken, oauthSigner, signal) {
|
|
739
|
+
ready();
|
|
740
|
+
if (params.kind !== 'oauth')
|
|
741
|
+
throw new Error('Wallet session cannot submit OAuth credentials');
|
|
742
|
+
return bounded(signal, async (active) => {
|
|
743
|
+
const claims = oauthClaims(accessToken);
|
|
744
|
+
const proof = await oauthSigner.proof({ htm: 'POST', htu: oauthContext.dpopHtu, nonce, accessToken });
|
|
745
|
+
active.throwIfAborted();
|
|
746
|
+
const approved = presented({ holder: '', credentials: [], holder_proof: null, oauth: { access_token: accessToken, dpop_proof: proof, session_id: sessionId }, iat: Number(claims.iat) });
|
|
747
|
+
await checkOAuth(approved);
|
|
748
|
+
active.throwIfAborted();
|
|
749
|
+
return approved;
|
|
750
|
+
});
|
|
751
|
+
},
|
|
752
|
+
submitOAuthPresentation(approved, signal) {
|
|
753
|
+
approved = presented(approved);
|
|
754
|
+
ready();
|
|
755
|
+
return bounded(signal, async (active) => {
|
|
756
|
+
if (oauthSubmitted)
|
|
757
|
+
throw new Error('OAuth presentation already sent; reconcile the original retained callback');
|
|
758
|
+
await checkOAuth(approved);
|
|
759
|
+
active.throwIfAborted();
|
|
760
|
+
// Recheck after asynchronous proof validation to fence concurrent submissions.
|
|
761
|
+
if (oauthSubmitted)
|
|
762
|
+
throw new Error('OAuth presentation already sent; reconcile the original retained callback');
|
|
763
|
+
oauthSubmitted = true;
|
|
764
|
+
// A definite 429 (the agent's limiter answers before the handler claims anything) is the
|
|
765
|
+
// one refusal repeated, with the SAME token and proof, and only while both the session and
|
|
766
|
+
// the proof's own freshness window (iat + 60 s) leave room for a full attempt. Anything
|
|
767
|
+
// else, including a PaidBackoffError, means nothing more was sent.
|
|
768
|
+
const proofIat = Number(decodeJson(approved.oauth.dpop_proof.split('.')[1]).iat);
|
|
769
|
+
const deadline = Math.min(sessionDeadline() ?? 0, (proofIat + 60) * 1000);
|
|
770
|
+
const response = await paced('POST /v1/sessions/{id}/oauth-response', () => control('/v1/sessions/' + sessionId + '/oauth-response', 'POST', undefined, active, false, { accessToken: approved.oauth.access_token, proof: approved.oauth.dpop_proof }), LIMITED, deadline > clock.now() ? deadline : undefined, active);
|
|
771
|
+
ok(response, [200, 202]);
|
|
772
|
+
const status = decode(response.body).status;
|
|
773
|
+
if (status !== (response.status === 202 ? 'awaiting_client_approval' : 'accepted'))
|
|
774
|
+
throw new Error('Invalid OAuth presentation submission result');
|
|
775
|
+
});
|
|
776
|
+
},
|
|
777
|
+
async create(signal) {
|
|
778
|
+
if (submitted)
|
|
779
|
+
throw new Error('Paid creation already sent; reconcile by reading the original session');
|
|
780
|
+
signal?.throwIfAborted();
|
|
781
|
+
submitted = true;
|
|
782
|
+
const response = await paced('POST /v1/sessions', () => control('/v1/sessions', 'POST', { ...unsigned, execution_initialization: initialization }, signal, true), BUSY, creationDeadline(), signal);
|
|
783
|
+
ok(response, [200, 201]);
|
|
784
|
+
const reply = decode(response.body);
|
|
785
|
+
if (reply.session_id !== sessionId || reply.poll_secret !== pollSecret || executionBodyHash(object(reply.service_profile)) !== executionBodyHash(pin)
|
|
786
|
+
|| reply.qr_payload != null || (params.kind !== 'oauth' && reply.request_uri !== requestUri))
|
|
787
|
+
throw new Error('Initialized paid creation reply changed identity, owner or provider');
|
|
788
|
+
if (params.kind === 'oauth' && (reply.nonce !== nonce || reply.dpop_htu !== oauthContext.dpopHtu || reply.platform_audience !== oauthContext.platformAudience || reply.request_uri != null))
|
|
789
|
+
throw new Error('OAuth creation reply changed its original nonce or audience');
|
|
790
|
+
checkGrantParams(reply.session_grant_params);
|
|
791
|
+
checkContext(reply.execution_context);
|
|
792
|
+
}, reconcile: (signal) => poll(signal), poll,
|
|
793
|
+
async proposals(signal, options) {
|
|
794
|
+
// A held listing only from an agent advertising it, and only inside this attempt's budget.
|
|
795
|
+
const wait = proposalWait && options?.waitMs !== undefined && Number.isSafeInteger(options.waitMs) && options.waitMs > 0
|
|
796
|
+
? Math.min(options.waitMs, MAX_PROPOSAL_WAIT_MS, attemptBudgetMs - 5_000) : 0;
|
|
797
|
+
const response = await read('GET /v1/sessions/{id}/execution', '/v1/sessions/' + sessionId + '/execution' + (wait > 0 ? '?wait_ms=' + wait : ''), signal);
|
|
798
|
+
ok(response, [200]);
|
|
799
|
+
const values = decode(response.body).proposals;
|
|
800
|
+
if (!Array.isArray(values) || values.length > 256)
|
|
801
|
+
throw new Error('Invalid paid proposals');
|
|
802
|
+
return values.map(value => { const p = object(value); exact(p, ['id', 'stage', 'operator_key', 'unsigned_body', 'expires']); id(p.id); object(p.unsigned_body); return structuredClone(p); });
|
|
803
|
+
},
|
|
804
|
+
async approveRequest(proposal, stage, member, signal) {
|
|
805
|
+
await approve(proposal, member, stage, requestBody(stage, member), signal);
|
|
806
|
+
},
|
|
807
|
+
prepareRequestApproval(proposal, stage, member, signal) {
|
|
808
|
+
return signApproval(proposal, member, stage, requestBody(stage, member), signal);
|
|
809
|
+
},
|
|
810
|
+
prepareCredentialApproval(proposal, member, approved, signal) {
|
|
811
|
+
return signApproval(proposal, member, 'credential', credentialBody(approved), signal);
|
|
812
|
+
},
|
|
813
|
+
sendRetainedApproval, sendRetainedApprovals, batchApprovals, proposalWait,
|
|
814
|
+
async approvalState(proposal, signal) {
|
|
815
|
+
id(proposal);
|
|
816
|
+
const response = await read('GET /v1/sessions/{id}/execution/{delivery}', '/v1/sessions/' + sessionId + '/execution/' + proposal, signal);
|
|
817
|
+
ok(response, [200]);
|
|
818
|
+
const state = decode(response.body);
|
|
819
|
+
if (state.id !== proposal || typeof state.state !== 'string' || !/^[a-z_]{1,32}$/.test(state.state))
|
|
820
|
+
throw new Error('Invalid paid delivery state');
|
|
821
|
+
return state.state;
|
|
822
|
+
},
|
|
823
|
+
async presentations(signal) {
|
|
824
|
+
const response = await read('GET /v1/sessions/{id}/presentations', '/v1/sessions/' + sessionId + '/presentations', signal);
|
|
825
|
+
ok(response, [200]);
|
|
826
|
+
const values = decode(response.body).presentations;
|
|
827
|
+
if (!Array.isArray(values) || values.length > 16)
|
|
828
|
+
throw new Error('Invalid retained presentation list');
|
|
829
|
+
return values.map(value => {
|
|
830
|
+
const p = object(value);
|
|
831
|
+
exact(p, ['id', 'presentation', 'expires', 'selected']);
|
|
832
|
+
const presentation = presented(p.presentation);
|
|
833
|
+
if (presentation.oauth !== null && presentation.oauth.session_id !== sessionId)
|
|
834
|
+
throw new Error('Retained OAuth presentation differs from the original session');
|
|
835
|
+
if (p.id !== callbackId(presentation) || p.expires !== ready().expires || typeof p.selected !== 'boolean')
|
|
836
|
+
throw new Error('Retained presentation identity changed');
|
|
837
|
+
return { id: id(p.id), presentation, expires: ready().expires, selected: p.selected };
|
|
838
|
+
});
|
|
839
|
+
},
|
|
840
|
+
async resumePresentation(callback, approved, signal) {
|
|
841
|
+
approved = presented(approved);
|
|
842
|
+
if (approved.oauth !== null && approved.oauth.session_id !== sessionId)
|
|
843
|
+
throw new Error('OAuth presentation differs from the original session');
|
|
844
|
+
if (id(callback) !== callbackId(approved) || (params.kind === 'oauth') !== (approved.oauth !== null))
|
|
845
|
+
throw new Error('Callback differs from the client-accepted presentation');
|
|
846
|
+
const response = await paced('POST /v1/sessions/{id}/presentations/{callback}/resume', () => control('/v1/sessions/' + sessionId + '/presentations/' + callback + '/resume', 'POST', undefined, signal), LIMITED, sessionDeadline(), signal);
|
|
847
|
+
ok(response, [200]);
|
|
848
|
+
},
|
|
849
|
+
async approveCredentials(proposal, member, approved, signal) {
|
|
850
|
+
await approve(proposal, member, 'credential', credentialBody(approved), signal);
|
|
851
|
+
},
|
|
852
|
+
async rejectProposal(proposal, signal) {
|
|
853
|
+
const response = await control('/v1/sessions/' + sessionId + '/execution/' + id(proposal) + '/reject', 'POST', undefined, signal);
|
|
854
|
+
ok(response, [204]);
|
|
855
|
+
},
|
|
856
|
+
async requestObject(signal) {
|
|
857
|
+
const c = ready();
|
|
858
|
+
if (params.kind === 'oauth')
|
|
859
|
+
throw new Error('OAuth sessions have no wallet request object');
|
|
860
|
+
const member = members.find(m => m.index === jarIndex);
|
|
861
|
+
const response = await read('GET /v1/request/{id}', '/v1/request/' + sessionId, signal, true);
|
|
862
|
+
ok(response, [200]);
|
|
863
|
+
const jwt = new TextDecoder('utf-8', { fatal: true }).decode(response.body).trim();
|
|
864
|
+
if (jwt.split('.').length !== 3)
|
|
865
|
+
throw new Error('Invalid compact Request Object');
|
|
866
|
+
const request = await verifyRequestObject(jwt, { nowSecs: Math.floor(Date.now() / 1000), leewaySecs: 0,
|
|
867
|
+
resolveKey: (did) => { if (did !== profile.clientId.replace(/^decentralized_identifier:/, ''))
|
|
868
|
+
throw new Error('Request issuer changed'); return Promise.resolve({ kty: 'OKP', crv: 'Ed25519', x: b64(protocolHex(member.publicKey, 32, 'drawn signer key')) }); } });
|
|
869
|
+
const claims = request.claims;
|
|
870
|
+
if (request.header.alg !== 'EdDSA' || claims.client_id !== profile.clientId || claims.response_uri !== profile.endpoint + '/v1/response?session=' + sessionId
|
|
871
|
+
|| claims.response_mode !== 'direct_post.jwt' || claims.response_type !== 'vp_token' || claims.state !== c.state || claims.nonce !== nonce
|
|
872
|
+
|| !Number.isSafeInteger(claims.iat) || !Number.isSafeInteger(claims.exp) || Number(claims.iat) > Math.floor(Date.now() / 1000) + 60
|
|
873
|
+
|| Number(claims.exp) <= Number(claims.iat) || Number(claims.exp) - Number(claims.iat) > 600
|
|
874
|
+
|| Number(claims.exp) <= Math.floor(Date.now() / 1000) || Number(claims.exp) > params.operation.exp || claims.client_metadata?.jwks?.keys?.length !== 1
|
|
875
|
+
|| executionBodyHash(object(claims.dcql_query)) !== executionBodyHash(dcql)
|
|
876
|
+
|| executionBodyHash(object(claims.client_metadata?.jwks?.keys?.[0])) !== executionBodyHash(c.key))
|
|
877
|
+
throw new Error('Request Object changed its client-selected session or query');
|
|
878
|
+
if (claims.transaction_data !== undefined) {
|
|
879
|
+
if (!Array.isArray(claims.transaction_data) || claims.transaction_data.length !== 1)
|
|
880
|
+
throw new Error('Invalid request transaction data');
|
|
881
|
+
const td = decodeJson(claims.transaction_data[0]);
|
|
882
|
+
if (td.type !== 'keykeeper-op/v1' || ['chain_id', 'slot_id', 'action', 'payload_digest', 'description'].some(k => td[k] !== params.operation[k]))
|
|
883
|
+
throw new Error('Request transaction data changed the authorized operation');
|
|
884
|
+
}
|
|
885
|
+
const qrPayload = 'openid4vp://?client_id=' + encodeURIComponent(profile.clientId) + '&request_uri=' + encodeURIComponent(requestUri);
|
|
886
|
+
return { request, requestUri, qrPayload };
|
|
887
|
+
} });
|
|
888
|
+
});
|
|
889
|
+
}
|