@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.cjs CHANGED
@@ -1440,6 +1440,22 @@ var init_protocol = __esm({
1440
1440
  }
1441
1441
  });
1442
1442
 
1443
+ // src/slack/client-ids.ts
1444
+ function mergeSlackClientIds(ids) {
1445
+ const out = [];
1446
+ for (const raw of ids) {
1447
+ const id = raw?.trim() ?? "";
1448
+ if (!id || out.includes(id)) continue;
1449
+ out.push(id);
1450
+ }
1451
+ return out;
1452
+ }
1453
+ var init_client_ids = __esm({
1454
+ "src/slack/client-ids.ts"() {
1455
+ "use strict";
1456
+ }
1457
+ });
1458
+
1443
1459
  // src/store/private-file.ts
1444
1460
  function writePrivateFile(path2, contents) {
1445
1461
  (0, import_node_fs6.mkdirSync)((0, import_node_path8.dirname)(path2), { recursive: true });
@@ -2511,6 +2527,12 @@ function normalizeIntegrations(raw) {
2511
2527
  const id = source.slackClientId.trim();
2512
2528
  if (id) out.slackClientId = id;
2513
2529
  }
2530
+ if (Array.isArray(source.slackClientIds)) {
2531
+ const ids = mergeSlackClientIds(
2532
+ source.slackClientIds.filter((id) => typeof id === "string")
2533
+ );
2534
+ if (ids.length > 0) out.slackClientIds = ids;
2535
+ }
2514
2536
  if (typeof source.slackClientSecret === "string") {
2515
2537
  const secret = source.slackClientSecret.trim();
2516
2538
  if (secret) out.slackClientSecret = secret;
@@ -3089,6 +3111,11 @@ function updateIntegrationsSettings(patch) {
3089
3111
  integrations.slackClientId = patch.slackClientId.trim();
3090
3112
  }
3091
3113
  }
3114
+ if ("slackClientIds" in patch) {
3115
+ const ids = mergeSlackClientIds(patch.slackClientIds ?? []);
3116
+ if (ids.length === 0) delete integrations.slackClientIds;
3117
+ else integrations.slackClientIds = ids;
3118
+ }
3092
3119
  if ("slackClientSecret" in patch) {
3093
3120
  if (patch.slackClientSecret == null || patch.slackClientSecret.trim() === "") {
3094
3121
  delete integrations.slackClientSecret;
@@ -3879,6 +3906,7 @@ var init_app_settings = __esm({
3879
3906
  init_nested_electron_env();
3880
3907
  init_account_profile();
3881
3908
  init_protocol();
3909
+ init_client_ids();
3882
3910
  init_paths();
3883
3911
  init_private_file();
3884
3912
  init_secret_vault();
@@ -7354,9 +7382,9 @@ function parseOneQuestion(raw) {
7354
7382
  if (!question) return null;
7355
7383
  const options = parseOptions(o.options);
7356
7384
  if (options.length < 1) return null;
7357
- const header = typeof o.header === "string" && o.header.trim() ? o.header.trim() : void 0;
7385
+ const header2 = typeof o.header === "string" && o.header.trim() ? o.header.trim() : void 0;
7358
7386
  const multiSelect = Boolean(o.multiSelect ?? o.multi_select);
7359
- return { question, header, multiSelect, options };
7387
+ return { question, header: header2, multiSelect, options };
7360
7388
  }
7361
7389
  function parsePlanQuestionsInput(input) {
7362
7390
  const root = asRecord2(input);
@@ -7470,12 +7498,12 @@ function formatPlanQuestionAnswers(questions2, answers) {
7470
7498
  for (let i = 0; i < questions2.length; i++) {
7471
7499
  const q = questions2[i];
7472
7500
  const a = answers.find((x) => x.questionIndex === i);
7473
- const header = q.header ? `**${q.header}** \u2014 ` : "";
7501
+ const header2 = q.header ? `**${q.header}** \u2014 ` : "";
7474
7502
  const parts = [];
7475
7503
  if (a?.selected.length) parts.push(a.selected.join(", "));
7476
7504
  if (a?.other?.trim()) parts.push(a.other.trim());
7477
7505
  const body = parts.length ? parts.join(" \xB7 ") : "(no answer)";
7478
- lines.push(`${i + 1}. ${header}${q.question} `);
7506
+ lines.push(`${i + 1}. ${header2}${q.question} `);
7479
7507
  lines.push(` \u2192 ${body}`);
7480
7508
  }
7481
7509
  return lines.join("\n");
@@ -7484,8 +7512,8 @@ function formatPlanQuestionsForChat(questions2) {
7484
7512
  const lines = ["### Questions for you", ""];
7485
7513
  for (let i = 0; i < questions2.length; i++) {
7486
7514
  const q = questions2[i];
7487
- const header = q.header ? `**${q.header}** \u2014 ` : "";
7488
- lines.push(`${i + 1}. ${header}${q.question}`);
7515
+ const header2 = q.header ? `**${q.header}** \u2014 ` : "";
7516
+ lines.push(`${i + 1}. ${header2}${q.question}`);
7489
7517
  for (let oi = 0; oi < q.options.length; oi++) {
7490
7518
  const opt = q.options[oi];
7491
7519
  const desc = opt.description?.trim();
@@ -9802,9 +9830,9 @@ async function ensureWorktreeSideboardIgnored(worktreePath) {
9802
9830
  if (missing.length > 0) {
9803
9831
  const prefix = body && !body.endsWith("\n") ? `${body}
9804
9832
  ` : body;
9805
- const header = body.includes(EXCLUDE_COMMENT) ? "" : `${EXCLUDE_COMMENT}
9833
+ const header2 = body.includes(EXCLUDE_COMMENT) ? "" : `${EXCLUDE_COMMENT}
9806
9834
  `;
9807
- (0, import_node_fs21.writeFileSync)(excludePath, `${prefix}${header}${missing.join("\n")}
9835
+ (0, import_node_fs21.writeFileSync)(excludePath, `${prefix}${header2}${missing.join("\n")}
9808
9836
  `, "utf8");
9809
9837
  }
9810
9838
  const listed = await git(["ls-files", "-z", "--", ".sideboard"], worktreePath, {
@@ -12086,16 +12114,16 @@ async function fetchOriginWithAuth(repoPath, args, timeoutMs) {
12086
12114
  const token = await resolveGithubAgentToken(mode, repoPath);
12087
12115
  if (!token) return false;
12088
12116
  const remoteUrl2 = await originRemoteUrl(repoPath);
12089
- const tryHttps = async (header) => git(args, repoPath, {
12117
+ const tryHttps = async (header2) => git(args, repoPath, {
12090
12118
  reject: false,
12091
12119
  timeoutMs,
12092
12120
  env: githubHttpsRetryEnv(remoteUrl2),
12093
12121
  config: {
12094
- "http.extraHeader": header
12122
+ "http.extraHeader": header2
12095
12123
  }
12096
12124
  });
12097
- const bearer = await tryHttps(`AUTHORIZATION: bearer ${token}`);
12098
- if (bearer.exitCode === 0) return true;
12125
+ const bearer2 = await tryHttps(`AUTHORIZATION: bearer ${token}`);
12126
+ if (bearer2.exitCode === 0) return true;
12099
12127
  const basic = Buffer.from(`x-access-token:${token}`, "utf8").toString("base64");
12100
12128
  const basicFetch = await tryHttps(`Authorization: Basic ${basic}`);
12101
12129
  return basicFetch.exitCode === 0;
@@ -12439,19 +12467,19 @@ async function pushBranch(worktreePath, branchName) {
12439
12467
  );
12440
12468
  }
12441
12469
  const remoteUrl2 = await originRemoteUrl(worktreePath);
12442
- const tryHttps = async (header) => git(["push", "-u", "origin", branchName], worktreePath, {
12470
+ const tryHttps = async (header2) => git(["push", "-u", "origin", branchName], worktreePath, {
12443
12471
  reject: false,
12444
12472
  env: githubHttpsRetryEnv(remoteUrl2),
12445
12473
  config: {
12446
- "http.extraHeader": header
12474
+ "http.extraHeader": header2
12447
12475
  }
12448
12476
  });
12449
- const bearer = await tryHttps(`AUTHORIZATION: bearer ${token}`);
12450
- if (bearer.exitCode === 0) return;
12477
+ const bearer2 = await tryHttps(`AUTHORIZATION: bearer ${token}`);
12478
+ if (bearer2.exitCode === 0) return;
12451
12479
  const basic = Buffer.from(`x-access-token:${token}`, "utf8").toString("base64");
12452
12480
  const basicPush = await tryHttps(`Authorization: Basic ${basic}`);
12453
12481
  if (basicPush.exitCode === 0) return;
12454
- const httpsErr = (basicPush.stderr || bearer.stderr || bearer.stdout).trim();
12482
+ const httpsErr = (basicPush.stderr || bearer2.stderr || bearer2.stdout).trim();
12455
12483
  throw new Error(httpsErr || sshErr || `git push origin ${branchName} failed`);
12456
12484
  }
12457
12485
  async function markCursorPrReady(cwd, slug, selector) {
@@ -12633,7 +12661,7 @@ var init_worktree = __esm({
12633
12661
  init_workspace_scratch();
12634
12662
  init_worktree_labels();
12635
12663
  init_team_slugs();
12636
- PR_INFO_JSON_FIELDS = "number,title,headRefName,url,isCrossRepository,author,isDraft,labels";
12664
+ PR_INFO_JSON_FIELDS = "number,title,headRefName,url,isCrossRepository,author,isDraft,labels,state";
12637
12665
  PR_DETAILS_JSON_FIELDS = [
12638
12666
  "number",
12639
12667
  "title",
@@ -16461,8 +16489,8 @@ async function listenMcpUiProxy(opts) {
16461
16489
  res.writeHead(404).end();
16462
16490
  return;
16463
16491
  }
16464
- const header = req.headers["mcp-session-id"];
16465
- const sid = typeof header === "string" ? header : "";
16492
+ const header2 = req.headers["mcp-session-id"];
16493
+ const sid = typeof header2 === "string" ? header2 : "";
16466
16494
  const sessionKey = `${target.server}:${target.dirsKey}`;
16467
16495
  let transport = sid ? transports.get(`${sessionKey}:${sid}`) : void 0;
16468
16496
  if (!transport) {
@@ -17239,9 +17267,9 @@ function filenameFromUrl(url, fallback = "attachment") {
17239
17267
  }
17240
17268
  return fallback;
17241
17269
  }
17242
- function filenameFromContentDisposition(header) {
17243
- if (!header) return void 0;
17244
- const star = header.match(/filename\*\s*=\s*(?:UTF-8''|utf-8'')([^;]+)/i);
17270
+ function filenameFromContentDisposition(header2) {
17271
+ if (!header2) return void 0;
17272
+ const star = header2.match(/filename\*\s*=\s*(?:UTF-8''|utf-8'')([^;]+)/i);
17245
17273
  if (star?.[1]) {
17246
17274
  try {
17247
17275
  return decodeURIComponent(star[1].trim().replace(/^["']|["']$/g, ""));
@@ -17249,7 +17277,7 @@ function filenameFromContentDisposition(header) {
17249
17277
  return star[1].trim().replace(/^["']|["']$/g, "");
17250
17278
  }
17251
17279
  }
17252
- const plain = header.match(/filename\s*=\s*("(?:\\.|[^"])*"|[^;]+)/i);
17280
+ const plain = header2.match(/filename\s*=\s*("(?:\\.|[^"])*"|[^;]+)/i);
17253
17281
  if (!plain?.[1]) return void 0;
17254
17282
  return plain[1].trim().replace(/^["']|["']$/g, "").replace(/\\"/g, '"');
17255
17283
  }
@@ -29879,16 +29907,16 @@ function splitCombinedDiff(stdout) {
29879
29907
  for (const part of parts) {
29880
29908
  if (!part.trim()) continue;
29881
29909
  const full = `diff --git ${part}`.replace(/\n$/, "");
29882
- const header = full.match(/^diff --git a\/(.+?) b\/(.+?)(?:\n|$)/);
29883
- if (!header) continue;
29884
- map.set(header[2], full);
29910
+ const header2 = full.match(/^diff --git a\/(.+?) b\/(.+?)(?:\n|$)/);
29911
+ if (!header2) continue;
29912
+ map.set(header2[2], full);
29885
29913
  }
29886
29914
  return map;
29887
29915
  }
29888
29916
  function syntheticAddPatch(path2, content, maxHunk) {
29889
29917
  const lines = content.split("\n");
29890
29918
  const body = lines.map((l) => `+${l}`).join("\n");
29891
- const header = `diff --git a/${path2} b/${path2}
29919
+ const header2 = `diff --git a/${path2} b/${path2}
29892
29920
  new file mode 100644
29893
29921
  --- /dev/null
29894
29922
  +++ b/${path2}
@@ -29897,7 +29925,7 @@ new file mode 100644
29897
29925
  return {
29898
29926
  path: path2,
29899
29927
  status: "A",
29900
- patch: capPatch(`${header}${body}`, maxHunk),
29928
+ patch: capPatch(`${header2}${body}`, maxHunk),
29901
29929
  additions: lines.length,
29902
29930
  deletions: 0
29903
29931
  };
@@ -35809,6 +35837,7 @@ __export(index_exports, {
35809
35837
  AbleTimeOAuthCancelledError: () => AbleTimeOAuthCancelledError,
35810
35838
  BAKED_ABLETIME_OAUTH_CLIENT_ID: () => BAKED_ABLETIME_OAUTH_CLIENT_ID,
35811
35839
  BAKED_REMOTE_RELAY_URL: () => BAKED_REMOTE_RELAY_URL,
35840
+ BAKED_SLACK_CLIENT_ID: () => BAKED_SLACK_CLIENT_ID,
35812
35841
  BAKED_SLACK_RELAY_URL: () => BAKED_SLACK_RELAY_URL,
35813
35842
  BASE_ALLOWED_TOOLS: () => BASE_ALLOWED_TOOLS,
35814
35843
  BRIGHTSY_MCP_ALLOWED_TOOLS: () => BRIGHTSY_MCP_ALLOWED_TOOLS,
@@ -36113,6 +36142,7 @@ __export(index_exports, {
36113
36142
  createOrUpdatePr: () => createOrUpdatePr,
36114
36143
  createPrStack: () => createPrStack,
36115
36144
  createSchedule: () => createSchedule,
36145
+ createSlackOrgApp: () => createSlackOrgApp,
36116
36146
  createThread: () => createThread,
36117
36147
  createThreadWorktree: () => createThreadWorktree,
36118
36148
  currentBranch: () => currentBranch,
@@ -36536,6 +36566,7 @@ __export(index_exports, {
36536
36566
  mergePrStack: () => mergePrStack,
36537
36567
  mergeSetupOutput: () => mergeSetupOutput,
36538
36568
  mergeSideboardIntoMcpServersJson: () => mergeSideboardIntoMcpServersJson,
36569
+ mergeSlackClientIds: () => mergeSlackClientIds,
36539
36570
  mergeUsage: () => mergeUsage,
36540
36571
  messagePartParentId: () => messagePartParentId,
36541
36572
  messagesForCompactArchive: () => messagesForCompactArchive,
@@ -36743,6 +36774,7 @@ __export(index_exports, {
36743
36774
  saveAppSettings: () => saveAppSettings,
36744
36775
  saveLinearOAuth: () => saveLinearOAuth,
36745
36776
  saveRemotePhoneToken: () => saveRemotePhoneToken,
36777
+ saveSlackOrgCredentials: () => saveSlackOrgCredentials,
36746
36778
  saveWorktreeRunPorts: () => saveWorktreeRunPorts,
36747
36779
  scheduleNeedsCaffeinate: () => scheduleNeedsCaffeinate,
36748
36780
  schedulesPath: () => schedulesPath,
@@ -39209,8 +39241,8 @@ function dispatchPhoneWorkspace(cmd, emit, publishOpened) {
39209
39241
  emit({ op: "error", chatId: cmd.chatId, message: "That agent is not on this Mac." });
39210
39242
  return;
39211
39243
  }
39212
- void readPhoneHeader(thread).then((header) => {
39213
- emit({ op: "header", chatId: cmd.chatId, ...header });
39244
+ void readPhoneHeader(thread).then((header2) => {
39245
+ emit({ op: "header", chatId: cmd.chatId, ...header2 });
39214
39246
  });
39215
39247
  return;
39216
39248
  }
@@ -40067,12 +40099,52 @@ function sourceWarning(label, err) {
40067
40099
  const message = err instanceof Error ? err.message : String(err);
40068
40100
  return message ? `${label}: ${message}` : `${label} failed.`;
40069
40101
  }
40102
+ function phonePrNumberQuery(query) {
40103
+ const match = query.trim().match(/^#?(\d+)$/);
40104
+ if (!match) return null;
40105
+ const n = Number(match[1]);
40106
+ if (!Number.isSafeInteger(n) || n <= 0) return null;
40107
+ return n;
40108
+ }
40109
+ function phonePrMatchesQuery(pr, query) {
40110
+ const raw = query.trim().toLowerCase();
40111
+ if (!raw) return true;
40112
+ const q = raw.replace(/^#/, "");
40113
+ if (!q) return pr.title.toLowerCase().includes(raw);
40114
+ return pr.title.toLowerCase().includes(q) || String(pr.number).includes(q);
40115
+ }
40116
+ function prIsListedOpen(pr) {
40117
+ const state = pr.state?.trim().toLowerCase();
40118
+ return state !== "closed" && state !== "merged";
40119
+ }
40120
+ function mergePrs(groups) {
40121
+ const out = [];
40122
+ const seen = /* @__PURE__ */ new Set();
40123
+ for (const group of groups) {
40124
+ for (const pr of group) {
40125
+ if (!pr || seen.has(pr.number) || !prIsListedOpen(pr)) continue;
40126
+ seen.add(pr.number);
40127
+ out.push(pr);
40128
+ }
40129
+ }
40130
+ return out;
40131
+ }
40132
+ async function loadPhonePrs(path2, query) {
40133
+ const number = phonePrNumberQuery(query);
40134
+ if (!query) return listPrs(path2, { state: "open", limit: 40 });
40135
+ const [searched, recent, exact] = await Promise.all([
40136
+ listPrs(path2, { state: "open", limit: 40, query: number == null ? query : String(number) }),
40137
+ listPrs(path2, { state: "open", limit: number == null ? 40 : 200 }),
40138
+ number == null ? Promise.resolve(null) : getPr(path2, number).catch(() => null)
40139
+ ]);
40140
+ return mergePrs([exact ? [exact] : [], searched, recent]).filter((pr) => phonePrMatchesQuery(pr, query));
40141
+ }
40070
40142
  async function listPhoneSources(repoPath, query) {
40071
40143
  const path2 = assertKnownProject(repoPath);
40072
40144
  const q = query?.trim() ?? "";
40073
40145
  const warnings = [];
40074
40146
  const [prs, branches, issues] = await Promise.all([
40075
- listPrs(path2, { state: "open", limit: 40, ...q ? { query: q } : {} }).catch((err) => {
40147
+ loadPhonePrs(path2, q).catch((err) => {
40076
40148
  warnings.push(sourceWarning("Pull requests", err));
40077
40149
  return [];
40078
40150
  }),
@@ -41091,26 +41163,6 @@ function slackOAuthHtmlPage(title, body) {
41091
41163
  <style>body{font-family:ui-sans-serif,system-ui,sans-serif;padding:48px 24px;max-width:36rem;margin:0 auto;color:#1a1a1a}
41092
41164
  h1{font-size:1.25rem}p{line-height:1.5;color:#444}</style></head><body>${body}</body></html>`;
41093
41165
  }
41094
- function parseSlackOAuthCallbackUrl(reqUrl) {
41095
- let url;
41096
- try {
41097
- url = new URL(reqUrl, SLACK_OAUTH_REDIRECT);
41098
- } catch {
41099
- return null;
41100
- }
41101
- if (url.pathname !== SLACK_OAUTH_CALLBACK_PATH) return null;
41102
- return url;
41103
- }
41104
- function parseSlackOAuthResultUrl(reqUrl) {
41105
- let url;
41106
- try {
41107
- url = new URL(reqUrl, SLACK_OAUTH_REDIRECT);
41108
- } catch {
41109
- return null;
41110
- }
41111
- if (url.pathname !== SLACK_OAUTH_RESULT_PATH) return null;
41112
- return url;
41113
- }
41114
41166
 
41115
41167
  // src/slack/baked-app.ts
41116
41168
  var BAKED_SLACK_CLIENT_ID = "7592788819232.11813536272562";
@@ -41192,11 +41244,15 @@ async function exchangeSlackOAuthCode(opts) {
41192
41244
  team_name: data.team?.name?.trim() || teamId,
41193
41245
  user_id: data.authed_user?.id?.trim() || void 0,
41194
41246
  bot_token: data.access_token?.trim() || void 0,
41247
+ bot_user_id: data.bot_user_id?.trim() || void 0,
41195
41248
  user_token: data.authed_user?.access_token?.trim() || void 0,
41196
41249
  scopes: [data.scope, data.authed_user?.scope].filter(Boolean).join(",")
41197
41250
  };
41198
41251
  }
41199
41252
 
41253
+ // src/slack/events-api.ts
41254
+ var import_node_crypto23 = require("crypto");
41255
+
41200
41256
  // src/slack/socket-mode.ts
41201
41257
  var import_ws3 = require("ws");
41202
41258
 
@@ -41478,8 +41534,988 @@ function connectSession(ws, opts, log) {
41478
41534
  });
41479
41535
  }
41480
41536
 
41537
+ // src/slack/events-api.ts
41538
+ var MAX_SKEW_MS = 5 * 6e4;
41539
+ function verifySlackRequestSignature(opts) {
41540
+ const timestamp = opts.timestamp.trim();
41541
+ const signature = opts.signature.trim();
41542
+ const seconds = Number(timestamp);
41543
+ if (!timestamp || !signature || !Number.isFinite(seconds)) return false;
41544
+ const now = opts.nowMs ?? Date.now();
41545
+ if (Math.abs(now - seconds * 1e3) > MAX_SKEW_MS) return false;
41546
+ const hmac = (0, import_node_crypto23.createHmac)("sha256", opts.signingSecret).update(`v0:${timestamp}:${opts.rawBody}`).digest("hex");
41547
+ const expected = Buffer.from(`v0=${hmac}`);
41548
+ const presented = Buffer.from(signature);
41549
+ return expected.length === presented.length && (0, import_node_crypto23.timingSafeEqual)(expected, presented);
41550
+ }
41551
+ function parseSlackEventsBody(raw) {
41552
+ try {
41553
+ const parsed = JSON.parse(raw);
41554
+ if (!parsed || typeof parsed !== "object") return null;
41555
+ return parsed;
41556
+ } catch {
41557
+ return null;
41558
+ }
41559
+ }
41560
+ function asSocketFrame(body) {
41561
+ return {
41562
+ type: "events_api",
41563
+ payload: {
41564
+ team_id: typeof body.team_id === "string" ? body.team_id : void 0,
41565
+ event: body.event
41566
+ }
41567
+ };
41568
+ }
41569
+ function inboundFromEventsBody(body) {
41570
+ if (body.type !== "event_callback") return null;
41571
+ return inboundFromSocketFrame(asSocketFrame(body));
41572
+ }
41573
+ function lifecycleFromEventsBody(body) {
41574
+ if (body.type !== "event_callback") return null;
41575
+ return lifecycleFromSocketFrame(asSocketFrame(body));
41576
+ }
41577
+ var SlackEventDeduper = class {
41578
+ constructor(ttlMs = 10 * 6e4) {
41579
+ this.ttlMs = ttlMs;
41580
+ }
41581
+ ttlMs;
41582
+ seen = /* @__PURE__ */ new Map();
41583
+ duplicate(eventId, now = Date.now()) {
41584
+ const id = eventId.trim();
41585
+ if (!id) return false;
41586
+ for (const [key, expires] of this.seen) {
41587
+ if (expires <= now) this.seen.delete(key);
41588
+ }
41589
+ if (this.seen.has(id)) return true;
41590
+ this.seen.set(id, now + this.ttlMs);
41591
+ return false;
41592
+ }
41593
+ };
41594
+
41595
+ // src/slack/secret-box.ts
41596
+ var import_node_crypto24 = require("crypto");
41597
+ var VERSION = "v1";
41598
+ function parseSlackTokenKey(raw) {
41599
+ const text7 = raw.trim();
41600
+ if (!text7) throw new Error("SIDEBOARD_SLACK_TOKEN_KEY is empty");
41601
+ const buf = /^[0-9a-fA-F]{64}$/.test(text7) ? Buffer.from(text7, "hex") : Buffer.from(text7, "base64");
41602
+ if (buf.length !== 32) {
41603
+ throw new Error("SIDEBOARD_SLACK_TOKEN_KEY must be 32 bytes (base64 or 64 hex characters)");
41604
+ }
41605
+ return buf;
41606
+ }
41607
+ function sealSecret(key, plaintext) {
41608
+ const iv = (0, import_node_crypto24.randomBytes)(12);
41609
+ const cipher = (0, import_node_crypto24.createCipheriv)("aes-256-gcm", key, iv);
41610
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
41611
+ const tag = cipher.getAuthTag();
41612
+ return [VERSION, iv.toString("base64url"), tag.toString("base64url"), ciphertext.toString("base64url")].join(
41613
+ "."
41614
+ );
41615
+ }
41616
+ function openSecret(key, sealed) {
41617
+ const [version, ivB64, tagB64, ctB64] = sealed.split(".");
41618
+ if (version !== VERSION || !ivB64 || !tagB64 || !ctB64 || sealed.split(".").length !== 4) {
41619
+ throw new Error("Slack secret ciphertext is not recognized");
41620
+ }
41621
+ const decipher = (0, import_node_crypto24.createDecipheriv)("aes-256-gcm", key, Buffer.from(ivB64, "base64url"));
41622
+ decipher.setAuthTag(Buffer.from(tagB64, "base64url"));
41623
+ return Buffer.concat([
41624
+ decipher.update(Buffer.from(ctB64, "base64url")),
41625
+ decipher.final()
41626
+ ]).toString("utf8");
41627
+ }
41628
+
41629
+ // src/slack/oauth-state.ts
41630
+ var import_node_crypto25 = require("crypto");
41631
+ function slackOAuthState(clientId, bakedClientId) {
41632
+ const nonce = (0, import_node_crypto25.randomBytes)(16).toString("hex");
41633
+ const id = clientId.trim();
41634
+ if (!id || id === bakedClientId.trim()) return nonce;
41635
+ return `c.${Buffer.from(id, "utf8").toString("base64url")}.${nonce}`;
41636
+ }
41637
+ function clientIdFromOAuthState(state) {
41638
+ if (!state.startsWith("c.")) return null;
41639
+ const rest = state.slice(2);
41640
+ const dot = rest.lastIndexOf(".");
41641
+ if (dot <= 0) return null;
41642
+ if (!/^[0-9a-f]{32}$/.test(rest.slice(dot + 1))) return null;
41643
+ try {
41644
+ const id = Buffer.from(rest.slice(0, dot), "base64url").toString("utf8").trim();
41645
+ if (!id || id.includes("\0")) return null;
41646
+ return id;
41647
+ } catch {
41648
+ return null;
41649
+ }
41650
+ }
41651
+
41652
+ // src/slack/oauth.ts
41653
+ init_app_settings();
41654
+
41655
+ // src/slack/workspaces.ts
41656
+ var import_node_path71 = require("path");
41657
+ init_paths();
41658
+ init_secure_file();
41659
+ function storePath2() {
41660
+ return (0, import_node_path71.join)(appDataDir(), "slack-workspaces.json");
41661
+ }
41662
+ function readStore2() {
41663
+ try {
41664
+ const path2 = storePath2();
41665
+ const wasEncrypted = isSecureFileEncrypted(path2);
41666
+ const parsed = readSecureJson(path2);
41667
+ const workspaces = Array.isArray(parsed?.workspaces) ? parsed.workspaces : [];
41668
+ if (workspaces.length > 0 && !wasEncrypted && resolveVaultKey()) {
41669
+ writeSecureJson(path2, { workspaces });
41670
+ }
41671
+ return workspaces;
41672
+ } catch {
41673
+ return [];
41674
+ }
41675
+ }
41676
+ function writeStore2(workspaces) {
41677
+ writeSecureJson(storePath2(), { workspaces });
41678
+ return workspaces;
41679
+ }
41680
+ function toInfo(ws) {
41681
+ return {
41682
+ team_id: ws.team_id,
41683
+ team_name: ws.team_name,
41684
+ user_id: ws.user_id,
41685
+ has_bot_token: Boolean(ws.bot_token),
41686
+ has_user_token: Boolean(ws.user_token),
41687
+ connected_at: ws.connected_at
41688
+ };
41689
+ }
41690
+ function slackWorkspaceCanListen(ws) {
41691
+ return Boolean(
41692
+ ws.bot_token?.trim() && ws.user_id?.trim() && (ws.user_token?.trim() || ws.listen_grant?.trim())
41693
+ );
41694
+ }
41695
+ function listSlackWorkspaces() {
41696
+ return readStore2().map(toInfo).sort((a, b) => a.team_name.localeCompare(b.team_name));
41697
+ }
41698
+ function listSlackWorkspacesRaw() {
41699
+ return readStore2();
41700
+ }
41701
+ function getSlackWorkspace(teamId) {
41702
+ const id = teamId.trim();
41703
+ if (!id) return null;
41704
+ return readStore2().find(
41705
+ (ws) => ws.team_id === id || ws.team_name.toLowerCase() === id.toLowerCase()
41706
+ ) ?? null;
41707
+ }
41708
+ function upsertSlackWorkspace(entry) {
41709
+ const workspaces = readStore2().filter((ws) => ws.team_id !== entry.team_id);
41710
+ workspaces.push(entry);
41711
+ writeStore2(workspaces);
41712
+ return toInfo(entry);
41713
+ }
41714
+ function disconnectSlackWorkspace(teamId) {
41715
+ const id = teamId.trim();
41716
+ writeStore2(readStore2().filter((ws) => ws.team_id !== id));
41717
+ return listSlackWorkspaces();
41718
+ }
41719
+ function tokenKind(token) {
41720
+ if (token.startsWith("xoxb-")) return "bot";
41721
+ if (token.startsWith("xoxp-") || token.startsWith("xoxe.xoxp-")) return "user";
41722
+ return "unknown";
41723
+ }
41724
+ async function connectSlackToken(rawToken) {
41725
+ const token = rawToken.trim();
41726
+ if (!token) throw new Error("Paste a Slack bot (xoxb-) or user (xoxp-) token");
41727
+ const auth = await slackAuthTest(token);
41728
+ const teamId = auth.team_id?.trim();
41729
+ if (!teamId) throw new Error("Slack auth.test did not return a team_id");
41730
+ const existing = getSlackWorkspace(teamId);
41731
+ const kind = tokenKind(token);
41732
+ const authUserId = auth.user_id?.trim();
41733
+ const userId = kind === "bot" ? existing?.user_id || authUserId : authUserId || existing?.user_id;
41734
+ const next = {
41735
+ team_id: teamId,
41736
+ team_name: auth.team?.trim() || existing?.team_name || teamId,
41737
+ user_id: userId,
41738
+ bot_token: kind === "bot" ? token : existing?.bot_token,
41739
+ user_token: kind === "user" || kind === "unknown" ? token : existing?.user_token,
41740
+ listen_grant: existing?.user_id && userId && existing.user_id !== userId ? void 0 : existing?.listen_grant,
41741
+ scopes: existing?.scopes,
41742
+ connected_at: existing?.connected_at || (/* @__PURE__ */ new Date()).toISOString()
41743
+ };
41744
+ if (kind === "unknown" && auth.bot_id) {
41745
+ next.bot_token = token;
41746
+ next.user_token = existing?.user_token;
41747
+ next.user_id = existing?.user_id || authUserId;
41748
+ if (existing?.user_id && next.user_id && existing.user_id !== next.user_id) {
41749
+ next.listen_grant = void 0;
41750
+ }
41751
+ }
41752
+ return upsertSlackWorkspace(next);
41753
+ }
41754
+ function slackTokenFor(ws, _kind = "read") {
41755
+ const token = (ws.bot_token || ws.user_token)?.trim();
41756
+ if (!token) {
41757
+ throw new Error(`Slack workspace ${ws.team_name} has no token`);
41758
+ }
41759
+ return token;
41760
+ }
41761
+
41762
+ // src/slack/oauth.ts
41763
+ var SLACK_BOT_SCOPES = [
41764
+ "app_mentions:read",
41765
+ "channels:history",
41766
+ "channels:read",
41767
+ "groups:history",
41768
+ "groups:read",
41769
+ "im:history",
41770
+ "im:read",
41771
+ "im:write",
41772
+ "mpim:history",
41773
+ "mpim:read",
41774
+ "chat:write",
41775
+ "chat:write.public",
41776
+ "reactions:write",
41777
+ "users:read",
41778
+ "users:read.email"
41779
+ ].join(",");
41780
+ function slackOAuthCredentials() {
41781
+ const settings = loadAppSettings();
41782
+ const clientId = process.env.SIDEBOARD_SLACK_CLIENT_ID?.trim() || settings.integrations.slackClientId?.trim() || BAKED_SLACK_CLIENT_ID.trim();
41783
+ const clientSecret = process.env.SIDEBOARD_SLACK_CLIENT_SECRET?.trim() || settings.integrations.slackClientSecret?.trim() || "";
41784
+ if (!clientId) {
41785
+ throw new Error(
41786
+ "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."
41787
+ );
41788
+ }
41789
+ return { clientId, clientSecret: clientSecret || null };
41790
+ }
41791
+ var SLACK_OAUTH_CANCELLED = "Slack sign-in cancelled";
41792
+ var SlackOAuthCancelledError = class extends Error {
41793
+ constructor(message = SLACK_OAUTH_CANCELLED) {
41794
+ super(message);
41795
+ this.name = "SlackOAuthCancelledError";
41796
+ }
41797
+ };
41798
+ function isSlackOAuthCancelled(err) {
41799
+ if (err instanceof SlackOAuthCancelledError) return true;
41800
+ const message = err instanceof Error ? err.message : String(err);
41801
+ if (message.includes(SLACK_OAUTH_CANCELLED)) return true;
41802
+ return err instanceof Error && err.name === "SlackOAuthCancelledError";
41803
+ }
41804
+ function slackOAuthAuthorizeUrl(clientId, state) {
41805
+ const params = new URLSearchParams({
41806
+ client_id: clientId,
41807
+ scope: SLACK_BOT_SCOPES,
41808
+ redirect_uri: slackOAuthRedirectUri(),
41809
+ state
41810
+ });
41811
+ return `https://slack.com/oauth/v2/authorize?${params.toString()}`;
41812
+ }
41813
+ function sleep(ms, signal) {
41814
+ return new Promise((resolve3, reject) => {
41815
+ if (signal?.aborted) {
41816
+ reject(new SlackOAuthCancelledError());
41817
+ return;
41818
+ }
41819
+ const timer = setTimeout(() => {
41820
+ signal?.removeEventListener("abort", onAbort);
41821
+ resolve3();
41822
+ }, ms);
41823
+ const onAbort = () => {
41824
+ clearTimeout(timer);
41825
+ reject(new SlackOAuthCancelledError());
41826
+ };
41827
+ signal?.addEventListener("abort", onAbort, { once: true });
41828
+ });
41829
+ }
41830
+ function upsertFromPayload(payload) {
41831
+ const existing = getSlackWorkspace(payload.team_id);
41832
+ return upsertSlackWorkspace({
41833
+ team_id: payload.team_id,
41834
+ team_name: payload.team_name || existing?.team_name || payload.team_id,
41835
+ user_id: payload.user_id || existing?.user_id,
41836
+ bot_token: payload.bot_token || existing?.bot_token,
41837
+ user_token: payload.user_token || existing?.user_token,
41838
+ listen_grant: payload.listen_grant || existing?.listen_grant,
41839
+ scopes: payload.scopes || existing?.scopes,
41840
+ connected_at: (/* @__PURE__ */ new Date()).toISOString()
41841
+ });
41842
+ }
41843
+ async function startSlackOAuth(opts) {
41844
+ if (opts?.signal?.aborted) {
41845
+ throw new SlackOAuthCancelledError();
41846
+ }
41847
+ const clientId = opts?.clientId?.trim() || slackOAuthCredentials().clientId;
41848
+ const state = slackOAuthState(clientId, BAKED_SLACK_CLIENT_ID);
41849
+ const authorizeUrl = slackOAuthAuthorizeUrl(clientId, state);
41850
+ const timeoutMs = opts?.timeoutMs ?? 5 * 6e4;
41851
+ const pollIntervalMs = opts?.pollIntervalMs ?? 400;
41852
+ const fetchImpl = opts?.fetchImpl ?? fetch;
41853
+ const resultUrl = opts?.resultUrlForState?.(state) ?? slackOAuthResultUrl(state);
41854
+ await Promise.resolve(opts?.openUrl?.(authorizeUrl));
41855
+ if (opts?.signal?.aborted) {
41856
+ throw new SlackOAuthCancelledError();
41857
+ }
41858
+ const deadline = Date.now() + timeoutMs;
41859
+ while (Date.now() < deadline) {
41860
+ if (opts?.signal?.aborted) {
41861
+ throw new SlackOAuthCancelledError();
41862
+ }
41863
+ let res;
41864
+ try {
41865
+ res = await fetchImpl(resultUrl);
41866
+ } catch {
41867
+ if (opts?.signal?.aborted) throw new SlackOAuthCancelledError();
41868
+ await sleep(pollIntervalMs, opts?.signal);
41869
+ continue;
41870
+ }
41871
+ let data;
41872
+ try {
41873
+ data = await res.json();
41874
+ } catch {
41875
+ await sleep(pollIntervalMs, opts?.signal);
41876
+ continue;
41877
+ }
41878
+ if (data.ok && data.team_id?.trim()) {
41879
+ return upsertFromPayload({
41880
+ team_id: data.team_id.trim(),
41881
+ team_name: data.team_name?.trim() || data.team_id.trim(),
41882
+ user_id: data.user_id?.trim() || void 0,
41883
+ bot_token: data.bot_token?.trim() || void 0,
41884
+ user_token: data.user_token?.trim() || void 0,
41885
+ listen_grant: data.listen_grant?.trim() || void 0,
41886
+ scopes: data.scopes?.trim() || ""
41887
+ });
41888
+ }
41889
+ const err = data.error?.trim();
41890
+ if (err && err !== "pending") {
41891
+ if (/cancel/i.test(err) || /access_denied/i.test(err)) {
41892
+ throw new SlackOAuthCancelledError(`Slack OAuth: ${err}`);
41893
+ }
41894
+ throw new Error(err.startsWith("Slack") ? err : `Slack OAuth: ${err}`);
41895
+ }
41896
+ await sleep(pollIntervalMs, opts?.signal);
41897
+ }
41898
+ throw new Error("Slack sign-in timed out \u2014 try again");
41899
+ }
41900
+
41901
+ // src/slack/org-manifest.ts
41902
+ var BOT_EVENTS = [
41903
+ "app_home_opened",
41904
+ "app_mention",
41905
+ "app_uninstalled",
41906
+ "message.im",
41907
+ "message.mpim"
41908
+ ];
41909
+ function yamlList(scopes, indent) {
41910
+ return scopes.split(",").map((scope) => scope.trim()).filter(Boolean).map((scope) => `${indent}- ${scope}`).join("\n");
41911
+ }
41912
+ function slackOrgManifest(opts) {
41913
+ const eventsUrl = opts.eventsUrl.trim();
41914
+ const redirectUrl = opts.redirectUrl.trim();
41915
+ return `display_information:
41916
+ name: Sideboard
41917
+ description: Drive Sideboard agents from Slack DMs and @mentions.
41918
+ background_color: "#111827"
41919
+ long_description: >-
41920
+ Sideboard sends DMs and @mentions to the orchestrator on a Mac in this
41921
+ workspace and posts replies back in thread. Agents can list, read, and
41922
+ post in Slack. Message text is not used to train models.
41923
+
41924
+ features:
41925
+ app_home:
41926
+ home_tab_enabled: true
41927
+ messages_tab_enabled: true
41928
+ messages_tab_read_only_enabled: false
41929
+ bot_user:
41930
+ display_name: Sideboard
41931
+ always_online: true
41932
+
41933
+ oauth_config:
41934
+ redirect_urls:
41935
+ - ${redirectUrl}
41936
+ scopes:
41937
+ bot:
41938
+ ${yamlList(SLACK_BOT_SCOPES, " ")}
41939
+
41940
+ settings:
41941
+ org_deploy_enabled: false
41942
+ socket_mode_enabled: false
41943
+ token_rotation_enabled: false
41944
+ event_subscriptions:
41945
+ request_url: ${eventsUrl}
41946
+ bot_events:
41947
+ ${BOT_EVENTS.map((event) => ` - ${event}`).join("\n")}
41948
+ `;
41949
+ }
41950
+ function slackEventsPath(registrationId) {
41951
+ return `/slack/events/${registrationId}`;
41952
+ }
41953
+ function slackEventsUrl(origin, registrationId) {
41954
+ return `${origin.replace(/\/$/, "")}${slackEventsPath(registrationId)}`;
41955
+ }
41956
+
41957
+ // src/relay/slack-http.ts
41958
+ var EVENTS_PREFIX = "/slack/events/";
41959
+ var APPS_PATH = "/slack/apps";
41960
+ var BODY_LIMIT = 262144;
41961
+ async function handleSlackHttp(ctx) {
41962
+ const url = parseUrl(ctx.reqUrl);
41963
+ if (!url) return false;
41964
+ const path2 = url.pathname;
41965
+ if (path2 === "/slack/callback") return handleCallback(ctx, url);
41966
+ if (path2 === "/slack/oauth/result") return handleResult(ctx, url);
41967
+ if (path2 === APPS_PATH && ctx.req.method === "POST") {
41968
+ await handleCreate(ctx);
41969
+ return true;
41970
+ }
41971
+ const creds = path2.match(/^\/slack\/apps\/([A-Za-z0-9_-]+)\/credentials$/);
41972
+ if (creds && ctx.req.method === "POST") {
41973
+ await handleCredentials(ctx, creds[1]);
41974
+ return true;
41975
+ }
41976
+ if (path2.startsWith(EVENTS_PREFIX) && ctx.req.method === "POST") {
41977
+ await handleEvents(ctx, decodeURIComponent(path2.slice(EVENTS_PREFIX.length)));
41978
+ return true;
41979
+ }
41980
+ return false;
41981
+ }
41982
+ function parseUrl(reqUrl) {
41983
+ try {
41984
+ return new URL(reqUrl, "http://127.0.0.1");
41985
+ } catch {
41986
+ return null;
41987
+ }
41988
+ }
41989
+ async function handleCreate(ctx) {
41990
+ if (!ctx.accounts || !ctx.apps) {
41991
+ sendJson(ctx.res, 503, {
41992
+ ok: false,
41993
+ error: "Per-company Slack apps need SIDEBOARD_SLACK_TOKEN_KEY and the relay account database"
41994
+ });
41995
+ return;
41996
+ }
41997
+ const accountId = ctx.accounts.verifyCredential(bearer(ctx.req));
41998
+ if (!accountId) {
41999
+ sendJson(ctx.res, 401, { ok: false, error: "Sign in to the relay before creating a Slack app" });
42000
+ return;
42001
+ }
42002
+ const created = ctx.apps.create(accountId);
42003
+ const eventsUrl = slackEventsUrl(ctx.publicOrigin, created.registrationId);
42004
+ sendJson(ctx.res, 200, {
42005
+ ok: true,
42006
+ registrationId: created.registrationId,
42007
+ writeToken: created.writeToken,
42008
+ eventsUrl,
42009
+ manifest: slackOrgManifest({ eventsUrl, redirectUrl: ctx.redirectUri })
42010
+ });
42011
+ }
42012
+ async function handleCredentials(ctx, registrationId) {
42013
+ if (!ctx.apps) {
42014
+ sendJson(ctx.res, 503, { ok: false, error: "Per-company Slack apps are off on this relay" });
42015
+ return;
42016
+ }
42017
+ const body = await readJson3(ctx.req);
42018
+ const writeToken = stringField(body, "writeToken");
42019
+ const clientId = stringField(body, "clientId");
42020
+ const clientSecret = stringField(body, "clientSecret");
42021
+ const signingSecret = stringField(body, "signingSecret");
42022
+ try {
42023
+ ctx.apps.saveCredentials(registrationId, writeToken, { clientId, clientSecret, signingSecret });
42024
+ } catch (err) {
42025
+ const message = err instanceof Error ? err.message : String(err);
42026
+ sendJson(ctx.res, 400, { ok: false, error: message });
42027
+ return;
42028
+ }
42029
+ sendJson(ctx.res, 200, { ok: true });
42030
+ }
42031
+ async function handleEvents(ctx, registrationId) {
42032
+ if (!ctx.apps) {
42033
+ sendJson(ctx.res, 503, { ok: false, error: "Per-company Slack apps are off on this relay" });
42034
+ return;
42035
+ }
42036
+ const app = ctx.apps.getByRegistration(registrationId);
42037
+ if (!app) {
42038
+ sendJson(ctx.res, 404, { ok: false, error: "Unknown Slack app" });
42039
+ return;
42040
+ }
42041
+ const raw = await readBody(ctx.req);
42042
+ const body = parseSlackEventsBody(raw);
42043
+ if (!body) {
42044
+ sendJson(ctx.res, 400, { ok: false, error: "Invalid JSON" });
42045
+ return;
42046
+ }
42047
+ if (body.type === "url_verification") {
42048
+ if (app.signingSecret && !signed(ctx, app.signingSecret, raw)) {
42049
+ sendJson(ctx.res, 401, { ok: false, error: "Bad signature" });
42050
+ return;
42051
+ }
42052
+ const challenge = typeof body.challenge === "string" ? body.challenge : "";
42053
+ sendJson(ctx.res, 200, { challenge });
42054
+ return;
42055
+ }
42056
+ if (body.type !== "event_callback") {
42057
+ sendJson(ctx.res, 200, { ok: true });
42058
+ return;
42059
+ }
42060
+ if (!app.signingSecret || !signed(ctx, app.signingSecret, raw)) {
42061
+ sendJson(ctx.res, 401, { ok: false, error: "Bad signature" });
42062
+ return;
42063
+ }
42064
+ const teamId = typeof body.team_id === "string" ? body.team_id.trim() : "";
42065
+ if (app.teamId && teamId && teamId !== app.teamId) {
42066
+ sendJson(ctx.res, 401, { ok: false, error: "Slack team does not match this app" });
42067
+ return;
42068
+ }
42069
+ const eventId = typeof body.event_id === "string" ? body.event_id : "";
42070
+ if (ctx.dedupe.duplicate(eventId)) {
42071
+ sendJson(ctx.res, 200, { ok: true });
42072
+ return;
42073
+ }
42074
+ sendJson(ctx.res, 200, { ok: true });
42075
+ if (!app.teamId) {
42076
+ ctx.log(`slack event ${eventId || "?"} before install for ${registrationId}`);
42077
+ return;
42078
+ }
42079
+ const life = lifecycleFromEventsBody(body);
42080
+ if (life?.kind === "app_uninstalled") {
42081
+ ctx.apps.clearInstall(life.teamId);
42082
+ ctx.grants.revokeTeam(life.teamId);
42083
+ ctx.hub.uninstallTeam(life.teamId);
42084
+ return;
42085
+ }
42086
+ if (life?.kind === "app_home_opened") {
42087
+ void ctx.hub.handleAppHomeOpened(life.teamId, life.userId);
42088
+ return;
42089
+ }
42090
+ const inbound = inboundFromEventsBody(body);
42091
+ if (inbound) ctx.hub.routeEvent(inbound);
42092
+ }
42093
+ function signed(ctx, signingSecret, raw) {
42094
+ const timestamp = header(ctx.req, "x-slack-request-timestamp");
42095
+ const signature = header(ctx.req, "x-slack-signature");
42096
+ return verifySlackRequestSignature({ signingSecret, timestamp, rawBody: raw, signature });
42097
+ }
42098
+ async function handleCallback(ctx, url) {
42099
+ const error = url.searchParams.get("error")?.trim();
42100
+ const state = url.searchParams.get("state")?.trim() ?? "";
42101
+ const code = url.searchParams.get("code")?.trim() ?? "";
42102
+ if (error) {
42103
+ if (state) ctx.pending.put(state, { ok: false, error: `Slack OAuth: ${error}` });
42104
+ sendHtml(ctx.res, 400, "Slack", `<h1>Authorization cancelled</h1><p>${escapeHtml2(error)}</p>`);
42105
+ return true;
42106
+ }
42107
+ if (!state || !code) {
42108
+ sendHtml(ctx.res, 400, "Slack", "<h1>Invalid callback</h1><p>State or code missing.</p>");
42109
+ return true;
42110
+ }
42111
+ try {
42112
+ const creds = resolveOAuthClient(ctx, state);
42113
+ const payload = await exchangeSlackOAuthCode({
42114
+ clientId: creds.clientId,
42115
+ clientSecret: creds.clientSecret,
42116
+ code,
42117
+ redirectUri: ctx.redirectUri,
42118
+ fetchImpl: ctx.fetchImpl
42119
+ });
42120
+ if (ctx.apps && payload.bot_token) {
42121
+ ctx.apps.recordInstall({
42122
+ clientId: creds.clientId,
42123
+ teamId: payload.team_id,
42124
+ botToken: payload.bot_token,
42125
+ botUserId: payload.bot_user_id ?? ""
42126
+ });
42127
+ }
42128
+ const listenGrant = payload.user_id ? ctx.grants.issue(payload.team_id, payload.user_id) : null;
42129
+ ctx.pending.put(state, {
42130
+ ok: true,
42131
+ payload: publicPayload({
42132
+ ...payload,
42133
+ ...listenGrant ? { listen_grant: listenGrant } : {}
42134
+ })
42135
+ });
42136
+ if (payload.bot_token) {
42137
+ ctx.hub.rememberBot(payload.team_id, payload.bot_token);
42138
+ if (payload.user_id) void ctx.hub.handleAppHomeOpened(payload.team_id, payload.user_id);
42139
+ }
42140
+ sendHtml(
42141
+ ctx.res,
42142
+ 200,
42143
+ "Slack connected",
42144
+ "<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>"
42145
+ );
42146
+ } catch (err) {
42147
+ const message = err instanceof Error ? err.message : String(err);
42148
+ ctx.pending.put(state, { ok: false, error: message });
42149
+ sendHtml(ctx.res, 400, "Slack", `<h1>Could not connect Slack</h1><p>${escapeHtml2(message)}</p>`);
42150
+ }
42151
+ return true;
42152
+ }
42153
+ function resolveOAuthClient(ctx, state) {
42154
+ const fromState = clientIdFromOAuthState(state);
42155
+ if (!fromState) {
42156
+ if (!ctx.bakedClientSecret) throw new Error("Relay is missing SIDEBOARD_SLACK_CLIENT_SECRET");
42157
+ return { clientId: ctx.bakedClientId, clientSecret: ctx.bakedClientSecret };
42158
+ }
42159
+ const secret = ctx.apps?.clientSecretFor(fromState);
42160
+ if (!secret) throw new Error("This Slack app is not registered on the relay");
42161
+ return { clientId: fromState, clientSecret: secret };
42162
+ }
42163
+ function publicPayload(payload) {
42164
+ return {
42165
+ team_id: payload.team_id,
42166
+ team_name: payload.team_name,
42167
+ user_id: payload.user_id,
42168
+ bot_token: payload.bot_token,
42169
+ user_token: payload.user_token,
42170
+ listen_grant: payload.listen_grant,
42171
+ scopes: payload.scopes
42172
+ };
42173
+ }
42174
+ function handleResult(ctx, url) {
42175
+ const state = url.searchParams.get("state")?.trim() ?? "";
42176
+ const value = ctx.pending.take(state);
42177
+ if (!value) {
42178
+ sendJson(ctx.res, 404, { ok: false, error: "pending" });
42179
+ return true;
42180
+ }
42181
+ if (!value.ok) {
42182
+ sendJson(ctx.res, 400, { ok: false, error: value.error });
42183
+ return true;
42184
+ }
42185
+ sendJson(ctx.res, 200, { ok: true, ...value.payload });
42186
+ return true;
42187
+ }
42188
+ function bearer(req) {
42189
+ const value = header(req, "authorization");
42190
+ const match = /^Bearer\s+(\S+)/i.exec(value);
42191
+ return match?.[1]?.trim() ?? "";
42192
+ }
42193
+ function header(req, name) {
42194
+ const value = req.headers[name];
42195
+ return typeof value === "string" ? value.trim() : "";
42196
+ }
42197
+ function stringField(body, key) {
42198
+ const value = body?.[key];
42199
+ return typeof value === "string" ? value : "";
42200
+ }
42201
+ async function readJson3(req) {
42202
+ const raw = await readBody(req);
42203
+ if (!raw) return null;
42204
+ try {
42205
+ const parsed = JSON.parse(raw);
42206
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
42207
+ return parsed;
42208
+ } catch {
42209
+ return null;
42210
+ }
42211
+ }
42212
+ function readBody(req) {
42213
+ return new Promise((resolve3, reject) => {
42214
+ const chunks = [];
42215
+ let size = 0;
42216
+ req.on("data", (chunk) => {
42217
+ const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
42218
+ size += buf.length;
42219
+ if (size > BODY_LIMIT) {
42220
+ reject(new Error("body too large"));
42221
+ req.destroy();
42222
+ return;
42223
+ }
42224
+ chunks.push(buf);
42225
+ });
42226
+ req.on("end", () => resolve3(Buffer.concat(chunks).toString("utf8")));
42227
+ req.on("error", reject);
42228
+ });
42229
+ }
42230
+ function sendHtml(res, status, title, body) {
42231
+ res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
42232
+ res.end(slackOAuthHtmlPage(title, body));
42233
+ }
42234
+ function sendJson(res, status, body) {
42235
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
42236
+ res.end(JSON.stringify(body));
42237
+ }
42238
+
42239
+ // src/relay/slack-apps.ts
42240
+ var import_node_crypto26 = require("crypto");
42241
+ var import_node_fs72 = require("fs");
42242
+ var import_node_module7 = require("module");
42243
+ var import_node_path72 = require("path");
42244
+ var SlackAppStore = class {
42245
+ db;
42246
+ key;
42247
+ constructor(filePath, key) {
42248
+ if (key.length !== 32) throw new Error("Slack token key must be 32 bytes");
42249
+ (0, import_node_fs72.mkdirSync)((0, import_node_path72.dirname)(filePath), { recursive: true });
42250
+ this.key = key;
42251
+ this.db = openDatabase(filePath);
42252
+ this.db.exec(`
42253
+ CREATE TABLE IF NOT EXISTS slack_apps (
42254
+ registration_id TEXT PRIMARY KEY,
42255
+ account_id TEXT NOT NULL,
42256
+ write_token_hash TEXT NOT NULL,
42257
+ team_id TEXT,
42258
+ client_id TEXT,
42259
+ client_secret_enc TEXT,
42260
+ signing_secret_enc TEXT,
42261
+ bot_token_enc TEXT,
42262
+ bot_user_id TEXT,
42263
+ created_at INTEGER NOT NULL
42264
+ );
42265
+ CREATE UNIQUE INDEX IF NOT EXISTS slack_apps_client
42266
+ ON slack_apps(client_id) WHERE client_id IS NOT NULL;
42267
+ CREATE UNIQUE INDEX IF NOT EXISTS slack_apps_team
42268
+ ON slack_apps(team_id) WHERE team_id IS NOT NULL;
42269
+ `);
42270
+ }
42271
+ close() {
42272
+ this.db.close();
42273
+ }
42274
+ /** Mint a row. The write token is returned once and authorizes credential upload. */
42275
+ create(accountId) {
42276
+ const owner = accountId.trim();
42277
+ if (!owner) throw new Error("Slack app registration needs a Sideboard account");
42278
+ const registrationId = (0, import_node_crypto26.randomBytes)(16).toString("base64url");
42279
+ const writeToken = (0, import_node_crypto26.randomBytes)(32).toString("base64url");
42280
+ this.db.prepare(
42281
+ `INSERT INTO slack_apps (
42282
+ registration_id, account_id, write_token_hash, created_at
42283
+ ) VALUES (?, ?, ?, ?)`
42284
+ ).run(registrationId, owner, sha2562(writeToken), Date.now());
42285
+ return { registrationId, writeToken };
42286
+ }
42287
+ saveCredentials(registrationId, writeToken, creds) {
42288
+ const row2 = this.row(registrationId);
42289
+ if (!row2 || !sameHash(row2.write_token_hash, sha2562(writeToken.trim()))) {
42290
+ throw new Error("Slack app write token was rejected");
42291
+ }
42292
+ const clientId = creds.clientId.trim();
42293
+ const clientSecret = creds.clientSecret.trim();
42294
+ const signingSecret = creds.signingSecret.trim();
42295
+ if (!clientId || !clientSecret || !signingSecret) {
42296
+ throw new Error("Slack app credentials need a client id, client secret, and signing secret");
42297
+ }
42298
+ const taken = this.db.prepare(
42299
+ "SELECT registration_id FROM slack_apps WHERE client_id = ? AND registration_id != ?"
42300
+ ).get(clientId, row2.registration_id);
42301
+ if (taken) throw new Error("That Slack client id is already registered");
42302
+ this.db.prepare(
42303
+ `UPDATE slack_apps
42304
+ SET client_id = ?, client_secret_enc = ?, signing_secret_enc = ?
42305
+ WHERE registration_id = ?`
42306
+ ).run(clientId, sealSecret(this.key, clientSecret), sealSecret(this.key, signingSecret), row2.registration_id);
42307
+ }
42308
+ clientSecretFor(clientId) {
42309
+ const id = clientId.trim();
42310
+ if (!id) return null;
42311
+ const row2 = this.db.prepare("SELECT client_secret_enc FROM slack_apps WHERE client_id = ?").get(id);
42312
+ if (!row2?.client_secret_enc) return null;
42313
+ return openSecret(this.key, row2.client_secret_enc);
42314
+ }
42315
+ /**
42316
+ * OAuth finished for this client id. Rejects a different bot user than the
42317
+ * one already stored for the company.
42318
+ */
42319
+ recordInstall(input) {
42320
+ const clientId = input.clientId.trim();
42321
+ const teamId = input.teamId.trim();
42322
+ const botToken = input.botToken.trim();
42323
+ const botUserId = input.botUserId.trim();
42324
+ if (!clientId || !teamId || !botToken) return false;
42325
+ const row2 = this.db.prepare("SELECT registration_id, team_id, bot_user_id FROM slack_apps WHERE client_id = ?").get(clientId);
42326
+ if (!row2) return false;
42327
+ if (row2.team_id && row2.team_id !== teamId) {
42328
+ throw new Error("This Slack app is already installed on another workspace");
42329
+ }
42330
+ if (botUserId && row2.bot_user_id && row2.bot_user_id !== botUserId) {
42331
+ throw new Error("This Slack app\u2019s bot user does not match the stored install");
42332
+ }
42333
+ this.db.prepare(
42334
+ `UPDATE slack_apps
42335
+ SET team_id = ?, bot_token_enc = ?, bot_user_id = COALESCE(?, bot_user_id)
42336
+ WHERE registration_id = ?`
42337
+ ).run(teamId, sealSecret(this.key, botToken), botUserId || null, row2.registration_id);
42338
+ return true;
42339
+ }
42340
+ /** Error string when a desktop presents a different bot than the company app. */
42341
+ botUserMismatch(teamId, botUserId) {
42342
+ const row2 = this.teamRow(teamId);
42343
+ if (!row2?.bot_user_id) return null;
42344
+ if (row2.bot_user_id === botUserId.trim()) return null;
42345
+ return "This Mac\u2019s bot token is not the company\u2019s Sideboard Slack app";
42346
+ }
42347
+ /** Refresh the stored bot token after a desktop register for this team. */
42348
+ saveBot(teamId, botToken, botUserId) {
42349
+ const row2 = this.teamRow(teamId);
42350
+ const token = botToken.trim();
42351
+ const user = botUserId.trim();
42352
+ if (!row2 || !token || !user) return;
42353
+ if (row2.bot_user_id && row2.bot_user_id !== user) return;
42354
+ 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);
42355
+ }
42356
+ getByRegistration(registrationId) {
42357
+ const row2 = this.row(registrationId);
42358
+ if (!row2) return null;
42359
+ return {
42360
+ registrationId: row2.registration_id,
42361
+ teamId: row2.team_id,
42362
+ signingSecret: row2.signing_secret_enc ? openSecret(this.key, row2.signing_secret_enc) : null
42363
+ };
42364
+ }
42365
+ listBots() {
42366
+ const rows = this.db.prepare(
42367
+ `SELECT team_id, bot_token_enc FROM slack_apps
42368
+ WHERE team_id IS NOT NULL AND bot_token_enc IS NOT NULL`
42369
+ ).all();
42370
+ return rows.map((row2) => ({
42371
+ teamId: row2.team_id,
42372
+ botToken: openSecret(this.key, row2.bot_token_enc)
42373
+ }));
42374
+ }
42375
+ /**
42376
+ * Slack removed the install. Drop the bot token and team so a reinstall can
42377
+ * record again. Keep the client id, secrets, and registration id — the events
42378
+ * URL in the Slack app is that registration id.
42379
+ */
42380
+ clearInstall(teamId) {
42381
+ const id = teamId.trim();
42382
+ if (!id) return;
42383
+ this.db.prepare(
42384
+ `UPDATE slack_apps
42385
+ SET team_id = NULL, bot_token_enc = NULL, bot_user_id = NULL
42386
+ WHERE team_id = ?`
42387
+ ).run(id);
42388
+ }
42389
+ row(registrationId) {
42390
+ const id = registrationId.trim();
42391
+ if (!id) return null;
42392
+ return this.db.prepare("SELECT * FROM slack_apps WHERE registration_id = ?").get(id) ?? null;
42393
+ }
42394
+ teamRow(teamId) {
42395
+ const id = teamId.trim();
42396
+ if (!id) return null;
42397
+ return this.db.prepare("SELECT * FROM slack_apps WHERE team_id = ?").get(id) ?? null;
42398
+ }
42399
+ };
42400
+ function sha2562(value) {
42401
+ return (0, import_node_crypto26.createHash)("sha256").update(value).digest("hex");
42402
+ }
42403
+ function sameHash(stored, presented) {
42404
+ const left = Buffer.from(stored);
42405
+ const right = Buffer.from(presented);
42406
+ return left.length === right.length && (0, import_node_crypto26.timingSafeEqual)(left, right);
42407
+ }
42408
+ function thisModuleFile3() {
42409
+ const cjsFile = typeof __filename !== "undefined" ? __filename : "";
42410
+ return cjsFile || process.argv[1] || (0, import_node_path72.join)(process.cwd(), "package.json");
42411
+ }
42412
+ function openDatabase(filePath) {
42413
+ const req = (0, import_node_module7.createRequire)(thisModuleFile3());
42414
+ const { DatabaseSync: SqliteDatabase } = req("node:sqlite");
42415
+ const db = new SqliteDatabase(filePath);
42416
+ db.exec("PRAGMA journal_mode = WAL");
42417
+ return db;
42418
+ }
42419
+
42420
+ // src/relay/slack-grants.ts
42421
+ var import_node_crypto28 = require("crypto");
42422
+ var import_node_fs73 = require("fs");
42423
+ var import_node_module8 = require("module");
42424
+ var import_node_path73 = require("path");
42425
+
42426
+ // src/slack/listen-grant.ts
42427
+ var import_node_crypto27 = require("crypto");
42428
+ var MemorySlackListenGrants = class {
42429
+ rows = /* @__PURE__ */ new Map();
42430
+ issue(teamId, userId) {
42431
+ const team = teamId.trim();
42432
+ const user = userId.trim();
42433
+ if (!team || !user) return null;
42434
+ const grant = (0, import_node_crypto27.randomBytes)(32).toString("base64url");
42435
+ this.rows.set(hashListenGrant(grant), { teamId: team, userId: user });
42436
+ return grant;
42437
+ }
42438
+ verify(teamId, userId, grant) {
42439
+ const token = grant.trim();
42440
+ if (!token) return false;
42441
+ const row2 = this.rows.get(hashListenGrant(token));
42442
+ if (!row2) return false;
42443
+ return row2.teamId === teamId.trim() && row2.userId === userId.trim();
42444
+ }
42445
+ revokeTeam(teamId) {
42446
+ const team = teamId.trim();
42447
+ if (!team) return;
42448
+ for (const [hash, row2] of this.rows) {
42449
+ if (row2.teamId === team) this.rows.delete(hash);
42450
+ }
42451
+ }
42452
+ close() {
42453
+ this.rows.clear();
42454
+ }
42455
+ };
42456
+ function hashListenGrant(grant) {
42457
+ return (0, import_node_crypto27.createHash)("sha256").update(grant.trim()).digest("hex");
42458
+ }
42459
+
42460
+ // src/relay/slack-grants.ts
42461
+ var SlackListenGrantStore = class {
42462
+ db;
42463
+ constructor(filePath) {
42464
+ (0, import_node_fs73.mkdirSync)((0, import_node_path73.dirname)(filePath), { recursive: true });
42465
+ this.db = openDatabase2(filePath);
42466
+ this.db.exec(`
42467
+ CREATE TABLE IF NOT EXISTS slack_listen_grants (
42468
+ grant_hash TEXT PRIMARY KEY,
42469
+ team_id TEXT NOT NULL,
42470
+ user_id TEXT NOT NULL,
42471
+ created_at INTEGER NOT NULL
42472
+ );
42473
+ CREATE INDEX IF NOT EXISTS slack_listen_grants_team
42474
+ ON slack_listen_grants(team_id);
42475
+ `);
42476
+ }
42477
+ close() {
42478
+ this.db.close();
42479
+ }
42480
+ issue(teamId, userId) {
42481
+ const team = teamId.trim();
42482
+ const user = userId.trim();
42483
+ if (!team || !user) return null;
42484
+ const grant = (0, import_node_crypto28.randomBytes)(32).toString("base64url");
42485
+ this.db.prepare(
42486
+ `INSERT INTO slack_listen_grants (grant_hash, team_id, user_id, created_at)
42487
+ VALUES (?, ?, ?, ?)`
42488
+ ).run(hashListenGrant(grant), team, user, Date.now());
42489
+ return grant;
42490
+ }
42491
+ verify(teamId, userId, grant) {
42492
+ const token = grant.trim();
42493
+ const team = teamId.trim();
42494
+ const user = userId.trim();
42495
+ if (!token || !team || !user) return false;
42496
+ const row2 = this.db.prepare("SELECT team_id, user_id FROM slack_listen_grants WHERE grant_hash = ?").get(hashListenGrant(token));
42497
+ return row2?.team_id === team && row2.user_id === user;
42498
+ }
42499
+ revokeTeam(teamId) {
42500
+ const team = teamId.trim();
42501
+ if (!team) return;
42502
+ this.db.prepare("DELETE FROM slack_listen_grants WHERE team_id = ?").run(team);
42503
+ }
42504
+ };
42505
+ function thisModuleFile4() {
42506
+ const cjsFile = typeof __filename !== "undefined" ? __filename : "";
42507
+ return cjsFile || process.argv[1] || (0, import_node_path73.join)(process.cwd(), "package.json");
42508
+ }
42509
+ function openDatabase2(filePath) {
42510
+ const req = (0, import_node_module8.createRequire)(thisModuleFile4());
42511
+ const { DatabaseSync: SqliteDatabase } = req("node:sqlite");
42512
+ const db = new SqliteDatabase(filePath);
42513
+ db.exec("PRAGMA journal_mode = WAL");
42514
+ return db;
42515
+ }
42516
+
41481
42517
  // src/slack/relay-protocol.ts
41482
- var import_node_crypto23 = require("crypto");
42518
+ var import_node_crypto29 = require("crypto");
41483
42519
  var SLACK_RELAY_PING_INTERVAL_MS = 2e4;
41484
42520
  var SLACK_RELAY_PONG_TIMEOUT_MS = 15e3;
41485
42521
  function slackRelaySessionKey(teamId, userId, deviceId) {
@@ -41489,7 +42525,7 @@ function slackRelayUserKey(teamId, userId) {
41489
42525
  return `${teamId.trim()}:${userId.trim()}`;
41490
42526
  }
41491
42527
  function newSlackRelayEventId() {
41492
- return (0, import_node_crypto23.randomBytes)(12).toString("hex");
42528
+ return (0, import_node_crypto29.randomBytes)(12).toString("hex");
41493
42529
  }
41494
42530
  function parseSlackRelayClientMessage(raw) {
41495
42531
  try {
@@ -41508,7 +42544,8 @@ function parseSlackRelayClientMessage(raw) {
41508
42544
  const deviceLabel = typeof parsed.deviceLabel === "string" ? parsed.deviceLabel.trim() : void 0;
41509
42545
  const botToken = typeof parsed.botToken === "string" ? parsed.botToken.trim() : "";
41510
42546
  const userToken = typeof parsed.userToken === "string" ? parsed.userToken.trim() : "";
41511
- if (!teamId || !userId || !deviceId || !botToken || !userToken) return null;
42547
+ const listenGrant = typeof parsed.listenGrant === "string" ? parsed.listenGrant.trim() : "";
42548
+ if (!teamId || !userId || !deviceId || !botToken || !userToken && !listenGrant) return null;
41512
42549
  return {
41513
42550
  type: "register",
41514
42551
  teamId,
@@ -41516,7 +42553,8 @@ function parseSlackRelayClientMessage(raw) {
41516
42553
  deviceId,
41517
42554
  deviceLabel: deviceLabel || void 0,
41518
42555
  botToken,
41519
- userToken
42556
+ ...userToken ? { userToken } : {},
42557
+ ...listenGrant ? { listenGrant } : {}
41520
42558
  };
41521
42559
  }
41522
42560
  return null;
@@ -41567,10 +42605,10 @@ function parseSlackRelayServerMessage(raw) {
41567
42605
 
41568
42606
  // src/slack/app-home.ts
41569
42607
  var SLACK_APP_HOME_DOWNLOAD = "https://sideboard-downloads.t3.tigrisfiles.io/Sideboard-latest-arm64.dmg";
41570
- var SLACK_APP_HOME_LANDING = "https://www.sideboard.cloud/slack/";
41571
- var SLACK_APP_HOME_PRIVACY = "https://www.sideboard.cloud/privacy/";
41572
- var SLACK_APP_HOME_SUPPORT = "https://www.sideboard.cloud/support/";
41573
- var SLACK_APP_HOME_SUPPORT_EMAIL = "support@sideboard.cloud";
42608
+ var SLACK_APP_HOME_LANDING = "https://www.sideboard.build/slack/";
42609
+ var SLACK_APP_HOME_PRIVACY = "https://www.sideboard.build/privacy/";
42610
+ var SLACK_APP_HOME_SUPPORT = "https://www.sideboard.build/support/";
42611
+ var SLACK_APP_HOME_SUPPORT_EMAIL = "support@sideboard.build";
41574
42612
  var SLACK_NO_MAC_ONLINE_REPLY = [
41575
42613
  "No Sideboard Mac is online for your Slack user.",
41576
42614
  "Open Sideboard \u2192 Settings \u2192 Remote and wait for Relay connected.",
@@ -41588,7 +42626,7 @@ function slackAppHomeView(opts) {
41588
42626
  "",
41589
42627
  "*First run*",
41590
42628
  "1. Download Sideboard for Apple Silicon and keep it open.",
41591
- "2. Settings \u2192 Remote \u2192 Slack \u2192 Add via browser. Name this Mac (`Work`, `Personal`, \u2026).",
42629
+ "2. Settings \u2192 Collaboration \u2192 Add via browser. Name this Mac on Settings \u2192 Remote (`Work`, `Personal`, \u2026).",
41592
42630
  "3. Wait until status shows Relay connected, then DM @Sideboard."
41593
42631
  ].join("\n");
41594
42632
  return {
@@ -41662,11 +42700,26 @@ var SlackRelayHub = class {
41662
42700
  fetchImpl;
41663
42701
  authTest;
41664
42702
  log;
42703
+ guardBotUser = null;
42704
+ onBotAccepted = null;
42705
+ verifyListenGrant = null;
41665
42706
  constructor(opts = {}) {
41666
42707
  this.fetchImpl = opts.fetchImpl;
41667
42708
  this.log = opts.onLog ?? (() => void 0);
41668
42709
  this.authTest = opts.authTest ?? (async (token) => slackApi(token, "auth.test", void 0, this.fetchImpl));
41669
42710
  }
42711
+ /**
42712
+ * Company apps reject a bot user that is not the one stored for that team,
42713
+ * then persist a matching bot token. The baked app leaves both unset.
42714
+ */
42715
+ setBotHooks(hooks2) {
42716
+ this.guardBotUser = hooks2.guardBotUser ?? null;
42717
+ this.onBotAccepted = hooks2.onBotAccepted ?? null;
42718
+ }
42719
+ /** Accept a relay listen grant in place of a Slack user token. */
42720
+ setListenGrantVerifier(verify2) {
42721
+ this.verifyListenGrant = verify2;
42722
+ }
41670
42723
  sessionFor(teamId, userId, deviceId) {
41671
42724
  return this.sessions.get(slackRelaySessionKey(teamId, userId, deviceId)) ?? null;
41672
42725
  }
@@ -41705,43 +42758,61 @@ var SlackRelayHub = class {
41705
42758
  msg.deviceId,
41706
42759
  msg.deviceLabel,
41707
42760
  msg.botToken,
41708
- msg.userToken
42761
+ msg.userToken ?? "",
42762
+ msg.listenGrant
41709
42763
  );
41710
42764
  }
41711
42765
  }
41712
- async register(socket, teamId, userId, deviceId, deviceLabel, botToken, userToken) {
42766
+ async register(socket, teamId, userId, deviceId, deviceLabel, botToken, userToken, listenGrant) {
41713
42767
  const claimedTeam = teamId.trim();
41714
42768
  const claimedUser = userId.trim();
41715
42769
  const claimedDevice = deviceId.trim();
41716
42770
  const label = (deviceLabel?.trim() || claimedDevice).slice(0, 64);
41717
42771
  const bot = botToken.trim();
41718
42772
  const user = userToken.trim();
41719
- if (!claimedTeam || !claimedUser || !claimedDevice || !bot || !user) {
42773
+ const grant = listenGrant?.trim() ?? "";
42774
+ let botUserId = "";
42775
+ if (!claimedTeam || !claimedUser || !claimedDevice || !bot || !user && !grant) {
41720
42776
  this.send(socket, {
41721
42777
  type: "error",
41722
- message: "register needs teamId, userId, deviceId, botToken, and userToken"
42778
+ message: "register needs teamId, userId, deviceId, botToken, and a user token or listen grant"
41723
42779
  });
41724
42780
  return;
41725
42781
  }
41726
42782
  try {
41727
- const userAuth = await this.authTest(user);
41728
- const userTeam = userAuth.team_id?.trim();
41729
- const userAuthId = userAuth.user_id?.trim();
41730
- if (!userTeam || !userAuthId) {
41731
- this.send(socket, {
41732
- type: "error",
41733
- message: "user token auth.test did not return team_id/user_id"
41734
- });
41735
- return;
42783
+ let proved = false;
42784
+ if (user) {
42785
+ try {
42786
+ const userAuth = await this.authTest(user);
42787
+ const userTeam = userAuth.team_id?.trim();
42788
+ const userAuthId = userAuth.user_id?.trim();
42789
+ if (!userTeam || !userAuthId) {
42790
+ if (!grant) {
42791
+ this.send(socket, {
42792
+ type: "error",
42793
+ message: "user token auth.test did not return team_id/user_id"
42794
+ });
42795
+ return;
42796
+ }
42797
+ } else if (userTeam !== claimedTeam || userAuthId !== claimedUser) {
42798
+ this.send(socket, {
42799
+ type: "error",
42800
+ message: `User token identity ${userTeam}/${userAuthId} does not match claimed ${claimedTeam}/${claimedUser}`
42801
+ });
42802
+ this.log(
42803
+ `register rejected: claimed ${claimedTeam}/${claimedUser} user-token ${userTeam}/${userAuthId}`
42804
+ );
42805
+ return;
42806
+ } else {
42807
+ proved = true;
42808
+ }
42809
+ } catch (err) {
42810
+ if (!grant) throw err;
42811
+ }
41736
42812
  }
41737
- if (userTeam !== claimedTeam || userAuthId !== claimedUser) {
41738
- this.send(socket, {
41739
- type: "error",
41740
- message: `User token identity ${userTeam}/${userAuthId} does not match claimed ${claimedTeam}/${claimedUser}`
41741
- });
41742
- this.log(
41743
- `register rejected: claimed ${claimedTeam}/${claimedUser} user-token ${userTeam}/${userAuthId}`
41744
- );
42813
+ if (!proved && !this.verifyListenGrant?.(claimedTeam, claimedUser, grant)) {
42814
+ this.send(socket, { type: "error", message: "listen grant was rejected" });
42815
+ this.log(`register rejected: ${claimedTeam}/${claimedUser} listen grant`);
41745
42816
  return;
41746
42817
  }
41747
42818
  const botAuth = await this.authTest(bot);
@@ -41761,6 +42832,22 @@ var SlackRelayHub = class {
41761
42832
  this.log(`register rejected: claimed team ${claimedTeam} bot ${botTeam}`);
41762
42833
  return;
41763
42834
  }
42835
+ botUserId = botAuth.user_id?.trim() ?? "";
42836
+ if (this.guardBotUser) {
42837
+ if (!botUserId) {
42838
+ this.send(socket, {
42839
+ type: "error",
42840
+ message: "bot token auth.test did not return user_id"
42841
+ });
42842
+ return;
42843
+ }
42844
+ const guard = this.guardBotUser(claimedTeam, botUserId);
42845
+ if (guard) {
42846
+ this.send(socket, { type: "error", message: guard });
42847
+ this.log(`register rejected: ${claimedTeam} bot user ${botUserId}`);
42848
+ return;
42849
+ }
42850
+ }
41764
42851
  } catch (err) {
41765
42852
  const errMsg = err instanceof Error ? err.message : String(err);
41766
42853
  this.send(socket, { type: "error", message: `auth.test failed: ${errMsg}` });
@@ -41788,6 +42875,7 @@ var SlackRelayHub = class {
41788
42875
  this.sessions.set(key, session);
41789
42876
  this.bySocket.set(socket, key);
41790
42877
  this.rememberBot(claimedTeam, bot);
42878
+ if (botUserId) this.onBotAccepted?.(claimedTeam, bot, botUserId);
41791
42879
  this.send(socket, {
41792
42880
  type: "registered",
41793
42881
  teamId: claimedTeam,
@@ -41942,9 +43030,9 @@ var SlackRelayHub = class {
41942
43030
  };
41943
43031
 
41944
43032
  // src/relay/static.ts
41945
- var import_node_fs72 = require("fs");
43033
+ var import_node_fs74 = require("fs");
41946
43034
  var import_promises = require("fs/promises");
41947
- var import_node_path71 = __toESM(require("path"), 1);
43035
+ var import_node_path74 = __toESM(require("path"), 1);
41948
43036
  var TYPES = {
41949
43037
  ".css": "text/css; charset=utf-8",
41950
43038
  ".html": "text/html; charset=utf-8",
@@ -41957,6 +43045,7 @@ var TYPES = {
41957
43045
  ".svg": "image/svg+xml",
41958
43046
  ".txt": "text/plain; charset=utf-8",
41959
43047
  ".webp": "image/webp",
43048
+ ".xml": "application/xml; charset=utf-8",
41960
43049
  ".woff2": "font/woff2"
41961
43050
  };
41962
43051
  function requestHostname(req) {
@@ -41967,6 +43056,45 @@ function hostnameAllowed(host, allowed) {
41967
43056
  if (!allowed || allowed.length === 0) return true;
41968
43057
  return allowed.includes(host);
41969
43058
  }
43059
+ var CANONICAL_SITE_HOST = "www.sideboard.build";
43060
+ function isOAuthSitePath(pathname) {
43061
+ return pathname === "/oauth" || pathname.startsWith("/oauth/");
43062
+ }
43063
+ function marketingRedirectLocation(opts) {
43064
+ let pathname = "/";
43065
+ let search = "";
43066
+ try {
43067
+ const url = new URL(opts.requestUrl, "http://relay.local");
43068
+ pathname = url.pathname;
43069
+ search = url.search;
43070
+ } catch {
43071
+ return null;
43072
+ }
43073
+ const hostname2 = opts.hostname.toLowerCase();
43074
+ const canonical = opts.canonicalHost.toLowerCase();
43075
+ const staticHosts = opts.staticHosts ?? [];
43076
+ const listedSite = staticHosts.length > 0 && staticHosts.includes(hostname2);
43077
+ const listedRedirect = (opts.redirectHosts ?? []).includes(hostname2);
43078
+ const alias = hostname2 !== canonical && (listedSite || listedRedirect);
43079
+ if (alias && !isOAuthSitePath(pathname)) {
43080
+ return `https://${canonical}${pathname}${search}`;
43081
+ }
43082
+ return null;
43083
+ }
43084
+ async function directorySlashLocation(root, requestUrl) {
43085
+ let url;
43086
+ try {
43087
+ url = new URL(requestUrl, "http://relay.local");
43088
+ } catch {
43089
+ return null;
43090
+ }
43091
+ if (isOAuthSitePath(url.pathname) || url.pathname.endsWith("/")) return null;
43092
+ const candidate = resolveStaticPath(root, requestUrl);
43093
+ if (!candidate) return null;
43094
+ if (await fileSize(candidate) != null) return null;
43095
+ if (await fileSize(import_node_path74.default.join(candidate, "index.html")) == null) return null;
43096
+ return `${url.pathname}/${url.search}`;
43097
+ }
41970
43098
  function resolveStaticPath(root, requestUrl) {
41971
43099
  let pathname;
41972
43100
  try {
@@ -41975,9 +43103,9 @@ function resolveStaticPath(root, requestUrl) {
41975
43103
  return null;
41976
43104
  }
41977
43105
  if (!pathname.startsWith("/") || pathname.includes("\0")) return null;
41978
- const rootResolved = import_node_path71.default.resolve(root);
41979
- const candidate = import_node_path71.default.resolve(rootResolved, `.${pathname}`);
41980
- if (candidate !== rootResolved && !candidate.startsWith(rootResolved + import_node_path71.default.sep)) {
43106
+ const rootResolved = import_node_path74.default.resolve(root);
43107
+ const candidate = import_node_path74.default.resolve(rootResolved, `.${pathname}`);
43108
+ if (candidate !== rootResolved && !candidate.startsWith(rootResolved + import_node_path74.default.sep)) {
41981
43109
  return null;
41982
43110
  }
41983
43111
  return candidate;
@@ -41991,7 +43119,7 @@ async function fileSize(file) {
41991
43119
  }
41992
43120
  }
41993
43121
  function sendFile(req, res, file, size) {
41994
- const ext = import_node_path71.default.extname(file).toLowerCase();
43122
+ const ext = import_node_path74.default.extname(file).toLowerCase();
41995
43123
  res.writeHead(200, {
41996
43124
  "Content-Type": TYPES[ext] ?? "application/octet-stream",
41997
43125
  "Content-Length": size,
@@ -42001,23 +43129,52 @@ function sendFile(req, res, file, size) {
42001
43129
  res.end();
42002
43130
  return true;
42003
43131
  }
42004
- (0, import_node_fs72.createReadStream)(file).pipe(res);
43132
+ (0, import_node_fs74.createReadStream)(file).pipe(res);
42005
43133
  return true;
42006
43134
  }
43135
+ async function serveMarketingSite(req, res, opts) {
43136
+ const reqUrl = req.url || "/";
43137
+ const hostname2 = requestHostname(req);
43138
+ const canonical = opts.canonicalHost.toLowerCase();
43139
+ if (req.method === "GET" || req.method === "HEAD") {
43140
+ const location = marketingRedirectLocation({
43141
+ requestUrl: reqUrl,
43142
+ hostname: hostname2,
43143
+ canonicalHost: canonical,
43144
+ staticHosts: opts.staticHosts,
43145
+ redirectHosts: opts.redirectHosts
43146
+ });
43147
+ if (location) {
43148
+ res.writeHead(301, { Location: location });
43149
+ res.end();
43150
+ return true;
43151
+ }
43152
+ if (hostnameAllowed(hostname2, opts.staticHosts)) {
43153
+ const slash = await directorySlashLocation(opts.root, reqUrl);
43154
+ if (slash) {
43155
+ res.writeHead(301, { Location: slash });
43156
+ res.end();
43157
+ return true;
43158
+ }
43159
+ }
43160
+ }
43161
+ if (!hostnameAllowed(hostname2, opts.staticHosts)) return false;
43162
+ return tryServeStatic(req, res, opts.root);
43163
+ }
42007
43164
  async function tryServeStatic(req, res, root) {
42008
43165
  if (req.method !== "GET" && req.method !== "HEAD") return false;
42009
43166
  const candidate = resolveStaticPath(root, req.url || "/");
42010
43167
  if (!candidate) return false;
42011
43168
  const direct = await fileSize(candidate);
42012
43169
  if (direct != null) return sendFile(req, res, candidate, direct);
42013
- const asIndex = import_node_path71.default.join(candidate, "index.html");
43170
+ const asIndex = import_node_path74.default.join(candidate, "index.html");
42014
43171
  const indexSize = await fileSize(asIndex);
42015
43172
  if (indexSize != null) return sendFile(req, res, asIndex, indexSize);
42016
43173
  return false;
42017
43174
  }
42018
43175
 
42019
43176
  // src/remote/hub.ts
42020
- var import_node_crypto24 = require("crypto");
43177
+ var import_node_crypto30 = require("crypto");
42021
43178
  init_protocol();
42022
43179
  var CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
42023
43180
  var CODE_TTL_MS = 10 * 60 * 1e3;
@@ -42028,7 +43185,7 @@ function send(socket, msg) {
42028
43185
  }
42029
43186
  }
42030
43187
  function newCode() {
42031
- const bytes = (0, import_node_crypto24.randomBytes)(6);
43188
+ const bytes = (0, import_node_crypto30.randomBytes)(6);
42032
43189
  let code = "";
42033
43190
  for (let i = 0; i < 6; i++) code += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
42034
43191
  return code;
@@ -42299,7 +43456,7 @@ var RemoteHub = class {
42299
43456
  host.phone = null;
42300
43457
  }
42301
43458
  const created = sessionToken == null;
42302
- const token = sessionToken ?? (0, import_node_crypto24.randomBytes)(24).toString("hex");
43459
+ const token = sessionToken ?? (0, import_node_crypto30.randomBytes)(24).toString("hex");
42303
43460
  if (host.sessionToken && host.sessionToken !== token) {
42304
43461
  this.phonesByToken.delete(host.sessionToken);
42305
43462
  }
@@ -42352,32 +43509,32 @@ var RemoteHub = class {
42352
43509
  init_protocol();
42353
43510
 
42354
43511
  // src/relay/accounts.ts
42355
- var import_node_crypto25 = require("crypto");
42356
- var import_node_fs73 = require("fs");
42357
- var import_node_module7 = require("module");
42358
- var import_node_path72 = require("path");
43512
+ var import_node_crypto31 = require("crypto");
43513
+ var import_node_fs75 = require("fs");
43514
+ var import_node_module9 = require("module");
43515
+ var import_node_path75 = require("path");
42359
43516
  var GITHUB_ACCOUNT_ISSUER = "https://github.com";
42360
43517
  var CURSOR_ACCOUNT_ISSUER = "https://api.cursor.com/v1/origin";
42361
43518
  var RELAY_DEVICE_CAP = 3;
42362
- function thisModuleFile3() {
43519
+ function thisModuleFile5() {
42363
43520
  const cjsFile = typeof __filename !== "undefined" ? __filename : "";
42364
- return cjsFile || process.argv[1] || (0, import_node_path72.join)(process.cwd(), "package.json");
43521
+ return cjsFile || process.argv[1] || (0, import_node_path75.join)(process.cwd(), "package.json");
42365
43522
  }
42366
- function openDatabase(filePath) {
42367
- const req = (0, import_node_module7.createRequire)(thisModuleFile3());
43523
+ function openDatabase3(filePath) {
43524
+ const req = (0, import_node_module9.createRequire)(thisModuleFile5());
42368
43525
  const specifier = "node:sqlite";
42369
43526
  const { DatabaseSync: SqliteDatabase } = req(specifier);
42370
43527
  const db = new SqliteDatabase(filePath);
42371
43528
  db.exec("PRAGMA journal_mode = WAL");
42372
43529
  return db;
42373
43530
  }
42374
- function sha2562(value) {
42375
- return (0, import_node_crypto25.createHash)("sha256").update(value).digest("hex");
43531
+ function sha2563(value) {
43532
+ return (0, import_node_crypto31.createHash)("sha256").update(value).digest("hex");
42376
43533
  }
42377
- function sameHash(a, b) {
43534
+ function sameHash2(a, b) {
42378
43535
  const left = Buffer.from(a);
42379
43536
  const right = Buffer.from(b);
42380
- return left.length === right.length && (0, import_node_crypto25.timingSafeEqual)(left, right);
43537
+ return left.length === right.length && (0, import_node_crypto31.timingSafeEqual)(left, right);
42381
43538
  }
42382
43539
  function normalizeEmail(email) {
42383
43540
  const trimmed = email?.trim().toLowerCase() ?? "";
@@ -42398,8 +43555,8 @@ function assertRelayAccountsDurable(filePath) {
42398
43555
  if (process.env.SIDEBOARD_RELAY_ACCOUNTS_EPHEMERAL === "1") return;
42399
43556
  if (process.env.NODE_ENV !== "production") return;
42400
43557
  if (process.platform !== "linux") return;
42401
- const dir = (0, import_node_fs73.realpathSync)((0, import_node_path72.dirname)(filePath));
42402
- const mounts = (0, import_node_fs73.readFileSync)("/proc/mounts", "utf8");
43558
+ const dir = (0, import_node_fs75.realpathSync)((0, import_node_path75.dirname)(filePath));
43559
+ const mounts = (0, import_node_fs75.readFileSync)("/proc/mounts", "utf8");
42403
43560
  const point = longestMountPoint(dir, mounts);
42404
43561
  if (point === "/") {
42405
43562
  throw new Error(
@@ -42410,8 +43567,8 @@ function assertRelayAccountsDurable(filePath) {
42410
43567
  var RelayAccountStore = class {
42411
43568
  db;
42412
43569
  constructor(filePath) {
42413
- (0, import_node_fs73.mkdirSync)((0, import_node_path72.dirname)(filePath), { recursive: true });
42414
- this.db = openDatabase(filePath);
43570
+ (0, import_node_fs75.mkdirSync)((0, import_node_path75.dirname)(filePath), { recursive: true });
43571
+ this.db = openDatabase3(filePath);
42415
43572
  this.db.exec(`
42416
43573
  CREATE TABLE IF NOT EXISTS accounts (
42417
43574
  id TEXT PRIMARY KEY,
@@ -42482,7 +43639,7 @@ var RelayAccountStore = class {
42482
43639
  this.insertIdentity(issuer, subject, accountId, email, verified);
42483
43640
  } else {
42484
43641
  const byEmail = verified ? this.accountIdForVerifiedEmail(email) : void 0;
42485
- accountId = byEmail ?? (0, import_node_crypto25.randomUUID)();
43642
+ accountId = byEmail ?? (0, import_node_crypto31.randomUUID)();
42486
43643
  if (!byEmail) {
42487
43644
  this.db.prepare("INSERT INTO accounts (id, created_at, device_cap) VALUES (?, ?, ?)").run(accountId, Date.now(), RELAY_DEVICE_CAP);
42488
43645
  }
@@ -42500,14 +43657,14 @@ var RelayAccountStore = class {
42500
43657
  verifyCredential(token) {
42501
43658
  const trimmed = token.trim();
42502
43659
  if (!trimmed) return null;
42503
- const row2 = this.db.prepare("SELECT account_id FROM credentials WHERE token_hash = ?").get(sha2562(trimmed));
43660
+ const row2 = this.db.prepare("SELECT account_id FROM credentials WHERE token_hash = ?").get(sha2563(trimmed));
42504
43661
  return row2?.account_id ?? null;
42505
43662
  }
42506
43663
  /** Drop one Mac credential. The account and its other Macs stay. */
42507
43664
  logout(token) {
42508
43665
  const trimmed = token.trim();
42509
43666
  if (!trimmed) return;
42510
- this.db.prepare("DELETE FROM credentials WHERE token_hash = ?").run(sha2562(trimmed));
43667
+ this.db.prepare("DELETE FROM credentials WHERE token_hash = ?").run(sha2563(trimmed));
42511
43668
  }
42512
43669
  /** Delete the account and every identity, credential, and Mac bound to it. */
42513
43670
  revokeAccount(accountId) {
@@ -42545,7 +43702,7 @@ var RelayAccountStore = class {
42545
43702
  return { ok: false, message: "sign in required" };
42546
43703
  }
42547
43704
  const device = this.db.prepare("SELECT device_id, account_id, host_secret_hash FROM devices WHERE device_id = ?").get(deviceId);
42548
- const secretHash = sha2562(hostSecret);
43705
+ const secretHash = sha2563(hostSecret);
42549
43706
  if (!device) {
42550
43707
  const count = this.db.prepare("SELECT COUNT(*) AS n FROM devices WHERE account_id = ?").get(accountId);
42551
43708
  if (count.n >= account.device_cap) {
@@ -42562,7 +43719,7 @@ var RelayAccountStore = class {
42562
43719
  this.db.exec("ROLLBACK");
42563
43720
  return { ok: false, message: "This Mac is registered to another account." };
42564
43721
  }
42565
- if (!sameHash(device.host_secret_hash, secretHash)) {
43722
+ if (!sameHash2(device.host_secret_hash, secretHash)) {
42566
43723
  this.db.exec("ROLLBACK");
42567
43724
  return { ok: false, message: "host secret rejected" };
42568
43725
  }
@@ -42579,12 +43736,12 @@ var RelayAccountStore = class {
42579
43736
  const id = deviceId.trim();
42580
43737
  const token = sessionToken.trim();
42581
43738
  if (!id || !token) return;
42582
- this.db.prepare("UPDATE devices SET session_token_hash = ? WHERE device_id = ?").run(sha2562(token), id);
43739
+ this.db.prepare("UPDATE devices SET session_token_hash = ? WHERE device_id = ?").run(sha2563(token), id);
42583
43740
  }
42584
43741
  findPhoneSession(sessionToken) {
42585
43742
  const token = sessionToken.trim();
42586
43743
  if (!token) return null;
42587
- const row2 = this.db.prepare("SELECT device_id, device_label FROM devices WHERE session_token_hash = ?").get(sha2562(token));
43744
+ const row2 = this.db.prepare("SELECT device_id, device_label FROM devices WHERE session_token_hash = ?").get(sha2563(token));
42588
43745
  if (!row2) return null;
42589
43746
  return { deviceId: row2.device_id, deviceLabel: row2.device_label };
42590
43747
  }
@@ -42604,14 +43761,14 @@ var RelayAccountStore = class {
42604
43761
  ).run(issuer, subject, accountId, email, verified ? 1 : 0);
42605
43762
  }
42606
43763
  mintCredential(accountId) {
42607
- const credential = (0, import_node_crypto25.randomBytes)(32).toString("hex");
42608
- this.db.prepare("INSERT INTO credentials (token_hash, account_id, created_at) VALUES (?, ?, ?)").run(sha2562(credential), accountId, Date.now());
43764
+ const credential = (0, import_node_crypto31.randomBytes)(32).toString("hex");
43765
+ this.db.prepare("INSERT INTO credentials (token_hash, account_id, created_at) VALUES (?, ?, ?)").run(sha2563(credential), accountId, Date.now());
42609
43766
  return credential;
42610
43767
  }
42611
43768
  };
42612
43769
 
42613
43770
  // src/relay/account-cursor.ts
42614
- var import_node_crypto26 = require("crypto");
43771
+ var import_node_crypto32 = require("crypto");
42615
43772
  var JWKS_URL = "https://api.cursor.com/v1/origin/keys";
42616
43773
  var RECEIPT_TYP = "origin-user-confirmation-receipt+jwt";
42617
43774
  var usedJti = /* @__PURE__ */ new Map();
@@ -42643,8 +43800,8 @@ async function cursorIdentityFromReceipt(receipt, expected, fetchImpl, nowMs = D
42643
43800
  throw new Error("Cursor sign-in receipt was not a signed token.");
42644
43801
  }
42645
43802
  const [hSeg, pSeg, sSeg] = parts;
42646
- const header = b64urlJson(hSeg);
42647
- if (header.alg !== "EdDSA" || header.typ !== RECEIPT_TYP || typeof header.kid !== "string") {
43803
+ const header2 = b64urlJson(hSeg);
43804
+ if (header2.alg !== "EdDSA" || header2.typ !== RECEIPT_TYP || typeof header2.kid !== "string") {
42648
43805
  throw new Error("Cursor sign-in receipt was not a user confirmation.");
42649
43806
  }
42650
43807
  const payload = b64urlJson(pSeg);
@@ -42662,11 +43819,11 @@ async function cursorIdentityFromReceipt(receipt, expected, fetchImpl, nowMs = D
42662
43819
  const jwksRes = await fetchImpl(JWKS_URL);
42663
43820
  const body = await jwksRes.json();
42664
43821
  const jwk = (body.keys ?? []).find(
42665
- (key2) => key2.kid === header.kid && key2.kty === "OKP" && key2.crv === "Ed25519" && key2.x
43822
+ (key2) => key2.kid === header2.kid && key2.kty === "OKP" && key2.crv === "Ed25519" && key2.x
42666
43823
  );
42667
43824
  if (!jwk?.x) throw new Error("Cursor did not publish the key that signed this receipt.");
42668
- const key = (0, import_node_crypto26.createPublicKey)({ key: { kty: "OKP", crv: "Ed25519", x: jwk.x }, format: "jwk" });
42669
- const ok = (0, import_node_crypto26.verify)(null, Buffer.from(`${hSeg}.${pSeg}`), key, b64urlBuf(sSeg));
43825
+ const key = (0, import_node_crypto32.createPublicKey)({ key: { kty: "OKP", crv: "Ed25519", x: jwk.x }, format: "jwk" });
43826
+ const ok = (0, import_node_crypto32.verify)(null, Buffer.from(`${hSeg}.${pSeg}`), key, b64urlBuf(sSeg));
42670
43827
  if (!ok) throw new Error("Cursor sign-in receipt signature did not verify.");
42671
43828
  if (!rememberJti(jti, exp * 1e3, nowMs)) throw new Error("Cursor sign-in receipt was already used.");
42672
43829
  const email = typeof payload.email === "string" && payload.email.trim() ? payload.email.trim() : null;
@@ -42692,7 +43849,7 @@ function cursorGitHostEntry() {
42692
43849
  }
42693
43850
 
42694
43851
  // src/relay/account-entire.ts
42695
- var import_node_crypto27 = require("crypto");
43852
+ var import_node_crypto33 = require("crypto");
42696
43853
  var ENTIRE_AUTHORIZE_ORIGIN = "https://auth.entire.io";
42697
43854
  var ENTIRE_DEFAULT_ISSUER = "https://us.auth.entire.io";
42698
43855
  var ISSUER_SUFFIX = ".auth.entire.io";
@@ -42715,10 +43872,10 @@ function entireAccountIssuer(value) {
42715
43872
  return `https://${host}`;
42716
43873
  }
42717
43874
  function newEntireCodeVerifier() {
42718
- return (0, import_node_crypto27.randomBytes)(32).toString("base64url");
43875
+ return (0, import_node_crypto33.randomBytes)(32).toString("base64url");
42719
43876
  }
42720
43877
  function entireCodeChallenge(verifier) {
42721
- return (0, import_node_crypto27.createHash)("sha256").update(verifier).digest("base64url");
43878
+ return (0, import_node_crypto33.createHash)("sha256").update(verifier).digest("base64url");
42722
43879
  }
42723
43880
  function entireAuthorizeUrl(clientId, redirectUri, state, codeChallenge) {
42724
43881
  const url = new URL("/authorize", ENTIRE_AUTHORIZE_ORIGIN);
@@ -42731,7 +43888,7 @@ function entireAuthorizeUrl(clientId, redirectUri, state, codeChallenge) {
42731
43888
  url.searchParams.set("code_challenge_method", "S256");
42732
43889
  return url.toString();
42733
43890
  }
42734
- async function readJson3(res) {
43891
+ async function readJson4(res) {
42735
43892
  const text7 = await res.text();
42736
43893
  if (!text7) return {};
42737
43894
  try {
@@ -42775,13 +43932,13 @@ async function entireIdentityFromCode(client, code, redirectUri, ctx, fetchImpl)
42775
43932
  headers,
42776
43933
  body
42777
43934
  });
42778
- const token = accessToken(await readJson3(tokenRes));
43935
+ const token = accessToken(await readJson4(tokenRes));
42779
43936
  const userRes = await fetchImpl(`${issuer}/userinfo`, {
42780
43937
  redirect: "error",
42781
43938
  headers: { Accept: "application/json", Authorization: `Bearer ${token}` }
42782
43939
  });
42783
43940
  if (!userRes.ok) throw new Error("Entire did not return an account.");
42784
- const user = await readJson3(userRes);
43941
+ const user = await readJson4(userRes);
42785
43942
  const subject = typeof user.sub === "string" ? user.sub.trim() : "";
42786
43943
  if (!subject) throw new Error("Entire did not return an account id.");
42787
43944
  const email = typeof user.email === "string" ? user.email.trim() : "";
@@ -42884,7 +44041,7 @@ function providerOf(value) {
42884
44041
  function relayAuthorizeUrl(provider, client, redirectUri, state, ctx = EMPTY_AUTH) {
42885
44042
  return GIT_HOST_AUTH[provider].authorizeUrl(client, redirectUri, state, ctx);
42886
44043
  }
42887
- async function readJson4(res) {
44044
+ async function readJson5(res) {
42888
44045
  const text7 = await res.text();
42889
44046
  if (!text7) return {};
42890
44047
  try {
@@ -42915,17 +44072,17 @@ async function fetchGithubIdentity(client, code, redirectUri, state, fetchImpl,
42915
44072
  redirect_uri: redirectUri
42916
44073
  })
42917
44074
  });
42918
- const token = accessToken2(await readJson4(tokenRes));
44075
+ const token = accessToken2(await readJson5(tokenRes));
42919
44076
  const userRes = await fetchImpl("https://api.github.com/user", {
42920
44077
  headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "sideboard-relay" }
42921
44078
  });
42922
- const user = await readJson4(userRes);
44079
+ const user = await readJson5(userRes);
42923
44080
  const subject = typeof user.id === "number" ? String(user.id) : "";
42924
44081
  if (!subject) throw new Error("GitHub did not return an account id.");
42925
44082
  const emailRes = await fetchImpl("https://api.github.com/user/emails", {
42926
44083
  headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "sideboard-relay" }
42927
44084
  });
42928
- const emails = await readJson4(emailRes);
44085
+ const emails = await readJson5(emailRes);
42929
44086
  const list = Array.isArray(emails) ? emails : [];
42930
44087
  const primary = list.find((row2) => row2.primary === true && row2.verified === true);
42931
44088
  const anyVerified = list.find((row2) => row2.verified === true);
@@ -42936,7 +44093,7 @@ async function fetchGithubIdentity(client, code, redirectUri, state, fetchImpl,
42936
44093
  async function fetchRelayIdentity(provider, client, credential, redirectUri, state, fetchImpl, ctx = EMPTY_AUTH) {
42937
44094
  return GIT_HOST_AUTH[provider].fetchIdentity(client, credential, redirectUri, state, fetchImpl, ctx);
42938
44095
  }
42939
- async function readBody(req) {
44096
+ async function readBody2(req) {
42940
44097
  const chunks = [];
42941
44098
  let size = 0;
42942
44099
  for await (const chunk of req) {
@@ -42949,7 +44106,7 @@ async function readBody(req) {
42949
44106
  if (!text7) return {};
42950
44107
  return JSON.parse(text7);
42951
44108
  }
42952
- function sendJson(res, status, body) {
44109
+ function sendJson2(res, status, body) {
42953
44110
  res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
42954
44111
  res.end(JSON.stringify(body));
42955
44112
  }
@@ -43018,7 +44175,7 @@ function relayOAuthReturnPage(title, body) {
43018
44175
  </body>
43019
44176
  </html>`;
43020
44177
  }
43021
- function sendHtml(res, status, title, body) {
44178
+ function sendHtml2(res, status, title, body) {
43022
44179
  res.writeHead(status, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
43023
44180
  res.end(relayOAuthReturnPage(title, body));
43024
44181
  }
@@ -43032,21 +44189,21 @@ async function handleRelayAccountHttp(opts) {
43032
44189
  if (method === "POST" && path2 === REMOTE_LOGIN_PATH) {
43033
44190
  let body;
43034
44191
  try {
43035
- body = await readBody(opts.req);
44192
+ body = await readBody2(opts.req);
43036
44193
  } catch {
43037
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
44194
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
43038
44195
  return true;
43039
44196
  }
43040
44197
  const provider = providerOf(typeof body.provider === "string" ? body.provider : "");
43041
44198
  const state = typeof body.state === "string" ? body.state.trim() : "";
43042
44199
  if (!provider || !STATE_RE.test(state)) {
43043
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
44200
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
43044
44201
  return true;
43045
44202
  }
43046
44203
  const client = opts.oauth[provider];
43047
44204
  const host = provider ? GIT_HOST_AUTH[provider] : null;
43048
44205
  if (!client?.clientId || host?.requiresClientSecret && !client.clientSecret) {
43049
- sendJson(opts.res, 503, {
44206
+ sendJson2(opts.res, 503, {
43050
44207
  ok: false,
43051
44208
  error: `${GIT_HOST_AUTH[provider].label} sign-in is not configured on this relay.`
43052
44209
  });
@@ -43057,14 +44214,14 @@ async function handleRelayAccountHttp(opts) {
43057
44214
  if (linkToken) {
43058
44215
  accountId = opts.store.verifyCredential(linkToken);
43059
44216
  if (!accountId) {
43060
- sendJson(opts.res, 401, { ok: false, error: "sign in required" });
44217
+ sendJson2(opts.res, 401, { ok: false, error: "sign in required" });
43061
44218
  return true;
43062
44219
  }
43063
44220
  }
43064
44221
  const codeVerifier = provider === "entire" ? newEntireCodeVerifier() : null;
43065
44222
  const auth = { codeVerifier, issuer: null };
43066
44223
  opts.sessions.begin(state, provider, accountId, codeVerifier);
43067
- sendJson(opts.res, 200, {
44224
+ sendJson2(opts.res, 200, {
43068
44225
  ok: true,
43069
44226
  url: relayAuthorizeUrl(provider, client, redirectUri, state, auth)
43070
44227
  });
@@ -43076,20 +44233,20 @@ async function handleRelayAccountHttp(opts) {
43076
44233
  const providerError = url.searchParams.get("error")?.trim() ?? "";
43077
44234
  const pending = STATE_RE.test(state) ? opts.sessions.takeLogin(state) : null;
43078
44235
  if (!pending) {
43079
- sendHtml(opts.res, 400, "Sideboard", "<h1>Sign-in expired</h1><p>Return to Sideboard and try again.</p>");
44236
+ sendHtml2(opts.res, 400, "Sideboard", "<h1>Sign-in expired</h1><p>Return to Sideboard and try again.</p>");
43080
44237
  return true;
43081
44238
  }
43082
44239
  const credential = url.searchParams.get(GIT_HOST_AUTH[pending.provider].credentialParam)?.trim() ?? "";
43083
44240
  if (providerError || !credential) {
43084
44241
  const message = providerError || "Sign-in was cancelled.";
43085
44242
  opts.sessions.putResult(state, { ok: false, error: message });
43086
- sendHtml(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml2(message)}</p>`);
44243
+ sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml2(message)}</p>`);
43087
44244
  return true;
43088
44245
  }
43089
44246
  const client = opts.oauth[pending.provider];
43090
44247
  if (!client) {
43091
44248
  opts.sessions.putResult(state, { ok: false, error: "Sign-in is not configured on this relay." });
43092
- sendHtml(opts.res, 503, "Sideboard", "<h1>Sign-in is not configured</h1>");
44249
+ sendHtml2(opts.res, 503, "Sideboard", "<h1>Sign-in is not configured</h1>");
43093
44250
  return true;
43094
44251
  }
43095
44252
  try {
@@ -43102,14 +44259,14 @@ async function handleRelayAccountHttp(opts) {
43102
44259
  fetchImpl,
43103
44260
  { codeVerifier: pending.codeVerifier, issuer: url.searchParams.get("iss") }
43104
44261
  );
43105
- const signed = opts.store.signIn(identity, pending.accountId);
44262
+ const signed2 = opts.store.signIn(identity, pending.accountId);
43106
44263
  opts.sessions.putResult(state, {
43107
44264
  ok: true,
43108
- credential: signed.credential,
43109
- email: signed.email,
43110
- accountId: signed.accountId
44265
+ credential: signed2.credential,
44266
+ email: signed2.email,
44267
+ accountId: signed2.accountId
43111
44268
  });
43112
- sendHtml(
44269
+ sendHtml2(
43113
44270
  opts.res,
43114
44271
  200,
43115
44272
  "Sideboard",
@@ -43118,7 +44275,7 @@ async function handleRelayAccountHttp(opts) {
43118
44275
  } catch (err) {
43119
44276
  const message = err instanceof Error ? err.message : String(err);
43120
44277
  opts.sessions.putResult(state, { ok: false, error: message });
43121
- sendHtml(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml2(message)}</p>`);
44278
+ sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml2(message)}</p>`);
43122
44279
  }
43123
44280
  return true;
43124
44281
  }
@@ -43126,19 +44283,19 @@ async function handleRelayAccountHttp(opts) {
43126
44283
  const url = new URL(reqUrl, origin);
43127
44284
  const state = url.searchParams.get("state")?.trim() ?? "";
43128
44285
  if (!STATE_RE.test(state)) {
43129
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
44286
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
43130
44287
  return true;
43131
44288
  }
43132
44289
  const result = opts.sessions.takeResult(state);
43133
44290
  if (result === void 0 || result === null) {
43134
- sendJson(opts.res, 404, { ok: false, error: "pending" });
44291
+ sendJson2(opts.res, 404, { ok: false, error: "pending" });
43135
44292
  return true;
43136
44293
  }
43137
44294
  if (!result.ok) {
43138
- sendJson(opts.res, 400, { ok: false, error: result.error });
44295
+ sendJson2(opts.res, 400, { ok: false, error: result.error });
43139
44296
  return true;
43140
44297
  }
43141
- sendJson(opts.res, 200, {
44298
+ sendJson2(opts.res, 200, {
43142
44299
  ok: true,
43143
44300
  credential: result.credential,
43144
44301
  email: result.email,
@@ -43149,14 +44306,14 @@ async function handleRelayAccountHttp(opts) {
43149
44306
  if (method === "POST" && path2 === REMOTE_LOGOUT_PATH) {
43150
44307
  let body;
43151
44308
  try {
43152
- body = await readBody(opts.req);
44309
+ body = await readBody2(opts.req);
43153
44310
  } catch {
43154
- sendJson(opts.res, 400, { ok: false, error: "invalid logout request" });
44311
+ sendJson2(opts.res, 400, { ok: false, error: "invalid logout request" });
43155
44312
  return true;
43156
44313
  }
43157
44314
  const token = typeof body.accountToken === "string" ? body.accountToken : "";
43158
44315
  opts.store.logout(token);
43159
- sendJson(opts.res, 200, { ok: true });
44316
+ sendJson2(opts.res, 200, { ok: true });
43160
44317
  return true;
43161
44318
  }
43162
44319
  return false;
@@ -43164,11 +44321,7 @@ async function handleRelayAccountHttp(opts) {
43164
44321
 
43165
44322
  // src/relay/server.ts
43166
44323
  init_abletime_oauth();
43167
- function sendHtml2(res, status, title, body) {
43168
- res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
43169
- res.end(slackOAuthHtmlPage(title, body));
43170
- }
43171
- function sendJson2(res, status, body) {
44324
+ function sendJson3(res, status, body) {
43172
44325
  res.writeHead(status, { "Content-Type": "application/json" });
43173
44326
  res.end(JSON.stringify(body));
43174
44327
  }
@@ -43212,6 +44365,18 @@ async function startRelayServer(opts) {
43212
44365
  const accountsPath = opts.accountsPath?.trim() ?? "";
43213
44366
  if (accountsPath) assertRelayAccountsDurable(accountsPath);
43214
44367
  const accountStore = accountsPath ? new RelayAccountStore(accountsPath) : null;
44368
+ const slackTokenKey = (opts.slackTokenKey ?? process.env.SIDEBOARD_SLACK_TOKEN_KEY ?? "").trim();
44369
+ const slackApps = accountsPath && slackTokenKey ? new SlackAppStore(accountsPath, parseSlackTokenKey(slackTokenKey)) : null;
44370
+ if (slackApps) {
44371
+ for (const row2 of slackApps.listBots()) hub.rememberBot(row2.teamId, row2.botToken);
44372
+ hub.setBotHooks({
44373
+ guardBotUser: (teamId, botUserId) => slackApps.botUserMismatch(teamId, botUserId),
44374
+ onBotAccepted: (teamId, botToken, botUserId) => slackApps.saveBot(teamId, botToken, botUserId)
44375
+ });
44376
+ }
44377
+ const listenGrants = accountsPath ? new SlackListenGrantStore(accountsPath) : new MemorySlackListenGrants();
44378
+ hub.setListenGrantVerifier((teamId, userId, grant) => listenGrants.verify(teamId, userId, grant));
44379
+ const slackDedupe = new SlackEventDeduper();
43215
44380
  const accountSessions = new RelayLoginSessions();
43216
44381
  const relayOAuth = opts.relayOAuth ?? {};
43217
44382
  const authMarks = /* @__PURE__ */ new Map();
@@ -43228,83 +44393,7 @@ async function startRelayServer(opts) {
43228
44393
  } : void 0,
43229
44394
  onAuthorized: (socket) => authMarks.get(socket)?.()
43230
44395
  });
43231
- const handleCallback = async (reqUrl, res) => {
43232
- const url2 = parseSlackOAuthCallbackUrl(reqUrl);
43233
- if (!url2) return false;
43234
- const error = url2.searchParams.get("error")?.trim();
43235
- const state = url2.searchParams.get("state")?.trim() ?? "";
43236
- const code = url2.searchParams.get("code")?.trim() ?? "";
43237
- if (error) {
43238
- if (state) pending.put(state, { ok: false, error: `Slack OAuth: ${error}` });
43239
- sendHtml2(
43240
- res,
43241
- 400,
43242
- "Slack",
43243
- `<h1>Authorization cancelled</h1><p>${escapeHtml2(error)}</p>`
43244
- );
43245
- return true;
43246
- }
43247
- if (!state || !code) {
43248
- sendHtml2(res, 400, "Slack", "<h1>Invalid callback</h1><p>State or code missing.</p>");
43249
- return true;
43250
- }
43251
- if (!clientSecret) {
43252
- pending.put(state, {
43253
- ok: false,
43254
- error: "Relay is missing SIDEBOARD_SLACK_CLIENT_SECRET"
43255
- });
43256
- sendHtml2(
43257
- res,
43258
- 500,
43259
- "Slack",
43260
- "<h1>Relay misconfigured</h1><p>OAuth client secret is not set on the relay.</p>"
43261
- );
43262
- return true;
43263
- }
43264
- try {
43265
- const payload = await exchangeSlackOAuthCode({
43266
- clientId,
43267
- clientSecret,
43268
- code,
43269
- redirectUri,
43270
- fetchImpl: opts.fetchImpl
43271
- });
43272
- pending.put(state, { ok: true, payload });
43273
- if (payload.bot_token) {
43274
- hub.rememberBot(payload.team_id, payload.bot_token);
43275
- if (payload.user_id) {
43276
- void hub.handleAppHomeOpened(payload.team_id, payload.user_id);
43277
- }
43278
- }
43279
- sendHtml2(
43280
- res,
43281
- 200,
43282
- "Slack connected",
43283
- '<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>'
43284
- );
43285
- } catch (err) {
43286
- const message = err instanceof Error ? err.message : String(err);
43287
- pending.put(state, { ok: false, error: message });
43288
- sendHtml2(res, 400, "Slack", `<h1>Could not connect Slack</h1><p>${escapeHtml2(message)}</p>`);
43289
- }
43290
- return true;
43291
- };
43292
- const handleResult = (reqUrl, res) => {
43293
- const url2 = parseSlackOAuthResultUrl(reqUrl);
43294
- if (!url2) return false;
43295
- const state = url2.searchParams.get("state")?.trim() ?? "";
43296
- const value = pending.take(state);
43297
- if (!value) {
43298
- sendJson2(res, 404, { ok: false, error: "pending" });
43299
- return true;
43300
- }
43301
- if (!value.ok) {
43302
- sendJson2(res, 400, { ok: false, error: value.error });
43303
- return true;
43304
- }
43305
- sendJson2(res, 200, { ok: true, ...value.payload });
43306
- return true;
43307
- };
44396
+ const publicOrigin = () => opts.relayPublicOrigin?.trim() || process.env.SIDEBOARD_RELAY_PUBLIC_ORIGIN?.trim() || `http://127.0.0.1:${boundPort}`;
43308
44397
  const httpServer = (0, import_node_http5.createServer)((req, res) => {
43309
44398
  void (async () => {
43310
44399
  const reqUrl = req.url || "/";
@@ -43314,13 +44403,30 @@ async function startRelayServer(opts) {
43314
44403
  store: accountStore,
43315
44404
  oauth: relayOAuth,
43316
44405
  sessions: accountSessions,
43317
- publicOrigin: opts.relayPublicOrigin?.trim() || process.env.SIDEBOARD_RELAY_PUBLIC_ORIGIN?.trim() || `http://127.0.0.1:${boundPort}`,
44406
+ publicOrigin: publicOrigin(),
43318
44407
  fetchImpl: opts.fetchImpl
43319
44408
  })) {
43320
44409
  return;
43321
44410
  }
43322
- if (await handleCallback(reqUrl, res)) return;
43323
- if (handleResult(reqUrl, res)) return;
44411
+ if (await handleSlackHttp({
44412
+ req,
44413
+ res,
44414
+ reqUrl,
44415
+ accounts: accountStore,
44416
+ apps: slackApps,
44417
+ hub,
44418
+ grants: listenGrants,
44419
+ pending,
44420
+ bakedClientId: clientId,
44421
+ bakedClientSecret: clientSecret,
44422
+ redirectUri,
44423
+ publicOrigin: publicOrigin(),
44424
+ fetchImpl: opts.fetchImpl,
44425
+ dedupe: slackDedupe,
44426
+ log
44427
+ })) {
44428
+ return;
44429
+ }
43324
44430
  const ableTimeBounce = ableTimeOAuthLocalBounceUrl(reqUrl);
43325
44431
  if (ableTimeBounce && (req.method === "GET" || req.method === "HEAD")) {
43326
44432
  res.writeHead(200, {
@@ -43332,7 +44438,7 @@ async function startRelayServer(opts) {
43332
44438
  return;
43333
44439
  }
43334
44440
  if (req.url === "/health") {
43335
- sendJson2(res, 200, {
44441
+ sendJson3(res, 200, {
43336
44442
  ok: true,
43337
44443
  service: "sideboard-relay",
43338
44444
  sessions: hub.listSessions().length,
@@ -43340,20 +44446,16 @@ async function startRelayServer(opts) {
43340
44446
  });
43341
44447
  return;
43342
44448
  }
43343
- const hostname2 = requestHostname(req);
43344
- const canonical = (opts.canonicalSiteHost ?? "www.sideboard.cloud").toLowerCase();
43345
- const staticHosts = opts.staticHosts ?? [];
43346
- const servesSite = staticHosts.length > 0 && staticHosts.includes(hostname2);
43347
- if (opts.redirectHosts?.includes(hostname2) && hostname2 !== canonical && !servesSite) {
43348
- res.writeHead(301, { Location: `https://${canonical}${reqUrl}` });
43349
- res.end();
43350
- return;
43351
- }
43352
- if (opts.staticRoot && hostnameAllowed(hostname2, opts.staticHosts) && await tryServeStatic(req, res, opts.staticRoot)) {
44449
+ if (opts.staticRoot && await serveMarketingSite(req, res, {
44450
+ root: opts.staticRoot,
44451
+ canonicalHost: opts.canonicalSiteHost ?? CANONICAL_SITE_HOST,
44452
+ staticHosts: opts.staticHosts,
44453
+ redirectHosts: opts.redirectHosts
44454
+ })) {
43353
44455
  return;
43354
44456
  }
43355
44457
  if (req.url === "/") {
43356
- sendJson2(res, 200, {
44458
+ sendJson3(res, 200, {
43357
44459
  ok: true,
43358
44460
  service: "sideboard-relay",
43359
44461
  sessions: hub.listSessions().length,
@@ -43493,6 +44595,7 @@ async function startRelayServer(opts) {
43493
44595
  void hub.handleAppHomeOpened(event.teamId, event.userId);
43494
44596
  return;
43495
44597
  }
44598
+ listenGrants.revokeTeam(event.teamId);
43496
44599
  hub.uninstallTeam(event.teamId);
43497
44600
  }
43498
44601
  }).catch((err) => {
@@ -43517,6 +44620,8 @@ async function startRelayServer(opts) {
43517
44620
  httpServer.close((err) => err ? reject(err) : resolve3());
43518
44621
  });
43519
44622
  await socketModeDone.catch(() => void 0);
44623
+ slackApps?.close();
44624
+ listenGrants.close();
43520
44625
  accountStore?.close();
43521
44626
  }
43522
44627
  };
@@ -43881,7 +44986,7 @@ init_stage_files();
43881
44986
  init_consume_attachments();
43882
44987
 
43883
44988
  // src/composer/pasted-text.ts
43884
- var import_node_crypto28 = require("crypto");
44989
+ var import_node_crypto34 = require("crypto");
43885
44990
  var PASTE_ATTACH_MIN_CHARS = 1200;
43886
44991
  var PASTE_ATTACH_MIN_LINES = 15;
43887
44992
  var PASTED_NAME_RE = /^Pasted text #(\d+)\.txt$/i;
@@ -43908,7 +45013,7 @@ function nextPastedTextName(existing) {
43908
45013
  }
43909
45014
  function buildPastedTextAttachment(text7, opts) {
43910
45015
  return {
43911
- id: opts?.id ?? (0, import_node_crypto28.randomUUID)(),
45016
+ id: opts?.id ?? (0, import_node_crypto34.randomUUID)(),
43912
45017
  name: opts?.name ?? "Pasted text #1.txt",
43913
45018
  kind: "file",
43914
45019
  path: opts?.path,
@@ -43983,22 +45088,22 @@ init_error_detail();
43983
45088
  init_cursor_stream_cutoff();
43984
45089
 
43985
45090
  // src/agents/tool-result-clip.ts
43986
- var import_node_fs74 = require("fs");
43987
- var import_node_path73 = require("path");
45091
+ var import_node_fs76 = require("fs");
45092
+ var import_node_path76 = require("path");
43988
45093
  init_workspace_scratch();
43989
45094
  init_error_detail();
43990
45095
  function spillPath(cwd, prefix) {
43991
45096
  const stamp = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
43992
45097
  const safe = prefix.replace(/[^a-zA-Z0-9_-]+/g, "-").slice(0, 40) || "tool";
43993
- return (0, import_node_path73.join)(cwd, CLI_DIR, `${safe}-${stamp}.txt`);
45098
+ return (0, import_node_path76.join)(cwd, CLI_DIR, `${safe}-${stamp}.txt`);
43994
45099
  }
43995
45100
  function spillToolResultToCli(content, opts) {
43996
45101
  const cwd = opts?.cwd?.trim();
43997
45102
  if (!cwd || !content) return null;
43998
45103
  const file = spillPath(cwd, opts?.prefix ?? "tool-result");
43999
45104
  try {
44000
- (0, import_node_fs74.mkdirSync)((0, import_node_path73.join)(cwd, CLI_DIR), { recursive: true });
44001
- (0, import_node_fs74.writeFileSync)(file, content, "utf8");
45105
+ (0, import_node_fs76.mkdirSync)((0, import_node_path76.join)(cwd, CLI_DIR), { recursive: true });
45106
+ (0, import_node_fs76.writeFileSync)(file, content, "utf8");
44002
45107
  return file;
44003
45108
  } catch {
44004
45109
  return null;
@@ -44084,8 +45189,8 @@ function createClippedMcpServer() {
44084
45189
 
44085
45190
  // src/mcp/server.ts
44086
45191
  var import_zod11 = require("zod");
44087
- var import_node_crypto31 = require("crypto");
44088
- var import_node_path77 = require("path");
45192
+ var import_node_crypto37 = require("crypto");
45193
+ var import_node_path80 = require("path");
44089
45194
  init_orchestrator();
44090
45195
  init_task_state();
44091
45196
  init_worktree();
@@ -45766,8 +46871,8 @@ function registerScheduleTools(server) {
45766
46871
  }
45767
46872
 
45768
46873
  // src/agent-rpc/handlers.ts
45769
- var import_node_crypto29 = require("crypto");
45770
- var import_node_path74 = require("path");
46874
+ var import_node_crypto35 = require("crypto");
46875
+ var import_node_path77 = require("path");
45771
46876
  init_wait_for_job();
45772
46877
  init_wait_for_turn();
45773
46878
 
@@ -45849,7 +46954,7 @@ var handlePermissionAsk = async (params, _ctx) => {
45849
46954
  // src/agent-rpc/handlers.ts
45850
46955
  init_protocol2();
45851
46956
  function presentArtifactResult(input) {
45852
- const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto29.randomUUID)().slice(0, 8)}`;
46957
+ const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto35.randomUUID)().slice(0, 8)}`;
45853
46958
  return {
45854
46959
  ok: true,
45855
46960
  artifact_id: id,
@@ -45874,7 +46979,7 @@ function invalidParams2(message) {
45874
46979
  function jobCwd(rec) {
45875
46980
  const raw = str7(rec.cwd).trim();
45876
46981
  if (!raw) throw invalidParams2("cwd is required");
45877
- if (!(0, import_node_path74.isAbsolute)(raw)) throw invalidParams2("cwd must be an absolute path");
46982
+ if (!(0, import_node_path77.isAbsolute)(raw)) throw invalidParams2("cwd must be an absolute path");
45878
46983
  return raw;
45879
46984
  }
45880
46985
  async function handleRuntimePing(_params, _ctx) {
@@ -46007,36 +47112,36 @@ init_gh_errors();
46007
47112
  init_git_auth_mode();
46008
47113
 
46009
47114
  // src/board/load-home-board.ts
46010
- var import_node_fs76 = require("fs");
46011
- var import_node_path76 = require("path");
47115
+ var import_node_fs78 = require("fs");
47116
+ var import_node_path79 = require("path");
46012
47117
  init_worktree();
46013
47118
  init_paths();
46014
47119
 
46015
47120
  // src/board/board-pins.ts
46016
- var import_node_crypto30 = require("crypto");
46017
- var import_node_fs75 = require("fs");
46018
- var import_node_path75 = require("path");
47121
+ var import_node_crypto36 = require("crypto");
47122
+ var import_node_fs77 = require("fs");
47123
+ var import_node_path78 = require("path");
46019
47124
  init_paths();
46020
47125
  init_home_board();
46021
47126
  var FILE = "home-board-pins.json";
46022
- var VERSION = 1;
47127
+ var VERSION2 = 1;
46023
47128
  function pinsFile() {
46024
- return (0, import_node_path75.join)(appDataDir(), FILE);
47129
+ return (0, import_node_path78.join)(appDataDir(), FILE);
46025
47130
  }
46026
47131
  function readDisk() {
46027
47132
  const path2 = pinsFile();
46028
- if (!(0, import_node_fs75.existsSync)(path2)) return [];
47133
+ if (!(0, import_node_fs77.existsSync)(path2)) return [];
46029
47134
  try {
46030
- const raw = JSON.parse((0, import_node_fs75.readFileSync)(path2, "utf8"));
46031
- if (raw?.version !== VERSION || !Array.isArray(raw.items)) return [];
47135
+ const raw = JSON.parse((0, import_node_fs77.readFileSync)(path2, "utf8"));
47136
+ if (raw?.version !== VERSION2 || !Array.isArray(raw.items)) return [];
46032
47137
  return raw.items.filter((item) => item?.id && item.kind && item.ref);
46033
47138
  } catch {
46034
47139
  return [];
46035
47140
  }
46036
47141
  }
46037
47142
  function writeDisk(items) {
46038
- (0, import_node_fs75.mkdirSync)(appDataDir(), { recursive: true });
46039
- (0, import_node_fs75.writeFileSync)(pinsFile(), JSON.stringify({ version: VERSION, items }, null, 2), "utf8");
47143
+ (0, import_node_fs77.mkdirSync)(appDataDir(), { recursive: true });
47144
+ (0, import_node_fs77.writeFileSync)(pinsFile(), JSON.stringify({ version: VERSION2, items }, null, 2), "utf8");
46040
47145
  }
46041
47146
  function listBoardPins() {
46042
47147
  return readDisk();
@@ -46045,7 +47150,7 @@ function addBoardPin(input) {
46045
47150
  const ref = input.ref.trim();
46046
47151
  if (!ref) throw new Error("Board item needs a ref");
46047
47152
  const pin = {
46048
- id: (0, import_node_crypto30.randomUUID)(),
47153
+ id: (0, import_node_crypto36.randomUUID)(),
46049
47154
  kind: input.kind,
46050
47155
  ref,
46051
47156
  repoPath: input.repoPath.trim(),
@@ -46088,7 +47193,7 @@ function replaceBoardPins(items) {
46088
47193
  }
46089
47194
  function clearBoardPins() {
46090
47195
  try {
46091
- (0, import_node_fs75.unlinkSync)(pinsFile());
47196
+ (0, import_node_fs77.unlinkSync)(pinsFile());
46092
47197
  } catch {
46093
47198
  }
46094
47199
  }
@@ -46105,7 +47210,7 @@ function homeBoardWorkspaceKey(workspaces) {
46105
47210
  return workspaces.map((w) => w.path).filter(Boolean).sort().join("\n");
46106
47211
  }
46107
47212
  function cacheFile() {
46108
- return (0, import_node_path76.join)(appDataDir(), "home-board-cache.json");
47213
+ return (0, import_node_path79.join)(appDataDir(), "home-board-cache.json");
46109
47214
  }
46110
47215
  function emptyInputs() {
46111
47216
  return {
@@ -46131,9 +47236,9 @@ function shouldCacheHomeBoardInputs(inputs) {
46131
47236
  }
46132
47237
  function readDiskCache() {
46133
47238
  const path2 = cacheFile();
46134
- if (!(0, import_node_fs76.existsSync)(path2)) return null;
47239
+ if (!(0, import_node_fs78.existsSync)(path2)) return null;
46135
47240
  try {
46136
- const raw = JSON.parse((0, import_node_fs76.readFileSync)(path2, "utf8"));
47241
+ const raw = JSON.parse((0, import_node_fs78.readFileSync)(path2, "utf8"));
46137
47242
  if (raw?.version !== CACHE_VERSION || typeof raw.fetchedAt !== "number") {
46138
47243
  return null;
46139
47244
  }
@@ -46147,14 +47252,14 @@ function readDiskCache() {
46147
47252
  }
46148
47253
  function writeDiskCache(entry) {
46149
47254
  try {
46150
- (0, import_node_fs76.mkdirSync)(appDataDir(), { recursive: true });
46151
- (0, import_node_fs76.writeFileSync)(cacheFile(), JSON.stringify(entry), "utf8");
47255
+ (0, import_node_fs78.mkdirSync)(appDataDir(), { recursive: true });
47256
+ (0, import_node_fs78.writeFileSync)(cacheFile(), JSON.stringify(entry), "utf8");
46152
47257
  } catch {
46153
47258
  }
46154
47259
  }
46155
47260
  function deleteDiskCache() {
46156
47261
  try {
46157
- (0, import_node_fs76.unlinkSync)(cacheFile());
47262
+ (0, import_node_fs78.unlinkSync)(cacheFile());
46158
47263
  } catch {
46159
47264
  }
46160
47265
  }
@@ -46370,7 +47475,7 @@ async function startMcpServer() {
46370
47475
  async () => {
46371
47476
  const threads = orch.getThreads();
46372
47477
  const lines = threads.map((t) => {
46373
- const repo = t.repoPath === GLOBAL_WORKSPACE_ID2 ? "Orchestration" : (0, import_node_path77.basename)(t.repoPath) || t.repoPath;
47478
+ const repo = t.repoPath === GLOBAL_WORKSPACE_ID2 ? "Orchestration" : (0, import_node_path80.basename)(t.repoPath) || t.repoPath;
46374
47479
  const live = orch.threadLooksLive(t) ? readTurnLive(t.id) : null;
46375
47480
  const parent = t.parentThreadId ? ` parent:${t.parentThreadId.slice(0, 8)}` : "";
46376
47481
  const preview = lastMessagePreview(t.messages, 80);
@@ -46978,7 +48083,7 @@ async function startMcpServer() {
46978
48083
  const ident = issue?.identifier ?? ref.trim();
46979
48084
  const attachments = issue ? [
46980
48085
  {
46981
- id: (0, import_node_crypto31.randomUUID)(),
48086
+ id: (0, import_node_crypto37.randomUUID)(),
46982
48087
  name: issue.identifier,
46983
48088
  kind: "issue",
46984
48089
  content: [
@@ -47540,7 +48645,7 @@ init_protocol2();
47540
48645
  init_metadata();
47541
48646
 
47542
48647
  // src/agent-rpc/server.ts
47543
- var import_node_crypto32 = require("crypto");
48648
+ var import_node_crypto38 = require("crypto");
47544
48649
  var import_node_http6 = require("http");
47545
48650
  var import_ws5 = require("ws");
47546
48651
  init_protocol2();
@@ -47549,7 +48654,7 @@ function tokensEqual(a, b) {
47549
48654
  const left = Buffer.from(a);
47550
48655
  const right = Buffer.from(b);
47551
48656
  if (left.length !== right.length) return false;
47552
- return (0, import_node_crypto32.timingSafeEqual)(left, right);
48657
+ return (0, import_node_crypto38.timingSafeEqual)(left, right);
47553
48658
  }
47554
48659
  function authTokenFromUpgrade(req) {
47555
48660
  try {
@@ -47559,7 +48664,7 @@ function authTokenFromUpgrade(req) {
47559
48664
  return "";
47560
48665
  }
47561
48666
  }
47562
- function sendJson3(ws, value) {
48667
+ function sendJson4(ws, value) {
47563
48668
  if (ws.readyState !== ws.OPEN) return;
47564
48669
  ws.send(JSON.stringify(value));
47565
48670
  }
@@ -47582,9 +48687,9 @@ var AgentRpcServer = class {
47582
48687
  async listen(opts = {}) {
47583
48688
  const host = opts.host ?? "127.0.0.1";
47584
48689
  const port = opts.port ?? 0;
47585
- const authToken = (0, import_node_crypto32.randomBytes)(24).toString("base64url");
48690
+ const authToken = (0, import_node_crypto38.randomBytes)(24).toString("base64url");
47586
48691
  this.meta = {
47587
- runtimeId: (0, import_node_crypto32.randomUUID)(),
48692
+ runtimeId: (0, import_node_crypto38.randomUUID)(),
47588
48693
  pid: process.pid,
47589
48694
  protocolVersion: AGENT_RPC_PROTOCOL_VERSION,
47590
48695
  authToken,
@@ -47644,36 +48749,36 @@ var AgentRpcServer = class {
47644
48749
  async onMessage(ws, raw) {
47645
48750
  const parsed = parseRpcFrame(raw);
47646
48751
  if (parsed === void 0) {
47647
- sendJson3(ws, rpcError(null, RPC_PARSE_ERROR, "Parse error"));
48752
+ sendJson4(ws, rpcError(null, RPC_PARSE_ERROR, "Parse error"));
47648
48753
  return;
47649
48754
  }
47650
48755
  if (!isJsonRpcRequest(parsed)) {
47651
- sendJson3(ws, rpcError(null, RPC_INVALID_REQUEST, "Invalid request"));
48756
+ sendJson4(ws, rpcError(null, RPC_INVALID_REQUEST, "Invalid request"));
47652
48757
  return;
47653
48758
  }
47654
48759
  const id = parsed.id;
47655
48760
  const expected = this.meta?.authToken ?? "";
47656
48761
  const got = typeof parsed.authToken === "string" ? parsed.authToken : "";
47657
48762
  if (!expected || !got || !tokensEqual(got, expected)) {
47658
- sendJson3(ws, rpcError(id, RPC_UNAUTHORIZED, "Unauthorized"));
48763
+ sendJson4(ws, rpcError(id, RPC_UNAUTHORIZED, "Unauthorized"));
47659
48764
  return;
47660
48765
  }
47661
48766
  const handler = this.handlers[parsed.method];
47662
48767
  if (!handler) {
47663
- sendJson3(ws, rpcError(id, RPC_METHOD_NOT_FOUND, `Method not found: ${parsed.method}`));
48768
+ sendJson4(ws, rpcError(id, RPC_METHOD_NOT_FOUND, `Method not found: ${parsed.method}`));
47664
48769
  return;
47665
48770
  }
47666
48771
  const ctx = {
47667
48772
  cwd: this.cwd(),
47668
- notify: (method, params) => sendJson3(ws, rpcNotify(method, params))
48773
+ notify: (method, params) => sendJson4(ws, rpcNotify(method, params))
47669
48774
  };
47670
48775
  try {
47671
48776
  const result = await handler(parsed.params, ctx);
47672
- sendJson3(ws, rpcResult(id, result));
48777
+ sendJson4(ws, rpcResult(id, result));
47673
48778
  } catch (err) {
47674
48779
  const message = err instanceof Error ? err.message : String(err);
47675
48780
  const code = err && typeof err === "object" && "rpcCode" in err && typeof err.rpcCode === "number" ? err.rpcCode : RPC_INTERNAL_ERROR;
47676
- sendJson3(ws, rpcError(id, code, message));
48781
+ sendJson4(ws, rpcError(id, code, message));
47677
48782
  }
47678
48783
  }
47679
48784
  async close() {
@@ -48383,248 +49488,59 @@ init_host();
48383
49488
  init_model_context();
48384
49489
  init_meta();
48385
49490
 
48386
- // src/slack/workspaces.ts
48387
- var import_node_path78 = require("path");
48388
- init_paths();
48389
- init_secure_file();
48390
- function storePath2() {
48391
- return (0, import_node_path78.join)(appDataDir(), "slack-workspaces.json");
49491
+ // src/slack/org-app-client.ts
49492
+ function originOf(relayWsUrl) {
49493
+ return slackRelayHttpOrigin(relayWsUrl ?? slackRelayUrl());
48392
49494
  }
48393
- function readStore2() {
49495
+ async function readError(res) {
48394
49496
  try {
48395
- const path2 = storePath2();
48396
- const wasEncrypted = isSecureFileEncrypted(path2);
48397
- const parsed = readSecureJson(path2);
48398
- const workspaces = Array.isArray(parsed?.workspaces) ? parsed.workspaces : [];
48399
- if (workspaces.length > 0 && !wasEncrypted && resolveVaultKey()) {
48400
- writeSecureJson(path2, { workspaces });
48401
- }
48402
- return workspaces;
49497
+ const body = await res.json();
49498
+ if (body.error?.trim()) return body.error.trim();
48403
49499
  } catch {
48404
- return [];
48405
49500
  }
49501
+ return `Relay returned ${res.status}`;
48406
49502
  }
48407
- function writeStore2(workspaces) {
48408
- writeSecureJson(storePath2(), { workspaces });
48409
- return workspaces;
48410
- }
48411
- function toInfo(ws) {
49503
+ async function createSlackOrgApp(opts) {
49504
+ const token = opts.accountToken.trim();
49505
+ if (!token) throw new Error("Sign in on Settings \u2192 Remote before creating a Slack app");
49506
+ const fetchImpl = opts.fetchImpl ?? fetch;
49507
+ const res = await fetchImpl(`${originOf(opts.relayWsUrl)}/slack/apps`, {
49508
+ method: "POST",
49509
+ headers: { Authorization: `Bearer ${token}` }
49510
+ });
49511
+ if (!res.ok) throw new Error(await readError(res));
49512
+ const body = await res.json();
49513
+ if (!body.registrationId || !body.writeToken || !body.manifest || !body.eventsUrl) {
49514
+ throw new Error("Relay did not return a Slack app registration");
49515
+ }
48412
49516
  return {
48413
- team_id: ws.team_id,
48414
- team_name: ws.team_name,
48415
- user_id: ws.user_id,
48416
- has_bot_token: Boolean(ws.bot_token),
48417
- has_user_token: Boolean(ws.user_token),
48418
- connected_at: ws.connected_at
48419
- };
48420
- }
48421
- function listSlackWorkspaces() {
48422
- return readStore2().map(toInfo).sort((a, b) => a.team_name.localeCompare(b.team_name));
48423
- }
48424
- function listSlackWorkspacesRaw() {
48425
- return readStore2();
48426
- }
48427
- function getSlackWorkspace(teamId) {
48428
- const id = teamId.trim();
48429
- if (!id) return null;
48430
- return readStore2().find(
48431
- (ws) => ws.team_id === id || ws.team_name.toLowerCase() === id.toLowerCase()
48432
- ) ?? null;
48433
- }
48434
- function upsertSlackWorkspace(entry) {
48435
- const workspaces = readStore2().filter((ws) => ws.team_id !== entry.team_id);
48436
- workspaces.push(entry);
48437
- writeStore2(workspaces);
48438
- return toInfo(entry);
48439
- }
48440
- function disconnectSlackWorkspace(teamId) {
48441
- const id = teamId.trim();
48442
- writeStore2(readStore2().filter((ws) => ws.team_id !== id));
48443
- return listSlackWorkspaces();
48444
- }
48445
- function tokenKind(token) {
48446
- if (token.startsWith("xoxb-")) return "bot";
48447
- if (token.startsWith("xoxp-") || token.startsWith("xoxe.xoxp-")) return "user";
48448
- return "unknown";
48449
- }
48450
- async function connectSlackToken(rawToken) {
48451
- const token = rawToken.trim();
48452
- if (!token) throw new Error("Paste a Slack bot (xoxb-) or user (xoxp-) token");
48453
- const auth = await slackAuthTest(token);
48454
- const teamId = auth.team_id?.trim();
48455
- if (!teamId) throw new Error("Slack auth.test did not return a team_id");
48456
- const existing = getSlackWorkspace(teamId);
48457
- const kind = tokenKind(token);
48458
- const next = {
48459
- team_id: teamId,
48460
- team_name: auth.team?.trim() || existing?.team_name || teamId,
48461
- user_id: auth.user_id?.trim() || existing?.user_id,
48462
- bot_token: kind === "bot" ? token : existing?.bot_token,
48463
- user_token: kind === "user" || kind === "unknown" ? token : existing?.user_token,
48464
- scopes: existing?.scopes,
48465
- connected_at: existing?.connected_at || (/* @__PURE__ */ new Date()).toISOString()
49517
+ registrationId: body.registrationId,
49518
+ writeToken: body.writeToken,
49519
+ eventsUrl: body.eventsUrl,
49520
+ manifest: body.manifest
48466
49521
  };
48467
- if (kind === "unknown" && auth.bot_id) {
48468
- next.bot_token = token;
48469
- next.user_token = existing?.user_token;
48470
- }
48471
- return upsertSlackWorkspace(next);
48472
49522
  }
48473
- function slackTokenFor(ws, kind = "read") {
48474
- const token = (kind === "write" ? ws.bot_token || ws.user_token : ws.user_token || ws.bot_token)?.trim();
48475
- if (!token) {
48476
- throw new Error(`Slack workspace ${ws.team_name} has no token`);
48477
- }
48478
- return token;
48479
- }
48480
-
48481
- // src/slack/oauth.ts
48482
- var import_node_crypto33 = require("crypto");
48483
- init_app_settings();
48484
- var SLACK_BOT_SCOPES = [
48485
- "app_mentions:read",
48486
- "channels:history",
48487
- "channels:read",
48488
- "groups:history",
48489
- "groups:read",
48490
- "im:history",
48491
- "im:read",
48492
- "im:write",
48493
- "mpim:history",
48494
- "mpim:read",
48495
- "chat:write",
48496
- "chat:write.public",
48497
- "reactions:write",
48498
- "users:read",
48499
- "users:read.email"
48500
- ].join(",");
48501
- var SLACK_USER_SCOPES = [
48502
- "channels:history",
48503
- "channels:read",
48504
- "groups:history",
48505
- "im:history",
48506
- "mpim:history",
48507
- "users:read"
48508
- ].join(",");
48509
- function slackOAuthCredentials() {
48510
- const settings = loadAppSettings();
48511
- const clientId = process.env.SIDEBOARD_SLACK_CLIENT_ID?.trim() || settings.integrations.slackClientId?.trim() || BAKED_SLACK_CLIENT_ID.trim();
48512
- const clientSecret = process.env.SIDEBOARD_SLACK_CLIENT_SECRET?.trim() || settings.integrations.slackClientSecret?.trim() || "";
48513
- if (!clientId) {
48514
- throw new Error(
48515
- "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."
48516
- );
48517
- }
48518
- return { clientId, clientSecret: clientSecret || null };
48519
- }
48520
- var SLACK_OAUTH_CANCELLED = "Slack sign-in cancelled";
48521
- var SlackOAuthCancelledError = class extends Error {
48522
- constructor(message = SLACK_OAUTH_CANCELLED) {
48523
- super(message);
48524
- this.name = "SlackOAuthCancelledError";
48525
- }
48526
- };
48527
- function isSlackOAuthCancelled(err) {
48528
- if (err instanceof SlackOAuthCancelledError) return true;
48529
- const message = err instanceof Error ? err.message : String(err);
48530
- if (message.includes(SLACK_OAUTH_CANCELLED)) return true;
48531
- return err instanceof Error && err.name === "SlackOAuthCancelledError";
48532
- }
48533
- function slackOAuthAuthorizeUrl(clientId, state) {
48534
- const params = new URLSearchParams({
48535
- client_id: clientId,
48536
- scope: SLACK_BOT_SCOPES,
48537
- user_scope: SLACK_USER_SCOPES,
48538
- redirect_uri: slackOAuthRedirectUri(),
48539
- state
48540
- });
48541
- return `https://slack.com/oauth/v2/authorize?${params.toString()}`;
48542
- }
48543
- function sleep(ms, signal) {
48544
- return new Promise((resolve3, reject) => {
48545
- if (signal?.aborted) {
48546
- reject(new SlackOAuthCancelledError());
48547
- return;
48548
- }
48549
- const timer = setTimeout(() => {
48550
- signal?.removeEventListener("abort", onAbort);
48551
- resolve3();
48552
- }, ms);
48553
- const onAbort = () => {
48554
- clearTimeout(timer);
48555
- reject(new SlackOAuthCancelledError());
48556
- };
48557
- signal?.addEventListener("abort", onAbort, { once: true });
48558
- });
48559
- }
48560
- function upsertFromPayload(payload) {
48561
- return upsertSlackWorkspace({
48562
- team_id: payload.team_id,
48563
- team_name: payload.team_name,
48564
- user_id: payload.user_id,
48565
- bot_token: payload.bot_token,
48566
- user_token: payload.user_token,
48567
- scopes: payload.scopes,
48568
- connected_at: (/* @__PURE__ */ new Date()).toISOString()
48569
- });
48570
- }
48571
- async function startSlackOAuth(opts) {
48572
- if (opts?.signal?.aborted) {
48573
- throw new SlackOAuthCancelledError();
48574
- }
48575
- const { clientId } = slackOAuthCredentials();
48576
- const state = (0, import_node_crypto33.randomBytes)(16).toString("hex");
48577
- const authorizeUrl = slackOAuthAuthorizeUrl(clientId, state);
48578
- const timeoutMs = opts?.timeoutMs ?? 5 * 6e4;
48579
- const pollIntervalMs = opts?.pollIntervalMs ?? 400;
48580
- const fetchImpl = opts?.fetchImpl ?? fetch;
48581
- const resultUrl = opts?.resultUrlForState?.(state) ?? slackOAuthResultUrl(state);
48582
- await Promise.resolve(opts?.openUrl?.(authorizeUrl));
48583
- if (opts?.signal?.aborted) {
48584
- throw new SlackOAuthCancelledError();
48585
- }
48586
- const deadline = Date.now() + timeoutMs;
48587
- while (Date.now() < deadline) {
48588
- if (opts?.signal?.aborted) {
48589
- throw new SlackOAuthCancelledError();
48590
- }
48591
- let res;
48592
- try {
48593
- res = await fetchImpl(resultUrl);
48594
- } catch {
48595
- if (opts?.signal?.aborted) throw new SlackOAuthCancelledError();
48596
- await sleep(pollIntervalMs, opts?.signal);
48597
- continue;
48598
- }
48599
- let data;
48600
- try {
48601
- data = await res.json();
48602
- } catch {
48603
- await sleep(pollIntervalMs, opts?.signal);
48604
- continue;
48605
- }
48606
- if (data.ok && data.team_id?.trim()) {
48607
- return upsertFromPayload({
48608
- team_id: data.team_id.trim(),
48609
- team_name: data.team_name?.trim() || data.team_id.trim(),
48610
- user_id: data.user_id?.trim() || void 0,
48611
- bot_token: data.bot_token?.trim() || void 0,
48612
- user_token: data.user_token?.trim() || void 0,
48613
- scopes: data.scopes?.trim() || ""
48614
- });
48615
- }
48616
- const err = data.error?.trim();
48617
- if (err && err !== "pending") {
48618
- if (/cancel/i.test(err) || /access_denied/i.test(err)) {
48619
- throw new SlackOAuthCancelledError(`Slack OAuth: ${err}`);
48620
- }
48621
- throw new Error(err.startsWith("Slack") ? err : `Slack OAuth: ${err}`);
49523
+ async function saveSlackOrgCredentials(opts) {
49524
+ const fetchImpl = opts.fetchImpl ?? fetch;
49525
+ const res = await fetchImpl(
49526
+ `${originOf(opts.relayWsUrl)}/slack/apps/${encodeURIComponent(opts.registrationId)}/credentials`,
49527
+ {
49528
+ method: "POST",
49529
+ headers: { "Content-Type": "application/json" },
49530
+ body: JSON.stringify({
49531
+ writeToken: opts.writeToken,
49532
+ clientId: opts.clientId,
49533
+ clientSecret: opts.clientSecret,
49534
+ signingSecret: opts.signingSecret
49535
+ })
48622
49536
  }
48623
- await sleep(pollIntervalMs, opts?.signal);
48624
- }
48625
- throw new Error("Slack sign-in timed out \u2014 try again");
49537
+ );
49538
+ if (!res.ok) throw new Error(await readError(res));
48626
49539
  }
48627
49540
 
49541
+ // src/index.ts
49542
+ init_client_ids();
49543
+
48628
49544
  // src/slack/listen.ts
48629
49545
  init_orchestrator_capable();
48630
49546
  init_orchestrator();
@@ -48635,19 +49551,19 @@ init_turn_live();
48635
49551
  init_thread_store();
48636
49552
 
48637
49553
  // src/slack/reply-target.ts
48638
- var import_node_fs77 = require("fs");
48639
- var import_node_path79 = require("path");
49554
+ var import_node_fs79 = require("fs");
49555
+ var import_node_path81 = require("path");
48640
49556
  init_paths();
48641
49557
  init_private_file();
48642
49558
  init_secure_file();
48643
49559
  function storePath3() {
48644
- return (0, import_node_path79.join)(appDataDir(), "slack-reply-to.json");
49560
+ return (0, import_node_path81.join)(appDataDir(), "slack-reply-to.json");
48645
49561
  }
48646
49562
  function readStore3() {
48647
49563
  const path2 = storePath3();
48648
- if (!(0, import_node_fs77.existsSync)(path2)) return {};
49564
+ if (!(0, import_node_fs79.existsSync)(path2)) return {};
48649
49565
  try {
48650
- const parsed = isSecureFileEncrypted(path2) ? readSecureJson(path2) : JSON.parse((0, import_node_fs77.readFileSync)(path2, "utf8"));
49566
+ const parsed = isSecureFileEncrypted(path2) ? readSecureJson(path2) : JSON.parse((0, import_node_fs79.readFileSync)(path2, "utf8"));
48651
49567
  return parsed?.targets && typeof parsed.targets === "object" ? parsed.targets : {};
48652
49568
  } catch {
48653
49569
  return {};
@@ -48703,9 +49619,11 @@ async function runSlackRelayClient(opts) {
48703
49619
  const deviceId = opts.deviceId.trim();
48704
49620
  if (!url) throw new Error("Relay URL is empty");
48705
49621
  if (!deviceId) throw new Error("Relay needs a deviceId for this Mac");
48706
- if (opts.workspaces.length === 0) {
49622
+ if (opts.workspaces.length === 0 || opts.workspaces.some(
49623
+ (ws) => !ws.botToken.trim() || !ws.userId.trim() || !ws.userToken?.trim() && !ws.listenGrant?.trim()
49624
+ )) {
48707
49625
  throw new Error(
48708
- "Relay needs a connected Slack workspace with bot + user tokens (Add via browser)."
49626
+ "Relay needs Add via browser so this Mac can prove which Slack user it is."
48709
49627
  );
48710
49628
  }
48711
49629
  let backoff = BACKOFF_START_MS3;
@@ -48811,7 +49729,8 @@ function connectSession2(ws, opts, log) {
48811
49729
  deviceId: opts.deviceId.trim(),
48812
49730
  deviceLabel: opts.deviceLabel?.trim() || void 0,
48813
49731
  botToken: wsInfo.botToken,
48814
- userToken: wsInfo.userToken
49732
+ ...wsInfo.userToken?.trim() ? { userToken: wsInfo.userToken.trim() } : {},
49733
+ ...wsInfo.listenGrant?.trim() ? { listenGrant: wsInfo.listenGrant.trim() } : {}
48815
49734
  });
48816
49735
  }
48817
49736
  pingOnce();
@@ -49181,8 +50100,8 @@ function startSlackTurnProgress(msg, threadId, opts) {
49181
50100
  finishWith: (text7) => {
49182
50101
  stop();
49183
50102
  return run2(async () => {
49184
- const signed = signForThisMac(text7.trim());
49185
- if (!signed) {
50103
+ const signed2 = signForThisMac(text7.trim());
50104
+ if (!signed2) {
49186
50105
  if (!postedTs) return;
49187
50106
  const ts = postedTs;
49188
50107
  postedTs = null;
@@ -49196,14 +50115,14 @@ function startSlackTurnProgress(msg, threadId, opts) {
49196
50115
  }
49197
50116
  if (postedTs) {
49198
50117
  try {
49199
- await updateSlackText(target, postedTs, signed, opts);
50118
+ await updateSlackText(target, postedTs, signed2, opts);
49200
50119
  return;
49201
50120
  } catch (err) {
49202
50121
  const errMsg = err instanceof Error ? err.message : String(err);
49203
50122
  log(`progress update error: ${errMsg}`);
49204
50123
  }
49205
50124
  }
49206
- await postSlackText(target, signed, opts);
50125
+ await postSlackText(target, signed2, opts);
49207
50126
  });
49208
50127
  }
49209
50128
  };
@@ -49436,12 +50355,10 @@ async function runSlackListen(opts = {}) {
49436
50355
  if (!relay) {
49437
50356
  throw new Error("Slack Listen needs the hosted relay URL.");
49438
50357
  }
49439
- const withIdentity = connected.filter(
49440
- (w) => w.bot_token?.trim() && w.user_token?.trim() && w.user_id?.trim()
49441
- );
50358
+ const withIdentity = connected.filter(slackWorkspaceCanListen);
49442
50359
  if (withIdentity.length === 0) {
49443
50360
  throw new Error(
49444
- "Slack Listen needs Add via browser (bot token + your Slack user id). Paste-only bot tokens cannot prove which Slack user owns this Mac."
50361
+ "Slack Listen needs Add via browser so this Mac can prove which Slack user it is. A pasted bot token cannot."
49445
50362
  );
49446
50363
  }
49447
50364
  const device = ensureSlackDeviceIdentity();
@@ -49453,12 +50370,17 @@ async function runSlackListen(opts = {}) {
49453
50370
  WebSocketImpl: opts.WebSocketImpl,
49454
50371
  deviceId: device.deviceId,
49455
50372
  deviceLabel: device.deviceLabel,
49456
- workspaces: withIdentity.map((w) => ({
49457
- teamId: w.team_id,
49458
- userId: w.user_id.trim(),
49459
- botToken: w.bot_token.trim(),
49460
- userToken: w.user_token.trim()
49461
- })),
50373
+ workspaces: withIdentity.map((w) => {
50374
+ const userToken = w.user_token?.trim();
50375
+ const listenGrant = w.listen_grant?.trim();
50376
+ return {
50377
+ teamId: w.team_id,
50378
+ userId: w.user_id.trim(),
50379
+ botToken: w.bot_token.trim(),
50380
+ ...userToken ? { userToken } : {},
50381
+ ...listenGrant ? { listenGrant } : {}
50382
+ };
50383
+ }),
49462
50384
  onEvent: onInbound,
49463
50385
  onUninstalled: (teamId) => {
49464
50386
  disconnectSlackWorkspace(teamId);
@@ -49471,9 +50393,7 @@ async function runSlackListen(opts = {}) {
49471
50393
  }
49472
50394
  function resolveSlackListenMode(opts) {
49473
50395
  const relay = (opts?.relayUrl ?? slackRelayUrl()).trim();
49474
- const count = opts?.workspaceCount ?? listSlackWorkspacesRaw().filter(
49475
- (w) => w.bot_token?.trim() && w.user_token?.trim() && w.user_id?.trim()
49476
- ).length;
50396
+ const count = listSlackWorkspacesRaw().filter(slackWorkspaceCanListen).length;
49477
50397
  if (relay && count > 0) return "relay";
49478
50398
  return null;
49479
50399
  }
@@ -49482,7 +50402,7 @@ function resolveSlackListenMode(opts) {
49482
50402
  init_protocol();
49483
50403
 
49484
50404
  // src/relay/account-login.ts
49485
- var import_node_crypto34 = require("crypto");
50405
+ var import_node_crypto39 = require("crypto");
49486
50406
  init_fetch();
49487
50407
  init_protocol();
49488
50408
  var RemoteAccountLoginCancelled = class extends Error {
@@ -49537,7 +50457,7 @@ async function relayFetch(fetchImpl, url, init) {
49537
50457
  throw relayFetchError(err, url);
49538
50458
  }
49539
50459
  }
49540
- async function readJson5(res, url) {
50460
+ async function readJson6(res, url) {
49541
50461
  try {
49542
50462
  return await res.json();
49543
50463
  } catch {
@@ -49550,7 +50470,7 @@ async function readJson5(res, url) {
49550
50470
  async function startRemoteAccountLogin(opts) {
49551
50471
  if (opts.signal?.aborted) throw new RemoteAccountLoginCancelled();
49552
50472
  const origin = (opts.origin ?? remoteAccountHttpOrigin()).replace(/\/+$/, "");
49553
- const state = (0, import_node_crypto34.randomBytes)(16).toString("hex");
50473
+ const state = (0, import_node_crypto39.randomBytes)(16).toString("hex");
49554
50474
  const timeoutMs = opts.timeoutMs ?? 5 * 6e4;
49555
50475
  const pollIntervalMs = opts.pollIntervalMs ?? 400;
49556
50476
  const linkToken = opts.linkToken?.trim() ?? "";
@@ -49564,7 +50484,7 @@ async function startRemoteAccountLogin(opts) {
49564
50484
  ...linkToken ? { accountToken: linkToken } : {}
49565
50485
  })
49566
50486
  });
49567
- const startBody = await readJson5(started, startUrl);
50487
+ const startBody = await readJson6(started, startUrl);
49568
50488
  if (!started.ok || !startBody.url) {
49569
50489
  throw new Error(startBody.error || `Could not start sign-in (HTTP ${started.status}).`);
49570
50490
  }
@@ -49612,8 +50532,8 @@ async function disconnectRemoteAccount(opts) {
49612
50532
  }
49613
50533
 
49614
50534
  // src/slack/outbound-watch.ts
49615
- var import_node_fs78 = require("fs");
49616
- var import_node_path80 = require("path");
50535
+ var import_node_fs80 = require("fs");
50536
+ var import_node_path82 = require("path");
49617
50537
  init_paths();
49618
50538
  init_private_file();
49619
50539
  init_secure_file();
@@ -49626,7 +50546,7 @@ var POLL_INTERVAL_MS = 12e3;
49626
50546
  var lastPollMs = 0;
49627
50547
  var nameCache = /* @__PURE__ */ new Map();
49628
50548
  function storePath4() {
49629
- return (0, import_node_path80.join)(appDataDir(), "slack-outbound-watch.json");
50549
+ return (0, import_node_path82.join)(appDataDir(), "slack-outbound-watch.json");
49630
50550
  }
49631
50551
  function watchId(teamId, channelId, ts) {
49632
50552
  return `${teamId}:${channelId}:${ts}`;
@@ -49639,9 +50559,9 @@ function tsNewer(a, b) {
49639
50559
  }
49640
50560
  function readStore4() {
49641
50561
  const path2 = storePath4();
49642
- if (!(0, import_node_fs78.existsSync)(path2)) return [];
50562
+ if (!(0, import_node_fs80.existsSync)(path2)) return [];
49643
50563
  try {
49644
- const parsed = isSecureFileEncrypted(path2) ? readSecureJson(path2) : JSON.parse((0, import_node_fs78.readFileSync)(path2, "utf8"));
50564
+ const parsed = isSecureFileEncrypted(path2) ? readSecureJson(path2) : JSON.parse((0, import_node_fs80.readFileSync)(path2, "utf8"));
49645
50565
  return Array.isArray(parsed?.watches) ? parsed.watches : [];
49646
50566
  } catch {
49647
50567
  return [];
@@ -49976,6 +50896,7 @@ async function pollSlackOutboundWatches(opts) {
49976
50896
  AbleTimeOAuthCancelledError,
49977
50897
  BAKED_ABLETIME_OAUTH_CLIENT_ID,
49978
50898
  BAKED_REMOTE_RELAY_URL,
50899
+ BAKED_SLACK_CLIENT_ID,
49979
50900
  BAKED_SLACK_RELAY_URL,
49980
50901
  BASE_ALLOWED_TOOLS,
49981
50902
  BRIGHTSY_MCP_ALLOWED_TOOLS,
@@ -50280,6 +51201,7 @@ async function pollSlackOutboundWatches(opts) {
50280
51201
  createOrUpdatePr,
50281
51202
  createPrStack,
50282
51203
  createSchedule,
51204
+ createSlackOrgApp,
50283
51205
  createThread,
50284
51206
  createThreadWorktree,
50285
51207
  currentBranch,
@@ -50703,6 +51625,7 @@ async function pollSlackOutboundWatches(opts) {
50703
51625
  mergePrStack,
50704
51626
  mergeSetupOutput,
50705
51627
  mergeSideboardIntoMcpServersJson,
51628
+ mergeSlackClientIds,
50706
51629
  mergeUsage,
50707
51630
  messagePartParentId,
50708
51631
  messagesForCompactArchive,
@@ -50910,6 +51833,7 @@ async function pollSlackOutboundWatches(opts) {
50910
51833
  saveAppSettings,
50911
51834
  saveLinearOAuth,
50912
51835
  saveRemotePhoneToken,
51836
+ saveSlackOrgCredentials,
50913
51837
  saveWorktreeRunPorts,
50914
51838
  scheduleNeedsCaffeinate,
50915
51839
  schedulesPath,