@velmlabs/unstuck-core 0.1.7 → 0.2.1

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-Df0pBZ0z.js';
2
- export { V as ViewerConnection } from './takeover-Df0pBZ0z.js';
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
- type LinkHandler = (info: LinkInfo) => void;
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
- /** Starts a JPEG screencast. Frames carry page CSS-pixel dimensions. Returns a stop function. */
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. */
@@ -81,16 +86,33 @@ interface FrameSink {
81
86
  send(b: Uint8Array): void;
82
87
  readonly bufferedAmount: number;
83
88
  }
84
- /**
85
- * Newest-frame-only sender: never queues more than one pending frame per viewer.
86
- * Slow viewers skip frames instead of building a backlog.
87
- */
88
- declare function createLatestSender(conn: FrameSink, opts?: {
89
+ interface LatestSenderOptions {
89
90
  highWaterMark?: number;
90
- }): {
91
+ /** Clock for the ack timeout (default Date.now). */
92
+ now?: () => number;
93
+ }
94
+ interface LatestSender {
95
+ /** Sends `frame` (an encoded type-1 frame) now if there is room, else keeps it as the one pending frame. */
91
96
  push(frame: Uint8Array): void;
97
+ /** Sends the pending frame if there is room now (called on a timer and after each ack). */
92
98
  drain(): void;
93
- };
99
+ /** Drops the pending frame (the stream moved to another page); numbering and credit carry on. */
100
+ clear(): void;
101
+ /**
102
+ * The viewer opted in to frame credit: from now on frames go out as type 2 with a sequence number, and at most
103
+ * CREDIT_MAX_IN_FLIGHT of them may be unacknowledged. Without this call the sender behaves exactly as before.
104
+ */
105
+ enableCredit(): void;
106
+ /** The viewer has drawn frame `seq` (and so is done with every earlier one). Stale, duplicate and unknown acks are ignored. */
107
+ ack(seq: number): void;
108
+ }
109
+ /**
110
+ * Newest-frame-only sender: never queues more than one pending frame per viewer.
111
+ * Slow viewers skip frames instead of building a backlog. Two signals hold frames back: the socket's own buffer
112
+ * (bufferedAmount, where the runtime reports it) and, once negotiated, end-to-end frame credit from the viewer's acks
113
+ * (which also works where bufferedAmount is always 0: Workers' client sockets, a Durable Object relay).
114
+ */
115
+ declare function createLatestSender(conn: FrameSink, opts?: LatestSenderOptions): LatestSender;
94
116
 
95
117
  type SessionEvent = 'published' | 'notified' | 'viewer_joined' | 'viewer_left' | 'done' | 'cant_solve' | 'timeout' | 'cancel' | 'error';
96
118
  declare class InvalidTransitionError extends Error {
@@ -157,5 +179,80 @@ declare function siteOf(host: string): string;
157
179
  /** True for a bare public suffix ("com", "co.uk", "github.io"): never a site an agent may allow wholesale. */
158
180
  declare function isPublicSuffix(host: string): boolean;
159
181
 
160
- export { CdpClient, DEFAULT_TIMEOUT_S, InvalidTransitionError, LinkInfo, MemoryEventLog, PopupSource, RelayError, Transport, applyInput, createEngine, createLatestSender, createRelayTransport, importSecret, isPublicSuffix, isTerminal, newSecret, newSessionId, nextStatus, probeCapabilities, signToken, siteOf, startScreencast, startScreenshotPolling, verifyToken };
161
- export type { Capabilities, Engine, EngineOptions, EventLog, FrameSink, LinkHandler, RelayErrorDetail, RelayTransportOptions, ScreencastOptions, SessionEvent, TakeoverCallOptions, TokenCheck, UnstuckEvent, UnstuckEventType };
182
+ declare const CLOUD_RELAY_URL = "wss://relay.unstuck.sh";
183
+ /** Unstuck Cloud's viewer, on its own origin; each engine links to the build of its own version. */
184
+ declare const CLOUD_VIEWER_URL = "https://view.unstuck.sh/v";
185
+ type TransportChoice = {
186
+ kind: 'relay';
187
+ url: string;
188
+ agentKey?: string;
189
+ source: 'flag' | 'UNSTUCK_RELAY_URL' | 'UNSTUCK_API_KEY';
190
+ } | {
191
+ kind: 'embedded';
192
+ };
193
+ /** Relay spec §5.6: flags → UNSTUCK_RELAY_URL (+ UNSTUCK_AGENT_KEY) → UNSTUCK_API_KEY (Unstuck Cloud) → embedded. */
194
+ declare function selectTransport(flags: {
195
+ relay?: string;
196
+ agentKey?: string;
197
+ }, env: Record<string, string | undefined>): TransportChoice;
198
+ /**
199
+ * Where links open the viewer: UNSTUCK_VIEWER_URL (https, or http on this machine), else the hosted viewer pinned to this engine's
200
+ * version for the Unstuck Cloud relay, else undefined (the relay's own page, e.g. a self-hosted relay).
201
+ */
202
+ declare function viewerUrlFor(choice: TransportChoice, env: Record<string, string | undefined>, version: string): string | undefined;
203
+ /** The relay transport for a chosen relay. Never logs the key; `warn` gets one line when Unstuck Cloud rejects the API key. */
204
+ declare function buildRelayTransport(choice: Extract<TransportChoice, {
205
+ kind: 'relay';
206
+ }>, o: {
207
+ env: Record<string, string | undefined>;
208
+ version: string;
209
+ warn: (line: string) => void;
210
+ }): Transport;
211
+ declare const CLOUD_API_URL = "https://unstuck.sh";
212
+ /** Where to send phone alerts: only for Unstuck Cloud via UNSTUCK_API_KEY, not for self-hosted relays or embedded mode. */
213
+ declare function cloudAlertsFor(choice: TransportChoice, env: Record<string, string | undefined>): {
214
+ apiBase: string;
215
+ apiKey: string;
216
+ } | null;
217
+
218
+ interface CloudAlerterOptions {
219
+ /** Unstuck Cloud's API origin, e.g. https://unstuck.sh. */
220
+ apiBase: string;
221
+ apiKey: string;
222
+ fetch?: typeof fetch;
223
+ /** One line per problem; never contains the link secret or the API key. */
224
+ log?: (line: string) => void;
225
+ now?: () => number;
226
+ }
227
+ /** 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. */
228
+ type AlertProblem = 'alerts_not_allowed' | 'no_devices' | 'seal_failed' | 'notify_failed' | 'unauthorized' | 'error';
229
+ /** How many paired phones Unstuck Cloud accepted the alert for, or why none. */
230
+ type AlertOutcome = {
231
+ delivered: number;
232
+ } | {
233
+ delivered: 0;
234
+ problem: AlertProblem;
235
+ };
236
+ type CloudAlerter = (info: LinkInfo, site: string | undefined) => Promise<AlertOutcome>;
237
+ /** The sealed payload's caps (code points): a long reason must not push the link past what push and Telegram carry. */
238
+ declare const MAX_REASON = 200;
239
+ declare const MAX_SITE = 253;
240
+ /**
241
+ * Seals each takeover link to the account's paired phones and asks Unstuck Cloud to deliver it (notifications spec §4.2).
242
+ * Cloud only ever sees ciphertext. Never rejects: an alert that can't be sent is one line on the log, and the outcome
243
+ * says why.
244
+ */
245
+ declare function createCloudAlerter(o: CloudAlerterOptions): CloudAlerter;
246
+ /**
247
+ * A takeover's alert, from its link handler: none with `alerts: false`; with `'required'`, a link that reached no paired
248
+ * phone fails the takeover at once with `alert_failed` instead of letting it wait for its timeout, unless someone already
249
+ * joined through the link the handler passed on. An alerter that rejects counts as no phone reached.
250
+ * Returns the outcome (never rejects), or null when no alert is sent (no Unstuck Cloud alerter, or `alerts: false`).
251
+ */
252
+ declare function sendTakeoverAlert(alerter: CloudAlerter | null | undefined, alerts: boolean | 'required' | undefined, info: LinkInfo, site: string | undefined, takeover: TakeoverControl): Promise<AlertOutcome> | null;
253
+
254
+ /** Keeps only plausible hostnames that aren't bare public suffixes (a leading "*." is accepted), at most 20. */
255
+ declare function hostnames(raw: unknown): string[];
256
+
257
+ 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 };
258
+ 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
- await cdp.send("Page.startScreencast", {
84
- format: "jpeg",
85
- quality: opts.quality ?? 70,
86
- maxWidth: opts.maxWidth ?? 1600,
87
- maxHeight: opts.maxHeight ?? 1600
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();
@@ -531,24 +550,64 @@ function safeInput(msg) {
531
550
  }
532
551
 
533
552
  // src/stream/latest.ts
553
+ import { FRAME_SEQ_MAX, withFrameSeq } from "@velmlabs/unstuck-protocol";
554
+ var CREDIT_MAX_IN_FLIGHT = 3;
555
+ var CREDIT_ACK_TIMEOUT_MS = 1e3;
556
+ var CREDIT_GRANT_MAX_MS = 8e3;
534
557
  function createLatestSender(conn, opts = {}) {
535
558
  const mark = opts.highWaterMark ?? 512 * 1024;
559
+ const now = opts.now ?? Date.now;
536
560
  let pending = null;
561
+ let credit = false;
562
+ let sentSeq = 0;
563
+ let ackedSeq = 0;
564
+ let since = 0;
565
+ let grantAfter = CREDIT_ACK_TIMEOUT_MS;
566
+ const room = () => {
567
+ if (!(conn.bufferedAmount < mark)) return false;
568
+ if (!credit || sentSeq - ackedSeq < CREDIT_MAX_IN_FLIGHT) return true;
569
+ if (now() - since < grantAfter) return false;
570
+ ackedSeq = sentSeq - CREDIT_MAX_IN_FLIGHT + 1;
571
+ grantAfter = Math.min(grantAfter * 2, CREDIT_GRANT_MAX_MS);
572
+ return true;
573
+ };
574
+ const send = (frame) => {
575
+ if (!credit) return conn.send(frame);
576
+ if (sentSeq === FRAME_SEQ_MAX) sentSeq = ackedSeq = 0;
577
+ conn.send(withFrameSeq(frame, ++sentSeq));
578
+ since = now();
579
+ };
580
+ const drain = () => {
581
+ if (pending && room()) {
582
+ const f = pending;
583
+ pending = null;
584
+ send(f);
585
+ }
586
+ };
537
587
  return {
538
588
  push(frame) {
539
- if (conn.bufferedAmount < mark) {
589
+ if (room()) {
540
590
  pending = null;
541
- conn.send(frame);
591
+ send(frame);
542
592
  } else {
543
593
  pending = frame;
544
594
  }
545
595
  },
546
- drain() {
547
- if (pending && conn.bufferedAmount < mark) {
548
- const f = pending;
549
- pending = null;
550
- conn.send(f);
551
- }
596
+ drain,
597
+ clear() {
598
+ pending = null;
599
+ },
600
+ enableCredit() {
601
+ if (credit) return;
602
+ credit = true;
603
+ since = now();
604
+ },
605
+ ack(seq) {
606
+ if (!credit || !Number.isInteger(seq) || seq <= ackedSeq || seq > sentSeq) return;
607
+ ackedSeq = seq;
608
+ since = now();
609
+ grantAfter = CREDIT_ACK_TIMEOUT_MS;
610
+ drain();
552
611
  }
553
612
  };
554
613
  }
@@ -681,6 +740,7 @@ function runTakeover(deps, cdp, opts) {
681
740
  let stopScreencast = null;
682
741
  let streamGen = 0;
683
742
  let sender = null;
743
+ let holderSender = null;
684
744
  let drainTimer = null;
685
745
  let leftTimer = null;
686
746
  let transportDown = false;
@@ -727,6 +787,7 @@ function runTakeover(deps, cdp, opts) {
727
787
  streamGen++;
728
788
  if (drainTimer) clearInterval(drainTimer);
729
789
  drainTimer = null;
790
+ sender?.clear();
730
791
  sender = null;
731
792
  const stop = stopScreencast;
732
793
  stopScreencast = null;
@@ -777,8 +838,8 @@ function runTakeover(deps, cdp, opts) {
777
838
  resumeKey = newSessionId();
778
839
  if (status === "waiting") go("viewer_joined");
779
840
  emit("viewer_joined");
780
- sendJson(conn, { t: "ready", reason: opts.reason, site: opts.site ?? "", expiresAt, resumeKey, ...vn ? { vn } : {} });
781
- sender = createLatestSender(conn);
841
+ sendJson(conn, { t: "ready", reason: opts.reason, site: opts.site ?? "", expiresAt, resumeKey, ...vn ? { vn } : {}, credit: 1 });
842
+ sender = holderSender = createLatestSender(conn, { now });
782
843
  if (lastFrame) sender.push(lastFrame);
783
844
  fieldFeed.onTargetChanged();
784
845
  if (!stopScreencast) await startStream();
@@ -813,7 +874,8 @@ function runTakeover(deps, cdp, opts) {
813
874
  await stopStream();
814
875
  lastFrame = null;
815
876
  if (!holder || isTerminal(status)) return;
816
- sender = createLatestSender(holder);
877
+ holderSender?.clear();
878
+ sender = holderSender;
817
879
  fieldFeed.onTargetChanged();
818
880
  await startStream();
819
881
  }
@@ -918,6 +980,10 @@ function runTakeover(deps, cdp, opts) {
918
980
  switch (msg.t) {
919
981
  case "ping":
920
982
  return sendJson(conn, { t: "pong" });
983
+ case "credit":
984
+ return void (conn === holder && holderSender?.enableCredit());
985
+ case "ack":
986
+ return void (conn === holder && holderSender?.ack(msg.seq));
921
987
  case "done":
922
988
  return finish("resolved");
923
989
  case "cant_solve": {
@@ -1011,9 +1077,18 @@ function runTakeover(deps, cdp, opts) {
1011
1077
  emit("published");
1012
1078
  go("notified");
1013
1079
  emit("link", { expiresAt });
1014
- opts.onLink?.({ sessionId, url, reason: opts.reason, expiresAt, ...code !== void 0 ? { code } : {} });
1015
- })();
1016
- return { result, cancel: (detail) => finish("cancelled", detail) };
1080
+ try {
1081
+ opts.onLink?.({ sessionId, url, reason: opts.reason, expiresAt, ...code !== void 0 ? { code } : {} }, { fail, joined });
1082
+ } catch {
1083
+ }
1084
+ })().catch((e) => finish("failed", `internal_error: ${e?.message ?? String(e)}`));
1085
+ function fail(detail) {
1086
+ finish("failed", detail);
1087
+ }
1088
+ function joined() {
1089
+ return redeemed;
1090
+ }
1091
+ return { result, cancel: (detail) => finish("cancelled", detail), fail, joined };
1017
1092
  }
1018
1093
  function newCode() {
1019
1094
  const buf = new Uint32Array(1);
@@ -1038,12 +1113,14 @@ function createEngine(opts) {
1038
1113
  const key = importSecret(opts.secret ?? newSecret());
1039
1114
  const now = opts.now ?? (() => Date.now());
1040
1115
  const running = /* @__PURE__ */ new Set();
1116
+ let closed = false;
1041
1117
  return {
1042
1118
  async takeover(cdp, call) {
1043
1119
  let closedBefore;
1044
1120
  const off = cdp.onClose((reason) => closedBefore ??= reason);
1045
1121
  const k = await key;
1046
1122
  off();
1123
+ if (closed) return { status: "cancelled", sessionId: "", url: "", durationS: 0, detail: "engine_closed" };
1047
1124
  const session = runTakeover({ transport: opts.transport, key: k, log: opts.log, now }, cdp, {
1048
1125
  closedBefore,
1049
1126
  reason: call.reason,
@@ -1062,6 +1139,7 @@ function createEngine(opts) {
1062
1139
  }
1063
1140
  },
1064
1141
  async close() {
1142
+ closed = true;
1065
1143
  const results = [...running].map((s) => {
1066
1144
  s.cancel("engine_closed");
1067
1145
  return s.result;
@@ -1119,8 +1197,11 @@ function createRelayTransport(opts) {
1119
1197
  send(d) {
1120
1198
  if (!conn.closed && ws.readyState === 1) ws.send(encodeEnvelope(c, typeof d === "string" ? enc3.encode(d) : d));
1121
1199
  },
1200
+ // Workers' client WebSocket has no bufferedAmount. Reporting 0 for it disables backpressure on the engine-to-relay hop
1201
+ // for such sockets: frames are always sent rather than coalesced. The alternative, undefined, turns into NaN in the
1202
+ // sealed layer, and `NaN < mark` is never true, so the screencast would never send a frame at all.
1122
1203
  get bufferedAmount() {
1123
- return ws.bufferedAmount;
1204
+ return ws.bufferedAmount ?? 0;
1124
1205
  },
1125
1206
  onMessage: (h) => void conn.messages.push(h),
1126
1207
  onClose: (h) => void conn.closes.push(h),
@@ -1272,15 +1353,178 @@ function createRelayTransport(opts) {
1272
1353
  }
1273
1354
  };
1274
1355
  }
1356
+
1357
+ // src/cloud/transport.ts
1358
+ var CLOUD_RELAY_URL = "wss://relay.unstuck.sh";
1359
+ var CLOUD_VIEWER_URL = "https://view.unstuck.sh/v";
1360
+ function selectTransport(flags, env) {
1361
+ if (flags.relay) return { kind: "relay", url: flags.relay, agentKey: flags.agentKey ?? env.UNSTUCK_AGENT_KEY, source: "flag" };
1362
+ if (env.UNSTUCK_RELAY_URL) return { kind: "relay", url: env.UNSTUCK_RELAY_URL, agentKey: env.UNSTUCK_AGENT_KEY, source: "UNSTUCK_RELAY_URL" };
1363
+ 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" };
1364
+ return { kind: "embedded" };
1365
+ }
1366
+ function viewerUrlFor(choice, env, version) {
1367
+ if (choice.kind !== "relay") return void 0;
1368
+ if (env.UNSTUCK_VIEWER_URL) return /^(https:\/\/|http:\/\/(127\.0\.0\.1|localhost)[:/])/.test(env.UNSTUCK_VIEWER_URL) ? env.UNSTUCK_VIEWER_URL : void 0;
1369
+ return choice.url.replace(/\/+$/, "") === CLOUD_RELAY_URL ? `${CLOUD_VIEWER_URL}/${version}` : void 0;
1370
+ }
1371
+ function buildRelayTransport(choice, o) {
1372
+ const viewerUrl = viewerUrlFor(choice, o.env, o.version);
1373
+ const relay = createRelayTransport({ url: choice.url, agentKey: choice.agentKey, ...viewerUrl ? { viewerUrl } : {} });
1374
+ const publish = relay.publish.bind(relay);
1375
+ relay.publish = (id, opts) => publish(id, opts).catch((e) => {
1376
+ 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");
1377
+ throw e;
1378
+ });
1379
+ return relay;
1380
+ }
1381
+ var CLOUD_API_URL = "https://unstuck.sh";
1382
+ function cloudAlertsFor(choice, env) {
1383
+ if (choice.kind !== "relay" || choice.source !== "UNSTUCK_API_KEY" || !choice.agentKey) return null;
1384
+ return { apiBase: (env.UNSTUCK_CLOUD_API || CLOUD_API_URL).replace(/\/+$/, ""), apiKey: choice.agentKey };
1385
+ }
1386
+
1387
+ // src/cloud/alerts.ts
1388
+ import { sealAlert } from "@velmlabs/unstuck-protocol";
1389
+ var AlertFailure = class extends Error {
1390
+ constructor(message, problem) {
1391
+ super(message);
1392
+ this.problem = problem;
1393
+ }
1394
+ problem;
1395
+ };
1396
+ var CACHE_MS = 6e4;
1397
+ var ALERT_TIMEOUT_MS = 1e4;
1398
+ var MAX_REASON = 200;
1399
+ var MAX_SITE = 253;
1400
+ var cut = (s, n) => [...s].slice(0, n).join("");
1401
+ var logLabel = (d) => cut(String(d.label ?? "").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, "").trim(), 64) || "phone";
1402
+ var logId = (id) => id.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64);
1403
+ function splitLink(url) {
1404
+ const hash = url.indexOf("#");
1405
+ if (hash < 0) return null;
1406
+ const q = new URLSearchParams(url.slice(hash + 1));
1407
+ const t = q.get("t");
1408
+ const k = q.get("k");
1409
+ return t && k ? { t, k, viewerUrl: url.slice(0, hash) } : null;
1410
+ }
1411
+ function createCloudAlerter(o) {
1412
+ const base = o.apiBase.replace(/\/+$/, "");
1413
+ const doFetch = o.fetch ?? ((...a) => fetch(...a));
1414
+ const log = o.log ?? ((l) => console.error(l));
1415
+ const now = o.now ?? Date.now;
1416
+ const headers = { Authorization: `Bearer ${o.apiKey}` };
1417
+ let cache = null;
1418
+ let lastSet = null;
1419
+ async function within(what, call) {
1420
+ const ac = new AbortController();
1421
+ let timer;
1422
+ const timeout = new Promise((_, reject) => {
1423
+ timer = setTimeout(() => {
1424
+ ac.abort();
1425
+ reject(new AlertFailure(`${what} took longer than ${ALERT_TIMEOUT_MS / 1e3} s`, "error"));
1426
+ }, ALERT_TIMEOUT_MS);
1427
+ });
1428
+ try {
1429
+ return await Promise.race([call(ac.signal), timeout]);
1430
+ } finally {
1431
+ clearTimeout(timer);
1432
+ }
1433
+ }
1434
+ async function devices() {
1435
+ if (cache && now() - cache.at < CACHE_MS) return cache.devices;
1436
+ const list = await within("devices lookup", async (signal) => {
1437
+ const res = await doFetch(`${base}/api/v1/agent/devices`, { headers, signal });
1438
+ if (res.status === 403 && (await res.json().catch(() => null))?.error === "alerts_not_allowed") {
1439
+ log("[unstuck] alerts are not enabled for this API key (turn them on in your unstuck.sh dashboard)");
1440
+ return null;
1441
+ }
1442
+ if (!res.ok) throw new AlertFailure(`devices lookup answered ${res.status}`, res.status === 401 ? "unauthorized" : "error");
1443
+ return (await res.json()).devices;
1444
+ });
1445
+ if (list) cache = { at: now(), devices: list };
1446
+ return list;
1447
+ }
1448
+ const none = (problem) => ({ delivered: 0, problem });
1449
+ return async (info, site) => {
1450
+ try {
1451
+ const link = splitLink(info.url);
1452
+ if (!link) return none("error");
1453
+ const list = await devices();
1454
+ if (!list) return none("alerts_not_allowed");
1455
+ if (list.length === 0) return none("no_devices");
1456
+ const payload = { t: link.t, k: link.k, reason: cut(info.reason, MAX_REASON), site: cut(site ?? "", MAX_SITE), expiresAt: info.expiresAt };
1457
+ const results = await Promise.all(
1458
+ list.map(async (d) => {
1459
+ try {
1460
+ return { d, blob: await sealAlert(d.publicKey, d.id, info.sessionId, payload) };
1461
+ } catch {
1462
+ log(`[unstuck] skipped phone ${logLabel(d)} (${logId(d.id)}): its key is not valid`);
1463
+ return null;
1464
+ }
1465
+ })
1466
+ );
1467
+ const ok = results.filter((r) => r !== null);
1468
+ if (ok.length === 0) return none("seal_failed");
1469
+ const named = ok.map((r) => `${logLabel(r.d)} (${logId(r.d.id)})`).join(", ");
1470
+ if (named !== lastSet) {
1471
+ lastSet = named;
1472
+ log(`[unstuck] alert sealed to ${ok.length} phone(s): ${named}`);
1473
+ }
1474
+ const sealed = ok.map((r) => ({ device: r.d.id, blob: r.blob }));
1475
+ const res = await within(
1476
+ "notify",
1477
+ (signal) => doFetch(`${base}/api/v1/agent/notify`, {
1478
+ method: "POST",
1479
+ headers: { ...headers, "Content-Type": "application/json" },
1480
+ body: JSON.stringify({ sessionId: info.sessionId, viewerUrl: link.viewerUrl, sealed }),
1481
+ signal
1482
+ })
1483
+ );
1484
+ if (!res.ok) throw new AlertFailure(`notify answered ${res.status}`, res.status === 401 ? "unauthorized" : "notify_failed");
1485
+ return { delivered: ok.length };
1486
+ } catch (e) {
1487
+ log(`[unstuck] could not send the phone alert: ${String(e?.message ?? e).replaceAll(o.apiKey, "***")}`);
1488
+ return none(e instanceof AlertFailure ? e.problem : "error");
1489
+ }
1490
+ };
1491
+ }
1492
+ function sendTakeoverAlert(alerter, alerts, info, site, takeover) {
1493
+ if (alerts === false || !alerter) return null;
1494
+ const failed = () => ({ delivered: 0, problem: "error" });
1495
+ let sent;
1496
+ try {
1497
+ sent = Promise.resolve(alerter(info, site)).catch(failed);
1498
+ } catch {
1499
+ sent = Promise.resolve(failed());
1500
+ }
1501
+ if (alerts === "required") void sent.then((r) => r.delivered === 0 && !takeover.joined() && takeover.fail("alert_failed"));
1502
+ return sent;
1503
+ }
1504
+
1505
+ // src/cloud/sites.ts
1506
+ function hostnames(raw) {
1507
+ if (!Array.isArray(raw)) return [];
1508
+ 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);
1509
+ }
1275
1510
  export {
1511
+ CLOUD_API_URL,
1512
+ CLOUD_RELAY_URL,
1513
+ CLOUD_VIEWER_URL,
1276
1514
  DEFAULT_TIMEOUT_S,
1277
1515
  InvalidTransitionError,
1516
+ MAX_REASON,
1517
+ MAX_SITE,
1278
1518
  MemoryEventLog,
1279
1519
  RelayError,
1280
1520
  applyInput,
1521
+ buildRelayTransport,
1522
+ cloudAlertsFor,
1523
+ createCloudAlerter,
1281
1524
  createEngine,
1282
1525
  createLatestSender,
1283
1526
  createRelayTransport,
1527
+ hostnames,
1284
1528
  importSecret,
1285
1529
  isPublicSuffix,
1286
1530
  isTerminal,
@@ -1288,9 +1532,12 @@ export {
1288
1532
  newSessionId,
1289
1533
  nextStatus,
1290
1534
  probeCapabilities,
1535
+ selectTransport,
1536
+ sendTakeoverAlert,
1291
1537
  signToken,
1292
1538
  siteOf,
1293
1539
  startScreencast,
1294
1540
  startScreenshotPolling,
1295
- verifyToken
1541
+ verifyToken,
1542
+ viewerUrlFor
1296
1543
  };
@@ -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, Transport as T, ViewerConnection as V };
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.1.7",
3
+ "version": "0.2.1",
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.1.7"
50
+ "@velmlabs/unstuck-protocol": "0.2.1"
51
51
  },
52
52
  "publishConfig": {
53
53
  "access": "public"