kiteline 0.2.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.
- package/README.md +2 -2
- package/dist/auth-CYNu-f_h.mjs +104 -0
- package/dist/{banner-CXnDgf5p.mjs → banner-C1Jj4n4W.mjs} +44 -42
- package/dist/cli.mjs +30 -10
- package/dist/client.BPI7fHX3-CSey2FaL.mjs +1437 -0
- package/dist/control-BEq2N-wP.mjs +101 -0
- package/dist/control-BpOGsRCZ.mjs +1 -0
- package/dist/devices-command-Bubh46v1.mjs +76 -0
- package/dist/{package-CbMOnF6R.mjs → package-BoxBh8MJ.mjs} +1 -1
- package/dist/pair-command-DBxw6BfK.mjs +107 -0
- package/dist/{service-BCgNAv2Z.mjs → service-C2w4PsA8.mjs} +16 -22
- package/dist/{src-DSH8d4ZM.mjs → src-CR4MmTcf.mjs} +1048 -1421
- package/dist/web/assets/MagnifyingGlass.es-DH9Sttou.js +1 -0
- package/dist/web/assets/Plus.es-1uU9mFYr.js +1 -0
- package/dist/web/assets/composer-BcIdpxHM.js +1 -0
- package/dist/web/assets/copy-button-DRCJdYml.js +1 -0
- package/dist/web/assets/format-BHMU9nwj.js +9 -0
- package/dist/web/assets/index-BRaZDA7B.css +1 -0
- package/dist/web/assets/index-TWMUhgcM.js +11 -0
- package/dist/web/assets/lazy/{core-CuC-kkU7.js → core-pRLcnHpb.js} +1 -1
- package/dist/web/assets/new-BbSpVHmG.js +1 -0
- package/dist/web/assets/prefs-q6daUElH.js +1 -0
- package/dist/web/assets/routes-lV-e8sSj.js +1 -0
- package/dist/web/assets/s._sessionId-t7H-a-HP.js +45 -0
- package/dist/web/assets/settings-CbonbiKb.js +1 -0
- package/dist/web/assets/status-CKsUN4Lx.js +1 -0
- package/dist/web/index.html +3 -3
- package/dist/web/sw.js +1 -1
- package/package.json +1 -1
- package/dist/auth-YhkfTv6K.mjs +0 -60
- package/dist/show-pairing-CTd0UfS1.mjs +0 -30
- package/dist/show-pairing-Zurbk9wK.mjs +0 -1
- package/dist/web/assets/IconBase.es-h0cGkmPy.js +0 -9
- package/dist/web/assets/MagnifyingGlass.es-CpSmmHxy.js +0 -1
- package/dist/web/assets/composer-WnPpY669.js +0 -1
- package/dist/web/assets/copy-button-DBETbWKF.js +0 -1
- package/dist/web/assets/index-CA73h-Vn.css +0 -1
- package/dist/web/assets/index-CTAi3HIp.js +0 -11
- package/dist/web/assets/new-D_XEbYrm.js +0 -1
- package/dist/web/assets/prefs-D6OSXuFe.js +0 -1
- package/dist/web/assets/routes-Csbxwlji.js +0 -1
- package/dist/web/assets/s._sessionId-BlR4dPFc.js +0 -45
- package/dist/web/assets/settings-DRpTnWMo.js +0 -1
- package/dist/web/assets/status-C7fEa4v1.js +0 -1
|
@@ -1,17 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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 { randomBytes, 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
|
-
// ../../
|
|
2736
|
-
|
|
2737
|
-
|
|
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
|
|
2740
|
-
return
|
|
2776
|
+
function random(length) {
|
|
2777
|
+
return crypto.getRandomValues(new Uint8Array(length));
|
|
2741
2778
|
}
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
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
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
const result = fn();
|
|
2762
|
-
cached = { result };
|
|
2763
|
-
return result;
|
|
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")))
|
|
2764
2797
|
};
|
|
2765
2798
|
}
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
return (
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
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
|
|
2772
2815
|
};
|
|
2773
2816
|
}
|
|
2774
|
-
|
|
2775
|
-
const
|
|
2776
|
-
|
|
2777
|
-
|
|
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));
|
|
2778
2826
|
}
|
|
2779
|
-
function
|
|
2780
|
-
return (
|
|
2827
|
+
async function sha256(data) {
|
|
2828
|
+
return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
|
|
2781
2829
|
}
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
const
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
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
|
+
};
|
|
2790
2851
|
}
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
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);
|
|
2800
2887
|
}
|
|
2801
|
-
|
|
2888
|
+
};
|
|
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
|
|
2920
|
+
};
|
|
2802
2921
|
}
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
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();
|
|
2967
|
+
}
|
|
2968
|
+
static load(file) {
|
|
2807
2969
|
try {
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
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
|
-
|
|
2858
|
-
return this
|
|
2982
|
+
get count() {
|
|
2983
|
+
return this.devices.length;
|
|
2859
2984
|
}
|
|
2860
|
-
|
|
2861
|
-
this
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
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
|
-
|
|
2868
|
-
|
|
3003
|
+
id,
|
|
3004
|
+
code,
|
|
3005
|
+
expiresAt
|
|
2869
3006
|
};
|
|
2870
3007
|
}
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
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
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
if (!
|
|
2885
|
-
|
|
2886
|
-
|
|
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
|
-
|
|
2890
|
-
|
|
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
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
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
|
-
|
|
2917
|
-
|
|
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
|
-
|
|
3135
|
+
this.save();
|
|
2920
3136
|
} catch (error) {
|
|
2921
|
-
|
|
3137
|
+
this.devices.pop();
|
|
2922
3138
|
throw error;
|
|
2923
3139
|
}
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
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
|
-
|
|
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
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
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
|
-
|
|
3172
|
+
requestInfo(r) {
|
|
3153
3173
|
return {
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
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
|
-
*
|
|
3163
|
-
*
|
|
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
|
-
|
|
3174
|
-
if (
|
|
3175
|
-
const
|
|
3176
|
-
if (
|
|
3177
|
-
|
|
3178
|
-
|
|
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
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
if (
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
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
|
-
|
|
3302
|
-
|
|
3274
|
+
removeAll(by) {
|
|
3275
|
+
for (const device of [...this.devices]) this.remove(device.id, by);
|
|
3303
3276
|
}
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3308
|
-
|
|
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
|
-
|
|
3324
|
-
const
|
|
3325
|
-
|
|
3326
|
-
|
|
3327
|
-
}
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
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
|
-
|
|
3437
|
-
|
|
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
|
-
|
|
3443
|
-
|
|
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
|
-
}
|
|
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
|
-
|
|
3448
|
-
} catch
|
|
3449
|
-
|
|
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;
|
|
@@ -3478,544 +3382,42 @@ async function validateORPCError(map, error) {
|
|
|
3478
3382
|
}) : error;
|
|
3479
3383
|
if (!config.data) return defined ? error : new ORPCError(code, {
|
|
3480
3384
|
defined: true,
|
|
3481
|
-
status,
|
|
3482
|
-
message,
|
|
3483
|
-
data,
|
|
3484
|
-
cause
|
|
3485
|
-
});
|
|
3486
|
-
const validated = await config.data["~standard"].validate(error.data);
|
|
3487
|
-
if (validated.issues) return defined ? new ORPCError(code, {
|
|
3488
|
-
defined: false,
|
|
3489
|
-
status,
|
|
3490
|
-
message,
|
|
3491
|
-
data,
|
|
3492
|
-
cause
|
|
3493
|
-
}) : error;
|
|
3494
|
-
return new ORPCError(code, {
|
|
3495
|
-
defined: true,
|
|
3496
|
-
status,
|
|
3497
|
-
message,
|
|
3498
|
-
data: validated.value,
|
|
3499
|
-
cause
|
|
3500
|
-
});
|
|
3501
|
-
}
|
|
3502
|
-
var ContractProcedure = class {
|
|
3503
|
-
/**
|
|
3504
|
-
* This property holds the defined options for the contract procedure.
|
|
3505
|
-
*/
|
|
3506
|
-
"~orpc";
|
|
3507
|
-
constructor(def) {
|
|
3508
|
-
if (def.route?.successStatus && isORPCErrorStatus(def.route.successStatus)) throw new Error("[ContractProcedure] Invalid successStatus.");
|
|
3509
|
-
if (Object.values(def.errorMap).some((val) => val && val.status && !isORPCErrorStatus(val.status))) throw new Error("[ContractProcedure] Invalid error status code.");
|
|
3510
|
-
this["~orpc"] = def;
|
|
3511
|
-
}
|
|
3512
|
-
};
|
|
3513
|
-
function isContractProcedure(item) {
|
|
3514
|
-
if (item instanceof ContractProcedure) return true;
|
|
3515
|
-
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
|
-
}
|
|
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("/")}`;
|
|
3385
|
+
status,
|
|
3386
|
+
message,
|
|
3387
|
+
data,
|
|
3388
|
+
cause
|
|
3389
|
+
});
|
|
3390
|
+
const validated = await config.data["~standard"].validate(error.data);
|
|
3391
|
+
if (validated.issues) return defined ? new ORPCError(code, {
|
|
3392
|
+
defined: false,
|
|
3393
|
+
status,
|
|
3394
|
+
message,
|
|
3395
|
+
data,
|
|
3396
|
+
cause
|
|
3397
|
+
}) : error;
|
|
3398
|
+
return new ORPCError(code, {
|
|
3399
|
+
defined: true,
|
|
3400
|
+
status,
|
|
3401
|
+
message,
|
|
3402
|
+
data: validated.value,
|
|
3403
|
+
cause
|
|
3404
|
+
});
|
|
3962
3405
|
}
|
|
3963
|
-
var
|
|
3964
|
-
|
|
3965
|
-
|
|
3966
|
-
|
|
3967
|
-
|
|
3968
|
-
|
|
3969
|
-
|
|
3970
|
-
|
|
3971
|
-
|
|
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()));
|
|
3406
|
+
var ContractProcedure = class {
|
|
3407
|
+
/**
|
|
3408
|
+
* This property holds the defined options for the contract procedure.
|
|
3409
|
+
*/
|
|
3410
|
+
"~orpc";
|
|
3411
|
+
constructor(def) {
|
|
3412
|
+
if (def.route?.successStatus && isORPCErrorStatus(def.route.successStatus)) throw new Error("[ContractProcedure] Invalid successStatus.");
|
|
3413
|
+
if (Object.values(def.errorMap).some((val) => val && val.status && !isORPCErrorStatus(val.status))) throw new Error("[ContractProcedure] Invalid error status code.");
|
|
3414
|
+
this["~orpc"] = def;
|
|
4017
3415
|
}
|
|
4018
3416
|
};
|
|
3417
|
+
function isContractProcedure(item) {
|
|
3418
|
+
if (item instanceof ContractProcedure) return true;
|
|
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"];
|
|
3420
|
+
}
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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
|
|
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.
|
|
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.
|
|
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,159 +12680,104 @@ 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));
|
|
13241
|
-
};
|
|
13242
|
-
};
|
|
13243
|
-
// src/context.ts
|
|
13244
|
-
function createContext({ authed, shared }) {
|
|
13245
|
-
return {
|
|
13246
|
-
...shared,
|
|
13247
|
-
authed
|
|
12686
|
+
await log$1(fn, "-->", method, path, c.res.status, time(start));
|
|
13248
12687
|
};
|
|
13249
|
-
}
|
|
13250
|
-
// ../../packages/api/src/tunnel/crypto.ts
|
|
13251
|
-
const encoder$1 = new TextEncoder();
|
|
13252
|
-
const LABEL = encoder$1.encode("kiteline-tunnel-v1");
|
|
13253
|
-
const AAD = encoder$1.encode("kiteline-tunnel-v1/message");
|
|
13254
|
-
const NONCE_BYTES = 16;
|
|
13255
|
-
/** Handshake frames, then sealed messages. The first byte says which. */
|
|
13256
|
-
const Frame = {
|
|
13257
|
-
Hello: 1,
|
|
13258
|
-
Welcome: 2,
|
|
13259
|
-
Confirm: 3,
|
|
13260
|
-
Sealed: 16
|
|
13261
12688
|
};
|
|
13262
|
-
|
|
13263
|
-
|
|
13264
|
-
|
|
13265
|
-
|
|
13266
|
-
|
|
13267
|
-
|
|
13268
|
-
|
|
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."), "");
|
|
13269
12771
|
}
|
|
13270
|
-
return out;
|
|
13271
|
-
}
|
|
13272
|
-
function random(length) {
|
|
13273
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
13274
|
-
}
|
|
13275
|
-
/** What a pairing token stands for on every device: the same value the computer's cookie holds. */
|
|
13276
|
-
async function deviceSecret(token) {
|
|
13277
|
-
const key = await crypto.subtle.importKey("raw", encoder$1.encode(token), {
|
|
13278
|
-
name: "HMAC",
|
|
13279
|
-
hash: "SHA-256"
|
|
13280
|
-
}, false, ["sign"]);
|
|
13281
|
-
return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder$1.encode("kiteline-device-v1")));
|
|
13282
|
-
}
|
|
13283
|
-
/** The device secret as a key for the handshake. A phone keeps it non-extractable: usable, never readable. */
|
|
13284
|
-
function importSecret(secret, extractable = false) {
|
|
13285
|
-
return crypto.subtle.importKey("raw", secret, {
|
|
13286
|
-
name: "HMAC",
|
|
13287
|
-
hash: "SHA-256"
|
|
13288
|
-
}, extractable, ["sign"]);
|
|
13289
|
-
}
|
|
13290
|
-
async function ephemeral() {
|
|
13291
|
-
const pair = await crypto.subtle.generateKey({
|
|
13292
|
-
name: "ECDH",
|
|
13293
|
-
namedCurve: "P-256"
|
|
13294
|
-
}, false, ["deriveBits"]);
|
|
13295
|
-
const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
|
|
13296
|
-
return {
|
|
13297
|
-
privateKey: pair.privateKey,
|
|
13298
|
-
publicKey
|
|
13299
|
-
};
|
|
13300
|
-
}
|
|
13301
|
-
async function agree(privateKey, peerPublic) {
|
|
13302
|
-
const peer = await crypto.subtle.importKey("raw", peerPublic, {
|
|
13303
|
-
name: "ECDH",
|
|
13304
|
-
namedCurve: "P-256"
|
|
13305
|
-
}, false, []);
|
|
13306
|
-
return new Uint8Array(await crypto.subtle.deriveBits({
|
|
13307
|
-
name: "ECDH",
|
|
13308
|
-
public: peer
|
|
13309
|
-
}, privateKey, 256));
|
|
13310
12772
|
}
|
|
13311
|
-
|
|
13312
|
-
|
|
13313
|
-
}
|
|
13314
|
-
/** Keys for one connection, from the key exchange, the device secret and everything both sides said. */
|
|
13315
|
-
async function schedule(secret, exchanged, transcript) {
|
|
13316
|
-
const ikm = new Uint8Array(await crypto.subtle.sign("HMAC", secret, concat(exchanged, transcript)));
|
|
13317
|
-
const base = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
|
|
13318
|
-
const bits = (label) => crypto.subtle.deriveBits({
|
|
13319
|
-
name: "HKDF",
|
|
13320
|
-
hash: "SHA-256",
|
|
13321
|
-
salt: transcript,
|
|
13322
|
-
info: encoder$1.encode(label)
|
|
13323
|
-
}, base, 256);
|
|
13324
|
-
const aes = async (label) => crypto.subtle.importKey("raw", await bits(label), { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
13325
|
-
const mac = async (label) => crypto.subtle.importKey("raw", await bits(label), {
|
|
13326
|
-
name: "HMAC",
|
|
13327
|
-
hash: "SHA-256"
|
|
13328
|
-
}, false, ["sign", "verify"]);
|
|
12773
|
+
// src/context.ts
|
|
12774
|
+
function createContext({ caller, shared }) {
|
|
13329
12775
|
return {
|
|
13330
|
-
|
|
13331
|
-
|
|
13332
|
-
|
|
13333
|
-
clientConfirm: await mac("client-confirm")
|
|
12776
|
+
...shared,
|
|
12777
|
+
caller,
|
|
12778
|
+
authed: caller !== null
|
|
13334
12779
|
};
|
|
13335
12780
|
}
|
|
13336
|
-
/** Seals and opens one connection's messages, strictly in order. */
|
|
13337
|
-
var Cipher = class Cipher {
|
|
13338
|
-
sendKey;
|
|
13339
|
-
receiveKey;
|
|
13340
|
-
sent = 0n;
|
|
13341
|
-
received = 0n;
|
|
13342
|
-
constructor(sendKey, receiveKey) {
|
|
13343
|
-
this.sendKey = sendKey;
|
|
13344
|
-
this.receiveKey = receiveKey;
|
|
13345
|
-
}
|
|
13346
|
-
static iv(counter) {
|
|
13347
|
-
const iv = /* @__PURE__ */ new Uint8Array(12);
|
|
13348
|
-
new DataView(iv.buffer).setBigUint64(4, counter);
|
|
13349
|
-
return iv;
|
|
13350
|
-
}
|
|
13351
|
-
/** Callers must seal in the order the frames go out; the counter is taken here. */
|
|
13352
|
-
async seal(plain) {
|
|
13353
|
-
const iv = Cipher.iv(this.sent++);
|
|
13354
|
-
const sealed = await crypto.subtle.encrypt({
|
|
13355
|
-
name: "AES-GCM",
|
|
13356
|
-
iv,
|
|
13357
|
-
additionalData: AAD
|
|
13358
|
-
}, this.sendKey, plain);
|
|
13359
|
-
return concat(Uint8Array.of(Frame.Sealed), new Uint8Array(sealed));
|
|
13360
|
-
}
|
|
13361
|
-
/** Throws on anything altered, replayed, reordered or not from the other end. */
|
|
13362
|
-
async open(frame) {
|
|
13363
|
-
if (frame[0] !== Frame.Sealed) throw new HandshakeError("Expected a sealed message.");
|
|
13364
|
-
const iv = Cipher.iv(this.received++);
|
|
13365
|
-
const plain = await crypto.subtle.decrypt({
|
|
13366
|
-
name: "AES-GCM",
|
|
13367
|
-
iv,
|
|
13368
|
-
additionalData: AAD
|
|
13369
|
-
}, this.receiveKey, frame.subarray(1));
|
|
13370
|
-
return new Uint8Array(plain);
|
|
13371
|
-
}
|
|
13372
|
-
};
|
|
13373
|
-
/** The computer's side: answers a phone's hello, and accepts it only once it proves the pairing. */
|
|
13374
|
-
async function respond(secret, hello, send, next) {
|
|
13375
|
-
if (hello[0] !== Frame.Hello || hello.length !== 83) throw new HandshakeError("That wasn't a handshake.");
|
|
13376
|
-
if (hello[1] !== 1) throw new HandshakeError(`Unsupported tunnel version ${hello[1]}.`);
|
|
13377
|
-
const clientPublic = hello.slice(2, 67);
|
|
13378
|
-
const clientNonce = hello.slice(67);
|
|
13379
|
-
const mine = await ephemeral();
|
|
13380
|
-
const hostNonce = random(NONCE_BYTES);
|
|
13381
|
-
const transcript = await sha256(concat(LABEL, clientPublic, clientNonce, mine.publicKey, hostNonce));
|
|
13382
|
-
const keys = await schedule(secret, await agree(mine.privateKey, clientPublic), transcript);
|
|
13383
|
-
const proof = new Uint8Array(await crypto.subtle.sign("HMAC", keys.hostConfirm, transcript));
|
|
13384
|
-
send(concat(Uint8Array.of(Frame.Welcome), mine.publicKey, hostNonce, proof));
|
|
13385
|
-
const confirm = await next();
|
|
13386
|
-
if (confirm[0] !== Frame.Confirm || confirm.length !== 33) throw new HandshakeError("The phone didn't finish the handshake.");
|
|
13387
|
-
if (!await crypto.subtle.verify("HMAC", keys.clientConfirm, confirm.slice(1), transcript)) throw new HandshakeError("This phone isn't paired with this computer.");
|
|
13388
|
-
return new Cipher(keys.s2c, keys.c2s);
|
|
13389
|
-
}
|
|
13390
12781
|
// ../../packages/api/src/tunnel/messages.ts
|
|
13391
12782
|
/**
|
|
13392
12783
|
* What travels inside the sealed tunnel: HTTP requests from the phone and streamed responses from
|
|
@@ -13526,19 +12917,26 @@ var SocketTimeout = class extends Error {
|
|
|
13526
12917
|
const MAX_BODY = 41943040;
|
|
13527
12918
|
const HANDSHAKE_MS = 2e4;
|
|
13528
12919
|
/**
|
|
13529
|
-
* The computer's end of one phone's tunnel. Answers the handshake
|
|
13530
|
-
*
|
|
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.
|
|
13531
12923
|
*/
|
|
13532
|
-
async function serveTunnel(ws,
|
|
12924
|
+
async function serveTunnel(ws, keyFor, handle, hooks = {}) {
|
|
13533
12925
|
const socket = new FrameSocket(ws);
|
|
13534
12926
|
let cipher;
|
|
12927
|
+
let identity;
|
|
13535
12928
|
try {
|
|
13536
|
-
|
|
12929
|
+
const hello = await socket.next(HANDSHAKE_MS);
|
|
12930
|
+
({cipher, identity} = await respond(keyFor, hello, (frame) => socket.send(frame), () => socket.next(HANDSHAKE_MS)));
|
|
13537
12931
|
} catch (error) {
|
|
12932
|
+
const reason = error instanceof UnknownKey && error.identity.kind === "pairing" ? "code expired" : "not paired";
|
|
13538
12933
|
const unpaired = error instanceof HandshakeError;
|
|
13539
|
-
socket.close(unpaired ? RelayClose.NotPaired : RelayClose.BadRequest, unpaired ?
|
|
12934
|
+
socket.close(unpaired ? RelayClose.NotPaired : RelayClose.BadRequest, unpaired ? reason : "bad handshake");
|
|
13540
12935
|
return;
|
|
13541
12936
|
}
|
|
12937
|
+
const who = identity;
|
|
12938
|
+
hooks.opened?.(who, (code, reason) => socket.close(code, reason));
|
|
12939
|
+
socket.onClose(() => hooks.closed?.(who));
|
|
13542
12940
|
const streams = /* @__PURE__ */ new Map();
|
|
13543
12941
|
let sending = Promise.resolve();
|
|
13544
12942
|
let closed = false;
|
|
@@ -13564,7 +12962,7 @@ async function serveTunnel(ws, secret, handle) {
|
|
|
13564
12962
|
headers: head.headers,
|
|
13565
12963
|
body,
|
|
13566
12964
|
signal: stream.abort.signal
|
|
13567
|
-
}));
|
|
12965
|
+
}), who);
|
|
13568
12966
|
if (!streams.has(id)) return;
|
|
13569
12967
|
await post(Msg.Response, id, new TextEncoder().encode(JSON.stringify({
|
|
13570
12968
|
status: response.status,
|
|
@@ -13643,7 +13041,7 @@ function joinChunks(chunks, size) {
|
|
|
13643
13041
|
return out;
|
|
13644
13042
|
}
|
|
13645
13043
|
// src/relay.ts
|
|
13646
|
-
/** The relay's secret for this computer, kept beside
|
|
13044
|
+
/** The relay's secret for this computer, kept beside its other keys. Its hash is our address. */
|
|
13647
13045
|
function relaySecret(home) {
|
|
13648
13046
|
const file = join(home, "relay.json");
|
|
13649
13047
|
try {
|
|
@@ -13661,10 +13059,20 @@ function relaySecret(home) {
|
|
|
13661
13059
|
}, null, 2)}\n`, { mode: 384 });
|
|
13662
13060
|
return secret;
|
|
13663
13061
|
}
|
|
13664
|
-
/**
|
|
13665
|
-
|
|
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) {
|
|
13666
13067
|
const { pathname } = new URL(request.url);
|
|
13667
|
-
|
|
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/");
|
|
13668
13076
|
}
|
|
13669
13077
|
async function hostAddress(home) {
|
|
13670
13078
|
return hostIdFor(fromBase64Url(relaySecret(home)));
|
|
@@ -13672,13 +13080,30 @@ async function hostAddress(home) {
|
|
|
13672
13080
|
async function startRelay(options) {
|
|
13673
13081
|
const secret = relaySecret(options.home);
|
|
13674
13082
|
const hostId = await hostIdFor(fromBase64Url(secret));
|
|
13675
|
-
const
|
|
13676
|
-
const
|
|
13677
|
-
|
|
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 });
|
|
13678
13087
|
const headers = new Headers(request.headers);
|
|
13679
13088
|
headers.delete("cookie");
|
|
13680
|
-
headers.
|
|
13681
|
-
return options.handle(new Request(request, { headers }));
|
|
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
|
+
};
|
|
13682
13107
|
};
|
|
13683
13108
|
let attempt = 0;
|
|
13684
13109
|
let connected = false;
|
|
@@ -13713,7 +13138,16 @@ async function startRelay(options) {
|
|
|
13713
13138
|
attempt = 0;
|
|
13714
13139
|
if (!connected) options.log("Connected to the relay: phones can reach this computer from anywhere.");
|
|
13715
13140
|
connected = true;
|
|
13716
|
-
} else if (message.t === "open" && /^[\w-]{22}$/.test(message.channel))
|
|
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
|
+
}
|
|
13717
13151
|
});
|
|
13718
13152
|
ws.addEventListener("close", (event) => {
|
|
13719
13153
|
if (silence) clearInterval(silence);
|
|
@@ -13736,6 +13170,10 @@ async function startRelay(options) {
|
|
|
13736
13170
|
get connected() {
|
|
13737
13171
|
return connected;
|
|
13738
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
|
+
},
|
|
13739
13177
|
stop() {
|
|
13740
13178
|
stopped = true;
|
|
13741
13179
|
if (silence) clearInterval(silence);
|
|
@@ -13755,20 +13193,24 @@ try {
|
|
|
13755
13193
|
}
|
|
13756
13194
|
const { port, host, allowBypass } = settings;
|
|
13757
13195
|
const home = kitelineHome(settings.home);
|
|
13758
|
-
const
|
|
13759
|
-
|
|
13760
|
-
|
|
13761
|
-
});
|
|
13762
|
-
|
|
13763
|
-
const
|
|
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 = {
|
|
13764
13202
|
publicUrl: settings.publicUrl,
|
|
13765
13203
|
loopbackOnly: host === "127.0.0.1" || host === "localhost",
|
|
13766
13204
|
...settings.relay ? { relay: {
|
|
13767
13205
|
url: settings.relay,
|
|
13768
13206
|
hostId: await hostAddress(home)
|
|
13769
13207
|
} } : {}
|
|
13770
|
-
}
|
|
13208
|
+
};
|
|
13209
|
+
const webPort = dev ? 4546 : port;
|
|
13210
|
+
const pairingLink = pairingLinks(webPort, where);
|
|
13771
13211
|
const limiter = new PairLimiter();
|
|
13212
|
+
const interactive = !dev && !!process.stdin.isTTY && !!process.stdout.isTTY;
|
|
13213
|
+
const log = (message) => console.log(` ${message}`);
|
|
13772
13214
|
const manager = new RunManager({
|
|
13773
13215
|
claudePath: settings.claudePath ?? null,
|
|
13774
13216
|
allowBypass,
|
|
@@ -13778,47 +13220,187 @@ const manager = new RunManager({
|
|
|
13778
13220
|
});
|
|
13779
13221
|
const shared = {
|
|
13780
13222
|
manager,
|
|
13781
|
-
|
|
13223
|
+
devices,
|
|
13224
|
+
pairingLink,
|
|
13782
13225
|
allowBypass,
|
|
13783
13226
|
version: version$1
|
|
13784
13227
|
};
|
|
13785
|
-
|
|
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
|
+
}
|
|
13786
13241
|
const cookie = getCookie(c, DEVICE_COOKIE);
|
|
13787
|
-
|
|
13242
|
+
const device = cookie ? devices.fromCookie(cookie) : null;
|
|
13243
|
+
if (device) return {
|
|
13244
|
+
kind: "device",
|
|
13245
|
+
...device
|
|
13246
|
+
};
|
|
13788
13247
|
const header = c.req.header("authorization");
|
|
13789
|
-
|
|
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
|
+
});
|
|
13790
13309
|
}
|
|
13791
13310
|
const app = new Hono();
|
|
13792
13311
|
if (process.env.KITELINE_DEBUG) app.use(logger());
|
|
13793
13312
|
app.use(compress());
|
|
13794
|
-
app.get("/auth/status", (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
|
+
*/
|
|
13795
13330
|
app.post("/auth/pair", async (c) => {
|
|
13796
|
-
const
|
|
13797
|
-
if (limiter.blocked(ip)) return c.json({
|
|
13798
|
-
ok: false,
|
|
13799
|
-
error: "Too many wrong codes. Wait ten minutes and try again."
|
|
13800
|
-
}, 429);
|
|
13331
|
+
const tunnel = c.env?.tunnel;
|
|
13801
13332
|
const body = await c.req.json().catch(() => ({}));
|
|
13802
|
-
|
|
13803
|
-
if (
|
|
13804
|
-
|
|
13805
|
-
|
|
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({
|
|
13806
13346
|
ok: false,
|
|
13807
|
-
error: "
|
|
13808
|
-
},
|
|
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);
|
|
13809
13358
|
}
|
|
13810
|
-
|
|
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);
|
|
13811
13380
|
const https = c.req.header("x-forwarded-proto") === "https" || new URL(c.req.url).protocol === "https:";
|
|
13812
|
-
setCookie(c, DEVICE_COOKIE,
|
|
13381
|
+
setCookie(c, DEVICE_COOKIE, Devices.cookieFor(status.device), {
|
|
13813
13382
|
httpOnly: true,
|
|
13814
13383
|
sameSite: "Strict",
|
|
13815
13384
|
secure: https,
|
|
13816
13385
|
path: "/",
|
|
13817
13386
|
maxAge: 3456e4
|
|
13818
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"));
|
|
13819
13398
|
return c.json({ ok: true });
|
|
13820
13399
|
});
|
|
13400
|
+
/** Unpairing: the device is forgotten here too, so its key opens nothing even if it was copied. */
|
|
13821
13401
|
app.post("/auth/logout", (c) => {
|
|
13402
|
+
const caller = callerOf(c);
|
|
13403
|
+
if (caller?.kind === "device") devices.remove(caller.id, caller);
|
|
13822
13404
|
deleteCookie(c, DEVICE_COOKIE, { path: "/" });
|
|
13823
13405
|
return c.json({ ok: true });
|
|
13824
13406
|
});
|
|
@@ -13826,16 +13408,24 @@ const rpcHandler = new RPCHandler(appRouter, { interceptors: [onError((error) =>
|
|
|
13826
13408
|
if (process.env.KITELINE_DEBUG) console.error(error);
|
|
13827
13409
|
})] });
|
|
13828
13410
|
app.use("/rpc/*", async (c, next) => {
|
|
13829
|
-
const
|
|
13830
|
-
|
|
13831
|
-
|
|
13832
|
-
|
|
13833
|
-
|
|
13834
|
-
|
|
13835
|
-
|
|
13836
|
-
|
|
13837
|
-
|
|
13838
|
-
|
|
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();
|
|
13839
13429
|
await next();
|
|
13840
13430
|
});
|
|
13841
13431
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
@@ -13857,24 +13447,60 @@ if (!dev && webDir) {
|
|
|
13857
13447
|
});
|
|
13858
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."));
|
|
13859
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
|
+
}
|
|
13860
13470
|
const server = serve({
|
|
13861
13471
|
fetch: app.fetch,
|
|
13862
13472
|
port,
|
|
13863
13473
|
hostname: host
|
|
13864
13474
|
}, () => {
|
|
13865
|
-
printBanner(
|
|
13475
|
+
printBanner(addressesFor(webPort, where), {
|
|
13866
13476
|
version: version$1,
|
|
13867
13477
|
dev,
|
|
13868
13478
|
relay: settings.relay
|
|
13869
13479
|
});
|
|
13870
|
-
if (!dev)
|
|
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`);
|
|
13871
13496
|
if (settings.relay) startRelay({
|
|
13872
13497
|
relay: settings.relay,
|
|
13873
13498
|
home,
|
|
13874
|
-
token,
|
|
13875
13499
|
version: version$1,
|
|
13876
|
-
|
|
13877
|
-
|
|
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
|
|
13878
13504
|
}).then((started) => {
|
|
13879
13505
|
relay = started;
|
|
13880
13506
|
});
|
|
@@ -13887,6 +13513,7 @@ server.on("error", (error) => {
|
|
|
13887
13513
|
function shutdown() {
|
|
13888
13514
|
relay?.stop();
|
|
13889
13515
|
manager.stopAll();
|
|
13516
|
+
devices.flush();
|
|
13890
13517
|
server.close();
|
|
13891
13518
|
setTimeout(() => process.exit(0), 300).unref();
|
|
13892
13519
|
}
|