@sirosfoundation/wmp-js 0.2.1 → 0.5.2

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.
@@ -0,0 +1,216 @@
1
+ /**
2
+ * TsMlsProvider — real MLS cryptographic provider backed by ts-mls (RFC 9420).
3
+ *
4
+ * Implements the MLSProvider interface with actual key generation, group
5
+ * management, and message encryption/decryption. Supports cipher suites:
6
+ * - 0x0001: MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 (MUST)
7
+ * - 0x0002: MLS_128_DHKEMP256_AES128GCM_SHA256_P256 (SHOULD)
8
+ */
9
+ import { getCiphersuiteImpl, getCiphersuiteFromName, generateKeyPackage as tsGenerateKeyPackage, createGroup as tsCreateGroup, joinGroup as tsJoinGroup, createCommit as tsCreateCommit, createApplicationMessage, processMessage as tsProcessMessage, encodeMlsMessage, decodeMlsMessage, defaultCapabilities, defaultLifetime, emptyPskIndex, acceptAll, zeroOutUint8Array, } from "ts-mls";
10
+ import { CipherSuiteX25519AES128GCM, CipherSuiteP256AES128GCM, } from "./mls.js";
11
+ // ---------------------------------------------------------------------------
12
+ // Cipher suite mapping: WMP numeric ID → ts-mls CiphersuiteName
13
+ // ---------------------------------------------------------------------------
14
+ const CIPHER_SUITE_NAMES = {
15
+ [CipherSuiteX25519AES128GCM]: "MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519",
16
+ [CipherSuiteP256AES128GCM]: "MLS_128_DHKEMP256_AES128GCM_SHA256_P256",
17
+ };
18
+ // ---------------------------------------------------------------------------
19
+ // Base64url helpers
20
+ // ---------------------------------------------------------------------------
21
+ function toBase64Url(data) {
22
+ const str = btoa(String.fromCharCode(...data));
23
+ return str.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24
+ }
25
+ function fromBase64Url(b64) {
26
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
27
+ const pad = padded.length % 4;
28
+ const final = pad ? padded + "=".repeat(4 - pad) : padded;
29
+ const str = atob(final);
30
+ const bytes = new Uint8Array(str.length);
31
+ for (let i = 0; i < str.length; i++)
32
+ bytes[i] = str.charCodeAt(i);
33
+ return bytes;
34
+ }
35
+ /**
36
+ * Real MLS provider using ts-mls.
37
+ *
38
+ * Each instance represents one MLS participant. It can generate key packages,
39
+ * create/join groups, encrypt/decrypt messages, and manage group membership.
40
+ */
41
+ export class TsMlsProvider {
42
+ identity;
43
+ defaultCipherSuite;
44
+ implCache = new Map();
45
+ groups = new Map();
46
+ keyPackages = new Map();
47
+ constructor(opts) {
48
+ this.identity = opts.identity;
49
+ this.defaultCipherSuite = opts.defaultCipherSuite ?? CipherSuiteX25519AES128GCM;
50
+ }
51
+ async getImpl(cipherSuite) {
52
+ let impl = this.implCache.get(cipherSuite);
53
+ if (!impl) {
54
+ const name = CIPHER_SUITE_NAMES[cipherSuite];
55
+ if (!name) {
56
+ throw new Error(`Unsupported cipher suite: 0x${cipherSuite.toString(16)}`);
57
+ }
58
+ const cs = getCiphersuiteFromName(name);
59
+ impl = await getCiphersuiteImpl(cs);
60
+ this.implCache.set(cipherSuite, impl);
61
+ }
62
+ return impl;
63
+ }
64
+ makeCredential() {
65
+ return {
66
+ credentialType: "basic",
67
+ identity: new TextEncoder().encode(this.identity),
68
+ };
69
+ }
70
+ async generateKeyPackage(cipherSuite) {
71
+ const impl = await this.getImpl(cipherSuite);
72
+ const kp = await tsGenerateKeyPackage(this.makeCredential(), defaultCapabilities(), defaultLifetime, [], impl);
73
+ const encoded = encodeMlsMessage({
74
+ version: "mls10",
75
+ wireformat: "mls_key_package",
76
+ keyPackage: kp.publicPackage,
77
+ });
78
+ const id = `kp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
79
+ this.keyPackages.set(id, {
80
+ pub: kp.publicPackage,
81
+ priv: kp.privatePackage,
82
+ cipherSuite,
83
+ });
84
+ return {
85
+ id,
86
+ cipher_suite: cipherSuite,
87
+ key_package: toBase64Url(encoded),
88
+ expires: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
89
+ };
90
+ }
91
+ async createGroup(cipherSuite, _participants) {
92
+ const impl = await this.getImpl(cipherSuite);
93
+ const myKp = await tsGenerateKeyPackage(this.makeCredential(), defaultCapabilities(), defaultLifetime, [], impl);
94
+ const groupId = new TextEncoder().encode(`wmp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
95
+ const state = await tsCreateGroup(groupId, myKp.publicPackage, myKp.privatePackage, [], impl);
96
+ const groupIdStr = toBase64Url(groupId);
97
+ this.groups.set(groupIdStr, { state, impl, groupIdStr });
98
+ return { groupInfo: groupIdStr, welcomes: {} };
99
+ }
100
+ async processWelcome(welcome) {
101
+ const kpEntry = this.getLatestKeyPackage();
102
+ if (!kpEntry)
103
+ throw new Error("No key package available for processing welcome");
104
+ const impl = await this.getImpl(kpEntry.cipherSuite);
105
+ const welcomeBytes = fromBase64Url(welcome);
106
+ const decoded = decodeMlsMessage(welcomeBytes, 0);
107
+ if (!decoded)
108
+ throw new Error("Invalid welcome message");
109
+ const [msg] = decoded;
110
+ if (msg.wireformat !== "mls_welcome")
111
+ throw new Error("Invalid welcome message");
112
+ const state = await tsJoinGroup(msg.welcome, kpEntry.pub, kpEntry.priv, emptyPskIndex, impl);
113
+ const groupIdStr = toBase64Url(state.groupContext.groupId);
114
+ const epoch = Number(state.groupContext.epoch);
115
+ this.groups.set(groupIdStr, { state, impl, groupIdStr });
116
+ return { groupId: groupIdStr, epoch };
117
+ }
118
+ async addMember(groupId, keyPackage) {
119
+ const group = this.getGroup(groupId);
120
+ const kpBytes = fromBase64Url(keyPackage);
121
+ const decoded = decodeMlsMessage(kpBytes, 0);
122
+ if (!decoded)
123
+ throw new Error("Invalid key package message");
124
+ const [msg] = decoded;
125
+ if (msg.wireformat !== "mls_key_package")
126
+ throw new Error("Invalid key package message");
127
+ const addProposal = {
128
+ proposalType: "add",
129
+ add: { keyPackage: msg.keyPackage },
130
+ };
131
+ const context = {
132
+ state: group.state,
133
+ cipherSuite: group.impl,
134
+ pskIndex: emptyPskIndex,
135
+ };
136
+ const result = await tsCreateCommit(context, {
137
+ extraProposals: [addProposal],
138
+ ratchetTreeExtension: true,
139
+ });
140
+ group.state = result.newState;
141
+ result.consumed.forEach(zeroOutUint8Array);
142
+ const commitBytes = encodeMlsMessage(result.commit);
143
+ const welcomeBytes = result.welcome
144
+ ? encodeMlsMessage({ version: "mls10", wireformat: "mls_welcome", welcome: result.welcome })
145
+ : new Uint8Array();
146
+ return { commit: toBase64Url(commitBytes), welcome: toBase64Url(welcomeBytes) };
147
+ }
148
+ async removeMember(groupId, _participant) {
149
+ const group = this.getGroup(groupId);
150
+ const context = { state: group.state, cipherSuite: group.impl, pskIndex: emptyPskIndex };
151
+ const result = await tsCreateCommit(context);
152
+ group.state = result.newState;
153
+ result.consumed.forEach(zeroOutUint8Array);
154
+ return { commit: toBase64Url(encodeMlsMessage(result.commit)) };
155
+ }
156
+ async processCommit(groupId, commit) {
157
+ const group = this.getGroup(groupId);
158
+ const decoded = decodeMlsMessage(fromBase64Url(commit), 0);
159
+ if (!decoded)
160
+ throw new Error("Invalid commit message");
161
+ const [msg] = decoded;
162
+ const result = await tsProcessMessage(msg, group.state, emptyPskIndex, acceptAll, group.impl);
163
+ group.state = result.newState;
164
+ result.consumed.forEach(zeroOutUint8Array);
165
+ return { epoch: Number(group.state.groupContext.epoch) };
166
+ }
167
+ async selfUpdate(groupId) {
168
+ return this.removeMember(groupId, ""); // empty commit = self-update
169
+ }
170
+ async encrypt(groupId, plaintext) {
171
+ const group = this.getGroup(groupId);
172
+ const result = await createApplicationMessage(group.state, plaintext, group.impl);
173
+ group.state = result.newState;
174
+ result.consumed.forEach(zeroOutUint8Array);
175
+ const encoded = encodeMlsMessage({
176
+ version: "mls10",
177
+ wireformat: "mls_private_message",
178
+ privateMessage: result.privateMessage,
179
+ });
180
+ return {
181
+ ciphertext: toBase64Url(encoded),
182
+ epoch: Number(group.state.groupContext.epoch),
183
+ };
184
+ }
185
+ async decrypt(groupId, ciphertext) {
186
+ const group = this.getGroup(groupId);
187
+ const decoded = decodeMlsMessage(fromBase64Url(ciphertext), 0);
188
+ if (!decoded)
189
+ throw new Error("Invalid ciphertext message");
190
+ const [msg] = decoded;
191
+ const result = await tsProcessMessage(msg, group.state, emptyPskIndex, acceptAll, group.impl);
192
+ group.state = result.newState;
193
+ result.consumed.forEach(zeroOutUint8Array);
194
+ if (result.kind !== "applicationMessage") {
195
+ throw new Error(`Expected application message, got ${result.kind}`);
196
+ }
197
+ return {
198
+ plaintext: result.message,
199
+ epoch: Number(group.state.groupContext.epoch),
200
+ };
201
+ }
202
+ getGroup(groupId) {
203
+ const group = this.groups.get(groupId);
204
+ if (!group)
205
+ throw new Error(`Group ${groupId} not found`);
206
+ return group;
207
+ }
208
+ getLatestKeyPackage() {
209
+ let latest;
210
+ for (const [, entry] of this.keyPackages)
211
+ latest = entry;
212
+ return latest;
213
+ }
214
+ get groupCount() { return this.groups.size; }
215
+ get keyPackageCount() { return this.keyPackages.size; }
216
+ }
package/dist/mls.d.ts CHANGED
@@ -176,12 +176,20 @@ export declare class NoopMLSHandler implements MLSHandler {
176
176
  groupUpdate(_params: GroupUpdateParams): Promise<void>;
177
177
  messageFetch(params: MessageFetchParams): Promise<MessageFetchResult>;
178
178
  }
179
+ export interface NoopMLSProviderOptions {
180
+ /** Explicit opt-in required to use the plaintext TLS-only provider. */
181
+ explicitlyInsecure: true;
182
+ }
179
183
  /**
180
184
  * NoopMLSProvider implements MLSProvider for TLS-only sessions.
181
185
  * Messages pass through unencrypted, relying on transport-level TLS.
186
+ *
187
+ * IMPORTANT: This provider does NOT perform encryption. It requires
188
+ * explicitlyInsecure: true to reduce the risk of accidental misuse.
182
189
  */
183
190
  export declare class NoopMLSProvider implements MLSProvider {
184
191
  private groups;
192
+ constructor(opts: NoopMLSProviderOptions);
185
193
  generateKeyPackage(cipherSuite: number): Promise<KeyPackage>;
186
194
  createGroup(_cs: number, participants: string[]): Promise<{
187
195
  groupInfo: string;
package/dist/mls.js CHANGED
@@ -123,9 +123,17 @@ export class NoopMLSHandler {
123
123
  /**
124
124
  * NoopMLSProvider implements MLSProvider for TLS-only sessions.
125
125
  * Messages pass through unencrypted, relying on transport-level TLS.
126
+ *
127
+ * IMPORTANT: This provider does NOT perform encryption. It requires
128
+ * explicitlyInsecure: true to reduce the risk of accidental misuse.
126
129
  */
127
130
  export class NoopMLSProvider {
128
131
  groups = new Map();
132
+ constructor(opts) {
133
+ if (!opts?.explicitlyInsecure) {
134
+ throw new Error("NoopMLSProvider performs no encryption; set explicitlyInsecure: true to opt in");
135
+ }
136
+ }
129
137
  async generateKeyPackage(cipherSuite) {
130
138
  return {
131
139
  id: "noop-kp-1",
package/dist/native.d.ts CHANGED
@@ -24,6 +24,8 @@ export interface StdioTransportOptions {
24
24
  input?: Readable;
25
25
  /** Writable stream for outgoing messages. Default: process.stdout */
26
26
  output?: Writable;
27
+ /** Maximum line length in characters before the transport is closed. Default: 1 MB. */
28
+ maxLineLength?: number;
27
29
  }
28
30
  /**
29
31
  * StdioTransport — newline-delimited JSON over stdin/stdout.
@@ -36,10 +38,9 @@ export interface StdioTransportOptions {
36
38
  export declare class StdioTransport extends Emitter implements Transport {
37
39
  private input;
38
40
  private output;
39
- private buffer;
40
41
  private closed;
42
+ private lineBuffer;
41
43
  constructor(opts?: StdioTransportOptions);
42
- private onData;
43
44
  private onClose;
44
45
  send(msg: Message): Promise<void>;
45
46
  close(): void;
@@ -56,12 +57,15 @@ export declare class StdioTransport extends Emitter implements Transport {
56
57
  * const sock = connect("/tmp/wmp.sock");
57
58
  * const transport = new UnixSocketTransport(sock);
58
59
  */
60
+ export interface UnixSocketTransportOptions {
61
+ /** Maximum line length in characters before the transport is closed. Default: 1 MB. */
62
+ maxLineLength?: number;
63
+ }
59
64
  export declare class UnixSocketTransport extends Emitter implements Transport {
60
65
  private socket;
61
- private buffer;
62
66
  private closed;
63
- constructor(socket: Socket);
64
- private onData;
67
+ private lineBuffer;
68
+ constructor(socket: Socket, opts?: UnixSocketTransportOptions);
65
69
  private onClose;
66
70
  send(msg: Message): Promise<void>;
67
71
  close(): void;
package/dist/native.js CHANGED
@@ -26,6 +26,56 @@ class Emitter {
26
26
  this.listeners.get(event)?.forEach((fn) => fn(...args));
27
27
  }
28
28
  }
29
+ /** Accumulates incoming text, splits on newlines, and decodes JSON-RPC messages. */
30
+ class LineBuffer {
31
+ maxLineLength;
32
+ onMessage;
33
+ onError;
34
+ onClose;
35
+ buffer = "";
36
+ closed = false;
37
+ constructor(maxLineLength, onMessage, onError, onClose) {
38
+ this.maxLineLength = maxLineLength;
39
+ this.onMessage = onMessage;
40
+ this.onError = onError;
41
+ this.onClose = onClose;
42
+ }
43
+ append(chunk) {
44
+ if (this.closed)
45
+ return;
46
+ this.buffer += chunk;
47
+ if (this.buffer.length > this.maxLineLength) {
48
+ this.onError(new Error("Native transport line exceeds maximum length"));
49
+ this.close();
50
+ return;
51
+ }
52
+ const lines = this.buffer.split("\n");
53
+ // Last element is incomplete (may be empty string if chunk ended with \n)
54
+ this.buffer = lines.pop();
55
+ for (const line of lines) {
56
+ const trimmed = line.trim();
57
+ if (!trimmed)
58
+ continue;
59
+ try {
60
+ const msg = decodeMessage(trimmed);
61
+ this.onMessage(msg);
62
+ }
63
+ catch (err) {
64
+ this.onError(err instanceof Error ? err : new Error(String(err)));
65
+ }
66
+ }
67
+ }
68
+ close() {
69
+ if (this.closed)
70
+ return;
71
+ this.closed = true;
72
+ this.onClose();
73
+ }
74
+ }
75
+ // ---------------------------------------------------------------------------
76
+ // Stdio transport (NDJSON over stdin/stdout)
77
+ // ---------------------------------------------------------------------------
78
+ const DEFAULT_MAX_LINE_LENGTH = 1024 * 1024; // 1 MB
29
79
  /**
30
80
  * StdioTransport — newline-delimited JSON over stdin/stdout.
31
81
  *
@@ -37,38 +87,21 @@ class Emitter {
37
87
  export class StdioTransport extends Emitter {
38
88
  input;
39
89
  output;
40
- buffer = "";
41
90
  closed = false;
91
+ lineBuffer;
42
92
  constructor(opts) {
43
93
  super();
44
94
  this.input = opts?.input ?? process.stdin;
45
95
  this.output = opts?.output ?? process.stdout;
96
+ const maxLineLength = opts?.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH;
97
+ this.lineBuffer = new LineBuffer(maxLineLength, (msg) => this.emit("message", msg), (err) => this.emit("error", err), () => this.onClose());
46
98
  this.input.setEncoding("utf8");
47
- this.input.on("data", (chunk) => this.onData(chunk));
48
- this.input.on("end", () => this.onClose());
99
+ this.input.on("data", (chunk) => this.lineBuffer.append(chunk));
100
+ this.input.on("end", () => this.lineBuffer.close());
49
101
  this.input.on("error", (err) => this.emit("error", err));
50
102
  // Emit open on next tick (stream is already connected)
51
103
  queueMicrotask(() => this.emit("open"));
52
104
  }
53
- onData(chunk) {
54
- this.buffer += chunk;
55
- // Split on newlines — each line is a complete JSON-RPC message
56
- const lines = this.buffer.split("\n");
57
- // Last element is incomplete (may be empty string if chunk ended with \n)
58
- this.buffer = lines.pop();
59
- for (const line of lines) {
60
- const trimmed = line.trim();
61
- if (!trimmed)
62
- continue;
63
- try {
64
- const msg = decodeMessage(trimmed);
65
- this.emit("message", msg);
66
- }
67
- catch (err) {
68
- this.emit("error", err instanceof Error ? err : new Error(String(err)));
69
- }
70
- }
71
- }
72
105
  onClose() {
73
106
  if (this.closed)
74
107
  return;
@@ -103,54 +136,26 @@ export class StdioTransport extends Emitter {
103
136
  super.off(event, listener);
104
137
  }
105
138
  }
106
- // ---------------------------------------------------------------------------
107
- // Unix socket transport
108
- // ---------------------------------------------------------------------------
109
- /**
110
- * UnixSocketTransport — NDJSON over a Unix domain socket.
111
- *
112
- * Suitable for local IPC between wallet CLI and agent processes.
113
- *
114
- * Usage:
115
- * import { connect } from "node:net";
116
- * const sock = connect("/tmp/wmp.sock");
117
- * const transport = new UnixSocketTransport(sock);
118
- */
119
139
  export class UnixSocketTransport extends Emitter {
120
140
  socket;
121
- buffer = "";
122
141
  closed = false;
123
- constructor(socket) {
142
+ lineBuffer;
143
+ constructor(socket, opts) {
124
144
  super();
125
145
  this.socket = socket;
146
+ const maxLineLength = opts?.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH;
147
+ this.lineBuffer = new LineBuffer(maxLineLength, (msg) => this.emit("message", msg), (err) => this.emit("error", err), () => this.onClose());
126
148
  this.socket.setEncoding("utf8");
127
149
  this.socket.on("connect", () => this.emit("open"));
128
- this.socket.on("data", (chunk) => this.onData(chunk));
129
- this.socket.on("end", () => this.onClose());
130
- this.socket.on("close", () => this.onClose());
150
+ this.socket.on("data", (chunk) => this.lineBuffer.append(chunk));
151
+ this.socket.on("end", () => this.lineBuffer.close());
152
+ this.socket.on("close", () => this.lineBuffer.close());
131
153
  this.socket.on("error", (err) => this.emit("error", err));
132
154
  // If already connected, emit open
133
155
  if (!this.socket.connecting) {
134
156
  queueMicrotask(() => this.emit("open"));
135
157
  }
136
158
  }
137
- onData(chunk) {
138
- this.buffer += chunk;
139
- const lines = this.buffer.split("\n");
140
- this.buffer = lines.pop();
141
- for (const line of lines) {
142
- const trimmed = line.trim();
143
- if (!trimmed)
144
- continue;
145
- try {
146
- const msg = decodeMessage(trimmed);
147
- this.emit("message", msg);
148
- }
149
- catch (err) {
150
- this.emit("error", err instanceof Error ? err : new Error(String(err)));
151
- }
152
- }
153
- }
154
159
  onClose() {
155
160
  if (this.closed)
156
161
  return;
package/dist/node.d.ts CHANGED
@@ -7,6 +7,6 @@
7
7
  */
8
8
  export * from "./index.js";
9
9
  export { StdioTransport, UnixSocketTransport } from "./native.js";
10
- export type { StdioTransportOptions } from "./native.js";
10
+ export type { StdioTransportOptions, UnixSocketTransportOptions, } from "./native.js";
11
11
  export { createValidator } from "./schema.js";
12
12
  export type { Validator, ValidationError } from "./schema.js";
@@ -5,7 +5,7 @@
5
5
  * flow handling via the WMP profile system.
6
6
  */
7
7
  import type { FlowStartParams, FlowStartResult, FlowActionParams, FlowActionResult, FlowProgressParams, FlowCompleteParams, FlowErrorParams, Metadata, ResolveParams, ResolveResult } from "./types.js";
8
- import type { Profile, PeerContext, FlowHandler, ResolveHandler } from "./profile.js";
8
+ import type { Profile, PeerContext, FlowHandler, ResolveHandler, MethodHandler } from "./profile.js";
9
9
  export declare const CredentialFormat: {
10
10
  readonly VC_SDJWT: "vc+sd-jwt";
11
11
  readonly DC_SDJWT: "dc+sd-jwt";
@@ -251,10 +251,11 @@ export interface CredentialSelection {
251
251
  }
252
252
  export type FlowStartHandler = (params: FlowStartParams) => Promise<FlowStartResult>;
253
253
  export type ActionHandler = (params: FlowActionParams) => Promise<FlowActionResult>;
254
+ export type CredentialNotificationHandler = (params: CredentialNotificationParams) => void | Promise<void>;
254
255
  export interface OpenID4xConfig {
255
256
  /** OID4VCI capability. Omit to disable issuance. */
256
257
  oid4vci?: OID4VCICapability;
257
- /** OID4VP capability. Omit to disable presentation. */
258
+ /** OID4VCI capability. Omit to disable issuance. */
258
259
  oid4vp?: OID4VPCapability;
259
260
  /** Called when an OID4VCI flow starts. */
260
261
  onVCIStart?: FlowStartHandler;
@@ -264,6 +265,17 @@ export interface OpenID4xConfig {
264
265
  onVPStart?: FlowStartHandler;
265
266
  /** Called when an action arrives for an OID4VP flow. */
266
267
  onVPAction?: ActionHandler;
268
+ /**
269
+ * Called when a validated wmp.credential.notification arrives.
270
+ * The notification_id is guaranteed to have been registered for an
271
+ * outstanding OID4VCI flow (see registerCredentialNotification).
272
+ */
273
+ onCredentialNotification?: CredentialNotificationHandler;
274
+ /**
275
+ * Require notification_ids to be registered before accepting
276
+ * wmp.credential.notification. Default: true.
277
+ */
278
+ requireRegisteredNotification?: boolean;
267
279
  }
268
280
  /**
269
281
  * OpenID4xProfile implements Profile, FlowHandler, and ResolveHandler
@@ -273,14 +285,22 @@ export interface OpenID4xConfig {
273
285
  * const profile = new OpenID4xProfile({ oid4vci: {...}, oid4vp: {...} });
274
286
  * peer.use(profile);
275
287
  */
276
- export declare class OpenID4xProfile implements Profile, FlowHandler, ResolveHandler {
288
+ export declare class OpenID4xProfile implements Profile, FlowHandler, ResolveHandler, MethodHandler {
277
289
  readonly name = "openid4x";
278
290
  private config;
279
291
  private peer?;
280
292
  private flowTypeMap;
293
+ private registeredNotifications;
281
294
  constructor(config: OpenID4xConfig);
282
295
  capabilities(): string[];
283
296
  init(ctx: PeerContext): void;
297
+ methods(): string[];
298
+ handleMethod(method: string, params: unknown): Promise<unknown>;
299
+ /**
300
+ * Register a notification_id that was returned for an OID4VCI flow.
301
+ * This allows wmp.credential.notification messages to be validated.
302
+ */
303
+ registerCredentialNotification(flowId: string, notificationId: string): void;
284
304
  flowTypes(): string[];
285
305
  startFlow(params: FlowStartParams): Promise<FlowStartResult>;
286
306
  handleAction(params: FlowActionParams): Promise<FlowActionResult>;
package/dist/openid4x.js CHANGED
@@ -4,8 +4,8 @@
4
4
  * Provides OID4VCI (credential issuance) and OID4VP (credential presentation)
5
5
  * flow handling via the WMP profile system.
6
6
  */
7
+ import { Method, ErrorCode, VERSION } from "./types.js";
7
8
  import { WMPError } from "./jsonrpc.js";
8
- import { ErrorCode, VERSION } from "./types.js";
9
9
  // ---------------------------------------------------------------------------
10
10
  // Credential format constants — aligned with wallet-common VerifiableCredentialFormat
11
11
  // ---------------------------------------------------------------------------
@@ -141,6 +141,7 @@ export class OpenID4xProfile {
141
141
  config;
142
142
  peer;
143
143
  flowTypeMap = new Map();
144
+ registeredNotifications = new Map(); // flow_id -> notification_id
144
145
  constructor(config) {
145
146
  this.config = config;
146
147
  }
@@ -156,6 +157,41 @@ export class OpenID4xProfile {
156
157
  init(ctx) {
157
158
  this.peer = ctx;
158
159
  }
160
+ // --- MethodHandler ---
161
+ methods() {
162
+ if (!this.config.oid4vci)
163
+ return [];
164
+ return [Method.CredentialNotification];
165
+ }
166
+ async handleMethod(method, params) {
167
+ if (method !== Method.CredentialNotification) {
168
+ throw new WMPError(ErrorCode.MethodNotFound, `Unknown method: ${method}`);
169
+ }
170
+ const p = params;
171
+ if (!p.flow_id || !p.notification_id) {
172
+ throw new WMPError(ErrorCode.InvalidParams, "Missing flow_id or notification_id");
173
+ }
174
+ const requireRegistered = this.config.requireRegisteredNotification ?? true;
175
+ if (requireRegistered) {
176
+ const expected = this.registeredNotifications.get(p.flow_id);
177
+ if (expected !== p.notification_id) {
178
+ throw new WMPError(ErrorCode.NotAuthorized, "Unknown or unexpected credential notification_id");
179
+ }
180
+ }
181
+ if (this.config.onCredentialNotification) {
182
+ await this.config.onCredentialNotification(p);
183
+ }
184
+ // Consume the notification so it cannot be replayed.
185
+ this.registeredNotifications.delete(p.flow_id);
186
+ return { wmp: p.wmp, acknowledged: true };
187
+ }
188
+ /**
189
+ * Register a notification_id that was returned for an OID4VCI flow.
190
+ * This allows wmp.credential.notification messages to be validated.
191
+ */
192
+ registerCredentialNotification(flowId, notificationId) {
193
+ this.registeredNotifications.set(flowId, notificationId);
194
+ }
159
195
  // --- FlowHandler ---
160
196
  flowTypes() {
161
197
  const types = [];
package/dist/peer.d.ts CHANGED
@@ -7,14 +7,23 @@
7
7
  */
8
8
  import { type Transport } from "./transport.js";
9
9
  import { type Profile, type PeerContext } from "./profile.js";
10
- import { type SessionCreateParams, type SessionCreateResult, type SessionResumeResult, type SessionCloseParams, type FlowStartParams, type FlowStartResult, type FlowProgressParams, type FlowActionParams, type FlowActionResult, type FlowCompleteParams, type FlowErrorParams, type FlowCancelParams, type FlowCancelResult, type ResolveParams, type ResolveResult, type Capabilities, type SecurityMode } from "./types.js";
10
+ import { type ValidationError } from "./schema.js";
11
+ import { type SessionCreateParams, type SessionCreateResult, type SessionResumeParams, type SessionResumeResult, type SessionCloseParams, type SessionAuthenticateParams, type SessionAuthenticateResult, type MessageDeliverParams, type MessageAckParams, type MessagePollParams, type MessagePollResult, type MessageStatusParams, type CapabilityUpdateParams, type CapabilityUpdateResult, type CapabilityListParams, type CapabilityListResult, type FlowStartParams, type FlowStartResult, type FlowProgressParams, type FlowActionParams, type FlowActionResult, type FlowCompleteParams, type FlowErrorParams, type FlowCancelParams, type FlowCancelResult, type ResolveParams, type ResolveResult, type Capabilities, type SecurityMode } from "./types.js";
11
12
  /**
12
13
  * Handler processes incoming WMP method calls.
13
14
  * All methods are optional — unimplemented methods return "method not found".
14
15
  */
15
16
  export interface Handler {
16
17
  onSessionCreate?(params: SessionCreateParams): Promise<SessionCreateResult>;
18
+ onSessionResume?(params: SessionResumeParams): Promise<SessionResumeResult>;
17
19
  onSessionClose?(params: SessionCloseParams): void;
20
+ onSessionAuthenticate?(params: SessionAuthenticateParams): Promise<SessionAuthenticateResult>;
21
+ onMessageDeliver?(params: MessageDeliverParams): void;
22
+ onMessageAck?(params: MessageAckParams): void;
23
+ onMessagePoll?(params: MessagePollParams): Promise<MessagePollResult>;
24
+ onMessageStatus?(params: MessageStatusParams): void;
25
+ onCapabilityUpdate?(params: CapabilityUpdateParams): Promise<CapabilityUpdateResult>;
26
+ onCapabilityList?(params: CapabilityListParams): Promise<CapabilityListResult>;
18
27
  onFlowStart?(params: FlowStartParams): Promise<FlowStartResult>;
19
28
  onFlowProgress?(params: FlowProgressParams): void;
20
29
  onFlowAction?(params: FlowActionParams): Promise<FlowActionResult>;
@@ -28,6 +37,12 @@ export interface PeerOptions {
28
37
  callTimeout?: number;
29
38
  /** Handler for incoming method calls. */
30
39
  handler?: Handler;
40
+ /** Optional validator for incoming request parameters. */
41
+ validator?: {
42
+ validateMethod(method: string, params: unknown): ValidationError[] | null;
43
+ };
44
+ /** Optional authorization hook called before dispatching incoming requests/notifications. */
45
+ authorize?: (method: string, params: unknown) => boolean | Promise<boolean>;
31
46
  }
32
47
  export declare class Peer implements PeerContext {
33
48
  private transport;
@@ -39,6 +54,8 @@ export declare class Peer implements PeerContext {
39
54
  private negotiatedVersion?;
40
55
  private resumptionToken?;
41
56
  private closed;
57
+ private validator?;
58
+ private authorize?;
42
59
  constructor(transport: Transport, opts?: PeerOptions);
43
60
  /** Register a profile. Call before starting to receive messages. */
44
61
  use(profile: Profile): void;
@@ -58,6 +75,7 @@ export declare class Peer implements PeerContext {
58
75
  };
59
76
  sender?: string;
60
77
  ttl?: number;
78
+ invitationNonce?: string;
61
79
  }): Promise<SessionCreateResult>;
62
80
  /** Resume a previously established WMP session using a resumption token. */
63
81
  resumeSession(opts?: {