kiteline 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/{banner-DJdyE8-G.mjs → banner-CXnDgf5p.mjs} +73 -4
- package/dist/cli.mjs +10 -6
- package/dist/{package-D46-e3oS.mjs → package-CbMOnF6R.mjs} +1 -1
- package/dist/{service-1H4ozSPX.mjs → service-BCgNAv2Z.mjs} +3 -2
- package/dist/{show-pairing-jhFEXWi7.mjs → show-pairing-CTd0UfS1.mjs} +1 -1
- package/dist/show-pairing-Zurbk9wK.mjs +1 -0
- package/dist/{src-BnClcgTs.mjs → src-DSH8d4ZM.mjs} +520 -7
- package/dist/web/assets/{IconBase.es-CfbvcPwJ.js → IconBase.es-h0cGkmPy.js} +1 -1
- package/dist/web/assets/MagnifyingGlass.es-CpSmmHxy.js +1 -0
- package/dist/web/assets/{composer-B6OuQTWV.js → composer-WnPpY669.js} +1 -1
- package/dist/web/assets/{copy-button-DrJvfi1A.js → copy-button-DBETbWKF.js} +1 -1
- package/dist/web/assets/index-CTAi3HIp.js +11 -0
- package/dist/web/assets/lazy/{core-DbyPnbRm.js → core-CuC-kkU7.js} +1 -1
- package/dist/web/assets/{new-x01_nUpy.js → new-D_XEbYrm.js} +1 -1
- package/dist/web/assets/prefs-D6OSXuFe.js +1 -0
- package/dist/web/assets/routes-Csbxwlji.js +1 -0
- package/dist/web/assets/{s._sessionId-BtgSN22Q.js → s._sessionId-BlR4dPFc.js} +8 -8
- package/dist/web/assets/settings-DRpTnWMo.js +1 -0
- package/dist/web/assets/{status-BFb0ZUqi.js → status-C7fEa4v1.js} +1 -1
- package/dist/web/index.html +2 -2
- package/dist/web/sw.js +1 -1
- package/package.json +1 -1
- package/dist/show-pairing-u0LfkF9W.mjs +0 -1
- package/dist/web/assets/MagnifyingGlass.es-DLNPT1gT.js +0 -1
- package/dist/web/assets/index-Da9GDrpu.js +0 -11
- package/dist/web/assets/prefs-CliZrwNF.js +0 -1
- package/dist/web/assets/routes-NIOlnkZY.js +0 -1
- package/dist/web/assets/settings-B7yar__r.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as version$1 } from "./package-
|
|
2
|
-
import { a as loadToken, i as kitelineHome, n as PairLimiter, o as safeEqual, r as deviceSecret, t as DEVICE_COOKIE } from "./auth-YhkfTv6K.mjs";
|
|
3
|
-
import { a as printAlreadyRunning, c as savePairing, f as readSettings, l as SettingsError, o as printBanner, r as buildPairing, s as printSettingsError } from "./banner-
|
|
1
|
+
import { t as version$1 } from "./package-CbMOnF6R.mjs";
|
|
2
|
+
import { a as loadToken, i as kitelineHome, n as PairLimiter, o as safeEqual, r as deviceSecret$1, t as DEVICE_COOKIE } from "./auth-YhkfTv6K.mjs";
|
|
3
|
+
import { _ as hostIdFor, a as printAlreadyRunning, c as savePairing, f as readSettings, g as fromBase64Url, h as RelayPath, l as SettingsError, m as RelayClose, o as printBanner, r as buildPairing, s as printSettingsError, v as relaySocketUrl, y as toBase64Url } from "./banner-CXnDgf5p.mjs";
|
|
4
4
|
import { createReadStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { homedir, hostname, platform } from "node:os";
|
|
6
6
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -9,7 +9,7 @@ import { STATUS_CODES, ServerResponse, createServer } from "node:http";
|
|
|
9
9
|
import { Http2ServerRequest, constants } from "node:http2";
|
|
10
10
|
import { Readable } from "node:stream";
|
|
11
11
|
import { versions } from "node:process";
|
|
12
|
-
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
13
13
|
import { readdir, stat } from "node:fs/promises";
|
|
14
14
|
import { getSessionInfo, getSessionMessages, listSessions, query, renameSession, resolveSettings } from "@anthropic-ai/claude-agent-sdk";
|
|
15
15
|
// ../../node_modules/.pnpm/@hono+node-server@2.1.5_hono@4.13.14/node_modules/@hono/node-server/dist/index.mjs
|
|
@@ -13247,6 +13247,502 @@ function createContext({ authed, shared }) {
|
|
|
13247
13247
|
authed
|
|
13248
13248
|
};
|
|
13249
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
|
+
};
|
|
13262
|
+
var HandshakeError = class extends Error {};
|
|
13263
|
+
function concat(...parts) {
|
|
13264
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
13265
|
+
let at = 0;
|
|
13266
|
+
for (const part of parts) {
|
|
13267
|
+
out.set(part, at);
|
|
13268
|
+
at += part.length;
|
|
13269
|
+
}
|
|
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
|
+
}
|
|
13311
|
+
async function sha256(data) {
|
|
13312
|
+
return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
|
|
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"]);
|
|
13329
|
+
return {
|
|
13330
|
+
c2s: await aes("client-to-host"),
|
|
13331
|
+
s2c: await aes("host-to-client"),
|
|
13332
|
+
hostConfirm: await mac("host-confirm"),
|
|
13333
|
+
clientConfirm: await mac("client-confirm")
|
|
13334
|
+
};
|
|
13335
|
+
}
|
|
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
|
+
// ../../packages/api/src/tunnel/messages.ts
|
|
13391
|
+
/**
|
|
13392
|
+
* What travels inside the sealed tunnel: HTTP requests from the phone and streamed responses from
|
|
13393
|
+
* the computer, several at once, each on its own numbered stream.
|
|
13394
|
+
*/
|
|
13395
|
+
const Msg = {
|
|
13396
|
+
Request: 1,
|
|
13397
|
+
Body: 2,
|
|
13398
|
+
End: 3,
|
|
13399
|
+
Cancel: 4,
|
|
13400
|
+
Response: 17,
|
|
13401
|
+
Data: 18,
|
|
13402
|
+
Done: 19,
|
|
13403
|
+
Fail: 20,
|
|
13404
|
+
Ping: 32,
|
|
13405
|
+
Pong: 33
|
|
13406
|
+
};
|
|
13407
|
+
/** Body and response chunks stay under this, so one big reply never holds up the others for long. */
|
|
13408
|
+
const CHUNK = 65536;
|
|
13409
|
+
const encoder = new TextEncoder();
|
|
13410
|
+
const decoder = new TextDecoder();
|
|
13411
|
+
function pack(type, stream, payload) {
|
|
13412
|
+
const head = /* @__PURE__ */ new Uint8Array(5);
|
|
13413
|
+
head[0] = type;
|
|
13414
|
+
new DataView(head.buffer).setUint32(1, stream);
|
|
13415
|
+
return payload?.length ? concat(head, payload) : head;
|
|
13416
|
+
}
|
|
13417
|
+
function unpack(message) {
|
|
13418
|
+
if (message.length < 5) throw new Error("A tunnel message was cut short.");
|
|
13419
|
+
return {
|
|
13420
|
+
type: message[0],
|
|
13421
|
+
stream: new DataView(message.buffer, message.byteOffset, message.byteLength).getUint32(1),
|
|
13422
|
+
payload: message.subarray(5)
|
|
13423
|
+
};
|
|
13424
|
+
}
|
|
13425
|
+
const parseJson = (payload) => JSON.parse(decoder.decode(payload));
|
|
13426
|
+
const text = (value) => encoder.encode(value);
|
|
13427
|
+
// ../../packages/api/src/tunnel/socket.ts
|
|
13428
|
+
/** A WebSocket's messages as two in-order queues: frames for the tunnel, text for the relay's notes. */
|
|
13429
|
+
var FrameSocket = class {
|
|
13430
|
+
ws;
|
|
13431
|
+
frames = [];
|
|
13432
|
+
texts = [];
|
|
13433
|
+
waiting = [];
|
|
13434
|
+
ended = null;
|
|
13435
|
+
closeListeners = /* @__PURE__ */ new Set();
|
|
13436
|
+
constructor(ws) {
|
|
13437
|
+
this.ws = ws;
|
|
13438
|
+
ws.binaryType = "arraybuffer";
|
|
13439
|
+
ws.addEventListener("message", (event) => {
|
|
13440
|
+
const data = event.data;
|
|
13441
|
+
if (typeof data === "string") this.deliver(false, data);
|
|
13442
|
+
else if (data instanceof ArrayBuffer) this.deliver(true, new Uint8Array(data));
|
|
13443
|
+
});
|
|
13444
|
+
ws.addEventListener("close", (event) => this.end(event.code, event.reason));
|
|
13445
|
+
ws.addEventListener("error", () => this.end(1006, "connection error"));
|
|
13446
|
+
}
|
|
13447
|
+
get closed() {
|
|
13448
|
+
return this.ended;
|
|
13449
|
+
}
|
|
13450
|
+
onClose(listener) {
|
|
13451
|
+
if (this.ended) listener(this.ended.code, this.ended.reason);
|
|
13452
|
+
else this.closeListeners.add(listener);
|
|
13453
|
+
}
|
|
13454
|
+
deliver(binary, value) {
|
|
13455
|
+
const at = this.waiting.findIndex((w) => w.binary === binary);
|
|
13456
|
+
if (at !== -1) {
|
|
13457
|
+
const [waiter] = this.waiting.splice(at, 1);
|
|
13458
|
+
waiter?.resolve(value);
|
|
13459
|
+
} else if (binary) this.frames.push(value);
|
|
13460
|
+
else this.texts.push(value);
|
|
13461
|
+
}
|
|
13462
|
+
end(code, reason) {
|
|
13463
|
+
if (this.ended) return;
|
|
13464
|
+
this.ended = {
|
|
13465
|
+
code,
|
|
13466
|
+
reason
|
|
13467
|
+
};
|
|
13468
|
+
const error = new SocketClosed(code, reason);
|
|
13469
|
+
for (const waiter of this.waiting.splice(0)) waiter.reject(error);
|
|
13470
|
+
for (const listener of this.closeListeners) listener(code, reason);
|
|
13471
|
+
this.closeListeners.clear();
|
|
13472
|
+
}
|
|
13473
|
+
take(binary, timeoutMs) {
|
|
13474
|
+
const queued = binary ? this.frames.shift() : this.texts.shift();
|
|
13475
|
+
if (queued !== void 0) return Promise.resolve(queued);
|
|
13476
|
+
if (this.ended) return Promise.reject(new SocketClosed(this.ended.code, this.ended.reason));
|
|
13477
|
+
return new Promise((resolve, reject) => {
|
|
13478
|
+
const waiter = {
|
|
13479
|
+
binary,
|
|
13480
|
+
resolve,
|
|
13481
|
+
reject
|
|
13482
|
+
};
|
|
13483
|
+
this.waiting.push(waiter);
|
|
13484
|
+
if (timeoutMs !== void 0) setTimeout(() => {
|
|
13485
|
+
const at = this.waiting.indexOf(waiter);
|
|
13486
|
+
if (at === -1) return;
|
|
13487
|
+
this.waiting.splice(at, 1);
|
|
13488
|
+
reject(new SocketTimeout());
|
|
13489
|
+
}, timeoutMs);
|
|
13490
|
+
});
|
|
13491
|
+
}
|
|
13492
|
+
next(timeoutMs) {
|
|
13493
|
+
return this.take(true, timeoutMs);
|
|
13494
|
+
}
|
|
13495
|
+
nextText(timeoutMs) {
|
|
13496
|
+
return this.take(false, timeoutMs);
|
|
13497
|
+
}
|
|
13498
|
+
send(frame) {
|
|
13499
|
+
if (this.ws.readyState === WebSocket.OPEN) this.ws.send(frame);
|
|
13500
|
+
}
|
|
13501
|
+
close(code, reason) {
|
|
13502
|
+
try {
|
|
13503
|
+
this.ws.close(code, reason.slice(0, 120));
|
|
13504
|
+
} catch {
|
|
13505
|
+
this.ws.close();
|
|
13506
|
+
}
|
|
13507
|
+
this.end(code, reason);
|
|
13508
|
+
}
|
|
13509
|
+
};
|
|
13510
|
+
var SocketClosed = class extends Error {
|
|
13511
|
+
code;
|
|
13512
|
+
reason;
|
|
13513
|
+
constructor(code, reason) {
|
|
13514
|
+
super(reason || `Connection closed (${code}).`);
|
|
13515
|
+
this.code = code;
|
|
13516
|
+
this.reason = reason;
|
|
13517
|
+
}
|
|
13518
|
+
};
|
|
13519
|
+
var SocketTimeout = class extends Error {
|
|
13520
|
+
constructor() {
|
|
13521
|
+
super("Timed out.");
|
|
13522
|
+
}
|
|
13523
|
+
};
|
|
13524
|
+
// ../../packages/api/src/tunnel/host.ts
|
|
13525
|
+
/** More than the biggest real request: six photos at the limit, base64 in JSON. */
|
|
13526
|
+
const MAX_BODY = 41943040;
|
|
13527
|
+
const HANDSHAKE_MS = 2e4;
|
|
13528
|
+
/**
|
|
13529
|
+
* The computer's end of one phone's tunnel. Answers the handshake, refuses a phone that can't prove
|
|
13530
|
+
* the pairing, then turns each request into a `Request` for `handle` and streams the answer back.
|
|
13531
|
+
*/
|
|
13532
|
+
async function serveTunnel(ws, secret, handle) {
|
|
13533
|
+
const socket = new FrameSocket(ws);
|
|
13534
|
+
let cipher;
|
|
13535
|
+
try {
|
|
13536
|
+
cipher = await respond(secret, await socket.next(HANDSHAKE_MS), (frame) => socket.send(frame), () => socket.next(HANDSHAKE_MS));
|
|
13537
|
+
} catch (error) {
|
|
13538
|
+
const unpaired = error instanceof HandshakeError;
|
|
13539
|
+
socket.close(unpaired ? RelayClose.NotPaired : RelayClose.BadRequest, unpaired ? "not paired" : "bad handshake");
|
|
13540
|
+
return;
|
|
13541
|
+
}
|
|
13542
|
+
const streams = /* @__PURE__ */ new Map();
|
|
13543
|
+
let sending = Promise.resolve();
|
|
13544
|
+
let closed = false;
|
|
13545
|
+
socket.onClose(() => {
|
|
13546
|
+
closed = true;
|
|
13547
|
+
for (const stream of streams.values()) stream.abort.abort();
|
|
13548
|
+
streams.clear();
|
|
13549
|
+
});
|
|
13550
|
+
const post = (type, stream, payload) => {
|
|
13551
|
+
const message = pack(type, stream, payload);
|
|
13552
|
+
sending = sending.then(async () => {
|
|
13553
|
+
if (!closed) socket.send(await cipher.seal(message));
|
|
13554
|
+
});
|
|
13555
|
+
sending.catch(() => socket.close(RelayClose.BadRequest, "send failed"));
|
|
13556
|
+
return sending;
|
|
13557
|
+
};
|
|
13558
|
+
const run = async (id, stream) => {
|
|
13559
|
+
const { head } = stream;
|
|
13560
|
+
try {
|
|
13561
|
+
const body = head.body && !["GET", "HEAD"].includes(head.method) ? joinChunks(stream.chunks, stream.size) : null;
|
|
13562
|
+
const response = await handle(new Request(new URL(head.path, "http://kiteline.tunnel"), {
|
|
13563
|
+
method: head.method,
|
|
13564
|
+
headers: head.headers,
|
|
13565
|
+
body,
|
|
13566
|
+
signal: stream.abort.signal
|
|
13567
|
+
}));
|
|
13568
|
+
if (!streams.has(id)) return;
|
|
13569
|
+
await post(Msg.Response, id, new TextEncoder().encode(JSON.stringify({
|
|
13570
|
+
status: response.status,
|
|
13571
|
+
headers: [...response.headers]
|
|
13572
|
+
})));
|
|
13573
|
+
if (response.body) {
|
|
13574
|
+
const reader = response.body.getReader();
|
|
13575
|
+
stream.abort.signal.addEventListener("abort", () => void reader.cancel().catch(() => {}), { once: true });
|
|
13576
|
+
for (;;) {
|
|
13577
|
+
const { done, value } = await reader.read();
|
|
13578
|
+
if (done || !streams.has(id)) break;
|
|
13579
|
+
for (let at = 0; at < value.length; at += CHUNK) await post(Msg.Data, id, value.subarray(at, at + CHUNK));
|
|
13580
|
+
}
|
|
13581
|
+
}
|
|
13582
|
+
if (streams.delete(id)) await post(Msg.Done, id);
|
|
13583
|
+
} catch (error) {
|
|
13584
|
+
if (streams.delete(id) && !stream.abort.signal.aborted) await post(Msg.Fail, id, text(error instanceof Error ? error.message : String(error)));
|
|
13585
|
+
}
|
|
13586
|
+
};
|
|
13587
|
+
try {
|
|
13588
|
+
for (;;) {
|
|
13589
|
+
const frame = await socket.next();
|
|
13590
|
+
const { type, stream: id, payload } = unpack(await cipher.open(frame));
|
|
13591
|
+
switch (type) {
|
|
13592
|
+
case Msg.Ping:
|
|
13593
|
+
post(Msg.Pong, 0);
|
|
13594
|
+
break;
|
|
13595
|
+
case Msg.Request: {
|
|
13596
|
+
if (streams.has(id)) break;
|
|
13597
|
+
const stream = {
|
|
13598
|
+
head: parseJson(payload),
|
|
13599
|
+
chunks: [],
|
|
13600
|
+
size: 0,
|
|
13601
|
+
abort: new AbortController()
|
|
13602
|
+
};
|
|
13603
|
+
streams.set(id, stream);
|
|
13604
|
+
if (!stream.head.body) run(id, stream);
|
|
13605
|
+
break;
|
|
13606
|
+
}
|
|
13607
|
+
case Msg.Body: {
|
|
13608
|
+
const stream = streams.get(id);
|
|
13609
|
+
if (!stream) break;
|
|
13610
|
+
stream.size += payload.length;
|
|
13611
|
+
if (stream.size > MAX_BODY) {
|
|
13612
|
+
streams.delete(id);
|
|
13613
|
+
post(Msg.Fail, id, text("That's too big to send."));
|
|
13614
|
+
break;
|
|
13615
|
+
}
|
|
13616
|
+
stream.chunks.push(payload.slice());
|
|
13617
|
+
break;
|
|
13618
|
+
}
|
|
13619
|
+
case Msg.End: {
|
|
13620
|
+
const stream = streams.get(id);
|
|
13621
|
+
if (stream) run(id, stream);
|
|
13622
|
+
break;
|
|
13623
|
+
}
|
|
13624
|
+
case Msg.Cancel: {
|
|
13625
|
+
const stream = streams.get(id);
|
|
13626
|
+
streams.delete(id);
|
|
13627
|
+
stream?.abort.abort();
|
|
13628
|
+
break;
|
|
13629
|
+
}
|
|
13630
|
+
}
|
|
13631
|
+
}
|
|
13632
|
+
} catch {
|
|
13633
|
+
socket.close(1e3, "closing");
|
|
13634
|
+
}
|
|
13635
|
+
}
|
|
13636
|
+
function joinChunks(chunks, size) {
|
|
13637
|
+
const out = new Uint8Array(size);
|
|
13638
|
+
let at = 0;
|
|
13639
|
+
for (const chunk of chunks) {
|
|
13640
|
+
out.set(chunk, at);
|
|
13641
|
+
at += chunk.length;
|
|
13642
|
+
}
|
|
13643
|
+
return out;
|
|
13644
|
+
}
|
|
13645
|
+
// src/relay.ts
|
|
13646
|
+
/** The relay's secret for this computer, kept beside the pairing token. Its hash is our address. */
|
|
13647
|
+
function relaySecret(home) {
|
|
13648
|
+
const file = join(home, "relay.json");
|
|
13649
|
+
try {
|
|
13650
|
+
const stored = JSON.parse(readFileSync(file, "utf8"));
|
|
13651
|
+
if (typeof stored.secret === "string" && /^[\w-]{43}$/.test(stored.secret)) return stored.secret;
|
|
13652
|
+
} catch {}
|
|
13653
|
+
const secret = toBase64Url(randomBytes(32));
|
|
13654
|
+
mkdirSync(home, {
|
|
13655
|
+
recursive: true,
|
|
13656
|
+
mode: 448
|
|
13657
|
+
});
|
|
13658
|
+
writeFileSync(file, `${JSON.stringify({
|
|
13659
|
+
secret,
|
|
13660
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
13661
|
+
}, null, 2)}\n`, { mode: 384 });
|
|
13662
|
+
return secret;
|
|
13663
|
+
}
|
|
13664
|
+
/** Only the API and the pairing check go through: the phone's app comes from the relay itself. */
|
|
13665
|
+
function allowed(request) {
|
|
13666
|
+
const { pathname } = new URL(request.url);
|
|
13667
|
+
return (request.method === "POST" || request.method === "GET") && (pathname.startsWith("/rpc/") || pathname === "/auth/status");
|
|
13668
|
+
}
|
|
13669
|
+
async function hostAddress(home) {
|
|
13670
|
+
return hostIdFor(fromBase64Url(relaySecret(home)));
|
|
13671
|
+
}
|
|
13672
|
+
async function startRelay(options) {
|
|
13673
|
+
const secret = relaySecret(options.home);
|
|
13674
|
+
const hostId = await hostIdFor(fromBase64Url(secret));
|
|
13675
|
+
const pairingKey = await importSecret(await deviceSecret(options.token));
|
|
13676
|
+
const handle = async (request) => {
|
|
13677
|
+
if (!allowed(request)) return new Response("Not through the relay.", { status: 404 });
|
|
13678
|
+
const headers = new Headers(request.headers);
|
|
13679
|
+
headers.delete("cookie");
|
|
13680
|
+
headers.set("authorization", `Bearer ${options.token}`);
|
|
13681
|
+
return options.handle(new Request(request, { headers }));
|
|
13682
|
+
};
|
|
13683
|
+
let attempt = 0;
|
|
13684
|
+
let connected = false;
|
|
13685
|
+
let stopped = false;
|
|
13686
|
+
let socket = null;
|
|
13687
|
+
let silence = null;
|
|
13688
|
+
const connect = () => {
|
|
13689
|
+
if (stopped) return;
|
|
13690
|
+
const ws = new WebSocket(relaySocketUrl(options.relay, RelayPath.host));
|
|
13691
|
+
socket = ws;
|
|
13692
|
+
let lastHeard = Date.now();
|
|
13693
|
+
ws.addEventListener("open", () => {
|
|
13694
|
+
ws.send(JSON.stringify({
|
|
13695
|
+
t: "hello",
|
|
13696
|
+
secret,
|
|
13697
|
+
version: options.version
|
|
13698
|
+
}));
|
|
13699
|
+
silence = setInterval(() => {
|
|
13700
|
+
if (Date.now() - lastHeard > 75e3) ws.close();
|
|
13701
|
+
else ws.send(JSON.stringify({ t: "ping" }));
|
|
13702
|
+
}, 3e4);
|
|
13703
|
+
});
|
|
13704
|
+
ws.addEventListener("message", (event) => {
|
|
13705
|
+
lastHeard = Date.now();
|
|
13706
|
+
let message;
|
|
13707
|
+
try {
|
|
13708
|
+
message = JSON.parse(String(event.data));
|
|
13709
|
+
} catch {
|
|
13710
|
+
return;
|
|
13711
|
+
}
|
|
13712
|
+
if (message.t === "ready") {
|
|
13713
|
+
attempt = 0;
|
|
13714
|
+
if (!connected) options.log("Connected to the relay: phones can reach this computer from anywhere.");
|
|
13715
|
+
connected = true;
|
|
13716
|
+
} else if (message.t === "open" && /^[\w-]{22}$/.test(message.channel)) serveTunnel(new WebSocket(relaySocketUrl(options.relay, RelayPath.data + message.channel)), pairingKey, handle);
|
|
13717
|
+
});
|
|
13718
|
+
ws.addEventListener("close", (event) => {
|
|
13719
|
+
if (silence) clearInterval(silence);
|
|
13720
|
+
if (stopped) return;
|
|
13721
|
+
if (connected) options.log("Lost the relay; reconnecting.");
|
|
13722
|
+
else if (attempt === 0) {
|
|
13723
|
+
const why = event.code === RelayClose.TooMany ? "it's full right now" : "couldn't reach it";
|
|
13724
|
+
options.log(`The relay at ${options.relay} isn't answering (${why}); retrying in the background.`);
|
|
13725
|
+
}
|
|
13726
|
+
connected = false;
|
|
13727
|
+
attempt++;
|
|
13728
|
+
const wait = Math.min(3e4, 1e3 * 2 ** Math.min(attempt, 5)) + Math.random() * 1e3;
|
|
13729
|
+
setTimeout(connect, wait).unref();
|
|
13730
|
+
});
|
|
13731
|
+
ws.addEventListener("error", () => {});
|
|
13732
|
+
};
|
|
13733
|
+
connect();
|
|
13734
|
+
return {
|
|
13735
|
+
hostId,
|
|
13736
|
+
get connected() {
|
|
13737
|
+
return connected;
|
|
13738
|
+
},
|
|
13739
|
+
stop() {
|
|
13740
|
+
stopped = true;
|
|
13741
|
+
if (silence) clearInterval(silence);
|
|
13742
|
+
socket?.close();
|
|
13743
|
+
}
|
|
13744
|
+
};
|
|
13745
|
+
}
|
|
13250
13746
|
// src/index.ts
|
|
13251
13747
|
const dev = process.argv.includes("--dev");
|
|
13252
13748
|
let settings;
|
|
@@ -13263,10 +13759,14 @@ const token = loadToken(home, {
|
|
|
13263
13759
|
fixed: settings.token,
|
|
13264
13760
|
rotate: process.argv.includes("--new-token")
|
|
13265
13761
|
});
|
|
13266
|
-
const secret = deviceSecret(token);
|
|
13762
|
+
const secret = deviceSecret$1(token);
|
|
13267
13763
|
const pairing = buildPairing(dev ? 4546 : port, token, {
|
|
13268
13764
|
publicUrl: settings.publicUrl,
|
|
13269
|
-
loopbackOnly: host === "127.0.0.1" || host === "localhost"
|
|
13765
|
+
loopbackOnly: host === "127.0.0.1" || host === "localhost",
|
|
13766
|
+
...settings.relay ? { relay: {
|
|
13767
|
+
url: settings.relay,
|
|
13768
|
+
hostId: await hostAddress(home)
|
|
13769
|
+
} } : {}
|
|
13270
13770
|
});
|
|
13271
13771
|
const limiter = new PairLimiter();
|
|
13272
13772
|
const manager = new RunManager({
|
|
@@ -13356,6 +13856,7 @@ if (!dev && webDir) {
|
|
|
13356
13856
|
return c.html(indexHtml);
|
|
13357
13857
|
});
|
|
13358
13858
|
} 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
|
+
let relay = null;
|
|
13359
13860
|
const server = serve({
|
|
13360
13861
|
fetch: app.fetch,
|
|
13361
13862
|
port,
|
|
@@ -13363,9 +13864,20 @@ const server = serve({
|
|
|
13363
13864
|
}, () => {
|
|
13364
13865
|
printBanner(pairing, {
|
|
13365
13866
|
version: version$1,
|
|
13366
|
-
dev
|
|
13867
|
+
dev,
|
|
13868
|
+
relay: settings.relay
|
|
13367
13869
|
});
|
|
13368
13870
|
if (!dev) savePairing(home, pairing, version$1);
|
|
13871
|
+
if (settings.relay) startRelay({
|
|
13872
|
+
relay: settings.relay,
|
|
13873
|
+
home,
|
|
13874
|
+
token,
|
|
13875
|
+
version: version$1,
|
|
13876
|
+
handle: (request) => app.fetch(request),
|
|
13877
|
+
log: (message) => console.log(` ${message}`)
|
|
13878
|
+
}).then((started) => {
|
|
13879
|
+
relay = started;
|
|
13880
|
+
});
|
|
13369
13881
|
});
|
|
13370
13882
|
server.on("error", (error) => {
|
|
13371
13883
|
if (error.code !== "EADDRINUSE") throw error;
|
|
@@ -13373,6 +13885,7 @@ server.on("error", (error) => {
|
|
|
13373
13885
|
process.exit(1);
|
|
13374
13886
|
});
|
|
13375
13887
|
function shutdown() {
|
|
13888
|
+
relay?.stop();
|
|
13376
13889
|
manager.stopAll();
|
|
13377
13890
|
server.close();
|
|
13378
13891
|
setTimeout(() => process.exit(0), 300).unref();
|