@t3foundry/tasra-sdk 0.0.0-stage → 0.3.1-next.1
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 +148 -0
- package/LICENSE +202 -0
- package/NOTICE +94 -0
- package/README.md +137 -2
- package/SECURITY.md +115 -0
- package/dist/app/approvals.d.ts +50 -0
- package/dist/app/approvals.js +90 -0
- package/dist/app/authorization.d.ts +19 -0
- package/dist/app/authorization.js +20 -0
- package/dist/app/client.d.ts +231 -0
- package/dist/app/client.js +272 -0
- package/dist/app/creation.d.ts +73 -0
- package/dist/app/creation.js +77 -0
- package/dist/app/deployment.d.ts +36 -0
- package/dist/app/deployment.js +18 -0
- package/dist/app/identity.d.ts +211 -0
- package/dist/app/identity.js +287 -0
- package/dist/app/index.d.ts +22 -0
- package/dist/app/index.js +12 -0
- package/dist/app/manifest.d.ts +74 -0
- package/dist/app/manifest.js +120 -0
- package/dist/app/node.d.ts +30 -0
- package/dist/app/node.js +159 -0
- package/dist/app/ready-slot.d.ts +157 -0
- package/dist/app/ready-slot.js +199 -0
- package/dist/app/tasra-client.d.ts +125 -0
- package/dist/app/tasra-client.js +79 -0
- package/dist/app/viem.d.ts +10 -0
- package/dist/app/viem.js +32 -0
- package/dist/app/wallet.d.ts +126 -0
- package/dist/app/wallet.js +137 -0
- package/dist/auth/dpop.d.ts +86 -0
- package/dist/auth/dpop.js +142 -0
- package/dist/auth/holderProof.d.ts +102 -0
- package/dist/auth/holderProof.js +161 -0
- package/dist/auth/identityScope.d.ts +19 -0
- package/dist/auth/identityScope.js +82 -0
- package/dist/auth/index.d.ts +11 -0
- package/dist/auth/index.js +13 -0
- package/dist/auth/oid4vp.d.ts +230 -0
- package/dist/auth/oid4vp.js +780 -0
- package/dist/auth/rego/wasm/PINS.json +11 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm.d.ts +76 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm.js +379 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm_bg.wasm +0 -0
- package/dist/auth/rego.d.ts +192 -0
- package/dist/auth/rego.js +492 -0
- package/dist/auth/verifier.d.ts +166 -0
- package/dist/auth/verifier.js +211 -0
- package/dist/chain/abis/accountantSetRegistry.d.ts +441 -0
- package/dist/chain/abis/accountantSetRegistry.js +574 -0
- package/dist/chain/abis/accountantSlashing.d.ts +2071 -0
- package/dist/chain/abis/accountantSlashing.js +2670 -0
- package/dist/chain/abis/bondingCurve.d.ts +398 -0
- package/dist/chain/abis/bondingCurve.js +521 -0
- package/dist/chain/abis/equivocationSlasher.d.ts +292 -0
- package/dist/chain/abis/equivocationSlasher.js +379 -0
- package/dist/chain/abis/fixedTasraPriceOracle.d.ts +52 -0
- package/dist/chain/abis/fixedTasraPriceOracle.js +72 -0
- package/dist/chain/abis/index.d.ts +12801 -0
- package/dist/chain/abis/index.js +64 -0
- package/dist/chain/abis/keeperShareRegistry.d.ts +519 -0
- package/dist/chain/abis/keeperShareRegistry.js +675 -0
- package/dist/chain/abis/keyRegistry.d.ts +2421 -0
- package/dist/chain/abis/keyRegistry.js +3114 -0
- package/dist/chain/abis/livenessRegistry.d.ts +402 -0
- package/dist/chain/abis/livenessRegistry.js +524 -0
- package/dist/chain/abis/mockEurc.d.ts +210 -0
- package/dist/chain/abis/mockEurc.js +276 -0
- package/dist/chain/abis/nodeRegistry.d.ts +1630 -0
- package/dist/chain/abis/nodeRegistry.js +2113 -0
- package/dist/chain/abis/platformExecutor.d.ts +328 -0
- package/dist/chain/abis/platformExecutor.js +429 -0
- package/dist/chain/abis/prevrandaoSaltBeacon.d.ts +16 -0
- package/dist/chain/abis/prevrandaoSaltBeacon.js +24 -0
- package/dist/chain/abis/serviceRegistry.d.ts +556 -0
- package/dist/chain/abis/serviceRegistry.js +719 -0
- package/dist/chain/abis/settlement.d.ts +1624 -0
- package/dist/chain/abis/settlement.js +2096 -0
- package/dist/chain/abis/tasraSwapRouter.d.ts +92 -0
- package/dist/chain/abis/tasraSwapRouter.js +122 -0
- package/dist/chain/abis/tasraToken.d.ts +455 -0
- package/dist/chain/abis/tasraToken.js +599 -0
- package/dist/chain/abis/tasraVestingVault.d.ts +165 -0
- package/dist/chain/abis/tasraVestingVault.js +215 -0
- package/dist/chain/abis/thresholdRandomBeacon.d.ts +378 -0
- package/dist/chain/abis/thresholdRandomBeacon.js +494 -0
- package/dist/chain/abis/treasury.d.ts +301 -0
- package/dist/chain/abis/treasury.js +390 -0
- package/dist/chain/abis/verifierSetRegistry.d.ts +445 -0
- package/dist/chain/abis/verifierSetRegistry.js +579 -0
- package/dist/chain/client.d.ts +212 -0
- package/dist/chain/client.js +576 -0
- package/dist/chain/commitmentRecovery.d.ts +21 -0
- package/dist/chain/commitmentRecovery.js +44 -0
- package/dist/chain/committeeClient.d.ts +102 -0
- package/dist/chain/committeeClient.js +137 -0
- package/dist/chain/deployments.d.ts +56 -0
- package/dist/chain/deployments.js +269 -0
- package/dist/chain/discovery.d.ts +49 -0
- package/dist/chain/discovery.js +107 -0
- package/dist/chain/events.d.ts +58 -0
- package/dist/chain/events.js +125 -0
- package/dist/chain/format.d.ts +25 -0
- package/dist/chain/format.js +51 -0
- package/dist/chain/index.d.ts +41 -0
- package/dist/chain/index.js +56 -0
- package/dist/chain/manifest.d.ts +165 -0
- package/dist/chain/manifest.js +132 -0
- package/dist/chain/network-profiles.json +75 -0
- package/dist/chain/networks.d.ts +73 -0
- package/dist/chain/networks.js +62 -0
- package/dist/chain/node.d.ts +44 -0
- package/dist/chain/node.js +176 -0
- package/dist/chain/offchain.d.ts +149 -0
- package/dist/chain/offchain.js +73 -0
- package/dist/chain/provisionRule.d.ts +164 -0
- package/dist/chain/provisionRule.js +212 -0
- package/dist/chain/registeredAgent.d.ts +64 -0
- package/dist/chain/registeredAgent.js +140 -0
- package/dist/chain/registeredOperation.d.ts +49 -0
- package/dist/chain/registeredOperation.js +136 -0
- package/dist/chain/registeredRelay.d.ts +206 -0
- package/dist/chain/registeredRelay.js +312 -0
- package/dist/chain/revertReason.d.ts +14 -0
- package/dist/chain/revertReason.js +62 -0
- package/dist/chain/ruleAmendment.d.ts +80 -0
- package/dist/chain/ruleAmendment.js +195 -0
- package/dist/chain/ruleAmendmentCore.d.ts +129 -0
- package/dist/chain/ruleAmendmentCore.js +152 -0
- package/dist/chain/ruleInput.d.ts +10 -0
- package/dist/chain/ruleInput.js +13 -0
- package/dist/chain/serviceIdentity.d.ts +176 -0
- package/dist/chain/serviceIdentity.js +237 -0
- package/dist/chain/serviceProfiles.d.ts +39 -0
- package/dist/chain/serviceProfiles.js +74 -0
- package/dist/chain/services.d.ts +141 -0
- package/dist/chain/services.js +79 -0
- package/dist/chain/slotClient.d.ts +55 -0
- package/dist/chain/slotClient.js +62 -0
- package/dist/chain/slotSeed.d.ts +31 -0
- package/dist/chain/slotSeed.js +98 -0
- package/dist/chain/write.d.ts +431 -0
- package/dist/chain/write.js +958 -0
- package/dist/client/client.d.ts +112 -0
- package/dist/client/client.js +111 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +2 -0
- package/dist/client/session.d.ts +67 -0
- package/dist/client/session.js +238 -0
- package/dist/committee/client.d.ts +284 -0
- package/dist/committee/client.js +351 -0
- package/dist/committee/dual-sign.d.ts +110 -0
- package/dist/committee/dual-sign.js +202 -0
- package/dist/committee/ecdsa.d.ts +36 -0
- package/dist/committee/ecdsa.js +45 -0
- package/dist/committee/extraction.d.ts +82 -0
- package/dist/committee/extraction.js +96 -0
- package/dist/committee/index.d.ts +19 -0
- package/dist/committee/index.js +13 -0
- package/dist/committee/oauth.d.ts +51 -0
- package/dist/committee/oauth.js +90 -0
- package/dist/committee/receipts.d.ts +51 -0
- package/dist/committee/receipts.js +59 -0
- package/dist/committee/request.d.ts +264 -0
- package/dist/committee/request.js +305 -0
- package/dist/committee/token.d.ts +274 -0
- package/dist/committee/token.js +418 -0
- package/dist/crypto/constants.d.ts +10 -0
- package/dist/crypto/constants.js +32 -0
- package/dist/crypto/detect.d.ts +20 -0
- package/dist/crypto/detect.js +44 -0
- package/dist/crypto/envelope.d.ts +60 -0
- package/dist/crypto/envelope.js +243 -0
- package/dist/crypto/frost.d.ts +49 -0
- package/dist/crypto/frost.js +152 -0
- package/dist/crypto/hex.d.ts +7 -0
- package/dist/crypto/hex.js +24 -0
- package/dist/crypto/ibe-blob.d.ts +114 -0
- package/dist/crypto/ibe-blob.js +208 -0
- package/dist/crypto/ibe.d.ts +88 -0
- package/dist/crypto/ibe.js +262 -0
- package/dist/crypto/index.d.ts +12 -0
- package/dist/crypto/index.js +12 -0
- package/dist/crypto/kem.d.ts +55 -0
- package/dist/crypto/kem.js +241 -0
- package/dist/decryption/client.d.ts +64 -0
- package/dist/decryption/client.js +82 -0
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/errors.d.ts +124 -0
- package/dist/errors.js +167 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +98 -0
- package/dist/keys/index.d.ts +1 -0
- package/dist/keys/index.js +4 -0
- package/dist/keys/node-client.d.ts +27 -0
- package/dist/keys/node-client.js +97 -0
- package/dist/oid4vp/binding.d.ts +76 -0
- package/dist/oid4vp/binding.js +118 -0
- package/dist/oid4vp/did-web.d.ts +49 -0
- package/dist/oid4vp/did-web.js +57 -0
- package/dist/oid4vp/index.d.ts +9 -0
- package/dist/oid4vp/index.js +10 -0
- package/dist/oid4vp/jose.d.ts +166 -0
- package/dist/oid4vp/jose.js +242 -0
- package/dist/oid4vp/jwe.d.ts +30 -0
- package/dist/oid4vp/jwe.js +93 -0
- package/dist/oid4vp/oid4vci.d.ts +84 -0
- package/dist/oid4vp/oid4vci.js +85 -0
- package/dist/oid4vp/request-object.d.ts +109 -0
- package/dist/oid4vp/request-object.js +96 -0
- package/dist/oid4vp/sd-jwt.d.ts +177 -0
- package/dist/oid4vp/sd-jwt.js +208 -0
- package/dist/oid4vp/verifier-agent.d.ts +161 -0
- package/dist/oid4vp/verifier-agent.js +132 -0
- package/dist/oid4vp/wallet.d.ts +116 -0
- package/dist/oid4vp/wallet.js +108 -0
- package/dist/recipient/store.d.ts +67 -0
- package/dist/recipient/store.js +98 -0
- package/dist/signing/ecdsa.d.ts +49 -0
- package/dist/signing/ecdsa.js +79 -0
- package/dist/signing/frost.d.ts +88 -0
- package/dist/signing/frost.js +145 -0
- package/dist/signing/index.d.ts +4 -0
- package/dist/signing/index.js +3 -0
- package/dist/slots/faucet.d.ts +23 -0
- package/dist/slots/faucet.js +35 -0
- package/dist/slots/index.d.ts +2 -0
- package/dist/slots/index.js +4 -0
- package/dist/verifier-agent/index.d.ts +241 -0
- package/dist/verifier-agent/index.js +411 -0
- package/docs/DEVELOPER-EXPERIENCE.md +62 -0
- package/docs/README.md +33 -0
- package/docs/access-control.md +76 -0
- package/docs/ai-development.md +292 -0
- package/docs/api.md +338 -0
- package/docs/application-api.md +335 -0
- package/docs/architecture.md +65 -0
- package/docs/basics.md +48 -0
- package/docs/capabilities.md +86 -0
- package/docs/chain.md +153 -0
- package/docs/compatibility.md +36 -0
- package/docs/consumer-migrations.md +80 -0
- package/docs/create-slot.md +104 -0
- package/docs/document-signing.md +243 -0
- package/docs/encrypted-notes.md +129 -0
- package/docs/encryption.md +100 -0
- package/docs/errors.md +76 -0
- package/docs/flows.md +289 -0
- package/docs/fuji.md +127 -0
- package/docs/funding.md +126 -0
- package/docs/getting-started.md +94 -0
- package/docs/glossary.md +44 -0
- package/docs/installation.md +132 -0
- package/docs/manage-slot.md +95 -0
- package/docs/native-approvals.md +124 -0
- package/docs/prerequisites.md +137 -0
- package/docs/read-slot.md +41 -0
- package/docs/reference/README.md +30 -0
- package/docs/reference/app-node.md +102 -0
- package/docs/reference/app.md +1737 -0
- package/docs/reference/chain-node.md +159 -0
- package/docs/reference/chain.md +3609 -0
- package/docs/reference/committee.md +2176 -0
- package/docs/reference/main.md +4068 -0
- package/docs/reference/oid4vp.md +2547 -0
- package/docs/reference/verifier-agent.md +498 -0
- package/docs/shared-account.md +168 -0
- package/docs/signing-and-encryption.md +52 -0
- package/docs/signing.md +172 -0
- package/examples/committee-slot.ts +16 -0
- package/examples/connect-fuji.ts +41 -0
- package/examples/connect-network.ts +14 -0
- package/examples/credential-approvals.ts +46 -0
- package/examples/document-signing/README.md +59 -0
- package/examples/document-signing/backend.ts +132 -0
- package/examples/document-signing/build.mjs +19 -0
- package/examples/document-signing/config.ts +34 -0
- package/examples/document-signing/gitignore.template +9 -0
- package/examples/document-signing/model.ts +140 -0
- package/examples/document-signing/network.ts +58 -0
- package/examples/document-signing/package.json +25 -0
- package/examples/document-signing/public/index.html +27 -0
- package/examples/document-signing/public/sample.pdf +31 -0
- package/examples/document-signing/public/styles.css +531 -0
- package/examples/document-signing/server.ts +358 -0
- package/examples/document-signing/setup.ts +111 -0
- package/examples/document-signing/store.ts +105 -0
- package/examples/document-signing/tsconfig.json +24 -0
- package/examples/document-signing/verify.ts +24 -0
- package/examples/document-signing/web/app.ts +312 -0
- package/examples/document-signing/web/preview.ts +67 -0
- package/examples/document-signing/web/wallet.ts +146 -0
- package/examples/document-signing/workflow.test.ts +228 -0
- package/examples/document-signing/workflow.ts +241 -0
- package/examples/document-signing.ts +96 -0
- package/examples/encrypted-notes.ts +86 -0
- package/examples/ethers-signer.ts +204 -0
- package/examples/fund-slot.ts +73 -0
- package/examples/getting-started.ts +25 -0
- package/examples/learning-authorize.ts +23 -0
- package/examples/learning-cancel-slot.ts +11 -0
- package/examples/learning-context.ts +28 -0
- package/examples/learning-create-slot.ts +25 -0
- package/examples/learning-read-slot.ts +8 -0
- package/examples/learning-renew-slot.ts +12 -0
- package/examples/learning-sign.ts +8 -0
- package/examples/live-config.ts +71 -0
- package/examples/minimal.ts +6 -0
- package/examples/native-approvals.ts +57 -0
- package/examples/network.ts +58 -0
- package/examples/offline.ts +16 -0
- package/examples/personal-vault.ts +20 -0
- package/examples/provision-slot.ts +47 -0
- package/examples/shared-account.ts +46 -0
- package/examples/slot-address.ts +13 -0
- package/examples/slot-creation.ts +9 -0
- package/examples/tutorial-negative.ts +26 -0
- package/examples/tutorial-support.ts +76 -0
- package/examples/viem-account.ts +203 -0
- package/package.json +303 -4
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { TasraError } from '../errors.js';
|
|
2
|
+
/** The operation the holder is authorizing - signed by the creator's EIP-712 key. */
|
|
3
|
+
import type { DpopSigner } from '../auth/dpop.js';
|
|
4
|
+
/** Operation details signed by a slot creator or delegate for credential authorization. */
|
|
5
|
+
export interface PresentationOperation {
|
|
6
|
+
/** EVM chain identifier. */
|
|
7
|
+
chain_id: number;
|
|
8
|
+
/** 0x-hex 32-byte slot identifier */
|
|
9
|
+
slot_id: string;
|
|
10
|
+
/** "sign" | "decrypt" | "ibe-extract" | "dual-approve" */
|
|
11
|
+
action: string;
|
|
12
|
+
/** 0x-hex 32-byte digest (sha256 of the message for sign/ibe-extract) */
|
|
13
|
+
payload_digest: string;
|
|
14
|
+
/** Human-readable description shown in transaction_data */
|
|
15
|
+
description: string;
|
|
16
|
+
/** Unix timestamp - when the authorization expires */
|
|
17
|
+
exp: number;
|
|
18
|
+
}
|
|
19
|
+
/** EIP-712 delegation from the slot creator to a delegate address. */
|
|
20
|
+
export interface PresentationDelegation {
|
|
21
|
+
/** EVM chain identifier. */
|
|
22
|
+
chain_id: number;
|
|
23
|
+
/** Slot identifiers covered by this delegation. */
|
|
24
|
+
slot_ids: string[];
|
|
25
|
+
/** 0x-hex 20-byte delegate address */
|
|
26
|
+
delegate: string;
|
|
27
|
+
/** Operation names the delegate may authorize. */
|
|
28
|
+
actions: string[];
|
|
29
|
+
/** Expiration time in Unix seconds. */
|
|
30
|
+
exp: number;
|
|
31
|
+
/** Delegation nonce included in the signed payload. */
|
|
32
|
+
nonce: number;
|
|
33
|
+
/** 0x-hex 65-byte EIP-712 signature */
|
|
34
|
+
signature: string;
|
|
35
|
+
}
|
|
36
|
+
/** Signed operation, optional delegation and payload submitted to the verifier agent. */
|
|
37
|
+
export interface CreateSessionParams {
|
|
38
|
+
/** Signed operation details presented for authorization. */
|
|
39
|
+
operation: PresentationOperation;
|
|
40
|
+
/** 0x-hex 65-byte EIP-712 signature over the operation */
|
|
41
|
+
operationSig: string;
|
|
42
|
+
/** Optional EIP-712 delegation from the slot creator */
|
|
43
|
+
delegation?: PresentationDelegation;
|
|
44
|
+
/** The raw payload as 0x-hex */
|
|
45
|
+
messageHex: string;
|
|
46
|
+
}
|
|
47
|
+
/** Wallet presentation link and polling credentials for an opened authorization session. */
|
|
48
|
+
export interface CreateSessionResult {
|
|
49
|
+
/** Opened authorization session identifier. */
|
|
50
|
+
sessionId: string;
|
|
51
|
+
/** Bearer token for polling - treat as a secret */
|
|
52
|
+
pollSecret: string;
|
|
53
|
+
/** OpenID4VP deep link for a wallet or QR code. */
|
|
54
|
+
qrPayload: string;
|
|
55
|
+
/** URL from which the wallet retrieves the signed request. */
|
|
56
|
+
requestUri: string;
|
|
57
|
+
}
|
|
58
|
+
/** an `oauth` session - the client brings a DPoP-bound access token. */
|
|
59
|
+
export interface CreateOauthSessionResult {
|
|
60
|
+
/** Opened authorization session identifier. */
|
|
61
|
+
sessionId: string;
|
|
62
|
+
/** Session secret used for polling and OAuth submission. Never expose it in logs. */
|
|
63
|
+
pollSecret: string;
|
|
64
|
+
/** Initial DPoP challenge nonce for this session. */
|
|
65
|
+
nonce: string;
|
|
66
|
+
/** Canonical OAuth response URI to bind into the DPoP proof. */
|
|
67
|
+
dpopHtu: string;
|
|
68
|
+
/** Audience the identity provider must include in the access token for this platform. */
|
|
69
|
+
platformAudience: string;
|
|
70
|
+
}
|
|
71
|
+
/** Displayable authorization progress. A done phase means the committee answered; it does not mean the requested signing or decryption operation executed. */
|
|
72
|
+
export type SessionPhase = 'awaiting_wallet' | 'verifying' | 'done' | 'failed';
|
|
73
|
+
/** Authorization session progress and optional committee result or failure detail. */
|
|
74
|
+
export interface SessionStatusResult {
|
|
75
|
+
/** Pending, completed or failed authorization state. */
|
|
76
|
+
status: 'pending' | 'done' | 'failed';
|
|
77
|
+
/** Displayable progress within the authorization lifecycle. */
|
|
78
|
+
phase: SessionPhase;
|
|
79
|
+
/** Committee token returned after successful authorization. */
|
|
80
|
+
compoundToken?: Record<string, unknown>;
|
|
81
|
+
/** Verifier membership proofs for the selected snapshot. */
|
|
82
|
+
verifierProofs?: unknown;
|
|
83
|
+
/** Operation context used to derive the request-binding hash. */
|
|
84
|
+
bindingPreimage?: Record<string, unknown>;
|
|
85
|
+
/** Optional failure detail reported by the verifier agent. */
|
|
86
|
+
error?: string;
|
|
87
|
+
/** the sealed presentation (base64url `bincode(Ciphertext)`) the token's
|
|
88
|
+
* `evidence_hash` names — post it to the keeper beside the token as `evidence_ct`. */
|
|
89
|
+
evidenceCt?: string;
|
|
90
|
+
}
|
|
91
|
+
/** Why a session did not yield a token - the class the UI explains, with a NON-SECRET
|
|
92
|
+
* correlation reference (the session id; the poll secret is never part of an error). */
|
|
93
|
+
export type VerifierAgentSessionErrorKind =
|
|
94
|
+
/** The deadline passed while the verifier-agent still reported `pending`. */
|
|
95
|
+
'timeout'
|
|
96
|
+
/** The verifier-agent reported `failed`: a verifier or the wallet refused (`error` says which). */
|
|
97
|
+
| 'refused'
|
|
98
|
+
/** The verifier-agent (or its store) could not answer - retry later, the session may still complete. */
|
|
99
|
+
| 'unavailable'
|
|
100
|
+
/** The verifier-agent answered something the contract does not allow (a malformed reply, 401/404). */
|
|
101
|
+
| 'protocol'
|
|
102
|
+
/** The caller's `AbortSignal` fired. */
|
|
103
|
+
| 'cancelled';
|
|
104
|
+
/**
|
|
105
|
+
* A Verifier Agent session did not produce a compound token. `kind` says why;
|
|
106
|
+
* `retryable` is true only for `timeout` and `unavailable` - the session may
|
|
107
|
+
* still complete, so poll again. Extends {@link TasraError}.
|
|
108
|
+
*/
|
|
109
|
+
export declare class VerifierAgentSessionError extends TasraError {
|
|
110
|
+
/** Failure category used to select recovery behavior. */
|
|
111
|
+
readonly kind: VerifierAgentSessionErrorKind;
|
|
112
|
+
/** The session id - safe to show and to log. */
|
|
113
|
+
readonly correlation: string;
|
|
114
|
+
/** The HTTP status that produced a `protocol`/`unavailable` error, when there was one. */
|
|
115
|
+
readonly httpStatus?: number;
|
|
116
|
+
constructor(kind: VerifierAgentSessionErrorKind, correlation: string, message: string, httpStatus?: number);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The compound token the verifier-agent hands back must be the wire shape the keepers verify -
|
|
120
|
+
* checked field by field before anything is built on it.
|
|
121
|
+
*
|
|
122
|
+
* @param raw - Untrusted compound_token response value.
|
|
123
|
+
* @param correlation - Session identifier used to correlate validation errors.
|
|
124
|
+
*/
|
|
125
|
+
export declare function assertCompoundTokenWire(raw: unknown, correlation: string): Record<string, unknown>;
|
|
126
|
+
/**
|
|
127
|
+
* Compute the `payload_digest` for a given action and message.
|
|
128
|
+
*
|
|
129
|
+
* For `sign` and `ibe-extract`, this is `sha256(message_bytes)` as 0x-hex.
|
|
130
|
+
* Other actions should supply the digest directly.
|
|
131
|
+
*
|
|
132
|
+
* @param action - Operation name: sign and ibe-extract hash the supplied bytes.
|
|
133
|
+
* @param messageHex - Hexadecimal message bytes or an already computed digest for other actions.
|
|
134
|
+
*/
|
|
135
|
+
export declare function payloadDigest(action: string, messageHex: string): string;
|
|
136
|
+
/**
|
|
137
|
+
* Create an OID4VP session on the Verifier Agent.
|
|
138
|
+
*
|
|
139
|
+
* The verifier-agent derives a nonce, generates an ECDH key for JWE, and returns a QR
|
|
140
|
+
* payload the wallet scans. The session ID and poll secret are used to poll
|
|
141
|
+
* for the result.
|
|
142
|
+
*
|
|
143
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL from the selected network manifest.
|
|
144
|
+
* @param params - Signed operation, optional delegation and raw payload.
|
|
145
|
+
*/
|
|
146
|
+
export declare function createOid4vpSession(verifierAgentUrl: string, params: CreateSessionParams): Promise<CreateSessionResult>;
|
|
147
|
+
/**
|
|
148
|
+
* Open an `oauth` session - same creator authorisation, same committee draw, same
|
|
149
|
+
* derived nonce, same poll contract as {@link createOid4vpSession}. No QR, no Request
|
|
150
|
+
* Object, no JWE key: the client presents an access token its own IdP minted.
|
|
151
|
+
*
|
|
152
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL from the selected network manifest.
|
|
153
|
+
* @param params - Signed operation, optional delegation and raw payload.
|
|
154
|
+
*/
|
|
155
|
+
export declare function createOauthSession(verifierAgentUrl: string, params: CreateSessionParams): Promise<CreateOauthSessionResult>;
|
|
156
|
+
/**
|
|
157
|
+
* Submit a DPoP-bound access token and proof to an OAuth session. The signer must use the key bound to that token. Retry once when the server responds with a DPoP nonce challenge.
|
|
158
|
+
*
|
|
159
|
+
* Speaks the RFC 9449 §9 resource-server contract — token in `Authorization: DPoP`, proof in
|
|
160
|
+
* `DPoP:` — so a conformant client library needs no custom code. It also handles the
|
|
161
|
+
* `use_dpop_nonce` challenge ITSELF: on a `401` carrying `DPoP-Nonce`, it re-mints the proof
|
|
162
|
+
* with the server's nonce and resends ONCE. One retry, not a loop: a server that keeps
|
|
163
|
+
* challenging is broken, and retrying forever would hide that.
|
|
164
|
+
*
|
|
165
|
+
* `signer` must be the key the token is bound to — see `../auth/dpop.js` for the two shapes.
|
|
166
|
+
*
|
|
167
|
+
* Note: the proof is signed over `dpopHtu` — the agent's PUBLIC origin plus this session's route,
|
|
168
|
+
* as {@link createOauthSession} returned it — and posted to `verifierAgentUrl`. When the two
|
|
169
|
+
* name the same host (the normal case) they are the same URL. When a client reaches the
|
|
170
|
+
* agent through a different base URL, the proof must still name the public one: that is
|
|
171
|
+
* the origin the verifiers approved.
|
|
172
|
+
*
|
|
173
|
+
* Throws `VerifierAgentSessionError`: `refused` when the agent reports the session failed
|
|
174
|
+
* (the committee refused, or could not be reached — `message` says which; not retryable on
|
|
175
|
+
* this session), `unavailable` for other 502/503/504, `protocol` for any other non-2xx.
|
|
176
|
+
*
|
|
177
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL.
|
|
178
|
+
* @param args - Session credentials, DPoP-bound access token, nonce, `dpopHtu` and matching signer.
|
|
179
|
+
*/
|
|
180
|
+
export declare function submitOauthResponse(verifierAgentUrl: string, args: {
|
|
181
|
+
sessionId: string;
|
|
182
|
+
pollSecret: string;
|
|
183
|
+
accessToken: string;
|
|
184
|
+
/** Initial DPoP challenge nonce returned when the OAuth session was created. */
|
|
185
|
+
nonce: string;
|
|
186
|
+
dpopHtu: string;
|
|
187
|
+
signer: DpopSigner;
|
|
188
|
+
}): Promise<void>;
|
|
189
|
+
/**
|
|
190
|
+
* Fetch and validate one authorization session status. Transport failures and HTTP 502, 503 or 504 produce an unavailable error; malformed or other failed replies produce a protocol error. The polling secret is sent in the Authorization header.
|
|
191
|
+
*
|
|
192
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL.
|
|
193
|
+
* @param sessionId - Opened session identifier.
|
|
194
|
+
* @param pollSecret - Secret returned at session creation; do not expose it in logs.
|
|
195
|
+
*/
|
|
196
|
+
export declare function pollOid4vpSession(verifierAgentUrl: string, sessionId: string, pollSecret: string): Promise<SessionStatusResult>;
|
|
197
|
+
/**
|
|
198
|
+
* Shared validation for the explicit-URL and registered-agent transports.
|
|
199
|
+
*
|
|
200
|
+
* @param data - Untrusted JSON session response.
|
|
201
|
+
* @param sessionId - Session identifier used to correlate validation errors.
|
|
202
|
+
*/
|
|
203
|
+
export declare function parseVerifierAgentSessionStatus(data: Record<string, unknown>, sessionId: string): SessionStatusResult;
|
|
204
|
+
/** Polling backoff, cancellation, progress callback and randomness options. */
|
|
205
|
+
export interface WaitOpts {
|
|
206
|
+
/** Ceiling for the growing interval (default 4 times intervalMs). */
|
|
207
|
+
maxIntervalMs?: number;
|
|
208
|
+
/** Cancel (a user closed the wallet prompt): rejects with `cancelled`. */
|
|
209
|
+
signal?: AbortSignal;
|
|
210
|
+
/** Called on every poll with the phase the UI may show. */
|
|
211
|
+
onPhase?: (phase: SessionPhase) => void;
|
|
212
|
+
/** Randomness for the jitter (tests inject a fixed value). */
|
|
213
|
+
random?: () => number;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The next polling delay: geometric growth (times1.5) capped at `max`, plus or minus20 % full jitter.
|
|
217
|
+
* Pure, so the schedule is testable without timers.
|
|
218
|
+
*
|
|
219
|
+
* @param previousMs - Previous polling delay in milliseconds, or zero before the first poll.
|
|
220
|
+
* @param baseMs - Initial polling interval in milliseconds.
|
|
221
|
+
* @param maxMs - Maximum interval before jitter is applied.
|
|
222
|
+
* @param random - Random source returning a value between zero and one.
|
|
223
|
+
*/
|
|
224
|
+
export declare function nextPollDelay(previousMs: number, baseMs: number, maxMs: number, random?: () => number): number;
|
|
225
|
+
/**
|
|
226
|
+
* Poll until the session reaches a terminal state (done or failed) - bounded by
|
|
227
|
+
* `timeoutMs`, with a growing jittered interval so many clients never poll in lock-step.
|
|
228
|
+
* A transient `unavailable` answer (a 503, a dropped connection) is retried within the
|
|
229
|
+
* deadline; a `protocol` answer stops at once; the deadline is a `timeout` error; the
|
|
230
|
+
* caller's `signal` is a `cancelled` error. A terminal `failed` is RETURNED (the caller
|
|
231
|
+
* decides how to explain it) - see `awaitVerifierAgentResult` for the version that throws `refused`.
|
|
232
|
+
*
|
|
233
|
+
* @param pollSecret - bearer token returned by `createOid4vpSession`
|
|
234
|
+
* @param intervalMs - initial polling interval in milliseconds (default 2000)
|
|
235
|
+
* @param timeoutMs - total deadline in milliseconds (default 300000 = 5 min)
|
|
236
|
+
*
|
|
237
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL.
|
|
238
|
+
* @param sessionId - Opened session identifier.
|
|
239
|
+
* @param opts - Cancellation, phase callback and polling backoff controls.
|
|
240
|
+
*/
|
|
241
|
+
export declare function waitForSession(verifierAgentUrl: string, sessionId: string, pollSecret: string, intervalMs?: number, timeoutMs?: number, opts?: WaitOpts): Promise<SessionStatusResult>;
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
// Verifier Agent client - creates OID4VP sessions on the platform verifier-agent and
|
|
2
|
+
// polls for the compound token result.
|
|
3
|
+
//
|
|
4
|
+
// Usage:
|
|
5
|
+
// const session = await createOid4vpSession(verifierAgentUrl, {
|
|
6
|
+
// operation: { chain_id, slot_id, action, payload_digest, description, exp },
|
|
7
|
+
// operationSig: '0x...',
|
|
8
|
+
// messageHex: '0x...',
|
|
9
|
+
// })
|
|
10
|
+
// // ... wallet scans session.qrPayload ...
|
|
11
|
+
// const result = await pollOid4vpSession(verifierAgentUrl, session.sessionId, session.pollSecret)
|
|
12
|
+
// // result.compoundToken + result.bindingPreimage to committeeSign()
|
|
13
|
+
import { sha256 } from '@noble/hashes/sha256';
|
|
14
|
+
import { bytesToHex } from '@noble/hashes/utils';
|
|
15
|
+
import { TasraError } from '../errors.js';
|
|
16
|
+
/**
|
|
17
|
+
* A Verifier Agent session did not produce a compound token. `kind` says why;
|
|
18
|
+
* `retryable` is true only for `timeout` and `unavailable` - the session may
|
|
19
|
+
* still complete, so poll again. Extends {@link TasraError}.
|
|
20
|
+
*/
|
|
21
|
+
export class VerifierAgentSessionError extends TasraError {
|
|
22
|
+
/** Failure category used to select recovery behavior. */
|
|
23
|
+
kind;
|
|
24
|
+
/** The session id - safe to show and to log. */
|
|
25
|
+
correlation;
|
|
26
|
+
/** The HTTP status that produced a `protocol`/`unavailable` error, when there was one. */
|
|
27
|
+
httpStatus;
|
|
28
|
+
constructor(kind, correlation, message, httpStatus) {
|
|
29
|
+
super(`${message} (session ${correlation.slice(0, 12)}…)`, {
|
|
30
|
+
retryable: kind === 'timeout' || kind === 'unavailable',
|
|
31
|
+
});
|
|
32
|
+
this.kind = kind;
|
|
33
|
+
this.correlation = correlation;
|
|
34
|
+
this.httpStatus = httpStatus;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const PHASES = new Set(['awaiting_wallet', 'verifying', 'done', 'failed']);
|
|
38
|
+
const STATUSES = new Set(['pending', 'done', 'failed']);
|
|
39
|
+
const HEX32 = /^0x[0-9a-f]{64}$/i;
|
|
40
|
+
/**
|
|
41
|
+
* The compound token the verifier-agent hands back must be the wire shape the keepers verify -
|
|
42
|
+
* checked field by field before anything is built on it.
|
|
43
|
+
*
|
|
44
|
+
* @param raw - Untrusted compound_token response value.
|
|
45
|
+
* @param correlation - Session identifier used to correlate validation errors.
|
|
46
|
+
*/
|
|
47
|
+
export function assertCompoundTokenWire(raw, correlation) {
|
|
48
|
+
const bad = (why) => {
|
|
49
|
+
throw new VerifierAgentSessionError('protocol', correlation, `compound_token: ${why}`);
|
|
50
|
+
};
|
|
51
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
52
|
+
bad('not an object');
|
|
53
|
+
const t = { ...raw };
|
|
54
|
+
// Reference-side optional fields are serialized as null for non-IBE operations. Normalize
|
|
55
|
+
// absence before consumers decode the token; never replace it with a zero hash.
|
|
56
|
+
for (const key of ['identity_hash', 'request_hash'])
|
|
57
|
+
if (t[key] === null)
|
|
58
|
+
delete t[key];
|
|
59
|
+
for (const k of ['seed', 'slot_id', 'vp_hash', 'holder_hash', 'rule_hash']) {
|
|
60
|
+
if (typeof t[k] !== 'string' || !HEX32.test(t[k]))
|
|
61
|
+
bad(`${k} is not a 32-byte hex string`);
|
|
62
|
+
}
|
|
63
|
+
if (typeof t.token_type !== 'string')
|
|
64
|
+
bad('token_type missing');
|
|
65
|
+
for (const k of ['epoch', 'iat', 'exp']) {
|
|
66
|
+
if (typeof t[k] !== 'number' || !Number.isFinite(t[k]))
|
|
67
|
+
bad(`${k} is not a number`);
|
|
68
|
+
}
|
|
69
|
+
if (t.exp <= t.iat)
|
|
70
|
+
bad('exp is not after iat');
|
|
71
|
+
if (t.request_hash !== undefined && (typeof t.request_hash !== 'string' || !HEX32.test(t.request_hash)))
|
|
72
|
+
bad('request_hash is not a 32-byte hex string');
|
|
73
|
+
if (t.identity_hash !== undefined && (typeof t.identity_hash !== 'string' || !HEX32.test(t.identity_hash)))
|
|
74
|
+
bad('identity_hash is not a 32-byte hex string');
|
|
75
|
+
if (t.binding !== undefined && !['unbound', 'holder_key', 'issuer_asserted'].includes(t.binding))
|
|
76
|
+
bad('binding is not a known strength');
|
|
77
|
+
if (!Array.isArray(t.verifier_indexes) || !t.verifier_indexes.every(i => Number.isInteger(i) && i >= 0))
|
|
78
|
+
bad('verifier_indexes is not an index list');
|
|
79
|
+
if (!Array.isArray(t.signatures) || t.signatures.length === 0)
|
|
80
|
+
bad('signatures missing');
|
|
81
|
+
const checkSignatures = (list, what) => {
|
|
82
|
+
for (const sig of list) {
|
|
83
|
+
const sg = sig;
|
|
84
|
+
if (!sg || typeof sg !== 'object' || !Number.isInteger(sg.verifier_index) || typeof sg.signature !== 'string')
|
|
85
|
+
bad(`a ${what} entry is not {verifier_index, signature}`);
|
|
86
|
+
if (!t.verifier_indexes.includes(sg.verifier_index))
|
|
87
|
+
bad(`a ${what} entry names an index outside the committee`);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
checkSignatures(t.signatures, 'signature');
|
|
91
|
+
// the sealed-evidence binding is all-or-none.
|
|
92
|
+
for (const key of ['evidence_hash', 'evidence_key_id', 'evidence_signatures'])
|
|
93
|
+
if (t[key] === null)
|
|
94
|
+
delete t[key];
|
|
95
|
+
const evidence = ['evidence_hash', 'evidence_key_id', 'evidence_signatures'].filter(k => t[k] !== undefined).length;
|
|
96
|
+
if (evidence !== 0 && evidence !== 3)
|
|
97
|
+
bad('evidence_hash, evidence_key_id and evidence_signatures come together or not at all');
|
|
98
|
+
if (evidence === 3) {
|
|
99
|
+
for (const k of ['evidence_hash', 'evidence_key_id']) {
|
|
100
|
+
if (typeof t[k] !== 'string' || !HEX32.test(t[k]))
|
|
101
|
+
bad(`${k} is not a 32-byte hex string`);
|
|
102
|
+
}
|
|
103
|
+
if (!Array.isArray(t.evidence_signatures) || t.evidence_signatures.length === 0)
|
|
104
|
+
bad('evidence_signatures missing');
|
|
105
|
+
checkSignatures(t.evidence_signatures, 'evidence signature');
|
|
106
|
+
}
|
|
107
|
+
return t;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Compute the `payload_digest` for a given action and message.
|
|
111
|
+
*
|
|
112
|
+
* For `sign` and `ibe-extract`, this is `sha256(message_bytes)` as 0x-hex.
|
|
113
|
+
* Other actions should supply the digest directly.
|
|
114
|
+
*
|
|
115
|
+
* @param action - Operation name: sign and ibe-extract hash the supplied bytes.
|
|
116
|
+
* @param messageHex - Hexadecimal message bytes or an already computed digest for other actions.
|
|
117
|
+
*/
|
|
118
|
+
export function payloadDigest(action, messageHex) {
|
|
119
|
+
const clean = messageHex.replace(/^0x/, '');
|
|
120
|
+
const messageBytes = new Uint8Array(clean.match(/.{1,2}/g)?.map((b) => parseInt(b, 16)) ?? []);
|
|
121
|
+
if (action === 'sign' || action === 'ibe-extract') {
|
|
122
|
+
return '0x' + bytesToHex(sha256(messageBytes));
|
|
123
|
+
}
|
|
124
|
+
throw new Error(`payloadDigest not implemented for action "${action}" — supply it directly`);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Create an OID4VP session on the Verifier Agent.
|
|
128
|
+
*
|
|
129
|
+
* The verifier-agent derives a nonce, generates an ECDH key for JWE, and returns a QR
|
|
130
|
+
* payload the wallet scans. The session ID and poll secret are used to poll
|
|
131
|
+
* for the result.
|
|
132
|
+
*
|
|
133
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL from the selected network manifest.
|
|
134
|
+
* @param params - Signed operation, optional delegation and raw payload.
|
|
135
|
+
*/
|
|
136
|
+
export async function createOid4vpSession(verifierAgentUrl, params) {
|
|
137
|
+
const url = `${verifierAgentUrl.replace(/\/$/, '')}/v1/sessions`;
|
|
138
|
+
const resp = await fetch(url, {
|
|
139
|
+
method: 'POST',
|
|
140
|
+
headers: { 'Content-Type': 'application/json' },
|
|
141
|
+
body: JSON.stringify({
|
|
142
|
+
operation: params.operation,
|
|
143
|
+
operation_sig: params.operationSig,
|
|
144
|
+
delegation: params.delegation,
|
|
145
|
+
message_hex: params.messageHex,
|
|
146
|
+
}),
|
|
147
|
+
});
|
|
148
|
+
if (!resp.ok) {
|
|
149
|
+
const body = await resp.text();
|
|
150
|
+
throw new Error(`createOid4vpSession failed (${resp.status}): ${body}`);
|
|
151
|
+
}
|
|
152
|
+
const data = (await resp.json());
|
|
153
|
+
for (const k of ['session_id', 'poll_secret', 'qr_payload', 'request_uri']) {
|
|
154
|
+
if (typeof data[k] !== 'string' || !data[k])
|
|
155
|
+
throw new Error(`createOid4vpSession: reply lacks ${k}`);
|
|
156
|
+
}
|
|
157
|
+
if (!data.qr_payload.startsWith('openid4vp://'))
|
|
158
|
+
throw new Error('createOid4vpSession: qr_payload is not an openid4vp:// request');
|
|
159
|
+
return {
|
|
160
|
+
sessionId: data.session_id,
|
|
161
|
+
pollSecret: data.poll_secret,
|
|
162
|
+
qrPayload: data.qr_payload,
|
|
163
|
+
requestUri: data.request_uri,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Open an `oauth` session - same creator authorisation, same committee draw, same
|
|
168
|
+
* derived nonce, same poll contract as {@link createOid4vpSession}. No QR, no Request
|
|
169
|
+
* Object, no JWE key: the client presents an access token its own IdP minted.
|
|
170
|
+
*
|
|
171
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL from the selected network manifest.
|
|
172
|
+
* @param params - Signed operation, optional delegation and raw payload.
|
|
173
|
+
*/
|
|
174
|
+
export async function createOauthSession(verifierAgentUrl, params) {
|
|
175
|
+
const url = `${verifierAgentUrl.replace(/\/$/, '')}/v1/sessions`;
|
|
176
|
+
const resp = await fetch(url, {
|
|
177
|
+
method: 'POST',
|
|
178
|
+
headers: { 'Content-Type': 'application/json' },
|
|
179
|
+
body: JSON.stringify({
|
|
180
|
+
operation: params.operation,
|
|
181
|
+
operation_sig: params.operationSig,
|
|
182
|
+
delegation: params.delegation,
|
|
183
|
+
message_hex: params.messageHex,
|
|
184
|
+
kind: 'oauth',
|
|
185
|
+
}),
|
|
186
|
+
});
|
|
187
|
+
if (!resp.ok) {
|
|
188
|
+
const body = await resp.text();
|
|
189
|
+
throw new Error(`createOauthSession failed (${resp.status}): ${body}`);
|
|
190
|
+
}
|
|
191
|
+
const data = (await resp.json());
|
|
192
|
+
for (const k of ['session_id', 'poll_secret', 'nonce', 'dpop_htu', 'platform_audience']) {
|
|
193
|
+
if (typeof data[k] !== 'string' || !data[k]) {
|
|
194
|
+
throw new Error(`createOauthSession: reply lacks ${k}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
// A wallet session's reply would carry a QR. Getting one back means the agent ignored
|
|
198
|
+
// `kind` - an older build - and the client would otherwise wait forever for a wallet that
|
|
199
|
+
// is never coming.
|
|
200
|
+
if (data.qr_payload !== undefined) {
|
|
201
|
+
throw new Error('createOauthSession: the agent returned a wallet session (qr_payload present) — it ' +
|
|
202
|
+
'predates and does not support the oauth session kind');
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
sessionId: data.session_id,
|
|
206
|
+
pollSecret: data.poll_secret,
|
|
207
|
+
nonce: data.nonce,
|
|
208
|
+
dpopHtu: data.dpop_htu,
|
|
209
|
+
platformAudience: data.platform_audience,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Submit a DPoP-bound access token and proof to an OAuth session. The signer must use the key bound to that token. Retry once when the server responds with a DPoP nonce challenge.
|
|
214
|
+
*
|
|
215
|
+
* Speaks the RFC 9449 §9 resource-server contract — token in `Authorization: DPoP`, proof in
|
|
216
|
+
* `DPoP:` — so a conformant client library needs no custom code. It also handles the
|
|
217
|
+
* `use_dpop_nonce` challenge ITSELF: on a `401` carrying `DPoP-Nonce`, it re-mints the proof
|
|
218
|
+
* with the server's nonce and resends ONCE. One retry, not a loop: a server that keeps
|
|
219
|
+
* challenging is broken, and retrying forever would hide that.
|
|
220
|
+
*
|
|
221
|
+
* `signer` must be the key the token is bound to — see `../auth/dpop.js` for the two shapes.
|
|
222
|
+
*
|
|
223
|
+
* Note: the proof is signed over `dpopHtu` — the agent's PUBLIC origin plus this session's route,
|
|
224
|
+
* as {@link createOauthSession} returned it — and posted to `verifierAgentUrl`. When the two
|
|
225
|
+
* name the same host (the normal case) they are the same URL. When a client reaches the
|
|
226
|
+
* agent through a different base URL, the proof must still name the public one: that is
|
|
227
|
+
* the origin the verifiers approved.
|
|
228
|
+
*
|
|
229
|
+
* Throws `VerifierAgentSessionError`: `refused` when the agent reports the session failed
|
|
230
|
+
* (the committee refused, or could not be reached — `message` says which; not retryable on
|
|
231
|
+
* this session), `unavailable` for other 502/503/504, `protocol` for any other non-2xx.
|
|
232
|
+
*
|
|
233
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL.
|
|
234
|
+
* @param args - Session credentials, DPoP-bound access token, nonce, `dpopHtu` and matching signer.
|
|
235
|
+
*/
|
|
236
|
+
export async function submitOauthResponse(verifierAgentUrl, args) {
|
|
237
|
+
const base = verifierAgentUrl.replace(/\/$/, '');
|
|
238
|
+
const url = `${base}/v1/sessions/${encodeURIComponent(args.sessionId)}/oauth-response`;
|
|
239
|
+
const send = async (nonce) => {
|
|
240
|
+
const proof = await args.signer.proof({
|
|
241
|
+
htm: 'POST',
|
|
242
|
+
htu: args.dpopHtu,
|
|
243
|
+
nonce,
|
|
244
|
+
accessToken: args.accessToken,
|
|
245
|
+
});
|
|
246
|
+
return fetch(url, {
|
|
247
|
+
method: 'POST',
|
|
248
|
+
headers: {
|
|
249
|
+
Authorization: `DPoP ${args.accessToken}`,
|
|
250
|
+
DPoP: proof,
|
|
251
|
+
'X-Poll-Secret': args.pollSecret,
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
};
|
|
255
|
+
let resp = await send(args.nonce);
|
|
256
|
+
if (resp.status === 401) {
|
|
257
|
+
const challenge = resp.headers.get('dpop-nonce');
|
|
258
|
+
const wantsNonce = (resp.headers.get('www-authenticate') ?? '').includes('use_dpop_nonce');
|
|
259
|
+
if (challenge && wantsNonce) {
|
|
260
|
+
resp = await send(challenge);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (!resp.ok) {
|
|
264
|
+
const body = await resp.text();
|
|
265
|
+
// The agent answers a delivery that FAILED the session with `{status: "failed", error}`
|
|
266
|
+
// — a committee refusal (403), an unreachable quorum (503) or disagreeing verifiers
|
|
267
|
+
// (502). The session is over either way, so this is `refused` (not retryable) whatever
|
|
268
|
+
// the status: re-sending to the same session cannot succeed, a new session might.
|
|
269
|
+
let failed;
|
|
270
|
+
try {
|
|
271
|
+
failed = JSON.parse(body);
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
failed = undefined;
|
|
275
|
+
}
|
|
276
|
+
if (failed?.status === 'failed' && typeof failed.error === 'string') {
|
|
277
|
+
throw new VerifierAgentSessionError('refused', args.sessionId, `submitOauthResponse: session failed (HTTP ${resp.status}): ${failed.error.slice(0, 500)}`, resp.status);
|
|
278
|
+
}
|
|
279
|
+
const kind = resp.status === 502 || resp.status === 503 || resp.status === 504 ? 'unavailable' : 'protocol';
|
|
280
|
+
throw new VerifierAgentSessionError(kind, args.sessionId, `submitOauthResponse: HTTP ${resp.status}${body ? `: ${body.slice(0, 300)}` : ''}`, resp.status);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Fetch and validate one authorization session status. Transport failures and HTTP 502, 503 or 504 produce an unavailable error; malformed or other failed replies produce a protocol error. The polling secret is sent in the Authorization header.
|
|
285
|
+
*
|
|
286
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL.
|
|
287
|
+
* @param sessionId - Opened session identifier.
|
|
288
|
+
* @param pollSecret - Secret returned at session creation; do not expose it in logs.
|
|
289
|
+
*/
|
|
290
|
+
export async function pollOid4vpSession(verifierAgentUrl, sessionId, pollSecret) {
|
|
291
|
+
const url = `${verifierAgentUrl.replace(/\/$/, '')}/v1/sessions/${encodeURIComponent(sessionId)}`;
|
|
292
|
+
let resp;
|
|
293
|
+
try {
|
|
294
|
+
resp = await fetch(url, { headers: { 'Authorization': `Bearer ${pollSecret}` } });
|
|
295
|
+
}
|
|
296
|
+
catch (e) {
|
|
297
|
+
throw new VerifierAgentSessionError('unavailable', sessionId, `poll: ${e instanceof Error ? e.message : String(e)}`);
|
|
298
|
+
}
|
|
299
|
+
if (!resp.ok) {
|
|
300
|
+
const body = (await resp.text()).slice(0, 300);
|
|
301
|
+
const kind = resp.status === 502 || resp.status === 503 || resp.status === 504 ? 'unavailable' : 'protocol';
|
|
302
|
+
throw new VerifierAgentSessionError(kind, sessionId, `poll: HTTP ${resp.status}${body ? `: ${body}` : ''}`, resp.status);
|
|
303
|
+
}
|
|
304
|
+
let data;
|
|
305
|
+
try {
|
|
306
|
+
data = (await resp.json());
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
throw new VerifierAgentSessionError('protocol', sessionId, 'poll: reply is not JSON');
|
|
310
|
+
}
|
|
311
|
+
return parseVerifierAgentSessionStatus(data, sessionId);
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Shared validation for the explicit-URL and registered-agent transports.
|
|
315
|
+
*
|
|
316
|
+
* @param data - Untrusted JSON session response.
|
|
317
|
+
* @param sessionId - Session identifier used to correlate validation errors.
|
|
318
|
+
*/
|
|
319
|
+
export function parseVerifierAgentSessionStatus(data, sessionId) {
|
|
320
|
+
if (typeof data.status !== 'string' || !STATUSES.has(data.status))
|
|
321
|
+
throw new VerifierAgentSessionError('protocol', sessionId, `poll: status ${JSON.stringify(data.status)} is not pending | done | failed`);
|
|
322
|
+
const status = data.status;
|
|
323
|
+
const phase = typeof data.phase === 'string' && PHASES.has(data.phase)
|
|
324
|
+
? data.phase
|
|
325
|
+
: status === 'pending' ? 'awaiting_wallet' : status;
|
|
326
|
+
if ((status === 'done') !== (phase === 'done') || (status === 'failed') !== (phase === 'failed'))
|
|
327
|
+
throw new VerifierAgentSessionError('protocol', sessionId, `poll: phase ${phase} contradicts status ${status}`);
|
|
328
|
+
if (status === 'done')
|
|
329
|
+
data.compound_token = assertCompoundTokenWire(data.compound_token, sessionId);
|
|
330
|
+
// Absent optional fields arrive as JSON `null` from the verifier-agent (serde `Option`): null = absent.
|
|
331
|
+
if (data.error != null && typeof data.error !== 'string')
|
|
332
|
+
throw new VerifierAgentSessionError('protocol', sessionId, 'poll: error is not a string');
|
|
333
|
+
if (data.evidence_ct != null && (typeof data.evidence_ct !== 'string' || !/^[A-Za-z0-9_-]+$/.test(data.evidence_ct)))
|
|
334
|
+
throw new VerifierAgentSessionError('protocol', sessionId, 'poll: evidence_ct is not base64url');
|
|
335
|
+
return {
|
|
336
|
+
status,
|
|
337
|
+
phase,
|
|
338
|
+
compoundToken: (data.compound_token ?? undefined),
|
|
339
|
+
verifierProofs: data.verifier_proofs ?? undefined,
|
|
340
|
+
bindingPreimage: (data.binding_preimage ?? undefined),
|
|
341
|
+
error: (data.error ?? undefined),
|
|
342
|
+
...(typeof data.evidence_ct === 'string' ? { evidenceCt: data.evidence_ct } : {}),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* The next polling delay: geometric growth (times1.5) capped at `max`, plus or minus20 % full jitter.
|
|
347
|
+
* Pure, so the schedule is testable without timers.
|
|
348
|
+
*
|
|
349
|
+
* @param previousMs - Previous polling delay in milliseconds, or zero before the first poll.
|
|
350
|
+
* @param baseMs - Initial polling interval in milliseconds.
|
|
351
|
+
* @param maxMs - Maximum interval before jitter is applied.
|
|
352
|
+
* @param random - Random source returning a value between zero and one.
|
|
353
|
+
*/
|
|
354
|
+
export function nextPollDelay(previousMs, baseMs, maxMs, random = Math.random) {
|
|
355
|
+
const grown = previousMs <= 0 ? baseMs : Math.min(maxMs, previousMs * 1.5);
|
|
356
|
+
const jitter = (random() * 2 - 1) * 0.2 * grown;
|
|
357
|
+
return Math.max(1, Math.round(grown + jitter));
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Poll until the session reaches a terminal state (done or failed) - bounded by
|
|
361
|
+
* `timeoutMs`, with a growing jittered interval so many clients never poll in lock-step.
|
|
362
|
+
* A transient `unavailable` answer (a 503, a dropped connection) is retried within the
|
|
363
|
+
* deadline; a `protocol` answer stops at once; the deadline is a `timeout` error; the
|
|
364
|
+
* caller's `signal` is a `cancelled` error. A terminal `failed` is RETURNED (the caller
|
|
365
|
+
* decides how to explain it) - see `awaitVerifierAgentResult` for the version that throws `refused`.
|
|
366
|
+
*
|
|
367
|
+
* @param pollSecret - bearer token returned by `createOid4vpSession`
|
|
368
|
+
* @param intervalMs - initial polling interval in milliseconds (default 2000)
|
|
369
|
+
* @param timeoutMs - total deadline in milliseconds (default 300000 = 5 min)
|
|
370
|
+
*
|
|
371
|
+
* @param verifierAgentUrl - Verifier-agent HTTP base URL.
|
|
372
|
+
* @param sessionId - Opened session identifier.
|
|
373
|
+
* @param opts - Cancellation, phase callback and polling backoff controls.
|
|
374
|
+
*/
|
|
375
|
+
export async function waitForSession(verifierAgentUrl, sessionId, pollSecret, intervalMs = 2000, timeoutMs = 300_000, opts = {}) {
|
|
376
|
+
const deadline = Date.now() + timeoutMs;
|
|
377
|
+
const max = opts.maxIntervalMs ?? intervalMs * 4;
|
|
378
|
+
let delay = 0;
|
|
379
|
+
let lastUnavailable;
|
|
380
|
+
while (true) {
|
|
381
|
+
if (opts.signal?.aborted)
|
|
382
|
+
throw new VerifierAgentSessionError('cancelled', sessionId, 'polling cancelled');
|
|
383
|
+
if (Date.now() >= deadline) {
|
|
384
|
+
throw new VerifierAgentSessionError('timeout', sessionId, lastUnavailable ? `no answer within ${timeoutMs} ms (last: ${lastUnavailable.message})` : `still pending after ${timeoutMs} ms`);
|
|
385
|
+
}
|
|
386
|
+
try {
|
|
387
|
+
const result = await pollOid4vpSession(verifierAgentUrl, sessionId, pollSecret);
|
|
388
|
+
opts.onPhase?.(result.phase);
|
|
389
|
+
if (result.status !== 'pending')
|
|
390
|
+
return result;
|
|
391
|
+
lastUnavailable = undefined;
|
|
392
|
+
}
|
|
393
|
+
catch (e) {
|
|
394
|
+
if (e instanceof VerifierAgentSessionError && e.kind === 'unavailable') {
|
|
395
|
+
lastUnavailable = e;
|
|
396
|
+
}
|
|
397
|
+
else {
|
|
398
|
+
throw e;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
delay = nextPollDelay(delay, intervalMs, max, opts.random);
|
|
402
|
+
const remaining = deadline - Date.now();
|
|
403
|
+
if (remaining <= 0)
|
|
404
|
+
continue;
|
|
405
|
+
await new Promise((resolve) => {
|
|
406
|
+
const t = setTimeout(() => { opts.signal?.removeEventListener('abort', onAbort); resolve(); }, Math.min(delay, remaining));
|
|
407
|
+
const onAbort = () => { clearTimeout(t); resolve(); };
|
|
408
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
}
|