@sirosfoundation/wmp-js 0.2.0 → 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/README.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # @sirosfoundation/wmp-js
2
2
 
3
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
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/sirosfoundation/wmp-js/badge)](https://scorecard.dev/viewer/?uri=github.com/sirosfoundation/wmp-js)
4
5
  [![License](https://img.shields.io/badge/license-BSD--2--Clause-blue)](LICENSE)
5
6
 
6
7
  TypeScript implementation of the Wallet Messaging Protocol (WMP) — a JSON-RPC 2.0 protocol for bidirectional communication between wallet frontends and backend services.
@@ -0,0 +1,46 @@
1
+ /**
2
+ * WMP endpoint discovery — mirrors go-wmp/pkg/wmp/discovery.go.
3
+ */
4
+ /** Well-known WMP configuration as served at /.well-known/wmp-configuration. */
5
+ export interface WellKnownConfig {
6
+ supported_versions: string[];
7
+ endpoints: Record<string, string>;
8
+ security_modes: string[];
9
+ capabilities?: Record<string, unknown>;
10
+ accepted_schemes?: string[];
11
+ mls_key_packages?: string;
12
+ relay?: string;
13
+ identity_providers?: string[];
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;
32
+ }
33
+ /**
34
+ * Extract the domain from a WMP identifier.
35
+ *
36
+ * Supports x509:san:dns, x509:san:uri, https://, and did:web schemes.
37
+ * Returns an empty string if the scheme is not recognised (e.g. did:key).
38
+ */
39
+ export declare function extractDomain(identifier: string): string;
40
+ /**
41
+ * Fetch the well-known WMP configuration for any WMP identifier.
42
+ *
43
+ * Extracts the domain and fetches `https://<domain>/.well-known/wmp-configuration`.
44
+ * Throws if no domain can be extracted or the fetch fails.
45
+ */
46
+ export declare function discoverEndpoint(identifier: string, fetchFn?: typeof globalThis.fetch): Promise<WellKnownConfig>;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * WMP endpoint discovery — mirrors go-wmp/pkg/wmp/discovery.go.
3
+ */
4
+ /**
5
+ * Extract the domain from a WMP identifier.
6
+ *
7
+ * Supports x509:san:dns, x509:san:uri, https://, and did:web schemes.
8
+ * Returns an empty string if the scheme is not recognised (e.g. did:key).
9
+ */
10
+ export function extractDomain(identifier) {
11
+ if (identifier.startsWith("x509:san:dns:")) {
12
+ return identifier.slice("x509:san:dns:".length);
13
+ }
14
+ if (identifier.startsWith("x509:san:uri:")) {
15
+ try {
16
+ const url = new URL(identifier.slice("x509:san:uri:".length));
17
+ return url.hostname;
18
+ }
19
+ catch {
20
+ return "";
21
+ }
22
+ }
23
+ if (identifier.startsWith("https://")) {
24
+ try {
25
+ const url = new URL(identifier);
26
+ return url.hostname;
27
+ }
28
+ catch {
29
+ return "";
30
+ }
31
+ }
32
+ if (identifier.startsWith("did:web:")) {
33
+ const rest = identifier.slice("did:web:".length);
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;
48
+ }
49
+ return "";
50
+ }
51
+ /**
52
+ * Fetch the well-known WMP configuration for any WMP identifier.
53
+ *
54
+ * Extracts the domain and fetches `https://<domain>/.well-known/wmp-configuration`.
55
+ * Throws if no domain can be extracted or the fetch fails.
56
+ */
57
+ export async function discoverEndpoint(identifier, fetchFn = globalThis.fetch.bind(globalThis)) {
58
+ const domain = extractDomain(identifier);
59
+ if (!domain) {
60
+ throw new Error(`Cannot extract domain from identifier "${identifier}": use session parameters or a profile resolver`);
61
+ }
62
+ const url = `https://${domain}/.well-known/wmp-configuration`;
63
+ const resp = await fetchFn(url, {
64
+ headers: { Accept: "application/json" },
65
+ });
66
+ if (!resp.ok) {
67
+ throw new Error(`WMP discovery failed for ${url}: HTTP ${resp.status}`);
68
+ }
69
+ return (await resp.json());
70
+ }
@@ -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, } 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";
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,8 +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
- 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 { CredentialFormat, allFormats, isValidFormat, GrantType, ResponseMode, ProofType, OID4FlowType, VCIStep, VPStep, OID4Action, OpenID4xProfile, buildVCIFlowStart, withAttestation, } from "./openid4x.js";
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";
26
+ export { extractDomain, discoverEndpoint } from "./discovery.js";
27
+ export type { WellKnownConfig } from "./discovery.js";
28
+ export type { ErdsMetadata, RecipientMetadata } from "./discovery.js";
29
+ export { InvitationPurpose, createInvitation, invitationSigningPayload, invitationToURI, invitationToHTTPSURI, parseInvitationURI, parseInvitationJSON, isInvitationExpired, generateNonce, MemoryInvitationStore, validateInvitationNonce, } from "./invitation.js";
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, } 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,7 +13,16 @@ 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
- export { CredentialFormat, allFormats, isValidFormat, GrantType, ResponseMode, ProofType, OID4FlowType, VCIStep, VPStep, OID4Action, OpenID4xProfile, } from "./openid4x.js";
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";
25
+ // Discovery
26
+ export { extractDomain, discoverEndpoint } from "./discovery.js";
27
+ // Invitation
28
+ export { InvitationPurpose, createInvitation, invitationSigningPayload, invitationToURI, invitationToHTTPSURI, parseInvitationURI, parseInvitationJSON, isInvitationExpired, generateNonce, MemoryInvitationStore, validateInvitationNonce, } from "./invitation.js";
@@ -0,0 +1,131 @@
1
+ /**
2
+ * WMP Invitation — session bootstrap via out-of-band invitation exchange.
3
+ * See wmp-invitation.md for the specification.
4
+ */
5
+ import type { Capabilities } from "./types.js";
6
+ /** Invitation purpose values. */
7
+ export declare const InvitationPurpose: {
8
+ readonly Session: "session";
9
+ readonly OID4VCI: "oid4vci";
10
+ readonly OID4VP: "oid4vp";
11
+ readonly Join: "join";
12
+ };
13
+ /** A self-contained, signed invitation that bootstraps a WMP session. */
14
+ export interface Invitation {
15
+ /** Inviter's wallet provider identifier (domain-based, discoverable). */
16
+ provider: string;
17
+ /** Inviter's participant identifier (may be non-discoverable, e.g. did:key). */
18
+ sender: string;
19
+ /** Unique, cryptographically random nonce (at least 128 bits). */
20
+ nonce: string;
21
+ /** Inviter's relay endpoint URL (optional shortcut, skips well-known fetch). */
22
+ relay?: string;
23
+ /** Purpose of the invitation. Default: "session". */
24
+ purpose?: string;
25
+ /** Existing session to join (when purpose is "join"). */
26
+ session_id?: string;
27
+ /** Human-readable label for the inviter (informational only). */
28
+ label?: string;
29
+ /** Pre-advertised capabilities (informational, subject to negotiation). */
30
+ capabilities?: Capabilities;
31
+ /** ISO 8601 expiry timestamp. */
32
+ expires_at: string;
33
+ /** Detached JWS signature over the invitation payload. */
34
+ signature: string;
35
+ }
36
+ /** Options for creating an invitation. */
37
+ export interface CreateInvitationOptions {
38
+ provider: string;
39
+ sender: string;
40
+ /** TTL in seconds. Default: 300 (5 minutes). */
41
+ ttl?: number;
42
+ relay?: string;
43
+ purpose?: string;
44
+ session_id?: string;
45
+ label?: string;
46
+ capabilities?: Capabilities;
47
+ }
48
+ /**
49
+ * Generate a cryptographically random nonce with the "inv-" prefix.
50
+ * Uses 128 bits of randomness.
51
+ */
52
+ export declare function generateNonce(): string;
53
+ /**
54
+ * Create an unsigned invitation. The caller must set `signature` after
55
+ * signing the payload with the sender's key.
56
+ */
57
+ export declare function createInvitation(opts: CreateInvitationOptions): Invitation;
58
+ /**
59
+ * Get the signing payload for an invitation (all fields except `signature`).
60
+ * The caller should JCS-canonicalize and sign this JSON.
61
+ */
62
+ export declare function invitationSigningPayload(inv: Invitation): Record<string, unknown>;
63
+ /**
64
+ * Serialize an invitation to a `wmp://invite?data=<base64url>` URI.
65
+ */
66
+ export declare function invitationToURI(inv: Invitation): string;
67
+ /**
68
+ * Serialize an invitation to an HTTPS fallback URI:
69
+ * `https://<provider-domain>/wmp/invite#<base64url>`.
70
+ */
71
+ export declare function invitationToHTTPSURI(inv: Invitation): string;
72
+ /**
73
+ * Parse an invitation from a `wmp://invite?data=...` URI or
74
+ * `https://...#...` HTTPS fallback URI.
75
+ * Does NOT verify the signature.
76
+ */
77
+ export declare function parseInvitationURI(uri: string): Invitation;
78
+ /**
79
+ * Parse an invitation from raw JSON.
80
+ * Does NOT verify the signature.
81
+ */
82
+ export declare function parseInvitationJSON(data: string | object): Invitation;
83
+ /**
84
+ * Check whether an invitation has expired.
85
+ */
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>;
107
+ /**
108
+ * InvitationStore tracks issued invitation nonces.
109
+ */
110
+ export interface InvitationStore {
111
+ /** Store a nonce with its invitation. Rejects if nonce already exists. */
112
+ put(nonce: string, inv: Invitation): void;
113
+ /** Atomically consume a nonce. Returns the invitation or undefined. */
114
+ consume(nonce: string): Invitation | undefined;
115
+ /** Remove expired nonces. Returns the count removed. */
116
+ cleanup(): number;
117
+ }
118
+ /**
119
+ * Thread-safe (single-threaded JS) in-memory invitation store.
120
+ */
121
+ export declare class MemoryInvitationStore implements InvitationStore {
122
+ private nonces;
123
+ put(nonce: string, inv: Invitation): void;
124
+ consume(nonce: string): Invitation | undefined;
125
+ cleanup(): number;
126
+ }
127
+ /**
128
+ * Validate an invitation_nonce from a wmp.session.create request.
129
+ * Returns the original invitation on success, or throws with an error reason.
130
+ */
131
+ export declare function validateInvitationNonce(store: InvitationStore, nonce: string | undefined): Invitation;
@@ -0,0 +1,210 @@
1
+ /**
2
+ * WMP Invitation — session bootstrap via out-of-band invitation exchange.
3
+ * See wmp-invitation.md for the specification.
4
+ */
5
+ import { extractDomain } from "./discovery.js";
6
+ // ---------------------------------------------------------------------------
7
+ // Constants
8
+ // ---------------------------------------------------------------------------
9
+ /** Invitation purpose values. */
10
+ export const InvitationPurpose = {
11
+ Session: "session",
12
+ OID4VCI: "oid4vci",
13
+ OID4VP: "oid4vp",
14
+ Join: "join",
15
+ };
16
+ // ---------------------------------------------------------------------------
17
+ // Nonce generation
18
+ // ---------------------------------------------------------------------------
19
+ /**
20
+ * Generate a cryptographically random nonce with the "inv-" prefix.
21
+ * Uses 128 bits of randomness.
22
+ */
23
+ export function generateNonce() {
24
+ const bytes = new Uint8Array(16);
25
+ globalThis.crypto.getRandomValues(bytes);
26
+ // base64url encode without padding
27
+ const b64 = btoa(String.fromCharCode(...bytes))
28
+ .replace(/\+/g, "-")
29
+ .replace(/\//g, "_")
30
+ .replace(/=+$/, "");
31
+ return `inv-${b64}`;
32
+ }
33
+ // ---------------------------------------------------------------------------
34
+ // Invitation creation & parsing
35
+ // ---------------------------------------------------------------------------
36
+ /**
37
+ * Create an unsigned invitation. The caller must set `signature` after
38
+ * signing the payload with the sender's key.
39
+ */
40
+ export function createInvitation(opts) {
41
+ const ttl = opts.ttl ?? 300;
42
+ const expiresAt = new Date(Date.now() + ttl * 1000).toISOString();
43
+ return {
44
+ provider: opts.provider,
45
+ sender: opts.sender,
46
+ nonce: generateNonce(),
47
+ relay: opts.relay,
48
+ purpose: opts.purpose ?? InvitationPurpose.Session,
49
+ session_id: opts.session_id,
50
+ label: opts.label,
51
+ capabilities: opts.capabilities,
52
+ expires_at: expiresAt,
53
+ signature: "", // caller sets after signing
54
+ };
55
+ }
56
+ /**
57
+ * Get the signing payload for an invitation (all fields except `signature`).
58
+ * The caller should JCS-canonicalize and sign this JSON.
59
+ */
60
+ export function invitationSigningPayload(inv) {
61
+ const { signature: _, ...rest } = inv;
62
+ // Remove undefined values
63
+ return JSON.parse(JSON.stringify(rest));
64
+ }
65
+ /**
66
+ * Serialize an invitation to a `wmp://invite?data=<base64url>` URI.
67
+ */
68
+ export function invitationToURI(inv) {
69
+ const json = JSON.stringify(inv);
70
+ const b64 = btoa(json)
71
+ .replace(/\+/g, "-")
72
+ .replace(/\//g, "_")
73
+ .replace(/=+$/, "");
74
+ return `wmp://invite?data=${b64}`;
75
+ }
76
+ /**
77
+ * Serialize an invitation to an HTTPS fallback URI:
78
+ * `https://<provider-domain>/wmp/invite#<base64url>`.
79
+ */
80
+ export function invitationToHTTPSURI(inv) {
81
+ const domain = extractDomain(inv.provider);
82
+ if (!domain) {
83
+ throw new Error(`Cannot extract domain from provider "${inv.provider}"`);
84
+ }
85
+ const json = JSON.stringify(inv);
86
+ const b64 = btoa(json)
87
+ .replace(/\+/g, "-")
88
+ .replace(/\//g, "_")
89
+ .replace(/=+$/, "");
90
+ return `https://${domain}/wmp/invite#${b64}`;
91
+ }
92
+ /**
93
+ * Parse an invitation from a `wmp://invite?data=...` URI or
94
+ * `https://...#...` HTTPS fallback URI.
95
+ * Does NOT verify the signature.
96
+ */
97
+ export function parseInvitationURI(uri) {
98
+ let encoded;
99
+ if (uri.startsWith("wmp://invite")) {
100
+ const url = new URL(uri);
101
+ const data = url.searchParams.get("data");
102
+ if (!data) {
103
+ const ref = url.searchParams.get("ref");
104
+ if (ref) {
105
+ throw new Error(`Invitation uses ref="${ref}": fetch the URL to get the full invitation`);
106
+ }
107
+ throw new Error("Invitation URI missing 'data' parameter");
108
+ }
109
+ encoded = data;
110
+ }
111
+ else if (uri.includes("/wmp/invite#")) {
112
+ const idx = uri.lastIndexOf("#");
113
+ if (idx < 0 || idx === uri.length - 1) {
114
+ throw new Error("HTTPS invitation URI missing fragment");
115
+ }
116
+ encoded = uri.slice(idx + 1);
117
+ }
118
+ else {
119
+ throw new Error(`Unrecognised invitation URI scheme: "${uri}"`);
120
+ }
121
+ // base64url decode
122
+ const padded = encoded.replace(/-/g, "+").replace(/_/g, "/");
123
+ const json = atob(padded);
124
+ return JSON.parse(json);
125
+ }
126
+ /**
127
+ * Parse an invitation from raw JSON.
128
+ * Does NOT verify the signature.
129
+ */
130
+ export function parseInvitationJSON(data) {
131
+ if (typeof data === "string") {
132
+ return JSON.parse(data);
133
+ }
134
+ return data;
135
+ }
136
+ /**
137
+ * Check whether an invitation has expired.
138
+ */
139
+ export function isInvitationExpired(inv) {
140
+ return new Date(inv.expires_at).getTime() < Date.now();
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
+ }
164
+ /**
165
+ * Thread-safe (single-threaded JS) in-memory invitation store.
166
+ */
167
+ export class MemoryInvitationStore {
168
+ nonces = new Map();
169
+ put(nonce, inv) {
170
+ if (this.nonces.has(nonce)) {
171
+ throw new Error(`Nonce "${nonce}" already exists`);
172
+ }
173
+ this.nonces.set(nonce, inv);
174
+ }
175
+ consume(nonce) {
176
+ const inv = this.nonces.get(nonce);
177
+ if (!inv)
178
+ return undefined;
179
+ if (isInvitationExpired(inv)) {
180
+ this.nonces.delete(nonce);
181
+ return undefined;
182
+ }
183
+ this.nonces.delete(nonce);
184
+ return inv;
185
+ }
186
+ cleanup() {
187
+ let count = 0;
188
+ for (const [nonce, inv] of this.nonces) {
189
+ if (isInvitationExpired(inv)) {
190
+ this.nonces.delete(nonce);
191
+ count++;
192
+ }
193
+ }
194
+ return count;
195
+ }
196
+ }
197
+ /**
198
+ * Validate an invitation_nonce from a wmp.session.create request.
199
+ * Returns the original invitation on success, or throws with an error reason.
200
+ */
201
+ export function validateInvitationNonce(store, nonce) {
202
+ if (!nonce) {
203
+ throw new Error("missing invitation_nonce");
204
+ }
205
+ const inv = store.consume(nonce);
206
+ if (!inv) {
207
+ throw new Error("invalid_invitation_nonce");
208
+ }
209
+ return inv;
210
+ }