@dimchansky/meshpost 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/channel.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Delivery, ListenOptions, Room, SendResult } from './room.js';
1
+ import { type Delivery, type ListenOptions, type Room, type SendResult } from './room.js';
2
2
  export interface ChannelOptions {
3
3
  /** Delivery mode for this logical channel. @default 'unreliable' */
4
4
  delivery?: Delivery;
@@ -18,9 +18,44 @@ export interface Channel {
18
18
  /** Subscribe to packets sent to this channel name. Returns an unsubscribe function. */
19
19
  onPacket(fn: (from: string, bytes: Uint8Array) => void, options?: ListenOptions): () => void;
20
20
  }
21
+ /** Synchronous serializer/deserializer pair for `createCodecChannel()` and `createRpc()`. */
22
+ export interface Codec<T> {
23
+ /** Encode a value into a binary `Uint8Array`. */
24
+ encode(value: T): Uint8Array;
25
+ /** Decode (and optionally validate) a binary `Uint8Array` into `T`. Throw on malformed input. */
26
+ decode(bytes: Uint8Array): T;
27
+ }
28
+ /** Named logical message stream with typed synchronous `send()` and validated `onMessage()`. */
29
+ export interface CodecChannel<T> {
30
+ /** Logical channel name (1-64 UTF-8 bytes). */
31
+ readonly name: string;
32
+ /** Delivery mode configured for this channel. */
33
+ readonly delivery: Delivery;
34
+ /** Encode and send a typed value synchronously. Returns a per-recipient result map. */
35
+ send(value: T, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
36
+ /** Subscribe to decoded, validated values on this channel. Malformed incoming frames are ignored. */
37
+ onMessage(fn: (from: string, value: T) => void, options?: ListenOptions): () => void;
38
+ }
39
+ /** Zero-copy identity codec for raw `Uint8Array` payloads. */
40
+ export declare const binaryCodec: Codec<Uint8Array>;
41
+ /** Strict UTF-8 string codec (rejects invalid UTF-8 byte sequences on `decode`). */
42
+ export declare const textCodec: Codec<string>;
43
+ /**
44
+ * Create a UTF-8 JSON codec with optional runtime schema validation.
45
+ * Pass a TypeScript type guard (`(v): v is MyType => ...`) to infer `Codec<MyType>` automatically.
46
+ */
47
+ export declare function jsonCodec<T>(validate: (value: unknown) => value is T): Codec<T>;
48
+ export declare function jsonCodec<T = unknown>(validate?: (value: unknown) => boolean): Codec<T>;
21
49
  /**
22
50
  * Create a named logical channel multiplexed over a Room's existing data channels.
23
51
  * Adds a compact length-prefixed UTF-8 header (`[len, ...nameBytes, ...payload]`)
24
- * without opening additional WebRTC RTCDataChannels.
52
+ * without opening additional WebRTC RTCDataChannels, and dispatches incoming packets
53
+ * in `O(1)` time via a per-Room shared router.
25
54
  */
26
55
  export declare function createChannel(room: Room, name: string, options?: ChannelOptions): Channel;
56
+ /**
57
+ * Create a typed logical channel using a synchronous `Codec<T>` (such as `jsonCodec` or `textCodec`).
58
+ * Preserves synchronous `ReadonlyMap<string, SendResult>` backpressure on `send()`, and drops
59
+ * malformed incoming frames without consuming `{ once: true }` subscriptions.
60
+ */
61
+ export declare function createCodecChannel<T>(room: Room, name: string, codec: Codec<T>, options?: ChannelOptions): CodecChannel<T>;
package/dist/channel.js CHANGED
@@ -1,11 +1,197 @@
1
+ import { isRoomClosed, onRoomClose } from './room.js';
1
2
  const encoder = new TextEncoder();
3
+ const strictDecoder = new TextDecoder('utf-8', { fatal: true });
2
4
  const maxNameBytes = 64;
5
+ const routers = new WeakMap();
6
+ function createModeTable() {
7
+ return {
8
+ byName: new Map(),
9
+ lengthCounts: new Uint32Array(maxNameBytes + 1)
10
+ };
11
+ }
12
+ function getRouter(room) {
13
+ let router = routers.get(room);
14
+ if (router)
15
+ return router;
16
+ const unreliable = createModeTable();
17
+ const reliable = createModeTable();
18
+ let activeSubs = 0;
19
+ let offRoomPacket;
20
+ let offRoomClose;
21
+ const detachIfIdle = () => {
22
+ if (activeSubs === 0 && offRoomPacket) {
23
+ const stopPacket = offRoomPacket;
24
+ const stopClose = offRoomClose;
25
+ offRoomPacket = undefined;
26
+ offRoomClose = undefined;
27
+ stopPacket();
28
+ stopClose?.();
29
+ }
30
+ };
31
+ const dispatch = (from, bytes, mode) => {
32
+ const table = mode === 'reliable' ? reliable : unreliable;
33
+ if (table.byName.size === 0 || bytes.byteLength < 2)
34
+ return;
35
+ const len = bytes[0];
36
+ if (len === 0 ||
37
+ len > maxNameBytes ||
38
+ bytes.byteLength < 1 + len ||
39
+ table.lengthCounts[len] === 0) {
40
+ return;
41
+ }
42
+ let channelName;
43
+ try {
44
+ channelName = strictDecoder.decode(bytes.subarray(1, 1 + len));
45
+ }
46
+ catch {
47
+ return;
48
+ }
49
+ const subs = table.byName.get(channelName);
50
+ if (!subs || subs.size === 0)
51
+ return;
52
+ const payload = bytes.subarray(1 + len);
53
+ for (const entry of [...subs]) {
54
+ if (!subs.has(entry))
55
+ continue;
56
+ if (entry.once)
57
+ entry.off();
58
+ try {
59
+ entry.fn(from, payload);
60
+ }
61
+ catch (error) {
62
+ globalThis.reportError?.(error);
63
+ }
64
+ }
65
+ };
66
+ const clearAll = () => {
67
+ for (const table of [unreliable, reliable]) {
68
+ for (const subs of [...table.byName.values()]) {
69
+ for (const entry of [...subs])
70
+ entry.off();
71
+ }
72
+ table.byName.clear();
73
+ table.lengthCounts.fill(0);
74
+ }
75
+ activeSubs = 0;
76
+ detachIfIdle();
77
+ };
78
+ const ensureAttached = () => {
79
+ if (offRoomPacket)
80
+ return;
81
+ offRoomPacket = room.onPacket(dispatch);
82
+ offRoomClose = onRoomClose(room, clearAll);
83
+ };
84
+ router = {
85
+ subscribe(delivery, name, nameLen, fn, options) {
86
+ if (typeof fn !== 'function')
87
+ throw new TypeError('Expected a listener function');
88
+ const signal = options?.signal;
89
+ if (signal?.aborted || isRoomClosed(room))
90
+ return () => { };
91
+ ensureAttached();
92
+ if (isRoomClosed(room)) {
93
+ clearAll();
94
+ return () => { };
95
+ }
96
+ const table = delivery === 'reliable' ? reliable : unreliable;
97
+ let subs = table.byName.get(name);
98
+ if (!subs) {
99
+ subs = new Set();
100
+ table.byName.set(name, subs);
101
+ table.lengthCounts[nameLen] = (table.lengthCounts[nameLen] ?? 0) + 1;
102
+ }
103
+ let removed = false;
104
+ const entry = {
105
+ fn,
106
+ once: Boolean(options?.once),
107
+ off() {
108
+ if (removed)
109
+ return;
110
+ removed = true;
111
+ signal?.removeEventListener('abort', entry.off);
112
+ const current = table.byName.get(name);
113
+ if (current?.delete(entry)) {
114
+ activeSubs = Math.max(0, activeSubs - 1);
115
+ if (current.size === 0) {
116
+ table.byName.delete(name);
117
+ const prevLenCount = table.lengthCounts[nameLen] ?? 0;
118
+ table.lengthCounts[nameLen] = prevLenCount > 0 ? prevLenCount - 1 : 0;
119
+ }
120
+ }
121
+ detachIfIdle();
122
+ }
123
+ };
124
+ subs.add(entry);
125
+ activeSubs++;
126
+ signal?.addEventListener('abort', entry.off, { once: true });
127
+ return entry.off;
128
+ }
129
+ };
130
+ routers.set(room, router);
131
+ return router;
132
+ }
133
+ /** @internal */
134
+ export function isValidCodec(value) {
135
+ return (Boolean(value) &&
136
+ typeof value === 'object' &&
137
+ typeof value.encode === 'function' &&
138
+ typeof value.decode === 'function');
139
+ }
140
+ /** Zero-copy identity codec for raw `Uint8Array` payloads. */
141
+ export const binaryCodec = Object.freeze({
142
+ encode(value) {
143
+ if (!(value instanceof Uint8Array))
144
+ throw new TypeError('Expected a Uint8Array');
145
+ return value;
146
+ },
147
+ decode(bytes) {
148
+ return bytes;
149
+ }
150
+ });
151
+ /** Strict UTF-8 string codec (rejects invalid UTF-8 byte sequences on `decode`). */
152
+ export const textCodec = Object.freeze({
153
+ encode(value) {
154
+ if (typeof value !== 'string')
155
+ throw new TypeError('Expected a string');
156
+ return encoder.encode(value);
157
+ },
158
+ decode(bytes) {
159
+ return strictDecoder.decode(bytes);
160
+ }
161
+ });
162
+ export function jsonCodec(validate) {
163
+ if (validate !== undefined && typeof validate !== 'function') {
164
+ throw new TypeError('Invalid validator function');
165
+ }
166
+ return Object.freeze({
167
+ encode(value) {
168
+ const json = JSON.stringify(value);
169
+ if (json === undefined)
170
+ throw new TypeError('Value is not JSON-serializable');
171
+ return encoder.encode(json);
172
+ },
173
+ decode(bytes) {
174
+ const parsed = JSON.parse(strictDecoder.decode(bytes));
175
+ if (validate && !validate(parsed)) {
176
+ throw new Error('Invalid JSON payload');
177
+ }
178
+ return parsed;
179
+ }
180
+ });
181
+ }
3
182
  /**
4
183
  * Create a named logical channel multiplexed over a Room's existing data channels.
5
184
  * Adds a compact length-prefixed UTF-8 header (`[len, ...nameBytes, ...payload]`)
6
- * without opening additional WebRTC RTCDataChannels.
185
+ * without opening additional WebRTC RTCDataChannels, and dispatches incoming packets
186
+ * in `O(1)` time via a per-Room shared router.
7
187
  */
8
188
  export function createChannel(room, name, options = {}) {
189
+ if (!room ||
190
+ typeof room !== 'object' ||
191
+ typeof room.send !== 'function' ||
192
+ typeof room.onPacket !== 'function') {
193
+ throw new TypeError('Invalid room');
194
+ }
9
195
  if (typeof name !== 'string' || name.length === 0)
10
196
  throw new TypeError('Invalid channel name');
11
197
  const nameBytes = encoder.encode(name);
@@ -17,6 +203,7 @@ export function createChannel(room, name, options = {}) {
17
203
  const prefix = new Uint8Array(1 + nameBytes.length);
18
204
  prefix[0] = nameBytes.length;
19
205
  prefix.set(nameBytes, 1);
206
+ const router = getRouter(room);
20
207
  return {
21
208
  name,
22
209
  delivery,
@@ -28,23 +215,50 @@ export function createChannel(room, name, options = {}) {
28
215
  framed.set(bytes, prefix.length);
29
216
  return room.send(framed, sendOptions.to === undefined ? { delivery } : { to: sendOptions.to, delivery });
30
217
  },
31
- onPacket(fn, options) {
32
- if (options?.signal?.aborted)
218
+ onPacket(fn, listenOptions) {
219
+ return router.subscribe(delivery, name, nameBytes.length, fn, listenOptions);
220
+ }
221
+ };
222
+ }
223
+ /**
224
+ * Create a typed logical channel using a synchronous `Codec<T>` (such as `jsonCodec` or `textCodec`).
225
+ * Preserves synchronous `ReadonlyMap<string, SendResult>` backpressure on `send()`, and drops
226
+ * malformed incoming frames without consuming `{ once: true }` subscriptions.
227
+ */
228
+ export function createCodecChannel(room, name, codec, options = {}) {
229
+ if (!isValidCodec(codec))
230
+ throw new TypeError('Invalid codec');
231
+ const channel = createChannel(room, name, options);
232
+ return {
233
+ name: channel.name,
234
+ delivery: channel.delivery,
235
+ send(value, sendOptions = {}) {
236
+ const bytes = codec.encode(value);
237
+ if (!(bytes instanceof Uint8Array)) {
238
+ throw new TypeError('Codec encode() must return a Uint8Array');
239
+ }
240
+ return channel.send(bytes, sendOptions);
241
+ },
242
+ onMessage(fn, listenOptions) {
243
+ if (typeof fn !== 'function')
244
+ throw new TypeError('Expected a listener function');
245
+ if (listenOptions?.signal?.aborted || isRoomClosed(room))
33
246
  return () => { };
34
- const once = Boolean(options?.once);
35
- const roomOptions = options?.signal ? { signal: options.signal } : undefined;
247
+ const once = Boolean(listenOptions?.once);
248
+ const subOptions = listenOptions?.signal ? { signal: listenOptions.signal } : undefined;
36
249
  let off = () => { };
37
- off = room.onPacket((from, bytes, mode) => {
38
- if (mode !== delivery || bytes.byteLength < prefix.length)
250
+ off = channel.onPacket((from, bytes) => {
251
+ let decoded;
252
+ try {
253
+ decoded = codec.decode(bytes);
254
+ }
255
+ catch {
39
256
  return;
40
- for (let i = 0; i < prefix.length; i++) {
41
- if (bytes[i] !== prefix[i])
42
- return;
43
257
  }
44
258
  if (once)
45
259
  off();
46
- fn(from, bytes.subarray(prefix.length));
47
- }, roomOptions);
260
+ fn(from, decoded);
261
+ }, subOptions);
48
262
  return off;
49
263
  }
50
264
  };
@@ -0,0 +1,34 @@
1
+ export declare const replayWindowMs = 60000;
2
+ export declare const midTtlMs: number;
3
+ export declare const maxMidLength = 64;
4
+ export declare const maxSeenMids = 2048;
5
+ export declare const errorCooldownMs = 15000;
6
+ export declare const minBoxBytes = 28;
7
+ export declare const minBoxChars = 38;
8
+ export declare const maxBoxChars: number;
9
+ export interface DerivedSignalingKeys {
10
+ readonly aeadKey: CryptoKey;
11
+ readonly privateId: string;
12
+ }
13
+ export type ReplayCheckResult = 'ok' | 'clock-skew' | 'replay' | 'invalid';
14
+ export interface ReplayGuard {
15
+ recordMid(scopedMid: string, now?: number): boolean;
16
+ checkAuthenticated(from: string, data: {
17
+ readonly mid?: unknown;
18
+ readonly ts?: unknown;
19
+ }, now?: number): ReplayCheckResult;
20
+ prune(now?: number): void;
21
+ }
22
+ /**
23
+ * Derive an AES-256-GCM signaling key and a domain-separated 128-bit hex `privateId`
24
+ * from a shared password using a single 256-bit PBKDF2-HMAC-SHA256 pass (100,000 iterations)
25
+ * followed by RFC 5869 HKDF-SHA256 expansion.
26
+ */
27
+ export declare function deriveSignalingKeys(password: string, baseScope: string, insecureMessage?: string): Promise<DerivedSignalingKeys>;
28
+ export declare function sealPayload(key: CryptoKey, plain: Uint8Array, aad: string): Promise<Uint8Array>;
29
+ export declare function openPayload(key: CryptoKey, boxed: Uint8Array, aad: string): Promise<Uint8Array | null>;
30
+ export declare function sealEnvelope(key: CryptoKey, envelope: object, aad: string): Promise<Uint8Array>;
31
+ export declare function openEnvelope(key: CryptoKey, boxed: Uint8Array, aad: string): Promise<Record<string, unknown> | null>;
32
+ export declare function toBase64Url(bytes: Uint8Array): string;
33
+ export declare function fromBase64Url(value: unknown, maxChars?: number): Uint8Array | null;
34
+ export declare function createReplayGuard(): ReplayGuard;
package/dist/crypto.js ADDED
@@ -0,0 +1,158 @@
1
+ import { namespaceHash } from './signaling.js';
2
+ const encoder = new TextEncoder();
3
+ const decoder = new TextDecoder();
4
+ export const replayWindowMs = 60_000;
5
+ export const midTtlMs = replayWindowMs * 2;
6
+ export const maxMidLength = 64;
7
+ export const maxSeenMids = 2048;
8
+ export const errorCooldownMs = 15_000;
9
+ export const minBoxBytes = 28;
10
+ export const minBoxChars = 38;
11
+ export const maxBoxChars = 96 * 1024;
12
+ const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
13
+ function bytesToHex(bytes) {
14
+ let out = '';
15
+ for (let i = 0; i < bytes.length; i++) {
16
+ out += bytes[i].toString(16).padStart(2, '0');
17
+ }
18
+ return out;
19
+ }
20
+ /**
21
+ * Derive an AES-256-GCM signaling key and a domain-separated 128-bit hex `privateId`
22
+ * from a shared password using a single 256-bit PBKDF2-HMAC-SHA256 pass (100,000 iterations)
23
+ * followed by RFC 5869 HKDF-SHA256 expansion.
24
+ */
25
+ export async function deriveSignalingKeys(password, baseScope, insecureMessage = 'Password encryption requires a secure context (crypto.subtle)') {
26
+ const subtle = globalThis.crypto?.subtle;
27
+ if (!subtle)
28
+ throw new Error(insecureMessage);
29
+ const salt = encoder.encode('meshpost/1/' + namespaceHash(baseScope));
30
+ const pbkdf2Key = await subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, [
31
+ 'deriveBits'
32
+ ]);
33
+ const masterBits = await subtle.deriveBits({ name: 'PBKDF2', salt, iterations: 100_000, hash: 'SHA-256' }, pbkdf2Key, 256);
34
+ const hkdfKey = await subtle.importKey('raw', masterBits, 'HKDF', false, [
35
+ 'deriveKey',
36
+ 'deriveBits'
37
+ ]);
38
+ const emptySalt = new Uint8Array(0);
39
+ const [aeadKey, topicBits] = await Promise.all([
40
+ subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: emptySalt, info: encoder.encode('meshpost/1/aead') }, hkdfKey, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']),
41
+ subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: emptySalt, info: encoder.encode('meshpost/1/topic') }, hkdfKey, 128)
42
+ ]);
43
+ return {
44
+ aeadKey,
45
+ privateId: bytesToHex(new Uint8Array(topicBits))
46
+ };
47
+ }
48
+ export async function sealPayload(key, plain, aad) {
49
+ const iv = crypto.getRandomValues(new Uint8Array(12));
50
+ const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, plain.buffer instanceof ArrayBuffer
51
+ ? new Uint8Array(plain.buffer, plain.byteOffset, plain.byteLength)
52
+ : Uint8Array.from(plain)));
53
+ const out = new Uint8Array(12 + cipher.byteLength);
54
+ out.set(iv, 0);
55
+ out.set(cipher, 12);
56
+ return out;
57
+ }
58
+ export async function openPayload(key, boxed, aad) {
59
+ if (boxed.byteLength < minBoxBytes)
60
+ return null;
61
+ try {
62
+ const iv = Uint8Array.from(boxed.subarray(0, 12));
63
+ const cipher = Uint8Array.from(boxed.subarray(12));
64
+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, cipher));
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ export async function sealEnvelope(key, envelope, aad) {
71
+ return sealPayload(key, encoder.encode(JSON.stringify(envelope)), aad);
72
+ }
73
+ export async function openEnvelope(key, boxed, aad) {
74
+ const plain = await openPayload(key, boxed, aad);
75
+ if (!plain)
76
+ return null;
77
+ try {
78
+ const parsed = JSON.parse(decoder.decode(plain));
79
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
80
+ ? parsed
81
+ : null;
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
87
+ export function toBase64Url(bytes) {
88
+ const chunkSize = 0x8000;
89
+ let binary = '';
90
+ for (let i = 0; i < bytes.length; i += chunkSize) {
91
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
92
+ }
93
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
94
+ }
95
+ export function fromBase64Url(value, maxChars = maxBoxChars) {
96
+ if (typeof value !== 'string' ||
97
+ value.length < minBoxChars ||
98
+ value.length > maxChars ||
99
+ value.length % 4 === 1 ||
100
+ !base64UrlPattern.test(value)) {
101
+ return null;
102
+ }
103
+ try {
104
+ const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
105
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
106
+ const binary = atob(padded);
107
+ if (binary.length < minBoxBytes)
108
+ return null;
109
+ const out = new Uint8Array(binary.length);
110
+ for (let i = 0; i < binary.length; i++)
111
+ out[i] = binary.charCodeAt(i);
112
+ return out;
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ }
118
+ export function createReplayGuard() {
119
+ const seenMids = new Map();
120
+ const recordMid = (scopedMid, now = Date.now()) => {
121
+ const prev = seenMids.get(scopedMid);
122
+ if (prev !== undefined && now - prev < midTtlMs)
123
+ return false;
124
+ if (seenMids.size >= maxSeenMids) {
125
+ for (const [key, at] of seenMids) {
126
+ if (now - at >= midTtlMs || seenMids.size >= maxSeenMids) {
127
+ seenMids.delete(key);
128
+ if (seenMids.size < maxSeenMids)
129
+ break;
130
+ }
131
+ }
132
+ }
133
+ seenMids.delete(scopedMid);
134
+ seenMids.set(scopedMid, now);
135
+ return true;
136
+ };
137
+ return {
138
+ recordMid,
139
+ checkAuthenticated(from, data, now = Date.now()) {
140
+ if (typeof data.mid !== 'string' ||
141
+ data.mid.length === 0 ||
142
+ data.mid.length > maxMidLength ||
143
+ typeof data.ts !== 'number' ||
144
+ !Number.isFinite(data.ts)) {
145
+ return 'invalid';
146
+ }
147
+ if (Math.abs(now - data.ts) > replayWindowMs)
148
+ return 'clock-skew';
149
+ return recordMid(from + ':' + data.mid, now) ? 'ok' : 'replay';
150
+ },
151
+ prune(now = Date.now()) {
152
+ for (const [mid, at] of seenMids) {
153
+ if (now - at >= midTtlMs)
154
+ seenMids.delete(mid);
155
+ }
156
+ }
157
+ };
158
+ }
@@ -0,0 +1,45 @@
1
+ export interface CreateIdentityOptions {
2
+ /**
3
+ * Whether the private ECDSA key can be exported via `exportIdentity()`.
4
+ * Pass `false` when using non-extractable session or process identities.
5
+ * @default true
6
+ */
7
+ extractable?: boolean;
8
+ }
9
+ export interface PeerIdentity {
10
+ /**
11
+ * Deterministic 22-character base64url identifier (`[A-Za-z0-9_-]{22}`):
12
+ * the first 128 bits (16 bytes) of `SHA-256("meshpost/1/userid:" || rawUncompressedPublicKey65B)`.
13
+ */
14
+ readonly userId: string;
15
+ /**
16
+ * Base64url-encoded 65-byte uncompressed P-256 public key (`0x04 || X(32B) || Y(32B)`, 87 chars).
17
+ */
18
+ readonly publicKey: string;
19
+ }
20
+ export interface SerializedIdentity {
21
+ readonly v: 1;
22
+ readonly crv: 'P-256';
23
+ /** 32-byte canonical base64url X coordinate (43 chars). */
24
+ readonly x: string;
25
+ /** 32-byte canonical base64url Y coordinate (43 chars). */
26
+ readonly y: string;
27
+ /** 32-byte canonical base64url private scalar (43 chars). */
28
+ readonly d: string;
29
+ }
30
+ /**
31
+ * Generate a fresh WebCrypto `ECDSA P-256` peer identity with a deterministic 128-bit `userId`.
32
+ */
33
+ export declare function createIdentity(options?: CreateIdentityOptions): Promise<PeerIdentity>;
34
+ /**
35
+ * Serialize an extractable `PeerIdentity` to a compact, JSON-safe object suitable for `localStorage`.
36
+ */
37
+ export declare function exportIdentity(identity: PeerIdentity): Promise<SerializedIdentity>;
38
+ /**
39
+ * Type guard checking whether an unknown JSON value has the canonical `SerializedIdentity` shape.
40
+ */
41
+ export declare function isSerializedIdentity(value: unknown): value is SerializedIdentity;
42
+ /**
43
+ * Import and cryptographically self-verify a `SerializedIdentity` (`(x, y)` verified against `d`).
44
+ */
45
+ export declare function importIdentity(data: unknown, options?: CreateIdentityOptions): Promise<PeerIdentity>;