@t3foundry/tasra-sdk 0.3.1-next.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/CHANGELOG.md +1067 -28
  2. package/README.md +15 -0
  3. package/dist/app/approvals.d.ts +66 -4
  4. package/dist/app/approvals.js +153 -16
  5. package/dist/app/authorization.d.ts +1 -1
  6. package/dist/app/authorization.js +1 -1
  7. package/dist/app/browser.d.ts +63 -0
  8. package/dist/app/browser.js +242 -0
  9. package/dist/app/client.d.ts +114 -13
  10. package/dist/app/client.js +302 -76
  11. package/dist/app/identity.js +21 -9
  12. package/dist/app/index.d.ts +28 -3
  13. package/dist/app/index.js +16 -1
  14. package/dist/app/memory-store.d.ts +7 -0
  15. package/dist/app/memory-store.js +55 -0
  16. package/dist/app/node.d.ts +34 -6
  17. package/dist/app/node.js +387 -64
  18. package/dist/app/paid-allowance.d.ts +325 -0
  19. package/dist/app/paid-allowance.js +1290 -0
  20. package/dist/app/paid-approval.d.ts +122 -0
  21. package/dist/app/paid-approval.js +379 -0
  22. package/dist/app/paid-journal.d.ts +51 -0
  23. package/dist/app/paid-journal.js +117 -0
  24. package/dist/app/paid-keys.d.ts +12 -0
  25. package/dist/app/paid-keys.js +20 -0
  26. package/dist/app/paid-operation.d.ts +821 -0
  27. package/dist/app/paid-operation.js +1720 -0
  28. package/dist/app/paid-reservation.d.ts +157 -0
  29. package/dist/app/paid-reservation.js +323 -0
  30. package/dist/app/paid-session.d.ts +147 -0
  31. package/dist/app/paid-session.js +578 -0
  32. package/dist/app/payer-queue.d.ts +11 -0
  33. package/dist/app/payer-queue.js +27 -0
  34. package/dist/app/policy-bootstrap.d.ts +342 -0
  35. package/dist/app/policy-bootstrap.js +365 -0
  36. package/dist/app/policy-operation.d.ts +47 -0
  37. package/dist/app/policy-operation.js +101 -0
  38. package/dist/app/ready-slot.d.ts +12 -0
  39. package/dist/app/ready-slot.js +5 -2
  40. package/dist/app/rotation-lock.d.ts +38 -0
  41. package/dist/app/rotation-lock.js +42 -0
  42. package/dist/app/session-decrypt.d.ts +135 -0
  43. package/dist/app/session-decrypt.js +335 -0
  44. package/dist/app/session-grants.d.ts +349 -0
  45. package/dist/app/session-grants.js +811 -0
  46. package/dist/app/signing-intents.d.ts +78 -0
  47. package/dist/app/signing-intents.js +95 -0
  48. package/dist/app/store-commit.d.ts +63 -0
  49. package/dist/app/store-commit.js +126 -0
  50. package/dist/app/store-errors.d.ts +8 -0
  51. package/dist/app/store-errors.js +11 -0
  52. package/dist/app/tasra-client.d.ts +2 -0
  53. package/dist/app/tasra-client.js +1 -1
  54. package/dist/app/wallet.js +4 -1
  55. package/dist/auth/holderProof.d.ts +3 -0
  56. package/dist/auth/holderProof.js +8 -7
  57. package/dist/auth/verifier.d.ts +4 -2
  58. package/dist/auth/verifier.js +5 -2
  59. package/dist/chain/abis/index.d.ts +6178 -4101
  60. package/dist/chain/abis/index.js +3 -0
  61. package/dist/chain/abis/keyRegistry.d.ts +256 -0
  62. package/dist/chain/abis/keyRegistry.js +333 -0
  63. package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
  64. package/dist/chain/abis/prepaidFaultOracle.js +413 -0
  65. package/dist/chain/abis/settlement.d.ts +2203 -703
  66. package/dist/chain/abis/settlement.js +2685 -764
  67. package/dist/chain/allowance.d.ts +358 -0
  68. package/dist/chain/allowance.js +800 -0
  69. package/dist/chain/billing.d.ts +85 -0
  70. package/dist/chain/billing.js +197 -0
  71. package/dist/chain/chainId.d.ts +13 -0
  72. package/dist/chain/chainId.js +26 -0
  73. package/dist/chain/client.d.ts +15 -1
  74. package/dist/chain/client.js +57 -1
  75. package/dist/chain/commitmentRecovery.d.ts +51 -0
  76. package/dist/chain/commitmentRecovery.js +38 -0
  77. package/dist/chain/committeeClient.d.ts +17 -10
  78. package/dist/chain/committeeClient.js +64 -16
  79. package/dist/chain/committeeDraw.d.ts +12 -0
  80. package/dist/chain/committeeDraw.js +56 -0
  81. package/dist/chain/custodyHealth.d.ts +212 -0
  82. package/dist/chain/custodyHealth.js +365 -0
  83. package/dist/chain/deployments.js +2 -0
  84. package/dist/chain/events.js +2 -0
  85. package/dist/chain/headFollower.d.ts +77 -0
  86. package/dist/chain/headFollower.js +219 -0
  87. package/dist/chain/headPrefetch.d.ts +23 -0
  88. package/dist/chain/headPrefetch.js +67 -0
  89. package/dist/chain/index.d.ts +50 -8
  90. package/dist/chain/index.js +28 -3
  91. package/dist/chain/keeperExecution.d.ts +44 -0
  92. package/dist/chain/keeperExecution.js +127 -0
  93. package/dist/chain/keeperRecovery.d.ts +78 -0
  94. package/dist/chain/keeperRecovery.js +91 -0
  95. package/dist/chain/node.d.ts +24 -1
  96. package/dist/chain/node.js +88 -43
  97. package/dist/chain/offchain.d.ts +2 -0
  98. package/dist/chain/paidAgentTransport.d.ts +38 -0
  99. package/dist/chain/paidAgentTransport.js +1 -0
  100. package/dist/chain/paidEpoch.d.ts +66 -0
  101. package/dist/chain/paidEpoch.js +139 -0
  102. package/dist/chain/paidPacing.d.ts +81 -0
  103. package/dist/chain/paidPacing.js +136 -0
  104. package/dist/chain/pinnedReads.d.ts +49 -0
  105. package/dist/chain/pinnedReads.js +218 -0
  106. package/dist/chain/prepaid.d.ts +383 -0
  107. package/dist/chain/prepaid.js +1046 -0
  108. package/dist/chain/prepaidEscape.d.ts +274 -0
  109. package/dist/chain/prepaidEscape.js +432 -0
  110. package/dist/chain/prepaidFault.d.ts +94 -0
  111. package/dist/chain/prepaidFault.js +148 -0
  112. package/dist/chain/receipt.d.ts +24 -0
  113. package/dist/chain/receipt.js +82 -0
  114. package/dist/chain/registeredAgent.d.ts +68 -3
  115. package/dist/chain/registeredAgent.js +143 -42
  116. package/dist/chain/registeredOperation.d.ts +10 -1
  117. package/dist/chain/registeredOperation.js +18 -3
  118. package/dist/chain/registeredPaidAgent.d.ts +254 -0
  119. package/dist/chain/registeredPaidAgent.js +889 -0
  120. package/dist/chain/registeredRelay.d.ts +31 -1
  121. package/dist/chain/registeredRelay.js +164 -43
  122. package/dist/chain/relayVoucher.d.ts +64 -0
  123. package/dist/chain/relayVoucher.js +69 -0
  124. package/dist/chain/reservation.d.ts +239 -0
  125. package/dist/chain/reservation.js +746 -0
  126. package/dist/chain/reshareRoster.d.ts +64 -0
  127. package/dist/chain/reshareRoster.js +85 -0
  128. package/dist/chain/revertReason.d.ts +8 -0
  129. package/dist/chain/revertReason.js +2 -1
  130. package/dist/chain/rotationLock.d.ts +130 -0
  131. package/dist/chain/rotationLock.js +168 -0
  132. package/dist/chain/serviceRequestPolicy.d.ts +47 -0
  133. package/dist/chain/serviceRequestPolicy.js +86 -0
  134. package/dist/chain/services.d.ts +7 -0
  135. package/dist/chain/services.js +44 -4
  136. package/dist/chain/slotClient.js +11 -2
  137. package/dist/chain/slotHandoff.d.ts +81 -0
  138. package/dist/chain/slotHandoff.js +166 -0
  139. package/dist/chain/slotSeed.d.ts +47 -5
  140. package/dist/chain/slotSeed.js +173 -42
  141. package/dist/chain/verifierSnapshot.d.ts +36 -0
  142. package/dist/chain/verifierSnapshot.js +197 -0
  143. package/dist/chain/write.d.ts +111 -21
  144. package/dist/chain/write.js +378 -146
  145. package/dist/committee/blsSharing.d.ts +53 -0
  146. package/dist/committee/blsSharing.js +90 -0
  147. package/dist/committee/client.d.ts +62 -23
  148. package/dist/committee/client.js +288 -72
  149. package/dist/committee/dual-operation.d.ts +165 -0
  150. package/dist/committee/dual-operation.js +229 -0
  151. package/dist/committee/dual-sign.d.ts +26 -1
  152. package/dist/committee/dual-sign.js +85 -7
  153. package/dist/committee/ecdsa.d.ts +38 -0
  154. package/dist/committee/ecdsa.js +87 -15
  155. package/dist/committee/evidence.d.ts +30 -0
  156. package/dist/committee/evidence.js +65 -0
  157. package/dist/committee/execution.d.ts +414 -0
  158. package/dist/committee/execution.js +446 -0
  159. package/dist/committee/extraction.js +33 -26
  160. package/dist/committee/index.d.ts +30 -7
  161. package/dist/committee/index.js +18 -6
  162. package/dist/committee/keeperExecution.d.ts +37 -0
  163. package/dist/committee/keeperExecution.js +141 -0
  164. package/dist/committee/oauth.d.ts +14 -4
  165. package/dist/committee/oauth.js +17 -5
  166. package/dist/committee/payment.d.ts +369 -0
  167. package/dist/committee/payment.js +339 -0
  168. package/dist/committee/recovery.d.ts +136 -0
  169. package/dist/committee/recovery.js +204 -0
  170. package/dist/committee/recoveryJson.d.ts +2 -0
  171. package/dist/committee/recoveryJson.js +87 -0
  172. package/dist/committee/request.d.ts +63 -27
  173. package/dist/committee/request.js +77 -66
  174. package/dist/committee/session-grant.d.ts +320 -0
  175. package/dist/committee/session-grant.js +397 -0
  176. package/dist/committee/status-refresh.d.ts +257 -0
  177. package/dist/committee/status-refresh.js +619 -0
  178. package/dist/committee/token.d.ts +163 -15
  179. package/dist/committee/token.js +247 -10
  180. package/dist/crypto/bn254.d.ts +70 -0
  181. package/dist/crypto/bn254.js +222 -0
  182. package/dist/crypto/ibe.d.ts +32 -0
  183. package/dist/crypto/ibe.js +56 -8
  184. package/dist/crypto/index.d.ts +1 -1
  185. package/dist/crypto/index.js +1 -1
  186. package/dist/crypto/kem.d.ts +31 -0
  187. package/dist/crypto/kem.js +113 -7
  188. package/dist/crypto/recipient.d.ts +75 -0
  189. package/dist/crypto/recipient.js +107 -0
  190. package/dist/decryption/client.d.ts +10 -16
  191. package/dist/decryption/client.js +8 -76
  192. package/dist/decryption/index.d.ts +2 -0
  193. package/dist/decryption/index.js +2 -0
  194. package/dist/decryption/sealed.d.ts +72 -0
  195. package/dist/decryption/sealed.js +147 -0
  196. package/dist/decryption/session.d.ts +115 -0
  197. package/dist/decryption/session.js +358 -0
  198. package/dist/errors.d.ts +406 -1
  199. package/dist/errors.js +400 -5
  200. package/dist/index.d.ts +9 -2
  201. package/dist/index.js +6 -1
  202. package/dist/internal/bounded.d.ts +66 -0
  203. package/dist/internal/bounded.js +126 -0
  204. package/dist/internal/network.d.ts +4 -0
  205. package/dist/internal/network.js +40 -0
  206. package/dist/internal/retryAfter.d.ts +8 -0
  207. package/dist/internal/retryAfter.js +28 -0
  208. package/dist/internal/sleep.d.ts +6 -0
  209. package/dist/internal/sleep.js +15 -0
  210. package/dist/internal/typedData.d.ts +13 -0
  211. package/dist/internal/typedData.js +77 -0
  212. package/dist/internal/viemErrors.d.ts +26 -0
  213. package/dist/internal/viemErrors.js +49 -0
  214. package/dist/oid4vp/binding.d.ts +27 -1
  215. package/dist/oid4vp/binding.js +36 -1
  216. package/dist/oid4vp/jose.d.ts +4 -2
  217. package/dist/oid4vp/jose.js +39 -7
  218. package/dist/oid4vp/request-object.d.ts +61 -4
  219. package/dist/oid4vp/request-object.js +140 -5
  220. package/dist/oid4vp/verifier-agent.d.ts +18 -8
  221. package/dist/oid4vp/verifier-agent.js +48 -6
  222. package/dist/oid4vp/wallet.d.ts +2 -4
  223. package/dist/oid4vp/wallet.js +1 -0
  224. package/dist/retry.d.ts +78 -0
  225. package/dist/retry.js +137 -0
  226. package/dist/signing/frost.d.ts +1 -1
  227. package/dist/verifier-agent/index.d.ts +41 -5
  228. package/dist/verifier-agent/index.js +124 -9
  229. package/dist/verifier-agent/payment.d.ts +7 -0
  230. package/dist/verifier-agent/payment.js +17 -0
  231. package/docs/api.md +8 -2
  232. package/docs/application-api.md +25 -2
  233. package/docs/chain.md +155 -9
  234. package/docs/consumer-migrations.md +61 -0
  235. package/docs/encrypted-notes.md +3 -2
  236. package/docs/encryption.md +4 -2
  237. package/docs/errors.md +14 -1
  238. package/docs/flows.md +2 -2
  239. package/docs/funding.md +902 -0
  240. package/docs/native-approvals.md +63 -0
  241. package/docs/reference/README.md +9 -8
  242. package/docs/reference/app-browser.md +232 -0
  243. package/docs/reference/app-node.md +38 -8
  244. package/docs/reference/app.md +4621 -805
  245. package/docs/reference/chain-node.md +74 -16
  246. package/docs/reference/chain.md +6740 -1592
  247. package/docs/reference/committee.md +5630 -987
  248. package/docs/reference/main.md +1439 -140
  249. package/docs/reference/oid4vp.md +297 -144
  250. package/docs/reference/verifier-agent.md +77 -35
  251. package/docs/signing.md +6 -0
  252. package/examples/encrypted-notes.ts +21 -6
  253. package/examples/getting-started.ts +2 -7
  254. package/examples/live-config.ts +24 -17
  255. package/package.json +17 -5
@@ -0,0 +1,365 @@
1
+ // Customer authorization bootstrap: a holder application runs paid operations on a slot whose rule
2
+ // salt it never holds.
3
+ //
4
+ // The slot's creator (the party that holds the rule and its salt) signs a short-lived EIP-712
5
+ // statement that binds the exact raw rule (by keccak256, the hash verifier tokens carry) to the
6
+ // slot's on-chain salted commitment and rule version, on one chain and KeyRegistry, for one holder
7
+ // application and a bounded set of actions. The holder receives that statement and the raw rule,
8
+ // never the salt. Before anything is signed or spent, paidOperation checks the statement's
9
+ // signature against the slot creator it reads on chain, and its commitment and rule version
10
+ // against the same canonical slot read; afterwards the verifier quorum's token binds the same rule
11
+ // hash. A monotonic per-slot sequence refuses an older statement once a newer one was accepted.
12
+ //
13
+ // paidPolicyOperation adds an application-chosen operation key: the operation is bound to that key
14
+ // in the durable store before any reservation, and calling it again with the same key resumes the
15
+ // original journal entry instead of starting a second operation.
16
+ import { concat, hashTypedData, isAddress, keccak256, recoverTypedDataAddress, toHex } from 'viem';
17
+ import { keyRegistryAbi } from '../chain/abis/keyRegistry.js';
18
+ import { requireAddress } from '../chain/deployments.js';
19
+ import { ruleCommitment } from '../chain/write.js';
20
+ import { canonicalize, MAX_RULE_LEN } from '../auth/oid4vp.js';
21
+ import { presentationOperationTypedData } from '../oid4vp/verifier-agent.js';
22
+ import { TasraError } from '../errors.js';
23
+ import { storeIdentity } from './store-commit.js';
24
+ /** EIP-712 domain name of a slot policy statement (version `1`, the KeyRegistry as verifying contract). */
25
+ export const SLOT_POLICY_DOMAIN_NAME = 'Tasra Slot Policy';
26
+ /** EIP-712 domain name of a holder application's policy retrieval request. */
27
+ export const SLOT_POLICY_REQUEST_DOMAIN_NAME = 'Tasra Slot Policy Request';
28
+ /** Longest lifetime of one slot policy statement, in seconds (one day). */
29
+ export const SLOT_POLICY_MAX_LIFETIME_SECS = 86_400;
30
+ /** Longest age of a policy retrieval request, in seconds. */
31
+ export const SLOT_POLICY_REQUEST_MAX_AGE_SECS = 120;
32
+ const SKEW_SECS = 60;
33
+ const HEX32 = /^0x[0-9a-fA-F]{64}$/;
34
+ const SIGNATURE = /^0x[0-9a-fA-F]{130}$/;
35
+ const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
36
+ const ACTION_BITS = { 'sign': 1, 'decrypt': 2, 'ibe-extract': 4, 'dual-approve': 8 };
37
+ const ACTIONS = Object.keys(ACTION_BITS);
38
+ const POLICY_TYPES = {
39
+ SlotPolicy: [
40
+ { name: 'slotId', type: 'bytes32' },
41
+ { name: 'ruleVersion', type: 'uint64' },
42
+ { name: 'ruleCommitment', type: 'bytes32' },
43
+ { name: 'ruleHash', type: 'bytes32' },
44
+ { name: 'audience', type: 'address' },
45
+ { name: 'actions', type: 'uint8' },
46
+ { name: 'sequence', type: 'uint64' },
47
+ { name: 'issuedAt', type: 'uint64' },
48
+ { name: 'expiresAt', type: 'uint64' },
49
+ { name: 'bootstrapId', type: 'bytes32' },
50
+ ],
51
+ };
52
+ const REQUEST_TYPES = {
53
+ SlotPolicyRequest: [
54
+ { name: 'slotId', type: 'bytes32' },
55
+ { name: 'audience', type: 'address' },
56
+ { name: 'nonce', type: 'bytes32' },
57
+ { name: 'issuedAt', type: 'uint64' },
58
+ ],
59
+ };
60
+ /** A slot policy statement or retrieval request refused before anything was signed or spent. */
61
+ export class SlotPolicyError extends TasraError {
62
+ /** Refusal category; never infer it from the message. */
63
+ code;
64
+ constructor(code, message, opts = {}) {
65
+ super(message, { cause: opts.cause });
66
+ this.code = code;
67
+ }
68
+ }
69
+ const lower = (value) => value.toLowerCase();
70
+ const same = (a, b) => lower(a) === lower(b);
71
+ const now = () => Math.floor(Date.now() / 1000);
72
+ const uint = (value, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && value >= 0 && value <= max;
73
+ const address = (value) => typeof value === 'string' && isAddress(value, { strict: false }) && !same(value, ZERO_ADDRESS);
74
+ const hex32 = (value) => typeof value === 'string' && HEX32.test(value);
75
+ const random32 = () => { const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32)); const value = toHex(bytes); bytes.fill(0); return value; };
76
+ function onlyKeys(value, allowed, what) {
77
+ for (const key of Object.keys(value))
78
+ if (!allowed.includes(key))
79
+ throw new SlotPolicyError('malformed', `${what} has an unknown field ${key}`);
80
+ }
81
+ function actionBits(actions) {
82
+ if (!Array.isArray(actions) || actions.length === 0 || actions.length > ACTIONS.length || new Set(actions).size !== actions.length) {
83
+ throw new SlotPolicyError('malformed', 'Policy actions must be a non-empty list of distinct committee actions');
84
+ }
85
+ let bits = 0;
86
+ for (const action of actions) {
87
+ if (!ACTIONS.includes(action))
88
+ throw new SlotPolicyError('malformed', `Unknown committee action ${String(action)}`);
89
+ bits |= ACTION_BITS[action];
90
+ }
91
+ return bits;
92
+ }
93
+ /** Validate an untrusted statement's shape and bounds; returns a normalized copy. */
94
+ function statementShape(value) {
95
+ if (!value || typeof value !== 'object' || Array.isArray(value))
96
+ throw new SlotPolicyError('malformed', 'Policy statement must be an object');
97
+ const s = value;
98
+ onlyKeys(s, ['chainId', 'keyRegistry', 'slot', 'ruleVersion', 'ruleCommitment', 'ruleHash', 'audience', 'actions', 'sequence', 'issuedAt', 'expiresAt', 'bootstrapId'], 'Policy statement');
99
+ if (!uint(s.chainId) || s.chainId === 0 || !address(s.keyRegistry) || !hex32(s.slot) || !uint(s.ruleVersion) || !hex32(s.ruleCommitment) || !hex32(s.ruleHash)
100
+ || !address(s.audience) || !uint(s.sequence) || !uint(s.issuedAt) || !uint(s.expiresAt) || !hex32(s.bootstrapId) || !Array.isArray(s.actions)) {
101
+ throw new SlotPolicyError('malformed', 'Policy statement has a missing or invalid field');
102
+ }
103
+ actionBits(s.actions);
104
+ return { chainId: s.chainId, keyRegistry: s.keyRegistry, slot: lower(s.slot), ruleVersion: s.ruleVersion, ruleCommitment: lower(s.ruleCommitment),
105
+ ruleHash: lower(s.ruleHash), audience: s.audience, actions: [...s.actions], sequence: s.sequence, issuedAt: s.issuedAt,
106
+ expiresAt: s.expiresAt, bootstrapId: lower(s.bootstrapId) };
107
+ }
108
+ /** Validate an untrusted bootstrap's shape and bounds; returns a normalized copy. */
109
+ function bootstrapShape(value) {
110
+ if (!value || typeof value !== 'object' || Array.isArray(value))
111
+ throw new SlotPolicyError('malformed', 'Policy bootstrap must be an object');
112
+ const b = value;
113
+ onlyKeys(b, ['statement', 'rule', 'signature'], 'Policy bootstrap');
114
+ if (typeof b.rule !== 'string' || b.rule.length === 0 || new TextEncoder().encode(b.rule).length > MAX_RULE_LEN) {
115
+ throw new SlotPolicyError('malformed', `Policy rule must be 1..${MAX_RULE_LEN} bytes`);
116
+ }
117
+ if (typeof b.signature !== 'string' || !SIGNATURE.test(b.signature))
118
+ throw new SlotPolicyError('malformed', 'Policy signature must be 65 bytes');
119
+ return { statement: statementShape(b.statement), rule: b.rule, signature: b.signature };
120
+ }
121
+ /**
122
+ * The EIP-712 typed data a slot creator signs for a slot policy statement.
123
+ * @param statement Statement to sign or verify.
124
+ */
125
+ export function slotPolicyTypedData(statement) {
126
+ const s = statementShape(statement);
127
+ return { domain: { name: SLOT_POLICY_DOMAIN_NAME, version: '1', chainId: s.chainId, verifyingContract: s.keyRegistry }, types: POLICY_TYPES, primaryType: 'SlotPolicy',
128
+ message: { slotId: s.slot, ruleVersion: BigInt(s.ruleVersion), ruleCommitment: s.ruleCommitment, ruleHash: s.ruleHash, audience: s.audience,
129
+ actions: actionBits(s.actions), sequence: BigInt(s.sequence), issuedAt: BigInt(s.issuedAt), expiresAt: BigInt(s.expiresAt), bootstrapId: s.bootstrapId } };
130
+ }
131
+ /**
132
+ * The EIP-712 hash of a slot policy statement, the identity the holder's store records.
133
+ * @param statement Statement to hash.
134
+ */
135
+ export function slotPolicyHash(statement) {
136
+ return hashTypedData(slotPolicyTypedData(statement));
137
+ }
138
+ /**
139
+ * Check a slot policy bootstrap offline: shape and bounds, deployment, slot, holder application,
140
+ * action scope, lifetime, that the rule is the one the statement hashes, and the creator's
141
+ * signature. The on-chain half (current creator, commitment and rule version at one canonical
142
+ * block) is checked by paidOperation, which needs the chain anyway. Throws {@link SlotPolicyError}.
143
+ * @param bootstrap Untrusted bootstrap as received.
144
+ * @param expected Deployment, slot, holder application, action and signer to expect.
145
+ * @returns The normalized bootstrap and the address that signed it.
146
+ */
147
+ export async function verifySlotPolicyBootstrap(bootstrap, expected) {
148
+ const b = bootstrapShape(bootstrap), s = b.statement, at = expected.nowSecs ?? now();
149
+ if (s.chainId !== expected.chainId || !same(s.keyRegistry, expected.keyRegistry))
150
+ throw new SlotPolicyError('wrong-deployment', `Policy statement names chain ${s.chainId} registry ${s.keyRegistry}, not the approved deployment`);
151
+ if (!same(s.slot, expected.slot))
152
+ throw new SlotPolicyError('wrong-slot', `Policy statement describes slot ${s.slot}, not ${expected.slot}`);
153
+ if (!same(s.audience, expected.audience))
154
+ throw new SlotPolicyError('wrong-audience', `Policy statement was issued to ${s.audience}, not this application ${expected.audience}`);
155
+ if (expected.action !== undefined && !s.actions.includes(expected.action))
156
+ throw new SlotPolicyError('out-of-scope', `Policy statement does not allow ${expected.action}`);
157
+ if (s.expiresAt <= s.issuedAt || s.expiresAt - s.issuedAt > SLOT_POLICY_MAX_LIFETIME_SECS)
158
+ throw new SlotPolicyError('stale', `Policy statement lifetime must be 1..${SLOT_POLICY_MAX_LIFETIME_SECS} seconds`);
159
+ if (s.issuedAt > at + SKEW_SECS)
160
+ throw new SlotPolicyError('stale', 'Policy statement is not valid yet');
161
+ if (s.expiresAt <= at)
162
+ throw new SlotPolicyError('stale', 'Policy statement expired');
163
+ if (keccak256(toHex(b.rule)).toLowerCase() !== s.ruleHash)
164
+ throw new SlotPolicyError('substituted-rule', 'Supplied rule is not the rule the policy statement hashes');
165
+ let signer;
166
+ try {
167
+ signer = await recoverTypedDataAddress({ ...slotPolicyTypedData(s), signature: b.signature });
168
+ }
169
+ catch (cause) {
170
+ throw new SlotPolicyError('malformed', 'Policy signature does not recover', { cause });
171
+ }
172
+ if (expected.signer !== undefined && !same(signer, expected.signer))
173
+ throw new SlotPolicyError('wrong-signer', `Policy statement is signed by ${signer}, not the slot creator ${expected.signer}`);
174
+ return { bootstrap: b, signer };
175
+ }
176
+ /**
177
+ * Compare a verified statement with the slot read on chain at one canonical block; throws `changed-policy`.
178
+ * @param statement Verified statement.
179
+ * @param signer Address that signed it.
180
+ * @param observed Creator, commitment and rule version as read.
181
+ */
182
+ export function requireCurrentSlotPolicy(statement, signer, observed) {
183
+ if (!same(observed.creator, signer))
184
+ throw new SlotPolicyError('changed-policy', `Slot creator is ${observed.creator}; the policy statement is signed by ${signer}`);
185
+ if (!same(observed.ruleCommitment, statement.ruleCommitment))
186
+ throw new SlotPolicyError('changed-policy', 'Slot rule commitment differs from the policy statement');
187
+ if (observed.ruleVersion !== statement.ruleVersion)
188
+ throw new SlotPolicyError('changed-policy', `Slot rule version is ${observed.ruleVersion}; the policy statement names ${statement.ruleVersion}`);
189
+ }
190
+ /** Store key of the highest accepted statement per deployment, slot and holder application. */
191
+ function sequenceKey(s) {
192
+ return 'paid-policy-seq-' + keccak256(concat([toHex('tasra/slot-policy-sequence/v1'), toHex(BigInt(s.chainId), { size: 8 }), s.keyRegistry, s.slot, s.audience])).slice(2);
193
+ }
194
+ /**
195
+ * Accept a verified statement against the holder's durable high-water mark: a lower sequence than
196
+ * one already accepted is `replayed`, the same sequence with another statement `equivocated`.
197
+ * Records a higher one. Needs the private store the operation journals in.
198
+ */
199
+ export async function admitSlotPolicySequence(store, statement) {
200
+ const key = sequenceKey(statement), hash = slotPolicyHash(statement).toLowerCase();
201
+ await store.withLock(key, async () => {
202
+ const seen = await store.load(key);
203
+ if (seen !== undefined) {
204
+ if (!seen || seen.schema !== 1 || !uint(seen.sequence) || !hex32(seen.hash))
205
+ throw new TasraError('Invalid slot policy sequence record');
206
+ if (statement.sequence < seen.sequence)
207
+ throw new SlotPolicyError('replayed', `Policy statement sequence ${statement.sequence} is older than the accepted ${seen.sequence}`);
208
+ if (statement.sequence === seen.sequence) {
209
+ if (seen.hash !== hash)
210
+ throw new SlotPolicyError('equivocated', `Another policy statement with sequence ${statement.sequence} was already accepted`);
211
+ return;
212
+ }
213
+ }
214
+ await store.save(key, { schema: 1, sequence: statement.sequence, hash });
215
+ });
216
+ }
217
+ /**
218
+ * Issue a slot policy bootstrap as the slot creator. Reads the slot at the latest block and refuses
219
+ * (`not-issuable`) unless it is live, the signer is its creator and the rule and salt reproduce its
220
+ * commitment; then signs a statement that carries the rule hash, commitment and rule version but
221
+ * not the salt. Hand the result to the holder application named as `audience`.
222
+ * @param chain Reader for the deployment that owns the slot.
223
+ * @param input Creator signer, slot, rule, salt, holder application, scope, sequence and lifetime.
224
+ */
225
+ export async function issueSlotPolicyBootstrap(chain, input) {
226
+ const keyRegistry = requireAddress(chain.addresses, 'KeyRegistry');
227
+ if (!hex32(input.slot) || !hex32(input.salt))
228
+ throw new SlotPolicyError('malformed', 'Slot and salt must be 32 bytes');
229
+ if (!address(input.audience))
230
+ throw new SlotPolicyError('malformed', 'Audience must be a non-zero address');
231
+ if (!uint(input.sequence))
232
+ throw new SlotPolicyError('malformed', 'Sequence must be a non-negative safe integer');
233
+ const ttl = input.ttlSecs ?? 900;
234
+ if (!uint(ttl, SLOT_POLICY_MAX_LIFETIME_SECS) || ttl === 0)
235
+ throw new SlotPolicyError('malformed', `Policy lifetime must be 1..${SLOT_POLICY_MAX_LIFETIME_SECS} seconds`);
236
+ if (typeof input.rule !== 'string' || input.rule.length === 0 || new TextEncoder().encode(input.rule).length > MAX_RULE_LEN)
237
+ throw new SlotPolicyError('malformed', `Policy rule must be 1..${MAX_RULE_LEN} bytes`);
238
+ canonicalize(input.rule);
239
+ actionBits(input.actions);
240
+ const [chainId, slot] = await Promise.all([chain.client.getChainId(),
241
+ chain.client.readContract({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'getKeySlot', args: [input.slot] })]);
242
+ if (!slot.exists || slot.cancelled)
243
+ throw new SlotPolicyError('not-issuable', `Slot ${input.slot} is not live`);
244
+ if (!same(slot.creator, input.signer.address))
245
+ throw new SlotPolicyError('not-issuable', `Slot ${input.slot} has creator ${slot.creator}, not ${input.signer.address}`);
246
+ if (!same(slot.ruleCommitment, ruleCommitment(input.salt, input.rule)))
247
+ throw new SlotPolicyError('not-issuable', 'Rule and salt do not reproduce the slot commitment');
248
+ const issuedAt = input.nowSecs ?? now();
249
+ const statement = { chainId, keyRegistry, slot: lower(input.slot), ruleVersion: Number(slot.ruleVersion), ruleCommitment: lower(slot.ruleCommitment),
250
+ ruleHash: keccak256(toHex(input.rule)), audience: input.audience, actions: [...input.actions], sequence: input.sequence, issuedAt, expiresAt: issuedAt + ttl, bootstrapId: random32() };
251
+ const signature = await input.signer.signTypedData(slotPolicyTypedData(statement));
252
+ return { statement, rule: input.rule, signature };
253
+ }
254
+ /**
255
+ * The EIP-712 typed data a holder application signs to request a slot policy statement.
256
+ * @param request Request fields (signature excluded).
257
+ */
258
+ export function slotPolicyRequestTypedData(request) {
259
+ if (!uint(request.chainId) || request.chainId === 0 || !address(request.keyRegistry) || !hex32(request.slot) || !address(request.audience) || !hex32(request.nonce) || !uint(request.issuedAt)) {
260
+ throw new SlotPolicyError('malformed', 'Policy request has a missing or invalid field');
261
+ }
262
+ return { domain: { name: SLOT_POLICY_REQUEST_DOMAIN_NAME, version: '1', chainId: request.chainId, verifyingContract: request.keyRegistry }, types: REQUEST_TYPES,
263
+ primaryType: 'SlotPolicyRequest', message: { slotId: request.slot, audience: request.audience, nonce: request.nonce, issuedAt: BigInt(request.issuedAt) } };
264
+ }
265
+ /**
266
+ * Sign a request for a slot policy statement with the holder application's key. The key identifies
267
+ * the application to the issuer; it is neither a holder credential nor a control-plane key.
268
+ * @param signer Holder application key.
269
+ * @param request Chain, KeyRegistry and slot; nonce and time default to fresh values.
270
+ */
271
+ export async function createSlotPolicyRequest(signer, request) {
272
+ const fields = { chainId: request.chainId, keyRegistry: request.keyRegistry, slot: request.slot, audience: signer.address, nonce: request.nonce ?? random32(), issuedAt: request.nowSecs ?? now() };
273
+ return { ...fields, signature: await signer.signTypedData(slotPolicyRequestTypedData(fields)) };
274
+ }
275
+ /**
276
+ * Check a holder application's policy request on the issuer side: shape, deployment, age and that
277
+ * its `audience` signed it. The issuer then checks that the audience is an enrolled application
278
+ * for this slot and that the nonce is new. Throws {@link SlotPolicyError}.
279
+ * @param request Untrusted request as received.
280
+ * @param expected Deployment of the issuer, current time and accepted age.
281
+ * @returns The normalized request.
282
+ */
283
+ export async function verifySlotPolicyRequest(request, expected) {
284
+ if (!request || typeof request !== 'object' || Array.isArray(request))
285
+ throw new SlotPolicyError('malformed', 'Policy request must be an object');
286
+ onlyKeys(request, ['chainId', 'keyRegistry', 'slot', 'audience', 'nonce', 'issuedAt', 'signature'], 'Policy request');
287
+ if (typeof request.signature !== 'string' || !SIGNATURE.test(request.signature))
288
+ throw new SlotPolicyError('malformed', 'Policy request signature must be 65 bytes');
289
+ const { signature, ...fields } = request;
290
+ const typed = slotPolicyRequestTypedData(fields);
291
+ if (fields.chainId !== expected.chainId || !same(fields.keyRegistry, expected.keyRegistry))
292
+ throw new SlotPolicyError('wrong-deployment', 'Policy request names another deployment');
293
+ const at = expected.nowSecs ?? now(), maxAge = expected.maxAgeSecs ?? SLOT_POLICY_REQUEST_MAX_AGE_SECS;
294
+ if (!uint(maxAge, 3600) || maxAge === 0)
295
+ throw new SlotPolicyError('malformed', 'Policy request age limit must be 1..3600 seconds');
296
+ if (fields.issuedAt > at + SKEW_SECS || fields.issuedAt + maxAge < at)
297
+ throw new SlotPolicyError('stale', 'Policy request is too old or not valid yet');
298
+ let signer;
299
+ try {
300
+ signer = await recoverTypedDataAddress({ ...typed, signature });
301
+ }
302
+ catch (cause) {
303
+ throw new SlotPolicyError('malformed', 'Policy request signature does not recover', { cause });
304
+ }
305
+ if (!same(signer, fields.audience))
306
+ throw new SlotPolicyError('wrong-signer', 'Policy request is not signed by its audience');
307
+ return { ...fields, slot: lower(fields.slot), nonce: lower(fields.nonce), signature };
308
+ }
309
+ /** A {@link paidPolicyOperation} refused without starting a second operation. */
310
+ export class PolicyOperationError extends TasraError {
311
+ /** Refusal category; never infer it from the message. */
312
+ code;
313
+ /** The original operation's request ID, when one is known. */
314
+ requestId;
315
+ constructor(code, message, opts = {}) {
316
+ super(message, { retryable: opts.retryable ?? false });
317
+ this.code = code;
318
+ if (opts.requestId !== undefined)
319
+ this.requestId = opts.requestId;
320
+ }
321
+ }
322
+ const OPERATION_KEY = /^[A-Za-z0-9._:-]{1,128}$/;
323
+ const MAX_ATTEMPTS = 16;
324
+ /** Store key of one operation key's binding. */
325
+ export function policyOperationKey(statement, operationKey) {
326
+ if (typeof operationKey !== 'string' || !OPERATION_KEY.test(operationKey))
327
+ throw new TasraError('Operation key must be 1..128 characters of A-Z a-z 0-9 . _ : -');
328
+ return 'paid-policy-op-' + keccak256(concat([toHex('tasra/policy-operation/v1'), toHex(BigInt(statement.chainId), { size: 8 }), statement.keyRegistry, statement.slot,
329
+ statement.audience, toHex(operationKey)])).slice(2);
330
+ }
331
+ /** The operation identity a key binds: deployment, slot, action, exact payload digest, holder family and session mode. */
332
+ export function policyOperationFingerprint(input) {
333
+ const built = presentationOperationTypedData({ ...input.operation, chainId: input.chainId, keyRegistry: input.keyRegistry, slotId: input.slot, description: '', nowSecs: 0, ttlSecs: 1 });
334
+ return keccak256(toHex(JSON.stringify({ chainId: input.chainId, keyRegistry: lower(input.keyRegistry), slot: lower(input.slot), action: input.operation.action,
335
+ payloadDigest: toHex(built.payloadDigest), holder: input.holderKind === 'oauth' ? 'oauth' : 'wallet', sessionGrant: input.sessionGrant })));
336
+ }
337
+ /** Whether a stored value is a well-formed operation key binding. */
338
+ export function validBinding(value) {
339
+ const b = value;
340
+ return !!b && b.schema === 1 && hex32(b.fingerprint) && hex32(b.policy) && uint(b.generation) && b.generation >= 1 && uint(b.createdAt) && Array.isArray(b.attempts)
341
+ && b.attempts.length <= MAX_ATTEMPTS && b.attempts.every(a => uint(a?.generation) && hex32(a?.requestId) && uint(a?.notAfter));
342
+ }
343
+ /** In-process calls per store identity and binding key. */
344
+ const running = new Map();
345
+ /** Mark one binding key running in this process for the duration of `work`; refuses a second. */
346
+ export async function exclusivelyRunning(store, key, work) {
347
+ const id = storeIdentity(store);
348
+ let keys = running.get(id);
349
+ if (!keys) {
350
+ keys = new Set();
351
+ running.set(id, keys);
352
+ }
353
+ if (keys.has(key))
354
+ throw new PolicyOperationError('in-flight', 'Another call with this operation key is running in this process', { retryable: true });
355
+ keys.add(key);
356
+ try {
357
+ return await work();
358
+ }
359
+ finally {
360
+ keys.delete(key);
361
+ if (keys.size === 0)
362
+ running.delete(id);
363
+ }
364
+ }
365
+ export { MAX_ATTEMPTS as POLICY_OPERATION_MAX_ATTEMPTS, SKEW_SECS as POLICY_SKEW_SECS };
@@ -0,0 +1,47 @@
1
+ import type { Address, Hex } from 'viem';
2
+ import { type PaidOperation, type PaidOperationConfig, type PaidOperationRequest } from './paid-operation.js';
3
+ import { type SlotPolicyBootstrap } from './policy-bootstrap.js';
4
+ /** One holder-application operation started from a slot policy bootstrap. */
5
+ export interface PaidPolicyOperationRequest extends Omit<PaidOperationRequest, 'rule'> {
6
+ /** Creator-signed slot policy bootstrap issued to this application. Used only when the key starts an operation. */
7
+ policy: SlotPolicyBootstrap;
8
+ /** This holder application's key, the bootstrap's audience. */
9
+ audience: Address;
10
+ /**
11
+ * Application-chosen idempotency key, 1..128 characters of `A-Z a-z 0-9 . _ : -`, unique per
12
+ * intended operation. A second call with it resumes the original operation, never a new one.
13
+ */
14
+ operationKey: string;
15
+ /**
16
+ * Start again an original that never reached its journal (nothing of it was reserved): only
17
+ * when no request was derived for it, or its payment window has passed. Default false.
18
+ */
19
+ restartUnjournaled?: boolean;
20
+ }
21
+ /**
22
+ * Run or resume one paid operation for a holder application that holds a slot policy bootstrap
23
+ * instead of the rule salt. The first call with an operation key binds the key to this exact
24
+ * operation in the durable store before anything is signed, then runs paidOperation with the
25
+ * bootstrap. A later call with the same key, after a lost response, a crash or an uncertain step,
26
+ * resumes the journaled original with resumePaidOperation (a fresher bootstrap is not needed and
27
+ * not used), so a changed policy, an expired grant or an unknown keeper outcome never starts a
28
+ * replacement. A key bound to another operation, a closed original and an original that never
29
+ * reached its journal are refused with {@link PolicyOperationError}.
30
+ * @param config Approved deployment, creator signer, gas payer, store, agent, accountants and limits.
31
+ * @param request Slot, operation, bootstrap, application key, operation key and holder strategy.
32
+ */
33
+ export declare function paidPolicyOperation(config: PaidOperationConfig, request: PaidPolicyOperationRequest): Promise<PaidOperation>;
34
+ /**
35
+ * Read the binding of one operation key: the operation it names and the request IDs derived for
36
+ * it (the last one is the operation). Undefined when the key was never used.
37
+ * @param config The configuration the operation runs with.
38
+ * @param request Slot, application key and operation key.
39
+ */
40
+ export declare function readPolicyOperation(config: Pick<PaidOperationConfig, 'deployment' | 'store'>, request: {
41
+ slot: Hex;
42
+ audience: Address;
43
+ operationKey: string;
44
+ }): Promise<{
45
+ requestIds: Hex[];
46
+ generation: number;
47
+ } | undefined>;
@@ -0,0 +1,101 @@
1
+ // One holder-application operation per operation key, started from a slot policy bootstrap.
2
+ //
3
+ // The key's binding (the exact operation it names and the request IDs derived for it) is saved
4
+ // before anything is signed, and every request ID before its witnesses are fetched, so before the
5
+ // operation's own journal and long before any reservation. A later call with the same key never
6
+ // starts a second operation: it resumes the journaled original, refuses a different operation,
7
+ // and refuses a closed or never-journaled original unless the application explicitly restarts the
8
+ // latter once nothing of it can still be reserved.
9
+ import { paidOperation, paidOperationPhase, resumePaidOperation } from './paid-operation.js';
10
+ import { exclusivelyRunning, policyOperationFingerprint, policyOperationKey, slotPolicyHash, validBinding, verifySlotPolicyBootstrap, PolicyOperationError, POLICY_OPERATION_MAX_ATTEMPTS, POLICY_SKEW_SECS } from './policy-bootstrap.js';
11
+ import { TasraError } from '../errors.js';
12
+ const now = () => Math.floor(Date.now() / 1000);
13
+ /**
14
+ * Run or resume one paid operation for a holder application that holds a slot policy bootstrap
15
+ * instead of the rule salt. The first call with an operation key binds the key to this exact
16
+ * operation in the durable store before anything is signed, then runs paidOperation with the
17
+ * bootstrap. A later call with the same key, after a lost response, a crash or an uncertain step,
18
+ * resumes the journaled original with resumePaidOperation (a fresher bootstrap is not needed and
19
+ * not used), so a changed policy, an expired grant or an unknown keeper outcome never starts a
20
+ * replacement. A key bound to another operation, a closed original and an original that never
21
+ * reached its journal are refused with {@link PolicyOperationError}.
22
+ * @param config Approved deployment, creator signer, gas payer, store, agent, accountants and limits.
23
+ * @param request Slot, operation, bootstrap, application key, operation key and holder strategy.
24
+ */
25
+ export async function paidPolicyOperation(config, request) {
26
+ const { policy, audience, operationKey, restartUnjournaled, ...rest } = request;
27
+ const d = config.deployment, store = config.store;
28
+ const target = { chainId: d.chainId, keyRegistry: d.keyRegistry, slot: request.slot, audience };
29
+ const key = policyOperationKey(target, operationKey);
30
+ const fingerprint = policyOperationFingerprint({ ...target, operation: request.operation, holderKind: request.holder?.kind ?? '', sessionGrant: request.sessionGrant !== undefined });
31
+ return exclusivelyRunning(store, key, async () => {
32
+ const decision = await store.withLock(key, async () => {
33
+ const bound = await store.load(key);
34
+ if (bound === undefined) {
35
+ // Checked before the key is bound, so a refused bootstrap leaves nothing behind.
36
+ const { bootstrap } = await verifySlotPolicyBootstrap(policy, { ...target, action: request.operation.action, signer: config.creator.address });
37
+ await store.save(key, { schema: 1, fingerprint, policy: slotPolicyHash(bootstrap.statement), generation: 1, createdAt: now(), attempts: [] });
38
+ return { start: 1 };
39
+ }
40
+ if (!validBinding(bound))
41
+ throw new TasraError('Invalid policy operation binding');
42
+ if (bound.fingerprint !== fingerprint)
43
+ throw new PolicyOperationError('key-reused', 'This operation key is bound to a different operation');
44
+ const last = bound.attempts.at(-1);
45
+ if (last) {
46
+ const phase = await paidOperationPhase(store, last.requestId);
47
+ if (phase === 'failed' || phase === 'abandoned') {
48
+ throw new PolicyOperationError('closed', `The original operation is ${phase}; it is never replaced under the same key`, { requestId: last.requestId });
49
+ }
50
+ if (phase !== undefined)
51
+ return { resume: last.requestId };
52
+ // Derived but never journaled: it may still be on its way to its journal and reservation
53
+ // until its payment window closes.
54
+ if (!restartUnjournaled)
55
+ throw new PolicyOperationError('unjournaled', 'The original operation never reached its journal; restart it explicitly', { requestId: last.requestId });
56
+ if (now() <= last.notAfter)
57
+ throw new PolicyOperationError('in-flight', 'The original operation may still be journaled and reserved until its payment window closes', { requestId: last.requestId, retryable: true });
58
+ }
59
+ else if (!restartUnjournaled) {
60
+ throw new PolicyOperationError('unjournaled', 'The original operation derived no request; restart it explicitly');
61
+ }
62
+ const { bootstrap } = await verifySlotPolicyBootstrap(policy, { ...target, action: request.operation.action, signer: config.creator.address });
63
+ const next = { ...bound, policy: slotPolicyHash(bootstrap.statement), generation: bound.generation + 1 };
64
+ await store.save(key, next);
65
+ return { start: next.generation };
66
+ });
67
+ if ('resume' in decision) {
68
+ return resumePaidOperation(config, decision.resume, { holder: request.holder, signal: request.signal, observeRequest: request.observeRequest });
69
+ }
70
+ const generation = decision.start, ttl = request.operation.ttlSecs ?? 600;
71
+ const onRequestId = async (requestId) => {
72
+ await store.withLock(key, async () => {
73
+ const bound = await store.load(key);
74
+ if (!validBinding(bound) || bound.fingerprint !== fingerprint || bound.generation !== generation) {
75
+ throw new PolicyOperationError('superseded', 'A later call with this operation key took over; this one stopped before any reservation');
76
+ }
77
+ if (bound.attempts.length >= POLICY_OPERATION_MAX_ATTEMPTS)
78
+ throw new TasraError('Too many attempts recorded for this operation key');
79
+ // The intent was signed with an expiry of at most now + ttl; past that it can never be reserved.
80
+ await store.save(key, { ...bound, attempts: [...bound.attempts, { generation, requestId: requestId.toLowerCase(), notAfter: now() + ttl + POLICY_SKEW_SECS }] });
81
+ });
82
+ await request.onRequestId?.(requestId);
83
+ };
84
+ return paidOperation(config, { ...rest, rule: { policy, audience }, onRequestId });
85
+ });
86
+ }
87
+ /**
88
+ * Read the binding of one operation key: the operation it names and the request IDs derived for
89
+ * it (the last one is the operation). Undefined when the key was never used.
90
+ * @param config The configuration the operation runs with.
91
+ * @param request Slot, application key and operation key.
92
+ */
93
+ export async function readPolicyOperation(config, request) {
94
+ const key = policyOperationKey({ chainId: config.deployment.chainId, keyRegistry: config.deployment.keyRegistry, slot: request.slot, audience: request.audience }, request.operationKey);
95
+ const bound = await config.store.load(key);
96
+ if (bound === undefined)
97
+ return undefined;
98
+ if (!validBinding(bound))
99
+ throw new TasraError('Invalid policy operation binding');
100
+ return { requestIds: bound.attempts.map(a => a.requestId), generation: bound.generation };
101
+ }
@@ -36,6 +36,18 @@ export interface ApplicationStore {
36
36
  * Exclusively serialize work for the key across all participating processes or tabs.
37
37
  */
38
38
  withLock<T>(key: string, operation: () => Promise<T>): Promise<T>;
39
+ /**
40
+ * Optional: keys starting with `prefix`, in any order. Used only for one-time maintenance
41
+ * such as backfilling the paid operation index; stores without it still work everywhere else.
42
+ */
43
+ list?(prefix: string): Promise<string[]>;
44
+ /**
45
+ * Optional: atomically and durably create the record `key` only if it does not exist, across all
46
+ * participating processes or tabs. Resolves true for exactly one caller, false when the key
47
+ * already exists. Paid approvals use it as a one-use, generation-bound send claim; without it a
48
+ * retained approval is sent once and never resent.
49
+ */
50
+ claim?(key: string): Promise<boolean>;
39
51
  }
40
52
  /**
41
53
  * Named slot intent with an authorization rule, key threshold and verifier quorum.
@@ -1,3 +1,4 @@
1
+ import { headFollowerOf } from '../chain/headFollower.js';
1
2
  import { isOauthFormat, validate as validateRule } from '../auth/oid4vp.js';
2
3
  import { prepareSlot, createPreparedSlot } from './creation.js';
3
4
  import { createTasraWriteClient, ruleCommitment } from '../chain/write.js';
@@ -5,6 +6,7 @@ import { provisionRule } from '../chain/provisionRule.js';
5
6
  import { requireRule } from '../chain/ruleInput.js';
6
7
  import { resolveSlotKeeperUrls } from '../chain/discovery.js';
7
8
  import { TasraError } from '../errors.js';
9
+ import { WRITE_POLL_INTERVAL_MS } from '../chain/receipt.js';
8
10
  /** A creation state that requires inspection or reconciliation before resuming. */
9
11
  export class ApplicationSlotRecoveryError extends TasraError {
10
12
  /** Recovery category; never infer it from the message. */
@@ -121,7 +123,7 @@ export async function createApplicationSlot(app, input, options) {
121
123
  progress({ step, phase: transaction.phase, slotId, ...(transaction.hash ? { transactionHash: transaction.hash } : {}) });
122
124
  }
123
125
  }
124
- }, options: { signal, maxWaitMs: timeoutMs } });
126
+ }, options: { signal } });
125
127
  await save();
126
128
  }
127
129
  let slot = await app.slots.get(slotId);
@@ -159,7 +161,8 @@ export async function createApplicationSlot(app, input, options) {
159
161
  throw new ApplicationSlotRecoveryError('VERIFIER_POLICY_OUTCOME_UNKNOWN', request.name, `Verifier policy outcome unknown for ${slotId}; reconcile its transaction hash before resuming`, { slotId });
160
162
  if (state.verifierPolicy?.hash && state.verifierPolicy.phase !== 'confirmed') {
161
163
  progress({ step: 'verifier_policy', phase: 'submitted', slotId, transactionHash: state.verifierPolicy.hash });
162
- const receipt = await chain.client.waitForTransactionReceipt({ hash: state.verifierPolicy.hash, timeout: timeoutMs });
164
+ const receipt = await chain.client.waitForTransactionReceipt({ hash: state.verifierPolicy.hash, timeout: timeoutMs, pollingInterval: WRITE_POLL_INTERVAL_MS });
165
+ headFollowerOf(chain.client)?.noteMinedBlock(receipt.blockNumber);
163
166
  if (receipt.status !== 'success')
164
167
  throw new ApplicationSlotRecoveryError('VERIFIER_POLICY_REVERTED', request.name, 'Verifier policy transaction reverted; reconcile before resuming', { slotId, transactionHash: state.verifierPolicy.hash });
165
168
  state.verifierPolicy.phase = 'confirmed';
@@ -0,0 +1,38 @@
1
+ import { type Hex } from 'viem';
2
+ import type { TasraApplication } from './client.js';
3
+ import type { ApplicationStore } from './ready-slot.js';
4
+ import type { TasraWallet, WalletTransactionJournal } from './wallet.js';
5
+ /** The slot was already locked against rotation: nothing was sent (the lock is set-once). */
6
+ export interface RotationAlreadyLocked {
7
+ /** Nothing was sent: no rotation could change this slot's key already. */
8
+ phase: 'already-locked';
9
+ /** The slot found locked. */
10
+ slotId: Hex;
11
+ /** The creator locked it earlier. */
12
+ lockedByCreator: boolean;
13
+ /** It is a threshold-ECDSA slot, which the network locks by its mode. */
14
+ lockedByMode: boolean;
15
+ /** No transaction: kept so code reading `.hash` of a journal still compiles. */
16
+ hash?: undefined;
17
+ }
18
+ /**
19
+ * Lock a slot's key against every rotation, for good, with a durable named transaction from the
20
+ * slot creator's wallet (`KeyRegistry.lockKeyRotation`). Afterwards no creator, operator vote or
21
+ * revocation notice can rotate the key; resharing still works, because it keeps the key. Use it
22
+ * when the key is an identity that must never change, such as a custody address.
23
+ *
24
+ * The lock is SET-ONCE: a slot already locked resolves `already-locked` without sending. Every
25
+ * threshold-ECDSA slot is locked by its mode already, so it resolves that way too and never emits
26
+ * `KeyRotationLocked`. Refused before sending, as a `RotationLockError`: `no-slot`, `cancelled`,
27
+ * `unsupported` (a KeyRegistry without the lock) and `not-creator`; `not-confirmed` when the
28
+ * transaction confirmed but the chain does not show the lock. A transaction whose outcome was
29
+ * unknown is reconciled by calling this again with the same name (the wallet's journal).
30
+ * @param app Application client for the slot deployment.
31
+ * @param slotId Slot whose rotation is being locked.
32
+ * @param options Creator wallet and durable store for the named lock transaction.
33
+ */
34
+ export declare function lockKeyRotation(app: Pick<TasraApplication, 'deployment' | 'chain'>, slotId: Hex, options: {
35
+ wallet: TasraWallet;
36
+ store: ApplicationStore;
37
+ name?: string;
38
+ }): Promise<WalletTransactionJournal | RotationAlreadyLocked>;