@desplega.ai/slack-mock 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,7 +38,7 @@ Talk to the bot as a human and watch the thread:
38
38
  ```bash
39
39
  curl -X POST http://127.0.0.1:4040/mock/messages -H 'content-type: application/json' \
40
40
  -d '{"channel":"general","user":"alice","text":"<@U0BOT00000> hello"}'
41
- open http://127.0.0.1:4040/c/general # live view (add ?refresh=2)
41
+ open http://127.0.0.1:4040/c/general # live view: new messages arrive over SSE and flash (?live=0 turns it off, ?refresh=2 polls instead)
42
42
  bun src/cli.ts screenshot http://127.0.0.1:4040/c/general --out general.png
43
43
  ```
44
44
 
@@ -104,6 +104,35 @@ bun run lint
104
104
  bun run build # dist/ (JS for Bun + .d.ts). CI publishes to npm when the version in package.json changes on main
105
105
  ```
106
106
 
107
+ ## Hosted demo
108
+
109
+ https://demo.slack-mock.dev runs `scripts/demo-server.ts`: the mock plus a small
110
+ demo bot (`scripts/demo-bot.ts`) in one container, deployed to Fly.io from
111
+ `main` by `.github/workflows/deploy.yml` (`fly.toml`, `Dockerfile`). State
112
+ lives in a JSONL journal on a volume and resets daily. Run it yourself:
113
+
114
+ ```bash
115
+ docker build -t slack-mock-demo . && docker run -p 8080:8080 -e ADMIN_AUTH=demo:secret slack-mock-demo
116
+ ```
117
+
118
+ `PUBLIC_URL`, `ADMIN_AUTH` (basic auth for the UI and `/mock/*`), `DATA_FILE`,
119
+ `RESET_EVERY_HOURS` and `MANIFEST` configure it. The same knobs exist on the
120
+ CLI (`--public-url`, `--auth`) and as `SlackMockOptions` (`publicUrl`, `adminAuth`).
121
+
122
+ The same image also serves a workspace for an *external* bot, the Agent Swarm demo at
123
+ https://swarm-demo.slack-mock.dev (`fly.swarm.toml`, app `slack-mock-swarm`). Knobs that make
124
+ that possible, all read by `scripts/demo-server.ts`:
125
+
126
+ | Env | Effect |
127
+ |---|---|
128
+ | `DEMO_BOT=off` | Skip the built-in demo bot; some other Bolt app connects over Socket Mode. |
129
+ | `SLACK_MOCK_BOT_TOKEN`, `SLACK_MOCK_APP_TOKEN` | The tokens the app must present (`botToken` / `appToken` options). The defaults are public, so set these on any shared host. |
130
+ | `APP_NAME` | Bot display name (`appName`). |
131
+ | `SEED_FILE` | JSON with `users`, `channels`, `messages` and `driver.prompts` (`scripts/seed.ts`); replaces the built-in `#general` and is applied whenever the journal has no channels, so the workspace comes back after every reset. `seeds/agent-swarm-demo.json` is the shipped example. |
132
+ | `UI_PUBLIC=true` | Keep `/` and `/c/...` readable without credentials while `ADMIN_AUTH` still gates `/mock/*` (`publicUi` option). The composer then shows a sign-in instead of the browser's basic-auth prompt. |
133
+ | `PRESENTER_AUTH` | `user:password` that may only `POST /mock/messages` and `GET /mock/presenter` (`presenterAuth` option). Lets a presenter drive a public-read workspace from the composer without the admin credential. Opening `/c/<channel>#presenter=user:password` signs that browser in. |
134
+ | `DRIVER_INTERVAL_MINUTES` | Every N minutes post the next `driver.prompts` entry as that user, mentioning the bot, while an app is connected (`scripts/driver.ts`). `0` disables it. |
135
+
107
136
  ## Docs
108
137
 
109
138
  - `skills/slack-mock/SKILL.md`: how to use the package from another repo (agents and humans).
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
  import {
4
4
  SlackMock
5
- } from "./index-thgwpw70.js";
5
+ } from "./index-eyfkn32t.js";
6
6
  import {
7
7
  screenshot
8
8
  } from "./index-v7mbr1cx.js";
@@ -12,7 +12,8 @@ import { parseArgs } from "util";
12
12
  var USAGE = `slack-mock: a mock Slack server (Web API + Socket Mode) for testing bots
13
13
 
14
14
  Usage:
15
- slack-mock serve [--port 4040] [--host 127.0.0.1] [--data ./data/slack.jsonl] [--manifest app.json] [--no-seed] [--quiet] [--panel 50]
15
+ slack-mock serve [--port 4040] [--host 127.0.0.1] [--data ./data/slack.jsonl] [--manifest app.json]
16
+ [--no-seed] [--quiet] [--panel 50] [--auth user:pass] [--public-url https://mock.example.com]
16
17
  slack-mock screenshot <url> --out shot.png [--width 800] [--height 1000]
17
18
 
18
19
  serve prints the env vars to give your bot (SLACK_BOT_TOKEN, SLACK_APP_TOKEN, SLACK_API_URL)
@@ -32,11 +33,15 @@ async function main(argv) {
32
33
  manifest: { type: "string" },
33
34
  "no-seed": { type: "boolean", default: false },
34
35
  quiet: { type: "boolean", default: false },
35
- panel: { type: "string" }
36
+ panel: { type: "string" },
37
+ auth: { type: "string" },
38
+ "public-url": { type: "string" }
36
39
  }
37
40
  });
38
41
  const mock = await SlackMock.start({
39
42
  panelWidth: values.panel,
43
+ adminAuth: values.auth,
44
+ publicUrl: values["public-url"],
40
45
  port: Number(values.port),
41
46
  host: values.host,
42
47
  dataFile: values.data,
@@ -1545,6 +1545,19 @@ a:hover{text-decoration:underline}
1545
1545
  .sm-eph-note{font-size:12px;color:#8a6d1a;margin-top:4px}
1546
1546
  .sm-stream{display:inline-block;margin-left:4px;color:#616061;font-weight:700;animation:sm-pulse 1s ease-in-out infinite}
1547
1547
  @keyframes sm-pulse{0%,100%{opacity:.25}50%{opacity:1}}
1548
+ @keyframes sm-flash{0%{background:#fff3bf}100%{background:transparent}}
1549
+ @keyframes sm-flash-soft{0%{background:#eaf3ff}100%{background:transparent}}
1550
+ .sm-msg-new{animation:sm-flash 2.4s ease-out}
1551
+ .sm-msg-changed{animation:sm-flash-soft .9s ease-out}
1552
+ @media (prefers-reduced-motion:reduce){.sm-msg-new,.sm-msg-changed{animation:none}}
1553
+ .sm-live{font-size:11px;font-weight:600;color:#2eb67d;margin-left:10px;vertical-align:middle}
1554
+ .sm-live-off{color:#e8912d}
1555
+ .sm-composer-lock{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 0 2px;font-size:13px;color:#616061}
1556
+ .sm-composer-lock[hidden]{display:none}
1557
+ .sm-composer-lock input{font:inherit;font-size:13px;padding:5px 8px;border:1px solid #bbb;border-radius:4px;width:130px}
1558
+ .sm-composer-lock .sm-lock-go{font:inherit;font-size:13px;padding:5px 10px;border:1px solid #1264a3;border-radius:4px;background:#1264a3;color:#fff;cursor:pointer}
1559
+ .sm-composer-lock .sm-err{color:#e01e5a}
1560
+ .sm-composer-text:disabled{background:#f8f8f8;color:#888}
1548
1561
 
1549
1562
  .sm-pill{background:#e8f5fa;color:#1264a3;border-radius:3px;padding:0 2px}
1550
1563
  .sm-link{color:#1264a3}
@@ -1818,7 +1831,7 @@ function renderMessage(store, ctx, m, opts, flags = {}) {
1818
1831
  }
1819
1832
  const streaming = m.streaming_state === "in_progress" ? `<span class="sm-stream" title="streaming">\u2022\u2022\u2022</span>` : "";
1820
1833
  const open = flags.openTs && flags.openTs === m.ts ? " sm-msg-open" : "";
1821
- return `<div class="sm-msg${flags.ephemeral ? " sm-msg-eph" : ""}${open}">${avatarHtml(m, name)}<div class="sm-msg-body"><div class="sm-msg-head"><span class="sm-name">${escapeHtml(name)}</span>${isApp ? `<span class="sm-badge">APP</span>` : ""}<span class="sm-time">${timeOf(m.ts)}</span>${streaming}</div>${body.join("")}</div></div>`;
1834
+ return `<div class="sm-msg${flags.ephemeral ? " sm-msg-eph" : ""}${open}" data-ts="${escapeHtml(m.ts)}">${avatarHtml(m, name)}<div class="sm-msg-body"><div class="sm-msg-head"><span class="sm-name">${escapeHtml(name)}</span>${isApp ? `<span class="sm-badge">APP</span>` : ""}<span class="sm-time">${timeOf(m.ts)}</span>${streaming}</div>${body.join("")}</div></div>`;
1822
1835
  }
1823
1836
  function renderMessageList(store, ctx, messages, opts, flags = {}) {
1824
1837
  const out = [];
@@ -1910,7 +1923,9 @@ function composer(store, opts, channel, threadTs) {
1910
1923
  const options = users.map((u, i) => `<option value="${escapeHtml(u.id)}"${i === 0 ? " selected" : ""}>${escapeHtml(u.real_name || u.name)}</option>`).join("");
1911
1924
  const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
1912
1925
  const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
1913
- return `<div class="sm-composer" data-channel="${escapeHtml(channel.id)}"${thread}><div class="sm-mentions"></div><div class="sm-composer-box"><textarea class="sm-composer-text" rows="2" placeholder="${escapeHtml(placeholder)}"></textarea><div class="sm-composer-row"><select class="sm-composer-user" aria-label="Post as">${options}</select><button type="button" class="sm-composer-send">Send</button></div></div><div class="sm-composer-hint">Enter to send, Shift+Enter for a new line, @name to mention</div></div>`;
1926
+ const gated = opts.writeGated ? ' data-gated="1"' : "";
1927
+ const lock = opts.writeGated ? `<div class="sm-composer-lock" hidden><span>Reading is open. Sign in to post.</span><input class="sm-lock-user" placeholder="user" autocomplete="username"><input class="sm-lock-pass" type="password" placeholder="password" autocomplete="current-password"><button type="button" class="sm-lock-go">Sign in</button><span class="sm-err"></span></div>` : "";
1928
+ return `<div class="sm-composer" data-channel="${escapeHtml(channel.id)}"${thread}${gated}><div class="sm-mentions"></div><div class="sm-composer-box"><textarea class="sm-composer-text" rows="2" placeholder="${escapeHtml(placeholder)}" data-placeholder="${escapeHtml(placeholder)}"></textarea><div class="sm-composer-row"><select class="sm-composer-user" aria-label="Post as">${options}</select><button type="button" class="sm-composer-send">Send</button></div></div>${lock}<div class="sm-composer-hint">Enter to send, Shift+Enter for a new line, @name to mention<span class="sm-lock-state"></span></div></div>`;
1914
1929
  }
1915
1930
  function mentionData(store) {
1916
1931
  const users = [...store.users.values()].filter((u) => !u.deleted).map((u) => ({
@@ -1941,7 +1956,31 @@ if(handle){
1941
1956
  var raw=document.getElementById("sm-users");
1942
1957
  var PEOPLE=(raw?JSON.parse(raw.textContent||"[]"):[]).concat([{name:"here",real:"Notify everyone online",initials:"@",color:"#616061"},{name:"channel",real:"Notify everyone in the channel",initials:"@",color:"#616061"}]);
1943
1958
  function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&amp;":c==="<"?"&lt;":c===">"?"&gt;":"&quot;"})}
1944
- function send(box){var t=box.querySelector(".sm-composer-text"),text=t.value.trim();if(!text)return;var body={channel:box.dataset.channel,user:box.querySelector(".sm-composer-user").value,text:text};if(box.dataset.thread)body.thread_ts=box.dataset.thread;t.disabled=true;fetch("/mock/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body)}).then(function(){location.reload()}).catch(function(){t.disabled=false})}
1959
+ var GATED=${opts.writeGated ? "true" : "false"},LIVE=${opts.live !== false && !opts.refreshSec ? "true" : "false"},CK="sm-presenter";
1960
+ function cred(){try{return localStorage.getItem(CK)||""}catch(e){return ""}}
1961
+ function setCred(v){try{if(v)localStorage.setItem(CK,v);else localStorage.removeItem(CK)}catch(e){}}
1962
+ (function(){var m=/[#&]presenter=([^&]+)/.exec(location.hash||"");if(m){setCred(btoa(decodeURIComponent(m[1])));history.replaceState(null,"",location.pathname+location.search)}})();
1963
+ function authHeaders(h){var c=cred();if(c)h.authorization="Basic "+c;return h}
1964
+ function lockUi(){document.querySelectorAll(".sm-composer").forEach(function(box){var locked=GATED&&!cred(),lock=box.querySelector(".sm-composer-lock"),ta=box.querySelector(".sm-composer-text"),btn=box.querySelector(".sm-composer-send"),state=box.querySelector(".sm-lock-state");if(lock)lock.hidden=!locked;ta.disabled=locked;btn.disabled=locked;ta.placeholder=locked?"Sign in to post":(ta.dataset.placeholder||"");if(state)state.innerHTML=GATED&&!locked?' \xB7 signed in \xB7 <a href="#" class="sm-lock-out">Sign out</a>':""})}
1965
+ function signIn(box){if(!box)return;var u=box.querySelector(".sm-lock-user").value.trim(),p=box.querySelector(".sm-lock-pass").value,err=box.querySelector(".sm-err");if(!u){err.textContent="Enter the presenter user";return}var c=btoa(u+":"+p);err.textContent="";fetch("/mock/presenter",{headers:{authorization:"Basic "+c}}).then(function(r){if(!r.ok)throw new Error(r.status===401||r.status===403?"Wrong user or password":"Sign-in failed ("+r.status+")");setCred(c);lockUi();box.querySelector(".sm-composer-text").focus()}).catch(function(e){err.textContent=e.message})}
1966
+ document.addEventListener("click",function(e){var out=e.target.closest(".sm-lock-out");if(out){e.preventDefault();setCred("");lockUi();return}var go=e.target.closest(".sm-lock-go");if(go)signIn(go.closest(".sm-composer"))});
1967
+ document.addEventListener("keydown",function(e){var c=e.target.classList;if(e.key==="Enter"&&c&&(c.contains("sm-lock-pass")||c.contains("sm-lock-user"))){e.preventDefault();signIn(e.target.closest(".sm-composer"))}});
1968
+ lockUi();
1969
+ var pending=null;
1970
+ function refresh(){if(pending)return;pending=setTimeout(function(){pending=null;fetch(location.href,{headers:{accept:"text/html"},credentials:"same-origin"}).then(function(r){return r.ok?r.text():Promise.reject(r.status)}).then(apply).catch(function(){})},120)}
1971
+ function apply(html){var doc=new DOMParser().parseFromString(html,"text/html");[".sm-side",".sm-page",".sm-panel-body"].forEach(function(sel){var cur=document.querySelector(sel),nxt=doc.querySelector(sel);if(!cur||!nxt)return;var seen={};cur.querySelectorAll(".sm-msg[data-ts]").forEach(function(el){el.classList.remove("sm-msg-new","sm-msg-changed");seen[el.dataset.ts]=el.outerHTML});var atBottom=cur.scrollHeight-cur.scrollTop-cur.clientHeight<80;cur.innerHTML=nxt.innerHTML;cur.querySelectorAll(".sm-msg[data-ts]").forEach(function(el){var prev=seen[el.dataset.ts];if(prev===undefined)el.classList.add("sm-msg-new");else if(prev!==el.outerHTML)el.classList.add("sm-msg-changed")});if(atBottom)cur.scrollTop=cur.scrollHeight});if(doc.title)document.title=doc.title}
1972
+ if(LIVE&&window.EventSource){
1973
+ var box0=document.querySelector(".sm-composer"),pm=/^\\/c\\/([^/]+)/.exec(location.pathname),chan=box0?box0.dataset.channel:(pm?decodeURIComponent(pm[1]):null);
1974
+ if(chan){
1975
+ var h1=document.querySelector(".sm-top h1"),dot=null;
1976
+ if(h1){dot=document.createElement("span");dot.className="sm-live";dot.textContent="\u25CF live";h1.appendChild(dot)}
1977
+ var es=new EventSource("/c/"+encodeURIComponent(chan)+"/events"),down=false;
1978
+ es.addEventListener("change",refresh);
1979
+ es.onopen=function(){if(dot){dot.textContent="\u25CF live";dot.classList.remove("sm-live-off")}if(down){down=false;refresh()}};
1980
+ es.onerror=function(){down=true;if(dot){dot.textContent="\u25CF reconnecting";dot.classList.add("sm-live-off")}};
1981
+ }
1982
+ }
1983
+ function send(box){var t=box.querySelector(".sm-composer-text"),text=t.value.trim();if(!text||t.disabled)return;var body={channel:box.dataset.channel,user:box.querySelector(".sm-composer-user").value,text:text};if(box.dataset.thread)body.thread_ts=box.dataset.thread;t.disabled=true;fetch("/mock/messages",{method:"POST",headers:authHeaders({"content-type":"application/json"}),body:JSON.stringify(body)}).then(function(r){t.disabled=false;if(r.status===401||r.status===403){setCred("");lockUi();var err=box.querySelector(".sm-err");if(err)err.textContent="Not signed in, or the credential changed. Sign in to post.";return}if(!r.ok)throw new Error("send failed "+r.status);t.value="";if(LIVE)refresh();else location.reload()}).catch(function(){t.disabled=false})}
1945
1984
  document.querySelectorAll(".sm-composer").forEach(function(box){
1946
1985
  var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
1947
1986
  function close(){items=[];menu.style.display="none"}
@@ -1961,6 +2000,11 @@ document.querySelectorAll(".sm-composer").forEach(function(box){
1961
2000
  ta.addEventListener("blur",function(){setTimeout(close,150)});
1962
2001
  menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
1963
2002
  ta.addEventListener("keydown",function(e){
2003
+ if(e.key==="Backspace"&&ta.selectionStart===ta.selectionEnd&&ta.selectionStart>0){
2004
+ var pos=ta.selectionStart,before=ta.value.slice(0,pos),hit="";
2005
+ for(var k=0;k<PEOPLE.length;k++){var tok="@"+PEOPLE[k].name;var cand=before.endsWith(tok)?tok:"";if(cand&&cand.length>hit.length){var at=before.length-cand.length;if(at===0||/s/.test(before.charAt(at-1)))hit=cand}}
2006
+ if(hit){e.preventDefault();ta.value=before.slice(0,before.length-hit.length)+ta.value.slice(pos);ta.selectionStart=ta.selectionEnd=pos-hit.length;close();return}
2007
+ }
1964
2008
  if(items.length){
1965
2009
  if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
1966
2010
  if(e.key==="ArrowUp"){e.preventDefault();active=(active-1+items.length)%items.length;paint();return}
@@ -2915,9 +2959,38 @@ class SlackMock {
2915
2959
  });
2916
2960
  this.log(`listening on ${this.baseUrl}`);
2917
2961
  }
2918
- get baseUrl() {
2962
+ get localUrl() {
2919
2963
  return `http://${this.server.hostname}:${this.server.port}`;
2920
2964
  }
2965
+ get baseUrl() {
2966
+ return (this.opts.publicUrl ?? this.localUrl).replace(/\/$/, "");
2967
+ }
2968
+ publicBase(req) {
2969
+ const host = req.headers.get("host");
2970
+ if (!host)
2971
+ return this.baseUrl;
2972
+ const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || new URL(req.url).protocol.replace(":", "");
2973
+ const hostname = host.replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
2974
+ const loopback = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "0.0.0.0";
2975
+ if (loopback)
2976
+ return `${proto}://${host}`;
2977
+ return this.opts.publicUrl ? this.baseUrl : `${proto}://${host}`;
2978
+ }
2979
+ authorizedAdmin(req) {
2980
+ const expected = this.opts.adminAuth;
2981
+ if (!expected)
2982
+ return true;
2983
+ return basicAuthMatches(req, expected);
2984
+ }
2985
+ authorizedPresenter(req) {
2986
+ if (this.authorizedAdmin(req))
2987
+ return true;
2988
+ const expected = this.opts.presenterAuth;
2989
+ return Boolean(expected) && basicAuthMatches(req, expected);
2990
+ }
2991
+ get writeGated() {
2992
+ return this.opts.publicUi === true && Boolean(this.opts.adminAuth);
2993
+ }
2921
2994
  get apiUrl() {
2922
2995
  return `${this.baseUrl}/api/`;
2923
2996
  }
@@ -2935,6 +3008,9 @@ class SlackMock {
2935
3008
  get bot() {
2936
3009
  return this.store.bot;
2937
3010
  }
3011
+ get connectionCount() {
3012
+ return this.hub.connectionCount;
3013
+ }
2938
3014
  get team() {
2939
3015
  return this.store.team;
2940
3016
  }
@@ -2948,6 +3024,12 @@ class SlackMock {
2948
3024
  const path = url.pathname;
2949
3025
  this.lastRequestAt = Date.now();
2950
3026
  try {
3027
+ const isUiSurface = path === "/" || path === "" || path.startsWith("/c/");
3028
+ const isAdminSurface = path.startsWith("/mock/") || isUiSurface && !this.opts.publicUi;
3029
+ const isPresenterRoute = path === "/mock/messages" && req.method === "POST" || path === "/mock/presenter";
3030
+ const allowed = isPresenterRoute ? this.authorizedPresenter(req) : this.authorizedAdmin(req);
3031
+ if (isAdminSurface && !allowed)
3032
+ return denied(req, path);
2951
3033
  if (path.startsWith("/link/") || path === "/link") {
2952
3034
  const ticket = url.searchParams.get("ticket") ?? "";
2953
3035
  if (!this.hub.tickets.has(ticket))
@@ -2958,7 +3040,7 @@ class SlackMock {
2958
3040
  return new Response("upgrade failed", { status: 400 });
2959
3041
  }
2960
3042
  if (path.startsWith("/api/"))
2961
- return await this.handleApi(req, path.slice(5));
3043
+ return await this.handleApi(req, path.slice(5), this.publicBase(req));
2962
3044
  if (path.startsWith("/upload/v1/"))
2963
3045
  return await this.handleUpload(req, path.slice("/upload/v1/".length));
2964
3046
  if (path.startsWith("/files-pri/"))
@@ -2967,6 +3049,14 @@ class SlackMock {
2967
3049
  return await this.handleResponseUrl(req, path.slice("/actions/".length));
2968
3050
  if (path.startsWith("/mock/"))
2969
3051
  return await this.handleAdmin(req, path.slice(6), url);
3052
+ const events = /^\/c\/([^/]+)\/events\/?$/.exec(path);
3053
+ if (events) {
3054
+ const channel = this.store.channelByName(events[1])?.id ?? events[1];
3055
+ if (!this.store.channels.has(channel))
3056
+ return new Response("channel not found", { status: 404 });
3057
+ server.timeout(req, 0);
3058
+ return this.handleEvents(channel);
3059
+ }
2970
3060
  return this.handleUi(path, url);
2971
3061
  } catch (e) {
2972
3062
  this.log(`unhandled error on ${req.method} ${path}: ${e instanceof Error ? e.stack : e}`);
@@ -2984,7 +3074,7 @@ class SlackMock {
2984
3074
  }
2985
3075
  return null;
2986
3076
  }
2987
- async handleApi(req, method) {
3077
+ async handleApi(req, method, baseUrl) {
2988
3078
  let args = {};
2989
3079
  try {
2990
3080
  args = await parseArgs(req);
@@ -3039,8 +3129,8 @@ class SlackMock {
3039
3129
  const ctx = {
3040
3130
  store: this.store,
3041
3131
  hub: this.hub,
3042
- baseUrl: this.baseUrl,
3043
- wsUrl: this.baseUrl.replace(/^http/, "ws"),
3132
+ baseUrl,
3133
+ wsUrl: baseUrl.replace(/^http/, "ws"),
3044
3134
  actor,
3045
3135
  triggerIds: this.triggerIds,
3046
3136
  pendingUploads: this.pendingUploads
@@ -3059,6 +3149,7 @@ class SlackMock {
3059
3149
  }
3060
3150
  }
3061
3151
  async handleUpload(req, fileId) {
3152
+ const baseUrl = this.publicBase(req);
3062
3153
  const pending = this.pendingUploads.get(fileId);
3063
3154
  if (!pending)
3064
3155
  return new Response("unknown upload", { status: 404 });
@@ -3081,7 +3172,7 @@ class SlackMock {
3081
3172
  name: pending.name,
3082
3173
  user: pending.user,
3083
3174
  bytes,
3084
- baseUrl: this.baseUrl
3175
+ baseUrl
3085
3176
  });
3086
3177
  return new Response("OK");
3087
3178
  }
@@ -3168,7 +3259,9 @@ class SlackMock {
3168
3259
  refreshSec: Number.isFinite(refresh) && refresh > 0 ? refresh : undefined,
3169
3260
  connections: this.hub.connectionCount,
3170
3261
  panelWidth: panel ? /^\d+$/.test(panel) ? `${panel}%` : /^\d+(px|%|vw|rem)$/.test(panel) ? panel : undefined : undefined,
3171
- threadView: url.searchParams.has("full") ? "full" : "panel"
3262
+ threadView: url.searchParams.has("full") ? "full" : "panel",
3263
+ live: url.searchParams.get("live") !== "0",
3264
+ writeGated: this.writeGated
3172
3265
  };
3173
3266
  let html;
3174
3267
  if (path === "/" || path === "")
@@ -3184,6 +3277,53 @@ class SlackMock {
3184
3277
  }
3185
3278
  return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
3186
3279
  }
3280
+ handleEvents(channelId) {
3281
+ const enc = new TextEncoder;
3282
+ let unsubscribe = () => {};
3283
+ let ping;
3284
+ const stop = () => {
3285
+ unsubscribe();
3286
+ if (ping)
3287
+ clearInterval(ping);
3288
+ };
3289
+ const stream = new ReadableStream({
3290
+ start: (controller) => {
3291
+ const send = (event, data) => {
3292
+ try {
3293
+ controller.enqueue(enc.encode(`event: ${event}
3294
+ data: ${JSON.stringify(data)}
3295
+
3296
+ `));
3297
+ } catch {
3298
+ stop();
3299
+ }
3300
+ };
3301
+ send("hello", { channel: channelId });
3302
+ unsubscribe = this.store.onChange((change) => {
3303
+ if (change.kind === "api.call" || change.kind.startsWith("view."))
3304
+ return;
3305
+ const scoped = changeChannel(change);
3306
+ if (scoped && scoped !== channelId)
3307
+ return;
3308
+ send("change", {
3309
+ kind: change.kind,
3310
+ channel: scoped ?? null,
3311
+ ts: "message" in change ? change.message.ts : undefined
3312
+ });
3313
+ });
3314
+ ping = setInterval(() => send("ping", Date.now()), 25000);
3315
+ ping.unref?.();
3316
+ },
3317
+ cancel: stop
3318
+ });
3319
+ return new Response(stream, {
3320
+ headers: {
3321
+ "content-type": "text/event-stream; charset=utf-8",
3322
+ "cache-control": "no-cache, no-transform",
3323
+ "x-accel-buffering": "no"
3324
+ }
3325
+ });
3326
+ }
3187
3327
  isSubscribed(type) {
3188
3328
  return this.subscribed.has(type);
3189
3329
  }
@@ -3318,9 +3458,16 @@ class SlackMock {
3318
3458
  }
3319
3459
  resolveMentions(text) {
3320
3460
  const byName = new Map;
3321
- for (const u of this.store.users.values())
3461
+ for (const u of this.store.users.values()) {
3462
+ if (u.deleted)
3463
+ continue;
3322
3464
  byName.set(u.name.toLowerCase(), u.id);
3323
- return text.replace(/(^|[^<\w])@([\w.-]+)/g, (whole, lead, name) => {
3465
+ if (u.real_name)
3466
+ byName.set(u.real_name.toLowerCase(), u.id);
3467
+ }
3468
+ const names = [...byName.keys(), "here", "channel", "everyone"].sort((a, b) => b.length - a.length).map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3469
+ const re = new RegExp(`(^|[^<\\w])@(${names.join("|")})(?![\\w.-])`, "gi");
3470
+ return text.replace(re, (whole, lead, name) => {
3324
3471
  const lower = name.toLowerCase();
3325
3472
  if (lower === "here" || lower === "channel" || lower === "everyone")
3326
3473
  return `${lead}<!${lower}>`;
@@ -3616,6 +3763,8 @@ class SlackMock {
3616
3763
  const json = (body2, status = 200) => Response.json(body2, { status });
3617
3764
  const body = req.method === "POST" ? await req.json().catch(() => ({})) : {};
3618
3765
  try {
3766
+ if (path === "presenter")
3767
+ return json({ ok: true, role: this.authorizedAdmin(req) ? "admin" : "presenter" });
3619
3768
  if (path === "state") {
3620
3769
  return json({
3621
3770
  team: this.store.team,
@@ -3689,5 +3838,30 @@ function findButton(blocks, actionId) {
3689
3838
  }
3690
3839
  return;
3691
3840
  }
3841
+ function changeChannel(change) {
3842
+ if ("message" in change)
3843
+ return change.message.channel;
3844
+ if ("channel" in change)
3845
+ return typeof change.channel === "string" ? change.channel : change.channel.id;
3846
+ return;
3847
+ }
3848
+ function basicAuthMatches(req, expected) {
3849
+ const header = req.headers.get("authorization") ?? "";
3850
+ if (!header.toLowerCase().startsWith("basic "))
3851
+ return false;
3852
+ try {
3853
+ return Buffer.from(header.slice(6).trim(), "base64").toString("utf8") === expected;
3854
+ } catch {
3855
+ return false;
3856
+ }
3857
+ }
3858
+ function denied(req, path) {
3859
+ if (path.startsWith("/mock/") && req.headers.has("authorization"))
3860
+ return new Response("forbidden", { status: 403 });
3861
+ return new Response("authentication required", {
3862
+ status: 401,
3863
+ headers: { "www-authenticate": 'Basic realm="slack-mock"' }
3864
+ });
3865
+ }
3692
3866
 
3693
3867
  export { SlackApiError, Store, SlackMock };
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  SlackApiError,
4
4
  SlackMock,
5
5
  Store
6
- } from "./index-thgwpw70.js";
6
+ } from "./index-eyfkn32t.js";
7
7
  import {
8
8
  findChrome,
9
9
  screenshot
@@ -21,5 +21,9 @@ export interface RenderOptions {
21
21
  panelWidth?: string;
22
22
  /** "panel" (default) shows the thread beside the channel, "full" shows it alone. */
23
23
  threadView?: "panel" | "full";
24
+ /** Push changes over SSE and flash new messages (default true; `?live=0` turns it off). */
25
+ live?: boolean;
26
+ /** Reading is open but posting needs a credential: the composer shows a presenter sign-in. */
27
+ writeGated?: boolean;
24
28
  }
25
29
  export declare function renderPage(store: Store, view: View, opts?: RenderOptions): string;
package/dist/server.d.ts CHANGED
@@ -41,6 +41,26 @@ export interface SlackMockOptions extends StoreOptions {
41
41
  eventDelayMs?: number;
42
42
  /** Default width of the thread side panel in the HTML UI, e.g. "50%" or "640px". `?panel=` overrides per request. */
43
43
  panelWidth?: string;
44
+ /**
45
+ * Public base URL (e.g. "https://demo.slack-mock.dev") used in every URL the mock hands out:
46
+ * Socket Mode link, file download and upload URLs, response_urls, permalinks. When unset, URLs
47
+ * are derived from each request's Host header (honouring X-Forwarded-Proto), falling back to the
48
+ * local address.
49
+ */
50
+ publicUrl?: string;
51
+ /** "user:password" HTTP basic auth for the HTML UI and the /mock admin API (the Slack API stays token-based). */
52
+ adminAuth?: string;
53
+ /**
54
+ * Keep the HTML UI ("/" and "/c/...") readable without credentials while `adminAuth` still gates
55
+ * the /mock admin API. Default false: `adminAuth` covers both surfaces.
56
+ */
57
+ publicUi?: boolean;
58
+ /**
59
+ * "user:password" that may only post messages (`POST /mock/messages`) and check its role
60
+ * (`GET /mock/presenter`). With `publicUi` the HTML composer shows a sign-in for it, so a presenter
61
+ * can drive a public-read workspace without the admin credential. `adminAuth` always implies it.
62
+ */
63
+ presenterAuth?: string;
44
64
  log?: boolean | ((msg: string) => void);
45
65
  }
46
66
  export interface PostMessageInput {
@@ -102,7 +122,17 @@ export declare class SlackMock {
102
122
  static start(opts?: SlackMockOptions): Promise<SlackMock>;
103
123
  private seed;
104
124
  listen(): void;
125
+ /** Address of this process's listener, for in-process clients and tests. */
126
+ get localUrl(): string;
127
+ /** Base URL handed to bots and browsers: `publicUrl` when configured, else the local address. */
105
128
  get baseUrl(): string;
129
+ /** Base URL for links generated while serving `req`: publicUrl, else the request's own host. */
130
+ private publicBase;
131
+ private authorizedAdmin;
132
+ /** `presenterAuth` (or `adminAuth`) may post messages and read its role, nothing else. */
133
+ private authorizedPresenter;
134
+ /** Visitors can read the UI but posting needs a credential: the composer shows a sign-in. */
135
+ private get writeGated();
106
136
  get apiUrl(): string;
107
137
  get port(): number;
108
138
  /** Environment variables a Bolt app needs to talk to this mock. */
@@ -114,6 +144,8 @@ export declare class SlackMock {
114
144
  appToken: string;
115
145
  userToken?: string;
116
146
  };
147
+ /** Number of Socket Mode connections the app currently holds. */
148
+ get connectionCount(): number;
117
149
  get team(): {
118
150
  id: string;
119
151
  name: string;
@@ -128,6 +160,11 @@ export declare class SlackMock {
128
160
  private handleResponseUrl;
129
161
  private postAsBot;
130
162
  private handleUi;
163
+ /**
164
+ * Server-sent events for one channel: every store change that touches it, plus workspace-wide
165
+ * ones (users, files). The HTML UI listens here and re-fetches the page on each event.
166
+ */
167
+ private handleEvents;
131
168
  private isSubscribed;
132
169
  /** Manifest event name for a message in this channel: message.channels / groups / im / mpim. */
133
170
  private messageEventName;
@@ -152,6 +189,11 @@ export declare class SlackMock {
152
189
  private resolveChannel;
153
190
  private defaultHuman;
154
191
  /** Turn `@name` and `@here` / `@channel` in human-typed text into Slack mention syntax. */
192
+ /**
193
+ * Turn `@name` / `@Display Name` / `@here` into Slack mention syntax. Handles names with
194
+ * spaces (the app user is often "Agent Swarm"), matching the longest known name first,
195
+ * case-insensitively, against both `name` and `real_name`.
196
+ */
155
197
  resolveMentions(text: string): string;
156
198
  /** A human posts a message; resolves once the app acked the resulting events. */
157
199
  postMessage(input: PostMessageInput): Promise<SlackMessage>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@desplega.ai/slack-mock",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Mock Slack server (Web API + Socket Mode) for end-to-end testing Slack bots",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/cli.ts CHANGED
@@ -6,7 +6,8 @@ import { SlackMock } from "./server.ts";
6
6
  const USAGE = `slack-mock: a mock Slack server (Web API + Socket Mode) for testing bots
7
7
 
8
8
  Usage:
9
- slack-mock serve [--port 4040] [--host 127.0.0.1] [--data ./data/slack.jsonl] [--manifest app.json] [--no-seed] [--quiet] [--panel 50]
9
+ slack-mock serve [--port 4040] [--host 127.0.0.1] [--data ./data/slack.jsonl] [--manifest app.json]
10
+ [--no-seed] [--quiet] [--panel 50] [--auth user:pass] [--public-url https://mock.example.com]
10
11
  slack-mock screenshot <url> --out shot.png [--width 800] [--height 1000]
11
12
 
12
13
  serve prints the env vars to give your bot (SLACK_BOT_TOKEN, SLACK_APP_TOKEN, SLACK_API_URL)
@@ -28,10 +29,14 @@ async function main(argv: string[]): Promise<void> {
28
29
  "no-seed": { type: "boolean", default: false },
29
30
  quiet: { type: "boolean", default: false },
30
31
  panel: { type: "string" },
32
+ auth: { type: "string" },
33
+ "public-url": { type: "string" },
31
34
  },
32
35
  });
33
36
  const mock = await SlackMock.start({
34
37
  panelWidth: values.panel,
38
+ adminAuth: values.auth,
39
+ publicUrl: values["public-url"],
35
40
  port: Number(values.port),
36
41
  host: values.host,
37
42
  dataFile: values.data,
@@ -32,6 +32,10 @@ export interface RenderOptions {
32
32
  panelWidth?: string;
33
33
  /** "panel" (default) shows the thread beside the channel, "full" shows it alone. */
34
34
  threadView?: "panel" | "full";
35
+ /** Push changes over SSE and flash new messages (default true; `?live=0` turns it off). */
36
+ live?: boolean;
37
+ /** Reading is open but posting needs a credential: the composer shows a presenter sign-in. */
38
+ writeGated?: boolean;
35
39
  }
36
40
 
37
41
  const DEFAULT_PANEL_WIDTH = "50%";
@@ -148,6 +152,19 @@ a:hover{text-decoration:underline}
148
152
  .sm-eph-note{font-size:12px;color:#8a6d1a;margin-top:4px}
149
153
  .sm-stream{display:inline-block;margin-left:4px;color:#616061;font-weight:700;animation:sm-pulse 1s ease-in-out infinite}
150
154
  @keyframes sm-pulse{0%,100%{opacity:.25}50%{opacity:1}}
155
+ @keyframes sm-flash{0%{background:#fff3bf}100%{background:transparent}}
156
+ @keyframes sm-flash-soft{0%{background:#eaf3ff}100%{background:transparent}}
157
+ .sm-msg-new{animation:sm-flash 2.4s ease-out}
158
+ .sm-msg-changed{animation:sm-flash-soft .9s ease-out}
159
+ @media (prefers-reduced-motion:reduce){.sm-msg-new,.sm-msg-changed{animation:none}}
160
+ .sm-live{font-size:11px;font-weight:600;color:#2eb67d;margin-left:10px;vertical-align:middle}
161
+ .sm-live-off{color:#e8912d}
162
+ .sm-composer-lock{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 0 2px;font-size:13px;color:#616061}
163
+ .sm-composer-lock[hidden]{display:none}
164
+ .sm-composer-lock input{font:inherit;font-size:13px;padding:5px 8px;border:1px solid #bbb;border-radius:4px;width:130px}
165
+ .sm-composer-lock .sm-lock-go{font:inherit;font-size:13px;padding:5px 10px;border:1px solid #1264a3;border-radius:4px;background:#1264a3;color:#fff;cursor:pointer}
166
+ .sm-composer-lock .sm-err{color:#e01e5a}
167
+ .sm-composer-text:disabled{background:#f8f8f8;color:#888}
151
168
 
152
169
  .sm-pill{background:#e8f5fa;color:#1264a3;border-radius:3px;padding:0 2px}
153
170
  .sm-link{color:#1264a3}
@@ -459,7 +476,7 @@ function renderMessage(
459
476
  ? `<span class="sm-stream" title="streaming">•••</span>`
460
477
  : "";
461
478
  const open = flags.openTs && flags.openTs === m.ts ? " sm-msg-open" : "";
462
- return `<div class="sm-msg${flags.ephemeral ? " sm-msg-eph" : ""}${open}">${avatarHtml(m, name)}<div class="sm-msg-body"><div class="sm-msg-head"><span class="sm-name">${escapeHtml(name)}</span>${isApp ? `<span class="sm-badge">APP</span>` : ""}<span class="sm-time">${timeOf(m.ts)}</span>${streaming}</div>${body.join("")}</div></div>`;
479
+ return `<div class="sm-msg${flags.ephemeral ? " sm-msg-eph" : ""}${open}" data-ts="${escapeHtml(m.ts)}">${avatarHtml(m, name)}<div class="sm-msg-body"><div class="sm-msg-head"><span class="sm-name">${escapeHtml(name)}</span>${isApp ? `<span class="sm-badge">APP</span>` : ""}<span class="sm-time">${timeOf(m.ts)}</span>${streaming}</div>${body.join("")}</div></div>`;
463
480
  }
464
481
 
465
482
  function renderMessageList(
@@ -643,7 +660,11 @@ function composer(
643
660
  .join("");
644
661
  const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
645
662
  const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
646
- return `<div class="sm-composer" data-channel="${escapeHtml(channel.id)}"${thread}><div class="sm-mentions"></div><div class="sm-composer-box"><textarea class="sm-composer-text" rows="2" placeholder="${escapeHtml(placeholder)}"></textarea><div class="sm-composer-row"><select class="sm-composer-user" aria-label="Post as">${options}</select><button type="button" class="sm-composer-send">Send</button></div></div><div class="sm-composer-hint">Enter to send, Shift+Enter for a new line, @name to mention</div></div>`;
663
+ const gated = opts.writeGated ? ' data-gated="1"' : "";
664
+ const lock = opts.writeGated
665
+ ? `<div class="sm-composer-lock" hidden><span>Reading is open. Sign in to post.</span><input class="sm-lock-user" placeholder="user" autocomplete="username"><input class="sm-lock-pass" type="password" placeholder="password" autocomplete="current-password"><button type="button" class="sm-lock-go">Sign in</button><span class="sm-err"></span></div>`
666
+ : "";
667
+ return `<div class="sm-composer" data-channel="${escapeHtml(channel.id)}"${thread}${gated}><div class="sm-mentions"></div><div class="sm-composer-box"><textarea class="sm-composer-text" rows="2" placeholder="${escapeHtml(placeholder)}" data-placeholder="${escapeHtml(placeholder)}"></textarea><div class="sm-composer-row"><select class="sm-composer-user" aria-label="Post as">${options}</select><button type="button" class="sm-composer-send">Send</button></div></div>${lock}<div class="sm-composer-hint">Enter to send, Shift+Enter for a new line, @name to mention<span class="sm-lock-state"></span></div></div>`;
647
668
  }
648
669
 
649
670
  /** Mention targets for the composer autocomplete: every user, bots included. */
@@ -685,7 +706,31 @@ if(handle){
685
706
  var raw=document.getElementById("sm-users");
686
707
  var PEOPLE=(raw?JSON.parse(raw.textContent||"[]"):[]).concat([{name:"here",real:"Notify everyone online",initials:"@",color:"#616061"},{name:"channel",real:"Notify everyone in the channel",initials:"@",color:"#616061"}]);
687
708
  function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&amp;":c==="<"?"&lt;":c===">"?"&gt;":"&quot;"})}
688
- function send(box){var t=box.querySelector(".sm-composer-text"),text=t.value.trim();if(!text)return;var body={channel:box.dataset.channel,user:box.querySelector(".sm-composer-user").value,text:text};if(box.dataset.thread)body.thread_ts=box.dataset.thread;t.disabled=true;fetch("/mock/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body)}).then(function(){location.reload()}).catch(function(){t.disabled=false})}
709
+ var GATED=${opts.writeGated ? "true" : "false"},LIVE=${opts.live !== false && !opts.refreshSec ? "true" : "false"},CK="sm-presenter";
710
+ function cred(){try{return localStorage.getItem(CK)||""}catch(e){return ""}}
711
+ function setCred(v){try{if(v)localStorage.setItem(CK,v);else localStorage.removeItem(CK)}catch(e){}}
712
+ (function(){var m=/[#&]presenter=([^&]+)/.exec(location.hash||"");if(m){setCred(btoa(decodeURIComponent(m[1])));history.replaceState(null,"",location.pathname+location.search)}})();
713
+ function authHeaders(h){var c=cred();if(c)h.authorization="Basic "+c;return h}
714
+ function lockUi(){document.querySelectorAll(".sm-composer").forEach(function(box){var locked=GATED&&!cred(),lock=box.querySelector(".sm-composer-lock"),ta=box.querySelector(".sm-composer-text"),btn=box.querySelector(".sm-composer-send"),state=box.querySelector(".sm-lock-state");if(lock)lock.hidden=!locked;ta.disabled=locked;btn.disabled=locked;ta.placeholder=locked?"Sign in to post":(ta.dataset.placeholder||"");if(state)state.innerHTML=GATED&&!locked?' · signed in · <a href="#" class="sm-lock-out">Sign out</a>':""})}
715
+ function signIn(box){if(!box)return;var u=box.querySelector(".sm-lock-user").value.trim(),p=box.querySelector(".sm-lock-pass").value,err=box.querySelector(".sm-err");if(!u){err.textContent="Enter the presenter user";return}var c=btoa(u+":"+p);err.textContent="";fetch("/mock/presenter",{headers:{authorization:"Basic "+c}}).then(function(r){if(!r.ok)throw new Error(r.status===401||r.status===403?"Wrong user or password":"Sign-in failed ("+r.status+")");setCred(c);lockUi();box.querySelector(".sm-composer-text").focus()}).catch(function(e){err.textContent=e.message})}
716
+ document.addEventListener("click",function(e){var out=e.target.closest(".sm-lock-out");if(out){e.preventDefault();setCred("");lockUi();return}var go=e.target.closest(".sm-lock-go");if(go)signIn(go.closest(".sm-composer"))});
717
+ document.addEventListener("keydown",function(e){var c=e.target.classList;if(e.key==="Enter"&&c&&(c.contains("sm-lock-pass")||c.contains("sm-lock-user"))){e.preventDefault();signIn(e.target.closest(".sm-composer"))}});
718
+ lockUi();
719
+ var pending=null;
720
+ function refresh(){if(pending)return;pending=setTimeout(function(){pending=null;fetch(location.href,{headers:{accept:"text/html"},credentials:"same-origin"}).then(function(r){return r.ok?r.text():Promise.reject(r.status)}).then(apply).catch(function(){})},120)}
721
+ function apply(html){var doc=new DOMParser().parseFromString(html,"text/html");[".sm-side",".sm-page",".sm-panel-body"].forEach(function(sel){var cur=document.querySelector(sel),nxt=doc.querySelector(sel);if(!cur||!nxt)return;var seen={};cur.querySelectorAll(".sm-msg[data-ts]").forEach(function(el){el.classList.remove("sm-msg-new","sm-msg-changed");seen[el.dataset.ts]=el.outerHTML});var atBottom=cur.scrollHeight-cur.scrollTop-cur.clientHeight<80;cur.innerHTML=nxt.innerHTML;cur.querySelectorAll(".sm-msg[data-ts]").forEach(function(el){var prev=seen[el.dataset.ts];if(prev===undefined)el.classList.add("sm-msg-new");else if(prev!==el.outerHTML)el.classList.add("sm-msg-changed")});if(atBottom)cur.scrollTop=cur.scrollHeight});if(doc.title)document.title=doc.title}
722
+ if(LIVE&&window.EventSource){
723
+ var box0=document.querySelector(".sm-composer"),pm=/^\\/c\\/([^/]+)/.exec(location.pathname),chan=box0?box0.dataset.channel:(pm?decodeURIComponent(pm[1]):null);
724
+ if(chan){
725
+ var h1=document.querySelector(".sm-top h1"),dot=null;
726
+ if(h1){dot=document.createElement("span");dot.className="sm-live";dot.textContent="● live";h1.appendChild(dot)}
727
+ var es=new EventSource("/c/"+encodeURIComponent(chan)+"/events"),down=false;
728
+ es.addEventListener("change",refresh);
729
+ es.onopen=function(){if(dot){dot.textContent="● live";dot.classList.remove("sm-live-off")}if(down){down=false;refresh()}};
730
+ es.onerror=function(){down=true;if(dot){dot.textContent="● reconnecting";dot.classList.add("sm-live-off")}};
731
+ }
732
+ }
733
+ function send(box){var t=box.querySelector(".sm-composer-text"),text=t.value.trim();if(!text||t.disabled)return;var body={channel:box.dataset.channel,user:box.querySelector(".sm-composer-user").value,text:text};if(box.dataset.thread)body.thread_ts=box.dataset.thread;t.disabled=true;fetch("/mock/messages",{method:"POST",headers:authHeaders({"content-type":"application/json"}),body:JSON.stringify(body)}).then(function(r){t.disabled=false;if(r.status===401||r.status===403){setCred("");lockUi();var err=box.querySelector(".sm-err");if(err)err.textContent="Not signed in, or the credential changed. Sign in to post.";return}if(!r.ok)throw new Error("send failed "+r.status);t.value="";if(LIVE)refresh();else location.reload()}).catch(function(){t.disabled=false})}
689
734
  document.querySelectorAll(".sm-composer").forEach(function(box){
690
735
  var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
691
736
  function close(){items=[];menu.style.display="none"}
@@ -705,6 +750,11 @@ document.querySelectorAll(".sm-composer").forEach(function(box){
705
750
  ta.addEventListener("blur",function(){setTimeout(close,150)});
706
751
  menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
707
752
  ta.addEventListener("keydown",function(e){
753
+ if(e.key==="Backspace"&&ta.selectionStart===ta.selectionEnd&&ta.selectionStart>0){
754
+ var pos=ta.selectionStart,before=ta.value.slice(0,pos),hit="";
755
+ for(var k=0;k<PEOPLE.length;k++){var tok="@"+PEOPLE[k].name;var cand=before.endsWith(tok)?tok:"";if(cand&&cand.length>hit.length){var at=before.length-cand.length;if(at===0||/s/.test(before.charAt(at-1)))hit=cand}}
756
+ if(hit){e.preventDefault();ta.value=before.slice(0,before.length-hit.length)+ta.value.slice(pos);ta.selectionStart=ta.selectionEnd=pos-hit.length;close();return}
757
+ }
708
758
  if(items.length){
709
759
  if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
710
760
  if(e.key==="ArrowUp"){e.preventDefault();active=(active-1+items.length)%items.length;paint();return}
package/src/server.ts CHANGED
@@ -66,6 +66,26 @@ export interface SlackMockOptions extends StoreOptions {
66
66
  eventDelayMs?: number;
67
67
  /** Default width of the thread side panel in the HTML UI, e.g. "50%" or "640px". `?panel=` overrides per request. */
68
68
  panelWidth?: string;
69
+ /**
70
+ * Public base URL (e.g. "https://demo.slack-mock.dev") used in every URL the mock hands out:
71
+ * Socket Mode link, file download and upload URLs, response_urls, permalinks. When unset, URLs
72
+ * are derived from each request's Host header (honouring X-Forwarded-Proto), falling back to the
73
+ * local address.
74
+ */
75
+ publicUrl?: string;
76
+ /** "user:password" HTTP basic auth for the HTML UI and the /mock admin API (the Slack API stays token-based). */
77
+ adminAuth?: string;
78
+ /**
79
+ * Keep the HTML UI ("/" and "/c/...") readable without credentials while `adminAuth` still gates
80
+ * the /mock admin API. Default false: `adminAuth` covers both surfaces.
81
+ */
82
+ publicUi?: boolean;
83
+ /**
84
+ * "user:password" that may only post messages (`POST /mock/messages`) and check its role
85
+ * (`GET /mock/presenter`). With `publicUi` the HTML composer shows a sign-in for it, so a presenter
86
+ * can drive a public-read workspace without the admin credential. `adminAuth` always implies it.
87
+ */
88
+ presenterAuth?: string;
69
89
  log?: boolean | ((msg: string) => void);
70
90
  }
71
91
 
@@ -228,10 +248,53 @@ export class SlackMock {
228
248
  this.log(`listening on ${this.baseUrl}`);
229
249
  }
230
250
 
231
- get baseUrl(): string {
251
+ /** Address of this process's listener, for in-process clients and tests. */
252
+ get localUrl(): string {
232
253
  return `http://${this.server.hostname}:${this.server.port}`;
233
254
  }
234
255
 
256
+ /** Base URL handed to bots and browsers: `publicUrl` when configured, else the local address. */
257
+ get baseUrl(): string {
258
+ return (this.opts.publicUrl ?? this.localUrl).replace(/\/$/, "");
259
+ }
260
+
261
+ /** Base URL for links generated while serving `req`: publicUrl, else the request's own host. */
262
+ private publicBase(req: Request): string {
263
+ const host = req.headers.get("host");
264
+ if (!host) return this.baseUrl;
265
+ const proto =
266
+ req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() ||
267
+ new URL(req.url).protocol.replace(":", "");
268
+ const hostname = host.replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
269
+ const loopback =
270
+ hostname === "localhost" ||
271
+ hostname === "127.0.0.1" ||
272
+ hostname === "::1" ||
273
+ hostname === "0.0.0.0";
274
+ // Clients on the same box (tests, the demo bot in the container) must get URLs they can reach,
275
+ // even when a public URL is configured for everybody else.
276
+ if (loopback) return `${proto}://${host}`;
277
+ return this.opts.publicUrl ? this.baseUrl : `${proto}://${host}`;
278
+ }
279
+
280
+ private authorizedAdmin(req: Request): boolean {
281
+ const expected = this.opts.adminAuth;
282
+ if (!expected) return true;
283
+ return basicAuthMatches(req, expected);
284
+ }
285
+
286
+ /** `presenterAuth` (or `adminAuth`) may post messages and read its role, nothing else. */
287
+ private authorizedPresenter(req: Request): boolean {
288
+ if (this.authorizedAdmin(req)) return true;
289
+ const expected = this.opts.presenterAuth;
290
+ return Boolean(expected) && basicAuthMatches(req, expected as string);
291
+ }
292
+
293
+ /** Visitors can read the UI but posting needs a credential: the composer shows a sign-in. */
294
+ private get writeGated(): boolean {
295
+ return this.opts.publicUi === true && Boolean(this.opts.adminAuth);
296
+ }
297
+
235
298
  get apiUrl(): string {
236
299
  return `${this.baseUrl}/api/`;
237
300
  }
@@ -253,6 +316,10 @@ export class SlackMock {
253
316
  get bot() {
254
317
  return this.store.bot;
255
318
  }
319
+ /** Number of Socket Mode connections the app currently holds. */
320
+ get connectionCount(): number {
321
+ return this.hub.connectionCount;
322
+ }
256
323
 
257
324
  get team() {
258
325
  return this.store.team;
@@ -269,6 +336,12 @@ export class SlackMock {
269
336
  const path = url.pathname;
270
337
  this.lastRequestAt = Date.now();
271
338
  try {
339
+ const isUiSurface = path === "/" || path === "" || path.startsWith("/c/");
340
+ const isAdminSurface = path.startsWith("/mock/") || (isUiSurface && !this.opts.publicUi);
341
+ const isPresenterRoute =
342
+ (path === "/mock/messages" && req.method === "POST") || path === "/mock/presenter";
343
+ const allowed = isPresenterRoute ? this.authorizedPresenter(req) : this.authorizedAdmin(req);
344
+ if (isAdminSurface && !allowed) return denied(req, path);
272
345
  if (path.startsWith("/link/") || path === "/link") {
273
346
  const ticket = url.searchParams.get("ticket") ?? "";
274
347
  if (!this.hub.tickets.has(ticket)) return new Response("invalid ticket", { status: 403 });
@@ -276,13 +349,23 @@ export class SlackMock {
276
349
  if (server.upgrade(req, { data: { id: slackId("S", 6), ticket } })) return undefined;
277
350
  return new Response("upgrade failed", { status: 400 });
278
351
  }
279
- if (path.startsWith("/api/")) return await this.handleApi(req, path.slice(5));
352
+ if (path.startsWith("/api/"))
353
+ return await this.handleApi(req, path.slice(5), this.publicBase(req));
280
354
  if (path.startsWith("/upload/v1/"))
281
355
  return await this.handleUpload(req, path.slice("/upload/v1/".length));
282
356
  if (path.startsWith("/files-pri/")) return this.handleDownload(req, path);
283
357
  if (path.startsWith("/actions/"))
284
358
  return await this.handleResponseUrl(req, path.slice("/actions/".length));
285
359
  if (path.startsWith("/mock/")) return await this.handleAdmin(req, path.slice(6), url);
360
+ const events = /^\/c\/([^/]+)\/events\/?$/.exec(path);
361
+ if (events) {
362
+ const channel = this.store.channelByName(events[1]!)?.id ?? events[1]!;
363
+ if (!this.store.channels.has(channel))
364
+ return new Response("channel not found", { status: 404 });
365
+ // Bun closes idle HTTP responses after 10s by default; an SSE stream must outlive that.
366
+ server.timeout(req, 0);
367
+ return this.handleEvents(channel);
368
+ }
286
369
  return this.handleUi(path, url);
287
370
  } catch (e) {
288
371
  this.log(`unhandled error on ${req.method} ${path}: ${e instanceof Error ? e.stack : e}`);
@@ -301,7 +384,7 @@ export class SlackMock {
301
384
  return null;
302
385
  }
303
386
 
304
- private async handleApi(req: Request, method: string): Promise<Response> {
387
+ private async handleApi(req: Request, method: string, baseUrl: string): Promise<Response> {
305
388
  let args: Args = {};
306
389
  try {
307
390
  args = await parseArgs(req);
@@ -359,8 +442,8 @@ export class SlackMock {
359
442
  const ctx: ApiContext = {
360
443
  store: this.store,
361
444
  hub: this.hub,
362
- baseUrl: this.baseUrl,
363
- wsUrl: this.baseUrl.replace(/^http/, "ws"),
445
+ baseUrl,
446
+ wsUrl: baseUrl.replace(/^http/, "ws"),
364
447
  actor,
365
448
  triggerIds: this.triggerIds,
366
449
  pendingUploads: this.pendingUploads,
@@ -380,6 +463,7 @@ export class SlackMock {
380
463
  }
381
464
 
382
465
  private async handleUpload(req: Request, fileId: string): Promise<Response> {
466
+ const baseUrl = this.publicBase(req);
383
467
  const pending = this.pendingUploads.get(fileId);
384
468
  if (!pending) return new Response("unknown upload", { status: 404 });
385
469
  let bytes: Uint8Array;
@@ -400,7 +484,7 @@ export class SlackMock {
400
484
  name: pending.name,
401
485
  user: pending.user,
402
486
  bytes,
403
- baseUrl: this.baseUrl,
487
+ baseUrl,
404
488
  });
405
489
  return new Response("OK");
406
490
  }
@@ -510,6 +594,8 @@ export class SlackMock {
510
594
  : undefined
511
595
  : undefined,
512
596
  threadView: url.searchParams.has("full") ? ("full" as const) : ("panel" as const),
597
+ live: url.searchParams.get("live") !== "0",
598
+ writeGated: this.writeGated,
513
599
  };
514
600
  let html: string;
515
601
  if (path === "/" || path === "") html = renderPage(this.store, { kind: "index" }, opts);
@@ -526,6 +612,52 @@ export class SlackMock {
526
612
  return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
527
613
  }
528
614
 
615
+ /**
616
+ * Server-sent events for one channel: every store change that touches it, plus workspace-wide
617
+ * ones (users, files). The HTML UI listens here and re-fetches the page on each event.
618
+ */
619
+ private handleEvents(channelId: string): Response {
620
+ const enc = new TextEncoder();
621
+ let unsubscribe: () => void = () => {};
622
+ let ping: ReturnType<typeof setInterval> | undefined;
623
+ const stop = () => {
624
+ unsubscribe();
625
+ if (ping) clearInterval(ping);
626
+ };
627
+ const stream = new ReadableStream<Uint8Array>({
628
+ start: (controller) => {
629
+ const send = (event: string, data: unknown) => {
630
+ try {
631
+ controller.enqueue(enc.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));
632
+ } catch {
633
+ stop();
634
+ }
635
+ };
636
+ send("hello", { channel: channelId });
637
+ unsubscribe = this.store.onChange((change) => {
638
+ if (change.kind === "api.call" || change.kind.startsWith("view.")) return;
639
+ const scoped = changeChannel(change);
640
+ if (scoped && scoped !== channelId) return;
641
+ send("change", {
642
+ kind: change.kind,
643
+ channel: scoped ?? null,
644
+ ts: "message" in change ? change.message.ts : undefined,
645
+ });
646
+ });
647
+ ping = setInterval(() => send("ping", Date.now()), 25_000);
648
+ (ping as { unref?: () => void }).unref?.();
649
+ },
650
+ cancel: stop,
651
+ });
652
+ return new Response(stream, {
653
+ headers: {
654
+ "content-type": "text/event-stream; charset=utf-8",
655
+ "cache-control": "no-cache, no-transform",
656
+ "x-accel-buffering": "no",
657
+ },
658
+ });
659
+ }
660
+
529
661
  // -------------------------------------------------- event dispatching
530
662
 
531
663
  private isSubscribed(type: string): boolean {
@@ -686,10 +818,23 @@ export class SlackMock {
686
818
  }
687
819
 
688
820
  /** Turn `@name` and `@here` / `@channel` in human-typed text into Slack mention syntax. */
821
+ /**
822
+ * Turn `@name` / `@Display Name` / `@here` into Slack mention syntax. Handles names with
823
+ * spaces (the app user is often "Agent Swarm"), matching the longest known name first,
824
+ * case-insensitively, against both `name` and `real_name`.
825
+ */
689
826
  resolveMentions(text: string): string {
690
827
  const byName = new Map<string, string>();
691
- for (const u of this.store.users.values()) byName.set(u.name.toLowerCase(), u.id);
692
- return text.replace(/(^|[^<\w])@([\w.-]+)/g, (whole, lead: string, name: string) => {
828
+ for (const u of this.store.users.values()) {
829
+ if (u.deleted) continue;
830
+ byName.set(u.name.toLowerCase(), u.id);
831
+ if (u.real_name) byName.set(u.real_name.toLowerCase(), u.id);
832
+ }
833
+ const names = [...byName.keys(), "here", "channel", "everyone"]
834
+ .sort((a, b) => b.length - a.length)
835
+ .map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
836
+ const re = new RegExp(`(^|[^<\\w])@(${names.join("|")})(?![\\w.-])`, "gi");
837
+ return text.replace(re, (whole: string, lead: string, name: string) => {
693
838
  const lower = name.toLowerCase();
694
839
  if (lower === "here" || lower === "channel" || lower === "everyone")
695
840
  return `${lead}<!${lower}>`;
@@ -1109,6 +1254,8 @@ export class SlackMock {
1109
1254
  ? ((await req.json().catch(() => ({}))) as Record<string, unknown>)
1110
1255
  : {};
1111
1256
  try {
1257
+ if (path === "presenter")
1258
+ return json({ ok: true, role: this.authorizedAdmin(req) ? "admin" : "presenter" });
1112
1259
  if (path === "state") {
1113
1260
  return json({
1114
1261
  team: this.store.team,
@@ -1196,3 +1343,35 @@ function findButton(
1196
1343
  }
1197
1344
 
1198
1345
  export { SlackApiError };
1346
+
1347
+ /** Channel a store change belongs to, or undefined for workspace-wide changes. */
1348
+ function changeChannel(change: Change): string | undefined {
1349
+ if ("message" in change) return change.message.channel;
1350
+ if ("channel" in change)
1351
+ return typeof change.channel === "string" ? change.channel : change.channel.id;
1352
+ return undefined;
1353
+ }
1354
+
1355
+ function basicAuthMatches(req: Request, expected: string): boolean {
1356
+ const header = req.headers.get("authorization") ?? "";
1357
+ if (!header.toLowerCase().startsWith("basic ")) return false;
1358
+ try {
1359
+ return Buffer.from(header.slice(6).trim(), "base64").toString("utf8") === expected;
1360
+ } catch {
1361
+ return false;
1362
+ }
1363
+ }
1364
+
1365
+ /**
1366
+ * 401 + WWW-Authenticate makes the browser ask for credentials. A /mock request that already
1367
+ * carried a (wrong) Authorization header gets a plain 403 instead, so the composer's fetch never
1368
+ * triggers the native prompt and can show its own sign-in form.
1369
+ */
1370
+ function denied(req: Request, path: string): Response {
1371
+ if (path.startsWith("/mock/") && req.headers.has("authorization"))
1372
+ return new Response("forbidden", { status: 403 });
1373
+ return new Response("authentication required", {
1374
+ status: 401,
1375
+ headers: { "www-authenticate": 'Basic realm="slack-mock"' },
1376
+ });
1377
+ }