@velmlabs/unstuck-core 0.1.7 → 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/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as CdpClient, P as PopupSource, L as LinkInfo, T as Transport } from './takeover
|
|
2
|
-
export { V as ViewerConnection } from './takeover
|
|
1
|
+
import { C as CdpClient, P as PopupSource, L as LinkInfo, T as TakeoverControl, a as Transport } from './takeover--acOYavq.js';
|
|
2
|
+
export { V as ViewerConnection } from './takeover--acOYavq.js';
|
|
3
3
|
import { TakeoverResult, Frame, ViewerInput, SessionStatus } from '@velmlabs/unstuck-protocol';
|
|
4
4
|
|
|
5
5
|
type UnstuckEventType = 'created' | 'published' | 'link' | 'viewer_joined' | 'viewer_left' | 'viewer_rejected' | 'status' | 'finished' | 'navigation_blocked';
|
|
@@ -18,7 +18,8 @@ declare class MemoryEventLog implements EventLog {
|
|
|
18
18
|
append(e: UnstuckEvent): void;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
/** Gets each takeover's link; `takeover.fail(detail)` ends that takeover as failed (e.g. when the link can't be delivered). */
|
|
22
|
+
type LinkHandler = (info: LinkInfo, takeover: TakeoverControl) => void;
|
|
22
23
|
interface EngineOptions {
|
|
23
24
|
transport: Transport;
|
|
24
25
|
log?: EventLog;
|
|
@@ -44,7 +45,7 @@ interface TakeoverCallOptions {
|
|
|
44
45
|
interface Engine {
|
|
45
46
|
/** Never rejects: every failure becomes a TakeoverResult. */
|
|
46
47
|
takeover(cdp: CdpClient, opts: TakeoverCallOptions): Promise<TakeoverResult>;
|
|
47
|
-
/** Cancels in-flight takeovers (detail `engine_closed`) and closes the transport. */
|
|
48
|
+
/** Cancels in-flight takeovers (detail `engine_closed`) and closes the transport; later takeovers end the same way. */
|
|
48
49
|
close(): Promise<void>;
|
|
49
50
|
}
|
|
50
51
|
declare const DEFAULT_TIMEOUT_S = 600;
|
|
@@ -55,7 +56,11 @@ interface ScreencastOptions {
|
|
|
55
56
|
maxWidth?: number;
|
|
56
57
|
maxHeight?: number;
|
|
57
58
|
}
|
|
58
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* Starts a JPEG screencast. Frames carry page CSS-pixel dimensions. Returns a stop function.
|
|
61
|
+
* Chrome only sends a screencast frame when the page repaints, so one screenshot goes out first through `onFrame`,
|
|
62
|
+
* unless a screencast frame beats it: a static page is shown at once.
|
|
63
|
+
*/
|
|
59
64
|
declare function startScreencast(cdp: CdpClient, onFrame: (f: Frame) => void, opts?: ScreencastOptions): Promise<() => Promise<void>>;
|
|
60
65
|
|
|
61
66
|
/** Fallback frame source for browsers without Page.startScreencast: periodic JPEG screenshots. */
|
|
@@ -157,5 +162,80 @@ declare function siteOf(host: string): string;
|
|
|
157
162
|
/** True for a bare public suffix ("com", "co.uk", "github.io"): never a site an agent may allow wholesale. */
|
|
158
163
|
declare function isPublicSuffix(host: string): boolean;
|
|
159
164
|
|
|
160
|
-
|
|
161
|
-
|
|
165
|
+
declare const CLOUD_RELAY_URL = "wss://relay.unstuck.sh";
|
|
166
|
+
/** Unstuck Cloud's viewer, on its own origin; each engine links to the build of its own version. */
|
|
167
|
+
declare const CLOUD_VIEWER_URL = "https://view.unstuck.sh/v";
|
|
168
|
+
type TransportChoice = {
|
|
169
|
+
kind: 'relay';
|
|
170
|
+
url: string;
|
|
171
|
+
agentKey?: string;
|
|
172
|
+
source: 'flag' | 'UNSTUCK_RELAY_URL' | 'UNSTUCK_API_KEY';
|
|
173
|
+
} | {
|
|
174
|
+
kind: 'embedded';
|
|
175
|
+
};
|
|
176
|
+
/** Relay spec §5.6: flags → UNSTUCK_RELAY_URL (+ UNSTUCK_AGENT_KEY) → UNSTUCK_API_KEY (Unstuck Cloud) → embedded. */
|
|
177
|
+
declare function selectTransport(flags: {
|
|
178
|
+
relay?: string;
|
|
179
|
+
agentKey?: string;
|
|
180
|
+
}, env: Record<string, string | undefined>): TransportChoice;
|
|
181
|
+
/**
|
|
182
|
+
* Where links open the viewer: UNSTUCK_VIEWER_URL (https, or http on this machine), else the hosted viewer pinned to this engine's
|
|
183
|
+
* version for the Unstuck Cloud relay, else undefined (the relay's own page, e.g. a self-hosted relay).
|
|
184
|
+
*/
|
|
185
|
+
declare function viewerUrlFor(choice: TransportChoice, env: Record<string, string | undefined>, version: string): string | undefined;
|
|
186
|
+
/** The relay transport for a chosen relay. Never logs the key; `warn` gets one line when Unstuck Cloud rejects the API key. */
|
|
187
|
+
declare function buildRelayTransport(choice: Extract<TransportChoice, {
|
|
188
|
+
kind: 'relay';
|
|
189
|
+
}>, o: {
|
|
190
|
+
env: Record<string, string | undefined>;
|
|
191
|
+
version: string;
|
|
192
|
+
warn: (line: string) => void;
|
|
193
|
+
}): Transport;
|
|
194
|
+
declare const CLOUD_API_URL = "https://unstuck.sh";
|
|
195
|
+
/** Where to send phone alerts: only for Unstuck Cloud via UNSTUCK_API_KEY, not for self-hosted relays or embedded mode. */
|
|
196
|
+
declare function cloudAlertsFor(choice: TransportChoice, env: Record<string, string | undefined>): {
|
|
197
|
+
apiBase: string;
|
|
198
|
+
apiKey: string;
|
|
199
|
+
} | null;
|
|
200
|
+
|
|
201
|
+
interface CloudAlerterOptions {
|
|
202
|
+
/** Unstuck Cloud's API origin, e.g. https://unstuck.sh. */
|
|
203
|
+
apiBase: string;
|
|
204
|
+
apiKey: string;
|
|
205
|
+
fetch?: typeof fetch;
|
|
206
|
+
/** One line per problem; never contains the link secret or the API key. */
|
|
207
|
+
log?: (line: string) => void;
|
|
208
|
+
now?: () => number;
|
|
209
|
+
}
|
|
210
|
+
/** Why no phone got the link: the key may not send alerts, no phone is paired, no phone's key could seal it, Cloud refused it. */
|
|
211
|
+
type AlertProblem = 'alerts_not_allowed' | 'no_devices' | 'seal_failed' | 'notify_failed' | 'unauthorized' | 'error';
|
|
212
|
+
/** How many paired phones Unstuck Cloud accepted the alert for, or why none. */
|
|
213
|
+
type AlertOutcome = {
|
|
214
|
+
delivered: number;
|
|
215
|
+
} | {
|
|
216
|
+
delivered: 0;
|
|
217
|
+
problem: AlertProblem;
|
|
218
|
+
};
|
|
219
|
+
type CloudAlerter = (info: LinkInfo, site: string | undefined) => Promise<AlertOutcome>;
|
|
220
|
+
/** The sealed payload's caps (code points): a long reason must not push the link past what push and Telegram carry. */
|
|
221
|
+
declare const MAX_REASON = 200;
|
|
222
|
+
declare const MAX_SITE = 253;
|
|
223
|
+
/**
|
|
224
|
+
* Seals each takeover link to the account's paired phones and asks Unstuck Cloud to deliver it (notifications spec §4.2).
|
|
225
|
+
* Cloud only ever sees ciphertext. Never rejects: an alert that can't be sent is one line on the log, and the outcome
|
|
226
|
+
* says why.
|
|
227
|
+
*/
|
|
228
|
+
declare function createCloudAlerter(o: CloudAlerterOptions): CloudAlerter;
|
|
229
|
+
/**
|
|
230
|
+
* A takeover's alert, from its link handler: none with `alerts: false`; with `'required'`, a link that reached no paired
|
|
231
|
+
* phone fails the takeover at once with `alert_failed` instead of letting it wait for its timeout, unless someone already
|
|
232
|
+
* joined through the link the handler passed on. An alerter that rejects counts as no phone reached.
|
|
233
|
+
* Returns the outcome (never rejects), or null when no alert is sent (no Unstuck Cloud alerter, or `alerts: false`).
|
|
234
|
+
*/
|
|
235
|
+
declare function sendTakeoverAlert(alerter: CloudAlerter | null | undefined, alerts: boolean | 'required' | undefined, info: LinkInfo, site: string | undefined, takeover: TakeoverControl): Promise<AlertOutcome> | null;
|
|
236
|
+
|
|
237
|
+
/** Keeps only plausible hostnames that aren't bare public suffixes (a leading "*." is accepted), at most 20. */
|
|
238
|
+
declare function hostnames(raw: unknown): string[];
|
|
239
|
+
|
|
240
|
+
export { CLOUD_API_URL, CLOUD_RELAY_URL, CLOUD_VIEWER_URL, CdpClient, DEFAULT_TIMEOUT_S, InvalidTransitionError, LinkInfo, MAX_REASON, MAX_SITE, MemoryEventLog, PopupSource, RelayError, TakeoverControl, Transport, applyInput, buildRelayTransport, cloudAlertsFor, createCloudAlerter, createEngine, createLatestSender, createRelayTransport, hostnames, importSecret, isPublicSuffix, isTerminal, newSecret, newSessionId, nextStatus, probeCapabilities, selectTransport, sendTakeoverAlert, signToken, siteOf, startScreencast, startScreenshotPolling, verifyToken, viewerUrlFor };
|
|
241
|
+
export type { AlertOutcome, AlertProblem, Capabilities, CloudAlerter, CloudAlerterOptions, Engine, EngineOptions, EventLog, FrameSink, LinkHandler, RelayErrorDetail, RelayTransportOptions, ScreencastOptions, SessionEvent, TakeoverCallOptions, TokenCheck, TransportChoice, UnstuckEvent, UnstuckEventType };
|
package/dist/index.js
CHANGED
|
@@ -68,10 +68,23 @@ function b64ToBytes(b64) {
|
|
|
68
68
|
const bin = atob(b64);
|
|
69
69
|
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
70
70
|
}
|
|
71
|
+
async function captureFrame(cdp, quality, maxWidth, maxHeight) {
|
|
72
|
+
const m = await cdp.send("Page.getLayoutMetrics");
|
|
73
|
+
const css = m.cssVisualViewport;
|
|
74
|
+
if (!css?.clientWidth || !css.clientHeight) return null;
|
|
75
|
+
const dpr = m.visualViewport?.clientWidth ? m.visualViewport.clientWidth / css.clientWidth : 1;
|
|
76
|
+
const scale = Math.min(1, maxWidth / (css.clientWidth * dpr), maxHeight / (css.clientHeight * dpr));
|
|
77
|
+
const clip = { x: css.pageX, y: css.pageY, width: css.clientWidth, height: css.clientHeight, scale };
|
|
78
|
+
const shot = await cdp.send("Page.captureScreenshot", { format: "jpeg", quality, ...scale < 1 ? { clip } : {} });
|
|
79
|
+
if (typeof shot.data !== "string") return null;
|
|
80
|
+
return { width: Math.round(css.clientWidth), height: Math.round(css.clientHeight), jpeg: b64ToBytes(shot.data) };
|
|
81
|
+
}
|
|
71
82
|
async function startScreencast(cdp, onFrame, opts = {}) {
|
|
72
83
|
let stopped = false;
|
|
84
|
+
let framed = false;
|
|
73
85
|
const off = cdp.on("Page.screencastFrame", (e) => {
|
|
74
86
|
if (stopped) return;
|
|
87
|
+
framed = true;
|
|
75
88
|
cdp.send("Page.screencastFrameAck", { sessionId: e.sessionId }).catch(() => {
|
|
76
89
|
});
|
|
77
90
|
onFrame({
|
|
@@ -80,12 +93,18 @@ async function startScreencast(cdp, onFrame, opts = {}) {
|
|
|
80
93
|
jpeg: b64ToBytes(e.data)
|
|
81
94
|
});
|
|
82
95
|
});
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
96
|
+
const quality = opts.quality ?? 70;
|
|
97
|
+
const maxWidth = opts.maxWidth ?? 1600;
|
|
98
|
+
const maxHeight = opts.maxHeight ?? 1600;
|
|
99
|
+
await cdp.send("Page.startScreencast", { format: "jpeg", quality, maxWidth, maxHeight });
|
|
100
|
+
void captureFrame(cdp, quality, maxWidth, maxHeight).then(
|
|
101
|
+
(f) => {
|
|
102
|
+
if (f && !framed && !stopped) onFrame(f);
|
|
103
|
+
},
|
|
104
|
+
() => {
|
|
105
|
+
}
|
|
106
|
+
// only a head start: the screencast's own frames follow
|
|
107
|
+
);
|
|
89
108
|
return async () => {
|
|
90
109
|
stopped = true;
|
|
91
110
|
off();
|
|
@@ -1011,9 +1030,18 @@ function runTakeover(deps, cdp, opts) {
|
|
|
1011
1030
|
emit("published");
|
|
1012
1031
|
go("notified");
|
|
1013
1032
|
emit("link", { expiresAt });
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1033
|
+
try {
|
|
1034
|
+
opts.onLink?.({ sessionId, url, reason: opts.reason, expiresAt, ...code !== void 0 ? { code } : {} }, { fail, joined });
|
|
1035
|
+
} catch {
|
|
1036
|
+
}
|
|
1037
|
+
})().catch((e) => finish("failed", `internal_error: ${e?.message ?? String(e)}`));
|
|
1038
|
+
function fail(detail) {
|
|
1039
|
+
finish("failed", detail);
|
|
1040
|
+
}
|
|
1041
|
+
function joined() {
|
|
1042
|
+
return redeemed;
|
|
1043
|
+
}
|
|
1044
|
+
return { result, cancel: (detail) => finish("cancelled", detail), fail, joined };
|
|
1017
1045
|
}
|
|
1018
1046
|
function newCode() {
|
|
1019
1047
|
const buf = new Uint32Array(1);
|
|
@@ -1038,12 +1066,14 @@ function createEngine(opts) {
|
|
|
1038
1066
|
const key = importSecret(opts.secret ?? newSecret());
|
|
1039
1067
|
const now = opts.now ?? (() => Date.now());
|
|
1040
1068
|
const running = /* @__PURE__ */ new Set();
|
|
1069
|
+
let closed = false;
|
|
1041
1070
|
return {
|
|
1042
1071
|
async takeover(cdp, call) {
|
|
1043
1072
|
let closedBefore;
|
|
1044
1073
|
const off = cdp.onClose((reason) => closedBefore ??= reason);
|
|
1045
1074
|
const k = await key;
|
|
1046
1075
|
off();
|
|
1076
|
+
if (closed) return { status: "cancelled", sessionId: "", url: "", durationS: 0, detail: "engine_closed" };
|
|
1047
1077
|
const session = runTakeover({ transport: opts.transport, key: k, log: opts.log, now }, cdp, {
|
|
1048
1078
|
closedBefore,
|
|
1049
1079
|
reason: call.reason,
|
|
@@ -1062,6 +1092,7 @@ function createEngine(opts) {
|
|
|
1062
1092
|
}
|
|
1063
1093
|
},
|
|
1064
1094
|
async close() {
|
|
1095
|
+
closed = true;
|
|
1065
1096
|
const results = [...running].map((s) => {
|
|
1066
1097
|
s.cancel("engine_closed");
|
|
1067
1098
|
return s.result;
|
|
@@ -1119,8 +1150,11 @@ function createRelayTransport(opts) {
|
|
|
1119
1150
|
send(d) {
|
|
1120
1151
|
if (!conn.closed && ws.readyState === 1) ws.send(encodeEnvelope(c, typeof d === "string" ? enc3.encode(d) : d));
|
|
1121
1152
|
},
|
|
1153
|
+
// Workers' client WebSocket has no bufferedAmount. Reporting 0 for it disables backpressure on the engine-to-relay hop
|
|
1154
|
+
// for such sockets: frames are always sent rather than coalesced. The alternative, undefined, turns into NaN in the
|
|
1155
|
+
// sealed layer, and `NaN < mark` is never true, so the screencast would never send a frame at all.
|
|
1122
1156
|
get bufferedAmount() {
|
|
1123
|
-
return ws.bufferedAmount;
|
|
1157
|
+
return ws.bufferedAmount ?? 0;
|
|
1124
1158
|
},
|
|
1125
1159
|
onMessage: (h) => void conn.messages.push(h),
|
|
1126
1160
|
onClose: (h) => void conn.closes.push(h),
|
|
@@ -1272,15 +1306,178 @@ function createRelayTransport(opts) {
|
|
|
1272
1306
|
}
|
|
1273
1307
|
};
|
|
1274
1308
|
}
|
|
1309
|
+
|
|
1310
|
+
// src/cloud/transport.ts
|
|
1311
|
+
var CLOUD_RELAY_URL = "wss://relay.unstuck.sh";
|
|
1312
|
+
var CLOUD_VIEWER_URL = "https://view.unstuck.sh/v";
|
|
1313
|
+
function selectTransport(flags, env) {
|
|
1314
|
+
if (flags.relay) return { kind: "relay", url: flags.relay, agentKey: flags.agentKey ?? env.UNSTUCK_AGENT_KEY, source: "flag" };
|
|
1315
|
+
if (env.UNSTUCK_RELAY_URL) return { kind: "relay", url: env.UNSTUCK_RELAY_URL, agentKey: env.UNSTUCK_AGENT_KEY, source: "UNSTUCK_RELAY_URL" };
|
|
1316
|
+
if (env.UNSTUCK_API_KEY) return { kind: "relay", url: env.UNSTUCK_CLOUD_URL ?? CLOUD_RELAY_URL, agentKey: env.UNSTUCK_API_KEY, source: "UNSTUCK_API_KEY" };
|
|
1317
|
+
return { kind: "embedded" };
|
|
1318
|
+
}
|
|
1319
|
+
function viewerUrlFor(choice, env, version) {
|
|
1320
|
+
if (choice.kind !== "relay") return void 0;
|
|
1321
|
+
if (env.UNSTUCK_VIEWER_URL) return /^(https:\/\/|http:\/\/(127\.0\.0\.1|localhost)[:/])/.test(env.UNSTUCK_VIEWER_URL) ? env.UNSTUCK_VIEWER_URL : void 0;
|
|
1322
|
+
return choice.url.replace(/\/+$/, "") === CLOUD_RELAY_URL ? `${CLOUD_VIEWER_URL}/${version}` : void 0;
|
|
1323
|
+
}
|
|
1324
|
+
function buildRelayTransport(choice, o) {
|
|
1325
|
+
const viewerUrl = viewerUrlFor(choice, o.env, o.version);
|
|
1326
|
+
const relay = createRelayTransport({ url: choice.url, agentKey: choice.agentKey, ...viewerUrl ? { viewerUrl } : {} });
|
|
1327
|
+
const publish = relay.publish.bind(relay);
|
|
1328
|
+
relay.publish = (id, opts) => publish(id, opts).catch((e) => {
|
|
1329
|
+
if (choice.source === "UNSTUCK_API_KEY" && e.detail === "relay_unauthorized") o.warn("[unstuck] unstuck.sh rejected the API key: check the key in your dashboard");
|
|
1330
|
+
throw e;
|
|
1331
|
+
});
|
|
1332
|
+
return relay;
|
|
1333
|
+
}
|
|
1334
|
+
var CLOUD_API_URL = "https://unstuck.sh";
|
|
1335
|
+
function cloudAlertsFor(choice, env) {
|
|
1336
|
+
if (choice.kind !== "relay" || choice.source !== "UNSTUCK_API_KEY" || !choice.agentKey) return null;
|
|
1337
|
+
return { apiBase: (env.UNSTUCK_CLOUD_API || CLOUD_API_URL).replace(/\/+$/, ""), apiKey: choice.agentKey };
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
// src/cloud/alerts.ts
|
|
1341
|
+
import { sealAlert } from "@velmlabs/unstuck-protocol";
|
|
1342
|
+
var AlertFailure = class extends Error {
|
|
1343
|
+
constructor(message, problem) {
|
|
1344
|
+
super(message);
|
|
1345
|
+
this.problem = problem;
|
|
1346
|
+
}
|
|
1347
|
+
problem;
|
|
1348
|
+
};
|
|
1349
|
+
var CACHE_MS = 6e4;
|
|
1350
|
+
var ALERT_TIMEOUT_MS = 1e4;
|
|
1351
|
+
var MAX_REASON = 200;
|
|
1352
|
+
var MAX_SITE = 253;
|
|
1353
|
+
var cut = (s, n) => [...s].slice(0, n).join("");
|
|
1354
|
+
var logLabel = (d) => cut(String(d.label ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, "").trim(), 64) || "phone";
|
|
1355
|
+
var logId = (id) => id.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64);
|
|
1356
|
+
function splitLink(url) {
|
|
1357
|
+
const hash = url.indexOf("#");
|
|
1358
|
+
if (hash < 0) return null;
|
|
1359
|
+
const q = new URLSearchParams(url.slice(hash + 1));
|
|
1360
|
+
const t = q.get("t");
|
|
1361
|
+
const k = q.get("k");
|
|
1362
|
+
return t && k ? { t, k, viewerUrl: url.slice(0, hash) } : null;
|
|
1363
|
+
}
|
|
1364
|
+
function createCloudAlerter(o) {
|
|
1365
|
+
const base = o.apiBase.replace(/\/+$/, "");
|
|
1366
|
+
const doFetch = o.fetch ?? ((...a) => fetch(...a));
|
|
1367
|
+
const log = o.log ?? ((l) => console.error(l));
|
|
1368
|
+
const now = o.now ?? Date.now;
|
|
1369
|
+
const headers = { Authorization: `Bearer ${o.apiKey}` };
|
|
1370
|
+
let cache = null;
|
|
1371
|
+
let lastSet = null;
|
|
1372
|
+
async function within(what, call) {
|
|
1373
|
+
const ac = new AbortController();
|
|
1374
|
+
let timer;
|
|
1375
|
+
const timeout = new Promise((_, reject) => {
|
|
1376
|
+
timer = setTimeout(() => {
|
|
1377
|
+
ac.abort();
|
|
1378
|
+
reject(new AlertFailure(`${what} took longer than ${ALERT_TIMEOUT_MS / 1e3} s`, "error"));
|
|
1379
|
+
}, ALERT_TIMEOUT_MS);
|
|
1380
|
+
});
|
|
1381
|
+
try {
|
|
1382
|
+
return await Promise.race([call(ac.signal), timeout]);
|
|
1383
|
+
} finally {
|
|
1384
|
+
clearTimeout(timer);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
async function devices() {
|
|
1388
|
+
if (cache && now() - cache.at < CACHE_MS) return cache.devices;
|
|
1389
|
+
const list = await within("devices lookup", async (signal) => {
|
|
1390
|
+
const res = await doFetch(`${base}/api/v1/agent/devices`, { headers, signal });
|
|
1391
|
+
if (res.status === 403 && (await res.json().catch(() => null))?.error === "alerts_not_allowed") {
|
|
1392
|
+
log("[unstuck] alerts are not enabled for this API key (turn them on in your unstuck.sh dashboard)");
|
|
1393
|
+
return null;
|
|
1394
|
+
}
|
|
1395
|
+
if (!res.ok) throw new AlertFailure(`devices lookup answered ${res.status}`, res.status === 401 ? "unauthorized" : "error");
|
|
1396
|
+
return (await res.json()).devices;
|
|
1397
|
+
});
|
|
1398
|
+
if (list) cache = { at: now(), devices: list };
|
|
1399
|
+
return list;
|
|
1400
|
+
}
|
|
1401
|
+
const none = (problem) => ({ delivered: 0, problem });
|
|
1402
|
+
return async (info, site) => {
|
|
1403
|
+
try {
|
|
1404
|
+
const link = splitLink(info.url);
|
|
1405
|
+
if (!link) return none("error");
|
|
1406
|
+
const list = await devices();
|
|
1407
|
+
if (!list) return none("alerts_not_allowed");
|
|
1408
|
+
if (list.length === 0) return none("no_devices");
|
|
1409
|
+
const payload = { t: link.t, k: link.k, reason: cut(info.reason, MAX_REASON), site: cut(site ?? "", MAX_SITE), expiresAt: info.expiresAt };
|
|
1410
|
+
const results = await Promise.all(
|
|
1411
|
+
list.map(async (d) => {
|
|
1412
|
+
try {
|
|
1413
|
+
return { d, blob: await sealAlert(d.publicKey, d.id, info.sessionId, payload) };
|
|
1414
|
+
} catch {
|
|
1415
|
+
log(`[unstuck] skipped phone ${logLabel(d)} (${logId(d.id)}): its key is not valid`);
|
|
1416
|
+
return null;
|
|
1417
|
+
}
|
|
1418
|
+
})
|
|
1419
|
+
);
|
|
1420
|
+
const ok = results.filter((r) => r !== null);
|
|
1421
|
+
if (ok.length === 0) return none("seal_failed");
|
|
1422
|
+
const named = ok.map((r) => `${logLabel(r.d)} (${logId(r.d.id)})`).join(", ");
|
|
1423
|
+
if (named !== lastSet) {
|
|
1424
|
+
lastSet = named;
|
|
1425
|
+
log(`[unstuck] alert sealed to ${ok.length} phone(s): ${named}`);
|
|
1426
|
+
}
|
|
1427
|
+
const sealed = ok.map((r) => ({ device: r.d.id, blob: r.blob }));
|
|
1428
|
+
const res = await within(
|
|
1429
|
+
"notify",
|
|
1430
|
+
(signal) => doFetch(`${base}/api/v1/agent/notify`, {
|
|
1431
|
+
method: "POST",
|
|
1432
|
+
headers: { ...headers, "Content-Type": "application/json" },
|
|
1433
|
+
body: JSON.stringify({ sessionId: info.sessionId, viewerUrl: link.viewerUrl, sealed }),
|
|
1434
|
+
signal
|
|
1435
|
+
})
|
|
1436
|
+
);
|
|
1437
|
+
if (!res.ok) throw new AlertFailure(`notify answered ${res.status}`, res.status === 401 ? "unauthorized" : "notify_failed");
|
|
1438
|
+
return { delivered: ok.length };
|
|
1439
|
+
} catch (e) {
|
|
1440
|
+
log(`[unstuck] could not send the phone alert: ${String(e?.message ?? e).replaceAll(o.apiKey, "***")}`);
|
|
1441
|
+
return none(e instanceof AlertFailure ? e.problem : "error");
|
|
1442
|
+
}
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
function sendTakeoverAlert(alerter, alerts, info, site, takeover) {
|
|
1446
|
+
if (alerts === false || !alerter) return null;
|
|
1447
|
+
const failed = () => ({ delivered: 0, problem: "error" });
|
|
1448
|
+
let sent;
|
|
1449
|
+
try {
|
|
1450
|
+
sent = Promise.resolve(alerter(info, site)).catch(failed);
|
|
1451
|
+
} catch {
|
|
1452
|
+
sent = Promise.resolve(failed());
|
|
1453
|
+
}
|
|
1454
|
+
if (alerts === "required") void sent.then((r) => r.delivered === 0 && !takeover.joined() && takeover.fail("alert_failed"));
|
|
1455
|
+
return sent;
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
// src/cloud/sites.ts
|
|
1459
|
+
function hostnames(raw) {
|
|
1460
|
+
if (!Array.isArray(raw)) return [];
|
|
1461
|
+
return raw.filter((h) => typeof h === "string" && /^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(h) && h.length <= 253).filter((h) => h.toLowerCase() === "localhost" || !isPublicSuffix(h)).slice(0, 20);
|
|
1462
|
+
}
|
|
1275
1463
|
export {
|
|
1464
|
+
CLOUD_API_URL,
|
|
1465
|
+
CLOUD_RELAY_URL,
|
|
1466
|
+
CLOUD_VIEWER_URL,
|
|
1276
1467
|
DEFAULT_TIMEOUT_S,
|
|
1277
1468
|
InvalidTransitionError,
|
|
1469
|
+
MAX_REASON,
|
|
1470
|
+
MAX_SITE,
|
|
1278
1471
|
MemoryEventLog,
|
|
1279
1472
|
RelayError,
|
|
1280
1473
|
applyInput,
|
|
1474
|
+
buildRelayTransport,
|
|
1475
|
+
cloudAlertsFor,
|
|
1476
|
+
createCloudAlerter,
|
|
1281
1477
|
createEngine,
|
|
1282
1478
|
createLatestSender,
|
|
1283
1479
|
createRelayTransport,
|
|
1480
|
+
hostnames,
|
|
1284
1481
|
importSecret,
|
|
1285
1482
|
isPublicSuffix,
|
|
1286
1483
|
isTerminal,
|
|
@@ -1288,9 +1485,12 @@ export {
|
|
|
1288
1485
|
newSessionId,
|
|
1289
1486
|
nextStatus,
|
|
1290
1487
|
probeCapabilities,
|
|
1488
|
+
selectTransport,
|
|
1489
|
+
sendTakeoverAlert,
|
|
1291
1490
|
signToken,
|
|
1292
1491
|
siteOf,
|
|
1293
1492
|
startScreencast,
|
|
1294
1493
|
startScreenshotPolling,
|
|
1295
|
-
verifyToken
|
|
1494
|
+
verifyToken,
|
|
1495
|
+
viewerUrlFor
|
|
1296
1496
|
};
|
|
@@ -38,9 +38,16 @@ interface LinkInfo {
|
|
|
38
38
|
/** The 6-digit code the human must enter, when required. Never part of the URL. */
|
|
39
39
|
code?: string;
|
|
40
40
|
}
|
|
41
|
+
/** What a link handler can do to the takeover it got the link for. */
|
|
42
|
+
interface TakeoverControl {
|
|
43
|
+
/** Ends the takeover at once as `failed` with this detail (e.g. `alert_failed`); nothing happens once it has ended. */
|
|
44
|
+
fail(detail: string): void;
|
|
45
|
+
/** Someone has opened the link and joined (true from the first accepted hello on, also after they left). */
|
|
46
|
+
joined(): boolean;
|
|
47
|
+
}
|
|
41
48
|
/** Pages the agent's page opens (e.g. a CAPTCHA provider's popup). */
|
|
42
49
|
interface PopupSource {
|
|
43
50
|
onPopup(cb: (popup: CdpClient) => void): () => void;
|
|
44
51
|
}
|
|
45
52
|
|
|
46
|
-
export type { CdpClient as C, LinkInfo as L, PopupSource as P,
|
|
53
|
+
export type { CdpClient as C, LinkInfo as L, PopupSource as P, TakeoverControl as T, ViewerConnection as V, Transport as a };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@velmlabs/unstuck-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "The Unstuck takeover engine core: screencast, input, sessions and transports, usable in Node or Cloudflare Workers.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"tldts": "^7.5.2",
|
|
50
|
-
"@velmlabs/unstuck-protocol": "0.
|
|
50
|
+
"@velmlabs/unstuck-protocol": "0.2.0"
|
|
51
51
|
},
|
|
52
52
|
"publishConfig": {
|
|
53
53
|
"access": "public"
|