kiteline 0.1.0 → 0.3.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.
Files changed (42) hide show
  1. package/README.md +5 -5
  2. package/dist/auth-CYNu-f_h.mjs +104 -0
  3. package/dist/{banner-DJdyE8-G.mjs → banner-C1Jj4n4W.mjs} +112 -41
  4. package/dist/cli.mjs +35 -11
  5. package/dist/client.BPI7fHX3-CSey2FaL.mjs +1437 -0
  6. package/dist/control-BEq2N-wP.mjs +101 -0
  7. package/dist/control-BpOGsRCZ.mjs +1 -0
  8. package/dist/devices-command-Bubh46v1.mjs +76 -0
  9. package/dist/{package-D46-e3oS.mjs → package-BoxBh8MJ.mjs} +1 -1
  10. package/dist/pair-command-DBxw6BfK.mjs +107 -0
  11. package/dist/{service-1H4ozSPX.mjs → service-C2w4PsA8.mjs} +17 -22
  12. package/dist/{src-BnClcgTs.mjs → src-CR4MmTcf.mjs} +1375 -1235
  13. package/dist/web/assets/{MagnifyingGlass.es-DLNPT1gT.js → MagnifyingGlass.es-DH9Sttou.js} +1 -1
  14. package/dist/web/assets/Plus.es-1uU9mFYr.js +1 -0
  15. package/dist/web/assets/composer-BcIdpxHM.js +1 -0
  16. package/dist/web/assets/copy-button-DRCJdYml.js +1 -0
  17. package/dist/web/assets/format-BHMU9nwj.js +9 -0
  18. package/dist/web/assets/index-BRaZDA7B.css +1 -0
  19. package/dist/web/assets/index-TWMUhgcM.js +11 -0
  20. package/dist/web/assets/lazy/{core-DbyPnbRm.js → core-pRLcnHpb.js} +1 -1
  21. package/dist/web/assets/new-BbSpVHmG.js +1 -0
  22. package/dist/web/assets/{prefs-CliZrwNF.js → prefs-q6daUElH.js} +1 -1
  23. package/dist/web/assets/routes-lV-e8sSj.js +1 -0
  24. package/dist/web/assets/s._sessionId-t7H-a-HP.js +45 -0
  25. package/dist/web/assets/settings-CbonbiKb.js +1 -0
  26. package/dist/web/assets/status-CKsUN4Lx.js +1 -0
  27. package/dist/web/index.html +3 -3
  28. package/dist/web/sw.js +1 -1
  29. package/package.json +1 -1
  30. package/dist/auth-YhkfTv6K.mjs +0 -60
  31. package/dist/show-pairing-jhFEXWi7.mjs +0 -30
  32. package/dist/show-pairing-u0LfkF9W.mjs +0 -1
  33. package/dist/web/assets/IconBase.es-CfbvcPwJ.js +0 -9
  34. package/dist/web/assets/composer-B6OuQTWV.js +0 -1
  35. package/dist/web/assets/copy-button-DrJvfi1A.js +0 -1
  36. package/dist/web/assets/index-CA73h-Vn.css +0 -1
  37. package/dist/web/assets/index-Da9GDrpu.js +0 -11
  38. package/dist/web/assets/new-x01_nUpy.js +0 -1
  39. package/dist/web/assets/routes-NIOlnkZY.js +0 -1
  40. package/dist/web/assets/s._sessionId-BtgSN22Q.js +0 -45
  41. package/dist/web/assets/settings-B7yar__r.js +0 -1
  42. package/dist/web/assets/status-BFb0ZUqi.js +0 -1
@@ -1,17 +1,20 @@
1
- import { t as version$1 } from "./package-D46-e3oS.mjs";
2
- import { a as loadToken, i as kitelineHome, n as PairLimiter, o as safeEqual, r as deviceSecret, t as DEVICE_COOKIE } from "./auth-YhkfTv6K.mjs";
3
- import { a as printAlreadyRunning, c as savePairing, f as readSettings, l as SettingsError, o as printBanner, r as buildPairing, s as printSettingsError } from "./banner-DJdyE8-G.mjs";
4
- import { createReadStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
1
+ import { A as runWithSpan, C as isObject$1, D as parseEmptyableJSON, E as overlayProxy, M as toArray, N as value, S as isAsyncIteratorObject, T as onError, _ as toORPCError, a as toHttpPath, b as asyncIteratorWithSpan, c as toStandardLazyRequest, d as HibernationEventIterator, f as flattenHeader, g as isORPCErrorStatus, h as fallbackORPCErrorStatus, i as StandardRPCSerializer, j as setSpanError, k as resolveMaybeOptionalOptions, n as StandardRPCJsonSerializer, p as ORPCError, s as toFetchResponse, u as mapEventIterator, v as NullProtoObj, w as isTypescriptObject, x as intercept, y as ORPC_NAME } from "./client.BPI7fHX3-CSey2FaL.mjs";
2
+ import { t as version$1 } from "./package-BoxBh8MJ.mjs";
3
+ import { a as localAddress, c as safeEqual, i as loadComputerKey, l as saveServerInfo, n as PairLimiter, r as kitelineHome, t as DEVICE_COOKIE } from "./auth-CYNu-f_h.mjs";
4
+ import { _ as RelayPath, a as pairingLinks, b as relaySocketUrl, c as printPairingCode, d as SettingsError, f as command, g as RelayClose, i as dim, l as printSettingsError, m as readSettings, n as addressesFor, o as printAlreadyRunning, r as bold, s as printBanner, t as accent, u as spaced, v as fromBase64Url, x as toBase64Url, y as hostIdFor } from "./banner-C1Jj4n4W.mjs";
5
5
  import { homedir, hostname, platform } from "node:os";
6
+ import { createReadStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
7
  import { dirname, join, resolve } from "node:path";
7
8
  import { fileURLToPath } from "node:url";
9
+ import { randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
8
10
  import { STATUS_CODES, ServerResponse, createServer } from "node:http";
9
11
  import { Http2ServerRequest, constants } from "node:http2";
10
12
  import { Readable } from "node:stream";
11
13
  import { versions } from "node:process";
12
- import { randomUUID } from "node:crypto";
13
14
  import { readdir, stat } from "node:fs/promises";
14
15
  import { getSessionInfo, getSessionMessages, listSessions, query, renameSession, resolveSettings } from "@anthropic-ai/claude-agent-sdk";
16
+ import { EventEmitter } from "node:events";
17
+ import { createInterface } from "node:readline";
15
18
  // ../../node_modules/.pnpm/@hono+node-server@2.1.5_hono@4.13.14/node_modules/@hono/node-server/dist/index.mjs
16
19
  var RequestError = class extends Error {
17
20
  constructor(message, options) {
@@ -2732,724 +2735,625 @@ var SessionTracker = class {
2732
2735
  return this.entries;
2733
2736
  }
2734
2737
  };
2735
- // ../../node_modules/.pnpm/@orpc+shared@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/shared/dist/index.mjs
2736
- function resolveMaybeOptionalOptions(rest) {
2737
- return rest[0] ?? {};
2738
+ // ../../packages/api/src/tunnel/crypto.ts
2739
+ const encoder$1 = new TextEncoder();
2740
+ const decoder$1 = new TextDecoder();
2741
+ const LABEL = encoder$1.encode("kiteline-tunnel-v2");
2742
+ const AAD = encoder$1.encode("kiteline-tunnel-v2/message");
2743
+ const NONCE_BYTES = 16;
2744
+ /** A key's name: a device's id, or a pairing code's. Always 22 base64url characters. */
2745
+ const ID_BYTES = 22;
2746
+ const HELLO_BYTES = 106;
2747
+ /** Handshake frames, then sealed messages. The first byte says which. */
2748
+ const Frame = {
2749
+ Hello: 1,
2750
+ Welcome: 2,
2751
+ Confirm: 3,
2752
+ Sealed: 16
2753
+ };
2754
+ const KINDS = {
2755
+ 1: "device",
2756
+ 2: "pairing"
2757
+ };
2758
+ var HandshakeError = class extends Error {};
2759
+ /** The phone named a key this computer doesn't hold: never paired, removed, or a code that's done. */
2760
+ var UnknownKey = class extends HandshakeError {
2761
+ identity;
2762
+ constructor(identity) {
2763
+ super(identity.kind === "pairing" ? "That pairing code has expired or was already used." : "This phone isn't paired with this computer.");
2764
+ this.identity = identity;
2765
+ }
2766
+ };
2767
+ function concat(...parts) {
2768
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
2769
+ let at = 0;
2770
+ for (const part of parts) {
2771
+ out.set(part, at);
2772
+ at += part.length;
2773
+ }
2774
+ return out;
2738
2775
  }
2739
- function toArray(value) {
2740
- return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
2776
+ function random(length) {
2777
+ return crypto.getRandomValues(new Uint8Array(length));
2741
2778
  }
2742
- const DEFAULT_MAX_BIGINT_DIGITS = 4300;
2743
- const BIGINT_PATTERN = /^-?(?:0|[1-9]\d*)$/;
2744
- function parseBigIntString(value, maxDigits) {
2745
- if ((value.startsWith("-") ? value.length - 1 : value.length) > maxDigits || !BIGINT_PATTERN.test(value)) return;
2746
- return BigInt(value);
2779
+ function base64Url(bytes) {
2780
+ let binary = "";
2781
+ for (const byte of bytes) binary += String.fromCharCode(byte);
2782
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2747
2783
  }
2748
- const ORPC_NAME = "orpc";
2749
- const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
2750
- const ORPC_SHARED_PACKAGE_VERSION = "1.16.1";
2751
- var AbortError = class extends Error {
2752
- constructor(...rest) {
2753
- super(...rest);
2754
- this.name = "AbortError";
2784
+ /**
2785
+ * A one-time pairing code as a tunnel key, and the name it goes by. The name is a hash, so the relay,
2786
+ * which sees it, learns nothing it could pair with.
2787
+ */
2788
+ async function pairingKey(code) {
2789
+ const id = base64Url(await sha256(encoder$1.encode(`kiteline-pair-id/${code}`))).slice(0, ID_BYTES);
2790
+ const key = await crypto.subtle.importKey("raw", encoder$1.encode(code), {
2791
+ name: "HMAC",
2792
+ hash: "SHA-256"
2793
+ }, false, ["sign"]);
2794
+ return {
2795
+ id,
2796
+ secret: new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder$1.encode("kiteline-pair-v2")))
2797
+ };
2798
+ }
2799
+ /** A secret as a key for the handshake. A phone keeps it non-extractable: usable, never readable. */
2800
+ function importSecret(secret, extractable = false) {
2801
+ return crypto.subtle.importKey("raw", secret, {
2802
+ name: "HMAC",
2803
+ hash: "SHA-256"
2804
+ }, extractable, ["sign"]);
2805
+ }
2806
+ async function ephemeral() {
2807
+ const pair = await crypto.subtle.generateKey({
2808
+ name: "ECDH",
2809
+ namedCurve: "P-256"
2810
+ }, false, ["deriveBits"]);
2811
+ const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
2812
+ return {
2813
+ privateKey: pair.privateKey,
2814
+ publicKey
2815
+ };
2816
+ }
2817
+ async function agree(privateKey, peerPublic) {
2818
+ const peer = await crypto.subtle.importKey("raw", peerPublic, {
2819
+ name: "ECDH",
2820
+ namedCurve: "P-256"
2821
+ }, false, []);
2822
+ return new Uint8Array(await crypto.subtle.deriveBits({
2823
+ name: "ECDH",
2824
+ public: peer
2825
+ }, privateKey, 256));
2826
+ }
2827
+ async function sha256(data) {
2828
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
2829
+ }
2830
+ /** Keys for one connection, from the key exchange, the device secret and everything both sides said. */
2831
+ async function schedule(secret, exchanged, transcript) {
2832
+ const ikm = new Uint8Array(await crypto.subtle.sign("HMAC", secret, concat(exchanged, transcript)));
2833
+ const base = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
2834
+ const bits = (label) => crypto.subtle.deriveBits({
2835
+ name: "HKDF",
2836
+ hash: "SHA-256",
2837
+ salt: transcript,
2838
+ info: encoder$1.encode(label)
2839
+ }, base, 256);
2840
+ const aes = async (label) => crypto.subtle.importKey("raw", await bits(label), { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
2841
+ const mac = async (label) => crypto.subtle.importKey("raw", await bits(label), {
2842
+ name: "HMAC",
2843
+ hash: "SHA-256"
2844
+ }, false, ["sign", "verify"]);
2845
+ return {
2846
+ c2s: await aes("client-to-host"),
2847
+ s2c: await aes("host-to-client"),
2848
+ hostConfirm: await mac("host-confirm"),
2849
+ clientConfirm: await mac("client-confirm")
2850
+ };
2851
+ }
2852
+ /** Seals and opens one connection's messages, strictly in order. */
2853
+ var Cipher = class Cipher {
2854
+ sendKey;
2855
+ receiveKey;
2856
+ sent = 0n;
2857
+ received = 0n;
2858
+ constructor(sendKey, receiveKey) {
2859
+ this.sendKey = sendKey;
2860
+ this.receiveKey = receiveKey;
2861
+ }
2862
+ static iv(counter) {
2863
+ const iv = /* @__PURE__ */ new Uint8Array(12);
2864
+ new DataView(iv.buffer).setBigUint64(4, counter);
2865
+ return iv;
2866
+ }
2867
+ /** Callers must seal in the order the frames go out; the counter is taken here. */
2868
+ async seal(plain) {
2869
+ const iv = Cipher.iv(this.sent++);
2870
+ const sealed = await crypto.subtle.encrypt({
2871
+ name: "AES-GCM",
2872
+ iv,
2873
+ additionalData: AAD
2874
+ }, this.sendKey, plain);
2875
+ return concat(Uint8Array.of(Frame.Sealed), new Uint8Array(sealed));
2876
+ }
2877
+ /** Throws on anything altered, replayed, reordered or not from the other end. */
2878
+ async open(frame) {
2879
+ if (frame[0] !== Frame.Sealed) throw new HandshakeError("Expected a sealed message.");
2880
+ const iv = Cipher.iv(this.received++);
2881
+ const plain = await crypto.subtle.decrypt({
2882
+ name: "AES-GCM",
2883
+ iv,
2884
+ additionalData: AAD
2885
+ }, this.receiveKey, frame.subarray(1));
2886
+ return new Uint8Array(plain);
2755
2887
  }
2756
2888
  };
2757
- function once(fn) {
2758
- let cached;
2759
- return () => {
2760
- if (cached) return cached.result;
2761
- const result = fn();
2762
- cached = { result };
2763
- return result;
2764
- };
2765
- }
2766
- function sequential(fn) {
2767
- let lastOperationPromise = Promise.resolve();
2768
- return (...args) => {
2769
- return lastOperationPromise = lastOperationPromise.catch(() => {}).then(() => {
2770
- return fn(...args);
2771
- });
2889
+ /**
2890
+ * The computer's side: looks up the key the phone names, answers its hello, and accepts it only once
2891
+ * it proves it holds that key. Says which key it was, so the computer knows who's at the other end.
2892
+ */
2893
+ async function respond(keyFor, hello, send, next) {
2894
+ if (hello[0] !== Frame.Hello) throw new HandshakeError("That wasn't a handshake.");
2895
+ if (hello[1] !== 2) throw new HandshakeError(`Unsupported tunnel version ${hello[1]}.`);
2896
+ const kind = KINDS[hello[2] ?? 0];
2897
+ const id = decoder$1.decode(hello.subarray(3, 25));
2898
+ if (hello.length !== HELLO_BYTES || !kind || !/^[\w-]{22}$/.test(id)) throw new HandshakeError("That wasn't a handshake.");
2899
+ const identity = {
2900
+ kind,
2901
+ id
2902
+ };
2903
+ const secret = await keyFor(identity);
2904
+ if (!secret) throw new UnknownKey(identity);
2905
+ const name = hello.slice(2, 25);
2906
+ const clientPublic = hello.slice(25, 90);
2907
+ const clientNonce = hello.slice(90);
2908
+ const mine = await ephemeral();
2909
+ const hostNonce = random(NONCE_BYTES);
2910
+ const transcript = await sha256(concat(LABEL, name, clientPublic, clientNonce, mine.publicKey, hostNonce));
2911
+ const keys = await schedule(secret, await agree(mine.privateKey, clientPublic), transcript);
2912
+ const proof = new Uint8Array(await crypto.subtle.sign("HMAC", keys.hostConfirm, transcript));
2913
+ send(concat(Uint8Array.of(Frame.Welcome), mine.publicKey, hostNonce, proof));
2914
+ const confirm = await next();
2915
+ if (confirm[0] !== Frame.Confirm || confirm.length !== 33) throw new HandshakeError("The phone didn't finish the handshake.");
2916
+ if (!await crypto.subtle.verify("HMAC", keys.clientConfirm, confirm.slice(1), transcript)) throw new HandshakeError("This phone isn't paired with this computer.");
2917
+ return {
2918
+ cipher: new Cipher(keys.s2c, keys.c2s),
2919
+ identity
2772
2920
  };
2773
2921
  }
2774
- const SPAN_ERROR_STATUS = 2;
2775
- const GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
2776
- function getGlobalOtelConfig() {
2777
- return globalThis[GLOBAL_OTEL_CONFIG_KEY];
2778
- }
2779
- function startSpan(name, options = {}, context) {
2780
- return (getGlobalOtelConfig()?.tracer)?.startSpan(name, options, context);
2781
- }
2782
- function setSpanError(span, error, options = {}) {
2783
- if (!span) return;
2784
- const exception = toOtelException(error);
2785
- span.recordException(exception);
2786
- if (!options.signal?.aborted || options.signal.reason !== error) span.setStatus({
2787
- code: SPAN_ERROR_STATUS,
2788
- message: exception.message
2789
- });
2790
- }
2791
- function toOtelException(error) {
2792
- if (error instanceof Error) {
2793
- const exception = {
2794
- message: error.message,
2795
- name: error.name,
2796
- stack: error.stack
2797
- };
2798
- if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) exception.code = error.code;
2799
- return exception;
2922
+ // ../../packages/api/src/devices.ts
2923
+ /**
2924
+ * The devices paired with this computer, and the ones asking to be.
2925
+ *
2926
+ * A pairing code works once, for ten minutes, and using it only asks: the device gets in once someone
2927
+ * approves it, in the terminal or on a device that's already paired, after checking both screens show
2928
+ * the same six digits. Each device then gets a key of its own, so any one of them can be removed
2929
+ * without touching the rest. Kept in devices.json (mode 600); codes and requests live in memory only.
2930
+ */
2931
+ const CODE_TTL_MS = 6e5;
2932
+ /** How long a request waits for an answer. */
2933
+ const REQUEST_TTL_MS = 3e5;
2934
+ /** How long an answered request can still be collected by the device that asked. */
2935
+ const COLLECT_MS = 6e5;
2936
+ /** A spent or expired code is remembered a while, to tell "expired" from "never made here". */
2937
+ const CODE_MEMORY_MS = 36e5;
2938
+ const MAX_CODES = 20;
2939
+ const MAX_PENDING = 5;
2940
+ /** Seen this recently counts as active, between one request and the next. */
2941
+ const ACTIVE_MS = 12e4;
2942
+ const SAVE_SEEN_MS = 6e4;
2943
+ const token = (bytes) => randomBytes(bytes).toString("base64url");
2944
+ /** What a device calls itself, made safe to print in a terminal and show in a list. */
2945
+ function cleanName(name) {
2946
+ return (typeof name === "string" ? name.replace(/[\p{C}]/gu, " ").replace(/\s+/g, " ").trim() : "").slice(0, 60) || "A device";
2947
+ }
2948
+ function isStored(value) {
2949
+ const d = value;
2950
+ return !!d && typeof d.id === "string" && /^[\w-]{22}$/.test(d.id) && typeof d.secret === "string" && d.secret.length >= 43 && typeof d.name === "string" && typeof d.pairedAt === "string";
2951
+ }
2952
+ var Devices = class Devices extends EventEmitter {
2953
+ file;
2954
+ devices;
2955
+ keys = /* @__PURE__ */ new Map();
2956
+ codes = /* @__PURE__ */ new Map();
2957
+ asking = /* @__PURE__ */ new Map();
2958
+ claims = /* @__PURE__ */ new Map();
2959
+ live = /* @__PURE__ */ new Map();
2960
+ watchers = /* @__PURE__ */ new Set();
2961
+ saveTimer = null;
2962
+ constructor(file) {
2963
+ super();
2964
+ this.file = file;
2965
+ this.devices = Devices.load(file);
2966
+ setInterval(() => this.sweep(), 15e3).unref();
2800
2967
  }
2801
- return { message: String(error) };
2802
- }
2803
- async function runWithSpan({ name, context, ...options }, fn) {
2804
- const tracer = getGlobalOtelConfig()?.tracer;
2805
- if (!tracer) return fn();
2806
- const callback = async (span) => {
2968
+ static load(file) {
2807
2969
  try {
2808
- return await fn(span);
2809
- } catch (e) {
2810
- setSpanError(span, e, options);
2811
- throw e;
2812
- } finally {
2813
- span.end();
2814
- }
2815
- };
2816
- if (context) return tracer.startActiveSpan(name, options, context, callback);
2817
- else return tracer.startActiveSpan(name, options, callback);
2818
- }
2819
- async function runInSpanContext(span, fn) {
2820
- const otelConfig = getGlobalOtelConfig();
2821
- if (!span || !otelConfig) return fn();
2822
- const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
2823
- return otelConfig.context.with(ctx, fn);
2824
- }
2825
- function isAsyncIteratorObject(maybe) {
2826
- if (!maybe || typeof maybe !== "object") return false;
2827
- return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
2828
- }
2829
- const asyncDisposeSymbol = Symbol.asyncDispose ?? Symbol.for("asyncDispose");
2830
- var AsyncIteratorClass = class {
2831
- #isDone = false;
2832
- #isExecuteComplete = false;
2833
- #cleanup;
2834
- #next;
2835
- constructor(next, cleanup) {
2836
- this.#cleanup = cleanup;
2837
- this.#next = sequential(async () => {
2838
- if (this.#isDone) return {
2839
- done: true,
2840
- value: void 0
2841
- };
2842
- try {
2843
- const result = await next();
2844
- if (result.done) this.#isDone = true;
2845
- return result;
2846
- } catch (err) {
2847
- this.#isDone = true;
2848
- throw err;
2849
- } finally {
2850
- if (this.#isDone && !this.#isExecuteComplete) {
2851
- this.#isExecuteComplete = true;
2852
- await this.#cleanup("next");
2853
- }
2854
- }
2855
- });
2970
+ const data = JSON.parse(readFileSync(file, "utf8"));
2971
+ return Array.isArray(data.devices) ? data.devices.filter(isStored).map((d) => ({
2972
+ ...d,
2973
+ name: cleanName(d.name),
2974
+ lastSeen: typeof d.lastSeen === "string" ? d.lastSeen : null,
2975
+ approvedBy: typeof d.approvedBy === "string" ? d.approvedBy : "terminal",
2976
+ via: d.via === "relay" ? "relay" : "direct"
2977
+ })) : [];
2978
+ } catch {
2979
+ return [];
2980
+ }
2856
2981
  }
2857
- next() {
2858
- return this.#next();
2982
+ get count() {
2983
+ return this.devices.length;
2859
2984
  }
2860
- async return(value) {
2861
- this.#isDone = true;
2862
- if (!this.#isExecuteComplete) {
2863
- this.#isExecuteComplete = true;
2864
- await this.#cleanup("return");
2865
- }
2985
+ names() {
2986
+ return this.devices.map((d) => d.name);
2987
+ }
2988
+ /** A fresh one-time code. Each stands alone: making one leaves the others as they were. */
2989
+ async createCode() {
2990
+ const now = Date.now();
2991
+ const open = [...this.codes.values()].filter((c) => !c.request && c.expiresAt > now);
2992
+ for (const old of open.slice(0, Math.max(0, open.length - MAX_CODES + 1))) old.expiresAt = now;
2993
+ const code = token(16);
2994
+ const { id, secret } = await pairingKey(code);
2995
+ const expiresAt = now + CODE_TTL_MS;
2996
+ this.codes.set(id, {
2997
+ id,
2998
+ key: await importSecret(secret),
2999
+ expiresAt,
3000
+ request: null
3001
+ });
2866
3002
  return {
2867
- done: true,
2868
- value
3003
+ id,
3004
+ code,
3005
+ expiresAt
2869
3006
  };
2870
3007
  }
2871
- async throw(err) {
2872
- this.#isDone = true;
2873
- if (!this.#isExecuteComplete) {
2874
- this.#isExecuteComplete = true;
2875
- await this.#cleanup("throw");
2876
- }
2877
- throw err;
3008
+ /** A code nobody used after all: it stops working now. */
3009
+ cancelCode(id) {
3010
+ const code = this.codes.get(id);
3011
+ if (code && !code.request) code.expiresAt = Math.min(code.expiresAt, Date.now());
2878
3012
  }
2879
- /**
2880
- * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
2881
- */
2882
- async [asyncDisposeSymbol]() {
2883
- this.#isDone = true;
2884
- if (!this.#isExecuteComplete) {
2885
- this.#isExecuteComplete = true;
2886
- await this.#cleanup("dispose");
3013
+ /** A device asks to pair with a code. That spends the code, whatever the answer. */
3014
+ async claim(given, details) {
3015
+ const id = "id" in given ? given.id : (await pairingKey(given.code)).id;
3016
+ const code = this.codes.get(id);
3017
+ const now = Date.now();
3018
+ if (!code) return {
3019
+ ok: false,
3020
+ problem: "unknown"
3021
+ };
3022
+ if (code.request) return {
3023
+ ok: false,
3024
+ problem: "used"
3025
+ };
3026
+ if (code.expiresAt <= now) return {
3027
+ ok: false,
3028
+ problem: "expired"
3029
+ };
3030
+ if (this.pending().length >= MAX_PENDING) return {
3031
+ ok: false,
3032
+ problem: "busy"
3033
+ };
3034
+ const request = {
3035
+ id: token(12),
3036
+ claim: token(24),
3037
+ code: id,
3038
+ name: cleanName(details.name),
3039
+ match: String(randomInt(0, 1e6)).padStart(6, "0"),
3040
+ via: details.via,
3041
+ requestedAt: now,
3042
+ expiresAt: now + REQUEST_TTL_MS,
3043
+ forgetAt: now + REQUEST_TTL_MS + COLLECT_MS,
3044
+ state: "pending",
3045
+ device: null,
3046
+ wake: /* @__PURE__ */ new Set()
3047
+ };
3048
+ code.request = request.id;
3049
+ this.asking.set(request.id, request);
3050
+ this.claims.set(request.claim, request.id);
3051
+ this.emit("request", this.requestInfo(request));
3052
+ this.changed();
3053
+ return {
3054
+ ok: true,
3055
+ request: {
3056
+ id: request.id,
3057
+ claim: request.claim,
3058
+ match: request.match,
3059
+ expiresAt: request.expiresAt
3060
+ }
3061
+ };
3062
+ }
3063
+ /** Where a request stands, for the device that made it; waits up to `waitMs` for an answer. */
3064
+ async status(claim, waitMs = 0, signal) {
3065
+ const request = this.byClaim(claim);
3066
+ if (!request) return null;
3067
+ if (request.state === "pending" && waitMs > 0 && !signal?.aborted) await new Promise((resolve) => {
3068
+ const done = () => {
3069
+ clearTimeout(timer);
3070
+ request.wake.delete(done);
3071
+ signal?.removeEventListener("abort", done);
3072
+ resolve();
3073
+ };
3074
+ const timer = setTimeout(done, Math.max(0, Math.min(waitMs, request.expiresAt - Date.now() + 50)));
3075
+ request.wake.add(done);
3076
+ signal?.addEventListener("abort", done, { once: true });
3077
+ });
3078
+ this.refresh(request);
3079
+ switch (request.state) {
3080
+ case "pending": return {
3081
+ state: "pending",
3082
+ match: request.match,
3083
+ expiresAt: request.expiresAt
3084
+ };
3085
+ case "approved": {
3086
+ const device = request.device && this.devices.find((d) => d.id === request.device?.id);
3087
+ if (!device) return { state: "denied" };
3088
+ return {
3089
+ state: "approved",
3090
+ device: {
3091
+ id: device.id,
3092
+ name: device.name,
3093
+ secret: device.secret
3094
+ }
3095
+ };
3096
+ }
3097
+ default: return { state: request.state };
2887
3098
  }
2888
3099
  }
2889
- [Symbol.asyncIterator]() {
2890
- return this;
3100
+ /** The device that asked changed its mind. */
3101
+ cancel(claim) {
3102
+ const request = this.byClaim(claim);
3103
+ if (request?.state === "pending") this.settle(request, "cancelled", null);
2891
3104
  }
2892
- };
2893
- function asyncIteratorWithSpan({ name, ...options }, iterator) {
2894
- let span;
2895
- return new AsyncIteratorClass(async () => {
2896
- span ??= startSpan(name);
2897
- try {
2898
- const result = await runInSpanContext(span, () => iterator.next());
2899
- span?.addEvent(result.done ? "completed" : "yielded");
2900
- return result;
2901
- } catch (err) {
2902
- setSpanError(span, err, options);
2903
- throw err;
2904
- }
2905
- }, async (reason) => {
2906
- try {
2907
- if (reason !== "next") await runInSpanContext(span, () => iterator.return?.());
2908
- } catch (err) {
2909
- setSpanError(span, err, options);
2910
- throw err;
2911
- } finally {
2912
- span?.end();
3105
+ /** Allow or decline a request. Says so if it was already answered, elsewhere or by the clock. */
3106
+ decide(id, allow, by) {
3107
+ const request = this.asking.get(id);
3108
+ if (!request) return {
3109
+ ok: false,
3110
+ state: "gone"
3111
+ };
3112
+ this.refresh(request);
3113
+ if (request.state !== "pending") return {
3114
+ ok: false,
3115
+ state: request.state
3116
+ };
3117
+ if (!allow) {
3118
+ this.settle(request, "denied", by);
3119
+ return {
3120
+ ok: true,
3121
+ device: null
3122
+ };
2913
3123
  }
2914
- });
2915
- }
2916
- function onError(callback) {
2917
- return async (options, ...rest) => {
3124
+ const device = {
3125
+ id: token(16),
3126
+ name: request.name,
3127
+ secret: token(32),
3128
+ pairedAt: (/* @__PURE__ */ new Date()).toISOString(),
3129
+ lastSeen: null,
3130
+ approvedBy: by.kind === "terminal" ? "terminal" : by.name,
3131
+ via: request.via
3132
+ };
3133
+ this.devices.push(device);
2918
3134
  try {
2919
- return await options.next();
3135
+ this.save();
2920
3136
  } catch (error) {
2921
- await callback(error, options, ...rest);
3137
+ this.devices.pop();
2922
3138
  throw error;
2923
3139
  }
2924
- };
2925
- }
2926
- function intercept(interceptors, options, main) {
2927
- const next = (options2, index) => {
2928
- const interceptor = interceptors[index];
2929
- if (!interceptor) return main(options2);
2930
- return interceptor({
2931
- ...options2,
2932
- next: (newOptions = options2) => next(newOptions, index + 1)
3140
+ request.device = device;
3141
+ this.settle(request, "approved", by);
3142
+ return {
3143
+ ok: true,
3144
+ device: this.info(device)
3145
+ };
3146
+ }
3147
+ byClaim(claim) {
3148
+ const id = this.claims.get(claim);
3149
+ return id ? this.asking.get(id) : void 0;
3150
+ }
3151
+ pending() {
3152
+ return [...this.asking.values()].filter((r) => {
3153
+ this.refresh(r);
3154
+ return r.state === "pending";
2933
3155
  });
2934
- };
2935
- return next(options, 0);
2936
- }
2937
- function parseEmptyableJSON(text) {
2938
- if (!text) return;
2939
- return JSON.parse(text);
2940
- }
2941
- function stringifyJSON(value) {
2942
- return JSON.stringify(value);
2943
- }
2944
- function getConstructor(value) {
2945
- if (!isTypescriptObject(value)) return null;
2946
- return Object.getPrototypeOf(value)?.constructor;
2947
- }
2948
- function isObject$1(value) {
2949
- if (!value || typeof value !== "object") return false;
2950
- const proto = Object.getPrototypeOf(value);
2951
- return proto === Object.prototype || !proto || !proto.constructor;
2952
- }
2953
- function isTypescriptObject(value) {
2954
- return !!value && (typeof value === "object" || typeof value === "function");
2955
- }
2956
- function setOwn(object, key, value) {
2957
- if (key === "__proto__") Object.defineProperty(object, key, {
2958
- value,
2959
- writable: true,
2960
- enumerable: true,
2961
- configurable: true
2962
- });
2963
- else object[key] = value;
2964
- }
2965
- function copyOnWrite(parent, key, original) {
2966
- const value = parent[key];
2967
- if (value !== original) return value;
2968
- let copy;
2969
- if (Array.isArray(value)) copy = value.slice();
2970
- else if (isObject$1(value)) copy = { ...value };
2971
- else return value;
2972
- setOwn(parent, key, copy);
2973
- return copy;
2974
- }
2975
- const NullProtoObj = /* @__PURE__ */ (() => {
2976
- const e = function() {};
2977
- e.prototype = /* @__PURE__ */ Object.create(null);
2978
- Object.freeze(e.prototype);
2979
- return e;
2980
- })();
2981
- function value(value2, ...args) {
2982
- if (typeof value2 === "function") return value2(...args);
2983
- return value2;
2984
- }
2985
- function overlayProxy(target, partial) {
2986
- return new Proxy(typeof target === "function" ? partial : target, {
2987
- get(_, prop) {
2988
- const targetValue = prop in partial ? partial : value(target);
2989
- const v = Reflect.get(targetValue, prop);
2990
- return typeof v === "function" ? v.bind(targetValue) : v;
2991
- },
2992
- has(_, prop) {
2993
- return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
2994
- }
2995
- });
2996
- }
2997
- const REGEXP_FLAGS = /^[dgimsuvy]*$/;
2998
- function isValidRegExpFlags(flags) {
2999
- return REGEXP_FLAGS.test(flags) && new Set(flags).size === flags.length && !(flags.includes("u") && flags.includes("v"));
3000
- }
3001
- function createLazyRegExp(pattern, flags) {
3002
- let compiled;
3003
- let lastIndex = 0;
3004
- const compile = () => {
3005
- if (compiled === void 0) {
3006
- compiled = new RegExp(pattern, flags);
3007
- compiled.lastIndex = lastIndex;
3008
- }
3009
- return compiled;
3010
- };
3011
- return new Proxy(Object.create(RegExp.prototype), {
3012
- get(_, prop) {
3013
- if (prop === Symbol.toStringTag) return "RegExp";
3014
- if (compiled === void 0) {
3015
- if (prop === "lastIndex") return lastIndex;
3016
- if (!(prop in RegExp.prototype)) return;
3017
- }
3018
- const target = compile();
3019
- const value = Reflect.get(target, prop, target);
3020
- return typeof value === "function" && prop !== "constructor" ? value.bind(target) : value;
3021
- },
3022
- set(_, prop, value) {
3023
- if (compiled === void 0 && prop === "lastIndex") {
3024
- lastIndex = value;
3025
- return true;
3026
- }
3027
- const target = compile();
3028
- return Reflect.set(target, prop, value, target);
3029
- },
3030
- has(_, prop) {
3031
- if (compiled === void 0) return prop === "lastIndex" || prop in RegExp.prototype;
3032
- return Reflect.has(compiled, prop);
3033
- }
3034
- });
3035
- }
3036
- function tryDecodeURIComponent$1(value) {
3037
- try {
3038
- return decodeURIComponent(value);
3039
- } catch {
3040
- return value;
3041
3156
  }
3042
- }
3043
- // ../../node_modules/.pnpm/@orpc+client@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/client/dist/shared/client.D_0j2fRr.mjs
3044
- const ORPC_CLIENT_PACKAGE_NAME = "@orpc/client";
3045
- const ORPC_CLIENT_PACKAGE_VERSION = "1.16.1";
3046
- const COMMON_ORPC_ERROR_DEFS = {
3047
- BAD_REQUEST: {
3048
- status: 400,
3049
- message: "Bad Request"
3050
- },
3051
- UNAUTHORIZED: {
3052
- status: 401,
3053
- message: "Unauthorized"
3054
- },
3055
- FORBIDDEN: {
3056
- status: 403,
3057
- message: "Forbidden"
3058
- },
3059
- NOT_FOUND: {
3060
- status: 404,
3061
- message: "Not Found"
3062
- },
3063
- METHOD_NOT_SUPPORTED: {
3064
- status: 405,
3065
- message: "Method Not Supported"
3066
- },
3067
- NOT_ACCEPTABLE: {
3068
- status: 406,
3069
- message: "Not Acceptable"
3070
- },
3071
- TIMEOUT: {
3072
- status: 408,
3073
- message: "Request Timeout"
3074
- },
3075
- CONFLICT: {
3076
- status: 409,
3077
- message: "Conflict"
3078
- },
3079
- PRECONDITION_FAILED: {
3080
- status: 412,
3081
- message: "Precondition Failed"
3082
- },
3083
- PAYLOAD_TOO_LARGE: {
3084
- status: 413,
3085
- message: "Payload Too Large"
3086
- },
3087
- UNSUPPORTED_MEDIA_TYPE: {
3088
- status: 415,
3089
- message: "Unsupported Media Type"
3090
- },
3091
- UNPROCESSABLE_CONTENT: {
3092
- status: 422,
3093
- message: "Unprocessable Content"
3094
- },
3095
- TOO_MANY_REQUESTS: {
3096
- status: 429,
3097
- message: "Too Many Requests"
3098
- },
3099
- CLIENT_CLOSED_REQUEST: {
3100
- status: 499,
3101
- message: "Client Closed Request"
3102
- },
3103
- INTERNAL_SERVER_ERROR: {
3104
- status: 500,
3105
- message: "Internal Server Error"
3106
- },
3107
- NOT_IMPLEMENTED: {
3108
- status: 501,
3109
- message: "Not Implemented"
3110
- },
3111
- BAD_GATEWAY: {
3112
- status: 502,
3113
- message: "Bad Gateway"
3114
- },
3115
- SERVICE_UNAVAILABLE: {
3116
- status: 503,
3117
- message: "Service Unavailable"
3118
- },
3119
- GATEWAY_TIMEOUT: {
3120
- status: 504,
3121
- message: "Gateway Timeout"
3157
+ refresh(request) {
3158
+ if (request.state === "pending" && request.expiresAt <= Date.now()) this.settle(request, "expired", null);
3122
3159
  }
3123
- };
3124
- function fallbackORPCErrorStatus(code, status) {
3125
- return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
3126
- }
3127
- function fallbackORPCErrorMessage(code, message) {
3128
- return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
3129
- }
3130
- let globalORPCErrorConstructors;
3131
- var ORPCError = class ORPCError extends Error {
3132
- defined;
3133
- code;
3134
- status;
3135
- data;
3136
- static {
3137
- const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(`__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`);
3138
- globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet();
3139
- globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
3140
- globalORPCErrorConstructors.add(ORPCError);
3141
- }
3142
- constructor(code, ...rest) {
3143
- const options = resolveMaybeOptionalOptions(rest);
3144
- if (options.status !== void 0 && !isORPCErrorStatus(options.status)) throw new Error("[ORPCError] Invalid error status code.");
3145
- const message = fallbackORPCErrorMessage(code, options.message);
3146
- super(message, options);
3147
- this.code = code;
3148
- this.status = fallbackORPCErrorStatus(code, options.status);
3149
- this.defined = options.defined ?? false;
3150
- this.data = options.data;
3160
+ settle(request, state, by) {
3161
+ request.state = state;
3162
+ request.forgetAt = Date.now() + COLLECT_MS;
3163
+ for (const wake of [...request.wake]) wake();
3164
+ this.emit("settled", {
3165
+ ...this.requestInfo(request),
3166
+ state,
3167
+ by,
3168
+ device: request.device ? this.info(request.device) : null
3169
+ });
3170
+ this.changed();
3151
3171
  }
3152
- toJSON() {
3172
+ requestInfo(r) {
3153
3173
  return {
3154
- defined: this.defined,
3155
- code: this.code,
3156
- status: this.status,
3157
- message: this.message,
3158
- data: this.data
3174
+ id: r.id,
3175
+ name: r.name,
3176
+ match: r.match,
3177
+ via: r.via,
3178
+ code: r.code,
3179
+ requestedAt: r.requestedAt,
3180
+ expiresAt: r.expiresAt
3181
+ };
3182
+ }
3183
+ /** The device a cookie stands for: `<id>.<secret>`. */
3184
+ fromCookie(value) {
3185
+ const [id, secret] = value.split(".");
3186
+ if (!id || !secret) return null;
3187
+ const device = this.devices.find((d) => d.id === id);
3188
+ if (!device) return null;
3189
+ const given = Buffer.from(secret);
3190
+ const held = Buffer.from(device.secret);
3191
+ return given.length === held.length && timingSafeEqual(given, held) ? this.ref(device) : null;
3192
+ }
3193
+ /** A paired device's cookie, for the server to hand over when its pairing is approved. */
3194
+ static cookieFor(device) {
3195
+ return `${device.id}.${device.secret}`;
3196
+ }
3197
+ device(id) {
3198
+ const device = this.devices.find((d) => d.id === id);
3199
+ return device ? this.ref(device) : null;
3200
+ }
3201
+ ref(device) {
3202
+ return {
3203
+ id: device.id,
3204
+ name: device.name
3159
3205
  };
3160
3206
  }
3161
3207
  /**
3162
- * Workaround for Next.js where different contexts use separate
3163
- * dependency graphs, causing multiple ORPCError constructors existing and breaking
3164
- * `instanceof` checks across contexts.
3165
- *
3166
- * This is particularly problematic with "Optimized SSR", where orpc-client
3167
- * executes in one context but is invoked from another. When an error is thrown
3168
- * in the execution context, `instanceof ORPCError` checks fail in the
3169
- * invocation context due to separate class constructors.
3170
- *
3171
- * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
3208
+ * The tunnel key a phone names: its own, while it's paired, or a pairing code's, while that code can
3209
+ * still be used or its request is waiting to be answered and collected.
3172
3210
  */
3173
- static [Symbol.hasInstance](instance) {
3174
- if (globalORPCErrorConstructors.has(this)) {
3175
- const constructor = getConstructor(instance);
3176
- if (constructor && globalORPCErrorConstructors.has(constructor)) return true;
3177
- }
3178
- return super[Symbol.hasInstance](instance);
3179
- }
3180
- };
3181
- function toORPCError(error) {
3182
- return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
3183
- message: "Internal server error",
3184
- cause: error
3185
- });
3186
- }
3187
- function isORPCErrorStatus(status) {
3188
- return status < 200 || status >= 400;
3189
- }
3190
- function isORPCErrorJson(json) {
3191
- if (!isObject$1(json)) return false;
3192
- const validKeys = [
3193
- "defined",
3194
- "code",
3195
- "status",
3196
- "message",
3197
- "data"
3198
- ];
3199
- if (Object.keys(json).some((k) => !validKeys.includes(k))) return false;
3200
- return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && isORPCErrorStatus(json.status) && "message" in json && typeof json.message === "string";
3201
- }
3202
- function createORPCErrorFromJson(json, options = {}) {
3203
- return new ORPCError(json.code, {
3204
- ...options,
3205
- ...json
3206
- });
3207
- }
3208
- // ../../node_modules/.pnpm/@orpc+standard-server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/standard-server/dist/index.mjs
3209
- var EventEncoderError = class extends TypeError {};
3210
- var EventDecoderError = class extends TypeError {};
3211
- var ErrorEvent = class extends Error {
3212
- data;
3213
- constructor(options) {
3214
- super(options?.message ?? "An error event was received", options);
3215
- this.data = options?.data;
3216
- }
3217
- };
3218
- const LINE_ENDING_REGEX$1 = /\r\n|\r(?!\n)|\n/;
3219
- const MESSAGE_DELIMITER_REGEX = /(?:\r\n|\r(?!\n)|\n){2}/;
3220
- const MESSAGE_DELIMITER_GLOBAL_REGEX = /(?:\r\n|\r(?!\n)|\n){2}/g;
3221
- const CR = 13;
3222
- const LF = 10;
3223
- const SPACE = 32;
3224
- function decodeEventMessage(encoded) {
3225
- const message = {
3226
- data: void 0,
3227
- event: void 0,
3228
- id: void 0,
3229
- retry: void 0,
3230
- comments: []
3231
- };
3232
- for (const line of encoded.split(LINE_ENDING_REGEX$1)) {
3233
- if (line === "") continue;
3234
- const index = line.indexOf(":");
3235
- const value = index === -1 ? "" : line.slice(line.charCodeAt(index + 1) === SPACE ? index + 2 : index + 1);
3236
- if (index === 0) {
3237
- message.comments.push(value);
3238
- continue;
3239
- }
3240
- switch (index === -1 ? line : line.slice(0, index)) {
3241
- case "data":
3242
- message.data = message.data === void 0 ? value : `${message.data}
3243
- ${value}`;
3244
- break;
3245
- case "event":
3246
- message.event = value;
3247
- break;
3248
- case "id":
3249
- message.id = value;
3250
- break;
3251
- case "retry": {
3252
- const maybeInteger = Number.parseInt(value, 10);
3253
- if (maybeInteger >= 0 && maybeInteger.toString() === value) message.retry = maybeInteger;
3254
- break;
3211
+ key(identity) {
3212
+ if (identity.kind === "device") {
3213
+ const device = this.devices.find((d) => d.id === identity.id);
3214
+ if (!device) return null;
3215
+ let key = this.keys.get(device.id);
3216
+ if (!key) {
3217
+ key = importSecret(new Uint8Array(Buffer.from(device.secret, "base64url")));
3218
+ this.keys.set(device.id, key);
3255
3219
  }
3256
- }
3220
+ return key;
3221
+ }
3222
+ const code = this.codes.get(identity.id);
3223
+ if (!code) return null;
3224
+ if (!code.request) return code.expiresAt > Date.now() ? code.key : null;
3225
+ const request = this.asking.get(code.request);
3226
+ if (request) this.refresh(request);
3227
+ return request && (request.state === "pending" || request.state === "approved") ? code.key : null;
3228
+ }
3229
+ /** A device is using Kiteline, by a request, a stream or a tunnel. Call what comes back when it's done. */
3230
+ using(id) {
3231
+ const device = this.devices.find((d) => d.id === id);
3232
+ if (!device) return () => {};
3233
+ const wasActive = this.info(device).active;
3234
+ this.live.set(id, (this.live.get(id) ?? 0) + 1);
3235
+ this.seen(device);
3236
+ if (!wasActive) this.changed();
3237
+ let done = false;
3238
+ return () => {
3239
+ if (done) return;
3240
+ done = true;
3241
+ const left = (this.live.get(id) ?? 1) - 1;
3242
+ if (left > 0) this.live.set(id, left);
3243
+ else this.live.delete(id);
3244
+ this.seen(device);
3245
+ };
3257
3246
  }
3258
- return message;
3259
- }
3260
- var EventDecoder = class {
3261
- constructor(options = {}) {
3262
- this.options = options;
3263
- }
3264
- pending = [];
3265
- tail = "";
3266
- discardLeadingLF = false;
3267
- feed(chunk) {
3268
- if (chunk === "") return;
3269
- if (this.discardLeadingLF) {
3270
- this.discardLeadingLF = false;
3271
- if (chunk.charCodeAt(0) === LF) {
3272
- chunk = chunk.slice(1);
3273
- if (chunk === "") return;
3274
- }
3275
- }
3276
- const scan = this.tail + chunk;
3277
- if (!MESSAGE_DELIMITER_REGEX.test(scan)) {
3278
- this.pending.push(chunk);
3279
- this.tail = scan.slice(-3);
3280
- return;
3281
- }
3282
- this.pending.push(chunk);
3283
- const buffered = this.pending.length === 1 ? chunk : this.pending.join("");
3284
- const offset = buffered.length - scan.length;
3285
- const parts = [];
3286
- let start = 0;
3287
- for (const match of scan.matchAll(MESSAGE_DELIMITER_GLOBAL_REGEX)) {
3288
- parts.push(buffered.slice(start, offset + match.index));
3289
- start = offset + match.index + match[0].length;
3290
- }
3291
- const incomplete = buffered.slice(start);
3292
- this.pending.length = 0;
3293
- this.tail = incomplete.slice(-3);
3294
- if (incomplete === "") this.discardLeadingLF = chunk.charCodeAt(chunk.length - 1) === CR;
3295
- else this.pending.push(incomplete);
3296
- for (const encoded of parts) {
3297
- const message = decodeEventMessage(encoded);
3298
- if (this.options.onEvent) this.options.onEvent(message);
3247
+ seen(device) {
3248
+ device.lastSeen = (/* @__PURE__ */ new Date()).toISOString();
3249
+ this.saveTimer ??= setTimeout(() => {
3250
+ try {
3251
+ this.save();
3252
+ } catch {}
3253
+ }, SAVE_SEEN_MS);
3254
+ this.saveTimer.unref?.();
3255
+ }
3256
+ remove(id, by) {
3257
+ const at = this.devices.findIndex((d) => d.id === id);
3258
+ if (at === -1) return null;
3259
+ const [device] = this.devices.splice(at, 1);
3260
+ if (!device) return null;
3261
+ try {
3262
+ this.save();
3263
+ } catch (error) {
3264
+ this.devices.splice(at, 0, device);
3265
+ throw error;
3299
3266
  }
3267
+ this.keys.delete(id);
3268
+ this.live.delete(id);
3269
+ const removed = this.info(device);
3270
+ this.emit("removed", removed, by);
3271
+ this.changed();
3272
+ return removed;
3300
3273
  }
3301
- end() {
3302
- if (this.pending.length !== 0) throw new EventDecoderError("Event Iterator ended before complete");
3274
+ removeAll(by) {
3275
+ for (const device of [...this.devices]) this.remove(device.id, by);
3303
3276
  }
3304
- };
3305
- var EventDecoderStream = class extends TransformStream {
3306
- constructor() {
3307
- let decoder;
3308
- super({
3309
- start(controller) {
3310
- decoder = new EventDecoder({ onEvent: (event) => {
3311
- controller.enqueue(event);
3312
- } });
3313
- },
3314
- transform(chunk) {
3315
- decoder.feed(chunk);
3316
- },
3317
- flush() {
3318
- decoder.end();
3319
- }
3320
- });
3277
+ snapshot(current) {
3278
+ return {
3279
+ devices: this.devices.map((d) => this.info(d, current)),
3280
+ requests: this.pending().map((r) => this.requestInfo(r))
3281
+ };
3321
3282
  }
3322
- };
3323
- const LINE_ENDING_REGEX = /\r\n|[\n\r]/;
3324
- const LINE_ENDING_GLOBAL_REGEX = /\r\n|[\n\r]/g;
3325
- function containsLineBreak(value) {
3326
- return LINE_ENDING_REGEX.test(value);
3327
- }
3328
- function assertEventId(id) {
3329
- if (containsLineBreak(id)) throw new EventEncoderError("Event's id must not contain a carriage return or newline character");
3330
- }
3331
- function assertEventName(event) {
3332
- if (containsLineBreak(event)) throw new EventEncoderError("Event's event must not contain a carriage return or newline character");
3333
- }
3334
- function assertEventRetry(retry) {
3335
- if (!Number.isInteger(retry) || retry < 0) throw new EventEncoderError("Event's retry must be a integer and >= 0");
3336
- }
3337
- function assertEventComment(comment) {
3338
- if (containsLineBreak(comment)) throw new EventEncoderError("Event's comment must not contain a carriage return or newline character");
3339
- }
3340
- function encodeEventData(data) {
3341
- if (data === void 0) return "";
3342
- return `data: ${data.replace(LINE_ENDING_GLOBAL_REGEX, "\ndata: ")}
3343
- `;
3344
- }
3345
- function encodeEventComments(comments) {
3346
- let output = "";
3347
- for (const comment of comments ?? []) {
3348
- assertEventComment(comment);
3349
- output += `: ${comment}
3350
- `;
3351
- }
3352
- return output;
3353
- }
3354
- function encodeEventMessage(message) {
3355
- let output = "";
3356
- output += encodeEventComments(message.comments);
3357
- if (message.event !== void 0) {
3358
- assertEventName(message.event);
3359
- output += `event: ${message.event}
3360
- `;
3361
- }
3362
- if (message.retry !== void 0) {
3363
- assertEventRetry(message.retry);
3364
- output += `retry: ${message.retry}
3365
- `;
3366
- }
3367
- if (message.id !== void 0) {
3368
- assertEventId(message.id);
3369
- output += `id: ${message.id}
3370
- `;
3371
- }
3372
- output += encodeEventData(message.data);
3373
- output += "\n";
3374
- return output;
3375
- }
3376
- const EVENT_SOURCE_META_SYMBOL = Symbol("ORPC_EVENT_SOURCE_META");
3377
- function withEventMeta(container, meta) {
3378
- if (meta.id === void 0 && meta.retry === void 0 && !meta.comments?.length) return container;
3379
- if (meta.id !== void 0) assertEventId(meta.id);
3380
- if (meta.retry !== void 0) assertEventRetry(meta.retry);
3381
- if (meta.comments !== void 0) for (const comment of meta.comments) assertEventComment(comment);
3382
- return new Proxy(container, { get(target, prop, receiver) {
3383
- if (prop === EVENT_SOURCE_META_SYMBOL) return meta;
3384
- return Reflect.get(target, prop, receiver);
3385
- } });
3386
- }
3387
- function getEventMeta(container) {
3388
- return isTypescriptObject(container) ? Reflect.get(container, EVENT_SOURCE_META_SYMBOL) : void 0;
3389
- }
3390
- var HibernationEventIterator = class extends AsyncIteratorClass {
3391
- /**
3392
- * this property is not transferred to the client, so it should be optional for type safety
3393
- */
3394
- hibernationCallback;
3395
- constructor(hibernationCallback) {
3396
- super(async () => {
3397
- throw new Error("Cannot iterate over hibernating iterator directly");
3398
- }, async (reason) => {
3399
- if (reason !== "next") throw new Error("Cannot cleanup hibernating iterator directly");
3400
- });
3401
- this.hibernationCallback = hibernationCallback;
3402
- }
3403
- };
3404
- function generateContentDisposition(filename, disposition = "inline") {
3405
- return `${disposition}; filename="${filename.replace(/[^\x20-\x7E]/g, "_").replace(/"/g, "\\\"")}"; filename*=utf-8''${encodeURIComponent(filename).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(Number.parseInt(hex, 16)))}`;
3406
- }
3407
- function getFilenameFromContentDisposition(contentDisposition) {
3408
- const encodedFilenameStarMatch = contentDisposition.match(/filename\*=(UTF-8'')?([^;]*)/i);
3409
- if (encodedFilenameStarMatch && typeof encodedFilenameStarMatch[2] === "string") return tryDecodeURIComponent$1(encodedFilenameStarMatch[2]);
3410
- const encodedFilenameMatch = contentDisposition.match(/filename="((?:\\"|[^"])*)"/i);
3411
- if (encodedFilenameMatch && typeof encodedFilenameMatch[1] === "string") return encodedFilenameMatch[1].replace(/\\"/g, "\"");
3412
- }
3413
- function flattenHeader(header) {
3414
- if (typeof header === "string" || header === void 0) return header;
3415
- if (header.length === 0) return;
3416
- return header.join(", ");
3417
- }
3418
- // ../../node_modules/.pnpm/@orpc+client@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/client/dist/shared/client.BLtwTQUg.mjs
3419
- function mapEventIterator(iterator, maps) {
3420
- const mapError = async (error) => {
3421
- let mappedError = await maps.error(error);
3422
- if (mappedError !== error) {
3423
- const meta = getEventMeta(error);
3424
- if (meta && isTypescriptObject(mappedError)) mappedError = withEventMeta(mappedError, meta);
3425
- }
3426
- return mappedError;
3427
- };
3428
- return new AsyncIteratorClass(async () => {
3429
- const { done, value } = await (async () => {
3430
- try {
3431
- return await iterator.next();
3432
- } catch (error) {
3433
- throw await mapError(error);
3283
+ /** The devices and requests, again whenever they change, until `signal` aborts. */
3284
+ async *watch(current, signal) {
3285
+ const queue = new AsyncQueue();
3286
+ this.watchers.add(queue);
3287
+ const stop = () => queue.close();
3288
+ signal?.addEventListener("abort", stop, { once: true });
3289
+ let last = "";
3290
+ const fresh = () => {
3291
+ const snapshot = this.snapshot(current);
3292
+ const json = JSON.stringify(snapshot);
3293
+ if (json === last) return null;
3294
+ last = json;
3295
+ return snapshot;
3296
+ };
3297
+ try {
3298
+ yield fresh() ?? this.snapshot(current);
3299
+ for await (const _ of queue) {
3300
+ const snapshot = fresh();
3301
+ if (snapshot) yield snapshot;
3434
3302
  }
3435
- })();
3436
- let mappedValue = await maps.value(value, done);
3437
- if (mappedValue !== value) {
3438
- const meta = getEventMeta(value);
3439
- if (meta && isTypescriptObject(mappedValue)) mappedValue = withEventMeta(mappedValue, meta);
3303
+ } finally {
3304
+ signal?.removeEventListener("abort", stop);
3305
+ this.watchers.delete(queue);
3440
3306
  }
3307
+ }
3308
+ changed() {
3309
+ for (const queue of this.watchers) queue.push(true);
3310
+ }
3311
+ info(d, current) {
3312
+ const seen = d.lastSeen ? Date.parse(d.lastSeen) : 0;
3441
3313
  return {
3442
- done,
3443
- value: mappedValue
3314
+ id: d.id,
3315
+ name: d.name,
3316
+ pairedAt: d.pairedAt,
3317
+ lastSeen: d.lastSeen ? (/* @__PURE__ */ new Date(Math.floor(seen / 6e4) * 6e4)).toISOString() : null,
3318
+ approvedBy: d.approvedBy,
3319
+ via: d.via,
3320
+ active: (this.live.get(d.id) ?? 0) > 0 || !!seen && Date.now() - seen < ACTIVE_MS,
3321
+ current: d.id === current
3444
3322
  };
3445
- }, async () => {
3323
+ }
3324
+ /** Expires what's due; watchers see a device go from active to last seen. */
3325
+ sweep() {
3326
+ const now = Date.now();
3327
+ for (const request of [...this.asking.values()]) if (request.state === "pending") this.refresh(request);
3328
+ else if (request.forgetAt <= now) {
3329
+ this.asking.delete(request.id);
3330
+ this.claims.delete(request.claim);
3331
+ }
3332
+ for (const code of [...this.codes.values()]) if (code.expiresAt + CODE_MEMORY_MS <= now && !(code.request && this.asking.has(code.request))) this.codes.delete(code.id);
3333
+ this.changed();
3334
+ }
3335
+ save() {
3336
+ if (this.saveTimer) clearTimeout(this.saveTimer);
3337
+ this.saveTimer = null;
3338
+ mkdirSync(dirname(this.file), {
3339
+ recursive: true,
3340
+ mode: 448
3341
+ });
3342
+ const temp = `${this.file}.${process.pid}.tmp`;
3343
+ writeFileSync(temp, `${JSON.stringify({
3344
+ version: 1,
3345
+ devices: this.devices
3346
+ }, null, 2)}\n`, { mode: 384 });
3347
+ renameSync(temp, this.file);
3348
+ }
3349
+ /** Writes what's waiting, before the server stops. */
3350
+ flush() {
3351
+ if (!this.saveTimer) return;
3446
3352
  try {
3447
- await iterator.return?.();
3448
- } catch (error) {
3449
- throw await mapError(error);
3450
- }
3451
- });
3452
- }
3353
+ this.save();
3354
+ } catch {}
3355
+ }
3356
+ };
3453
3357
  // ../../node_modules/.pnpm/@orpc+contract@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/contract/dist/shared/contract.D_dZrO__.mjs
3454
3358
  var ValidationError = class extends Error {
3455
3359
  issues;
@@ -3514,508 +3418,6 @@ function isContractProcedure(item) {
3514
3418
  if (item instanceof ContractProcedure) return true;
3515
3419
  return (typeof item === "object" || typeof item === "function") && item !== null && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "errorMap" in item["~orpc"] && "route" in item["~orpc"] && "meta" in item["~orpc"];
3516
3420
  }
3517
- // ../../node_modules/.pnpm/@orpc+standard-server-fetch@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/standard-server-fetch/dist/index.mjs
3518
- function toEventIterator(stream, options = {}) {
3519
- const reader = (stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream()))?.getReader();
3520
- let span;
3521
- let isCancelled = false;
3522
- return new AsyncIteratorClass(async () => {
3523
- span ??= startSpan("consume_event_iterator_stream");
3524
- try {
3525
- while (true) {
3526
- if (reader === void 0) return {
3527
- done: true,
3528
- value: void 0
3529
- };
3530
- const { done, value } = await runInSpanContext(span, () => reader.read());
3531
- if (done) {
3532
- if (isCancelled) throw new AbortError("Stream was cancelled");
3533
- return {
3534
- done: true,
3535
- value: void 0
3536
- };
3537
- }
3538
- switch (value.event ?? (value.data !== void 0 ? "message" : void 0)) {
3539
- case "message": {
3540
- let message = parseEmptyableJSON(value.data);
3541
- if (isTypescriptObject(message)) message = withEventMeta(message, value);
3542
- span?.addEvent("message");
3543
- return {
3544
- done: false,
3545
- value: message
3546
- };
3547
- }
3548
- case "error": {
3549
- let error = new ErrorEvent({ data: parseEmptyableJSON(value.data) });
3550
- error = withEventMeta(error, value);
3551
- span?.addEvent("error");
3552
- throw error;
3553
- }
3554
- case "done":
3555
- case "close": {
3556
- let done2 = parseEmptyableJSON(value.data);
3557
- if (isTypescriptObject(done2)) done2 = withEventMeta(done2, value);
3558
- span?.addEvent("done");
3559
- return {
3560
- done: true,
3561
- value: done2
3562
- };
3563
- }
3564
- default: span?.addEvent("maybe_keepalive");
3565
- }
3566
- }
3567
- } catch (e) {
3568
- if (!(e instanceof ErrorEvent)) setSpanError(span, e, options);
3569
- throw e;
3570
- }
3571
- }, async (reason) => {
3572
- try {
3573
- if (reason !== "next") {
3574
- isCancelled = true;
3575
- span?.addEvent("cancelled");
3576
- }
3577
- await runInSpanContext(span, () => reader?.cancel());
3578
- } catch (e) {
3579
- setSpanError(span, e, options);
3580
- throw e;
3581
- } finally {
3582
- span?.end();
3583
- }
3584
- });
3585
- }
3586
- function toEventStream(iterator, options = {}) {
3587
- const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
3588
- const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
3589
- const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
3590
- const initialCommentEnabled = options.eventIteratorInitialCommentEnabled ?? true;
3591
- const initialComment = options.eventIteratorInitialComment ?? "";
3592
- let cancelled = false;
3593
- let timeout;
3594
- let span;
3595
- return new ReadableStream({
3596
- start(controller) {
3597
- span = startSpan("stream_event_iterator");
3598
- if (initialCommentEnabled) controller.enqueue(encodeEventMessage({ comments: [initialComment] }));
3599
- },
3600
- async pull(controller) {
3601
- try {
3602
- if (keepAliveEnabled) timeout = setInterval(() => {
3603
- controller.enqueue(encodeEventMessage({ comments: [keepAliveComment] }));
3604
- span?.addEvent("keepalive");
3605
- }, keepAliveInterval);
3606
- const value = await runInSpanContext(span, () => iterator.next());
3607
- clearInterval(timeout);
3608
- if (cancelled) return;
3609
- const meta = getEventMeta(value.value);
3610
- if (!value.done || value.value !== void 0 || meta !== void 0) {
3611
- const event = value.done ? "done" : "message";
3612
- controller.enqueue(encodeEventMessage({
3613
- ...meta,
3614
- event,
3615
- data: stringifyJSON(value.value)
3616
- }));
3617
- span?.addEvent(event);
3618
- }
3619
- if (value.done) {
3620
- controller.close();
3621
- span?.end();
3622
- }
3623
- } catch (err) {
3624
- clearInterval(timeout);
3625
- if (cancelled) return;
3626
- if (err instanceof ErrorEvent) {
3627
- controller.enqueue(encodeEventMessage({
3628
- ...getEventMeta(err),
3629
- event: "error",
3630
- data: stringifyJSON(err.data)
3631
- }));
3632
- span?.addEvent("error");
3633
- controller.close();
3634
- } else {
3635
- setSpanError(span, err);
3636
- controller.error(err);
3637
- }
3638
- span?.end();
3639
- }
3640
- },
3641
- async cancel() {
3642
- try {
3643
- cancelled = true;
3644
- clearInterval(timeout);
3645
- span?.addEvent("cancelled");
3646
- await runInSpanContext(span, () => iterator.return?.());
3647
- } catch (e) {
3648
- setSpanError(span, e);
3649
- throw e;
3650
- } finally {
3651
- span?.end();
3652
- }
3653
- }
3654
- }).pipeThrough(new TextEncoderStream());
3655
- }
3656
- function toStandardBody(re, options = {}) {
3657
- return runWithSpan({
3658
- name: "parse_standard_body",
3659
- signal: options.signal
3660
- }, async () => {
3661
- const contentDisposition = re.headers.get("content-disposition");
3662
- if (typeof contentDisposition === "string") {
3663
- const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
3664
- const blob2 = await re.blob();
3665
- return new File([blob2], fileName, { type: blob2.type });
3666
- }
3667
- const contentType = re.headers.get("content-type");
3668
- if (!contentType || contentType.startsWith("application/json")) return parseEmptyableJSON(await re.text());
3669
- if (contentType.startsWith("multipart/form-data")) return await re.formData();
3670
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
3671
- const text = await re.text();
3672
- return new URLSearchParams(text);
3673
- }
3674
- if (contentType.startsWith("text/event-stream")) return toEventIterator(re.body, options);
3675
- if (contentType.startsWith("text/plain")) return await re.text();
3676
- const blob = await re.blob();
3677
- return new File([blob], "blob", { type: blob.type });
3678
- });
3679
- }
3680
- function toFetchBody(body, headers, options = {}) {
3681
- if (body instanceof ReadableStream) return body;
3682
- const currentContentDisposition = headers.get("content-disposition");
3683
- headers.delete("content-type");
3684
- headers.delete("content-disposition");
3685
- if (body === void 0) return;
3686
- if (body instanceof Blob) {
3687
- headers.set("content-type", body.type);
3688
- headers.set("content-length", body.size.toString());
3689
- headers.set("content-disposition", currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : "blob"));
3690
- return body;
3691
- }
3692
- if (body instanceof FormData) return body;
3693
- if (body instanceof URLSearchParams) return body;
3694
- if (isAsyncIteratorObject(body)) {
3695
- headers.set("content-type", "text/event-stream");
3696
- return toEventStream(body, options);
3697
- }
3698
- headers.set("content-type", "application/json");
3699
- return stringifyJSON(body);
3700
- }
3701
- function toStandardHeaders(headers, standardHeaders = {}) {
3702
- headers.forEach((value, key) => {
3703
- if (Array.isArray(standardHeaders[key])) standardHeaders[key].push(value);
3704
- else if (standardHeaders[key] !== void 0) standardHeaders[key] = [standardHeaders[key], value];
3705
- else standardHeaders[key] = value;
3706
- });
3707
- return standardHeaders;
3708
- }
3709
- function toFetchHeaders(headers, fetchHeaders = new Headers()) {
3710
- for (const [key, value] of Object.entries(headers)) if (Array.isArray(value)) for (const v of value) fetchHeaders.append(key, v);
3711
- else if (value !== void 0) fetchHeaders.append(key, value);
3712
- return fetchHeaders;
3713
- }
3714
- function toStandardLazyRequest(request) {
3715
- return {
3716
- url: new URL(request.url),
3717
- signal: request.signal,
3718
- method: request.method,
3719
- body: once(() => toStandardBody(request, { signal: request.signal })),
3720
- get headers() {
3721
- const headers = toStandardHeaders(request.headers);
3722
- Object.defineProperty(this, "headers", {
3723
- value: headers,
3724
- writable: true
3725
- });
3726
- return headers;
3727
- },
3728
- set headers(value) {
3729
- Object.defineProperty(this, "headers", {
3730
- value,
3731
- writable: true
3732
- });
3733
- }
3734
- };
3735
- }
3736
- function toFetchResponse(response, options = {}) {
3737
- const headers = toFetchHeaders(response.headers);
3738
- const body = toFetchBody(response.body, headers, options);
3739
- return new Response(body, {
3740
- headers,
3741
- status: response.status
3742
- });
3743
- }
3744
- // ../../node_modules/.pnpm/@orpc+client@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/client/dist/shared/client.BPI7fHX3.mjs
3745
- const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
3746
- BIGINT: 0,
3747
- DATE: 1,
3748
- NAN: 2,
3749
- UNDEFINED: 3,
3750
- URL: 4,
3751
- REGEXP: 5,
3752
- SET: 6,
3753
- MAP: 7
3754
- };
3755
- const BUILT_IN_TYPES = new Set(Object.values(STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES));
3756
- const SERIALIZED_REGEXP_FORMAT = /^\/(.*)\/([a-z]*)$/;
3757
- function invalidSerializedData(detail) {
3758
- return /* @__PURE__ */ new TypeError(`Invalid RPC serialized data: ${detail}`);
3759
- }
3760
- function invalidSerializedType(type, name, expected) {
3761
- return invalidSerializedData(`type ${type} (${name}) expects ${expected}.`);
3762
- }
3763
- var StandardRPCJsonSerializer = class {
3764
- customSerializers;
3765
- constructor(options = {}) {
3766
- this.customSerializers = options.customJsonSerializers ?? [];
3767
- if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) throw new Error("Custom serializer type must be unique.");
3768
- }
3769
- serialize(data, segments = [], meta = [], maps = [], blobs = []) {
3770
- for (const custom of this.customSerializers) if (custom.condition(data)) {
3771
- const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
3772
- meta.push([custom.type, ...segments]);
3773
- return result;
3774
- }
3775
- if (data instanceof Blob) {
3776
- maps.push(segments);
3777
- blobs.push(data);
3778
- return [
3779
- data,
3780
- meta,
3781
- maps,
3782
- blobs
3783
- ];
3784
- }
3785
- if (typeof data === "bigint") {
3786
- meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
3787
- return [
3788
- data.toString(),
3789
- meta,
3790
- maps,
3791
- blobs
3792
- ];
3793
- }
3794
- if (data instanceof Date) {
3795
- meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
3796
- if (Number.isNaN(data.getTime())) return [
3797
- null,
3798
- meta,
3799
- maps,
3800
- blobs
3801
- ];
3802
- return [
3803
- data.toISOString(),
3804
- meta,
3805
- maps,
3806
- blobs
3807
- ];
3808
- }
3809
- if (Number.isNaN(data)) {
3810
- meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
3811
- return [
3812
- null,
3813
- meta,
3814
- maps,
3815
- blobs
3816
- ];
3817
- }
3818
- if (data instanceof URL) {
3819
- meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
3820
- return [
3821
- data.toString(),
3822
- meta,
3823
- maps,
3824
- blobs
3825
- ];
3826
- }
3827
- if (data instanceof RegExp) {
3828
- meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
3829
- return [
3830
- data.toString(),
3831
- meta,
3832
- maps,
3833
- blobs
3834
- ];
3835
- }
3836
- if (data instanceof Set) {
3837
- const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
3838
- meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
3839
- return result;
3840
- }
3841
- if (data instanceof Map) {
3842
- const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
3843
- meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
3844
- return result;
3845
- }
3846
- if (Array.isArray(data)) return [
3847
- data.map((v, i) => {
3848
- if (v === void 0) {
3849
- meta.push([
3850
- STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED,
3851
- ...segments,
3852
- i
3853
- ]);
3854
- return null;
3855
- }
3856
- return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
3857
- }),
3858
- meta,
3859
- maps,
3860
- blobs
3861
- ];
3862
- if (isObject$1(data)) {
3863
- const json = {};
3864
- for (const k in data) {
3865
- if (k === "toJSON" && typeof data[k] === "function") continue;
3866
- json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
3867
- }
3868
- return [
3869
- json,
3870
- meta,
3871
- maps,
3872
- blobs
3873
- ];
3874
- }
3875
- return [
3876
- data,
3877
- meta,
3878
- maps,
3879
- blobs
3880
- ];
3881
- }
3882
- deserialize(json, meta, maps, getBlob) {
3883
- const ref = { data: json };
3884
- const input = { data: json };
3885
- if (maps && getBlob) maps.forEach((segments, i) => {
3886
- const blob = getBlob(i);
3887
- if (!(blob instanceof Blob)) throw invalidSerializedData(`blob ${i} is not a Blob.`);
3888
- let original = input;
3889
- let currentRef = ref;
3890
- let preSegment = "data";
3891
- segments.forEach((segment) => {
3892
- original = original[preSegment];
3893
- currentRef = copyOnWrite(currentRef, preSegment, original);
3894
- preSegment = segment;
3895
- if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
3896
- });
3897
- currentRef[preSegment] = blob;
3898
- });
3899
- for (const item of meta) {
3900
- const type = item[0];
3901
- const custom = this.customSerializers.find((custom2) => custom2.type === type);
3902
- if (custom === void 0 && !BUILT_IN_TYPES.has(type)) continue;
3903
- let original = input;
3904
- let currentRef = ref;
3905
- let preSegment = "data";
3906
- for (let i = 1; i < item.length; i++) {
3907
- original = original[preSegment];
3908
- currentRef = copyOnWrite(currentRef, preSegment, original);
3909
- preSegment = item[i];
3910
- if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
3911
- }
3912
- if (custom !== void 0) {
3913
- currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
3914
- continue;
3915
- }
3916
- const serialized = currentRef[preSegment];
3917
- switch (type) {
3918
- case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT: {
3919
- if (typeof serialized !== "string") throw invalidSerializedType(type, "bigint", "a string");
3920
- const value = parseBigIntString(serialized, DEFAULT_MAX_BIGINT_DIGITS);
3921
- if (value === void 0) throw invalidSerializedType(type, "bigint", `a decimal integer string of at most ${DEFAULT_MAX_BIGINT_DIGITS} digits`);
3922
- currentRef[preSegment] = value;
3923
- break;
3924
- }
3925
- case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
3926
- if (typeof serialized !== "string" && serialized !== null) throw invalidSerializedType(type, "date", "a string or null");
3927
- currentRef[preSegment] = new Date(serialized ?? NaN);
3928
- break;
3929
- case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
3930
- if (serialized !== null) throw invalidSerializedType(type, "nan", "null");
3931
- currentRef[preSegment] = NaN;
3932
- break;
3933
- case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
3934
- if (serialized !== null) throw invalidSerializedType(type, "undefined", "null");
3935
- currentRef[preSegment] = void 0;
3936
- break;
3937
- case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
3938
- if (typeof serialized !== "string") throw invalidSerializedType(type, "url", "a string");
3939
- currentRef[preSegment] = new URL(serialized);
3940
- break;
3941
- case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
3942
- if (typeof serialized !== "string") throw invalidSerializedType(type, "regexp", "a string");
3943
- const match = serialized.match(SERIALIZED_REGEXP_FORMAT);
3944
- if (match === null || !isValidRegExpFlags(match[2])) throw invalidSerializedData(`type ${type} (regexp) expects a "/pattern/flags" string.`);
3945
- currentRef[preSegment] = createLazyRegExp(match[1], match[2]);
3946
- break;
3947
- }
3948
- case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
3949
- if (!Array.isArray(serialized)) throw invalidSerializedType(type, "set", "an array");
3950
- currentRef[preSegment] = new Set(serialized);
3951
- break;
3952
- case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
3953
- if (!Array.isArray(serialized)) throw invalidSerializedType(type, "map", "an array");
3954
- currentRef[preSegment] = new Map(serialized);
3955
- }
3956
- }
3957
- return ref.data;
3958
- }
3959
- };
3960
- function toHttpPath(path) {
3961
- return `/${path.map(encodeURIComponent).join("/")}`;
3962
- }
3963
- var StandardRPCSerializer = class {
3964
- constructor(jsonSerializer) {
3965
- this.jsonSerializer = jsonSerializer;
3966
- }
3967
- serialize(data) {
3968
- if (isAsyncIteratorObject(data)) return mapEventIterator(data, {
3969
- value: async (value) => this.#serialize(value, false),
3970
- error: async (e) => {
3971
- return new ErrorEvent({
3972
- data: this.#serialize(toORPCError(e).toJSON(), false),
3973
- cause: e
3974
- });
3975
- }
3976
- });
3977
- return this.#serialize(data, true);
3978
- }
3979
- #serialize(data, enableFormData) {
3980
- const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
3981
- const meta = meta_.length === 0 ? void 0 : meta_;
3982
- if (!enableFormData || blobs.length === 0) return {
3983
- json,
3984
- meta
3985
- };
3986
- const form = new FormData();
3987
- form.set("data", stringifyJSON({
3988
- json,
3989
- meta,
3990
- maps
3991
- }));
3992
- blobs.forEach((blob, i) => {
3993
- form.set(i.toString(), blob);
3994
- });
3995
- return form;
3996
- }
3997
- deserialize(data) {
3998
- if (isAsyncIteratorObject(data)) return mapEventIterator(data, {
3999
- value: async (value) => this.#deserialize(value),
4000
- error: async (e) => {
4001
- if (!(e instanceof ErrorEvent)) return e;
4002
- const deserialized = this.#deserialize(e.data);
4003
- if (isORPCErrorJson(deserialized)) return createORPCErrorFromJson(deserialized, { cause: e });
4004
- return new ErrorEvent({
4005
- data: deserialized,
4006
- cause: e
4007
- });
4008
- }
4009
- });
4010
- return this.#deserialize(data);
4011
- }
4012
- #deserialize(data) {
4013
- if (data === void 0) return;
4014
- if (!(data instanceof FormData)) return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
4015
- const serialized = JSON.parse(data.get("data"));
4016
- return this.jsonSerializer.deserialize(serialized.json, serialized.meta ?? [], serialized.maps, (i) => data.get(i.toString()));
4017
- }
4018
- };
4019
3421
  // ../../node_modules/.pnpm/@orpc+contract@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/contract/dist/index.mjs
4020
3422
  function mergeMeta(meta1, meta2) {
4021
3423
  return {
@@ -4216,7 +3618,7 @@ function fallbackContractConfig(key, value) {
4216
3618
  if (value === void 0) return DEFAULT_CONFIG$1[key];
4217
3619
  return value;
4218
3620
  }
4219
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/server/dist/shared/server.DEBcqOjg.mjs
3621
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/shared/server.DEBcqOjg.mjs
4220
3622
  const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
4221
3623
  function lazy(loader, meta = {}) {
4222
3624
  return { [LAZY_SYMBOL]: {
@@ -4489,7 +3891,7 @@ function createContractedProcedure(procedure, contract) {
4489
3891
  meta: contract["~orpc"].meta
4490
3892
  });
4491
3893
  }
4492
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/server/dist/index.mjs
3894
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/index.mjs
4493
3895
  const DEFAULT_CONFIG = {
4494
3896
  initialInputValidationIndex: 0,
4495
3897
  initialOutputValidationIndex: 0,
@@ -10416,6 +9818,49 @@ function refine(fn, _params = {}) {
10416
9818
  function superRefine(fn, params) {
10417
9819
  return /* @__PURE__ */ _superRefine(fn, params);
10418
9820
  }
9821
+ // ../../packages/api/src/routers/devices.ts
9822
+ const id = object({ id: string().min(1).max(64) });
9823
+ const current = (context) => context.caller?.kind === "device" ? context.caller.id : void 0;
9824
+ const actor = (context) => context.caller ?? { kind: "terminal" };
9825
+ const ANSWERED = {
9826
+ approved: "That device was already allowed.",
9827
+ denied: "That request was already declined.",
9828
+ expired: "That request expired before anyone answered it.",
9829
+ cancelled: "That device stopped asking.",
9830
+ gone: "That request isn't waiting any more."
9831
+ };
9832
+ /** The devices paired with this computer, and the ones asking to be: any paired device can answer. */
9833
+ const devicesRouter = {
9834
+ list: protectedProcedure.handler(({ context }) => context.devices.snapshot(current(context))),
9835
+ watch: protectedProcedure.handler(async function* ({ context, signal }) {
9836
+ yield* context.devices.watch(current(context), signal);
9837
+ }),
9838
+ /** A one-time pairing code for another device: a link and its QR code, for ten minutes. */
9839
+ code: protectedProcedure.handler(async ({ context }) => {
9840
+ const code = await context.devices.createCode();
9841
+ return {
9842
+ id: code.id,
9843
+ expiresAt: code.expiresAt,
9844
+ ...context.pairingLink(code.code)
9845
+ };
9846
+ }),
9847
+ cancelCode: protectedProcedure.input(id).handler(({ input, context }) => {
9848
+ context.devices.cancelCode(input.id);
9849
+ }),
9850
+ decide: protectedProcedure.input(object({
9851
+ id: string().min(1).max(64),
9852
+ allow: boolean()
9853
+ })).handler(({ input, context }) => {
9854
+ const result = context.devices.decide(input.id, input.allow, actor(context));
9855
+ if (!result.ok) throw new ORPCError("CONFLICT", { message: ANSWERED[result.state] });
9856
+ return { device: result.device };
9857
+ }),
9858
+ remove: protectedProcedure.input(id).handler(({ input, context }) => {
9859
+ const removed = context.devices.remove(input.id, actor(context));
9860
+ if (!removed) throw new ORPCError("NOT_FOUND", { message: "That device isn't paired any more." });
9861
+ return { device: removed };
9862
+ })
9863
+ };
10419
9864
  // ../../packages/api/src/routers/fs.ts
10420
9865
  const SKIP = /* @__PURE__ */ new Set([
10421
9866
  "node_modules",
@@ -10629,21 +10074,21 @@ const appRouter = {
10629
10074
  home: homedir(),
10630
10075
  platform: platform(),
10631
10076
  version: context.version,
10632
- allowBypass: context.allowBypass,
10633
- pairing: context.pairing
10077
+ allowBypass: context.allowBypass
10634
10078
  })) },
10079
+ devices: devicesRouter,
10635
10080
  sessions: sessionsRouter,
10636
10081
  runs: runsRouter,
10637
10082
  fs: fsRouter
10638
10083
  };
10639
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/server/dist/shared/server.DZ5BIITo.mjs
10084
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/shared/server.DZ5BIITo.mjs
10640
10085
  function resolveFriendlyStandardHandleOptions(options) {
10641
10086
  return {
10642
10087
  ...options,
10643
10088
  context: options.context ?? {}
10644
10089
  };
10645
10090
  }
10646
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/server/dist/shared/server.CMf4nKky.mjs
10091
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/shared/server.CMf4nKky.mjs
10647
10092
  var CompositeStandardHandlerPlugin = class {
10648
10093
  plugins;
10649
10094
  constructor(plugins = []) {
@@ -10822,13 +10267,14 @@ var StandardRPCMatcher = class {
10822
10267
  };
10823
10268
  var StandardRPCHandler = class extends StandardHandler {
10824
10269
  constructor(router, options = {}) {
10825
- const serializer = new StandardRPCSerializer(new StandardRPCJsonSerializer(options));
10270
+ const jsonSerializer = new StandardRPCJsonSerializer(options);
10271
+ const serializer = new StandardRPCSerializer(jsonSerializer);
10826
10272
  const matcher = new StandardRPCMatcher(options);
10827
10273
  const codec = new StandardRPCCodec(serializer);
10828
10274
  super(router, matcher, codec, options);
10829
10275
  }
10830
10276
  };
10831
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/server/dist/shared/server.TEVCLCFC.mjs
10277
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/shared/server.TEVCLCFC.mjs
10832
10278
  const STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL = Symbol("STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT");
10833
10279
  var StrictGetMethodPlugin = class {
10834
10280
  error;
@@ -10860,7 +10306,7 @@ var StrictGetMethodPlugin = class {
10860
10306
  });
10861
10307
  }
10862
10308
  };
10863
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/server/dist/adapters/fetch/index.mjs
10309
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/adapters/fetch/index.mjs
10864
10310
  var CompositeFetchHandlerPlugin = class extends CompositeStandardHandlerPlugin {
10865
10311
  initRuntimeAdapter(options) {
10866
10312
  for (const plugin of this.plugins) plugin.initRuntimeAdapter?.(options);
@@ -13211,7 +12657,7 @@ const colorStatus = async (status) => {
13211
12657
  }
13212
12658
  return `${status}`;
13213
12659
  };
13214
- async function log(fn, prefix, method, path, status = 0, elapsed) {
12660
+ async function log$1(fn, prefix, method, path, status = 0, elapsed) {
13215
12661
  fn(prefix === "<--" ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`);
13216
12662
  }
13217
12663
  /**
@@ -13234,17 +12680,505 @@ const logger = (fn = console.log) => {
13234
12680
  return async function logger(c, next) {
13235
12681
  const { method, url } = c.req;
13236
12682
  const path = url.slice(url.indexOf("/", 8));
13237
- await log(fn, "<--", method, path);
12683
+ await log$1(fn, "<--", method, path);
13238
12684
  const start = Date.now();
13239
12685
  await next();
13240
- await log(fn, "-->", method, path, c.res.status, time(start));
12686
+ await log$1(fn, "-->", method, path, c.res.status, time(start));
13241
12687
  };
13242
12688
  };
12689
+ // src/console.ts
12690
+ const say = (...lines) => console.log(lines.map((line) => line ? ` ${line}` : "").join("\n"));
12691
+ /**
12692
+ * Kiteline in a terminal, like pairing Bluetooth: it shows a pairing code while nothing is paired,
12693
+ * makes a fresh one whenever you press Enter, and asks about each device that wants to pair, with
12694
+ * the digits its screen shows so you know it's yours.
12695
+ */
12696
+ function startConsole({ devices, pairingLink }) {
12697
+ const rl = createInterface({
12698
+ input: process.stdin,
12699
+ output: process.stdout,
12700
+ terminal: true
12701
+ });
12702
+ rl.on("SIGINT", () => process.kill(process.pid, "SIGINT"));
12703
+ const waiting = [];
12704
+ let asking = null;
12705
+ const showCode = async () => {
12706
+ const code = await devices.createCode();
12707
+ printPairingCode({
12708
+ url: pairingLink(code.code).url,
12709
+ expiresAt: code.expiresAt
12710
+ }, { more: "Press Enter for a new code." });
12711
+ };
12712
+ const ask = () => {
12713
+ if (asking) return;
12714
+ const next = waiting.shift();
12715
+ if (!next) return;
12716
+ asking = next;
12717
+ say("", `${accent("◆")} ${bold(next.name)} wants to pair${next.via === "relay" ? ", through the relay" : ""}.`, ` Allow it only if it's yours and its screen shows ${bold(spaced(next.match))}.`);
12718
+ rl.setPrompt(` Allow it? ${dim("y or n")} `);
12719
+ rl.prompt();
12720
+ };
12721
+ devices.on("request", (request) => {
12722
+ waiting.push(request);
12723
+ ask();
12724
+ });
12725
+ devices.on("settled", (request) => {
12726
+ const at = waiting.findIndex((r) => r.id === request.id);
12727
+ if (at !== -1) waiting.splice(at, 1);
12728
+ if (asking?.id === request.id) {
12729
+ asking = null;
12730
+ console.log();
12731
+ if (request.state === "approved") say(`${request.name} was allowed${request.by?.kind === "device" ? ` on ${request.by.name}` : ""}.`, "");
12732
+ else if (request.state === "denied") say(`${request.name} was declined${request.by?.kind === "device" ? ` on ${request.by.name}` : ""}.`, "");
12733
+ else if (request.state === "expired") say(`${request.name} waited too long; ask it to try again.`, "");
12734
+ else say(`${request.name} stopped asking.`, "");
12735
+ ask();
12736
+ return;
12737
+ }
12738
+ if (request.state === "approved" && request.by?.kind === "device") say(`${accent("◆")} Paired ${bold(request.name)}, allowed on ${request.by.name}.`, "");
12739
+ });
12740
+ devices.on("removed", (device, by) => {
12741
+ say(`Removed ${device.name}${by.kind === "device" && by.id !== device.id ? `, on ${by.name}` : ""}.`, "");
12742
+ });
12743
+ rl.on("line", (line) => {
12744
+ const answer = line.trim().toLowerCase();
12745
+ const request = asking;
12746
+ if (request) {
12747
+ if (![
12748
+ "y",
12749
+ "yes",
12750
+ "n",
12751
+ "no"
12752
+ ].includes(answer)) {
12753
+ rl.prompt();
12754
+ return;
12755
+ }
12756
+ const allow = answer.startsWith("y");
12757
+ asking = null;
12758
+ const result = devices.decide(request.id, allow, { kind: "terminal" });
12759
+ if (!result.ok) say(`Too late: that request was ${result.state === "gone" ? "already answered" : result.state}.`, "");
12760
+ else if (allow) say(`${accent("◆")} Paired ${bold(request.name)}.`, "");
12761
+ else say(`Declined ${request.name}.`, "");
12762
+ ask();
12763
+ return;
12764
+ }
12765
+ if (!answer) showCode();
12766
+ });
12767
+ if (devices.count === 0) showCode();
12768
+ else {
12769
+ const names = devices.names();
12770
+ say(`${dim("Paired")} ${names.slice(0, 3).join(", ")}${names.length > 3 ? ` and ${names.length - 3} more` : ""}`, "", dim("Press Enter to pair another device."), "");
12771
+ }
12772
+ }
13243
12773
  // src/context.ts
13244
- function createContext({ authed, shared }) {
12774
+ function createContext({ caller, shared }) {
13245
12775
  return {
13246
12776
  ...shared,
13247
- authed
12777
+ caller,
12778
+ authed: caller !== null
12779
+ };
12780
+ }
12781
+ // ../../packages/api/src/tunnel/messages.ts
12782
+ /**
12783
+ * What travels inside the sealed tunnel: HTTP requests from the phone and streamed responses from
12784
+ * the computer, several at once, each on its own numbered stream.
12785
+ */
12786
+ const Msg = {
12787
+ Request: 1,
12788
+ Body: 2,
12789
+ End: 3,
12790
+ Cancel: 4,
12791
+ Response: 17,
12792
+ Data: 18,
12793
+ Done: 19,
12794
+ Fail: 20,
12795
+ Ping: 32,
12796
+ Pong: 33
12797
+ };
12798
+ /** Body and response chunks stay under this, so one big reply never holds up the others for long. */
12799
+ const CHUNK = 65536;
12800
+ const encoder = new TextEncoder();
12801
+ const decoder = new TextDecoder();
12802
+ function pack(type, stream, payload) {
12803
+ const head = /* @__PURE__ */ new Uint8Array(5);
12804
+ head[0] = type;
12805
+ new DataView(head.buffer).setUint32(1, stream);
12806
+ return payload?.length ? concat(head, payload) : head;
12807
+ }
12808
+ function unpack(message) {
12809
+ if (message.length < 5) throw new Error("A tunnel message was cut short.");
12810
+ return {
12811
+ type: message[0],
12812
+ stream: new DataView(message.buffer, message.byteOffset, message.byteLength).getUint32(1),
12813
+ payload: message.subarray(5)
12814
+ };
12815
+ }
12816
+ const parseJson = (payload) => JSON.parse(decoder.decode(payload));
12817
+ const text = (value) => encoder.encode(value);
12818
+ // ../../packages/api/src/tunnel/socket.ts
12819
+ /** A WebSocket's messages as two in-order queues: frames for the tunnel, text for the relay's notes. */
12820
+ var FrameSocket = class {
12821
+ ws;
12822
+ frames = [];
12823
+ texts = [];
12824
+ waiting = [];
12825
+ ended = null;
12826
+ closeListeners = /* @__PURE__ */ new Set();
12827
+ constructor(ws) {
12828
+ this.ws = ws;
12829
+ ws.binaryType = "arraybuffer";
12830
+ ws.addEventListener("message", (event) => {
12831
+ const data = event.data;
12832
+ if (typeof data === "string") this.deliver(false, data);
12833
+ else if (data instanceof ArrayBuffer) this.deliver(true, new Uint8Array(data));
12834
+ });
12835
+ ws.addEventListener("close", (event) => this.end(event.code, event.reason));
12836
+ ws.addEventListener("error", () => this.end(1006, "connection error"));
12837
+ }
12838
+ get closed() {
12839
+ return this.ended;
12840
+ }
12841
+ onClose(listener) {
12842
+ if (this.ended) listener(this.ended.code, this.ended.reason);
12843
+ else this.closeListeners.add(listener);
12844
+ }
12845
+ deliver(binary, value) {
12846
+ const at = this.waiting.findIndex((w) => w.binary === binary);
12847
+ if (at !== -1) {
12848
+ const [waiter] = this.waiting.splice(at, 1);
12849
+ waiter?.resolve(value);
12850
+ } else if (binary) this.frames.push(value);
12851
+ else this.texts.push(value);
12852
+ }
12853
+ end(code, reason) {
12854
+ if (this.ended) return;
12855
+ this.ended = {
12856
+ code,
12857
+ reason
12858
+ };
12859
+ const error = new SocketClosed(code, reason);
12860
+ for (const waiter of this.waiting.splice(0)) waiter.reject(error);
12861
+ for (const listener of this.closeListeners) listener(code, reason);
12862
+ this.closeListeners.clear();
12863
+ }
12864
+ take(binary, timeoutMs) {
12865
+ const queued = binary ? this.frames.shift() : this.texts.shift();
12866
+ if (queued !== void 0) return Promise.resolve(queued);
12867
+ if (this.ended) return Promise.reject(new SocketClosed(this.ended.code, this.ended.reason));
12868
+ return new Promise((resolve, reject) => {
12869
+ const waiter = {
12870
+ binary,
12871
+ resolve,
12872
+ reject
12873
+ };
12874
+ this.waiting.push(waiter);
12875
+ if (timeoutMs !== void 0) setTimeout(() => {
12876
+ const at = this.waiting.indexOf(waiter);
12877
+ if (at === -1) return;
12878
+ this.waiting.splice(at, 1);
12879
+ reject(new SocketTimeout());
12880
+ }, timeoutMs);
12881
+ });
12882
+ }
12883
+ next(timeoutMs) {
12884
+ return this.take(true, timeoutMs);
12885
+ }
12886
+ nextText(timeoutMs) {
12887
+ return this.take(false, timeoutMs);
12888
+ }
12889
+ send(frame) {
12890
+ if (this.ws.readyState === WebSocket.OPEN) this.ws.send(frame);
12891
+ }
12892
+ close(code, reason) {
12893
+ try {
12894
+ this.ws.close(code, reason.slice(0, 120));
12895
+ } catch {
12896
+ this.ws.close();
12897
+ }
12898
+ this.end(code, reason);
12899
+ }
12900
+ };
12901
+ var SocketClosed = class extends Error {
12902
+ code;
12903
+ reason;
12904
+ constructor(code, reason) {
12905
+ super(reason || `Connection closed (${code}).`);
12906
+ this.code = code;
12907
+ this.reason = reason;
12908
+ }
12909
+ };
12910
+ var SocketTimeout = class extends Error {
12911
+ constructor() {
12912
+ super("Timed out.");
12913
+ }
12914
+ };
12915
+ // ../../packages/api/src/tunnel/host.ts
12916
+ /** More than the biggest real request: six photos at the limit, base64 in JSON. */
12917
+ const MAX_BODY = 41943040;
12918
+ const HANDSHAKE_MS = 2e4;
12919
+ /**
12920
+ * The computer's end of one phone's tunnel. Answers the handshake with the key the phone names,
12921
+ * refuses a phone that can't prove it, then turns each request into a `Request` for `handle`, saying
12922
+ * who it's from, and streams the answer back.
12923
+ */
12924
+ async function serveTunnel(ws, keyFor, handle, hooks = {}) {
12925
+ const socket = new FrameSocket(ws);
12926
+ let cipher;
12927
+ let identity;
12928
+ try {
12929
+ const hello = await socket.next(HANDSHAKE_MS);
12930
+ ({cipher, identity} = await respond(keyFor, hello, (frame) => socket.send(frame), () => socket.next(HANDSHAKE_MS)));
12931
+ } catch (error) {
12932
+ const reason = error instanceof UnknownKey && error.identity.kind === "pairing" ? "code expired" : "not paired";
12933
+ const unpaired = error instanceof HandshakeError;
12934
+ socket.close(unpaired ? RelayClose.NotPaired : RelayClose.BadRequest, unpaired ? reason : "bad handshake");
12935
+ return;
12936
+ }
12937
+ const who = identity;
12938
+ hooks.opened?.(who, (code, reason) => socket.close(code, reason));
12939
+ socket.onClose(() => hooks.closed?.(who));
12940
+ const streams = /* @__PURE__ */ new Map();
12941
+ let sending = Promise.resolve();
12942
+ let closed = false;
12943
+ socket.onClose(() => {
12944
+ closed = true;
12945
+ for (const stream of streams.values()) stream.abort.abort();
12946
+ streams.clear();
12947
+ });
12948
+ const post = (type, stream, payload) => {
12949
+ const message = pack(type, stream, payload);
12950
+ sending = sending.then(async () => {
12951
+ if (!closed) socket.send(await cipher.seal(message));
12952
+ });
12953
+ sending.catch(() => socket.close(RelayClose.BadRequest, "send failed"));
12954
+ return sending;
12955
+ };
12956
+ const run = async (id, stream) => {
12957
+ const { head } = stream;
12958
+ try {
12959
+ const body = head.body && !["GET", "HEAD"].includes(head.method) ? joinChunks(stream.chunks, stream.size) : null;
12960
+ const response = await handle(new Request(new URL(head.path, "http://kiteline.tunnel"), {
12961
+ method: head.method,
12962
+ headers: head.headers,
12963
+ body,
12964
+ signal: stream.abort.signal
12965
+ }), who);
12966
+ if (!streams.has(id)) return;
12967
+ await post(Msg.Response, id, new TextEncoder().encode(JSON.stringify({
12968
+ status: response.status,
12969
+ headers: [...response.headers]
12970
+ })));
12971
+ if (response.body) {
12972
+ const reader = response.body.getReader();
12973
+ stream.abort.signal.addEventListener("abort", () => void reader.cancel().catch(() => {}), { once: true });
12974
+ for (;;) {
12975
+ const { done, value } = await reader.read();
12976
+ if (done || !streams.has(id)) break;
12977
+ for (let at = 0; at < value.length; at += CHUNK) await post(Msg.Data, id, value.subarray(at, at + CHUNK));
12978
+ }
12979
+ }
12980
+ if (streams.delete(id)) await post(Msg.Done, id);
12981
+ } catch (error) {
12982
+ if (streams.delete(id) && !stream.abort.signal.aborted) await post(Msg.Fail, id, text(error instanceof Error ? error.message : String(error)));
12983
+ }
12984
+ };
12985
+ try {
12986
+ for (;;) {
12987
+ const frame = await socket.next();
12988
+ const { type, stream: id, payload } = unpack(await cipher.open(frame));
12989
+ switch (type) {
12990
+ case Msg.Ping:
12991
+ post(Msg.Pong, 0);
12992
+ break;
12993
+ case Msg.Request: {
12994
+ if (streams.has(id)) break;
12995
+ const stream = {
12996
+ head: parseJson(payload),
12997
+ chunks: [],
12998
+ size: 0,
12999
+ abort: new AbortController()
13000
+ };
13001
+ streams.set(id, stream);
13002
+ if (!stream.head.body) run(id, stream);
13003
+ break;
13004
+ }
13005
+ case Msg.Body: {
13006
+ const stream = streams.get(id);
13007
+ if (!stream) break;
13008
+ stream.size += payload.length;
13009
+ if (stream.size > MAX_BODY) {
13010
+ streams.delete(id);
13011
+ post(Msg.Fail, id, text("That's too big to send."));
13012
+ break;
13013
+ }
13014
+ stream.chunks.push(payload.slice());
13015
+ break;
13016
+ }
13017
+ case Msg.End: {
13018
+ const stream = streams.get(id);
13019
+ if (stream) run(id, stream);
13020
+ break;
13021
+ }
13022
+ case Msg.Cancel: {
13023
+ const stream = streams.get(id);
13024
+ streams.delete(id);
13025
+ stream?.abort.abort();
13026
+ break;
13027
+ }
13028
+ }
13029
+ }
13030
+ } catch {
13031
+ socket.close(1e3, "closing");
13032
+ }
13033
+ }
13034
+ function joinChunks(chunks, size) {
13035
+ const out = new Uint8Array(size);
13036
+ let at = 0;
13037
+ for (const chunk of chunks) {
13038
+ out.set(chunk, at);
13039
+ at += chunk.length;
13040
+ }
13041
+ return out;
13042
+ }
13043
+ // src/relay.ts
13044
+ /** The relay's secret for this computer, kept beside its other keys. Its hash is our address. */
13045
+ function relaySecret(home) {
13046
+ const file = join(home, "relay.json");
13047
+ try {
13048
+ const stored = JSON.parse(readFileSync(file, "utf8"));
13049
+ if (typeof stored.secret === "string" && /^[\w-]{43}$/.test(stored.secret)) return stored.secret;
13050
+ } catch {}
13051
+ const secret = toBase64Url(randomBytes(32));
13052
+ mkdirSync(home, {
13053
+ recursive: true,
13054
+ mode: 448
13055
+ });
13056
+ writeFileSync(file, `${JSON.stringify({
13057
+ secret,
13058
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
13059
+ }, null, 2)}\n`, { mode: 384 });
13060
+ return secret;
13061
+ }
13062
+ /**
13063
+ * Only the API and the pairing check go through, and only what each key is for: a paired phone's
13064
+ * reaches the API, a pairing code's reaches nothing but asking to pair. The app comes from the relay.
13065
+ */
13066
+ function allowed(request, identity) {
13067
+ const { pathname } = new URL(request.url);
13068
+ const { method } = request;
13069
+ if (pathname === "/auth/status") return method === "GET";
13070
+ if (identity.kind === "pairing") {
13071
+ if (pathname === "/auth/pair") return method === "POST";
13072
+ return /^\/auth\/pair\/[\w-]+$/.test(pathname) && (method === "GET" || method === "DELETE");
13073
+ }
13074
+ if (pathname === "/auth/logout") return method === "POST";
13075
+ return (method === "POST" || method === "GET") && pathname.startsWith("/rpc/");
13076
+ }
13077
+ async function hostAddress(home) {
13078
+ return hostIdFor(fromBase64Url(relaySecret(home)));
13079
+ }
13080
+ async function startRelay(options) {
13081
+ const secret = relaySecret(options.home);
13082
+ const hostId = await hostIdFor(fromBase64Url(secret));
13083
+ const open = /* @__PURE__ */ new Map();
13084
+ const keyOf = (identity) => `${identity.kind}:${identity.id}`;
13085
+ const handle = async (request, identity) => {
13086
+ if (!allowed(request, identity)) return new Response("Not through the relay.", { status: 404 });
13087
+ const headers = new Headers(request.headers);
13088
+ headers.delete("cookie");
13089
+ headers.delete("authorization");
13090
+ return options.handle(new Request(request, { headers }), identity);
13091
+ };
13092
+ /** Keeps each open tunnel by its key, to end them when a device is removed. Returns the cleanup. */
13093
+ const track = (identity, close) => {
13094
+ const key = keyOf(identity);
13095
+ const closers = open.get(key) ?? /* @__PURE__ */ new Set();
13096
+ open.set(key, closers);
13097
+ closers.add(close);
13098
+ const release = options.track?.(identity);
13099
+ const limit = identity.kind === "pairing" ? setTimeout(() => close(RelayClose.NotPaired, "code expired"), 18e5) : null;
13100
+ limit?.unref();
13101
+ return () => {
13102
+ if (limit) clearTimeout(limit);
13103
+ closers.delete(close);
13104
+ if (!closers.size) open.delete(key);
13105
+ release?.();
13106
+ };
13107
+ };
13108
+ let attempt = 0;
13109
+ let connected = false;
13110
+ let stopped = false;
13111
+ let socket = null;
13112
+ let silence = null;
13113
+ const connect = () => {
13114
+ if (stopped) return;
13115
+ const ws = new WebSocket(relaySocketUrl(options.relay, RelayPath.host));
13116
+ socket = ws;
13117
+ let lastHeard = Date.now();
13118
+ ws.addEventListener("open", () => {
13119
+ ws.send(JSON.stringify({
13120
+ t: "hello",
13121
+ secret,
13122
+ version: options.version
13123
+ }));
13124
+ silence = setInterval(() => {
13125
+ if (Date.now() - lastHeard > 75e3) ws.close();
13126
+ else ws.send(JSON.stringify({ t: "ping" }));
13127
+ }, 3e4);
13128
+ });
13129
+ ws.addEventListener("message", (event) => {
13130
+ lastHeard = Date.now();
13131
+ let message;
13132
+ try {
13133
+ message = JSON.parse(String(event.data));
13134
+ } catch {
13135
+ return;
13136
+ }
13137
+ if (message.t === "ready") {
13138
+ attempt = 0;
13139
+ if (!connected) options.log("Connected to the relay: phones can reach this computer from anywhere.");
13140
+ connected = true;
13141
+ } else if (message.t === "open" && /^[\w-]{22}$/.test(message.channel)) {
13142
+ const data = new WebSocket(relaySocketUrl(options.relay, RelayPath.data + message.channel));
13143
+ let done;
13144
+ serveTunnel(data, options.keyFor, handle, {
13145
+ opened: (identity, close) => {
13146
+ done = track(identity, close);
13147
+ },
13148
+ closed: () => done?.()
13149
+ });
13150
+ }
13151
+ });
13152
+ ws.addEventListener("close", (event) => {
13153
+ if (silence) clearInterval(silence);
13154
+ if (stopped) return;
13155
+ if (connected) options.log("Lost the relay; reconnecting.");
13156
+ else if (attempt === 0) {
13157
+ const why = event.code === RelayClose.TooMany ? "it's full right now" : "couldn't reach it";
13158
+ options.log(`The relay at ${options.relay} isn't answering (${why}); retrying in the background.`);
13159
+ }
13160
+ connected = false;
13161
+ attempt++;
13162
+ const wait = Math.min(3e4, 1e3 * 2 ** Math.min(attempt, 5)) + Math.random() * 1e3;
13163
+ setTimeout(connect, wait).unref();
13164
+ });
13165
+ ws.addEventListener("error", () => {});
13166
+ };
13167
+ connect();
13168
+ return {
13169
+ hostId,
13170
+ get connected() {
13171
+ return connected;
13172
+ },
13173
+ /** Ends every tunnel open with this key, say because its device was just removed. */
13174
+ disconnect(identity, reason = "not paired") {
13175
+ for (const close of [...open.get(keyOf(identity)) ?? []]) close(RelayClose.NotPaired, reason);
13176
+ },
13177
+ stop() {
13178
+ stopped = true;
13179
+ if (silence) clearInterval(silence);
13180
+ socket?.close();
13181
+ }
13248
13182
  };
13249
13183
  }
13250
13184
  // src/index.ts
@@ -13259,16 +13193,24 @@ try {
13259
13193
  }
13260
13194
  const { port, host, allowBypass } = settings;
13261
13195
  const home = kitelineHome(settings.home);
13262
- const token = loadToken(home, {
13263
- fixed: settings.token,
13264
- rotate: process.argv.includes("--new-token")
13265
- });
13266
- const secret = deviceSecret(token);
13267
- const pairing = buildPairing(dev ? 4546 : port, token, {
13196
+ const startOver = process.argv.includes("--new-token");
13197
+ const computer = loadComputerKey(home, { rotate: startOver });
13198
+ const devices = new Devices(join(home, "devices.json"));
13199
+ if (startOver) devices.removeAll({ kind: "terminal" });
13200
+ rmSync(join(home, "pairing.json"), { force: true });
13201
+ const where = {
13268
13202
  publicUrl: settings.publicUrl,
13269
- loopbackOnly: host === "127.0.0.1" || host === "localhost"
13270
- });
13203
+ loopbackOnly: host === "127.0.0.1" || host === "localhost",
13204
+ ...settings.relay ? { relay: {
13205
+ url: settings.relay,
13206
+ hostId: await hostAddress(home)
13207
+ } } : {}
13208
+ };
13209
+ const webPort = dev ? 4546 : port;
13210
+ const pairingLink = pairingLinks(webPort, where);
13271
13211
  const limiter = new PairLimiter();
13212
+ const interactive = !dev && !!process.stdin.isTTY && !!process.stdout.isTTY;
13213
+ const log = (message) => console.log(` ${message}`);
13272
13214
  const manager = new RunManager({
13273
13215
  claudePath: settings.claudePath ?? null,
13274
13216
  allowBypass,
@@ -13278,47 +13220,187 @@ const manager = new RunManager({
13278
13220
  });
13279
13221
  const shared = {
13280
13222
  manager,
13281
- pairing,
13223
+ devices,
13224
+ pairingLink,
13282
13225
  allowBypass,
13283
13226
  version: version$1
13284
13227
  };
13285
- function isAuthed(c) {
13228
+ /**
13229
+ * Who a request is from: the device whose tunnel or cookie it came with, or the computer's own
13230
+ * `kiteline` commands, which hold the computer's key. Through the relay, only the tunnel counts.
13231
+ */
13232
+ function callerOf(c) {
13233
+ const tunnel = c.env?.tunnel;
13234
+ if (tunnel) {
13235
+ const device = tunnel.kind === "device" ? devices.device(tunnel.id) : null;
13236
+ return device ? {
13237
+ kind: "device",
13238
+ ...device
13239
+ } : null;
13240
+ }
13286
13241
  const cookie = getCookie(c, DEVICE_COOKIE);
13287
- if (cookie && safeEqual(cookie, secret)) return true;
13242
+ const device = cookie ? devices.fromCookie(cookie) : null;
13243
+ if (device) return {
13244
+ kind: "device",
13245
+ ...device
13246
+ };
13288
13247
  const header = c.req.header("authorization");
13289
- return !!header?.startsWith("Bearer ") && safeEqual(header.slice(7), token);
13248
+ if (header?.startsWith("Bearer ") && safeEqual(header.slice(7), computer.key)) return { kind: "terminal" };
13249
+ return null;
13250
+ }
13251
+ const CLAIM_ERRORS = {
13252
+ unknown: `That pairing code isn't one this computer made. Make a new one with ${command("pair")}.`,
13253
+ expired: `That pairing code has expired. Make a new one with ${command("pair")}.`,
13254
+ used: `That pairing code was already used. Make a new one with ${command("pair")}.`,
13255
+ busy: "Too many devices are waiting to pair. Answer those first, or wait a few minutes."
13256
+ };
13257
+ /** Each device's open streams, so they end the moment it's removed. */
13258
+ const streams = /* @__PURE__ */ new Map();
13259
+ /** Passes a device's response on, and knows when it's done: until then the device counts as active. */
13260
+ function guarded(response, device, release) {
13261
+ if (!device || !response.body) {
13262
+ release();
13263
+ return response;
13264
+ }
13265
+ const reader = response.body.getReader();
13266
+ let cut = null;
13267
+ let finished = false;
13268
+ const finish = () => {
13269
+ if (finished) return;
13270
+ finished = true;
13271
+ if (cut) streams.get(device)?.delete(cut);
13272
+ release();
13273
+ };
13274
+ const body = new ReadableStream({
13275
+ start(controller) {
13276
+ cut = () => {
13277
+ reader.cancel().catch(() => {});
13278
+ try {
13279
+ controller.close();
13280
+ } catch {}
13281
+ finish();
13282
+ };
13283
+ const open = streams.get(device) ?? /* @__PURE__ */ new Set();
13284
+ streams.set(device, open);
13285
+ open.add(cut);
13286
+ },
13287
+ async pull(controller) {
13288
+ try {
13289
+ const { done, value } = await reader.read();
13290
+ if (done) {
13291
+ controller.close();
13292
+ finish();
13293
+ } else controller.enqueue(value);
13294
+ } catch (error) {
13295
+ controller.error(error);
13296
+ finish();
13297
+ }
13298
+ },
13299
+ cancel(reason) {
13300
+ finish();
13301
+ return reader.cancel(reason);
13302
+ }
13303
+ });
13304
+ return new Response(body, {
13305
+ status: response.status,
13306
+ statusText: response.statusText,
13307
+ headers: response.headers
13308
+ });
13290
13309
  }
13291
13310
  const app = new Hono();
13292
13311
  if (process.env.KITELINE_DEBUG) app.use(logger());
13293
13312
  app.use(compress());
13294
- app.get("/auth/status", (c) => c.json({ authed: isAuthed(c) }));
13313
+ app.get("/auth/status", (c) => {
13314
+ const caller = callerOf(c);
13315
+ if (caller) return c.json({
13316
+ authed: true,
13317
+ device: caller.kind === "device" ? caller : null
13318
+ });
13319
+ const stale = !!getCookie(c, DEVICE_COOKIE);
13320
+ if (stale) deleteCookie(c, DEVICE_COOKIE, { path: "/" });
13321
+ return c.json({
13322
+ authed: false,
13323
+ stale
13324
+ });
13325
+ });
13326
+ /**
13327
+ * Asking to pair. The code is spent either way, and the device only gets in once someone allows it.
13328
+ * Through the relay the handshake already proved the code, and the tunnel says which.
13329
+ */
13295
13330
  app.post("/auth/pair", async (c) => {
13296
- const ip = getConnInfo(c).remote.address ?? "unknown";
13297
- if (limiter.blocked(ip)) return c.json({
13298
- ok: false,
13299
- error: "Too many wrong codes. Wait ten minutes and try again."
13300
- }, 429);
13331
+ const tunnel = c.env?.tunnel;
13301
13332
  const body = await c.req.json().catch(() => ({}));
13302
- const given = typeof body.token === "string" ? body.token.trim() : "";
13303
- if (!given || !safeEqual(given, token)) {
13304
- limiter.fail(ip);
13305
- return c.json({
13333
+ let result;
13334
+ if (tunnel) {
13335
+ if (tunnel.kind !== "pairing") return c.json({
13336
+ ok: false,
13337
+ error: "This device is already paired."
13338
+ }, 409);
13339
+ result = await devices.claim({ id: tunnel.id }, {
13340
+ name: body.name,
13341
+ via: "relay"
13342
+ });
13343
+ } else {
13344
+ const ip = getConnInfo(c).remote.address ?? "unknown";
13345
+ if (limiter.blocked(ip)) return c.json({
13306
13346
  ok: false,
13307
- error: "That code doesn't match. Copy the link from your terminal again."
13308
- }, 401);
13347
+ error: "Too many wrong codes. Wait ten minutes and try again."
13348
+ }, 429);
13349
+ const code = typeof body.code === "string" ? body.code.trim() : "";
13350
+ result = /^[\w-]{16,64}$/.test(code) ? await devices.claim({ code }, {
13351
+ name: body.name,
13352
+ via: "direct"
13353
+ }) : {
13354
+ ok: false,
13355
+ problem: "unknown"
13356
+ };
13357
+ if (!result.ok && result.problem === "unknown") limiter.fail(ip);
13309
13358
  }
13310
- limiter.clear(ip);
13359
+ if (!result.ok) return c.json({
13360
+ ok: false,
13361
+ problem: result.problem,
13362
+ error: CLAIM_ERRORS[result.problem]
13363
+ }, result.problem === "busy" ? 429 : 410);
13364
+ const { claim, match, expiresAt } = result.request;
13365
+ return c.json({
13366
+ ok: true,
13367
+ claim,
13368
+ match,
13369
+ expiresAt
13370
+ });
13371
+ });
13372
+ /** The device that asked waits here for the answer: up to `wait` seconds, then it asks again. */
13373
+ app.get("/auth/pair/:claim", async (c) => {
13374
+ const tunnel = c.env?.tunnel;
13375
+ const wait = Math.min(25, Math.max(0, Number(c.req.query("wait")) || 0)) * 1e3;
13376
+ const status = await devices.status(c.req.param("claim"), wait, c.req.raw.signal);
13377
+ if (!status) return c.json({ state: "gone" }, 404);
13378
+ if (status.state !== "approved") return c.json(status);
13379
+ if (tunnel) return c.json(status);
13311
13380
  const https = c.req.header("x-forwarded-proto") === "https" || new URL(c.req.url).protocol === "https:";
13312
- setCookie(c, DEVICE_COOKIE, secret, {
13381
+ setCookie(c, DEVICE_COOKIE, Devices.cookieFor(status.device), {
13313
13382
  httpOnly: true,
13314
13383
  sameSite: "Strict",
13315
13384
  secure: https,
13316
13385
  path: "/",
13317
13386
  maxAge: 3456e4
13318
13387
  });
13388
+ return c.json({
13389
+ state: "approved",
13390
+ device: {
13391
+ id: status.device.id,
13392
+ name: status.device.name
13393
+ }
13394
+ });
13395
+ });
13396
+ app.delete("/auth/pair/:claim", (c) => {
13397
+ devices.cancel(c.req.param("claim"));
13319
13398
  return c.json({ ok: true });
13320
13399
  });
13400
+ /** Unpairing: the device is forgotten here too, so its key opens nothing even if it was copied. */
13321
13401
  app.post("/auth/logout", (c) => {
13402
+ const caller = callerOf(c);
13403
+ if (caller?.kind === "device") devices.remove(caller.id, caller);
13322
13404
  deleteCookie(c, DEVICE_COOKIE, { path: "/" });
13323
13405
  return c.json({ ok: true });
13324
13406
  });
@@ -13326,16 +13408,24 @@ const rpcHandler = new RPCHandler(appRouter, { interceptors: [onError((error) =>
13326
13408
  if (process.env.KITELINE_DEBUG) console.error(error);
13327
13409
  })] });
13328
13410
  app.use("/rpc/*", async (c, next) => {
13329
- const context = createContext({
13330
- context: c,
13331
- authed: isAuthed(c),
13332
- shared
13333
- });
13334
- const result = await rpcHandler.handle(c.req.raw, {
13335
- prefix: "/rpc",
13336
- context
13337
- });
13338
- if (result.matched) return c.newResponse(result.response.body, result.response);
13411
+ const caller = callerOf(c);
13412
+ const device = caller?.kind === "device" ? caller.id : null;
13413
+ const release = device ? devices.using(device) : () => {};
13414
+ let result;
13415
+ try {
13416
+ result = await rpcHandler.handle(c.req.raw, {
13417
+ prefix: "/rpc",
13418
+ context: createContext({
13419
+ caller,
13420
+ shared
13421
+ })
13422
+ });
13423
+ } catch (error) {
13424
+ release();
13425
+ throw error;
13426
+ }
13427
+ if (result.matched) return guarded(result.response, device, release);
13428
+ release();
13339
13429
  await next();
13340
13430
  });
13341
13431
  const here = dirname(fileURLToPath(import.meta.url));
@@ -13356,16 +13446,64 @@ if (!dev && webDir) {
13356
13446
  return c.html(indexHtml);
13357
13447
  });
13358
13448
  } else if (!dev) app.get("/", (c) => c.text("Kiteline's API is running. Build the web app with `pnpm build` to serve it from here."));
13449
+ let relay = null;
13450
+ devices.on("removed", (device, by) => {
13451
+ const self = by.kind === "device" && by.id === device.id;
13452
+ setTimeout(() => {
13453
+ for (const cut of [...streams.get(device.id) ?? []]) cut();
13454
+ streams.delete(device.id);
13455
+ relay?.disconnect({
13456
+ kind: "device",
13457
+ id: device.id
13458
+ });
13459
+ }, self ? 1e3 : 0);
13460
+ });
13461
+ if (!interactive) {
13462
+ devices.on("request", (r) => log(`${r.name} asks to pair; its screen shows ${spaced(r.match)}.`));
13463
+ devices.on("settled", (r) => {
13464
+ if (r.state === "approved") log(`Paired ${r.name}, allowed ${r.by?.kind === "device" ? `on ${r.by.name}` : "in the terminal"}.`);
13465
+ else if (r.state === "denied") log(`Declined ${r.name}.`);
13466
+ else if (r.state === "expired") log(`Nobody answered ${r.name} in time; it isn't paired.`);
13467
+ });
13468
+ devices.on("removed", (device) => log(`Removed ${device.name}.`));
13469
+ }
13359
13470
  const server = serve({
13360
13471
  fetch: app.fetch,
13361
13472
  port,
13362
13473
  hostname: host
13363
13474
  }, () => {
13364
- printBanner(pairing, {
13475
+ printBanner(addressesFor(webPort, where), {
13476
+ version: version$1,
13477
+ dev,
13478
+ relay: settings.relay
13479
+ });
13480
+ if (!dev) saveServerInfo(home, {
13481
+ version: version$1,
13482
+ pid: process.pid,
13483
+ local: localAddress(port, host),
13484
+ relay: settings.relay,
13485
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
13486
+ });
13487
+ if (process.env.KITELINE_TOKEN?.trim()) log(`KITELINE_TOKEN isn't used any more: each device pairs with a one-time code from ${command("pair")}.`);
13488
+ if (startOver) log("Every device was unpaired.");
13489
+ else if (computer.replaced) log(`Pairing works differently from this version on: pair each phone again, once, with ${command("pair")}.`);
13490
+ if (interactive) startConsole({
13491
+ devices,
13492
+ pairingLink
13493
+ });
13494
+ else if (devices.count) log(`Pair another device with: ${command("pair")}\n`);
13495
+ else log(`Pair your phone with: ${command("pair")}\n`);
13496
+ if (settings.relay) startRelay({
13497
+ relay: settings.relay,
13498
+ home,
13365
13499
  version: version$1,
13366
- dev
13500
+ keyFor: (identity) => devices.key(identity),
13501
+ handle: (request, identity) => app.fetch(request, { tunnel: identity }),
13502
+ track: (identity) => identity.kind === "device" ? devices.using(identity.id) : void 0,
13503
+ log
13504
+ }).then((started) => {
13505
+ relay = started;
13367
13506
  });
13368
- if (!dev) savePairing(home, pairing, version$1);
13369
13507
  });
13370
13508
  server.on("error", (error) => {
13371
13509
  if (error.code !== "EADDRINUSE") throw error;
@@ -13373,7 +13511,9 @@ server.on("error", (error) => {
13373
13511
  process.exit(1);
13374
13512
  });
13375
13513
  function shutdown() {
13514
+ relay?.stop();
13376
13515
  manager.stopAll();
13516
+ devices.flush();
13377
13517
  server.close();
13378
13518
  setTimeout(() => process.exit(0), 300).unref();
13379
13519
  }