@sirosfoundation/wmp-js 0.5.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/completion.d.ts +107 -0
- package/dist/completion.js +544 -0
- package/dist/consent.d.ts +53 -0
- package/dist/consent.js +136 -0
- package/dist/discovery.d.ts +48 -8
- package/dist/discovery.js +119 -38
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +10 -0
- package/dist/evidence.d.ts +1 -0
- package/dist/evidence.js +1 -0
- package/dist/index.d.ts +14 -6
- package/dist/index.js +12 -3
- package/dist/jsonrpc.d.ts +2 -0
- package/dist/jsonrpc.js +4 -1
- package/dist/openid4x.d.ts +165 -17
- package/dist/openid4x.js +176 -3
- package/dist/peer.d.ts +234 -3
- package/dist/peer.js +1007 -51
- package/dist/profile.d.ts +39 -0
- package/dist/random.d.ts +2 -0
- package/dist/random.js +7 -0
- package/dist/relay.js +4 -2
- package/dist/session-store.d.ts +75 -3
- package/dist/session-store.js +105 -4
- package/dist/signflow.d.ts +173 -0
- package/dist/signflow.js +464 -0
- package/dist/transport.d.ts +45 -4
- package/dist/transport.js +209 -42
- package/dist/types.d.ts +2 -0
- package/dist/types.js +2 -0
- package/dist/version.d.ts +30 -0
- package/dist/version.js +61 -0
- package/package.json +3 -3
package/dist/signflow.js
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wallet side of the WMP sign sub-flows and the match flow (profile Sections
|
|
3
|
+
* 3.1.5, 3.2.5, 3.2.6 and 3.3) — the responder counterpart of go-wmp's
|
|
4
|
+
* orchestrator-side FlowContext.RequestSign / RequestMatch.
|
|
5
|
+
*/
|
|
6
|
+
import { sha256, sha384, sha512 } from "@noble/hashes/sha2.js";
|
|
7
|
+
import { CompletionResultError, validVpToken, validateCompletionResult } from "./completion.js";
|
|
8
|
+
import { isSelectionHandle } from "./consent.js";
|
|
9
|
+
import { unsupportedError } from "./errors.js";
|
|
10
|
+
import { WMPError } from "./jsonrpc.js";
|
|
11
|
+
import { ErrorCode, Method, VERSION } from "./types.js";
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
// transaction_data capability (profile 2.3)
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
/** The capability a wallet offers when it processes OID4VP transaction_data end to end. */
|
|
16
|
+
export const CAPABILITY_TRANSACTION_DATA = "transaction_data";
|
|
17
|
+
/** First version of the transaction_data capability. */
|
|
18
|
+
export const TRANSACTION_DATA_VERSION_1 = 1;
|
|
19
|
+
/**
|
|
20
|
+
* Whether `caps` contains a transaction_data capability that lists `version`
|
|
21
|
+
* (go-wmp Capabilities.OffersTransactionData). Absence, an unparsable value or a
|
|
22
|
+
* list without the version all mean "not offered". Use it on what the peer
|
|
23
|
+
* OFFERED (`capabilities_offered`), never on the negotiated result: negotiation
|
|
24
|
+
* may fall back to all of the responder's capabilities when a peer offers none,
|
|
25
|
+
* which would read as support the peer never claimed.
|
|
26
|
+
*/
|
|
27
|
+
export function offersTransactionData(caps, version = TRANSACTION_DATA_VERSION_1) {
|
|
28
|
+
const raw = caps !== undefined && Object.hasOwn(caps, CAPABILITY_TRANSACTION_DATA) ? caps[CAPABILITY_TRANSACTION_DATA] : undefined;
|
|
29
|
+
// A malformed descriptor is not an offer: fail closed on every member we know.
|
|
30
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
|
31
|
+
return false;
|
|
32
|
+
const c = raw;
|
|
33
|
+
if (!Array.isArray(c.versions) || c.versions.length === 0 || !c.versions.every((v) => Number.isInteger(v) && v >= 1))
|
|
34
|
+
return false;
|
|
35
|
+
if (c.hash_algs !== undefined && (!Array.isArray(c.hash_algs) || !c.hash_algs.every((a) => typeof a === "string" && a !== "")))
|
|
36
|
+
return false;
|
|
37
|
+
return c.versions.includes(version);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The `data` of the -31005 a wallet answers with for transaction_data it will not
|
|
41
|
+
* process: {"unsupported": "transaction_data"}, plus `redirect_uri` when the
|
|
42
|
+
* verifier's response mode produced a redirect (additive, profile 2.3).
|
|
43
|
+
*/
|
|
44
|
+
export function transactionDataUnsupportedData(redirectUri) {
|
|
45
|
+
return { ...(redirectUri ? { redirect_uri: redirectUri } : {}), unsupported: CAPABILITY_TRANSACTION_DATA };
|
|
46
|
+
}
|
|
47
|
+
/** The -31005 error carrying {@link transactionDataUnsupportedData}. */
|
|
48
|
+
export function transactionDataUnsupportedError(redirectUri) {
|
|
49
|
+
return unsupportedError(CAPABILITY_TRANSACTION_DATA, redirectUri ? { redirect_uri: redirectUri } : undefined);
|
|
50
|
+
}
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
// transaction_data hashing and entry checks (profile 3.2.5)
|
|
53
|
+
// ---------------------------------------------------------------------------
|
|
54
|
+
// A Map, not an object: "constructor" or "toString" must not name an algorithm.
|
|
55
|
+
const HASHES = new Map([
|
|
56
|
+
["sha-256", sha256],
|
|
57
|
+
["sha-384", sha384],
|
|
58
|
+
["sha-512", sha512],
|
|
59
|
+
]);
|
|
60
|
+
/** Hash algorithms {@link transactionDataHash} computes. */
|
|
61
|
+
export const TRANSACTION_DATA_HASH_ALGS = [...HASHES.keys()];
|
|
62
|
+
function toBase64Url(bytes) {
|
|
63
|
+
let bin = "";
|
|
64
|
+
for (const b of bytes)
|
|
65
|
+
bin += String.fromCodePoint(b);
|
|
66
|
+
return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
67
|
+
}
|
|
68
|
+
function fromBase64Url(s) {
|
|
69
|
+
if (!/^[A-Za-z0-9_-]+$/.test(s))
|
|
70
|
+
throw new Error("not base64url");
|
|
71
|
+
const pad = (4 - (s.length % 4)) % 4;
|
|
72
|
+
if (pad === 3)
|
|
73
|
+
throw new Error("impossible base64url length");
|
|
74
|
+
const bin = atob(s.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat(pad));
|
|
75
|
+
return Uint8Array.from(bin, (c) => c.codePointAt(0) ?? 0);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* `transaction_data_hashes` element for an entry: base64url (no padding) of the
|
|
79
|
+
* hash of the ASCII bytes of `raw`, exactly as received (OID4VP 1.0 Appendix B:
|
|
80
|
+
* "base64url decoding is not performed before hashing"). Never hash a decoded
|
|
81
|
+
* and re-serialized object. Throws for an algorithm this library does not
|
|
82
|
+
* compute (the wallet then fails the sub-flow: it cannot bind) or a `raw` that is
|
|
83
|
+
* not ASCII.
|
|
84
|
+
*/
|
|
85
|
+
export function transactionDataHash(raw, alg = "sha-256") {
|
|
86
|
+
const h = HASHES.get(alg);
|
|
87
|
+
if (!h)
|
|
88
|
+
throw new Error(`unsupported transaction_data hash algorithm`);
|
|
89
|
+
// eslint-disable-next-line no-control-regex
|
|
90
|
+
if (!/^[\u0000-\u007f]*$/.test(raw))
|
|
91
|
+
throw new Error("transaction_data raw is not ASCII");
|
|
92
|
+
const bytes = new Uint8Array(raw.length);
|
|
93
|
+
for (let i = 0; i < raw.length; i++)
|
|
94
|
+
bytes[i] = raw.codePointAt(i) ?? 0;
|
|
95
|
+
return toBase64Url(h(bytes));
|
|
96
|
+
}
|
|
97
|
+
function deepEqual(a, b) {
|
|
98
|
+
if (a === b)
|
|
99
|
+
return true;
|
|
100
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
|
|
101
|
+
return false;
|
|
102
|
+
if (Array.isArray(a) !== Array.isArray(b))
|
|
103
|
+
return false;
|
|
104
|
+
const ka = Object.keys(a);
|
|
105
|
+
const kb = Object.keys(b);
|
|
106
|
+
if (ka.length !== kb.length)
|
|
107
|
+
return false;
|
|
108
|
+
return ka.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* A transaction_data_hashes_alg as a list for comparison: a bare string becomes a
|
|
112
|
+
* one-element list; anything else is kept as it is, malformed elements included,
|
|
113
|
+
* so a disagreement hidden in a bad element cannot pass.
|
|
114
|
+
*/
|
|
115
|
+
function algList(v) {
|
|
116
|
+
return typeof v === "string" ? [v] : v;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Decodes an entry's `raw` and returns the decoded object. The wallet validates
|
|
120
|
+
* and displays THIS, not the members the orchestrator sent next to it. Throws
|
|
121
|
+
* -32602 when `raw` is not base64url of a JSON object.
|
|
122
|
+
*/
|
|
123
|
+
export function decodeTransactionData(raw) {
|
|
124
|
+
try {
|
|
125
|
+
const v = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(fromBase64Url(raw)));
|
|
126
|
+
if (typeof v === "object" && v !== null && !Array.isArray(v))
|
|
127
|
+
return v;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
/* fall through */
|
|
131
|
+
}
|
|
132
|
+
throw invalidParams("transaction_data raw is not base64url of a JSON object");
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Refuses an entry whose members disagree with what `raw` decodes to (profile
|
|
136
|
+
* 3.2.5 requirement 2): otherwise a compromised orchestrator could show one
|
|
137
|
+
* transaction and bind another. Returns the decoded entry for display.
|
|
138
|
+
*/
|
|
139
|
+
export function checkTransactionDataEntry(entry) {
|
|
140
|
+
const d = decodeTransactionData(entry.raw);
|
|
141
|
+
if (d.type !== entry.type)
|
|
142
|
+
throw invalidParams("transaction_data type disagrees with raw");
|
|
143
|
+
if (!deepEqual(d.credential_ids, entry.credential_ids))
|
|
144
|
+
throw invalidParams("transaction_data credential_ids disagree with raw");
|
|
145
|
+
if (entry.payload !== undefined && !deepEqual(d.payload, entry.payload))
|
|
146
|
+
throw invalidParams("transaction_data payload disagrees with raw");
|
|
147
|
+
if (entry.transaction_data_hashes_alg !== undefined && !deepEqual(algList(d.transaction_data_hashes_alg), algList(entry.transaction_data_hashes_alg))) {
|
|
148
|
+
throw invalidParams("transaction_data_hashes_alg disagrees with raw");
|
|
149
|
+
}
|
|
150
|
+
return d;
|
|
151
|
+
}
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
// Sign sub-flow params
|
|
154
|
+
// ---------------------------------------------------------------------------
|
|
155
|
+
function invalidParams(reason) {
|
|
156
|
+
// The reason names a member or a rule, never a value.
|
|
157
|
+
return new WMPError(ErrorCode.InvalidParams, "Invalid params", { reason });
|
|
158
|
+
}
|
|
159
|
+
/** Sign actions a wallet answers: Core (generate_proof, sign_document, authorize) and the profile's. */
|
|
160
|
+
export const SIGN_ACTIONS = [
|
|
161
|
+
"generate_proof",
|
|
162
|
+
"sign_document",
|
|
163
|
+
"authorize",
|
|
164
|
+
"sign_presentation",
|
|
165
|
+
"sign_client_auth",
|
|
166
|
+
"decrypt_credential_response",
|
|
167
|
+
];
|
|
168
|
+
/** Upper bound on `count` (batch size) a wallet will generate proofs for. */
|
|
169
|
+
export const MAX_PROOF_COUNT = 256;
|
|
170
|
+
const STRING_MEMBERS = [
|
|
171
|
+
"nonce", "audience", "proof_type", "issuer", "response_uri", "verifier_jwk_thumbprint", "verifier_session_id",
|
|
172
|
+
"state", "response_mode", "reissuance_kid", "htm", "htu", "dpop_nonce", "ath", "key_id", "attestation_challenge",
|
|
173
|
+
"credential_type", "credential_issuer", "jwe",
|
|
174
|
+
];
|
|
175
|
+
const OBJECT_MEMBERS = ["proof_types_supported", "client_metadata", "verified_request", "response_encryption"];
|
|
176
|
+
function isObj(v) {
|
|
177
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Validates the `params` of a `sign` flow.start and returns them (a shallow
|
|
181
|
+
* copy that keeps members this library does not model). Throws a WMPError:
|
|
182
|
+
* -32602 for a malformed member, an unknown action or the old
|
|
183
|
+
* `credentials_to_include` shape; -31005 {"unsupported":"transaction_data"}
|
|
184
|
+
* for an entry that lacks `raw` (the wallet cannot bind to it and MUST refuse,
|
|
185
|
+
* profile 3.2.5). Error data names members, never values.
|
|
186
|
+
*/
|
|
187
|
+
export function parseSignSubFlowParams(raw) {
|
|
188
|
+
if (!isObj(raw))
|
|
189
|
+
throw invalidParams("params is not an object");
|
|
190
|
+
const p = raw;
|
|
191
|
+
if (typeof p.action !== "string" || !SIGN_ACTIONS.includes(p.action))
|
|
192
|
+
throw invalidParams("action is missing or unknown");
|
|
193
|
+
// Required for the sub-flows nested in an oid4vci/oid4vp flow; a plain Core sign flow has no parent.
|
|
194
|
+
if (p.parent_flow_id !== undefined && (typeof p.parent_flow_id !== "string" || p.parent_flow_id === "")) {
|
|
195
|
+
throw invalidParams("parent_flow_id is malformed");
|
|
196
|
+
}
|
|
197
|
+
for (const k of STRING_MEMBERS) {
|
|
198
|
+
if (p[k] !== undefined && typeof p[k] !== "string")
|
|
199
|
+
throw invalidParams(`${k} is not a string`);
|
|
200
|
+
}
|
|
201
|
+
for (const k of OBJECT_MEMBERS) {
|
|
202
|
+
if (p[k] !== undefined && !isObj(p[k]))
|
|
203
|
+
throw invalidParams(`${k} is not an object`);
|
|
204
|
+
}
|
|
205
|
+
if (p.count !== undefined && (!Number.isInteger(p.count) || p.count < 1 || p.count > MAX_PROOF_COUNT)) {
|
|
206
|
+
throw invalidParams(`count is not an integer from 1 to ${MAX_PROOF_COUNT}`);
|
|
207
|
+
}
|
|
208
|
+
if (p.deferred !== undefined && typeof p.deferred !== "boolean")
|
|
209
|
+
throw invalidParams("deferred is not a boolean");
|
|
210
|
+
if (p.selection_handle !== undefined && !isSelectionHandle(p.selection_handle))
|
|
211
|
+
throw invalidParams("selection_handle is malformed");
|
|
212
|
+
if (p.credential_response_encryption !== undefined) {
|
|
213
|
+
const c = p.credential_response_encryption;
|
|
214
|
+
if (!isObj(c) || typeof c.alg !== "string" || typeof c.enc !== "string" || (c.required !== undefined && typeof c.required !== "boolean")) {
|
|
215
|
+
throw invalidParams("credential_response_encryption is malformed");
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (p.auxiliary_data_to_issuer !== undefined && (!Array.isArray(p.auxiliary_data_to_issuer) || !p.auxiliary_data_to_issuer.every(isObj))) {
|
|
219
|
+
throw invalidParams("auxiliary_data_to_issuer is not an array of objects");
|
|
220
|
+
}
|
|
221
|
+
if (p.credentials_to_include !== undefined) {
|
|
222
|
+
const c = p.credentials_to_include;
|
|
223
|
+
if (!Array.isArray(c) || !c.every((e) => isObj(e) && Object.keys(e).length === 1 && typeof e.credential_query_id === "string" && e.credential_query_id !== "")) {
|
|
224
|
+
throw invalidParams("credentials_to_include is not an array of {credential_query_id}");
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (p.action === "sign_presentation" && (typeof p.nonce !== "string" || typeof p.audience !== "string")) {
|
|
228
|
+
throw invalidParams("sign_presentation needs nonce and audience");
|
|
229
|
+
}
|
|
230
|
+
if (p.transaction_data !== undefined) {
|
|
231
|
+
if (!Array.isArray(p.transaction_data))
|
|
232
|
+
throw invalidParams("transaction_data is not an array");
|
|
233
|
+
for (const e of p.transaction_data) {
|
|
234
|
+
if (!isObj(e))
|
|
235
|
+
throw invalidParams("transaction_data entry is not an object");
|
|
236
|
+
// An orchestrator that predates `raw`: the wallet cannot bind to the transaction.
|
|
237
|
+
if (typeof e.raw !== "string" || e.raw === "")
|
|
238
|
+
throw transactionDataUnsupportedError();
|
|
239
|
+
if (typeof e.type !== "string")
|
|
240
|
+
throw invalidParams("transaction_data entry type is not a string");
|
|
241
|
+
if (!Array.isArray(e.credential_ids) || !e.credential_ids.every((x) => typeof x === "string")) {
|
|
242
|
+
throw invalidParams("transaction_data entry credential_ids is not an array of strings");
|
|
243
|
+
}
|
|
244
|
+
if (e.payload !== undefined && !isObj(e.payload))
|
|
245
|
+
throw invalidParams("transaction_data entry payload is not an object");
|
|
246
|
+
if (e.transaction_data_hashes_alg !== undefined) {
|
|
247
|
+
const a = e.transaction_data_hashes_alg;
|
|
248
|
+
const ok = typeof a === "string" ? a !== "" : Array.isArray(a) && a.length > 0 && a.every((x) => typeof x === "string" && x !== "");
|
|
249
|
+
if (!ok)
|
|
250
|
+
throw invalidParams("transaction_data_hashes_alg is not a non-empty string or array of non-empty strings");
|
|
251
|
+
}
|
|
252
|
+
checkTransactionDataEntry(e);
|
|
253
|
+
}
|
|
254
|
+
if (p.transaction_data.length > 0 && p.action === "sign_presentation" && typeof p.response_mode !== "string") {
|
|
255
|
+
throw invalidParams("response_mode is required with transaction_data");
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (p.action === "sign_presentation") {
|
|
259
|
+
const top = p.response_mode;
|
|
260
|
+
const inner = isObj(p.verified_request) ? p.verified_request.response_mode : undefined;
|
|
261
|
+
if (top !== undefined && inner !== undefined && top !== inner) {
|
|
262
|
+
throw invalidParams("response_mode disagrees with verified_request.response_mode");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return { ...p };
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* The response mode a sign_presentation is answered in: the top-level member
|
|
269
|
+
* (profile 3.2.5, optional without transaction_data) or, when it is omitted, the
|
|
270
|
+
* one of the verified request. Without either the mode is plaintext.
|
|
271
|
+
*/
|
|
272
|
+
export function effectiveResponseMode(p) {
|
|
273
|
+
if (typeof p.response_mode === "string")
|
|
274
|
+
return p.response_mode;
|
|
275
|
+
const inner = isObj(p.verified_request) ? p.verified_request.response_mode : undefined;
|
|
276
|
+
return typeof inner === "string" ? inner : undefined;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* A notifier bound to ONE flow generation: its sends fail, without sending, once
|
|
280
|
+
* that flow ended (cancelled, completed, replaced under the same id), and never
|
|
281
|
+
* retire another generation's record. Falls back to plain `notify` for a
|
|
282
|
+
* PeerContext that cannot tell generations apart.
|
|
283
|
+
*/
|
|
284
|
+
export function boundNotifier(peer, flowId) {
|
|
285
|
+
const generation = peer.flowGeneration?.(flowId);
|
|
286
|
+
return {
|
|
287
|
+
notify: (method, params) => (peer.notifyFlow ? peer.notifyFlow(generation, method, params) : peer.notify(method, params)),
|
|
288
|
+
// Whether the flow this notifier was made for is still the active one.
|
|
289
|
+
current: () => !peer.flowGeneration || (generation !== undefined && peer.flowGeneration(flowId) === generation),
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Ends a sub-flow successfully (wmp.flow.complete). The result is checked first
|
|
294
|
+
* (default: the completion rules of {@link validateCompletionResult}; for a
|
|
295
|
+
* match flow pass {@link validateMatchResult}); a result that would be refused
|
|
296
|
+
* by the orchestrator is never sent.
|
|
297
|
+
*/
|
|
298
|
+
export async function completeSubFlow(peer, wmp, flowId, result, validate = (r) => validateCompletionResult(r)) {
|
|
299
|
+
validate(result);
|
|
300
|
+
await peer.notify(Method.FlowComplete, { wmp: meta(wmp), flow_id: flowId, result });
|
|
301
|
+
}
|
|
302
|
+
/** Ends a sub-flow with wmp.flow.error (a failure, not a refusal). */
|
|
303
|
+
export async function failSubFlow(peer, wmp, flowId, code, message, data) {
|
|
304
|
+
await peer.notify(Method.FlowError, { wmp: meta(wmp), flow_id: flowId, code, message, data });
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* The wallet declines the sub-flow (the user said no, it does not trust the
|
|
308
|
+
* verifier, a value the signature must bind is missing): wmp.flow.error -31006
|
|
309
|
+
* with data {"reason": "rejected"}, the well-known reason of Core 6.2
|
|
310
|
+
* (profile 3.2.6). Any other error is a failure, not a refusal.
|
|
311
|
+
*/
|
|
312
|
+
export async function rejectSubFlow(peer, wmp, flowId, message = "declined") {
|
|
313
|
+
await failSubFlow(peer, wmp, flowId, ErrorCode.FlowError, message, { reason: "rejected" });
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* The wallet will not process the sub-flow's transaction_data: wmp.flow.error
|
|
317
|
+
* -31005 with data {"unsupported": "transaction_data"} (profile 2.3).
|
|
318
|
+
*/
|
|
319
|
+
export async function unsupportedTransactionData(peer, wmp, flowId) {
|
|
320
|
+
await failSubFlow(peer, wmp, flowId, ErrorCode.CapabilityNotSupported, "Capability not supported", transactionDataUnsupportedData());
|
|
321
|
+
}
|
|
322
|
+
function meta(wmp) {
|
|
323
|
+
return { version: wmp.version || VERSION, ...(wmp.session_id ? { session_id: wmp.session_id } : {}) };
|
|
324
|
+
}
|
|
325
|
+
/** A member that is really there: a non-empty string, array or object. */
|
|
326
|
+
function present(v) {
|
|
327
|
+
if (typeof v === "string")
|
|
328
|
+
return v !== "";
|
|
329
|
+
if (Array.isArray(v))
|
|
330
|
+
return v.length > 0;
|
|
331
|
+
// Only a non-empty object: undefined and null (dropped or nulled by JSON), booleans
|
|
332
|
+
// and numbers are not a presentation or an error report.
|
|
333
|
+
return typeof v === "object" && v !== null && Object.keys(v).length > 0;
|
|
334
|
+
}
|
|
335
|
+
/** Response modes in which the wallet encrypts the response (profile 7.7). */
|
|
336
|
+
const ENCRYPTED_RESPONSE_MODES = new Set(["direct_post.jwt", "dc_api.jwt"]);
|
|
337
|
+
/** The members a decrypt_credential_response result may carry: control members only. */
|
|
338
|
+
const DECRYPT_RESULT_MEMBERS = new Set(["credential_count", "transaction_id", "interval", "error"]);
|
|
339
|
+
/**
|
|
340
|
+
* Checks the result of a sign sub-flow before it is sent: the completion rules
|
|
341
|
+
* and, per action, what must never reach the orchestrator. A
|
|
342
|
+
* decrypt_credential_response result carries control members only
|
|
343
|
+
* (credential_count or transaction_id with an optional interval, or an error):
|
|
344
|
+
* the decrypted credentials and their metadata stay in the wallet (profile
|
|
345
|
+
* 3.1.5.1), so any other member, credentials and credential_metadata first,
|
|
346
|
+
* refuses the result.
|
|
347
|
+
*/
|
|
348
|
+
export function validateSignResult(action, result, responseMode) {
|
|
349
|
+
validateCompletionResult(result);
|
|
350
|
+
const r = result;
|
|
351
|
+
// A proof is a compact JWS: a missing, empty or non-string proof_jwt must not be sent as one.
|
|
352
|
+
if (action === "generate_proof" && "proof_jwt" in r && (typeof r.proof_jwt !== "string" || r.proof_jwt === "")) {
|
|
353
|
+
throw new CompletionResultError("proof_jwt is not a non-empty string");
|
|
354
|
+
}
|
|
355
|
+
if (action === "sign_presentation") {
|
|
356
|
+
// An encrypted response mode: the wallet builds and encrypts the response
|
|
357
|
+
// itself and answers with response_jwe; a plaintext vp_token would reach the
|
|
358
|
+
// orchestrator unprotected and no later refusal can undo that (profile 7.7).
|
|
359
|
+
// A plaintext mode has no use for a JWE the orchestrator cannot read.
|
|
360
|
+
const encrypted = responseMode !== undefined && ENCRYPTED_RESPONSE_MODES.has(responseMode);
|
|
361
|
+
if ("error" in r) {
|
|
362
|
+
// An error result carries no presentation in any mode, and no response_jwe
|
|
363
|
+
// (profile 7.7): it reports a refusal, there is nothing to encrypt. The
|
|
364
|
+
// error itself must be real: undefined/null/empty would serialize to a
|
|
365
|
+
// result that says nothing at all.
|
|
366
|
+
if (!present(r.error))
|
|
367
|
+
throw new CompletionResultError("error is empty");
|
|
368
|
+
if ("vp_token" in r || "response_jwe" in r)
|
|
369
|
+
throw new CompletionResultError("an error result carries neither vp_token nor response_jwe");
|
|
370
|
+
}
|
|
371
|
+
else if (encrypted) {
|
|
372
|
+
if ("vp_token" in r)
|
|
373
|
+
throw new CompletionResultError("vp_token in an encrypted response mode; the response must be a response_jwe");
|
|
374
|
+
if (!("response_jwe" in r))
|
|
375
|
+
throw new CompletionResultError("an encrypted response mode needs a response_jwe");
|
|
376
|
+
}
|
|
377
|
+
else {
|
|
378
|
+
// A plaintext (or unspecified) mode answers with the VP token (profile
|
|
379
|
+
// 3.2.5); a result without one would end the sub-flow with no presentation.
|
|
380
|
+
if ("response_jwe" in r)
|
|
381
|
+
throw new CompletionResultError("response_jwe in a response mode that is not encrypted");
|
|
382
|
+
if (!validVpToken(r.vp_token))
|
|
383
|
+
throw new CompletionResultError("a successful sign_presentation result carries a vp_token: a string, an array of strings, or an object of query id to arrays of strings");
|
|
384
|
+
}
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (action !== "decrypt_credential_response")
|
|
388
|
+
return;
|
|
389
|
+
for (const k of Object.keys(r)) {
|
|
390
|
+
if (!DECRYPT_RESULT_MEMBERS.has(k))
|
|
391
|
+
throw new CompletionResultError("decryption result carries a member outside the control set");
|
|
392
|
+
}
|
|
393
|
+
if (!("credential_count" in r) && !("transaction_id" in r) && !("error" in r)) {
|
|
394
|
+
throw new CompletionResultError("decryption result carries no credential_count, transaction_id or error");
|
|
395
|
+
}
|
|
396
|
+
if ("error" in r && !present(r.error))
|
|
397
|
+
throw new CompletionResultError("error is empty");
|
|
398
|
+
}
|
|
399
|
+
/** The sub-flow a wallet was asked to answer, with the means to answer it. A sub-flow ends once. */
|
|
400
|
+
export class SignFlow {
|
|
401
|
+
peer;
|
|
402
|
+
wmp;
|
|
403
|
+
flowId;
|
|
404
|
+
params;
|
|
405
|
+
done = false;
|
|
406
|
+
constructor(peer, wmp, flowId, params) {
|
|
407
|
+
this.peer = peer;
|
|
408
|
+
this.wmp = wmp;
|
|
409
|
+
this.flowId = flowId;
|
|
410
|
+
this.params = params;
|
|
411
|
+
}
|
|
412
|
+
/** True once a terminal message (complete, reject, fail) was sent for this sub-flow. */
|
|
413
|
+
get ended() {
|
|
414
|
+
return this.done;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Sends at most one terminal message. The sub-flow counts as ended from the
|
|
418
|
+
* moment the send starts (a concurrent second terminal is refused); if the
|
|
419
|
+
* message is not sent (a result that fails validation, a transport error) it
|
|
420
|
+
* counts as not ended, so the caller can still answer another way.
|
|
421
|
+
*/
|
|
422
|
+
async terminal(send) {
|
|
423
|
+
if (this.done)
|
|
424
|
+
throw new Error("sub-flow already ended");
|
|
425
|
+
this.done = true;
|
|
426
|
+
try {
|
|
427
|
+
await send();
|
|
428
|
+
}
|
|
429
|
+
catch (err) {
|
|
430
|
+
this.done = false;
|
|
431
|
+
throw err;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
/** Completes with the sign result (e.g. `{ proof_jwt }`, `{ response_jwe }`). */
|
|
435
|
+
complete(result) {
|
|
436
|
+
return this.terminal(() => completeSubFlow(this.peer, this.wmp, this.flowId, result, (r) => validateSignResult(this.params.action, r, effectiveResponseMode(this.params))));
|
|
437
|
+
}
|
|
438
|
+
/** Declines the sub-flow (-31006, reason rejected). */
|
|
439
|
+
reject(message) {
|
|
440
|
+
return this.terminal(() => rejectSubFlow(this.peer, this.wmp, this.flowId, message));
|
|
441
|
+
}
|
|
442
|
+
/** Fails the sub-flow without refusing it. */
|
|
443
|
+
fail(code, message, data) {
|
|
444
|
+
return this.terminal(() => failSubFlow(this.peer, this.wmp, this.flowId, code, message, data));
|
|
445
|
+
}
|
|
446
|
+
/** Cannot process the request's transaction_data (-31005). */
|
|
447
|
+
unsupportedTransactionData() {
|
|
448
|
+
return this.terminal(() => unsupportedTransactionData(this.peer, this.wmp, this.flowId));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
/** Validates the params of a match flow.start (-32602 when malformed). */
|
|
452
|
+
export function parseMatchStartParams(raw) {
|
|
453
|
+
if (!isObj(raw))
|
|
454
|
+
throw invalidParams("params is not an object");
|
|
455
|
+
if (typeof raw.parent_flow_id !== "string" || raw.parent_flow_id === "")
|
|
456
|
+
throw invalidParams("parent_flow_id is missing");
|
|
457
|
+
if (!isObj(raw.dcql_query))
|
|
458
|
+
throw invalidParams("dcql_query is missing");
|
|
459
|
+
for (const k of ["client_metadata", "verified_request"]) {
|
|
460
|
+
if (raw[k] !== undefined && !isObj(raw[k]))
|
|
461
|
+
throw invalidParams(`${k} is not an object`);
|
|
462
|
+
}
|
|
463
|
+
return { ...raw };
|
|
464
|
+
}
|
package/dist/transport.d.ts
CHANGED
|
@@ -11,6 +11,12 @@ export interface TransportEvents {
|
|
|
11
11
|
error: (err: Error) => void;
|
|
12
12
|
close: () => void;
|
|
13
13
|
open: () => void;
|
|
14
|
+
/**
|
|
15
|
+
* The server answered a reconnect with 410 (Transport Section 4.3.4): events
|
|
16
|
+
* were lost. The transport has already discarded its cursor and opened a new
|
|
17
|
+
* stream with none; the application (Peer) now resumes the session.
|
|
18
|
+
*/
|
|
19
|
+
gap: () => void;
|
|
14
20
|
}
|
|
15
21
|
export type TransportEventName = keyof TransportEvents;
|
|
16
22
|
/**
|
|
@@ -55,8 +61,13 @@ export declare class WebSocketTransport extends Emitter implements Transport {
|
|
|
55
61
|
export interface HttpSseTransportOptions {
|
|
56
62
|
/** Authorization header value (e.g., "Bearer <token>"). */
|
|
57
63
|
authorization?: string;
|
|
58
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* Initial SSE cursor (the ID of the last event already processed). It is
|
|
66
|
+
* sent on the first connectSSE() and replaces itself as events arrive.
|
|
67
|
+
*/
|
|
59
68
|
lastEventId?: string;
|
|
69
|
+
/** How many processed event IDs to remember for replay dedupe. Default: 4096. */
|
|
70
|
+
dedupeWindow?: number;
|
|
60
71
|
/** Custom fetch implementation (default: global fetch). */
|
|
61
72
|
fetch?: typeof globalThis.fetch;
|
|
62
73
|
/** Custom EventSource constructor (for polyfills that support headers). */
|
|
@@ -77,7 +88,19 @@ export declare class HttpSseTransport extends Emitter implements Transport {
|
|
|
77
88
|
private fetchFn;
|
|
78
89
|
private EventSourceCtor;
|
|
79
90
|
private closed;
|
|
91
|
+
private cursor?;
|
|
92
|
+
private seenIds;
|
|
93
|
+
private dedupeWindow;
|
|
94
|
+
private pendingGap;
|
|
95
|
+
/** The event stream was open when the session ended: reopen it for the next session once bound. */
|
|
96
|
+
private reopenOnBind;
|
|
80
97
|
constructor(rpcUrl: string, eventsUrl: string, opts?: HttpSseTransportOptions);
|
|
98
|
+
/**
|
|
99
|
+
* The ID of the last event this transport delivered (the SSE cursor), or
|
|
100
|
+
* undefined when none was received or the cursor was discarded after a gap.
|
|
101
|
+
* Event IDs are opaque: store and send them back, never parse or compare.
|
|
102
|
+
*/
|
|
103
|
+
get lastEventId(): string | undefined;
|
|
81
104
|
/**
|
|
82
105
|
* Update the authorization header (e.g., after token refresh).
|
|
83
106
|
* Takes effect on the next POST request.
|
|
@@ -89,17 +112,35 @@ export declare class HttpSseTransport extends Emitter implements Transport {
|
|
|
89
112
|
* - `session_id` query parameter on SSE connections
|
|
90
113
|
*/
|
|
91
114
|
setSessionId(sessionId: string): void;
|
|
115
|
+
/**
|
|
116
|
+
* Forget the bound session and its replay state and close the event stream: the
|
|
117
|
+
* session ended. A later session starts clean (no stale Wmp-Session-Id, cursor
|
|
118
|
+
* or seen ids).
|
|
119
|
+
*/
|
|
120
|
+
clearSession(): void;
|
|
92
121
|
/**
|
|
93
122
|
* Connect the SSE stream. Call this after constructing the transport.
|
|
94
123
|
* Separated from the constructor so callers can register listeners first.
|
|
124
|
+
* Resumes from the transport's own cursor unless `lastEventId` is given.
|
|
95
125
|
*/
|
|
96
126
|
connectSSE(lastEventId?: string): void;
|
|
97
127
|
/**
|
|
98
|
-
* Reconnect the SSE stream with the current authorization/session state
|
|
99
|
-
* Useful after calling setAuthorization.
|
|
128
|
+
* Reconnect the SSE stream with the current authorization/session state
|
|
129
|
+
* and the recorded cursor. Useful after calling setAuthorization.
|
|
100
130
|
*/
|
|
101
131
|
reconnectSSE(lastEventId?: string): void;
|
|
102
|
-
private
|
|
132
|
+
private streamHeaders;
|
|
133
|
+
private streamUrl;
|
|
134
|
+
private openStream;
|
|
135
|
+
/**
|
|
136
|
+
* Handles one SSE event: an event whose ID was already processed (a replay
|
|
137
|
+
* after a reconnect) is dropped; otherwise it is delivered and then its ID
|
|
138
|
+
* becomes the cursor (Transport Section 4.3.2).
|
|
139
|
+
*/
|
|
140
|
+
private onSseEvent;
|
|
141
|
+
private recordEventId;
|
|
142
|
+
/** Probes the stream URL for a 410 after the EventSource gave up with `cursor`. */
|
|
143
|
+
private checkGap;
|
|
103
144
|
send(msg: Message): Promise<void>;
|
|
104
145
|
close(): void;
|
|
105
146
|
on<K extends TransportEventName>(event: K, listener: TransportEvents[K]): void;
|