@private.me/xbind 3.0.2 → 3.0.4
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 +2366 -204
- package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
- package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
- package/dist-standalone/_deps/shared/cjs/index.js +1 -463
- package/dist-standalone/_deps/shared/cjs/types.js +1 -315
- package/dist-standalone/_deps/shared/errors.js +1 -244
- package/dist-standalone/_deps/shared/index.js +1 -72
- package/dist-standalone/_deps/shared/types.js +1 -86
- package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
- package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
- package/dist-standalone/_deps/ux-helpers/index.js +1 -1
- package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
- package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
- package/dist-standalone/_deps/ux-helpers/search.js +1 -1
- package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
- package/dist-standalone/_deps/xchange/errors.js +1 -1
- package/dist-standalone/_deps/xchange/index.js +1 -1
- package/dist-standalone/_deps/xchange/invite-client.js +1 -1
- package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
- package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
- package/dist-standalone/_deps/xchange/xchange.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
- package/dist-standalone/_deps/xregistry/discovery.js +1 -1
- package/dist-standalone/_deps/xregistry/errors.js +1 -1
- package/dist-standalone/_deps/xregistry/index.js +1 -1
- package/dist-standalone/_deps/xregistry/registry.js +1 -1
- package/dist-standalone/_deps/xregistry/schema.js +1 -1
- package/dist-standalone/_deps/xregistry/types.js +1 -1
- package/dist-standalone/agent-call.d.ts +2 -2
- package/dist-standalone/agent-call.js +1 -659
- package/dist-standalone/agent-sdk.js +1 -328
- package/dist-standalone/agent.d.ts +2 -0
- package/dist-standalone/agent.js +1 -1800
- package/dist-standalone/approval.js +1 -193
- package/dist-standalone/async-iterators.d.ts +3 -3
- package/dist-standalone/async-iterators.js +1 -382
- package/dist-standalone/auth.js +1 -219
- package/dist-standalone/auto-accept.js +1 -229
- package/dist-standalone/backup-config.js +1 -201
- package/dist-standalone/backup.js +1 -326
- package/dist-standalone/batch-operations.js +1 -388
- package/dist-standalone/cancellation.js +1 -477
- package/dist-standalone/checkpoint.js +1 -186
- package/dist-standalone/circuit-breaker.js +1 -468
- package/dist-standalone/cjs/agent-call.js +1 -701
- package/dist-standalone/cjs/agent-sdk.js +1 -332
- package/dist-standalone/cjs/agent.js +1 -1837
- package/dist-standalone/cjs/approval.js +1 -199
- package/dist-standalone/cjs/async-iterators.js +1 -392
- package/dist-standalone/cjs/auth.js +1 -225
- package/dist-standalone/cjs/auto-accept.js +1 -233
- package/dist-standalone/cjs/backup-config.js +1 -207
- package/dist-standalone/cjs/backup.js +1 -330
- package/dist-standalone/cjs/batch-operations.js +1 -397
- package/dist-standalone/cjs/cancellation.js +1 -490
- package/dist-standalone/cjs/checkpoint.js +1 -193
- package/dist-standalone/cjs/circuit-breaker.js +1 -476
- package/dist-standalone/cjs/cli/init.js +1 -492
- package/dist-standalone/cjs/config-validation.js +1 -522
- package/dist-standalone/cjs/connect.js +1 -312
- package/dist-standalone/cjs/connection-pool.js +1 -506
- package/dist-standalone/cjs/correlation-id.js +1 -339
- package/dist-standalone/cjs/crypto-utils.js +1 -176
- package/dist-standalone/cjs/debug-mode.js +1 -534
- package/dist-standalone/cjs/did-document.js +1 -101
- package/dist-standalone/cjs/did-privateme.js +1 -130
- package/dist-standalone/cjs/did-web.js +1 -201
- package/dist-standalone/cjs/discovery.js +1 -462
- package/dist-standalone/cjs/dual-mode.js +1 -251
- package/dist-standalone/cjs/email-templates.js +1 -313
- package/dist-standalone/cjs/email-transport.js +1 -239
- package/dist-standalone/cjs/envelope.js +1 -538
- package/dist-standalone/cjs/errors.js +1 -913
- package/dist-standalone/cjs/event-emitter.js +1 -461
- package/dist-standalone/cjs/gateway-state.js +1 -55
- package/dist-standalone/cjs/gateway-transport.js +1 -120
- package/dist-standalone/cjs/graceful-degradation.js +1 -403
- package/dist-standalone/cjs/guardrails.js +1 -223
- package/dist-standalone/cjs/health-check.js +1 -336
- package/dist-standalone/cjs/http-compat.js +1 -272
- package/dist-standalone/cjs/http-status-map.js +1 -571
- package/dist-standalone/cjs/identity.js +1 -645
- package/dist-standalone/cjs/index.js +1 -406
- package/dist-standalone/cjs/invitation.js +1 -421
- package/dist-standalone/cjs/invite.js +1 -328
- package/dist-standalone/cjs/key-agreement.js +1 -335
- package/dist-standalone/cjs/lazy-init.js +1 -300
- package/dist-standalone/cjs/logger.js +1 -291
- package/dist-standalone/cjs/loopback-transport.js +1 -0
- package/dist-standalone/cjs/mdns-discovery.js +1 -202
- package/dist-standalone/cjs/nonce-store.js +1 -80
- package/dist-standalone/cjs/pairing-manager.js +1 -223
- package/dist-standalone/cjs/plugin-system.js +1 -264
- package/dist-standalone/cjs/plugins/logging.js +1 -168
- package/dist-standalone/cjs/plugins/metrics.js +1 -181
- package/dist-standalone/cjs/plugins/validation.js +1 -302
- package/dist-standalone/cjs/policy.js +1 -320
- package/dist-standalone/cjs/progress-callbacks.js +1 -583
- package/dist-standalone/cjs/redis-nonce-store.js +1 -76
- package/dist-standalone/cjs/registry-middleware.js +1 -50
- package/dist-standalone/cjs/retry-strategies.js +1 -544
- package/dist-standalone/cjs/retry-transport.js +1 -102
- package/dist-standalone/cjs/runtime/browser.js +1 -533
- package/dist-standalone/cjs/runtime/edge.js +1 -526
- package/dist-standalone/cjs/runtime/react-native.js +1 -394
- package/dist-standalone/cjs/security-policy.js +1 -245
- package/dist-standalone/cjs/serialization.js +1 -1040
- package/dist-standalone/cjs/split-channel.js +1 -225
- package/dist-standalone/cjs/subscription-proof.js +1 -230
- package/dist-standalone/cjs/succession.js +1 -148
- package/dist-standalone/cjs/timeouts.js +1 -412
- package/dist-standalone/cjs/trace-context.js +1 -424
- package/dist-standalone/cjs/trace-spans.js +1 -495
- package/dist-standalone/cjs/transport.js +1 -63
- package/dist-standalone/cjs/trust-registry.js +1 -991
- package/dist-standalone/cjs/types/error-response.js +1 -56
- package/dist-standalone/cjs/vault-auth.js +1 -178
- package/dist-standalone/cjs/vault-store-loader.js +1 -194
- package/dist-standalone/cjs/verify.js +1 -25
- package/dist-standalone/cjs/version-info.js +1 -543
- package/dist-standalone/cjs/xfetch.js +1 -340
- package/dist-standalone/cli/init.js +1 -455
- package/dist-standalone/cli/setup.js +1 -514
- package/dist-standalone/cli/types.js +1 -27
- package/dist-standalone/cli/xbind.js +1 -148
- package/dist-standalone/config-validation.js +1 -513
- package/dist-standalone/connect.js +1 -274
- package/dist-standalone/connection-pool.js +1 -500
- package/dist-standalone/correlation-id.js +1 -326
- package/dist-standalone/crypto-utils.d.ts +2 -7
- package/dist-standalone/crypto-utils.js +1 -157
- package/dist-standalone/debug-mode.js +1 -510
- package/dist-standalone/did-document.js +1 -96
- package/dist-standalone/did-privateme.js +1 -121
- package/dist-standalone/did-web.js +1 -196
- package/dist-standalone/discovery.js +1 -458
- package/dist-standalone/dual-mode.js +1 -247
- package/dist-standalone/email-templates.js +1 -309
- package/dist-standalone/email-transport.d.ts +2 -2
- package/dist-standalone/email-transport.js +1 -232
- package/dist-standalone/envelope.js +1 -525
- package/dist-standalone/errors.d.ts +13 -3
- package/dist-standalone/errors.js +1 -896
- package/dist-standalone/event-emitter.js +1 -456
- package/dist-standalone/gateway-state.d.ts +1 -1
- package/dist-standalone/gateway-state.js +1 -51
- package/dist-standalone/gateway-transport.js +1 -116
- package/dist-standalone/graceful-degradation.js +1 -396
- package/dist-standalone/guardrails.js +1 -216
- package/dist-standalone/health-check.d.ts +5 -1
- package/dist-standalone/health-check.js +1 -332
- package/dist-standalone/http-compat.d.ts +1 -1
- package/dist-standalone/http-compat.js +1 -267
- package/dist-standalone/http-status-map.js +1 -561
- package/dist-standalone/identity.js +1 -619
- package/dist-standalone/index.d.ts +15 -4
- package/dist-standalone/index.js +1 -78
- package/dist-standalone/invitation.js +1 -415
- package/dist-standalone/invite.js +1 -324
- package/dist-standalone/key-agreement.js +1 -325
- package/dist-standalone/lazy-init.d.ts +11 -6
- package/dist-standalone/lazy-init.js +1 -295
- package/dist-standalone/logger.js +1 -285
- package/dist-standalone/loopback-transport.d.ts +87 -0
- package/dist-standalone/loopback-transport.js +1 -0
- package/dist-standalone/mdns-discovery.js +1 -195
- package/dist-standalone/nonce-store.js +1 -76
- package/dist-standalone/pairing-manager.js +1 -219
- package/dist-standalone/plugin-system.js +1 -257
- package/dist-standalone/plugins/logging.js +1 -163
- package/dist-standalone/plugins/metrics.d.ts +4 -4
- package/dist-standalone/plugins/metrics.js +1 -176
- package/dist-standalone/plugins/validation.js +1 -297
- package/dist-standalone/policy.js +1 -315
- package/dist-standalone/progress-callbacks.js +1 -576
- package/dist-standalone/redis-nonce-store.js +1 -72
- package/dist-standalone/registry-middleware.js +1 -47
- package/dist-standalone/retry-strategies.js +1 -534
- package/dist-standalone/retry-transport.js +1 -98
- package/dist-standalone/runtime/browser.js +1 -516
- package/dist-standalone/runtime/edge.js +1 -511
- package/dist-standalone/runtime/react-native.d.ts +1 -1
- package/dist-standalone/runtime/react-native.js +1 -383
- package/dist-standalone/security-policy.js +1 -239
- package/dist-standalone/serialization.js +1 -1031
- package/dist-standalone/split-channel.d.ts +1 -1
- package/dist-standalone/split-channel.js +1 -219
- package/dist-standalone/subscription-proof.js +1 -224
- package/dist-standalone/succession.js +1 -142
- package/dist-standalone/timeouts.js +1 -398
- package/dist-standalone/trace-context.js +1 -414
- package/dist-standalone/trace-spans.js +1 -488
- package/dist-standalone/transport.d.ts +1 -1
- package/dist-standalone/transport.js +1 -59
- package/dist-standalone/trust-registry.d.ts +3 -3
- package/dist-standalone/trust-registry.js +1 -950
- package/dist-standalone/types/error-response.js +1 -52
- package/dist-standalone/vault-auth.js +1 -174
- package/dist-standalone/vault-store-loader.d.ts +9 -0
- package/dist-standalone/vault-store-loader.js +1 -187
- package/dist-standalone/verify.js +1 -16
- package/dist-standalone/version-info.js +1 -530
- package/dist-standalone/xfetch.js +1 -335
- package/package.json +1 -1
- package/share1.dat +0 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { XailTransportAdapter, EnvelopeHandler } from './transport.js';
|
|
2
|
+
import type { TransportEnvelope } from './envelope.js';
|
|
3
|
+
/**
|
|
4
|
+
* In-memory loopback transport for testing send/receive flows.
|
|
5
|
+
*
|
|
6
|
+
* LoopbackTransport enables testing Agent communication without network dependencies.
|
|
7
|
+
* Messages sent through this transport are immediately delivered to all registered handlers
|
|
8
|
+
* within the same process.
|
|
9
|
+
*
|
|
10
|
+
* **Use Cases:**
|
|
11
|
+
* - Unit testing Agent send/receive functionality
|
|
12
|
+
* - Integration testing multi-agent workflows (Alice → Bob)
|
|
13
|
+
* - Development/debugging of Agent communication patterns
|
|
14
|
+
* - CI/CD pipelines (no external dependencies)
|
|
15
|
+
*
|
|
16
|
+
* **Features:**
|
|
17
|
+
* - Zero network latency (synchronous delivery)
|
|
18
|
+
* - Message history tracking (`.sent` array)
|
|
19
|
+
* - Multiple handler support (broadcast to all receivers)
|
|
20
|
+
* - Clean disposal (removes all handlers)
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* import { Agent, MemoryTrustRegistry, LoopbackTransport } from '@private.me/xbind';
|
|
25
|
+
*
|
|
26
|
+
* const registry = new MemoryTrustRegistry();
|
|
27
|
+
* const transport = new LoopbackTransport();
|
|
28
|
+
*
|
|
29
|
+
* // Create two agents sharing the same transport
|
|
30
|
+
* const alice = await Agent.quickstart({ name: 'Alice', registry, transport });
|
|
31
|
+
* const bob = await Agent.quickstart({ name: 'Bob', registry, transport });
|
|
32
|
+
*
|
|
33
|
+
* // Alice sends to Bob
|
|
34
|
+
* await alice.send({
|
|
35
|
+
* to: bob.did,
|
|
36
|
+
* payload: { type: 'greeting', text: 'Hello Bob!' },
|
|
37
|
+
* scope: 'chat',
|
|
38
|
+
* });
|
|
39
|
+
*
|
|
40
|
+
* // Bob receives (via transport.onReceive handler)
|
|
41
|
+
* const envelope = transport.sent[0]!;
|
|
42
|
+
* const msg = await bob.receive(envelope);
|
|
43
|
+
* console.log(msg.value.payload); // { type: 'greeting', text: 'Hello Bob!' }
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* @see {@link https://private.me/docs/xbind.html#getting-started} - Getting Started guide
|
|
47
|
+
* @see {@link Agent.quickstart} - Zero-config Agent creation
|
|
48
|
+
* @see {@link MemoryTrustRegistry} - In-memory trust registry for testing
|
|
49
|
+
*/
|
|
50
|
+
export declare class LoopbackTransport implements XailTransportAdapter {
|
|
51
|
+
/**
|
|
52
|
+
* Array of all envelopes sent through this transport.
|
|
53
|
+
* Useful for testing/debugging to inspect message history.
|
|
54
|
+
*/
|
|
55
|
+
readonly sent: {
|
|
56
|
+
envelope: TransportEnvelope;
|
|
57
|
+
to: string;
|
|
58
|
+
}[];
|
|
59
|
+
private handlers;
|
|
60
|
+
/**
|
|
61
|
+
* Sends an envelope to a recipient DID.
|
|
62
|
+
*
|
|
63
|
+
* In LoopbackTransport, this immediately delivers the envelope to all registered
|
|
64
|
+
* handlers (via `onReceive`). The envelope is also stored in the `.sent` array.
|
|
65
|
+
*
|
|
66
|
+
* @param envelope - The transport envelope to send
|
|
67
|
+
* @param recipientDid - The DID of the recipient
|
|
68
|
+
* @returns Always succeeds with `ok(undefined)`
|
|
69
|
+
*/
|
|
70
|
+
send(envelope: TransportEnvelope, recipientDid: string): Promise<import("@private.me/shared").Result<undefined, never>>;
|
|
71
|
+
/**
|
|
72
|
+
* Registers a handler to be called when envelopes are received.
|
|
73
|
+
*
|
|
74
|
+
* Multiple handlers can be registered. All handlers will be called
|
|
75
|
+
* for each envelope sent through this transport.
|
|
76
|
+
*
|
|
77
|
+
* @param handler - Function to call with received envelopes
|
|
78
|
+
*/
|
|
79
|
+
onReceive(handler: EnvelopeHandler): void;
|
|
80
|
+
/**
|
|
81
|
+
* Cleans up the transport by removing all handlers.
|
|
82
|
+
*
|
|
83
|
+
* Call this method when done with the transport to prevent memory leaks
|
|
84
|
+
* in long-running test suites.
|
|
85
|
+
*/
|
|
86
|
+
dispose(): void;
|
|
87
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ok}from"./_deps/shared/index.js";export class LoopbackTransport{sent=[];handlers=[];async send(s,e){this.sent.push({envelope:s,to:e});for(const e of this.handlers)e(s);return ok(void 0)}onReceive(s){this.handlers.push(s)}dispose(){this.handlers=[]}}
|
|
@@ -1,195 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* @module mdns-discovery
|
|
3
|
-
* mDNS service discovery for local network device pairing.
|
|
4
|
-
*
|
|
5
|
-
* Service Type: _privateme._tcp.local (RFC 6763 compliant)
|
|
6
|
-
* Port: 58472 (dynamic range 58000-58999)
|
|
7
|
-
* TXT Record: did=z6Mk..., endpoint=http://192.168.1.5:58472, name=Desktop
|
|
8
|
-
*
|
|
9
|
-
* Security properties:
|
|
10
|
-
* - Physical proximity required (same LAN)
|
|
11
|
-
* - User confirmation on both devices
|
|
12
|
-
* - Nonce-based challenge-response
|
|
13
|
-
* - 60-second timeout
|
|
14
|
-
* - Gold Standard compliant (GS-CONNECT requirement #26)
|
|
15
|
-
*/
|
|
16
|
-
import Bonjour from 'bonjour-service';
|
|
17
|
-
import { ok, err } from"./_deps/shared/index.js";
|
|
18
|
-
/**
|
|
19
|
-
* Discovery error types.
|
|
20
|
-
*/
|
|
21
|
-
export var DiscoveryErrorCode;
|
|
22
|
-
(function (DiscoveryErrorCode) {
|
|
23
|
-
DiscoveryErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
|
|
24
|
-
DiscoveryErrorCode["TIMEOUT"] = "TIMEOUT";
|
|
25
|
-
DiscoveryErrorCode["NO_SERVICES"] = "NO_SERVICES";
|
|
26
|
-
DiscoveryErrorCode["INVALID_SERVICE"] = "INVALID_SERVICE";
|
|
27
|
-
})(DiscoveryErrorCode || (DiscoveryErrorCode = {}));
|
|
28
|
-
/**
|
|
29
|
-
* mDNS discovery manager.
|
|
30
|
-
*
|
|
31
|
-
* Advertises service on local network and scans for other devices.
|
|
32
|
-
* Uses bonjour-service library (RFC 6763/6762 compliant).
|
|
33
|
-
*/
|
|
34
|
-
export class MdnsDiscoveryManager {
|
|
35
|
-
bonjour;
|
|
36
|
-
service = null;
|
|
37
|
-
serviceType = 'privateme';
|
|
38
|
-
protocol = 'tcp';
|
|
39
|
-
port = 58472;
|
|
40
|
-
constructor() {
|
|
41
|
-
this.bonjour = new Bonjour();
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Advertise service on local network.
|
|
45
|
-
*
|
|
46
|
-
* Broadcasts mDNS announcement with device DID and HTTP endpoint.
|
|
47
|
-
* Other devices on the same LAN can discover this service via scan().
|
|
48
|
-
*
|
|
49
|
-
* @param name - Device name (e.g., "Desktop", "MacBook Pro")
|
|
50
|
-
* @param did - Device DID
|
|
51
|
-
* @param port - Local HTTP server port (default: 58472)
|
|
52
|
-
*
|
|
53
|
-
* @example
|
|
54
|
-
* ```typescript
|
|
55
|
-
* const manager = new MdnsDiscoveryManager();
|
|
56
|
-
* manager.advertise('Desktop', 'did:key:z6Mk...', 58472);
|
|
57
|
-
* // Service now visible to other devices on LAN
|
|
58
|
-
* ```
|
|
59
|
-
*/
|
|
60
|
-
advertise(name, did, port = this.port) {
|
|
61
|
-
// Stop existing advertisement
|
|
62
|
-
if (this.service) {
|
|
63
|
-
this.service.stop?.();
|
|
64
|
-
}
|
|
65
|
-
// Publish service
|
|
66
|
-
this.service = this.bonjour.publish({
|
|
67
|
-
name,
|
|
68
|
-
type: this.serviceType,
|
|
69
|
-
protocol: this.protocol,
|
|
70
|
-
port,
|
|
71
|
-
txt: {
|
|
72
|
-
did,
|
|
73
|
-
endpoint: `http://localhost:${port}`, // Will be replaced with actual IP by Bonjour
|
|
74
|
-
name,
|
|
75
|
-
},
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Scan local network for services.
|
|
80
|
-
*
|
|
81
|
-
* Discovers all Private.Me devices on the same LAN.
|
|
82
|
-
* Filters out own DID from results (can't pair with self).
|
|
83
|
-
*
|
|
84
|
-
* @param ownDid - Own device DID (to filter out)
|
|
85
|
-
* @param timeoutMs - Scan timeout in milliseconds (default: 5000ms)
|
|
86
|
-
* @returns Array of discovered services
|
|
87
|
-
*
|
|
88
|
-
* @example
|
|
89
|
-
* ```typescript
|
|
90
|
-
* const manager = new MdnsDiscoveryManager();
|
|
91
|
-
* const result = await manager.scan('did:key:z6Mk...myDid', 5000);
|
|
92
|
-
* if (result.ok) {
|
|
93
|
-
* console.log(`Found ${result.value.length} devices`);
|
|
94
|
-
* for (const service of result.value) {
|
|
95
|
-
* console.log(`${service.name} - ${service.did}`);
|
|
96
|
-
* }
|
|
97
|
-
* }
|
|
98
|
-
* ```
|
|
99
|
-
*/
|
|
100
|
-
async scan(ownDid, timeoutMs = 5000) {
|
|
101
|
-
return new Promise((resolve) => {
|
|
102
|
-
const discovered = new Map();
|
|
103
|
-
let resolved = false;
|
|
104
|
-
// Browse for services
|
|
105
|
-
const browser = this.bonjour.find({
|
|
106
|
-
type: this.serviceType,
|
|
107
|
-
protocol: this.protocol,
|
|
108
|
-
});
|
|
109
|
-
// Handle service discovery
|
|
110
|
-
browser.on('up', (service) => {
|
|
111
|
-
try {
|
|
112
|
-
// Parse TXT record
|
|
113
|
-
const txt = service.txt;
|
|
114
|
-
if (!txt || !txt.did || !txt.name) {
|
|
115
|
-
return; // Invalid service - missing required fields
|
|
116
|
-
}
|
|
117
|
-
// Filter out own DID
|
|
118
|
-
if (txt.did === ownDid) {
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
// Extract endpoint
|
|
122
|
-
const endpoint = txt.endpoint || `http://${service.host || 'localhost'}:${service.port}`;
|
|
123
|
-
// Extract addresses (filter IPv4 only)
|
|
124
|
-
const addresses = (service.addresses || []).filter((addr) => {
|
|
125
|
-
// Simple IPv4 check (contains dots, not colons)
|
|
126
|
-
return addr.includes('.') && !addr.includes(':');
|
|
127
|
-
});
|
|
128
|
-
const info = {
|
|
129
|
-
name: txt.name,
|
|
130
|
-
did: txt.did,
|
|
131
|
-
endpoint,
|
|
132
|
-
addresses,
|
|
133
|
-
port: service.port || this.port,
|
|
134
|
-
};
|
|
135
|
-
discovered.set(txt.did, info);
|
|
136
|
-
}
|
|
137
|
-
catch (error) {
|
|
138
|
-
// Ignore invalid service
|
|
139
|
-
}
|
|
140
|
-
});
|
|
141
|
-
// Timeout after specified duration
|
|
142
|
-
const timeoutId = setTimeout(() => {
|
|
143
|
-
if (resolved)
|
|
144
|
-
return;
|
|
145
|
-
resolved = true;
|
|
146
|
-
browser.stop();
|
|
147
|
-
if (discovered.size === 0) {
|
|
148
|
-
resolve(err({
|
|
149
|
-
code: DiscoveryErrorCode.NO_SERVICES,
|
|
150
|
-
message: 'No devices found on local network',
|
|
151
|
-
hint: 'Ensure both devices are on the same Wi-Fi network',
|
|
152
|
-
}));
|
|
153
|
-
}
|
|
154
|
-
else {
|
|
155
|
-
resolve(ok(Array.from(discovered.values())));
|
|
156
|
-
}
|
|
157
|
-
}, timeoutMs);
|
|
158
|
-
// Allow cleanup if promise resolves early
|
|
159
|
-
browser.on('error', (error) => {
|
|
160
|
-
if (resolved)
|
|
161
|
-
return;
|
|
162
|
-
resolved = true;
|
|
163
|
-
clearTimeout(timeoutId);
|
|
164
|
-
browser.stop();
|
|
165
|
-
resolve(err({
|
|
166
|
-
code: DiscoveryErrorCode.NETWORK_ERROR,
|
|
167
|
-
message: error.message,
|
|
168
|
-
hint: 'Check firewall settings and network connectivity',
|
|
169
|
-
}));
|
|
170
|
-
});
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Stop advertising service.
|
|
175
|
-
*
|
|
176
|
-
* Removes mDNS announcement from local network.
|
|
177
|
-
* Other devices will no longer see this service.
|
|
178
|
-
*/
|
|
179
|
-
stopAdvertising() {
|
|
180
|
-
if (this.service) {
|
|
181
|
-
this.service.stop?.();
|
|
182
|
-
this.service = null;
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* Release resources.
|
|
187
|
-
*
|
|
188
|
-
* Stops advertising and cleans up Bonjour instance.
|
|
189
|
-
* Call this when shutting down the application.
|
|
190
|
-
*/
|
|
191
|
-
destroy() {
|
|
192
|
-
this.stopAdvertising();
|
|
193
|
-
this.bonjour.destroy();
|
|
194
|
-
}
|
|
195
|
-
}
|
|
1
|
+
import Bonjour from"bonjour-service";import{ok,err}from"./_deps/shared/index.js";export var DiscoveryErrorCode;!function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.TIMEOUT="TIMEOUT",e.NO_SERVICES="NO_SERVICES",e.INVALID_SERVICE="INVALID_SERVICE"}(DiscoveryErrorCode||(DiscoveryErrorCode={}));export class MdnsDiscoveryManager{bonjour;service=null;serviceType="privateme";protocol="tcp";port=58472;constructor(){this.bonjour=new Bonjour}advertise(e,o,r=this.port){this.service&&this.service.stop?.(),this.service=this.bonjour.publish({name:e,type:this.serviceType,protocol:this.protocol,port:r,txt:{did:o,endpoint:`http://localhost:${r}`,name:e}})}async scan(e,o=5e3){return new Promise(r=>{const t=new Map;let s=!1;const i=this.bonjour.find({type:this.serviceType,protocol:this.protocol});i.on("up",o=>{try{const r=o.txt;if(!r||!r.did||!r.name)return;if(r.did===e)return;const s=r.endpoint||`http://${o.host||"localhost"}:${o.port}`,i=(o.addresses||[]).filter(e=>e.includes(".")&&!e.includes(":")),n={name:r.name,did:r.did,endpoint:s,addresses:i,port:o.port||this.port};t.set(r.did,n)}catch{}});const n=setTimeout(()=>{s||(s=!0,i.stop(),0===t.size?r(err({code:DiscoveryErrorCode.NO_SERVICES,message:"No devices found on local network",hint:"Ensure both devices are on the same Wi-Fi network"})):r(ok(Array.from(t.values()))))},o);i.on("error",e=>{s||(s=!0,clearTimeout(n),i.stop(),r(err({code:DiscoveryErrorCode.NETWORK_ERROR,message:e.message,hint:"Check firewall settings and network connectivity"})))})})}stopAdvertising(){this.service&&(this.service.stop?.(),this.service=null)}destroy(){this.stopAdvertising(),this.bonjour.destroy()}}
|
|
@@ -1,76 +1 @@
|
|
|
1
|
-
|
|
2
|
-
/** Default TTL for nonce entries: 10 minutes. */
|
|
3
|
-
const DEFAULT_TTL_MS = 10 * 60 * 1000;
|
|
4
|
-
/** Default cleanup interval: 60 seconds. */
|
|
5
|
-
const DEFAULT_CLEANUP_INTERVAL_MS = 60 * 1000;
|
|
6
|
-
/**
|
|
7
|
-
* In-memory nonce store for development and single-process deployments.
|
|
8
|
-
*
|
|
9
|
-
* Stores nonces in a Map keyed by "senderDid:nonce:shareContext" with expiry timestamps.
|
|
10
|
-
* Supports share-aware deduplication: same nonce + different shares = allowed (idempotent retry),
|
|
11
|
-
* same nonce + same share = blocked (true replay).
|
|
12
|
-
* Periodic cleanup removes expired entries to prevent unbounded growth.
|
|
13
|
-
*/
|
|
14
|
-
export class MemoryNonceStore {
|
|
15
|
-
seen = new Map();
|
|
16
|
-
ttlMs;
|
|
17
|
-
cleanupIntervalMs;
|
|
18
|
-
timer = null;
|
|
19
|
-
constructor(opts) {
|
|
20
|
-
this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;
|
|
21
|
-
this.cleanupIntervalMs = opts?.cleanupIntervalMs ?? DEFAULT_CLEANUP_INTERVAL_MS;
|
|
22
|
-
// Timer starts lazily on first check() to avoid blocking process exit in tests
|
|
23
|
-
}
|
|
24
|
-
/** Start cleanup timer on first use. */
|
|
25
|
-
ensureTimer() {
|
|
26
|
-
if (this.timer !== null)
|
|
27
|
-
return;
|
|
28
|
-
const t = setInterval(() => this.cleanup(), this.cleanupIntervalMs);
|
|
29
|
-
// Unref so the timer doesn't block Node.js process exit
|
|
30
|
-
if (typeof t === 'object' && 'unref' in t) {
|
|
31
|
-
t.unref(); // SAFETY: runtime check guards access
|
|
32
|
-
}
|
|
33
|
-
this.timer = t;
|
|
34
|
-
}
|
|
35
|
-
/** Build composite key: senderDid:nonce:shareGroupId:shareIndex */
|
|
36
|
-
buildKey(nonce, senderDid, shareContext) {
|
|
37
|
-
if (shareContext === undefined || shareContext === null) {
|
|
38
|
-
return `${senderDid}:${nonce}`;
|
|
39
|
-
}
|
|
40
|
-
const groupId = typeof shareContext.shareGroupId === 'string' ? shareContext.shareGroupId : '';
|
|
41
|
-
const index = typeof shareContext.shareIndex === 'number' ? String(shareContext.shareIndex) : '';
|
|
42
|
-
return `${senderDid}:${nonce}:${groupId}:${index}`;
|
|
43
|
-
}
|
|
44
|
-
async check(nonce, senderDid, shareContext) {
|
|
45
|
-
this.ensureTimer();
|
|
46
|
-
const key = this.buildKey(nonce, senderDid, shareContext);
|
|
47
|
-
const existing = this.seen.get(key);
|
|
48
|
-
const now = Date.now();
|
|
49
|
-
if (existing !== undefined && existing > now) {
|
|
50
|
-
return false;
|
|
51
|
-
}
|
|
52
|
-
this.seen.set(key, now + this.ttlMs);
|
|
53
|
-
return true;
|
|
54
|
-
}
|
|
55
|
-
cleanup() {
|
|
56
|
-
const now = Date.now();
|
|
57
|
-
const keys = Array.from(this.seen.keys());
|
|
58
|
-
for (const key of keys) {
|
|
59
|
-
const expiry = this.seen.get(key);
|
|
60
|
-
if (expiry !== undefined && expiry <= now) {
|
|
61
|
-
this.seen.delete(key);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
dispose() {
|
|
66
|
-
if (this.timer !== null) {
|
|
67
|
-
clearInterval(this.timer);
|
|
68
|
-
this.timer = null;
|
|
69
|
-
}
|
|
70
|
-
this.seen.clear();
|
|
71
|
-
}
|
|
72
|
-
/** Number of active (non-expired) entries. Useful for testing. */
|
|
73
|
-
get size() {
|
|
74
|
-
return this.seen.size;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
1
|
+
const DEFAULT_TTL_MS=6e5,DEFAULT_CLEANUP_INTERVAL_MS=6e4;export class MemoryNonceStore{seen=new Map;ttlMs;cleanupIntervalMs;timer=null;constructor(e){this.ttlMs=e?.ttlMs??6e5,this.cleanupIntervalMs=e?.cleanupIntervalMs??6e4}ensureTimer(){if(null!==this.timer)return;const e=setInterval(()=>this.cleanup(),this.cleanupIntervalMs);"object"==typeof e&&"unref"in e&&e.unref(),this.timer=e}buildKey(e,t,s){if(null==s)return`${t}:${e}`;return`${t}:${e}:${"string"==typeof s.shareGroupId?s.shareGroupId:""}:${"number"==typeof s.shareIndex?String(s.shareIndex):""}`}async check(e,t,s){this.ensureTimer();const n=this.buildKey(e,t,s),r=this.seen.get(n),i=Date.now();return!(void 0!==r&&r>i)&&(this.seen.set(n,i+this.ttlMs),!0)}cleanup(){const e=Date.now(),t=Array.from(this.seen.keys());for(const s of t){const t=this.seen.get(s);void 0!==t&&t<=e&&this.seen.delete(s)}}dispose(){null!==this.timer&&(clearInterval(this.timer),this.timer=null),this.seen.clear()}get size(){return this.seen.size}}
|
|
@@ -1,219 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* @module pairing-manager
|
|
3
|
-
* Security validation for peer-to-peer device pairing via mDNS.
|
|
4
|
-
*
|
|
5
|
-
* Security properties:
|
|
6
|
-
* - 16-byte cryptographically secure nonce (prevents replay attacks)
|
|
7
|
-
* - 60-second timeout (limits attack window)
|
|
8
|
-
* - User confirmation required on BOTH devices
|
|
9
|
-
* - Nonce echo in response (prevents MITM substitution)
|
|
10
|
-
* - Trust registry integration (stores paired DIDs with scopes)
|
|
11
|
-
* - Gold Standard compliant (GS-CONNECT requirement #26, GS-SEC-RNG compliant)
|
|
12
|
-
*/
|
|
13
|
-
import { ok, err } from"./_deps/shared/index.js";
|
|
14
|
-
/**
|
|
15
|
-
* Pairing manager for secure peer-to-peer device pairing.
|
|
16
|
-
*
|
|
17
|
-
* Implements challenge-response protocol with user confirmation.
|
|
18
|
-
* Integrates with trust registry for persistent pairing storage.
|
|
19
|
-
*/
|
|
20
|
-
export class PairingManager {
|
|
21
|
-
pendingNonces = new Map(); // nonce → timestamp
|
|
22
|
-
registry;
|
|
23
|
-
deviceDid;
|
|
24
|
-
/**
|
|
25
|
-
* Create pairing manager.
|
|
26
|
-
*
|
|
27
|
-
* @param deviceDid - DID of this device
|
|
28
|
-
* @param registry - Trust registry instance
|
|
29
|
-
*/
|
|
30
|
-
constructor(deviceDid, registry) {
|
|
31
|
-
this.deviceDid = deviceDid;
|
|
32
|
-
this.registry = registry;
|
|
33
|
-
// Clean up expired nonces every 10 seconds
|
|
34
|
-
setInterval(() => {
|
|
35
|
-
const now = Date.now();
|
|
36
|
-
for (const [nonce, timestamp] of this.pendingNonces.entries()) {
|
|
37
|
-
if (now - timestamp > 60_000) {
|
|
38
|
-
this.pendingNonces.delete(nonce);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}, 10_000);
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Create pairing request.
|
|
45
|
-
*
|
|
46
|
-
* Generates cryptographically secure nonce and stores it for validation.
|
|
47
|
-
* Device A calls this before sending request to Device B.
|
|
48
|
-
*
|
|
49
|
-
* @returns Pairing request to send to remote device
|
|
50
|
-
*
|
|
51
|
-
* @example
|
|
52
|
-
* ```typescript
|
|
53
|
-
* const manager = new PairingManager('did:key:z6MkA...', registry);
|
|
54
|
-
* const request = manager.createRequest();
|
|
55
|
-
* // Send request to Device B via HTTP POST
|
|
56
|
-
* const response = await fetch(`${deviceB.endpoint}/pair`, {
|
|
57
|
-
* method: 'POST',
|
|
58
|
-
* body: JSON.stringify(request),
|
|
59
|
-
* });
|
|
60
|
-
* ```
|
|
61
|
-
*/
|
|
62
|
-
createRequest() {
|
|
63
|
-
// Generate cryptographically secure nonce (GS-SEC-RNG: NEVER use Math.random)
|
|
64
|
-
const nonceBytes = new Uint8Array(16);
|
|
65
|
-
if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.getRandomValues) {
|
|
66
|
-
globalThis.crypto.getRandomValues(nonceBytes);
|
|
67
|
-
}
|
|
68
|
-
else {
|
|
69
|
-
// Node.js environment
|
|
70
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
71
|
-
const crypto = require('node:crypto');
|
|
72
|
-
crypto.getRandomValues(nonceBytes);
|
|
73
|
-
}
|
|
74
|
-
const nonce = Array.from(nonceBytes)
|
|
75
|
-
.map((b) => b.toString(16).padStart(2, '0'))
|
|
76
|
-
.join('');
|
|
77
|
-
const timestamp = Date.now();
|
|
78
|
-
// Store nonce for validation (60-second TTL)
|
|
79
|
-
this.pendingNonces.set(nonce, timestamp);
|
|
80
|
-
return {
|
|
81
|
-
device_a_did: this.deviceDid,
|
|
82
|
-
nonce,
|
|
83
|
-
timestamp,
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Validate pairing request.
|
|
88
|
-
*
|
|
89
|
-
* Checks timeout and nonce uniqueness.
|
|
90
|
-
* Device B calls this when receiving request from Device A.
|
|
91
|
-
*
|
|
92
|
-
* @param request - Pairing request from remote device
|
|
93
|
-
* @returns Ok if valid, Err with reason if invalid
|
|
94
|
-
*
|
|
95
|
-
* @example
|
|
96
|
-
* ```typescript
|
|
97
|
-
* // Device B receives request
|
|
98
|
-
* const validation = manager.validateRequest(request);
|
|
99
|
-
* if (!validation.ok) {
|
|
100
|
-
* return res.status(400).json({ error: validation.error });
|
|
101
|
-
* }
|
|
102
|
-
* ```
|
|
103
|
-
*/
|
|
104
|
-
validateRequest(request) {
|
|
105
|
-
// Check timeout (60-second window)
|
|
106
|
-
const age = Date.now() - request.timestamp;
|
|
107
|
-
if (age > 60_000) {
|
|
108
|
-
return err(`Request expired (${Math.floor(age / 1000)}s old, max 60s)`);
|
|
109
|
-
}
|
|
110
|
-
if (age < 0) {
|
|
111
|
-
return err('Request timestamp in the future (clock skew detected)');
|
|
112
|
-
}
|
|
113
|
-
// Check required fields
|
|
114
|
-
if (!request.device_a_did || !request.nonce || !request.timestamp) {
|
|
115
|
-
return err('Missing required fields (device_a_did, nonce, timestamp)');
|
|
116
|
-
}
|
|
117
|
-
return ok(undefined);
|
|
118
|
-
}
|
|
119
|
-
/**
|
|
120
|
-
* Accept pairing request.
|
|
121
|
-
*
|
|
122
|
-
* Shows UI prompt for user confirmation, then stores in trust registry.
|
|
123
|
-
* Device B calls this after validating request.
|
|
124
|
-
*
|
|
125
|
-
* @param request - Validated pairing request
|
|
126
|
-
* @param promptCallback - Async function to show UI prompt (returns true if accepted)
|
|
127
|
-
* @returns Pairing response to send back to Device A
|
|
128
|
-
*
|
|
129
|
-
* @example
|
|
130
|
-
* ```typescript
|
|
131
|
-
* const response = await manager.acceptPairing(request, async () => {
|
|
132
|
-
* // Show modal: "Device {name} wants to pair. Accept?"
|
|
133
|
-
* return await showConfirmationDialog({
|
|
134
|
-
* title: 'Pair with Device?',
|
|
135
|
-
* message: `DID: ${request.device_a_did.slice(0, 20)}...`,
|
|
136
|
-
* });
|
|
137
|
-
* });
|
|
138
|
-
*
|
|
139
|
-
* if (response.ok && response.value.accepted) {
|
|
140
|
-
* // Send response back to Device A
|
|
141
|
-
* }
|
|
142
|
-
* ```
|
|
143
|
-
*/
|
|
144
|
-
async acceptPairing(request, promptCallback) {
|
|
145
|
-
// Validate request first
|
|
146
|
-
const validation = this.validateRequest(request);
|
|
147
|
-
if (!validation.ok) {
|
|
148
|
-
return err(validation.error);
|
|
149
|
-
}
|
|
150
|
-
// Prompt user for confirmation
|
|
151
|
-
const accepted = await promptCallback();
|
|
152
|
-
if (accepted) {
|
|
153
|
-
// Store in trust registry (Device A → Device B)
|
|
154
|
-
const registerResult = await this.registry.register(request.device_a_did, new Uint8Array(32), 'Paired Device', ['pairing']);
|
|
155
|
-
if (!registerResult.ok) {
|
|
156
|
-
const errorMsg = typeof registerResult.error === 'string'
|
|
157
|
-
? registerResult.error
|
|
158
|
-
: 'Unknown error';
|
|
159
|
-
return err(`Failed to register pairing: ${errorMsg}`);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
// Return response (echo nonce to prevent MITM)
|
|
163
|
-
return ok({
|
|
164
|
-
device_b_did: this.deviceDid,
|
|
165
|
-
accepted,
|
|
166
|
-
nonce: request.nonce,
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* Finalize pairing.
|
|
171
|
-
*
|
|
172
|
-
* Verifies response nonce and stores remote DID in trust registry.
|
|
173
|
-
* Device A calls this after receiving response from Device B.
|
|
174
|
-
*
|
|
175
|
-
* @param response - Pairing response from Device B
|
|
176
|
-
* @param expectedNonce - Nonce from original request (for verification)
|
|
177
|
-
* @returns Ok if successful, Err if nonce mismatch or storage failed
|
|
178
|
-
*
|
|
179
|
-
* @example
|
|
180
|
-
* ```typescript
|
|
181
|
-
* const request = manager.createRequest();
|
|
182
|
-
* const response = await sendPairingRequest(deviceB.endpoint, request);
|
|
183
|
-
*
|
|
184
|
-
* const result = await manager.finalizePairing(response, request.nonce);
|
|
185
|
-
* if (result.ok) {
|
|
186
|
-
* console.log('Pairing successful!');
|
|
187
|
-
* } else {
|
|
188
|
-
* console.error('Pairing failed:', result.error);
|
|
189
|
-
* }
|
|
190
|
-
* ```
|
|
191
|
-
*/
|
|
192
|
-
async finalizePairing(response, expectedNonce) {
|
|
193
|
-
// Verify nonce echo (prevents MITM substitution)
|
|
194
|
-
if (response.nonce !== expectedNonce) {
|
|
195
|
-
return err('Nonce mismatch (possible MITM attack)');
|
|
196
|
-
}
|
|
197
|
-
// Check if pairing was accepted
|
|
198
|
-
if (!response.accepted) {
|
|
199
|
-
return err('Pairing rejected by remote device');
|
|
200
|
-
}
|
|
201
|
-
// Remove nonce from pending set
|
|
202
|
-
this.pendingNonces.delete(expectedNonce);
|
|
203
|
-
// Store in trust registry (Device B → Device A)
|
|
204
|
-
const registerResult = await this.registry.register(response.device_b_did, new Uint8Array(32), 'Paired Device', ['pairing']);
|
|
205
|
-
if (!registerResult.ok) {
|
|
206
|
-
const errorMsg = typeof registerResult.error === 'string'
|
|
207
|
-
? registerResult.error
|
|
208
|
-
: 'Unknown error';
|
|
209
|
-
return err(`Failed to register pairing: ${errorMsg}`);
|
|
210
|
-
}
|
|
211
|
-
return ok(undefined);
|
|
212
|
-
}
|
|
213
|
-
/**
|
|
214
|
-
* Get pending nonce count (for debugging/monitoring).
|
|
215
|
-
*/
|
|
216
|
-
getPendingNonceCount() {
|
|
217
|
-
return this.pendingNonces.size;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
1
|
+
import{ok,err}from"./_deps/shared/index.js";export class PairingManager{pendingNonces=new Map;registry;deviceDid;constructor(e,r){this.deviceDid=e,this.registry=r,setInterval(()=>{const e=Date.now();for(const[r,i]of this.pendingNonces.entries())e-i>6e4&&this.pendingNonces.delete(r)},1e4)}createRequest(){const e=new Uint8Array(16);if(void 0!==globalThis.crypto&&globalThis.crypto.getRandomValues)globalThis.crypto.getRandomValues(e);else{require("node:crypto").getRandomValues(e)}const r=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),i=Date.now();return this.pendingNonces.set(r,i),{device_a_did:this.deviceDid,nonce:r,timestamp:i}}validateRequest(e){const r=Date.now()-e.timestamp;return r>6e4?err(`Request expired (${Math.floor(r/1e3)}s old, max 60s)`):r<0?err("Request timestamp in the future (clock skew detected)"):e.device_a_did&&e.nonce&&e.timestamp?ok(void 0):err("Missing required fields (device_a_did, nonce, timestamp)")}async acceptPairing(e,r){const i=this.validateRequest(e);if(!i.ok)return err(i.error);const t=await r();if(t){const r=await this.registry.register(e.device_a_did,new Uint8Array(32),"Paired Device",["pairing"]);if(!r.ok){const e="string"==typeof r.error?r.error:"Unknown error";return err(`Failed to register pairing: ${e}`)}}return ok({device_b_did:this.deviceDid,accepted:t,nonce:e.nonce})}async finalizePairing(e,r){if(e.nonce!==r)return err("Nonce mismatch (possible MITM attack)");if(!e.accepted)return err("Pairing rejected by remote device");this.pendingNonces.delete(r);const i=await this.registry.register(e.device_b_did,new Uint8Array(32),"Paired Device",["pairing"]);if(!i.ok){const e="string"==typeof i.error?i.error:"Unknown error";return err(`Failed to register pairing: ${e}`)}return ok(void 0)}getPendingNonceCount(){return this.pendingNonces.size}}
|