wherever-dev 0.11.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/drafts.d.ts +119 -0
  2. package/dist/drafts.d.ts.map +1 -0
  3. package/dist/drafts.js +272 -0
  4. package/dist/drafts.js.map +1 -0
  5. package/dist/index.js +271 -15
  6. package/dist/index.js.map +1 -1
  7. package/dist/session-pool.d.ts +31 -0
  8. package/dist/session-pool.d.ts.map +1 -1
  9. package/dist/session-pool.js +34 -2
  10. package/dist/session-pool.js.map +1 -1
  11. package/package.json +1 -1
  12. package/public/_app/immutable/assets/0.BS_EGmNW.css +1 -0
  13. package/public/_app/immutable/chunks/BeRKnBIj.js +3 -0
  14. package/public/_app/immutable/chunks/{itgD7vGH.js.map → BeRKnBIj.js.map} +1 -1
  15. package/public/_app/immutable/chunks/{Dtm96ZKi.js → C8CBGqeA.js} +2 -2
  16. package/public/_app/immutable/chunks/{Dtm96ZKi.js.map → C8CBGqeA.js.map} +1 -1
  17. package/public/_app/immutable/chunks/{CRRPBe07.js → Cum3gQOV.js} +2 -2
  18. package/public/_app/immutable/chunks/{CRRPBe07.js.map → Cum3gQOV.js.map} +1 -1
  19. package/public/_app/immutable/chunks/{CE0jm7EC.js → CyQq9q8L.js} +2 -2
  20. package/public/_app/immutable/chunks/{CE0jm7EC.js.map → CyQq9q8L.js.map} +1 -1
  21. package/public/_app/immutable/chunks/{CAWbdcQM.js → D5t5dKgW.js} +2 -2
  22. package/public/_app/immutable/chunks/{CAWbdcQM.js.map → D5t5dKgW.js.map} +1 -1
  23. package/public/_app/immutable/chunks/{8jn76iTS.js → DdFruy3e.js} +2 -2
  24. package/public/_app/immutable/chunks/{8jn76iTS.js.map → DdFruy3e.js.map} +1 -1
  25. package/public/_app/immutable/chunks/{BDmEqqqL.js → vSWNc7VF.js} +2 -2
  26. package/public/_app/immutable/chunks/{BDmEqqqL.js.map → vSWNc7VF.js.map} +1 -1
  27. package/public/_app/immutable/entry/app.BzMua2z6.js +3 -0
  28. package/public/_app/immutable/entry/{app.YbNg9lmT.js.map → app.BzMua2z6.js.map} +1 -1
  29. package/public/_app/immutable/entry/start.B0ap2dTz.js +2 -0
  30. package/public/_app/immutable/entry/start.B0ap2dTz.js.map +1 -0
  31. package/public/_app/immutable/nodes/{0.BwSufUPS.js → 0.BDXduH3G.js} +3 -3
  32. package/public/_app/immutable/nodes/{0.BwSufUPS.js.map → 0.BDXduH3G.js.map} +1 -1
  33. package/public/_app/immutable/nodes/1.CqJo-807.js +2 -0
  34. package/public/_app/immutable/nodes/{1.x8yi4PgO.js.map → 1.CqJo-807.js.map} +1 -1
  35. package/public/_app/immutable/nodes/2.C6-6KHYk.js +110 -0
  36. package/public/_app/immutable/nodes/2.C6-6KHYk.js.map +1 -0
  37. package/public/_app/version.json +1 -1
  38. package/public/index.html +15 -15
  39. package/public/service-worker.js +1 -1
  40. package/public/_app/immutable/assets/0.BnJtv5fG.css +0 -1
  41. package/public/_app/immutable/chunks/itgD7vGH.js +0 -3
  42. package/public/_app/immutable/entry/app.YbNg9lmT.js +0 -3
  43. package/public/_app/immutable/entry/start.Mhebc2Bx.js +0 -2
  44. package/public/_app/immutable/entry/start.Mhebc2Bx.js.map +0 -1
  45. package/public/_app/immutable/nodes/1.x8yi4PgO.js +0 -2
  46. package/public/_app/immutable/nodes/2.BWbDsdRU.js +0 -104
  47. package/public/_app/immutable/nodes/2.BWbDsdRU.js.map +0 -1
package/dist/index.js CHANGED
@@ -2,7 +2,8 @@
2
2
  import { createServer as createHttpServer } from 'node:http';
3
3
  import { createServer as createHttpsServer, request as httpRequest } from 'node:https';
4
4
  import { WebSocketServer, WebSocket } from 'ws';
5
- import { SessionPool, getWhereverConfig, detectRemoteRepo } from './session-pool.js';
5
+ import { SessionPool, getWhereverConfig, getWhereverCertsDir, detectRemoteRepo } from './session-pool.js';
6
+ import { readDrafts, addDraft, deleteDraft, validateDraftInput } from './drafts.js';
6
7
  import { searchConversations } from './conversation-search.js';
7
8
  import { INITIAL_HISTORY_LIMIT, HISTORY_PAGE_SIZE } from './protocol.js';
8
9
  import fs from 'node:fs';
@@ -311,19 +312,123 @@ function evictPreviousConnection(clientKey, clients, pool, onSessionsUpdated) {
311
312
  function generateId() {
312
313
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
313
314
  }
315
+ /**
316
+ * Resolve the auth token WITHOUT requiring it on the command line.
317
+ *
318
+ * Anything in argv is world-readable: `ps -ef` (and /proc/<pid>/cmdline, which
319
+ * is mode 0444) shows the full command line of every process on the machine to
320
+ * every local user, so `--token <secret>` leaks the secret to any account on
321
+ * the box. That is fine for a laptop and NOT fine for a shared/bare-metal host,
322
+ * which is why the environment is the preferred channel for real deployments.
323
+ *
324
+ * Precedence, highest first:
325
+ * 1. `--token <value>` - explicit argv, kept for compatibility. LEAKS via ps.
326
+ * 2. `WHEREVER_TOKEN` - preferred for deployments.
327
+ * 3. `WHEREVER_TOKEN_FILE` - path to a file whose (trimmed) CONTENT is the
328
+ * token. The natural shape for a secret manager
329
+ * (sops-nix, systemd `LoadCredential`) which
330
+ * renders a root-owned 0400 file; nothing
331
+ * secret then exists in argv OR in the
332
+ * environment block.
333
+ * 4. `PI_REMOTE_TOKEN` - the pre-existing variable, still honoured.
334
+ *
335
+ * TRIMMING IS ASYMMETRIC ON PURPOSE, and the asymmetry is a compatibility rule,
336
+ * not an oversight. The two NEW sources are trimmed, because a secret manager
337
+ * renders a file with a trailing newline and `WHEREVER_TOKEN=$(cat ...)` is the
338
+ * obvious thing to write. The two PRE-EXISTING sources (`--token`,
339
+ * `PI_REMOTE_TOKEN`) are taken VERBATIM, exactly as before, because
340
+ * `authenticate()` compares the raw query parameter with `===`: trimming them
341
+ * would silently change WHICH string authenticates on an install that already
342
+ * has whitespace in its token, locking out every saved client URL. Likewise
343
+ * `--token` wins whenever the FLAG WAS GIVEN, even with an empty or missing
344
+ * value, because that is what the old `case '--token': token = args[++i]`
345
+ * did -- it overwrote whatever the environment had.
346
+ *
347
+ * An unreadable or empty `WHEREVER_TOKEN_FILE` is FATAL rather than "fall
348
+ * through to no token": silently starting an UNAUTHENTICATED server because a
349
+ * secret failed to mount is the one failure mode that must never happen
350
+ * quietly. Note this only fires when the file is the source actually being
351
+ * consulted: an explicit `--token`/`WHEREVER_TOKEN` above it still wins, and
352
+ * the server is authenticated either way.
353
+ */
354
+ function resolveToken(cliToken, cliTokenGiven) {
355
+ // `cliTokenGiven`, not `cliToken`, so that `--token ''` (and a trailing
356
+ // `--token` with no value) still SUPPRESSES the environment, as it did before.
357
+ if (cliTokenGiven)
358
+ return { token: cliToken || undefined, source: '--token' };
359
+ const envToken = process.env.WHEREVER_TOKEN;
360
+ if (envToken && envToken.trim())
361
+ return { token: envToken.trim(), source: 'WHEREVER_TOKEN' };
362
+ warnIfSetButBlank('WHEREVER_TOKEN', envToken);
363
+ const tokenFile = process.env.WHEREVER_TOKEN_FILE;
364
+ if (tokenFile && tokenFile.trim()) {
365
+ const resolvedPath = expandTilde(tokenFile.trim());
366
+ let contents;
367
+ try {
368
+ contents = fs.readFileSync(resolvedPath, 'utf8');
369
+ }
370
+ catch (err) {
371
+ console.error(`FATAL: WHEREVER_TOKEN_FILE is set to ${resolvedPath} but it could not be read ` +
372
+ `(${err.message}). Refusing to start: continuing would silently run an ` +
373
+ `UNAUTHENTICATED server.`);
374
+ process.exit(1);
375
+ }
376
+ const trimmed = contents.trim();
377
+ if (!trimmed) {
378
+ console.error(`FATAL: WHEREVER_TOKEN_FILE (${resolvedPath}) is empty. Refusing to start: continuing ` +
379
+ `would silently run an UNAUTHENTICATED server.`);
380
+ process.exit(1);
381
+ }
382
+ return { token: trimmed, source: `WHEREVER_TOKEN_FILE (${resolvedPath})` };
383
+ }
384
+ warnIfSetButBlank('WHEREVER_TOKEN_FILE', tokenFile);
385
+ // VERBATIM, including surrounding whitespace: see the trimming note above.
386
+ // `' '` is truthy and therefore enforced, exactly as it was before.
387
+ const legacy = process.env.PI_REMOTE_TOKEN;
388
+ if (legacy)
389
+ return { token: legacy, source: 'PI_REMOTE_TOKEN' };
390
+ return { token: undefined, source: 'none' };
391
+ }
392
+ /**
393
+ * A token variable that is SET but blank is almost always a secret that failed
394
+ * to render (a truncated file, a `$(cat ...)` that errored, a half-landed
395
+ * activation), and the consequence is an UNAUTHENTICATED server that looks
396
+ * perfectly healthy. It cannot be fatal -- `VAR=` is also the ordinary way to
397
+ * neutralise an inherited variable, which the test harness relies on -- so it
398
+ * is made LOUD instead. Silence is the only unacceptable outcome here.
399
+ */
400
+ function warnIfSetButBlank(name, value) {
401
+ if (value === undefined || value.length === 0)
402
+ return; // unset, or explicitly neutralised
403
+ if (value.trim().length > 0)
404
+ return;
405
+ console.warn(`[wherever] ${name} is set but contains only whitespace. Treating it as NOT SET. ` +
406
+ `If a secret was meant to be rendered here, it did not arrive, and this server may ` +
407
+ `be starting WITHOUT AUTHENTICATION.`);
408
+ }
314
409
  function parseArgs() {
315
410
  const args = process.argv.slice(2);
316
411
  let port = parseInt(process.env.PI_REMOTE_PORT || '31415', 10);
317
412
  let host = process.env.PI_REMOTE_HOST || '127.0.0.1';
318
- let token = process.env.PI_REMOTE_TOKEN || undefined;
413
+ // Kept separate from the env-derived token so `resolveToken` below can apply
414
+ // one documented precedence chain instead of "whoever assigned last wins".
415
+ // `cliTokenGiven` tracks the FLAG's presence separately from its VALUE, so
416
+ // `--token ''` still suppresses the environment the way it always did.
417
+ let cliToken = undefined;
418
+ let cliTokenGiven = false;
319
419
  // Idle eviction window. Longer than the old 5 min so a dip-in/dip-out mobile
320
420
  // user returns to a still-WARM session (no agent rebuild) most of the time.
321
421
  // With fast-first load a cold return is no longer slow to READ, but a warm
322
422
  // session also avoids the async agent build entirely. Override via
323
423
  // PI_IDLE_TIMEOUT (ms). See docs/plan-speed-up-long-session-load.md.
324
424
  let idleTimeout = parseInt(process.env.PI_IDLE_TIMEOUT || '1200000', 10);
325
- let sslKey = process.env.PI_REMOTE_SSL_KEY || undefined;
326
- let sslCert = process.env.PI_REMOTE_SSL_CERT || undefined;
425
+ // TLS material is addressed by PATH, and each half is resolved INDEPENDENTLY
426
+ // (flag > WHEREVER_* > PI_REMOTE_*). On a declaratively-managed host the key
427
+ // arrives from a secret manager at an arbitrary root-owned path (e.g.
428
+ // /run/secrets/wherever-key.pem) while the certificate is a world-readable
429
+ // file somewhere else entirely, so neither may be tied to a home directory.
430
+ let sslKey = process.env.WHEREVER_SSL_KEY || process.env.PI_REMOTE_SSL_KEY || undefined;
431
+ let sslCert = process.env.WHEREVER_SSL_CERT || process.env.PI_REMOTE_SSL_CERT || undefined;
327
432
  let noSsl = process.env.PI_REMOTE_NO_SSL === 'true' || process.env.PI_REMOTE_HTTP === 'true';
328
433
  let httpLocalhostFallbackPort = undefined;
329
434
  // Enables the eruda custom-plugin loader in the served dashboard (local
@@ -349,7 +454,8 @@ function parseArgs() {
349
454
  host = args[++i] || '127.0.0.1';
350
455
  break;
351
456
  case '--token':
352
- token = args[++i];
457
+ cliToken = args[++i];
458
+ cliTokenGiven = true;
353
459
  break;
354
460
  case '--idle-timeout':
355
461
  idleTimeout = parseInt(args[++i] || '300000', 10);
@@ -386,7 +492,22 @@ function parseArgs() {
386
492
  }
387
493
  }
388
494
  }
389
- return { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug };
495
+ const { token, source: tokenSource } = resolveToken(cliToken, cliTokenGiven);
496
+ // Scrub the token out of our own environment once it is resolved. Node builds
497
+ // a child's environment from `process.env`, and this server spawns children
498
+ // that are not ours to trust with it: the agent's own `bash` tool
499
+ // (session-pool.ts) and the memonaut indexer (conversation-search.ts) both
500
+ // inherit it, so `!env` typed in the dashboard -- or a prompt-injected agent
501
+ // running `echo $WHEREVER_TOKEN` -- would print the server's auth token into a
502
+ // transcript that is then indexed to disk. The value is already captured in
503
+ // `token` above; nothing reads these variables again.
504
+ delete process.env.WHEREVER_TOKEN;
505
+ delete process.env.PI_REMOTE_TOKEN;
506
+ return { port, host, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug };
507
+ }
508
+ /** Loopback-only binds are the safe default; everything else is reachable by others. */
509
+ function isLoopbackHost(host) {
510
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host.startsWith('127.');
390
511
  }
391
512
  function authenticate(req, token) {
392
513
  if (!token)
@@ -481,30 +602,64 @@ function sendThenTerminate(ws, msg, flushTimeoutMs = 1_000) {
481
602
  }
482
603
  }
483
604
  async function main() {
484
- const { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
605
+ const { port, host, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
485
606
  debugEnabled = debug;
486
607
  const sessionPool = new SessionPool(idleTimeout);
487
608
  await sessionPool.initialize();
488
609
  const clients = new Map();
489
- let actualSslKey = sslKey;
490
- let actualSslCert = sslCert;
610
+ // expandTilde so `~/certs/...` works from a systemd `Environment=` line or an
611
+ // EnvironmentFile, neither of which is shell-expanded. Without it the read
612
+ // below fails and (before the explicit-TLS check further down) the server
613
+ // quietly served plaintext instead.
614
+ let actualSslKey = sslKey ? expandTilde(sslKey) : sslKey;
615
+ let actualSslCert = sslCert ? expandTilde(sslCert) : sslCert;
491
616
  let isSecure = !noSsl;
617
+ let tlsExplicitlyConfigured = false;
492
618
  if (isSecure) {
619
+ // A key and a certificate only work as a PAIR, so "exactly one supplied" is a
620
+ // misconfiguration. It used to be silent: the `!key || !cert` test threw away
621
+ // the half that WAS supplied and used the self-signed pair, so an operator who
622
+ // pointed --ssl-key at a real key and forgot the cert got a working server
623
+ // presenting a completely different certificate, with nothing in the log. Say
624
+ // so, loudly; the behaviour (fall back to the self-signed pair) is unchanged.
625
+ if (!!actualSslKey !== !!actualSslCert) {
626
+ const supplied = actualSslKey ? '--ssl-key / WHEREVER_SSL_KEY' : '--ssl-cert / WHEREVER_SSL_CERT';
627
+ const missing = actualSslKey ? '--ssl-cert / WHEREVER_SSL_CERT' : '--ssl-key / WHEREVER_SSL_KEY';
628
+ console.warn(`[wherever] ${supplied} was supplied but ${missing} was not. A key and a certificate ` +
629
+ `must be given together; IGNORING the one supplied and using the self-signed pair instead.`);
630
+ actualSslKey = undefined;
631
+ actualSslCert = undefined;
632
+ }
633
+ // Whether the operator POINTED AT specific TLS material, as opposed to
634
+ // letting the server mint its own. It decides what happens if that material
635
+ // cannot be loaded further down: see the `tlsExplicitlyConfigured` branch.
636
+ tlsExplicitlyConfigured = !!(actualSslKey && actualSslCert);
493
637
  if (!actualSslKey || !actualSslCert) {
494
- // Automatic self-signed certificate generation
495
- const homeDir = os.homedir();
496
- const certsDir = path.join(homeDir, '.wherever', 'certs');
638
+ // Automatic self-signed certificate generation. These files are WRITTEN, so
639
+ // they belong to the state dir (WHEREVER_STATE_DIR, defaulting to the config
640
+ // dir, itself defaulting to ~/.wherever) -- with both unset this is exactly
641
+ // the ~/.wherever/certs it has always been.
642
+ const certsDir = getWhereverCertsDir();
643
+ // 0700 on creation: the state dir can now be pointed at a shared location
644
+ // (/var/lib/...), and a world-writable certs dir would let a local user
645
+ // swap in their own key/cert pair. An existing directory keeps its mode.
497
646
  const defaultKeyPath = path.join(certsDir, 'localhost.key');
498
647
  const defaultCertPath = path.join(certsDir, 'localhost.crt');
499
648
  if (!fs.existsSync(defaultKeyPath) || !fs.existsSync(defaultCertPath)) {
500
649
  console.log('Generating self-signed SSL certificates for secure HTTPS/WSS...');
501
650
  try {
502
- fs.mkdirSync(certsDir, { recursive: true });
651
+ fs.mkdirSync(certsDir, { recursive: true, mode: 0o700 });
503
652
  execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-keyout', defaultKeyPath, '-out', defaultCertPath, '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=localhost'], { stdio: 'ignore' });
653
+ // Assert 0600 ourselves rather than trusting openssl's default: it is
654
+ // a private key, and the mode it lands with has varied by version.
655
+ try {
656
+ fs.chmodSync(defaultKeyPath, 0o600);
657
+ }
658
+ catch { }
504
659
  console.log(`Self-signed certificates generated successfully in ${certsDir}`);
505
660
  }
506
661
  catch (err) {
507
- console.warn('Failed to generate self-signed certificates using OpenSSL. Falling back to HTTP.', err.message);
662
+ console.warn(`Failed to generate self-signed certificates in ${certsDir} using OpenSSL. Falling back to HTTP.`, err.message);
508
663
  isSecure = false;
509
664
  }
510
665
  }
@@ -779,6 +934,7 @@ async function main() {
779
934
  }
780
935
  const isApiRequest = pathname.startsWith('/sessions') ||
781
936
  pathname.startsWith('/search') ||
937
+ pathname.startsWith('/drafts') ||
782
938
  pathname.startsWith('/models') ||
783
939
  pathname.startsWith('/config') ||
784
940
  pathname.startsWith('/check-path') ||
@@ -819,6 +975,76 @@ async function main() {
819
975
  sendJSON(res, 200, { models });
820
976
  return;
821
977
  }
978
+ // --- Saved drafts (messages kept instead of sent) ----------------------
979
+ // Server-side on purpose: a draft saved on a phone must be there on the
980
+ // laptop, so the store is <config dir>/drafts.json, not browser storage.
981
+ // Behind the same token gate as the other API routes (via isApiRequest).
982
+ // Every mutation answers with the WHOLE new list, so the client never has to
983
+ // merge/cap/dedupe a list of its own: drafts.ts is the only writer.
984
+ if (pathname === '/drafts' && req.method === 'GET') {
985
+ try {
986
+ sendJSON(res, 200, { drafts: readDrafts() });
987
+ }
988
+ catch (err) {
989
+ // An unreadable/corrupt store is reported, never flattened to an empty
990
+ // list: the client would mirror that empty list over its offline copy.
991
+ sendJSON(res, 500, { error: err.message || 'Failed to read drafts' });
992
+ }
993
+ return;
994
+ }
995
+ if (pathname === '/drafts' && req.method === 'POST') {
996
+ let parsed;
997
+ try {
998
+ parsed = JSON.parse((await readBody(req)) || '{}');
999
+ }
1000
+ catch {
1001
+ sendJSON(res, 400, { error: 'Invalid request' });
1002
+ return;
1003
+ }
1004
+ const invalid = validateDraftInput(parsed);
1005
+ if (invalid) {
1006
+ // Rejected, not truncated: the composer clears itself once the server
1007
+ // has the draft, so a silently stored prefix would lose the tail.
1008
+ sendJSON(res, 400, { error: invalid });
1009
+ return;
1010
+ }
1011
+ try {
1012
+ const drafts = addDraft({
1013
+ text: parsed.text,
1014
+ sessionId: typeof parsed.sessionId === 'string' ? parsed.sessionId : undefined,
1015
+ cwd: typeof parsed.cwd === 'string' ? parsed.cwd : undefined,
1016
+ });
1017
+ sendJSON(res, 200, { drafts });
1018
+ }
1019
+ catch (err) {
1020
+ sendJSON(res, 500, { error: err.message || 'Failed to save draft' });
1021
+ }
1022
+ return;
1023
+ }
1024
+ // POST rather than DELETE, mirroring /session/delete: the same shape as the
1025
+ // rest of this API, and it survives proxies that drop the DELETE method.
1026
+ if (pathname === '/drafts/delete' && req.method === 'POST') {
1027
+ let parsed;
1028
+ try {
1029
+ parsed = JSON.parse((await readBody(req)) || '{}');
1030
+ }
1031
+ catch {
1032
+ sendJSON(res, 400, { error: 'Invalid request' });
1033
+ return;
1034
+ }
1035
+ const id = typeof parsed.id === 'string' ? parsed.id : '';
1036
+ if (!id) {
1037
+ sendJSON(res, 400, { error: 'Missing draft id' });
1038
+ return;
1039
+ }
1040
+ try {
1041
+ sendJSON(res, 200, { drafts: deleteDraft(id) });
1042
+ }
1043
+ catch (err) {
1044
+ sendJSON(res, 500, { error: err.message || 'Failed to delete draft' });
1045
+ }
1046
+ return;
1047
+ }
822
1048
  if (pathname === '/config' && req.method === 'GET') {
823
1049
  const config = getWhereverConfig();
824
1050
  let searchFolder = config.searchFolder;
@@ -1436,6 +1662,20 @@ async function main() {
1436
1662
  }
1437
1663
  }
1438
1664
  catch (err) {
1665
+ // Falling back to plaintext is only acceptable for material the server
1666
+ // chose for itself. When the operator EXPLICITLY pointed at a key and a
1667
+ // certificate, silently serving HTTP on the same (possibly 0.0.0.0)
1668
+ // address is the same fail-open ADR 0007 rules out for the token file:
1669
+ // it is the exact shape of a secret that has not been decrypted yet, and
1670
+ // clients would then send their token in cleartext to a server that looks
1671
+ // healthy. Refuse to start instead.
1672
+ if (tlsExplicitlyConfigured) {
1673
+ console.error(`FATAL: TLS was explicitly configured (key ${actualSslKey}, cert ${actualSslCert}) but ` +
1674
+ `could not be loaded: ${err.message}. Refusing to start: falling back to ` +
1675
+ `plaintext HTTP would silently expose traffic (and the auth token) on ${host}:${port}. ` +
1676
+ `Pass --no-ssl if plaintext is genuinely what you want.`);
1677
+ process.exit(1);
1678
+ }
1439
1679
  console.error(`Failed to load SSL certificates from ${actualSslKey} and ${actualSslCert}. Falling back to HTTP.`, err.message);
1440
1680
  server = createHttpServer(requestHandler);
1441
1681
  }
@@ -1615,8 +1855,24 @@ async function main() {
1615
1855
  wss.on('close', () => clearInterval(heartbeat));
1616
1856
  server.listen(port, host, () => {
1617
1857
  const protocol = isSecureServer ? 'https' : 'http';
1618
- const authInfo = token ? ' (token-protected)' : ' (no authentication)';
1858
+ // The SOURCE, never the token itself: this line goes to the journal, which
1859
+ // is readable by more people than the secret is.
1860
+ const authInfo = token ? ` (token-protected via ${tokenSource})` : ' (no authentication)';
1619
1861
  console.log(`\n🔐 Wherever Server: ${protocol}://${host}:${port}${authInfo}`);
1862
+ if (token && tokenSource === '--token') {
1863
+ console.warn('[wherever] the token came from the command line, which is visible to every user on this ' +
1864
+ 'machine via `ps`. For a real deployment set WHEREVER_TOKEN (or WHEREVER_TOKEN_FILE) instead.');
1865
+ }
1866
+ // Binding off-loopback with no token is a valid, long-supported choice (it
1867
+ // is how a trusted mesh/VPN setup runs), so it stays permitted. But it is
1868
+ // also exactly what a failed secret render looks like, and the two are
1869
+ // indistinguishable from the outside, so it must not slip by as one
1870
+ // parenthetical word in an otherwise cheerful startup line.
1871
+ if (!token && !isLoopbackHost(host)) {
1872
+ console.warn(`[wherever] WARNING: listening on ${host} with NO AUTHENTICATION. Anyone who can reach ` +
1873
+ `this address has full agent and filesystem access. If you meant to configure a token, ` +
1874
+ `it did not arrive: check WHEREVER_TOKEN / WHEREVER_TOKEN_FILE.`);
1875
+ }
1620
1876
  if (isSecureServer) {
1621
1877
  console.log(`
1622
1878
  👉 FIRST TIME CONNECTING?