@extension-use/relay 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +16 -2
- package/dist/chunk-SW45TV4N.js +685 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +164 -0
- package/dist/index.d.ts +232 -0
- package/dist/index.js +20 -0
- package/package.json +51 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ahmed Gamal and Extension-use contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @extension-use/relay
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Lets scripts, servers and AI agents drive a browser that runs an Extension-use extension. The extension dials out to the relay, so nothing listens on your computer except the relay itself (on 127.0.0.1 by default).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npx @extension-use/relay
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Then pair the browser from the extension's control panel, and call it:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
curl -H "Authorization: Bearer <token>" -d '{"action":"page.info"}' http://127.0.0.1:7777/v1/devices/default/calls
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
See the remote control guide in the Extension-use docs for pairing, tokens, the HTTP/SSE/WebSocket API and self-hosting.
|
|
16
|
+
|
|
17
|
+
License: MIT
|
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
// src/store.ts
|
|
2
|
+
import { createHash, randomBytes } from "crypto";
|
|
3
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
|
|
4
|
+
import { dirname } from "path";
|
|
5
|
+
var hashToken = (token) => createHash("sha256").update(token).digest("hex");
|
|
6
|
+
var newToken = (prefix) => `${prefix}_${randomBytes(24).toString("base64url")}`;
|
|
7
|
+
var newId = (prefix) => `${prefix}_${randomBytes(6).toString("hex")}`;
|
|
8
|
+
var Store = class {
|
|
9
|
+
constructor(file) {
|
|
10
|
+
this.file = file;
|
|
11
|
+
this.data = this.load();
|
|
12
|
+
}
|
|
13
|
+
file;
|
|
14
|
+
data;
|
|
15
|
+
load() {
|
|
16
|
+
if (this.file) {
|
|
17
|
+
try {
|
|
18
|
+
const parsed = JSON.parse(readFileSync(this.file, "utf8"));
|
|
19
|
+
if (parsed.version === 1) return parsed;
|
|
20
|
+
} catch {
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const fresh = { version: 1, ownerToken: newToken("eu_own"), tokens: [], devices: [] };
|
|
24
|
+
this.data = fresh;
|
|
25
|
+
this.save();
|
|
26
|
+
return fresh;
|
|
27
|
+
}
|
|
28
|
+
save() {
|
|
29
|
+
if (!this.file) return;
|
|
30
|
+
mkdirSync(dirname(this.file), { recursive: true });
|
|
31
|
+
const tmp = `${this.file}.tmp`;
|
|
32
|
+
writeFileSync(tmp, JSON.stringify(this.data, null, 2), { mode: 384 });
|
|
33
|
+
renameSync(tmp, this.file);
|
|
34
|
+
}
|
|
35
|
+
get ownerToken() {
|
|
36
|
+
return this.data.ownerToken;
|
|
37
|
+
}
|
|
38
|
+
/** Resolve a controller token: the owner token has every grant. */
|
|
39
|
+
controllerFor(token) {
|
|
40
|
+
if (token === this.data.ownerToken) return { name: "owner", grants: ["*"], owner: true };
|
|
41
|
+
const hash = hashToken(token);
|
|
42
|
+
const t = this.data.tokens.find((x) => x.hash === hash);
|
|
43
|
+
return t ? { name: t.name, grants: t.grants, owner: false } : void 0;
|
|
44
|
+
}
|
|
45
|
+
createToken(name, grants) {
|
|
46
|
+
if (!/^[\w.-]{1,64}$/.test(name)) throw new Error("Token names use letters, digits, '.', '_' and '-' (max 64)");
|
|
47
|
+
if (name === "owner" || this.data.tokens.some((t) => t.name === name)) throw new Error(`A token named "${name}" already exists`);
|
|
48
|
+
const token = newToken("eu_ctl");
|
|
49
|
+
this.data.tokens.push({ name, hash: hashToken(token), grants: grants.length ? grants : ["*"], createdAt: Date.now() });
|
|
50
|
+
this.save();
|
|
51
|
+
return token;
|
|
52
|
+
}
|
|
53
|
+
listTokens() {
|
|
54
|
+
return this.data.tokens.map(({ name, grants, createdAt }) => ({ name, grants, createdAt }));
|
|
55
|
+
}
|
|
56
|
+
revokeToken(name) {
|
|
57
|
+
const before = this.data.tokens.length;
|
|
58
|
+
this.data.tokens = this.data.tokens.filter((t) => t.name !== name);
|
|
59
|
+
this.save();
|
|
60
|
+
return this.data.tokens.length < before;
|
|
61
|
+
}
|
|
62
|
+
addDevice(name) {
|
|
63
|
+
const token = newToken("eu_dev");
|
|
64
|
+
const device = { id: newId("dev"), name, hash: hashToken(token), createdAt: Date.now() };
|
|
65
|
+
this.data.devices.push(device);
|
|
66
|
+
this.save();
|
|
67
|
+
return { device, token };
|
|
68
|
+
}
|
|
69
|
+
deviceForToken(token) {
|
|
70
|
+
const hash = hashToken(token);
|
|
71
|
+
return this.data.devices.find((d) => d.hash === hash);
|
|
72
|
+
}
|
|
73
|
+
listDevices() {
|
|
74
|
+
return this.data.devices.map(({ id, name, createdAt, lastSeen }) => ({ id, name, createdAt, ...lastSeen ? { lastSeen } : {} }));
|
|
75
|
+
}
|
|
76
|
+
touchDevice(id) {
|
|
77
|
+
const d = this.data.devices.find((x) => x.id === id);
|
|
78
|
+
if (d) {
|
|
79
|
+
d.lastSeen = Date.now();
|
|
80
|
+
this.save();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
removeDevice(id) {
|
|
84
|
+
const before = this.data.devices.length;
|
|
85
|
+
this.data.devices = this.data.devices.filter((d) => d.id !== id);
|
|
86
|
+
this.save();
|
|
87
|
+
return this.data.devices.length < before;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// src/backend.ts
|
|
92
|
+
var LOCAL_TENANT = "local";
|
|
93
|
+
var LocalBackend = class {
|
|
94
|
+
store;
|
|
95
|
+
constructor(dataFile) {
|
|
96
|
+
this.store = new Store(dataFile);
|
|
97
|
+
}
|
|
98
|
+
get ownerToken() {
|
|
99
|
+
return this.store.ownerToken;
|
|
100
|
+
}
|
|
101
|
+
async authenticateController(token) {
|
|
102
|
+
const c = this.store.controllerFor(token);
|
|
103
|
+
return c ? { tenant: LOCAL_TENANT, ...c } : void 0;
|
|
104
|
+
}
|
|
105
|
+
async authenticateDevice(token) {
|
|
106
|
+
const d = this.store.deviceForToken(token);
|
|
107
|
+
return d ? { tenant: LOCAL_TENANT, id: d.id, name: d.name, createdAt: d.createdAt, ...d.lastSeen ? { lastSeen: d.lastSeen } : {} } : void 0;
|
|
108
|
+
}
|
|
109
|
+
async createDevice(_tenant, name) {
|
|
110
|
+
const { device, token } = this.store.addDevice(name);
|
|
111
|
+
return { device: { tenant: LOCAL_TENANT, id: device.id, name: device.name, createdAt: device.createdAt }, token };
|
|
112
|
+
}
|
|
113
|
+
async listDevices() {
|
|
114
|
+
return this.store.listDevices().map((d) => ({ tenant: LOCAL_TENANT, ...d }));
|
|
115
|
+
}
|
|
116
|
+
async removeDevice(_tenant, id) {
|
|
117
|
+
return this.store.removeDevice(id);
|
|
118
|
+
}
|
|
119
|
+
async touchDevice(_tenant, id) {
|
|
120
|
+
this.store.touchDevice(id);
|
|
121
|
+
}
|
|
122
|
+
async createToken(_tenant, name, grants) {
|
|
123
|
+
return this.store.createToken(name, grants);
|
|
124
|
+
}
|
|
125
|
+
async listTokens() {
|
|
126
|
+
return this.store.listTokens();
|
|
127
|
+
}
|
|
128
|
+
async revokeToken(_tenant, name) {
|
|
129
|
+
return this.store.revokeToken(name);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
// src/server.ts
|
|
134
|
+
import { createServer } from "http";
|
|
135
|
+
import { randomInt } from "crypto";
|
|
136
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
137
|
+
import { connect } from "@extension-use/client";
|
|
138
|
+
import { ExtensionUseError, envelope, isEnvelope, matchAny, randomId } from "@extension-use/protocol";
|
|
139
|
+
import { REMOTE_PING_MS, isDeviceFrame } from "@extension-use/protocol/remote";
|
|
140
|
+
var RELAY_VERSION = "0.1.0";
|
|
141
|
+
var DeviceLink = class {
|
|
142
|
+
constructor(tenant, id, name, ws) {
|
|
143
|
+
this.tenant = tenant;
|
|
144
|
+
this.id = id;
|
|
145
|
+
this.name = name;
|
|
146
|
+
this.ws = ws;
|
|
147
|
+
}
|
|
148
|
+
tenant;
|
|
149
|
+
id;
|
|
150
|
+
name;
|
|
151
|
+
ws;
|
|
152
|
+
sessions = /* @__PURE__ */ new Map();
|
|
153
|
+
connectedAt = Date.now();
|
|
154
|
+
send(frame) {
|
|
155
|
+
if (this.ws.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(frame));
|
|
156
|
+
}
|
|
157
|
+
open(origin, label, sink) {
|
|
158
|
+
const s = randomId();
|
|
159
|
+
this.sessions.set(s, sink);
|
|
160
|
+
this.send({ t: "open", s, origin, label });
|
|
161
|
+
return s;
|
|
162
|
+
}
|
|
163
|
+
close(s) {
|
|
164
|
+
if (this.sessions.delete(s)) this.send({ t: "close", s });
|
|
165
|
+
}
|
|
166
|
+
endAll(reason) {
|
|
167
|
+
for (const sink of this.sessions.values()) sink.ended(reason);
|
|
168
|
+
this.sessions.clear();
|
|
169
|
+
}
|
|
170
|
+
terminate(code = 4e3, reason = "replaced") {
|
|
171
|
+
this.endAll(reason);
|
|
172
|
+
this.ws.close(code, reason);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
var STATUS_FOR = {
|
|
176
|
+
UNAUTHORIZED: 401,
|
|
177
|
+
NOT_GRANTED: 403,
|
|
178
|
+
BLOCKED_BY_POLICY: 403,
|
|
179
|
+
INVALID_INPUT: 400,
|
|
180
|
+
UNKNOWN_ACTION: 404,
|
|
181
|
+
TARGET_NOT_FOUND: 404,
|
|
182
|
+
ELEMENT_NOT_FOUND: 404,
|
|
183
|
+
DEVICE_OFFLINE: 503,
|
|
184
|
+
NOT_CONNECTED: 503,
|
|
185
|
+
TIMEOUT: 504,
|
|
186
|
+
QUOTA_EXCEEDED: 429,
|
|
187
|
+
PLAN_REQUIRED: 402,
|
|
188
|
+
NEEDS_USER_GESTURE: 409,
|
|
189
|
+
NEEDS_PERMISSION: 409
|
|
190
|
+
};
|
|
191
|
+
function createRelay(options = {}) {
|
|
192
|
+
const backend = options.backend ?? new LocalBackend(options.dataFile);
|
|
193
|
+
const log = options.log ?? (() => {
|
|
194
|
+
});
|
|
195
|
+
const devices = /* @__PURE__ */ new Map();
|
|
196
|
+
const pairings = /* @__PURE__ */ new Map();
|
|
197
|
+
const httpClients = /* @__PURE__ */ new Map();
|
|
198
|
+
const pairingTtl = options.pairingTtlMs ?? 5 * 6e4;
|
|
199
|
+
const codeDigits = Math.max(6, Math.min(12, options.pairingCodeDigits ?? 6));
|
|
200
|
+
const failedApprovals = /* @__PURE__ */ new Map();
|
|
201
|
+
const usage = (e) => {
|
|
202
|
+
try {
|
|
203
|
+
backend.recordUsage?.(e);
|
|
204
|
+
} catch {
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
async function resolveDevice(controller, id) {
|
|
208
|
+
if (id === "default") {
|
|
209
|
+
const online = [...devices.values()].filter((d2) => d2.tenant === controller.tenant).sort((a, b) => b.connectedAt - a.connectedAt);
|
|
210
|
+
if (online[0]) return online[0];
|
|
211
|
+
throw new ExtensionUseError("DEVICE_OFFLINE", "No paired browser is connected");
|
|
212
|
+
}
|
|
213
|
+
const d = devices.get(id);
|
|
214
|
+
if (d && d.tenant === controller.tenant) return d;
|
|
215
|
+
if (!(await backend.listDevices(controller.tenant)).some((x) => x.id === id)) throw new ExtensionUseError("TARGET_NOT_FOUND", `No paired device "${id}"`);
|
|
216
|
+
throw new ExtensionUseError("DEVICE_OFFLINE", `Device "${id}" is not connected`);
|
|
217
|
+
}
|
|
218
|
+
function controllerFilter(controller, device) {
|
|
219
|
+
const describeCalls = /* @__PURE__ */ new Set();
|
|
220
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
221
|
+
const allowed = (action) => controller.owner || matchAny(controller.grants, action);
|
|
222
|
+
const deny2 = (id, code, message, data) => envelope({ kind: "result", id, ok: false, error: { code, message, ...data !== void 0 ? { data } : {} } });
|
|
223
|
+
return {
|
|
224
|
+
/** A reply to send back instead of forwarding, or undefined to forward. */
|
|
225
|
+
async outgoing(env) {
|
|
226
|
+
if (env.kind !== "call") return void 0;
|
|
227
|
+
if (!allowed(env.action)) return deny2(env.id, "NOT_GRANTED", `Token "${controller.name}" may not call "${env.action}"`);
|
|
228
|
+
try {
|
|
229
|
+
await backend.checkCall?.(controller, env.action);
|
|
230
|
+
} catch (err) {
|
|
231
|
+
const e = ExtensionUseError.from(err);
|
|
232
|
+
return deny2(env.id, e.code, e.message, e.data);
|
|
233
|
+
}
|
|
234
|
+
if (env.action === "runtime.describe" && !controller.owner) describeCalls.add(env.id);
|
|
235
|
+
inFlight.set(env.id, { action: env.action, started: Date.now() });
|
|
236
|
+
return void 0;
|
|
237
|
+
},
|
|
238
|
+
incoming(env) {
|
|
239
|
+
if (env.kind === "result") {
|
|
240
|
+
const call = inFlight.get(env.id);
|
|
241
|
+
if (call) {
|
|
242
|
+
inFlight.delete(env.id);
|
|
243
|
+
usage({
|
|
244
|
+
kind: "call",
|
|
245
|
+
tenant: controller.tenant,
|
|
246
|
+
controller: controller.name,
|
|
247
|
+
device: device.id,
|
|
248
|
+
action: call.action,
|
|
249
|
+
ok: env.ok,
|
|
250
|
+
...env.ok ? {} : { code: env.error.code },
|
|
251
|
+
ms: Date.now() - call.started,
|
|
252
|
+
ts: Date.now()
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (controller.owner) return env;
|
|
257
|
+
if (env.kind === "welcome") return { ...env, capabilities: env.capabilities.filter((c) => allowed(c.action)) };
|
|
258
|
+
if (env.kind === "result" && describeCalls.delete(env.id) && env.ok) {
|
|
259
|
+
const out = env.output;
|
|
260
|
+
if (Array.isArray(out?.actions)) return { ...env, output: { ...out, actions: out.actions.filter((a) => allowed(a.name)) } };
|
|
261
|
+
}
|
|
262
|
+
return env;
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
function serial() {
|
|
267
|
+
let chain = Promise.resolve();
|
|
268
|
+
return (fn) => {
|
|
269
|
+
chain = chain.then(fn).catch(() => {
|
|
270
|
+
});
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function sessionTransport(device, controller, label) {
|
|
274
|
+
let s;
|
|
275
|
+
const filter = controllerFilter(controller, device);
|
|
276
|
+
const queue = serial();
|
|
277
|
+
return {
|
|
278
|
+
kind: "relay",
|
|
279
|
+
open(onMessage, onClose) {
|
|
280
|
+
s = device.open(`relay:${controller.name}`, label, {
|
|
281
|
+
deliver: (env) => onMessage(filter.incoming(env)),
|
|
282
|
+
ended: (reason) => onClose(reason)
|
|
283
|
+
});
|
|
284
|
+
},
|
|
285
|
+
send(env) {
|
|
286
|
+
queue(async () => {
|
|
287
|
+
const denied = await filter.outgoing(env);
|
|
288
|
+
if (denied) device.sessions.get(s)?.deliver(denied);
|
|
289
|
+
else device.send({ t: "msg", s, env });
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
close() {
|
|
293
|
+
if (s) device.close(s);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
async function httpClient(controller, device) {
|
|
298
|
+
const key = `${controller.tenant}:${controller.name}:${device.id}:${device.connectedAt}`;
|
|
299
|
+
let client = httpClients.get(key);
|
|
300
|
+
if (!client) {
|
|
301
|
+
client = connect(sessionTransport(device, controller, "http"), { name: `relay-http:${controller.name}`, handshakeTimeoutMs: 1e4 });
|
|
302
|
+
httpClients.set(key, client);
|
|
303
|
+
client.then(
|
|
304
|
+
(c) => c.onDisconnect(() => httpClients.delete(key)),
|
|
305
|
+
() => httpClients.delete(key)
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
return client;
|
|
309
|
+
}
|
|
310
|
+
function newCode() {
|
|
311
|
+
const raw = Array.from({ length: codeDigits }, () => randomInt(0, 10)).join("");
|
|
312
|
+
return raw.match(/.{1,3}/g).join("-");
|
|
313
|
+
}
|
|
314
|
+
function startPairing(name, remoteAddress) {
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
for (const [id, p] of pairings) {
|
|
317
|
+
if (p.result && p.expiresAt + 6e4 < now) pairings.delete(id);
|
|
318
|
+
else if (p.expiresAt < now && !p.result) pairings.set(id, { ...p, result: { status: "expired" } });
|
|
319
|
+
}
|
|
320
|
+
const pending = [...pairings.values()].filter((p) => !p.result);
|
|
321
|
+
const fromAddress = pending.filter((p) => p.remoteAddress === remoteAddress).length;
|
|
322
|
+
if (pending.length >= 1e3 || fromAddress >= 10) throw new ExtensionUseError("QUOTA_EXCEEDED", "Too many pairing requests; try again later");
|
|
323
|
+
const pairing = { pairingId: randomId(), code: newCode(), name: name.slice(0, 80) || "Browser", expiresAt: now + pairingTtl, remoteAddress };
|
|
324
|
+
pairings.set(pairing.pairingId, pairing);
|
|
325
|
+
log(`pairing request from "${pairing.name}": code ${pairing.code}`);
|
|
326
|
+
options.onPairingRequest?.({ ...pairing });
|
|
327
|
+
return { pairingId: pairing.pairingId, code: pairing.code, expiresAt: pairing.expiresAt };
|
|
328
|
+
}
|
|
329
|
+
function findPending(code, tenant) {
|
|
330
|
+
const now = Date.now();
|
|
331
|
+
const recent = (failedApprovals.get(tenant) ?? []).filter((t) => t > now - 10 * 6e4);
|
|
332
|
+
if (recent.length >= 10) throw new ExtensionUseError("QUOTA_EXCEEDED", "Too many wrong pairing codes; wait a few minutes");
|
|
333
|
+
const normalized = code.replace(/\D/g, "");
|
|
334
|
+
const p = [...pairings.values()].find((x) => !x.result && x.code.replace(/\D/g, "") === normalized);
|
|
335
|
+
if (!p) {
|
|
336
|
+
failedApprovals.set(tenant, [...recent, now]);
|
|
337
|
+
throw new ExtensionUseError("TARGET_NOT_FOUND", `No pending pairing with code ${code}`);
|
|
338
|
+
}
|
|
339
|
+
if (p.expiresAt < now) {
|
|
340
|
+
p.result = { status: "expired" };
|
|
341
|
+
throw new ExtensionUseError("TIMEOUT", `Pairing code ${code} expired`);
|
|
342
|
+
}
|
|
343
|
+
return p;
|
|
344
|
+
}
|
|
345
|
+
async function approve(code, opts = {}) {
|
|
346
|
+
const tenant = opts.tenant ?? "local";
|
|
347
|
+
const p = findPending(code, tenant);
|
|
348
|
+
await backend.checkNewDevice?.(tenant);
|
|
349
|
+
if (p.result) throw new ExtensionUseError("TARGET_NOT_FOUND", `No pending pairing with code ${code}`);
|
|
350
|
+
const { device, token } = await backend.createDevice(tenant, opts.name ?? p.name);
|
|
351
|
+
p.result = { status: "approved", deviceId: device.id, deviceToken: token, name: device.name };
|
|
352
|
+
log(`paired "${device.name}" as ${device.id} (${tenant})`);
|
|
353
|
+
return { deviceId: device.id, name: device.name };
|
|
354
|
+
}
|
|
355
|
+
function deny(code, tenant = "local") {
|
|
356
|
+
findPending(code, tenant).result = { status: "denied" };
|
|
357
|
+
}
|
|
358
|
+
function pairingStatus(id) {
|
|
359
|
+
const p = pairings.get(id);
|
|
360
|
+
if (!p) return { status: "expired" };
|
|
361
|
+
if (p.result) {
|
|
362
|
+
if (p.result.status === "approved") pairings.delete(id);
|
|
363
|
+
return p.result;
|
|
364
|
+
}
|
|
365
|
+
if (p.expiresAt < Date.now()) return { status: "expired" };
|
|
366
|
+
return { status: "pending" };
|
|
367
|
+
}
|
|
368
|
+
const sendJson = (res, status, body) => {
|
|
369
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
|
370
|
+
res.end(JSON.stringify(body));
|
|
371
|
+
};
|
|
372
|
+
const sendError = (res, err) => {
|
|
373
|
+
const e = ExtensionUseError.from(err);
|
|
374
|
+
sendJson(res, STATUS_FOR[e.code] ?? (e.code === "INTERNAL" ? 500 : 422), { ok: false, error: e.toPayload() });
|
|
375
|
+
};
|
|
376
|
+
const unauthorized = (res) => sendJson(res, 401, { ok: false, error: { code: "UNAUTHORIZED", message: "Missing or unknown token" } });
|
|
377
|
+
async function readJson(req) {
|
|
378
|
+
let size = 0;
|
|
379
|
+
const chunks = [];
|
|
380
|
+
for await (const chunk of req) {
|
|
381
|
+
size += chunk.length;
|
|
382
|
+
if (size > 1e6) throw new ExtensionUseError("INVALID_INPUT", "Body too large");
|
|
383
|
+
chunks.push(chunk);
|
|
384
|
+
}
|
|
385
|
+
if (!chunks.length) return {};
|
|
386
|
+
try {
|
|
387
|
+
const v = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
388
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) throw new Error();
|
|
389
|
+
return v;
|
|
390
|
+
} catch {
|
|
391
|
+
throw new ExtensionUseError("INVALID_INPUT", "Body must be a JSON object");
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
function bearer(req, url) {
|
|
395
|
+
const h = req.headers.authorization;
|
|
396
|
+
if (h?.startsWith("Bearer ")) return h.slice(7).trim();
|
|
397
|
+
if (url.pathname.endsWith("/events")) return url.searchParams.get("access_token") ?? void 0;
|
|
398
|
+
return void 0;
|
|
399
|
+
}
|
|
400
|
+
async function handle(req, res) {
|
|
401
|
+
const url = new URL(req.url ?? "/", "http://relay");
|
|
402
|
+
const path = url.pathname.replace(/\/+$/, "") || "/";
|
|
403
|
+
const method = req.method ?? "GET";
|
|
404
|
+
const parts = path.split("/").filter(Boolean);
|
|
405
|
+
try {
|
|
406
|
+
if (options.extraRoutes && !path.startsWith("/v1/") && await options.extraRoutes(req, res, url)) return;
|
|
407
|
+
res.setHeader("access-control-allow-origin", "*");
|
|
408
|
+
res.setHeader("access-control-allow-headers", "authorization, content-type");
|
|
409
|
+
res.setHeader("access-control-allow-methods", "GET, POST, DELETE, OPTIONS");
|
|
410
|
+
if (method === "OPTIONS") return void res.writeHead(204).end();
|
|
411
|
+
if (path === "/v1/health") return sendJson(res, 200, { ok: true, version: RELAY_VERSION, devicesOnline: devices.size });
|
|
412
|
+
if (path === "/v1/pairings" && method === "POST") {
|
|
413
|
+
const body = await readJson(req);
|
|
414
|
+
return sendJson(res, 200, startPairing(String(body.name ?? "Browser"), req.socket.remoteAddress ?? ""));
|
|
415
|
+
}
|
|
416
|
+
if (parts[0] === "v1" && parts[1] === "pairings" && parts.length === 3 && method === "GET" && parts[2] !== "pending") {
|
|
417
|
+
return sendJson(res, 200, pairingStatus(parts[2]));
|
|
418
|
+
}
|
|
419
|
+
const token = bearer(req, url);
|
|
420
|
+
const controller = token ? await backend.authenticateController(token) : void 0;
|
|
421
|
+
if (!controller) return unauthorized(res);
|
|
422
|
+
const ownerOnly = () => {
|
|
423
|
+
if (!controller.owner) throw new ExtensionUseError("NOT_GRANTED", "Only an owner token can do this");
|
|
424
|
+
};
|
|
425
|
+
if (path === "/v1/pairings/pending" && method === "GET") {
|
|
426
|
+
ownerOnly();
|
|
427
|
+
if (controller.tenant !== "local") return sendJson(res, 200, []);
|
|
428
|
+
return sendJson(res, 200, [...pairings.values()].filter((p) => !p.result && p.expiresAt > Date.now()).map(({ code, name, expiresAt }) => ({ code, name, expiresAt })));
|
|
429
|
+
}
|
|
430
|
+
if (path === "/v1/pairings/approve" && method === "POST") {
|
|
431
|
+
ownerOnly();
|
|
432
|
+
const body = await readJson(req);
|
|
433
|
+
return sendJson(res, 200, await approve(String(body.code ?? ""), { tenant: controller.tenant, ...typeof body.name === "string" ? { name: body.name } : {} }));
|
|
434
|
+
}
|
|
435
|
+
if (path === "/v1/pairings/deny" && method === "POST") {
|
|
436
|
+
ownerOnly();
|
|
437
|
+
deny(String((await readJson(req)).code ?? ""), controller.tenant);
|
|
438
|
+
return sendJson(res, 200, { ok: true });
|
|
439
|
+
}
|
|
440
|
+
if (path === "/v1/tokens" && method === "GET") {
|
|
441
|
+
ownerOnly();
|
|
442
|
+
return sendJson(res, 200, await backend.listTokens(controller.tenant));
|
|
443
|
+
}
|
|
444
|
+
if (path === "/v1/tokens" && method === "POST") {
|
|
445
|
+
ownerOnly();
|
|
446
|
+
const body = await readJson(req);
|
|
447
|
+
const grants = Array.isArray(body.grants) ? body.grants.map(String) : ["*"];
|
|
448
|
+
try {
|
|
449
|
+
return sendJson(res, 200, { name: body.name, grants, token: await backend.createToken(controller.tenant, String(body.name ?? ""), grants) });
|
|
450
|
+
} catch (e) {
|
|
451
|
+
if (e instanceof ExtensionUseError) throw e;
|
|
452
|
+
throw new ExtensionUseError("INVALID_INPUT", e.message);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (parts[1] === "tokens" && parts.length === 3 && method === "DELETE") {
|
|
456
|
+
ownerOnly();
|
|
457
|
+
return sendJson(res, await backend.revokeToken(controller.tenant, parts[2]) ? 200 : 404, { ok: true });
|
|
458
|
+
}
|
|
459
|
+
if (path === "/v1/devices" && method === "GET") {
|
|
460
|
+
const list = await backend.listDevices(controller.tenant);
|
|
461
|
+
return sendJson(res, 200, list.map(({ tenant: _t, ...d }) => ({ ...d, online: devices.get(d.id)?.tenant === controller.tenant })));
|
|
462
|
+
}
|
|
463
|
+
if (parts[1] === "devices" && parts.length === 3 && method === "DELETE") {
|
|
464
|
+
ownerOnly();
|
|
465
|
+
const removed = await backend.removeDevice(controller.tenant, parts[2]);
|
|
466
|
+
const link = devices.get(parts[2]);
|
|
467
|
+
if (removed && link?.tenant === controller.tenant) {
|
|
468
|
+
link.terminate(4001, "unpaired");
|
|
469
|
+
devices.delete(parts[2]);
|
|
470
|
+
}
|
|
471
|
+
return sendJson(res, removed ? 200 : 404, { ok: true });
|
|
472
|
+
}
|
|
473
|
+
if (parts[1] === "devices" && parts[3] === "calls" && method === "POST") {
|
|
474
|
+
const body = await readJson(req);
|
|
475
|
+
const action = String(body.action ?? "");
|
|
476
|
+
if (!controller.owner && !matchAny(controller.grants, action)) throw new ExtensionUseError("NOT_GRANTED", `Token "${controller.name}" may not call "${action}"`);
|
|
477
|
+
const device = await resolveDevice(controller, parts[2]);
|
|
478
|
+
const client = await httpClient(controller, device);
|
|
479
|
+
const output = await client.callRaw(action, body.input ?? {}, {
|
|
480
|
+
...body.target ? { target: body.target } : {},
|
|
481
|
+
...typeof body.timeoutMs === "number" ? { timeoutMs: body.timeoutMs } : {}
|
|
482
|
+
});
|
|
483
|
+
return sendJson(res, 200, { ok: true, output });
|
|
484
|
+
}
|
|
485
|
+
if (parts[1] === "devices" && parts[3] === "events" && method === "GET") {
|
|
486
|
+
const device = await resolveDevice(controller, parts[2]);
|
|
487
|
+
const patterns = (url.searchParams.get("events") ?? "*").split(",").filter(Boolean);
|
|
488
|
+
const client = await connect(sessionTransport(device, controller, "sse"), { name: `relay-sse:${controller.name}` });
|
|
489
|
+
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
|
|
490
|
+
res.write(`event: ready
|
|
491
|
+
data: ${JSON.stringify({ device: device.id })}
|
|
492
|
+
|
|
493
|
+
`);
|
|
494
|
+
for (const p of patterns) {
|
|
495
|
+
client.on(p, (payload, meta) => res.write(`event: ${meta.name}
|
|
496
|
+
data: ${JSON.stringify({ payload, ts: meta.ts, ...meta.tabId !== void 0 ? { tabId: meta.tabId } : {} })}
|
|
497
|
+
|
|
498
|
+
`));
|
|
499
|
+
}
|
|
500
|
+
const keepAlive = setInterval(() => res.write(": ping\n\n"), 15e3);
|
|
501
|
+
const end = () => {
|
|
502
|
+
clearInterval(keepAlive);
|
|
503
|
+
client.close();
|
|
504
|
+
};
|
|
505
|
+
client.onDisconnect(() => res.end());
|
|
506
|
+
req.on("close", end);
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
sendJson(res, 404, { ok: false, error: { code: "UNKNOWN_ACTION", message: `No route ${method} ${path}` } });
|
|
510
|
+
} catch (err) {
|
|
511
|
+
if (!res.headersSent) sendError(res, err);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: 32 * 1024 * 1024 });
|
|
515
|
+
function firstFrame(ws, timeoutMs = 5e3) {
|
|
516
|
+
return new Promise((resolve, reject) => {
|
|
517
|
+
const timer = setTimeout(() => reject(new Error("auth timeout")), timeoutMs);
|
|
518
|
+
ws.once("message", (data) => {
|
|
519
|
+
clearTimeout(timer);
|
|
520
|
+
try {
|
|
521
|
+
const frame = JSON.parse(data.toString());
|
|
522
|
+
if (isDeviceFrame(frame)) resolve(frame);
|
|
523
|
+
else reject(new Error("bad frame"));
|
|
524
|
+
} catch {
|
|
525
|
+
reject(new Error("bad frame"));
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
const fail = (ws, code, message) => {
|
|
531
|
+
ws.send(JSON.stringify({ t: "error", code, message }));
|
|
532
|
+
ws.close(4401, code);
|
|
533
|
+
};
|
|
534
|
+
async function acceptDevice(ws, remote) {
|
|
535
|
+
const frame = await firstFrame(ws).catch(() => void 0);
|
|
536
|
+
const record = frame?.t === "auth" ? await backend.authenticateDevice(frame.token) : void 0;
|
|
537
|
+
if (!record) return fail(ws, "UNAUTHORIZED", "Unknown device token: pair this browser again");
|
|
538
|
+
devices.get(record.id)?.terminate(4e3, "replaced by a new connection");
|
|
539
|
+
const link = new DeviceLink(record.tenant, record.id, record.name, ws);
|
|
540
|
+
devices.set(record.id, link);
|
|
541
|
+
void backend.touchDevice(record.tenant, record.id);
|
|
542
|
+
usage({ kind: "device.connected", tenant: record.tenant, device: record.id, ts: Date.now() });
|
|
543
|
+
log(`device online: ${record.name} (${record.id}) from ${remote}`);
|
|
544
|
+
link.send({ t: "ready", deviceId: record.id, name: record.name });
|
|
545
|
+
ws.on("message", (data) => {
|
|
546
|
+
let f;
|
|
547
|
+
try {
|
|
548
|
+
f = JSON.parse(data.toString());
|
|
549
|
+
} catch {
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
if (!isDeviceFrame(f)) return;
|
|
553
|
+
if (f.t === "ping") link.send({ t: "pong" });
|
|
554
|
+
else if (f.t === "msg" && isEnvelope(f.env)) link.sessions.get(f.s)?.deliver(f.env);
|
|
555
|
+
else if (f.t === "closed") {
|
|
556
|
+
const sink = link.sessions.get(f.s);
|
|
557
|
+
link.sessions.delete(f.s);
|
|
558
|
+
sink?.ended(f.reason ?? "closed by the extension");
|
|
559
|
+
}
|
|
560
|
+
});
|
|
561
|
+
ws.on("close", () => {
|
|
562
|
+
if (devices.get(record.id) === link) devices.delete(record.id);
|
|
563
|
+
link.endAll("The browser disconnected");
|
|
564
|
+
void backend.touchDevice(record.tenant, record.id);
|
|
565
|
+
usage({ kind: "device.disconnected", tenant: record.tenant, device: record.id, ts: Date.now() });
|
|
566
|
+
log(`device offline: ${record.name} (${record.id})`);
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
async function acceptController(ws, deviceId) {
|
|
570
|
+
const frame = await firstFrame(ws).catch(() => void 0);
|
|
571
|
+
const controller = frame?.t === "auth" ? await backend.authenticateController(frame.token) : void 0;
|
|
572
|
+
if (!controller) return fail(ws, "UNAUTHORIZED", "Missing or unknown token");
|
|
573
|
+
let device;
|
|
574
|
+
try {
|
|
575
|
+
device = await resolveDevice(controller, deviceId);
|
|
576
|
+
} catch (err) {
|
|
577
|
+
const e = ExtensionUseError.from(err);
|
|
578
|
+
return fail(ws, e.code, e.message);
|
|
579
|
+
}
|
|
580
|
+
const filter = controllerFilter(controller, device);
|
|
581
|
+
const queue = serial();
|
|
582
|
+
const s = device.open(`relay:${controller.name}`, "websocket", {
|
|
583
|
+
deliver: (env) => ws.readyState === WebSocket.OPEN && ws.send(JSON.stringify(filter.incoming(env))),
|
|
584
|
+
ended: (reason) => {
|
|
585
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
586
|
+
ws.send(JSON.stringify({ t: "error", code: "DEVICE_OFFLINE", message: reason }));
|
|
587
|
+
ws.close(4503, "device gone");
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
ws.send(JSON.stringify({ t: "ready", deviceId: device.id, name: device.name }));
|
|
592
|
+
ws.on("message", (data) => {
|
|
593
|
+
let env;
|
|
594
|
+
try {
|
|
595
|
+
env = JSON.parse(data.toString());
|
|
596
|
+
} catch {
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
if (!isEnvelope(env)) return;
|
|
600
|
+
const message = env;
|
|
601
|
+
queue(async () => {
|
|
602
|
+
const denied = await filter.outgoing(message);
|
|
603
|
+
if (denied) ws.send(JSON.stringify(denied));
|
|
604
|
+
else device.send({ t: "msg", s, env: message });
|
|
605
|
+
});
|
|
606
|
+
});
|
|
607
|
+
ws.on("close", () => device.close(s));
|
|
608
|
+
}
|
|
609
|
+
const heartbeat = setInterval(() => {
|
|
610
|
+
for (const ws of wss.clients) {
|
|
611
|
+
const w = ws;
|
|
612
|
+
if (w.alive === false) w.terminate();
|
|
613
|
+
else {
|
|
614
|
+
w.alive = false;
|
|
615
|
+
w.ping();
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}, REMOTE_PING_MS * 2);
|
|
619
|
+
heartbeat.unref();
|
|
620
|
+
const server = createServer((req, res) => void handle(req, res));
|
|
621
|
+
server.on("upgrade", (req, socket, head) => {
|
|
622
|
+
const path = new URL(req.url ?? "/", "http://relay").pathname;
|
|
623
|
+
const deviceMatch = /^\/v1\/devices\/([\w-]+)\/session$/.exec(path);
|
|
624
|
+
if (path !== "/v1/device" && !deviceMatch) {
|
|
625
|
+
socket.destroy();
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
629
|
+
ws.alive = true;
|
|
630
|
+
ws.on("pong", () => ws.alive = true);
|
|
631
|
+
if (deviceMatch) void acceptController(ws, deviceMatch[1]);
|
|
632
|
+
else void acceptDevice(ws, req.socket.remoteAddress ?? "");
|
|
633
|
+
});
|
|
634
|
+
});
|
|
635
|
+
const local = backend instanceof LocalBackend ? backend : void 0;
|
|
636
|
+
return {
|
|
637
|
+
backend,
|
|
638
|
+
/** The LocalBackend store (undefined with a custom backend). */
|
|
639
|
+
store: local?.store,
|
|
640
|
+
/** The local owner token (undefined with a custom backend). */
|
|
641
|
+
get ownerToken() {
|
|
642
|
+
if (!local) throw new Error("ownerToken is only available with the local backend");
|
|
643
|
+
return local.ownerToken;
|
|
644
|
+
},
|
|
645
|
+
devicesOnline: (tenant) => [...devices.values()].filter((d) => !tenant || d.tenant === tenant).map((d) => ({ id: d.id, name: d.name, tenant: d.tenant, sessions: d.sessions.size })),
|
|
646
|
+
pendingPairings: () => [...pairings.values()].filter((p) => !p.result && p.expiresAt > Date.now()).map(({ code, name, expiresAt, pairingId, remoteAddress }) => ({ code, name, expiresAt, pairingId, remoteAddress })),
|
|
647
|
+
approve,
|
|
648
|
+
deny,
|
|
649
|
+
/** Disconnect a tenant's live devices (e.g. after unpairing from a dashboard). */
|
|
650
|
+
disconnectDevice(tenant, id) {
|
|
651
|
+
const link = devices.get(id);
|
|
652
|
+
if (link?.tenant === tenant) {
|
|
653
|
+
link.terminate(4001, "unpaired");
|
|
654
|
+
devices.delete(id);
|
|
655
|
+
}
|
|
656
|
+
},
|
|
657
|
+
listen() {
|
|
658
|
+
return new Promise((resolve, reject) => {
|
|
659
|
+
server.once("error", reject);
|
|
660
|
+
server.listen(options.port ?? 7777, options.host ?? "127.0.0.1", () => {
|
|
661
|
+
const addr = server.address();
|
|
662
|
+
const port = typeof addr === "object" && addr ? addr.port : options.port ?? 7777;
|
|
663
|
+
resolve({ url: `http://${options.host ?? "127.0.0.1"}:${port}`, port });
|
|
664
|
+
});
|
|
665
|
+
});
|
|
666
|
+
},
|
|
667
|
+
async close() {
|
|
668
|
+
clearInterval(heartbeat);
|
|
669
|
+
for (const d of devices.values()) d.terminate(1001, "relay shutting down");
|
|
670
|
+
for (const ws of wss.clients) ws.terminate();
|
|
671
|
+
await new Promise((r) => server.close(() => r()));
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
export {
|
|
677
|
+
hashToken,
|
|
678
|
+
newToken,
|
|
679
|
+
newId,
|
|
680
|
+
Store,
|
|
681
|
+
LOCAL_TENANT,
|
|
682
|
+
LocalBackend,
|
|
683
|
+
RELAY_VERSION,
|
|
684
|
+
createRelay
|
|
685
|
+
};
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
RELAY_VERSION,
|
|
4
|
+
Store,
|
|
5
|
+
createRelay
|
|
6
|
+
} from "./chunk-SW45TV4N.js";
|
|
7
|
+
|
|
8
|
+
// src/cli.ts
|
|
9
|
+
import { homedir } from "os";
|
|
10
|
+
import { join } from "path";
|
|
11
|
+
import { createInterface } from "readline/promises";
|
|
12
|
+
var argv = process.argv.slice(2);
|
|
13
|
+
var flag = (name) => {
|
|
14
|
+
const i = argv.indexOf(`--${name}`);
|
|
15
|
+
return i >= 0 ? argv[i + 1] : void 0;
|
|
16
|
+
};
|
|
17
|
+
var positional = argv.filter((a, i) => !a.startsWith("--") && !(i > 0 && argv[i - 1].startsWith("--") && !["--no-prompt"].includes(argv[i - 1])));
|
|
18
|
+
var wantsHelp = argv.includes("--help") || argv.includes("-h");
|
|
19
|
+
var [command = wantsHelp ? "help" : "serve", sub, arg] = positional;
|
|
20
|
+
var port = Number(flag("port") ?? process.env.EXTENSION_USE_RELAY_PORT ?? 7777);
|
|
21
|
+
var host = flag("host") ?? "127.0.0.1";
|
|
22
|
+
var dataFile = flag("data") ?? process.env.EXTENSION_USE_RELAY_DATA ?? join(homedir(), ".extension-use", "relay.json");
|
|
23
|
+
var base = `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${port}`;
|
|
24
|
+
async function running() {
|
|
25
|
+
try {
|
|
26
|
+
const r = await fetch(`${base}/v1/health`, { signal: AbortSignal.timeout(800) });
|
|
27
|
+
return r.ok;
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function api(method, path, body) {
|
|
33
|
+
const owner = new Store(dataFile).ownerToken;
|
|
34
|
+
const r = await fetch(`${base}${path}`, {
|
|
35
|
+
method,
|
|
36
|
+
headers: { authorization: `Bearer ${owner}`, "content-type": "application/json" },
|
|
37
|
+
...body ? { body: JSON.stringify(body) } : {}
|
|
38
|
+
});
|
|
39
|
+
const json = await r.json();
|
|
40
|
+
if (!r.ok) throw new Error(json.error?.message ?? `HTTP ${r.status}`);
|
|
41
|
+
return json;
|
|
42
|
+
}
|
|
43
|
+
function table(rows) {
|
|
44
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
45
|
+
if (!list.length) return console.log("(none)");
|
|
46
|
+
console.table(list.map((r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, typeof v === "number" && /At$|^lastSeen$/.test(k) ? new Date(v).toLocaleString() : v]))));
|
|
47
|
+
}
|
|
48
|
+
function die(message) {
|
|
49
|
+
console.error(`\u2716 ${message}`);
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
async function serve() {
|
|
53
|
+
const interactive = process.stdin.isTTY && !argv.includes("--no-prompt");
|
|
54
|
+
const rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : void 0;
|
|
55
|
+
let asking = Promise.resolve();
|
|
56
|
+
const relay = createRelay({
|
|
57
|
+
port,
|
|
58
|
+
host,
|
|
59
|
+
dataFile,
|
|
60
|
+
log: (line) => console.log(`\xB7 ${line}`),
|
|
61
|
+
onPairingRequest(p) {
|
|
62
|
+
if (!rl) {
|
|
63
|
+
console.log(` approve with: npx @extension-use/relay approve ${p.code}`);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
asking = asking.then(async () => {
|
|
67
|
+
const answer = (await rl.question(` "${p.name}" wants to pair. Does the extension show code ${p.code}? Approve? [y/N] `)).trim().toLowerCase();
|
|
68
|
+
try {
|
|
69
|
+
if (answer === "y" || answer === "yes") {
|
|
70
|
+
const { deviceId } = await relay.approve(p.code);
|
|
71
|
+
console.log(` \u2714 paired as ${deviceId}`);
|
|
72
|
+
} else {
|
|
73
|
+
relay.deny(p.code);
|
|
74
|
+
console.log(" \u2716 denied");
|
|
75
|
+
}
|
|
76
|
+
} catch (e) {
|
|
77
|
+
console.log(` ${e.message}`);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
const { url } = await relay.listen().catch((e) => die(`Could not listen on ${host}:${port}: ${e.message}`));
|
|
83
|
+
console.log(`Extension-use relay ${RELAY_VERSION} on ${url}
|
|
84
|
+
data: ${dataFile}
|
|
85
|
+
owner token: ${relay.ownerToken}
|
|
86
|
+
(full access: keep it secret; create narrower tokens with "token create")
|
|
87
|
+
|
|
88
|
+
In your extension's control panel, choose "Connect to relay" and use ${url}.
|
|
89
|
+
Then call it, for example:
|
|
90
|
+
curl -H "Authorization: Bearer <token>" -H "content-type: application/json" \\
|
|
91
|
+
-d '{"action":"page.info"}' ${url}/v1/devices/default/calls
|
|
92
|
+
`);
|
|
93
|
+
if (host !== "127.0.0.1" && host !== "localhost") {
|
|
94
|
+
console.log("\u26A0 Listening beyond this machine. Put it behind HTTPS (a reverse proxy) before exposing it.\n");
|
|
95
|
+
}
|
|
96
|
+
const stop = async () => {
|
|
97
|
+
rl?.close();
|
|
98
|
+
await relay.close();
|
|
99
|
+
process.exit(0);
|
|
100
|
+
};
|
|
101
|
+
process.on("SIGINT", stop);
|
|
102
|
+
process.on("SIGTERM", stop);
|
|
103
|
+
}
|
|
104
|
+
async function main() {
|
|
105
|
+
switch (command) {
|
|
106
|
+
case "serve":
|
|
107
|
+
return serve();
|
|
108
|
+
case "owner-token":
|
|
109
|
+
return console.log(new Store(dataFile).ownerToken);
|
|
110
|
+
case "token": {
|
|
111
|
+
const live = await running();
|
|
112
|
+
if (sub === "create") {
|
|
113
|
+
if (!arg) die("Usage: token create <name> [--grants a,b]");
|
|
114
|
+
const grants = (flag("grants") ?? "*").split(",").map((s) => s.trim()).filter(Boolean);
|
|
115
|
+
const token = live ? (await api("POST", "/v1/tokens", { name: arg, grants })).token : new Store(dataFile).createToken(arg, grants);
|
|
116
|
+
console.log(`Token "${arg}" (${grants.join(", ")}):
|
|
117
|
+
${token}
|
|
118
|
+
It is shown only once.`);
|
|
119
|
+
} else if (sub === "list") {
|
|
120
|
+
table(live ? await api("GET", "/v1/tokens") : new Store(dataFile).listTokens());
|
|
121
|
+
} else if (sub === "revoke") {
|
|
122
|
+
if (!arg) die("Usage: token revoke <name>");
|
|
123
|
+
if (live) await api("DELETE", `/v1/tokens/${encodeURIComponent(arg)}`);
|
|
124
|
+
else if (!new Store(dataFile).revokeToken(arg)) die(`No token "${arg}"`);
|
|
125
|
+
console.log(`Revoked "${arg}"`);
|
|
126
|
+
} else die("Usage: token create|list|revoke");
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
case "devices":
|
|
130
|
+
return table(await running() ? await api("GET", "/v1/devices") : new Store(dataFile).listDevices());
|
|
131
|
+
case "unpair": {
|
|
132
|
+
if (!sub) die("Usage: unpair <deviceId>");
|
|
133
|
+
if (await running()) await api("DELETE", `/v1/devices/${encodeURIComponent(sub)}`);
|
|
134
|
+
else if (!new Store(dataFile).removeDevice(sub)) die(`No device "${sub}"`);
|
|
135
|
+
return console.log(`Unpaired ${sub}`);
|
|
136
|
+
}
|
|
137
|
+
case "approve": {
|
|
138
|
+
if (!sub) die("Usage: approve <code>");
|
|
139
|
+
if (!await running()) die(`No relay running on ${base}`);
|
|
140
|
+
const r = await api("POST", "/v1/pairings/approve", { code: sub });
|
|
141
|
+
return console.log(`Paired as ${r.deviceId}`);
|
|
142
|
+
}
|
|
143
|
+
case "help":
|
|
144
|
+
case "--help":
|
|
145
|
+
return console.log(`Usage: extension-use-relay [command] [options]
|
|
146
|
+
|
|
147
|
+
Commands:
|
|
148
|
+
serve (default) Start the relay
|
|
149
|
+
token create <name> [--grants a,b] Create a controller token (shown once)
|
|
150
|
+
token list | token revoke <name> List or revoke tokens
|
|
151
|
+
devices | unpair <deviceId> List or remove paired browsers
|
|
152
|
+
approve <code> Approve a pairing request
|
|
153
|
+
owner-token Print the owner token
|
|
154
|
+
|
|
155
|
+
Options:
|
|
156
|
+
--port <n> Port (default 7777, or EXTENSION_USE_RELAY_PORT)
|
|
157
|
+
--host <host> Address to listen on (default 127.0.0.1)
|
|
158
|
+
--data <file> Data file (default ~/.extension-use/relay.json, or EXTENSION_USE_RELAY_DATA)
|
|
159
|
+
--no-prompt Don't ask to confirm pairing codes in the terminal`);
|
|
160
|
+
default:
|
|
161
|
+
die(`Unknown command "${command}". Try --help.`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
main().catch((e) => die(e.message));
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
|
|
3
|
+
interface TokenRecord {
|
|
4
|
+
name: string;
|
|
5
|
+
hash: string;
|
|
6
|
+
/** Action patterns this token may call, e.g. ["*"] or ["dom.snapshot", "tabs.*"]. */
|
|
7
|
+
grants: string[];
|
|
8
|
+
createdAt: number;
|
|
9
|
+
}
|
|
10
|
+
interface DeviceRecord {
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
hash: string;
|
|
14
|
+
createdAt: number;
|
|
15
|
+
lastSeen?: number;
|
|
16
|
+
}
|
|
17
|
+
declare const hashToken: (token: string) => string;
|
|
18
|
+
declare const newToken: (prefix: string) => string;
|
|
19
|
+
declare const newId: (prefix: string) => string;
|
|
20
|
+
/** A tiny JSON-file store (or in memory when `file` is undefined). Single process only. */
|
|
21
|
+
declare class Store {
|
|
22
|
+
private readonly file?;
|
|
23
|
+
private data;
|
|
24
|
+
constructor(file?: string | undefined);
|
|
25
|
+
private load;
|
|
26
|
+
private save;
|
|
27
|
+
get ownerToken(): string;
|
|
28
|
+
/** Resolve a controller token: the owner token has every grant. */
|
|
29
|
+
controllerFor(token: string): {
|
|
30
|
+
name: string;
|
|
31
|
+
grants: string[];
|
|
32
|
+
owner: boolean;
|
|
33
|
+
} | undefined;
|
|
34
|
+
createToken(name: string, grants: string[]): string;
|
|
35
|
+
listTokens(): {
|
|
36
|
+
name: string;
|
|
37
|
+
grants: string[];
|
|
38
|
+
createdAt: number;
|
|
39
|
+
}[];
|
|
40
|
+
revokeToken(name: string): boolean;
|
|
41
|
+
addDevice(name: string): {
|
|
42
|
+
device: DeviceRecord;
|
|
43
|
+
token: string;
|
|
44
|
+
};
|
|
45
|
+
deviceForToken(token: string): DeviceRecord | undefined;
|
|
46
|
+
listDevices(): {
|
|
47
|
+
lastSeen?: number | undefined;
|
|
48
|
+
id: string;
|
|
49
|
+
name: string;
|
|
50
|
+
createdAt: number;
|
|
51
|
+
}[];
|
|
52
|
+
touchDevice(id: string): void;
|
|
53
|
+
removeDevice(id: string): boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Where a relay keeps tokens and devices, and the hooks a hosted service uses
|
|
58
|
+
* for accounts, usage and plan limits. The open-source relay ships
|
|
59
|
+
* LocalBackend: one implicit tenant, a JSON file, no limits.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/** Everything belongs to a tenant (an organization in a hosted relay; "local" otherwise). */
|
|
63
|
+
interface Controller {
|
|
64
|
+
tenant: string;
|
|
65
|
+
/** Token name, shown to the extension as `relay:<name>`. */
|
|
66
|
+
name: string;
|
|
67
|
+
grants: string[];
|
|
68
|
+
/** Can manage tokens, devices and pairings for the tenant. */
|
|
69
|
+
owner: boolean;
|
|
70
|
+
}
|
|
71
|
+
interface DeviceInfo {
|
|
72
|
+
tenant: string;
|
|
73
|
+
id: string;
|
|
74
|
+
name: string;
|
|
75
|
+
createdAt: number;
|
|
76
|
+
lastSeen?: number;
|
|
77
|
+
}
|
|
78
|
+
type UsageEvent = {
|
|
79
|
+
kind: "call";
|
|
80
|
+
tenant: string;
|
|
81
|
+
controller: string;
|
|
82
|
+
device: string;
|
|
83
|
+
action: string;
|
|
84
|
+
ok: boolean;
|
|
85
|
+
code?: string;
|
|
86
|
+
ms: number;
|
|
87
|
+
ts: number;
|
|
88
|
+
} | {
|
|
89
|
+
kind: "device.connected" | "device.disconnected";
|
|
90
|
+
tenant: string;
|
|
91
|
+
device: string;
|
|
92
|
+
ts: number;
|
|
93
|
+
};
|
|
94
|
+
interface RelayBackend {
|
|
95
|
+
authenticateController(token: string): Promise<Controller | undefined>;
|
|
96
|
+
authenticateDevice(token: string): Promise<DeviceInfo | undefined>;
|
|
97
|
+
createDevice(tenant: string, name: string): Promise<{
|
|
98
|
+
device: DeviceInfo;
|
|
99
|
+
token: string;
|
|
100
|
+
}>;
|
|
101
|
+
listDevices(tenant: string): Promise<DeviceInfo[]>;
|
|
102
|
+
removeDevice(tenant: string, id: string): Promise<boolean>;
|
|
103
|
+
touchDevice(tenant: string, id: string): Promise<void>;
|
|
104
|
+
createToken(tenant: string, name: string, grants: string[]): Promise<string>;
|
|
105
|
+
listTokens(tenant: string): Promise<{
|
|
106
|
+
name: string;
|
|
107
|
+
grants: string[];
|
|
108
|
+
createdAt: number;
|
|
109
|
+
}[]>;
|
|
110
|
+
revokeToken(tenant: string, name: string): Promise<boolean>;
|
|
111
|
+
/**
|
|
112
|
+
* Called before each call is forwarded. Throw an ExtensionUseError
|
|
113
|
+
* (QUOTA_EXCEEDED, PLAN_REQUIRED, with an upgrade URL in `data`) to refuse it.
|
|
114
|
+
* Keep it fast: it runs on every call.
|
|
115
|
+
*/
|
|
116
|
+
checkCall?(controller: Controller, action: string): Promise<void> | void;
|
|
117
|
+
/** Called before a pairing is approved, e.g. to enforce a device limit. */
|
|
118
|
+
checkNewDevice?(tenant: string): Promise<void> | void;
|
|
119
|
+
/** Usage events, for metering. Must not throw or block. Never carries payloads or page content. */
|
|
120
|
+
recordUsage?(event: UsageEvent): void;
|
|
121
|
+
}
|
|
122
|
+
declare const LOCAL_TENANT = "local";
|
|
123
|
+
/** The default backend: a single tenant in a JSON file (or memory). */
|
|
124
|
+
declare class LocalBackend implements RelayBackend {
|
|
125
|
+
readonly store: Store;
|
|
126
|
+
constructor(dataFile?: string);
|
|
127
|
+
get ownerToken(): string;
|
|
128
|
+
authenticateController(token: string): Promise<{
|
|
129
|
+
name: string;
|
|
130
|
+
grants: string[];
|
|
131
|
+
owner: boolean;
|
|
132
|
+
tenant: string;
|
|
133
|
+
} | undefined>;
|
|
134
|
+
authenticateDevice(token: string): Promise<{
|
|
135
|
+
lastSeen?: number | undefined;
|
|
136
|
+
tenant: string;
|
|
137
|
+
id: string;
|
|
138
|
+
name: string;
|
|
139
|
+
createdAt: number;
|
|
140
|
+
} | undefined>;
|
|
141
|
+
createDevice(_tenant: string, name: string): Promise<{
|
|
142
|
+
device: {
|
|
143
|
+
tenant: string;
|
|
144
|
+
id: string;
|
|
145
|
+
name: string;
|
|
146
|
+
createdAt: number;
|
|
147
|
+
};
|
|
148
|
+
token: string;
|
|
149
|
+
}>;
|
|
150
|
+
listDevices(): Promise<{
|
|
151
|
+
lastSeen?: number | undefined;
|
|
152
|
+
id: string;
|
|
153
|
+
name: string;
|
|
154
|
+
createdAt: number;
|
|
155
|
+
tenant: string;
|
|
156
|
+
}[]>;
|
|
157
|
+
removeDevice(_tenant: string, id: string): Promise<boolean>;
|
|
158
|
+
touchDevice(_tenant: string, id: string): Promise<void>;
|
|
159
|
+
createToken(_tenant: string, name: string, grants: string[]): Promise<string>;
|
|
160
|
+
listTokens(): Promise<{
|
|
161
|
+
name: string;
|
|
162
|
+
grants: string[];
|
|
163
|
+
createdAt: number;
|
|
164
|
+
}[]>;
|
|
165
|
+
revokeToken(_tenant: string, name: string): Promise<boolean>;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
declare const RELAY_VERSION = "0.1.0";
|
|
169
|
+
interface RelayOptions {
|
|
170
|
+
port?: number;
|
|
171
|
+
/** Default 127.0.0.1: only this machine can reach the relay. */
|
|
172
|
+
host?: string;
|
|
173
|
+
/** JSON file for tokens and paired devices (LocalBackend). Omit to keep everything in memory. */
|
|
174
|
+
dataFile?: string;
|
|
175
|
+
/** Storage, accounts and limits. Default: LocalBackend (one tenant, no limits). */
|
|
176
|
+
backend?: RelayBackend;
|
|
177
|
+
/** Called when an extension asks to pair. Approve with relay.approve(code). */
|
|
178
|
+
onPairingRequest?(request: PendingPairing): void;
|
|
179
|
+
/** Log lines (connections, pairings). Default: none. */
|
|
180
|
+
log?(line: string): void;
|
|
181
|
+
/** How long a pairing code stays valid. Default 5 minutes. */
|
|
182
|
+
pairingTtlMs?: number;
|
|
183
|
+
/** Digits in pairing codes. 6 for a local relay; use 9 or more when many tenants share a relay. */
|
|
184
|
+
pairingCodeDigits?: number;
|
|
185
|
+
/** Extra HTTP routes (a hosted dashboard, webhooks). Return true if handled. */
|
|
186
|
+
extraRoutes?(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> | boolean;
|
|
187
|
+
}
|
|
188
|
+
interface PendingPairing {
|
|
189
|
+
pairingId: string;
|
|
190
|
+
code: string;
|
|
191
|
+
name: string;
|
|
192
|
+
expiresAt: number;
|
|
193
|
+
remoteAddress: string;
|
|
194
|
+
}
|
|
195
|
+
declare function createRelay(options?: RelayOptions): {
|
|
196
|
+
backend: RelayBackend;
|
|
197
|
+
/** The LocalBackend store (undefined with a custom backend). */
|
|
198
|
+
store: Store | undefined;
|
|
199
|
+
/** The local owner token (undefined with a custom backend). */
|
|
200
|
+
readonly ownerToken: string;
|
|
201
|
+
devicesOnline: (tenant?: string) => {
|
|
202
|
+
id: string;
|
|
203
|
+
name: string;
|
|
204
|
+
tenant: string;
|
|
205
|
+
sessions: number;
|
|
206
|
+
}[];
|
|
207
|
+
pendingPairings: () => {
|
|
208
|
+
code: string;
|
|
209
|
+
name: string;
|
|
210
|
+
expiresAt: number;
|
|
211
|
+
pairingId: string;
|
|
212
|
+
remoteAddress: string;
|
|
213
|
+
}[];
|
|
214
|
+
approve: (code: string, opts?: {
|
|
215
|
+
tenant?: string;
|
|
216
|
+
name?: string;
|
|
217
|
+
}) => Promise<{
|
|
218
|
+
deviceId: string;
|
|
219
|
+
name: string;
|
|
220
|
+
}>;
|
|
221
|
+
deny: (code: string, tenant?: string) => void;
|
|
222
|
+
/** Disconnect a tenant's live devices (e.g. after unpairing from a dashboard). */
|
|
223
|
+
disconnectDevice(tenant: string, id: string): void;
|
|
224
|
+
listen(): Promise<{
|
|
225
|
+
url: string;
|
|
226
|
+
port: number;
|
|
227
|
+
}>;
|
|
228
|
+
close(): Promise<void>;
|
|
229
|
+
};
|
|
230
|
+
type Relay = ReturnType<typeof createRelay>;
|
|
231
|
+
|
|
232
|
+
export { type Controller, type DeviceInfo, type DeviceRecord, LOCAL_TENANT, LocalBackend, type PendingPairing, RELAY_VERSION, type Relay, type RelayBackend, type RelayOptions, Store, type TokenRecord, type UsageEvent, createRelay, hashToken, newId, newToken };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LOCAL_TENANT,
|
|
3
|
+
LocalBackend,
|
|
4
|
+
RELAY_VERSION,
|
|
5
|
+
Store,
|
|
6
|
+
createRelay,
|
|
7
|
+
hashToken,
|
|
8
|
+
newId,
|
|
9
|
+
newToken
|
|
10
|
+
} from "./chunk-SW45TV4N.js";
|
|
11
|
+
export {
|
|
12
|
+
LOCAL_TENANT,
|
|
13
|
+
LocalBackend,
|
|
14
|
+
RELAY_VERSION,
|
|
15
|
+
Store,
|
|
16
|
+
createRelay,
|
|
17
|
+
hashToken,
|
|
18
|
+
newId,
|
|
19
|
+
newToken
|
|
20
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extension-use/relay",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Relay that lets scripts, servers and agents drive a paired Extension-use extension. Run locally with npx, or self-host.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Ahmed Gamal",
|
|
7
|
+
"homepage": "https://extension-use.appzlr.com",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/ahmedGamalhamed/extension-use.git",
|
|
11
|
+
"directory": "packages/relay"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/ahmedGamalhamed/extension-use/issues"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"bin": {
|
|
18
|
+
"extension-use-relay": "./dist/cli.js"
|
|
19
|
+
},
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"source": "./src/index.ts",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./package.json": "./package.json"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist"
|
|
30
|
+
],
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=22"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"ws": "^8.18.3",
|
|
36
|
+
"@extension-use/client": "0.2.0",
|
|
37
|
+
"@extension-use/protocol": "0.2.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/ws": "^8.18.1",
|
|
41
|
+
"@extension-use/host": "0.2.0"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"browser-extension",
|
|
45
|
+
"chrome-extension",
|
|
46
|
+
"automation",
|
|
47
|
+
"relay",
|
|
48
|
+
"websocket",
|
|
49
|
+
"extension-use"
|
|
50
|
+
],
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsup src/index.ts src/cli.ts --format esm --dts --clean"
|
|
53
|
+
}
|
|
6
54
|
}
|