@sirosfoundation/wmp-js 0.2.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/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) 2026, SIROS Foundation
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @sirosfoundation/wmp-js
2
+
3
+ [![CI](https://github.com/sirosfoundation/wmp-js/actions/workflows/ci.yml/badge.svg)](https://github.com/sirosfoundation/wmp-js/actions/workflows/ci.yml)
4
+ [![License](https://img.shields.io/badge/license-BSD--2--Clause-blue)](LICENSE)
5
+
6
+ TypeScript implementation of the Wallet Messaging Protocol (WMP) — a JSON-RPC 2.0 protocol for bidirectional communication between wallet frontends and backend services.
7
+
8
+ ## Features
9
+
10
+ - **JSON-RPC 2.0** request/response and notification handling
11
+ - **Bidirectional peer** with concurrent request tracking and timeout support
12
+ - **Pluggable transports** — WebSocket and HTTP+SSE included
13
+ - **Flow profile** for orchestrating multi-step wallet flows (issuance, presentation, etc.)
14
+ - **Zero runtime dependencies**, ESM-only
15
+ - **Fully tested** — 38 tests
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install @sirosfoundation/wmp-js
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ```typescript
26
+ import { Peer, HttpSseTransport } from "@sirosfoundation/wmp-js";
27
+
28
+ const transport = new HttpSseTransport({
29
+ rpcUrl: "https://wallet-backend.example.com/wmp/rpc",
30
+ eventsUrl: "https://wallet-backend.example.com/wmp/events",
31
+ });
32
+
33
+ const peer = new Peer(transport, {
34
+ // Handle incoming notifications
35
+ onNotification: (method, params) => {
36
+ console.log("notification:", method, params);
37
+ },
38
+ });
39
+
40
+ await peer.connect();
41
+
42
+ // Create a session
43
+ const session = await peer.request("wmp.session.create", {
44
+ wmp: { version: "0.1", session_id: "" },
45
+ auth: { token: "bearer-token" },
46
+ });
47
+
48
+ // Start a flow
49
+ const flow = await peer.request("wmp.flow.start", {
50
+ wmp: { version: "0.1", session_id: session.session_id },
51
+ flow_type: "issuance",
52
+ flow_id: "flow-1",
53
+ });
54
+ ```
55
+
56
+ ## API
57
+
58
+ ### Transport
59
+
60
+ ```typescript
61
+ interface Transport {
62
+ send(data: string): Promise<void>;
63
+ onMessage(handler: (data: string) => void): void;
64
+ connect(): Promise<void>;
65
+ close(): void;
66
+ }
67
+ ```
68
+
69
+ Built-in transports:
70
+ - `WebSocketTransport` — full-duplex WebSocket
71
+ - `HttpSseTransport` — HTTP POST for requests, SSE for server notifications
72
+
73
+ ### Peer
74
+
75
+ Bidirectional JSON-RPC 2.0 peer over any `Transport`.
76
+
77
+ ```typescript
78
+ const peer = new Peer(transport, options);
79
+
80
+ // Send request and wait for response
81
+ const result = await peer.request("method.name", params);
82
+
83
+ // Send notification (no response expected)
84
+ peer.notify("method.name", params);
85
+ ```
86
+
87
+ ### Flow Profile
88
+
89
+ Higher-level abstraction for wallet flows.
90
+
91
+ ```typescript
92
+ import { Registry } from "@sirosfoundation/wmp-js";
93
+
94
+ const registry = new Registry();
95
+
96
+ registry.register("issuance", {
97
+ onStart: async (ctx, params) => { /* ... */ },
98
+ onProgress: async (ctx, params) => { /* ... */ },
99
+ onComplete: async (ctx, params) => { /* ... */ },
100
+ });
101
+ ```
102
+
103
+ ## Development
104
+
105
+ ```bash
106
+ npm install
107
+ npm test # run tests
108
+ npm run test:watch # watch mode
109
+ npm run build # compile TypeScript
110
+ npm run lint # type-check
111
+ ```
112
+
113
+ ## License
114
+
115
+ [BSD-2-Clause](LICENSE) — Copyright (c) 2026, SIROS Foundation
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @siros/wmp — Wallet Messaging Protocol client library
3
+ */
4
+ export { VERSION, Method, ErrorCode, FlowType, CloseReason, AckStatus, CancelReason, ResolveType, ServiceClass, } from "./types.js";
5
+ export type { Metadata, IdentityAssertion, TrustHint, RelayEntry, SecurityMode, Capabilities, AuthObject, SessionCreateParams, SessionCreateResult, SessionResumeParams, SessionCloseParams, SessionAuthenticateParams, SessionAuthenticateResult, MessageDeliverParams, MessageAckParams, MessagePollParams, MessagePollResult, MessageStatusParams, CapabilityUpdateParams, CapabilityUpdateResult, CapabilityListParams, CapabilityListResult, FlowStartParams, FlowStartResult, FlowProgressParams, FlowActionParams, FlowActionResult, FlowCompleteParams, FlowErrorParams, FlowCancelParams, FlowCancelResult, ResolveParams, ResolveResult, RelayRegisterParams, RelayRegisterResult, RelayCap, MethodName, } from "./types.js";
6
+ export { WMPError, createRequest, createNotification, createResponse, createErrorResponse, decodeMessage, decodeBatch, isRequest, isResponse, isNotification, } from "./jsonrpc.js";
7
+ export type { RPCError, Request, Response, Message } from "./jsonrpc.js";
8
+ export { WebSocketTransport, HttpSseTransport } from "./transport.js";
9
+ export type { Transport, TransportEvents, TransportEventName, WebSocketTransportOptions, HttpSseTransportOptions, } from "./transport.js";
10
+ export { Registry } from "./profile.js";
11
+ export type { Profile, PeerContext, FlowHandler, MethodHandler, ResolveHandler, } from "./profile.js";
12
+ export { Peer } from "./peer.js";
13
+ export type { Handler, PeerOptions } from "./peer.js";
14
+ export { MLSMethod, CipherSuiteX25519AES128GCM, CipherSuiteP256AES128GCM, CredentialType, MLSProfile, mlsMethods, NoopMLSHandler, NoopMLSProvider, } from "./mls.js";
15
+ export type { MLSMethodName, GroupCreateParams, GroupCreateResult, GroupJoinParams, GroupJoinResult, GroupAddParams, GroupAddResult, GroupRemoveParams, GroupRemoveResult, GroupUpdateParams, MessageFetchParams, MessageFetchResult, KeyPackage, KeyPackagesResponse, EncryptedEnvelope, MLSHandler, MLSProvider, } from "./mls.js";
16
+ export { CredentialFormat, allFormats, isValidFormat, GrantType, ResponseMode, ProofType, OID4FlowType, VCIStep, VPStep, OID4Action, OpenID4xProfile, } from "./openid4x.js";
17
+ export type { CredentialFormatType, OID4VCICapability, OID4VPCapability, CredentialDisplay, CredentialConfigurationSupported, CredentialResult, VPTokenResult, SignSubFlowParams, SelectionAction, ConsentAction, CredentialSelection, FlowStartHandler, ActionHandler, OpenID4xConfig, } from "./openid4x.js";
18
+ export { Relay } from "./relay.js";
19
+ export type { RelayConfig, QueuedMessage } from "./relay.js";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @siros/wmp — Wallet Messaging Protocol client library
3
+ */
4
+ // Types
5
+ export { VERSION, Method, ErrorCode, FlowType, CloseReason, AckStatus, CancelReason, ResolveType, ServiceClass, } from "./types.js";
6
+ // JSON-RPC
7
+ export { WMPError, createRequest, createNotification, createResponse, createErrorResponse, decodeMessage, decodeBatch, isRequest, isResponse, isNotification, } from "./jsonrpc.js";
8
+ // Transport
9
+ export { WebSocketTransport, HttpSseTransport } from "./transport.js";
10
+ // Profile system
11
+ export { Registry } from "./profile.js";
12
+ // Peer
13
+ export { Peer } from "./peer.js";
14
+ // MLS
15
+ export { MLSMethod, CipherSuiteX25519AES128GCM, CipherSuiteP256AES128GCM, CredentialType, MLSProfile, mlsMethods, NoopMLSHandler, NoopMLSProvider, } from "./mls.js";
16
+ // OpenID4x
17
+ export { CredentialFormat, allFormats, isValidFormat, GrantType, ResponseMode, ProofType, OID4FlowType, VCIStep, VPStep, OID4Action, OpenID4xProfile, } from "./openid4x.js";
18
+ // Relay
19
+ export { Relay } from "./relay.js";
@@ -0,0 +1,48 @@
1
+ /**
2
+ * JSON-RPC 2.0 message types — mirrors go-wmp/pkg/wmp/jsonrpc.go.
3
+ */
4
+ export interface RPCError {
5
+ code: number;
6
+ message: string;
7
+ data?: unknown;
8
+ }
9
+ export interface Request {
10
+ jsonrpc: "2.0";
11
+ id?: string | number;
12
+ method: string;
13
+ params: unknown;
14
+ }
15
+ export interface Response {
16
+ jsonrpc: "2.0";
17
+ id: string | number | null;
18
+ result?: unknown;
19
+ error?: RPCError;
20
+ }
21
+ export type Message = Request | Response;
22
+ /** Type guard: is this a JSON-RPC request/notification? */
23
+ export declare function isRequest(msg: Message): msg is Request;
24
+ /** Type guard: is this a JSON-RPC response? */
25
+ export declare function isResponse(msg: Message): msg is Response;
26
+ /** Type guard: is this a notification (request with no id)? */
27
+ export declare function isNotification(msg: Request): boolean;
28
+ /** Create a JSON-RPC 2.0 request. */
29
+ export declare function createRequest(method: string, params: unknown): Request;
30
+ /** Create a JSON-RPC 2.0 notification (no id, no response expected). */
31
+ export declare function createNotification(method: string, params: unknown): Request;
32
+ /** Create a JSON-RPC 2.0 success response. */
33
+ export declare function createResponse(id: string | number | null, result: unknown): Response;
34
+ /** Create a JSON-RPC 2.0 error response. */
35
+ export declare function createErrorResponse(id: string | number | null, error: RPCError): Response;
36
+ /** Parse a raw JSON string into a Message. Throws on invalid JSON-RPC. */
37
+ export declare function decodeMessage(data: string): Message;
38
+ /** Parse raw JSON that may be a batch (array) or single message. */
39
+ export declare function decodeBatch(data: string): Message[];
40
+ /** WMP-specific RPC error class. */
41
+ export declare class WMPError extends Error {
42
+ readonly code: number;
43
+ readonly data?: unknown;
44
+ constructor(code: number, message: string, data?: unknown);
45
+ toRPCError(): RPCError;
46
+ }
47
+ /** Reset the request ID counter (for testing). */
48
+ export declare function resetRequestIdCounter(): void;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * JSON-RPC 2.0 message types — mirrors go-wmp/pkg/wmp/jsonrpc.go.
3
+ */
4
+ /** Type guard: is this a JSON-RPC request/notification? */
5
+ export function isRequest(msg) {
6
+ return "method" in msg && typeof msg.method === "string";
7
+ }
8
+ /** Type guard: is this a JSON-RPC response? */
9
+ export function isResponse(msg) {
10
+ return "result" in msg || "error" in msg;
11
+ }
12
+ /** Type guard: is this a notification (request with no id)? */
13
+ export function isNotification(msg) {
14
+ return msg.id === undefined || msg.id === null;
15
+ }
16
+ let nextId = 1;
17
+ /** Create a JSON-RPC 2.0 request. */
18
+ export function createRequest(method, params) {
19
+ return { jsonrpc: "2.0", id: `req-${nextId++}`, method, params };
20
+ }
21
+ /** Create a JSON-RPC 2.0 notification (no id, no response expected). */
22
+ export function createNotification(method, params) {
23
+ return { jsonrpc: "2.0", method, params };
24
+ }
25
+ /** Create a JSON-RPC 2.0 success response. */
26
+ export function createResponse(id, result) {
27
+ return { jsonrpc: "2.0", id, result };
28
+ }
29
+ /** Create a JSON-RPC 2.0 error response. */
30
+ export function createErrorResponse(id, error) {
31
+ return { jsonrpc: "2.0", id, error };
32
+ }
33
+ /** Parse a raw JSON string into a Message. Throws on invalid JSON-RPC. */
34
+ export function decodeMessage(data) {
35
+ const obj = JSON.parse(data);
36
+ if (obj.jsonrpc !== "2.0") {
37
+ throw new Error("Invalid JSON-RPC version");
38
+ }
39
+ return obj;
40
+ }
41
+ /** Parse raw JSON that may be a batch (array) or single message. */
42
+ export function decodeBatch(data) {
43
+ const obj = JSON.parse(data);
44
+ if (Array.isArray(obj)) {
45
+ return obj.map((item) => {
46
+ if (item.jsonrpc !== "2.0") {
47
+ throw new Error("Invalid JSON-RPC version in batch");
48
+ }
49
+ return item;
50
+ });
51
+ }
52
+ if (obj.jsonrpc !== "2.0") {
53
+ throw new Error("Invalid JSON-RPC version");
54
+ }
55
+ return [obj];
56
+ }
57
+ /** WMP-specific RPC error class. */
58
+ export class WMPError extends Error {
59
+ code;
60
+ data;
61
+ constructor(code, message, data) {
62
+ super(`wmp: rpc error ${code}: ${message}`);
63
+ this.name = "WMPError";
64
+ this.code = code;
65
+ this.data = data;
66
+ }
67
+ toRPCError() {
68
+ return { code: this.code, message: this.message, data: this.data };
69
+ }
70
+ }
71
+ /** Reset the request ID counter (for testing). */
72
+ export function resetRequestIdCounter() {
73
+ nextId = 1;
74
+ }
package/dist/mls.d.ts ADDED
@@ -0,0 +1,215 @@
1
+ /**
2
+ * WMP MLS types and handler interface — mirrors go-wmp/pkg/wmp/mls/mls.go.
3
+ *
4
+ * Defines MLS group lifecycle methods, types, and the MLSHandler interface
5
+ * per the wmp-mls spec. Actual MLS cryptographic operations are delegated
6
+ * to an MLSProvider implementation backed by an MLS library.
7
+ */
8
+ import type { Metadata } from "./types.js";
9
+ export declare const MLSMethod: {
10
+ readonly GroupCreate: "wmp.mls.group.create";
11
+ readonly GroupJoin: "wmp.mls.group.join";
12
+ readonly GroupAdd: "wmp.mls.group.add";
13
+ readonly GroupRemove: "wmp.mls.group.remove";
14
+ readonly GroupUpdate: "wmp.mls.group.update";
15
+ readonly MessageFetch: "wmp.message.fetch";
16
+ };
17
+ export type MLSMethodName = (typeof MLSMethod)[keyof typeof MLSMethod];
18
+ /** MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 — MUST support. */
19
+ export declare const CipherSuiteX25519AES128GCM = 1;
20
+ /** MLS_128_DHKEMP256_AES128GCM_SHA256_P256 — SHOULD support. */
21
+ export declare const CipherSuiteP256AES128GCM = 2;
22
+ export declare const CredentialType: {
23
+ readonly Basic: "basic";
24
+ readonly X509: "x509";
25
+ };
26
+ export interface GroupCreateParams {
27
+ wmp: Metadata;
28
+ group_id: string;
29
+ cipher_suite: number;
30
+ accepted_credential_types?: string[];
31
+ accepted_identity_schemes?: string[];
32
+ group_info: string;
33
+ welcomes: Record<string, string>;
34
+ }
35
+ export interface GroupCreateResult {
36
+ wmp: Metadata;
37
+ group_id: string;
38
+ epoch: number;
39
+ }
40
+ export interface GroupJoinParams {
41
+ wmp: Metadata;
42
+ welcome_processed: boolean;
43
+ }
44
+ export interface GroupJoinResult {
45
+ wmp: Metadata;
46
+ group_id: string;
47
+ epoch: number;
48
+ }
49
+ export interface GroupAddParams {
50
+ wmp: Metadata;
51
+ participant: string;
52
+ commit: string;
53
+ welcome: string;
54
+ }
55
+ export interface GroupAddResult {
56
+ wmp: Metadata;
57
+ epoch: number;
58
+ }
59
+ export interface GroupRemoveParams {
60
+ wmp: Metadata;
61
+ participant: string;
62
+ commit: string;
63
+ }
64
+ export interface GroupRemoveResult {
65
+ wmp: Metadata;
66
+ epoch: number;
67
+ }
68
+ export interface GroupUpdateParams {
69
+ wmp: Metadata;
70
+ commit: string;
71
+ }
72
+ export interface MessageFetchParams {
73
+ wmp: Metadata;
74
+ since_epoch?: number;
75
+ sessions?: string[];
76
+ }
77
+ export interface MessageFetchResult {
78
+ wmp: Metadata;
79
+ messages: unknown[];
80
+ has_more: boolean;
81
+ }
82
+ export interface KeyPackage {
83
+ id: string;
84
+ cipher_suite: number;
85
+ key_package: string;
86
+ expires: string;
87
+ }
88
+ export interface KeyPackagesResponse {
89
+ key_packages: KeyPackage[];
90
+ }
91
+ export interface EncryptedEnvelope {
92
+ wmp: Metadata;
93
+ ciphertext: string;
94
+ }
95
+ /**
96
+ * MLSHandler processes MLS group lifecycle operations.
97
+ * Implement this to manage MLS groups in your application.
98
+ */
99
+ export interface MLSHandler {
100
+ groupCreate(params: GroupCreateParams): Promise<GroupCreateResult>;
101
+ groupJoin(params: GroupJoinParams): Promise<GroupJoinResult>;
102
+ groupAdd(params: GroupAddParams): Promise<GroupAddResult>;
103
+ groupRemove(params: GroupRemoveParams): Promise<GroupRemoveResult>;
104
+ groupUpdate(params: GroupUpdateParams): Promise<void>;
105
+ messageFetch(params: MessageFetchParams): Promise<MessageFetchResult>;
106
+ }
107
+ /**
108
+ * MLSProvider abstracts MLS cryptographic operations. Implementations wrap
109
+ * an MLS library to provide key package generation, group management,
110
+ * and message encryption/decryption.
111
+ */
112
+ export interface MLSProvider {
113
+ generateKeyPackage(cipherSuite: number): Promise<KeyPackage>;
114
+ createGroup(cipherSuite: number, participants: string[]): Promise<{
115
+ groupInfo: string;
116
+ welcomes: Record<string, string>;
117
+ }>;
118
+ processWelcome(welcome: string): Promise<{
119
+ groupId: string;
120
+ epoch: number;
121
+ }>;
122
+ addMember(groupId: string, keyPackage: string): Promise<{
123
+ commit: string;
124
+ welcome: string;
125
+ }>;
126
+ removeMember(groupId: string, participant: string): Promise<{
127
+ commit: string;
128
+ }>;
129
+ processCommit(groupId: string, commit: string): Promise<{
130
+ epoch: number;
131
+ }>;
132
+ selfUpdate(groupId: string): Promise<{
133
+ commit: string;
134
+ }>;
135
+ encrypt(groupId: string, plaintext: Uint8Array): Promise<{
136
+ ciphertext: string;
137
+ epoch: number;
138
+ }>;
139
+ decrypt(groupId: string, ciphertext: string): Promise<{
140
+ plaintext: Uint8Array;
141
+ epoch: number;
142
+ }>;
143
+ }
144
+ import type { MethodHandler } from "./profile.js";
145
+ /**
146
+ * MLSProfile is a WMP MethodHandler that dispatches wmp.mls.* methods to an
147
+ * MLSHandler. Register it with the peer's registry to enable MLS support:
148
+ *
149
+ * const mlsProfile = new MLSProfile(handler);
150
+ * for (const method of mlsMethods()) {
151
+ * registry.registerMethod(method, mlsProfile);
152
+ * }
153
+ */
154
+ export declare class MLSProfile implements MethodHandler {
155
+ private handler;
156
+ constructor(handler: MLSHandler);
157
+ methods(): string[];
158
+ handleMethod(method: string, params: unknown): Promise<unknown>;
159
+ }
160
+ /**
161
+ * Returns the list of MLS method names for registration convenience.
162
+ */
163
+ export declare function mlsMethods(): string[];
164
+ /**
165
+ * NoopMLSHandler implements MLSHandler for TLS-only sessions.
166
+ * It accepts group lifecycle operations but performs no actual MLS
167
+ * cryptographic operations. Suitable for point-to-point sessions
168
+ * where transport-level TLS provides sufficient security.
169
+ */
170
+ export declare class NoopMLSHandler implements MLSHandler {
171
+ private groups;
172
+ groupCreate(params: GroupCreateParams): Promise<GroupCreateResult>;
173
+ groupJoin(params: GroupJoinParams): Promise<GroupJoinResult>;
174
+ groupAdd(params: GroupAddParams): Promise<GroupAddResult>;
175
+ groupRemove(params: GroupRemoveParams): Promise<GroupRemoveResult>;
176
+ groupUpdate(_params: GroupUpdateParams): Promise<void>;
177
+ messageFetch(params: MessageFetchParams): Promise<MessageFetchResult>;
178
+ }
179
+ /**
180
+ * NoopMLSProvider implements MLSProvider for TLS-only sessions.
181
+ * Messages pass through unencrypted, relying on transport-level TLS.
182
+ */
183
+ export declare class NoopMLSProvider implements MLSProvider {
184
+ private groups;
185
+ generateKeyPackage(cipherSuite: number): Promise<KeyPackage>;
186
+ createGroup(_cs: number, participants: string[]): Promise<{
187
+ groupInfo: string;
188
+ welcomes: Record<string, string>;
189
+ }>;
190
+ processWelcome(_welcome: string): Promise<{
191
+ groupId: string;
192
+ epoch: number;
193
+ }>;
194
+ addMember(groupId: string, _kp: string): Promise<{
195
+ commit: string;
196
+ welcome: string;
197
+ }>;
198
+ removeMember(groupId: string, _p: string): Promise<{
199
+ commit: string;
200
+ }>;
201
+ processCommit(groupId: string, _commit: string): Promise<{
202
+ epoch: number;
203
+ }>;
204
+ selfUpdate(groupId: string): Promise<{
205
+ commit: string;
206
+ }>;
207
+ encrypt(_groupId: string, plaintext: Uint8Array): Promise<{
208
+ ciphertext: string;
209
+ epoch: number;
210
+ }>;
211
+ decrypt(_groupId: string, ciphertext: string): Promise<{
212
+ plaintext: Uint8Array;
213
+ epoch: number;
214
+ }>;
215
+ }
package/dist/mls.js ADDED
@@ -0,0 +1,176 @@
1
+ /**
2
+ * WMP MLS types and handler interface — mirrors go-wmp/pkg/wmp/mls/mls.go.
3
+ *
4
+ * Defines MLS group lifecycle methods, types, and the MLSHandler interface
5
+ * per the wmp-mls spec. Actual MLS cryptographic operations are delegated
6
+ * to an MLSProvider implementation backed by an MLS library.
7
+ */
8
+ // ---------------------------------------------------------------------------
9
+ // Method constants
10
+ // ---------------------------------------------------------------------------
11
+ export const MLSMethod = {
12
+ GroupCreate: "wmp.mls.group.create",
13
+ GroupJoin: "wmp.mls.group.join",
14
+ GroupAdd: "wmp.mls.group.add",
15
+ GroupRemove: "wmp.mls.group.remove",
16
+ GroupUpdate: "wmp.mls.group.update",
17
+ MessageFetch: "wmp.message.fetch",
18
+ };
19
+ // ---------------------------------------------------------------------------
20
+ // Cipher suite constants
21
+ // ---------------------------------------------------------------------------
22
+ /** MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 — MUST support. */
23
+ export const CipherSuiteX25519AES128GCM = 0x0001;
24
+ /** MLS_128_DHKEMP256_AES128GCM_SHA256_P256 — SHOULD support. */
25
+ export const CipherSuiteP256AES128GCM = 0x0002;
26
+ // ---------------------------------------------------------------------------
27
+ // MLS credential types
28
+ // ---------------------------------------------------------------------------
29
+ export const CredentialType = {
30
+ Basic: "basic",
31
+ X509: "x509",
32
+ };
33
+ import { WMPError } from "./jsonrpc.js";
34
+ import { ErrorCode } from "./types.js";
35
+ /**
36
+ * MLSProfile is a WMP MethodHandler that dispatches wmp.mls.* methods to an
37
+ * MLSHandler. Register it with the peer's registry to enable MLS support:
38
+ *
39
+ * const mlsProfile = new MLSProfile(handler);
40
+ * for (const method of mlsMethods()) {
41
+ * registry.registerMethod(method, mlsProfile);
42
+ * }
43
+ */
44
+ export class MLSProfile {
45
+ handler;
46
+ constructor(handler) {
47
+ this.handler = handler;
48
+ }
49
+ methods() {
50
+ return mlsMethods();
51
+ }
52
+ async handleMethod(method, params) {
53
+ const p = params;
54
+ switch (method) {
55
+ case MLSMethod.GroupCreate:
56
+ return this.handler.groupCreate(p);
57
+ case MLSMethod.GroupJoin:
58
+ return this.handler.groupJoin(p);
59
+ case MLSMethod.GroupAdd:
60
+ return this.handler.groupAdd(p);
61
+ case MLSMethod.GroupRemove:
62
+ return this.handler.groupRemove(p);
63
+ case MLSMethod.GroupUpdate:
64
+ await this.handler.groupUpdate(p);
65
+ return undefined;
66
+ case MLSMethod.MessageFetch:
67
+ return this.handler.messageFetch(p);
68
+ default:
69
+ throw new WMPError(ErrorCode.MethodNotFound, `Unknown MLS method: ${method}`);
70
+ }
71
+ }
72
+ }
73
+ /**
74
+ * Returns the list of MLS method names for registration convenience.
75
+ */
76
+ export function mlsMethods() {
77
+ return Object.values(MLSMethod);
78
+ }
79
+ // ---------------------------------------------------------------------------
80
+ // NoopMLSHandler — TLS-only sessions
81
+ // ---------------------------------------------------------------------------
82
+ /**
83
+ * NoopMLSHandler implements MLSHandler for TLS-only sessions.
84
+ * It accepts group lifecycle operations but performs no actual MLS
85
+ * cryptographic operations. Suitable for point-to-point sessions
86
+ * where transport-level TLS provides sufficient security.
87
+ */
88
+ export class NoopMLSHandler {
89
+ groups = new Map();
90
+ async groupCreate(params) {
91
+ const members = new Set(Object.keys(params.welcomes));
92
+ if (params.wmp.sender)
93
+ members.add(params.wmp.sender);
94
+ this.groups.set(params.group_id, { epoch: 0, members });
95
+ return { wmp: params.wmp, group_id: params.group_id, epoch: 0 };
96
+ }
97
+ async groupJoin(params) {
98
+ return { wmp: params.wmp, group_id: "noop-group", epoch: 0 };
99
+ }
100
+ async groupAdd(params) {
101
+ for (const [, g] of this.groups) {
102
+ g.members.add(params.participant);
103
+ g.epoch++;
104
+ return { wmp: params.wmp, epoch: g.epoch };
105
+ }
106
+ throw new WMPError(ErrorCode.MLSError, "No group found");
107
+ }
108
+ async groupRemove(params) {
109
+ for (const [, g] of this.groups) {
110
+ g.members.delete(params.participant);
111
+ g.epoch++;
112
+ return { wmp: params.wmp, epoch: g.epoch };
113
+ }
114
+ throw new WMPError(ErrorCode.MLSError, "No group found");
115
+ }
116
+ async groupUpdate(_params) {
117
+ // Noop: no key rotation.
118
+ }
119
+ async messageFetch(params) {
120
+ return { wmp: params.wmp, messages: [], has_more: false };
121
+ }
122
+ }
123
+ /**
124
+ * NoopMLSProvider implements MLSProvider for TLS-only sessions.
125
+ * Messages pass through unencrypted, relying on transport-level TLS.
126
+ */
127
+ export class NoopMLSProvider {
128
+ groups = new Map();
129
+ async generateKeyPackage(cipherSuite) {
130
+ return {
131
+ id: "noop-kp-1",
132
+ cipher_suite: cipherSuite,
133
+ key_package: "",
134
+ expires: "2099-12-31T23:59:59Z",
135
+ };
136
+ }
137
+ async createGroup(_cs, participants) {
138
+ const welcomes = {};
139
+ for (const p of participants)
140
+ welcomes[p] = "";
141
+ return { groupInfo: "", welcomes };
142
+ }
143
+ async processWelcome(_welcome) {
144
+ return { groupId: "noop-group", epoch: 0 };
145
+ }
146
+ async addMember(groupId, _kp) {
147
+ const g = this.groups.get(groupId) ?? { epoch: 0 };
148
+ g.epoch++;
149
+ this.groups.set(groupId, g);
150
+ return { commit: "", welcome: "" };
151
+ }
152
+ async removeMember(groupId, _p) {
153
+ const g = this.groups.get(groupId) ?? { epoch: 0 };
154
+ g.epoch++;
155
+ this.groups.set(groupId, g);
156
+ return { commit: "" };
157
+ }
158
+ async processCommit(groupId, _commit) {
159
+ const g = this.groups.get(groupId) ?? { epoch: 0 };
160
+ g.epoch++;
161
+ this.groups.set(groupId, g);
162
+ return { epoch: g.epoch };
163
+ }
164
+ async selfUpdate(groupId) {
165
+ const g = this.groups.get(groupId) ?? { epoch: 0 };
166
+ g.epoch++;
167
+ this.groups.set(groupId, g);
168
+ return { commit: "" };
169
+ }
170
+ async encrypt(_groupId, plaintext) {
171
+ return { ciphertext: new TextDecoder().decode(plaintext), epoch: 0 };
172
+ }
173
+ async decrypt(_groupId, ciphertext) {
174
+ return { plaintext: new TextEncoder().encode(ciphertext), epoch: 0 };
175
+ }
176
+ }