shellpuppet 0.4.0 → 0.4.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.
@@ -463,13 +463,11 @@ export class Daemon {
463
463
  promptScheduler;
464
464
  stopScheduleWatch;
465
465
  server;
466
+ /** Protocol accepted by dashboard authentication for this specific upgrade. */
467
+ dashboardUpgradeProtocols = new WeakMap();
466
468
  wss = new WebSocketServer({
467
469
  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),
470
+ handleProtocols: (_protocols, request) => this.dashboardUpgradeProtocols.get(request) ?? false,
473
471
  });
474
472
  sockets = new Set();
475
473
  /** Every watcher of a session, with the gate that orders its stream across snapshots. */
@@ -511,8 +509,8 @@ export class Daemon {
511
509
  dashboardWindowIds = new Map();
512
510
  dashboardAssignments = new Map();
513
511
  dashboardDesignated = null;
514
- /** The document proof survives a feed reconnect and expires with the proof ring. */
515
- dashboardDocumentFocus = new Map();
512
+ /** Remember focus across reconnects for the lifetime of the document proof. */
513
+ dashboardDocumentFocus = new WeakMap();
516
514
  liveDashboardEventSockets = new Set();
517
515
  /** A launched dashboard has 30 seconds to connect before a start may retry. */
518
516
  dashboardWindowStartedAt = 0;
@@ -1283,7 +1281,7 @@ export class Daemon {
1283
1281
  if (grantPresented) {
1284
1282
  const redeemed = this.tokens.redeemDashboardGrant(grant, this.now());
1285
1283
  if (redeemed !== null) {
1286
- this.retireDashboardFeeds();
1284
+ this.retireDashboardSockets();
1287
1285
  this.audit.record('dashboard', 'grant-redeem');
1288
1286
  res.writeHead(303, {
1289
1287
  location: '/dashboard',
@@ -1297,8 +1295,13 @@ export class Daemon {
1297
1295
  return;
1298
1296
  }
1299
1297
  const proof = cookie === null ? null : this.tokens.issueDashboardProof();
1300
- if (proof !== null)
1301
- this.retireDashboardFeeds();
1298
+ if (cookie !== null && proof === null) {
1299
+ this.auditDashboardRefusal(req, 'limit');
1300
+ res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8',
1301
+ 'cache-control': 'no-store', 'content-security-policy': PAGE_CSP });
1302
+ res.end('Too many dashboard windows are open. Close one and reload this page.');
1303
+ return;
1304
+ }
1302
1305
  this.sendDashboardPage(res, proof, req.method === 'HEAD');
1303
1306
  return;
1304
1307
  }
@@ -1334,7 +1337,7 @@ export class Daemon {
1334
1337
  this.pendingDashboardGrants.delete(grant);
1335
1338
  if (this.stopping || !opened.launched || opened.mode === 'default-browser') {
1336
1339
  this.tokens.revokeDashboardGrant(grant);
1337
- this.retireDashboardFeeds();
1340
+ this.retireDashboardSockets();
1338
1341
  this.auditDashboardRefusal(req, 'launch-failed');
1339
1342
  return false;
1340
1343
  }
@@ -1793,7 +1796,9 @@ export class Daemon {
1793
1796
  }
1794
1797
  }
1795
1798
  const requestedWindow = body['window'];
1796
- const launchingWindow = requestedWindow === undefined ? undefined : this.dashboardWindows().find((window) => window.pair === requestedWindow && dashboardProofFromProtocol(window.socket.protocol) === documentProof);
1799
+ const launchingWindow = requestedWindow === undefined || documentProof === undefined ? undefined
1800
+ : this.dashboardWindows().find(window => window.pair === requestedWindow &&
1801
+ tokensEqual(window.socket.protocol, `sp-csrf.${documentProof}`));
1797
1802
  if (requestedWindow !== undefined && launchingWindow === undefined) {
1798
1803
  json(res, 409, { error: 'The launching dashboard window has closed.' });
1799
1804
  return;
@@ -2207,9 +2212,7 @@ export class Daemon {
2207
2212
  json(res, 200, { id, name: body['name'], label: session.label });
2208
2213
  }
2209
2214
  /**
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`.
2215
+ * Authenticate a dashboard upgrade and select the offered protocol that proved it.
2213
2216
  */
2214
2217
  dashboardUpgradeCredential(req) {
2215
2218
  const token = this.dashboardCookieToken(req.headers.cookie);
@@ -2228,46 +2231,10 @@ export class Daemon {
2228
2231
  (site === undefined && mode === undefined))) {
2229
2232
  return { code: 403, reason: 'Forbidden', audit: 'fetch-site' };
2230
2233
  }
2231
- const accepted = offeredProtocols(req).some((protocol) => {
2232
- const proof = dashboardProofFromProtocol(protocol);
2233
- return proof !== null && this.tokens.acceptsDashboardProof(proof);
2234
- });
2235
- if (!accepted)
2234
+ const protocol = offeredProtocols(req).find(offer => this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(offer)));
2235
+ if (protocol === undefined)
2236
2236
  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;
2237
+ return { kind: 'dashboard', readOnly: false, dashboardToken: token, protocol };
2271
2238
  }
2272
2239
  /**
2273
2240
  * Who may open `/sessions/<id>/stream`, or why not.
@@ -2278,9 +2245,9 @@ export class Daemon {
2278
2245
  * upgrade's rules: a live `sp-csrf` subprotocol, a matching Origin, and
2279
2246
  * same-origin Fetch Metadata. A header is not the proof. A viewer cookie,
2280
2247
  * 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
2248
+ * When both are present and the dashboard checks pass, the dashboard cookie is the
2282
2249
  * 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
2250
+ * does not mask it. When the dashboard checks fail, a viewer cookie for this
2284
2251
  * session still opens the socket on its own rules.
2285
2252
  */
2286
2253
  sessionStreamDecision(req, url, sessionId) {
@@ -2292,9 +2259,8 @@ export class Daemon {
2292
2259
  return { ok: true, credential: { kind: 'client', readOnly: false } };
2293
2260
  }
2294
2261
  const dashboard = this.dashboardUpgradeCredential(req);
2295
- if (typeof dashboard === 'string') {
2296
- return { ok: true, credential: { kind: 'dashboard', readOnly: false,
2297
- dashboardToken: dashboard } };
2262
+ if ('kind' in dashboard) {
2263
+ return { ok: true, credential: dashboard };
2298
2264
  }
2299
2265
  const viewer = cookieValues(req.headers.cookie, VIEWER_COOKIE)
2300
2266
  .map((value) => ({ value, credential: this.tokens.verifyStreamToken(value) }))
@@ -4537,15 +4503,16 @@ export class Daemon {
4537
4503
  const segments = url.pathname.split('/').filter((s) => s !== '');
4538
4504
  // The dashboard feed is cookie-only. Its Origin rule is stricter than the
4539
4505
  // client-token sockets below, which still allow a missing Origin.
4540
- if (segments[0] === 'dashboard' && segments[1] === 'events' && segments.length === 2) {
4506
+ if (url.pathname === '/dashboard/events') {
4541
4507
  const credential = this.dashboardUpgradeCredential(req);
4542
- if (typeof credential !== 'string') {
4508
+ if ('code' in credential) {
4543
4509
  this.auditDashboardRefusal(req, credential.audit);
4544
4510
  reject(credential.code, credential.reason);
4545
4511
  return;
4546
4512
  }
4513
+ this.dashboardUpgradeProtocols.set(req, credential.protocol);
4547
4514
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4548
- this.attachDashboardSocket(ws, credential);
4515
+ this.attachDashboardSocket(ws, credential.dashboardToken);
4549
4516
  });
4550
4517
  return;
4551
4518
  }
@@ -4580,7 +4547,7 @@ export class Daemon {
4580
4547
  });
4581
4548
  return;
4582
4549
  }
4583
- if (segments[0] !== 'sessions' || segments[2] !== 'stream') {
4550
+ if (segments.length !== 3 || segments[0] !== 'sessions' || segments[2] !== 'stream') {
4584
4551
  reject(404, 'Not Found');
4585
4552
  return;
4586
4553
  }
@@ -4619,6 +4586,9 @@ export class Daemon {
4619
4586
  // dashboard credential is made passive in attachSocket, whatever the
4620
4587
  // query says, so this flag cannot turn that socket into a driver.
4621
4588
  const passive = passiveDrive(url);
4589
+ if (decision.credential.kind === 'dashboard') {
4590
+ this.dashboardUpgradeProtocols.set(req, decision.credential.protocol);
4591
+ }
4622
4592
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4623
4593
  // Which credential opened the socket travels with it, so the audit log
4624
4594
  // names that credential rather than assuming a browser: `client` for
@@ -4669,7 +4639,9 @@ export class Daemon {
4669
4639
  for (const [id, previous] of this.dashboardTransferable) {
4670
4640
  const owner = windows.find(w => this.dashboardAssignments.get(w.pair)?.includes(id));
4671
4641
  const recipient = owner?.socket.protocol;
4672
- if (recipient === previous || (previous === null && windows.length === 0))
4642
+ const unchanged = recipient === undefined ? previous === undefined
4643
+ : typeof previous === 'string' && tokensEqual(previous, recipient);
4644
+ if (unchanged || (previous === null && windows.length === 0))
4673
4645
  continue;
4674
4646
  this.dashboardTransferable.set(id, recipient);
4675
4647
  const session = this.manager.get(id);
@@ -4717,14 +4689,11 @@ export class Daemon {
4717
4689
  return this.tokens.verifyDashboardToken(this.dashboardSocketCredential.get(ws)) &&
4718
4690
  this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(ws.protocol));
4719
4691
  }
4720
- retireDashboardFeeds() {
4721
- for (const protocol of this.dashboardDocumentFocus.keys()) {
4722
- if (!this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(protocol)))
4723
- this.dashboardDocumentFocus.delete(protocol);
4724
- }
4692
+ retireDashboardSockets() {
4725
4693
  let changed = false;
4726
- for (const ws of this.dashboardEventSockets) {
4727
- if (ws.readyState === ws.OPEN && !this.dashboardFeedCurrent(ws)) {
4694
+ for (const ws of this.sockets) {
4695
+ const credential = this.dashboardSocketCredential.get(ws);
4696
+ if (credential !== undefined && ws.readyState === ws.OPEN && !this.tokens.verifyDashboardToken(credential)) {
4728
4697
  if (this.dashboardWindowIds.delete(ws))
4729
4698
  changed = true;
4730
4699
  this.liveDashboardEventSockets.delete(ws);
@@ -4734,8 +4703,20 @@ export class Daemon {
4734
4703
  if (changed)
4735
4704
  this.publishDashboardWindows();
4736
4705
  }
4737
- attachDashboardSocket(ws, credential) {
4706
+ retainSocketProof(ws, credential) {
4707
+ const proof = this.tokens.retainDashboardProof(dashboardProofFromProtocol(ws.protocol));
4708
+ if (proof === undefined) {
4709
+ ws.close(1008, 'Dashboard access expired');
4710
+ return undefined;
4711
+ }
4738
4712
  this.dashboardSocketCredential.set(ws, credential);
4713
+ ws.once('close', () => this.tokens.releaseDashboardProof(proof));
4714
+ return proof;
4715
+ }
4716
+ attachDashboardSocket(ws, credential) {
4717
+ const proof = this.retainSocketProof(ws, credential);
4718
+ if (proof === undefined)
4719
+ return;
4739
4720
  this.sockets.add(ws);
4740
4721
  this.dashboardEventSockets.add(ws);
4741
4722
  this.liveDashboardEventSockets.add(ws);
@@ -4790,7 +4771,7 @@ export class Daemon {
4790
4771
  if (claim.type === 'window-focus') {
4791
4772
  const at = claim.focusedAt === undefined ? performance.timeOrigin + performance.now() : claim.focusedAt;
4792
4773
  current.focused = Math.max(current.focused, this.dashboardFocusTime(at));
4793
- this.dashboardDocumentFocus.set(ws.protocol, { id: current.id, focused: current.focused });
4774
+ this.dashboardDocumentFocus.set(proof, { id: current.id, focused: current.focused });
4794
4775
  this.publishDashboardWindows();
4795
4776
  }
4796
4777
  else if (claim.type === 'window-designate') {
@@ -4824,10 +4805,10 @@ export class Daemon {
4824
4805
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.instance) ||
4825
4806
  claim.instance.length > 100)
4826
4807
  return;
4827
- const previous = this.dashboardDocumentFocus.get(ws.protocol);
4808
+ const previous = this.dashboardDocumentFocus.get(proof);
4828
4809
  const focused = Math.max(previous?.id === claim.id ? previous.focused : 0, this.dashboardFocusTime(claim.focusedAt));
4829
4810
  this.dashboardWindowIds.set(ws, { id: claim.id, instance: claim.instance, focused });
4830
- this.dashboardDocumentFocus.set(ws.protocol, { id: claim.id, focused });
4811
+ this.dashboardDocumentFocus.set(proof, { id: claim.id, focused });
4831
4812
  this.publishDashboardWindows();
4832
4813
  });
4833
4814
  ws.on('close', () => {
@@ -4893,7 +4874,7 @@ export class Daemon {
4893
4874
  }
4894
4875
  gridOfferedTo(id, ws) {
4895
4876
  const recipient = this.dashboardTransferable.get(id);
4896
- return (recipient === null || recipient === ws.protocol) &&
4877
+ return (recipient === null || (recipient !== undefined && tokensEqual(recipient, ws.protocol))) &&
4897
4878
  this.dashboardCredentialOwner.has(id) && this.dashboardSocketCredential.has(ws) &&
4898
4879
  tokensEqual(this.dashboardCredentialOwner.get(id), this.dashboardSocketCredential.get(ws));
4899
4880
  }
@@ -4963,9 +4944,10 @@ export class Daemon {
4963
4944
  // dashboard cookie did. The actor names the credential, not the person
4964
4945
  // or program behind it.
4965
4946
  const actor = credential.kind;
4947
+ if (credential.kind === 'dashboard' &&
4948
+ this.retainSocketProof(ws, credential.dashboardToken) === undefined)
4949
+ return;
4966
4950
  this.sockets.add(ws);
4967
- if (credential.dashboardToken !== undefined)
4968
- this.dashboardSocketCredential.set(ws, credential.dashboardToken);
4969
4951
  let watchers = this.sessionSockets.get(session.id);
4970
4952
  if (watchers === undefined) {
4971
4953
  watchers = new Map();
@@ -5331,6 +5313,8 @@ export class Daemon {
5331
5313
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
5332
5314
  };
5333
5315
  ws.on('message', (message) => {
5316
+ if (actor === 'dashboard' && ws.readyState !== ws.OPEN)
5317
+ return;
5334
5318
  this.callerContext.run(options.callerSession, () => {
5335
5319
  void onViewerMessage(message).catch((error) => {
5336
5320
  this.logger.warn('viewer message failed', { id: session.id, error: String(error) });