@velmlabs/unstuck-protocol 0.1.4 → 0.1.6

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
@@ -74,6 +74,10 @@ interface TakeoverParams {
74
74
  site?: string;
75
75
  /** Ask the human for a 6-digit code delivered with the link (relay spec §5.8). */
76
76
  requireCode?: boolean;
77
+ /** Sites besides the page's own the human may navigate to, e.g. ["accounts.google.com"] (page lock). */
78
+ allowedSites?: string[];
79
+ /** Send this takeover to the user's paired phones (Unstuck Cloud); undefined means yes, false skips it. */
80
+ alerts?: boolean;
77
81
  }
78
82
  interface CdpSendParams {
79
83
  pageId: string;
@@ -123,6 +127,8 @@ declare const ViewerToEngineSchema: _sinclair_typebox.TUnion<[_sinclair_typebox.
123
127
  token: _sinclair_typebox.TString;
124
128
  resumeKey: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
125
129
  code: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
130
+ /** The viewer's random value for this connection; engines that announce v: 2 echo it in ready (anti-replay). */
131
+ vn: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
126
132
  }>, _sinclair_typebox.TObject<{
127
133
  t: _sinclair_typebox.TLiteral<"mouse">;
128
134
  action: _sinclair_typebox.TUnion<[_sinclair_typebox.TLiteral<"down">, _sinclair_typebox.TLiteral<"up">, _sinclair_typebox.TLiteral<"move">]>;
@@ -179,6 +185,7 @@ declare const EngineToViewerSchema: _sinclair_typebox.TUnion<[_sinclair_typebox.
179
185
  site: _sinclair_typebox.TString;
180
186
  expiresAt: _sinclair_typebox.TNumber;
181
187
  resumeKey: _sinclair_typebox.TString;
188
+ vn: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
182
189
  }>, _sinclair_typebox.TObject<{
183
190
  t: _sinclair_typebox.TLiteral<"state">;
184
191
  status: _sinclair_typebox.TUnion<_sinclair_typebox.TLiteral<string>[]>;
@@ -214,6 +221,7 @@ type EngineToViewer = {
214
221
  site: string;
215
222
  expiresAt: number;
216
223
  resumeKey: string;
224
+ vn?: string;
217
225
  } | {
218
226
  t: 'state';
219
227
  status: SessionStatus;
@@ -247,6 +255,11 @@ declare const RELAY_LIMITS: {
247
255
  readonly agentPayloadMax: 2097152;
248
256
  readonly viewerPayloadMax: 65536;
249
257
  readonly viewersPerSession: 4;
258
+ /** Viewers that haven't been confirmed (see relay-core attachViewer) one client IP may hold in one session. */
259
+ readonly unconfirmedViewersPerIp: 2;
260
+ /** Viewer → agent bytes one viewer connection may send per window. */
261
+ readonly viewerBytesPerWindow: 2097152;
262
+ readonly viewerByteWindowMs: 10000;
250
263
  readonly idleMs: 120000;
251
264
  readonly heartbeatMs: 30000;
252
265
  readonly graceMs: 60000;
@@ -255,12 +268,16 @@ declare const RELAY_LIMITS: {
255
268
  readonly backpressureBytes: 4194304;
256
269
  readonly viewerUpgradesPerMinPerIp: 30;
257
270
  readonly agentUpgradesPerMinPerKey: 20;
271
+ /** Agent upgrades per client IP per minute, counted on refused authorizations only (key brute force). */
272
+ readonly agentAuthFailuresPerMinPerIp: 10;
258
273
  };
259
274
  declare const RELAY_CLOSE: {
260
275
  readonly agentReconnecting: 1012;
261
276
  readonly replaced: 4409;
262
277
  readonly badMessage: 1003;
263
278
  readonly tooBig: 1009;
279
+ readonly policy: 1008;
280
+ readonly tryAgainLater: 1013;
264
281
  /** A refused agent: 4000 + the HTTP status (4401, 4402, 4403, 4429). Clients can't read upgrade statuses. */
265
282
  readonly refused: (status: number) => number;
266
283
  };
@@ -313,6 +330,11 @@ declare function b64urlEncode(b: Uint8Array): string;
313
330
  declare function b64urlDecode(s: string): Uint8Array | null;
314
331
  /** Plaintext JSON messages start with '{'; screen frames start with their type byte (0x01). */
315
332
  declare const isJsonPlaintext: (p: Uint8Array) => boolean;
333
+ /**
334
+ * Pads a JSON plaintext with trailing spaces (still valid JSON for any peer) to 256 bytes, then to the next power of
335
+ * two up to what still fits 64 KB once sealed, so a relay can't tell keys, digits or the length of typed text from message sizes.
336
+ */
337
+ declare function padPlaintext(p: Uint8Array): Uint8Array;
316
338
  /**
317
339
  * Replay protection (relay spec §5.4): every message on a viewer connection is bound to that connection's random
318
340
  * nonce (sent by the engine in a sealed challenge) and carries a sequence number the receiver requires to increase.
@@ -326,5 +348,26 @@ declare function openMsg(key: CryptoKey, sessionId: string, dir: Direction, conn
326
348
  plain: Uint8Array;
327
349
  } | null>;
328
350
 
329
- export { EngineToViewerSchema, FRAME_TYPE_JPEG, FieldKinds, FieldSchema, KEY_SUBPROTOCOL_PREFIX, Methods, PROTOCOL_VERSION, RELAY_CLOSE, RELAY_LIMITS, RELAY_SUBPROTOCOL, RESUME_WINDOW_MS, RpcCallError, SESSION_ID_RE, SessionStatusSchema, ViewerErrorCodes, ViewerToEngineSchema, b64urlDecode, b64urlEncode, createRpcPeer, decodeEnvelope, decodeFrame, encodeEnvelope, encodeFrame, importE2eKey, isJsonPlaintext, newConnNonce, newE2eKey, open, openMsg, parseAgentToRelay, parseRelayToAgent, parseViewerMessage, seal, sealMsg };
330
- export type { AgentToRelay, CdpClosedParams, CdpEventParams, CdpSendParams, CdpSubscribeParams, Direction, EngineToViewer, Field, FieldKind, Frame, HelloParams, HelloResult, PagePopupParams, RelayToAgent, RpcError, RpcNotification, RpcPeer, RpcRequest, RpcResponse, SessionStatus, TakeoverLinkParams, TakeoverParams, TakeoverResult, TakeoverStatus, ViewerErrorCode, ViewerInput, ViewerToEngine };
351
+ interface AlertPayload {
352
+ t: string;
353
+ k: string;
354
+ reason: string;
355
+ site: string;
356
+ expiresAt: number;
357
+ }
358
+ /** ECDH P-256 key pair for a paired phone; the private key is non-extractable. */
359
+ declare function newDeviceKeyPair(): Promise<CryptoKeyPair>;
360
+ /** The raw 65-byte uncompressed public key, base64url. */
361
+ declare function exportDevicePublicKey(k: CryptoKey): Promise<string>;
362
+ /** Seals the payload to the device's public key; bound to the device and session. */
363
+ declare function sealAlert(devicePublicKey: string, deviceId: string, sessionId: string, p: AlertPayload): Promise<string>;
364
+ /** The payload, or null when the blob wasn't sealed to this key, device and session (or is malformed). */
365
+ declare function openAlert(devicePrivateKey: CryptoKey, deviceId: string, sessionId: string, blob: string): Promise<AlertPayload | null>;
366
+ /** Reads `#x=<device id>.<blob>`; null for any other fragment. */
367
+ declare function parseAlertFragment(hash: string): {
368
+ deviceId: string;
369
+ blob: string;
370
+ } | null;
371
+
372
+ export { EngineToViewerSchema, FRAME_TYPE_JPEG, FieldKinds, FieldSchema, KEY_SUBPROTOCOL_PREFIX, Methods, PROTOCOL_VERSION, RELAY_CLOSE, RELAY_LIMITS, RELAY_SUBPROTOCOL, RESUME_WINDOW_MS, RpcCallError, SESSION_ID_RE, SessionStatusSchema, ViewerErrorCodes, ViewerToEngineSchema, b64urlDecode, b64urlEncode, createRpcPeer, decodeEnvelope, decodeFrame, encodeEnvelope, encodeFrame, exportDevicePublicKey, importE2eKey, isJsonPlaintext, newConnNonce, newDeviceKeyPair, newE2eKey, open, openAlert, openMsg, padPlaintext, parseAgentToRelay, parseAlertFragment, parseRelayToAgent, parseViewerMessage, seal, sealAlert, sealMsg };
373
+ export type { AgentToRelay, AlertPayload, CdpClosedParams, CdpEventParams, CdpSendParams, CdpSubscribeParams, Direction, EngineToViewer, Field, FieldKind, Frame, HelloParams, HelloResult, PagePopupParams, RelayToAgent, RpcError, RpcNotification, RpcPeer, RpcRequest, RpcResponse, SessionStatus, TakeoverLinkParams, TakeoverParams, TakeoverResult, TakeoverStatus, ViewerErrorCode, ViewerInput, ViewerToEngine };
package/dist/index.js CHANGED
@@ -126,7 +126,14 @@ var Num = Type.Number();
126
126
  var Lit = (v) => Type.Literal(v);
127
127
  var ViewerToEngineSchema = Type.Union([
128
128
  Type.Object(
129
- { t: Lit("hello"), token: Type.String(), resumeKey: Type.Optional(Type.String()), code: Type.Optional(Type.String({ pattern: "^[0-9]{6}$" })) },
129
+ {
130
+ t: Lit("hello"),
131
+ token: Type.String(),
132
+ resumeKey: Type.Optional(Type.String()),
133
+ code: Type.Optional(Type.String({ pattern: "^[0-9]{6}$" })),
134
+ /** The viewer's random value for this connection; engines that announce v: 2 echo it in ready (anti-replay). */
135
+ vn: Type.Optional(Type.String({ pattern: "^[A-Za-z0-9_-]{16,64}$" }))
136
+ },
130
137
  { additionalProperties: false }
131
138
  ),
132
139
  Type.Object(
@@ -155,7 +162,7 @@ var ViewerToEngineSchema = Type.Union([
155
162
  ),
156
163
  Type.Object({ t: Lit("text"), text: Type.String() }, { additionalProperties: false }),
157
164
  Type.Object({ t: Lit("done") }, { additionalProperties: false }),
158
- Type.Object({ t: Lit("cant_solve"), reason: Type.Optional(Type.String()) }, { additionalProperties: false }),
165
+ Type.Object({ t: Lit("cant_solve"), reason: Type.Optional(Type.String({ maxLength: 200 })) }, { additionalProperties: false }),
159
166
  Type.Object({ t: Lit("ping") }, { additionalProperties: false })
160
167
  ]);
161
168
  var ViewerErrorCodes = ["token_invalid", "token_used", "expired", "session_closed", "bad_message", "code_required", "code_invalid"];
@@ -163,7 +170,7 @@ var FieldKinds = ["text", "numeric", "otp", "email", "password"];
163
170
  var FieldKindSchema = Type.Union(FieldKinds.map((k) => Lit(k)));
164
171
  var FieldSchema = Type.Object({ x: Num, y: Num, w: Num, h: Num, kind: FieldKindSchema }, { additionalProperties: false });
165
172
  var EngineToViewerSchema = Type.Union([
166
- Type.Object({ t: Lit("ready"), reason: Type.String(), site: Type.String(), expiresAt: Num, resumeKey: Type.String() }),
173
+ Type.Object({ t: Lit("ready"), reason: Type.String(), site: Type.String(), expiresAt: Num, resumeKey: Type.String(), vn: Type.Optional(Type.String()) }),
167
174
  Type.Object({ t: Lit("state"), status: SessionStatusSchema }),
168
175
  Type.Object({ t: Lit("error"), code: Type.Union(ViewerErrorCodes.map((c) => Lit(c))), message: Type.String() }),
169
176
  Type.Object({ t: Lit("pong") }),
@@ -191,6 +198,11 @@ var RELAY_LIMITS = {
191
198
  agentPayloadMax: 2097152,
192
199
  viewerPayloadMax: 65536,
193
200
  viewersPerSession: 4,
201
+ /** Viewers that haven't been confirmed (see relay-core attachViewer) one client IP may hold in one session. */
202
+ unconfirmedViewersPerIp: 2,
203
+ /** Viewer → agent bytes one viewer connection may send per window. */
204
+ viewerBytesPerWindow: 2097152,
205
+ viewerByteWindowMs: 1e4,
194
206
  idleMs: 12e4,
195
207
  heartbeatMs: 3e4,
196
208
  graceMs: 6e4,
@@ -198,18 +210,27 @@ var RELAY_LIMITS = {
198
210
  billableBytes: 4096,
199
211
  backpressureBytes: 4194304,
200
212
  viewerUpgradesPerMinPerIp: 30,
201
- agentUpgradesPerMinPerKey: 20
213
+ agentUpgradesPerMinPerKey: 20,
214
+ /** Agent upgrades per client IP per minute, counted on refused authorizations only (key brute force). */
215
+ agentAuthFailuresPerMinPerIp: 10
202
216
  };
203
217
  var RELAY_CLOSE = {
204
218
  agentReconnecting: 1012,
205
219
  replaced: 4409,
206
220
  badMessage: 1003,
207
221
  tooBig: 1009,
222
+ policy: 1008,
223
+ tryAgainLater: 1013,
208
224
  /** A refused agent: 4000 + the HTTP status (4401, 4402, 4403, 4429). Clients can't read upgrade statuses. */
209
225
  refused: (status) => 4e3 + status
210
226
  };
211
227
  var C = Type2.Integer({ minimum: 1, maximum: 4294967295 });
212
228
  var strict = { additionalProperties: false };
229
+ var CloseCode = Type2.Union([
230
+ Type2.Integer({ minimum: 1e3, maximum: 1003 }),
231
+ Type2.Integer({ minimum: 1007, maximum: 1014 }),
232
+ Type2.Integer({ minimum: 3e3, maximum: 4999 })
233
+ ]);
213
234
  var RelayToAgentSchema = Type2.Union([
214
235
  Type2.Object({ t: Type2.Literal("open"), c: C }, strict),
215
236
  Type2.Object({ t: Type2.Literal("close"), c: C }, strict),
@@ -218,7 +239,7 @@ var RelayToAgentSchema = Type2.Union([
218
239
  ]);
219
240
  var AgentToRelaySchema = Type2.Union([
220
241
  Type2.Object({ t: Type2.Literal("hello"), expiresAt: Type2.Number(), secret: Type2.String({ minLength: 1, maxLength: 128 }) }, strict),
221
- Type2.Object({ t: Type2.Literal("close"), c: C, code: Type2.Integer() }, strict),
242
+ Type2.Object({ t: Type2.Literal("close"), c: C, code: CloseCode }, strict),
222
243
  Type2.Object({ t: Type2.Literal("pong") }, strict),
223
244
  Type2.Object({ t: Type2.Literal("end") }, strict),
224
245
  Type2.Object({ t: Type2.Literal("event"), name: Type2.String({ maxLength: 64 }) }, strict)
@@ -293,6 +314,18 @@ function b64urlDecode(s) {
293
314
  }
294
315
  }
295
316
  var isJsonPlaintext = (p) => p[0] === 123;
317
+ var PAD_MIN = 256;
318
+ var PAD_MAX = 65536 - 32;
319
+ function padPlaintext(p) {
320
+ if (p.length >= PAD_MAX) return p;
321
+ let size = PAD_MIN;
322
+ while (size < p.length) size *= 2;
323
+ size = Math.min(size, PAD_MAX);
324
+ if (size === p.length) return p;
325
+ const out = new Uint8Array(size).fill(32);
326
+ out.set(p);
327
+ return out;
328
+ }
296
329
  var newConnNonce = () => b64urlEncode(crypto.getRandomValues(new Uint8Array(16)));
297
330
  var msgAad = (sessionId, dir, conn, seq) => enc.encode(`unstuck/1|${sessionId}|${dir}|${conn}|${seq}`);
298
331
  async function sealMsg(key, sessionId, dir, conn, seq, plain) {
@@ -318,6 +351,70 @@ async function openMsg(key, sessionId, dir, conn, sealed) {
318
351
  return null;
319
352
  }
320
353
  }
354
+
355
+ // src/alerts.ts
356
+ var PUB_BYTES = 65;
357
+ var IV_BYTES2 = 12;
358
+ var TAG_BYTES2 = 16;
359
+ var enc2 = new TextEncoder();
360
+ var dec = new TextDecoder();
361
+ var CURVE = { name: "ECDH", namedCurve: "P-256" };
362
+ function newDeviceKeyPair() {
363
+ return crypto.subtle.generateKey(CURVE, false, ["deriveBits"]);
364
+ }
365
+ async function exportDevicePublicKey(k) {
366
+ return b64urlEncode(new Uint8Array(await crypto.subtle.exportKey("raw", k)));
367
+ }
368
+ async function deriveAesKey(priv, pub, deviceId, sessionId, usage) {
369
+ const secret = await crypto.subtle.deriveBits({ name: "ECDH", public: pub }, priv, 256);
370
+ const hkdf = await crypto.subtle.importKey("raw", secret, "HKDF", false, ["deriveKey"]);
371
+ return crypto.subtle.deriveKey(
372
+ { name: "HKDF", hash: "SHA-256", salt: enc2.encode(sessionId), info: enc2.encode(`unstuck/notify/1|${deviceId}`) },
373
+ hkdf,
374
+ { name: "AES-GCM", length: 256 },
375
+ false,
376
+ [usage]
377
+ );
378
+ }
379
+ var aad2 = (sessionId, deviceId) => enc2.encode(`unstuck/notify/1|${sessionId}|${deviceId}`);
380
+ async function sealAlert(devicePublicKey, deviceId, sessionId, p) {
381
+ const raw = b64urlDecode(devicePublicKey);
382
+ if (!raw || raw.length !== PUB_BYTES) throw new Error("invalid device public key");
383
+ const devicePub = await crypto.subtle.importKey("raw", new Uint8Array(raw), CURVE, false, []);
384
+ const eph = await crypto.subtle.generateKey(CURVE, false, ["deriveBits"]);
385
+ const key = await deriveAesKey(eph.privateKey, devicePub, deviceId, sessionId, "encrypt");
386
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES2));
387
+ const ct = new Uint8Array(
388
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad2(sessionId, deviceId) }, key, enc2.encode(JSON.stringify(p)))
389
+ );
390
+ const ephPub = new Uint8Array(await crypto.subtle.exportKey("raw", eph.publicKey));
391
+ const out = new Uint8Array(PUB_BYTES + IV_BYTES2 + ct.length);
392
+ out.set(ephPub);
393
+ out.set(iv, PUB_BYTES);
394
+ out.set(ct, PUB_BYTES + IV_BYTES2);
395
+ return b64urlEncode(out);
396
+ }
397
+ async function openAlert(devicePrivateKey, deviceId, sessionId, blob) {
398
+ const raw = b64urlDecode(blob);
399
+ if (!raw || raw.length < PUB_BYTES + IV_BYTES2 + TAG_BYTES2) return null;
400
+ try {
401
+ const ephPub = await crypto.subtle.importKey("raw", raw.slice(0, PUB_BYTES), CURVE, false, []);
402
+ const key = await deriveAesKey(devicePrivateKey, ephPub, deviceId, sessionId, "decrypt");
403
+ const pt = await crypto.subtle.decrypt(
404
+ { name: "AES-GCM", iv: raw.slice(PUB_BYTES, PUB_BYTES + IV_BYTES2), additionalData: aad2(sessionId, deviceId) },
405
+ key,
406
+ raw.slice(PUB_BYTES + IV_BYTES2)
407
+ );
408
+ const p = JSON.parse(dec.decode(pt));
409
+ return p && typeof p === "object" ? p : null;
410
+ } catch {
411
+ return null;
412
+ }
413
+ }
414
+ function parseAlertFragment(hash) {
415
+ const m = /^#?x=([^.&=]+)\.([^.&=]+)$/.exec(hash);
416
+ return m ? { deviceId: m[1], blob: m[2] } : null;
417
+ }
321
418
  export {
322
419
  EngineToViewerSchema,
323
420
  FRAME_TYPE_JPEG,
@@ -342,15 +439,21 @@ export {
342
439
  decodeFrame,
343
440
  encodeEnvelope,
344
441
  encodeFrame,
442
+ exportDevicePublicKey,
345
443
  importE2eKey,
346
444
  isJsonPlaintext,
347
445
  newConnNonce,
446
+ newDeviceKeyPair,
348
447
  newE2eKey,
349
448
  open,
449
+ openAlert,
350
450
  openMsg,
451
+ padPlaintext,
351
452
  parseAgentToRelay,
453
+ parseAlertFragment,
352
454
  parseRelayToAgent,
353
455
  parseViewerMessage,
354
456
  seal,
457
+ sealAlert,
355
458
  sealMsg
356
459
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velmlabs/unstuck-protocol",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Wire protocol shared by the Unstuck engine, viewer and relays (frames, RPC, end-to-end encryption).",
5
5
  "keywords": [
6
6
  "ai",