shellpuppet 0.4.0 → 0.4.2

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 (44) hide show
  1. package/README.md +12 -1
  2. package/dist/cli/index.js +33 -13
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/client/http.d.ts +5 -0
  5. package/dist/client/http.js +8 -1
  6. package/dist/client/http.js.map +1 -1
  7. package/dist/client/input.d.ts +6 -0
  8. package/dist/client/input.js +14 -0
  9. package/dist/client/input.js.map +1 -0
  10. package/dist/core/mailbox.d.ts +18 -6
  11. package/dist/core/mailbox.js +35 -10
  12. package/dist/core/mailbox.js.map +1 -1
  13. package/dist/core/manager.d.ts +1 -2
  14. package/dist/core/manager.js +35 -16
  15. package/dist/core/manager.js.map +1 -1
  16. package/dist/core/session.d.ts +14 -0
  17. package/dist/core/session.js +16 -2
  18. package/dist/core/session.js.map +1 -1
  19. package/dist/core/types.d.ts +2 -0
  20. package/dist/core/types.js +2 -0
  21. package/dist/core/types.js.map +1 -1
  22. package/dist/daemon/audit.d.ts +7 -7
  23. package/dist/daemon/audit.js +19 -17
  24. package/dist/daemon/audit.js.map +1 -1
  25. package/dist/daemon/auth.d.ts +14 -13
  26. package/dist/daemon/auth.js +42 -25
  27. package/dist/daemon/auth.js.map +1 -1
  28. package/dist/daemon/config.d.ts +1 -1
  29. package/dist/daemon/config.js +1 -1
  30. package/dist/daemon/screenshot.d.ts +4 -2
  31. package/dist/daemon/screenshot.js +10 -1
  32. package/dist/daemon/screenshot.js.map +1 -1
  33. package/dist/daemon/server.d.ts +12 -15
  34. package/dist/daemon/server.js +204 -168
  35. package/dist/daemon/server.js.map +1 -1
  36. package/dist/mcp/tools.js +48 -31
  37. package/dist/mcp/tools.js.map +1 -1
  38. package/dist/viewer/dashboard.css +1 -1
  39. package/dist/viewer/dashboard.js +9 -3
  40. package/dist/viewer/index.html +1 -0
  41. package/dist/viewer/pane.js +118 -0
  42. package/dist/viewer/viewer.css +1 -1
  43. package/dist/viewer/viewer.js +1 -0
  44. package/package.json +1 -1
@@ -20,7 +20,7 @@ import { Mailbox, MailboxError, NAME_PATTERN, buildNudge } from '../core/mailbox
20
20
  import { buildMessagingPolicy, DEFAULT_NUDGE_INTERVAL_MS, DEFAULT_NUDGES_PER_MINUTE } from './config.js';
21
21
  import { NudgeScheduler } from './nudgeScheduler.js';
22
22
  import { ScheduleStore, PromptScheduler, watchSchedules } from './schedules.js';
23
- import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, } from '../core/session.js';
23
+ import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, submitOutcome, } from '../core/session.js';
24
24
  import { NativePtyUnavailableError } from '../core/nativePty.js';
25
25
  import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
26
26
  import { keyToBytes, knownKeys } from '../core/keys.js';
@@ -31,7 +31,7 @@ import { detectPrompt } from '../core/promptDetector.js';
31
31
  import { markFilteredSelectedOption } from '../core/selection.js';
32
32
  import { WaitConditionError } from '../core/waiter.js';
33
33
  import { agentNames, hideReasoning, latestResult, programName, signatureForSession } from '../core/reasoning.js';
34
- import { validResumeId, DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
34
+ import { validResumeId, DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_BODY_BYTES, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
35
35
  import { DASHBOARD_COOKIE, TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, dashboardCookie, dashboardProofFromProtocol, tokensEqual, viewerCookie, } from './auth.js';
36
36
  import { NULL_AUDITOR } from './audit.js';
37
37
  import { findBrowser, launchDashboard, launchViewer } from './viewerLauncher.js';
@@ -64,7 +64,6 @@ const STATE_PUBLISH_CHECK_MS = 10_000;
64
64
  * enough that a busy day of short-lived sessions does not ratchet memory.
65
65
  */
66
66
  const EXITED_SESSION_GRACE_MS = 15 * 60_000;
67
- const MAX_BODY_BYTES = 1_000_000;
68
67
  /**
69
68
  * Prompt-stall detection: how often live screens are scanned for a
70
69
  * permission prompt, and how long the SAME prompt must persist before an
@@ -204,6 +203,10 @@ const DASHBOARD_FONT_META = '<meta name="sp-dashboard-font-size" content="">';
204
203
  export { AlreadyRunningError };
205
204
  class HomeOwnershipError extends Error {
206
205
  }
206
+ class ClaimAuditError extends Error {
207
+ }
208
+ const CLAIM_RECOVERY_HINT = 'Claim the name again, using --replace if it is still held.';
209
+ const invalidClaim = { code: 'invalid-claim', hint: CLAIM_RECOVERY_HINT };
207
210
  /** The scheme and authority that open an absolute-form request target (`http://user@host:port`). */
208
211
  const SCHEME_AND_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i;
209
212
  /**
@@ -463,13 +466,11 @@ export class Daemon {
463
466
  promptScheduler;
464
467
  stopScheduleWatch;
465
468
  server;
469
+ /** Protocol accepted by dashboard authentication for this specific upgrade. */
470
+ dashboardUpgradeProtocols = new WeakMap();
466
471
  wss = new WebSocketServer({
467
472
  noServer: true,
468
- // Echo a subprotocol only when the dashboard credential opens the feed
469
- // or a session stream. A client token wins a session stream, so that
470
- // upgrade selects none even if the cookie and a live proof are also
471
- // offered. Returning false leaves the upgrade with none selected.
472
- handleProtocols: (protocols, request) => this.dashboardProtocol(protocols, request),
473
+ handleProtocols: (_protocols, request) => this.dashboardUpgradeProtocols.get(request) ?? false,
473
474
  });
474
475
  sockets = new Set();
475
476
  /** Every watcher of a session, with the gate that orders its stream across snapshots. */
@@ -511,8 +512,8 @@ export class Daemon {
511
512
  dashboardWindowIds = new Map();
512
513
  dashboardAssignments = new Map();
513
514
  dashboardDesignated = null;
514
- /** The document proof survives a feed reconnect and expires with the proof ring. */
515
- dashboardDocumentFocus = new Map();
515
+ /** Remember focus across reconnects for the lifetime of the document proof. */
516
+ dashboardDocumentFocus = new WeakMap();
516
517
  liveDashboardEventSockets = new Set();
517
518
  /** A launched dashboard has 30 seconds to connect before a start may retry. */
518
519
  dashboardWindowStartedAt = 0;
@@ -561,6 +562,7 @@ export class Daemon {
561
562
  compiledPolicy;
562
563
  /** Accepted launch times, for the sliding sixty-second cap. */
563
564
  launchTimes = [];
565
+ pendingProfileStarts = new Set();
564
566
  claimTimes = [];
565
567
  claimCount = 0;
566
568
  folderPickerBusy = false;
@@ -583,6 +585,7 @@ export class Daemon {
583
585
  const auditor = options.audit ?? NULL_AUDITOR;
584
586
  this.audit = {
585
587
  captureContent: auditor.captureContent,
588
+ recordRequired: auditor.recordRequired?.bind(auditor),
586
589
  record: (actor, action, session, meta) => auditor.record(actor, action, session, meta,
587
590
  // A session's timers and listeners can inherit the request that created
588
591
  // them. Daemon observations must not inherit that caller's identity.
@@ -1283,7 +1286,7 @@ export class Daemon {
1283
1286
  if (grantPresented) {
1284
1287
  const redeemed = this.tokens.redeemDashboardGrant(grant, this.now());
1285
1288
  if (redeemed !== null) {
1286
- this.retireDashboardFeeds();
1289
+ this.retireDashboardSockets();
1287
1290
  this.audit.record('dashboard', 'grant-redeem');
1288
1291
  res.writeHead(303, {
1289
1292
  location: '/dashboard',
@@ -1297,8 +1300,13 @@ export class Daemon {
1297
1300
  return;
1298
1301
  }
1299
1302
  const proof = cookie === null ? null : this.tokens.issueDashboardProof();
1300
- if (proof !== null)
1301
- this.retireDashboardFeeds();
1303
+ if (cookie !== null && proof === null) {
1304
+ this.auditDashboardRefusal(req, 'limit');
1305
+ res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8',
1306
+ 'cache-control': 'no-store', 'content-security-policy': PAGE_CSP });
1307
+ res.end('Too many dashboard windows are open. Close one and reload this page.');
1308
+ return;
1309
+ }
1302
1310
  this.sendDashboardPage(res, proof, req.method === 'HEAD');
1303
1311
  return;
1304
1312
  }
@@ -1334,7 +1342,7 @@ export class Daemon {
1334
1342
  this.pendingDashboardGrants.delete(grant);
1335
1343
  if (this.stopping || !opened.launched || opened.mode === 'default-browser') {
1336
1344
  this.tokens.revokeDashboardGrant(grant);
1337
- this.retireDashboardFeeds();
1345
+ this.retireDashboardSockets();
1338
1346
  this.auditDashboardRefusal(req, 'launch-failed');
1339
1347
  return false;
1340
1348
  }
@@ -1793,7 +1801,9 @@ export class Daemon {
1793
1801
  }
1794
1802
  }
1795
1803
  const requestedWindow = body['window'];
1796
- const launchingWindow = requestedWindow === undefined ? undefined : this.dashboardWindows().find((window) => window.pair === requestedWindow && dashboardProofFromProtocol(window.socket.protocol) === documentProof);
1804
+ const launchingWindow = requestedWindow === undefined || documentProof === undefined ? undefined
1805
+ : this.dashboardWindows().find(window => window.pair === requestedWindow &&
1806
+ tokensEqual(window.socket.protocol, `sp-csrf.${documentProof}`));
1797
1807
  if (requestedWindow !== undefined && launchingWindow === undefined) {
1798
1808
  json(res, 409, { error: 'The launching dashboard window has closed.' });
1799
1809
  return;
@@ -1963,13 +1973,18 @@ export class Daemon {
1963
1973
  json(res, 503, { error: 'The daemon is stopping.' });
1964
1974
  return;
1965
1975
  }
1966
- if (launcher && this.grantedLauncher(req)?.id !== launcher.id) {
1967
- json(res, 403, { error: 'Session launch permission required.' });
1968
- return;
1976
+ if (launcher) {
1977
+ const current = this.grantedLauncher(req, res);
1978
+ if (!current)
1979
+ return;
1980
+ if (current.id !== launcher.id) {
1981
+ json(res, 403, { error: 'Session launch permission required.' });
1982
+ return;
1983
+ }
1969
1984
  }
1970
1985
  const now = this.now();
1971
1986
  this.pruneLaunchTimes(now);
1972
- if (this.launchTimes.length >= 8) {
1987
+ if (this.launchTimes.length + this.pendingProfileStarts.size >= 8) {
1973
1988
  this.auditDashboardRefusal(req, 'rate', launcher?.name);
1974
1989
  json(res, 429, {
1975
1990
  error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
@@ -2022,18 +2037,20 @@ export class Daemon {
2022
2037
  json(res, 500, { error: `Failed to start session: ${String(error)}` });
2023
2038
  return;
2024
2039
  }
2025
- // Counted the moment the launch is accepted, before the start contract's
2026
- // wait: the rate check above and this record must sit in the same
2027
- // synchronous stretch, or twelve launches fired together would all pass
2028
- // the check before any of them was counted.
2029
- this.launchTimes.push(now);
2030
- // The same start contract as `POST /sessions`: the dashboard's pane is a
2031
- // session only once its program exists, and a start that ends before any
2032
- // program did fails as 1.1.0's spawn did, leaving nothing in the grid.
2033
- const startedSession = await this.programStarted(session, options, res, 'dashboard session start failed');
2034
- if (startedSession === null)
2035
- return;
2036
- session = startedSession;
2040
+ // Reserve before yielding. Only a confirmed program starts its rolling minute.
2041
+ const reserved = session;
2042
+ this.pendingProfileStarts.add(reserved);
2043
+ const releaseReservation = () => { this.pendingProfileStarts.delete(reserved); };
2044
+ try {
2045
+ const started = await this.programStarted(session, options, res, 'dashboard session start failed', releaseReservation);
2046
+ if (started === null)
2047
+ return;
2048
+ session = started;
2049
+ this.launchTimes.push(this.now());
2050
+ }
2051
+ finally {
2052
+ releaseReservation();
2053
+ }
2037
2054
  // A launch is an API call: the idle timer counts from it, so a session
2038
2055
  // that has just started is not reaped sooner than `idleMinutes` allows.
2039
2056
  this.lastActivity = Date.now();
@@ -2207,9 +2224,7 @@ export class Daemon {
2207
2224
  json(res, 200, { id, name: body['name'], label: session.label });
2208
2225
  }
2209
2226
  /**
2210
- * Authenticate the dashboard event feed and retain its issuing credential.
2211
- * The client token on the query is not a way in. The proof is the
2212
- * subprotocol, not `X-ShellPuppet-CSRF`.
2227
+ * Authenticate a dashboard upgrade and select the offered protocol that proved it.
2213
2228
  */
2214
2229
  dashboardUpgradeCredential(req) {
2215
2230
  const token = this.dashboardCookieToken(req.headers.cookie);
@@ -2228,46 +2243,10 @@ export class Daemon {
2228
2243
  (site === undefined && mode === undefined))) {
2229
2244
  return { code: 403, reason: 'Forbidden', audit: 'fetch-site' };
2230
2245
  }
2231
- const accepted = offeredProtocols(req).some((protocol) => {
2232
- const proof = dashboardProofFromProtocol(protocol);
2233
- return proof !== null && this.tokens.acceptsDashboardProof(proof);
2234
- });
2235
- if (!accepted)
2246
+ const protocol = offeredProtocols(req).find(offer => this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(offer)));
2247
+ if (protocol === undefined)
2236
2248
  return { code: 403, reason: 'Forbidden', audit: 'proof' };
2237
- return token;
2238
- }
2239
- /**
2240
- * Select `sp-csrf.<proof>` when this upgrade's credential is the dashboard
2241
- * cookie: the dashboard feed, or a session stream the client token did not
2242
- * take. The echo names that credential. A viewer or client socket, including
2243
- * a client token that also carries the cookie and offers a live proof,
2244
- * selects none. Returning false leaves the upgrade with none selected.
2245
- */
2246
- dashboardProtocol(protocols, request) {
2247
- let url;
2248
- try {
2249
- url = new URL(request.url ?? '/', 'http://127.0.0.1');
2250
- }
2251
- catch {
2252
- return false;
2253
- }
2254
- const segments = url.pathname.split('/').filter((part) => part !== '');
2255
- const sessionStream = segments.length === 3 && segments[0] === 'sessions' && segments[2] === 'stream';
2256
- if (url.pathname !== '/dashboard/events' && !sessionStream)
2257
- return false;
2258
- // Same preference as sessionStreamDecision: a live client token opens a
2259
- // client socket, so the echoed protocol must not say this is the dashboard.
2260
- if (sessionStream && this.tokens.verify(url.searchParams.get('token'))?.kind === 'client') {
2261
- return false;
2262
- }
2263
- if (this.dashboardCookieToken(request.headers.cookie) === null)
2264
- return false;
2265
- for (const protocol of protocols) {
2266
- const proof = dashboardProofFromProtocol(protocol);
2267
- if (proof !== null && this.tokens.acceptsDashboardProof(proof))
2268
- return protocol;
2269
- }
2270
- return false;
2249
+ return { kind: 'dashboard', readOnly: false, dashboardToken: token, protocol };
2271
2250
  }
2272
2251
  /**
2273
2252
  * Who may open `/sessions/<id>/stream`, or why not.
@@ -2278,9 +2257,9 @@ export class Daemon {
2278
2257
  * upgrade's rules: a live `sp-csrf` subprotocol, a matching Origin, and
2279
2258
  * same-origin Fetch Metadata. A header is not the proof. A viewer cookie,
2280
2259
  * including a read-only one, is never treated as the dashboard credential.
2281
- * When both are present and the proof is live, the dashboard cookie is the
2260
+ * When both are present and the dashboard checks pass, the dashboard cookie is the
2282
2261
  * one that opens the socket, so a read-only viewer cookie in the same jar
2283
- * does not mask it. When the proof is missing, a viewer cookie for this
2262
+ * does not mask it. When the dashboard checks fail, a viewer cookie for this
2284
2263
  * session still opens the socket on its own rules.
2285
2264
  */
2286
2265
  sessionStreamDecision(req, url, sessionId) {
@@ -2292,9 +2271,8 @@ export class Daemon {
2292
2271
  return { ok: true, credential: { kind: 'client', readOnly: false } };
2293
2272
  }
2294
2273
  const dashboard = this.dashboardUpgradeCredential(req);
2295
- if (typeof dashboard === 'string') {
2296
- return { ok: true, credential: { kind: 'dashboard', readOnly: false,
2297
- dashboardToken: dashboard } };
2274
+ if ('kind' in dashboard) {
2275
+ return { ok: true, credential: dashboard };
2298
2276
  }
2299
2277
  const viewer = cookieValues(req.headers.cookie, VIEWER_COOKIE)
2300
2278
  .map((value) => ({ value, credential: this.tokens.verifyStreamToken(value) }))
@@ -2554,7 +2532,7 @@ export class Daemon {
2554
2532
  });
2555
2533
  writePrivateRecord(path.join(this.options.home, 'previous-sessions.json'), { version: 1, outgoingInstanceId: this.instanceId, sessions });
2556
2534
  }
2557
- saveLauncherClaims(excludeId) {
2535
+ saveLauncherClaims(excludeId, next, beforePublish) {
2558
2536
  const grants = this.launchProfiles.sessionLaunch ?? [];
2559
2537
  const file = path.join(this.options.home, 'launcher-claims.json');
2560
2538
  if (!this.claimsRestored)
@@ -2562,25 +2540,57 @@ export class Daemon {
2562
2540
  if (grants.length || fs.existsSync(file)) {
2563
2541
  let discovery = this.requireHomeOwner();
2564
2542
  const claims = this.mailbox.savedClaims(grants).filter(claim => claim.id !== excludeId);
2565
- writePrivateRecord(file, claims, () => { discovery = this.requireHomeOwner(); });
2543
+ if (next)
2544
+ claims.push(next);
2545
+ writePrivateRecord(file, claims, () => {
2546
+ beforePublish?.();
2547
+ discovery = this.requireHomeOwner();
2548
+ });
2566
2549
  if (!this.stopping && (discovery.kind === 'missing' || discovery.kind === 'not-a-record')) {
2567
2550
  void this.keepStatePublished();
2568
2551
  }
2569
2552
  }
2570
2553
  }
2571
- grantedLauncher(req) {
2554
+ auditReplacement(actor, oldClaimId, next) {
2555
+ const failure = 'Could not write the audit record for the claim replacement.';
2556
+ if (!this.audit.recordRequired)
2557
+ throw new ClaimAuditError(failure);
2558
+ try {
2559
+ this.audit.recordRequired(actor, 'msg-replace', next.id, {
2560
+ name: next.name, oldClaimId, newClaimId: next.id, member: this.isReservedClaimName(next.name),
2561
+ });
2562
+ }
2563
+ catch {
2564
+ throw new ClaimAuditError(failure);
2565
+ }
2566
+ }
2567
+ presentedClaim(req, allowMarked = true) {
2568
+ const id = req.headers['x-shellpuppet-claim'];
2569
+ const secret = req.headers['x-shellpuppet-claim-secret'];
2570
+ if (id === undefined && secret === undefined)
2571
+ return {};
2572
+ const marked = req.headers['x-shellpuppet-inside-session'] === '1';
2573
+ if ((!marked || allowMarked) && typeof id === 'string' && typeof secret === 'string' &&
2574
+ this.mailbox.verifyClaim(id, secret, !marked))
2575
+ return { id };
2576
+ return { refused: true };
2577
+ }
2578
+ grantedLauncher(req, res) {
2572
2579
  this.lapseIdleClaims();
2573
2580
  let id = this.callerContext.getStore();
2574
2581
  if (id === undefined) {
2575
- const claim = headerOne(req, 'x-shellpuppet-claim');
2576
- const secret = headerOne(req, 'x-shellpuppet-claim-secret');
2577
- if (req.headers['x-shellpuppet-inside-session'] === '1' || !claim || !secret ||
2578
- !this.mailbox.verifyClaim(claim, secret))
2582
+ const claim = this.presentedClaim(req, false);
2583
+ if (claim.refused) {
2584
+ json(res, 403, { error: 'Session launch permission required.', ...invalidClaim });
2579
2585
  return undefined;
2580
- id = claim;
2586
+ }
2587
+ id = claim.id;
2581
2588
  }
2582
- const caller = this.mailbox.participant(id);
2583
- return caller && this.launchProfiles.sessionLaunch?.includes(caller.name) ? caller : undefined;
2589
+ const caller = id === undefined ? undefined : this.mailbox.participant(id);
2590
+ if (caller && this.launchProfiles.sessionLaunch?.includes(caller.name))
2591
+ return caller;
2592
+ json(res, 403, { error: 'Session launch permission required.' });
2593
+ return undefined;
2584
2594
  }
2585
2595
  messageAudit(action, entry, actor = 'daemon') {
2586
2596
  this.audit.record(actor, action, entry.from.id, {
@@ -2601,6 +2611,9 @@ export class Daemon {
2601
2611
  }
2602
2612
  }
2603
2613
  this.mailbox.end(id);
2614
+ this.closeParticipantSockets(id);
2615
+ }
2616
+ closeParticipantSockets(id) {
2604
2617
  for (const [ws, participant] of this.eventSockets) {
2605
2618
  if (participant === id)
2606
2619
  ws.close();
@@ -2841,18 +2854,14 @@ export class Daemon {
2841
2854
  return;
2842
2855
  }
2843
2856
  this.lapseIdleClaims();
2844
- const claimId = req.headers['x-shellpuppet-claim'];
2845
- const claimSecret = req.headers['x-shellpuppet-claim-secret'];
2846
- const claimPresented = claimId !== undefined || claimSecret !== undefined;
2847
- const claimValid = typeof claimId === 'string' && typeof claimSecret === 'string' &&
2848
- this.mailbox.verifyClaim(claimId, claimSecret);
2849
2857
  const route = segments[1];
2850
2858
  const creatingClaim = req.method === 'POST' && route === 'claims' && segments.length === 2;
2851
- if (claimPresented && !claimValid && !creatingClaim) {
2852
- json(res, 403, { error: 'Messaging claim was not recognised.' });
2859
+ const { id: claimId, refused } = this.presentedClaim(req);
2860
+ if (refused && !creatingClaim) {
2861
+ json(res, 403, { error: 'Messaging claim was not recognised.', ...invalidClaim });
2853
2862
  return;
2854
2863
  }
2855
- const caller = this.callerContext.getStore() ?? (claimValid ? claimId : undefined);
2864
+ const caller = this.callerContext.getStore() ?? claimId;
2856
2865
  if (creatingClaim) {
2857
2866
  // Each refusal says only what the daemon knows: a verified session, a valid claim, a mark on the request.
2858
2867
  if (this.callerContext.getStore() !== undefined) {
@@ -2860,9 +2869,9 @@ export class Daemon {
2860
2869
  return;
2861
2870
  }
2862
2871
  const marked = req.headers['x-shellpuppet-inside-session'] === '1';
2863
- if (claimValid || marked) {
2872
+ if (claimId !== undefined || marked) {
2864
2873
  const reasons = [];
2865
- if (claimValid) {
2874
+ if (claimId !== undefined) {
2866
2875
  reasons.push('This client already holds a messaging claim: release it first (msg release), or stop ' +
2867
2876
  'presenting it (SHELLPUPPET_CLAIM), to make another.');
2868
2877
  }
@@ -2876,10 +2885,18 @@ export class Daemon {
2876
2885
  return;
2877
2886
  }
2878
2887
  const body = await readBody(req);
2879
- if (typeof body['name'] !== 'string') {
2888
+ const name = body['name'];
2889
+ const replace = body['replace'] === true;
2890
+ if (typeof name !== 'string') {
2880
2891
  json(res, 400, { error: 'A valid name is required.' });
2881
2892
  return;
2882
2893
  }
2894
+ if (body['replace'] !== undefined && typeof body['replace'] !== 'boolean') {
2895
+ json(res, 400, { error: 'replace must be a boolean.' });
2896
+ return;
2897
+ }
2898
+ if (replace)
2899
+ this.lapseIdleClaims();
2883
2900
  const now = this.now();
2884
2901
  while (this.claimTimes.length > 0 && (this.claimTimes[0] ?? now) <= now - 60_000)
2885
2902
  this.claimTimes.shift();
@@ -2891,35 +2908,38 @@ export class Daemon {
2891
2908
  json(res, 429, { error: 'Messaging claim rate reached (8 in 60 seconds).' });
2892
2909
  return;
2893
2910
  }
2894
- const claim = this.mailbox.claim(body['name']);
2895
- this.claimTimes.push(now);
2896
- this.claimCount++;
2897
- if (this.launchProfiles.sessionLaunch?.includes(body['name'])) {
2898
- try {
2899
- this.saveLauncherClaims();
2900
- }
2901
- catch (error) {
2902
- this.mailbox.release(claim.claimId);
2903
- this.claimCount--;
2904
- throw error;
2905
- }
2906
- }
2907
- this.audit.record(actor, 'msg-claim', claim.claimId, {
2908
- fromId: claim.claimId, fromName: body['name'], toId: null, toName: null,
2909
- messageId: null, length: 0, member: this.isReservedClaimName(body['name']),
2911
+ const { claimId: newId, secret, previousId } = this.mailbox.claim(name, {
2912
+ replace,
2913
+ beforeCommit: (next, oldId) => {
2914
+ this.claimTimes.push(now);
2915
+ const audit = oldId === undefined ? undefined : () => this.auditReplacement(actor, oldId, next);
2916
+ if (this.launchProfiles.sessionLaunch?.includes(name))
2917
+ this.saveLauncherClaims(oldId, next, audit);
2918
+ else
2919
+ audit?.();
2920
+ },
2910
2921
  });
2911
- json(res, 201, claim);
2922
+ if (previousId !== undefined) {
2923
+ this.closeParticipantSockets(previousId);
2924
+ }
2925
+ else {
2926
+ this.claimCount++;
2927
+ this.audit.record(actor, 'msg-claim', newId, {
2928
+ fromId: newId, fromName: name, toId: null, toName: null,
2929
+ messageId: null, length: 0, member: this.isReservedClaimName(name),
2930
+ });
2931
+ }
2932
+ json(res, 201, { claimId: newId, secret });
2912
2933
  return;
2913
2934
  }
2914
2935
  if (caller === undefined) {
2915
2936
  json(res, 403, { error: 'Not a messaging participant.' });
2916
2937
  return;
2917
2938
  }
2918
- if (claimValid)
2919
- this.mailbox.touchClaim(claimId);
2920
2939
  if (req.method === 'DELETE' && route === 'claims' && segments.length === 3) {
2921
- if (!claimValid || claimId !== segments[2]) {
2922
- json(res, 403, { error: 'The matching claim is required.' });
2940
+ if (claimId === undefined || claimId !== segments[2]) {
2941
+ json(res, 403, { error: 'The matching claim is required.',
2942
+ ...(claimId === undefined ? {} : { hint: CLAIM_RECOVERY_HINT }) });
2923
2943
  return;
2924
2944
  }
2925
2945
  const name = this.mailbox.participant(claimId)?.name;
@@ -2993,7 +3013,7 @@ export class Daemon {
2993
3013
  finally {
2994
3014
  res.off('close', onClose);
2995
3015
  }
2996
- if (claimValid)
3016
+ if (claimId !== undefined && req.headers['x-shellpuppet-inside-session'] !== '1')
2997
3017
  this.mailbox.touchClaim(claimId);
2998
3018
  return;
2999
3019
  }
@@ -3055,10 +3075,8 @@ export class Daemon {
3055
3075
  return;
3056
3076
  }
3057
3077
  if (url.pathname === '/launcher/previous' && req.method === 'GET') {
3058
- if (!this.grantedLauncher(req)) {
3059
- json(res, 403, { error: 'Session launch permission required.' });
3078
+ if (!this.grantedLauncher(req, res))
3060
3079
  return;
3061
- }
3062
3080
  const file = path.join(this.options.home, 'previous-sessions.json');
3063
3081
  try {
3064
3082
  // Older version 1 records used the generated session id as an explicit name.
@@ -3079,11 +3097,9 @@ export class Daemon {
3079
3097
  return;
3080
3098
  }
3081
3099
  if (url.pathname === '/launcher/launch' && req.method === 'POST') {
3082
- const caller = this.grantedLauncher(req);
3083
- if (!caller) {
3084
- json(res, 403, { error: 'Session launch permission required.' });
3100
+ const caller = this.grantedLauncher(req, res);
3101
+ if (!caller)
3085
3102
  return;
3086
- }
3087
3103
  if ((headerOne(req, 'content-type') ?? '').split(';')[0]?.trim().toLowerCase() !== 'application/json') {
3088
3104
  json(res, 415, { error: 'The launch body must be JSON.' });
3089
3105
  return;
@@ -3484,6 +3500,7 @@ export class Daemon {
3484
3500
  // caller's request for a race in the session's lifetime. A session
3485
3501
  // whose input pipe has failed refuses the write too, and its error
3486
3502
  // says what to do.
3503
+ const submit = body['submit'] === true;
3487
3504
  let written;
3488
3505
  try {
3489
3506
  written = await session.writeWithResult(data);
@@ -3496,12 +3513,9 @@ export class Daemon {
3496
3513
  });
3497
3514
  return;
3498
3515
  }
3499
- // §4.5: content NEVER logged by default, only the length. Keystrokes
3500
- // are where the secrets are.
3501
- this.audit.record(actor, 'input', id, {
3502
- chars: data.length,
3503
- ...(this.audit.captureContent ? { data } : {}),
3504
- });
3516
+ const reporting = submit ? submitOutcome(written) : undefined;
3517
+ this.audit.record(actor, 'input', id, { chars: data.length,
3518
+ ...(reporting ? { submit: true, ...reporting } : {}) });
3505
3519
  this.broadcastControl(id, { type: 'input-source', source: 'agent' });
3506
3520
  // §3.1: TUIs silently swallow input while loading or when a panel has
3507
3521
  // stolen focus. verify re-reads the screen and reports whether the
@@ -3511,6 +3525,7 @@ export class Daemon {
3511
3525
  json(res, 200, {
3512
3526
  ok: true,
3513
3527
  bytes: data.length,
3528
+ ...reporting,
3514
3529
  verified: await this.verifyTyped(session, data, written.before),
3515
3530
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3516
3531
  ...(written.submitRetried ? { submitRetried: true } : {}),
@@ -3519,6 +3534,7 @@ export class Daemon {
3519
3534
  return;
3520
3535
  }
3521
3536
  json(res, 200, { ok: true, bytes: data.length,
3537
+ ...reporting,
3522
3538
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3523
3539
  ...(written.submitRetried ? { submitRetried: true } : {}),
3524
3540
  ...(written.message !== undefined ? { message: written.message } : {}),
@@ -3785,6 +3801,10 @@ export class Daemon {
3785
3801
  json(res, 409, { error: error.message });
3786
3802
  return;
3787
3803
  }
3804
+ if (error instanceof ClaimAuditError) {
3805
+ json(res, 503, { error: error.message });
3806
+ return;
3807
+ }
3788
3808
  if (error instanceof MailboxError) {
3789
3809
  const status = error.code === 'unknown-name' ? 404 :
3790
3810
  error.code === 'not-allowed' || error.code === 'unknown-sender' ? 403 :
@@ -3801,7 +3821,7 @@ export class Daemon {
3801
3821
  'text-too-large': 'A message exceeds the 16 KiB limit.',
3802
3822
  'mailbox-full': 'The mailbox is full.',
3803
3823
  };
3804
- json(res, status, { error: messages[error.code] });
3824
+ json(res, status, { error: messages[error.code], hint: error.hint });
3805
3825
  return;
3806
3826
  }
3807
3827
  if (error instanceof WaitConditionError) {
@@ -4180,11 +4200,11 @@ export class Daemon {
4180
4200
  * is returned with the response already sent. Only the proven ConPTY worker
4181
4201
  * timeout gets one replacement attempt under the same id.
4182
4202
  */
4183
- async programStarted(session, options, res, logMessage) {
4203
+ async programStarted(session, options, res, logMessage, onTerminalFailure) {
4184
4204
  this.startingIds.add(session.id);
4185
4205
  try {
4186
4206
  if (this.manager.get(session.id) === session)
4187
- return await this.manager.finishStart(session, options);
4207
+ return await this.manager.finishStart(session, options, onTerminalFailure);
4188
4208
  // Test-only dashboard factories may supply a session outside the manager.
4189
4209
  if (await session.startedProgramPid() !== null)
4190
4210
  return session;
@@ -4501,8 +4521,9 @@ export class Daemon {
4501
4521
  // refusal never reaches. An error with no listener would be an uncaught
4502
4522
  // exception, on which the daemon shuts down with every session.
4503
4523
  socket.on('error', () => socket.destroy());
4504
- const reject = (code, reason) => {
4505
- socket.write(`HTTP/1.1 ${String(code)} ${reason}\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n`);
4524
+ const reject = (code, reason, hint) => {
4525
+ const headers = hint ? `X-ShellPuppet-Hint: ${hint}\r\n` : '';
4526
+ socket.write(`HTTP/1.1 ${String(code)} ${reason}\r\n${headers}Referrer-Policy: no-referrer\r\nConnection: close\r\n\r\n`);
4506
4527
  socket.destroy();
4507
4528
  };
4508
4529
  if (!this.hostAllowed(req.headers.host)) {
@@ -4537,15 +4558,16 @@ export class Daemon {
4537
4558
  const segments = url.pathname.split('/').filter((s) => s !== '');
4538
4559
  // The dashboard feed is cookie-only. Its Origin rule is stricter than the
4539
4560
  // client-token sockets below, which still allow a missing Origin.
4540
- if (segments[0] === 'dashboard' && segments[1] === 'events' && segments.length === 2) {
4561
+ if (url.pathname === '/dashboard/events') {
4541
4562
  const credential = this.dashboardUpgradeCredential(req);
4542
- if (typeof credential !== 'string') {
4563
+ if ('code' in credential) {
4543
4564
  this.auditDashboardRefusal(req, credential.audit);
4544
4565
  reject(credential.code, credential.reason);
4545
4566
  return;
4546
4567
  }
4568
+ this.dashboardUpgradeProtocols.set(req, credential.protocol);
4547
4569
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4548
- this.attachDashboardSocket(ws, credential);
4570
+ this.attachDashboardSocket(ws, credential.dashboardToken);
4549
4571
  });
4550
4572
  return;
4551
4573
  }
@@ -4565,22 +4587,20 @@ export class Daemon {
4565
4587
  reject(403, 'Forbidden');
4566
4588
  return;
4567
4589
  }
4568
- const claimId = req.headers['x-shellpuppet-claim'];
4569
- const claimSecret = req.headers['x-shellpuppet-claim-secret'];
4570
- const claimPresented = claimId !== undefined || claimSecret !== undefined;
4571
- if (claimPresented)
4590
+ if (req.headers['x-shellpuppet-claim'] !== undefined || req.headers['x-shellpuppet-claim-secret'] !== undefined) {
4572
4591
  this.lapseIdleClaims();
4573
- if (claimPresented && (typeof claimId !== 'string' || typeof claimSecret !== 'string' ||
4574
- !this.mailbox.verifyClaim(claimId, claimSecret))) {
4575
- reject(403, 'Forbidden');
4592
+ }
4593
+ const claim = this.presentedClaim(req);
4594
+ if (claim.refused) {
4595
+ reject(403, 'Forbidden', CLAIM_RECOVERY_HINT);
4576
4596
  return;
4577
4597
  }
4578
4598
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4579
- this.callerContext.run(caller.session, () => this.attachEventSocket(ws, caller.session ?? (typeof claimId === 'string' ? claimId : undefined)));
4599
+ this.callerContext.run(caller.session, () => this.attachEventSocket(ws, caller.session ?? claim.id));
4580
4600
  });
4581
4601
  return;
4582
4602
  }
4583
- if (segments[0] !== 'sessions' || segments[2] !== 'stream') {
4603
+ if (segments.length !== 3 || segments[0] !== 'sessions' || segments[2] !== 'stream') {
4584
4604
  reject(404, 'Not Found');
4585
4605
  return;
4586
4606
  }
@@ -4619,6 +4639,9 @@ export class Daemon {
4619
4639
  // dashboard credential is made passive in attachSocket, whatever the
4620
4640
  // query says, so this flag cannot turn that socket into a driver.
4621
4641
  const passive = passiveDrive(url);
4642
+ if (decision.credential.kind === 'dashboard') {
4643
+ this.dashboardUpgradeProtocols.set(req, decision.credential.protocol);
4644
+ }
4622
4645
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4623
4646
  // Which credential opened the socket travels with it, so the audit log
4624
4647
  // names that credential rather than assuming a browser: `client` for
@@ -4669,7 +4692,9 @@ export class Daemon {
4669
4692
  for (const [id, previous] of this.dashboardTransferable) {
4670
4693
  const owner = windows.find(w => this.dashboardAssignments.get(w.pair)?.includes(id));
4671
4694
  const recipient = owner?.socket.protocol;
4672
- if (recipient === previous || (previous === null && windows.length === 0))
4695
+ const unchanged = recipient === undefined ? previous === undefined
4696
+ : typeof previous === 'string' && tokensEqual(previous, recipient);
4697
+ if (unchanged || (previous === null && windows.length === 0))
4673
4698
  continue;
4674
4699
  this.dashboardTransferable.set(id, recipient);
4675
4700
  const session = this.manager.get(id);
@@ -4717,14 +4742,11 @@ export class Daemon {
4717
4742
  return this.tokens.verifyDashboardToken(this.dashboardSocketCredential.get(ws)) &&
4718
4743
  this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(ws.protocol));
4719
4744
  }
4720
- retireDashboardFeeds() {
4721
- for (const protocol of this.dashboardDocumentFocus.keys()) {
4722
- if (!this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(protocol)))
4723
- this.dashboardDocumentFocus.delete(protocol);
4724
- }
4745
+ retireDashboardSockets() {
4725
4746
  let changed = false;
4726
- for (const ws of this.dashboardEventSockets) {
4727
- if (ws.readyState === ws.OPEN && !this.dashboardFeedCurrent(ws)) {
4747
+ for (const ws of this.sockets) {
4748
+ const credential = this.dashboardSocketCredential.get(ws);
4749
+ if (credential !== undefined && ws.readyState === ws.OPEN && !this.tokens.verifyDashboardToken(credential)) {
4728
4750
  if (this.dashboardWindowIds.delete(ws))
4729
4751
  changed = true;
4730
4752
  this.liveDashboardEventSockets.delete(ws);
@@ -4734,8 +4756,20 @@ export class Daemon {
4734
4756
  if (changed)
4735
4757
  this.publishDashboardWindows();
4736
4758
  }
4737
- attachDashboardSocket(ws, credential) {
4759
+ retainSocketProof(ws, credential) {
4760
+ const proof = this.tokens.retainDashboardProof(dashboardProofFromProtocol(ws.protocol));
4761
+ if (proof === undefined) {
4762
+ ws.close(1008, 'Dashboard access expired');
4763
+ return undefined;
4764
+ }
4738
4765
  this.dashboardSocketCredential.set(ws, credential);
4766
+ ws.once('close', () => this.tokens.releaseDashboardProof(proof));
4767
+ return proof;
4768
+ }
4769
+ attachDashboardSocket(ws, credential) {
4770
+ const proof = this.retainSocketProof(ws, credential);
4771
+ if (proof === undefined)
4772
+ return;
4739
4773
  this.sockets.add(ws);
4740
4774
  this.dashboardEventSockets.add(ws);
4741
4775
  this.liveDashboardEventSockets.add(ws);
@@ -4790,7 +4824,7 @@ export class Daemon {
4790
4824
  if (claim.type === 'window-focus') {
4791
4825
  const at = claim.focusedAt === undefined ? performance.timeOrigin + performance.now() : claim.focusedAt;
4792
4826
  current.focused = Math.max(current.focused, this.dashboardFocusTime(at));
4793
- this.dashboardDocumentFocus.set(ws.protocol, { id: current.id, focused: current.focused });
4827
+ this.dashboardDocumentFocus.set(proof, { id: current.id, focused: current.focused });
4794
4828
  this.publishDashboardWindows();
4795
4829
  }
4796
4830
  else if (claim.type === 'window-designate') {
@@ -4824,10 +4858,10 @@ export class Daemon {
4824
4858
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.instance) ||
4825
4859
  claim.instance.length > 100)
4826
4860
  return;
4827
- const previous = this.dashboardDocumentFocus.get(ws.protocol);
4861
+ const previous = this.dashboardDocumentFocus.get(proof);
4828
4862
  const focused = Math.max(previous?.id === claim.id ? previous.focused : 0, this.dashboardFocusTime(claim.focusedAt));
4829
4863
  this.dashboardWindowIds.set(ws, { id: claim.id, instance: claim.instance, focused });
4830
- this.dashboardDocumentFocus.set(ws.protocol, { id: claim.id, focused });
4864
+ this.dashboardDocumentFocus.set(proof, { id: claim.id, focused });
4831
4865
  this.publishDashboardWindows();
4832
4866
  });
4833
4867
  ws.on('close', () => {
@@ -4893,7 +4927,7 @@ export class Daemon {
4893
4927
  }
4894
4928
  gridOfferedTo(id, ws) {
4895
4929
  const recipient = this.dashboardTransferable.get(id);
4896
- return (recipient === null || recipient === ws.protocol) &&
4930
+ return (recipient === null || (recipient !== undefined && tokensEqual(recipient, ws.protocol))) &&
4897
4931
  this.dashboardCredentialOwner.has(id) && this.dashboardSocketCredential.has(ws) &&
4898
4932
  tokensEqual(this.dashboardCredentialOwner.get(id), this.dashboardSocketCredential.get(ws));
4899
4933
  }
@@ -4963,9 +4997,10 @@ export class Daemon {
4963
4997
  // dashboard cookie did. The actor names the credential, not the person
4964
4998
  // or program behind it.
4965
4999
  const actor = credential.kind;
5000
+ if (credential.kind === 'dashboard' &&
5001
+ this.retainSocketProof(ws, credential.dashboardToken) === undefined)
5002
+ return;
4966
5003
  this.sockets.add(ws);
4967
- if (credential.dashboardToken !== undefined)
4968
- this.dashboardSocketCredential.set(ws, credential.dashboardToken);
4969
5004
  let watchers = this.sessionSockets.get(session.id);
4970
5005
  if (watchers === undefined) {
4971
5006
  watchers = new Map();
@@ -5315,7 +5350,7 @@ export class Daemon {
5315
5350
  // is or that the window gained focus, is written above like a keystroke
5316
5351
  // because the program asked for it. Nobody typed it, so it is audited
5317
5352
  // as a report and leaves the "last input" indicator alone (§4.5, §5).
5318
- // Content only under captureContent, as for input.
5353
+ // Only reports allow opt-in content capture.
5319
5354
  if (report !== null) {
5320
5355
  this.audit.record(actor, 'report', session.id, {
5321
5356
  kind: report,
@@ -5326,11 +5361,12 @@ export class Daemon {
5326
5361
  }
5327
5362
  this.audit.record(actor, 'input', session.id, {
5328
5363
  chars: text.length,
5329
- ...(this.audit.captureContent ? { data: text } : {}),
5330
5364
  });
5331
5365
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
5332
5366
  };
5333
5367
  ws.on('message', (message) => {
5368
+ if (actor === 'dashboard' && ws.readyState !== ws.OPEN)
5369
+ return;
5334
5370
  this.callerContext.run(options.callerSession, () => {
5335
5371
  void onViewerMessage(message).catch((error) => {
5336
5372
  this.logger.warn('viewer message failed', { id: session.id, error: String(error) });