litepaseo 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +78 -0
- package/README.md +113 -39
- package/dist/server/cli.mjs +1346 -150
- package/dist/web/assets/{CodeBlockNode-CehKIzSk.js → CodeBlockNode-fLbELjCG.js} +1 -1
- package/dist/web/assets/CodeBlockNode-fLbELjCG.js.br +0 -0
- package/dist/web/assets/CodeBlockNode-fLbELjCG.js.gz +0 -0
- package/dist/web/assets/{FileViewer-01t53KTX.js → FileViewer-C7zGfiFt.js} +1 -1
- package/dist/web/assets/FileViewer-C7zGfiFt.js.br +0 -0
- package/dist/web/assets/FileViewer-C7zGfiFt.js.gz +0 -0
- package/dist/web/assets/{FilesPanel-B7NknFvl.js → FilesPanel-B1YfdWK8.js} +1 -1
- package/dist/web/assets/FilesPanel-B1YfdWK8.js.br +0 -0
- package/dist/web/assets/FilesPanel-B1YfdWK8.js.gz +0 -0
- package/dist/web/assets/{MarkdownMessage-UlvozPc5.js → MarkdownMessage-C30PkBRA.js} +5 -5
- package/dist/web/assets/MarkdownMessage-C30PkBRA.js.br +0 -0
- package/dist/web/assets/{MarkdownMessage-UlvozPc5.js.gz → MarkdownMessage-C30PkBRA.js.gz} +0 -0
- package/dist/web/assets/{PreCodeBlock-DPQTlYty.js → PreCodeBlock-3ozveRNf.js} +1 -1
- package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js → PreCodeBlock.vue_vue_type_style_index_0_lang-BPnMZFbo.js} +1 -1
- package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-BPnMZFbo.js.br +0 -0
- package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-BPnMZFbo.js.gz +0 -0
- package/dist/web/assets/{TerminalPanel-BdmAonFr.js → TerminalPanel-BR2okuCE.js} +1 -1
- package/dist/web/assets/TerminalPanel-BR2okuCE.js.br +0 -0
- package/dist/web/assets/TerminalPanel-BR2okuCE.js.gz +0 -0
- package/dist/web/assets/{Tooltip-BJ2o2M_0.js → Tooltip-Dh7ELGI1.js} +1 -1
- package/dist/web/assets/Tooltip-Dh7ELGI1.js.br +0 -0
- package/dist/web/assets/Tooltip-Dh7ELGI1.js.gz +0 -0
- package/dist/web/assets/index-BJ4CkuXT.js +30 -0
- package/dist/web/assets/index-BJ4CkuXT.js.br +0 -0
- package/dist/web/assets/index-BJ4CkuXT.js.gz +0 -0
- package/dist/web/assets/index-CaFqUnEO.css +1 -0
- package/dist/web/assets/index-CaFqUnEO.css.br +0 -0
- package/dist/web/assets/index-CaFqUnEO.css.gz +0 -0
- package/dist/web/assets/{index10-WpTfisco.js → index10-BXOnBXXV.js} +1 -1
- package/dist/web/assets/index10-BXOnBXXV.js.br +0 -0
- package/dist/web/assets/index10-BXOnBXXV.js.gz +0 -0
- package/dist/web/assets/index3-C1CbKHXb.js +1 -0
- package/dist/web/assets/index4-CE4EA6Rx.js +1 -0
- package/dist/web/assets/{index5-BCbIyN1t.js → index5-BrR0S3K6.js} +1 -1
- package/dist/web/assets/index5-BrR0S3K6.js.br +0 -0
- package/dist/web/assets/index5-BrR0S3K6.js.gz +0 -0
- package/dist/web/assets/{index6-CbdnTDhy.js → index6-DWBoE2gM.js} +1 -1
- package/dist/web/assets/index6-DWBoE2gM.js.br +0 -0
- package/dist/web/assets/index6-DWBoE2gM.js.gz +0 -0
- package/dist/web/assets/{index7-BzNzdNxO.js → index7-CoJTOvQ5.js} +1 -1
- package/dist/web/assets/index7-CoJTOvQ5.js.br +0 -0
- package/dist/web/assets/index7-CoJTOvQ5.js.gz +0 -0
- package/dist/web/assets/{index8-CD8jmACo.js → index8-CQGhir4p.js} +1 -1
- package/dist/web/assets/index8-CQGhir4p.js.br +0 -0
- package/dist/web/assets/index8-CQGhir4p.js.gz +0 -0
- package/dist/web/assets/{index9-9FYLmtt9.js → index9-D_kItRZJ.js} +1 -1
- package/dist/web/assets/index9-D_kItRZJ.js.br +0 -0
- package/dist/web/assets/index9-D_kItRZJ.js.gz +0 -0
- package/dist/web/index.html +2 -2
- package/dist/web/index.html.br +0 -0
- package/dist/web/index.html.gz +0 -0
- package/docs/cloudflare-access.md +111 -0
- package/docs/performance-plan.md +119 -241
- package/package.json +5 -2
- package/dist/web/assets/CodeBlockNode-CehKIzSk.js.br +0 -0
- package/dist/web/assets/CodeBlockNode-CehKIzSk.js.gz +0 -0
- package/dist/web/assets/FileViewer-01t53KTX.js.br +0 -0
- package/dist/web/assets/FileViewer-01t53KTX.js.gz +0 -0
- package/dist/web/assets/FilesPanel-B7NknFvl.js.br +0 -0
- package/dist/web/assets/FilesPanel-B7NknFvl.js.gz +0 -0
- package/dist/web/assets/MarkdownMessage-UlvozPc5.js.br +0 -0
- package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js.br +0 -0
- package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js.gz +0 -0
- package/dist/web/assets/TerminalPanel-BdmAonFr.js.br +0 -0
- package/dist/web/assets/TerminalPanel-BdmAonFr.js.gz +0 -0
- package/dist/web/assets/Tooltip-BJ2o2M_0.js.br +0 -0
- package/dist/web/assets/Tooltip-BJ2o2M_0.js.gz +0 -0
- package/dist/web/assets/index-D_YTh7Zw.css +0 -1
- package/dist/web/assets/index-D_YTh7Zw.css.br +0 -0
- package/dist/web/assets/index-D_YTh7Zw.css.gz +0 -0
- package/dist/web/assets/index-civcSERr.js +0 -27
- package/dist/web/assets/index-civcSERr.js.br +0 -0
- package/dist/web/assets/index-civcSERr.js.gz +0 -0
- package/dist/web/assets/index10-WpTfisco.js.br +0 -0
- package/dist/web/assets/index10-WpTfisco.js.gz +0 -0
- package/dist/web/assets/index3-C4yf5W5o.js +0 -1
- package/dist/web/assets/index4-Cwl0ij4U.js +0 -1
- package/dist/web/assets/index5-BCbIyN1t.js.br +0 -0
- package/dist/web/assets/index5-BCbIyN1t.js.gz +0 -0
- package/dist/web/assets/index6-CbdnTDhy.js.br +0 -0
- package/dist/web/assets/index6-CbdnTDhy.js.gz +0 -0
- package/dist/web/assets/index7-BzNzdNxO.js.br +0 -0
- package/dist/web/assets/index7-BzNzdNxO.js.gz +0 -0
- package/dist/web/assets/index8-CD8jmACo.js.br +0 -0
- package/dist/web/assets/index8-CD8jmACo.js.gz +0 -0
- package/dist/web/assets/index9-9FYLmtt9.js.br +0 -0
- package/dist/web/assets/index9-9FYLmtt9.js.gz +0 -0
- package/docs/operations.md +0 -143
package/dist/server/cli.mjs
CHANGED
|
@@ -20,9 +20,10 @@ import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
|
20
20
|
import QRCode from "qrcode";
|
|
21
21
|
import { AgentPermissionResponseSchema } from "@getpaseo/protocol/messages";
|
|
22
22
|
import webpush from "web-push";
|
|
23
|
+
import WebSocket, { WebSocketServer } from "ws";
|
|
23
24
|
import { fileURLToPath } from "node:url";
|
|
24
25
|
// src/server/version.ts
|
|
25
|
-
const VERSION = "0.
|
|
26
|
+
const VERSION = "0.3.1";
|
|
26
27
|
// src/server/rotating-log.ts
|
|
27
28
|
/** One writer (the supervisor); bounded active file plus numbered archives. */
|
|
28
29
|
var RotatingLog = class {
|
|
@@ -308,6 +309,7 @@ async function supervise(directory, cliPath, options = {}) {
|
|
|
308
309
|
await recoverSocket(path);
|
|
309
310
|
let child = null, stopping = false, ready = false, url = "", restarts = 0;
|
|
310
311
|
let failure = null, lastError = "";
|
|
312
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
311
313
|
let retry;
|
|
312
314
|
let killTimer;
|
|
313
315
|
let finish;
|
|
@@ -397,6 +399,8 @@ async function supervise(directory, cliPath, options = {}) {
|
|
|
397
399
|
if (input === "status") socket.end(JSON.stringify({
|
|
398
400
|
ready,
|
|
399
401
|
url,
|
|
402
|
+
version: VERSION,
|
|
403
|
+
startedAt,
|
|
400
404
|
pid: process.pid,
|
|
401
405
|
workerPid: child?.pid ?? null,
|
|
402
406
|
restarts,
|
|
@@ -2374,10 +2378,47 @@ function matchTotp(secret, code, now = Date.now()) {
|
|
|
2374
2378
|
return null;
|
|
2375
2379
|
}
|
|
2376
2380
|
const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
+
/** Compares digests, so neither the content nor the length of the secret leaks through timing. */
|
|
2382
|
+
const equalSecret = (a, b) => timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
|
|
2383
|
+
const MIN_DISTINCT_CHARACTERS = 8;
|
|
2384
|
+
const generateToken = () => randomBytes(32).toString("hex");
|
|
2385
|
+
/** Why a chosen access token is refused, or null when it is acceptable. */
|
|
2386
|
+
function tokenProblem(token) {
|
|
2387
|
+
if (token.length < 16) return `The token needs at least 16 characters.`;
|
|
2388
|
+
if (token.length > 200) return `The token can have at most 200 characters.`;
|
|
2389
|
+
if (!/^[\x21-\x7e]+$/.test(token)) return "Use letters, digits and punctuation only (no spaces or other characters).";
|
|
2390
|
+
if (new Set(token).size < MIN_DISTINCT_CHARACTERS) return `Use at least ${MIN_DISTINCT_CHARACTERS} different characters.`;
|
|
2391
|
+
return null;
|
|
2392
|
+
}
|
|
2393
|
+
/** Replaces the token file in one step, readable only by its owner. */
|
|
2394
|
+
function writeTokenFile(path, token) {
|
|
2395
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
2396
|
+
writeFileSync(temporary, token + "\n", { mode: 384 });
|
|
2397
|
+
renameSync(temporary, path);
|
|
2398
|
+
}
|
|
2399
|
+
/**
|
|
2400
|
+
* The current token from its file. Re-read when the file changes, so `litepaseo token set` and
|
|
2401
|
+
* `token rotate` take effect in a running server. A missing or unreadable file admits nobody.
|
|
2402
|
+
*/
|
|
2403
|
+
function tokenFile(path) {
|
|
2404
|
+
let cached = {
|
|
2405
|
+
key: "",
|
|
2406
|
+
token: ""
|
|
2407
|
+
};
|
|
2408
|
+
return () => {
|
|
2409
|
+
try {
|
|
2410
|
+
const info = statSync(path);
|
|
2411
|
+
const key = `${info.ino}:${info.mtimeMs}:${info.size}`;
|
|
2412
|
+
if (key !== cached.key) cached = {
|
|
2413
|
+
key,
|
|
2414
|
+
token: readFileSync(path, "utf8").trim()
|
|
2415
|
+
};
|
|
2416
|
+
return cached.token;
|
|
2417
|
+
} catch {
|
|
2418
|
+
return "";
|
|
2419
|
+
}
|
|
2420
|
+
};
|
|
2421
|
+
}
|
|
2381
2422
|
/**
|
|
2382
2423
|
* Login and sessions. A browser signs in once, with the access token and, when enabled, an authenticator code,
|
|
2383
2424
|
* and receives an opaque session secret (stored only as a hash). Sessions are listed and
|
|
@@ -2396,7 +2437,7 @@ var Auth = class {
|
|
|
2396
2437
|
pendingTotp = null;
|
|
2397
2438
|
constructor(store, token) {
|
|
2398
2439
|
this.store = store;
|
|
2399
|
-
this.token = token;
|
|
2440
|
+
this.token = typeof token === "string" ? () => token : token;
|
|
2400
2441
|
const saved = store.setting("totp_login_limit");
|
|
2401
2442
|
if (saved) this.global = JSON.parse(saved);
|
|
2402
2443
|
if (store.setting("auth_policy") !== "token-plus-totp-v1") {
|
|
@@ -2414,9 +2455,30 @@ var Auth = class {
|
|
|
2414
2455
|
totpEnabled() {
|
|
2415
2456
|
return this.store.setting("totp_secret") !== null;
|
|
2416
2457
|
}
|
|
2417
|
-
/**
|
|
2458
|
+
/** Whether `token` is the current access token. */
|
|
2418
2459
|
checkToken(token) {
|
|
2419
|
-
|
|
2460
|
+
const expected = this.token();
|
|
2461
|
+
return !!expected && equalSecret(token, expected);
|
|
2462
|
+
}
|
|
2463
|
+
/**
|
|
2464
|
+
* A bearer token (scripts on this machine) authenticates without creating a session. It
|
|
2465
|
+
* draws on the same failure budget as sign-in, so it cannot be used to guess the token.
|
|
2466
|
+
*/
|
|
2467
|
+
bearer(token, client, now = Date.now()) {
|
|
2468
|
+
const limit = this.limited(client, false, now);
|
|
2469
|
+
if (limit) return {
|
|
2470
|
+
ok: false,
|
|
2471
|
+
status: 429,
|
|
2472
|
+
retryAfter: limit
|
|
2473
|
+
};
|
|
2474
|
+
if (!this.checkToken(token)) {
|
|
2475
|
+
this.fail(client, false, now);
|
|
2476
|
+
return {
|
|
2477
|
+
ok: false,
|
|
2478
|
+
status: 401
|
|
2479
|
+
};
|
|
2480
|
+
}
|
|
2481
|
+
return { ok: true };
|
|
2420
2482
|
}
|
|
2421
2483
|
login(input, client, label, now = Date.now()) {
|
|
2422
2484
|
const tokenLimit = this.limited(client, false, now);
|
|
@@ -2802,10 +2864,622 @@ var UsageService = class {
|
|
|
2802
2864
|
return request;
|
|
2803
2865
|
}
|
|
2804
2866
|
};
|
|
2867
|
+
// src/server/dictation.ts
|
|
2868
|
+
/**
|
|
2869
|
+
* File transcription for phrases from dictation-stream and complete clips from older clients.
|
|
2870
|
+
* Wraps mono PCM as WAV for an OpenAI-compatible `/audio/transcriptions` endpoint.
|
|
2871
|
+
* Voice input is configured in LitePaseo; no Paseo host is involved.
|
|
2872
|
+
*
|
|
2873
|
+
* Request shape differs by model generation (OpenAI speech-to-text guide, 2026):
|
|
2874
|
+
* - `gpt-transcribe` takes `languages[]` (several expected languages, for code-switching) and
|
|
2875
|
+
* `keywords[]`; it "replaces the singular `language` field. Don't send both fields."
|
|
2876
|
+
* - `whisper-1`, `gpt-4o(-mini)-transcribe` and most compatible providers (Groq, local Whisper
|
|
2877
|
+
* servers) take a single `language` and a free-text `prompt`.
|
|
2878
|
+
* Paseo always sends `language` (default "en"), which is what breaks `gpt-transcribe` there.
|
|
2879
|
+
* Here the shape follows the model name, and a 400 about the language field retries once with
|
|
2880
|
+
* the other shape, so unknown models on compatible providers still work.
|
|
2881
|
+
*/
|
|
2882
|
+
const DEFAULT_BASE_URL = "https://api.openai.com/v1";
|
|
2883
|
+
/** Five minutes of 16 kHz, 16-bit mono speech (9.6 MB as WAV, under the 25 MB upload limit). */
|
|
2884
|
+
const MAX_DICTATION_BYTES = 96e5;
|
|
2885
|
+
const SETTING = "dictation";
|
|
2886
|
+
const UPSTREAM_TIMEOUT_MS = 11e4;
|
|
2887
|
+
/** Whisper reads at most 224 prompt tokens; keep the folded vocabulary well under that. */
|
|
2888
|
+
const LEGACY_PROMPT_CHARS = 600;
|
|
2889
|
+
const baseUrl = z.string().trim().max(500).transform((v) => (v || "https://api.openai.com/v1").replace(/\/+$/, "")).refine((v) => {
|
|
2890
|
+
try {
|
|
2891
|
+
return ["http:", "https:"].includes(new URL(v).protocol);
|
|
2892
|
+
} catch {
|
|
2893
|
+
return false;
|
|
2894
|
+
}
|
|
2895
|
+
}, "Base URL must be an http(s) address");
|
|
2896
|
+
const languageCode = z.string().trim().transform((v) => v.toLowerCase().replace("_", "-")).refine((v) => /^[a-z]{2,3}(-[a-z]{2})?$/.test(v), "Languages must be codes such as en, zh or zh-tw");
|
|
2897
|
+
/** The API rejects the whole request for a keyword with <, > or a line break. */
|
|
2898
|
+
const keyword = z.string().trim().min(1).max(100, "Each vocabulary term must be under 100 characters").refine((v) => !/[<>\r\n]/.test(v), "Vocabulary terms cannot contain < or >");
|
|
2899
|
+
const unique = (values) => [...new Set(values)];
|
|
2900
|
+
const DictationUpdate = z.object({
|
|
2901
|
+
baseUrl: baseUrl.optional().default(DEFAULT_BASE_URL),
|
|
2902
|
+
/** Omitted or empty keeps the saved key. */
|
|
2903
|
+
apiKey: z.string().trim().max(1e3).optional(),
|
|
2904
|
+
model: z.string().trim().max(200).optional().transform((v) => v || "gpt-transcribe"),
|
|
2905
|
+
languages: z.array(languageCode).max(10, "At most 10 languages").optional().default([]).transform(unique),
|
|
2906
|
+
keywords: z.array(keyword).max(100, "At most 100 vocabulary terms").optional().default([]).transform(unique)
|
|
2907
|
+
});
|
|
2908
|
+
function dictationConfig(store) {
|
|
2909
|
+
const raw = store.setting(SETTING);
|
|
2910
|
+
if (!raw) return null;
|
|
2911
|
+
try {
|
|
2912
|
+
const value = JSON.parse(raw);
|
|
2913
|
+
if (!value.apiKey || !value.baseUrl || !value.model) return null;
|
|
2914
|
+
return {
|
|
2915
|
+
baseUrl: value.baseUrl,
|
|
2916
|
+
apiKey: value.apiKey,
|
|
2917
|
+
model: value.model,
|
|
2918
|
+
languages: value.languages ?? [],
|
|
2919
|
+
keywords: value.keywords ?? []
|
|
2920
|
+
};
|
|
2921
|
+
} catch {
|
|
2922
|
+
return null;
|
|
2923
|
+
}
|
|
2924
|
+
}
|
|
2925
|
+
function dictationSettings(store) {
|
|
2926
|
+
const config = dictationConfig(store);
|
|
2927
|
+
return {
|
|
2928
|
+
configured: !!config,
|
|
2929
|
+
baseUrl: config?.baseUrl ?? "https://api.openai.com/v1",
|
|
2930
|
+
model: config?.model ?? "gpt-transcribe",
|
|
2931
|
+
languages: config?.languages ?? [],
|
|
2932
|
+
keywords: config?.keywords ?? [],
|
|
2933
|
+
keyHint: config ? "…" + config.apiKey.slice(-4) : ""
|
|
2934
|
+
};
|
|
2935
|
+
}
|
|
2936
|
+
function saveDictation(store, input) {
|
|
2937
|
+
const update = DictationUpdate.parse(input);
|
|
2938
|
+
const apiKey = update.apiKey || dictationConfig(store)?.apiKey;
|
|
2939
|
+
if (!apiKey) throw new Error("An API key is required");
|
|
2940
|
+
const config = {
|
|
2941
|
+
baseUrl: update.baseUrl,
|
|
2942
|
+
apiKey,
|
|
2943
|
+
model: update.model,
|
|
2944
|
+
languages: update.languages,
|
|
2945
|
+
keywords: update.keywords
|
|
2946
|
+
};
|
|
2947
|
+
store.setSetting(SETTING, JSON.stringify(config));
|
|
2948
|
+
return dictationSettings(store);
|
|
2949
|
+
}
|
|
2950
|
+
function clearDictation(store) {
|
|
2951
|
+
store.setSetting(SETTING, null);
|
|
2952
|
+
}
|
|
2953
|
+
/** A 44-byte RIFF header makes raw PCM16 a file every transcription API accepts. */
|
|
2954
|
+
function wav(pcm, rate) {
|
|
2955
|
+
const out = Buffer.alloc(44 + pcm.length);
|
|
2956
|
+
out.write("RIFF", 0);
|
|
2957
|
+
out.writeUInt32LE(36 + pcm.length, 4);
|
|
2958
|
+
out.write("WAVE", 8);
|
|
2959
|
+
out.write("fmt ", 12);
|
|
2960
|
+
out.writeUInt32LE(16, 16);
|
|
2961
|
+
out.writeUInt16LE(1, 20);
|
|
2962
|
+
out.writeUInt16LE(1, 22);
|
|
2963
|
+
out.writeUInt32LE(rate, 24);
|
|
2964
|
+
out.writeUInt32LE(rate * 2, 28);
|
|
2965
|
+
out.writeUInt16LE(2, 32);
|
|
2966
|
+
out.writeUInt16LE(16, 34);
|
|
2967
|
+
out.write("data", 36);
|
|
2968
|
+
out.writeUInt32LE(pcm.length, 40);
|
|
2969
|
+
out.set(pcm, 44);
|
|
2970
|
+
return out;
|
|
2971
|
+
}
|
|
2972
|
+
const shapeFor = (model) => /(^|\/)gpt-transcribe\b/i.test(model) ? "hints" : "single";
|
|
2973
|
+
/** The multipart fields besides the file, for one request shape. */
|
|
2974
|
+
function transcriptionFields(config, shape) {
|
|
2975
|
+
const fields = [["model", config.model], ["response_format", "json"]];
|
|
2976
|
+
if (shape === "hints") {
|
|
2977
|
+
for (const code of config.languages) fields.push(["languages[]", code]);
|
|
2978
|
+
for (const term of config.keywords) fields.push(["keywords[]", term]);
|
|
2979
|
+
return fields;
|
|
2980
|
+
}
|
|
2981
|
+
if (config.languages.length === 1) fields.push(["language", config.languages[0].split("-")[0]]);
|
|
2982
|
+
if (config.keywords.length) {
|
|
2983
|
+
let prompt = "";
|
|
2984
|
+
for (const term of config.keywords) {
|
|
2985
|
+
const next = prompt ? `${prompt}, ${term}` : term;
|
|
2986
|
+
if (next.length > LEGACY_PROMPT_CHARS) break;
|
|
2987
|
+
prompt = next;
|
|
2988
|
+
}
|
|
2989
|
+
fields.push(["prompt", prompt]);
|
|
2990
|
+
}
|
|
2991
|
+
return fields;
|
|
2992
|
+
}
|
|
2993
|
+
var DictationError = class extends Error {
|
|
2994
|
+
status;
|
|
2995
|
+
constructor(message, status) {
|
|
2996
|
+
super(message);
|
|
2997
|
+
this.status = status;
|
|
2998
|
+
}
|
|
2999
|
+
};
|
|
3000
|
+
async function send(config, file, shape, fetchImpl, signal) {
|
|
3001
|
+
const form = new FormData();
|
|
3002
|
+
form.append("file", file, "dictation.wav");
|
|
3003
|
+
for (const [name, value] of transcriptionFields(config, shape)) form.append(name, value);
|
|
3004
|
+
let response;
|
|
3005
|
+
try {
|
|
3006
|
+
response = await fetchImpl(config.baseUrl + "/audio/transcriptions", {
|
|
3007
|
+
method: "POST",
|
|
3008
|
+
headers: { authorization: `Bearer ${config.apiKey}` },
|
|
3009
|
+
body: form,
|
|
3010
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)]) : AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
|
|
3011
|
+
});
|
|
3012
|
+
} catch (error) {
|
|
3013
|
+
const timeout = error.name === "TimeoutError";
|
|
3014
|
+
throw new DictationError(timeout ? "The transcription service did not answer in time" : `Could not reach the transcription service: ${error.message}`.slice(0, 300), timeout ? 504 : 502);
|
|
3015
|
+
}
|
|
3016
|
+
const body = await response.text();
|
|
3017
|
+
let data = {};
|
|
3018
|
+
try {
|
|
3019
|
+
data = JSON.parse(body);
|
|
3020
|
+
} catch {}
|
|
3021
|
+
const detail = typeof data.error === "string" ? data.error : typeof data.error?.message === "string" ? data.error.message : response.ok ? "" : body;
|
|
3022
|
+
return {
|
|
3023
|
+
ok: response.ok,
|
|
3024
|
+
status: response.status,
|
|
3025
|
+
text: typeof data.text === "string" ? data.text : void 0,
|
|
3026
|
+
detail: String(detail)
|
|
3027
|
+
};
|
|
3028
|
+
}
|
|
3029
|
+
async function transcribe(config, pcm, rate, fetchImpl = fetch, signal) {
|
|
3030
|
+
const file = new Blob([wav(pcm, rate)], { type: "audio/wav" });
|
|
3031
|
+
const shape = shapeFor(config.model);
|
|
3032
|
+
let result = await send(config, file, shape, fetchImpl, signal);
|
|
3033
|
+
const hinted = config.languages.length > 0 || config.keywords.length > 0;
|
|
3034
|
+
if (!result.ok && result.status === 400 && hinted && /language|keyword|prompt/i.test(result.detail)) result = await send(config, file, shape === "hints" ? "single" : "hints", fetchImpl, signal).then((retry) => retry.ok ? retry : result);
|
|
3035
|
+
if (!result.ok) {
|
|
3036
|
+
const scrubbed = result.detail.split(config.apiKey).join("…").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
3037
|
+
throw new DictationError(`Transcription failed (${result.status})${scrubbed ? ": " + scrubbed : ""}`, 502);
|
|
3038
|
+
}
|
|
3039
|
+
if (result.text === void 0) throw new DictationError("The transcription service returned no text", 502);
|
|
3040
|
+
return result.text.trim();
|
|
3041
|
+
}
|
|
3042
|
+
// src/server/dictation-stream.ts
|
|
3043
|
+
const DICTATION_RATE = 24e3;
|
|
3044
|
+
const BYTES_PER_SECOND = DICTATION_RATE * 2;
|
|
3045
|
+
const MAX_BYTES = BYTES_PER_SECOND * 300;
|
|
3046
|
+
const MAX_BUFFERED = BYTES_PER_SECOND * 10;
|
|
3047
|
+
/** One-use, short-lived tickets keep credentials out of WebSocket URLs. */
|
|
3048
|
+
var DictationStreams = class {
|
|
3049
|
+
tickets = /* @__PURE__ */ new Map();
|
|
3050
|
+
sessions = /* @__PURE__ */ new Set();
|
|
3051
|
+
unsupported = /* @__PURE__ */ new Map();
|
|
3052
|
+
wss = new WebSocketServer({
|
|
3053
|
+
noServer: true,
|
|
3054
|
+
maxPayload: BYTES_PER_SECOND,
|
|
3055
|
+
perMessageDeflate: false
|
|
3056
|
+
});
|
|
3057
|
+
fetchImpl;
|
|
3058
|
+
log;
|
|
3059
|
+
constructor(fetchImpl = fetch, log = () => {}) {
|
|
3060
|
+
this.fetchImpl = fetchImpl;
|
|
3061
|
+
this.log = log;
|
|
3062
|
+
}
|
|
3063
|
+
issue(config, valid) {
|
|
3064
|
+
for (const [key, ticket] of this.tickets) if (ticket.expires < Date.now()) this.tickets.delete(key);
|
|
3065
|
+
if (this.tickets.size + this.sessions.size >= 16) throw new Error("Too many voice sessions. Try again shortly.");
|
|
3066
|
+
const ticket = randomUUID();
|
|
3067
|
+
this.tickets.set(ticket, {
|
|
3068
|
+
config,
|
|
3069
|
+
valid,
|
|
3070
|
+
expires: Date.now() + 3e4
|
|
3071
|
+
});
|
|
3072
|
+
return {
|
|
3073
|
+
ticket,
|
|
3074
|
+
rate: DICTATION_RATE
|
|
3075
|
+
};
|
|
3076
|
+
}
|
|
3077
|
+
attach(server) {
|
|
3078
|
+
server.on("upgrade", (request, socket, head) => {
|
|
3079
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
3080
|
+
if (url.pathname !== "/api/dictation/stream") {
|
|
3081
|
+
socket.destroy();
|
|
3082
|
+
return;
|
|
3083
|
+
}
|
|
3084
|
+
const key = url.searchParams.get("ticket") ?? "";
|
|
3085
|
+
const ticket = this.tickets.get(key);
|
|
3086
|
+
this.tickets.delete(key);
|
|
3087
|
+
if (!ticket || ticket.expires < Date.now() || !ticket.valid()) {
|
|
3088
|
+
socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
|
3089
|
+
return;
|
|
3090
|
+
}
|
|
3091
|
+
this.wss.handleUpgrade(request, socket, head, (client) => {
|
|
3092
|
+
const cacheKey = ticket.config.baseUrl + ":" + ticket.config.model;
|
|
3093
|
+
const stream = new DictationStream(client, ticket.config, ticket.valid, {
|
|
3094
|
+
fetch: this.fetchImpl,
|
|
3095
|
+
skipRealtime: (this.unsupported.get(cacheKey) ?? 0) > Date.now(),
|
|
3096
|
+
unsupported: () => {
|
|
3097
|
+
for (const [key, until] of this.unsupported) if (until < Date.now()) this.unsupported.delete(key);
|
|
3098
|
+
this.unsupported.set(cacheKey, Date.now() + 3e5);
|
|
3099
|
+
},
|
|
3100
|
+
closed: () => this.sessions.delete(stream),
|
|
3101
|
+
log: this.log
|
|
3102
|
+
});
|
|
3103
|
+
this.sessions.add(stream);
|
|
3104
|
+
stream.start();
|
|
3105
|
+
});
|
|
3106
|
+
});
|
|
3107
|
+
}
|
|
3108
|
+
close() {
|
|
3109
|
+
for (const stream of this.sessions) stream.close();
|
|
3110
|
+
this.tickets.clear();
|
|
3111
|
+
this.unsupported.clear();
|
|
3112
|
+
this.wss.close();
|
|
3113
|
+
}
|
|
3114
|
+
};
|
|
3115
|
+
/** Audio flows while recording. Realtime is preferred; file-only services transcribe phrases. */
|
|
3116
|
+
var DictationStream = class {
|
|
3117
|
+
upstream;
|
|
3118
|
+
mode = "connecting";
|
|
3119
|
+
closed = false;
|
|
3120
|
+
finishing = false;
|
|
3121
|
+
totalBytes = 0;
|
|
3122
|
+
segmentBytes = 0;
|
|
3123
|
+
silenceBytes = 0;
|
|
3124
|
+
speech = false;
|
|
3125
|
+
chunks = [];
|
|
3126
|
+
segments = [];
|
|
3127
|
+
commits = [];
|
|
3128
|
+
items = /* @__PURE__ */ new Map();
|
|
3129
|
+
jobs = [];
|
|
3130
|
+
activeJobs = 0;
|
|
3131
|
+
abort = new AbortController();
|
|
3132
|
+
started = Date.now();
|
|
3133
|
+
stopped = 0;
|
|
3134
|
+
firstText = null;
|
|
3135
|
+
deadline;
|
|
3136
|
+
heartbeat;
|
|
3137
|
+
client;
|
|
3138
|
+
config;
|
|
3139
|
+
valid;
|
|
3140
|
+
options;
|
|
3141
|
+
constructor(client, config, valid, options) {
|
|
3142
|
+
this.client = client;
|
|
3143
|
+
this.config = config;
|
|
3144
|
+
this.valid = valid;
|
|
3145
|
+
this.options = options;
|
|
3146
|
+
this.heartbeat = setInterval(() => {
|
|
3147
|
+
if (!valid()) this.fail("Your session ended. Sign in again.");
|
|
3148
|
+
else if (Date.now() - this.started > 43e4) this.fail("Voice session timed out.");
|
|
3149
|
+
else if (client.readyState === WebSocket.OPEN) client.ping();
|
|
3150
|
+
}, 1e4);
|
|
3151
|
+
this.heartbeat.unref();
|
|
3152
|
+
client.on("message", (data, binary) => {
|
|
3153
|
+
if (this.closed) return;
|
|
3154
|
+
if (!valid()) {
|
|
3155
|
+
this.fail("Your session ended. Sign in again.");
|
|
3156
|
+
return;
|
|
3157
|
+
}
|
|
3158
|
+
try {
|
|
3159
|
+
if (binary) this.append(Buffer.from(data));
|
|
3160
|
+
else {
|
|
3161
|
+
const event = JSON.parse(data.toString());
|
|
3162
|
+
if (event.type === "stop") this.finish();
|
|
3163
|
+
else if (event.type === "cancel") this.close();
|
|
3164
|
+
else this.fail("Unknown voice command.");
|
|
3165
|
+
}
|
|
3166
|
+
} catch {
|
|
3167
|
+
this.fail("Invalid voice data.");
|
|
3168
|
+
}
|
|
3169
|
+
});
|
|
3170
|
+
client.on("error", () => this.close());
|
|
3171
|
+
client.on("close", () => this.close());
|
|
3172
|
+
}
|
|
3173
|
+
async start() {
|
|
3174
|
+
const realtimeModel = /^(gpt-transcribe|gpt-live-transcribe|gpt-4o(-mini)?-transcribe|whisper-1)$/.test(this.config.model);
|
|
3175
|
+
if (this.options.skipRealtime || !realtimeModel) {
|
|
3176
|
+
this.ready("segmented");
|
|
3177
|
+
return;
|
|
3178
|
+
}
|
|
3179
|
+
try {
|
|
3180
|
+
await this.connectRealtime();
|
|
3181
|
+
if (!this.closed) this.ready("realtime");
|
|
3182
|
+
} catch (error) {
|
|
3183
|
+
if (this.closed) return;
|
|
3184
|
+
if (error instanceof Unavailable) {
|
|
3185
|
+
this.options.unsupported();
|
|
3186
|
+
this.ready("segmented");
|
|
3187
|
+
} else this.fail(error.message);
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
connectRealtime() {
|
|
3191
|
+
return new Promise((resolve, reject) => {
|
|
3192
|
+
const url = new URL(this.config.baseUrl + "/realtime");
|
|
3193
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
3194
|
+
url.searchParams.set("intent", "transcription");
|
|
3195
|
+
const ws = this.upstream = new WebSocket(url, {
|
|
3196
|
+
headers: { Authorization: `Bearer ${this.config.apiKey}` },
|
|
3197
|
+
handshakeTimeout: 4e3,
|
|
3198
|
+
maxPayload: 1048576
|
|
3199
|
+
});
|
|
3200
|
+
let settled = false;
|
|
3201
|
+
const finish = (error) => {
|
|
3202
|
+
if (settled) return;
|
|
3203
|
+
settled = true;
|
|
3204
|
+
clearTimeout(timeout);
|
|
3205
|
+
if (error) {
|
|
3206
|
+
this.upstream = void 0;
|
|
3207
|
+
ws.terminate();
|
|
3208
|
+
reject(error);
|
|
3209
|
+
} else resolve();
|
|
3210
|
+
};
|
|
3211
|
+
const timeout = setTimeout(() => finish(new Unavailable("Realtime connection timed out")), 5e3);
|
|
3212
|
+
ws.on("open", () => {
|
|
3213
|
+
const hints = /^(gpt-transcribe|gpt-live-transcribe)$/.test(this.config.model);
|
|
3214
|
+
const transcription = {
|
|
3215
|
+
model: this.config.model,
|
|
3216
|
+
...hints ? {
|
|
3217
|
+
...this.config.languages.length ? { languages: this.config.languages } : {},
|
|
3218
|
+
...this.config.keywords.length ? { keywords: this.config.keywords } : {}
|
|
3219
|
+
} : {
|
|
3220
|
+
...this.config.languages.length === 1 ? { language: this.config.languages[0].split("-")[0] } : {},
|
|
3221
|
+
...this.config.keywords.length ? { prompt: this.config.keywords.join(", ").slice(0, 600) } : {}
|
|
3222
|
+
}
|
|
3223
|
+
};
|
|
3224
|
+
ws.send(JSON.stringify({
|
|
3225
|
+
type: "session.update",
|
|
3226
|
+
session: {
|
|
3227
|
+
type: "transcription",
|
|
3228
|
+
audio: { input: {
|
|
3229
|
+
format: {
|
|
3230
|
+
type: "audio/pcm",
|
|
3231
|
+
rate: DICTATION_RATE
|
|
3232
|
+
},
|
|
3233
|
+
transcription,
|
|
3234
|
+
turn_detection: null
|
|
3235
|
+
} }
|
|
3236
|
+
}
|
|
3237
|
+
}));
|
|
3238
|
+
});
|
|
3239
|
+
ws.on("unexpected-response", (_, response) => {
|
|
3240
|
+
const status = response.statusCode;
|
|
3241
|
+
response.destroy();
|
|
3242
|
+
finish([
|
|
3243
|
+
400,
|
|
3244
|
+
404,
|
|
3245
|
+
405,
|
|
3246
|
+
501
|
|
3247
|
+
].includes(status ?? 0) ? new Unavailable("Realtime is not supported") : /* @__PURE__ */ new Error(`Voice connection failed (${status}). Check the transcription service settings.`));
|
|
3248
|
+
});
|
|
3249
|
+
ws.on("message", (data) => {
|
|
3250
|
+
let event;
|
|
3251
|
+
try {
|
|
3252
|
+
event = JSON.parse(data.toString());
|
|
3253
|
+
} catch {
|
|
3254
|
+
finish(/* @__PURE__ */ new Error("Invalid transcription service response."));
|
|
3255
|
+
return;
|
|
3256
|
+
}
|
|
3257
|
+
if (!settled) {
|
|
3258
|
+
if (event.type === "session.updated") finish();
|
|
3259
|
+
else if (event.type === "error") finish(new Unavailable("Realtime configuration is not supported"));
|
|
3260
|
+
} else if (this.mode === "realtime" && !this.closed) this.upstreamEvent(event);
|
|
3261
|
+
});
|
|
3262
|
+
ws.on("error", () => {
|
|
3263
|
+
if (!settled) finish(new Unavailable("Realtime is unavailable"));
|
|
3264
|
+
else if (this.mode === "realtime") this.fail("Voice connection interrupted. Please try again.");
|
|
3265
|
+
});
|
|
3266
|
+
ws.on("close", () => {
|
|
3267
|
+
if (!settled) finish(new Unavailable("Realtime is unavailable"));
|
|
3268
|
+
else if (this.mode === "realtime" && !this.closed) this.fail("Voice connection interrupted. Please try again.");
|
|
3269
|
+
});
|
|
3270
|
+
});
|
|
3271
|
+
}
|
|
3272
|
+
ready(mode) {
|
|
3273
|
+
if (this.closed) return;
|
|
3274
|
+
if (mode === "segmented" && this.config.model === "gpt-live-transcribe") {
|
|
3275
|
+
this.fail("This service does not support realtime transcription. Choose gpt-transcribe or a realtime-compatible service.");
|
|
3276
|
+
return;
|
|
3277
|
+
}
|
|
3278
|
+
this.mode = mode;
|
|
3279
|
+
this.send({
|
|
3280
|
+
type: "ready",
|
|
3281
|
+
mode,
|
|
3282
|
+
rate: DICTATION_RATE
|
|
3283
|
+
});
|
|
3284
|
+
}
|
|
3285
|
+
append(audio) {
|
|
3286
|
+
if (this.finishing || this.mode === "connecting") {
|
|
3287
|
+
this.fail("Voice session is not recording.");
|
|
3288
|
+
return;
|
|
3289
|
+
}
|
|
3290
|
+
if (!audio.length || audio.length % 2 || audio.length > BYTES_PER_SECOND) {
|
|
3291
|
+
this.fail("Invalid audio chunk.");
|
|
3292
|
+
return;
|
|
3293
|
+
}
|
|
3294
|
+
this.totalBytes += audio.length;
|
|
3295
|
+
if (this.totalBytes > MAX_BYTES) {
|
|
3296
|
+
this.fail("Recording exceeds five minutes.");
|
|
3297
|
+
return;
|
|
3298
|
+
}
|
|
3299
|
+
this.chunks.push(audio);
|
|
3300
|
+
this.segmentBytes += audio.length;
|
|
3301
|
+
let energy = 0;
|
|
3302
|
+
for (let i = 0; i < audio.length; i += 2) {
|
|
3303
|
+
const sample = audio.readInt16LE(i) / 32768;
|
|
3304
|
+
energy += sample * sample;
|
|
3305
|
+
}
|
|
3306
|
+
if (Math.sqrt(energy / (audio.length / 2)) >= .006) {
|
|
3307
|
+
this.speech = true;
|
|
3308
|
+
this.silenceBytes = 0;
|
|
3309
|
+
} else this.silenceBytes += audio.length;
|
|
3310
|
+
if (this.mode === "realtime") {
|
|
3311
|
+
if (!this.upstream || this.upstream.bufferedAmount > MAX_BUFFERED) {
|
|
3312
|
+
this.fail("Voice upload cannot keep up with recording.");
|
|
3313
|
+
return;
|
|
3314
|
+
}
|
|
3315
|
+
this.upstream.send(JSON.stringify({
|
|
3316
|
+
type: "input_audio_buffer.append",
|
|
3317
|
+
audio: audio.toString("base64")
|
|
3318
|
+
}));
|
|
3319
|
+
}
|
|
3320
|
+
if (this.speech && (this.segmentBytes >= BYTES_PER_SECOND && this.silenceBytes >= BYTES_PER_SECOND * .7 || this.segmentBytes >= BYTES_PER_SECOND * 30)) this.commit();
|
|
3321
|
+
else if (!this.speech && this.segmentBytes >= BYTES_PER_SECOND * 2) this.clearAudio();
|
|
3322
|
+
}
|
|
3323
|
+
clearAudio() {
|
|
3324
|
+
this.chunks = [];
|
|
3325
|
+
this.segmentBytes = this.silenceBytes = 0;
|
|
3326
|
+
this.speech = false;
|
|
3327
|
+
if (this.mode === "realtime") this.upstream?.send(JSON.stringify({ type: "input_audio_buffer.clear" }));
|
|
3328
|
+
}
|
|
3329
|
+
commit() {
|
|
3330
|
+
if (!this.segmentBytes) return;
|
|
3331
|
+
const segment = {
|
|
3332
|
+
text: "",
|
|
3333
|
+
done: false
|
|
3334
|
+
};
|
|
3335
|
+
this.segments.push(segment);
|
|
3336
|
+
if (this.mode === "realtime") {
|
|
3337
|
+
if (this.segmentBytes < BYTES_PER_SECOND / 10) this.upstream?.send(JSON.stringify({
|
|
3338
|
+
type: "input_audio_buffer.append",
|
|
3339
|
+
audio: Buffer.alloc(BYTES_PER_SECOND / 10 - this.segmentBytes).toString("base64")
|
|
3340
|
+
}));
|
|
3341
|
+
this.commits.push(segment);
|
|
3342
|
+
this.upstream?.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
|
|
3343
|
+
} else {
|
|
3344
|
+
this.jobs.push({
|
|
3345
|
+
audio: Buffer.concat(this.chunks),
|
|
3346
|
+
segment
|
|
3347
|
+
});
|
|
3348
|
+
this.pump();
|
|
3349
|
+
}
|
|
3350
|
+
this.chunks = [];
|
|
3351
|
+
this.segmentBytes = this.silenceBytes = 0;
|
|
3352
|
+
this.speech = false;
|
|
3353
|
+
}
|
|
3354
|
+
pump() {
|
|
3355
|
+
while (!this.closed && this.activeJobs < 2 && this.jobs.length) {
|
|
3356
|
+
const job = this.jobs.shift();
|
|
3357
|
+
this.activeJobs++;
|
|
3358
|
+
transcribe(this.config, job.audio, DICTATION_RATE, this.options.fetch, this.abort.signal).then((text) => {
|
|
3359
|
+
if (this.closed) return;
|
|
3360
|
+
job.segment.text = text;
|
|
3361
|
+
job.segment.done = true;
|
|
3362
|
+
this.publish();
|
|
3363
|
+
}).catch(() => {
|
|
3364
|
+
if (!this.closed) this.fail("Transcription failed. Please try again or check the service settings.");
|
|
3365
|
+
}).finally(() => {
|
|
3366
|
+
this.activeJobs--;
|
|
3367
|
+
this.pump();
|
|
3368
|
+
});
|
|
3369
|
+
}
|
|
3370
|
+
}
|
|
3371
|
+
upstreamEvent(event) {
|
|
3372
|
+
const id = typeof event.item_id === "string" ? event.item_id : "";
|
|
3373
|
+
if (event.type === "input_audio_buffer.committed") {
|
|
3374
|
+
const segment = this.commits.shift();
|
|
3375
|
+
if (!segment || !id) {
|
|
3376
|
+
this.fail("Unexpected transcription sequence.");
|
|
3377
|
+
return;
|
|
3378
|
+
}
|
|
3379
|
+
const draft = this.items.get(id);
|
|
3380
|
+
if (draft) {
|
|
3381
|
+
segment.text = draft.text;
|
|
3382
|
+
segment.done = draft.done;
|
|
3383
|
+
}
|
|
3384
|
+
segment.id = id;
|
|
3385
|
+
this.items.set(id, segment);
|
|
3386
|
+
this.publish();
|
|
3387
|
+
} else if (event.type === "conversation.item.input_audio_transcription.delta" || event.type === "conversation.item.input_audio_transcription.completed") {
|
|
3388
|
+
let segment = this.items.get(id);
|
|
3389
|
+
if (!segment) {
|
|
3390
|
+
segment = {
|
|
3391
|
+
text: "",
|
|
3392
|
+
done: false,
|
|
3393
|
+
id
|
|
3394
|
+
};
|
|
3395
|
+
this.items.set(id, segment);
|
|
3396
|
+
}
|
|
3397
|
+
if (event.type.endsWith(".completed")) {
|
|
3398
|
+
segment.text = String(event.transcript ?? "");
|
|
3399
|
+
segment.done = true;
|
|
3400
|
+
} else if (!segment.done) segment.text += String(event.delta ?? "");
|
|
3401
|
+
this.publish();
|
|
3402
|
+
} else if (event.type === "error" || event.type === "conversation.item.input_audio_transcription.failed") this.fail("The transcription service could not process this recording.");
|
|
3403
|
+
}
|
|
3404
|
+
text() {
|
|
3405
|
+
const parts = [];
|
|
3406
|
+
for (const segment of this.segments) {
|
|
3407
|
+
if (segment.text.trim()) parts.push(segment.text.trim());
|
|
3408
|
+
if (!segment.done) break;
|
|
3409
|
+
}
|
|
3410
|
+
if (this.mode === "realtime" && this.config.model === "gpt-live-transcribe") {
|
|
3411
|
+
for (const segment of this.items.values()) if (!this.segments.includes(segment) && segment.text.trim()) parts.push(segment.text.trim());
|
|
3412
|
+
}
|
|
3413
|
+
return parts.join(" ");
|
|
3414
|
+
}
|
|
3415
|
+
publish() {
|
|
3416
|
+
if (this.closed) return;
|
|
3417
|
+
const text = this.text();
|
|
3418
|
+
if (text && this.firstText === null) this.firstText = Date.now() - this.started;
|
|
3419
|
+
if (this.finishing && this.segments.every((s) => s.done)) {
|
|
3420
|
+
this.options.log({
|
|
3421
|
+
mode: this.mode,
|
|
3422
|
+
audioMs: this.totalBytes / BYTES_PER_SECOND * 1e3,
|
|
3423
|
+
firstTextMs: this.firstText,
|
|
3424
|
+
finishMs: Date.now() - this.stopped
|
|
3425
|
+
});
|
|
3426
|
+
this.send({
|
|
3427
|
+
type: "done",
|
|
3428
|
+
text
|
|
3429
|
+
});
|
|
3430
|
+
this.close();
|
|
3431
|
+
} else this.send({
|
|
3432
|
+
type: "partial",
|
|
3433
|
+
text
|
|
3434
|
+
});
|
|
3435
|
+
}
|
|
3436
|
+
finish() {
|
|
3437
|
+
if (this.finishing || this.closed) return;
|
|
3438
|
+
if (this.mode === "connecting") {
|
|
3439
|
+
this.fail("Voice session is still connecting.");
|
|
3440
|
+
return;
|
|
3441
|
+
}
|
|
3442
|
+
this.finishing = true;
|
|
3443
|
+
this.stopped = Date.now();
|
|
3444
|
+
if (this.speech) this.commit();
|
|
3445
|
+
else this.clearAudio();
|
|
3446
|
+
this.deadline = setTimeout(() => this.fail("Timed out waiting for transcription."), 12e4);
|
|
3447
|
+
this.publish();
|
|
3448
|
+
}
|
|
3449
|
+
send(event) {
|
|
3450
|
+
if (this.client.readyState === WebSocket.OPEN) {
|
|
3451
|
+
if (this.client.bufferedAmount > 1048576) {
|
|
3452
|
+
this.close();
|
|
3453
|
+
return;
|
|
3454
|
+
}
|
|
3455
|
+
this.client.send(JSON.stringify(event));
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
fail(message) {
|
|
3459
|
+
if (this.closed) return;
|
|
3460
|
+
this.send({
|
|
3461
|
+
type: "error",
|
|
3462
|
+
message,
|
|
3463
|
+
text: this.text()
|
|
3464
|
+
});
|
|
3465
|
+
this.close();
|
|
3466
|
+
}
|
|
3467
|
+
close() {
|
|
3468
|
+
if (this.closed) return;
|
|
3469
|
+
this.closed = true;
|
|
3470
|
+
clearInterval(this.heartbeat);
|
|
3471
|
+
clearTimeout(this.deadline);
|
|
3472
|
+
this.abort.abort();
|
|
3473
|
+
this.upstream?.terminate();
|
|
3474
|
+
this.chunks = [];
|
|
3475
|
+
this.jobs = [];
|
|
3476
|
+
this.client.close();
|
|
3477
|
+
this.options.closed();
|
|
3478
|
+
}
|
|
3479
|
+
};
|
|
3480
|
+
var Unavailable = class extends Error {};
|
|
2805
3481
|
// src/server/app.ts
|
|
2806
3482
|
const AGENT_FLUSH_MS = 100;
|
|
2807
|
-
/** Five minutes of 16 kHz, 16-bit mono speech. */
|
|
2808
|
-
const MAX_DICTATION_BYTES = 96e5;
|
|
2809
3483
|
const HOST_FLUSH_MS = 100;
|
|
2810
3484
|
function parseJson(text) {
|
|
2811
3485
|
try {
|
|
@@ -2829,9 +3503,25 @@ const SESSION_COOKIE = "lp_session";
|
|
|
2829
3503
|
/** Cookie-authenticated writes must carry this header; a cross-site form or image cannot. */
|
|
2830
3504
|
const CSRF_HEADER = "x-litepaseo";
|
|
2831
3505
|
const PUBLIC_API = /* @__PURE__ */ new Set(["/api/auth", "/api/login"]);
|
|
3506
|
+
/**
|
|
3507
|
+
* Requests that arrived through a tunnel or reverse proxy. A bearer token is never accepted from
|
|
3508
|
+
* them: over the network, only the browser sign-in (with its rate limits and optional
|
|
3509
|
+
* authenticator code) admits anyone.
|
|
3510
|
+
*/
|
|
3511
|
+
const proxied = (c) => [
|
|
3512
|
+
"cf-connecting-ip",
|
|
3513
|
+
"x-forwarded-for",
|
|
3514
|
+
"x-real-ip",
|
|
3515
|
+
"forwarded"
|
|
3516
|
+
].some((name) => c.req.header(name) !== void 0);
|
|
3517
|
+
/** `token` is the access token, or a function returning the current one (it can be rotated). */
|
|
2832
3518
|
function createApp(store, hosts, token, webRoot, options = {}) {
|
|
2833
3519
|
const app = new Hono();
|
|
2834
3520
|
const auth = new Auth(store, token);
|
|
3521
|
+
const dictationStreams = new DictationStreams(options.fetch, (metrics) => console.info(JSON.stringify({
|
|
3522
|
+
event: "dictation_complete",
|
|
3523
|
+
...metrics
|
|
3524
|
+
})));
|
|
2835
3525
|
const attachments = new Attachments();
|
|
2836
3526
|
const projectIcons = new IconCache();
|
|
2837
3527
|
const viewers = /* @__PURE__ */ new Map();
|
|
@@ -2852,12 +3542,19 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
2852
3542
|
c.header("Referrer-Policy", "no-referrer");
|
|
2853
3543
|
c.header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self'; manifest-src 'self'; frame-ancestors 'none'");
|
|
2854
3544
|
});
|
|
2855
|
-
app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method !== "POST" ? 1048576 : c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : c.req.path
|
|
3545
|
+
app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method !== "POST" ? 1048576 : c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : c.req.path === "/api/dictation/transcribe" ? MAX_DICTATION_BYTES : 1048576 })(c, next));
|
|
2856
3546
|
app.use("/api/*", async (c, next) => {
|
|
2857
3547
|
c.header("Cache-Control", "no-store");
|
|
2858
|
-
|
|
2859
|
-
|
|
3548
|
+
c.set("bearer", null);
|
|
3549
|
+
const bearer = /^Bearer (.+)$/.exec(c.req.header("authorization") ?? "")?.[1];
|
|
3550
|
+
if (bearer && !PUBLIC_API.has(c.req.path) && !auth.totpEnabled() && !proxied(c)) {
|
|
3551
|
+
const result = auth.bearer(bearer, clientId(c));
|
|
3552
|
+
if (!result.ok) {
|
|
3553
|
+
if (result.retryAfter) c.header("Retry-After", String(result.retryAfter));
|
|
3554
|
+
return c.json({ error: result.status === 429 ? "Too many attempts. Try again later." : "Sign in required" }, result.status);
|
|
3555
|
+
}
|
|
2860
3556
|
c.set("session", null);
|
|
3557
|
+
c.set("bearer", bearer);
|
|
2861
3558
|
return next();
|
|
2862
3559
|
}
|
|
2863
3560
|
const secret = getCookie(c, SESSION_COOKIE);
|
|
@@ -3050,6 +3747,8 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
3050
3747
|
const directoryStreams = /* @__PURE__ */ new Set();
|
|
3051
3748
|
let agentFlush;
|
|
3052
3749
|
let hostFlush;
|
|
3750
|
+
/** Set on shutdown: closing the hosts still reports changes, but the store is about to close. */
|
|
3751
|
+
let disposed = false;
|
|
3053
3752
|
const deliverAgents = (stream) => {
|
|
3054
3753
|
deliverWorkspaces(stream);
|
|
3055
3754
|
const { agents } = hosts;
|
|
@@ -3086,14 +3785,14 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
3086
3785
|
stream.lastWorkspaces = workspaces.seq;
|
|
3087
3786
|
};
|
|
3088
3787
|
hosts.onAgentsChanged(() => {
|
|
3089
|
-
if (agentFlush || !directoryStreams.size) return;
|
|
3788
|
+
if (disposed || agentFlush || !directoryStreams.size) return;
|
|
3090
3789
|
agentFlush = setTimeout(() => {
|
|
3091
3790
|
agentFlush = void 0;
|
|
3092
3791
|
for (const stream of directoryStreams) deliverAgents(stream);
|
|
3093
3792
|
}, AGENT_FLUSH_MS);
|
|
3094
3793
|
});
|
|
3095
3794
|
hosts.onHostsChanged(() => {
|
|
3096
|
-
if (hostFlush || !directoryStreams.size) return;
|
|
3795
|
+
if (disposed || hostFlush || !directoryStreams.size) return;
|
|
3097
3796
|
hostFlush = setTimeout(() => {
|
|
3098
3797
|
hostFlush = void 0;
|
|
3099
3798
|
const message = {
|
|
@@ -3103,7 +3802,12 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
3103
3802
|
for (const stream of directoryStreams) stream.send(message);
|
|
3104
3803
|
}, HOST_FLUSH_MS);
|
|
3105
3804
|
});
|
|
3106
|
-
|
|
3805
|
+
/** Re-checked on heartbeat: a revoked session, or a rotated token, loses its open streams. */
|
|
3806
|
+
const streamValidity = (c) => {
|
|
3807
|
+
const session = c.get("session"), bearer = c.get("bearer");
|
|
3808
|
+
if (session) return () => auth.stillValid(session.id);
|
|
3809
|
+
return () => !!bearer && !auth.totpEnabled() && auth.checkToken(bearer);
|
|
3810
|
+
};
|
|
3107
3811
|
app.get("/api/stream", (c) => {
|
|
3108
3812
|
const since = Number(c.req.query("since"));
|
|
3109
3813
|
const resumable = c.req.query("generation") === hosts.agents.generation && Number.isInteger(since);
|
|
@@ -3122,7 +3826,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
3122
3826
|
deliverAgents(stream);
|
|
3123
3827
|
directoryStreams.add(stream);
|
|
3124
3828
|
return () => directoryStreams.delete(stream);
|
|
3125
|
-
}, streamValidity(c
|
|
3829
|
+
}, streamValidity(c));
|
|
3126
3830
|
});
|
|
3127
3831
|
app.post("/api/hosts", async (c) => {
|
|
3128
3832
|
const input = z.object({
|
|
@@ -3254,7 +3958,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
3254
3958
|
if (!devices.size) viewers.delete(key);
|
|
3255
3959
|
}
|
|
3256
3960
|
};
|
|
3257
|
-
}, streamValidity(c
|
|
3961
|
+
}, streamValidity(c));
|
|
3258
3962
|
});
|
|
3259
3963
|
/** Bounded history pages; the browser bookmarks boundaries for forward navigation. */
|
|
3260
3964
|
app.get("/api/hosts/:host/agents/:agent/timeline", async (c) => {
|
|
@@ -3401,30 +4105,44 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
3401
4105
|
});
|
|
3402
4106
|
});
|
|
3403
4107
|
/**
|
|
3404
|
-
* Speech to text through the
|
|
3405
|
-
* browser
|
|
3406
|
-
*
|
|
4108
|
+
* Speech to text through the transcription service configured here, once for every host. The
|
|
4109
|
+
* browser streams PCM over a short-lived socket. The file endpoint remains for older
|
|
4110
|
+
* clients. The API key never leaves the server.
|
|
3407
4111
|
*/
|
|
3408
|
-
app.
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
4112
|
+
app.get("/api/dictation", (c) => c.json(dictationSettings(store)));
|
|
4113
|
+
app.post("/api/dictation/session", (c) => {
|
|
4114
|
+
const config = dictationConfig(store);
|
|
4115
|
+
if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
|
|
4116
|
+
try {
|
|
4117
|
+
return c.json(dictationStreams.issue(config, streamValidity(c)));
|
|
4118
|
+
} catch (error) {
|
|
4119
|
+
return c.json({ error: error.message }, 429);
|
|
4120
|
+
}
|
|
4121
|
+
});
|
|
4122
|
+
app.put("/api/dictation", async (c) => {
|
|
4123
|
+
try {
|
|
4124
|
+
return c.json(saveDictation(store, await c.req.json()));
|
|
4125
|
+
} catch (error) {
|
|
4126
|
+
const message = error instanceof z.ZodError ? error.issues[0]?.message ?? "Invalid settings" : error.message;
|
|
4127
|
+
return c.json({ error: message }, 400);
|
|
4128
|
+
}
|
|
4129
|
+
});
|
|
4130
|
+
app.delete("/api/dictation", (c) => {
|
|
4131
|
+
clearDictation(store);
|
|
4132
|
+
return c.json(dictationSettings(store));
|
|
4133
|
+
});
|
|
4134
|
+
app.post("/api/dictation/transcribe", async (c) => {
|
|
4135
|
+
const config = dictationConfig(store);
|
|
4136
|
+
if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
|
|
4137
|
+
const format = /^audio\/pcm;rate=(\d{4,6});bits=16$/.exec(c.req.header("x-audio-format") ?? "");
|
|
4138
|
+
if (!format) return c.json({ error: "Unsupported audio format" }, 415);
|
|
4139
|
+
const audio = new Uint8Array(await c.req.arrayBuffer());
|
|
3412
4140
|
if (audio.length < 3200 || audio.length % 2) return c.json({ error: "Recording too short" }, 400);
|
|
3413
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
3414
|
-
const id = randomUUID();
|
|
3415
4141
|
try {
|
|
3416
|
-
|
|
3417
|
-
const CHUNK = 32e3;
|
|
3418
|
-
let seq = 0;
|
|
3419
|
-
for (let offset = 0; offset < audio.length; offset += CHUNK, seq++) driver.sendDictationStreamChunk(id, seq, audio.subarray(offset, offset + CHUNK).toString("base64"), format);
|
|
3420
|
-
const result = await driver.finishDictationStream(id, seq - 1);
|
|
3421
|
-
return c.json({ text: result.text });
|
|
4142
|
+
return c.json({ text: await transcribe(config, audio, Number(format[1]), options.fetch) });
|
|
3422
4143
|
} catch (error) {
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
} catch {}
|
|
3426
|
-
const message = error instanceof Error ? error.message : "";
|
|
3427
|
-
return c.json({ error: /disabled|not enabled|unavailable|not configured/i.test(message) ? "Dictation is not enabled on this host. Turn it on in the host's Paseo settings." : "Transcription failed" + (message ? `: ${message.slice(0, 200)}` : "") }, 502);
|
|
4144
|
+
if (error instanceof DictationError) return c.json({ error: error.message }, error.status);
|
|
4145
|
+
throw error;
|
|
3428
4146
|
}
|
|
3429
4147
|
});
|
|
3430
4148
|
const attachmentOwner = (c) => c.get("session")?.id ?? "bearer";
|
|
@@ -3566,7 +4284,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
3566
4284
|
});
|
|
3567
4285
|
}
|
|
3568
4286
|
});
|
|
3569
|
-
registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c
|
|
4287
|
+
registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c));
|
|
3570
4288
|
app.get("/api/usage", async (c) => c.json(await usage.report(c.req.query("refresh") === "1")));
|
|
3571
4289
|
app.get("/api/board", (c) => c.json(store.board()));
|
|
3572
4290
|
app.put("/api/board", async (c) => {
|
|
@@ -3602,16 +4320,24 @@ function createApp(store, hosts, token, webRoot, options = {}) {
|
|
|
3602
4320
|
precompressed: true
|
|
3603
4321
|
}));
|
|
3604
4322
|
return Object.assign(app, {
|
|
4323
|
+
dictationStreams,
|
|
3605
4324
|
/** Open directory streams; lets tests prove that disconnects release them. */
|
|
3606
4325
|
openStreams: () => directoryStreams.size,
|
|
3607
|
-
dispose: () =>
|
|
4326
|
+
dispose: () => {
|
|
4327
|
+
disposed = true;
|
|
4328
|
+
clearTimeout(agentFlush);
|
|
4329
|
+
clearTimeout(hostFlush);
|
|
4330
|
+
agentFlush = hostFlush = void 0;
|
|
4331
|
+
attachments.close();
|
|
4332
|
+
dictationStreams.close();
|
|
4333
|
+
}
|
|
3608
4334
|
});
|
|
3609
4335
|
}
|
|
3610
4336
|
// src/server/worker.ts
|
|
3611
4337
|
async function runWorker(directory, webRoot) {
|
|
3612
4338
|
if (!process.send) throw new Error("worker is an internal supervised command");
|
|
3613
4339
|
const tokenPath = join(directory, "token");
|
|
3614
|
-
if (!existsSync(tokenPath)) writeFileSync(tokenPath,
|
|
4340
|
+
if (!existsSync(tokenPath)) writeFileSync(tokenPath, generateToken(), {
|
|
3615
4341
|
mode: 384,
|
|
3616
4342
|
flag: "wx"
|
|
3617
4343
|
});
|
|
@@ -3622,12 +4348,13 @@ async function runWorker(directory, webRoot) {
|
|
|
3622
4348
|
console.error("Could not initialize host", host.id);
|
|
3623
4349
|
}
|
|
3624
4350
|
const port = Number(process.env.LITEPASEO_PORT ?? 8787), hostname = process.env.LITEPASEO_BIND ?? "127.0.0.1";
|
|
3625
|
-
const app = createApp(store, hosts,
|
|
4351
|
+
const app = createApp(store, hosts, tokenFile(tokenPath), webRoot, { pushSubject: process.env.LITEPASEO_PUSH_SUBJECT });
|
|
3626
4352
|
const server = serve({
|
|
3627
4353
|
fetch: app.fetch,
|
|
3628
4354
|
port,
|
|
3629
4355
|
hostname
|
|
3630
4356
|
});
|
|
4357
|
+
app.dictationStreams.attach(server);
|
|
3631
4358
|
let stopping = false;
|
|
3632
4359
|
const shutdown = async () => {
|
|
3633
4360
|
if (stopping) return;
|
|
@@ -3740,7 +4467,7 @@ async function restore(source, directory) {
|
|
|
3740
4467
|
} finally {
|
|
3741
4468
|
db.close();
|
|
3742
4469
|
}
|
|
3743
|
-
if (!/^[
|
|
4470
|
+
if (!/^[\x21-\x7e]{1,200}$/.test(readFileSync(join(stage, "token"), "utf8").trim())) throw new Error("Invalid backup access token.");
|
|
3744
4471
|
writeFileSync(join(directory, ".restore-incomplete"), "Restore interrupted: restore the backup to a fresh home.\n", {
|
|
3745
4472
|
mode: 384,
|
|
3746
4473
|
flag: "wx"
|
|
@@ -3812,35 +4539,349 @@ async function resolveDataDirectory(env, home, platform, isLive = socketIsLive)
|
|
|
3812
4539
|
notice: `Moved LitePaseo data from ${legacy} to ${target}.`
|
|
3813
4540
|
};
|
|
3814
4541
|
}
|
|
4542
|
+
// src/server/cli-format.ts
|
|
4543
|
+
const json = {
|
|
4544
|
+
name: "json",
|
|
4545
|
+
summary: "Print machine-readable JSON"
|
|
4546
|
+
};
|
|
4547
|
+
const TOKEN_ACTIONS = ["set", "rotate"];
|
|
4548
|
+
const SERVICE_ACTIONS = [
|
|
4549
|
+
"print",
|
|
4550
|
+
"install",
|
|
4551
|
+
"uninstall",
|
|
4552
|
+
"status",
|
|
4553
|
+
"start",
|
|
4554
|
+
"stop",
|
|
4555
|
+
"restart"
|
|
4556
|
+
];
|
|
4557
|
+
const COMMANDS = [
|
|
4558
|
+
{
|
|
4559
|
+
name: "start",
|
|
4560
|
+
group: "Service",
|
|
4561
|
+
summary: "Start in the background",
|
|
4562
|
+
details: ["Waits up to 10 s until the web console answers, then prints its address.", "Does nothing if LitePaseo is already running."],
|
|
4563
|
+
flags: [json]
|
|
4564
|
+
},
|
|
4565
|
+
{
|
|
4566
|
+
name: "stop",
|
|
4567
|
+
group: "Service",
|
|
4568
|
+
summary: "Stop the background instance",
|
|
4569
|
+
details: ["Waits until the instance has exited."]
|
|
4570
|
+
},
|
|
4571
|
+
{
|
|
4572
|
+
name: "restart",
|
|
4573
|
+
group: "Service",
|
|
4574
|
+
summary: "Stop, then start again",
|
|
4575
|
+
details: ["Use after upgrading so the new version serves."],
|
|
4576
|
+
flags: [json]
|
|
4577
|
+
},
|
|
4578
|
+
{
|
|
4579
|
+
name: "status",
|
|
4580
|
+
group: "Service",
|
|
4581
|
+
summary: "Show state, address and processes",
|
|
4582
|
+
details: ["Exit status: 0 running, 3 not running."],
|
|
4583
|
+
flags: [json]
|
|
4584
|
+
},
|
|
4585
|
+
{
|
|
4586
|
+
name: "logs",
|
|
4587
|
+
group: "Service",
|
|
4588
|
+
summary: "Show recent logs",
|
|
4589
|
+
flags: [{
|
|
4590
|
+
name: "lines",
|
|
4591
|
+
short: "n",
|
|
4592
|
+
value: "<count>",
|
|
4593
|
+
summary: "Number of lines to show (default 100)"
|
|
4594
|
+
}, {
|
|
4595
|
+
name: "follow",
|
|
4596
|
+
short: "f",
|
|
4597
|
+
summary: "Keep printing new lines until Ctrl-C"
|
|
4598
|
+
}],
|
|
4599
|
+
examples: ["litepaseo logs -n 500", "litepaseo logs -f"]
|
|
4600
|
+
},
|
|
4601
|
+
{
|
|
4602
|
+
name: "serve",
|
|
4603
|
+
group: "Service",
|
|
4604
|
+
summary: "Run in the foreground (for service managers)"
|
|
4605
|
+
},
|
|
4606
|
+
{
|
|
4607
|
+
name: "token",
|
|
4608
|
+
group: "Sign-in",
|
|
4609
|
+
args: "[set|rotate]",
|
|
4610
|
+
summary: "Print, choose or replace the access token",
|
|
4611
|
+
details: [
|
|
4612
|
+
"The token is required to sign in from a browser.",
|
|
4613
|
+
"",
|
|
4614
|
+
"Actions:",
|
|
4615
|
+
" (none) print the current token",
|
|
4616
|
+
" set choose your own token: typed twice without echo, or read from standard input",
|
|
4617
|
+
" rotate replace it with a new random token and print it",
|
|
4618
|
+
"",
|
|
4619
|
+
`A chosen token needs at least 16 characters (letters, digits, punctuation; no spaces).`,
|
|
4620
|
+
"Both actions take effect immediately and sign out every browser."
|
|
4621
|
+
],
|
|
4622
|
+
examples: [
|
|
4623
|
+
"litepaseo token",
|
|
4624
|
+
"litepaseo token set",
|
|
4625
|
+
"litepaseo token rotate"
|
|
4626
|
+
]
|
|
4627
|
+
},
|
|
4628
|
+
{
|
|
4629
|
+
name: "totp-reset",
|
|
4630
|
+
group: "Sign-in",
|
|
4631
|
+
summary: "Turn off authenticator sign-in (lost phone)"
|
|
4632
|
+
},
|
|
4633
|
+
{
|
|
4634
|
+
name: "signout-all",
|
|
4635
|
+
group: "Sign-in",
|
|
4636
|
+
summary: "Sign out every browser and stop its notifications"
|
|
4637
|
+
},
|
|
4638
|
+
{
|
|
4639
|
+
name: "backup",
|
|
4640
|
+
group: "Data",
|
|
4641
|
+
args: "<directory>",
|
|
4642
|
+
positional: 1,
|
|
4643
|
+
summary: "Back up all data into a new directory",
|
|
4644
|
+
details: ["The backup contains credentials: keep it private."],
|
|
4645
|
+
examples: ["litepaseo backup ~/litepaseo-backup"]
|
|
4646
|
+
},
|
|
4647
|
+
{
|
|
4648
|
+
name: "restore",
|
|
4649
|
+
group: "Data",
|
|
4650
|
+
args: "<directory>",
|
|
4651
|
+
positional: 1,
|
|
4652
|
+
summary: "Restore a backup into an empty home",
|
|
4653
|
+
examples: ["LITEPASEO_HOME=~/.litepaseo-restored litepaseo restore ~/litepaseo-backup"]
|
|
4654
|
+
},
|
|
4655
|
+
{
|
|
4656
|
+
name: "service",
|
|
4657
|
+
group: "Autostart",
|
|
4658
|
+
args: "<action>",
|
|
4659
|
+
summary: "Manage the systemd / launchd user service",
|
|
4660
|
+
details: [
|
|
4661
|
+
"Actions:",
|
|
4662
|
+
" print show the service definition without installing it",
|
|
4663
|
+
" install install and start it at login",
|
|
4664
|
+
" uninstall stop and remove it",
|
|
4665
|
+
" status show the service manager's status",
|
|
4666
|
+
" start | stop | restart"
|
|
4667
|
+
],
|
|
4668
|
+
examples: ["litepaseo service install"]
|
|
4669
|
+
},
|
|
4670
|
+
{
|
|
4671
|
+
name: "version",
|
|
4672
|
+
group: "Other",
|
|
4673
|
+
summary: "Show version details",
|
|
4674
|
+
flags: [json]
|
|
4675
|
+
},
|
|
4676
|
+
{
|
|
4677
|
+
name: "help",
|
|
4678
|
+
group: "Other",
|
|
4679
|
+
args: "[command]",
|
|
4680
|
+
summary: "Show help for a command"
|
|
4681
|
+
}
|
|
4682
|
+
];
|
|
4683
|
+
function findCommand(name) {
|
|
4684
|
+
return COMMANDS.find((c) => c.name === name);
|
|
4685
|
+
}
|
|
4686
|
+
/** Edit distance counting a swap of neighbouring letters as one edit, the commonest typo. */
|
|
4687
|
+
function distance(a, b) {
|
|
4688
|
+
const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => i ? j ? 0 : i : j));
|
|
4689
|
+
for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
|
|
4690
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
4691
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
4692
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
4693
|
+
}
|
|
4694
|
+
return d[a.length][b.length];
|
|
4695
|
+
}
|
|
4696
|
+
/** The closest known name, if it is plausibly a typo. */
|
|
4697
|
+
function suggest(input, names) {
|
|
4698
|
+
let best, score = Infinity;
|
|
4699
|
+
for (const name of names) {
|
|
4700
|
+
const d = name.startsWith(input) && input.length >= 2 ? 0 : distance(input, name);
|
|
4701
|
+
if (d < score) [best, score] = [name, d];
|
|
4702
|
+
}
|
|
4703
|
+
return score <= Math.max(1, Math.floor((best?.length ?? 0) / 3)) ? best : void 0;
|
|
4704
|
+
}
|
|
4705
|
+
var UsageError = class extends Error {};
|
|
4706
|
+
/** Parses the arguments after the command name against its declared flags. */
|
|
4707
|
+
function parseArgs(command, argv) {
|
|
4708
|
+
const result = {
|
|
4709
|
+
positional: [],
|
|
4710
|
+
flags: {},
|
|
4711
|
+
help: false
|
|
4712
|
+
};
|
|
4713
|
+
const flags = command.flags ?? [];
|
|
4714
|
+
for (let i = 0; i < argv.length; i++) {
|
|
4715
|
+
const arg = argv[i];
|
|
4716
|
+
if (arg === "-h" || arg === "--help") {
|
|
4717
|
+
result.help = true;
|
|
4718
|
+
continue;
|
|
4719
|
+
}
|
|
4720
|
+
if (arg === "--") {
|
|
4721
|
+
result.positional.push(...argv.slice(i + 1));
|
|
4722
|
+
break;
|
|
4723
|
+
}
|
|
4724
|
+
if (!arg.startsWith("-") || arg === "-") {
|
|
4725
|
+
result.positional.push(arg);
|
|
4726
|
+
continue;
|
|
4727
|
+
}
|
|
4728
|
+
const [raw, inline] = arg.startsWith("--") ? [arg.slice(2).split("=")[0], arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : void 0] : [arg.slice(1), void 0];
|
|
4729
|
+
const flag = arg.startsWith("--") ? flags.find((f) => f.name === raw) : flags.find((f) => f.short === raw);
|
|
4730
|
+
if (!flag) throw new UsageError(`Unknown option ${arg} for '${command.name}'.`);
|
|
4731
|
+
if (!flag.value) {
|
|
4732
|
+
if (inline !== void 0) throw new UsageError(`Option --${flag.name} takes no value.`);
|
|
4733
|
+
result.flags[flag.name] = true;
|
|
4734
|
+
continue;
|
|
4735
|
+
}
|
|
4736
|
+
const value = inline ?? argv[++i];
|
|
4737
|
+
if (value === void 0) throw new UsageError(`Option ${arg} needs a value ${flag.value}.`);
|
|
4738
|
+
result.flags[flag.name] = value;
|
|
4739
|
+
}
|
|
4740
|
+
if (result.help) return result;
|
|
4741
|
+
const required = command.positional ?? 0;
|
|
4742
|
+
if (result.positional.length < required) throw new UsageError(`Missing ${command.args} for '${command.name}'.`);
|
|
4743
|
+
const allowed = command.args ? command.args.split(" ").length : 0;
|
|
4744
|
+
if (result.positional.length > allowed) throw new UsageError(`Unexpected argument '${result.positional[allowed]}' for '${command.name}'.`);
|
|
4745
|
+
return result;
|
|
4746
|
+
}
|
|
4747
|
+
function makeStyle(enabled) {
|
|
4748
|
+
const wrap = (open, close) => (s) => enabled ? `\x1b[${open}m${s}\x1b[${close}m` : s;
|
|
4749
|
+
return {
|
|
4750
|
+
bold: wrap(1, 22),
|
|
4751
|
+
dim: wrap(2, 22),
|
|
4752
|
+
green: wrap(32, 39),
|
|
4753
|
+
red: wrap(31, 39),
|
|
4754
|
+
yellow: wrap(33, 39),
|
|
4755
|
+
cyan: wrap(36, 39)
|
|
4756
|
+
};
|
|
4757
|
+
}
|
|
4758
|
+
/** Colour only for a terminal, and never against NO_COLOR; FORCE_COLOR overrides both. */
|
|
4759
|
+
function colorEnabled(env, isTTY) {
|
|
4760
|
+
if (env.FORCE_COLOR !== void 0) return env.FORCE_COLOR !== "0";
|
|
4761
|
+
if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
|
|
4762
|
+
return Boolean(isTTY) && env.TERM !== "dumb";
|
|
4763
|
+
}
|
|
4764
|
+
const usageOf = (c) => `litepaseo ${c.name}${c.args ? " " + c.args : ""}${c.flags?.length ? " [options]" : ""}`;
|
|
4765
|
+
function mainHelp(version, directory, s) {
|
|
4766
|
+
const lines = [
|
|
4767
|
+
`${s.bold("LitePaseo")} ${version}: a resource-conscious web console for your Paseo agents`,
|
|
4768
|
+
"",
|
|
4769
|
+
`${s.bold("Usage:")} litepaseo <command> [options]`
|
|
4770
|
+
];
|
|
4771
|
+
const groups = [...new Set(COMMANDS.map((c) => c.group))];
|
|
4772
|
+
for (const group of groups) {
|
|
4773
|
+
lines.push("", s.bold(group));
|
|
4774
|
+
for (const c of COMMANDS.filter((x) => x.group === group)) lines.push(` ${s.cyan((c.name + (c.args ? " " + c.args : "")).padEnd(22))}${c.summary}`);
|
|
4775
|
+
}
|
|
4776
|
+
lines.push("", s.bold("Options"), ` ${s.cyan("-h, --help".padEnd(22))}Show help (also after a command)`, ` ${s.cyan("-v, --version".padEnd(22))}Print the version`, "", s.bold("Environment"), ` ${s.cyan("LITEPASEO_HOME".padEnd(24))}Data directory ${s.dim(`(now ${directory})`)}`, ` ${s.cyan("LITEPASEO_PORT".padEnd(24))}Port ${s.dim("(8787)")}`, ` ${s.cyan("LITEPASEO_BIND".padEnd(24))}Listen address ${s.dim("(127.0.0.1)")}`, ` ${s.cyan("LITEPASEO_PUSH_SUBJECT".padEnd(24))}mailto: or https: contact for push services`, "", `Run ${s.bold("litepaseo help <command>")} for details on a command.`);
|
|
4777
|
+
return lines.join("\n");
|
|
4778
|
+
}
|
|
4779
|
+
function commandHelp(c, s) {
|
|
4780
|
+
const lines = [
|
|
4781
|
+
`${s.bold("Usage:")} ${usageOf(c)}`,
|
|
4782
|
+
"",
|
|
4783
|
+
c.summary + "."
|
|
4784
|
+
];
|
|
4785
|
+
if (c.details?.length) lines.push("", ...c.details);
|
|
4786
|
+
if (c.flags?.length) {
|
|
4787
|
+
lines.push("", s.bold("Options"));
|
|
4788
|
+
for (const f of c.flags) {
|
|
4789
|
+
const label = `${f.short ? `-${f.short}, ` : " "}--${f.name}${f.value ? " " + f.value : ""}`;
|
|
4790
|
+
lines.push(` ${s.cyan(label.padEnd(24))}${f.summary}`);
|
|
4791
|
+
}
|
|
4792
|
+
}
|
|
4793
|
+
if (c.examples?.length) lines.push("", s.bold("Examples"), ...c.examples.map((e) => " " + e));
|
|
4794
|
+
return lines.join("\n");
|
|
4795
|
+
}
|
|
4796
|
+
function formatDuration(ms) {
|
|
4797
|
+
const seconds = Math.max(0, Math.floor(ms / 1e3));
|
|
4798
|
+
const d = Math.floor(seconds / 86400), h = Math.floor(seconds % 86400 / 3600), m = Math.floor(seconds % 3600 / 60);
|
|
4799
|
+
if (d) return `${d}d ${h}h`;
|
|
4800
|
+
if (h) return `${h}h ${m}m`;
|
|
4801
|
+
if (m) return `${m}m ${seconds % 60}s`;
|
|
4802
|
+
return `${seconds}s`;
|
|
4803
|
+
}
|
|
4804
|
+
/** A note when the running instance is not the installed version (an upgrade needs a restart). */
|
|
4805
|
+
function versionNote(status, installed, s) {
|
|
4806
|
+
if (status.version === installed) return null;
|
|
4807
|
+
const running = status.version ? `version ${status.version}` : "an earlier version";
|
|
4808
|
+
return s.yellow(`! The running instance is ${running}; ${installed} is installed. Run 'litepaseo restart' to switch.`);
|
|
4809
|
+
}
|
|
4810
|
+
function formatStatus(status, installed, directory, s, now = Date.now()) {
|
|
4811
|
+
const state = status.ready ? s.green("● running") : status.restarts ? s.yellow("● restarting the worker") : s.yellow("● starting");
|
|
4812
|
+
const row = (label, value) => ` ${s.dim(label.padEnd(11))}${value}`;
|
|
4813
|
+
const lines = [`${s.bold("LitePaseo")} ${status.version ?? ""} ${state}`.replace(" ", " ")];
|
|
4814
|
+
if (status.url) lines.push(row("Address", s.cyan(status.url)));
|
|
4815
|
+
if (status.startedAt) {
|
|
4816
|
+
const started = new Date(status.startedAt);
|
|
4817
|
+
if (!Number.isNaN(started.getTime())) lines.push(row("Uptime", `${formatDuration(now - started.getTime())} ${s.dim(`(since ${started.toLocaleString()})`)}`));
|
|
4818
|
+
}
|
|
4819
|
+
lines.push(row("Processes", `supervisor ${status.pid}${status.workerPid ? `, worker ${status.workerPid}` : ", no worker"}`));
|
|
4820
|
+
if (status.restarts) lines.push(row("Restarts", String(status.restarts)));
|
|
4821
|
+
if (status.lastError) lines.push(row("Last error", s.red(status.lastError)));
|
|
4822
|
+
lines.push(row("Data", directory));
|
|
4823
|
+
const note = versionNote(status, installed, s);
|
|
4824
|
+
if (note) lines.push("", note);
|
|
4825
|
+
return lines.join("\n");
|
|
4826
|
+
}
|
|
4827
|
+
/** The last `count` lines of a text, keeping a trailing newline out of the count. */
|
|
4828
|
+
function lastLines(text, count) {
|
|
4829
|
+
if (count <= 0) return "";
|
|
4830
|
+
const body = text.endsWith("\n") ? text.slice(0, -1) : text;
|
|
4831
|
+
let index = body.length;
|
|
4832
|
+
for (let i = 0; i < count; i++) {
|
|
4833
|
+
index = body.lastIndexOf("\n", index - 1);
|
|
4834
|
+
if (index < 0) return text;
|
|
4835
|
+
}
|
|
4836
|
+
return text.slice(index + 1);
|
|
4837
|
+
}
|
|
3815
4838
|
// src/server/cli.ts
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
const
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
return
|
|
4839
|
+
/** `status` exit code when nothing is running, as for `systemctl status`. */
|
|
4840
|
+
const NOT_RUNNING = 3;
|
|
4841
|
+
const out = makeStyle(colorEnabled(process.env, process.stdout.isTTY));
|
|
4842
|
+
const err = makeStyle(colorEnabled(process.env, process.stderr.isTTY));
|
|
4843
|
+
const argv = process.argv.slice(2);
|
|
4844
|
+
const name = argv[0] ?? "help";
|
|
4845
|
+
/** Where data lives, for help text only: resolving it for real may migrate a legacy directory. */
|
|
4846
|
+
const displayDirectory = () => resolve(process.env.LITEPASEO_HOME || process.env.LITEPASEO_DATA_DIR || join(homedir(), ".litepaseo"));
|
|
4847
|
+
async function dataDirectory() {
|
|
4848
|
+
const { directory, notice } = await resolveDataDirectory(process.env, homedir(), process.platform);
|
|
4849
|
+
if (notice) console.error(notice);
|
|
4850
|
+
mkdirSync(directory, {
|
|
4851
|
+
recursive: true,
|
|
4852
|
+
mode: 448
|
|
4853
|
+
});
|
|
4854
|
+
process.umask(63);
|
|
4855
|
+
return {
|
|
4856
|
+
directory,
|
|
4857
|
+
socket: join(directory, "control.sock"),
|
|
4858
|
+
token: join(directory, "token"),
|
|
4859
|
+
log: join(directory, "service.log")
|
|
4860
|
+
};
|
|
4861
|
+
}
|
|
4862
|
+
function control(socket, action) {
|
|
4863
|
+
return new Promise((done, reject) => {
|
|
3833
4864
|
const s = connect(socket);
|
|
3834
|
-
let
|
|
4865
|
+
let text = "";
|
|
3835
4866
|
s.setTimeout(2e3, () => s.destroy(/* @__PURE__ */ new Error("Control request timed out")));
|
|
3836
4867
|
s.on("error", reject);
|
|
3837
4868
|
s.on("connect", () => s.end(action));
|
|
3838
|
-
s.on("data", (chunk) =>
|
|
3839
|
-
s.on("end", () =>
|
|
4869
|
+
s.on("data", (chunk) => text += chunk);
|
|
4870
|
+
s.on("end", () => done(text));
|
|
3840
4871
|
});
|
|
3841
4872
|
}
|
|
4873
|
+
async function status(paths) {
|
|
4874
|
+
const text = await control(paths.socket, "status").catch(() => null);
|
|
4875
|
+
if (!text) return null;
|
|
4876
|
+
try {
|
|
4877
|
+
return JSON.parse(text);
|
|
4878
|
+
} catch {
|
|
4879
|
+
return null;
|
|
4880
|
+
}
|
|
4881
|
+
}
|
|
4882
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3842
4883
|
/** The reason recorded by the supervisor that just stopped, if any. */
|
|
3843
|
-
function lastFailure(since) {
|
|
4884
|
+
function lastFailure(log, since) {
|
|
3844
4885
|
if (!existsSync(log)) return null;
|
|
3845
4886
|
const bytes = readFileSync(log);
|
|
3846
4887
|
const lines = bytes.subarray(bytes.length >= since ? since : 0).toString("utf8").trim().split("\n").reverse();
|
|
@@ -3850,107 +4891,262 @@ function lastFailure(since) {
|
|
|
3850
4891
|
} catch {}
|
|
3851
4892
|
return null;
|
|
3852
4893
|
}
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
return;
|
|
3865
|
-
}
|
|
3866
|
-
if (command === "service") {
|
|
3867
|
-
console.log(manageService(process.argv[3] ?? "print", {
|
|
3868
|
-
platform: process.platform,
|
|
3869
|
-
home: homedir(),
|
|
3870
|
-
directory,
|
|
3871
|
-
node: process.execPath,
|
|
3872
|
-
cli: fileURLToPath(import.meta.url),
|
|
3873
|
-
env: process.env,
|
|
3874
|
-
uid: process.getuid?.() ?? 0
|
|
3875
|
-
}));
|
|
4894
|
+
function printStarted(state, already) {
|
|
4895
|
+
console.log(`${out.green("●")} LitePaseo ${state.version ?? ""} ${already ? "is already running" : "is running"} at ${out.cyan(state.url)}`.replace(" ", " "));
|
|
4896
|
+
const note = versionNote(state, VERSION, out);
|
|
4897
|
+
if (note) console.log(note);
|
|
4898
|
+
else if (!already) console.log(out.dim(" Sign in with the access token from: litepaseo token"));
|
|
4899
|
+
}
|
|
4900
|
+
async function start(paths, args) {
|
|
4901
|
+
const running = await status(paths);
|
|
4902
|
+
if (running) {
|
|
4903
|
+
if (args.flags.json) console.log(JSON.stringify(running));
|
|
4904
|
+
else printStarted(running, true);
|
|
3876
4905
|
return;
|
|
3877
4906
|
}
|
|
3878
|
-
|
|
3879
|
-
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
4907
|
+
const logStart = existsSync(paths.log) ? statSync(paths.log).size : 0;
|
|
4908
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "serve"], {
|
|
4909
|
+
detached: true,
|
|
4910
|
+
stdio: "ignore",
|
|
4911
|
+
env: process.env
|
|
4912
|
+
});
|
|
4913
|
+
let exited = false;
|
|
4914
|
+
child.on("error", () => {});
|
|
4915
|
+
child.once("exit", () => {
|
|
4916
|
+
exited = true;
|
|
4917
|
+
});
|
|
4918
|
+
child.unref();
|
|
4919
|
+
for (let i = 0; i < 100; i++) {
|
|
4920
|
+
await sleep(100);
|
|
4921
|
+
if (exited) throw new Error(lastFailure(paths.log, logStart) ?? "Startup failed. Run 'litepaseo logs' for details.");
|
|
4922
|
+
const ready = await status(paths);
|
|
4923
|
+
if (ready?.ready) {
|
|
4924
|
+
if (args.flags.json) console.log(JSON.stringify(ready));
|
|
4925
|
+
else printStarted(ready, false);
|
|
4926
|
+
return;
|
|
4927
|
+
}
|
|
3885
4928
|
}
|
|
3886
|
-
|
|
3887
|
-
|
|
4929
|
+
throw new Error("Startup not ready after 10 s. Run 'litepaseo status' or 'litepaseo logs'.");
|
|
4930
|
+
}
|
|
4931
|
+
async function stop(paths, quiet = false) {
|
|
4932
|
+
if (!await control(paths.socket, "stop").catch(() => null)) {
|
|
4933
|
+
if (!quiet) console.log("LitePaseo is not running.");
|
|
3888
4934
|
return;
|
|
3889
4935
|
}
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
3897
|
-
|
|
4936
|
+
for (let i = 0; i < 150 && existsSync(paths.socket); i++) await sleep(100);
|
|
4937
|
+
if (existsSync(paths.socket)) throw new Error("LitePaseo has not stopped after 15 s. Run 'litepaseo status'.");
|
|
4938
|
+
if (!quiet) console.log("LitePaseo stopped.");
|
|
4939
|
+
}
|
|
4940
|
+
async function showStatus(paths, args) {
|
|
4941
|
+
const state = await status(paths);
|
|
4942
|
+
if (args.flags.json) console.log(JSON.stringify(state ?? { running: false }));
|
|
4943
|
+
else if (state) console.log(formatStatus(state, VERSION, paths.directory, out));
|
|
4944
|
+
else console.log(`${out.dim("○")} LitePaseo is not running\n ${out.dim("Start it with: litepaseo start")}`);
|
|
4945
|
+
if (!state) process.exitCode = NOT_RUNNING;
|
|
4946
|
+
}
|
|
4947
|
+
async function logs(paths, args) {
|
|
4948
|
+
const count = args.flags.lines === void 0 ? 100 : Number(args.flags.lines);
|
|
4949
|
+
if (!Number.isInteger(count) || count < 0) throw new UsageError("--lines needs a whole number.");
|
|
4950
|
+
let text = existsSync(paths.log) ? readFileSync(paths.log, "utf8") : "";
|
|
4951
|
+
if (text.split("\n").length <= count && existsSync(paths.log + ".1")) text = readFileSync(paths.log + ".1", "utf8") + text;
|
|
4952
|
+
const tail = lastLines(text, count);
|
|
4953
|
+
if (tail) process.stdout.write(tail.endsWith("\n") ? tail : tail + "\n");
|
|
4954
|
+
else if (!args.flags.follow) console.log(out.dim(`No logs yet in ${paths.log}`));
|
|
4955
|
+
if (!args.flags.follow) return;
|
|
4956
|
+
let position = existsSync(paths.log) ? statSync(paths.log).size : 0;
|
|
4957
|
+
let inode = existsSync(paths.log) ? statSync(paths.log).ino : 0;
|
|
4958
|
+
for (;;) {
|
|
4959
|
+
await sleep(500);
|
|
4960
|
+
if (!existsSync(paths.log)) continue;
|
|
4961
|
+
const info = statSync(paths.log);
|
|
4962
|
+
if (info.ino !== inode || info.size < position) [position, inode] = [0, info.ino];
|
|
4963
|
+
if (info.size === position) continue;
|
|
4964
|
+
const fd = openSync(paths.log, "r");
|
|
4965
|
+
try {
|
|
4966
|
+
const chunk = Buffer.alloc(info.size - position);
|
|
4967
|
+
const read = readSync(fd, chunk, 0, chunk.length, position);
|
|
4968
|
+
process.stdout.write(chunk.subarray(0, read));
|
|
4969
|
+
position += read;
|
|
4970
|
+
} finally {
|
|
4971
|
+
closeSync(fd);
|
|
3898
4972
|
}
|
|
3899
|
-
store.close();
|
|
3900
|
-
return;
|
|
3901
4973
|
}
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
4974
|
+
}
|
|
4975
|
+
/** Reads a line from the terminal without echoing it. */
|
|
4976
|
+
function promptHidden(question) {
|
|
4977
|
+
return new Promise((done, reject) => {
|
|
4978
|
+
const input = process.stdin;
|
|
4979
|
+
process.stderr.write(question);
|
|
4980
|
+
input.setRawMode(true);
|
|
4981
|
+
input.setEncoding("utf8");
|
|
4982
|
+
input.resume();
|
|
4983
|
+
let value = "";
|
|
4984
|
+
const finish = (error) => {
|
|
4985
|
+
input.setRawMode(false);
|
|
4986
|
+
input.pause();
|
|
4987
|
+
input.removeListener("data", onData);
|
|
4988
|
+
process.stderr.write("\n");
|
|
4989
|
+
if (error) reject(error);
|
|
4990
|
+
else done(value);
|
|
4991
|
+
};
|
|
4992
|
+
const onData = (chunk) => {
|
|
4993
|
+
for (const char of chunk) {
|
|
4994
|
+
if (char === "\r" || char === "\n") return finish();
|
|
4995
|
+
if (char === "" || char === "") return finish(/* @__PURE__ */ new Error("Cancelled; the token is unchanged."));
|
|
4996
|
+
if (char === "" || char === "\b") value = value.slice(0, -1);
|
|
4997
|
+
else value += char;
|
|
4998
|
+
}
|
|
4999
|
+
};
|
|
5000
|
+
input.on("data", onData);
|
|
5001
|
+
});
|
|
5002
|
+
}
|
|
5003
|
+
/** The new token from the terminal (typed twice) or from standard input, never from argv. */
|
|
5004
|
+
async function chosenToken() {
|
|
5005
|
+
if (process.stdin.isTTY) {
|
|
5006
|
+
const first = (await promptHidden("New access token: ")).trim();
|
|
5007
|
+
const problem = tokenProblem(first);
|
|
5008
|
+
if (problem) throw new Error(problem);
|
|
5009
|
+
if ((await promptHidden("Repeat it: ")).trim() !== first) throw new Error("The tokens differ; the token is unchanged.");
|
|
5010
|
+
return first;
|
|
5011
|
+
}
|
|
5012
|
+
const value = readFileSync(0, "utf8").trim();
|
|
5013
|
+
const problem = tokenProblem(value);
|
|
5014
|
+
if (problem) throw new Error(problem);
|
|
5015
|
+
return value;
|
|
5016
|
+
}
|
|
5017
|
+
async function token(paths, action) {
|
|
5018
|
+
if (action === void 0) {
|
|
5019
|
+
if (!existsSync(paths.token)) throw new Error("No access token yet: it is created on first start. Run 'litepaseo start'.");
|
|
5020
|
+
return console.log(readFileSync(paths.token, "utf8").trim());
|
|
5021
|
+
}
|
|
5022
|
+
if (!TOKEN_ACTIONS.includes(action)) {
|
|
5023
|
+
const guess = suggest(action, TOKEN_ACTIONS);
|
|
5024
|
+
throw new UsageError(`Unknown token action '${action}'.${guess ? ` Did you mean '${guess}'?` : ""} Actions: ${TOKEN_ACTIONS.join(", ")}.`);
|
|
5025
|
+
}
|
|
5026
|
+
const value = action === "set" ? await chosenToken() : generateToken();
|
|
5027
|
+
writeTokenFile(paths.token, value);
|
|
5028
|
+
const store = new Store(paths.directory);
|
|
5029
|
+
try {
|
|
5030
|
+
store.revokeSessions();
|
|
5031
|
+
} finally {
|
|
5032
|
+
store.close();
|
|
3909
5033
|
}
|
|
3910
|
-
if (
|
|
3911
|
-
|
|
3912
|
-
|
|
3913
|
-
|
|
3914
|
-
|
|
5034
|
+
if (action === "rotate") console.log(value);
|
|
5035
|
+
console.error(`${action === "set" ? "Access token saved" : "New access token above"}. Every browser is signed out; sign in again with the new token.`);
|
|
5036
|
+
const running = await status(paths);
|
|
5037
|
+
const note = running && versionNote(running, VERSION, err);
|
|
5038
|
+
if (note) console.error(note);
|
|
5039
|
+
}
|
|
5040
|
+
async function version(args) {
|
|
5041
|
+
const paths = await dataDirectory();
|
|
5042
|
+
const state = await status(paths);
|
|
5043
|
+
const details = {
|
|
5044
|
+
version: VERSION,
|
|
5045
|
+
node: process.versions.node,
|
|
5046
|
+
platform: `${process.platform}-${process.arch}`,
|
|
5047
|
+
home: paths.directory,
|
|
5048
|
+
running: state ? state.version ?? "unknown" : null
|
|
5049
|
+
};
|
|
5050
|
+
if (args.flags.json) return console.log(JSON.stringify(details));
|
|
5051
|
+
const row = (label, value) => ` ${out.dim(label.padEnd(10))}${value}`;
|
|
5052
|
+
console.log([
|
|
5053
|
+
`${out.bold("LitePaseo")} ${VERSION}`,
|
|
5054
|
+
row("Node.js", details.node),
|
|
5055
|
+
row("Platform", details.platform),
|
|
5056
|
+
row("Data", details.home),
|
|
5057
|
+
row("Running", state ? `${details.running} at ${out.cyan(state.url)}` : out.dim("not running"))
|
|
5058
|
+
].join("\n"));
|
|
5059
|
+
if (state) {
|
|
5060
|
+
const note = versionNote(state, VERSION, out);
|
|
5061
|
+
if (note) console.log("\n" + note);
|
|
3915
5062
|
}
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
5063
|
+
}
|
|
5064
|
+
async function run() {
|
|
5065
|
+
if (name === "--version" || name === "-v" || name === "-V") return console.log(VERSION);
|
|
5066
|
+
if (name === "--help" || name === "-h") return console.log(mainHelp(VERSION, displayDirectory(), out));
|
|
5067
|
+
if (name === "worker") return runWorker((await dataDirectory()).directory, fileURLToPath(new URL("../web/", import.meta.url)));
|
|
5068
|
+
const command = findCommand(name);
|
|
5069
|
+
if (!command) {
|
|
5070
|
+
const guess = suggest(name, COMMANDS.map((c) => c.name));
|
|
5071
|
+
throw new UsageError(`Unknown command '${name}'.${guess ? ` Did you mean '${guess}'?` : ""}`);
|
|
5072
|
+
}
|
|
5073
|
+
const args = parseArgs(command, argv.slice(1));
|
|
5074
|
+
if (args.help) return console.log(commandHelp(command, out));
|
|
5075
|
+
switch (command.name) {
|
|
5076
|
+
case "help": {
|
|
5077
|
+
const topic = args.positional[0];
|
|
5078
|
+
if (!topic) return console.log(mainHelp(VERSION, displayDirectory(), out));
|
|
5079
|
+
const target = findCommand(topic);
|
|
5080
|
+
if (!target) {
|
|
5081
|
+
const guess = suggest(topic, COMMANDS.map((c) => c.name));
|
|
5082
|
+
throw new UsageError(`No help for '${topic}'.${guess ? ` Did you mean '${guess}'?` : ""}`);
|
|
5083
|
+
}
|
|
5084
|
+
return console.log(commandHelp(target, out));
|
|
5085
|
+
}
|
|
5086
|
+
case "version": return version(args);
|
|
5087
|
+
}
|
|
5088
|
+
const paths = await dataDirectory();
|
|
5089
|
+
switch (command.name) {
|
|
5090
|
+
case "start": return start(paths, args);
|
|
5091
|
+
case "stop": return stop(paths);
|
|
5092
|
+
case "restart":
|
|
5093
|
+
await stop(paths, true);
|
|
5094
|
+
return start(paths, args);
|
|
5095
|
+
case "status": return showStatus(paths, args);
|
|
5096
|
+
case "logs": return logs(paths, args);
|
|
5097
|
+
case "serve": return supervise(paths.directory, fileURLToPath(import.meta.url));
|
|
5098
|
+
case "token": return token(paths, args.positional[0]);
|
|
5099
|
+
case "totp-reset":
|
|
5100
|
+
case "signout-all": {
|
|
5101
|
+
const store = new Store(paths.directory);
|
|
5102
|
+
try {
|
|
5103
|
+
if (command.name === "totp-reset") {
|
|
5104
|
+
store.setSetting("totp_secret", null);
|
|
5105
|
+
console.log("Authenticator sign-in is off. Sign in with the token from: litepaseo token");
|
|
5106
|
+
} else {
|
|
5107
|
+
store.revokeSessions();
|
|
5108
|
+
console.log("Every browser is signed out; their notifications stop.");
|
|
5109
|
+
}
|
|
5110
|
+
} finally {
|
|
5111
|
+
store.close();
|
|
5112
|
+
}
|
|
3920
5113
|
return;
|
|
3921
5114
|
}
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
child.unref();
|
|
3934
|
-
for (let i = 0; i < 100; i++) {
|
|
3935
|
-
await new Promise((r) => setTimeout(r, 100));
|
|
3936
|
-
if (exited) throw new Error(lastFailure(logStart) ?? "Startup failed. Run litepaseo logs for details.");
|
|
3937
|
-
const ready = await control("status").catch(() => null);
|
|
3938
|
-
if (ready && JSON.parse(ready).ready) {
|
|
3939
|
-
console.log(ready);
|
|
3940
|
-
console.log("Retrieve your browser access token with: litepaseo token");
|
|
3941
|
-
return;
|
|
5115
|
+
case "backup":
|
|
5116
|
+
backup(paths.directory, args.positional[0]);
|
|
5117
|
+
return console.log("Backup complete. Keep this directory private: it contains credentials.");
|
|
5118
|
+
case "restore":
|
|
5119
|
+
await restore(args.positional[0], paths.directory);
|
|
5120
|
+
return console.log(`Restore complete into ${paths.directory}. Start it with: litepaseo start`);
|
|
5121
|
+
case "service": {
|
|
5122
|
+
const action = args.positional[0] ?? "print";
|
|
5123
|
+
if (!SERVICE_ACTIONS.includes(action)) {
|
|
5124
|
+
const guess = suggest(action, SERVICE_ACTIONS);
|
|
5125
|
+
throw new UsageError(`Unknown service action '${action}'.${guess ? ` Did you mean '${guess}'?` : ""} Actions: ${SERVICE_ACTIONS.join(", ")}.`);
|
|
3942
5126
|
}
|
|
5127
|
+
return console.log(manageService(action, {
|
|
5128
|
+
platform: process.platform,
|
|
5129
|
+
home: homedir(),
|
|
5130
|
+
directory: paths.directory,
|
|
5131
|
+
node: process.execPath,
|
|
5132
|
+
cli: fileURLToPath(import.meta.url),
|
|
5133
|
+
env: process.env,
|
|
5134
|
+
uid: process.getuid?.() ?? 0
|
|
5135
|
+
}));
|
|
3943
5136
|
}
|
|
3944
|
-
throw new Error("Startup not ready after 10 s. Run litepaseo status or litepaseo logs.");
|
|
3945
5137
|
}
|
|
3946
|
-
if (command === "worker") return runWorker(directory, fileURLToPath(new URL("../web/", import.meta.url)));
|
|
3947
|
-
if (command === "serve") return supervise(directory, fileURLToPath(import.meta.url));
|
|
3948
|
-
throw new Error("Unknown command. Run litepaseo --help");
|
|
3949
5138
|
}
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
5139
|
+
run().catch(async (error) => {
|
|
5140
|
+
if (error instanceof UsageError) {
|
|
5141
|
+
console.error(`${err.red("error:")} ${error.message}`);
|
|
5142
|
+
const command = findCommand(name);
|
|
5143
|
+
console.error(err.dim(command && name !== "help" ? `Run 'litepaseo ${name} --help' for usage.` : "Run 'litepaseo --help' for the list of commands."));
|
|
5144
|
+
process.exitCode = 2;
|
|
5145
|
+
return;
|
|
5146
|
+
}
|
|
5147
|
+
console.error(`${err.red("error:")} ${error.message}`);
|
|
5148
|
+
if (name === "serve" && !(error instanceof StartupFailure)) try {
|
|
5149
|
+
new RotatingLog((await dataDirectory()).log).write(JSON.stringify({
|
|
3954
5150
|
event: "supervisor_start_failed",
|
|
3955
5151
|
error: error.message
|
|
3956
5152
|
}) + "\n");
|