@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.
@@ -7,8 +7,28 @@ export interface WellKnownConfig {
7
7
  endpoints: Record<string, string>;
8
8
  security_modes: string[];
9
9
  capabilities?: Record<string, unknown>;
10
+ accepted_schemes?: string[];
11
+ mls_key_packages?: string;
12
+ relay?: string;
10
13
  identity_providers?: string[];
11
14
  trust_frameworks?: string[];
15
+ erds?: ErdsMetadata;
16
+ recipient_metadata?: RecipientMetadata;
17
+ }
18
+ export interface ErdsMetadata {
19
+ consignment_modes?: string[];
20
+ assurance_levels?: string[];
21
+ supported_policies?: string[];
22
+ delegation?: boolean;
23
+ evidence_repository?: string;
24
+ evidence_retention?: string;
25
+ scheduled_delivery?: boolean;
26
+ }
27
+ export interface RecipientMetadata {
28
+ accepted_content_types?: string[];
29
+ max_message_size?: number;
30
+ consignment_preferences?: string;
31
+ encryption_required?: boolean;
12
32
  }
13
33
  /**
14
34
  * Extract the domain from a WMP identifier.
@@ -20,7 +40,12 @@ export declare function extractDomain(identifier: string): string;
20
40
  /**
21
41
  * Fetch the well-known WMP configuration for any WMP identifier.
22
42
  *
23
- * Extracts the domain and fetches `https://<domain>/.well-known/wmp-configuration`.
24
- * Throws if no domain can be extracted or the fetch fails.
43
+ * For a full URL (e.g. `https://host/wmp-engine/wmp`), tries the well-known
44
+ * at the URL's own path prefix FIRST (`https://host/wmp-engine/.well-known/
45
+ * wmp-configuration`) — path-prefixed deployments (a reverse proxy's
46
+ * location) serve it there — and falls back to the domain root.
47
+ * For bare identifiers (domains, DIDs), fetches the domain root.
48
+ *
49
+ * Throws if no domain can be extracted or every fetch fails.
25
50
  */
26
51
  export declare function discoverEndpoint(identifier: string, fetchFn?: typeof globalThis.fetch): Promise<WellKnownConfig>;
package/dist/discovery.js CHANGED
@@ -31,28 +31,71 @@ export function extractDomain(identifier) {
31
31
  }
32
32
  if (identifier.startsWith("did:web:")) {
33
33
  const rest = identifier.slice("did:web:".length);
34
- const domain = rest.split(":")[0];
35
- return decodeURIComponent(domain);
34
+ let domain;
35
+ try {
36
+ domain = decodeURIComponent(rest.split(":")[0]);
37
+ }
38
+ catch {
39
+ return "";
40
+ }
41
+ // Reject empty, overly long, or malformed hostnames.
42
+ if (!domain ||
43
+ domain.length > 253 ||
44
+ !/^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/i.test(domain)) {
45
+ return "";
46
+ }
47
+ return domain;
36
48
  }
37
49
  return "";
38
50
  }
39
51
  /**
40
52
  * Fetch the well-known WMP configuration for any WMP identifier.
41
53
  *
42
- * Extracts the domain and fetches `https://<domain>/.well-known/wmp-configuration`.
43
- * Throws if no domain can be extracted or the fetch fails.
54
+ * For a full URL (e.g. `https://host/wmp-engine/wmp`), tries the well-known
55
+ * at the URL's own path prefix FIRST (`https://host/wmp-engine/.well-known/
56
+ * wmp-configuration`) — path-prefixed deployments (a reverse proxy's
57
+ * location) serve it there — and falls back to the domain root.
58
+ * For bare identifiers (domains, DIDs), fetches the domain root.
59
+ *
60
+ * Throws if no domain can be extracted or every fetch fails.
44
61
  */
45
62
  export async function discoverEndpoint(identifier, fetchFn = globalThis.fetch.bind(globalThis)) {
46
63
  const domain = extractDomain(identifier);
47
64
  if (!domain) {
48
65
  throw new Error(`Cannot extract domain from identifier "${identifier}": use session parameters or a profile resolver`);
49
66
  }
50
- const url = `https://${domain}/.well-known/wmp-configuration`;
51
- const resp = await fetchFn(url, {
52
- headers: { Accept: "application/json" },
53
- });
54
- if (!resp.ok) {
55
- throw new Error(`WMP discovery failed for ${url}: HTTP ${resp.status}`);
67
+ // The candidate well-known URLs, first-wins: the URL's own path prefix
68
+ // (a reverse-proxied deployment), then the domain root.
69
+ const candidates = [];
70
+ if (identifier.startsWith("https://")) {
71
+ try {
72
+ const url = new URL(identifier);
73
+ const path = url.pathname.replace(/\/+$/, "").replace(/\/wmp$/, "");
74
+ if (path && path !== "/") {
75
+ candidates.push(`${url.origin}${path}/.well-known/wmp-configuration`);
76
+ }
77
+ }
78
+ catch {
79
+ // fall through to the domain root
80
+ }
81
+ }
82
+ candidates.push(`https://${domain}/.well-known/wmp-configuration`);
83
+ let lastError;
84
+ for (const url of candidates) {
85
+ try {
86
+ const resp = await fetchFn(url, {
87
+ headers: { Accept: "application/json" },
88
+ });
89
+ if (resp.ok) {
90
+ return (await resp.json());
91
+ }
92
+ lastError = new Error(`WMP discovery failed for ${url}: HTTP ${resp.status}`);
93
+ }
94
+ catch (err) {
95
+ lastError = err;
96
+ }
56
97
  }
57
- return (await resp.json());
98
+ throw lastError instanceof Error
99
+ ? lastError
100
+ : new Error(`WMP discovery failed for ${identifier}`);
58
101
  }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * WMP Evidence types — ETSI EN 319 522 (QERDS) alignment.
3
+ * See wmp-evidence.md for the specification.
4
+ */
5
+ export declare const EvidenceEvent: {
6
+ readonly Submitted: "submitted";
7
+ readonly SubmissionAccepted: "submission_accepted";
8
+ readonly SubmissionRejected: "submission_rejected";
9
+ readonly RelayAccepted: "relay_accepted";
10
+ readonly RelayFailed: "relay_failed";
11
+ readonly Delivered: "delivered";
12
+ readonly DeliveryFailed: "delivery_failed";
13
+ readonly Retrieved: "retrieved";
14
+ readonly RetrievalFailed: "retrieval_failed";
15
+ readonly ContentAccessTracked: "content_access_tracked";
16
+ readonly Accepted: "accepted";
17
+ readonly Rejected: "rejected";
18
+ readonly AcceptanceExpired: "acceptance_expired";
19
+ readonly ContentHandover: "content_handover";
20
+ readonly ContentHandoverFailed: "content_handover_failed";
21
+ readonly NotificationSent: "notification_sent";
22
+ readonly NotificationFailed: "notification_failed";
23
+ readonly NotificationDelivered: "notification_delivered";
24
+ readonly RelayToExternal: "relay_to_external";
25
+ readonly RelayToExternalFailed: "relay_to_external_failed";
26
+ readonly ReceivedFromExternal: "received_from_external";
27
+ };
28
+ export type EvidenceEventType = (typeof EvidenceEvent)[keyof typeof EvidenceEvent];
29
+ export declare const EventReasonCode: {
30
+ readonly PolicyViolation: "policy_violation";
31
+ readonly QuotaExceeded: "quota_exceeded";
32
+ readonly InvalidFormat: "invalid_format";
33
+ readonly InvalidRecipient: "invalid_recipient";
34
+ readonly InsufficientAssurance: "insufficient_assurance";
35
+ readonly ConsignmentModeUnsupported: "consignment_mode_unsupported";
36
+ readonly PolicyUnsupported: "policy_unsupported";
37
+ readonly RecipientRejected: "recipient_rejected";
38
+ readonly Timeout: "timeout";
39
+ readonly SystemError: "system_error";
40
+ readonly DelegationInvalid: "delegation_invalid";
41
+ };
42
+ export interface EvidenceEventReason {
43
+ code: string;
44
+ text?: string;
45
+ details?: Record<string, unknown>;
46
+ }
47
+ export interface EvidenceIssuer {
48
+ id: string;
49
+ name?: string;
50
+ country?: string;
51
+ }
52
+ export interface ExternalSystem {
53
+ type: string;
54
+ id: string;
55
+ }
56
+ export interface ExternalErds {
57
+ id: string;
58
+ name?: string;
59
+ policy?: string;
60
+ }
61
+ export interface EvidenceNotifyParams {
62
+ wmp: import("./types.js").Metadata;
63
+ evidence_id: string;
64
+ event_type: string;
65
+ evidence_version: string;
66
+ timestamp: string;
67
+ message_id?: string;
68
+ session_id?: string;
69
+ sender?: string;
70
+ recipient?: string;
71
+ event_reason?: EvidenceEventReason;
72
+ original_sender_delegate?: {
73
+ id: string;
74
+ identity_attributes?: Record<string, unknown>;
75
+ };
76
+ original_recipient_delegate?: {
77
+ id: string;
78
+ identity_attributes?: Record<string, unknown>;
79
+ };
80
+ submission_time?: string;
81
+ evidence_issuer_policy?: string[];
82
+ evidence_issuer?: EvidenceIssuer;
83
+ sender_assurance_level?: string;
84
+ recipient_assurance_level?: string;
85
+ sender_identity_attributes?: Record<string, unknown>;
86
+ recipient_identity_attributes?: Record<string, unknown>;
87
+ evidence_refers_to_recipient?: string;
88
+ external_system?: ExternalSystem;
89
+ external_erds?: ExternalErds;
90
+ transaction_log?: string;
91
+ extensions?: Record<string, unknown>;
92
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * WMP Evidence types — ETSI EN 319 522 (QERDS) alignment.
3
+ * See wmp-evidence.md for the specification.
4
+ */
5
+ // ---------------------------------------------------------------------------
6
+ // Evidence event types
7
+ // ---------------------------------------------------------------------------
8
+ export const EvidenceEvent = {
9
+ // Submission
10
+ Submitted: "submitted",
11
+ SubmissionAccepted: "submission_accepted",
12
+ SubmissionRejected: "submission_rejected",
13
+ // Relay
14
+ RelayAccepted: "relay_accepted",
15
+ RelayFailed: "relay_failed",
16
+ // Delivery
17
+ Delivered: "delivered",
18
+ DeliveryFailed: "delivery_failed",
19
+ // Retrieval
20
+ Retrieved: "retrieved",
21
+ RetrievalFailed: "retrieval_failed",
22
+ ContentAccessTracked: "content_access_tracked",
23
+ // Acceptance
24
+ Accepted: "accepted",
25
+ Rejected: "rejected",
26
+ AcceptanceExpired: "acceptance_expired",
27
+ // Consignment
28
+ ContentHandover: "content_handover",
29
+ ContentHandoverFailed: "content_handover_failed",
30
+ // Notification
31
+ NotificationSent: "notification_sent",
32
+ NotificationFailed: "notification_failed",
33
+ NotificationDelivered: "notification_delivered",
34
+ // Gateway
35
+ RelayToExternal: "relay_to_external",
36
+ RelayToExternalFailed: "relay_to_external_failed",
37
+ ReceivedFromExternal: "received_from_external",
38
+ };
39
+ // ---------------------------------------------------------------------------
40
+ // Evidence event reason codes
41
+ // ---------------------------------------------------------------------------
42
+ export const EventReasonCode = {
43
+ PolicyViolation: "policy_violation",
44
+ QuotaExceeded: "quota_exceeded",
45
+ InvalidFormat: "invalid_format",
46
+ InvalidRecipient: "invalid_recipient",
47
+ InsufficientAssurance: "insufficient_assurance",
48
+ ConsignmentModeUnsupported: "consignment_mode_unsupported",
49
+ PolicyUnsupported: "policy_unsupported",
50
+ RecipientRejected: "recipient_rejected",
51
+ Timeout: "timeout",
52
+ SystemError: "system_error",
53
+ DelegationInvalid: "delegation_invalid",
54
+ };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * @siros/wmp — Wallet Messaging Protocol client library
3
3
  */
4
- export { VERSION, Method, ErrorCode, FlowType, CloseReason, AckStatus, CancelReason, ResolveType, ServiceClass, AuthType, } from "./types.js";
5
- export type { Metadata, IdentityAssertion, TrustHint, RelayEntry, SecurityMode, Capabilities, AuthObject, SessionCreateParams, SessionCreateResult, SessionResumeParams, SessionResumeResult, 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";
4
+ export { VERSION, Method, ErrorCode, FlowType, CloseReason, AckStatus, ConsignmentMode, AssuranceLevel, CancelReason, ResolveType, ServiceClass, AuthType, } from "./types.js";
5
+ export type { Metadata, IdentityAssertion, TrustHint, RelayEntry, SenderDelegate, DelegateAuthorization, SecurityMode, Capabilities, AuthObject, SessionCreateParams, SessionCreateResult, SessionResumeParams, SessionResumeResult, 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
6
  export { WMPError, createRequest, createNotification, createResponse, createErrorResponse, decodeMessage, decodeBatch, isRequest, isResponse, isNotification, } from "./jsonrpc.js";
7
7
  export type { RPCError, Request, Response, Message } from "./jsonrpc.js";
8
8
  export { WebSocketTransport, HttpSseTransport } from "./transport.js";
@@ -12,12 +12,19 @@ export type { Profile, PeerContext, FlowHandler, MethodHandler, ResolveHandler,
12
12
  export { Peer } from "./peer.js";
13
13
  export type { Handler, PeerOptions } from "./peer.js";
14
14
  export { MLSMethod, CipherSuiteX25519AES128GCM, CipherSuiteP256AES128GCM, CredentialType, MLSProfile, mlsMethods, NoopMLSHandler, NoopMLSProvider, } from "./mls.js";
15
+ export { TsMlsProvider } from "./mls-provider.js";
16
+ export type { TsMlsProviderOptions } from "./mls-provider.js";
15
17
  export type { MLSMethodName, GroupCreateParams, GroupCreateResult, GroupJoinParams, GroupJoinResult, GroupAddParams, GroupAddResult, GroupRemoveParams, GroupRemoveResult, GroupUpdateParams, MessageFetchParams, MessageFetchResult, KeyPackage, KeyPackagesResponse, EncryptedEnvelope, MLSHandler, MLSProvider, } from "./mls.js";
16
18
  export { CredentialFormat, allFormats, isValidFormat, GrantType, ResponseMode, ProofType, OID4FlowType, VCIStep, VPStep, OID4Action, OpenID4xProfile, buildVCIFlowStart, withAttestation, } from "./openid4x.js";
17
19
  export type { CredentialFormatType, OID4VCICapability, OID4VPCapability, CredentialDisplay, CredentialConfigurationSupported, CredentialResult, CredentialEvent, CredentialNotificationParams, VPTokenResult, ClientAttestation, ClientAttestationProvider, OID4VCIFlowParams, OID4VPFlowParams, SignSubFlowParams, SelectionAction, ConsentAction, CredentialSelection, FlowStartHandler, ActionHandler, OpenID4xConfig, } from "./openid4x.js";
20
+ export { EvidenceEvent, EventReasonCode } from "./evidence.js";
21
+ export type { EvidenceEventType, EvidenceEventReason, EvidenceIssuer, ExternalSystem, ExternalErds, EvidenceNotifyParams, } from "./evidence.js";
18
22
  export { Relay } from "./relay.js";
19
23
  export type { RelayConfig, QueuedMessage } from "./relay.js";
24
+ export { MemorySessionStore } from "./session-store.js";
25
+ export type { Session, SessionStore } from "./session-store.js";
20
26
  export { extractDomain, discoverEndpoint } from "./discovery.js";
21
27
  export type { WellKnownConfig } from "./discovery.js";
28
+ export type { ErdsMetadata, RecipientMetadata } from "./discovery.js";
22
29
  export { InvitationPurpose, createInvitation, invitationSigningPayload, invitationToURI, invitationToHTTPSURI, parseInvitationURI, parseInvitationJSON, isInvitationExpired, generateNonce, MemoryInvitationStore, validateInvitationNonce, } from "./invitation.js";
23
30
  export type { Invitation, CreateInvitationOptions, InvitationStore, } from "./invitation.js";
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * @siros/wmp — Wallet Messaging Protocol client library
3
3
  */
4
4
  // Types
5
- export { VERSION, Method, ErrorCode, FlowType, CloseReason, AckStatus, CancelReason, ResolveType, ServiceClass, AuthType, } from "./types.js";
5
+ export { VERSION, Method, ErrorCode, FlowType, CloseReason, AckStatus, ConsignmentMode, AssuranceLevel, CancelReason, ResolveType, ServiceClass, AuthType, } from "./types.js";
6
6
  // JSON-RPC
7
7
  export { WMPError, createRequest, createNotification, createResponse, createErrorResponse, decodeMessage, decodeBatch, isRequest, isResponse, isNotification, } from "./jsonrpc.js";
8
8
  // Transport
@@ -13,10 +13,15 @@ export { Registry } from "./profile.js";
13
13
  export { Peer } from "./peer.js";
14
14
  // MLS
15
15
  export { MLSMethod, CipherSuiteX25519AES128GCM, CipherSuiteP256AES128GCM, CredentialType, MLSProfile, mlsMethods, NoopMLSHandler, NoopMLSProvider, } from "./mls.js";
16
+ export { TsMlsProvider } from "./mls-provider.js";
16
17
  // OpenID4x
17
18
  export { CredentialFormat, allFormats, isValidFormat, GrantType, ResponseMode, ProofType, OID4FlowType, VCIStep, VPStep, OID4Action, OpenID4xProfile, buildVCIFlowStart, withAttestation, } from "./openid4x.js";
19
+ // Evidence (ERDS)
20
+ export { EvidenceEvent, EventReasonCode } from "./evidence.js";
18
21
  // Relay
19
22
  export { Relay } from "./relay.js";
23
+ // Session store (server-side)
24
+ export { MemorySessionStore } from "./session-store.js";
20
25
  // Discovery
21
26
  export { extractDomain, discoverEndpoint } from "./discovery.js";
22
27
  // Invitation
@@ -84,6 +84,26 @@ export declare function parseInvitationJSON(data: string | object): Invitation;
84
84
  * Check whether an invitation has expired.
85
85
  */
86
86
  export declare function isInvitationExpired(inv: Invitation): boolean;
87
+ /**
88
+ * Verify the detached JWS signature of an invitation.
89
+ *
90
+ * The verifier receives the canonical signing payload (as a Uint8Array) and
91
+ * the detached signature string. It must return true iff the signature is
92
+ * valid for the sender's public key.
93
+ *
94
+ * IMPORTANT: parseInvitationURI / parseInvitationJSON do NOT verify the
95
+ * signature. Callers must call verifyInvitation before trusting an invitation.
96
+ */
97
+ export type InvitationVerifier = (payload: Uint8Array, signature: string) => boolean | Promise<boolean>;
98
+ /**
99
+ * Verify an invitation's signature and expiry.
100
+ *
101
+ * @param inv The parsed invitation.
102
+ * @param verifier Callback that verifies the detached JWS signature.
103
+ * @returns The invitation if valid.
104
+ * @throws Error if the invitation is expired or the signature is invalid.
105
+ */
106
+ export declare function verifyInvitation(inv: Invitation, verifier: InvitationVerifier): Promise<Invitation>;
87
107
  /**
88
108
  * InvitationStore tracks issued invitation nonces.
89
109
  */
@@ -139,6 +139,28 @@ export function parseInvitationJSON(data) {
139
139
  export function isInvitationExpired(inv) {
140
140
  return new Date(inv.expires_at).getTime() < Date.now();
141
141
  }
142
+ /**
143
+ * Verify an invitation's signature and expiry.
144
+ *
145
+ * @param inv The parsed invitation.
146
+ * @param verifier Callback that verifies the detached JWS signature.
147
+ * @returns The invitation if valid.
148
+ * @throws Error if the invitation is expired or the signature is invalid.
149
+ */
150
+ export async function verifyInvitation(inv, verifier) {
151
+ if (isInvitationExpired(inv)) {
152
+ throw new Error("invitation expired");
153
+ }
154
+ if (!inv.signature) {
155
+ throw new Error("invitation missing signature");
156
+ }
157
+ const payload = new TextEncoder().encode(JSON.stringify(invitationSigningPayload(inv)));
158
+ const valid = await verifier(payload, inv.signature);
159
+ if (!valid) {
160
+ throw new Error("invitation signature verification failed");
161
+ }
162
+ return inv;
163
+ }
142
164
  /**
143
165
  * Thread-safe (single-threaded JS) in-memory invitation store.
144
166
  */
package/dist/jsonrpc.d.ts CHANGED
@@ -33,10 +33,16 @@ export declare function createNotification(method: string, params: unknown): Req
33
33
  export declare function createResponse(id: string | number | null, result: unknown): Response;
34
34
  /** Create a JSON-RPC 2.0 error response. */
35
35
  export declare function createErrorResponse(id: string | number | null, error: RPCError): Response;
36
+ export interface DecodeOptions {
37
+ /** Maximum payload length in characters. Default: 4 MB. */
38
+ maxSize?: number;
39
+ /** Maximum object/array nesting depth. Default: 32. */
40
+ maxDepth?: number;
41
+ }
36
42
  /** Parse a raw JSON string into a Message. Throws on invalid JSON-RPC. */
37
- export declare function decodeMessage(data: string): Message;
43
+ export declare function decodeMessage(data: string, opts?: DecodeOptions): Message;
38
44
  /** Parse raw JSON that may be a batch (array) or single message. */
39
- export declare function decodeBatch(data: string): Message[];
45
+ export declare function decodeBatch(data: string, opts?: DecodeOptions): Message[];
40
46
  /** WMP-specific RPC error class. */
41
47
  export declare class WMPError extends Error {
42
48
  readonly code: number;
@@ -44,5 +50,5 @@ export declare class WMPError extends Error {
44
50
  constructor(code: number, message: string, data?: unknown);
45
51
  toRPCError(): RPCError;
46
52
  }
47
- /** Reset the request ID counter (for testing). */
53
+ /** @deprecated Request IDs are now random; this function is a no-op for compatibility. */
48
54
  export declare function resetRequestIdCounter(): void;
package/dist/jsonrpc.js CHANGED
@@ -13,10 +13,19 @@ export function isResponse(msg) {
13
13
  export function isNotification(msg) {
14
14
  return msg.id === undefined || msg.id === null;
15
15
  }
16
- let nextId = 1;
16
+ /** Generate a cryptographically random request ID. */
17
+ function generateRequestId() {
18
+ const bytes = new Uint8Array(16);
19
+ globalThis.crypto.getRandomValues(bytes);
20
+ const b64 = btoa(String.fromCharCode(...bytes))
21
+ .replace(/\+/g, "-")
22
+ .replace(/\//g, "_")
23
+ .replace(/=+$/, "");
24
+ return `req-${b64}`;
25
+ }
17
26
  /** Create a JSON-RPC 2.0 request. */
18
27
  export function createRequest(method, params) {
19
- return { jsonrpc: "2.0", id: `req-${nextId++}`, method, params };
28
+ return { jsonrpc: "2.0", id: generateRequestId(), method, params };
20
29
  }
21
30
  /** Create a JSON-RPC 2.0 notification (no id, no response expected). */
22
31
  export function createNotification(method, params) {
@@ -30,17 +39,58 @@ export function createResponse(id, result) {
30
39
  export function createErrorResponse(id, error) {
31
40
  return { jsonrpc: "2.0", id, error };
32
41
  }
42
+ const DEFAULT_MAX_SIZE = 4 * 1024 * 1024;
43
+ const DEFAULT_MAX_DEPTH = 32;
44
+ function parseJSONRPC(data, maxSize, maxDepth) {
45
+ if (data.length > maxSize) {
46
+ throw new Error("JSON-RPC message exceeds maximum size");
47
+ }
48
+ try {
49
+ return JSON.parse(data, (_key, value) => {
50
+ if (value !== null && typeof value === "object") {
51
+ checkDepth(value, 1, maxDepth);
52
+ }
53
+ return value;
54
+ });
55
+ }
56
+ catch (err) {
57
+ if (err instanceof Error && err.message.includes("depth")) {
58
+ throw err;
59
+ }
60
+ throw new Error("Invalid JSON-RPC payload");
61
+ }
62
+ }
63
+ function checkDepth(value, depth, maxDepth) {
64
+ if (depth > maxDepth) {
65
+ throw new Error("JSON-RPC message exceeds maximum nesting depth");
66
+ }
67
+ if (Array.isArray(value)) {
68
+ for (const item of value)
69
+ checkDepth(item, depth + 1, maxDepth);
70
+ }
71
+ else if (value !== null && typeof value === "object") {
72
+ for (const key in value) {
73
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
74
+ checkDepth(value[key], depth + 1, maxDepth);
75
+ }
76
+ }
77
+ }
78
+ }
33
79
  /** 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") {
80
+ export function decodeMessage(data, opts) {
81
+ const maxSize = opts?.maxSize ?? DEFAULT_MAX_SIZE;
82
+ const maxDepth = opts?.maxDepth ?? DEFAULT_MAX_DEPTH;
83
+ const obj = parseJSONRPC(data, maxSize, maxDepth);
84
+ if (obj === null || typeof obj !== "object" || obj.jsonrpc !== "2.0") {
37
85
  throw new Error("Invalid JSON-RPC version");
38
86
  }
39
87
  return obj;
40
88
  }
41
89
  /** Parse raw JSON that may be a batch (array) or single message. */
42
- export function decodeBatch(data) {
43
- const obj = JSON.parse(data);
90
+ export function decodeBatch(data, opts) {
91
+ const maxSize = opts?.maxSize ?? DEFAULT_MAX_SIZE;
92
+ const maxDepth = opts?.maxDepth ?? DEFAULT_MAX_DEPTH;
93
+ const obj = parseJSONRPC(data, maxSize, maxDepth);
44
94
  if (Array.isArray(obj)) {
45
95
  return obj.map((item) => {
46
96
  if (item.jsonrpc !== "2.0") {
@@ -49,7 +99,7 @@ export function decodeBatch(data) {
49
99
  return item;
50
100
  });
51
101
  }
52
- if (obj.jsonrpc !== "2.0") {
102
+ if (obj === null || typeof obj !== "object" || obj.jsonrpc !== "2.0") {
53
103
  throw new Error("Invalid JSON-RPC version");
54
104
  }
55
105
  return [obj];
@@ -68,7 +118,7 @@ export class WMPError extends Error {
68
118
  return { code: this.code, message: this.message, data: this.data };
69
119
  }
70
120
  }
71
- /** Reset the request ID counter (for testing). */
121
+ /** @deprecated Request IDs are now random; this function is a no-op for compatibility. */
72
122
  export function resetRequestIdCounter() {
73
- nextId = 1;
123
+ // no-op: IDs are cryptographically random.
74
124
  }
@@ -0,0 +1,65 @@
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 type { MLSProvider, KeyPackage } from "./mls.js";
10
+ export interface TsMlsProviderOptions {
11
+ /** Identity string for this participant (e.g., "wmp-inspector"). */
12
+ identity: string;
13
+ /** Default cipher suite. Default: 0x0001 (X25519). */
14
+ defaultCipherSuite?: number;
15
+ }
16
+ /**
17
+ * Real MLS provider using ts-mls.
18
+ *
19
+ * Each instance represents one MLS participant. It can generate key packages,
20
+ * create/join groups, encrypt/decrypt messages, and manage group membership.
21
+ */
22
+ export declare class TsMlsProvider implements MLSProvider {
23
+ private identity;
24
+ private defaultCipherSuite;
25
+ private implCache;
26
+ private groups;
27
+ private keyPackages;
28
+ constructor(opts: TsMlsProviderOptions);
29
+ private getImpl;
30
+ private makeCredential;
31
+ generateKeyPackage(cipherSuite: number): Promise<KeyPackage>;
32
+ createGroup(cipherSuite: number, _participants: string[]): Promise<{
33
+ groupInfo: string;
34
+ welcomes: Record<string, string>;
35
+ }>;
36
+ processWelcome(welcome: string): Promise<{
37
+ groupId: string;
38
+ epoch: number;
39
+ }>;
40
+ addMember(groupId: string, keyPackage: string): Promise<{
41
+ commit: string;
42
+ welcome: string;
43
+ }>;
44
+ removeMember(groupId: string, _participant: string): Promise<{
45
+ commit: string;
46
+ }>;
47
+ processCommit(groupId: string, commit: string): Promise<{
48
+ epoch: number;
49
+ }>;
50
+ selfUpdate(groupId: string): Promise<{
51
+ commit: string;
52
+ }>;
53
+ encrypt(groupId: string, plaintext: Uint8Array): Promise<{
54
+ ciphertext: string;
55
+ epoch: number;
56
+ }>;
57
+ decrypt(groupId: string, ciphertext: string): Promise<{
58
+ plaintext: Uint8Array;
59
+ epoch: number;
60
+ }>;
61
+ private getGroup;
62
+ private getLatestKeyPackage;
63
+ get groupCount(): number;
64
+ get keyPackageCount(): number;
65
+ }