@dxos/edge-client 0.6.12 → 0.6.13-main.09887cd
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/lib/browser/chunk-ZWJXA37R.mjs +113 -0
- package/dist/lib/browser/chunk-ZWJXA37R.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +368 -179
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +125 -0
- package/dist/lib/browser/testing/index.mjs.map +7 -0
- package/dist/lib/node/chunk-ANV2HBEH.cjs +136 -0
- package/dist/lib/node/chunk-ANV2HBEH.cjs.map +7 -0
- package/dist/lib/node/index.cjs +367 -176
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +155 -0
- package/dist/lib/node/testing/index.cjs.map +7 -0
- package/dist/lib/node-esm/chunk-HNVT57AU.mjs +115 -0
- package/dist/lib/node-esm/chunk-HNVT57AU.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +667 -0
- package/dist/lib/node-esm/index.mjs.map +7 -0
- package/dist/lib/node-esm/meta.json +1 -0
- package/dist/lib/node-esm/testing/index.mjs +126 -0
- package/dist/lib/node-esm/testing/index.mjs.map +7 -0
- package/dist/types/src/auth.d.ts +22 -0
- package/dist/types/src/auth.d.ts.map +1 -0
- package/dist/types/src/defs.d.ts.map +1 -1
- package/dist/types/src/edge-client.d.ts +24 -13
- package/dist/types/src/edge-client.d.ts.map +1 -1
- package/dist/types/src/edge-http-client.d.ts +35 -0
- package/dist/types/src/edge-http-client.d.ts.map +1 -0
- package/dist/types/src/errors.d.ts +4 -1
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +3 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/protocol.d.ts +2 -2
- package/dist/types/src/protocol.d.ts.map +1 -1
- package/dist/types/src/testing/index.d.ts +2 -0
- package/dist/types/src/testing/index.d.ts.map +1 -0
- package/dist/types/src/testing/test-utils.d.ts +21 -0
- package/dist/types/src/testing/test-utils.d.ts.map +1 -0
- package/dist/types/src/utils.d.ts +2 -0
- package/dist/types/src/utils.d.ts.map +1 -0
- package/package.json +29 -14
- package/src/auth.ts +135 -0
- package/src/defs.ts +2 -3
- package/src/edge-client.test.ts +50 -18
- package/src/edge-client.ts +84 -24
- package/src/edge-http-client.ts +151 -0
- package/src/errors.ts +8 -2
- package/src/index.ts +3 -0
- package/src/persistent-lifecycle.test.ts +2 -2
- package/src/protocol.test.ts +1 -2
- package/src/protocol.ts +2 -2
- package/src/testing/index.ts +5 -0
- package/src/testing/test-utils.ts +114 -0
- package/src/utils.ts +10 -0
- package/src/websocket.test.ts +5 -4
- package/dist/types/src/test-utils.d.ts +0 -11
- package/dist/types/src/test-utils.d.ts.map +0 -1
- package/src/test-utils.ts +0 -49
package/src/auth.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { createCredential, signPresentation } from '@dxos/credentials';
|
|
6
|
+
import { type Signer } from '@dxos/crypto';
|
|
7
|
+
import { Keyring } from '@dxos/keyring';
|
|
8
|
+
import { PublicKey } from '@dxos/keys';
|
|
9
|
+
import { type Chain, type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';
|
|
10
|
+
|
|
11
|
+
import type { EdgeIdentity } from './edge-client';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Edge identity backed by a device key without a credential chain.
|
|
15
|
+
*/
|
|
16
|
+
export const createDeviceEdgeIdentity = async (signer: Signer, key: PublicKey): Promise<EdgeIdentity> => {
|
|
17
|
+
return {
|
|
18
|
+
identityKey: key.toHex(),
|
|
19
|
+
peerKey: key.toHex(),
|
|
20
|
+
presentCredentials: async ({ challenge }) => {
|
|
21
|
+
return signPresentation({
|
|
22
|
+
presentation: {
|
|
23
|
+
credentials: [
|
|
24
|
+
// Verifier requires at least one credential in the presentation to establish the subject.
|
|
25
|
+
await createCredential({
|
|
26
|
+
assertion: {
|
|
27
|
+
'@type': 'dxos.halo.credentials.Auth',
|
|
28
|
+
},
|
|
29
|
+
issuer: key,
|
|
30
|
+
subject: key,
|
|
31
|
+
signer,
|
|
32
|
+
}),
|
|
33
|
+
],
|
|
34
|
+
},
|
|
35
|
+
signer,
|
|
36
|
+
signerKey: key,
|
|
37
|
+
nonce: challenge,
|
|
38
|
+
});
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Edge identity backed by a chain of credentials.
|
|
45
|
+
*/
|
|
46
|
+
export const createChainEdgeIdentity = async (
|
|
47
|
+
signer: Signer,
|
|
48
|
+
identityKey: PublicKey,
|
|
49
|
+
peerKey: PublicKey,
|
|
50
|
+
chain: Chain,
|
|
51
|
+
credentials: Credential[],
|
|
52
|
+
): Promise<EdgeIdentity> => {
|
|
53
|
+
const credentialsToSign =
|
|
54
|
+
credentials.length > 0
|
|
55
|
+
? credentials
|
|
56
|
+
: [
|
|
57
|
+
await createCredential({
|
|
58
|
+
assertion: {
|
|
59
|
+
'@type': 'dxos.halo.credentials.Auth',
|
|
60
|
+
},
|
|
61
|
+
issuer: identityKey,
|
|
62
|
+
subject: identityKey,
|
|
63
|
+
signer,
|
|
64
|
+
chain,
|
|
65
|
+
signingKey: peerKey,
|
|
66
|
+
}),
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
identityKey: identityKey.toHex(),
|
|
71
|
+
peerKey: peerKey.toHex(),
|
|
72
|
+
presentCredentials: async ({ challenge }) => {
|
|
73
|
+
return signPresentation({
|
|
74
|
+
presentation: {
|
|
75
|
+
credentials: credentialsToSign,
|
|
76
|
+
},
|
|
77
|
+
signer,
|
|
78
|
+
nonce: challenge,
|
|
79
|
+
signerKey: peerKey,
|
|
80
|
+
chain,
|
|
81
|
+
});
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Edge identity backed by a random ephemeral key without HALO.
|
|
88
|
+
*/
|
|
89
|
+
export const createEphemeralEdgeIdentity = async (): Promise<EdgeIdentity> => {
|
|
90
|
+
const keyring = new Keyring();
|
|
91
|
+
const key = await keyring.createKey();
|
|
92
|
+
return createDeviceEdgeIdentity(keyring, key);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Creates a HALO chain of credentials to act as an edge identity.
|
|
97
|
+
*/
|
|
98
|
+
export const createTestHaloEdgeIdentity = async (
|
|
99
|
+
signer: Signer,
|
|
100
|
+
identityKey: PublicKey,
|
|
101
|
+
deviceKey: PublicKey,
|
|
102
|
+
): Promise<EdgeIdentity> => {
|
|
103
|
+
const deviceAdmission = await createCredential({
|
|
104
|
+
assertion: {
|
|
105
|
+
'@type': 'dxos.halo.credentials.AuthorizedDevice',
|
|
106
|
+
deviceKey,
|
|
107
|
+
identityKey,
|
|
108
|
+
},
|
|
109
|
+
issuer: identityKey,
|
|
110
|
+
subject: deviceKey,
|
|
111
|
+
signer,
|
|
112
|
+
});
|
|
113
|
+
return createChainEdgeIdentity(signer, identityKey, deviceKey, { credential: deviceAdmission }, [
|
|
114
|
+
await createCredential({
|
|
115
|
+
assertion: {
|
|
116
|
+
'@type': 'dxos.halo.credentials.Auth',
|
|
117
|
+
},
|
|
118
|
+
issuer: identityKey,
|
|
119
|
+
subject: identityKey,
|
|
120
|
+
signer,
|
|
121
|
+
}),
|
|
122
|
+
]);
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
export const createStubEdgeIdentity = (): EdgeIdentity => {
|
|
126
|
+
const identityKey = PublicKey.random();
|
|
127
|
+
const deviceKey = PublicKey.random();
|
|
128
|
+
return {
|
|
129
|
+
identityKey: identityKey.toHex(),
|
|
130
|
+
peerKey: deviceKey.toHex(),
|
|
131
|
+
presentCredentials: async () => {
|
|
132
|
+
throw new Error('Stub identity does not support authentication.');
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
};
|
package/src/defs.ts
CHANGED
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
// Copyright 2024 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import {
|
|
6
|
-
|
|
5
|
+
import { bufWkt } from '@dxos/protocols/buf';
|
|
7
6
|
import { SwarmRequestSchema, SwarmResponseSchema, TextMessageSchema } from '@dxos/protocols/buf/dxos/edge/messenger_pb';
|
|
8
7
|
|
|
9
8
|
import { Protocol } from './protocol';
|
|
10
9
|
|
|
11
|
-
export const protocol = new Protocol([SwarmRequestSchema, SwarmResponseSchema, TextMessageSchema, AnySchema]);
|
|
10
|
+
export const protocol = new Protocol([SwarmRequestSchema, SwarmResponseSchema, TextMessageSchema, bufWkt.AnySchema]);
|
package/src/edge-client.test.ts
CHANGED
|
@@ -2,49 +2,81 @@
|
|
|
2
2
|
// Copyright 2024 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
6
|
-
import chaiAsPromised from 'chai-as-promised';
|
|
5
|
+
import { describe, expect, onTestFinished, test } from 'vitest';
|
|
7
6
|
|
|
8
|
-
import {
|
|
7
|
+
import { Trigger } from '@dxos/async';
|
|
8
|
+
import { Keyring } from '@dxos/keyring';
|
|
9
9
|
import { TextMessageSchema } from '@dxos/protocols/buf/dxos/edge/messenger_pb';
|
|
10
|
-
import {
|
|
10
|
+
import { openAndClose } from '@dxos/test-utils';
|
|
11
11
|
|
|
12
|
+
import { createEphemeralEdgeIdentity, createTestHaloEdgeIdentity } from './auth';
|
|
12
13
|
import { protocol } from './defs';
|
|
13
14
|
import { EdgeClient } from './edge-client';
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
chai.use(chaiAsPromised);
|
|
15
|
+
import { createTestEdgeWsServer } from './testing';
|
|
17
16
|
|
|
18
17
|
describe('EdgeClient', () => {
|
|
19
18
|
const textMessage = (message: string) => protocol.createMessage(TextMessageSchema, { payload: { message } });
|
|
20
19
|
|
|
21
20
|
test('reconnects on error', async () => {
|
|
22
|
-
const {
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
const { closeConnection, endpoint, cleanup } = await createTestEdgeWsServer(8001);
|
|
22
|
+
onTestFinished(cleanup);
|
|
23
|
+
|
|
24
|
+
const client = new EdgeClient(await createEphemeralEdgeIdentity(), { socketEndpoint: endpoint });
|
|
25
25
|
await openAndClose(client);
|
|
26
26
|
await client.send(textMessage('Hello world 1'));
|
|
27
27
|
expect(client.isOpen).is.true;
|
|
28
28
|
|
|
29
29
|
const reconnected = client.reconnect.waitForCount(1);
|
|
30
|
-
await
|
|
30
|
+
await closeConnection();
|
|
31
31
|
await reconnected;
|
|
32
|
-
await expect(client.send(textMessage('Hello world 2'))).
|
|
32
|
+
await expect(client.send(textMessage('Hello world 2'))).resolves.not.toThrow();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('isConnected', async () => {
|
|
36
|
+
const admitConnection = new Trigger();
|
|
37
|
+
const { closeConnection, endpoint, cleanup } = await createTestEdgeWsServer(8001, { admitConnection });
|
|
38
|
+
onTestFinished(cleanup);
|
|
39
|
+
|
|
40
|
+
const client = new EdgeClient(await createEphemeralEdgeIdentity(), { socketEndpoint: endpoint });
|
|
41
|
+
await openAndClose(client);
|
|
42
|
+
|
|
43
|
+
expect(client.isConnected).toBeFalsy();
|
|
44
|
+
admitConnection.wake();
|
|
45
|
+
await expect.poll(() => client.isConnected).toBeTruthy();
|
|
46
|
+
|
|
47
|
+
admitConnection.reset();
|
|
48
|
+
await closeConnection();
|
|
49
|
+
expect(client.isOpen).is.true;
|
|
50
|
+
await expect.poll(() => client.isConnected).toBeFalsy();
|
|
51
|
+
|
|
52
|
+
admitConnection.wake();
|
|
53
|
+
await expect.poll(() => client.isConnected).toBeTruthy();
|
|
33
54
|
});
|
|
34
55
|
|
|
35
56
|
test('set identity reconnects', async () => {
|
|
36
|
-
const { endpoint } = await
|
|
57
|
+
const { endpoint, cleanup } = await createTestEdgeWsServer(8002);
|
|
58
|
+
onTestFinished(cleanup);
|
|
37
59
|
|
|
38
|
-
const
|
|
39
|
-
const client = new EdgeClient(id, id, { socketEndpoint: endpoint });
|
|
60
|
+
const client = new EdgeClient(await createEphemeralEdgeIdentity(), { socketEndpoint: endpoint });
|
|
40
61
|
await openAndClose(client);
|
|
41
62
|
await client.send(textMessage('Hello world 1'));
|
|
42
63
|
expect(client.isOpen).is.true;
|
|
43
64
|
|
|
44
|
-
const newId = PublicKey.random().toHex();
|
|
45
65
|
const reconnected = client.reconnect.waitForCount(1);
|
|
46
|
-
client.setIdentity(
|
|
66
|
+
client.setIdentity(await createEphemeralEdgeIdentity());
|
|
47
67
|
await reconnected;
|
|
48
|
-
await expect(client.send(textMessage('Hello world 2'))).
|
|
68
|
+
await expect(client.send(textMessage('Hello world 2'))).resolves.not.toThrow();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test.skipIf(!process.env.EDGE_ENDPOINT)('connect to local edge server', async () => {
|
|
72
|
+
// const identity = await createEphemeralEdgeIdentity();
|
|
73
|
+
|
|
74
|
+
const keyring = new Keyring();
|
|
75
|
+
const identity = await createTestHaloEdgeIdentity(keyring, await keyring.createKey(), await keyring.createKey());
|
|
76
|
+
|
|
77
|
+
const client = new EdgeClient(identity, { socketEndpoint: process.env.EDGE_ENDPOINT! });
|
|
78
|
+
await openAndClose(client);
|
|
79
|
+
await client.send(textMessage('Hello world 1'));
|
|
80
|
+
expect(client.isOpen).is.true;
|
|
49
81
|
});
|
|
50
82
|
});
|
package/src/edge-client.ts
CHANGED
|
@@ -6,15 +6,18 @@ import WebSocket from 'isomorphic-ws';
|
|
|
6
6
|
|
|
7
7
|
import { Trigger, Event, scheduleTaskInterval, scheduleTask, TriggerState } from '@dxos/async';
|
|
8
8
|
import { Context, LifecycleState, Resource, type Lifecycle } from '@dxos/context';
|
|
9
|
-
import {
|
|
9
|
+
import { randomBytes } from '@dxos/crypto';
|
|
10
10
|
import { log } from '@dxos/log';
|
|
11
11
|
import { buf } from '@dxos/protocols/buf';
|
|
12
12
|
import { type Message, MessageSchema } from '@dxos/protocols/buf/dxos/edge/messenger_pb';
|
|
13
|
+
import { schema } from '@dxos/protocols/proto';
|
|
14
|
+
import { type Presentation } from '@dxos/protocols/proto/dxos/halo/credentials';
|
|
13
15
|
|
|
14
16
|
import { protocol } from './defs';
|
|
15
|
-
import {
|
|
17
|
+
import { EdgeConnectionClosedError, EdgeIdentityChangedError } from './errors';
|
|
16
18
|
import { PersistentLifecycle } from './persistent-lifecycle';
|
|
17
19
|
import { type Protocol, toUint8Array } from './protocol';
|
|
20
|
+
import { getEdgeUrlWithProtocol } from './utils';
|
|
18
21
|
|
|
19
22
|
const DEFAULT_TIMEOUT = 10_000;
|
|
20
23
|
const SIGNAL_KEEPALIVE_INTERVAL = 5_000;
|
|
@@ -22,13 +25,15 @@ const SIGNAL_KEEPALIVE_INTERVAL = 5_000;
|
|
|
22
25
|
export type MessageListener = (message: Message) => void | Promise<void>;
|
|
23
26
|
|
|
24
27
|
export interface EdgeConnection extends Required<Lifecycle> {
|
|
28
|
+
connected: Event;
|
|
25
29
|
reconnect: Event;
|
|
26
30
|
|
|
27
31
|
get info(): any;
|
|
28
32
|
get identityKey(): string;
|
|
29
33
|
get peerKey(): string;
|
|
30
34
|
get isOpen(): boolean;
|
|
31
|
-
|
|
35
|
+
get isConnected(): boolean;
|
|
36
|
+
setIdentity(identity: EdgeIdentity): void;
|
|
32
37
|
addListener(listener: MessageListener): () => void;
|
|
33
38
|
send(message: Message): Promise<void>;
|
|
34
39
|
}
|
|
@@ -37,13 +42,26 @@ export type MessengerConfig = {
|
|
|
37
42
|
socketEndpoint: string;
|
|
38
43
|
timeout?: number;
|
|
39
44
|
protocol?: Protocol;
|
|
45
|
+
disableAuth?: boolean;
|
|
40
46
|
};
|
|
41
47
|
|
|
48
|
+
export interface EdgeIdentity {
|
|
49
|
+
peerKey: string;
|
|
50
|
+
identityKey: string;
|
|
51
|
+
/**
|
|
52
|
+
* Returns credential presentation issued by the identity key.
|
|
53
|
+
* Presentation must have the provided challenge.
|
|
54
|
+
* Presentation may include ServiceAccess credentials.
|
|
55
|
+
*/
|
|
56
|
+
presentCredentials({ challenge }: { challenge: Uint8Array }): Promise<Presentation>;
|
|
57
|
+
}
|
|
58
|
+
|
|
42
59
|
/**
|
|
43
60
|
* Messenger client.
|
|
44
61
|
*/
|
|
45
62
|
export class EdgeClient extends Resource implements EdgeConnection {
|
|
46
|
-
public reconnect = new Event();
|
|
63
|
+
public readonly reconnect = new Event();
|
|
64
|
+
public readonly connected = new Event();
|
|
47
65
|
private readonly _persistentLifecycle = new PersistentLifecycle({
|
|
48
66
|
start: async () => this._openWebSocket(),
|
|
49
67
|
stop: async () => this._closeWebSocket(),
|
|
@@ -51,42 +69,48 @@ export class EdgeClient extends Resource implements EdgeConnection {
|
|
|
51
69
|
});
|
|
52
70
|
|
|
53
71
|
private readonly _listeners = new Set<MessageListener>();
|
|
54
|
-
private readonly _protocol: Protocol;
|
|
55
72
|
private _ready = new Trigger();
|
|
56
73
|
private _ws?: WebSocket = undefined;
|
|
57
74
|
private _keepaliveCtx?: Context = undefined;
|
|
58
75
|
private _heartBeatContext?: Context = undefined;
|
|
59
76
|
|
|
77
|
+
private _baseUrl: string;
|
|
78
|
+
|
|
60
79
|
constructor(
|
|
61
|
-
private
|
|
62
|
-
private _peerKey: string,
|
|
80
|
+
private _identity: EdgeIdentity,
|
|
63
81
|
private readonly _config: MessengerConfig,
|
|
64
82
|
) {
|
|
65
83
|
super();
|
|
66
|
-
this.
|
|
84
|
+
this._baseUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, 'ws');
|
|
67
85
|
}
|
|
68
86
|
|
|
69
87
|
// TODO(burdon): Attach logging.
|
|
70
88
|
public get info() {
|
|
71
89
|
return {
|
|
72
90
|
open: this.isOpen,
|
|
73
|
-
identity: this.
|
|
74
|
-
device: this.
|
|
91
|
+
identity: this._identity.identityKey,
|
|
92
|
+
device: this._identity.peerKey,
|
|
75
93
|
};
|
|
76
94
|
}
|
|
77
95
|
|
|
96
|
+
get isConnected() {
|
|
97
|
+
return Boolean(this._ws) && this._ready.state === TriggerState.RESOLVED;
|
|
98
|
+
}
|
|
99
|
+
|
|
78
100
|
get identityKey() {
|
|
79
|
-
return this.
|
|
101
|
+
return this._identity.identityKey;
|
|
80
102
|
}
|
|
81
103
|
|
|
82
104
|
get peerKey() {
|
|
83
|
-
return this.
|
|
105
|
+
return this._identity.peerKey;
|
|
84
106
|
}
|
|
85
107
|
|
|
86
|
-
setIdentity(
|
|
87
|
-
this.
|
|
88
|
-
|
|
89
|
-
|
|
108
|
+
setIdentity(identity: EdgeIdentity) {
|
|
109
|
+
if (identity.identityKey !== this._identity.identityKey || identity.peerKey !== this._identity.peerKey) {
|
|
110
|
+
log('Edge identity changed', { identity, oldIdentity: this._identity });
|
|
111
|
+
this._identity = identity;
|
|
112
|
+
this._persistentLifecycle.scheduleRestart();
|
|
113
|
+
}
|
|
90
114
|
}
|
|
91
115
|
|
|
92
116
|
public addListener(listener: MessageListener): () => void {
|
|
@@ -108,17 +132,32 @@ export class EdgeClient extends Resource implements EdgeConnection {
|
|
|
108
132
|
* Close connection and free resources.
|
|
109
133
|
*/
|
|
110
134
|
protected override async _close() {
|
|
111
|
-
log('closing...', { peerKey: this.
|
|
135
|
+
log('closing...', { peerKey: this._identity.peerKey });
|
|
112
136
|
await this._persistentLifecycle.close();
|
|
113
137
|
}
|
|
114
138
|
|
|
115
139
|
private async _openWebSocket() {
|
|
116
|
-
|
|
117
|
-
|
|
140
|
+
let protocolHeader: string | undefined;
|
|
141
|
+
|
|
142
|
+
if (!this._config.disableAuth) {
|
|
143
|
+
// TODO(dmaretskyi): Get challenge from the WWW-Authenticate header returned by the endpoint.
|
|
144
|
+
const challenge = randomBytes(32);
|
|
145
|
+
const credential = await this._identity.presentCredentials({ challenge });
|
|
146
|
+
protocolHeader = encodePresentationIntoAuthHeader(credential);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (this._ctx.disposed) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const url = new URL(`/ws/${this._identity.identityKey}/${this._identity.peerKey}`, this._baseUrl);
|
|
154
|
+
log('Opening websocket', { url: url.toString(), protocolHeader });
|
|
155
|
+
this._ws = new WebSocket(url, protocolHeader ? [protocolHeader] : []);
|
|
118
156
|
|
|
119
157
|
this._ws.onopen = () => {
|
|
120
158
|
log('opened', this.info);
|
|
121
159
|
this._ready.wake();
|
|
160
|
+
this.connected.emit();
|
|
122
161
|
};
|
|
123
162
|
this._ws.onclose = () => {
|
|
124
163
|
log('closed', this.info);
|
|
@@ -138,7 +177,7 @@ export class EdgeClient extends Resource implements EdgeConnection {
|
|
|
138
177
|
}
|
|
139
178
|
const data = await toUint8Array(event.data);
|
|
140
179
|
const message = buf.fromBinary(MessageSchema, data);
|
|
141
|
-
log('received', { peerKey: this.
|
|
180
|
+
log('received', { peerKey: this._identity.peerKey, payload: protocol.getPayloadType(message) });
|
|
142
181
|
if (message) {
|
|
143
182
|
for (const listener of this._listeners) {
|
|
144
183
|
try {
|
|
@@ -150,7 +189,11 @@ export class EdgeClient extends Resource implements EdgeConnection {
|
|
|
150
189
|
}
|
|
151
190
|
};
|
|
152
191
|
|
|
192
|
+
// TODO(dmaretskyi): Potential race condition here since web socket errors don't resolve this trigger.
|
|
153
193
|
await this._ready.wait({ timeout: this._config.timeout ?? DEFAULT_TIMEOUT });
|
|
194
|
+
log('Websocket is ready', { identity: this._identity.identityKey, peer: this._identity.peerKey });
|
|
195
|
+
|
|
196
|
+
// TODO(dmaretskyi): Potential leak: context re-assigned without disposing the previous one.
|
|
154
197
|
this._keepaliveCtx = new Context();
|
|
155
198
|
scheduleTaskInterval(
|
|
156
199
|
this._keepaliveCtx,
|
|
@@ -170,7 +213,7 @@ export class EdgeClient extends Resource implements EdgeConnection {
|
|
|
170
213
|
return;
|
|
171
214
|
}
|
|
172
215
|
try {
|
|
173
|
-
this._ready.throw(new
|
|
216
|
+
this._ready.throw(this.isOpen ? new EdgeIdentityChangedError() : new EdgeConnectionClosedError());
|
|
174
217
|
this._ready.reset();
|
|
175
218
|
void this._keepaliveCtx?.dispose();
|
|
176
219
|
this._keepaliveCtx = undefined;
|
|
@@ -197,11 +240,20 @@ export class EdgeClient extends Resource implements EdgeConnection {
|
|
|
197
240
|
*/
|
|
198
241
|
public async send(message: Message): Promise<void> {
|
|
199
242
|
if (this._ready.state !== TriggerState.RESOLVED) {
|
|
243
|
+
log('waiting for websocket to become ready');
|
|
200
244
|
await this._ready.wait({ timeout: this._config.timeout ?? DEFAULT_TIMEOUT });
|
|
201
245
|
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
246
|
+
if (!this._ws) {
|
|
247
|
+
throw new EdgeConnectionClosedError();
|
|
248
|
+
}
|
|
249
|
+
if (
|
|
250
|
+
message.source &&
|
|
251
|
+
(message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)
|
|
252
|
+
) {
|
|
253
|
+
throw new EdgeIdentityChangedError();
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
log('sending...', { peerKey: this._identity.peerKey, payload: protocol.getPayloadType(message) });
|
|
205
257
|
this._ws.send(buf.toBinary(MessageSchema, message));
|
|
206
258
|
}
|
|
207
259
|
|
|
@@ -220,3 +272,11 @@ export class EdgeClient extends Resource implements EdgeConnection {
|
|
|
220
272
|
);
|
|
221
273
|
}
|
|
222
274
|
}
|
|
275
|
+
|
|
276
|
+
const encodePresentationIntoAuthHeader = (presentation: Presentation): string => {
|
|
277
|
+
const encoded = schema.getCodecForType('dxos.halo.credentials.Presentation').encode(presentation);
|
|
278
|
+
// = and / characters are not allowed in the WebSocket subprotocol header.
|
|
279
|
+
const encodedToken = Buffer.from(encoded).toString('base64').replace(/=*$/, '').replaceAll('/', '|');
|
|
280
|
+
|
|
281
|
+
return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
|
|
282
|
+
};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { sleep } from '@dxos/async';
|
|
6
|
+
import { Context } from '@dxos/context';
|
|
7
|
+
import { type SpaceId } from '@dxos/keys';
|
|
8
|
+
import { log } from '@dxos/log';
|
|
9
|
+
import {
|
|
10
|
+
EdgeCallFailedError,
|
|
11
|
+
type EdgeHttpResponse,
|
|
12
|
+
type GetNotarizationResponseBody,
|
|
13
|
+
type PostNotarizationRequestBody,
|
|
14
|
+
type JoinSpaceRequest,
|
|
15
|
+
type JoinSpaceResponseBody,
|
|
16
|
+
EdgeAuthChallengeError,
|
|
17
|
+
} from '@dxos/protocols';
|
|
18
|
+
|
|
19
|
+
import { getEdgeUrlWithProtocol } from './utils';
|
|
20
|
+
|
|
21
|
+
const DEFAULT_RETRY_TIMEOUT = 1500;
|
|
22
|
+
const DEFAULT_RETRY_JITTER = 500;
|
|
23
|
+
const DEFAULT_MAX_RETRIES_COUNT = 3;
|
|
24
|
+
|
|
25
|
+
export class EdgeHttpClient {
|
|
26
|
+
private readonly _baseUrl: string;
|
|
27
|
+
|
|
28
|
+
constructor(baseUrl: string) {
|
|
29
|
+
this._baseUrl = getEdgeUrlWithProtocol(baseUrl, 'http');
|
|
30
|
+
log('created', { url: this._baseUrl });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
public getCredentialsForNotarization(spaceId: SpaceId, args?: EdgeHttpGetArgs): Promise<GetNotarizationResponseBody> {
|
|
34
|
+
return this._call(`/spaces/${spaceId}/notarization`, { ...args, method: 'GET' });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
public async notarizeCredentials(
|
|
38
|
+
spaceId: SpaceId,
|
|
39
|
+
body: PostNotarizationRequestBody,
|
|
40
|
+
args?: EdgeHttpGetArgs,
|
|
41
|
+
): Promise<void> {
|
|
42
|
+
await this._call(`/spaces/${spaceId}/notarization`, { ...args, body, method: 'POST' });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
public async joinSpaceByInvitation(
|
|
46
|
+
spaceId: SpaceId,
|
|
47
|
+
body: JoinSpaceRequest,
|
|
48
|
+
args?: EdgeHttpGetArgs,
|
|
49
|
+
): Promise<JoinSpaceResponseBody> {
|
|
50
|
+
return this._call(`/spaces/${spaceId}/join`, { ...args, body, method: 'POST' });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private async _call<T>(path: string, args: EdgeHttpCallArgs): Promise<T> {
|
|
54
|
+
const requestContext = args.context ?? new Context();
|
|
55
|
+
const shouldRetry = createRetryHandler(args);
|
|
56
|
+
const request = createRequest(args);
|
|
57
|
+
const url = `${this._baseUrl}${path.startsWith('/') ? path.slice(1) : path}`;
|
|
58
|
+
|
|
59
|
+
log.info('call', { method: args.method, path });
|
|
60
|
+
|
|
61
|
+
while (true) {
|
|
62
|
+
let processingError: EdgeCallFailedError;
|
|
63
|
+
let retryAfterHeaderValue: number = Number.NaN;
|
|
64
|
+
try {
|
|
65
|
+
const response = await fetch(url, request);
|
|
66
|
+
|
|
67
|
+
retryAfterHeaderValue = Number(response.headers.get('Retry-After'));
|
|
68
|
+
|
|
69
|
+
if (response.ok) {
|
|
70
|
+
const body = (await response.json()) as EdgeHttpResponse<T>;
|
|
71
|
+
if (body.success) {
|
|
72
|
+
return body.data;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (body.errorData?.type === 'auth_challenge' && typeof body.errorData?.challenge === 'string') {
|
|
76
|
+
processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
|
|
77
|
+
} else {
|
|
78
|
+
processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
|
|
79
|
+
}
|
|
80
|
+
} else {
|
|
81
|
+
processingError = EdgeCallFailedError.fromHttpFailure(response);
|
|
82
|
+
}
|
|
83
|
+
} catch (error: any) {
|
|
84
|
+
processingError = EdgeCallFailedError.fromProcessingFailureCause(error);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (processingError.isRetryable && (await shouldRetry(requestContext, retryAfterHeaderValue))) {
|
|
88
|
+
log.info('retrying edge request', { path, processingError });
|
|
89
|
+
} else {
|
|
90
|
+
throw processingError;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const createRequest = (args: EdgeHttpCallArgs): RequestInit => {
|
|
97
|
+
return {
|
|
98
|
+
method: args.method,
|
|
99
|
+
body: args.body && JSON.stringify(args.body),
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const createRetryHandler = (args: EdgeHttpCallArgs) => {
|
|
104
|
+
if (!args.retry || args.retry.count < 1) {
|
|
105
|
+
return async () => false;
|
|
106
|
+
}
|
|
107
|
+
let retries = 0;
|
|
108
|
+
const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
|
|
109
|
+
const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
|
|
110
|
+
const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;
|
|
111
|
+
return async (ctx: Context, retryAfter: number) => {
|
|
112
|
+
if (++retries > maxRetries || ctx.disposed) {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (retryAfter) {
|
|
117
|
+
await sleep(retryAfter);
|
|
118
|
+
} else {
|
|
119
|
+
const timeout = baseTimeout + Math.random() * jitter;
|
|
120
|
+
await sleep(timeout);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return true;
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
export type RetryConfig = {
|
|
128
|
+
/**
|
|
129
|
+
* A number of call retries, not counting the initial request.
|
|
130
|
+
*/
|
|
131
|
+
count: number;
|
|
132
|
+
/**
|
|
133
|
+
* Delay before retries in ms.
|
|
134
|
+
*/
|
|
135
|
+
timeout?: number;
|
|
136
|
+
/**
|
|
137
|
+
* A random amount of time before retrying to help prevent large bursts of requests.
|
|
138
|
+
*/
|
|
139
|
+
jitter?: number;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export type EdgeHttpGetArgs = { context?: Context; retry?: RetryConfig };
|
|
143
|
+
|
|
144
|
+
export type EdgeHttpPostArgs = { context?: Context; body?: any; retry?: RetryConfig };
|
|
145
|
+
|
|
146
|
+
type EdgeHttpCallArgs = {
|
|
147
|
+
method: string;
|
|
148
|
+
body?: any;
|
|
149
|
+
context?: Context;
|
|
150
|
+
retry?: RetryConfig;
|
|
151
|
+
};
|
package/src/errors.ts
CHANGED
|
@@ -2,8 +2,14 @@
|
|
|
2
2
|
// Copyright 2024 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
export class
|
|
5
|
+
export class EdgeConnectionClosedError extends Error {
|
|
6
6
|
constructor() {
|
|
7
|
-
super('
|
|
7
|
+
super('Edge connection closed.');
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export class EdgeIdentityChangedError extends Error {
|
|
12
|
+
constructor() {
|
|
13
|
+
super('Edge identity changed.');
|
|
8
14
|
}
|
|
9
15
|
}
|
package/src/index.ts
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
// Copyright 2024 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import { expect } from '
|
|
5
|
+
import { describe, expect, test } from 'vitest';
|
|
6
6
|
|
|
7
7
|
import { sleep, Trigger } from '@dxos/async';
|
|
8
8
|
import { log } from '@dxos/log';
|
|
9
|
-
import {
|
|
9
|
+
import { openAndClose } from '@dxos/test-utils';
|
|
10
10
|
|
|
11
11
|
import { PersistentLifecycle } from './persistent-lifecycle';
|
|
12
12
|
|
package/src/protocol.test.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Copyright 2024 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import { expect } from '
|
|
5
|
+
import { describe, expect, test } from 'vitest';
|
|
6
6
|
|
|
7
7
|
import { buf } from '@dxos/protocols/buf';
|
|
8
8
|
import {
|
|
@@ -11,7 +11,6 @@ import {
|
|
|
11
11
|
SwarmRequestSchema,
|
|
12
12
|
SwarmResponseSchema,
|
|
13
13
|
} from '@dxos/protocols/buf/dxos/edge/messenger_pb';
|
|
14
|
-
import { describe, test } from '@dxos/test';
|
|
15
14
|
|
|
16
15
|
import { Protocol } from './protocol';
|
|
17
16
|
|