@sideboard-ai/core 0.1.334 → 0.1.336

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 (67) hide show
  1. package/dist/{abletime-SO2YHMEI.js → abletime-OGOHNRVB.js} +4 -4
  2. package/dist/{abletime-5FBKBO3R.js → abletime-TNONAVJG.js} +4 -4
  3. package/dist/{abletime-oauth-EUC5FFMD.js → abletime-oauth-DAZEUQJI.js} +3 -3
  4. package/dist/{abletime-oauth-I34WZZZL.js → abletime-oauth-TYDQ73GK.js} +3 -3
  5. package/dist/{abletime-rest-EI5ZJ72Z.js → abletime-rest-3FWZGTX6.js} +3 -3
  6. package/dist/{abletime-rest-HEQXSZAQ.js → abletime-rest-B4VI46MI.js} +3 -3
  7. package/dist/{agents-5NJ3FROS.js → agents-ISEAOZD5.js} +7 -7
  8. package/dist/{agents-SRM6OVML.js → agents-VTLFLMMT.js} +7 -7
  9. package/dist/{app-settings-JAEV53LB.js → app-settings-KOSVLMO5.js} +1 -1
  10. package/dist/{app-settings-SHZWNJBV.js → app-settings-YS5AUJTF.js} +1 -1
  11. package/dist/{chunk-EY5BJAPV.js → chunk-23KYDM2U.js} +23 -0
  12. package/dist/{chunk-F4OUZDIB.js → chunk-4BRO5LNX.js} +3 -3
  13. package/dist/{chunk-RJT6JPNX.js → chunk-4O7436ZH.js} +5 -5
  14. package/dist/{chunk-JJRTVB7D.js → chunk-4OVQGZEI.js} +3 -3
  15. package/dist/{chunk-SKPX66MO.js → chunk-4SP26Z6H.js} +5 -5
  16. package/dist/{chunk-WXOJSFGO.js → chunk-54GBJC6J.js} +8 -8
  17. package/dist/{chunk-QNKJCD7B.js → chunk-5FGQTB2Z.js} +2 -2
  18. package/dist/{chunk-25KXB7W6.js → chunk-5TVRPOVS.js} +1 -1
  19. package/dist/{chunk-EW5D53VB.js → chunk-AFSLMWQK.js} +1 -1
  20. package/dist/{chunk-ELDJBZ52.js → chunk-B6TPN624.js} +5 -5
  21. package/dist/{chunk-QVLDZWHZ.js → chunk-BDQFZAE6.js} +1 -1
  22. package/dist/{chunk-LEUAYFSG.js → chunk-CDRGQ6GX.js} +3 -3
  23. package/dist/{chunk-4J7R2BFU.js → chunk-EKI7D2AJ.js} +21 -21
  24. package/dist/{chunk-P7S3XGKL.js → chunk-ERCYQTJU.js} +3 -3
  25. package/dist/{chunk-UV33UCV6.js → chunk-FCBUDWP6.js} +2 -2
  26. package/dist/{chunk-YMV5O7KY.js → chunk-FEGRY7NL.js} +3 -3
  27. package/dist/{chunk-CS6LQUL6.js → chunk-HNW5KMGK.js} +2 -2
  28. package/dist/{chunk-277I5IBI.js → chunk-I2C5ZRVO.js} +1 -1
  29. package/dist/{chunk-ZT5YPYZE.js → chunk-KAIOL2M5.js} +1 -1
  30. package/dist/{chunk-BAIPCN34.js → chunk-LYJ5AVK4.js} +2 -2
  31. package/dist/{chunk-6RUSADA7.js → chunk-MGEUXR6E.js} +3 -3
  32. package/dist/{chunk-7BAS6DF7.js → chunk-N6TGSJVC.js} +22 -0
  33. package/dist/{chunk-TLL2K2MY.js → chunk-NB4U75TJ.js} +7 -7
  34. package/dist/{chunk-MXQ66CLO.js → chunk-OMKTX7ZW.js} +3 -3
  35. package/dist/{chunk-QKJC725N.js → chunk-PSXBOMXI.js} +20 -20
  36. package/dist/{chunk-7MPRTC6X.js → chunk-Q73I6I2K.js} +1 -1
  37. package/dist/{chunk-RCRDNOAT.js → chunk-QWFNKOGA.js} +2 -2
  38. package/dist/{chunk-NCFYUUSC.js → chunk-SYTTUNX6.js} +1 -1
  39. package/dist/{chunk-HJIA4X3L.js → chunk-W6J3ZWLJ.js} +2 -2
  40. package/dist/{chunk-D6V6F74A.js → chunk-WSZIJNAR.js} +5 -5
  41. package/dist/{conductor-XSP3SOS2.js → conductor-77L3QTZ2.js} +5 -5
  42. package/dist/{conductor-LUPB6RBH.js → conductor-JH26KU3W.js} +5 -5
  43. package/dist/{coordinator-prompt-O75QUEHP.js → coordinator-prompt-UKJJAMBG.js} +4 -4
  44. package/dist/{coordinator-prompt-EJJNJ5K7.js → coordinator-prompt-WVVC2TLP.js} +4 -4
  45. package/dist/{global-workspace-3IG44NAT.js → global-workspace-B5IHENCP.js} +4 -4
  46. package/dist/{global-workspace-Q4OURN7M.js → global-workspace-QDIPRW6G.js} +4 -4
  47. package/dist/index.cjs +1492 -568
  48. package/dist/index.d.cts +101 -15
  49. package/dist/index.d.ts +101 -15
  50. package/dist/index.js +1420 -532
  51. package/dist/{linear-FRJRK6KI.js → linear-5E2WI4QQ.js} +2 -2
  52. package/dist/{linear-7HSIGV5S.js → linear-P3LP455O.js} +2 -2
  53. package/dist/{linear-list-LDMBSKYI.js → linear-list-AXK62DPW.js} +1 -1
  54. package/dist/{linear-list-I6DNJC6V.js → linear-list-Y3INIBYH.js} +1 -1
  55. package/dist/mcp/run-stdio.cjs +29 -1
  56. package/dist/mcp/run-stdio.js +16 -16
  57. package/dist/{optional-cli-KWIII44P.js → optional-cli-6J6C4I3X.js} +3 -3
  58. package/dist/{optional-cli-XJE4BELL.js → optional-cli-X6I35UNI.js} +4 -4
  59. package/dist/{orchestrator-WHXHBNRS.js → orchestrator-BOLYQZO7.js} +10 -10
  60. package/dist/{orchestrator-IYXIWNB5.js → orchestrator-ZUIU667R.js} +10 -10
  61. package/dist/{thread-store-PCIMS6RA.js → thread-store-DCO5MZWJ.js} +2 -2
  62. package/dist/{thread-store-NVFWKJFH.js → thread-store-QGBPSZU2.js} +2 -2
  63. package/dist/{workspaces-ALUHOCWK.js → workspaces-VXE2MBKD.js} +4 -4
  64. package/dist/{workspaces-QGKSXA76.js → workspaces-WZZNNUJL.js} +4 -4
  65. package/dist/{worktree-6WWUWH4K.js → worktree-GWS77LWX.js} +3 -3
  66. package/dist/{worktree-N435EXSP.js → worktree-S4YOAYRA.js} +3 -3
  67. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -17,13 +17,13 @@ import {
17
17
  toAbleTimeIssueInfo,
18
18
  updateAbleTimeTask,
19
19
  verifyAbleTimeConnection
20
- } from "./chunk-YMV5O7KY.js";
20
+ } from "./chunk-FEGRY7NL.js";
21
21
  import {
22
22
  clearOptionalCliPresenceCache,
23
23
  detectOptionalServiceClis,
24
24
  installOptionalServiceCli,
25
25
  optionalCliPresence
26
- } from "./chunk-UV33UCV6.js";
26
+ } from "./chunk-FCBUDWP6.js";
27
27
  import {
28
28
  AGENT_GIT_ACTIONS,
29
29
  BOARD_COLUMN_DEFS,
@@ -219,7 +219,7 @@ import {
219
219
  worktreeCleanupSettings,
220
220
  writeAgentBlock,
221
221
  writeWorktreeFile
222
- } from "./chunk-4J7R2BFU.js";
222
+ } from "./chunk-EKI7D2AJ.js";
223
223
  import {
224
224
  OPTIONAL_SERVICES,
225
225
  OPTIONAL_SERVICE_IDS,
@@ -235,7 +235,7 @@ import {
235
235
  optionalServiceConnected,
236
236
  optionalServiceSpec,
237
237
  verifyOptionalService
238
- } from "./chunk-RCRDNOAT.js";
238
+ } from "./chunk-QWFNKOGA.js";
239
239
  import {
240
240
  LEGACY_PLAN_FILE_REL,
241
241
  PLAN_FILE_NAME,
@@ -292,7 +292,7 @@ import {
292
292
  startLinearOAuth,
293
293
  updateLinearIssue,
294
294
  validateLinearApiKey
295
- } from "./chunk-7MPRTC6X.js";
295
+ } from "./chunk-Q73I6I2K.js";
296
296
  import {
297
297
  downloadAuthenticatedFile,
298
298
  extractHttpUrls,
@@ -380,7 +380,7 @@ import {
380
380
  userMcpNamesToDisable,
381
381
  worktreeMcpToolNames,
382
382
  writeInjectedMcpConfig
383
- } from "./chunk-TLL2K2MY.js";
383
+ } from "./chunk-NB4U75TJ.js";
384
384
  import {
385
385
  getAgentSetupInfo,
386
386
  installAgent,
@@ -392,7 +392,7 @@ import {
392
392
  prepareTerminalCommand,
393
393
  resolveLoginCommand,
394
394
  whichOnPath
395
- } from "./chunk-QNKJCD7B.js";
395
+ } from "./chunk-5FGQTB2Z.js";
396
396
  import {
397
397
  brightsyMcpServerName,
398
398
  connectBrightsyTeam,
@@ -403,7 +403,7 @@ import {
403
403
  listConnectedBrightsyTeams,
404
404
  switchBrightsyAccount
405
405
  } from "./chunk-XOEKCE6L.js";
406
- import "./chunk-ZT5YPYZE.js";
406
+ import "./chunk-KAIOL2M5.js";
407
407
  import {
408
408
  BRIGHTSY_SUMMARIZE_CONTEXT_TOOL,
409
409
  CHARS_PER_CONTEXT_TOKEN,
@@ -513,7 +513,7 @@ import {
513
513
  workspaceAgentChatSummaries,
514
514
  worktreeRunPortsPath,
515
515
  wrapReviewSkillMarkdown
516
- } from "./chunk-ELDJBZ52.js";
516
+ } from "./chunk-B6TPN624.js";
517
517
  import {
518
518
  STDERR_EVENT_MAX_CHARS,
519
519
  STDOUT_EVENT_MAX_CHARS,
@@ -579,10 +579,10 @@ import {
579
579
  parseAbleTimeOAuthCallbackUrl,
580
580
  resolveAbleTimeOAuthHost,
581
581
  startAbleTimeOAuth
582
- } from "./chunk-F4OUZDIB.js";
582
+ } from "./chunk-4BRO5LNX.js";
583
583
  import {
584
584
  looksLikeAbleTimeUlid
585
- } from "./chunk-HJIA4X3L.js";
585
+ } from "./chunk-W6J3ZWLJ.js";
586
586
  import {
587
587
  ABLETIME_MCP_PATH,
588
588
  ABLETIME_MCP_PM_PATH,
@@ -603,7 +603,7 @@ import {
603
603
  normalizeAbleTimeCredential,
604
604
  normalizeAbleTimeHost,
605
605
  rewriteAbleTimeError
606
- } from "./chunk-SKPX66MO.js";
606
+ } from "./chunk-4SP26Z6H.js";
607
607
  import {
608
608
  CLOUD_COORDINATOR_BUSY_REPLY,
609
609
  CLOUD_COORDINATOR_CANCELED_REPLY,
@@ -656,7 +656,7 @@ import {
656
656
  stageBuffersAsAttachments,
657
657
  syncWorkspacesFromThreads,
658
658
  takenTeamSlugsForOrchestration
659
- } from "./chunk-LEUAYFSG.js";
659
+ } from "./chunk-CDRGQ6GX.js";
660
660
  import {
661
661
  GITHUB_PR_BODY_MAX_CHARS,
662
662
  GITHUB_PR_BODY_SAFE_CHARS,
@@ -745,7 +745,7 @@ import {
745
745
  suggestSlug,
746
746
  switchWorktreeBranch,
747
747
  warmGithubAgentAuth
748
- } from "./chunk-JJRTVB7D.js";
748
+ } from "./chunk-4OVQGZEI.js";
749
749
  import {
750
750
  FAMOUS_SOCCER_TEAMS,
751
751
  WEEKDAY_LABELS,
@@ -801,7 +801,7 @@ import {
801
801
  worktreeNameFromPath,
802
802
  worktreeSlugForTicket,
803
803
  writeThread
804
- } from "./chunk-QVLDZWHZ.js";
804
+ } from "./chunk-BDQFZAE6.js";
805
805
  import "./chunk-BMRJNRQK.js";
806
806
  import {
807
807
  BRIGHTSY_OAUTH_CLIENT_ID,
@@ -1020,6 +1020,7 @@ import {
1020
1020
  loadAppSettings,
1021
1021
  loadSecretVault,
1022
1022
  maxConcurrentAgents,
1023
+ mergeSlackClientIds,
1023
1024
  mergeUsage,
1024
1025
  nextThinkingEffort,
1025
1026
  normalizeRemoteRelayUrl,
@@ -1087,7 +1088,7 @@ import {
1087
1088
  withTurnScopedCost,
1088
1089
  writeSecureJson,
1089
1090
  writeViewerContext
1090
- } from "./chunk-EY5BJAPV.js";
1091
+ } from "./chunk-23KYDM2U.js";
1091
1092
  import {
1092
1093
  stripNestedElectronEnv
1093
1094
  } from "./chunk-4TR3HZFT.js";
@@ -3375,8 +3376,8 @@ function dispatchPhoneWorkspace(cmd, emit, publishOpened) {
3375
3376
  emit({ op: "error", chatId: cmd.chatId, message: "That agent is not on this Mac." });
3376
3377
  return;
3377
3378
  }
3378
- void readPhoneHeader(thread).then((header) => {
3379
- emit({ op: "header", chatId: cmd.chatId, ...header });
3379
+ void readPhoneHeader(thread).then((header2) => {
3380
+ emit({ op: "header", chatId: cmd.chatId, ...header2 });
3380
3381
  });
3381
3382
  return;
3382
3383
  }
@@ -4209,12 +4210,52 @@ function sourceWarning(label, err) {
4209
4210
  const message = err instanceof Error ? err.message : String(err);
4210
4211
  return message ? `${label}: ${message}` : `${label} failed.`;
4211
4212
  }
4213
+ function phonePrNumberQuery(query) {
4214
+ const match = query.trim().match(/^#?(\d+)$/);
4215
+ if (!match) return null;
4216
+ const n = Number(match[1]);
4217
+ if (!Number.isSafeInteger(n) || n <= 0) return null;
4218
+ return n;
4219
+ }
4220
+ function phonePrMatchesQuery(pr, query) {
4221
+ const raw = query.trim().toLowerCase();
4222
+ if (!raw) return true;
4223
+ const q = raw.replace(/^#/, "");
4224
+ if (!q) return pr.title.toLowerCase().includes(raw);
4225
+ return pr.title.toLowerCase().includes(q) || String(pr.number).includes(q);
4226
+ }
4227
+ function prIsListedOpen(pr) {
4228
+ const state = pr.state?.trim().toLowerCase();
4229
+ return state !== "closed" && state !== "merged";
4230
+ }
4231
+ function mergePrs(groups) {
4232
+ const out = [];
4233
+ const seen = /* @__PURE__ */ new Set();
4234
+ for (const group of groups) {
4235
+ for (const pr of group) {
4236
+ if (!pr || seen.has(pr.number) || !prIsListedOpen(pr)) continue;
4237
+ seen.add(pr.number);
4238
+ out.push(pr);
4239
+ }
4240
+ }
4241
+ return out;
4242
+ }
4243
+ async function loadPhonePrs(path2, query) {
4244
+ const number = phonePrNumberQuery(query);
4245
+ if (!query) return listPrs(path2, { state: "open", limit: 40 });
4246
+ const [searched, recent, exact] = await Promise.all([
4247
+ listPrs(path2, { state: "open", limit: 40, query: number == null ? query : String(number) }),
4248
+ listPrs(path2, { state: "open", limit: number == null ? 40 : 200 }),
4249
+ number == null ? Promise.resolve(null) : getPr(path2, number).catch(() => null)
4250
+ ]);
4251
+ return mergePrs([exact ? [exact] : [], searched, recent]).filter((pr) => phonePrMatchesQuery(pr, query));
4252
+ }
4212
4253
  async function listPhoneSources(repoPath, query) {
4213
4254
  const path2 = assertKnownProject(repoPath);
4214
4255
  const q = query?.trim() ?? "";
4215
4256
  const warnings = [];
4216
4257
  const [prs, branches, issues] = await Promise.all([
4217
- listPrs(path2, { state: "open", limit: 40, ...q ? { query: q } : {} }).catch((err) => {
4258
+ loadPhonePrs(path2, q).catch((err) => {
4218
4259
  warnings.push(sourceWarning("Pull requests", err));
4219
4260
  return [];
4220
4261
  }),
@@ -5220,26 +5261,6 @@ function slackOAuthHtmlPage(title, body) {
5220
5261
  <style>body{font-family:ui-sans-serif,system-ui,sans-serif;padding:48px 24px;max-width:36rem;margin:0 auto;color:#1a1a1a}
5221
5262
  h1{font-size:1.25rem}p{line-height:1.5;color:#444}</style></head><body>${body}</body></html>`;
5222
5263
  }
5223
- function parseSlackOAuthCallbackUrl(reqUrl) {
5224
- let url;
5225
- try {
5226
- url = new URL(reqUrl, SLACK_OAUTH_REDIRECT);
5227
- } catch {
5228
- return null;
5229
- }
5230
- if (url.pathname !== SLACK_OAUTH_CALLBACK_PATH) return null;
5231
- return url;
5232
- }
5233
- function parseSlackOAuthResultUrl(reqUrl) {
5234
- let url;
5235
- try {
5236
- url = new URL(reqUrl, SLACK_OAUTH_REDIRECT);
5237
- } catch {
5238
- return null;
5239
- }
5240
- if (url.pathname !== SLACK_OAUTH_RESULT_PATH) return null;
5241
- return url;
5242
- }
5243
5264
 
5244
5265
  // src/slack/baked-app.ts
5245
5266
  var BAKED_SLACK_CLIENT_ID = "7592788819232.11813536272562";
@@ -5321,11 +5342,15 @@ async function exchangeSlackOAuthCode(opts) {
5321
5342
  team_name: data.team?.name?.trim() || teamId,
5322
5343
  user_id: data.authed_user?.id?.trim() || void 0,
5323
5344
  bot_token: data.access_token?.trim() || void 0,
5345
+ bot_user_id: data.bot_user_id?.trim() || void 0,
5324
5346
  user_token: data.authed_user?.access_token?.trim() || void 0,
5325
5347
  scopes: [data.scope, data.authed_user?.scope].filter(Boolean).join(",")
5326
5348
  };
5327
5349
  }
5328
5350
 
5351
+ // src/slack/events-api.ts
5352
+ import { createHmac, timingSafeEqual } from "crypto";
5353
+
5329
5354
  // src/slack/socket-mode.ts
5330
5355
  import { WebSocket as WsWebSocket2 } from "ws";
5331
5356
 
@@ -5596,19 +5621,994 @@ function connectSession(ws, opts, log) {
5596
5621
  });
5597
5622
  return;
5598
5623
  }
5599
- const life = lifecycleFromSocketFrame(frame);
5600
- if (life && opts.onLifecycle) {
5601
- void Promise.resolve(opts.onLifecycle(life)).catch((err) => {
5602
- const msg = err instanceof Error ? err.message : String(err);
5603
- log(`lifecycle error: ${msg}`);
5604
- });
5605
- }
5624
+ const life = lifecycleFromSocketFrame(frame);
5625
+ if (life && opts.onLifecycle) {
5626
+ void Promise.resolve(opts.onLifecycle(life)).catch((err) => {
5627
+ const msg = err instanceof Error ? err.message : String(err);
5628
+ log(`lifecycle error: ${msg}`);
5629
+ });
5630
+ }
5631
+ });
5632
+ });
5633
+ }
5634
+
5635
+ // src/slack/events-api.ts
5636
+ var MAX_SKEW_MS = 5 * 6e4;
5637
+ function verifySlackRequestSignature(opts) {
5638
+ const timestamp = opts.timestamp.trim();
5639
+ const signature = opts.signature.trim();
5640
+ const seconds = Number(timestamp);
5641
+ if (!timestamp || !signature || !Number.isFinite(seconds)) return false;
5642
+ const now = opts.nowMs ?? Date.now();
5643
+ if (Math.abs(now - seconds * 1e3) > MAX_SKEW_MS) return false;
5644
+ const hmac = createHmac("sha256", opts.signingSecret).update(`v0:${timestamp}:${opts.rawBody}`).digest("hex");
5645
+ const expected = Buffer.from(`v0=${hmac}`);
5646
+ const presented = Buffer.from(signature);
5647
+ return expected.length === presented.length && timingSafeEqual(expected, presented);
5648
+ }
5649
+ function parseSlackEventsBody(raw) {
5650
+ try {
5651
+ const parsed = JSON.parse(raw);
5652
+ if (!parsed || typeof parsed !== "object") return null;
5653
+ return parsed;
5654
+ } catch {
5655
+ return null;
5656
+ }
5657
+ }
5658
+ function asSocketFrame(body) {
5659
+ return {
5660
+ type: "events_api",
5661
+ payload: {
5662
+ team_id: typeof body.team_id === "string" ? body.team_id : void 0,
5663
+ event: body.event
5664
+ }
5665
+ };
5666
+ }
5667
+ function inboundFromEventsBody(body) {
5668
+ if (body.type !== "event_callback") return null;
5669
+ return inboundFromSocketFrame(asSocketFrame(body));
5670
+ }
5671
+ function lifecycleFromEventsBody(body) {
5672
+ if (body.type !== "event_callback") return null;
5673
+ return lifecycleFromSocketFrame(asSocketFrame(body));
5674
+ }
5675
+ var SlackEventDeduper = class {
5676
+ constructor(ttlMs = 10 * 6e4) {
5677
+ this.ttlMs = ttlMs;
5678
+ }
5679
+ ttlMs;
5680
+ seen = /* @__PURE__ */ new Map();
5681
+ duplicate(eventId, now = Date.now()) {
5682
+ const id = eventId.trim();
5683
+ if (!id) return false;
5684
+ for (const [key, expires] of this.seen) {
5685
+ if (expires <= now) this.seen.delete(key);
5686
+ }
5687
+ if (this.seen.has(id)) return true;
5688
+ this.seen.set(id, now + this.ttlMs);
5689
+ return false;
5690
+ }
5691
+ };
5692
+
5693
+ // src/slack/secret-box.ts
5694
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes2 } from "crypto";
5695
+ var VERSION = "v1";
5696
+ function parseSlackTokenKey(raw) {
5697
+ const text5 = raw.trim();
5698
+ if (!text5) throw new Error("SIDEBOARD_SLACK_TOKEN_KEY is empty");
5699
+ const buf = /^[0-9a-fA-F]{64}$/.test(text5) ? Buffer.from(text5, "hex") : Buffer.from(text5, "base64");
5700
+ if (buf.length !== 32) {
5701
+ throw new Error("SIDEBOARD_SLACK_TOKEN_KEY must be 32 bytes (base64 or 64 hex characters)");
5702
+ }
5703
+ return buf;
5704
+ }
5705
+ function sealSecret(key, plaintext) {
5706
+ const iv = randomBytes2(12);
5707
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
5708
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
5709
+ const tag = cipher.getAuthTag();
5710
+ return [VERSION, iv.toString("base64url"), tag.toString("base64url"), ciphertext.toString("base64url")].join(
5711
+ "."
5712
+ );
5713
+ }
5714
+ function openSecret(key, sealed) {
5715
+ const [version, ivB64, tagB64, ctB64] = sealed.split(".");
5716
+ if (version !== VERSION || !ivB64 || !tagB64 || !ctB64 || sealed.split(".").length !== 4) {
5717
+ throw new Error("Slack secret ciphertext is not recognized");
5718
+ }
5719
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64url"));
5720
+ decipher.setAuthTag(Buffer.from(tagB64, "base64url"));
5721
+ return Buffer.concat([
5722
+ decipher.update(Buffer.from(ctB64, "base64url")),
5723
+ decipher.final()
5724
+ ]).toString("utf8");
5725
+ }
5726
+
5727
+ // src/slack/oauth-state.ts
5728
+ import { randomBytes as randomBytes3 } from "crypto";
5729
+ function slackOAuthState(clientId, bakedClientId) {
5730
+ const nonce = randomBytes3(16).toString("hex");
5731
+ const id = clientId.trim();
5732
+ if (!id || id === bakedClientId.trim()) return nonce;
5733
+ return `c.${Buffer.from(id, "utf8").toString("base64url")}.${nonce}`;
5734
+ }
5735
+ function clientIdFromOAuthState(state) {
5736
+ if (!state.startsWith("c.")) return null;
5737
+ const rest = state.slice(2);
5738
+ const dot = rest.lastIndexOf(".");
5739
+ if (dot <= 0) return null;
5740
+ if (!/^[0-9a-f]{32}$/.test(rest.slice(dot + 1))) return null;
5741
+ try {
5742
+ const id = Buffer.from(rest.slice(0, dot), "base64url").toString("utf8").trim();
5743
+ if (!id || id.includes("\0")) return null;
5744
+ return id;
5745
+ } catch {
5746
+ return null;
5747
+ }
5748
+ }
5749
+
5750
+ // src/slack/workspaces.ts
5751
+ import { join as join3 } from "path";
5752
+ function storePath() {
5753
+ return join3(appDataDir(), "slack-workspaces.json");
5754
+ }
5755
+ function readStore() {
5756
+ try {
5757
+ const path2 = storePath();
5758
+ const wasEncrypted = isSecureFileEncrypted(path2);
5759
+ const parsed = readSecureJson(path2);
5760
+ const workspaces = Array.isArray(parsed?.workspaces) ? parsed.workspaces : [];
5761
+ if (workspaces.length > 0 && !wasEncrypted && resolveVaultKey()) {
5762
+ writeSecureJson(path2, { workspaces });
5763
+ }
5764
+ return workspaces;
5765
+ } catch {
5766
+ return [];
5767
+ }
5768
+ }
5769
+ function writeStore(workspaces) {
5770
+ writeSecureJson(storePath(), { workspaces });
5771
+ return workspaces;
5772
+ }
5773
+ function toInfo(ws) {
5774
+ return {
5775
+ team_id: ws.team_id,
5776
+ team_name: ws.team_name,
5777
+ user_id: ws.user_id,
5778
+ has_bot_token: Boolean(ws.bot_token),
5779
+ has_user_token: Boolean(ws.user_token),
5780
+ connected_at: ws.connected_at
5781
+ };
5782
+ }
5783
+ function slackWorkspaceCanListen(ws) {
5784
+ return Boolean(
5785
+ ws.bot_token?.trim() && ws.user_id?.trim() && (ws.user_token?.trim() || ws.listen_grant?.trim())
5786
+ );
5787
+ }
5788
+ function listSlackWorkspaces() {
5789
+ return readStore().map(toInfo).sort((a, b) => a.team_name.localeCompare(b.team_name));
5790
+ }
5791
+ function listSlackWorkspacesRaw() {
5792
+ return readStore();
5793
+ }
5794
+ function getSlackWorkspace(teamId) {
5795
+ const id = teamId.trim();
5796
+ if (!id) return null;
5797
+ return readStore().find(
5798
+ (ws) => ws.team_id === id || ws.team_name.toLowerCase() === id.toLowerCase()
5799
+ ) ?? null;
5800
+ }
5801
+ function upsertSlackWorkspace(entry) {
5802
+ const workspaces = readStore().filter((ws) => ws.team_id !== entry.team_id);
5803
+ workspaces.push(entry);
5804
+ writeStore(workspaces);
5805
+ return toInfo(entry);
5806
+ }
5807
+ function disconnectSlackWorkspace(teamId) {
5808
+ const id = teamId.trim();
5809
+ writeStore(readStore().filter((ws) => ws.team_id !== id));
5810
+ return listSlackWorkspaces();
5811
+ }
5812
+ function tokenKind(token) {
5813
+ if (token.startsWith("xoxb-")) return "bot";
5814
+ if (token.startsWith("xoxp-") || token.startsWith("xoxe.xoxp-")) return "user";
5815
+ return "unknown";
5816
+ }
5817
+ async function connectSlackToken(rawToken) {
5818
+ const token = rawToken.trim();
5819
+ if (!token) throw new Error("Paste a Slack bot (xoxb-) or user (xoxp-) token");
5820
+ const auth = await slackAuthTest(token);
5821
+ const teamId = auth.team_id?.trim();
5822
+ if (!teamId) throw new Error("Slack auth.test did not return a team_id");
5823
+ const existing = getSlackWorkspace(teamId);
5824
+ const kind = tokenKind(token);
5825
+ const authUserId = auth.user_id?.trim();
5826
+ const userId = kind === "bot" ? existing?.user_id || authUserId : authUserId || existing?.user_id;
5827
+ const next = {
5828
+ team_id: teamId,
5829
+ team_name: auth.team?.trim() || existing?.team_name || teamId,
5830
+ user_id: userId,
5831
+ bot_token: kind === "bot" ? token : existing?.bot_token,
5832
+ user_token: kind === "user" || kind === "unknown" ? token : existing?.user_token,
5833
+ listen_grant: existing?.user_id && userId && existing.user_id !== userId ? void 0 : existing?.listen_grant,
5834
+ scopes: existing?.scopes,
5835
+ connected_at: existing?.connected_at || (/* @__PURE__ */ new Date()).toISOString()
5836
+ };
5837
+ if (kind === "unknown" && auth.bot_id) {
5838
+ next.bot_token = token;
5839
+ next.user_token = existing?.user_token;
5840
+ next.user_id = existing?.user_id || authUserId;
5841
+ if (existing?.user_id && next.user_id && existing.user_id !== next.user_id) {
5842
+ next.listen_grant = void 0;
5843
+ }
5844
+ }
5845
+ return upsertSlackWorkspace(next);
5846
+ }
5847
+ function slackTokenFor(ws, _kind = "read") {
5848
+ const token = (ws.bot_token || ws.user_token)?.trim();
5849
+ if (!token) {
5850
+ throw new Error(`Slack workspace ${ws.team_name} has no token`);
5851
+ }
5852
+ return token;
5853
+ }
5854
+
5855
+ // src/slack/oauth.ts
5856
+ var SLACK_BOT_SCOPES = [
5857
+ "app_mentions:read",
5858
+ "channels:history",
5859
+ "channels:read",
5860
+ "groups:history",
5861
+ "groups:read",
5862
+ "im:history",
5863
+ "im:read",
5864
+ "im:write",
5865
+ "mpim:history",
5866
+ "mpim:read",
5867
+ "chat:write",
5868
+ "chat:write.public",
5869
+ "reactions:write",
5870
+ "users:read",
5871
+ "users:read.email"
5872
+ ].join(",");
5873
+ function slackOAuthCredentials() {
5874
+ const settings = loadAppSettings();
5875
+ const clientId = process.env.SIDEBOARD_SLACK_CLIENT_ID?.trim() || settings.integrations.slackClientId?.trim() || BAKED_SLACK_CLIENT_ID.trim();
5876
+ const clientSecret = process.env.SIDEBOARD_SLACK_CLIENT_SECRET?.trim() || settings.integrations.slackClientSecret?.trim() || "";
5877
+ if (!clientId) {
5878
+ throw new Error(
5879
+ "Slack browser sign-in needs a Slack app Client ID (Settings \u2192 Collaboration, or SIDEBOARD_SLACK_CLIENT_ID). You can still paste an xoxb- or xoxp- token."
5880
+ );
5881
+ }
5882
+ return { clientId, clientSecret: clientSecret || null };
5883
+ }
5884
+ var SLACK_OAUTH_CANCELLED = "Slack sign-in cancelled";
5885
+ var SlackOAuthCancelledError = class extends Error {
5886
+ constructor(message = SLACK_OAUTH_CANCELLED) {
5887
+ super(message);
5888
+ this.name = "SlackOAuthCancelledError";
5889
+ }
5890
+ };
5891
+ function isSlackOAuthCancelled(err) {
5892
+ if (err instanceof SlackOAuthCancelledError) return true;
5893
+ const message = err instanceof Error ? err.message : String(err);
5894
+ if (message.includes(SLACK_OAUTH_CANCELLED)) return true;
5895
+ return err instanceof Error && err.name === "SlackOAuthCancelledError";
5896
+ }
5897
+ function slackOAuthAuthorizeUrl(clientId, state) {
5898
+ const params = new URLSearchParams({
5899
+ client_id: clientId,
5900
+ scope: SLACK_BOT_SCOPES,
5901
+ redirect_uri: slackOAuthRedirectUri(),
5902
+ state
5903
+ });
5904
+ return `https://slack.com/oauth/v2/authorize?${params.toString()}`;
5905
+ }
5906
+ function sleep(ms, signal) {
5907
+ return new Promise((resolve, reject) => {
5908
+ if (signal?.aborted) {
5909
+ reject(new SlackOAuthCancelledError());
5910
+ return;
5911
+ }
5912
+ const timer = setTimeout(() => {
5913
+ signal?.removeEventListener("abort", onAbort);
5914
+ resolve();
5915
+ }, ms);
5916
+ const onAbort = () => {
5917
+ clearTimeout(timer);
5918
+ reject(new SlackOAuthCancelledError());
5919
+ };
5920
+ signal?.addEventListener("abort", onAbort, { once: true });
5921
+ });
5922
+ }
5923
+ function upsertFromPayload(payload) {
5924
+ const existing = getSlackWorkspace(payload.team_id);
5925
+ return upsertSlackWorkspace({
5926
+ team_id: payload.team_id,
5927
+ team_name: payload.team_name || existing?.team_name || payload.team_id,
5928
+ user_id: payload.user_id || existing?.user_id,
5929
+ bot_token: payload.bot_token || existing?.bot_token,
5930
+ user_token: payload.user_token || existing?.user_token,
5931
+ listen_grant: payload.listen_grant || existing?.listen_grant,
5932
+ scopes: payload.scopes || existing?.scopes,
5933
+ connected_at: (/* @__PURE__ */ new Date()).toISOString()
5934
+ });
5935
+ }
5936
+ async function startSlackOAuth(opts) {
5937
+ if (opts?.signal?.aborted) {
5938
+ throw new SlackOAuthCancelledError();
5939
+ }
5940
+ const clientId = opts?.clientId?.trim() || slackOAuthCredentials().clientId;
5941
+ const state = slackOAuthState(clientId, BAKED_SLACK_CLIENT_ID);
5942
+ const authorizeUrl = slackOAuthAuthorizeUrl(clientId, state);
5943
+ const timeoutMs = opts?.timeoutMs ?? 5 * 6e4;
5944
+ const pollIntervalMs = opts?.pollIntervalMs ?? 400;
5945
+ const fetchImpl = opts?.fetchImpl ?? fetch;
5946
+ const resultUrl = opts?.resultUrlForState?.(state) ?? slackOAuthResultUrl(state);
5947
+ await Promise.resolve(opts?.openUrl?.(authorizeUrl));
5948
+ if (opts?.signal?.aborted) {
5949
+ throw new SlackOAuthCancelledError();
5950
+ }
5951
+ const deadline = Date.now() + timeoutMs;
5952
+ while (Date.now() < deadline) {
5953
+ if (opts?.signal?.aborted) {
5954
+ throw new SlackOAuthCancelledError();
5955
+ }
5956
+ let res;
5957
+ try {
5958
+ res = await fetchImpl(resultUrl);
5959
+ } catch {
5960
+ if (opts?.signal?.aborted) throw new SlackOAuthCancelledError();
5961
+ await sleep(pollIntervalMs, opts?.signal);
5962
+ continue;
5963
+ }
5964
+ let data;
5965
+ try {
5966
+ data = await res.json();
5967
+ } catch {
5968
+ await sleep(pollIntervalMs, opts?.signal);
5969
+ continue;
5970
+ }
5971
+ if (data.ok && data.team_id?.trim()) {
5972
+ return upsertFromPayload({
5973
+ team_id: data.team_id.trim(),
5974
+ team_name: data.team_name?.trim() || data.team_id.trim(),
5975
+ user_id: data.user_id?.trim() || void 0,
5976
+ bot_token: data.bot_token?.trim() || void 0,
5977
+ user_token: data.user_token?.trim() || void 0,
5978
+ listen_grant: data.listen_grant?.trim() || void 0,
5979
+ scopes: data.scopes?.trim() || ""
5980
+ });
5981
+ }
5982
+ const err = data.error?.trim();
5983
+ if (err && err !== "pending") {
5984
+ if (/cancel/i.test(err) || /access_denied/i.test(err)) {
5985
+ throw new SlackOAuthCancelledError(`Slack OAuth: ${err}`);
5986
+ }
5987
+ throw new Error(err.startsWith("Slack") ? err : `Slack OAuth: ${err}`);
5988
+ }
5989
+ await sleep(pollIntervalMs, opts?.signal);
5990
+ }
5991
+ throw new Error("Slack sign-in timed out \u2014 try again");
5992
+ }
5993
+
5994
+ // src/slack/org-manifest.ts
5995
+ var BOT_EVENTS = [
5996
+ "app_home_opened",
5997
+ "app_mention",
5998
+ "app_uninstalled",
5999
+ "message.im",
6000
+ "message.mpim"
6001
+ ];
6002
+ function yamlList(scopes, indent) {
6003
+ return scopes.split(",").map((scope) => scope.trim()).filter(Boolean).map((scope) => `${indent}- ${scope}`).join("\n");
6004
+ }
6005
+ function slackOrgManifest(opts) {
6006
+ const eventsUrl = opts.eventsUrl.trim();
6007
+ const redirectUrl = opts.redirectUrl.trim();
6008
+ return `display_information:
6009
+ name: Sideboard
6010
+ description: Drive Sideboard agents from Slack DMs and @mentions.
6011
+ background_color: "#111827"
6012
+ long_description: >-
6013
+ Sideboard sends DMs and @mentions to the orchestrator on a Mac in this
6014
+ workspace and posts replies back in thread. Agents can list, read, and
6015
+ post in Slack. Message text is not used to train models.
6016
+
6017
+ features:
6018
+ app_home:
6019
+ home_tab_enabled: true
6020
+ messages_tab_enabled: true
6021
+ messages_tab_read_only_enabled: false
6022
+ bot_user:
6023
+ display_name: Sideboard
6024
+ always_online: true
6025
+
6026
+ oauth_config:
6027
+ redirect_urls:
6028
+ - ${redirectUrl}
6029
+ scopes:
6030
+ bot:
6031
+ ${yamlList(SLACK_BOT_SCOPES, " ")}
6032
+
6033
+ settings:
6034
+ org_deploy_enabled: false
6035
+ socket_mode_enabled: false
6036
+ token_rotation_enabled: false
6037
+ event_subscriptions:
6038
+ request_url: ${eventsUrl}
6039
+ bot_events:
6040
+ ${BOT_EVENTS.map((event) => ` - ${event}`).join("\n")}
6041
+ `;
6042
+ }
6043
+ function slackEventsPath(registrationId) {
6044
+ return `/slack/events/${registrationId}`;
6045
+ }
6046
+ function slackEventsUrl(origin, registrationId) {
6047
+ return `${origin.replace(/\/$/, "")}${slackEventsPath(registrationId)}`;
6048
+ }
6049
+
6050
+ // src/relay/slack-http.ts
6051
+ var EVENTS_PREFIX = "/slack/events/";
6052
+ var APPS_PATH = "/slack/apps";
6053
+ var BODY_LIMIT = 262144;
6054
+ async function handleSlackHttp(ctx) {
6055
+ const url = parseUrl(ctx.reqUrl);
6056
+ if (!url) return false;
6057
+ const path2 = url.pathname;
6058
+ if (path2 === "/slack/callback") return handleCallback(ctx, url);
6059
+ if (path2 === "/slack/oauth/result") return handleResult(ctx, url);
6060
+ if (path2 === APPS_PATH && ctx.req.method === "POST") {
6061
+ await handleCreate(ctx);
6062
+ return true;
6063
+ }
6064
+ const creds = path2.match(/^\/slack\/apps\/([A-Za-z0-9_-]+)\/credentials$/);
6065
+ if (creds && ctx.req.method === "POST") {
6066
+ await handleCredentials(ctx, creds[1]);
6067
+ return true;
6068
+ }
6069
+ if (path2.startsWith(EVENTS_PREFIX) && ctx.req.method === "POST") {
6070
+ await handleEvents(ctx, decodeURIComponent(path2.slice(EVENTS_PREFIX.length)));
6071
+ return true;
6072
+ }
6073
+ return false;
6074
+ }
6075
+ function parseUrl(reqUrl) {
6076
+ try {
6077
+ return new URL(reqUrl, "http://127.0.0.1");
6078
+ } catch {
6079
+ return null;
6080
+ }
6081
+ }
6082
+ async function handleCreate(ctx) {
6083
+ if (!ctx.accounts || !ctx.apps) {
6084
+ sendJson(ctx.res, 503, {
6085
+ ok: false,
6086
+ error: "Per-company Slack apps need SIDEBOARD_SLACK_TOKEN_KEY and the relay account database"
6087
+ });
6088
+ return;
6089
+ }
6090
+ const accountId = ctx.accounts.verifyCredential(bearer(ctx.req));
6091
+ if (!accountId) {
6092
+ sendJson(ctx.res, 401, { ok: false, error: "Sign in to the relay before creating a Slack app" });
6093
+ return;
6094
+ }
6095
+ const created = ctx.apps.create(accountId);
6096
+ const eventsUrl = slackEventsUrl(ctx.publicOrigin, created.registrationId);
6097
+ sendJson(ctx.res, 200, {
6098
+ ok: true,
6099
+ registrationId: created.registrationId,
6100
+ writeToken: created.writeToken,
6101
+ eventsUrl,
6102
+ manifest: slackOrgManifest({ eventsUrl, redirectUrl: ctx.redirectUri })
6103
+ });
6104
+ }
6105
+ async function handleCredentials(ctx, registrationId) {
6106
+ if (!ctx.apps) {
6107
+ sendJson(ctx.res, 503, { ok: false, error: "Per-company Slack apps are off on this relay" });
6108
+ return;
6109
+ }
6110
+ const body = await readJson(ctx.req);
6111
+ const writeToken = stringField(body, "writeToken");
6112
+ const clientId = stringField(body, "clientId");
6113
+ const clientSecret = stringField(body, "clientSecret");
6114
+ const signingSecret = stringField(body, "signingSecret");
6115
+ try {
6116
+ ctx.apps.saveCredentials(registrationId, writeToken, { clientId, clientSecret, signingSecret });
6117
+ } catch (err) {
6118
+ const message = err instanceof Error ? err.message : String(err);
6119
+ sendJson(ctx.res, 400, { ok: false, error: message });
6120
+ return;
6121
+ }
6122
+ sendJson(ctx.res, 200, { ok: true });
6123
+ }
6124
+ async function handleEvents(ctx, registrationId) {
6125
+ if (!ctx.apps) {
6126
+ sendJson(ctx.res, 503, { ok: false, error: "Per-company Slack apps are off on this relay" });
6127
+ return;
6128
+ }
6129
+ const app = ctx.apps.getByRegistration(registrationId);
6130
+ if (!app) {
6131
+ sendJson(ctx.res, 404, { ok: false, error: "Unknown Slack app" });
6132
+ return;
6133
+ }
6134
+ const raw = await readBody(ctx.req);
6135
+ const body = parseSlackEventsBody(raw);
6136
+ if (!body) {
6137
+ sendJson(ctx.res, 400, { ok: false, error: "Invalid JSON" });
6138
+ return;
6139
+ }
6140
+ if (body.type === "url_verification") {
6141
+ if (app.signingSecret && !signed(ctx, app.signingSecret, raw)) {
6142
+ sendJson(ctx.res, 401, { ok: false, error: "Bad signature" });
6143
+ return;
6144
+ }
6145
+ const challenge = typeof body.challenge === "string" ? body.challenge : "";
6146
+ sendJson(ctx.res, 200, { challenge });
6147
+ return;
6148
+ }
6149
+ if (body.type !== "event_callback") {
6150
+ sendJson(ctx.res, 200, { ok: true });
6151
+ return;
6152
+ }
6153
+ if (!app.signingSecret || !signed(ctx, app.signingSecret, raw)) {
6154
+ sendJson(ctx.res, 401, { ok: false, error: "Bad signature" });
6155
+ return;
6156
+ }
6157
+ const teamId = typeof body.team_id === "string" ? body.team_id.trim() : "";
6158
+ if (app.teamId && teamId && teamId !== app.teamId) {
6159
+ sendJson(ctx.res, 401, { ok: false, error: "Slack team does not match this app" });
6160
+ return;
6161
+ }
6162
+ const eventId = typeof body.event_id === "string" ? body.event_id : "";
6163
+ if (ctx.dedupe.duplicate(eventId)) {
6164
+ sendJson(ctx.res, 200, { ok: true });
6165
+ return;
6166
+ }
6167
+ sendJson(ctx.res, 200, { ok: true });
6168
+ if (!app.teamId) {
6169
+ ctx.log(`slack event ${eventId || "?"} before install for ${registrationId}`);
6170
+ return;
6171
+ }
6172
+ const life = lifecycleFromEventsBody(body);
6173
+ if (life?.kind === "app_uninstalled") {
6174
+ ctx.apps.clearInstall(life.teamId);
6175
+ ctx.grants.revokeTeam(life.teamId);
6176
+ ctx.hub.uninstallTeam(life.teamId);
6177
+ return;
6178
+ }
6179
+ if (life?.kind === "app_home_opened") {
6180
+ void ctx.hub.handleAppHomeOpened(life.teamId, life.userId);
6181
+ return;
6182
+ }
6183
+ const inbound = inboundFromEventsBody(body);
6184
+ if (inbound) ctx.hub.routeEvent(inbound);
6185
+ }
6186
+ function signed(ctx, signingSecret, raw) {
6187
+ const timestamp = header(ctx.req, "x-slack-request-timestamp");
6188
+ const signature = header(ctx.req, "x-slack-signature");
6189
+ return verifySlackRequestSignature({ signingSecret, timestamp, rawBody: raw, signature });
6190
+ }
6191
+ async function handleCallback(ctx, url) {
6192
+ const error = url.searchParams.get("error")?.trim();
6193
+ const state = url.searchParams.get("state")?.trim() ?? "";
6194
+ const code = url.searchParams.get("code")?.trim() ?? "";
6195
+ if (error) {
6196
+ if (state) ctx.pending.put(state, { ok: false, error: `Slack OAuth: ${error}` });
6197
+ sendHtml(ctx.res, 400, "Slack", `<h1>Authorization cancelled</h1><p>${escapeHtml(error)}</p>`);
6198
+ return true;
6199
+ }
6200
+ if (!state || !code) {
6201
+ sendHtml(ctx.res, 400, "Slack", "<h1>Invalid callback</h1><p>State or code missing.</p>");
6202
+ return true;
6203
+ }
6204
+ try {
6205
+ const creds = resolveOAuthClient(ctx, state);
6206
+ const payload = await exchangeSlackOAuthCode({
6207
+ clientId: creds.clientId,
6208
+ clientSecret: creds.clientSecret,
6209
+ code,
6210
+ redirectUri: ctx.redirectUri,
6211
+ fetchImpl: ctx.fetchImpl
6212
+ });
6213
+ if (ctx.apps && payload.bot_token) {
6214
+ ctx.apps.recordInstall({
6215
+ clientId: creds.clientId,
6216
+ teamId: payload.team_id,
6217
+ botToken: payload.bot_token,
6218
+ botUserId: payload.bot_user_id ?? ""
6219
+ });
6220
+ }
6221
+ const listenGrant = payload.user_id ? ctx.grants.issue(payload.team_id, payload.user_id) : null;
6222
+ ctx.pending.put(state, {
6223
+ ok: true,
6224
+ payload: publicPayload({
6225
+ ...payload,
6226
+ ...listenGrant ? { listen_grant: listenGrant } : {}
6227
+ })
6228
+ });
6229
+ if (payload.bot_token) {
6230
+ ctx.hub.rememberBot(payload.team_id, payload.bot_token);
6231
+ if (payload.user_id) void ctx.hub.handleAppHomeOpened(payload.team_id, payload.user_id);
6232
+ }
6233
+ sendHtml(
6234
+ ctx.res,
6235
+ 200,
6236
+ "Slack connected",
6237
+ "<h1>Slack workspace connected</h1><p>Open <strong>Sideboard \u2192 Settings \u2192 Collaboration</strong>. Confirm Relay connected on Settings \u2192 Remote, name this Mac, then DM @Sideboard.</p>"
6238
+ );
6239
+ } catch (err) {
6240
+ const message = err instanceof Error ? err.message : String(err);
6241
+ ctx.pending.put(state, { ok: false, error: message });
6242
+ sendHtml(ctx.res, 400, "Slack", `<h1>Could not connect Slack</h1><p>${escapeHtml(message)}</p>`);
6243
+ }
6244
+ return true;
6245
+ }
6246
+ function resolveOAuthClient(ctx, state) {
6247
+ const fromState = clientIdFromOAuthState(state);
6248
+ if (!fromState) {
6249
+ if (!ctx.bakedClientSecret) throw new Error("Relay is missing SIDEBOARD_SLACK_CLIENT_SECRET");
6250
+ return { clientId: ctx.bakedClientId, clientSecret: ctx.bakedClientSecret };
6251
+ }
6252
+ const secret = ctx.apps?.clientSecretFor(fromState);
6253
+ if (!secret) throw new Error("This Slack app is not registered on the relay");
6254
+ return { clientId: fromState, clientSecret: secret };
6255
+ }
6256
+ function publicPayload(payload) {
6257
+ return {
6258
+ team_id: payload.team_id,
6259
+ team_name: payload.team_name,
6260
+ user_id: payload.user_id,
6261
+ bot_token: payload.bot_token,
6262
+ user_token: payload.user_token,
6263
+ listen_grant: payload.listen_grant,
6264
+ scopes: payload.scopes
6265
+ };
6266
+ }
6267
+ function handleResult(ctx, url) {
6268
+ const state = url.searchParams.get("state")?.trim() ?? "";
6269
+ const value = ctx.pending.take(state);
6270
+ if (!value) {
6271
+ sendJson(ctx.res, 404, { ok: false, error: "pending" });
6272
+ return true;
6273
+ }
6274
+ if (!value.ok) {
6275
+ sendJson(ctx.res, 400, { ok: false, error: value.error });
6276
+ return true;
6277
+ }
6278
+ sendJson(ctx.res, 200, { ok: true, ...value.payload });
6279
+ return true;
6280
+ }
6281
+ function bearer(req) {
6282
+ const value = header(req, "authorization");
6283
+ const match = /^Bearer\s+(\S+)/i.exec(value);
6284
+ return match?.[1]?.trim() ?? "";
6285
+ }
6286
+ function header(req, name) {
6287
+ const value = req.headers[name];
6288
+ return typeof value === "string" ? value.trim() : "";
6289
+ }
6290
+ function stringField(body, key) {
6291
+ const value = body?.[key];
6292
+ return typeof value === "string" ? value : "";
6293
+ }
6294
+ async function readJson(req) {
6295
+ const raw = await readBody(req);
6296
+ if (!raw) return null;
6297
+ try {
6298
+ const parsed = JSON.parse(raw);
6299
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
6300
+ return parsed;
6301
+ } catch {
6302
+ return null;
6303
+ }
6304
+ }
6305
+ function readBody(req) {
6306
+ return new Promise((resolve, reject) => {
6307
+ const chunks = [];
6308
+ let size = 0;
6309
+ req.on("data", (chunk) => {
6310
+ const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
6311
+ size += buf.length;
6312
+ if (size > BODY_LIMIT) {
6313
+ reject(new Error("body too large"));
6314
+ req.destroy();
6315
+ return;
6316
+ }
6317
+ chunks.push(buf);
5606
6318
  });
6319
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
6320
+ req.on("error", reject);
5607
6321
  });
5608
6322
  }
6323
+ function sendHtml(res, status, title, body) {
6324
+ res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
6325
+ res.end(slackOAuthHtmlPage(title, body));
6326
+ }
6327
+ function sendJson(res, status, body) {
6328
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
6329
+ res.end(JSON.stringify(body));
6330
+ }
6331
+
6332
+ // src/relay/slack-apps.ts
6333
+ import { createHash, randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "crypto";
6334
+ import { mkdirSync as mkdirSync2 } from "fs";
6335
+ import { createRequire } from "module";
6336
+ import { dirname, join as join4 } from "path";
6337
+ var SlackAppStore = class {
6338
+ db;
6339
+ key;
6340
+ constructor(filePath, key) {
6341
+ if (key.length !== 32) throw new Error("Slack token key must be 32 bytes");
6342
+ mkdirSync2(dirname(filePath), { recursive: true });
6343
+ this.key = key;
6344
+ this.db = openDatabase(filePath);
6345
+ this.db.exec(`
6346
+ CREATE TABLE IF NOT EXISTS slack_apps (
6347
+ registration_id TEXT PRIMARY KEY,
6348
+ account_id TEXT NOT NULL,
6349
+ write_token_hash TEXT NOT NULL,
6350
+ team_id TEXT,
6351
+ client_id TEXT,
6352
+ client_secret_enc TEXT,
6353
+ signing_secret_enc TEXT,
6354
+ bot_token_enc TEXT,
6355
+ bot_user_id TEXT,
6356
+ created_at INTEGER NOT NULL
6357
+ );
6358
+ CREATE UNIQUE INDEX IF NOT EXISTS slack_apps_client
6359
+ ON slack_apps(client_id) WHERE client_id IS NOT NULL;
6360
+ CREATE UNIQUE INDEX IF NOT EXISTS slack_apps_team
6361
+ ON slack_apps(team_id) WHERE team_id IS NOT NULL;
6362
+ `);
6363
+ }
6364
+ close() {
6365
+ this.db.close();
6366
+ }
6367
+ /** Mint a row. The write token is returned once and authorizes credential upload. */
6368
+ create(accountId) {
6369
+ const owner = accountId.trim();
6370
+ if (!owner) throw new Error("Slack app registration needs a Sideboard account");
6371
+ const registrationId = randomBytes4(16).toString("base64url");
6372
+ const writeToken = randomBytes4(32).toString("base64url");
6373
+ this.db.prepare(
6374
+ `INSERT INTO slack_apps (
6375
+ registration_id, account_id, write_token_hash, created_at
6376
+ ) VALUES (?, ?, ?, ?)`
6377
+ ).run(registrationId, owner, sha2562(writeToken), Date.now());
6378
+ return { registrationId, writeToken };
6379
+ }
6380
+ saveCredentials(registrationId, writeToken, creds) {
6381
+ const row2 = this.row(registrationId);
6382
+ if (!row2 || !sameHash(row2.write_token_hash, sha2562(writeToken.trim()))) {
6383
+ throw new Error("Slack app write token was rejected");
6384
+ }
6385
+ const clientId = creds.clientId.trim();
6386
+ const clientSecret = creds.clientSecret.trim();
6387
+ const signingSecret = creds.signingSecret.trim();
6388
+ if (!clientId || !clientSecret || !signingSecret) {
6389
+ throw new Error("Slack app credentials need a client id, client secret, and signing secret");
6390
+ }
6391
+ const taken = this.db.prepare(
6392
+ "SELECT registration_id FROM slack_apps WHERE client_id = ? AND registration_id != ?"
6393
+ ).get(clientId, row2.registration_id);
6394
+ if (taken) throw new Error("That Slack client id is already registered");
6395
+ this.db.prepare(
6396
+ `UPDATE slack_apps
6397
+ SET client_id = ?, client_secret_enc = ?, signing_secret_enc = ?
6398
+ WHERE registration_id = ?`
6399
+ ).run(clientId, sealSecret(this.key, clientSecret), sealSecret(this.key, signingSecret), row2.registration_id);
6400
+ }
6401
+ clientSecretFor(clientId) {
6402
+ const id = clientId.trim();
6403
+ if (!id) return null;
6404
+ const row2 = this.db.prepare("SELECT client_secret_enc FROM slack_apps WHERE client_id = ?").get(id);
6405
+ if (!row2?.client_secret_enc) return null;
6406
+ return openSecret(this.key, row2.client_secret_enc);
6407
+ }
6408
+ /**
6409
+ * OAuth finished for this client id. Rejects a different bot user than the
6410
+ * one already stored for the company.
6411
+ */
6412
+ recordInstall(input) {
6413
+ const clientId = input.clientId.trim();
6414
+ const teamId = input.teamId.trim();
6415
+ const botToken = input.botToken.trim();
6416
+ const botUserId = input.botUserId.trim();
6417
+ if (!clientId || !teamId || !botToken) return false;
6418
+ const row2 = this.db.prepare("SELECT registration_id, team_id, bot_user_id FROM slack_apps WHERE client_id = ?").get(clientId);
6419
+ if (!row2) return false;
6420
+ if (row2.team_id && row2.team_id !== teamId) {
6421
+ throw new Error("This Slack app is already installed on another workspace");
6422
+ }
6423
+ if (botUserId && row2.bot_user_id && row2.bot_user_id !== botUserId) {
6424
+ throw new Error("This Slack app\u2019s bot user does not match the stored install");
6425
+ }
6426
+ this.db.prepare(
6427
+ `UPDATE slack_apps
6428
+ SET team_id = ?, bot_token_enc = ?, bot_user_id = COALESCE(?, bot_user_id)
6429
+ WHERE registration_id = ?`
6430
+ ).run(teamId, sealSecret(this.key, botToken), botUserId || null, row2.registration_id);
6431
+ return true;
6432
+ }
6433
+ /** Error string when a desktop presents a different bot than the company app. */
6434
+ botUserMismatch(teamId, botUserId) {
6435
+ const row2 = this.teamRow(teamId);
6436
+ if (!row2?.bot_user_id) return null;
6437
+ if (row2.bot_user_id === botUserId.trim()) return null;
6438
+ return "This Mac\u2019s bot token is not the company\u2019s Sideboard Slack app";
6439
+ }
6440
+ /** Refresh the stored bot token after a desktop register for this team. */
6441
+ saveBot(teamId, botToken, botUserId) {
6442
+ const row2 = this.teamRow(teamId);
6443
+ const token = botToken.trim();
6444
+ const user = botUserId.trim();
6445
+ if (!row2 || !token || !user) return;
6446
+ if (row2.bot_user_id && row2.bot_user_id !== user) return;
6447
+ this.db.prepare("UPDATE slack_apps SET bot_token_enc = ?, bot_user_id = ? WHERE registration_id = ?").run(sealSecret(this.key, token), user, row2.registration_id);
6448
+ }
6449
+ getByRegistration(registrationId) {
6450
+ const row2 = this.row(registrationId);
6451
+ if (!row2) return null;
6452
+ return {
6453
+ registrationId: row2.registration_id,
6454
+ teamId: row2.team_id,
6455
+ signingSecret: row2.signing_secret_enc ? openSecret(this.key, row2.signing_secret_enc) : null
6456
+ };
6457
+ }
6458
+ listBots() {
6459
+ const rows = this.db.prepare(
6460
+ `SELECT team_id, bot_token_enc FROM slack_apps
6461
+ WHERE team_id IS NOT NULL AND bot_token_enc IS NOT NULL`
6462
+ ).all();
6463
+ return rows.map((row2) => ({
6464
+ teamId: row2.team_id,
6465
+ botToken: openSecret(this.key, row2.bot_token_enc)
6466
+ }));
6467
+ }
6468
+ /**
6469
+ * Slack removed the install. Drop the bot token and team so a reinstall can
6470
+ * record again. Keep the client id, secrets, and registration id — the events
6471
+ * URL in the Slack app is that registration id.
6472
+ */
6473
+ clearInstall(teamId) {
6474
+ const id = teamId.trim();
6475
+ if (!id) return;
6476
+ this.db.prepare(
6477
+ `UPDATE slack_apps
6478
+ SET team_id = NULL, bot_token_enc = NULL, bot_user_id = NULL
6479
+ WHERE team_id = ?`
6480
+ ).run(id);
6481
+ }
6482
+ row(registrationId) {
6483
+ const id = registrationId.trim();
6484
+ if (!id) return null;
6485
+ return this.db.prepare("SELECT * FROM slack_apps WHERE registration_id = ?").get(id) ?? null;
6486
+ }
6487
+ teamRow(teamId) {
6488
+ const id = teamId.trim();
6489
+ if (!id) return null;
6490
+ return this.db.prepare("SELECT * FROM slack_apps WHERE team_id = ?").get(id) ?? null;
6491
+ }
6492
+ };
6493
+ function sha2562(value) {
6494
+ return createHash("sha256").update(value).digest("hex");
6495
+ }
6496
+ function sameHash(stored, presented) {
6497
+ const left = Buffer.from(stored);
6498
+ const right = Buffer.from(presented);
6499
+ return left.length === right.length && timingSafeEqual2(left, right);
6500
+ }
6501
+ function thisModuleFile() {
6502
+ const cjsFile = typeof __filename !== "undefined" ? __filename : "";
6503
+ return cjsFile || process.argv[1] || join4(process.cwd(), "package.json");
6504
+ }
6505
+ function openDatabase(filePath) {
6506
+ const req = createRequire(thisModuleFile());
6507
+ const { DatabaseSync: SqliteDatabase } = req("node:sqlite");
6508
+ const db = new SqliteDatabase(filePath);
6509
+ db.exec("PRAGMA journal_mode = WAL");
6510
+ return db;
6511
+ }
6512
+
6513
+ // src/relay/slack-grants.ts
6514
+ import { randomBytes as randomBytes6 } from "crypto";
6515
+ import { mkdirSync as mkdirSync3 } from "fs";
6516
+ import { createRequire as createRequire2 } from "module";
6517
+ import { dirname as dirname2, join as join5 } from "path";
6518
+
6519
+ // src/slack/listen-grant.ts
6520
+ import { createHash as createHash2, randomBytes as randomBytes5 } from "crypto";
6521
+ var MemorySlackListenGrants = class {
6522
+ rows = /* @__PURE__ */ new Map();
6523
+ issue(teamId, userId) {
6524
+ const team = teamId.trim();
6525
+ const user = userId.trim();
6526
+ if (!team || !user) return null;
6527
+ const grant = randomBytes5(32).toString("base64url");
6528
+ this.rows.set(hashListenGrant(grant), { teamId: team, userId: user });
6529
+ return grant;
6530
+ }
6531
+ verify(teamId, userId, grant) {
6532
+ const token = grant.trim();
6533
+ if (!token) return false;
6534
+ const row2 = this.rows.get(hashListenGrant(token));
6535
+ if (!row2) return false;
6536
+ return row2.teamId === teamId.trim() && row2.userId === userId.trim();
6537
+ }
6538
+ revokeTeam(teamId) {
6539
+ const team = teamId.trim();
6540
+ if (!team) return;
6541
+ for (const [hash, row2] of this.rows) {
6542
+ if (row2.teamId === team) this.rows.delete(hash);
6543
+ }
6544
+ }
6545
+ close() {
6546
+ this.rows.clear();
6547
+ }
6548
+ };
6549
+ function hashListenGrant(grant) {
6550
+ return createHash2("sha256").update(grant.trim()).digest("hex");
6551
+ }
6552
+
6553
+ // src/relay/slack-grants.ts
6554
+ var SlackListenGrantStore = class {
6555
+ db;
6556
+ constructor(filePath) {
6557
+ mkdirSync3(dirname2(filePath), { recursive: true });
6558
+ this.db = openDatabase2(filePath);
6559
+ this.db.exec(`
6560
+ CREATE TABLE IF NOT EXISTS slack_listen_grants (
6561
+ grant_hash TEXT PRIMARY KEY,
6562
+ team_id TEXT NOT NULL,
6563
+ user_id TEXT NOT NULL,
6564
+ created_at INTEGER NOT NULL
6565
+ );
6566
+ CREATE INDEX IF NOT EXISTS slack_listen_grants_team
6567
+ ON slack_listen_grants(team_id);
6568
+ `);
6569
+ }
6570
+ close() {
6571
+ this.db.close();
6572
+ }
6573
+ issue(teamId, userId) {
6574
+ const team = teamId.trim();
6575
+ const user = userId.trim();
6576
+ if (!team || !user) return null;
6577
+ const grant = randomBytes6(32).toString("base64url");
6578
+ this.db.prepare(
6579
+ `INSERT INTO slack_listen_grants (grant_hash, team_id, user_id, created_at)
6580
+ VALUES (?, ?, ?, ?)`
6581
+ ).run(hashListenGrant(grant), team, user, Date.now());
6582
+ return grant;
6583
+ }
6584
+ verify(teamId, userId, grant) {
6585
+ const token = grant.trim();
6586
+ const team = teamId.trim();
6587
+ const user = userId.trim();
6588
+ if (!token || !team || !user) return false;
6589
+ const row2 = this.db.prepare("SELECT team_id, user_id FROM slack_listen_grants WHERE grant_hash = ?").get(hashListenGrant(token));
6590
+ return row2?.team_id === team && row2.user_id === user;
6591
+ }
6592
+ revokeTeam(teamId) {
6593
+ const team = teamId.trim();
6594
+ if (!team) return;
6595
+ this.db.prepare("DELETE FROM slack_listen_grants WHERE team_id = ?").run(team);
6596
+ }
6597
+ };
6598
+ function thisModuleFile2() {
6599
+ const cjsFile = typeof __filename !== "undefined" ? __filename : "";
6600
+ return cjsFile || process.argv[1] || join5(process.cwd(), "package.json");
6601
+ }
6602
+ function openDatabase2(filePath) {
6603
+ const req = createRequire2(thisModuleFile2());
6604
+ const { DatabaseSync: SqliteDatabase } = req("node:sqlite");
6605
+ const db = new SqliteDatabase(filePath);
6606
+ db.exec("PRAGMA journal_mode = WAL");
6607
+ return db;
6608
+ }
5609
6609
 
5610
6610
  // src/slack/relay-protocol.ts
5611
- import { randomBytes as randomBytes2 } from "crypto";
6611
+ import { randomBytes as randomBytes7 } from "crypto";
5612
6612
  var SLACK_RELAY_PING_INTERVAL_MS = 2e4;
5613
6613
  var SLACK_RELAY_PONG_TIMEOUT_MS = 15e3;
5614
6614
  function slackRelaySessionKey(teamId, userId, deviceId) {
@@ -5618,7 +6618,7 @@ function slackRelayUserKey(teamId, userId) {
5618
6618
  return `${teamId.trim()}:${userId.trim()}`;
5619
6619
  }
5620
6620
  function newSlackRelayEventId() {
5621
- return randomBytes2(12).toString("hex");
6621
+ return randomBytes7(12).toString("hex");
5622
6622
  }
5623
6623
  function parseSlackRelayClientMessage(raw) {
5624
6624
  try {
@@ -5637,7 +6637,8 @@ function parseSlackRelayClientMessage(raw) {
5637
6637
  const deviceLabel = typeof parsed.deviceLabel === "string" ? parsed.deviceLabel.trim() : void 0;
5638
6638
  const botToken = typeof parsed.botToken === "string" ? parsed.botToken.trim() : "";
5639
6639
  const userToken = typeof parsed.userToken === "string" ? parsed.userToken.trim() : "";
5640
- if (!teamId || !userId || !deviceId || !botToken || !userToken) return null;
6640
+ const listenGrant = typeof parsed.listenGrant === "string" ? parsed.listenGrant.trim() : "";
6641
+ if (!teamId || !userId || !deviceId || !botToken || !userToken && !listenGrant) return null;
5641
6642
  return {
5642
6643
  type: "register",
5643
6644
  teamId,
@@ -5645,7 +6646,8 @@ function parseSlackRelayClientMessage(raw) {
5645
6646
  deviceId,
5646
6647
  deviceLabel: deviceLabel || void 0,
5647
6648
  botToken,
5648
- userToken
6649
+ ...userToken ? { userToken } : {},
6650
+ ...listenGrant ? { listenGrant } : {}
5649
6651
  };
5650
6652
  }
5651
6653
  return null;
@@ -5696,10 +6698,10 @@ function parseSlackRelayServerMessage(raw) {
5696
6698
 
5697
6699
  // src/slack/app-home.ts
5698
6700
  var SLACK_APP_HOME_DOWNLOAD = "https://sideboard-downloads.t3.tigrisfiles.io/Sideboard-latest-arm64.dmg";
5699
- var SLACK_APP_HOME_LANDING = "https://www.sideboard.cloud/slack/";
5700
- var SLACK_APP_HOME_PRIVACY = "https://www.sideboard.cloud/privacy/";
5701
- var SLACK_APP_HOME_SUPPORT = "https://www.sideboard.cloud/support/";
5702
- var SLACK_APP_HOME_SUPPORT_EMAIL = "support@sideboard.cloud";
6701
+ var SLACK_APP_HOME_LANDING = "https://www.sideboard.build/slack/";
6702
+ var SLACK_APP_HOME_PRIVACY = "https://www.sideboard.build/privacy/";
6703
+ var SLACK_APP_HOME_SUPPORT = "https://www.sideboard.build/support/";
6704
+ var SLACK_APP_HOME_SUPPORT_EMAIL = "support@sideboard.build";
5703
6705
  var SLACK_NO_MAC_ONLINE_REPLY = [
5704
6706
  "No Sideboard Mac is online for your Slack user.",
5705
6707
  "Open Sideboard \u2192 Settings \u2192 Remote and wait for Relay connected.",
@@ -5717,7 +6719,7 @@ function slackAppHomeView(opts) {
5717
6719
  "",
5718
6720
  "*First run*",
5719
6721
  "1. Download Sideboard for Apple Silicon and keep it open.",
5720
- "2. Settings \u2192 Remote \u2192 Slack \u2192 Add via browser. Name this Mac (`Work`, `Personal`, \u2026).",
6722
+ "2. Settings \u2192 Collaboration \u2192 Add via browser. Name this Mac on Settings \u2192 Remote (`Work`, `Personal`, \u2026).",
5721
6723
  "3. Wait until status shows Relay connected, then DM @Sideboard."
5722
6724
  ].join("\n");
5723
6725
  return {
@@ -5791,11 +6793,26 @@ var SlackRelayHub = class {
5791
6793
  fetchImpl;
5792
6794
  authTest;
5793
6795
  log;
6796
+ guardBotUser = null;
6797
+ onBotAccepted = null;
6798
+ verifyListenGrant = null;
5794
6799
  constructor(opts = {}) {
5795
6800
  this.fetchImpl = opts.fetchImpl;
5796
6801
  this.log = opts.onLog ?? (() => void 0);
5797
6802
  this.authTest = opts.authTest ?? (async (token) => slackApi(token, "auth.test", void 0, this.fetchImpl));
5798
6803
  }
6804
+ /**
6805
+ * Company apps reject a bot user that is not the one stored for that team,
6806
+ * then persist a matching bot token. The baked app leaves both unset.
6807
+ */
6808
+ setBotHooks(hooks) {
6809
+ this.guardBotUser = hooks.guardBotUser ?? null;
6810
+ this.onBotAccepted = hooks.onBotAccepted ?? null;
6811
+ }
6812
+ /** Accept a relay listen grant in place of a Slack user token. */
6813
+ setListenGrantVerifier(verify2) {
6814
+ this.verifyListenGrant = verify2;
6815
+ }
5799
6816
  sessionFor(teamId, userId, deviceId) {
5800
6817
  return this.sessions.get(slackRelaySessionKey(teamId, userId, deviceId)) ?? null;
5801
6818
  }
@@ -5834,43 +6851,61 @@ var SlackRelayHub = class {
5834
6851
  msg.deviceId,
5835
6852
  msg.deviceLabel,
5836
6853
  msg.botToken,
5837
- msg.userToken
6854
+ msg.userToken ?? "",
6855
+ msg.listenGrant
5838
6856
  );
5839
6857
  }
5840
6858
  }
5841
- async register(socket, teamId, userId, deviceId, deviceLabel, botToken, userToken) {
6859
+ async register(socket, teamId, userId, deviceId, deviceLabel, botToken, userToken, listenGrant) {
5842
6860
  const claimedTeam = teamId.trim();
5843
6861
  const claimedUser = userId.trim();
5844
6862
  const claimedDevice = deviceId.trim();
5845
6863
  const label = (deviceLabel?.trim() || claimedDevice).slice(0, 64);
5846
6864
  const bot = botToken.trim();
5847
6865
  const user = userToken.trim();
5848
- if (!claimedTeam || !claimedUser || !claimedDevice || !bot || !user) {
6866
+ const grant = listenGrant?.trim() ?? "";
6867
+ let botUserId = "";
6868
+ if (!claimedTeam || !claimedUser || !claimedDevice || !bot || !user && !grant) {
5849
6869
  this.send(socket, {
5850
6870
  type: "error",
5851
- message: "register needs teamId, userId, deviceId, botToken, and userToken"
6871
+ message: "register needs teamId, userId, deviceId, botToken, and a user token or listen grant"
5852
6872
  });
5853
6873
  return;
5854
6874
  }
5855
6875
  try {
5856
- const userAuth = await this.authTest(user);
5857
- const userTeam = userAuth.team_id?.trim();
5858
- const userAuthId = userAuth.user_id?.trim();
5859
- if (!userTeam || !userAuthId) {
5860
- this.send(socket, {
5861
- type: "error",
5862
- message: "user token auth.test did not return team_id/user_id"
5863
- });
5864
- return;
6876
+ let proved = false;
6877
+ if (user) {
6878
+ try {
6879
+ const userAuth = await this.authTest(user);
6880
+ const userTeam = userAuth.team_id?.trim();
6881
+ const userAuthId = userAuth.user_id?.trim();
6882
+ if (!userTeam || !userAuthId) {
6883
+ if (!grant) {
6884
+ this.send(socket, {
6885
+ type: "error",
6886
+ message: "user token auth.test did not return team_id/user_id"
6887
+ });
6888
+ return;
6889
+ }
6890
+ } else if (userTeam !== claimedTeam || userAuthId !== claimedUser) {
6891
+ this.send(socket, {
6892
+ type: "error",
6893
+ message: `User token identity ${userTeam}/${userAuthId} does not match claimed ${claimedTeam}/${claimedUser}`
6894
+ });
6895
+ this.log(
6896
+ `register rejected: claimed ${claimedTeam}/${claimedUser} user-token ${userTeam}/${userAuthId}`
6897
+ );
6898
+ return;
6899
+ } else {
6900
+ proved = true;
6901
+ }
6902
+ } catch (err) {
6903
+ if (!grant) throw err;
6904
+ }
5865
6905
  }
5866
- if (userTeam !== claimedTeam || userAuthId !== claimedUser) {
5867
- this.send(socket, {
5868
- type: "error",
5869
- message: `User token identity ${userTeam}/${userAuthId} does not match claimed ${claimedTeam}/${claimedUser}`
5870
- });
5871
- this.log(
5872
- `register rejected: claimed ${claimedTeam}/${claimedUser} user-token ${userTeam}/${userAuthId}`
5873
- );
6906
+ if (!proved && !this.verifyListenGrant?.(claimedTeam, claimedUser, grant)) {
6907
+ this.send(socket, { type: "error", message: "listen grant was rejected" });
6908
+ this.log(`register rejected: ${claimedTeam}/${claimedUser} listen grant`);
5874
6909
  return;
5875
6910
  }
5876
6911
  const botAuth = await this.authTest(bot);
@@ -5890,6 +6925,22 @@ var SlackRelayHub = class {
5890
6925
  this.log(`register rejected: claimed team ${claimedTeam} bot ${botTeam}`);
5891
6926
  return;
5892
6927
  }
6928
+ botUserId = botAuth.user_id?.trim() ?? "";
6929
+ if (this.guardBotUser) {
6930
+ if (!botUserId) {
6931
+ this.send(socket, {
6932
+ type: "error",
6933
+ message: "bot token auth.test did not return user_id"
6934
+ });
6935
+ return;
6936
+ }
6937
+ const guard = this.guardBotUser(claimedTeam, botUserId);
6938
+ if (guard) {
6939
+ this.send(socket, { type: "error", message: guard });
6940
+ this.log(`register rejected: ${claimedTeam} bot user ${botUserId}`);
6941
+ return;
6942
+ }
6943
+ }
5893
6944
  } catch (err) {
5894
6945
  const errMsg = err instanceof Error ? err.message : String(err);
5895
6946
  this.send(socket, { type: "error", message: `auth.test failed: ${errMsg}` });
@@ -5917,6 +6968,7 @@ var SlackRelayHub = class {
5917
6968
  this.sessions.set(key, session);
5918
6969
  this.bySocket.set(socket, key);
5919
6970
  this.rememberBot(claimedTeam, bot);
6971
+ if (botUserId) this.onBotAccepted?.(claimedTeam, bot, botUserId);
5920
6972
  this.send(socket, {
5921
6973
  type: "registered",
5922
6974
  teamId: claimedTeam,
@@ -6086,6 +7138,7 @@ var TYPES = {
6086
7138
  ".svg": "image/svg+xml",
6087
7139
  ".txt": "text/plain; charset=utf-8",
6088
7140
  ".webp": "image/webp",
7141
+ ".xml": "application/xml; charset=utf-8",
6089
7142
  ".woff2": "font/woff2"
6090
7143
  };
6091
7144
  function requestHostname(req) {
@@ -6096,6 +7149,45 @@ function hostnameAllowed(host, allowed) {
6096
7149
  if (!allowed || allowed.length === 0) return true;
6097
7150
  return allowed.includes(host);
6098
7151
  }
7152
+ var CANONICAL_SITE_HOST = "www.sideboard.build";
7153
+ function isOAuthSitePath(pathname) {
7154
+ return pathname === "/oauth" || pathname.startsWith("/oauth/");
7155
+ }
7156
+ function marketingRedirectLocation(opts) {
7157
+ let pathname = "/";
7158
+ let search = "";
7159
+ try {
7160
+ const url = new URL(opts.requestUrl, "http://relay.local");
7161
+ pathname = url.pathname;
7162
+ search = url.search;
7163
+ } catch {
7164
+ return null;
7165
+ }
7166
+ const hostname2 = opts.hostname.toLowerCase();
7167
+ const canonical = opts.canonicalHost.toLowerCase();
7168
+ const staticHosts = opts.staticHosts ?? [];
7169
+ const listedSite = staticHosts.length > 0 && staticHosts.includes(hostname2);
7170
+ const listedRedirect = (opts.redirectHosts ?? []).includes(hostname2);
7171
+ const alias = hostname2 !== canonical && (listedSite || listedRedirect);
7172
+ if (alias && !isOAuthSitePath(pathname)) {
7173
+ return `https://${canonical}${pathname}${search}`;
7174
+ }
7175
+ return null;
7176
+ }
7177
+ async function directorySlashLocation(root, requestUrl) {
7178
+ let url;
7179
+ try {
7180
+ url = new URL(requestUrl, "http://relay.local");
7181
+ } catch {
7182
+ return null;
7183
+ }
7184
+ if (isOAuthSitePath(url.pathname) || url.pathname.endsWith("/")) return null;
7185
+ const candidate = resolveStaticPath(root, requestUrl);
7186
+ if (!candidate) return null;
7187
+ if (await fileSize(candidate) != null) return null;
7188
+ if (await fileSize(path.join(candidate, "index.html")) == null) return null;
7189
+ return `${url.pathname}/${url.search}`;
7190
+ }
6099
7191
  function resolveStaticPath(root, requestUrl) {
6100
7192
  let pathname;
6101
7193
  try {
@@ -6133,6 +7225,35 @@ function sendFile(req, res, file, size) {
6133
7225
  createReadStream(file).pipe(res);
6134
7226
  return true;
6135
7227
  }
7228
+ async function serveMarketingSite(req, res, opts) {
7229
+ const reqUrl = req.url || "/";
7230
+ const hostname2 = requestHostname(req);
7231
+ const canonical = opts.canonicalHost.toLowerCase();
7232
+ if (req.method === "GET" || req.method === "HEAD") {
7233
+ const location = marketingRedirectLocation({
7234
+ requestUrl: reqUrl,
7235
+ hostname: hostname2,
7236
+ canonicalHost: canonical,
7237
+ staticHosts: opts.staticHosts,
7238
+ redirectHosts: opts.redirectHosts
7239
+ });
7240
+ if (location) {
7241
+ res.writeHead(301, { Location: location });
7242
+ res.end();
7243
+ return true;
7244
+ }
7245
+ if (hostnameAllowed(hostname2, opts.staticHosts)) {
7246
+ const slash = await directorySlashLocation(opts.root, reqUrl);
7247
+ if (slash) {
7248
+ res.writeHead(301, { Location: slash });
7249
+ res.end();
7250
+ return true;
7251
+ }
7252
+ }
7253
+ }
7254
+ if (!hostnameAllowed(hostname2, opts.staticHosts)) return false;
7255
+ return tryServeStatic(req, res, opts.root);
7256
+ }
6136
7257
  async function tryServeStatic(req, res, root) {
6137
7258
  if (req.method !== "GET" && req.method !== "HEAD") return false;
6138
7259
  const candidate = resolveStaticPath(root, req.url || "/");
@@ -6146,7 +7267,7 @@ async function tryServeStatic(req, res, root) {
6146
7267
  }
6147
7268
 
6148
7269
  // src/remote/hub.ts
6149
- import { randomBytes as randomBytes3 } from "crypto";
7270
+ import { randomBytes as randomBytes8 } from "crypto";
6150
7271
  var CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
6151
7272
  var CODE_TTL_MS = 10 * 60 * 1e3;
6152
7273
  function send(socket, msg) {
@@ -6156,7 +7277,7 @@ function send(socket, msg) {
6156
7277
  }
6157
7278
  }
6158
7279
  function newCode() {
6159
- const bytes = randomBytes3(6);
7280
+ const bytes = randomBytes8(6);
6160
7281
  let code = "";
6161
7282
  for (let i = 0; i < 6; i++) code += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
6162
7283
  return code;
@@ -6427,7 +7548,7 @@ var RemoteHub = class {
6427
7548
  host.phone = null;
6428
7549
  }
6429
7550
  const created = sessionToken == null;
6430
- const token = sessionToken ?? randomBytes3(24).toString("hex");
7551
+ const token = sessionToken ?? randomBytes8(24).toString("hex");
6431
7552
  if (host.sessionToken && host.sessionToken !== token) {
6432
7553
  this.phonesByToken.delete(host.sessionToken);
6433
7554
  }
@@ -6477,32 +7598,32 @@ var RemoteHub = class {
6477
7598
  };
6478
7599
 
6479
7600
  // src/relay/accounts.ts
6480
- import { createHash, randomBytes as randomBytes4, randomUUID as randomUUID3, timingSafeEqual } from "crypto";
6481
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync } from "fs";
6482
- import { createRequire } from "module";
6483
- import { dirname, join as join3 } from "path";
7601
+ import { createHash as createHash3, randomBytes as randomBytes9, randomUUID as randomUUID3, timingSafeEqual as timingSafeEqual3 } from "crypto";
7602
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync3, realpathSync } from "fs";
7603
+ import { createRequire as createRequire3 } from "module";
7604
+ import { dirname as dirname3, join as join6 } from "path";
6484
7605
  var GITHUB_ACCOUNT_ISSUER = "https://github.com";
6485
7606
  var CURSOR_ACCOUNT_ISSUER = "https://api.cursor.com/v1/origin";
6486
7607
  var RELAY_DEVICE_CAP = 3;
6487
- function thisModuleFile() {
7608
+ function thisModuleFile3() {
6488
7609
  const cjsFile = typeof __filename !== "undefined" ? __filename : "";
6489
- return cjsFile || process.argv[1] || join3(process.cwd(), "package.json");
7610
+ return cjsFile || process.argv[1] || join6(process.cwd(), "package.json");
6490
7611
  }
6491
- function openDatabase(filePath) {
6492
- const req = createRequire(thisModuleFile());
7612
+ function openDatabase3(filePath) {
7613
+ const req = createRequire3(thisModuleFile3());
6493
7614
  const specifier = "node:sqlite";
6494
7615
  const { DatabaseSync: SqliteDatabase } = req(specifier);
6495
7616
  const db = new SqliteDatabase(filePath);
6496
7617
  db.exec("PRAGMA journal_mode = WAL");
6497
7618
  return db;
6498
7619
  }
6499
- function sha2562(value) {
6500
- return createHash("sha256").update(value).digest("hex");
7620
+ function sha2563(value) {
7621
+ return createHash3("sha256").update(value).digest("hex");
6501
7622
  }
6502
- function sameHash(a, b) {
7623
+ function sameHash2(a, b) {
6503
7624
  const left = Buffer.from(a);
6504
7625
  const right = Buffer.from(b);
6505
- return left.length === right.length && timingSafeEqual(left, right);
7626
+ return left.length === right.length && timingSafeEqual3(left, right);
6506
7627
  }
6507
7628
  function normalizeEmail(email) {
6508
7629
  const trimmed = email?.trim().toLowerCase() ?? "";
@@ -6523,7 +7644,7 @@ function assertRelayAccountsDurable(filePath) {
6523
7644
  if (process.env.SIDEBOARD_RELAY_ACCOUNTS_EPHEMERAL === "1") return;
6524
7645
  if (process.env.NODE_ENV !== "production") return;
6525
7646
  if (process.platform !== "linux") return;
6526
- const dir = realpathSync(dirname(filePath));
7647
+ const dir = realpathSync(dirname3(filePath));
6527
7648
  const mounts = readFileSync3("/proc/mounts", "utf8");
6528
7649
  const point = longestMountPoint(dir, mounts);
6529
7650
  if (point === "/") {
@@ -6535,8 +7656,8 @@ function assertRelayAccountsDurable(filePath) {
6535
7656
  var RelayAccountStore = class {
6536
7657
  db;
6537
7658
  constructor(filePath) {
6538
- mkdirSync2(dirname(filePath), { recursive: true });
6539
- this.db = openDatabase(filePath);
7659
+ mkdirSync4(dirname3(filePath), { recursive: true });
7660
+ this.db = openDatabase3(filePath);
6540
7661
  this.db.exec(`
6541
7662
  CREATE TABLE IF NOT EXISTS accounts (
6542
7663
  id TEXT PRIMARY KEY,
@@ -6625,14 +7746,14 @@ var RelayAccountStore = class {
6625
7746
  verifyCredential(token) {
6626
7747
  const trimmed = token.trim();
6627
7748
  if (!trimmed) return null;
6628
- const row2 = this.db.prepare("SELECT account_id FROM credentials WHERE token_hash = ?").get(sha2562(trimmed));
7749
+ const row2 = this.db.prepare("SELECT account_id FROM credentials WHERE token_hash = ?").get(sha2563(trimmed));
6629
7750
  return row2?.account_id ?? null;
6630
7751
  }
6631
7752
  /** Drop one Mac credential. The account and its other Macs stay. */
6632
7753
  logout(token) {
6633
7754
  const trimmed = token.trim();
6634
7755
  if (!trimmed) return;
6635
- this.db.prepare("DELETE FROM credentials WHERE token_hash = ?").run(sha2562(trimmed));
7756
+ this.db.prepare("DELETE FROM credentials WHERE token_hash = ?").run(sha2563(trimmed));
6636
7757
  }
6637
7758
  /** Delete the account and every identity, credential, and Mac bound to it. */
6638
7759
  revokeAccount(accountId) {
@@ -6670,7 +7791,7 @@ var RelayAccountStore = class {
6670
7791
  return { ok: false, message: "sign in required" };
6671
7792
  }
6672
7793
  const device = this.db.prepare("SELECT device_id, account_id, host_secret_hash FROM devices WHERE device_id = ?").get(deviceId);
6673
- const secretHash = sha2562(hostSecret);
7794
+ const secretHash = sha2563(hostSecret);
6674
7795
  if (!device) {
6675
7796
  const count = this.db.prepare("SELECT COUNT(*) AS n FROM devices WHERE account_id = ?").get(accountId);
6676
7797
  if (count.n >= account.device_cap) {
@@ -6687,7 +7808,7 @@ var RelayAccountStore = class {
6687
7808
  this.db.exec("ROLLBACK");
6688
7809
  return { ok: false, message: "This Mac is registered to another account." };
6689
7810
  }
6690
- if (!sameHash(device.host_secret_hash, secretHash)) {
7811
+ if (!sameHash2(device.host_secret_hash, secretHash)) {
6691
7812
  this.db.exec("ROLLBACK");
6692
7813
  return { ok: false, message: "host secret rejected" };
6693
7814
  }
@@ -6704,12 +7825,12 @@ var RelayAccountStore = class {
6704
7825
  const id = deviceId.trim();
6705
7826
  const token = sessionToken.trim();
6706
7827
  if (!id || !token) return;
6707
- this.db.prepare("UPDATE devices SET session_token_hash = ? WHERE device_id = ?").run(sha2562(token), id);
7828
+ this.db.prepare("UPDATE devices SET session_token_hash = ? WHERE device_id = ?").run(sha2563(token), id);
6708
7829
  }
6709
7830
  findPhoneSession(sessionToken) {
6710
7831
  const token = sessionToken.trim();
6711
7832
  if (!token) return null;
6712
- const row2 = this.db.prepare("SELECT device_id, device_label FROM devices WHERE session_token_hash = ?").get(sha2562(token));
7833
+ const row2 = this.db.prepare("SELECT device_id, device_label FROM devices WHERE session_token_hash = ?").get(sha2563(token));
6713
7834
  if (!row2) return null;
6714
7835
  return { deviceId: row2.device_id, deviceLabel: row2.device_label };
6715
7836
  }
@@ -6729,8 +7850,8 @@ var RelayAccountStore = class {
6729
7850
  ).run(issuer, subject, accountId, email, verified ? 1 : 0);
6730
7851
  }
6731
7852
  mintCredential(accountId) {
6732
- const credential = randomBytes4(32).toString("hex");
6733
- this.db.prepare("INSERT INTO credentials (token_hash, account_id, created_at) VALUES (?, ?, ?)").run(sha2562(credential), accountId, Date.now());
7853
+ const credential = randomBytes9(32).toString("hex");
7854
+ this.db.prepare("INSERT INTO credentials (token_hash, account_id, created_at) VALUES (?, ?, ?)").run(sha2563(credential), accountId, Date.now());
6734
7855
  return credential;
6735
7856
  }
6736
7857
  };
@@ -6768,8 +7889,8 @@ async function cursorIdentityFromReceipt(receipt, expected, fetchImpl, nowMs = D
6768
7889
  throw new Error("Cursor sign-in receipt was not a signed token.");
6769
7890
  }
6770
7891
  const [hSeg, pSeg, sSeg] = parts;
6771
- const header = b64urlJson(hSeg);
6772
- if (header.alg !== "EdDSA" || header.typ !== RECEIPT_TYP || typeof header.kid !== "string") {
7892
+ const header2 = b64urlJson(hSeg);
7893
+ if (header2.alg !== "EdDSA" || header2.typ !== RECEIPT_TYP || typeof header2.kid !== "string") {
6773
7894
  throw new Error("Cursor sign-in receipt was not a user confirmation.");
6774
7895
  }
6775
7896
  const payload = b64urlJson(pSeg);
@@ -6787,7 +7908,7 @@ async function cursorIdentityFromReceipt(receipt, expected, fetchImpl, nowMs = D
6787
7908
  const jwksRes = await fetchImpl(JWKS_URL);
6788
7909
  const body = await jwksRes.json();
6789
7910
  const jwk = (body.keys ?? []).find(
6790
- (key2) => key2.kid === header.kid && key2.kty === "OKP" && key2.crv === "Ed25519" && key2.x
7911
+ (key2) => key2.kid === header2.kid && key2.kty === "OKP" && key2.crv === "Ed25519" && key2.x
6791
7912
  );
6792
7913
  if (!jwk?.x) throw new Error("Cursor did not publish the key that signed this receipt.");
6793
7914
  const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: jwk.x }, format: "jwk" });
@@ -6817,7 +7938,7 @@ function cursorGitHostEntry() {
6817
7938
  }
6818
7939
 
6819
7940
  // src/relay/account-entire.ts
6820
- import { createHash as createHash2, randomBytes as randomBytes5 } from "crypto";
7941
+ import { createHash as createHash4, randomBytes as randomBytes10 } from "crypto";
6821
7942
  var ENTIRE_AUTHORIZE_ORIGIN = "https://auth.entire.io";
6822
7943
  var ENTIRE_DEFAULT_ISSUER = "https://us.auth.entire.io";
6823
7944
  var ISSUER_SUFFIX = ".auth.entire.io";
@@ -6840,10 +7961,10 @@ function entireAccountIssuer(value) {
6840
7961
  return `https://${host}`;
6841
7962
  }
6842
7963
  function newEntireCodeVerifier() {
6843
- return randomBytes5(32).toString("base64url");
7964
+ return randomBytes10(32).toString("base64url");
6844
7965
  }
6845
7966
  function entireCodeChallenge(verifier) {
6846
- return createHash2("sha256").update(verifier).digest("base64url");
7967
+ return createHash4("sha256").update(verifier).digest("base64url");
6847
7968
  }
6848
7969
  function entireAuthorizeUrl(clientId, redirectUri, state, codeChallenge) {
6849
7970
  const url = new URL("/authorize", ENTIRE_AUTHORIZE_ORIGIN);
@@ -6856,7 +7977,7 @@ function entireAuthorizeUrl(clientId, redirectUri, state, codeChallenge) {
6856
7977
  url.searchParams.set("code_challenge_method", "S256");
6857
7978
  return url.toString();
6858
7979
  }
6859
- async function readJson(res) {
7980
+ async function readJson2(res) {
6860
7981
  const text5 = await res.text();
6861
7982
  if (!text5) return {};
6862
7983
  try {
@@ -6900,13 +8021,13 @@ async function entireIdentityFromCode(client, code, redirectUri, ctx, fetchImpl)
6900
8021
  headers,
6901
8022
  body
6902
8023
  });
6903
- const token = accessToken(await readJson(tokenRes));
8024
+ const token = accessToken(await readJson2(tokenRes));
6904
8025
  const userRes = await fetchImpl(`${issuer}/userinfo`, {
6905
8026
  redirect: "error",
6906
8027
  headers: { Accept: "application/json", Authorization: `Bearer ${token}` }
6907
8028
  });
6908
8029
  if (!userRes.ok) throw new Error("Entire did not return an account.");
6909
- const user = await readJson(userRes);
8030
+ const user = await readJson2(userRes);
6910
8031
  const subject = typeof user.sub === "string" ? user.sub.trim() : "";
6911
8032
  if (!subject) throw new Error("Entire did not return an account id.");
6912
8033
  const email = typeof user.email === "string" ? user.email.trim() : "";
@@ -7009,7 +8130,7 @@ function providerOf(value) {
7009
8130
  function relayAuthorizeUrl(provider, client, redirectUri, state, ctx = EMPTY_AUTH) {
7010
8131
  return GIT_HOST_AUTH[provider].authorizeUrl(client, redirectUri, state, ctx);
7011
8132
  }
7012
- async function readJson2(res) {
8133
+ async function readJson3(res) {
7013
8134
  const text5 = await res.text();
7014
8135
  if (!text5) return {};
7015
8136
  try {
@@ -7040,17 +8161,17 @@ async function fetchGithubIdentity(client, code, redirectUri, state, fetchImpl,
7040
8161
  redirect_uri: redirectUri
7041
8162
  })
7042
8163
  });
7043
- const token = accessToken2(await readJson2(tokenRes));
8164
+ const token = accessToken2(await readJson3(tokenRes));
7044
8165
  const userRes = await fetchImpl("https://api.github.com/user", {
7045
8166
  headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "sideboard-relay" }
7046
8167
  });
7047
- const user = await readJson2(userRes);
8168
+ const user = await readJson3(userRes);
7048
8169
  const subject = typeof user.id === "number" ? String(user.id) : "";
7049
8170
  if (!subject) throw new Error("GitHub did not return an account id.");
7050
8171
  const emailRes = await fetchImpl("https://api.github.com/user/emails", {
7051
8172
  headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "sideboard-relay" }
7052
8173
  });
7053
- const emails = await readJson2(emailRes);
8174
+ const emails = await readJson3(emailRes);
7054
8175
  const list = Array.isArray(emails) ? emails : [];
7055
8176
  const primary = list.find((row2) => row2.primary === true && row2.verified === true);
7056
8177
  const anyVerified = list.find((row2) => row2.verified === true);
@@ -7061,7 +8182,7 @@ async function fetchGithubIdentity(client, code, redirectUri, state, fetchImpl,
7061
8182
  async function fetchRelayIdentity(provider, client, credential, redirectUri, state, fetchImpl, ctx = EMPTY_AUTH) {
7062
8183
  return GIT_HOST_AUTH[provider].fetchIdentity(client, credential, redirectUri, state, fetchImpl, ctx);
7063
8184
  }
7064
- async function readBody(req) {
8185
+ async function readBody2(req) {
7065
8186
  const chunks = [];
7066
8187
  let size = 0;
7067
8188
  for await (const chunk of req) {
@@ -7074,7 +8195,7 @@ async function readBody(req) {
7074
8195
  if (!text5) return {};
7075
8196
  return JSON.parse(text5);
7076
8197
  }
7077
- function sendJson(res, status, body) {
8198
+ function sendJson2(res, status, body) {
7078
8199
  res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
7079
8200
  res.end(JSON.stringify(body));
7080
8201
  }
@@ -7143,7 +8264,7 @@ function relayOAuthReturnPage(title, body) {
7143
8264
  </body>
7144
8265
  </html>`;
7145
8266
  }
7146
- function sendHtml(res, status, title, body) {
8267
+ function sendHtml2(res, status, title, body) {
7147
8268
  res.writeHead(status, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
7148
8269
  res.end(relayOAuthReturnPage(title, body));
7149
8270
  }
@@ -7157,21 +8278,21 @@ async function handleRelayAccountHttp(opts) {
7157
8278
  if (method === "POST" && path2 === REMOTE_LOGIN_PATH) {
7158
8279
  let body;
7159
8280
  try {
7160
- body = await readBody(opts.req);
8281
+ body = await readBody2(opts.req);
7161
8282
  } catch {
7162
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
8283
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
7163
8284
  return true;
7164
8285
  }
7165
8286
  const provider = providerOf(typeof body.provider === "string" ? body.provider : "");
7166
8287
  const state = typeof body.state === "string" ? body.state.trim() : "";
7167
8288
  if (!provider || !STATE_RE.test(state)) {
7168
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
8289
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
7169
8290
  return true;
7170
8291
  }
7171
8292
  const client = opts.oauth[provider];
7172
8293
  const host = provider ? GIT_HOST_AUTH[provider] : null;
7173
8294
  if (!client?.clientId || host?.requiresClientSecret && !client.clientSecret) {
7174
- sendJson(opts.res, 503, {
8295
+ sendJson2(opts.res, 503, {
7175
8296
  ok: false,
7176
8297
  error: `${GIT_HOST_AUTH[provider].label} sign-in is not configured on this relay.`
7177
8298
  });
@@ -7182,14 +8303,14 @@ async function handleRelayAccountHttp(opts) {
7182
8303
  if (linkToken) {
7183
8304
  accountId = opts.store.verifyCredential(linkToken);
7184
8305
  if (!accountId) {
7185
- sendJson(opts.res, 401, { ok: false, error: "sign in required" });
8306
+ sendJson2(opts.res, 401, { ok: false, error: "sign in required" });
7186
8307
  return true;
7187
8308
  }
7188
8309
  }
7189
8310
  const codeVerifier = provider === "entire" ? newEntireCodeVerifier() : null;
7190
8311
  const auth = { codeVerifier, issuer: null };
7191
8312
  opts.sessions.begin(state, provider, accountId, codeVerifier);
7192
- sendJson(opts.res, 200, {
8313
+ sendJson2(opts.res, 200, {
7193
8314
  ok: true,
7194
8315
  url: relayAuthorizeUrl(provider, client, redirectUri, state, auth)
7195
8316
  });
@@ -7201,20 +8322,20 @@ async function handleRelayAccountHttp(opts) {
7201
8322
  const providerError = url.searchParams.get("error")?.trim() ?? "";
7202
8323
  const pending = STATE_RE.test(state) ? opts.sessions.takeLogin(state) : null;
7203
8324
  if (!pending) {
7204
- sendHtml(opts.res, 400, "Sideboard", "<h1>Sign-in expired</h1><p>Return to Sideboard and try again.</p>");
8325
+ sendHtml2(opts.res, 400, "Sideboard", "<h1>Sign-in expired</h1><p>Return to Sideboard and try again.</p>");
7205
8326
  return true;
7206
8327
  }
7207
8328
  const credential = url.searchParams.get(GIT_HOST_AUTH[pending.provider].credentialParam)?.trim() ?? "";
7208
8329
  if (providerError || !credential) {
7209
8330
  const message = providerError || "Sign-in was cancelled.";
7210
8331
  opts.sessions.putResult(state, { ok: false, error: message });
7211
- sendHtml(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml(message)}</p>`);
8332
+ sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml(message)}</p>`);
7212
8333
  return true;
7213
8334
  }
7214
8335
  const client = opts.oauth[pending.provider];
7215
8336
  if (!client) {
7216
8337
  opts.sessions.putResult(state, { ok: false, error: "Sign-in is not configured on this relay." });
7217
- sendHtml(opts.res, 503, "Sideboard", "<h1>Sign-in is not configured</h1>");
8338
+ sendHtml2(opts.res, 503, "Sideboard", "<h1>Sign-in is not configured</h1>");
7218
8339
  return true;
7219
8340
  }
7220
8341
  try {
@@ -7227,14 +8348,14 @@ async function handleRelayAccountHttp(opts) {
7227
8348
  fetchImpl,
7228
8349
  { codeVerifier: pending.codeVerifier, issuer: url.searchParams.get("iss") }
7229
8350
  );
7230
- const signed = opts.store.signIn(identity, pending.accountId);
8351
+ const signed2 = opts.store.signIn(identity, pending.accountId);
7231
8352
  opts.sessions.putResult(state, {
7232
8353
  ok: true,
7233
- credential: signed.credential,
7234
- email: signed.email,
7235
- accountId: signed.accountId
8354
+ credential: signed2.credential,
8355
+ email: signed2.email,
8356
+ accountId: signed2.accountId
7236
8357
  });
7237
- sendHtml(
8358
+ sendHtml2(
7238
8359
  opts.res,
7239
8360
  200,
7240
8361
  "Sideboard",
@@ -7243,7 +8364,7 @@ async function handleRelayAccountHttp(opts) {
7243
8364
  } catch (err) {
7244
8365
  const message = err instanceof Error ? err.message : String(err);
7245
8366
  opts.sessions.putResult(state, { ok: false, error: message });
7246
- sendHtml(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml(message)}</p>`);
8367
+ sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml(message)}</p>`);
7247
8368
  }
7248
8369
  return true;
7249
8370
  }
@@ -7251,19 +8372,19 @@ async function handleRelayAccountHttp(opts) {
7251
8372
  const url = new URL(reqUrl, origin);
7252
8373
  const state = url.searchParams.get("state")?.trim() ?? "";
7253
8374
  if (!STATE_RE.test(state)) {
7254
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
8375
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
7255
8376
  return true;
7256
8377
  }
7257
8378
  const result = opts.sessions.takeResult(state);
7258
8379
  if (result === void 0 || result === null) {
7259
- sendJson(opts.res, 404, { ok: false, error: "pending" });
8380
+ sendJson2(opts.res, 404, { ok: false, error: "pending" });
7260
8381
  return true;
7261
8382
  }
7262
8383
  if (!result.ok) {
7263
- sendJson(opts.res, 400, { ok: false, error: result.error });
8384
+ sendJson2(opts.res, 400, { ok: false, error: result.error });
7264
8385
  return true;
7265
8386
  }
7266
- sendJson(opts.res, 200, {
8387
+ sendJson2(opts.res, 200, {
7267
8388
  ok: true,
7268
8389
  credential: result.credential,
7269
8390
  email: result.email,
@@ -7274,25 +8395,21 @@ async function handleRelayAccountHttp(opts) {
7274
8395
  if (method === "POST" && path2 === REMOTE_LOGOUT_PATH) {
7275
8396
  let body;
7276
8397
  try {
7277
- body = await readBody(opts.req);
8398
+ body = await readBody2(opts.req);
7278
8399
  } catch {
7279
- sendJson(opts.res, 400, { ok: false, error: "invalid logout request" });
8400
+ sendJson2(opts.res, 400, { ok: false, error: "invalid logout request" });
7280
8401
  return true;
7281
8402
  }
7282
8403
  const token = typeof body.accountToken === "string" ? body.accountToken : "";
7283
8404
  opts.store.logout(token);
7284
- sendJson(opts.res, 200, { ok: true });
8405
+ sendJson2(opts.res, 200, { ok: true });
7285
8406
  return true;
7286
8407
  }
7287
8408
  return false;
7288
8409
  }
7289
8410
 
7290
8411
  // src/relay/server.ts
7291
- function sendHtml2(res, status, title, body) {
7292
- res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
7293
- res.end(slackOAuthHtmlPage(title, body));
7294
- }
7295
- function sendJson2(res, status, body) {
8412
+ function sendJson3(res, status, body) {
7296
8413
  res.writeHead(status, { "Content-Type": "application/json" });
7297
8414
  res.end(JSON.stringify(body));
7298
8415
  }
@@ -7336,99 +8453,35 @@ async function startRelayServer(opts) {
7336
8453
  const accountsPath = opts.accountsPath?.trim() ?? "";
7337
8454
  if (accountsPath) assertRelayAccountsDurable(accountsPath);
7338
8455
  const accountStore = accountsPath ? new RelayAccountStore(accountsPath) : null;
8456
+ const slackTokenKey = (opts.slackTokenKey ?? process.env.SIDEBOARD_SLACK_TOKEN_KEY ?? "").trim();
8457
+ const slackApps = accountsPath && slackTokenKey ? new SlackAppStore(accountsPath, parseSlackTokenKey(slackTokenKey)) : null;
8458
+ if (slackApps) {
8459
+ for (const row2 of slackApps.listBots()) hub.rememberBot(row2.teamId, row2.botToken);
8460
+ hub.setBotHooks({
8461
+ guardBotUser: (teamId, botUserId) => slackApps.botUserMismatch(teamId, botUserId),
8462
+ onBotAccepted: (teamId, botToken, botUserId) => slackApps.saveBot(teamId, botToken, botUserId)
8463
+ });
8464
+ }
8465
+ const listenGrants = accountsPath ? new SlackListenGrantStore(accountsPath) : new MemorySlackListenGrants();
8466
+ hub.setListenGrantVerifier((teamId, userId, grant) => listenGrants.verify(teamId, userId, grant));
8467
+ const slackDedupe = new SlackEventDeduper();
7339
8468
  const accountSessions = new RelayLoginSessions();
7340
8469
  const relayOAuth = opts.relayOAuth ?? {};
7341
8470
  const authMarks = /* @__PURE__ */ new Map();
7342
8471
  const remoteByIp = /* @__PURE__ */ new Map();
7343
- let remoteSockets = 0;
7344
- const remoteHub = new RemoteHub({
7345
- authorizeHost: accountStore ? (input) => {
7346
- const decision = accountStore.authorizeHost(input);
7347
- return decision.ok ? { ok: true } : { ok: false, message: decision.message };
7348
- } : void 0,
7349
- phoneSessions: accountStore ? {
7350
- find: (sessionToken) => accountStore.findPhoneSession(sessionToken),
7351
- save: (deviceId, sessionToken) => accountStore.savePhoneSession(deviceId, sessionToken)
7352
- } : void 0,
7353
- onAuthorized: (socket) => authMarks.get(socket)?.()
7354
- });
7355
- const handleCallback = async (reqUrl, res) => {
7356
- const url2 = parseSlackOAuthCallbackUrl(reqUrl);
7357
- if (!url2) return false;
7358
- const error = url2.searchParams.get("error")?.trim();
7359
- const state = url2.searchParams.get("state")?.trim() ?? "";
7360
- const code = url2.searchParams.get("code")?.trim() ?? "";
7361
- if (error) {
7362
- if (state) pending.put(state, { ok: false, error: `Slack OAuth: ${error}` });
7363
- sendHtml2(
7364
- res,
7365
- 400,
7366
- "Slack",
7367
- `<h1>Authorization cancelled</h1><p>${escapeHtml(error)}</p>`
7368
- );
7369
- return true;
7370
- }
7371
- if (!state || !code) {
7372
- sendHtml2(res, 400, "Slack", "<h1>Invalid callback</h1><p>State or code missing.</p>");
7373
- return true;
7374
- }
7375
- if (!clientSecret) {
7376
- pending.put(state, {
7377
- ok: false,
7378
- error: "Relay is missing SIDEBOARD_SLACK_CLIENT_SECRET"
7379
- });
7380
- sendHtml2(
7381
- res,
7382
- 500,
7383
- "Slack",
7384
- "<h1>Relay misconfigured</h1><p>OAuth client secret is not set on the relay.</p>"
7385
- );
7386
- return true;
7387
- }
7388
- try {
7389
- const payload = await exchangeSlackOAuthCode({
7390
- clientId,
7391
- clientSecret,
7392
- code,
7393
- redirectUri,
7394
- fetchImpl: opts.fetchImpl
7395
- });
7396
- pending.put(state, { ok: true, payload });
7397
- if (payload.bot_token) {
7398
- hub.rememberBot(payload.team_id, payload.bot_token);
7399
- if (payload.user_id) {
7400
- void hub.handleAppHomeOpened(payload.team_id, payload.user_id);
7401
- }
7402
- }
7403
- sendHtml2(
7404
- res,
7405
- 200,
7406
- "Slack connected",
7407
- '<h1>Slack workspace connected</h1><p>Open <strong>Sideboard \u2192 Settings \u2192 Remote \u2192 Slack</strong>. Confirm Relay connected, name this Mac, then DM @Sideboard.</p><p>Need the app? <a href="https://www.sideboard.cloud/slack/">Download Sideboard</a>.</p>'
7408
- );
7409
- } catch (err) {
7410
- const message = err instanceof Error ? err.message : String(err);
7411
- pending.put(state, { ok: false, error: message });
7412
- sendHtml2(res, 400, "Slack", `<h1>Could not connect Slack</h1><p>${escapeHtml(message)}</p>`);
7413
- }
7414
- return true;
7415
- };
7416
- const handleResult = (reqUrl, res) => {
7417
- const url2 = parseSlackOAuthResultUrl(reqUrl);
7418
- if (!url2) return false;
7419
- const state = url2.searchParams.get("state")?.trim() ?? "";
7420
- const value = pending.take(state);
7421
- if (!value) {
7422
- sendJson2(res, 404, { ok: false, error: "pending" });
7423
- return true;
7424
- }
7425
- if (!value.ok) {
7426
- sendJson2(res, 400, { ok: false, error: value.error });
7427
- return true;
7428
- }
7429
- sendJson2(res, 200, { ok: true, ...value.payload });
7430
- return true;
7431
- };
8472
+ let remoteSockets = 0;
8473
+ const remoteHub = new RemoteHub({
8474
+ authorizeHost: accountStore ? (input) => {
8475
+ const decision = accountStore.authorizeHost(input);
8476
+ return decision.ok ? { ok: true } : { ok: false, message: decision.message };
8477
+ } : void 0,
8478
+ phoneSessions: accountStore ? {
8479
+ find: (sessionToken) => accountStore.findPhoneSession(sessionToken),
8480
+ save: (deviceId, sessionToken) => accountStore.savePhoneSession(deviceId, sessionToken)
8481
+ } : void 0,
8482
+ onAuthorized: (socket) => authMarks.get(socket)?.()
8483
+ });
8484
+ const publicOrigin = () => opts.relayPublicOrigin?.trim() || process.env.SIDEBOARD_RELAY_PUBLIC_ORIGIN?.trim() || `http://127.0.0.1:${boundPort}`;
7432
8485
  const httpServer = createServer((req, res) => {
7433
8486
  void (async () => {
7434
8487
  const reqUrl = req.url || "/";
@@ -7438,13 +8491,30 @@ async function startRelayServer(opts) {
7438
8491
  store: accountStore,
7439
8492
  oauth: relayOAuth,
7440
8493
  sessions: accountSessions,
7441
- publicOrigin: opts.relayPublicOrigin?.trim() || process.env.SIDEBOARD_RELAY_PUBLIC_ORIGIN?.trim() || `http://127.0.0.1:${boundPort}`,
8494
+ publicOrigin: publicOrigin(),
7442
8495
  fetchImpl: opts.fetchImpl
7443
8496
  })) {
7444
8497
  return;
7445
8498
  }
7446
- if (await handleCallback(reqUrl, res)) return;
7447
- if (handleResult(reqUrl, res)) return;
8499
+ if (await handleSlackHttp({
8500
+ req,
8501
+ res,
8502
+ reqUrl,
8503
+ accounts: accountStore,
8504
+ apps: slackApps,
8505
+ hub,
8506
+ grants: listenGrants,
8507
+ pending,
8508
+ bakedClientId: clientId,
8509
+ bakedClientSecret: clientSecret,
8510
+ redirectUri,
8511
+ publicOrigin: publicOrigin(),
8512
+ fetchImpl: opts.fetchImpl,
8513
+ dedupe: slackDedupe,
8514
+ log
8515
+ })) {
8516
+ return;
8517
+ }
7448
8518
  const ableTimeBounce = ableTimeOAuthLocalBounceUrl(reqUrl);
7449
8519
  if (ableTimeBounce && (req.method === "GET" || req.method === "HEAD")) {
7450
8520
  res.writeHead(200, {
@@ -7456,7 +8526,7 @@ async function startRelayServer(opts) {
7456
8526
  return;
7457
8527
  }
7458
8528
  if (req.url === "/health") {
7459
- sendJson2(res, 200, {
8529
+ sendJson3(res, 200, {
7460
8530
  ok: true,
7461
8531
  service: "sideboard-relay",
7462
8532
  sessions: hub.listSessions().length,
@@ -7464,20 +8534,16 @@ async function startRelayServer(opts) {
7464
8534
  });
7465
8535
  return;
7466
8536
  }
7467
- const hostname2 = requestHostname(req);
7468
- const canonical = (opts.canonicalSiteHost ?? "www.sideboard.cloud").toLowerCase();
7469
- const staticHosts = opts.staticHosts ?? [];
7470
- const servesSite = staticHosts.length > 0 && staticHosts.includes(hostname2);
7471
- if (opts.redirectHosts?.includes(hostname2) && hostname2 !== canonical && !servesSite) {
7472
- res.writeHead(301, { Location: `https://${canonical}${reqUrl}` });
7473
- res.end();
7474
- return;
7475
- }
7476
- if (opts.staticRoot && hostnameAllowed(hostname2, opts.staticHosts) && await tryServeStatic(req, res, opts.staticRoot)) {
8537
+ if (opts.staticRoot && await serveMarketingSite(req, res, {
8538
+ root: opts.staticRoot,
8539
+ canonicalHost: opts.canonicalSiteHost ?? CANONICAL_SITE_HOST,
8540
+ staticHosts: opts.staticHosts,
8541
+ redirectHosts: opts.redirectHosts
8542
+ })) {
7477
8543
  return;
7478
8544
  }
7479
8545
  if (req.url === "/") {
7480
- sendJson2(res, 200, {
8546
+ sendJson3(res, 200, {
7481
8547
  ok: true,
7482
8548
  service: "sideboard-relay",
7483
8549
  sessions: hub.listSessions().length,
@@ -7617,6 +8683,7 @@ async function startRelayServer(opts) {
7617
8683
  void hub.handleAppHomeOpened(event.teamId, event.userId);
7618
8684
  return;
7619
8685
  }
8686
+ listenGrants.revokeTeam(event.teamId);
7620
8687
  hub.uninstallTeam(event.teamId);
7621
8688
  }
7622
8689
  }).catch((err) => {
@@ -7641,6 +8708,8 @@ async function startRelayServer(opts) {
7641
8708
  httpServer.close((err) => err ? reject(err) : resolve());
7642
8709
  });
7643
8710
  await socketModeDone.catch(() => void 0);
8711
+ slackApps?.close();
8712
+ listenGrants.close();
7644
8713
  accountStore?.close();
7645
8714
  }
7646
8715
  };
@@ -7697,7 +8766,7 @@ async function startHeadlessHost(opts) {
7697
8766
  };
7698
8767
  const refreshRunning = async () => {
7699
8768
  try {
7700
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-IYXIWNB5.js");
8769
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
7701
8770
  agentsRunning = getOrchestrator2().getRuntime().running;
7702
8771
  } catch {
7703
8772
  agentsRunning = 0;
@@ -9848,7 +10917,7 @@ async function handleJobStop(params, _ctx) {
9848
10917
  return stopDetachedJob(jobCwd(rec), id, reason ? { reason } : void 0);
9849
10918
  }
9850
10919
  async function defaultTurnWait(ref, timeoutMs) {
9851
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-IYXIWNB5.js");
10920
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
9852
10921
  const orch = getOrchestrator2();
9853
10922
  const thread = await orch.waitForTurn(ref, timeoutMs, {
9854
10923
  resolveIfStillRunning: true
@@ -9910,32 +10979,32 @@ function createAgentRpcDispatcher() {
9910
10979
  }
9911
10980
 
9912
10981
  // src/board/load-home-board.ts
9913
- import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync5, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "fs";
9914
- import { join as join5 } from "path";
10982
+ import { existsSync as existsSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync5, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "fs";
10983
+ import { join as join8 } from "path";
9915
10984
 
9916
10985
  // src/board/board-pins.ts
9917
10986
  import { randomUUID as randomUUID6 } from "crypto";
9918
- import { existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, unlinkSync as unlinkSync2, writeFileSync } from "fs";
9919
- import { join as join4 } from "path";
10987
+ import { existsSync as existsSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync4, unlinkSync as unlinkSync2, writeFileSync } from "fs";
10988
+ import { join as join7 } from "path";
9920
10989
  var FILE = "home-board-pins.json";
9921
- var VERSION = 1;
10990
+ var VERSION2 = 1;
9922
10991
  function pinsFile() {
9923
- return join4(appDataDir(), FILE);
10992
+ return join7(appDataDir(), FILE);
9924
10993
  }
9925
10994
  function readDisk() {
9926
10995
  const path2 = pinsFile();
9927
10996
  if (!existsSync2(path2)) return [];
9928
10997
  try {
9929
10998
  const raw = JSON.parse(readFileSync4(path2, "utf8"));
9930
- if (raw?.version !== VERSION || !Array.isArray(raw.items)) return [];
10999
+ if (raw?.version !== VERSION2 || !Array.isArray(raw.items)) return [];
9931
11000
  return raw.items.filter((item) => item?.id && item.kind && item.ref);
9932
11001
  } catch {
9933
11002
  return [];
9934
11003
  }
9935
11004
  }
9936
11005
  function writeDisk(items) {
9937
- mkdirSync3(appDataDir(), { recursive: true });
9938
- writeFileSync(pinsFile(), JSON.stringify({ version: VERSION, items }, null, 2), "utf8");
11006
+ mkdirSync5(appDataDir(), { recursive: true });
11007
+ writeFileSync(pinsFile(), JSON.stringify({ version: VERSION2, items }, null, 2), "utf8");
9939
11008
  }
9940
11009
  function listBoardPins() {
9941
11010
  return readDisk();
@@ -10003,7 +11072,7 @@ function homeBoardWorkspaceKey(workspaces) {
10003
11072
  return workspaces.map((w) => w.path).filter(Boolean).sort().join("\n");
10004
11073
  }
10005
11074
  function cacheFile() {
10006
- return join5(appDataDir(), "home-board-cache.json");
11075
+ return join8(appDataDir(), "home-board-cache.json");
10007
11076
  }
10008
11077
  function emptyInputs() {
10009
11078
  return {
@@ -10045,7 +11114,7 @@ function readDiskCache() {
10045
11114
  }
10046
11115
  function writeDiskCache(entry) {
10047
11116
  try {
10048
- mkdirSync4(appDataDir(), { recursive: true });
11117
+ mkdirSync6(appDataDir(), { recursive: true });
10049
11118
  writeFileSync2(cacheFile(), JSON.stringify(entry), "utf8");
10050
11119
  } catch {
10051
11120
  }
@@ -10201,7 +11270,7 @@ async function startMcpServer() {
10201
11270
  );
10202
11271
  }
10203
11272
  try {
10204
- const { maxConcurrentAgents: maxConcurrentAgents2 } = await import("./app-settings-JAEV53LB.js");
11273
+ const { maxConcurrentAgents: maxConcurrentAgents2 } = await import("./app-settings-KOSVLMO5.js");
10205
11274
  orch.setMaxConcurrent(maxConcurrentAgents2());
10206
11275
  } catch {
10207
11276
  }
@@ -10749,7 +11818,7 @@ async function startMcpServer() {
10749
11818
  if (!worktreeProfile) {
10750
11819
  registerConnectedIssueVendorTools(server);
10751
11820
  const { getCaffeinateHold: getCaffeinateHold2, setCaffeinateHold: setCaffeinateHold2 } = await import("./caffeinate-hold-ZNUEZGHB.js");
10752
- const { resolveNewThreadOptions: resolveNewThreadOptions2, resolveThreadDefaults: resolveThreadDefaults2 } = await import("./app-settings-JAEV53LB.js");
11821
+ const { resolveNewThreadOptions: resolveNewThreadOptions2, resolveThreadDefaults: resolveThreadDefaults2 } = await import("./app-settings-KOSVLMO5.js");
10753
11822
  const accountDefaults = resolveThreadDefaults2();
10754
11823
  const accountDefaultsHint = `Account defaults: agent=${accountDefaults.agent}, model=${accountDefaults.model?.trim() || "Auto"}, effort=${accountDefaults.effort}`;
10755
11824
  server.tool(
@@ -11433,14 +12502,14 @@ async function startMcpServer() {
11433
12502
  }
11434
12503
 
11435
12504
  // src/agent-rpc/server.ts
11436
- import { randomBytes as randomBytes6, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual2 } from "crypto";
12505
+ import { randomBytes as randomBytes11, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual4 } from "crypto";
11437
12506
  import { createServer as createServer2 } from "http";
11438
12507
  import { WebSocketServer as WebSocketServer2 } from "ws";
11439
12508
  function tokensEqual(a, b) {
11440
12509
  const left = Buffer.from(a);
11441
12510
  const right = Buffer.from(b);
11442
12511
  if (left.length !== right.length) return false;
11443
- return timingSafeEqual2(left, right);
12512
+ return timingSafeEqual4(left, right);
11444
12513
  }
11445
12514
  function authTokenFromUpgrade(req) {
11446
12515
  try {
@@ -11450,7 +12519,7 @@ function authTokenFromUpgrade(req) {
11450
12519
  return "";
11451
12520
  }
11452
12521
  }
11453
- function sendJson3(ws, value) {
12522
+ function sendJson4(ws, value) {
11454
12523
  if (ws.readyState !== ws.OPEN) return;
11455
12524
  ws.send(JSON.stringify(value));
11456
12525
  }
@@ -11473,7 +12542,7 @@ var AgentRpcServer = class {
11473
12542
  async listen(opts = {}) {
11474
12543
  const host = opts.host ?? "127.0.0.1";
11475
12544
  const port = opts.port ?? 0;
11476
- const authToken = randomBytes6(24).toString("base64url");
12545
+ const authToken = randomBytes11(24).toString("base64url");
11477
12546
  this.meta = {
11478
12547
  runtimeId: randomUUID8(),
11479
12548
  pid: process.pid,
@@ -11535,36 +12604,36 @@ var AgentRpcServer = class {
11535
12604
  async onMessage(ws, raw) {
11536
12605
  const parsed = parseRpcFrame(raw);
11537
12606
  if (parsed === void 0) {
11538
- sendJson3(ws, rpcError(null, RPC_PARSE_ERROR, "Parse error"));
12607
+ sendJson4(ws, rpcError(null, RPC_PARSE_ERROR, "Parse error"));
11539
12608
  return;
11540
12609
  }
11541
12610
  if (!isJsonRpcRequest(parsed)) {
11542
- sendJson3(ws, rpcError(null, RPC_INVALID_REQUEST, "Invalid request"));
12611
+ sendJson4(ws, rpcError(null, RPC_INVALID_REQUEST, "Invalid request"));
11543
12612
  return;
11544
12613
  }
11545
12614
  const id = parsed.id;
11546
12615
  const expected = this.meta?.authToken ?? "";
11547
12616
  const got = typeof parsed.authToken === "string" ? parsed.authToken : "";
11548
12617
  if (!expected || !got || !tokensEqual(got, expected)) {
11549
- sendJson3(ws, rpcError(id, RPC_UNAUTHORIZED, "Unauthorized"));
12618
+ sendJson4(ws, rpcError(id, RPC_UNAUTHORIZED, "Unauthorized"));
11550
12619
  return;
11551
12620
  }
11552
12621
  const handler = this.handlers[parsed.method];
11553
12622
  if (!handler) {
11554
- sendJson3(ws, rpcError(id, RPC_METHOD_NOT_FOUND, `Method not found: ${parsed.method}`));
12623
+ sendJson4(ws, rpcError(id, RPC_METHOD_NOT_FOUND, `Method not found: ${parsed.method}`));
11555
12624
  return;
11556
12625
  }
11557
12626
  const ctx = {
11558
12627
  cwd: this.cwd(),
11559
- notify: (method, params) => sendJson3(ws, rpcNotify(method, params))
12628
+ notify: (method, params) => sendJson4(ws, rpcNotify(method, params))
11560
12629
  };
11561
12630
  try {
11562
12631
  const result = await handler(parsed.params, ctx);
11563
- sendJson3(ws, rpcResult(id, result));
12632
+ sendJson4(ws, rpcResult(id, result));
11564
12633
  } catch (err) {
11565
12634
  const message = err instanceof Error ? err.message : String(err);
11566
12635
  const code = err && typeof err === "object" && "rpcCode" in err && typeof err.rpcCode === "number" ? err.rpcCode : RPC_INTERNAL_ERROR;
11567
- sendJson3(ws, rpcError(id, code, message));
12636
+ sendJson4(ws, rpcError(id, code, message));
11568
12637
  }
11569
12638
  }
11570
12639
  async close() {
@@ -12232,250 +13301,61 @@ async function runCloudConnect(opts) {
12232
13301
  }
12233
13302
  }
12234
13303
 
12235
- // src/slack/workspaces.ts
12236
- import { join as join6 } from "path";
12237
- function storePath() {
12238
- return join6(appDataDir(), "slack-workspaces.json");
13304
+ // src/slack/org-app-client.ts
13305
+ function originOf(relayWsUrl) {
13306
+ return slackRelayHttpOrigin(relayWsUrl ?? slackRelayUrl());
12239
13307
  }
12240
- function readStore() {
13308
+ async function readError(res) {
12241
13309
  try {
12242
- const path2 = storePath();
12243
- const wasEncrypted = isSecureFileEncrypted(path2);
12244
- const parsed = readSecureJson(path2);
12245
- const workspaces = Array.isArray(parsed?.workspaces) ? parsed.workspaces : [];
12246
- if (workspaces.length > 0 && !wasEncrypted && resolveVaultKey()) {
12247
- writeSecureJson(path2, { workspaces });
12248
- }
12249
- return workspaces;
13310
+ const body = await res.json();
13311
+ if (body.error?.trim()) return body.error.trim();
12250
13312
  } catch {
12251
- return [];
12252
13313
  }
13314
+ return `Relay returned ${res.status}`;
12253
13315
  }
12254
- function writeStore(workspaces) {
12255
- writeSecureJson(storePath(), { workspaces });
12256
- return workspaces;
12257
- }
12258
- function toInfo(ws) {
13316
+ async function createSlackOrgApp(opts) {
13317
+ const token = opts.accountToken.trim();
13318
+ if (!token) throw new Error("Sign in on Settings \u2192 Remote before creating a Slack app");
13319
+ const fetchImpl = opts.fetchImpl ?? fetch;
13320
+ const res = await fetchImpl(`${originOf(opts.relayWsUrl)}/slack/apps`, {
13321
+ method: "POST",
13322
+ headers: { Authorization: `Bearer ${token}` }
13323
+ });
13324
+ if (!res.ok) throw new Error(await readError(res));
13325
+ const body = await res.json();
13326
+ if (!body.registrationId || !body.writeToken || !body.manifest || !body.eventsUrl) {
13327
+ throw new Error("Relay did not return a Slack app registration");
13328
+ }
12259
13329
  return {
12260
- team_id: ws.team_id,
12261
- team_name: ws.team_name,
12262
- user_id: ws.user_id,
12263
- has_bot_token: Boolean(ws.bot_token),
12264
- has_user_token: Boolean(ws.user_token),
12265
- connected_at: ws.connected_at
12266
- };
12267
- }
12268
- function listSlackWorkspaces() {
12269
- return readStore().map(toInfo).sort((a, b) => a.team_name.localeCompare(b.team_name));
12270
- }
12271
- function listSlackWorkspacesRaw() {
12272
- return readStore();
12273
- }
12274
- function getSlackWorkspace(teamId) {
12275
- const id = teamId.trim();
12276
- if (!id) return null;
12277
- return readStore().find(
12278
- (ws) => ws.team_id === id || ws.team_name.toLowerCase() === id.toLowerCase()
12279
- ) ?? null;
12280
- }
12281
- function upsertSlackWorkspace(entry) {
12282
- const workspaces = readStore().filter((ws) => ws.team_id !== entry.team_id);
12283
- workspaces.push(entry);
12284
- writeStore(workspaces);
12285
- return toInfo(entry);
12286
- }
12287
- function disconnectSlackWorkspace(teamId) {
12288
- const id = teamId.trim();
12289
- writeStore(readStore().filter((ws) => ws.team_id !== id));
12290
- return listSlackWorkspaces();
12291
- }
12292
- function tokenKind(token) {
12293
- if (token.startsWith("xoxb-")) return "bot";
12294
- if (token.startsWith("xoxp-") || token.startsWith("xoxe.xoxp-")) return "user";
12295
- return "unknown";
12296
- }
12297
- async function connectSlackToken(rawToken) {
12298
- const token = rawToken.trim();
12299
- if (!token) throw new Error("Paste a Slack bot (xoxb-) or user (xoxp-) token");
12300
- const auth = await slackAuthTest(token);
12301
- const teamId = auth.team_id?.trim();
12302
- if (!teamId) throw new Error("Slack auth.test did not return a team_id");
12303
- const existing = getSlackWorkspace(teamId);
12304
- const kind = tokenKind(token);
12305
- const next = {
12306
- team_id: teamId,
12307
- team_name: auth.team?.trim() || existing?.team_name || teamId,
12308
- user_id: auth.user_id?.trim() || existing?.user_id,
12309
- bot_token: kind === "bot" ? token : existing?.bot_token,
12310
- user_token: kind === "user" || kind === "unknown" ? token : existing?.user_token,
12311
- scopes: existing?.scopes,
12312
- connected_at: existing?.connected_at || (/* @__PURE__ */ new Date()).toISOString()
13330
+ registrationId: body.registrationId,
13331
+ writeToken: body.writeToken,
13332
+ eventsUrl: body.eventsUrl,
13333
+ manifest: body.manifest
12313
13334
  };
12314
- if (kind === "unknown" && auth.bot_id) {
12315
- next.bot_token = token;
12316
- next.user_token = existing?.user_token;
12317
- }
12318
- return upsertSlackWorkspace(next);
12319
- }
12320
- function slackTokenFor(ws, kind = "read") {
12321
- const token = (kind === "write" ? ws.bot_token || ws.user_token : ws.user_token || ws.bot_token)?.trim();
12322
- if (!token) {
12323
- throw new Error(`Slack workspace ${ws.team_name} has no token`);
12324
- }
12325
- return token;
12326
- }
12327
-
12328
- // src/slack/oauth.ts
12329
- import { randomBytes as randomBytes7 } from "crypto";
12330
- var SLACK_BOT_SCOPES = [
12331
- "app_mentions:read",
12332
- "channels:history",
12333
- "channels:read",
12334
- "groups:history",
12335
- "groups:read",
12336
- "im:history",
12337
- "im:read",
12338
- "im:write",
12339
- "mpim:history",
12340
- "mpim:read",
12341
- "chat:write",
12342
- "chat:write.public",
12343
- "reactions:write",
12344
- "users:read",
12345
- "users:read.email"
12346
- ].join(",");
12347
- var SLACK_USER_SCOPES = [
12348
- "channels:history",
12349
- "channels:read",
12350
- "groups:history",
12351
- "im:history",
12352
- "mpim:history",
12353
- "users:read"
12354
- ].join(",");
12355
- function slackOAuthCredentials() {
12356
- const settings = loadAppSettings();
12357
- const clientId = process.env.SIDEBOARD_SLACK_CLIENT_ID?.trim() || settings.integrations.slackClientId?.trim() || BAKED_SLACK_CLIENT_ID.trim();
12358
- const clientSecret = process.env.SIDEBOARD_SLACK_CLIENT_SECRET?.trim() || settings.integrations.slackClientSecret?.trim() || "";
12359
- if (!clientId) {
12360
- throw new Error(
12361
- "Slack browser sign-in needs a Slack app Client ID (Settings \u2192 Remote \u2192 Slack, or SIDEBOARD_SLACK_CLIENT_ID). You can still paste an xoxb- or xoxp- token."
12362
- );
12363
- }
12364
- return { clientId, clientSecret: clientSecret || null };
12365
- }
12366
- var SLACK_OAUTH_CANCELLED = "Slack sign-in cancelled";
12367
- var SlackOAuthCancelledError = class extends Error {
12368
- constructor(message = SLACK_OAUTH_CANCELLED) {
12369
- super(message);
12370
- this.name = "SlackOAuthCancelledError";
12371
- }
12372
- };
12373
- function isSlackOAuthCancelled(err) {
12374
- if (err instanceof SlackOAuthCancelledError) return true;
12375
- const message = err instanceof Error ? err.message : String(err);
12376
- if (message.includes(SLACK_OAUTH_CANCELLED)) return true;
12377
- return err instanceof Error && err.name === "SlackOAuthCancelledError";
12378
- }
12379
- function slackOAuthAuthorizeUrl(clientId, state) {
12380
- const params = new URLSearchParams({
12381
- client_id: clientId,
12382
- scope: SLACK_BOT_SCOPES,
12383
- user_scope: SLACK_USER_SCOPES,
12384
- redirect_uri: slackOAuthRedirectUri(),
12385
- state
12386
- });
12387
- return `https://slack.com/oauth/v2/authorize?${params.toString()}`;
12388
- }
12389
- function sleep(ms, signal) {
12390
- return new Promise((resolve, reject) => {
12391
- if (signal?.aborted) {
12392
- reject(new SlackOAuthCancelledError());
12393
- return;
12394
- }
12395
- const timer = setTimeout(() => {
12396
- signal?.removeEventListener("abort", onAbort);
12397
- resolve();
12398
- }, ms);
12399
- const onAbort = () => {
12400
- clearTimeout(timer);
12401
- reject(new SlackOAuthCancelledError());
12402
- };
12403
- signal?.addEventListener("abort", onAbort, { once: true });
12404
- });
12405
- }
12406
- function upsertFromPayload(payload) {
12407
- return upsertSlackWorkspace({
12408
- team_id: payload.team_id,
12409
- team_name: payload.team_name,
12410
- user_id: payload.user_id,
12411
- bot_token: payload.bot_token,
12412
- user_token: payload.user_token,
12413
- scopes: payload.scopes,
12414
- connected_at: (/* @__PURE__ */ new Date()).toISOString()
12415
- });
12416
13335
  }
12417
- async function startSlackOAuth(opts) {
12418
- if (opts?.signal?.aborted) {
12419
- throw new SlackOAuthCancelledError();
12420
- }
12421
- const { clientId } = slackOAuthCredentials();
12422
- const state = randomBytes7(16).toString("hex");
12423
- const authorizeUrl = slackOAuthAuthorizeUrl(clientId, state);
12424
- const timeoutMs = opts?.timeoutMs ?? 5 * 6e4;
12425
- const pollIntervalMs = opts?.pollIntervalMs ?? 400;
12426
- const fetchImpl = opts?.fetchImpl ?? fetch;
12427
- const resultUrl = opts?.resultUrlForState?.(state) ?? slackOAuthResultUrl(state);
12428
- await Promise.resolve(opts?.openUrl?.(authorizeUrl));
12429
- if (opts?.signal?.aborted) {
12430
- throw new SlackOAuthCancelledError();
12431
- }
12432
- const deadline = Date.now() + timeoutMs;
12433
- while (Date.now() < deadline) {
12434
- if (opts?.signal?.aborted) {
12435
- throw new SlackOAuthCancelledError();
12436
- }
12437
- let res;
12438
- try {
12439
- res = await fetchImpl(resultUrl);
12440
- } catch {
12441
- if (opts?.signal?.aborted) throw new SlackOAuthCancelledError();
12442
- await sleep(pollIntervalMs, opts?.signal);
12443
- continue;
12444
- }
12445
- let data;
12446
- try {
12447
- data = await res.json();
12448
- } catch {
12449
- await sleep(pollIntervalMs, opts?.signal);
12450
- continue;
12451
- }
12452
- if (data.ok && data.team_id?.trim()) {
12453
- return upsertFromPayload({
12454
- team_id: data.team_id.trim(),
12455
- team_name: data.team_name?.trim() || data.team_id.trim(),
12456
- user_id: data.user_id?.trim() || void 0,
12457
- bot_token: data.bot_token?.trim() || void 0,
12458
- user_token: data.user_token?.trim() || void 0,
12459
- scopes: data.scopes?.trim() || ""
12460
- });
12461
- }
12462
- const err = data.error?.trim();
12463
- if (err && err !== "pending") {
12464
- if (/cancel/i.test(err) || /access_denied/i.test(err)) {
12465
- throw new SlackOAuthCancelledError(`Slack OAuth: ${err}`);
12466
- }
12467
- throw new Error(err.startsWith("Slack") ? err : `Slack OAuth: ${err}`);
13336
+ async function saveSlackOrgCredentials(opts) {
13337
+ const fetchImpl = opts.fetchImpl ?? fetch;
13338
+ const res = await fetchImpl(
13339
+ `${originOf(opts.relayWsUrl)}/slack/apps/${encodeURIComponent(opts.registrationId)}/credentials`,
13340
+ {
13341
+ method: "POST",
13342
+ headers: { "Content-Type": "application/json" },
13343
+ body: JSON.stringify({
13344
+ writeToken: opts.writeToken,
13345
+ clientId: opts.clientId,
13346
+ clientSecret: opts.clientSecret,
13347
+ signingSecret: opts.signingSecret
13348
+ })
12468
13349
  }
12469
- await sleep(pollIntervalMs, opts?.signal);
12470
- }
12471
- throw new Error("Slack sign-in timed out \u2014 try again");
13350
+ );
13351
+ if (!res.ok) throw new Error(await readError(res));
12472
13352
  }
12473
13353
 
12474
13354
  // src/slack/reply-target.ts
12475
13355
  import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
12476
- import { join as join7 } from "path";
13356
+ import { join as join9 } from "path";
12477
13357
  function storePath2() {
12478
- return join7(appDataDir(), "slack-reply-to.json");
13358
+ return join9(appDataDir(), "slack-reply-to.json");
12479
13359
  }
12480
13360
  function readStore2() {
12481
13361
  const path2 = storePath2();
@@ -12536,9 +13416,11 @@ async function runSlackRelayClient(opts) {
12536
13416
  const deviceId = opts.deviceId.trim();
12537
13417
  if (!url) throw new Error("Relay URL is empty");
12538
13418
  if (!deviceId) throw new Error("Relay needs a deviceId for this Mac");
12539
- if (opts.workspaces.length === 0) {
13419
+ if (opts.workspaces.length === 0 || opts.workspaces.some(
13420
+ (ws) => !ws.botToken.trim() || !ws.userId.trim() || !ws.userToken?.trim() && !ws.listenGrant?.trim()
13421
+ )) {
12540
13422
  throw new Error(
12541
- "Relay needs a connected Slack workspace with bot + user tokens (Add via browser)."
13423
+ "Relay needs Add via browser so this Mac can prove which Slack user it is."
12542
13424
  );
12543
13425
  }
12544
13426
  let backoff = BACKOFF_START_MS3;
@@ -12644,7 +13526,8 @@ function connectSession2(ws, opts, log) {
12644
13526
  deviceId: opts.deviceId.trim(),
12645
13527
  deviceLabel: opts.deviceLabel?.trim() || void 0,
12646
13528
  botToken: wsInfo.botToken,
12647
- userToken: wsInfo.userToken
13529
+ ...wsInfo.userToken?.trim() ? { userToken: wsInfo.userToken.trim() } : {},
13530
+ ...wsInfo.listenGrant?.trim() ? { listenGrant: wsInfo.listenGrant.trim() } : {}
12648
13531
  });
12649
13532
  }
12650
13533
  pingOnce();
@@ -13014,8 +13897,8 @@ function startSlackTurnProgress(msg, threadId, opts) {
13014
13897
  finishWith: (text5) => {
13015
13898
  stop();
13016
13899
  return run2(async () => {
13017
- const signed = signForThisMac(text5.trim());
13018
- if (!signed) {
13900
+ const signed2 = signForThisMac(text5.trim());
13901
+ if (!signed2) {
13019
13902
  if (!postedTs) return;
13020
13903
  const ts = postedTs;
13021
13904
  postedTs = null;
@@ -13029,14 +13912,14 @@ function startSlackTurnProgress(msg, threadId, opts) {
13029
13912
  }
13030
13913
  if (postedTs) {
13031
13914
  try {
13032
- await updateSlackText(target, postedTs, signed, opts);
13915
+ await updateSlackText(target, postedTs, signed2, opts);
13033
13916
  return;
13034
13917
  } catch (err) {
13035
13918
  const errMsg = err instanceof Error ? err.message : String(err);
13036
13919
  log(`progress update error: ${errMsg}`);
13037
13920
  }
13038
13921
  }
13039
- await postSlackText(target, signed, opts);
13922
+ await postSlackText(target, signed2, opts);
13040
13923
  });
13041
13924
  }
13042
13925
  };
@@ -13269,12 +14152,10 @@ async function runSlackListen(opts = {}) {
13269
14152
  if (!relay) {
13270
14153
  throw new Error("Slack Listen needs the hosted relay URL.");
13271
14154
  }
13272
- const withIdentity = connected.filter(
13273
- (w) => w.bot_token?.trim() && w.user_token?.trim() && w.user_id?.trim()
13274
- );
14155
+ const withIdentity = connected.filter(slackWorkspaceCanListen);
13275
14156
  if (withIdentity.length === 0) {
13276
14157
  throw new Error(
13277
- "Slack Listen needs Add via browser (bot token + your Slack user id). Paste-only bot tokens cannot prove which Slack user owns this Mac."
14158
+ "Slack Listen needs Add via browser so this Mac can prove which Slack user it is. A pasted bot token cannot."
13278
14159
  );
13279
14160
  }
13280
14161
  const device = ensureSlackDeviceIdentity();
@@ -13286,12 +14167,17 @@ async function runSlackListen(opts = {}) {
13286
14167
  WebSocketImpl: opts.WebSocketImpl,
13287
14168
  deviceId: device.deviceId,
13288
14169
  deviceLabel: device.deviceLabel,
13289
- workspaces: withIdentity.map((w) => ({
13290
- teamId: w.team_id,
13291
- userId: w.user_id.trim(),
13292
- botToken: w.bot_token.trim(),
13293
- userToken: w.user_token.trim()
13294
- })),
14170
+ workspaces: withIdentity.map((w) => {
14171
+ const userToken = w.user_token?.trim();
14172
+ const listenGrant = w.listen_grant?.trim();
14173
+ return {
14174
+ teamId: w.team_id,
14175
+ userId: w.user_id.trim(),
14176
+ botToken: w.bot_token.trim(),
14177
+ ...userToken ? { userToken } : {},
14178
+ ...listenGrant ? { listenGrant } : {}
14179
+ };
14180
+ }),
13295
14181
  onEvent: onInbound,
13296
14182
  onUninstalled: (teamId) => {
13297
14183
  disconnectSlackWorkspace(teamId);
@@ -13304,15 +14190,13 @@ async function runSlackListen(opts = {}) {
13304
14190
  }
13305
14191
  function resolveSlackListenMode(opts) {
13306
14192
  const relay = (opts?.relayUrl ?? slackRelayUrl()).trim();
13307
- const count = opts?.workspaceCount ?? listSlackWorkspacesRaw().filter(
13308
- (w) => w.bot_token?.trim() && w.user_token?.trim() && w.user_id?.trim()
13309
- ).length;
14193
+ const count = listSlackWorkspacesRaw().filter(slackWorkspaceCanListen).length;
13310
14194
  if (relay && count > 0) return "relay";
13311
14195
  return null;
13312
14196
  }
13313
14197
 
13314
14198
  // src/relay/account-login.ts
13315
- import { randomBytes as randomBytes8 } from "crypto";
14199
+ import { randomBytes as randomBytes12 } from "crypto";
13316
14200
  var RemoteAccountLoginCancelled = class extends Error {
13317
14201
  constructor() {
13318
14202
  super("Sign-in cancelled");
@@ -13365,7 +14249,7 @@ async function relayFetch(fetchImpl, url, init) {
13365
14249
  throw relayFetchError(err, url);
13366
14250
  }
13367
14251
  }
13368
- async function readJson3(res, url) {
14252
+ async function readJson4(res, url) {
13369
14253
  try {
13370
14254
  return await res.json();
13371
14255
  } catch {
@@ -13378,7 +14262,7 @@ async function readJson3(res, url) {
13378
14262
  async function startRemoteAccountLogin(opts) {
13379
14263
  if (opts.signal?.aborted) throw new RemoteAccountLoginCancelled();
13380
14264
  const origin = (opts.origin ?? remoteAccountHttpOrigin()).replace(/\/+$/, "");
13381
- const state = randomBytes8(16).toString("hex");
14265
+ const state = randomBytes12(16).toString("hex");
13382
14266
  const timeoutMs = opts.timeoutMs ?? 5 * 6e4;
13383
14267
  const pollIntervalMs = opts.pollIntervalMs ?? 400;
13384
14268
  const linkToken = opts.linkToken?.trim() ?? "";
@@ -13392,7 +14276,7 @@ async function startRemoteAccountLogin(opts) {
13392
14276
  ...linkToken ? { accountToken: linkToken } : {}
13393
14277
  })
13394
14278
  });
13395
- const startBody = await readJson3(started, startUrl);
14279
+ const startBody = await readJson4(started, startUrl);
13396
14280
  if (!started.ok || !startBody.url) {
13397
14281
  throw new Error(startBody.error || `Could not start sign-in (HTTP ${started.status}).`);
13398
14282
  }
@@ -13441,7 +14325,7 @@ async function disconnectRemoteAccount(opts) {
13441
14325
 
13442
14326
  // src/slack/outbound-watch.ts
13443
14327
  import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
13444
- import { join as join8 } from "path";
14328
+ import { join as join10 } from "path";
13445
14329
  var MAX_WATCHES = 40;
13446
14330
  var MAX_REPLIES_PER_WATCH = 30;
13447
14331
  var WATCH_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -13449,7 +14333,7 @@ var POLL_INTERVAL_MS = 12e3;
13449
14333
  var lastPollMs = 0;
13450
14334
  var nameCache = /* @__PURE__ */ new Map();
13451
14335
  function storePath3() {
13452
- return join8(appDataDir(), "slack-outbound-watch.json");
14336
+ return join10(appDataDir(), "slack-outbound-watch.json");
13453
14337
  }
13454
14338
  function watchId(teamId, channelId, ts) {
13455
14339
  return `${teamId}:${channelId}:${ts}`;
@@ -13516,7 +14400,7 @@ async function continueSourceThread(threadId, prompt) {
13516
14400
  await continueOnReply(threadId, prompt);
13517
14401
  return;
13518
14402
  }
13519
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-IYXIWNB5.js");
14403
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
13520
14404
  await getOrchestrator2().send(threadId, prompt);
13521
14405
  } catch {
13522
14406
  }
@@ -13798,6 +14682,7 @@ export {
13798
14682
  AbleTimeOAuthCancelledError,
13799
14683
  BAKED_ABLETIME_OAUTH_CLIENT_ID,
13800
14684
  BAKED_REMOTE_RELAY_URL,
14685
+ BAKED_SLACK_CLIENT_ID,
13801
14686
  BAKED_SLACK_RELAY_URL,
13802
14687
  BASE_ALLOWED_TOOLS,
13803
14688
  BRIGHTSY_MCP_ALLOWED_TOOLS,
@@ -14102,6 +14987,7 @@ export {
14102
14987
  createOrUpdatePr,
14103
14988
  createPrStack,
14104
14989
  createSchedule,
14990
+ createSlackOrgApp,
14105
14991
  createThread,
14106
14992
  createThreadWorktree,
14107
14993
  currentBranch,
@@ -14525,6 +15411,7 @@ export {
14525
15411
  mergePrStack,
14526
15412
  mergeSetupOutput,
14527
15413
  mergeSideboardIntoMcpServersJson,
15414
+ mergeSlackClientIds,
14528
15415
  mergeUsage,
14529
15416
  messagePartParentId,
14530
15417
  messagesForCompactArchive,
@@ -14732,6 +15619,7 @@ export {
14732
15619
  saveAppSettings,
14733
15620
  saveLinearOAuth,
14734
15621
  saveRemotePhoneToken,
15622
+ saveSlackOrgCredentials,
14735
15623
  saveWorktreeRunPorts,
14736
15624
  scheduleNeedsCaffeinate,
14737
15625
  schedulesPath,