@sideboard-ai/core 0.1.333 → 0.1.335

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 +1476 -568
  48. package/dist/index.d.cts +101 -15
  49. package/dist/index.d.ts +101 -15
  50. package/dist/index.js +1403 -531
  51. package/dist/{linear-FRJRK6KI.js → linear-5E2WI4QQ.js} +2 -2
  52. package/dist/{linear-7HSIGV5S.js → linear-P3LP455O.js} +2 -2
  53. package/dist/{linear-list-LDMBSKYI.js → linear-list-AXK62DPW.js} +1 -1
  54. package/dist/{linear-list-I6DNJC6V.js → linear-list-Y3INIBYH.js} +1 -1
  55. package/dist/mcp/run-stdio.cjs +29 -1
  56. package/dist/mcp/run-stdio.js +16 -16
  57. package/dist/{optional-cli-KWIII44P.js → optional-cli-6J6C4I3X.js} +3 -3
  58. package/dist/{optional-cli-XJE4BELL.js → optional-cli-X6I35UNI.js} +4 -4
  59. package/dist/{orchestrator-WHXHBNRS.js → orchestrator-BOLYQZO7.js} +10 -10
  60. package/dist/{orchestrator-IYXIWNB5.js → orchestrator-ZUIU667R.js} +10 -10
  61. package/dist/{thread-store-PCIMS6RA.js → thread-store-DCO5MZWJ.js} +2 -2
  62. package/dist/{thread-store-NVFWKJFH.js → thread-store-QGBPSZU2.js} +2 -2
  63. package/dist/{workspaces-ALUHOCWK.js → workspaces-VXE2MBKD.js} +4 -4
  64. package/dist/{workspaces-QGKSXA76.js → workspaces-WZZNNUJL.js} +4 -4
  65. package/dist/{worktree-6WWUWH4K.js → worktree-GWS77LWX.js} +3 -3
  66. package/dist/{worktree-N435EXSP.js → worktree-S4YOAYRA.js} +3 -3
  67. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -17,13 +17,13 @@ import {
17
17
  toAbleTimeIssueInfo,
18
18
  updateAbleTimeTask,
19
19
  verifyAbleTimeConnection
20
- } from "./chunk-YMV5O7KY.js";
20
+ } from "./chunk-FEGRY7NL.js";
21
21
  import {
22
22
  clearOptionalCliPresenceCache,
23
23
  detectOptionalServiceClis,
24
24
  installOptionalServiceCli,
25
25
  optionalCliPresence
26
- } from "./chunk-UV33UCV6.js";
26
+ } from "./chunk-FCBUDWP6.js";
27
27
  import {
28
28
  AGENT_GIT_ACTIONS,
29
29
  BOARD_COLUMN_DEFS,
@@ -219,7 +219,7 @@ import {
219
219
  worktreeCleanupSettings,
220
220
  writeAgentBlock,
221
221
  writeWorktreeFile
222
- } from "./chunk-4J7R2BFU.js";
222
+ } from "./chunk-EKI7D2AJ.js";
223
223
  import {
224
224
  OPTIONAL_SERVICES,
225
225
  OPTIONAL_SERVICE_IDS,
@@ -235,7 +235,7 @@ import {
235
235
  optionalServiceConnected,
236
236
  optionalServiceSpec,
237
237
  verifyOptionalService
238
- } from "./chunk-RCRDNOAT.js";
238
+ } from "./chunk-QWFNKOGA.js";
239
239
  import {
240
240
  LEGACY_PLAN_FILE_REL,
241
241
  PLAN_FILE_NAME,
@@ -292,7 +292,7 @@ import {
292
292
  startLinearOAuth,
293
293
  updateLinearIssue,
294
294
  validateLinearApiKey
295
- } from "./chunk-7MPRTC6X.js";
295
+ } from "./chunk-Q73I6I2K.js";
296
296
  import {
297
297
  downloadAuthenticatedFile,
298
298
  extractHttpUrls,
@@ -380,7 +380,7 @@ import {
380
380
  userMcpNamesToDisable,
381
381
  worktreeMcpToolNames,
382
382
  writeInjectedMcpConfig
383
- } from "./chunk-TLL2K2MY.js";
383
+ } from "./chunk-NB4U75TJ.js";
384
384
  import {
385
385
  getAgentSetupInfo,
386
386
  installAgent,
@@ -392,7 +392,7 @@ import {
392
392
  prepareTerminalCommand,
393
393
  resolveLoginCommand,
394
394
  whichOnPath
395
- } from "./chunk-QNKJCD7B.js";
395
+ } from "./chunk-5FGQTB2Z.js";
396
396
  import {
397
397
  brightsyMcpServerName,
398
398
  connectBrightsyTeam,
@@ -403,7 +403,7 @@ import {
403
403
  listConnectedBrightsyTeams,
404
404
  switchBrightsyAccount
405
405
  } from "./chunk-XOEKCE6L.js";
406
- import "./chunk-ZT5YPYZE.js";
406
+ import "./chunk-KAIOL2M5.js";
407
407
  import {
408
408
  BRIGHTSY_SUMMARIZE_CONTEXT_TOOL,
409
409
  CHARS_PER_CONTEXT_TOKEN,
@@ -513,7 +513,7 @@ import {
513
513
  workspaceAgentChatSummaries,
514
514
  worktreeRunPortsPath,
515
515
  wrapReviewSkillMarkdown
516
- } from "./chunk-ELDJBZ52.js";
516
+ } from "./chunk-B6TPN624.js";
517
517
  import {
518
518
  STDERR_EVENT_MAX_CHARS,
519
519
  STDOUT_EVENT_MAX_CHARS,
@@ -579,10 +579,10 @@ import {
579
579
  parseAbleTimeOAuthCallbackUrl,
580
580
  resolveAbleTimeOAuthHost,
581
581
  startAbleTimeOAuth
582
- } from "./chunk-F4OUZDIB.js";
582
+ } from "./chunk-4BRO5LNX.js";
583
583
  import {
584
584
  looksLikeAbleTimeUlid
585
- } from "./chunk-HJIA4X3L.js";
585
+ } from "./chunk-W6J3ZWLJ.js";
586
586
  import {
587
587
  ABLETIME_MCP_PATH,
588
588
  ABLETIME_MCP_PM_PATH,
@@ -603,7 +603,7 @@ import {
603
603
  normalizeAbleTimeCredential,
604
604
  normalizeAbleTimeHost,
605
605
  rewriteAbleTimeError
606
- } from "./chunk-SKPX66MO.js";
606
+ } from "./chunk-4SP26Z6H.js";
607
607
  import {
608
608
  CLOUD_COORDINATOR_BUSY_REPLY,
609
609
  CLOUD_COORDINATOR_CANCELED_REPLY,
@@ -656,7 +656,7 @@ import {
656
656
  stageBuffersAsAttachments,
657
657
  syncWorkspacesFromThreads,
658
658
  takenTeamSlugsForOrchestration
659
- } from "./chunk-LEUAYFSG.js";
659
+ } from "./chunk-CDRGQ6GX.js";
660
660
  import {
661
661
  GITHUB_PR_BODY_MAX_CHARS,
662
662
  GITHUB_PR_BODY_SAFE_CHARS,
@@ -745,7 +745,7 @@ import {
745
745
  suggestSlug,
746
746
  switchWorktreeBranch,
747
747
  warmGithubAgentAuth
748
- } from "./chunk-JJRTVB7D.js";
748
+ } from "./chunk-4OVQGZEI.js";
749
749
  import {
750
750
  FAMOUS_SOCCER_TEAMS,
751
751
  WEEKDAY_LABELS,
@@ -801,7 +801,7 @@ import {
801
801
  worktreeNameFromPath,
802
802
  worktreeSlugForTicket,
803
803
  writeThread
804
- } from "./chunk-QVLDZWHZ.js";
804
+ } from "./chunk-BDQFZAE6.js";
805
805
  import "./chunk-BMRJNRQK.js";
806
806
  import {
807
807
  BRIGHTSY_OAUTH_CLIENT_ID,
@@ -1020,6 +1020,7 @@ import {
1020
1020
  loadAppSettings,
1021
1021
  loadSecretVault,
1022
1022
  maxConcurrentAgents,
1023
+ mergeSlackClientIds,
1023
1024
  mergeUsage,
1024
1025
  nextThinkingEffort,
1025
1026
  normalizeRemoteRelayUrl,
@@ -1087,7 +1088,7 @@ import {
1087
1088
  withTurnScopedCost,
1088
1089
  writeSecureJson,
1089
1090
  writeViewerContext
1090
- } from "./chunk-EY5BJAPV.js";
1091
+ } from "./chunk-23KYDM2U.js";
1091
1092
  import {
1092
1093
  stripNestedElectronEnv
1093
1094
  } from "./chunk-4TR3HZFT.js";
@@ -3375,8 +3376,8 @@ function dispatchPhoneWorkspace(cmd, emit, publishOpened) {
3375
3376
  emit({ op: "error", chatId: cmd.chatId, message: "That agent is not on this Mac." });
3376
3377
  return;
3377
3378
  }
3378
- void readPhoneHeader(thread).then((header) => {
3379
- emit({ op: "header", chatId: cmd.chatId, ...header });
3379
+ void readPhoneHeader(thread).then((header2) => {
3380
+ emit({ op: "header", chatId: cmd.chatId, ...header2 });
3380
3381
  });
3381
3382
  return;
3382
3383
  }
@@ -4209,12 +4210,52 @@ function sourceWarning(label, err) {
4209
4210
  const message = err instanceof Error ? err.message : String(err);
4210
4211
  return message ? `${label}: ${message}` : `${label} failed.`;
4211
4212
  }
4213
+ function phonePrNumberQuery(query) {
4214
+ const match = query.trim().match(/^#?(\d+)$/);
4215
+ if (!match) return null;
4216
+ const n = Number(match[1]);
4217
+ if (!Number.isSafeInteger(n) || n <= 0) return null;
4218
+ return n;
4219
+ }
4220
+ function phonePrMatchesQuery(pr, query) {
4221
+ const raw = query.trim().toLowerCase();
4222
+ if (!raw) return true;
4223
+ const q = raw.replace(/^#/, "");
4224
+ if (!q) return pr.title.toLowerCase().includes(raw);
4225
+ return pr.title.toLowerCase().includes(q) || String(pr.number).includes(q);
4226
+ }
4227
+ function prIsListedOpen(pr) {
4228
+ const state = pr.state?.trim().toLowerCase();
4229
+ return state !== "closed" && state !== "merged";
4230
+ }
4231
+ function mergePrs(groups) {
4232
+ const out = [];
4233
+ const seen = /* @__PURE__ */ new Set();
4234
+ for (const group of groups) {
4235
+ for (const pr of group) {
4236
+ if (!pr || seen.has(pr.number) || !prIsListedOpen(pr)) continue;
4237
+ seen.add(pr.number);
4238
+ out.push(pr);
4239
+ }
4240
+ }
4241
+ return out;
4242
+ }
4243
+ async function loadPhonePrs(path2, query) {
4244
+ const number = phonePrNumberQuery(query);
4245
+ if (!query) return listPrs(path2, { state: "open", limit: 40 });
4246
+ const [searched, recent, exact] = await Promise.all([
4247
+ listPrs(path2, { state: "open", limit: 40, query: number == null ? query : String(number) }),
4248
+ listPrs(path2, { state: "open", limit: number == null ? 40 : 200 }),
4249
+ number == null ? Promise.resolve(null) : getPr(path2, number).catch(() => null)
4250
+ ]);
4251
+ return mergePrs([exact ? [exact] : [], searched, recent]).filter((pr) => phonePrMatchesQuery(pr, query));
4252
+ }
4212
4253
  async function listPhoneSources(repoPath, query) {
4213
4254
  const path2 = assertKnownProject(repoPath);
4214
4255
  const q = query?.trim() ?? "";
4215
4256
  const warnings = [];
4216
4257
  const [prs, branches, issues] = await Promise.all([
4217
- listPrs(path2, { state: "open", limit: 40, ...q ? { query: q } : {} }).catch((err) => {
4258
+ loadPhonePrs(path2, q).catch((err) => {
4218
4259
  warnings.push(sourceWarning("Pull requests", err));
4219
4260
  return [];
4220
4261
  }),
@@ -5220,26 +5261,6 @@ function slackOAuthHtmlPage(title, body) {
5220
5261
  <style>body{font-family:ui-sans-serif,system-ui,sans-serif;padding:48px 24px;max-width:36rem;margin:0 auto;color:#1a1a1a}
5221
5262
  h1{font-size:1.25rem}p{line-height:1.5;color:#444}</style></head><body>${body}</body></html>`;
5222
5263
  }
5223
- function parseSlackOAuthCallbackUrl(reqUrl) {
5224
- let url;
5225
- try {
5226
- url = new URL(reqUrl, SLACK_OAUTH_REDIRECT);
5227
- } catch {
5228
- return null;
5229
- }
5230
- if (url.pathname !== SLACK_OAUTH_CALLBACK_PATH) return null;
5231
- return url;
5232
- }
5233
- function parseSlackOAuthResultUrl(reqUrl) {
5234
- let url;
5235
- try {
5236
- url = new URL(reqUrl, SLACK_OAUTH_REDIRECT);
5237
- } catch {
5238
- return null;
5239
- }
5240
- if (url.pathname !== SLACK_OAUTH_RESULT_PATH) return null;
5241
- return url;
5242
- }
5243
5264
 
5244
5265
  // src/slack/baked-app.ts
5245
5266
  var BAKED_SLACK_CLIENT_ID = "7592788819232.11813536272562";
@@ -5321,11 +5342,15 @@ async function exchangeSlackOAuthCode(opts) {
5321
5342
  team_name: data.team?.name?.trim() || teamId,
5322
5343
  user_id: data.authed_user?.id?.trim() || void 0,
5323
5344
  bot_token: data.access_token?.trim() || void 0,
5345
+ bot_user_id: data.bot_user_id?.trim() || void 0,
5324
5346
  user_token: data.authed_user?.access_token?.trim() || void 0,
5325
5347
  scopes: [data.scope, data.authed_user?.scope].filter(Boolean).join(",")
5326
5348
  };
5327
5349
  }
5328
5350
 
5351
+ // src/slack/events-api.ts
5352
+ import { createHmac, timingSafeEqual } from "crypto";
5353
+
5329
5354
  // src/slack/socket-mode.ts
5330
5355
  import { WebSocket as WsWebSocket2 } from "ws";
5331
5356
 
@@ -5596,19 +5621,978 @@ function connectSession(ws, opts, log) {
5596
5621
  });
5597
5622
  return;
5598
5623
  }
5599
- const life = lifecycleFromSocketFrame(frame);
5600
- if (life && opts.onLifecycle) {
5601
- void Promise.resolve(opts.onLifecycle(life)).catch((err) => {
5602
- const msg = err instanceof Error ? err.message : String(err);
5603
- log(`lifecycle error: ${msg}`);
5604
- });
5605
- }
5624
+ const life = lifecycleFromSocketFrame(frame);
5625
+ if (life && opts.onLifecycle) {
5626
+ void Promise.resolve(opts.onLifecycle(life)).catch((err) => {
5627
+ const msg = err instanceof Error ? err.message : String(err);
5628
+ log(`lifecycle error: ${msg}`);
5629
+ });
5630
+ }
5631
+ });
5632
+ });
5633
+ }
5634
+
5635
+ // src/slack/events-api.ts
5636
+ var MAX_SKEW_MS = 5 * 6e4;
5637
+ function verifySlackRequestSignature(opts) {
5638
+ const timestamp = opts.timestamp.trim();
5639
+ const signature = opts.signature.trim();
5640
+ const seconds = Number(timestamp);
5641
+ if (!timestamp || !signature || !Number.isFinite(seconds)) return false;
5642
+ const now = opts.nowMs ?? Date.now();
5643
+ if (Math.abs(now - seconds * 1e3) > MAX_SKEW_MS) return false;
5644
+ const hmac = createHmac("sha256", opts.signingSecret).update(`v0:${timestamp}:${opts.rawBody}`).digest("hex");
5645
+ const expected = Buffer.from(`v0=${hmac}`);
5646
+ const presented = Buffer.from(signature);
5647
+ return expected.length === presented.length && timingSafeEqual(expected, presented);
5648
+ }
5649
+ function parseSlackEventsBody(raw) {
5650
+ try {
5651
+ const parsed = JSON.parse(raw);
5652
+ if (!parsed || typeof parsed !== "object") return null;
5653
+ return parsed;
5654
+ } catch {
5655
+ return null;
5656
+ }
5657
+ }
5658
+ function asSocketFrame(body) {
5659
+ return {
5660
+ type: "events_api",
5661
+ payload: {
5662
+ team_id: typeof body.team_id === "string" ? body.team_id : void 0,
5663
+ event: body.event
5664
+ }
5665
+ };
5666
+ }
5667
+ function inboundFromEventsBody(body) {
5668
+ if (body.type !== "event_callback") return null;
5669
+ return inboundFromSocketFrame(asSocketFrame(body));
5670
+ }
5671
+ function lifecycleFromEventsBody(body) {
5672
+ if (body.type !== "event_callback") return null;
5673
+ return lifecycleFromSocketFrame(asSocketFrame(body));
5674
+ }
5675
+ var SlackEventDeduper = class {
5676
+ constructor(ttlMs = 10 * 6e4) {
5677
+ this.ttlMs = ttlMs;
5678
+ }
5679
+ ttlMs;
5680
+ seen = /* @__PURE__ */ new Map();
5681
+ duplicate(eventId, now = Date.now()) {
5682
+ const id = eventId.trim();
5683
+ if (!id) return false;
5684
+ for (const [key, expires] of this.seen) {
5685
+ if (expires <= now) this.seen.delete(key);
5686
+ }
5687
+ if (this.seen.has(id)) return true;
5688
+ this.seen.set(id, now + this.ttlMs);
5689
+ return false;
5690
+ }
5691
+ };
5692
+
5693
+ // src/slack/secret-box.ts
5694
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes2 } from "crypto";
5695
+ var VERSION = "v1";
5696
+ function parseSlackTokenKey(raw) {
5697
+ const text5 = raw.trim();
5698
+ if (!text5) throw new Error("SIDEBOARD_SLACK_TOKEN_KEY is empty");
5699
+ const buf = /^[0-9a-fA-F]{64}$/.test(text5) ? Buffer.from(text5, "hex") : Buffer.from(text5, "base64");
5700
+ if (buf.length !== 32) {
5701
+ throw new Error("SIDEBOARD_SLACK_TOKEN_KEY must be 32 bytes (base64 or 64 hex characters)");
5702
+ }
5703
+ return buf;
5704
+ }
5705
+ function sealSecret(key, plaintext) {
5706
+ const iv = randomBytes2(12);
5707
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
5708
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
5709
+ const tag = cipher.getAuthTag();
5710
+ return [VERSION, iv.toString("base64url"), tag.toString("base64url"), ciphertext.toString("base64url")].join(
5711
+ "."
5712
+ );
5713
+ }
5714
+ function openSecret(key, sealed) {
5715
+ const [version, ivB64, tagB64, ctB64] = sealed.split(".");
5716
+ if (version !== VERSION || !ivB64 || !tagB64 || !ctB64 || sealed.split(".").length !== 4) {
5717
+ throw new Error("Slack secret ciphertext is not recognized");
5718
+ }
5719
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64url"));
5720
+ decipher.setAuthTag(Buffer.from(tagB64, "base64url"));
5721
+ return Buffer.concat([
5722
+ decipher.update(Buffer.from(ctB64, "base64url")),
5723
+ decipher.final()
5724
+ ]).toString("utf8");
5725
+ }
5726
+
5727
+ // src/slack/oauth-state.ts
5728
+ import { randomBytes as randomBytes3 } from "crypto";
5729
+ function slackOAuthState(clientId, bakedClientId) {
5730
+ const nonce = randomBytes3(16).toString("hex");
5731
+ const id = clientId.trim();
5732
+ if (!id || id === bakedClientId.trim()) return nonce;
5733
+ return `c.${Buffer.from(id, "utf8").toString("base64url")}.${nonce}`;
5734
+ }
5735
+ function clientIdFromOAuthState(state) {
5736
+ if (!state.startsWith("c.")) return null;
5737
+ const rest = state.slice(2);
5738
+ const dot = rest.lastIndexOf(".");
5739
+ if (dot <= 0) return null;
5740
+ if (!/^[0-9a-f]{32}$/.test(rest.slice(dot + 1))) return null;
5741
+ try {
5742
+ const id = Buffer.from(rest.slice(0, dot), "base64url").toString("utf8").trim();
5743
+ if (!id || id.includes("\0")) return null;
5744
+ return id;
5745
+ } catch {
5746
+ return null;
5747
+ }
5748
+ }
5749
+
5750
+ // src/slack/workspaces.ts
5751
+ import { join as join3 } from "path";
5752
+ function storePath() {
5753
+ return join3(appDataDir(), "slack-workspaces.json");
5754
+ }
5755
+ function readStore() {
5756
+ try {
5757
+ const path2 = storePath();
5758
+ const wasEncrypted = isSecureFileEncrypted(path2);
5759
+ const parsed = readSecureJson(path2);
5760
+ const workspaces = Array.isArray(parsed?.workspaces) ? parsed.workspaces : [];
5761
+ if (workspaces.length > 0 && !wasEncrypted && resolveVaultKey()) {
5762
+ writeSecureJson(path2, { workspaces });
5763
+ }
5764
+ return workspaces;
5765
+ } catch {
5766
+ return [];
5767
+ }
5768
+ }
5769
+ function writeStore(workspaces) {
5770
+ writeSecureJson(storePath(), { workspaces });
5771
+ return workspaces;
5772
+ }
5773
+ function toInfo(ws) {
5774
+ return {
5775
+ team_id: ws.team_id,
5776
+ team_name: ws.team_name,
5777
+ user_id: ws.user_id,
5778
+ has_bot_token: Boolean(ws.bot_token),
5779
+ has_user_token: Boolean(ws.user_token),
5780
+ connected_at: ws.connected_at
5781
+ };
5782
+ }
5783
+ function slackWorkspaceCanListen(ws) {
5784
+ return Boolean(
5785
+ ws.bot_token?.trim() && ws.user_id?.trim() && (ws.user_token?.trim() || ws.listen_grant?.trim())
5786
+ );
5787
+ }
5788
+ function listSlackWorkspaces() {
5789
+ return readStore().map(toInfo).sort((a, b) => a.team_name.localeCompare(b.team_name));
5790
+ }
5791
+ function listSlackWorkspacesRaw() {
5792
+ return readStore();
5793
+ }
5794
+ function getSlackWorkspace(teamId) {
5795
+ const id = teamId.trim();
5796
+ if (!id) return null;
5797
+ return readStore().find(
5798
+ (ws) => ws.team_id === id || ws.team_name.toLowerCase() === id.toLowerCase()
5799
+ ) ?? null;
5800
+ }
5801
+ function upsertSlackWorkspace(entry) {
5802
+ const workspaces = readStore().filter((ws) => ws.team_id !== entry.team_id);
5803
+ workspaces.push(entry);
5804
+ writeStore(workspaces);
5805
+ return toInfo(entry);
5806
+ }
5807
+ function disconnectSlackWorkspace(teamId) {
5808
+ const id = teamId.trim();
5809
+ writeStore(readStore().filter((ws) => ws.team_id !== id));
5810
+ return listSlackWorkspaces();
5811
+ }
5812
+ function tokenKind(token) {
5813
+ if (token.startsWith("xoxb-")) return "bot";
5814
+ if (token.startsWith("xoxp-") || token.startsWith("xoxe.xoxp-")) return "user";
5815
+ return "unknown";
5816
+ }
5817
+ async function connectSlackToken(rawToken) {
5818
+ const token = rawToken.trim();
5819
+ if (!token) throw new Error("Paste a Slack bot (xoxb-) or user (xoxp-) token");
5820
+ const auth = await slackAuthTest(token);
5821
+ const teamId = auth.team_id?.trim();
5822
+ if (!teamId) throw new Error("Slack auth.test did not return a team_id");
5823
+ const existing = getSlackWorkspace(teamId);
5824
+ const kind = tokenKind(token);
5825
+ const next = {
5826
+ team_id: teamId,
5827
+ team_name: auth.team?.trim() || existing?.team_name || teamId,
5828
+ user_id: auth.user_id?.trim() || existing?.user_id,
5829
+ bot_token: kind === "bot" ? token : existing?.bot_token,
5830
+ user_token: kind === "user" || kind === "unknown" ? token : existing?.user_token,
5831
+ scopes: existing?.scopes,
5832
+ connected_at: existing?.connected_at || (/* @__PURE__ */ new Date()).toISOString()
5833
+ };
5834
+ if (kind === "unknown" && auth.bot_id) {
5835
+ next.bot_token = token;
5836
+ next.user_token = existing?.user_token;
5837
+ }
5838
+ return upsertSlackWorkspace(next);
5839
+ }
5840
+ function slackTokenFor(ws, _kind = "read") {
5841
+ const token = (ws.bot_token || ws.user_token)?.trim();
5842
+ if (!token) {
5843
+ throw new Error(`Slack workspace ${ws.team_name} has no token`);
5844
+ }
5845
+ return token;
5846
+ }
5847
+
5848
+ // src/slack/oauth.ts
5849
+ var SLACK_BOT_SCOPES = [
5850
+ "app_mentions:read",
5851
+ "channels:history",
5852
+ "channels:read",
5853
+ "groups:history",
5854
+ "groups:read",
5855
+ "im:history",
5856
+ "im:read",
5857
+ "im:write",
5858
+ "mpim:history",
5859
+ "mpim:read",
5860
+ "chat:write",
5861
+ "chat:write.public",
5862
+ "reactions:write",
5863
+ "users:read",
5864
+ "users:read.email"
5865
+ ].join(",");
5866
+ function slackOAuthCredentials() {
5867
+ const settings = loadAppSettings();
5868
+ const clientId = process.env.SIDEBOARD_SLACK_CLIENT_ID?.trim() || settings.integrations.slackClientId?.trim() || BAKED_SLACK_CLIENT_ID.trim();
5869
+ const clientSecret = process.env.SIDEBOARD_SLACK_CLIENT_SECRET?.trim() || settings.integrations.slackClientSecret?.trim() || "";
5870
+ if (!clientId) {
5871
+ throw new Error(
5872
+ "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."
5873
+ );
5874
+ }
5875
+ return { clientId, clientSecret: clientSecret || null };
5876
+ }
5877
+ var SLACK_OAUTH_CANCELLED = "Slack sign-in cancelled";
5878
+ var SlackOAuthCancelledError = class extends Error {
5879
+ constructor(message = SLACK_OAUTH_CANCELLED) {
5880
+ super(message);
5881
+ this.name = "SlackOAuthCancelledError";
5882
+ }
5883
+ };
5884
+ function isSlackOAuthCancelled(err) {
5885
+ if (err instanceof SlackOAuthCancelledError) return true;
5886
+ const message = err instanceof Error ? err.message : String(err);
5887
+ if (message.includes(SLACK_OAUTH_CANCELLED)) return true;
5888
+ return err instanceof Error && err.name === "SlackOAuthCancelledError";
5889
+ }
5890
+ function slackOAuthAuthorizeUrl(clientId, state) {
5891
+ const params = new URLSearchParams({
5892
+ client_id: clientId,
5893
+ scope: SLACK_BOT_SCOPES,
5894
+ redirect_uri: slackOAuthRedirectUri(),
5895
+ state
5896
+ });
5897
+ return `https://slack.com/oauth/v2/authorize?${params.toString()}`;
5898
+ }
5899
+ function sleep(ms, signal) {
5900
+ return new Promise((resolve, reject) => {
5901
+ if (signal?.aborted) {
5902
+ reject(new SlackOAuthCancelledError());
5903
+ return;
5904
+ }
5905
+ const timer = setTimeout(() => {
5906
+ signal?.removeEventListener("abort", onAbort);
5907
+ resolve();
5908
+ }, ms);
5909
+ const onAbort = () => {
5910
+ clearTimeout(timer);
5911
+ reject(new SlackOAuthCancelledError());
5912
+ };
5913
+ signal?.addEventListener("abort", onAbort, { once: true });
5914
+ });
5915
+ }
5916
+ function upsertFromPayload(payload) {
5917
+ const existing = getSlackWorkspace(payload.team_id);
5918
+ return upsertSlackWorkspace({
5919
+ team_id: payload.team_id,
5920
+ team_name: payload.team_name || existing?.team_name || payload.team_id,
5921
+ user_id: payload.user_id || existing?.user_id,
5922
+ bot_token: payload.bot_token || existing?.bot_token,
5923
+ user_token: payload.user_token || existing?.user_token,
5924
+ listen_grant: payload.listen_grant || existing?.listen_grant,
5925
+ scopes: payload.scopes || existing?.scopes,
5926
+ connected_at: (/* @__PURE__ */ new Date()).toISOString()
5927
+ });
5928
+ }
5929
+ async function startSlackOAuth(opts) {
5930
+ if (opts?.signal?.aborted) {
5931
+ throw new SlackOAuthCancelledError();
5932
+ }
5933
+ const clientId = opts?.clientId?.trim() || slackOAuthCredentials().clientId;
5934
+ const state = slackOAuthState(clientId, BAKED_SLACK_CLIENT_ID);
5935
+ const authorizeUrl = slackOAuthAuthorizeUrl(clientId, state);
5936
+ const timeoutMs = opts?.timeoutMs ?? 5 * 6e4;
5937
+ const pollIntervalMs = opts?.pollIntervalMs ?? 400;
5938
+ const fetchImpl = opts?.fetchImpl ?? fetch;
5939
+ const resultUrl = opts?.resultUrlForState?.(state) ?? slackOAuthResultUrl(state);
5940
+ await Promise.resolve(opts?.openUrl?.(authorizeUrl));
5941
+ if (opts?.signal?.aborted) {
5942
+ throw new SlackOAuthCancelledError();
5943
+ }
5944
+ const deadline = Date.now() + timeoutMs;
5945
+ while (Date.now() < deadline) {
5946
+ if (opts?.signal?.aborted) {
5947
+ throw new SlackOAuthCancelledError();
5948
+ }
5949
+ let res;
5950
+ try {
5951
+ res = await fetchImpl(resultUrl);
5952
+ } catch {
5953
+ if (opts?.signal?.aborted) throw new SlackOAuthCancelledError();
5954
+ await sleep(pollIntervalMs, opts?.signal);
5955
+ continue;
5956
+ }
5957
+ let data;
5958
+ try {
5959
+ data = await res.json();
5960
+ } catch {
5961
+ await sleep(pollIntervalMs, opts?.signal);
5962
+ continue;
5963
+ }
5964
+ if (data.ok && data.team_id?.trim()) {
5965
+ return upsertFromPayload({
5966
+ team_id: data.team_id.trim(),
5967
+ team_name: data.team_name?.trim() || data.team_id.trim(),
5968
+ user_id: data.user_id?.trim() || void 0,
5969
+ bot_token: data.bot_token?.trim() || void 0,
5970
+ user_token: data.user_token?.trim() || void 0,
5971
+ listen_grant: data.listen_grant?.trim() || void 0,
5972
+ scopes: data.scopes?.trim() || ""
5973
+ });
5974
+ }
5975
+ const err = data.error?.trim();
5976
+ if (err && err !== "pending") {
5977
+ if (/cancel/i.test(err) || /access_denied/i.test(err)) {
5978
+ throw new SlackOAuthCancelledError(`Slack OAuth: ${err}`);
5979
+ }
5980
+ throw new Error(err.startsWith("Slack") ? err : `Slack OAuth: ${err}`);
5981
+ }
5982
+ await sleep(pollIntervalMs, opts?.signal);
5983
+ }
5984
+ throw new Error("Slack sign-in timed out \u2014 try again");
5985
+ }
5986
+
5987
+ // src/slack/org-manifest.ts
5988
+ var BOT_EVENTS = [
5989
+ "app_home_opened",
5990
+ "app_mention",
5991
+ "app_uninstalled",
5992
+ "message.im",
5993
+ "message.mpim"
5994
+ ];
5995
+ function yamlList(scopes, indent) {
5996
+ return scopes.split(",").map((scope) => scope.trim()).filter(Boolean).map((scope) => `${indent}- ${scope}`).join("\n");
5997
+ }
5998
+ function slackOrgManifest(opts) {
5999
+ const eventsUrl = opts.eventsUrl.trim();
6000
+ const redirectUrl = opts.redirectUrl.trim();
6001
+ return `display_information:
6002
+ name: Sideboard
6003
+ description: Drive Sideboard agents from Slack DMs and @mentions.
6004
+ background_color: "#111827"
6005
+ long_description: >-
6006
+ Sideboard sends DMs and @mentions to the orchestrator on a Mac in this
6007
+ workspace and posts replies back in thread. Agents can list, read, and
6008
+ post in Slack. Message text is not used to train models.
6009
+
6010
+ features:
6011
+ app_home:
6012
+ home_tab_enabled: true
6013
+ messages_tab_enabled: true
6014
+ messages_tab_read_only_enabled: false
6015
+ bot_user:
6016
+ display_name: Sideboard
6017
+ always_online: true
6018
+
6019
+ oauth_config:
6020
+ redirect_urls:
6021
+ - ${redirectUrl}
6022
+ scopes:
6023
+ bot:
6024
+ ${yamlList(SLACK_BOT_SCOPES, " ")}
6025
+
6026
+ settings:
6027
+ org_deploy_enabled: false
6028
+ socket_mode_enabled: false
6029
+ token_rotation_enabled: false
6030
+ event_subscriptions:
6031
+ request_url: ${eventsUrl}
6032
+ bot_events:
6033
+ ${BOT_EVENTS.map((event) => ` - ${event}`).join("\n")}
6034
+ `;
6035
+ }
6036
+ function slackEventsPath(registrationId) {
6037
+ return `/slack/events/${registrationId}`;
6038
+ }
6039
+ function slackEventsUrl(origin, registrationId) {
6040
+ return `${origin.replace(/\/$/, "")}${slackEventsPath(registrationId)}`;
6041
+ }
6042
+
6043
+ // src/relay/slack-http.ts
6044
+ var EVENTS_PREFIX = "/slack/events/";
6045
+ var APPS_PATH = "/slack/apps";
6046
+ var BODY_LIMIT = 262144;
6047
+ async function handleSlackHttp(ctx) {
6048
+ const url = parseUrl(ctx.reqUrl);
6049
+ if (!url) return false;
6050
+ const path2 = url.pathname;
6051
+ if (path2 === "/slack/callback") return handleCallback(ctx, url);
6052
+ if (path2 === "/slack/oauth/result") return handleResult(ctx, url);
6053
+ if (path2 === APPS_PATH && ctx.req.method === "POST") {
6054
+ await handleCreate(ctx);
6055
+ return true;
6056
+ }
6057
+ const creds = path2.match(/^\/slack\/apps\/([A-Za-z0-9_-]+)\/credentials$/);
6058
+ if (creds && ctx.req.method === "POST") {
6059
+ await handleCredentials(ctx, creds[1]);
6060
+ return true;
6061
+ }
6062
+ if (path2.startsWith(EVENTS_PREFIX) && ctx.req.method === "POST") {
6063
+ await handleEvents(ctx, decodeURIComponent(path2.slice(EVENTS_PREFIX.length)));
6064
+ return true;
6065
+ }
6066
+ return false;
6067
+ }
6068
+ function parseUrl(reqUrl) {
6069
+ try {
6070
+ return new URL(reqUrl, "http://127.0.0.1");
6071
+ } catch {
6072
+ return null;
6073
+ }
6074
+ }
6075
+ async function handleCreate(ctx) {
6076
+ if (!ctx.accounts || !ctx.apps) {
6077
+ sendJson(ctx.res, 503, {
6078
+ ok: false,
6079
+ error: "Per-company Slack apps need SIDEBOARD_SLACK_TOKEN_KEY and the relay account database"
6080
+ });
6081
+ return;
6082
+ }
6083
+ const accountId = ctx.accounts.verifyCredential(bearer(ctx.req));
6084
+ if (!accountId) {
6085
+ sendJson(ctx.res, 401, { ok: false, error: "Sign in to the relay before creating a Slack app" });
6086
+ return;
6087
+ }
6088
+ const created = ctx.apps.create(accountId);
6089
+ const eventsUrl = slackEventsUrl(ctx.publicOrigin, created.registrationId);
6090
+ sendJson(ctx.res, 200, {
6091
+ ok: true,
6092
+ registrationId: created.registrationId,
6093
+ writeToken: created.writeToken,
6094
+ eventsUrl,
6095
+ manifest: slackOrgManifest({ eventsUrl, redirectUrl: ctx.redirectUri })
6096
+ });
6097
+ }
6098
+ async function handleCredentials(ctx, registrationId) {
6099
+ if (!ctx.apps) {
6100
+ sendJson(ctx.res, 503, { ok: false, error: "Per-company Slack apps are off on this relay" });
6101
+ return;
6102
+ }
6103
+ const body = await readJson(ctx.req);
6104
+ const writeToken = stringField(body, "writeToken");
6105
+ const clientId = stringField(body, "clientId");
6106
+ const clientSecret = stringField(body, "clientSecret");
6107
+ const signingSecret = stringField(body, "signingSecret");
6108
+ try {
6109
+ ctx.apps.saveCredentials(registrationId, writeToken, { clientId, clientSecret, signingSecret });
6110
+ } catch (err) {
6111
+ const message = err instanceof Error ? err.message : String(err);
6112
+ sendJson(ctx.res, 400, { ok: false, error: message });
6113
+ return;
6114
+ }
6115
+ sendJson(ctx.res, 200, { ok: true });
6116
+ }
6117
+ async function handleEvents(ctx, registrationId) {
6118
+ if (!ctx.apps) {
6119
+ sendJson(ctx.res, 503, { ok: false, error: "Per-company Slack apps are off on this relay" });
6120
+ return;
6121
+ }
6122
+ const app = ctx.apps.getByRegistration(registrationId);
6123
+ if (!app) {
6124
+ sendJson(ctx.res, 404, { ok: false, error: "Unknown Slack app" });
6125
+ return;
6126
+ }
6127
+ const raw = await readBody(ctx.req);
6128
+ const body = parseSlackEventsBody(raw);
6129
+ if (!body) {
6130
+ sendJson(ctx.res, 400, { ok: false, error: "Invalid JSON" });
6131
+ return;
6132
+ }
6133
+ if (body.type === "url_verification") {
6134
+ if (app.signingSecret && !signed(ctx, app.signingSecret, raw)) {
6135
+ sendJson(ctx.res, 401, { ok: false, error: "Bad signature" });
6136
+ return;
6137
+ }
6138
+ const challenge = typeof body.challenge === "string" ? body.challenge : "";
6139
+ sendJson(ctx.res, 200, { challenge });
6140
+ return;
6141
+ }
6142
+ if (body.type !== "event_callback") {
6143
+ sendJson(ctx.res, 200, { ok: true });
6144
+ return;
6145
+ }
6146
+ if (!app.signingSecret || !signed(ctx, app.signingSecret, raw)) {
6147
+ sendJson(ctx.res, 401, { ok: false, error: "Bad signature" });
6148
+ return;
6149
+ }
6150
+ const teamId = typeof body.team_id === "string" ? body.team_id.trim() : "";
6151
+ if (app.teamId && teamId && teamId !== app.teamId) {
6152
+ sendJson(ctx.res, 401, { ok: false, error: "Slack team does not match this app" });
6153
+ return;
6154
+ }
6155
+ const eventId = typeof body.event_id === "string" ? body.event_id : "";
6156
+ if (ctx.dedupe.duplicate(eventId)) {
6157
+ sendJson(ctx.res, 200, { ok: true });
6158
+ return;
6159
+ }
6160
+ sendJson(ctx.res, 200, { ok: true });
6161
+ if (!app.teamId) {
6162
+ ctx.log(`slack event ${eventId || "?"} before install for ${registrationId}`);
6163
+ return;
6164
+ }
6165
+ const life = lifecycleFromEventsBody(body);
6166
+ if (life?.kind === "app_uninstalled") {
6167
+ ctx.apps.deleteByTeam(life.teamId);
6168
+ ctx.grants.revokeTeam(life.teamId);
6169
+ ctx.hub.uninstallTeam(life.teamId);
6170
+ return;
6171
+ }
6172
+ if (life?.kind === "app_home_opened") {
6173
+ void ctx.hub.handleAppHomeOpened(life.teamId, life.userId);
6174
+ return;
6175
+ }
6176
+ const inbound = inboundFromEventsBody(body);
6177
+ if (inbound) ctx.hub.routeEvent(inbound);
6178
+ }
6179
+ function signed(ctx, signingSecret, raw) {
6180
+ const timestamp = header(ctx.req, "x-slack-request-timestamp");
6181
+ const signature = header(ctx.req, "x-slack-signature");
6182
+ return verifySlackRequestSignature({ signingSecret, timestamp, rawBody: raw, signature });
6183
+ }
6184
+ async function handleCallback(ctx, url) {
6185
+ const error = url.searchParams.get("error")?.trim();
6186
+ const state = url.searchParams.get("state")?.trim() ?? "";
6187
+ const code = url.searchParams.get("code")?.trim() ?? "";
6188
+ if (error) {
6189
+ if (state) ctx.pending.put(state, { ok: false, error: `Slack OAuth: ${error}` });
6190
+ sendHtml(ctx.res, 400, "Slack", `<h1>Authorization cancelled</h1><p>${escapeHtml(error)}</p>`);
6191
+ return true;
6192
+ }
6193
+ if (!state || !code) {
6194
+ sendHtml(ctx.res, 400, "Slack", "<h1>Invalid callback</h1><p>State or code missing.</p>");
6195
+ return true;
6196
+ }
6197
+ try {
6198
+ const creds = resolveOAuthClient(ctx, state);
6199
+ const payload = await exchangeSlackOAuthCode({
6200
+ clientId: creds.clientId,
6201
+ clientSecret: creds.clientSecret,
6202
+ code,
6203
+ redirectUri: ctx.redirectUri,
6204
+ fetchImpl: ctx.fetchImpl
6205
+ });
6206
+ if (ctx.apps && payload.bot_token) {
6207
+ ctx.apps.recordInstall({
6208
+ clientId: creds.clientId,
6209
+ teamId: payload.team_id,
6210
+ botToken: payload.bot_token,
6211
+ botUserId: payload.bot_user_id ?? ""
6212
+ });
6213
+ }
6214
+ const listenGrant = payload.user_id ? ctx.grants.issue(payload.team_id, payload.user_id) : null;
6215
+ ctx.pending.put(state, {
6216
+ ok: true,
6217
+ payload: publicPayload({
6218
+ ...payload,
6219
+ ...listenGrant ? { listen_grant: listenGrant } : {}
6220
+ })
6221
+ });
6222
+ if (payload.bot_token) {
6223
+ ctx.hub.rememberBot(payload.team_id, payload.bot_token);
6224
+ if (payload.user_id) void ctx.hub.handleAppHomeOpened(payload.team_id, payload.user_id);
6225
+ }
6226
+ sendHtml(
6227
+ ctx.res,
6228
+ 200,
6229
+ "Slack connected",
6230
+ "<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>"
6231
+ );
6232
+ } catch (err) {
6233
+ const message = err instanceof Error ? err.message : String(err);
6234
+ ctx.pending.put(state, { ok: false, error: message });
6235
+ sendHtml(ctx.res, 400, "Slack", `<h1>Could not connect Slack</h1><p>${escapeHtml(message)}</p>`);
6236
+ }
6237
+ return true;
6238
+ }
6239
+ function resolveOAuthClient(ctx, state) {
6240
+ const fromState = clientIdFromOAuthState(state);
6241
+ if (!fromState) {
6242
+ if (!ctx.bakedClientSecret) throw new Error("Relay is missing SIDEBOARD_SLACK_CLIENT_SECRET");
6243
+ return { clientId: ctx.bakedClientId, clientSecret: ctx.bakedClientSecret };
6244
+ }
6245
+ const secret = ctx.apps?.clientSecretFor(fromState);
6246
+ if (!secret) throw new Error("This Slack app is not registered on the relay");
6247
+ return { clientId: fromState, clientSecret: secret };
6248
+ }
6249
+ function publicPayload(payload) {
6250
+ return {
6251
+ team_id: payload.team_id,
6252
+ team_name: payload.team_name,
6253
+ user_id: payload.user_id,
6254
+ bot_token: payload.bot_token,
6255
+ user_token: payload.user_token,
6256
+ listen_grant: payload.listen_grant,
6257
+ scopes: payload.scopes
6258
+ };
6259
+ }
6260
+ function handleResult(ctx, url) {
6261
+ const state = url.searchParams.get("state")?.trim() ?? "";
6262
+ const value = ctx.pending.take(state);
6263
+ if (!value) {
6264
+ sendJson(ctx.res, 404, { ok: false, error: "pending" });
6265
+ return true;
6266
+ }
6267
+ if (!value.ok) {
6268
+ sendJson(ctx.res, 400, { ok: false, error: value.error });
6269
+ return true;
6270
+ }
6271
+ sendJson(ctx.res, 200, { ok: true, ...value.payload });
6272
+ return true;
6273
+ }
6274
+ function bearer(req) {
6275
+ const value = header(req, "authorization");
6276
+ const match = /^Bearer\s+(\S+)/i.exec(value);
6277
+ return match?.[1]?.trim() ?? "";
6278
+ }
6279
+ function header(req, name) {
6280
+ const value = req.headers[name];
6281
+ return typeof value === "string" ? value.trim() : "";
6282
+ }
6283
+ function stringField(body, key) {
6284
+ const value = body?.[key];
6285
+ return typeof value === "string" ? value : "";
6286
+ }
6287
+ async function readJson(req) {
6288
+ const raw = await readBody(req);
6289
+ if (!raw) return null;
6290
+ try {
6291
+ const parsed = JSON.parse(raw);
6292
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
6293
+ return parsed;
6294
+ } catch {
6295
+ return null;
6296
+ }
6297
+ }
6298
+ function readBody(req) {
6299
+ return new Promise((resolve, reject) => {
6300
+ const chunks = [];
6301
+ let size = 0;
6302
+ req.on("data", (chunk) => {
6303
+ const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
6304
+ size += buf.length;
6305
+ if (size > BODY_LIMIT) {
6306
+ reject(new Error("body too large"));
6307
+ req.destroy();
6308
+ return;
6309
+ }
6310
+ chunks.push(buf);
5606
6311
  });
6312
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
6313
+ req.on("error", reject);
5607
6314
  });
5608
6315
  }
6316
+ function sendHtml(res, status, title, body) {
6317
+ res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
6318
+ res.end(slackOAuthHtmlPage(title, body));
6319
+ }
6320
+ function sendJson(res, status, body) {
6321
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
6322
+ res.end(JSON.stringify(body));
6323
+ }
6324
+
6325
+ // src/relay/slack-apps.ts
6326
+ import { createHash, randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "crypto";
6327
+ import { mkdirSync as mkdirSync2 } from "fs";
6328
+ import { createRequire } from "module";
6329
+ import { dirname, join as join4 } from "path";
6330
+ var SlackAppStore = class {
6331
+ db;
6332
+ key;
6333
+ constructor(filePath, key) {
6334
+ if (key.length !== 32) throw new Error("Slack token key must be 32 bytes");
6335
+ mkdirSync2(dirname(filePath), { recursive: true });
6336
+ this.key = key;
6337
+ this.db = openDatabase(filePath);
6338
+ this.db.exec(`
6339
+ CREATE TABLE IF NOT EXISTS slack_apps (
6340
+ registration_id TEXT PRIMARY KEY,
6341
+ account_id TEXT NOT NULL,
6342
+ write_token_hash TEXT NOT NULL,
6343
+ team_id TEXT,
6344
+ client_id TEXT,
6345
+ client_secret_enc TEXT,
6346
+ signing_secret_enc TEXT,
6347
+ bot_token_enc TEXT,
6348
+ bot_user_id TEXT,
6349
+ created_at INTEGER NOT NULL
6350
+ );
6351
+ CREATE UNIQUE INDEX IF NOT EXISTS slack_apps_client
6352
+ ON slack_apps(client_id) WHERE client_id IS NOT NULL;
6353
+ CREATE UNIQUE INDEX IF NOT EXISTS slack_apps_team
6354
+ ON slack_apps(team_id) WHERE team_id IS NOT NULL;
6355
+ `);
6356
+ }
6357
+ close() {
6358
+ this.db.close();
6359
+ }
6360
+ /** Mint a row. The write token is returned once and authorizes credential upload. */
6361
+ create(accountId) {
6362
+ const owner = accountId.trim();
6363
+ if (!owner) throw new Error("Slack app registration needs a Sideboard account");
6364
+ const registrationId = randomBytes4(16).toString("base64url");
6365
+ const writeToken = randomBytes4(32).toString("base64url");
6366
+ this.db.prepare(
6367
+ `INSERT INTO slack_apps (
6368
+ registration_id, account_id, write_token_hash, created_at
6369
+ ) VALUES (?, ?, ?, ?)`
6370
+ ).run(registrationId, owner, sha2562(writeToken), Date.now());
6371
+ return { registrationId, writeToken };
6372
+ }
6373
+ saveCredentials(registrationId, writeToken, creds) {
6374
+ const row2 = this.row(registrationId);
6375
+ if (!row2 || !sameHash(row2.write_token_hash, sha2562(writeToken.trim()))) {
6376
+ throw new Error("Slack app write token was rejected");
6377
+ }
6378
+ const clientId = creds.clientId.trim();
6379
+ const clientSecret = creds.clientSecret.trim();
6380
+ const signingSecret = creds.signingSecret.trim();
6381
+ if (!clientId || !clientSecret || !signingSecret) {
6382
+ throw new Error("Slack app credentials need a client id, client secret, and signing secret");
6383
+ }
6384
+ const taken = this.db.prepare(
6385
+ "SELECT registration_id FROM slack_apps WHERE client_id = ? AND registration_id != ?"
6386
+ ).get(clientId, row2.registration_id);
6387
+ if (taken) throw new Error("That Slack client id is already registered");
6388
+ this.db.prepare(
6389
+ `UPDATE slack_apps
6390
+ SET client_id = ?, client_secret_enc = ?, signing_secret_enc = ?
6391
+ WHERE registration_id = ?`
6392
+ ).run(clientId, sealSecret(this.key, clientSecret), sealSecret(this.key, signingSecret), row2.registration_id);
6393
+ }
6394
+ clientSecretFor(clientId) {
6395
+ const id = clientId.trim();
6396
+ if (!id) return null;
6397
+ const row2 = this.db.prepare("SELECT client_secret_enc FROM slack_apps WHERE client_id = ?").get(id);
6398
+ if (!row2?.client_secret_enc) return null;
6399
+ return openSecret(this.key, row2.client_secret_enc);
6400
+ }
6401
+ /**
6402
+ * OAuth finished for this client id. Rejects a different bot user than the
6403
+ * one already stored for the company.
6404
+ */
6405
+ recordInstall(input) {
6406
+ const clientId = input.clientId.trim();
6407
+ const teamId = input.teamId.trim();
6408
+ const botToken = input.botToken.trim();
6409
+ const botUserId = input.botUserId.trim();
6410
+ if (!clientId || !teamId || !botToken) return false;
6411
+ const row2 = this.db.prepare("SELECT registration_id, team_id, bot_user_id FROM slack_apps WHERE client_id = ?").get(clientId);
6412
+ if (!row2) return false;
6413
+ if (row2.team_id && row2.team_id !== teamId) {
6414
+ throw new Error("This Slack app is already installed on another workspace");
6415
+ }
6416
+ if (botUserId && row2.bot_user_id && row2.bot_user_id !== botUserId) {
6417
+ throw new Error("This Slack app\u2019s bot user does not match the stored install");
6418
+ }
6419
+ this.db.prepare(
6420
+ `UPDATE slack_apps
6421
+ SET team_id = ?, bot_token_enc = ?, bot_user_id = COALESCE(?, bot_user_id)
6422
+ WHERE registration_id = ?`
6423
+ ).run(teamId, sealSecret(this.key, botToken), botUserId || null, row2.registration_id);
6424
+ return true;
6425
+ }
6426
+ /** Error string when a desktop presents a different bot than the company app. */
6427
+ botUserMismatch(teamId, botUserId) {
6428
+ const row2 = this.teamRow(teamId);
6429
+ if (!row2?.bot_user_id) return null;
6430
+ if (row2.bot_user_id === botUserId.trim()) return null;
6431
+ return "This Mac\u2019s bot token is not the company\u2019s Sideboard Slack app";
6432
+ }
6433
+ /** Refresh the stored bot token after a desktop register for this team. */
6434
+ saveBot(teamId, botToken, botUserId) {
6435
+ const row2 = this.teamRow(teamId);
6436
+ const token = botToken.trim();
6437
+ const user = botUserId.trim();
6438
+ if (!row2 || !token || !user) return;
6439
+ if (row2.bot_user_id && row2.bot_user_id !== user) return;
6440
+ 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);
6441
+ }
6442
+ getByRegistration(registrationId) {
6443
+ const row2 = this.row(registrationId);
6444
+ if (!row2) return null;
6445
+ return {
6446
+ registrationId: row2.registration_id,
6447
+ teamId: row2.team_id,
6448
+ signingSecret: row2.signing_secret_enc ? openSecret(this.key, row2.signing_secret_enc) : null
6449
+ };
6450
+ }
6451
+ listBots() {
6452
+ const rows = this.db.prepare(
6453
+ `SELECT team_id, bot_token_enc FROM slack_apps
6454
+ WHERE team_id IS NOT NULL AND bot_token_enc IS NOT NULL`
6455
+ ).all();
6456
+ return rows.map((row2) => ({
6457
+ teamId: row2.team_id,
6458
+ botToken: openSecret(this.key, row2.bot_token_enc)
6459
+ }));
6460
+ }
6461
+ deleteByTeam(teamId) {
6462
+ const id = teamId.trim();
6463
+ if (!id) return;
6464
+ this.db.prepare("DELETE FROM slack_apps WHERE team_id = ?").run(id);
6465
+ }
6466
+ row(registrationId) {
6467
+ const id = registrationId.trim();
6468
+ if (!id) return null;
6469
+ return this.db.prepare("SELECT * FROM slack_apps WHERE registration_id = ?").get(id) ?? null;
6470
+ }
6471
+ teamRow(teamId) {
6472
+ const id = teamId.trim();
6473
+ if (!id) return null;
6474
+ return this.db.prepare("SELECT * FROM slack_apps WHERE team_id = ?").get(id) ?? null;
6475
+ }
6476
+ };
6477
+ function sha2562(value) {
6478
+ return createHash("sha256").update(value).digest("hex");
6479
+ }
6480
+ function sameHash(stored, presented) {
6481
+ const left = Buffer.from(stored);
6482
+ const right = Buffer.from(presented);
6483
+ return left.length === right.length && timingSafeEqual2(left, right);
6484
+ }
6485
+ function thisModuleFile() {
6486
+ const cjsFile = typeof __filename !== "undefined" ? __filename : "";
6487
+ return cjsFile || process.argv[1] || join4(process.cwd(), "package.json");
6488
+ }
6489
+ function openDatabase(filePath) {
6490
+ const req = createRequire(thisModuleFile());
6491
+ const { DatabaseSync: SqliteDatabase } = req("node:sqlite");
6492
+ const db = new SqliteDatabase(filePath);
6493
+ db.exec("PRAGMA journal_mode = WAL");
6494
+ return db;
6495
+ }
6496
+
6497
+ // src/relay/slack-grants.ts
6498
+ import { randomBytes as randomBytes6 } from "crypto";
6499
+ import { mkdirSync as mkdirSync3 } from "fs";
6500
+ import { createRequire as createRequire2 } from "module";
6501
+ import { dirname as dirname2, join as join5 } from "path";
6502
+
6503
+ // src/slack/listen-grant.ts
6504
+ import { createHash as createHash2, randomBytes as randomBytes5 } from "crypto";
6505
+ var MemorySlackListenGrants = class {
6506
+ rows = /* @__PURE__ */ new Map();
6507
+ issue(teamId, userId) {
6508
+ const team = teamId.trim();
6509
+ const user = userId.trim();
6510
+ if (!team || !user) return null;
6511
+ const grant = randomBytes5(32).toString("base64url");
6512
+ this.rows.set(hashListenGrant(grant), { teamId: team, userId: user });
6513
+ return grant;
6514
+ }
6515
+ verify(teamId, userId, grant) {
6516
+ const token = grant.trim();
6517
+ if (!token) return false;
6518
+ const row2 = this.rows.get(hashListenGrant(token));
6519
+ if (!row2) return false;
6520
+ return row2.teamId === teamId.trim() && row2.userId === userId.trim();
6521
+ }
6522
+ revokeTeam(teamId) {
6523
+ const team = teamId.trim();
6524
+ if (!team) return;
6525
+ for (const [hash, row2] of this.rows) {
6526
+ if (row2.teamId === team) this.rows.delete(hash);
6527
+ }
6528
+ }
6529
+ close() {
6530
+ this.rows.clear();
6531
+ }
6532
+ };
6533
+ function hashListenGrant(grant) {
6534
+ return createHash2("sha256").update(grant.trim()).digest("hex");
6535
+ }
6536
+
6537
+ // src/relay/slack-grants.ts
6538
+ var SlackListenGrantStore = class {
6539
+ db;
6540
+ constructor(filePath) {
6541
+ mkdirSync3(dirname2(filePath), { recursive: true });
6542
+ this.db = openDatabase2(filePath);
6543
+ this.db.exec(`
6544
+ CREATE TABLE IF NOT EXISTS slack_listen_grants (
6545
+ grant_hash TEXT PRIMARY KEY,
6546
+ team_id TEXT NOT NULL,
6547
+ user_id TEXT NOT NULL,
6548
+ created_at INTEGER NOT NULL
6549
+ );
6550
+ CREATE INDEX IF NOT EXISTS slack_listen_grants_team
6551
+ ON slack_listen_grants(team_id);
6552
+ `);
6553
+ }
6554
+ close() {
6555
+ this.db.close();
6556
+ }
6557
+ issue(teamId, userId) {
6558
+ const team = teamId.trim();
6559
+ const user = userId.trim();
6560
+ if (!team || !user) return null;
6561
+ const grant = randomBytes6(32).toString("base64url");
6562
+ this.db.prepare(
6563
+ `INSERT INTO slack_listen_grants (grant_hash, team_id, user_id, created_at)
6564
+ VALUES (?, ?, ?, ?)`
6565
+ ).run(hashListenGrant(grant), team, user, Date.now());
6566
+ return grant;
6567
+ }
6568
+ verify(teamId, userId, grant) {
6569
+ const token = grant.trim();
6570
+ const team = teamId.trim();
6571
+ const user = userId.trim();
6572
+ if (!token || !team || !user) return false;
6573
+ const row2 = this.db.prepare("SELECT team_id, user_id FROM slack_listen_grants WHERE grant_hash = ?").get(hashListenGrant(token));
6574
+ return row2?.team_id === team && row2.user_id === user;
6575
+ }
6576
+ revokeTeam(teamId) {
6577
+ const team = teamId.trim();
6578
+ if (!team) return;
6579
+ this.db.prepare("DELETE FROM slack_listen_grants WHERE team_id = ?").run(team);
6580
+ }
6581
+ };
6582
+ function thisModuleFile2() {
6583
+ const cjsFile = typeof __filename !== "undefined" ? __filename : "";
6584
+ return cjsFile || process.argv[1] || join5(process.cwd(), "package.json");
6585
+ }
6586
+ function openDatabase2(filePath) {
6587
+ const req = createRequire2(thisModuleFile2());
6588
+ const { DatabaseSync: SqliteDatabase } = req("node:sqlite");
6589
+ const db = new SqliteDatabase(filePath);
6590
+ db.exec("PRAGMA journal_mode = WAL");
6591
+ return db;
6592
+ }
5609
6593
 
5610
6594
  // src/slack/relay-protocol.ts
5611
- import { randomBytes as randomBytes2 } from "crypto";
6595
+ import { randomBytes as randomBytes7 } from "crypto";
5612
6596
  var SLACK_RELAY_PING_INTERVAL_MS = 2e4;
5613
6597
  var SLACK_RELAY_PONG_TIMEOUT_MS = 15e3;
5614
6598
  function slackRelaySessionKey(teamId, userId, deviceId) {
@@ -5618,7 +6602,7 @@ function slackRelayUserKey(teamId, userId) {
5618
6602
  return `${teamId.trim()}:${userId.trim()}`;
5619
6603
  }
5620
6604
  function newSlackRelayEventId() {
5621
- return randomBytes2(12).toString("hex");
6605
+ return randomBytes7(12).toString("hex");
5622
6606
  }
5623
6607
  function parseSlackRelayClientMessage(raw) {
5624
6608
  try {
@@ -5637,7 +6621,8 @@ function parseSlackRelayClientMessage(raw) {
5637
6621
  const deviceLabel = typeof parsed.deviceLabel === "string" ? parsed.deviceLabel.trim() : void 0;
5638
6622
  const botToken = typeof parsed.botToken === "string" ? parsed.botToken.trim() : "";
5639
6623
  const userToken = typeof parsed.userToken === "string" ? parsed.userToken.trim() : "";
5640
- if (!teamId || !userId || !deviceId || !botToken || !userToken) return null;
6624
+ const listenGrant = typeof parsed.listenGrant === "string" ? parsed.listenGrant.trim() : "";
6625
+ if (!teamId || !userId || !deviceId || !botToken || !userToken && !listenGrant) return null;
5641
6626
  return {
5642
6627
  type: "register",
5643
6628
  teamId,
@@ -5645,7 +6630,8 @@ function parseSlackRelayClientMessage(raw) {
5645
6630
  deviceId,
5646
6631
  deviceLabel: deviceLabel || void 0,
5647
6632
  botToken,
5648
- userToken
6633
+ ...userToken ? { userToken } : {},
6634
+ ...listenGrant ? { listenGrant } : {}
5649
6635
  };
5650
6636
  }
5651
6637
  return null;
@@ -5696,10 +6682,10 @@ function parseSlackRelayServerMessage(raw) {
5696
6682
 
5697
6683
  // src/slack/app-home.ts
5698
6684
  var SLACK_APP_HOME_DOWNLOAD = "https://sideboard-downloads.t3.tigrisfiles.io/Sideboard-latest-arm64.dmg";
5699
- var SLACK_APP_HOME_LANDING = "https://www.sideboard.cloud/slack/";
5700
- var SLACK_APP_HOME_PRIVACY = "https://www.sideboard.cloud/privacy/";
5701
- var SLACK_APP_HOME_SUPPORT = "https://www.sideboard.cloud/support/";
5702
- var SLACK_APP_HOME_SUPPORT_EMAIL = "support@sideboard.cloud";
6685
+ var SLACK_APP_HOME_LANDING = "https://www.sideboard.build/slack/";
6686
+ var SLACK_APP_HOME_PRIVACY = "https://www.sideboard.build/privacy/";
6687
+ var SLACK_APP_HOME_SUPPORT = "https://www.sideboard.build/support/";
6688
+ var SLACK_APP_HOME_SUPPORT_EMAIL = "support@sideboard.build";
5703
6689
  var SLACK_NO_MAC_ONLINE_REPLY = [
5704
6690
  "No Sideboard Mac is online for your Slack user.",
5705
6691
  "Open Sideboard \u2192 Settings \u2192 Remote and wait for Relay connected.",
@@ -5717,7 +6703,7 @@ function slackAppHomeView(opts) {
5717
6703
  "",
5718
6704
  "*First run*",
5719
6705
  "1. Download Sideboard for Apple Silicon and keep it open.",
5720
- "2. Settings \u2192 Remote \u2192 Slack \u2192 Add via browser. Name this Mac (`Work`, `Personal`, \u2026).",
6706
+ "2. Settings \u2192 Collaboration \u2192 Add via browser. Name this Mac on Settings \u2192 Remote (`Work`, `Personal`, \u2026).",
5721
6707
  "3. Wait until status shows Relay connected, then DM @Sideboard."
5722
6708
  ].join("\n");
5723
6709
  return {
@@ -5791,11 +6777,26 @@ var SlackRelayHub = class {
5791
6777
  fetchImpl;
5792
6778
  authTest;
5793
6779
  log;
6780
+ guardBotUser = null;
6781
+ onBotAccepted = null;
6782
+ verifyListenGrant = null;
5794
6783
  constructor(opts = {}) {
5795
6784
  this.fetchImpl = opts.fetchImpl;
5796
6785
  this.log = opts.onLog ?? (() => void 0);
5797
6786
  this.authTest = opts.authTest ?? (async (token) => slackApi(token, "auth.test", void 0, this.fetchImpl));
5798
6787
  }
6788
+ /**
6789
+ * Company apps reject a bot user that is not the one stored for that team,
6790
+ * then persist a matching bot token. The baked app leaves both unset.
6791
+ */
6792
+ setBotHooks(hooks) {
6793
+ this.guardBotUser = hooks.guardBotUser ?? null;
6794
+ this.onBotAccepted = hooks.onBotAccepted ?? null;
6795
+ }
6796
+ /** Accept a relay listen grant in place of a Slack user token. */
6797
+ setListenGrantVerifier(verify2) {
6798
+ this.verifyListenGrant = verify2;
6799
+ }
5799
6800
  sessionFor(teamId, userId, deviceId) {
5800
6801
  return this.sessions.get(slackRelaySessionKey(teamId, userId, deviceId)) ?? null;
5801
6802
  }
@@ -5834,43 +6835,61 @@ var SlackRelayHub = class {
5834
6835
  msg.deviceId,
5835
6836
  msg.deviceLabel,
5836
6837
  msg.botToken,
5837
- msg.userToken
6838
+ msg.userToken ?? "",
6839
+ msg.listenGrant
5838
6840
  );
5839
6841
  }
5840
6842
  }
5841
- async register(socket, teamId, userId, deviceId, deviceLabel, botToken, userToken) {
6843
+ async register(socket, teamId, userId, deviceId, deviceLabel, botToken, userToken, listenGrant) {
5842
6844
  const claimedTeam = teamId.trim();
5843
6845
  const claimedUser = userId.trim();
5844
6846
  const claimedDevice = deviceId.trim();
5845
6847
  const label = (deviceLabel?.trim() || claimedDevice).slice(0, 64);
5846
6848
  const bot = botToken.trim();
5847
6849
  const user = userToken.trim();
5848
- if (!claimedTeam || !claimedUser || !claimedDevice || !bot || !user) {
6850
+ const grant = listenGrant?.trim() ?? "";
6851
+ let botUserId = "";
6852
+ if (!claimedTeam || !claimedUser || !claimedDevice || !bot || !user && !grant) {
5849
6853
  this.send(socket, {
5850
6854
  type: "error",
5851
- message: "register needs teamId, userId, deviceId, botToken, and userToken"
6855
+ message: "register needs teamId, userId, deviceId, botToken, and a user token or listen grant"
5852
6856
  });
5853
6857
  return;
5854
6858
  }
5855
6859
  try {
5856
- const userAuth = await this.authTest(user);
5857
- const userTeam = userAuth.team_id?.trim();
5858
- const userAuthId = userAuth.user_id?.trim();
5859
- if (!userTeam || !userAuthId) {
5860
- this.send(socket, {
5861
- type: "error",
5862
- message: "user token auth.test did not return team_id/user_id"
5863
- });
5864
- return;
6860
+ let proved = false;
6861
+ if (user) {
6862
+ try {
6863
+ const userAuth = await this.authTest(user);
6864
+ const userTeam = userAuth.team_id?.trim();
6865
+ const userAuthId = userAuth.user_id?.trim();
6866
+ if (!userTeam || !userAuthId) {
6867
+ if (!grant) {
6868
+ this.send(socket, {
6869
+ type: "error",
6870
+ message: "user token auth.test did not return team_id/user_id"
6871
+ });
6872
+ return;
6873
+ }
6874
+ } else if (userTeam !== claimedTeam || userAuthId !== claimedUser) {
6875
+ this.send(socket, {
6876
+ type: "error",
6877
+ message: `User token identity ${userTeam}/${userAuthId} does not match claimed ${claimedTeam}/${claimedUser}`
6878
+ });
6879
+ this.log(
6880
+ `register rejected: claimed ${claimedTeam}/${claimedUser} user-token ${userTeam}/${userAuthId}`
6881
+ );
6882
+ return;
6883
+ } else {
6884
+ proved = true;
6885
+ }
6886
+ } catch (err) {
6887
+ if (!grant) throw err;
6888
+ }
5865
6889
  }
5866
- if (userTeam !== claimedTeam || userAuthId !== claimedUser) {
5867
- this.send(socket, {
5868
- type: "error",
5869
- message: `User token identity ${userTeam}/${userAuthId} does not match claimed ${claimedTeam}/${claimedUser}`
5870
- });
5871
- this.log(
5872
- `register rejected: claimed ${claimedTeam}/${claimedUser} user-token ${userTeam}/${userAuthId}`
5873
- );
6890
+ if (!proved && !this.verifyListenGrant?.(claimedTeam, claimedUser, grant)) {
6891
+ this.send(socket, { type: "error", message: "listen grant was rejected" });
6892
+ this.log(`register rejected: ${claimedTeam}/${claimedUser} listen grant`);
5874
6893
  return;
5875
6894
  }
5876
6895
  const botAuth = await this.authTest(bot);
@@ -5890,6 +6909,22 @@ var SlackRelayHub = class {
5890
6909
  this.log(`register rejected: claimed team ${claimedTeam} bot ${botTeam}`);
5891
6910
  return;
5892
6911
  }
6912
+ botUserId = botAuth.user_id?.trim() ?? "";
6913
+ if (this.guardBotUser) {
6914
+ if (!botUserId) {
6915
+ this.send(socket, {
6916
+ type: "error",
6917
+ message: "bot token auth.test did not return user_id"
6918
+ });
6919
+ return;
6920
+ }
6921
+ const guard = this.guardBotUser(claimedTeam, botUserId);
6922
+ if (guard) {
6923
+ this.send(socket, { type: "error", message: guard });
6924
+ this.log(`register rejected: ${claimedTeam} bot user ${botUserId}`);
6925
+ return;
6926
+ }
6927
+ }
5893
6928
  } catch (err) {
5894
6929
  const errMsg = err instanceof Error ? err.message : String(err);
5895
6930
  this.send(socket, { type: "error", message: `auth.test failed: ${errMsg}` });
@@ -5917,6 +6952,7 @@ var SlackRelayHub = class {
5917
6952
  this.sessions.set(key, session);
5918
6953
  this.bySocket.set(socket, key);
5919
6954
  this.rememberBot(claimedTeam, bot);
6955
+ if (botUserId) this.onBotAccepted?.(claimedTeam, bot, botUserId);
5920
6956
  this.send(socket, {
5921
6957
  type: "registered",
5922
6958
  teamId: claimedTeam,
@@ -6086,6 +7122,7 @@ var TYPES = {
6086
7122
  ".svg": "image/svg+xml",
6087
7123
  ".txt": "text/plain; charset=utf-8",
6088
7124
  ".webp": "image/webp",
7125
+ ".xml": "application/xml; charset=utf-8",
6089
7126
  ".woff2": "font/woff2"
6090
7127
  };
6091
7128
  function requestHostname(req) {
@@ -6096,6 +7133,45 @@ function hostnameAllowed(host, allowed) {
6096
7133
  if (!allowed || allowed.length === 0) return true;
6097
7134
  return allowed.includes(host);
6098
7135
  }
7136
+ var CANONICAL_SITE_HOST = "www.sideboard.build";
7137
+ function isOAuthSitePath(pathname) {
7138
+ return pathname === "/oauth" || pathname.startsWith("/oauth/");
7139
+ }
7140
+ function marketingRedirectLocation(opts) {
7141
+ let pathname = "/";
7142
+ let search = "";
7143
+ try {
7144
+ const url = new URL(opts.requestUrl, "http://relay.local");
7145
+ pathname = url.pathname;
7146
+ search = url.search;
7147
+ } catch {
7148
+ return null;
7149
+ }
7150
+ const hostname2 = opts.hostname.toLowerCase();
7151
+ const canonical = opts.canonicalHost.toLowerCase();
7152
+ const staticHosts = opts.staticHosts ?? [];
7153
+ const listedSite = staticHosts.length > 0 && staticHosts.includes(hostname2);
7154
+ const listedRedirect = (opts.redirectHosts ?? []).includes(hostname2);
7155
+ const alias = hostname2 !== canonical && (listedSite || listedRedirect);
7156
+ if (alias && !isOAuthSitePath(pathname)) {
7157
+ return `https://${canonical}${pathname}${search}`;
7158
+ }
7159
+ return null;
7160
+ }
7161
+ async function directorySlashLocation(root, requestUrl) {
7162
+ let url;
7163
+ try {
7164
+ url = new URL(requestUrl, "http://relay.local");
7165
+ } catch {
7166
+ return null;
7167
+ }
7168
+ if (isOAuthSitePath(url.pathname) || url.pathname.endsWith("/")) return null;
7169
+ const candidate = resolveStaticPath(root, requestUrl);
7170
+ if (!candidate) return null;
7171
+ if (await fileSize(candidate) != null) return null;
7172
+ if (await fileSize(path.join(candidate, "index.html")) == null) return null;
7173
+ return `${url.pathname}/${url.search}`;
7174
+ }
6099
7175
  function resolveStaticPath(root, requestUrl) {
6100
7176
  let pathname;
6101
7177
  try {
@@ -6133,6 +7209,35 @@ function sendFile(req, res, file, size) {
6133
7209
  createReadStream(file).pipe(res);
6134
7210
  return true;
6135
7211
  }
7212
+ async function serveMarketingSite(req, res, opts) {
7213
+ const reqUrl = req.url || "/";
7214
+ const hostname2 = requestHostname(req);
7215
+ const canonical = opts.canonicalHost.toLowerCase();
7216
+ if (req.method === "GET" || req.method === "HEAD") {
7217
+ const location = marketingRedirectLocation({
7218
+ requestUrl: reqUrl,
7219
+ hostname: hostname2,
7220
+ canonicalHost: canonical,
7221
+ staticHosts: opts.staticHosts,
7222
+ redirectHosts: opts.redirectHosts
7223
+ });
7224
+ if (location) {
7225
+ res.writeHead(301, { Location: location });
7226
+ res.end();
7227
+ return true;
7228
+ }
7229
+ if (hostnameAllowed(hostname2, opts.staticHosts)) {
7230
+ const slash = await directorySlashLocation(opts.root, reqUrl);
7231
+ if (slash) {
7232
+ res.writeHead(301, { Location: slash });
7233
+ res.end();
7234
+ return true;
7235
+ }
7236
+ }
7237
+ }
7238
+ if (!hostnameAllowed(hostname2, opts.staticHosts)) return false;
7239
+ return tryServeStatic(req, res, opts.root);
7240
+ }
6136
7241
  async function tryServeStatic(req, res, root) {
6137
7242
  if (req.method !== "GET" && req.method !== "HEAD") return false;
6138
7243
  const candidate = resolveStaticPath(root, req.url || "/");
@@ -6146,7 +7251,7 @@ async function tryServeStatic(req, res, root) {
6146
7251
  }
6147
7252
 
6148
7253
  // src/remote/hub.ts
6149
- import { randomBytes as randomBytes3 } from "crypto";
7254
+ import { randomBytes as randomBytes8 } from "crypto";
6150
7255
  var CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
6151
7256
  var CODE_TTL_MS = 10 * 60 * 1e3;
6152
7257
  function send(socket, msg) {
@@ -6156,7 +7261,7 @@ function send(socket, msg) {
6156
7261
  }
6157
7262
  }
6158
7263
  function newCode() {
6159
- const bytes = randomBytes3(6);
7264
+ const bytes = randomBytes8(6);
6160
7265
  let code = "";
6161
7266
  for (let i = 0; i < 6; i++) code += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
6162
7267
  return code;
@@ -6427,7 +7532,7 @@ var RemoteHub = class {
6427
7532
  host.phone = null;
6428
7533
  }
6429
7534
  const created = sessionToken == null;
6430
- const token = sessionToken ?? randomBytes3(24).toString("hex");
7535
+ const token = sessionToken ?? randomBytes8(24).toString("hex");
6431
7536
  if (host.sessionToken && host.sessionToken !== token) {
6432
7537
  this.phonesByToken.delete(host.sessionToken);
6433
7538
  }
@@ -6477,32 +7582,32 @@ var RemoteHub = class {
6477
7582
  };
6478
7583
 
6479
7584
  // src/relay/accounts.ts
6480
- import { createHash, randomBytes as randomBytes4, randomUUID as randomUUID3, timingSafeEqual } from "crypto";
6481
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync } from "fs";
6482
- import { createRequire } from "module";
6483
- import { dirname, join as join3 } from "path";
7585
+ import { createHash as createHash3, randomBytes as randomBytes9, randomUUID as randomUUID3, timingSafeEqual as timingSafeEqual3 } from "crypto";
7586
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync3, realpathSync } from "fs";
7587
+ import { createRequire as createRequire3 } from "module";
7588
+ import { dirname as dirname3, join as join6 } from "path";
6484
7589
  var GITHUB_ACCOUNT_ISSUER = "https://github.com";
6485
7590
  var CURSOR_ACCOUNT_ISSUER = "https://api.cursor.com/v1/origin";
6486
7591
  var RELAY_DEVICE_CAP = 3;
6487
- function thisModuleFile() {
7592
+ function thisModuleFile3() {
6488
7593
  const cjsFile = typeof __filename !== "undefined" ? __filename : "";
6489
- return cjsFile || process.argv[1] || join3(process.cwd(), "package.json");
7594
+ return cjsFile || process.argv[1] || join6(process.cwd(), "package.json");
6490
7595
  }
6491
- function openDatabase(filePath) {
6492
- const req = createRequire(thisModuleFile());
7596
+ function openDatabase3(filePath) {
7597
+ const req = createRequire3(thisModuleFile3());
6493
7598
  const specifier = "node:sqlite";
6494
7599
  const { DatabaseSync: SqliteDatabase } = req(specifier);
6495
7600
  const db = new SqliteDatabase(filePath);
6496
7601
  db.exec("PRAGMA journal_mode = WAL");
6497
7602
  return db;
6498
7603
  }
6499
- function sha2562(value) {
6500
- return createHash("sha256").update(value).digest("hex");
7604
+ function sha2563(value) {
7605
+ return createHash3("sha256").update(value).digest("hex");
6501
7606
  }
6502
- function sameHash(a, b) {
7607
+ function sameHash2(a, b) {
6503
7608
  const left = Buffer.from(a);
6504
7609
  const right = Buffer.from(b);
6505
- return left.length === right.length && timingSafeEqual(left, right);
7610
+ return left.length === right.length && timingSafeEqual3(left, right);
6506
7611
  }
6507
7612
  function normalizeEmail(email) {
6508
7613
  const trimmed = email?.trim().toLowerCase() ?? "";
@@ -6523,7 +7628,7 @@ function assertRelayAccountsDurable(filePath) {
6523
7628
  if (process.env.SIDEBOARD_RELAY_ACCOUNTS_EPHEMERAL === "1") return;
6524
7629
  if (process.env.NODE_ENV !== "production") return;
6525
7630
  if (process.platform !== "linux") return;
6526
- const dir = realpathSync(dirname(filePath));
7631
+ const dir = realpathSync(dirname3(filePath));
6527
7632
  const mounts = readFileSync3("/proc/mounts", "utf8");
6528
7633
  const point = longestMountPoint(dir, mounts);
6529
7634
  if (point === "/") {
@@ -6535,8 +7640,8 @@ function assertRelayAccountsDurable(filePath) {
6535
7640
  var RelayAccountStore = class {
6536
7641
  db;
6537
7642
  constructor(filePath) {
6538
- mkdirSync2(dirname(filePath), { recursive: true });
6539
- this.db = openDatabase(filePath);
7643
+ mkdirSync4(dirname3(filePath), { recursive: true });
7644
+ this.db = openDatabase3(filePath);
6540
7645
  this.db.exec(`
6541
7646
  CREATE TABLE IF NOT EXISTS accounts (
6542
7647
  id TEXT PRIMARY KEY,
@@ -6625,14 +7730,14 @@ var RelayAccountStore = class {
6625
7730
  verifyCredential(token) {
6626
7731
  const trimmed = token.trim();
6627
7732
  if (!trimmed) return null;
6628
- const row2 = this.db.prepare("SELECT account_id FROM credentials WHERE token_hash = ?").get(sha2562(trimmed));
7733
+ const row2 = this.db.prepare("SELECT account_id FROM credentials WHERE token_hash = ?").get(sha2563(trimmed));
6629
7734
  return row2?.account_id ?? null;
6630
7735
  }
6631
7736
  /** Drop one Mac credential. The account and its other Macs stay. */
6632
7737
  logout(token) {
6633
7738
  const trimmed = token.trim();
6634
7739
  if (!trimmed) return;
6635
- this.db.prepare("DELETE FROM credentials WHERE token_hash = ?").run(sha2562(trimmed));
7740
+ this.db.prepare("DELETE FROM credentials WHERE token_hash = ?").run(sha2563(trimmed));
6636
7741
  }
6637
7742
  /** Delete the account and every identity, credential, and Mac bound to it. */
6638
7743
  revokeAccount(accountId) {
@@ -6670,7 +7775,7 @@ var RelayAccountStore = class {
6670
7775
  return { ok: false, message: "sign in required" };
6671
7776
  }
6672
7777
  const device = this.db.prepare("SELECT device_id, account_id, host_secret_hash FROM devices WHERE device_id = ?").get(deviceId);
6673
- const secretHash = sha2562(hostSecret);
7778
+ const secretHash = sha2563(hostSecret);
6674
7779
  if (!device) {
6675
7780
  const count = this.db.prepare("SELECT COUNT(*) AS n FROM devices WHERE account_id = ?").get(accountId);
6676
7781
  if (count.n >= account.device_cap) {
@@ -6687,7 +7792,7 @@ var RelayAccountStore = class {
6687
7792
  this.db.exec("ROLLBACK");
6688
7793
  return { ok: false, message: "This Mac is registered to another account." };
6689
7794
  }
6690
- if (!sameHash(device.host_secret_hash, secretHash)) {
7795
+ if (!sameHash2(device.host_secret_hash, secretHash)) {
6691
7796
  this.db.exec("ROLLBACK");
6692
7797
  return { ok: false, message: "host secret rejected" };
6693
7798
  }
@@ -6704,12 +7809,12 @@ var RelayAccountStore = class {
6704
7809
  const id = deviceId.trim();
6705
7810
  const token = sessionToken.trim();
6706
7811
  if (!id || !token) return;
6707
- this.db.prepare("UPDATE devices SET session_token_hash = ? WHERE device_id = ?").run(sha2562(token), id);
7812
+ this.db.prepare("UPDATE devices SET session_token_hash = ? WHERE device_id = ?").run(sha2563(token), id);
6708
7813
  }
6709
7814
  findPhoneSession(sessionToken) {
6710
7815
  const token = sessionToken.trim();
6711
7816
  if (!token) return null;
6712
- const row2 = this.db.prepare("SELECT device_id, device_label FROM devices WHERE session_token_hash = ?").get(sha2562(token));
7817
+ const row2 = this.db.prepare("SELECT device_id, device_label FROM devices WHERE session_token_hash = ?").get(sha2563(token));
6713
7818
  if (!row2) return null;
6714
7819
  return { deviceId: row2.device_id, deviceLabel: row2.device_label };
6715
7820
  }
@@ -6729,8 +7834,8 @@ var RelayAccountStore = class {
6729
7834
  ).run(issuer, subject, accountId, email, verified ? 1 : 0);
6730
7835
  }
6731
7836
  mintCredential(accountId) {
6732
- const credential = randomBytes4(32).toString("hex");
6733
- this.db.prepare("INSERT INTO credentials (token_hash, account_id, created_at) VALUES (?, ?, ?)").run(sha2562(credential), accountId, Date.now());
7837
+ const credential = randomBytes9(32).toString("hex");
7838
+ this.db.prepare("INSERT INTO credentials (token_hash, account_id, created_at) VALUES (?, ?, ?)").run(sha2563(credential), accountId, Date.now());
6734
7839
  return credential;
6735
7840
  }
6736
7841
  };
@@ -6768,8 +7873,8 @@ async function cursorIdentityFromReceipt(receipt, expected, fetchImpl, nowMs = D
6768
7873
  throw new Error("Cursor sign-in receipt was not a signed token.");
6769
7874
  }
6770
7875
  const [hSeg, pSeg, sSeg] = parts;
6771
- const header = b64urlJson(hSeg);
6772
- if (header.alg !== "EdDSA" || header.typ !== RECEIPT_TYP || typeof header.kid !== "string") {
7876
+ const header2 = b64urlJson(hSeg);
7877
+ if (header2.alg !== "EdDSA" || header2.typ !== RECEIPT_TYP || typeof header2.kid !== "string") {
6773
7878
  throw new Error("Cursor sign-in receipt was not a user confirmation.");
6774
7879
  }
6775
7880
  const payload = b64urlJson(pSeg);
@@ -6787,7 +7892,7 @@ async function cursorIdentityFromReceipt(receipt, expected, fetchImpl, nowMs = D
6787
7892
  const jwksRes = await fetchImpl(JWKS_URL);
6788
7893
  const body = await jwksRes.json();
6789
7894
  const jwk = (body.keys ?? []).find(
6790
- (key2) => key2.kid === header.kid && key2.kty === "OKP" && key2.crv === "Ed25519" && key2.x
7895
+ (key2) => key2.kid === header2.kid && key2.kty === "OKP" && key2.crv === "Ed25519" && key2.x
6791
7896
  );
6792
7897
  if (!jwk?.x) throw new Error("Cursor did not publish the key that signed this receipt.");
6793
7898
  const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: jwk.x }, format: "jwk" });
@@ -6817,7 +7922,7 @@ function cursorGitHostEntry() {
6817
7922
  }
6818
7923
 
6819
7924
  // src/relay/account-entire.ts
6820
- import { createHash as createHash2, randomBytes as randomBytes5 } from "crypto";
7925
+ import { createHash as createHash4, randomBytes as randomBytes10 } from "crypto";
6821
7926
  var ENTIRE_AUTHORIZE_ORIGIN = "https://auth.entire.io";
6822
7927
  var ENTIRE_DEFAULT_ISSUER = "https://us.auth.entire.io";
6823
7928
  var ISSUER_SUFFIX = ".auth.entire.io";
@@ -6840,10 +7945,10 @@ function entireAccountIssuer(value) {
6840
7945
  return `https://${host}`;
6841
7946
  }
6842
7947
  function newEntireCodeVerifier() {
6843
- return randomBytes5(32).toString("base64url");
7948
+ return randomBytes10(32).toString("base64url");
6844
7949
  }
6845
7950
  function entireCodeChallenge(verifier) {
6846
- return createHash2("sha256").update(verifier).digest("base64url");
7951
+ return createHash4("sha256").update(verifier).digest("base64url");
6847
7952
  }
6848
7953
  function entireAuthorizeUrl(clientId, redirectUri, state, codeChallenge) {
6849
7954
  const url = new URL("/authorize", ENTIRE_AUTHORIZE_ORIGIN);
@@ -6856,7 +7961,7 @@ function entireAuthorizeUrl(clientId, redirectUri, state, codeChallenge) {
6856
7961
  url.searchParams.set("code_challenge_method", "S256");
6857
7962
  return url.toString();
6858
7963
  }
6859
- async function readJson(res) {
7964
+ async function readJson2(res) {
6860
7965
  const text5 = await res.text();
6861
7966
  if (!text5) return {};
6862
7967
  try {
@@ -6900,13 +8005,13 @@ async function entireIdentityFromCode(client, code, redirectUri, ctx, fetchImpl)
6900
8005
  headers,
6901
8006
  body
6902
8007
  });
6903
- const token = accessToken(await readJson(tokenRes));
8008
+ const token = accessToken(await readJson2(tokenRes));
6904
8009
  const userRes = await fetchImpl(`${issuer}/userinfo`, {
6905
8010
  redirect: "error",
6906
8011
  headers: { Accept: "application/json", Authorization: `Bearer ${token}` }
6907
8012
  });
6908
8013
  if (!userRes.ok) throw new Error("Entire did not return an account.");
6909
- const user = await readJson(userRes);
8014
+ const user = await readJson2(userRes);
6910
8015
  const subject = typeof user.sub === "string" ? user.sub.trim() : "";
6911
8016
  if (!subject) throw new Error("Entire did not return an account id.");
6912
8017
  const email = typeof user.email === "string" ? user.email.trim() : "";
@@ -7009,7 +8114,7 @@ function providerOf(value) {
7009
8114
  function relayAuthorizeUrl(provider, client, redirectUri, state, ctx = EMPTY_AUTH) {
7010
8115
  return GIT_HOST_AUTH[provider].authorizeUrl(client, redirectUri, state, ctx);
7011
8116
  }
7012
- async function readJson2(res) {
8117
+ async function readJson3(res) {
7013
8118
  const text5 = await res.text();
7014
8119
  if (!text5) return {};
7015
8120
  try {
@@ -7040,17 +8145,17 @@ async function fetchGithubIdentity(client, code, redirectUri, state, fetchImpl,
7040
8145
  redirect_uri: redirectUri
7041
8146
  })
7042
8147
  });
7043
- const token = accessToken2(await readJson2(tokenRes));
8148
+ const token = accessToken2(await readJson3(tokenRes));
7044
8149
  const userRes = await fetchImpl("https://api.github.com/user", {
7045
8150
  headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "sideboard-relay" }
7046
8151
  });
7047
- const user = await readJson2(userRes);
8152
+ const user = await readJson3(userRes);
7048
8153
  const subject = typeof user.id === "number" ? String(user.id) : "";
7049
8154
  if (!subject) throw new Error("GitHub did not return an account id.");
7050
8155
  const emailRes = await fetchImpl("https://api.github.com/user/emails", {
7051
8156
  headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "sideboard-relay" }
7052
8157
  });
7053
- const emails = await readJson2(emailRes);
8158
+ const emails = await readJson3(emailRes);
7054
8159
  const list = Array.isArray(emails) ? emails : [];
7055
8160
  const primary = list.find((row2) => row2.primary === true && row2.verified === true);
7056
8161
  const anyVerified = list.find((row2) => row2.verified === true);
@@ -7061,7 +8166,7 @@ async function fetchGithubIdentity(client, code, redirectUri, state, fetchImpl,
7061
8166
  async function fetchRelayIdentity(provider, client, credential, redirectUri, state, fetchImpl, ctx = EMPTY_AUTH) {
7062
8167
  return GIT_HOST_AUTH[provider].fetchIdentity(client, credential, redirectUri, state, fetchImpl, ctx);
7063
8168
  }
7064
- async function readBody(req) {
8169
+ async function readBody2(req) {
7065
8170
  const chunks = [];
7066
8171
  let size = 0;
7067
8172
  for await (const chunk of req) {
@@ -7074,7 +8179,7 @@ async function readBody(req) {
7074
8179
  if (!text5) return {};
7075
8180
  return JSON.parse(text5);
7076
8181
  }
7077
- function sendJson(res, status, body) {
8182
+ function sendJson2(res, status, body) {
7078
8183
  res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
7079
8184
  res.end(JSON.stringify(body));
7080
8185
  }
@@ -7143,7 +8248,7 @@ function relayOAuthReturnPage(title, body) {
7143
8248
  </body>
7144
8249
  </html>`;
7145
8250
  }
7146
- function sendHtml(res, status, title, body) {
8251
+ function sendHtml2(res, status, title, body) {
7147
8252
  res.writeHead(status, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
7148
8253
  res.end(relayOAuthReturnPage(title, body));
7149
8254
  }
@@ -7157,21 +8262,21 @@ async function handleRelayAccountHttp(opts) {
7157
8262
  if (method === "POST" && path2 === REMOTE_LOGIN_PATH) {
7158
8263
  let body;
7159
8264
  try {
7160
- body = await readBody(opts.req);
8265
+ body = await readBody2(opts.req);
7161
8266
  } catch {
7162
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
8267
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
7163
8268
  return true;
7164
8269
  }
7165
8270
  const provider = providerOf(typeof body.provider === "string" ? body.provider : "");
7166
8271
  const state = typeof body.state === "string" ? body.state.trim() : "";
7167
8272
  if (!provider || !STATE_RE.test(state)) {
7168
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
8273
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
7169
8274
  return true;
7170
8275
  }
7171
8276
  const client = opts.oauth[provider];
7172
8277
  const host = provider ? GIT_HOST_AUTH[provider] : null;
7173
8278
  if (!client?.clientId || host?.requiresClientSecret && !client.clientSecret) {
7174
- sendJson(opts.res, 503, {
8279
+ sendJson2(opts.res, 503, {
7175
8280
  ok: false,
7176
8281
  error: `${GIT_HOST_AUTH[provider].label} sign-in is not configured on this relay.`
7177
8282
  });
@@ -7182,14 +8287,14 @@ async function handleRelayAccountHttp(opts) {
7182
8287
  if (linkToken) {
7183
8288
  accountId = opts.store.verifyCredential(linkToken);
7184
8289
  if (!accountId) {
7185
- sendJson(opts.res, 401, { ok: false, error: "sign in required" });
8290
+ sendJson2(opts.res, 401, { ok: false, error: "sign in required" });
7186
8291
  return true;
7187
8292
  }
7188
8293
  }
7189
8294
  const codeVerifier = provider === "entire" ? newEntireCodeVerifier() : null;
7190
8295
  const auth = { codeVerifier, issuer: null };
7191
8296
  opts.sessions.begin(state, provider, accountId, codeVerifier);
7192
- sendJson(opts.res, 200, {
8297
+ sendJson2(opts.res, 200, {
7193
8298
  ok: true,
7194
8299
  url: relayAuthorizeUrl(provider, client, redirectUri, state, auth)
7195
8300
  });
@@ -7201,20 +8306,20 @@ async function handleRelayAccountHttp(opts) {
7201
8306
  const providerError = url.searchParams.get("error")?.trim() ?? "";
7202
8307
  const pending = STATE_RE.test(state) ? opts.sessions.takeLogin(state) : null;
7203
8308
  if (!pending) {
7204
- sendHtml(opts.res, 400, "Sideboard", "<h1>Sign-in expired</h1><p>Return to Sideboard and try again.</p>");
8309
+ sendHtml2(opts.res, 400, "Sideboard", "<h1>Sign-in expired</h1><p>Return to Sideboard and try again.</p>");
7205
8310
  return true;
7206
8311
  }
7207
8312
  const credential = url.searchParams.get(GIT_HOST_AUTH[pending.provider].credentialParam)?.trim() ?? "";
7208
8313
  if (providerError || !credential) {
7209
8314
  const message = providerError || "Sign-in was cancelled.";
7210
8315
  opts.sessions.putResult(state, { ok: false, error: message });
7211
- sendHtml(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml(message)}</p>`);
8316
+ sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml(message)}</p>`);
7212
8317
  return true;
7213
8318
  }
7214
8319
  const client = opts.oauth[pending.provider];
7215
8320
  if (!client) {
7216
8321
  opts.sessions.putResult(state, { ok: false, error: "Sign-in is not configured on this relay." });
7217
- sendHtml(opts.res, 503, "Sideboard", "<h1>Sign-in is not configured</h1>");
8322
+ sendHtml2(opts.res, 503, "Sideboard", "<h1>Sign-in is not configured</h1>");
7218
8323
  return true;
7219
8324
  }
7220
8325
  try {
@@ -7227,14 +8332,14 @@ async function handleRelayAccountHttp(opts) {
7227
8332
  fetchImpl,
7228
8333
  { codeVerifier: pending.codeVerifier, issuer: url.searchParams.get("iss") }
7229
8334
  );
7230
- const signed = opts.store.signIn(identity, pending.accountId);
8335
+ const signed2 = opts.store.signIn(identity, pending.accountId);
7231
8336
  opts.sessions.putResult(state, {
7232
8337
  ok: true,
7233
- credential: signed.credential,
7234
- email: signed.email,
7235
- accountId: signed.accountId
8338
+ credential: signed2.credential,
8339
+ email: signed2.email,
8340
+ accountId: signed2.accountId
7236
8341
  });
7237
- sendHtml(
8342
+ sendHtml2(
7238
8343
  opts.res,
7239
8344
  200,
7240
8345
  "Sideboard",
@@ -7243,7 +8348,7 @@ async function handleRelayAccountHttp(opts) {
7243
8348
  } catch (err) {
7244
8349
  const message = err instanceof Error ? err.message : String(err);
7245
8350
  opts.sessions.putResult(state, { ok: false, error: message });
7246
- sendHtml(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml(message)}</p>`);
8351
+ sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml(message)}</p>`);
7247
8352
  }
7248
8353
  return true;
7249
8354
  }
@@ -7251,19 +8356,19 @@ async function handleRelayAccountHttp(opts) {
7251
8356
  const url = new URL(reqUrl, origin);
7252
8357
  const state = url.searchParams.get("state")?.trim() ?? "";
7253
8358
  if (!STATE_RE.test(state)) {
7254
- sendJson(opts.res, 400, { ok: false, error: "invalid login request" });
8359
+ sendJson2(opts.res, 400, { ok: false, error: "invalid login request" });
7255
8360
  return true;
7256
8361
  }
7257
8362
  const result = opts.sessions.takeResult(state);
7258
8363
  if (result === void 0 || result === null) {
7259
- sendJson(opts.res, 404, { ok: false, error: "pending" });
8364
+ sendJson2(opts.res, 404, { ok: false, error: "pending" });
7260
8365
  return true;
7261
8366
  }
7262
8367
  if (!result.ok) {
7263
- sendJson(opts.res, 400, { ok: false, error: result.error });
8368
+ sendJson2(opts.res, 400, { ok: false, error: result.error });
7264
8369
  return true;
7265
8370
  }
7266
- sendJson(opts.res, 200, {
8371
+ sendJson2(opts.res, 200, {
7267
8372
  ok: true,
7268
8373
  credential: result.credential,
7269
8374
  email: result.email,
@@ -7274,25 +8379,21 @@ async function handleRelayAccountHttp(opts) {
7274
8379
  if (method === "POST" && path2 === REMOTE_LOGOUT_PATH) {
7275
8380
  let body;
7276
8381
  try {
7277
- body = await readBody(opts.req);
8382
+ body = await readBody2(opts.req);
7278
8383
  } catch {
7279
- sendJson(opts.res, 400, { ok: false, error: "invalid logout request" });
8384
+ sendJson2(opts.res, 400, { ok: false, error: "invalid logout request" });
7280
8385
  return true;
7281
8386
  }
7282
8387
  const token = typeof body.accountToken === "string" ? body.accountToken : "";
7283
8388
  opts.store.logout(token);
7284
- sendJson(opts.res, 200, { ok: true });
8389
+ sendJson2(opts.res, 200, { ok: true });
7285
8390
  return true;
7286
8391
  }
7287
8392
  return false;
7288
8393
  }
7289
8394
 
7290
8395
  // src/relay/server.ts
7291
- function sendHtml2(res, status, title, body) {
7292
- res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
7293
- res.end(slackOAuthHtmlPage(title, body));
7294
- }
7295
- function sendJson2(res, status, body) {
8396
+ function sendJson3(res, status, body) {
7296
8397
  res.writeHead(status, { "Content-Type": "application/json" });
7297
8398
  res.end(JSON.stringify(body));
7298
8399
  }
@@ -7336,99 +8437,35 @@ async function startRelayServer(opts) {
7336
8437
  const accountsPath = opts.accountsPath?.trim() ?? "";
7337
8438
  if (accountsPath) assertRelayAccountsDurable(accountsPath);
7338
8439
  const accountStore = accountsPath ? new RelayAccountStore(accountsPath) : null;
8440
+ const slackTokenKey = (opts.slackTokenKey ?? process.env.SIDEBOARD_SLACK_TOKEN_KEY ?? "").trim();
8441
+ const slackApps = accountsPath && slackTokenKey ? new SlackAppStore(accountsPath, parseSlackTokenKey(slackTokenKey)) : null;
8442
+ if (slackApps) {
8443
+ for (const row2 of slackApps.listBots()) hub.rememberBot(row2.teamId, row2.botToken);
8444
+ hub.setBotHooks({
8445
+ guardBotUser: (teamId, botUserId) => slackApps.botUserMismatch(teamId, botUserId),
8446
+ onBotAccepted: (teamId, botToken, botUserId) => slackApps.saveBot(teamId, botToken, botUserId)
8447
+ });
8448
+ }
8449
+ const listenGrants = accountsPath ? new SlackListenGrantStore(accountsPath) : new MemorySlackListenGrants();
8450
+ hub.setListenGrantVerifier((teamId, userId, grant) => listenGrants.verify(teamId, userId, grant));
8451
+ const slackDedupe = new SlackEventDeduper();
7339
8452
  const accountSessions = new RelayLoginSessions();
7340
8453
  const relayOAuth = opts.relayOAuth ?? {};
7341
8454
  const authMarks = /* @__PURE__ */ new Map();
7342
8455
  const remoteByIp = /* @__PURE__ */ new Map();
7343
8456
  let remoteSockets = 0;
7344
- const remoteHub = new RemoteHub({
7345
- authorizeHost: accountStore ? (input) => {
7346
- const decision = accountStore.authorizeHost(input);
7347
- return decision.ok ? { ok: true } : { ok: false, message: decision.message };
7348
- } : void 0,
7349
- phoneSessions: accountStore ? {
7350
- find: (sessionToken) => accountStore.findPhoneSession(sessionToken),
7351
- save: (deviceId, sessionToken) => accountStore.savePhoneSession(deviceId, sessionToken)
7352
- } : void 0,
7353
- onAuthorized: (socket) => authMarks.get(socket)?.()
7354
- });
7355
- const handleCallback = async (reqUrl, res) => {
7356
- const url2 = parseSlackOAuthCallbackUrl(reqUrl);
7357
- if (!url2) return false;
7358
- const error = url2.searchParams.get("error")?.trim();
7359
- const state = url2.searchParams.get("state")?.trim() ?? "";
7360
- const code = url2.searchParams.get("code")?.trim() ?? "";
7361
- if (error) {
7362
- if (state) pending.put(state, { ok: false, error: `Slack OAuth: ${error}` });
7363
- sendHtml2(
7364
- res,
7365
- 400,
7366
- "Slack",
7367
- `<h1>Authorization cancelled</h1><p>${escapeHtml(error)}</p>`
7368
- );
7369
- return true;
7370
- }
7371
- if (!state || !code) {
7372
- sendHtml2(res, 400, "Slack", "<h1>Invalid callback</h1><p>State or code missing.</p>");
7373
- return true;
7374
- }
7375
- if (!clientSecret) {
7376
- pending.put(state, {
7377
- ok: false,
7378
- error: "Relay is missing SIDEBOARD_SLACK_CLIENT_SECRET"
7379
- });
7380
- sendHtml2(
7381
- res,
7382
- 500,
7383
- "Slack",
7384
- "<h1>Relay misconfigured</h1><p>OAuth client secret is not set on the relay.</p>"
7385
- );
7386
- return true;
7387
- }
7388
- try {
7389
- const payload = await exchangeSlackOAuthCode({
7390
- clientId,
7391
- clientSecret,
7392
- code,
7393
- redirectUri,
7394
- fetchImpl: opts.fetchImpl
7395
- });
7396
- pending.put(state, { ok: true, payload });
7397
- if (payload.bot_token) {
7398
- hub.rememberBot(payload.team_id, payload.bot_token);
7399
- if (payload.user_id) {
7400
- void hub.handleAppHomeOpened(payload.team_id, payload.user_id);
7401
- }
7402
- }
7403
- sendHtml2(
7404
- res,
7405
- 200,
7406
- "Slack connected",
7407
- '<h1>Slack workspace connected</h1><p>Open <strong>Sideboard \u2192 Settings \u2192 Remote \u2192 Slack</strong>. Confirm Relay connected, name this Mac, then DM @Sideboard.</p><p>Need the app? <a href="https://www.sideboard.cloud/slack/">Download Sideboard</a>.</p>'
7408
- );
7409
- } catch (err) {
7410
- const message = err instanceof Error ? err.message : String(err);
7411
- pending.put(state, { ok: false, error: message });
7412
- sendHtml2(res, 400, "Slack", `<h1>Could not connect Slack</h1><p>${escapeHtml(message)}</p>`);
7413
- }
7414
- return true;
7415
- };
7416
- const handleResult = (reqUrl, res) => {
7417
- const url2 = parseSlackOAuthResultUrl(reqUrl);
7418
- if (!url2) return false;
7419
- const state = url2.searchParams.get("state")?.trim() ?? "";
7420
- const value = pending.take(state);
7421
- if (!value) {
7422
- sendJson2(res, 404, { ok: false, error: "pending" });
7423
- return true;
7424
- }
7425
- if (!value.ok) {
7426
- sendJson2(res, 400, { ok: false, error: value.error });
7427
- return true;
7428
- }
7429
- sendJson2(res, 200, { ok: true, ...value.payload });
7430
- return true;
7431
- };
8457
+ const remoteHub = new RemoteHub({
8458
+ authorizeHost: accountStore ? (input) => {
8459
+ const decision = accountStore.authorizeHost(input);
8460
+ return decision.ok ? { ok: true } : { ok: false, message: decision.message };
8461
+ } : void 0,
8462
+ phoneSessions: accountStore ? {
8463
+ find: (sessionToken) => accountStore.findPhoneSession(sessionToken),
8464
+ save: (deviceId, sessionToken) => accountStore.savePhoneSession(deviceId, sessionToken)
8465
+ } : void 0,
8466
+ onAuthorized: (socket) => authMarks.get(socket)?.()
8467
+ });
8468
+ const publicOrigin = () => opts.relayPublicOrigin?.trim() || process.env.SIDEBOARD_RELAY_PUBLIC_ORIGIN?.trim() || `http://127.0.0.1:${boundPort}`;
7432
8469
  const httpServer = createServer((req, res) => {
7433
8470
  void (async () => {
7434
8471
  const reqUrl = req.url || "/";
@@ -7438,13 +8475,30 @@ async function startRelayServer(opts) {
7438
8475
  store: accountStore,
7439
8476
  oauth: relayOAuth,
7440
8477
  sessions: accountSessions,
7441
- publicOrigin: opts.relayPublicOrigin?.trim() || process.env.SIDEBOARD_RELAY_PUBLIC_ORIGIN?.trim() || `http://127.0.0.1:${boundPort}`,
8478
+ publicOrigin: publicOrigin(),
7442
8479
  fetchImpl: opts.fetchImpl
7443
8480
  })) {
7444
8481
  return;
7445
8482
  }
7446
- if (await handleCallback(reqUrl, res)) return;
7447
- if (handleResult(reqUrl, res)) return;
8483
+ if (await handleSlackHttp({
8484
+ req,
8485
+ res,
8486
+ reqUrl,
8487
+ accounts: accountStore,
8488
+ apps: slackApps,
8489
+ hub,
8490
+ grants: listenGrants,
8491
+ pending,
8492
+ bakedClientId: clientId,
8493
+ bakedClientSecret: clientSecret,
8494
+ redirectUri,
8495
+ publicOrigin: publicOrigin(),
8496
+ fetchImpl: opts.fetchImpl,
8497
+ dedupe: slackDedupe,
8498
+ log
8499
+ })) {
8500
+ return;
8501
+ }
7448
8502
  const ableTimeBounce = ableTimeOAuthLocalBounceUrl(reqUrl);
7449
8503
  if (ableTimeBounce && (req.method === "GET" || req.method === "HEAD")) {
7450
8504
  res.writeHead(200, {
@@ -7456,7 +8510,7 @@ async function startRelayServer(opts) {
7456
8510
  return;
7457
8511
  }
7458
8512
  if (req.url === "/health") {
7459
- sendJson2(res, 200, {
8513
+ sendJson3(res, 200, {
7460
8514
  ok: true,
7461
8515
  service: "sideboard-relay",
7462
8516
  sessions: hub.listSessions().length,
@@ -7464,20 +8518,16 @@ async function startRelayServer(opts) {
7464
8518
  });
7465
8519
  return;
7466
8520
  }
7467
- const hostname2 = requestHostname(req);
7468
- const canonical = (opts.canonicalSiteHost ?? "www.sideboard.cloud").toLowerCase();
7469
- const staticHosts = opts.staticHosts ?? [];
7470
- const servesSite = staticHosts.length > 0 && staticHosts.includes(hostname2);
7471
- if (opts.redirectHosts?.includes(hostname2) && hostname2 !== canonical && !servesSite) {
7472
- res.writeHead(301, { Location: `https://${canonical}${reqUrl}` });
7473
- res.end();
7474
- return;
7475
- }
7476
- if (opts.staticRoot && hostnameAllowed(hostname2, opts.staticHosts) && await tryServeStatic(req, res, opts.staticRoot)) {
8521
+ if (opts.staticRoot && await serveMarketingSite(req, res, {
8522
+ root: opts.staticRoot,
8523
+ canonicalHost: opts.canonicalSiteHost ?? CANONICAL_SITE_HOST,
8524
+ staticHosts: opts.staticHosts,
8525
+ redirectHosts: opts.redirectHosts
8526
+ })) {
7477
8527
  return;
7478
8528
  }
7479
8529
  if (req.url === "/") {
7480
- sendJson2(res, 200, {
8530
+ sendJson3(res, 200, {
7481
8531
  ok: true,
7482
8532
  service: "sideboard-relay",
7483
8533
  sessions: hub.listSessions().length,
@@ -7617,6 +8667,7 @@ async function startRelayServer(opts) {
7617
8667
  void hub.handleAppHomeOpened(event.teamId, event.userId);
7618
8668
  return;
7619
8669
  }
8670
+ listenGrants.revokeTeam(event.teamId);
7620
8671
  hub.uninstallTeam(event.teamId);
7621
8672
  }
7622
8673
  }).catch((err) => {
@@ -7641,6 +8692,8 @@ async function startRelayServer(opts) {
7641
8692
  httpServer.close((err) => err ? reject(err) : resolve());
7642
8693
  });
7643
8694
  await socketModeDone.catch(() => void 0);
8695
+ slackApps?.close();
8696
+ listenGrants.close();
7644
8697
  accountStore?.close();
7645
8698
  }
7646
8699
  };
@@ -7697,7 +8750,7 @@ async function startHeadlessHost(opts) {
7697
8750
  };
7698
8751
  const refreshRunning = async () => {
7699
8752
  try {
7700
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-IYXIWNB5.js");
8753
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
7701
8754
  agentsRunning = getOrchestrator2().getRuntime().running;
7702
8755
  } catch {
7703
8756
  agentsRunning = 0;
@@ -9848,7 +10901,7 @@ async function handleJobStop(params, _ctx) {
9848
10901
  return stopDetachedJob(jobCwd(rec), id, reason ? { reason } : void 0);
9849
10902
  }
9850
10903
  async function defaultTurnWait(ref, timeoutMs) {
9851
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-IYXIWNB5.js");
10904
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
9852
10905
  const orch = getOrchestrator2();
9853
10906
  const thread = await orch.waitForTurn(ref, timeoutMs, {
9854
10907
  resolveIfStillRunning: true
@@ -9910,32 +10963,32 @@ function createAgentRpcDispatcher() {
9910
10963
  }
9911
10964
 
9912
10965
  // src/board/load-home-board.ts
9913
- import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync5, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "fs";
9914
- import { join as join5 } from "path";
10966
+ import { existsSync as existsSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync5, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "fs";
10967
+ import { join as join8 } from "path";
9915
10968
 
9916
10969
  // src/board/board-pins.ts
9917
10970
  import { randomUUID as randomUUID6 } from "crypto";
9918
- import { existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, unlinkSync as unlinkSync2, writeFileSync } from "fs";
9919
- import { join as join4 } from "path";
10971
+ import { existsSync as existsSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync4, unlinkSync as unlinkSync2, writeFileSync } from "fs";
10972
+ import { join as join7 } from "path";
9920
10973
  var FILE = "home-board-pins.json";
9921
- var VERSION = 1;
10974
+ var VERSION2 = 1;
9922
10975
  function pinsFile() {
9923
- return join4(appDataDir(), FILE);
10976
+ return join7(appDataDir(), FILE);
9924
10977
  }
9925
10978
  function readDisk() {
9926
10979
  const path2 = pinsFile();
9927
10980
  if (!existsSync2(path2)) return [];
9928
10981
  try {
9929
10982
  const raw = JSON.parse(readFileSync4(path2, "utf8"));
9930
- if (raw?.version !== VERSION || !Array.isArray(raw.items)) return [];
10983
+ if (raw?.version !== VERSION2 || !Array.isArray(raw.items)) return [];
9931
10984
  return raw.items.filter((item) => item?.id && item.kind && item.ref);
9932
10985
  } catch {
9933
10986
  return [];
9934
10987
  }
9935
10988
  }
9936
10989
  function writeDisk(items) {
9937
- mkdirSync3(appDataDir(), { recursive: true });
9938
- writeFileSync(pinsFile(), JSON.stringify({ version: VERSION, items }, null, 2), "utf8");
10990
+ mkdirSync5(appDataDir(), { recursive: true });
10991
+ writeFileSync(pinsFile(), JSON.stringify({ version: VERSION2, items }, null, 2), "utf8");
9939
10992
  }
9940
10993
  function listBoardPins() {
9941
10994
  return readDisk();
@@ -10003,7 +11056,7 @@ function homeBoardWorkspaceKey(workspaces) {
10003
11056
  return workspaces.map((w) => w.path).filter(Boolean).sort().join("\n");
10004
11057
  }
10005
11058
  function cacheFile() {
10006
- return join5(appDataDir(), "home-board-cache.json");
11059
+ return join8(appDataDir(), "home-board-cache.json");
10007
11060
  }
10008
11061
  function emptyInputs() {
10009
11062
  return {
@@ -10045,7 +11098,7 @@ function readDiskCache() {
10045
11098
  }
10046
11099
  function writeDiskCache(entry) {
10047
11100
  try {
10048
- mkdirSync4(appDataDir(), { recursive: true });
11101
+ mkdirSync6(appDataDir(), { recursive: true });
10049
11102
  writeFileSync2(cacheFile(), JSON.stringify(entry), "utf8");
10050
11103
  } catch {
10051
11104
  }
@@ -10201,7 +11254,7 @@ async function startMcpServer() {
10201
11254
  );
10202
11255
  }
10203
11256
  try {
10204
- const { maxConcurrentAgents: maxConcurrentAgents2 } = await import("./app-settings-JAEV53LB.js");
11257
+ const { maxConcurrentAgents: maxConcurrentAgents2 } = await import("./app-settings-KOSVLMO5.js");
10205
11258
  orch.setMaxConcurrent(maxConcurrentAgents2());
10206
11259
  } catch {
10207
11260
  }
@@ -10749,7 +11802,7 @@ async function startMcpServer() {
10749
11802
  if (!worktreeProfile) {
10750
11803
  registerConnectedIssueVendorTools(server);
10751
11804
  const { getCaffeinateHold: getCaffeinateHold2, setCaffeinateHold: setCaffeinateHold2 } = await import("./caffeinate-hold-ZNUEZGHB.js");
10752
- const { resolveNewThreadOptions: resolveNewThreadOptions2, resolveThreadDefaults: resolveThreadDefaults2 } = await import("./app-settings-JAEV53LB.js");
11805
+ const { resolveNewThreadOptions: resolveNewThreadOptions2, resolveThreadDefaults: resolveThreadDefaults2 } = await import("./app-settings-KOSVLMO5.js");
10753
11806
  const accountDefaults = resolveThreadDefaults2();
10754
11807
  const accountDefaultsHint = `Account defaults: agent=${accountDefaults.agent}, model=${accountDefaults.model?.trim() || "Auto"}, effort=${accountDefaults.effort}`;
10755
11808
  server.tool(
@@ -11433,14 +12486,14 @@ async function startMcpServer() {
11433
12486
  }
11434
12487
 
11435
12488
  // src/agent-rpc/server.ts
11436
- import { randomBytes as randomBytes6, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual2 } from "crypto";
12489
+ import { randomBytes as randomBytes11, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual4 } from "crypto";
11437
12490
  import { createServer as createServer2 } from "http";
11438
12491
  import { WebSocketServer as WebSocketServer2 } from "ws";
11439
12492
  function tokensEqual(a, b) {
11440
12493
  const left = Buffer.from(a);
11441
12494
  const right = Buffer.from(b);
11442
12495
  if (left.length !== right.length) return false;
11443
- return timingSafeEqual2(left, right);
12496
+ return timingSafeEqual4(left, right);
11444
12497
  }
11445
12498
  function authTokenFromUpgrade(req) {
11446
12499
  try {
@@ -11450,7 +12503,7 @@ function authTokenFromUpgrade(req) {
11450
12503
  return "";
11451
12504
  }
11452
12505
  }
11453
- function sendJson3(ws, value) {
12506
+ function sendJson4(ws, value) {
11454
12507
  if (ws.readyState !== ws.OPEN) return;
11455
12508
  ws.send(JSON.stringify(value));
11456
12509
  }
@@ -11473,7 +12526,7 @@ var AgentRpcServer = class {
11473
12526
  async listen(opts = {}) {
11474
12527
  const host = opts.host ?? "127.0.0.1";
11475
12528
  const port = opts.port ?? 0;
11476
- const authToken = randomBytes6(24).toString("base64url");
12529
+ const authToken = randomBytes11(24).toString("base64url");
11477
12530
  this.meta = {
11478
12531
  runtimeId: randomUUID8(),
11479
12532
  pid: process.pid,
@@ -11535,36 +12588,36 @@ var AgentRpcServer = class {
11535
12588
  async onMessage(ws, raw) {
11536
12589
  const parsed = parseRpcFrame(raw);
11537
12590
  if (parsed === void 0) {
11538
- sendJson3(ws, rpcError(null, RPC_PARSE_ERROR, "Parse error"));
12591
+ sendJson4(ws, rpcError(null, RPC_PARSE_ERROR, "Parse error"));
11539
12592
  return;
11540
12593
  }
11541
12594
  if (!isJsonRpcRequest(parsed)) {
11542
- sendJson3(ws, rpcError(null, RPC_INVALID_REQUEST, "Invalid request"));
12595
+ sendJson4(ws, rpcError(null, RPC_INVALID_REQUEST, "Invalid request"));
11543
12596
  return;
11544
12597
  }
11545
12598
  const id = parsed.id;
11546
12599
  const expected = this.meta?.authToken ?? "";
11547
12600
  const got = typeof parsed.authToken === "string" ? parsed.authToken : "";
11548
12601
  if (!expected || !got || !tokensEqual(got, expected)) {
11549
- sendJson3(ws, rpcError(id, RPC_UNAUTHORIZED, "Unauthorized"));
12602
+ sendJson4(ws, rpcError(id, RPC_UNAUTHORIZED, "Unauthorized"));
11550
12603
  return;
11551
12604
  }
11552
12605
  const handler = this.handlers[parsed.method];
11553
12606
  if (!handler) {
11554
- sendJson3(ws, rpcError(id, RPC_METHOD_NOT_FOUND, `Method not found: ${parsed.method}`));
12607
+ sendJson4(ws, rpcError(id, RPC_METHOD_NOT_FOUND, `Method not found: ${parsed.method}`));
11555
12608
  return;
11556
12609
  }
11557
12610
  const ctx = {
11558
12611
  cwd: this.cwd(),
11559
- notify: (method, params) => sendJson3(ws, rpcNotify(method, params))
12612
+ notify: (method, params) => sendJson4(ws, rpcNotify(method, params))
11560
12613
  };
11561
12614
  try {
11562
12615
  const result = await handler(parsed.params, ctx);
11563
- sendJson3(ws, rpcResult(id, result));
12616
+ sendJson4(ws, rpcResult(id, result));
11564
12617
  } catch (err) {
11565
12618
  const message = err instanceof Error ? err.message : String(err);
11566
12619
  const code = err && typeof err === "object" && "rpcCode" in err && typeof err.rpcCode === "number" ? err.rpcCode : RPC_INTERNAL_ERROR;
11567
- sendJson3(ws, rpcError(id, code, message));
12620
+ sendJson4(ws, rpcError(id, code, message));
11568
12621
  }
11569
12622
  }
11570
12623
  async close() {
@@ -12232,250 +13285,61 @@ async function runCloudConnect(opts) {
12232
13285
  }
12233
13286
  }
12234
13287
 
12235
- // src/slack/workspaces.ts
12236
- import { join as join6 } from "path";
12237
- function storePath() {
12238
- return join6(appDataDir(), "slack-workspaces.json");
13288
+ // src/slack/org-app-client.ts
13289
+ function originOf(relayWsUrl) {
13290
+ return slackRelayHttpOrigin(relayWsUrl ?? slackRelayUrl());
12239
13291
  }
12240
- function readStore() {
13292
+ async function readError(res) {
12241
13293
  try {
12242
- const path2 = storePath();
12243
- const wasEncrypted = isSecureFileEncrypted(path2);
12244
- const parsed = readSecureJson(path2);
12245
- const workspaces = Array.isArray(parsed?.workspaces) ? parsed.workspaces : [];
12246
- if (workspaces.length > 0 && !wasEncrypted && resolveVaultKey()) {
12247
- writeSecureJson(path2, { workspaces });
12248
- }
12249
- return workspaces;
13294
+ const body = await res.json();
13295
+ if (body.error?.trim()) return body.error.trim();
12250
13296
  } catch {
12251
- return [];
12252
13297
  }
13298
+ return `Relay returned ${res.status}`;
12253
13299
  }
12254
- function writeStore(workspaces) {
12255
- writeSecureJson(storePath(), { workspaces });
12256
- return workspaces;
12257
- }
12258
- function toInfo(ws) {
13300
+ async function createSlackOrgApp(opts) {
13301
+ const token = opts.accountToken.trim();
13302
+ if (!token) throw new Error("Sign in on Settings \u2192 Remote before creating a Slack app");
13303
+ const fetchImpl = opts.fetchImpl ?? fetch;
13304
+ const res = await fetchImpl(`${originOf(opts.relayWsUrl)}/slack/apps`, {
13305
+ method: "POST",
13306
+ headers: { Authorization: `Bearer ${token}` }
13307
+ });
13308
+ if (!res.ok) throw new Error(await readError(res));
13309
+ const body = await res.json();
13310
+ if (!body.registrationId || !body.writeToken || !body.manifest || !body.eventsUrl) {
13311
+ throw new Error("Relay did not return a Slack app registration");
13312
+ }
12259
13313
  return {
12260
- team_id: ws.team_id,
12261
- team_name: ws.team_name,
12262
- user_id: ws.user_id,
12263
- has_bot_token: Boolean(ws.bot_token),
12264
- has_user_token: Boolean(ws.user_token),
12265
- connected_at: ws.connected_at
12266
- };
12267
- }
12268
- function listSlackWorkspaces() {
12269
- return readStore().map(toInfo).sort((a, b) => a.team_name.localeCompare(b.team_name));
12270
- }
12271
- function listSlackWorkspacesRaw() {
12272
- return readStore();
12273
- }
12274
- function getSlackWorkspace(teamId) {
12275
- const id = teamId.trim();
12276
- if (!id) return null;
12277
- return readStore().find(
12278
- (ws) => ws.team_id === id || ws.team_name.toLowerCase() === id.toLowerCase()
12279
- ) ?? null;
12280
- }
12281
- function upsertSlackWorkspace(entry) {
12282
- const workspaces = readStore().filter((ws) => ws.team_id !== entry.team_id);
12283
- workspaces.push(entry);
12284
- writeStore(workspaces);
12285
- return toInfo(entry);
12286
- }
12287
- function disconnectSlackWorkspace(teamId) {
12288
- const id = teamId.trim();
12289
- writeStore(readStore().filter((ws) => ws.team_id !== id));
12290
- return listSlackWorkspaces();
12291
- }
12292
- function tokenKind(token) {
12293
- if (token.startsWith("xoxb-")) return "bot";
12294
- if (token.startsWith("xoxp-") || token.startsWith("xoxe.xoxp-")) return "user";
12295
- return "unknown";
12296
- }
12297
- async function connectSlackToken(rawToken) {
12298
- const token = rawToken.trim();
12299
- if (!token) throw new Error("Paste a Slack bot (xoxb-) or user (xoxp-) token");
12300
- const auth = await slackAuthTest(token);
12301
- const teamId = auth.team_id?.trim();
12302
- if (!teamId) throw new Error("Slack auth.test did not return a team_id");
12303
- const existing = getSlackWorkspace(teamId);
12304
- const kind = tokenKind(token);
12305
- const next = {
12306
- team_id: teamId,
12307
- team_name: auth.team?.trim() || existing?.team_name || teamId,
12308
- user_id: auth.user_id?.trim() || existing?.user_id,
12309
- bot_token: kind === "bot" ? token : existing?.bot_token,
12310
- user_token: kind === "user" || kind === "unknown" ? token : existing?.user_token,
12311
- scopes: existing?.scopes,
12312
- connected_at: existing?.connected_at || (/* @__PURE__ */ new Date()).toISOString()
13314
+ registrationId: body.registrationId,
13315
+ writeToken: body.writeToken,
13316
+ eventsUrl: body.eventsUrl,
13317
+ manifest: body.manifest
12313
13318
  };
12314
- if (kind === "unknown" && auth.bot_id) {
12315
- next.bot_token = token;
12316
- next.user_token = existing?.user_token;
12317
- }
12318
- return upsertSlackWorkspace(next);
12319
- }
12320
- function slackTokenFor(ws, kind = "read") {
12321
- const token = (kind === "write" ? ws.bot_token || ws.user_token : ws.user_token || ws.bot_token)?.trim();
12322
- if (!token) {
12323
- throw new Error(`Slack workspace ${ws.team_name} has no token`);
12324
- }
12325
- return token;
12326
- }
12327
-
12328
- // src/slack/oauth.ts
12329
- import { randomBytes as randomBytes7 } from "crypto";
12330
- var SLACK_BOT_SCOPES = [
12331
- "app_mentions:read",
12332
- "channels:history",
12333
- "channels:read",
12334
- "groups:history",
12335
- "groups:read",
12336
- "im:history",
12337
- "im:read",
12338
- "im:write",
12339
- "mpim:history",
12340
- "mpim:read",
12341
- "chat:write",
12342
- "chat:write.public",
12343
- "reactions:write",
12344
- "users:read",
12345
- "users:read.email"
12346
- ].join(",");
12347
- var SLACK_USER_SCOPES = [
12348
- "channels:history",
12349
- "channels:read",
12350
- "groups:history",
12351
- "im:history",
12352
- "mpim:history",
12353
- "users:read"
12354
- ].join(",");
12355
- function slackOAuthCredentials() {
12356
- const settings = loadAppSettings();
12357
- const clientId = process.env.SIDEBOARD_SLACK_CLIENT_ID?.trim() || settings.integrations.slackClientId?.trim() || BAKED_SLACK_CLIENT_ID.trim();
12358
- const clientSecret = process.env.SIDEBOARD_SLACK_CLIENT_SECRET?.trim() || settings.integrations.slackClientSecret?.trim() || "";
12359
- if (!clientId) {
12360
- throw new Error(
12361
- "Slack browser sign-in needs a Slack app Client ID (Settings \u2192 Remote \u2192 Slack, or SIDEBOARD_SLACK_CLIENT_ID). You can still paste an xoxb- or xoxp- token."
12362
- );
12363
- }
12364
- return { clientId, clientSecret: clientSecret || null };
12365
- }
12366
- var SLACK_OAUTH_CANCELLED = "Slack sign-in cancelled";
12367
- var SlackOAuthCancelledError = class extends Error {
12368
- constructor(message = SLACK_OAUTH_CANCELLED) {
12369
- super(message);
12370
- this.name = "SlackOAuthCancelledError";
12371
- }
12372
- };
12373
- function isSlackOAuthCancelled(err) {
12374
- if (err instanceof SlackOAuthCancelledError) return true;
12375
- const message = err instanceof Error ? err.message : String(err);
12376
- if (message.includes(SLACK_OAUTH_CANCELLED)) return true;
12377
- return err instanceof Error && err.name === "SlackOAuthCancelledError";
12378
- }
12379
- function slackOAuthAuthorizeUrl(clientId, state) {
12380
- const params = new URLSearchParams({
12381
- client_id: clientId,
12382
- scope: SLACK_BOT_SCOPES,
12383
- user_scope: SLACK_USER_SCOPES,
12384
- redirect_uri: slackOAuthRedirectUri(),
12385
- state
12386
- });
12387
- return `https://slack.com/oauth/v2/authorize?${params.toString()}`;
12388
- }
12389
- function sleep(ms, signal) {
12390
- return new Promise((resolve, reject) => {
12391
- if (signal?.aborted) {
12392
- reject(new SlackOAuthCancelledError());
12393
- return;
12394
- }
12395
- const timer = setTimeout(() => {
12396
- signal?.removeEventListener("abort", onAbort);
12397
- resolve();
12398
- }, ms);
12399
- const onAbort = () => {
12400
- clearTimeout(timer);
12401
- reject(new SlackOAuthCancelledError());
12402
- };
12403
- signal?.addEventListener("abort", onAbort, { once: true });
12404
- });
12405
- }
12406
- function upsertFromPayload(payload) {
12407
- return upsertSlackWorkspace({
12408
- team_id: payload.team_id,
12409
- team_name: payload.team_name,
12410
- user_id: payload.user_id,
12411
- bot_token: payload.bot_token,
12412
- user_token: payload.user_token,
12413
- scopes: payload.scopes,
12414
- connected_at: (/* @__PURE__ */ new Date()).toISOString()
12415
- });
12416
13319
  }
12417
- async function startSlackOAuth(opts) {
12418
- if (opts?.signal?.aborted) {
12419
- throw new SlackOAuthCancelledError();
12420
- }
12421
- const { clientId } = slackOAuthCredentials();
12422
- const state = randomBytes7(16).toString("hex");
12423
- const authorizeUrl = slackOAuthAuthorizeUrl(clientId, state);
12424
- const timeoutMs = opts?.timeoutMs ?? 5 * 6e4;
12425
- const pollIntervalMs = opts?.pollIntervalMs ?? 400;
12426
- const fetchImpl = opts?.fetchImpl ?? fetch;
12427
- const resultUrl = opts?.resultUrlForState?.(state) ?? slackOAuthResultUrl(state);
12428
- await Promise.resolve(opts?.openUrl?.(authorizeUrl));
12429
- if (opts?.signal?.aborted) {
12430
- throw new SlackOAuthCancelledError();
12431
- }
12432
- const deadline = Date.now() + timeoutMs;
12433
- while (Date.now() < deadline) {
12434
- if (opts?.signal?.aborted) {
12435
- throw new SlackOAuthCancelledError();
12436
- }
12437
- let res;
12438
- try {
12439
- res = await fetchImpl(resultUrl);
12440
- } catch {
12441
- if (opts?.signal?.aborted) throw new SlackOAuthCancelledError();
12442
- await sleep(pollIntervalMs, opts?.signal);
12443
- continue;
12444
- }
12445
- let data;
12446
- try {
12447
- data = await res.json();
12448
- } catch {
12449
- await sleep(pollIntervalMs, opts?.signal);
12450
- continue;
12451
- }
12452
- if (data.ok && data.team_id?.trim()) {
12453
- return upsertFromPayload({
12454
- team_id: data.team_id.trim(),
12455
- team_name: data.team_name?.trim() || data.team_id.trim(),
12456
- user_id: data.user_id?.trim() || void 0,
12457
- bot_token: data.bot_token?.trim() || void 0,
12458
- user_token: data.user_token?.trim() || void 0,
12459
- scopes: data.scopes?.trim() || ""
12460
- });
12461
- }
12462
- const err = data.error?.trim();
12463
- if (err && err !== "pending") {
12464
- if (/cancel/i.test(err) || /access_denied/i.test(err)) {
12465
- throw new SlackOAuthCancelledError(`Slack OAuth: ${err}`);
12466
- }
12467
- throw new Error(err.startsWith("Slack") ? err : `Slack OAuth: ${err}`);
13320
+ async function saveSlackOrgCredentials(opts) {
13321
+ const fetchImpl = opts.fetchImpl ?? fetch;
13322
+ const res = await fetchImpl(
13323
+ `${originOf(opts.relayWsUrl)}/slack/apps/${encodeURIComponent(opts.registrationId)}/credentials`,
13324
+ {
13325
+ method: "POST",
13326
+ headers: { "Content-Type": "application/json" },
13327
+ body: JSON.stringify({
13328
+ writeToken: opts.writeToken,
13329
+ clientId: opts.clientId,
13330
+ clientSecret: opts.clientSecret,
13331
+ signingSecret: opts.signingSecret
13332
+ })
12468
13333
  }
12469
- await sleep(pollIntervalMs, opts?.signal);
12470
- }
12471
- throw new Error("Slack sign-in timed out \u2014 try again");
13334
+ );
13335
+ if (!res.ok) throw new Error(await readError(res));
12472
13336
  }
12473
13337
 
12474
13338
  // src/slack/reply-target.ts
12475
13339
  import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
12476
- import { join as join7 } from "path";
13340
+ import { join as join9 } from "path";
12477
13341
  function storePath2() {
12478
- return join7(appDataDir(), "slack-reply-to.json");
13342
+ return join9(appDataDir(), "slack-reply-to.json");
12479
13343
  }
12480
13344
  function readStore2() {
12481
13345
  const path2 = storePath2();
@@ -12536,9 +13400,11 @@ async function runSlackRelayClient(opts) {
12536
13400
  const deviceId = opts.deviceId.trim();
12537
13401
  if (!url) throw new Error("Relay URL is empty");
12538
13402
  if (!deviceId) throw new Error("Relay needs a deviceId for this Mac");
12539
- if (opts.workspaces.length === 0) {
13403
+ if (opts.workspaces.length === 0 || opts.workspaces.some(
13404
+ (ws) => !ws.botToken.trim() || !ws.userId.trim() || !ws.userToken?.trim() && !ws.listenGrant?.trim()
13405
+ )) {
12540
13406
  throw new Error(
12541
- "Relay needs a connected Slack workspace with bot + user tokens (Add via browser)."
13407
+ "Relay needs Add via browser so this Mac can prove which Slack user it is."
12542
13408
  );
12543
13409
  }
12544
13410
  let backoff = BACKOFF_START_MS3;
@@ -12644,7 +13510,8 @@ function connectSession2(ws, opts, log) {
12644
13510
  deviceId: opts.deviceId.trim(),
12645
13511
  deviceLabel: opts.deviceLabel?.trim() || void 0,
12646
13512
  botToken: wsInfo.botToken,
12647
- userToken: wsInfo.userToken
13513
+ ...wsInfo.userToken?.trim() ? { userToken: wsInfo.userToken.trim() } : {},
13514
+ ...wsInfo.listenGrant?.trim() ? { listenGrant: wsInfo.listenGrant.trim() } : {}
12648
13515
  });
12649
13516
  }
12650
13517
  pingOnce();
@@ -13014,8 +13881,8 @@ function startSlackTurnProgress(msg, threadId, opts) {
13014
13881
  finishWith: (text5) => {
13015
13882
  stop();
13016
13883
  return run2(async () => {
13017
- const signed = signForThisMac(text5.trim());
13018
- if (!signed) {
13884
+ const signed2 = signForThisMac(text5.trim());
13885
+ if (!signed2) {
13019
13886
  if (!postedTs) return;
13020
13887
  const ts = postedTs;
13021
13888
  postedTs = null;
@@ -13029,14 +13896,14 @@ function startSlackTurnProgress(msg, threadId, opts) {
13029
13896
  }
13030
13897
  if (postedTs) {
13031
13898
  try {
13032
- await updateSlackText(target, postedTs, signed, opts);
13899
+ await updateSlackText(target, postedTs, signed2, opts);
13033
13900
  return;
13034
13901
  } catch (err) {
13035
13902
  const errMsg = err instanceof Error ? err.message : String(err);
13036
13903
  log(`progress update error: ${errMsg}`);
13037
13904
  }
13038
13905
  }
13039
- await postSlackText(target, signed, opts);
13906
+ await postSlackText(target, signed2, opts);
13040
13907
  });
13041
13908
  }
13042
13909
  };
@@ -13269,12 +14136,10 @@ async function runSlackListen(opts = {}) {
13269
14136
  if (!relay) {
13270
14137
  throw new Error("Slack Listen needs the hosted relay URL.");
13271
14138
  }
13272
- const withIdentity = connected.filter(
13273
- (w) => w.bot_token?.trim() && w.user_token?.trim() && w.user_id?.trim()
13274
- );
14139
+ const withIdentity = connected.filter(slackWorkspaceCanListen);
13275
14140
  if (withIdentity.length === 0) {
13276
14141
  throw new Error(
13277
- "Slack Listen needs Add via browser (bot token + your Slack user id). Paste-only bot tokens cannot prove which Slack user owns this Mac."
14142
+ "Slack Listen needs Add via browser so this Mac can prove which Slack user it is. A pasted bot token cannot."
13278
14143
  );
13279
14144
  }
13280
14145
  const device = ensureSlackDeviceIdentity();
@@ -13286,12 +14151,17 @@ async function runSlackListen(opts = {}) {
13286
14151
  WebSocketImpl: opts.WebSocketImpl,
13287
14152
  deviceId: device.deviceId,
13288
14153
  deviceLabel: device.deviceLabel,
13289
- workspaces: withIdentity.map((w) => ({
13290
- teamId: w.team_id,
13291
- userId: w.user_id.trim(),
13292
- botToken: w.bot_token.trim(),
13293
- userToken: w.user_token.trim()
13294
- })),
14154
+ workspaces: withIdentity.map((w) => {
14155
+ const userToken = w.user_token?.trim();
14156
+ const listenGrant = w.listen_grant?.trim();
14157
+ return {
14158
+ teamId: w.team_id,
14159
+ userId: w.user_id.trim(),
14160
+ botToken: w.bot_token.trim(),
14161
+ ...userToken ? { userToken } : {},
14162
+ ...listenGrant ? { listenGrant } : {}
14163
+ };
14164
+ }),
13295
14165
  onEvent: onInbound,
13296
14166
  onUninstalled: (teamId) => {
13297
14167
  disconnectSlackWorkspace(teamId);
@@ -13304,15 +14174,13 @@ async function runSlackListen(opts = {}) {
13304
14174
  }
13305
14175
  function resolveSlackListenMode(opts) {
13306
14176
  const relay = (opts?.relayUrl ?? slackRelayUrl()).trim();
13307
- const count = opts?.workspaceCount ?? listSlackWorkspacesRaw().filter(
13308
- (w) => w.bot_token?.trim() && w.user_token?.trim() && w.user_id?.trim()
13309
- ).length;
14177
+ const count = listSlackWorkspacesRaw().filter(slackWorkspaceCanListen).length;
13310
14178
  if (relay && count > 0) return "relay";
13311
14179
  return null;
13312
14180
  }
13313
14181
 
13314
14182
  // src/relay/account-login.ts
13315
- import { randomBytes as randomBytes8 } from "crypto";
14183
+ import { randomBytes as randomBytes12 } from "crypto";
13316
14184
  var RemoteAccountLoginCancelled = class extends Error {
13317
14185
  constructor() {
13318
14186
  super("Sign-in cancelled");
@@ -13365,7 +14233,7 @@ async function relayFetch(fetchImpl, url, init) {
13365
14233
  throw relayFetchError(err, url);
13366
14234
  }
13367
14235
  }
13368
- async function readJson3(res, url) {
14236
+ async function readJson4(res, url) {
13369
14237
  try {
13370
14238
  return await res.json();
13371
14239
  } catch {
@@ -13378,7 +14246,7 @@ async function readJson3(res, url) {
13378
14246
  async function startRemoteAccountLogin(opts) {
13379
14247
  if (opts.signal?.aborted) throw new RemoteAccountLoginCancelled();
13380
14248
  const origin = (opts.origin ?? remoteAccountHttpOrigin()).replace(/\/+$/, "");
13381
- const state = randomBytes8(16).toString("hex");
14249
+ const state = randomBytes12(16).toString("hex");
13382
14250
  const timeoutMs = opts.timeoutMs ?? 5 * 6e4;
13383
14251
  const pollIntervalMs = opts.pollIntervalMs ?? 400;
13384
14252
  const linkToken = opts.linkToken?.trim() ?? "";
@@ -13392,7 +14260,7 @@ async function startRemoteAccountLogin(opts) {
13392
14260
  ...linkToken ? { accountToken: linkToken } : {}
13393
14261
  })
13394
14262
  });
13395
- const startBody = await readJson3(started, startUrl);
14263
+ const startBody = await readJson4(started, startUrl);
13396
14264
  if (!started.ok || !startBody.url) {
13397
14265
  throw new Error(startBody.error || `Could not start sign-in (HTTP ${started.status}).`);
13398
14266
  }
@@ -13441,7 +14309,7 @@ async function disconnectRemoteAccount(opts) {
13441
14309
 
13442
14310
  // src/slack/outbound-watch.ts
13443
14311
  import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
13444
- import { join as join8 } from "path";
14312
+ import { join as join10 } from "path";
13445
14313
  var MAX_WATCHES = 40;
13446
14314
  var MAX_REPLIES_PER_WATCH = 30;
13447
14315
  var WATCH_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -13449,7 +14317,7 @@ var POLL_INTERVAL_MS = 12e3;
13449
14317
  var lastPollMs = 0;
13450
14318
  var nameCache = /* @__PURE__ */ new Map();
13451
14319
  function storePath3() {
13452
- return join8(appDataDir(), "slack-outbound-watch.json");
14320
+ return join10(appDataDir(), "slack-outbound-watch.json");
13453
14321
  }
13454
14322
  function watchId(teamId, channelId, ts) {
13455
14323
  return `${teamId}:${channelId}:${ts}`;
@@ -13516,7 +14384,7 @@ async function continueSourceThread(threadId, prompt) {
13516
14384
  await continueOnReply(threadId, prompt);
13517
14385
  return;
13518
14386
  }
13519
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-IYXIWNB5.js");
14387
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
13520
14388
  await getOrchestrator2().send(threadId, prompt);
13521
14389
  } catch {
13522
14390
  }
@@ -13798,6 +14666,7 @@ export {
13798
14666
  AbleTimeOAuthCancelledError,
13799
14667
  BAKED_ABLETIME_OAUTH_CLIENT_ID,
13800
14668
  BAKED_REMOTE_RELAY_URL,
14669
+ BAKED_SLACK_CLIENT_ID,
13801
14670
  BAKED_SLACK_RELAY_URL,
13802
14671
  BASE_ALLOWED_TOOLS,
13803
14672
  BRIGHTSY_MCP_ALLOWED_TOOLS,
@@ -14102,6 +14971,7 @@ export {
14102
14971
  createOrUpdatePr,
14103
14972
  createPrStack,
14104
14973
  createSchedule,
14974
+ createSlackOrgApp,
14105
14975
  createThread,
14106
14976
  createThreadWorktree,
14107
14977
  currentBranch,
@@ -14525,6 +15395,7 @@ export {
14525
15395
  mergePrStack,
14526
15396
  mergeSetupOutput,
14527
15397
  mergeSideboardIntoMcpServersJson,
15398
+ mergeSlackClientIds,
14528
15399
  mergeUsage,
14529
15400
  messagePartParentId,
14530
15401
  messagesForCompactArchive,
@@ -14732,6 +15603,7 @@ export {
14732
15603
  saveAppSettings,
14733
15604
  saveLinearOAuth,
14734
15605
  saveRemotePhoneToken,
15606
+ saveSlackOrgCredentials,
14735
15607
  saveWorktreeRunPorts,
14736
15608
  scheduleNeedsCaffeinate,
14737
15609
  schedulesPath,