litepaseo 0.3.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.
Files changed (89) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +22 -5
  3. package/dist/server/cli.mjs +650 -32
  4. package/dist/web/assets/{CodeBlockNode-D-c_NpDN.js → CodeBlockNode-fLbELjCG.js} +1 -1
  5. package/dist/web/assets/CodeBlockNode-fLbELjCG.js.br +0 -0
  6. package/dist/web/assets/CodeBlockNode-fLbELjCG.js.gz +0 -0
  7. package/dist/web/assets/{FileViewer-C6rgOMRo.js → FileViewer-C7zGfiFt.js} +1 -1
  8. package/dist/web/assets/FileViewer-C7zGfiFt.js.br +0 -0
  9. package/dist/web/assets/FileViewer-C7zGfiFt.js.gz +0 -0
  10. package/dist/web/assets/{FilesPanel-CNkBvKGD.js → FilesPanel-B1YfdWK8.js} +1 -1
  11. package/dist/web/assets/FilesPanel-B1YfdWK8.js.br +0 -0
  12. package/dist/web/assets/FilesPanel-B1YfdWK8.js.gz +0 -0
  13. package/dist/web/assets/{MarkdownMessage-DjRNZCD0.js → MarkdownMessage-C30PkBRA.js} +5 -5
  14. package/dist/web/assets/MarkdownMessage-C30PkBRA.js.br +0 -0
  15. package/dist/web/assets/MarkdownMessage-C30PkBRA.js.gz +0 -0
  16. package/dist/web/assets/{PreCodeBlock-BitPoeXT.js → PreCodeBlock-3ozveRNf.js} +1 -1
  17. package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js → PreCodeBlock.vue_vue_type_style_index_0_lang-BPnMZFbo.js} +1 -1
  18. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-BPnMZFbo.js.br +0 -0
  19. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-BPnMZFbo.js.gz +0 -0
  20. package/dist/web/assets/{TerminalPanel-CpGnkfa7.js → TerminalPanel-BR2okuCE.js} +1 -1
  21. package/dist/web/assets/TerminalPanel-BR2okuCE.js.br +0 -0
  22. package/dist/web/assets/TerminalPanel-BR2okuCE.js.gz +0 -0
  23. package/dist/web/assets/{Tooltip-C9GHriiI.js → Tooltip-Dh7ELGI1.js} +1 -1
  24. package/dist/web/assets/Tooltip-Dh7ELGI1.js.br +0 -0
  25. package/dist/web/assets/Tooltip-Dh7ELGI1.js.gz +0 -0
  26. package/dist/web/assets/index-BJ4CkuXT.js +30 -0
  27. package/dist/web/assets/index-BJ4CkuXT.js.br +0 -0
  28. package/dist/web/assets/index-BJ4CkuXT.js.gz +0 -0
  29. package/dist/web/assets/{index-Wf4Xa0ob.css → index-CaFqUnEO.css} +1 -1
  30. package/dist/web/assets/index-CaFqUnEO.css.br +0 -0
  31. package/dist/web/assets/index-CaFqUnEO.css.gz +0 -0
  32. package/dist/web/assets/{index10-QexvIpKb.js → index10-BXOnBXXV.js} +1 -1
  33. package/dist/web/assets/index10-BXOnBXXV.js.br +0 -0
  34. package/dist/web/assets/index10-BXOnBXXV.js.gz +0 -0
  35. package/dist/web/assets/index3-C1CbKHXb.js +1 -0
  36. package/dist/web/assets/index4-CE4EA6Rx.js +1 -0
  37. package/dist/web/assets/{index5-DaBM1kaC.js → index5-BrR0S3K6.js} +1 -1
  38. package/dist/web/assets/index5-BrR0S3K6.js.br +0 -0
  39. package/dist/web/assets/index5-BrR0S3K6.js.gz +0 -0
  40. package/dist/web/assets/{index6-1dcCVob7.js → index6-DWBoE2gM.js} +1 -1
  41. package/dist/web/assets/index6-DWBoE2gM.js.br +0 -0
  42. package/dist/web/assets/index6-DWBoE2gM.js.gz +0 -0
  43. package/dist/web/assets/{index7-DGSFcnYT.js → index7-CoJTOvQ5.js} +1 -1
  44. package/dist/web/assets/index7-CoJTOvQ5.js.br +0 -0
  45. package/dist/web/assets/index7-CoJTOvQ5.js.gz +0 -0
  46. package/dist/web/assets/{index8-BjPxjipz.js → index8-CQGhir4p.js} +1 -1
  47. package/dist/web/assets/index8-CQGhir4p.js.br +0 -0
  48. package/dist/web/assets/index8-CQGhir4p.js.gz +0 -0
  49. package/dist/web/assets/{index9-VNQsX15e.js → index9-D_kItRZJ.js} +1 -1
  50. package/dist/web/assets/index9-D_kItRZJ.js.br +0 -0
  51. package/dist/web/assets/index9-D_kItRZJ.js.gz +0 -0
  52. package/dist/web/index.html +2 -2
  53. package/dist/web/index.html.br +0 -0
  54. package/dist/web/index.html.gz +0 -0
  55. package/docs/cloudflare-access.md +111 -0
  56. package/package.json +4 -1
  57. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js.br +0 -0
  58. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js.gz +0 -0
  59. package/dist/web/assets/FileViewer-C6rgOMRo.js.br +0 -0
  60. package/dist/web/assets/FileViewer-C6rgOMRo.js.gz +0 -0
  61. package/dist/web/assets/FilesPanel-CNkBvKGD.js.br +0 -0
  62. package/dist/web/assets/FilesPanel-CNkBvKGD.js.gz +0 -0
  63. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js.br +0 -0
  64. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js.gz +0 -0
  65. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js.br +0 -0
  66. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js.gz +0 -0
  67. package/dist/web/assets/TerminalPanel-CpGnkfa7.js.br +0 -0
  68. package/dist/web/assets/TerminalPanel-CpGnkfa7.js.gz +0 -0
  69. package/dist/web/assets/Tooltip-C9GHriiI.js.br +0 -0
  70. package/dist/web/assets/Tooltip-C9GHriiI.js.gz +0 -0
  71. package/dist/web/assets/index-D4mQel3H.js +0 -30
  72. package/dist/web/assets/index-D4mQel3H.js.br +0 -0
  73. package/dist/web/assets/index-D4mQel3H.js.gz +0 -0
  74. package/dist/web/assets/index-Wf4Xa0ob.css.br +0 -0
  75. package/dist/web/assets/index-Wf4Xa0ob.css.gz +0 -0
  76. package/dist/web/assets/index10-QexvIpKb.js.br +0 -0
  77. package/dist/web/assets/index10-QexvIpKb.js.gz +0 -0
  78. package/dist/web/assets/index3-B9LRPNVQ.js +0 -1
  79. package/dist/web/assets/index4-CTBFr99S.js +0 -1
  80. package/dist/web/assets/index5-DaBM1kaC.js.br +0 -0
  81. package/dist/web/assets/index5-DaBM1kaC.js.gz +0 -0
  82. package/dist/web/assets/index6-1dcCVob7.js.br +0 -0
  83. package/dist/web/assets/index6-1dcCVob7.js.gz +0 -0
  84. package/dist/web/assets/index7-DGSFcnYT.js.br +0 -0
  85. package/dist/web/assets/index7-DGSFcnYT.js.gz +0 -0
  86. package/dist/web/assets/index8-BjPxjipz.js.br +0 -0
  87. package/dist/web/assets/index8-BjPxjipz.js.gz +0 -0
  88. package/dist/web/assets/index9-VNQsX15e.js.br +0 -0
  89. package/dist/web/assets/index9-VNQsX15e.js.gz +0 -0
@@ -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.3.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 {
@@ -2377,10 +2378,47 @@ function matchTotp(secret, code, now = Date.now()) {
2377
2378
  return null;
2378
2379
  }
2379
2380
  const sha256 = (text) => createHash("sha256").update(text).digest("hex");
2380
- const equalSecret = (a, b) => {
2381
- const x = Buffer.from(a), y = Buffer.from(b);
2382
- return x.length === y.length && timingSafeEqual(x, y);
2383
- };
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
+ }
2384
2422
  /**
2385
2423
  * Login and sessions. A browser signs in once, with the access token and, when enabled, an authenticator code,
2386
2424
  * and receives an opaque session secret (stored only as a hash). Sessions are listed and
@@ -2399,7 +2437,7 @@ var Auth = class {
2399
2437
  pendingTotp = null;
2400
2438
  constructor(store, token) {
2401
2439
  this.store = store;
2402
- this.token = token;
2440
+ this.token = typeof token === "string" ? () => token : token;
2403
2441
  const saved = store.setting("totp_login_limit");
2404
2442
  if (saved) this.global = JSON.parse(saved);
2405
2443
  if (store.setting("auth_policy") !== "token-plus-totp-v1") {
@@ -2417,9 +2455,30 @@ var Auth = class {
2417
2455
  totpEnabled() {
2418
2456
  return this.store.setting("totp_secret") !== null;
2419
2457
  }
2420
- /** Validates a bearer token (CLI, tests) without creating a session. */
2458
+ /** Whether `token` is the current access token. */
2421
2459
  checkToken(token) {
2422
- return equalSecret(token, this.token);
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 };
2423
2482
  }
2424
2483
  login(input, client, label, now = Date.now()) {
2425
2484
  const tokenLimit = this.limited(client, false, now);
@@ -2807,9 +2866,9 @@ var UsageService = class {
2807
2866
  };
2808
2867
  // src/server/dictation.ts
2809
2868
  /**
2810
- * Voice input configured once in LitePaseo instead of on every Paseo host. The browser records
2811
- * 16 kHz mono PCM and posts it once; the server wraps it as WAV and sends it to an
2812
- * OpenAI-compatible `/audio/transcriptions` endpoint. No host is involved.
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.
2813
2872
  *
2814
2873
  * Request shape differs by model generation (OpenAI speech-to-text guide, 2026):
2815
2874
  * - `gpt-transcribe` takes `languages[]` (several expected languages, for code-switching) and
@@ -2938,7 +2997,7 @@ var DictationError = class extends Error {
2938
2997
  this.status = status;
2939
2998
  }
2940
2999
  };
2941
- async function send(config, file, shape, fetchImpl) {
3000
+ async function send(config, file, shape, fetchImpl, signal) {
2942
3001
  const form = new FormData();
2943
3002
  form.append("file", file, "dictation.wav");
2944
3003
  for (const [name, value] of transcriptionFields(config, shape)) form.append(name, value);
@@ -2948,7 +3007,7 @@ async function send(config, file, shape, fetchImpl) {
2948
3007
  method: "POST",
2949
3008
  headers: { authorization: `Bearer ${config.apiKey}` },
2950
3009
  body: form,
2951
- signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
3010
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)]) : AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
2952
3011
  });
2953
3012
  } catch (error) {
2954
3013
  const timeout = error.name === "TimeoutError";
@@ -2967,12 +3026,12 @@ async function send(config, file, shape, fetchImpl) {
2967
3026
  detail: String(detail)
2968
3027
  };
2969
3028
  }
2970
- async function transcribe(config, pcm, rate, fetchImpl = fetch) {
3029
+ async function transcribe(config, pcm, rate, fetchImpl = fetch, signal) {
2971
3030
  const file = new Blob([wav(pcm, rate)], { type: "audio/wav" });
2972
3031
  const shape = shapeFor(config.model);
2973
- let result = await send(config, file, shape, fetchImpl);
3032
+ let result = await send(config, file, shape, fetchImpl, signal);
2974
3033
  const hinted = config.languages.length > 0 || config.keywords.length > 0;
2975
- if (!result.ok && result.status === 400 && hinted && /language|keyword|prompt/i.test(result.detail)) result = await send(config, file, shape === "hints" ? "single" : "hints", fetchImpl).then((retry) => retry.ok ? retry : result);
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);
2976
3035
  if (!result.ok) {
2977
3036
  const scrubbed = result.detail.split(config.apiKey).join("…").replace(/\s+/g, " ").trim().slice(0, 200);
2978
3037
  throw new DictationError(`Transcription failed (${result.status})${scrubbed ? ": " + scrubbed : ""}`, 502);
@@ -2980,6 +3039,445 @@ async function transcribe(config, pcm, rate, fetchImpl = fetch) {
2980
3039
  if (result.text === void 0) throw new DictationError("The transcription service returned no text", 502);
2981
3040
  return result.text.trim();
2982
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 {};
2983
3481
  // src/server/app.ts
2984
3482
  const AGENT_FLUSH_MS = 100;
2985
3483
  const HOST_FLUSH_MS = 100;
@@ -3005,9 +3503,25 @@ const SESSION_COOKIE = "lp_session";
3005
3503
  /** Cookie-authenticated writes must carry this header; a cross-site form or image cannot. */
3006
3504
  const CSRF_HEADER = "x-litepaseo";
3007
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). */
3008
3518
  function createApp(store, hosts, token, webRoot, options = {}) {
3009
3519
  const app = new Hono();
3010
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
+ })));
3011
3525
  const attachments = new Attachments();
3012
3526
  const projectIcons = new IconCache();
3013
3527
  const viewers = /* @__PURE__ */ new Map();
@@ -3031,9 +3545,16 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3031
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));
3032
3546
  app.use("/api/*", async (c, next) => {
3033
3547
  c.header("Cache-Control", "no-store");
3034
- const bearer = c.req.header("authorization")?.replace(/^Bearer /, "");
3035
- if (bearer && !PUBLIC_API.has(c.req.path) && !auth.totpEnabled() && auth.checkToken(bearer)) {
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
+ }
3036
3556
  c.set("session", null);
3557
+ c.set("bearer", bearer);
3037
3558
  return next();
3038
3559
  }
3039
3560
  const secret = getCookie(c, SESSION_COOKIE);
@@ -3281,7 +3802,12 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3281
3802
  for (const stream of directoryStreams) stream.send(message);
3282
3803
  }, HOST_FLUSH_MS);
3283
3804
  });
3284
- const streamValidity = (session) => session ? () => auth.stillValid(session.id) : () => !auth.totpEnabled();
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
+ };
3285
3811
  app.get("/api/stream", (c) => {
3286
3812
  const since = Number(c.req.query("since"));
3287
3813
  const resumable = c.req.query("generation") === hosts.agents.generation && Number.isInteger(since);
@@ -3300,7 +3826,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3300
3826
  deliverAgents(stream);
3301
3827
  directoryStreams.add(stream);
3302
3828
  return () => directoryStreams.delete(stream);
3303
- }, streamValidity(c.get("session")));
3829
+ }, streamValidity(c));
3304
3830
  });
3305
3831
  app.post("/api/hosts", async (c) => {
3306
3832
  const input = z.object({
@@ -3432,7 +3958,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3432
3958
  if (!devices.size) viewers.delete(key);
3433
3959
  }
3434
3960
  };
3435
- }, streamValidity(c.get("session")));
3961
+ }, streamValidity(c));
3436
3962
  });
3437
3963
  /** Bounded history pages; the browser bookmarks boundaries for forward navigation. */
3438
3964
  app.get("/api/hosts/:host/agents/:agent/timeline", async (c) => {
@@ -3580,10 +4106,19 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3580
4106
  });
3581
4107
  /**
3582
4108
  * Speech to text through the transcription service configured here, once for every host. The
3583
- * browser records 16 kHz mono PCM and posts it once when the user stops: one request, no
3584
- * socket kept open while idle. The API key never leaves the server.
4109
+ * browser streams PCM over a short-lived socket. The file endpoint remains for older
4110
+ * clients. The API key never leaves the server.
3585
4111
  */
3586
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
+ });
3587
4122
  app.put("/api/dictation", async (c) => {
3588
4123
  try {
3589
4124
  return c.json(saveDictation(store, await c.req.json()));
@@ -3749,7 +4284,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3749
4284
  });
3750
4285
  }
3751
4286
  });
3752
- registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c.get("session")));
4287
+ registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c));
3753
4288
  app.get("/api/usage", async (c) => c.json(await usage.report(c.req.query("refresh") === "1")));
3754
4289
  app.get("/api/board", (c) => c.json(store.board()));
3755
4290
  app.put("/api/board", async (c) => {
@@ -3785,6 +4320,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3785
4320
  precompressed: true
3786
4321
  }));
3787
4322
  return Object.assign(app, {
4323
+ dictationStreams,
3788
4324
  /** Open directory streams; lets tests prove that disconnects release them. */
3789
4325
  openStreams: () => directoryStreams.size,
3790
4326
  dispose: () => {
@@ -3793,6 +4329,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3793
4329
  clearTimeout(hostFlush);
3794
4330
  agentFlush = hostFlush = void 0;
3795
4331
  attachments.close();
4332
+ dictationStreams.close();
3796
4333
  }
3797
4334
  });
3798
4335
  }
@@ -3800,7 +4337,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3800
4337
  async function runWorker(directory, webRoot) {
3801
4338
  if (!process.send) throw new Error("worker is an internal supervised command");
3802
4339
  const tokenPath = join(directory, "token");
3803
- if (!existsSync(tokenPath)) writeFileSync(tokenPath, randomBytes(32).toString("hex"), {
4340
+ if (!existsSync(tokenPath)) writeFileSync(tokenPath, generateToken(), {
3804
4341
  mode: 384,
3805
4342
  flag: "wx"
3806
4343
  });
@@ -3811,12 +4348,13 @@ async function runWorker(directory, webRoot) {
3811
4348
  console.error("Could not initialize host", host.id);
3812
4349
  }
3813
4350
  const port = Number(process.env.LITEPASEO_PORT ?? 8787), hostname = process.env.LITEPASEO_BIND ?? "127.0.0.1";
3814
- const app = createApp(store, hosts, readFileSync(tokenPath, "utf8").trim(), webRoot, { pushSubject: process.env.LITEPASEO_PUSH_SUBJECT });
4351
+ const app = createApp(store, hosts, tokenFile(tokenPath), webRoot, { pushSubject: process.env.LITEPASEO_PUSH_SUBJECT });
3815
4352
  const server = serve({
3816
4353
  fetch: app.fetch,
3817
4354
  port,
3818
4355
  hostname
3819
4356
  });
4357
+ app.dictationStreams.attach(server);
3820
4358
  let stopping = false;
3821
4359
  const shutdown = async () => {
3822
4360
  if (stopping) return;
@@ -3929,7 +4467,7 @@ async function restore(source, directory) {
3929
4467
  } finally {
3930
4468
  db.close();
3931
4469
  }
3932
- if (!/^[a-f0-9]{64}\s*$/.test(readFileSync(join(stage, "token"), "utf8"))) throw new Error("Invalid backup access token.");
4470
+ if (!/^[\x21-\x7e]{1,200}$/.test(readFileSync(join(stage, "token"), "utf8").trim())) throw new Error("Invalid backup access token.");
3933
4471
  writeFileSync(join(directory, ".restore-incomplete"), "Restore interrupted: restore the backup to a fresh home.\n", {
3934
4472
  mode: 384,
3935
4473
  flag: "wx"
@@ -4006,6 +4544,7 @@ const json = {
4006
4544
  name: "json",
4007
4545
  summary: "Print machine-readable JSON"
4008
4546
  };
4547
+ const TOKEN_ACTIONS = ["set", "rotate"];
4009
4548
  const SERVICE_ACTIONS = [
4010
4549
  "print",
4011
4550
  "install",
@@ -4067,8 +4606,24 @@ const COMMANDS = [
4067
4606
  {
4068
4607
  name: "token",
4069
4608
  group: "Sign-in",
4070
- summary: "Print the access token",
4071
- details: ["The token is required to sign in from a browser."]
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
+ ]
4072
4627
  },
4073
4628
  {
4074
4629
  name: "totp-reset",
@@ -4417,6 +4972,71 @@ async function logs(paths, args) {
4417
4972
  }
4418
4973
  }
4419
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();
5033
+ }
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
+ }
4420
5040
  async function version(args) {
4421
5041
  const paths = await dataDirectory();
4422
5042
  const state = await status(paths);
@@ -4475,9 +5095,7 @@ async function run() {
4475
5095
  case "status": return showStatus(paths, args);
4476
5096
  case "logs": return logs(paths, args);
4477
5097
  case "serve": return supervise(paths.directory, fileURLToPath(import.meta.url));
4478
- case "token":
4479
- if (!existsSync(paths.token)) throw new Error("No access token yet: it is created on first start. Run 'litepaseo start'.");
4480
- return console.log(readFileSync(paths.token, "utf8").trim());
5098
+ case "token": return token(paths, args.positional[0]);
4481
5099
  case "totp-reset":
4482
5100
  case "signout-all": {
4483
5101
  const store = new Store(paths.directory);