@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/transport.js CHANGED
@@ -93,6 +93,12 @@ export class HttpSseTransport extends Emitter {
93
93
  fetchFn;
94
94
  EventSourceCtor;
95
95
  closed = false;
96
+ cursor;
97
+ seenIds = new Set();
98
+ dedupeWindow;
99
+ pendingGap = false;
100
+ /** The event stream was open when the session ended: reopen it for the next session once bound. */
101
+ reopenOnBind = false;
96
102
  constructor(rpcUrl, eventsUrl, opts) {
97
103
  super();
98
104
  this.rpcUrl = rpcUrl;
@@ -100,6 +106,16 @@ export class HttpSseTransport extends Emitter {
100
106
  this.authorization = opts?.authorization;
101
107
  this.fetchFn = opts?.fetch ?? globalThis.fetch.bind(globalThis);
102
108
  this.EventSourceCtor = opts?.EventSource ?? globalThis.EventSource;
109
+ this.cursor = opts?.lastEventId || undefined;
110
+ this.dedupeWindow = opts?.dedupeWindow ?? 4096;
111
+ }
112
+ /**
113
+ * The ID of the last event this transport delivered (the SSE cursor), or
114
+ * undefined when none was received or the cursor was discarded after a gap.
115
+ * Event IDs are opaque: store and send them back, never parse or compare.
116
+ */
117
+ get lastEventId() {
118
+ return this.cursor;
103
119
  }
104
120
  /**
105
121
  * Update the authorization header (e.g., after token refresh).
@@ -114,63 +130,198 @@ export class HttpSseTransport extends Emitter {
114
130
  * - `session_id` query parameter on SSE connections
115
131
  */
116
132
  setSessionId(sessionId) {
133
+ let reopen = this.reopenOnBind;
134
+ if (this.sessionId !== sessionId) {
135
+ const hadSession = this.sessionId !== undefined;
136
+ // A stream is tied to the session it was opened for (its events are ignored
137
+ // once that is no longer the bound one), so a stream that is open (also one
138
+ // opened before the first binding) is closed and reopened for the new session.
139
+ if (this.eventSource !== null) {
140
+ reopen = true;
141
+ this.eventSource.close();
142
+ this.eventSource = null;
143
+ }
144
+ if (hadSession) {
145
+ // Event IDs are unique only within a session: another session's cursor
146
+ // would draw a 410 and its seen IDs could swallow this session's events.
147
+ // (The first binding keeps a cursor the transport was seeded with.)
148
+ this.cursor = undefined;
149
+ this.seenIds.clear();
150
+ this.pendingGap = false;
151
+ }
152
+ }
117
153
  this.sessionId = sessionId;
154
+ if (reopen && !this.closed && this.eventSource === null) {
155
+ this.reopenOnBind = false;
156
+ this.openStream(this.cursor);
157
+ }
158
+ }
159
+ /**
160
+ * Forget the bound session and its replay state and close the event stream: the
161
+ * session ended. A later session starts clean (no stale Wmp-Session-Id, cursor
162
+ * or seen ids).
163
+ */
164
+ clearSession() {
165
+ // If a stream was open it is reopened when the next session is bound.
166
+ this.reopenOnBind = this.reopenOnBind || this.eventSource !== null;
167
+ this.sessionId = undefined;
168
+ this.cursor = undefined;
169
+ this.seenIds.clear();
170
+ this.pendingGap = false;
171
+ this.eventSource?.close();
172
+ this.eventSource = null;
118
173
  }
119
174
  /**
120
175
  * Connect the SSE stream. Call this after constructing the transport.
121
176
  * Separated from the constructor so callers can register listeners first.
177
+ * Resumes from the transport's own cursor unless `lastEventId` is given.
122
178
  */
123
179
  connectSSE(lastEventId) {
124
- this.eventSource?.close();
125
- this.eventSource = null;
126
- this.setupEventSource(lastEventId);
180
+ if (lastEventId !== undefined)
181
+ this.cursor = lastEventId || undefined;
182
+ this.openStream(this.cursor);
127
183
  }
128
184
  /**
129
- * Reconnect the SSE stream with the current authorization/session state.
130
- * Useful after calling setAuthorization.
185
+ * Reconnect the SSE stream with the current authorization/session state
186
+ * and the recorded cursor. Useful after calling setAuthorization.
131
187
  */
132
188
  reconnectSSE(lastEventId) {
133
189
  this.connectSSE(lastEventId);
134
190
  }
135
- setupEventSource(lastEventId) {
136
- // Build the SSE URL with session_id (required for tenant routing)
137
- // and optional lastEventId for event replay.
138
- let url = this.eventsUrl;
139
- if (this.sessionId) {
140
- const sep = url.includes("?") ? "&" : "?";
141
- url += `${sep}session_id=${encodeURIComponent(this.sessionId)}`;
142
- }
143
- if (lastEventId) {
144
- const sep = url.includes("?") ? "&" : "?";
145
- url += `${sep}lastEventId=${encodeURIComponent(lastEventId)}`;
146
- }
147
- this.eventSource = new this.EventSourceCtor(url);
148
- this.eventSource.onopen = () => this.emit("open");
149
- this.eventSource.onerror = () => {
150
- if (!this.closed) {
151
- this.emit("error", new Error("SSE connection error"));
191
+ streamHeaders(cursor) {
192
+ const h = {};
193
+ if (this.authorization)
194
+ h["Authorization"] = this.authorization;
195
+ if (cursor)
196
+ h["Last-Event-ID"] = cursor;
197
+ return h;
198
+ }
199
+ streamUrl(cursor) {
200
+ // session_id (required for tenant routing) and the cursor. The cursor goes
201
+ // as last_event_id (Transport Section 4.3.3) and, for servers that predate
202
+ // that name, as lastEventId. Only the query string is touched: a relative
203
+ // URL ("events", "/x", "//host/x") must resolve exactly as it was supplied.
204
+ const hashAt = this.eventsUrl.indexOf("#");
205
+ const hash = hashAt < 0 ? "" : this.eventsUrl.slice(hashAt);
206
+ const noHash = hashAt < 0 ? this.eventsUrl : this.eventsUrl.slice(0, hashAt);
207
+ const qAt = noHash.indexOf("?");
208
+ const base = qAt < 0 ? noHash : noHash.slice(0, qAt);
209
+ const params = new URLSearchParams(qAt < 0 ? "" : noHash.slice(qAt + 1));
210
+ if (this.sessionId)
211
+ params.set("session_id", this.sessionId);
212
+ // The cursor names are reserved: whatever the supplied URL carried, only the
213
+ // current cursor (none after a 410) goes out, or the recovery request would
214
+ // draw the same 410 again.
215
+ params.delete("last_event_id");
216
+ params.delete("lastEventId");
217
+ if (cursor) {
218
+ params.set("last_event_id", cursor);
219
+ params.set("lastEventId", cursor);
220
+ }
221
+ const query = params.toString();
222
+ return base + (query ? `?${query}` : "") + hash;
223
+ }
224
+ openStream(cursor) {
225
+ this.eventSource?.close();
226
+ this.eventSource = null;
227
+ const headers = this.streamHeaders(cursor);
228
+ // Polyfills that can set request headers read `headers` from the init
229
+ // object; a native EventSource ignores it.
230
+ const init = Object.keys(headers).length > 0 ? { headers } : undefined;
231
+ const es = new this.EventSourceCtor(this.streamUrl(cursor), init);
232
+ this.eventSource = es;
233
+ // The session this stream belongs to: once it is no longer the bound one (or
234
+ // the stream was replaced or closed) nothing it delivers may touch the
235
+ // cursor, the seen ids or the application.
236
+ const session = this.sessionId;
237
+ es.onopen = () => {
238
+ if (this.eventSource !== es)
239
+ return;
240
+ this.emit("open");
241
+ if (this.pendingGap) {
242
+ this.pendingGap = false;
243
+ this.emit("gap");
152
244
  }
153
245
  };
154
- // WMP events use the "wmp" event type per the spec.
155
- this.eventSource.addEventListener("wmp", (ev) => {
156
- try {
157
- const msg = decodeMessage(ev.data, { maxSize: 4 * 1024 * 1024 });
158
- this.emit("message", msg);
159
- }
160
- catch (err) {
161
- this.emit("error", err instanceof Error ? err : new Error(String(err)));
162
- }
163
- });
164
- // Also handle default "message" events for compatibility.
165
- this.eventSource.onmessage = (ev) => {
166
- try {
167
- const msg = decodeMessage(ev.data, { maxSize: 4 * 1024 * 1024 });
168
- this.emit("message", msg);
169
- }
170
- catch (err) {
171
- this.emit("error", err instanceof Error ? err : new Error(String(err)));
246
+ es.onerror = () => {
247
+ if (this.closed || this.eventSource !== es)
248
+ return;
249
+ // A closed stream with a cursor may be the 410 of a gap; the EventSource
250
+ // API does not expose the status, so ask.
251
+ if (es.readyState === 2 /* CLOSED */ && this.cursor) {
252
+ void this.checkGap(es, this.cursor);
253
+ return;
172
254
  }
255
+ this.emit("error", new Error("SSE connection error"));
173
256
  };
257
+ // WMP events use the "wmp" event type per the spec.
258
+ es.addEventListener("wmp", (ev) => this.onSseEvent(ev, es, session));
259
+ // Also handle default "message" events for compatibility.
260
+ es.onmessage = (ev) => this.onSseEvent(ev, es, session);
261
+ }
262
+ /**
263
+ * Handles one SSE event: an event whose ID was already processed (a replay
264
+ * after a reconnect) is dropped; otherwise it is delivered and then its ID
265
+ * becomes the cursor (Transport Section 4.3.2).
266
+ */
267
+ onSseEvent(ev, source, session) {
268
+ const current = () => this.eventSource === source && this.sessionId === session;
269
+ if (!current())
270
+ return; // a stale stream or session
271
+ const id = typeof ev.lastEventId === "string" && ev.lastEventId !== "" ? ev.lastEventId : undefined;
272
+ if (id !== undefined && this.seenIds.has(id))
273
+ return;
274
+ try {
275
+ this.emit("message", decodeMessage(ev.data, { maxSize: 4 * 1024 * 1024 }));
276
+ }
277
+ catch (err) {
278
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
279
+ }
280
+ finally {
281
+ // Handling the message may have ended the session (a session.close event):
282
+ // its id must not become the next session's cursor.
283
+ if (id !== undefined && current())
284
+ this.recordEventId(id);
285
+ }
286
+ }
287
+ recordEventId(id) {
288
+ this.cursor = id;
289
+ this.seenIds.add(id);
290
+ if (this.seenIds.size > this.dedupeWindow) {
291
+ // Sets iterate in insertion order: drop the oldest.
292
+ this.seenIds.delete(this.seenIds.values().next().value);
293
+ }
294
+ }
295
+ /** Probes the stream URL for a 410 after the EventSource gave up with `cursor`. */
296
+ async checkGap(failed, cursor) {
297
+ // The session the stream (and so the probe) belongs to: a 410 for a session
298
+ // that is no longer the bound one says nothing about the current session.
299
+ const session = this.sessionId;
300
+ let status;
301
+ try {
302
+ const abort = new AbortController();
303
+ const resp = await this.fetchFn(this.streamUrl(cursor), {
304
+ headers: { ...this.streamHeaders(cursor), Accept: "text/event-stream" },
305
+ signal: abort.signal,
306
+ });
307
+ status = resp.status;
308
+ abort.abort(); // only the status matters; do not hold the stream open
309
+ }
310
+ catch {
311
+ status = undefined;
312
+ }
313
+ if (this.closed || this.eventSource !== failed || this.sessionId !== session)
314
+ return;
315
+ if (status === 410) {
316
+ // Discard the cursor (never reconnect with it again) and open a stream
317
+ // with none; "gap" is emitted once it is open, so the resume's re-sent
318
+ // notifications have a connection to arrive on.
319
+ this.cursor = undefined;
320
+ this.pendingGap = true;
321
+ this.openStream(undefined);
322
+ return;
323
+ }
324
+ this.emit("error", new Error("SSE connection error"));
174
325
  }
175
326
  async send(msg) {
176
327
  if (this.closed) {
@@ -182,8 +333,24 @@ export class HttpSseTransport extends Emitter {
182
333
  if (this.authorization) {
183
334
  headers["Authorization"] = this.authorization;
184
335
  }
185
- if (this.sessionId) {
186
- headers["Wmp-Session-Id"] = this.sessionId;
336
+ // A session.create must not carry a session id (Transport 4.3.1: the server
337
+ // assigns it and refuses a request that names one). The binding itself stays,
338
+ // in case the create fails and the old session is still the one in use.
339
+ const method = msg.method;
340
+ let routeId = this.sessionId;
341
+ if (method === "wmp.session.create") {
342
+ routeId = undefined;
343
+ }
344
+ else if (method === "wmp.session.resume") {
345
+ // A resume is addressed to the session it asks for, which may not be the one
346
+ // currently bound (the binding changes only if the resume succeeds): header
347
+ // and body must name the same session.
348
+ const asked = msg.params?.session_id;
349
+ if (typeof asked === "string" && asked !== "")
350
+ routeId = asked;
351
+ }
352
+ if (routeId) {
353
+ headers["Wmp-Session-Id"] = routeId;
187
354
  }
188
355
  const resp = await this.fetchFn(this.rpcUrl, {
189
356
  method: "POST",
package/dist/types.d.ts CHANGED
@@ -115,6 +115,8 @@ export declare const ErrorCode: {
115
115
  readonly PolicyUnsupported: -31018;
116
116
  /** Core §3.8.2: the decrypted plaintext does not match the sender's `plaintext_hash` commitment (§5.2.1). The message MUST NOT be acknowledged. */
117
117
  readonly PlaintextHashMismatch: -31019;
118
+ /** Core §3.8: the issuer of an OID4VCI offer is not registered to issue the credential configurations it offers (OpenID4x §3.1.6). */
119
+ readonly IssuerNotEntitled: -31020;
118
120
  };
119
121
  export interface AuthObject {
120
122
  type: string;
package/dist/types.js CHANGED
@@ -56,6 +56,8 @@ export const ErrorCode = {
56
56
  PolicyUnsupported: -31018,
57
57
  /** Core §3.8.2: the decrypted plaintext does not match the sender's `plaintext_hash` commitment (§5.2.1). The message MUST NOT be acknowledged. */
58
58
  PlaintextHashMismatch: -31019,
59
+ /** Core §3.8: the issuer of an OID4VCI offer is not registered to issue the credential configurations it offers (OpenID4x §3.1.6). */
60
+ IssuerNotEntitled: -31020,
59
61
  };
60
62
  /** Authentication type constants. */
61
63
  export const AuthType = {
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Protocol version negotiation (Core Section 2.2.2) — mirrors
3
+ * go-wmp/pkg/wmp/version.go (v0.11.0).
4
+ */
5
+ import { WMPError } from "./jsonrpc.js";
6
+ /** Versions this library speaks. */
7
+ export declare const SUPPORTED_VERSIONS: readonly string[];
8
+ /**
9
+ * Parses a "MAJOR.MINOR" version. Both parts are plain decimal digits without
10
+ * leading zeros; signs, spaces, empty parts and extra components are rejected.
11
+ */
12
+ export declare function parseVersion(v: unknown): {
13
+ major: number;
14
+ minor: number;
15
+ } | undefined;
16
+ /**
17
+ * Returns the highest version in `supported` that has the same MAJOR as
18
+ * `offered` and a MINOR that is not greater than offered's, as the entry from
19
+ * `supported`, unmodified (minors compare numerically: "0.10" is above "0.9").
20
+ * Undefined when `offered` is not a valid version or nothing is compatible; the
21
+ * caller then rejects with {@link versionRejection}. Unparseable entries in
22
+ * `supported` are ignored.
23
+ */
24
+ export declare function negotiateVersion(offered: string, supported: readonly string[]): string | undefined;
25
+ /**
26
+ * The error for an offered version that {@link negotiateVersion} could not
27
+ * match: -32602 when it is not a valid "MAJOR.MINOR" string (including an
28
+ * absent one), else -31013 carrying supported_versions (Core 2.2.2 and 3.8).
29
+ */
30
+ export declare function versionRejection(offered: unknown, supported: readonly string[]): WMPError;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Protocol version negotiation (Core Section 2.2.2) — mirrors
3
+ * go-wmp/pkg/wmp/version.go (v0.11.0).
4
+ */
5
+ import { WMPError } from "./jsonrpc.js";
6
+ import { ErrorCode } from "./types.js";
7
+ /** Versions this library speaks. */
8
+ export const SUPPORTED_VERSIONS = ["0.1"];
9
+ /** One decimal component: digits only, no leading zero ("0.01" is malformed), at most 6 digits. */
10
+ function parsePart(s) {
11
+ if (s === "" || s.length > 6 || (s.length > 1 && s[0] === "0"))
12
+ return undefined;
13
+ return /^[0-9]+$/.test(s) ? Number(s) : undefined;
14
+ }
15
+ /**
16
+ * Parses a "MAJOR.MINOR" version. Both parts are plain decimal digits without
17
+ * leading zeros; signs, spaces, empty parts and extra components are rejected.
18
+ */
19
+ export function parseVersion(v) {
20
+ if (typeof v !== "string")
21
+ return undefined;
22
+ const i = v.indexOf(".");
23
+ if (i < 0)
24
+ return undefined;
25
+ const major = parsePart(v.slice(0, i));
26
+ const minor = parsePart(v.slice(i + 1));
27
+ return major === undefined || minor === undefined ? undefined : { major, minor };
28
+ }
29
+ /**
30
+ * Returns the highest version in `supported` that has the same MAJOR as
31
+ * `offered` and a MINOR that is not greater than offered's, as the entry from
32
+ * `supported`, unmodified (minors compare numerically: "0.10" is above "0.9").
33
+ * Undefined when `offered` is not a valid version or nothing is compatible; the
34
+ * caller then rejects with {@link versionRejection}. Unparseable entries in
35
+ * `supported` are ignored.
36
+ */
37
+ export function negotiateVersion(offered, supported) {
38
+ const off = parseVersion(offered);
39
+ if (!off)
40
+ return undefined;
41
+ let best = -1;
42
+ let selected;
43
+ for (const s of supported) {
44
+ const v = parseVersion(s);
45
+ if (!v || v.major !== off.major || v.minor > off.minor || v.minor <= best)
46
+ continue;
47
+ best = v.minor;
48
+ selected = s;
49
+ }
50
+ return selected;
51
+ }
52
+ /**
53
+ * The error for an offered version that {@link negotiateVersion} could not
54
+ * match: -32602 when it is not a valid "MAJOR.MINOR" string (including an
55
+ * absent one), else -31013 carrying supported_versions (Core 2.2.2 and 3.8).
56
+ */
57
+ export function versionRejection(offered, supported) {
58
+ if (!parseVersion(offered))
59
+ return new WMPError(ErrorCode.InvalidParams, "Invalid params");
60
+ return new WMPError(ErrorCode.VersionNotSupported, "Version not supported", { supported_versions: [...supported] });
61
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sirosfoundation/wmp-js",
3
- "version": "0.5.2",
3
+ "version": "0.7.0",
4
4
  "description": "Wallet Messaging Protocol (WMP) client library — JSON-RPC 2.0 over WebSocket and HTTP+SSE",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -26,9 +26,9 @@
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",
29
- "@vitest/coverage-v8": "^4.1.10",
29
+ "@vitest/coverage-v8": "^5.0.5",
30
30
  "typescript": "^7.0.2",
31
- "vitest": "^4.1.9"
31
+ "vitest": "^5.0.5"
32
32
  },
33
33
  "license": "BSD-2-Clause",
34
34
  "repository": {