@sirosfoundation/wmp-js 0.2.1 → 0.5.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/peer.js CHANGED
@@ -21,10 +21,14 @@ export class Peer {
21
21
  negotiatedVersion;
22
22
  resumptionToken;
23
23
  closed = false;
24
+ validator;
25
+ authorize;
24
26
  constructor(transport, opts) {
25
27
  this.transport = transport;
26
28
  this.handler = opts?.handler ?? {};
27
29
  this.callTimeout = opts?.callTimeout ?? 30_000;
30
+ this.validator = opts?.validator;
31
+ this.authorize = opts?.authorize;
28
32
  // Wire up transport events.
29
33
  this.transport.on("message", (msg) => this.dispatch(msg));
30
34
  this.transport.on("error", (err) => this.onTransportError(err));
@@ -79,16 +83,18 @@ export class Peer {
79
83
  security: opts.security ?? { mode: "tls" },
80
84
  ttl: opts.ttl,
81
85
  auth: opts.auth,
86
+ invitation_nonce: opts.invitationNonce,
82
87
  };
83
88
  const result = await this.call(Method.SessionCreate, params);
84
- if (result.wmp?.session_id) {
85
- this.sessionId = result.wmp.session_id;
86
- // Propagate session ID to transport for header/URL binding.
87
- this.bindSessionToTransport(result.wmp.session_id);
89
+ if (!result.wmp?.session_id || typeof result.wmp.session_id !== "string") {
90
+ throw new WMPError(ErrorCode.SessionNotFound, "session.create response missing session_id");
88
91
  }
89
- if (result.wmp?.version) {
90
- this.negotiatedVersion = result.wmp.version;
92
+ if (result.wmp.version && result.wmp.version !== VERSION) {
93
+ throw new WMPError(ErrorCode.VersionNotSupported, `negotiated version ${result.wmp.version} is not supported`);
91
94
  }
95
+ this.sessionId = result.wmp.session_id;
96
+ this.bindSessionToTransport(result.wmp.session_id);
97
+ this.negotiatedVersion = result.wmp.version ?? VERSION;
92
98
  if (result.resumption_token) {
93
99
  this.resumptionToken = result.resumption_token;
94
100
  }
@@ -251,13 +257,22 @@ export class Peer {
251
257
  }
252
258
  }
253
259
  handleRequest(req) {
260
+ const dispatch = async () => {
261
+ if (this.authorize) {
262
+ const allowed = await this.authorize(req.method, req.params);
263
+ if (!allowed) {
264
+ throw new WMPError(ErrorCode.NotAuthorized, `Not authorized to call ${req.method}`);
265
+ }
266
+ }
267
+ return this.dispatchMethod(req.method, req.params);
268
+ };
254
269
  if (isNotification(req)) {
255
- this.dispatchMethod(req.method, req.params).catch(() => {
270
+ dispatch().catch(() => {
256
271
  /* notifications get no error response */
257
272
  });
258
273
  }
259
274
  else {
260
- this.dispatchMethod(req.method, req.params)
275
+ dispatch()
261
276
  .then((result) => {
262
277
  const resp = createResponse(req.id, result);
263
278
  return this.transport.send(resp);
@@ -270,6 +285,13 @@ export class Peer {
270
285
  }
271
286
  }
272
287
  async dispatchMethod(method, params) {
288
+ if (this.validator) {
289
+ const errors = this.validator.validateMethod(method, params);
290
+ if (errors) {
291
+ const detail = errors.map((e) => `${e.path}: ${e.message}`).join("; ");
292
+ throw new WMPError(ErrorCode.InvalidParams, `Invalid params for ${method}: ${detail}`);
293
+ }
294
+ }
273
295
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- JSON-RPC params are untyped
274
296
  const p = params;
275
297
  switch (method) {
@@ -279,11 +301,53 @@ export class Peer {
279
301
  return this.handler.onSessionCreate(p);
280
302
  }
281
303
  break;
304
+ case Method.SessionResume:
305
+ if (this.handler.onSessionResume) {
306
+ return this.handler.onSessionResume(p);
307
+ }
308
+ break;
282
309
  case Method.SessionClose:
283
310
  if (this.handler.onSessionClose) {
284
311
  this.handler.onSessionClose(p);
285
312
  }
286
313
  return undefined;
314
+ case Method.SessionAuthenticate:
315
+ if (this.handler.onSessionAuthenticate) {
316
+ return this.handler.onSessionAuthenticate(p);
317
+ }
318
+ break;
319
+ // Messages
320
+ case Method.MessageDeliver:
321
+ if (this.handler.onMessageDeliver) {
322
+ this.handler.onMessageDeliver(p);
323
+ }
324
+ return undefined;
325
+ case Method.MessageAck:
326
+ if (this.handler.onMessageAck) {
327
+ this.handler.onMessageAck(p);
328
+ }
329
+ return undefined;
330
+ case Method.MessagePoll:
331
+ if (this.handler.onMessagePoll) {
332
+ return this.handler.onMessagePoll(p);
333
+ }
334
+ break;
335
+ case Method.MessageStatus:
336
+ if (this.handler.onMessageStatus) {
337
+ this.handler.onMessageStatus(p);
338
+ }
339
+ return undefined;
340
+ // Capabilities
341
+ case Method.CapabilityUpdate:
342
+ if (this.handler.onCapabilityUpdate) {
343
+ return this.handler.onCapabilityUpdate(p);
344
+ }
345
+ break;
346
+ case Method.CapabilityList:
347
+ if (this.handler.onCapabilityList) {
348
+ return this.handler.onCapabilityList(p);
349
+ }
350
+ break;
287
351
  // Flows — delegate to profile FlowHandlers first, then handler.
288
352
  case Method.FlowStart: {
289
353
  const fh = this.registry.getFlowHandler(p.flow_type);
@@ -409,8 +473,12 @@ function toRPCError(err) {
409
473
  if (err instanceof WMPError) {
410
474
  return { code: err.code, message: err.message, data: err.data };
411
475
  }
476
+ // Sanitize unexpected internal errors to avoid leaking implementation details.
477
+ if (typeof console !== "undefined" && console.error) {
478
+ console.error("Peer handler internal error:", err);
479
+ }
412
480
  return {
413
481
  code: ErrorCode.InternalError,
414
- message: err instanceof Error ? err.message : String(err),
482
+ message: "Internal error",
415
483
  };
416
484
  }
package/dist/schema.d.ts CHANGED
@@ -28,5 +28,6 @@ export interface Validator {
28
28
  * Create a schema validator by loading schemas from the filesystem.
29
29
  *
30
30
  * @param schemaDir Path to the wmp/schema directory containing the JSON Schema files.
31
+ * @param strict When true, unknown methods/responses are reported as validation errors.
31
32
  */
32
- export declare function createValidator(schemaDir: string): Validator;
33
+ export declare function createValidator(schemaDir: string, strict?: boolean): Validator;
package/dist/schema.js CHANGED
@@ -38,8 +38,9 @@ const RESPONSE_SCHEMAS = {
38
38
  * Create a schema validator by loading schemas from the filesystem.
39
39
  *
40
40
  * @param schemaDir Path to the wmp/schema directory containing the JSON Schema files.
41
+ * @param strict When true, unknown methods/responses are reported as validation errors.
41
42
  */
42
- export function createValidator(schemaDir) {
43
+ export function createValidator(schemaDir, strict = false) {
43
44
  const ajv = new Ajv2020({
44
45
  strict: false,
45
46
  allErrors: true,
@@ -89,14 +90,20 @@ export function createValidator(schemaDir) {
89
90
  return {
90
91
  validateMethod(method, message) {
91
92
  const schema = METHOD_SCHEMAS[method];
92
- if (!schema)
93
- return null; // No schema for this method.
93
+ if (!schema) {
94
+ return strict
95
+ ? [{ path: "/", message: `No schema defined for method ${method}` }]
96
+ : null;
97
+ }
94
98
  return validate(schema, message);
95
99
  },
96
100
  validateResponse(method, message) {
97
101
  const schema = RESPONSE_SCHEMAS[method];
98
- if (!schema)
99
- return null;
102
+ if (!schema) {
103
+ return strict
104
+ ? [{ path: "/", message: `No response schema defined for method ${method}` }]
105
+ : null;
106
+ }
100
107
  return validate(schema, message);
101
108
  },
102
109
  validateMetadata(metadata) {
@@ -0,0 +1,33 @@
1
+ /**
2
+ * SessionStore — server-side session persistence interface.
3
+ * Mirrors go-wmp/pkg/wmp/session.go for alignment.
4
+ */
5
+ import type { Capabilities, SecurityMode } from "./types.js";
6
+ export interface Session {
7
+ id: string;
8
+ participants: string[];
9
+ capabilities: Capabilities;
10
+ security: SecurityMode;
11
+ createdAt: string;
12
+ expiresAt?: string;
13
+ metadata?: Record<string, unknown>;
14
+ }
15
+ export interface SessionStore {
16
+ create(session: Session): Promise<void>;
17
+ get(id: string): Promise<Session | undefined>;
18
+ update(session: Session): Promise<void>;
19
+ delete(id: string): Promise<void>;
20
+ cleanup(): Promise<number>;
21
+ }
22
+ /**
23
+ * In-memory SessionStore — suitable for development and testing.
24
+ */
25
+ export declare class MemorySessionStore implements SessionStore {
26
+ private sessions;
27
+ create(session: Session): Promise<void>;
28
+ get(id: string): Promise<Session | undefined>;
29
+ update(session: Session): Promise<void>;
30
+ delete(id: string): Promise<void>;
31
+ cleanup(): Promise<number>;
32
+ get size(): number;
33
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * SessionStore — server-side session persistence interface.
3
+ * Mirrors go-wmp/pkg/wmp/session.go for alignment.
4
+ */
5
+ /**
6
+ * In-memory SessionStore — suitable for development and testing.
7
+ */
8
+ export class MemorySessionStore {
9
+ sessions = new Map();
10
+ async create(session) {
11
+ this.sessions.set(session.id, { ...session });
12
+ }
13
+ async get(id) {
14
+ return this.sessions.get(id);
15
+ }
16
+ async update(session) {
17
+ this.sessions.set(session.id, { ...session });
18
+ }
19
+ async delete(id) {
20
+ this.sessions.delete(id);
21
+ }
22
+ async cleanup() {
23
+ const now = new Date().toISOString();
24
+ let count = 0;
25
+ for (const [id, session] of this.sessions) {
26
+ if (session.expiresAt && session.expiresAt < now) {
27
+ this.sessions.delete(id);
28
+ count++;
29
+ }
30
+ }
31
+ return count;
32
+ }
33
+ get size() {
34
+ return this.sessions.size;
35
+ }
36
+ }
@@ -37,6 +37,8 @@ declare class Emitter {
37
37
  export interface WebSocketTransportOptions {
38
38
  /** WebSocket subprotocol. Default: "wmp.v1" */
39
39
  protocols?: string | string[];
40
+ /** Allow unencrypted ws:// URLs. Default: false. */
41
+ allowInsecure?: boolean;
40
42
  }
41
43
  /**
42
44
  * WebSocket transport — bidirectional, persistent connection.
@@ -92,6 +94,12 @@ export declare class HttpSseTransport extends Emitter implements Transport {
92
94
  * Separated from the constructor so callers can register listeners first.
93
95
  */
94
96
  connectSSE(lastEventId?: string): void;
97
+ /**
98
+ * Reconnect the SSE stream with the current authorization/session state.
99
+ * Useful after calling setAuthorization.
100
+ */
101
+ reconnectSSE(lastEventId?: string): void;
102
+ private setupEventSource;
95
103
  send(msg: Message): Promise<void>;
96
104
  close(): void;
97
105
  on<K extends TransportEventName>(event: K, listener: TransportEvents[K]): void;
package/dist/transport.js CHANGED
@@ -32,6 +32,19 @@ export class WebSocketTransport extends Emitter {
32
32
  constructor(url, opts) {
33
33
  super();
34
34
  const protocols = opts?.protocols ?? "wmp.v1";
35
+ let parsed;
36
+ try {
37
+ parsed = new URL(url);
38
+ }
39
+ catch {
40
+ throw new Error("Invalid WebSocket URL");
41
+ }
42
+ if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:") {
43
+ throw new Error(`Invalid WebSocket URL scheme: ${parsed.protocol}. Use ws:// or wss://`);
44
+ }
45
+ if (parsed.protocol === "ws:" && !opts?.allowInsecure) {
46
+ throw new Error("Unencrypted ws:// WebSocket URLs are not allowed unless allowInsecure is true");
47
+ }
35
48
  this.ws = new WebSocket(url, protocols);
36
49
  this.ws.onopen = () => this.emit("open");
37
50
  this.ws.onclose = () => this.emit("close");
@@ -41,7 +54,7 @@ export class WebSocketTransport extends Emitter {
41
54
  };
42
55
  this.ws.onmessage = (ev) => {
43
56
  try {
44
- const msg = decodeMessage(String(ev.data));
57
+ const msg = decodeMessage(String(ev.data), { maxSize: 4 * 1024 * 1024 });
45
58
  this.emit("message", msg);
46
59
  }
47
60
  catch (err) {
@@ -108,6 +121,18 @@ export class HttpSseTransport extends Emitter {
108
121
  * Separated from the constructor so callers can register listeners first.
109
122
  */
110
123
  connectSSE(lastEventId) {
124
+ this.eventSource?.close();
125
+ this.eventSource = null;
126
+ this.setupEventSource(lastEventId);
127
+ }
128
+ /**
129
+ * Reconnect the SSE stream with the current authorization/session state.
130
+ * Useful after calling setAuthorization.
131
+ */
132
+ reconnectSSE(lastEventId) {
133
+ this.connectSSE(lastEventId);
134
+ }
135
+ setupEventSource(lastEventId) {
111
136
  // Build the SSE URL with session_id (required for tenant routing)
112
137
  // and optional lastEventId for event replay.
113
138
  let url = this.eventsUrl;
@@ -129,7 +154,7 @@ export class HttpSseTransport extends Emitter {
129
154
  // WMP events use the "wmp" event type per the spec.
130
155
  this.eventSource.addEventListener("wmp", (ev) => {
131
156
  try {
132
- const msg = decodeMessage(ev.data);
157
+ const msg = decodeMessage(ev.data, { maxSize: 4 * 1024 * 1024 });
133
158
  this.emit("message", msg);
134
159
  }
135
160
  catch (err) {
@@ -139,7 +164,7 @@ export class HttpSseTransport extends Emitter {
139
164
  // Also handle default "message" events for compatibility.
140
165
  this.eventSource.onmessage = (ev) => {
141
166
  try {
142
- const msg = decodeMessage(ev.data);
167
+ const msg = decodeMessage(ev.data, { maxSize: 4 * 1024 * 1024 });
143
168
  this.emit("message", msg);
144
169
  }
145
170
  catch (err) {
package/dist/types.d.ts CHANGED
@@ -15,6 +15,8 @@ export interface Metadata {
15
15
  identity_assertions?: IdentityAssertion[];
16
16
  relay_chain?: RelayEntry[];
17
17
  trace_id?: string;
18
+ sender_delegate?: SenderDelegate;
19
+ deliver_after?: string;
18
20
  }
19
21
  export interface IdentityAssertion {
20
22
  type: string;
@@ -44,6 +46,17 @@ export interface RelayEntry {
44
46
  signature?: string;
45
47
  service_class?: string;
46
48
  }
49
+ export interface SenderDelegate {
50
+ id: string;
51
+ identity_assertions?: IdentityAssertion[];
52
+ authorization?: DelegateAuthorization;
53
+ }
54
+ export interface DelegateAuthorization {
55
+ type: string;
56
+ credential?: string;
57
+ scope?: string[];
58
+ valid_until?: string;
59
+ }
47
60
  export interface SecurityMode {
48
61
  mode: string;
49
62
  min_tls_version?: string;
@@ -96,12 +109,19 @@ export declare const ErrorCode: {
96
109
  readonly IdentityAssertionInvalid: -31012;
97
110
  readonly VersionNotSupported: -31013;
98
111
  readonly QueueFull: -31014;
112
+ readonly DelegationInvalid: -31015;
113
+ readonly ConsignmentModeUnsupported: -31016;
114
+ readonly AssuranceLevelUnsupported: -31017;
115
+ readonly PolicyUnsupported: -31018;
99
116
  };
100
117
  export interface AuthObject {
101
118
  type: string;
102
119
  token?: string;
120
+ proof?: string;
121
+ challenge?: string;
103
122
  signature?: string;
104
123
  x5c?: string[];
124
+ did_auth?: unknown;
105
125
  [key: string]: unknown;
106
126
  }
107
127
  /** Authentication type constants. */
@@ -150,14 +170,12 @@ export interface SessionCloseParams {
150
170
  }
151
171
  export interface SessionAuthenticateParams {
152
172
  wmp: Metadata;
153
- type: string;
154
- token?: string;
155
- response?: string;
156
- [key: string]: unknown;
173
+ auth: AuthObject;
157
174
  }
158
175
  export interface SessionAuthenticateResult {
159
176
  wmp: Metadata;
160
177
  authenticated: boolean;
178
+ identity?: string;
161
179
  }
162
180
  export declare const CloseReason: {
163
181
  readonly Complete: "complete";
@@ -171,6 +189,12 @@ export interface MessageDeliverParams {
171
189
  content_type?: string;
172
190
  body?: unknown;
173
191
  ciphertext?: string;
192
+ reply_to?: string;
193
+ in_reply_to?: string;
194
+ message_type?: string;
195
+ consignment_mode?: string;
196
+ recipient_assurance_level?: string;
197
+ applicable_policies?: string[];
174
198
  }
175
199
  export interface MessageAckParams {
176
200
  wmp: Metadata;
@@ -198,6 +222,16 @@ export declare const AckStatus: {
198
222
  readonly Processed: "processed";
199
223
  readonly Failed: "failed";
200
224
  };
225
+ export declare const ConsignmentMode: {
226
+ readonly Basic: "basic";
227
+ readonly Consented: "consented";
228
+ readonly ConsentedSigned: "consented_signed";
229
+ };
230
+ export declare const AssuranceLevel: {
231
+ readonly Low: "low";
232
+ readonly Substantial: "substantial";
233
+ readonly High: "high";
234
+ };
201
235
  export interface CapabilityUpdateParams {
202
236
  wmp: Metadata;
203
237
  add?: Capabilities;
package/dist/types.js CHANGED
@@ -50,6 +50,10 @@ export const ErrorCode = {
50
50
  IdentityAssertionInvalid: -31012,
51
51
  VersionNotSupported: -31013,
52
52
  QueueFull: -31014,
53
+ DelegationInvalid: -31015,
54
+ ConsignmentModeUnsupported: -31016,
55
+ AssuranceLevelUnsupported: -31017,
56
+ PolicyUnsupported: -31018,
53
57
  };
54
58
  /** Authentication type constants. */
55
59
  export const AuthType = {
@@ -74,6 +78,16 @@ export const AckStatus = {
74
78
  Processed: "processed",
75
79
  Failed: "failed",
76
80
  };
81
+ export const ConsignmentMode = {
82
+ Basic: "basic",
83
+ Consented: "consented",
84
+ ConsentedSigned: "consented_signed",
85
+ };
86
+ export const AssuranceLevel = {
87
+ Low: "low",
88
+ Substantial: "substantial",
89
+ High: "high",
90
+ };
77
91
  export const FlowType = {
78
92
  Approval: "approval",
79
93
  Sign: "sign",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sirosfoundation/wmp-js",
3
- "version": "0.2.1",
3
+ "version": "0.5.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",
@@ -36,7 +36,10 @@
36
36
  "url": "https://github.com/sirosfoundation/wmp-js.git"
37
37
  },
38
38
  "dependencies": {
39
+ "@noble/curves": "^2.0.1",
40
+ "@noble/hashes": "^2.2.0",
39
41
  "ajv": "^8.20.0",
40
- "ajv-formats": "^3.0.1"
42
+ "ajv-formats": "^3.0.1",
43
+ "ts-mls": "^1.6.2"
41
44
  }
42
45
  }