shellpuppet 0.4.1 → 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.
@@ -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
  /**
@@ -559,6 +562,7 @@ export class Daemon {
559
562
  compiledPolicy;
560
563
  /** Accepted launch times, for the sliding sixty-second cap. */
561
564
  launchTimes = [];
565
+ pendingProfileStarts = new Set();
562
566
  claimTimes = [];
563
567
  claimCount = 0;
564
568
  folderPickerBusy = false;
@@ -581,6 +585,7 @@ export class Daemon {
581
585
  const auditor = options.audit ?? NULL_AUDITOR;
582
586
  this.audit = {
583
587
  captureContent: auditor.captureContent,
588
+ recordRequired: auditor.recordRequired?.bind(auditor),
584
589
  record: (actor, action, session, meta) => auditor.record(actor, action, session, meta,
585
590
  // A session's timers and listeners can inherit the request that created
586
591
  // them. Daemon observations must not inherit that caller's identity.
@@ -1968,13 +1973,18 @@ export class Daemon {
1968
1973
  json(res, 503, { error: 'The daemon is stopping.' });
1969
1974
  return;
1970
1975
  }
1971
- if (launcher && this.grantedLauncher(req)?.id !== launcher.id) {
1972
- json(res, 403, { error: 'Session launch permission required.' });
1973
- 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
+ }
1974
1984
  }
1975
1985
  const now = this.now();
1976
1986
  this.pruneLaunchTimes(now);
1977
- if (this.launchTimes.length >= 8) {
1987
+ if (this.launchTimes.length + this.pendingProfileStarts.size >= 8) {
1978
1988
  this.auditDashboardRefusal(req, 'rate', launcher?.name);
1979
1989
  json(res, 429, {
1980
1990
  error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
@@ -2027,18 +2037,20 @@ export class Daemon {
2027
2037
  json(res, 500, { error: `Failed to start session: ${String(error)}` });
2028
2038
  return;
2029
2039
  }
2030
- // Counted the moment the launch is accepted, before the start contract's
2031
- // wait: the rate check above and this record must sit in the same
2032
- // synchronous stretch, or twelve launches fired together would all pass
2033
- // the check before any of them was counted.
2034
- this.launchTimes.push(now);
2035
- // The same start contract as `POST /sessions`: the dashboard's pane is a
2036
- // session only once its program exists, and a start that ends before any
2037
- // program did fails as 1.1.0's spawn did, leaving nothing in the grid.
2038
- const startedSession = await this.programStarted(session, options, res, 'dashboard session start failed');
2039
- if (startedSession === null)
2040
- return;
2041
- 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
+ }
2042
2054
  // A launch is an API call: the idle timer counts from it, so a session
2043
2055
  // that has just started is not reaped sooner than `idleMinutes` allows.
2044
2056
  this.lastActivity = Date.now();
@@ -2520,7 +2532,7 @@ export class Daemon {
2520
2532
  });
2521
2533
  writePrivateRecord(path.join(this.options.home, 'previous-sessions.json'), { version: 1, outgoingInstanceId: this.instanceId, sessions });
2522
2534
  }
2523
- saveLauncherClaims(excludeId) {
2535
+ saveLauncherClaims(excludeId, next, beforePublish) {
2524
2536
  const grants = this.launchProfiles.sessionLaunch ?? [];
2525
2537
  const file = path.join(this.options.home, 'launcher-claims.json');
2526
2538
  if (!this.claimsRestored)
@@ -2528,25 +2540,57 @@ export class Daemon {
2528
2540
  if (grants.length || fs.existsSync(file)) {
2529
2541
  let discovery = this.requireHomeOwner();
2530
2542
  const claims = this.mailbox.savedClaims(grants).filter(claim => claim.id !== excludeId);
2531
- writePrivateRecord(file, claims, () => { discovery = this.requireHomeOwner(); });
2543
+ if (next)
2544
+ claims.push(next);
2545
+ writePrivateRecord(file, claims, () => {
2546
+ beforePublish?.();
2547
+ discovery = this.requireHomeOwner();
2548
+ });
2532
2549
  if (!this.stopping && (discovery.kind === 'missing' || discovery.kind === 'not-a-record')) {
2533
2550
  void this.keepStatePublished();
2534
2551
  }
2535
2552
  }
2536
2553
  }
2537
- 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) {
2538
2579
  this.lapseIdleClaims();
2539
2580
  let id = this.callerContext.getStore();
2540
2581
  if (id === undefined) {
2541
- const claim = headerOne(req, 'x-shellpuppet-claim');
2542
- const secret = headerOne(req, 'x-shellpuppet-claim-secret');
2543
- if (req.headers['x-shellpuppet-inside-session'] === '1' || !claim || !secret ||
2544
- !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 });
2545
2585
  return undefined;
2546
- id = claim;
2586
+ }
2587
+ id = claim.id;
2547
2588
  }
2548
- const caller = this.mailbox.participant(id);
2549
- 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;
2550
2594
  }
2551
2595
  messageAudit(action, entry, actor = 'daemon') {
2552
2596
  this.audit.record(actor, action, entry.from.id, {
@@ -2567,6 +2611,9 @@ export class Daemon {
2567
2611
  }
2568
2612
  }
2569
2613
  this.mailbox.end(id);
2614
+ this.closeParticipantSockets(id);
2615
+ }
2616
+ closeParticipantSockets(id) {
2570
2617
  for (const [ws, participant] of this.eventSockets) {
2571
2618
  if (participant === id)
2572
2619
  ws.close();
@@ -2807,18 +2854,14 @@ export class Daemon {
2807
2854
  return;
2808
2855
  }
2809
2856
  this.lapseIdleClaims();
2810
- const claimId = req.headers['x-shellpuppet-claim'];
2811
- const claimSecret = req.headers['x-shellpuppet-claim-secret'];
2812
- const claimPresented = claimId !== undefined || claimSecret !== undefined;
2813
- const claimValid = typeof claimId === 'string' && typeof claimSecret === 'string' &&
2814
- this.mailbox.verifyClaim(claimId, claimSecret);
2815
2857
  const route = segments[1];
2816
2858
  const creatingClaim = req.method === 'POST' && route === 'claims' && segments.length === 2;
2817
- if (claimPresented && !claimValid && !creatingClaim) {
2818
- 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 });
2819
2862
  return;
2820
2863
  }
2821
- const caller = this.callerContext.getStore() ?? (claimValid ? claimId : undefined);
2864
+ const caller = this.callerContext.getStore() ?? claimId;
2822
2865
  if (creatingClaim) {
2823
2866
  // Each refusal says only what the daemon knows: a verified session, a valid claim, a mark on the request.
2824
2867
  if (this.callerContext.getStore() !== undefined) {
@@ -2826,9 +2869,9 @@ export class Daemon {
2826
2869
  return;
2827
2870
  }
2828
2871
  const marked = req.headers['x-shellpuppet-inside-session'] === '1';
2829
- if (claimValid || marked) {
2872
+ if (claimId !== undefined || marked) {
2830
2873
  const reasons = [];
2831
- if (claimValid) {
2874
+ if (claimId !== undefined) {
2832
2875
  reasons.push('This client already holds a messaging claim: release it first (msg release), or stop ' +
2833
2876
  'presenting it (SHELLPUPPET_CLAIM), to make another.');
2834
2877
  }
@@ -2842,10 +2885,18 @@ export class Daemon {
2842
2885
  return;
2843
2886
  }
2844
2887
  const body = await readBody(req);
2845
- if (typeof body['name'] !== 'string') {
2888
+ const name = body['name'];
2889
+ const replace = body['replace'] === true;
2890
+ if (typeof name !== 'string') {
2846
2891
  json(res, 400, { error: 'A valid name is required.' });
2847
2892
  return;
2848
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();
2849
2900
  const now = this.now();
2850
2901
  while (this.claimTimes.length > 0 && (this.claimTimes[0] ?? now) <= now - 60_000)
2851
2902
  this.claimTimes.shift();
@@ -2857,35 +2908,38 @@ export class Daemon {
2857
2908
  json(res, 429, { error: 'Messaging claim rate reached (8 in 60 seconds).' });
2858
2909
  return;
2859
2910
  }
2860
- const claim = this.mailbox.claim(body['name']);
2861
- this.claimTimes.push(now);
2862
- this.claimCount++;
2863
- if (this.launchProfiles.sessionLaunch?.includes(body['name'])) {
2864
- try {
2865
- this.saveLauncherClaims();
2866
- }
2867
- catch (error) {
2868
- this.mailbox.release(claim.claimId);
2869
- this.claimCount--;
2870
- throw error;
2871
- }
2872
- }
2873
- this.audit.record(actor, 'msg-claim', claim.claimId, {
2874
- fromId: claim.claimId, fromName: body['name'], toId: null, toName: null,
2875
- 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
+ },
2876
2921
  });
2877
- 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 });
2878
2933
  return;
2879
2934
  }
2880
2935
  if (caller === undefined) {
2881
2936
  json(res, 403, { error: 'Not a messaging participant.' });
2882
2937
  return;
2883
2938
  }
2884
- if (claimValid)
2885
- this.mailbox.touchClaim(claimId);
2886
2939
  if (req.method === 'DELETE' && route === 'claims' && segments.length === 3) {
2887
- if (!claimValid || claimId !== segments[2]) {
2888
- 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 }) });
2889
2943
  return;
2890
2944
  }
2891
2945
  const name = this.mailbox.participant(claimId)?.name;
@@ -2959,7 +3013,7 @@ export class Daemon {
2959
3013
  finally {
2960
3014
  res.off('close', onClose);
2961
3015
  }
2962
- if (claimValid)
3016
+ if (claimId !== undefined && req.headers['x-shellpuppet-inside-session'] !== '1')
2963
3017
  this.mailbox.touchClaim(claimId);
2964
3018
  return;
2965
3019
  }
@@ -3021,10 +3075,8 @@ export class Daemon {
3021
3075
  return;
3022
3076
  }
3023
3077
  if (url.pathname === '/launcher/previous' && req.method === 'GET') {
3024
- if (!this.grantedLauncher(req)) {
3025
- json(res, 403, { error: 'Session launch permission required.' });
3078
+ if (!this.grantedLauncher(req, res))
3026
3079
  return;
3027
- }
3028
3080
  const file = path.join(this.options.home, 'previous-sessions.json');
3029
3081
  try {
3030
3082
  // Older version 1 records used the generated session id as an explicit name.
@@ -3045,11 +3097,9 @@ export class Daemon {
3045
3097
  return;
3046
3098
  }
3047
3099
  if (url.pathname === '/launcher/launch' && req.method === 'POST') {
3048
- const caller = this.grantedLauncher(req);
3049
- if (!caller) {
3050
- json(res, 403, { error: 'Session launch permission required.' });
3100
+ const caller = this.grantedLauncher(req, res);
3101
+ if (!caller)
3051
3102
  return;
3052
- }
3053
3103
  if ((headerOne(req, 'content-type') ?? '').split(';')[0]?.trim().toLowerCase() !== 'application/json') {
3054
3104
  json(res, 415, { error: 'The launch body must be JSON.' });
3055
3105
  return;
@@ -3450,6 +3500,7 @@ export class Daemon {
3450
3500
  // caller's request for a race in the session's lifetime. A session
3451
3501
  // whose input pipe has failed refuses the write too, and its error
3452
3502
  // says what to do.
3503
+ const submit = body['submit'] === true;
3453
3504
  let written;
3454
3505
  try {
3455
3506
  written = await session.writeWithResult(data);
@@ -3462,12 +3513,9 @@ export class Daemon {
3462
3513
  });
3463
3514
  return;
3464
3515
  }
3465
- // §4.5: content NEVER logged by default, only the length. Keystrokes
3466
- // are where the secrets are.
3467
- this.audit.record(actor, 'input', id, {
3468
- chars: data.length,
3469
- ...(this.audit.captureContent ? { data } : {}),
3470
- });
3516
+ const reporting = submit ? submitOutcome(written) : undefined;
3517
+ this.audit.record(actor, 'input', id, { chars: data.length,
3518
+ ...(reporting ? { submit: true, ...reporting } : {}) });
3471
3519
  this.broadcastControl(id, { type: 'input-source', source: 'agent' });
3472
3520
  // §3.1: TUIs silently swallow input while loading or when a panel has
3473
3521
  // stolen focus. verify re-reads the screen and reports whether the
@@ -3477,6 +3525,7 @@ export class Daemon {
3477
3525
  json(res, 200, {
3478
3526
  ok: true,
3479
3527
  bytes: data.length,
3528
+ ...reporting,
3480
3529
  verified: await this.verifyTyped(session, data, written.before),
3481
3530
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3482
3531
  ...(written.submitRetried ? { submitRetried: true } : {}),
@@ -3485,6 +3534,7 @@ export class Daemon {
3485
3534
  return;
3486
3535
  }
3487
3536
  json(res, 200, { ok: true, bytes: data.length,
3537
+ ...reporting,
3488
3538
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3489
3539
  ...(written.submitRetried ? { submitRetried: true } : {}),
3490
3540
  ...(written.message !== undefined ? { message: written.message } : {}),
@@ -3751,6 +3801,10 @@ export class Daemon {
3751
3801
  json(res, 409, { error: error.message });
3752
3802
  return;
3753
3803
  }
3804
+ if (error instanceof ClaimAuditError) {
3805
+ json(res, 503, { error: error.message });
3806
+ return;
3807
+ }
3754
3808
  if (error instanceof MailboxError) {
3755
3809
  const status = error.code === 'unknown-name' ? 404 :
3756
3810
  error.code === 'not-allowed' || error.code === 'unknown-sender' ? 403 :
@@ -3767,7 +3821,7 @@ export class Daemon {
3767
3821
  'text-too-large': 'A message exceeds the 16 KiB limit.',
3768
3822
  'mailbox-full': 'The mailbox is full.',
3769
3823
  };
3770
- json(res, status, { error: messages[error.code] });
3824
+ json(res, status, { error: messages[error.code], hint: error.hint });
3771
3825
  return;
3772
3826
  }
3773
3827
  if (error instanceof WaitConditionError) {
@@ -4146,11 +4200,11 @@ export class Daemon {
4146
4200
  * is returned with the response already sent. Only the proven ConPTY worker
4147
4201
  * timeout gets one replacement attempt under the same id.
4148
4202
  */
4149
- async programStarted(session, options, res, logMessage) {
4203
+ async programStarted(session, options, res, logMessage, onTerminalFailure) {
4150
4204
  this.startingIds.add(session.id);
4151
4205
  try {
4152
4206
  if (this.manager.get(session.id) === session)
4153
- return await this.manager.finishStart(session, options);
4207
+ return await this.manager.finishStart(session, options, onTerminalFailure);
4154
4208
  // Test-only dashboard factories may supply a session outside the manager.
4155
4209
  if (await session.startedProgramPid() !== null)
4156
4210
  return session;
@@ -4467,8 +4521,9 @@ export class Daemon {
4467
4521
  // refusal never reaches. An error with no listener would be an uncaught
4468
4522
  // exception, on which the daemon shuts down with every session.
4469
4523
  socket.on('error', () => socket.destroy());
4470
- const reject = (code, reason) => {
4471
- 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`);
4472
4527
  socket.destroy();
4473
4528
  };
4474
4529
  if (!this.hostAllowed(req.headers.host)) {
@@ -4532,18 +4587,16 @@ export class Daemon {
4532
4587
  reject(403, 'Forbidden');
4533
4588
  return;
4534
4589
  }
4535
- const claimId = req.headers['x-shellpuppet-claim'];
4536
- const claimSecret = req.headers['x-shellpuppet-claim-secret'];
4537
- const claimPresented = claimId !== undefined || claimSecret !== undefined;
4538
- if (claimPresented)
4590
+ if (req.headers['x-shellpuppet-claim'] !== undefined || req.headers['x-shellpuppet-claim-secret'] !== undefined) {
4539
4591
  this.lapseIdleClaims();
4540
- if (claimPresented && (typeof claimId !== 'string' || typeof claimSecret !== 'string' ||
4541
- !this.mailbox.verifyClaim(claimId, claimSecret))) {
4542
- reject(403, 'Forbidden');
4592
+ }
4593
+ const claim = this.presentedClaim(req);
4594
+ if (claim.refused) {
4595
+ reject(403, 'Forbidden', CLAIM_RECOVERY_HINT);
4543
4596
  return;
4544
4597
  }
4545
4598
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4546
- 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));
4547
4600
  });
4548
4601
  return;
4549
4602
  }
@@ -5297,7 +5350,7 @@ export class Daemon {
5297
5350
  // is or that the window gained focus, is written above like a keystroke
5298
5351
  // because the program asked for it. Nobody typed it, so it is audited
5299
5352
  // as a report and leaves the "last input" indicator alone (§4.5, §5).
5300
- // Content only under captureContent, as for input.
5353
+ // Only reports allow opt-in content capture.
5301
5354
  if (report !== null) {
5302
5355
  this.audit.record(actor, 'report', session.id, {
5303
5356
  kind: report,
@@ -5308,7 +5361,6 @@ export class Daemon {
5308
5361
  }
5309
5362
  this.audit.record(actor, 'input', session.id, {
5310
5363
  chars: text.length,
5311
- ...(this.audit.captureContent ? { data: text } : {}),
5312
5364
  });
5313
5365
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
5314
5366
  };