@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,126 @@
1
+ // Bounded, evicting maps for hot-path reuse. Nothing here grows without limit.
2
+ /**
3
+ * A least-recently-used map holding at most `max` entries; the oldest is evicted first.
4
+ * Store only values that are a pure function of the key (decoded public points), never secrets.
5
+ */
6
+ export class BoundedCache {
7
+ max;
8
+ #entries = new Map();
9
+ constructor(max) {
10
+ this.max = max;
11
+ if (!Number.isSafeInteger(max) || max < 1)
12
+ throw new Error('cache bound must be a positive integer');
13
+ }
14
+ /** Number of entries currently held. */
15
+ get size() { return this.#entries.size; }
16
+ /**
17
+ * Return the cached value (refreshing it as most recently used), or `undefined`.
18
+ * @param key Cache key.
19
+ */
20
+ peek(key) {
21
+ if (!this.#entries.has(key))
22
+ return undefined;
23
+ const value = this.#entries.get(key);
24
+ this.#entries.delete(key);
25
+ this.#entries.set(key, value);
26
+ return value;
27
+ }
28
+ /**
29
+ * Return the cached value, or compute, store and return it. A throwing `compute` stores nothing.
30
+ * @param key Cache key.
31
+ * @param compute Pure derivation of the value from the key.
32
+ */
33
+ getOrCompute(key, compute) {
34
+ if (this.#entries.has(key)) {
35
+ const value = this.#entries.get(key);
36
+ this.#entries.delete(key);
37
+ this.#entries.set(key, value);
38
+ return value;
39
+ }
40
+ const value = compute();
41
+ if (this.#entries.size >= this.max)
42
+ this.#entries.delete(this.#entries.keys().next().value);
43
+ this.#entries.set(key, value);
44
+ return value;
45
+ }
46
+ }
47
+ /**
48
+ * Share one in-flight promise per key among concurrent callers. An entry lives only while its
49
+ * promise is pending (a settled result, success or failure, is never reused), and at most
50
+ * `max` keys are shared at once; beyond that a caller simply runs its own request.
51
+ */
52
+ export class SingleFlight {
53
+ max;
54
+ #pending = new Map();
55
+ constructor(max) {
56
+ this.max = max;
57
+ if (!Number.isSafeInteger(max) || max < 1)
58
+ throw new Error('single-flight bound must be a positive integer');
59
+ }
60
+ /** Number of keys currently in flight. */
61
+ get size() { return this.#pending.size; }
62
+ /**
63
+ * Join the pending request for `key`, or start one with `run`.
64
+ * @param key Identity of the request; equal keys must denote identical requests.
65
+ * @param run Starts the request.
66
+ */
67
+ run(key, run) {
68
+ const existing = this.#pending.get(key);
69
+ if (existing)
70
+ return existing;
71
+ if (this.#pending.size >= this.max)
72
+ return run();
73
+ const started = run();
74
+ this.#pending.set(key, started);
75
+ const clear = () => { if (this.#pending.get(key) === started)
76
+ this.#pending.delete(key); };
77
+ started.then(clear, clear);
78
+ return started;
79
+ }
80
+ }
81
+ /**
82
+ * A least-recently-used map of at most `max` entries, each dropped once its own expiry passes.
83
+ * Store only values that can never change for their key (a read pinned to a finalized block).
84
+ */
85
+ export class ExpiringCache {
86
+ max;
87
+ #entries = new Map();
88
+ constructor(max) {
89
+ this.max = max;
90
+ if (!Number.isSafeInteger(max) || max < 1)
91
+ throw new Error('cache bound must be a positive integer');
92
+ }
93
+ /** Number of entries currently held, expired ones included until touched or evicted. */
94
+ get size() { return this.#entries.size; }
95
+ /**
96
+ * Return an unexpired value, or `undefined`. A hit becomes the most recently used entry.
97
+ * @param key Cache key.
98
+ * @param now Current time in milliseconds.
99
+ */
100
+ get(key, now = Date.now()) {
101
+ const entry = this.#entries.get(key);
102
+ if (!entry)
103
+ return undefined;
104
+ this.#entries.delete(key);
105
+ if (entry.expiresAt <= now)
106
+ return undefined;
107
+ this.#entries.set(key, entry);
108
+ return entry.value;
109
+ }
110
+ /**
111
+ * Store `value` until `expiresAt`; an already expired value is not stored. At the bound the
112
+ * least recently used entry is evicted.
113
+ * @param key Cache key.
114
+ * @param value Immutable value for the key.
115
+ * @param expiresAt Expiry in milliseconds.
116
+ * @param now Current time in milliseconds.
117
+ */
118
+ set(key, value, expiresAt, now = Date.now()) {
119
+ this.#entries.delete(key);
120
+ if (!(expiresAt > now))
121
+ return;
122
+ if (this.#entries.size >= this.max)
123
+ this.#entries.delete(this.#entries.keys().next().value);
124
+ this.#entries.set(key, { value, expiresAt });
125
+ }
126
+ }
@@ -0,0 +1,4 @@
1
+ /** Bound the complete operation, including response bodies and transports ignoring abort. */
2
+ export declare function withNetworkDeadline<T>(work: (signal: AbortSignal) => Promise<T>, caller?: AbortSignal): Promise<T>;
3
+ /** Resolve four operators at a time (two registry reads each), preserving input order. */
4
+ export declare function resolveKeeperMembers<T, U>(members: readonly T[], resolve: (member: T) => Promise<U>, signal: AbortSignal): Promise<U[]>;
@@ -0,0 +1,40 @@
1
+ /** One overall budget for keeper discovery or a single keeper operation. */
2
+ const DEADLINE_MS = 15_000;
3
+ /** Bound the complete operation, including response bodies and transports ignoring abort. */
4
+ export async function withNetworkDeadline(work, caller) {
5
+ caller?.throwIfAborted();
6
+ const controller = new AbortController();
7
+ const signal = caller ? AbortSignal.any([caller, controller.signal]) : controller.signal;
8
+ const timer = setTimeout(() => controller.abort(new DOMException('Keeper operation exceeded its 15-second deadline', 'TimeoutError')), DEADLINE_MS);
9
+ let onAbort;
10
+ try {
11
+ const cancelled = new Promise((_, reject) => {
12
+ onAbort = () => reject(signal.reason);
13
+ signal.addEventListener('abort', onAbort, { once: true });
14
+ if (signal.aborted)
15
+ onAbort();
16
+ });
17
+ signal.throwIfAborted();
18
+ return await Promise.race([cancelled, work(signal)]);
19
+ }
20
+ finally {
21
+ clearTimeout(timer);
22
+ if (onAbort)
23
+ signal.removeEventListener('abort', onAbort);
24
+ controller.abort();
25
+ }
26
+ }
27
+ /** Resolve four operators at a time (two registry reads each), preserving input order. */
28
+ export async function resolveKeeperMembers(members, resolve, signal) {
29
+ const results = new Array(members.length);
30
+ let next = 0;
31
+ const worker = async () => {
32
+ while (next < members.length) {
33
+ signal.throwIfAborted();
34
+ const index = next++;
35
+ results[index] = await resolve(members[index]);
36
+ }
37
+ };
38
+ await Promise.all(Array.from({ length: Math.min(4, members.length) }, worker));
39
+ return results;
40
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Parse an HTTP `Retry-After` value (delta-seconds or an HTTP-date) into milliseconds.
3
+ * Returns undefined for a missing, malformed, negative or absurd (over one day) value; a date
4
+ * in the past is zero.
5
+ * @param value Raw header value, or null/undefined when absent.
6
+ * @param nowMs Current time in ms, for the HTTP-date form.
7
+ */
8
+ export declare function parseRetryAfter(value: string | null | undefined, nowMs?: number): number | undefined;
@@ -0,0 +1,28 @@
1
+ // Shared by errors.ts and retry.ts without an import cycle.
2
+ const MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1000;
3
+ /**
4
+ * Parse an HTTP `Retry-After` value (delta-seconds or an HTTP-date) into milliseconds.
5
+ * Returns undefined for a missing, malformed, negative or absurd (over one day) value; a date
6
+ * in the past is zero.
7
+ * @param value Raw header value, or null/undefined when absent.
8
+ * @param nowMs Current time in ms, for the HTTP-date form.
9
+ */
10
+ export function parseRetryAfter(value, nowMs = Date.now()) {
11
+ if (typeof value !== 'string')
12
+ return undefined;
13
+ const text = value.trim();
14
+ if (!text || text.length > 64)
15
+ return undefined;
16
+ if (/^[0-9]+$/.test(text)) {
17
+ const ms = Number(text) * 1000;
18
+ return Number.isSafeInteger(ms) && ms <= MAX_RETRY_AFTER_MS ? ms : undefined;
19
+ }
20
+ // HTTP-date (IMF-fixdate and the obsolete forms Date.parse understands); never a bare number.
21
+ if (!/[A-Za-z]/.test(text))
22
+ return undefined;
23
+ const at = Date.parse(text);
24
+ if (!Number.isFinite(at))
25
+ return undefined;
26
+ const ms = Math.max(0, at - nowMs);
27
+ return ms <= MAX_RETRY_AFTER_MS ? ms : undefined;
28
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Wait `ms` milliseconds, rejecting with the signal's reason as soon as it aborts.
3
+ * @param ms Wait in milliseconds.
4
+ * @param signal Optional cancellation.
5
+ */
6
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
@@ -0,0 +1,15 @@
1
+ // Shared by retry.ts and oid4vp/request-object.ts.
2
+ /**
3
+ * Wait `ms` milliseconds, rejecting with the signal's reason as soon as it aborts.
4
+ * @param ms Wait in milliseconds.
5
+ * @param signal Optional cancellation.
6
+ */
7
+ export function sleep(ms, signal) {
8
+ return new Promise((resolve, reject) => {
9
+ signal?.throwIfAborted();
10
+ const done = () => { signal?.removeEventListener('abort', abort); resolve(); };
11
+ const timer = setTimeout(done, ms);
12
+ const abort = () => { clearTimeout(timer); reject(signal.reason); };
13
+ signal?.addEventListener('abort', abort, { once: true });
14
+ });
15
+ }
@@ -0,0 +1,13 @@
1
+ import { type Address, type Hex, type TypedDataDefinition } from 'viem';
2
+ /**
3
+ * `hashTypedData` memoized by the complete typed data (domain, primary type, types, message).
4
+ * @param td Typed data built by the SDK.
5
+ */
6
+ export declare function typedDataHash(td: TypedDataDefinition): Hex;
7
+ /**
8
+ * `recoverTypedDataAddress` memoized by the exact digest and signature bytes. The caller still
9
+ * compares the returned address with the signer it independently expects.
10
+ * @param td Typed data the signature claims to sign.
11
+ * @param signature 65-byte hex signature.
12
+ */
13
+ export declare function recoverTypedDataSigner(td: TypedDataDefinition, signature: Hex): Promise<Address>;
@@ -0,0 +1,77 @@
1
+ // Bounded memoization of EIP-712 hashing and signer recovery for the paid hot path.
2
+ //
3
+ // One paid operation rebuilds the same payment, certificate and stage typed data many times
4
+ // (every approval reconstructs and then re-verifies them), and each rebuild re-ran the JS
5
+ // keccak of every type string and every secp256k1 recovery. Both are PURE functions of their
6
+ // exact inputs, so the cache key is the complete input: the domain, primary type, type list and
7
+ // message for a hash, and the exact digest plus signature bytes for a recovery. Nothing here
8
+ // skips a check: callers still compare the recovered address against their own policy, and an
9
+ // input that cannot be keyed unambiguously is simply computed without the cache.
10
+ import { hashTypedData, recoverAddress } from 'viem';
11
+ import { BoundedCache } from './bounded.js';
12
+ const hashes = new BoundedCache(1024);
13
+ const signers = new BoundedCache(1024);
14
+ // Values the SDK builds typed data from: strings, safe numbers, bigints, booleans, plain
15
+ // objects and arrays. Anything else (undefined, NaN, functions, class instances) makes the
16
+ // JSON form ambiguous, so it is not keyed at all.
17
+ function keyPart(key, value) {
18
+ // Key the holder's own DATA property, never a getter or a toJSON substitute: only a value that
19
+ // reads the same every time can stand for what hashTypedData will read.
20
+ const descriptor = Object.getOwnPropertyDescriptor(this, key);
21
+ if (!descriptor || !Object.hasOwn(descriptor, 'value'))
22
+ throw new Error('unkeyable accessor');
23
+ const original = descriptor.value;
24
+ if (typeof original === 'bigint')
25
+ return { '\u0000bigint': original.toString() };
26
+ if (original !== value || (original !== null && typeof original === 'object' && 'toJSON' in original))
27
+ throw new Error('unkeyable substitute');
28
+ if (typeof value === 'number' && !Number.isFinite(value))
29
+ throw new Error('unkeyable number');
30
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol')
31
+ throw new Error('unkeyable value');
32
+ if (value !== null && typeof value === 'object') {
33
+ const array = Array.isArray(value);
34
+ if (!array && ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
35
+ throw new Error('unkeyable object');
36
+ // Every own property must be an enumerable string key (an array's length aside): a hidden
37
+ // field is read by hashTypedData but would be missing from the JSON key.
38
+ if (Object.getOwnPropertySymbols(value).length
39
+ || Object.getOwnPropertyNames(value).length !== Object.keys(value).length + (array ? 1 : 0))
40
+ throw new Error('unkeyable hidden property');
41
+ }
42
+ return value;
43
+ }
44
+ function typedDataKey(td) {
45
+ try {
46
+ return JSON.stringify([td.domain, td.primaryType, td.types, td.message], keyPart);
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ }
52
+ /**
53
+ * `hashTypedData` memoized by the complete typed data (domain, primary type, types, message).
54
+ * @param td Typed data built by the SDK.
55
+ */
56
+ export function typedDataHash(td) {
57
+ const key = typedDataKey(td);
58
+ return key === undefined ? hashTypedData(td) : hashes.getOrCompute(key, () => hashTypedData(td));
59
+ }
60
+ /**
61
+ * `recoverTypedDataAddress` memoized by the exact digest and signature bytes. The caller still
62
+ * compares the returned address with the signer it independently expects.
63
+ * @param td Typed data the signature claims to sign.
64
+ * @param signature 65-byte hex signature.
65
+ */
66
+ export async function recoverTypedDataSigner(td, signature) {
67
+ const hash = typedDataHash(td);
68
+ if (typeof signature !== 'string' || !/^0x[0-9a-fA-F]*$/.test(signature))
69
+ return recoverAddress({ hash, signature });
70
+ const key = hash + ':' + signature.slice(2).toLowerCase();
71
+ const known = signers.peek(key);
72
+ if (known !== undefined)
73
+ return known;
74
+ const address = await recoverAddress({ hash, signature });
75
+ signers.getOrCompute(key, () => address);
76
+ return address;
77
+ }
@@ -0,0 +1,26 @@
1
+ /** A viem error as any copy of viem builds it: an object with its class name and a short message. */
2
+ export interface ViemErrorLike {
3
+ name: string;
4
+ message: string;
5
+ shortMessage: string;
6
+ cause?: unknown;
7
+ }
8
+ /**
9
+ * True when `error` looks like a viem error (any class), thrown by any copy of viem.
10
+ * @param error Anything caught.
11
+ */
12
+ export declare function isAnyViemError(error: unknown): error is ViemErrorLike;
13
+ /**
14
+ * True when `error` is a viem error named `name`, thrown by any copy of viem (its ES module or
15
+ * CommonJS build, or another installed version).
16
+ * @param error Anything caught.
17
+ * @param name viem error class name, such as `TransactionReceiptNotFoundError`.
18
+ */
19
+ export declare function isViemError(error: unknown, name: string): error is ViemErrorLike;
20
+ /**
21
+ * True when `error` is a viem error and it, or an error in its `cause` chain, is a viem error named
22
+ * one of `names` - what viem's `BaseError.walk` finds, for an error from any copy of viem.
23
+ * @param error Anything caught.
24
+ * @param names viem error class names to look for.
25
+ */
26
+ export declare function viemErrorChainHas(error: unknown, names: readonly string[]): boolean;
@@ -0,0 +1,49 @@
1
+ // Recognising a viem error by its name, not by its class.
2
+ //
3
+ // A caller hands the SDK its own viem client. When that client was built from viem's CommonJS
4
+ // entry (`require('viem')`) while this package imports viem's ES module build, or when the caller
5
+ // has a second copy of viem in its tree, the errors that client throws are instances of DIFFERENT
6
+ // classes with the same names: `error instanceof TransactionReceiptNotFoundError` is then false for
7
+ // a receipt that is simply not there yet. Every viem error extends viem's BaseError, which sets a
8
+ // `name` (the class name) and a `shortMessage`, so those two identify the error whichever copy of
9
+ // viem threw it.
10
+ /**
11
+ * True when `error` looks like a viem error (any class), thrown by any copy of viem.
12
+ * @param error Anything caught.
13
+ */
14
+ export function isAnyViemError(error) {
15
+ if (typeof error !== 'object' || error === null)
16
+ return false;
17
+ const e = error;
18
+ return typeof e.name === 'string' && typeof e.message === 'string' && typeof e.shortMessage === 'string';
19
+ }
20
+ /**
21
+ * True when `error` is a viem error named `name`, thrown by any copy of viem (its ES module or
22
+ * CommonJS build, or another installed version).
23
+ * @param error Anything caught.
24
+ * @param name viem error class name, such as `TransactionReceiptNotFoundError`.
25
+ */
26
+ export function isViemError(error, name) {
27
+ return isAnyViemError(error) && error.name === name;
28
+ }
29
+ /** Longest `cause` chain walked; viem nests a handful of levels. */
30
+ const MAX_CAUSE_DEPTH = 32;
31
+ /**
32
+ * True when `error` is a viem error and it, or an error in its `cause` chain, is a viem error named
33
+ * one of `names` - what viem's `BaseError.walk` finds, for an error from any copy of viem.
34
+ * @param error Anything caught.
35
+ * @param names viem error class names to look for.
36
+ */
37
+ export function viemErrorChainHas(error, names) {
38
+ if (!isAnyViemError(error))
39
+ return false;
40
+ const seen = new Set();
41
+ let e = error;
42
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof e === 'object' && e !== null && !seen.has(e); depth++) {
43
+ seen.add(e);
44
+ if (names.some(name => isViemError(e, name)))
45
+ return true;
46
+ e = e.cause;
47
+ }
48
+ return false;
49
+ }
@@ -18,7 +18,7 @@ export declare const COMMITTEE_ACTIONS: readonly CommitteeAction[];
18
18
  * @param action - Operation name bound into the request.
19
19
  * @param payloadDigest - 32-byte action-specific payload digest.
20
20
  */
21
- export declare function requestHash(chainId: number | bigint, slotId: Uint8Array, action: CommitteeAction, payloadDigest: Uint8Array): Uint8Array;
21
+ export declare function requestHash(chainId: number | bigint, slotId: Uint8Array, action: CommitteeAction | 'relay', payloadDigest: Uint8Array): Uint8Array;
22
22
  /**
23
23
  * The authenticated context a wallet nonce binds beyond the request hash and the session
24
24
  * random (the reference nonce context): the beacon epoch, the anchored verifier-set
@@ -51,6 +51,32 @@ export interface NonceContext {
51
51
  * @param ctx - Beacon epoch, verifier snapshot, committee policy and operation expiry to bind.
52
52
  */
53
53
  export declare function derivedNonce(reqHash: Uint8Array, random: Uint8Array, ctx: NonceContext): string;
54
+ /** Domain of the session-mode nonce ({@link vpSessionNonce}): a new name, so it never equals a plain nonce. */
55
+ export declare const VP_SESSION_NONCE_DOMAIN = "keykeeper/vp-session-nonce/v1";
56
+ /**
57
+ * The nonce of a presentation that also OPENS a session grant:
58
+ * `base64url(keccak256("keykeeper/vp-session-nonce/v1" || request_hash || random || epoch u64 BE ||
59
+ * snapshot_root || registry_size u32 BE || committee u32 BE || quorum u32 BE || operation_exp i64 BE
60
+ * || session_key_thumbprint))`, unpadded. The holder key that signs the KB-JWT (or the DPoP proof)
61
+ * thereby authorizes exactly the session key with that RFC 7638 thumbprint. Mirrors the reference
62
+ * `vp_session_nonce`; vectors: `test/vp-session-nonce-vectors.json`.
63
+ *
64
+ * @param reqHash - 32-byte request-binding hash.
65
+ * @param random - The session's 32-byte random.
66
+ * @param ctx - Beacon epoch, verifier snapshot, committee policy and operation expiry to bind.
67
+ * @param sessionKeyThumbprint - 32-byte RFC 7638 SHA-256 thumbprint of the fresh session key.
68
+ */
69
+ export declare function vpSessionNonce(reqHash: Uint8Array, random: Uint8Array, ctx: NonceContext, sessionKeyThumbprint: Uint8Array): string;
70
+ /**
71
+ * The nonce a presentation must carry: {@link vpSessionNonce} when it opens a session (a session key
72
+ * thumbprint is named), else {@link derivedNonce}. The reference `vp_nonce_bound`.
73
+ *
74
+ * @param reqHash - 32-byte request-binding hash.
75
+ * @param random - The session's 32-byte random.
76
+ * @param ctx - Nonce context.
77
+ * @param sessionKeyThumbprint - The fresh session key's thumbprint, only when a session grant is requested.
78
+ */
79
+ export declare function vpNonceBound(reqHash: Uint8Array, random: Uint8Array, ctx: NonceContext, sessionKeyThumbprint?: Uint8Array): string;
54
80
  /**
55
81
  * The per-action `payload_digest` the keeper recomputes at `enforce_request_binding`:
56
82
  * `sign` = sha256(message), `ibe-extract` = sha256(identity), `decrypt` = the ciphertext
@@ -58,13 +58,48 @@ export function requestHash(chainId, slotId, action, payloadDigest) {
58
58
  * @param ctx - Beacon epoch, verifier snapshot, committee policy and operation expiry to bind.
59
59
  */
60
60
  export function derivedNonce(reqHash, random, ctx) {
61
+ return nonceOver(VP_NONCE_DOMAIN, reqHash, random, ctx);
62
+ }
63
+ /** Domain of the session-mode nonce ({@link vpSessionNonce}): a new name, so it never equals a plain nonce. */
64
+ export const VP_SESSION_NONCE_DOMAIN = 'keykeeper/vp-session-nonce/v1';
65
+ /**
66
+ * The nonce of a presentation that also OPENS a session grant:
67
+ * `base64url(keccak256("keykeeper/vp-session-nonce/v1" || request_hash || random || epoch u64 BE ||
68
+ * snapshot_root || registry_size u32 BE || committee u32 BE || quorum u32 BE || operation_exp i64 BE
69
+ * || session_key_thumbprint))`, unpadded. The holder key that signs the KB-JWT (or the DPoP proof)
70
+ * thereby authorizes exactly the session key with that RFC 7638 thumbprint. Mirrors the reference
71
+ * `vp_session_nonce`; vectors: `test/vp-session-nonce-vectors.json`.
72
+ *
73
+ * @param reqHash - 32-byte request-binding hash.
74
+ * @param random - The session's 32-byte random.
75
+ * @param ctx - Beacon epoch, verifier snapshot, committee policy and operation expiry to bind.
76
+ * @param sessionKeyThumbprint - 32-byte RFC 7638 SHA-256 thumbprint of the fresh session key.
77
+ */
78
+ export function vpSessionNonce(reqHash, random, ctx, sessionKeyThumbprint) {
79
+ if (sessionKeyThumbprint.length !== 32)
80
+ throw new Error('vpSessionNonce: sessionKeyThumbprint must be 32 bytes');
81
+ return nonceOver(VP_SESSION_NONCE_DOMAIN, reqHash, random, ctx, sessionKeyThumbprint);
82
+ }
83
+ /**
84
+ * The nonce a presentation must carry: {@link vpSessionNonce} when it opens a session (a session key
85
+ * thumbprint is named), else {@link derivedNonce}. The reference `vp_nonce_bound`.
86
+ *
87
+ * @param reqHash - 32-byte request-binding hash.
88
+ * @param random - The session's 32-byte random.
89
+ * @param ctx - Nonce context.
90
+ * @param sessionKeyThumbprint - The fresh session key's thumbprint, only when a session grant is requested.
91
+ */
92
+ export function vpNonceBound(reqHash, random, ctx, sessionKeyThumbprint) {
93
+ return sessionKeyThumbprint === undefined ? derivedNonce(reqHash, random, ctx) : vpSessionNonce(reqHash, random, ctx, sessionKeyThumbprint);
94
+ }
95
+ function nonceOver(domain, reqHash, random, ctx, ...tail) {
61
96
  if (reqHash.length !== 32)
62
97
  throw new Error('derivedNonce: reqHash must be 32 bytes');
63
98
  if (random.length !== 32)
64
99
  throw new Error('derivedNonce: random must be 32 bytes');
65
100
  if (ctx.snapshotRoot.length !== 32)
66
101
  throw new Error('derivedNonce: snapshotRoot must be 32 bytes');
67
- return b64url(keccak_256(concat(utf8(VP_NONCE_DOMAIN), reqHash, random, be64(ctx.epoch), ctx.snapshotRoot, be32(ctx.registrySize), be32(ctx.committee), be32(ctx.quorum), be64(BigInt.asUintN(64, BigInt(ctx.operationExp))))));
102
+ return b64url(keccak_256(concat(utf8(domain), reqHash, random, be64(ctx.epoch), ctx.snapshotRoot, be32(ctx.registrySize), be32(ctx.committee), be32(ctx.quorum), be64(BigInt.asUintN(64, BigInt(ctx.operationExp))), ...tail)));
68
103
  }
69
104
  /**
70
105
  * The per-action `payload_digest` the keeper recomputes at `enforce_request_binding`:
@@ -90,13 +90,15 @@ export declare function didJwk(jwk: Jwk): string;
90
90
  /**
91
91
  * Construct a holder identity from a 32-byte P-256 private scalar.
92
92
  *
93
- * @param privateKey - 32-byte P-256 private scalar.
93
+ * @param privateKey - 32-byte P-256 private scalar. Copied: the holder's `privateKey` never
94
+ * shares memory with it, so the caller may wipe its bytes once this returns.
94
95
  */
95
96
  export declare function p256HolderKey(privateKey: Uint8Array): HolderKey;
96
97
  /**
97
98
  * An Ed25519 holder key from a 32-byte seed - the shape `tasra-cli vc issue-sd-jwt` binds.
98
99
  *
99
- * @param seed - 32-byte Ed25519 secret seed.
100
+ * @param seed - 32-byte Ed25519 secret seed. Copied: the holder's `privateKey` never shares
101
+ * memory with it, so the caller may wipe its bytes once this returns.
100
102
  */
101
103
  export declare function ed25519HolderKey(seed: Uint8Array): HolderKey;
102
104
  /** Generate a random P-256 holder key and its did:jwk identifier. */
@@ -72,29 +72,61 @@ export function didJwk(jwk) {
72
72
  const canon = jwk.kty === 'EC' ? { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y } : { kty: jwk.kty, crv: jwk.crv, x: jwk.x };
73
73
  return `did:jwk:${b64url(JSON.stringify(canon))}`;
74
74
  }
75
+ /**
76
+ * Copy caller key bytes into a fresh, plain `Uint8Array` that shares no memory with the input.
77
+ * `slice()` is not enough: on a Node `Buffer` it returns a VIEW of the same memory.
78
+ */
79
+ function ownedKeyBytes(bytes) {
80
+ // Uint8Array.from would silently coerce a string or number array; only real bytes are a key.
81
+ if (!(bytes instanceof Uint8Array))
82
+ throw new Error('Holder key must be a Uint8Array');
83
+ return Uint8Array.from(bytes);
84
+ }
75
85
  /**
76
86
  * Construct a holder identity from a 32-byte P-256 private scalar.
77
87
  *
78
- * @param privateKey - 32-byte P-256 private scalar.
88
+ * @param privateKey - 32-byte P-256 private scalar. Copied: the holder's `privateKey` never
89
+ * shares memory with it, so the caller may wipe its bytes once this returns.
79
90
  */
80
91
  export function p256HolderKey(privateKey) {
81
92
  if (privateKey.length !== 32)
82
93
  throw new Error('P-256 private key must be 32 bytes');
83
- const publicJwk = p256PublicJwk(privateKey);
84
- return { privateKey, publicJwk, did: didJwk(publicJwk) };
94
+ const owned = ownedKeyBytes(privateKey);
95
+ try {
96
+ const publicJwk = p256PublicJwk(owned);
97
+ return { privateKey: owned, publicJwk, did: didJwk(publicJwk) };
98
+ }
99
+ catch (error) {
100
+ owned.fill(0);
101
+ throw error;
102
+ }
85
103
  }
86
104
  /**
87
105
  * An Ed25519 holder key from a 32-byte seed - the shape `tasra-cli vc issue-sd-jwt` binds.
88
106
  *
89
- * @param seed - 32-byte Ed25519 secret seed.
107
+ * @param seed - 32-byte Ed25519 secret seed. Copied: the holder's `privateKey` never shares
108
+ * memory with it, so the caller may wipe its bytes once this returns.
90
109
  */
91
110
  export function ed25519HolderKey(seed) {
92
- const publicJwk = { kty: 'OKP', crv: 'Ed25519', x: b64url(ed25519.getPublicKey(seed)) };
93
- return { privateKey: seed, publicJwk, did: didJwk(publicJwk) };
111
+ const owned = ownedKeyBytes(seed);
112
+ try {
113
+ const publicJwk = { kty: 'OKP', crv: 'Ed25519', x: b64url(ed25519.getPublicKey(owned)) };
114
+ return { privateKey: owned, publicJwk, did: didJwk(publicJwk) };
115
+ }
116
+ catch (error) {
117
+ owned.fill(0);
118
+ throw error;
119
+ }
94
120
  }
95
121
  /** Generate a random P-256 holder key and its did:jwk identifier. */
96
122
  export function randomHolderKey() {
97
- return p256HolderKey(p256.utils.randomPrivateKey());
123
+ const scalar = p256.utils.randomPrivateKey();
124
+ try {
125
+ return p256HolderKey(scalar);
126
+ }
127
+ finally {
128
+ scalar.fill(0);
129
+ }
98
130
  }
99
131
  // base58btc (did:key)
100
132
  const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';