@augmentd-labs/canvas-edge 0.4.1 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/node_modules/canvas-stored/package.json +2 -15
- package/node_modules/canvas-stored/src/backends/file/index.js +35 -4
- package/node_modules/canvas-stored/src/index.js +13 -1
- package/package.json +6 -5
- package/src/EdgeClient.js +1 -129
- package/src/env.js +4 -2
- package/src/mirror-runtime.js +10 -4
- package/src/remote-config.js +7 -3
- package/src/runtime.js +1 -0
package/README.md
CHANGED
|
@@ -75,3 +75,12 @@ mirrors.json). `CANVAS_DIRECTION=pull` makes the container a backup target
|
|
|
75
75
|
|
|
76
76
|
Protocol: canvas-server `docs/canvas-edge-protocol.md` (tunnel) and
|
|
77
77
|
`docs/sync-protocol.md` (file plane).
|
|
78
|
+
|
|
79
|
+
### Client certificates (0.5.0+)
|
|
80
|
+
|
|
81
|
+
Hub remotes retain `tls: { certFile, keyFile }` from the shared client config.
|
|
82
|
+
Workspace remotes can carry the same optional fields. Pairing, tunnel sockets,
|
|
83
|
+
mirror status calls, and object transfers all use the identity. Container bootstrap
|
|
84
|
+
accepts `CANVAS_TLS_CERT`/`CANVAS_TLS_KEY` as a complete pair of file paths; mount
|
|
85
|
+
these files read-only. Use leaf-first PEM chains and protected unencrypted RSA/EC
|
|
86
|
+
keys. Server verification is enabled. Restart the daemon/container after renewal.
|
|
@@ -1,25 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "canvas-stored",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.3",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "./src/index.js",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"author": "Jozef Melich <me@idnc.sk>",
|
|
8
8
|
"license": "AGPL-3.0-or-later",
|
|
9
|
-
"dependencies": {
|
|
10
|
-
"cacache": "^20.0.4",
|
|
11
|
-
"chokidar": "^5.0.0",
|
|
12
|
-
"debug": "^4.4.3",
|
|
13
|
-
"eventemitter2": "^6.4.9",
|
|
14
|
-
"exifr": "^7.1.3",
|
|
15
|
-
"file-type": "^21.3.3",
|
|
16
|
-
"fs-extra": "^11.3.4",
|
|
17
|
-
"image-size": "^2.0.2",
|
|
18
|
-
"imap": "^0.8.19",
|
|
19
|
-
"lmdb": "^3.5.2",
|
|
20
|
-
"music-metadata": "^11.9.0",
|
|
21
|
-
"picomatch": "^2.3.1"
|
|
22
|
-
},
|
|
9
|
+
"dependencies": {},
|
|
23
10
|
"engines": {
|
|
24
11
|
"node": ">=20.0.0"
|
|
25
12
|
}
|
|
@@ -288,6 +288,29 @@ export default class FileBackend extends StorageBackend {
|
|
|
288
288
|
return { key, size: stats.size };
|
|
289
289
|
}
|
|
290
290
|
|
|
291
|
+
// Create-only placement: link(2) fails with EEXIST even for an unindexed
|
|
292
|
+
// file, directory or dangling symlink. Never use rename-over for this path.
|
|
293
|
+
async createFrom(key, srcPath) {
|
|
294
|
+
const dest = this.#resolvePath(key);
|
|
295
|
+
await fs.ensureDir(path.dirname(dest));
|
|
296
|
+
try {
|
|
297
|
+
await fs.link(srcPath, dest);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (error.code !== 'EXDEV') throw error;
|
|
300
|
+
// Stage on the destination filesystem, then publish atomically.
|
|
301
|
+
const sibling = path.join(path.dirname(dest), `${TMP_DIR}-${process.pid}-${Math.random().toString(16).slice(2)}`);
|
|
302
|
+
try {
|
|
303
|
+
await fs.copyFile(srcPath, sibling);
|
|
304
|
+
await fs.link(sibling, dest);
|
|
305
|
+
} finally {
|
|
306
|
+
await fs.remove(sibling).catch(() => {});
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
const stat = await this.stat(key);
|
|
310
|
+
if (!stat) throw new Error(`Upload destination disappeared: ${key}`);
|
|
311
|
+
return stat;
|
|
312
|
+
}
|
|
313
|
+
|
|
291
314
|
// ── Retention ─────────────────────────────────────────────────────────
|
|
292
315
|
//
|
|
293
316
|
// Bytes an overwrite or delete is about to displace are kept for a while
|
|
@@ -399,8 +422,11 @@ export default class FileBackend extends StorageBackend {
|
|
|
399
422
|
|
|
400
423
|
async stat(key) {
|
|
401
424
|
const filePath = this.#resolvePath(key);
|
|
402
|
-
|
|
403
|
-
|
|
425
|
+
let stats;
|
|
426
|
+
try { stats = await fs.stat(filePath); } catch (error) {
|
|
427
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return null;
|
|
428
|
+
throw error;
|
|
429
|
+
}
|
|
404
430
|
if (!stats.isFile()) return null;
|
|
405
431
|
// dev/ino feed rename matching (same inode at a new path) and the
|
|
406
432
|
// liveness checks — stored keeps them in location metadata.
|
|
@@ -413,7 +439,6 @@ export default class FileBackend extends StorageBackend {
|
|
|
413
439
|
async *list(options = {}) {
|
|
414
440
|
const { prefix = '', recursive = true, onError = null } = options;
|
|
415
441
|
const searchPath = this.#resolvePath(prefix);
|
|
416
|
-
if (!await fs.pathExists(searchPath)) return;
|
|
417
442
|
|
|
418
443
|
let entries;
|
|
419
444
|
try {
|
|
@@ -426,7 +451,13 @@ export default class FileBackend extends StorageBackend {
|
|
|
426
451
|
const relativePath = path.join(prefix, entry.name);
|
|
427
452
|
if (this.#isIgnored(relativePath)) continue;
|
|
428
453
|
if (entry.isFile()) {
|
|
429
|
-
|
|
454
|
+
try {
|
|
455
|
+
const stat = await this.stat(relativePath);
|
|
456
|
+
if (stat) yield stat;
|
|
457
|
+
} catch (error) {
|
|
458
|
+
if (typeof onError !== 'function') throw error;
|
|
459
|
+
onError(relativePath, error);
|
|
460
|
+
}
|
|
430
461
|
} else if (entry.isDirectory() && recursive) {
|
|
431
462
|
yield* this.list({ ...options, prefix: relativePath });
|
|
432
463
|
}
|
|
@@ -417,7 +417,14 @@ export default class Stored extends EventEmitter2 {
|
|
|
417
417
|
try {
|
|
418
418
|
if (current) await this.#retain(backendName, destKey, current);
|
|
419
419
|
let placed = null;
|
|
420
|
-
if (
|
|
420
|
+
if (String(options.ifNoneMatch || '').trim() === '*') {
|
|
421
|
+
if (typeof backend.createFrom !== 'function') return { ok: false, reason: 'unsupported-backend' };
|
|
422
|
+
try { placed = await backend.createFrom(destKey, tempPath); }
|
|
423
|
+
catch (error) {
|
|
424
|
+
if (error.code === 'EEXIST') return { ok: false, reason: 'precondition-failed', current: null };
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
427
|
+
} else if (typeof backend.renameFrom === 'function') {
|
|
421
428
|
try { placed = await backend.renameFrom(destKey, tempPath); }
|
|
422
429
|
catch (err) { if (err.code !== 'EXDEV') throw err; }
|
|
423
430
|
}
|
|
@@ -968,6 +975,11 @@ export default class Stored extends EventEmitter2 {
|
|
|
968
975
|
const existing = this.#index.get(id);
|
|
969
976
|
const locations = existing?.locations || [];
|
|
970
977
|
const match = locations.find(l => l.backend === file.backend && l.key === file.key);
|
|
978
|
+
// Avoid LMDB/index/change-feed churn on warm scans. Still emit
|
|
979
|
+
// the row to consumers: their document index may need repair.
|
|
980
|
+
if (match && match.synced === true && match.size === file.size && match.mtime === file.modified
|
|
981
|
+
&& (file.ino == null || (match.ino === file.ino && match.dev === file.dev))
|
|
982
|
+
&& existing.size === file.size && existing.mimeType === file.mimeType) return;
|
|
971
983
|
if (match) {
|
|
972
984
|
match.size = file.size;
|
|
973
985
|
match.mtime = file.modified;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@augmentd-labs/canvas-edge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.2",
|
|
4
4
|
"description": "Canvas device runtime: folder mirrors (canvas-stored Mirror engine) + edge tunnel client (dist artifact)",
|
|
5
5
|
"license": "AGPL-3.0-or-later",
|
|
6
6
|
"type": "module",
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
"node": ">=20.18.0"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@augmentd-labs/canvas-protocol": "^0.
|
|
24
|
-
"canvas-stored": "1.9.
|
|
23
|
+
"@augmentd-labs/canvas-protocol": "^0.5.0",
|
|
24
|
+
"canvas-stored": "1.9.3",
|
|
25
25
|
"cacache": "^20.0.4",
|
|
26
26
|
"chokidar": "^5.0.0",
|
|
27
27
|
"debug": "^4.4.3",
|
|
@@ -36,7 +36,8 @@
|
|
|
36
36
|
"picomatch": "^2.3.1",
|
|
37
37
|
"fastify": "^4.29.1",
|
|
38
38
|
"pino": "^10.3.1",
|
|
39
|
-
"socket.io-client": "^4.8.3"
|
|
39
|
+
"socket.io-client": "^4.8.3",
|
|
40
|
+
"@augmentd-labs/canvas-api-client": "^0.4.1"
|
|
40
41
|
},
|
|
41
42
|
"repository": {
|
|
42
43
|
"type": "git",
|
|
@@ -46,6 +47,6 @@
|
|
|
46
47
|
"bundleDependencies": [
|
|
47
48
|
"canvas-stored"
|
|
48
49
|
],
|
|
49
|
-
"canvasRev": "
|
|
50
|
+
"canvasRev": "52fc07d",
|
|
50
51
|
"canvasSource": "runtimes/edge"
|
|
51
52
|
}
|
package/src/EdgeClient.js
CHANGED
|
@@ -1,129 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import { io } from 'socket.io-client';
|
|
4
|
-
|
|
5
|
-
const CHUNK_SIZE = 256 * 1024;
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* canvas-edge tunnel client.
|
|
9
|
-
*
|
|
10
|
-
* Dials out to a canvas-server instance, announces what this runtime hosts,
|
|
11
|
-
* and replays proxied requests into the local fastify app (`app.inject()`),
|
|
12
|
-
* so the tunnel and localhost serve identical APIs by construction.
|
|
13
|
-
* Reconnection/backoff and heartbeat come from socket.io.
|
|
14
|
-
*
|
|
15
|
-
* See docs/canvas-edge-protocol.md for the frame protocol.
|
|
16
|
-
*/
|
|
17
|
-
export default class EdgeClient {
|
|
18
|
-
#serverUrl;
|
|
19
|
-
#token;
|
|
20
|
-
#localApp;
|
|
21
|
-
#announce;
|
|
22
|
-
#socket = null;
|
|
23
|
-
#announced = false;
|
|
24
|
-
#forwarded = [];
|
|
25
|
-
|
|
26
|
-
constructor({ serverUrl, token, localApp, announce }) {
|
|
27
|
-
if (!serverUrl || !token || !localApp?.inject || !announce?.instanceId) {
|
|
28
|
-
throw new Error('EdgeClient requires serverUrl, token, localApp (fastify) and announce.instanceId');
|
|
29
|
-
}
|
|
30
|
-
this.#serverUrl = serverUrl.replace(/\/+$/, '');
|
|
31
|
-
this.#token = token;
|
|
32
|
-
this.#localApp = localApp;
|
|
33
|
-
this.#announce = announce;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* One-time pairing: exchange a user API token for a device token via the
|
|
38
|
-
* existing device registration endpoint. Persist the result locally and
|
|
39
|
-
* never touch the user token again.
|
|
40
|
-
*/
|
|
41
|
-
static async pair({ serverUrl, userToken, name, type = 'edge', ...deviceInfo }) {
|
|
42
|
-
const res = await fetch(`${serverUrl.replace(/\/+$/, '')}/rest/v2/auth/devices/register`, {
|
|
43
|
-
method: 'POST',
|
|
44
|
-
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${userToken}` },
|
|
45
|
-
body: JSON.stringify({ name, type, ...deviceInfo }),
|
|
46
|
-
});
|
|
47
|
-
const json = await res.json().catch(() => null);
|
|
48
|
-
if (!res.ok || !json?.payload?.token) {
|
|
49
|
-
throw new Error(`Edge pairing failed: ${json?.message || res.statusText}`);
|
|
50
|
-
}
|
|
51
|
-
return { token: json.payload.token, deviceId: json.payload.deviceId || json.payload.id };
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
get connected() {
|
|
55
|
-
return this.#socket?.connected === true;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
connect() {
|
|
59
|
-
if (this.#socket) return this;
|
|
60
|
-
this.#socket = io(this.#serverUrl, {
|
|
61
|
-
auth: { token: this.#token },
|
|
62
|
-
transports: ['websocket'],
|
|
63
|
-
});
|
|
64
|
-
// Announce on every (re)connect — announce is idempotent full state.
|
|
65
|
-
this.#socket.on('connect', () => this.#socket.emit('edge:announce', this.#announce));
|
|
66
|
-
this.#socket.on('edge:announced', () => { this.#announced = true; });
|
|
67
|
-
this.#socket.on('disconnect', () => { this.#announced = false; });
|
|
68
|
-
this.#socket.on('edge:req', (frame) => this.handleRequest(frame));
|
|
69
|
-
return this;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Resolves once the server has acked the announce; rejects on timeout. */
|
|
73
|
-
waitForAnnounce(timeoutMs = 10_000) {
|
|
74
|
-
if (this.#announced) return Promise.resolve();
|
|
75
|
-
if (!this.#socket) return Promise.reject(new Error('not connected — call connect() first'));
|
|
76
|
-
return new Promise((resolve, reject) => {
|
|
77
|
-
const timer = setTimeout(() => {
|
|
78
|
-
this.#socket?.off('edge:announced', onAck);
|
|
79
|
-
reject(new Error(`edge announce not acked within ${timeoutMs}ms`));
|
|
80
|
-
}, timeoutMs);
|
|
81
|
-
const onAck = () => { clearTimeout(timer); resolve(); };
|
|
82
|
-
this.#socket.once('edge:announced', onAck);
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Dispatch a proxied request into the local app and stream the answer back.
|
|
88
|
-
* `socket` is injectable for tests.
|
|
89
|
-
*/
|
|
90
|
-
async handleRequest(frame = {}, socket = this.#socket) {
|
|
91
|
-
const { id, method, path, headers = {}, body, bodyEncoding } = frame;
|
|
92
|
-
if (!id || !method || !path) return;
|
|
93
|
-
try {
|
|
94
|
-
const payload = body == null
|
|
95
|
-
? undefined
|
|
96
|
-
: (bodyEncoding === 'base64' ? Buffer.from(body, 'base64') : body);
|
|
97
|
-
const res = await this.#localApp.inject({ method, url: path, headers, payload });
|
|
98
|
-
socket.emit('edge:res', { id, status: res.statusCode, headers: res.headers });
|
|
99
|
-
const buf = res.rawPayload;
|
|
100
|
-
for (let offset = 0, seq = 0; offset < buf.length; offset += CHUNK_SIZE, seq++) {
|
|
101
|
-
socket.emit('edge:chunk', { id, seq, data: buf.subarray(offset, offset + CHUNK_SIZE).toString('base64') });
|
|
102
|
-
}
|
|
103
|
-
socket.emit('edge:end', { id });
|
|
104
|
-
} catch (err) {
|
|
105
|
-
socket.emit('edge:err', { id, code: 'EDGE_DISPATCH_FAILED', message: err.message });
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Relay all events from a local wildcard emitter (EventEmitter2) up the
|
|
111
|
-
* tunnel; the server re-emits them through its WorkspaceManager.
|
|
112
|
-
*/
|
|
113
|
-
forwardEvents(emitter) {
|
|
114
|
-
const socket = () => this.#socket;
|
|
115
|
-
const listener = function (payload) {
|
|
116
|
-
socket()?.emit('edge:event', { name: this.event, payload });
|
|
117
|
-
};
|
|
118
|
-
emitter.on('**', listener);
|
|
119
|
-
this.#forwarded.push([emitter, listener]);
|
|
120
|
-
return this;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
close() {
|
|
124
|
-
for (const [emitter, listener] of this.#forwarded) emitter.off('**', listener);
|
|
125
|
-
this.#forwarded = [];
|
|
126
|
-
this.#socket?.disconnect();
|
|
127
|
-
this.#socket = null;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
1
|
+
export { default } from '@augmentd-labs/canvas-api-client/edge';
|
package/src/env.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
import { resolveTls } from '@augmentd-labs/canvas-api-client/tls';
|
|
3
4
|
import fs from 'fs';
|
|
4
5
|
import os from 'os';
|
|
5
6
|
import path from 'path';
|
|
@@ -81,7 +82,7 @@ export function ensureEnvConfig(env = process.env) {
|
|
|
81
82
|
const prior = remotes[hubId] || {};
|
|
82
83
|
// A device token minted for this remote stays authoritative; env only
|
|
83
84
|
// seeds the user/API token it started from.
|
|
84
|
-
remotes[hubId] = { ...prior, url, apiBase: prior.apiBase || '/rest/v2', auth: { ...(prior.auth || {}), token }, source: 'env' };
|
|
85
|
+
remotes[hubId] = { ...prior, url, apiBase: prior.apiBase || '/rest/v2', auth: { ...(prior.auth || {}), token }, source: 'env', ...(resolveTls(prior.url && new URL(prior.url).origin !== new URL(url).origin ? undefined : prior.tls, env) ? { tls: resolveTls(prior.url && new URL(prior.url).origin !== new URL(url).origin ? undefined : prior.tls, env) } : { tls: undefined }) };
|
|
85
86
|
writeJson(EDGE_PATHS.remotes, remotes);
|
|
86
87
|
|
|
87
88
|
const cfg = readJson(EDGE_PATHS.mirrors, { version: 1, mirrors: [] }) || { version: 1, mirrors: [] };
|
|
@@ -142,7 +143,7 @@ export async function ensureDeviceToken(remoteId, { logger = null } = {}) {
|
|
|
142
143
|
if (!r?.url || r.source !== 'env' || r.device?.token || !r.auth?.token) return hubFor(remoteId);
|
|
143
144
|
const identity = deviceIdentity(null);
|
|
144
145
|
const paired = await EdgeClient.pair({
|
|
145
|
-
serverUrl: r.url, userToken: r.auth.token, name: identity.deviceName, type: 'edge',
|
|
146
|
+
serverUrl: r.url, tls: resolveTls(r.tls), userToken: r.auth.token, name: identity.deviceName, type: 'edge',
|
|
146
147
|
deviceId: identity.deviceId, hostname: os.hostname(), platform: process.platform, arch: process.arch,
|
|
147
148
|
});
|
|
148
149
|
remotes[remoteId] = { ...r, device: { deviceId: paired.deviceId || identity.deviceId, token: paired.token, registeredAt: new Date().toISOString() } };
|
|
@@ -161,6 +162,7 @@ export function hubFor(remoteId) {
|
|
|
161
162
|
return {
|
|
162
163
|
id: remoteId,
|
|
163
164
|
url: String(r.url).replace(/\/+$/, ''),
|
|
165
|
+
tls: resolveTls(r.tls),
|
|
164
166
|
apiBase: r.apiBase || '/rest/v2',
|
|
165
167
|
token,
|
|
166
168
|
deviceId: deviceToken && r.device?.deviceId ? String(r.device.deviceId) : null,
|
package/src/mirror-runtime.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
import { createTlsTransport } from '@augmentd-labs/canvas-api-client/tls';
|
|
3
4
|
import fs from 'fs';
|
|
4
5
|
import path from 'path';
|
|
5
6
|
import { io } from 'socket.io-client';
|
|
@@ -29,6 +30,7 @@ const STATUS_HEARTBEAT_MS = 60000;
|
|
|
29
30
|
* ledger as `full` so a hub that lost its replica table rebuilds it.
|
|
30
31
|
*/
|
|
31
32
|
export class MirrorRuntime {
|
|
33
|
+
#transport;
|
|
32
34
|
#mirror;
|
|
33
35
|
#hub;
|
|
34
36
|
#identity;
|
|
@@ -45,6 +47,7 @@ export class MirrorRuntime {
|
|
|
45
47
|
constructor({ mirror, hub, identity, logger }) {
|
|
46
48
|
this.#mirror = mirror;
|
|
47
49
|
this.#hub = hub;
|
|
50
|
+
this.#transport = createTlsTransport(hub.url, hub.tls);
|
|
48
51
|
this.#identity = identity;
|
|
49
52
|
this.#logger = logger;
|
|
50
53
|
}
|
|
@@ -87,6 +90,7 @@ export class MirrorRuntime {
|
|
|
87
90
|
this.#stored.addBackend('trash', { driver: 'file', root: path.join(internal, 'trash'), watch: false });
|
|
88
91
|
this.#stored.addBackend('conflicts', { driver: 'file', root: path.join(internal, 'conflicts'), watch: false });
|
|
89
92
|
this.#stored.addBackend('canvas:hub', {
|
|
93
|
+
fetch: this.#transport.fetch,
|
|
90
94
|
driver: 'canvas', url: this.#hub.url, apiBase: this.#hub.apiBase, token: this.#hub.token,
|
|
91
95
|
workspaceId: this.#mirror.workspaceId || this.#mirror.workspaceName, backend: 'workspace:home',
|
|
92
96
|
deviceId: this.#identity.deviceId, deviceName: this.#identity.deviceName, prefixes: this.#mirror.pins || [], pollInterval: 30000,
|
|
@@ -113,6 +117,7 @@ export class MirrorRuntime {
|
|
|
113
117
|
}
|
|
114
118
|
|
|
115
119
|
async stop() {
|
|
120
|
+
// Close pooled TLS connections after stopping mirror activity below.
|
|
116
121
|
clearInterval(this.#reporter);
|
|
117
122
|
clearTimeout(this.#reportTimer);
|
|
118
123
|
this.#socket?.close();
|
|
@@ -121,6 +126,7 @@ export class MirrorRuntime {
|
|
|
121
126
|
await this.#stored?.stop().catch(() => {});
|
|
122
127
|
this.#engine = null;
|
|
123
128
|
this.#stored = null;
|
|
129
|
+
await this.#transport.dispose();
|
|
124
130
|
}
|
|
125
131
|
|
|
126
132
|
status() {
|
|
@@ -133,7 +139,7 @@ export class MirrorRuntime {
|
|
|
133
139
|
|
|
134
140
|
async #fetchHubExclusions() {
|
|
135
141
|
try {
|
|
136
|
-
const res = await fetch(`${this.#hub.url}${this.#hub.apiBase}/workspaces/${encodeURIComponent(this.#mirror.workspaceName)}/backends/file/workspace%3Ahome`, {
|
|
142
|
+
const res = await this.#transport.fetch(`${this.#hub.url}${this.#hub.apiBase}/workspaces/${encodeURIComponent(this.#mirror.workspaceName)}/backends/file/workspace%3Ahome`, {
|
|
137
143
|
headers: { authorization: `Bearer ${this.#hub.token}` },
|
|
138
144
|
});
|
|
139
145
|
const json = await res.json();
|
|
@@ -147,7 +153,7 @@ export class MirrorRuntime {
|
|
|
147
153
|
async #resolveWorkspaceId() {
|
|
148
154
|
if (this.#mirror.workspaceId && /^[0-9a-f-]{36}$/i.test(this.#mirror.workspaceId)) return this.#mirror.workspaceId;
|
|
149
155
|
try {
|
|
150
|
-
const res = await fetch(`${this.#hub.url}${this.#hub.apiBase}/workspaces/${encodeURIComponent(this.#mirror.workspaceName)}`, { headers: { authorization: `Bearer ${this.#hub.token}` } });
|
|
156
|
+
const res = await this.#transport.fetch(`${this.#hub.url}${this.#hub.apiBase}/workspaces/${encodeURIComponent(this.#mirror.workspaceName)}`, { headers: { authorization: `Bearer ${this.#hub.token}` } });
|
|
151
157
|
const json = await res.json();
|
|
152
158
|
return json?.payload?.workspace?.id || json?.payload?.id || this.#mirror.workspaceId || this.#mirror.workspaceName;
|
|
153
159
|
} catch { return this.#mirror.workspaceId || this.#mirror.workspaceName; }
|
|
@@ -156,7 +162,7 @@ export class MirrorRuntime {
|
|
|
156
162
|
async #connectSocket() {
|
|
157
163
|
try {
|
|
158
164
|
const wsId = await this.#resolveWorkspaceId();
|
|
159
|
-
const socket = io(this.#hub.url, { auth: { token: this.#hub.token }, transports: ['websocket'], reconnection: true, reconnectionDelay: 1000, reconnectionDelayMax: 30000 });
|
|
165
|
+
const socket = io(this.#hub.url, { ...this.#transport.socketOptions, auth: { token: this.#hub.token }, transports: this.#transport.socketOptions.transports || ['websocket'], reconnection: true, reconnectionDelay: 1000, reconnectionDelayMax: 30000 });
|
|
160
166
|
this.#socket = socket;
|
|
161
167
|
socket.on('connect', () => { socket.emit('subscribe', { channel: `workspace:${wsId}` }); this.resync().catch(() => {}); });
|
|
162
168
|
socket.on('backend.changed', (e) => { if (!e?.backend || e.backend === 'workspace:home') this.nudge(); });
|
|
@@ -188,7 +194,7 @@ export class MirrorRuntime {
|
|
|
188
194
|
this.#pendingApplied = full ? [] : mergePairs(this.#pendingApplied, delta);
|
|
189
195
|
const applied = full ? (typeof engine.appliedSnapshot === 'function' ? engine.appliedSnapshot() : []) : this.#pendingApplied;
|
|
190
196
|
try {
|
|
191
|
-
const res = await fetch(`${this.#hub.url}${this.#hub.apiBase}/workspaces/${ws}/mirrors/${encodeURIComponent(this.#identity.deviceId)}/status`, {
|
|
197
|
+
const res = await this.#transport.fetch(`${this.#hub.url}${this.#hub.apiBase}/workspaces/${ws}/mirrors/${encodeURIComponent(this.#identity.deviceId)}/status`, {
|
|
192
198
|
method: 'POST',
|
|
193
199
|
headers: { authorization: `Bearer ${this.#hub.token}`, 'content-type': 'application/json' },
|
|
194
200
|
body: JSON.stringify({
|
package/src/remote-config.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
import { normalizeTls } from '@augmentd-labs/canvas-api-client/tls';
|
|
3
4
|
import fs from 'node:fs';
|
|
4
5
|
import path from 'node:path';
|
|
5
6
|
|
|
@@ -18,7 +19,8 @@ import path from 'node:path';
|
|
|
18
19
|
*/
|
|
19
20
|
|
|
20
21
|
export function workspaceConfigPath(dir) {
|
|
21
|
-
|
|
22
|
+
const home = path.join(dir, '.workspace', 'workspace.json');
|
|
23
|
+
return fs.existsSync(home) ? home : path.join(dir, 'workspace.json');
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
export function readWorkspaceConfig(dir) {
|
|
@@ -35,11 +37,12 @@ export function listRemotes(config = {}) {
|
|
|
35
37
|
url: remote.url.replace(/\/+$/, ''),
|
|
36
38
|
token: remote.token,
|
|
37
39
|
enabled: remote.enabled !== false,
|
|
40
|
+
...(remote.tls ? { tls: normalizeTls(remote.tls) } : {}),
|
|
38
41
|
}));
|
|
39
42
|
}
|
|
40
43
|
|
|
41
44
|
/** Add or update (matched by url) a remote entry, persisting workspace.json. */
|
|
42
|
-
export function saveRemote(dir, { url, token, enabled = true }) {
|
|
45
|
+
export function saveRemote(dir, { url, token, enabled = true, tls }) {
|
|
43
46
|
if (!url || !token) throw new Error('remote requires url and token');
|
|
44
47
|
const file = workspaceConfigPath(dir);
|
|
45
48
|
const config = readWorkspaceConfig(dir);
|
|
@@ -50,8 +53,9 @@ export function saveRemote(dir, { url, token, enabled = true }) {
|
|
|
50
53
|
existing.url = normalizedUrl;
|
|
51
54
|
existing.token = token;
|
|
52
55
|
existing.enabled = enabled;
|
|
56
|
+
if (tls !== undefined) existing.tls = normalizeTls(tls);
|
|
53
57
|
} else {
|
|
54
|
-
remotes.push({ url: normalizedUrl, token, enabled });
|
|
58
|
+
remotes.push({ url: normalizedUrl, token, enabled, ...(tls ? { tls: normalizeTls(tls) } : {}) });
|
|
55
59
|
}
|
|
56
60
|
config.remotes = remotes;
|
|
57
61
|
fs.writeFileSync(file, JSON.stringify(config, null, 2) + '\n');
|