@desplega.ai/slack-mock 0.1.0 → 0.1.2
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 +30 -1
- package/dist/cli.js +8 -3
- package/dist/{index-thgwpw70.js → index-hqq20tz9.js} +201 -17
- package/dist/index.js +1 -1
- package/dist/render/index.d.ts +4 -0
- package/dist/server.d.ts +42 -0
- package/dist/store.d.ts +3 -1
- package/package.json +1 -1
- package/src/cli.ts +6 -1
- package/src/render/index.ts +81 -4
- package/src/server.ts +187 -8
- package/src/store.ts +6 -1
- package/src/web-api.ts +5 -1
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 (
|
|
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-
|
|
5
|
+
} from "./index-hqq20tz9.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]
|
|
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,
|
|
@@ -359,10 +359,10 @@ class Store {
|
|
|
359
359
|
this.emit({ kind: "message.add", message });
|
|
360
360
|
return message;
|
|
361
361
|
}
|
|
362
|
-
updateMessage(channelId, ts, patch, editor) {
|
|
362
|
+
updateMessage(channelId, ts, patch, editor, opts = {}) {
|
|
363
363
|
const message = this.message(channelId, ts);
|
|
364
364
|
const previous = structuredClone(message);
|
|
365
|
-
Object.assign(message, patch, { edited: { user: editor, ts: nextTs() } });
|
|
365
|
+
Object.assign(message, patch, opts.markEdited === false ? {} : { edited: { user: editor, ts: nextTs() } });
|
|
366
366
|
this.emit({ kind: "message.update", message, previous });
|
|
367
367
|
return message;
|
|
368
368
|
}
|
|
@@ -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}
|
|
@@ -1799,7 +1812,12 @@ function renderMessage(store, ctx, m, opts, flags = {}) {
|
|
|
1799
1812
|
const isApp = Boolean(m.bot_id);
|
|
1800
1813
|
const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
|
|
1801
1814
|
const body = [];
|
|
1802
|
-
if (
|
|
1815
|
+
if (m.streaming_state !== undefined) {
|
|
1816
|
+
if (m.text)
|
|
1817
|
+
body.push(`<div class="sm-text">${mrkdwnToHtml(markdownToMrkdwn(m.text), ctx)}</div>`);
|
|
1818
|
+
if (blocks)
|
|
1819
|
+
body.push(renderBlocks(blocks, ctx));
|
|
1820
|
+
} else if (blocks)
|
|
1803
1821
|
body.push(renderBlocks(blocks, ctx));
|
|
1804
1822
|
else if (m.text)
|
|
1805
1823
|
body.push(`<div class="sm-text">${mrkdwnToHtml(m.text, ctx)}</div>`);
|
|
@@ -1818,7 +1836,10 @@ function renderMessage(store, ctx, m, opts, flags = {}) {
|
|
|
1818
1836
|
}
|
|
1819
1837
|
const streaming = m.streaming_state === "in_progress" ? `<span class="sm-stream" title="streaming">\u2022\u2022\u2022</span>` : "";
|
|
1820
1838
|
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>`;
|
|
1839
|
+
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>`;
|
|
1840
|
+
}
|
|
1841
|
+
function markdownToMrkdwn(text) {
|
|
1842
|
+
return text.split(/(```[\s\S]*?```)/).map((part, i) => i % 2 === 1 ? part : part.replace(/\*\*(.+?)\*\*/g, "*$1*").replace(/__(.+?)__/g, "*$1*").replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, "<$2|$1>").replace(/^#{1,6}\s+(.+)$/gm, "*$1*").replace(/^(\s*)[-*]\s+/gm, "$1\u2022 ")).join("");
|
|
1822
1843
|
}
|
|
1823
1844
|
function renderMessageList(store, ctx, messages, opts, flags = {}) {
|
|
1824
1845
|
const out = [];
|
|
@@ -1910,7 +1931,9 @@ function composer(store, opts, channel, threadTs) {
|
|
|
1910
1931
|
const options = users.map((u, i) => `<option value="${escapeHtml(u.id)}"${i === 0 ? " selected" : ""}>${escapeHtml(u.real_name || u.name)}</option>`).join("");
|
|
1911
1932
|
const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
|
|
1912
1933
|
const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
|
|
1913
|
-
|
|
1934
|
+
const gated = opts.writeGated ? ' data-gated="1"' : "";
|
|
1935
|
+
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>` : "";
|
|
1936
|
+
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
1937
|
}
|
|
1915
1938
|
function mentionData(store) {
|
|
1916
1939
|
const users = [...store.users.values()].filter((u) => !u.deleted).map((u) => ({
|
|
@@ -1941,7 +1964,31 @@ if(handle){
|
|
|
1941
1964
|
var raw=document.getElementById("sm-users");
|
|
1942
1965
|
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
1966
|
function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&":c==="<"?"<":c===">"?">":"""})}
|
|
1944
|
-
|
|
1967
|
+
var GATED=${opts.writeGated ? "true" : "false"},LIVE=${opts.live !== false && !opts.refreshSec ? "true" : "false"},CK="sm-presenter";
|
|
1968
|
+
function cred(){try{return localStorage.getItem(CK)||""}catch(e){return ""}}
|
|
1969
|
+
function setCred(v){try{if(v)localStorage.setItem(CK,v);else localStorage.removeItem(CK)}catch(e){}}
|
|
1970
|
+
(function(){var m=/[#&]presenter=([^&]+)/.exec(location.hash||"");if(m){setCred(btoa(decodeURIComponent(m[1])));history.replaceState(null,"",location.pathname+location.search)}})();
|
|
1971
|
+
function authHeaders(h){var c=cred();if(c)h.authorization="Basic "+c;return h}
|
|
1972
|
+
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>':""})}
|
|
1973
|
+
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})}
|
|
1974
|
+
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"))});
|
|
1975
|
+
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"))}});
|
|
1976
|
+
lockUi();
|
|
1977
|
+
var pending=null;
|
|
1978
|
+
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)}
|
|
1979
|
+
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}
|
|
1980
|
+
if(LIVE&&window.EventSource){
|
|
1981
|
+
var box0=document.querySelector(".sm-composer"),pm=/^\\/c\\/([^/]+)/.exec(location.pathname),chan=box0?box0.dataset.channel:(pm?decodeURIComponent(pm[1]):null);
|
|
1982
|
+
if(chan){
|
|
1983
|
+
var h1=document.querySelector(".sm-top h1"),dot=null;
|
|
1984
|
+
if(h1){dot=document.createElement("span");dot.className="sm-live";dot.textContent="\u25CF live";h1.appendChild(dot)}
|
|
1985
|
+
var es=new EventSource("/c/"+encodeURIComponent(chan)+"/events"),down=false;
|
|
1986
|
+
es.addEventListener("change",refresh);
|
|
1987
|
+
es.onopen=function(){if(dot){dot.textContent="\u25CF live";dot.classList.remove("sm-live-off")}if(down){down=false;refresh()}};
|
|
1988
|
+
es.onerror=function(){down=true;if(dot){dot.textContent="\u25CF reconnecting";dot.classList.add("sm-live-off")}};
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
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
1992
|
document.querySelectorAll(".sm-composer").forEach(function(box){
|
|
1946
1993
|
var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
|
|
1947
1994
|
function close(){items=[];menu.style.display="none"}
|
|
@@ -1961,6 +2008,11 @@ document.querySelectorAll(".sm-composer").forEach(function(box){
|
|
|
1961
2008
|
ta.addEventListener("blur",function(){setTimeout(close,150)});
|
|
1962
2009
|
menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
|
|
1963
2010
|
ta.addEventListener("keydown",function(e){
|
|
2011
|
+
if(e.key==="Backspace"&&ta.selectionStart===ta.selectionEnd&&ta.selectionStart>0){
|
|
2012
|
+
var pos=ta.selectionStart,before=ta.value.slice(0,pos),hit="";
|
|
2013
|
+
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}}
|
|
2014
|
+
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}
|
|
2015
|
+
}
|
|
1964
2016
|
if(items.length){
|
|
1965
2017
|
if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
|
|
1966
2018
|
if(e.key==="ArrowUp"){e.preventDefault();active=(active-1+items.length)%items.length;paint();return}
|
|
@@ -2442,7 +2494,7 @@ var handlers = {
|
|
|
2442
2494
|
const existing = ctx.store.message(channel.id, ts);
|
|
2443
2495
|
if (existing.streaming_state !== "in_progress")
|
|
2444
2496
|
throw new SlackApiError("message_not_in_streaming_state");
|
|
2445
|
-
const message = ctx.store.updateMessage(channel.id, ts, { text: existing.text + streamText(args) }, ctx.actor.userId);
|
|
2497
|
+
const message = ctx.store.updateMessage(channel.id, ts, { text: existing.text + streamText(args) }, ctx.actor.userId, { markEdited: false });
|
|
2446
2498
|
return { channel: channel.id, ts: message.ts };
|
|
2447
2499
|
},
|
|
2448
2500
|
"chat.stopStream": (ctx, args) => {
|
|
@@ -2457,7 +2509,9 @@ var handlers = {
|
|
|
2457
2509
|
};
|
|
2458
2510
|
if (Array.isArray(args.blocks))
|
|
2459
2511
|
patch.blocks = args.blocks;
|
|
2460
|
-
const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId
|
|
2512
|
+
const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId, {
|
|
2513
|
+
markEdited: false
|
|
2514
|
+
});
|
|
2461
2515
|
return { channel: channel.id, ts, message: wireMessage(message) };
|
|
2462
2516
|
},
|
|
2463
2517
|
"chat.getPermalink": (ctx, args) => {
|
|
@@ -2915,9 +2969,38 @@ class SlackMock {
|
|
|
2915
2969
|
});
|
|
2916
2970
|
this.log(`listening on ${this.baseUrl}`);
|
|
2917
2971
|
}
|
|
2918
|
-
get
|
|
2972
|
+
get localUrl() {
|
|
2919
2973
|
return `http://${this.server.hostname}:${this.server.port}`;
|
|
2920
2974
|
}
|
|
2975
|
+
get baseUrl() {
|
|
2976
|
+
return (this.opts.publicUrl ?? this.localUrl).replace(/\/$/, "");
|
|
2977
|
+
}
|
|
2978
|
+
publicBase(req) {
|
|
2979
|
+
const host = req.headers.get("host");
|
|
2980
|
+
if (!host)
|
|
2981
|
+
return this.baseUrl;
|
|
2982
|
+
const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || new URL(req.url).protocol.replace(":", "");
|
|
2983
|
+
const hostname = host.replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
|
|
2984
|
+
const loopback = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "0.0.0.0";
|
|
2985
|
+
if (loopback)
|
|
2986
|
+
return `${proto}://${host}`;
|
|
2987
|
+
return this.opts.publicUrl ? this.baseUrl : `${proto}://${host}`;
|
|
2988
|
+
}
|
|
2989
|
+
authorizedAdmin(req) {
|
|
2990
|
+
const expected = this.opts.adminAuth;
|
|
2991
|
+
if (!expected)
|
|
2992
|
+
return true;
|
|
2993
|
+
return basicAuthMatches(req, expected);
|
|
2994
|
+
}
|
|
2995
|
+
authorizedPresenter(req) {
|
|
2996
|
+
if (this.authorizedAdmin(req))
|
|
2997
|
+
return true;
|
|
2998
|
+
const expected = this.opts.presenterAuth;
|
|
2999
|
+
return Boolean(expected) && basicAuthMatches(req, expected);
|
|
3000
|
+
}
|
|
3001
|
+
get writeGated() {
|
|
3002
|
+
return this.opts.publicUi === true && Boolean(this.opts.adminAuth);
|
|
3003
|
+
}
|
|
2921
3004
|
get apiUrl() {
|
|
2922
3005
|
return `${this.baseUrl}/api/`;
|
|
2923
3006
|
}
|
|
@@ -2935,6 +3018,9 @@ class SlackMock {
|
|
|
2935
3018
|
get bot() {
|
|
2936
3019
|
return this.store.bot;
|
|
2937
3020
|
}
|
|
3021
|
+
get connectionCount() {
|
|
3022
|
+
return this.hub.connectionCount;
|
|
3023
|
+
}
|
|
2938
3024
|
get team() {
|
|
2939
3025
|
return this.store.team;
|
|
2940
3026
|
}
|
|
@@ -2948,6 +3034,12 @@ class SlackMock {
|
|
|
2948
3034
|
const path = url.pathname;
|
|
2949
3035
|
this.lastRequestAt = Date.now();
|
|
2950
3036
|
try {
|
|
3037
|
+
const isUiSurface = path === "/" || path === "" || path.startsWith("/c/");
|
|
3038
|
+
const isAdminSurface = path.startsWith("/mock/") || isUiSurface && !this.opts.publicUi;
|
|
3039
|
+
const isPresenterRoute = path === "/mock/messages" && req.method === "POST" || path === "/mock/presenter";
|
|
3040
|
+
const allowed = isPresenterRoute ? this.authorizedPresenter(req) : this.authorizedAdmin(req);
|
|
3041
|
+
if (isAdminSurface && !allowed)
|
|
3042
|
+
return denied(req, path);
|
|
2951
3043
|
if (path.startsWith("/link/") || path === "/link") {
|
|
2952
3044
|
const ticket = url.searchParams.get("ticket") ?? "";
|
|
2953
3045
|
if (!this.hub.tickets.has(ticket))
|
|
@@ -2958,7 +3050,7 @@ class SlackMock {
|
|
|
2958
3050
|
return new Response("upgrade failed", { status: 400 });
|
|
2959
3051
|
}
|
|
2960
3052
|
if (path.startsWith("/api/"))
|
|
2961
|
-
return await this.handleApi(req, path.slice(5));
|
|
3053
|
+
return await this.handleApi(req, path.slice(5), this.publicBase(req));
|
|
2962
3054
|
if (path.startsWith("/upload/v1/"))
|
|
2963
3055
|
return await this.handleUpload(req, path.slice("/upload/v1/".length));
|
|
2964
3056
|
if (path.startsWith("/files-pri/"))
|
|
@@ -2967,6 +3059,14 @@ class SlackMock {
|
|
|
2967
3059
|
return await this.handleResponseUrl(req, path.slice("/actions/".length));
|
|
2968
3060
|
if (path.startsWith("/mock/"))
|
|
2969
3061
|
return await this.handleAdmin(req, path.slice(6), url);
|
|
3062
|
+
const events = /^\/c\/([^/]+)\/events\/?$/.exec(path);
|
|
3063
|
+
if (events) {
|
|
3064
|
+
const channel = this.store.channelByName(events[1])?.id ?? events[1];
|
|
3065
|
+
if (!this.store.channels.has(channel))
|
|
3066
|
+
return new Response("channel not found", { status: 404 });
|
|
3067
|
+
server.timeout(req, 0);
|
|
3068
|
+
return this.handleEvents(channel);
|
|
3069
|
+
}
|
|
2970
3070
|
return this.handleUi(path, url);
|
|
2971
3071
|
} catch (e) {
|
|
2972
3072
|
this.log(`unhandled error on ${req.method} ${path}: ${e instanceof Error ? e.stack : e}`);
|
|
@@ -2984,7 +3084,7 @@ class SlackMock {
|
|
|
2984
3084
|
}
|
|
2985
3085
|
return null;
|
|
2986
3086
|
}
|
|
2987
|
-
async handleApi(req, method) {
|
|
3087
|
+
async handleApi(req, method, baseUrl) {
|
|
2988
3088
|
let args = {};
|
|
2989
3089
|
try {
|
|
2990
3090
|
args = await parseArgs(req);
|
|
@@ -3039,8 +3139,8 @@ class SlackMock {
|
|
|
3039
3139
|
const ctx = {
|
|
3040
3140
|
store: this.store,
|
|
3041
3141
|
hub: this.hub,
|
|
3042
|
-
baseUrl
|
|
3043
|
-
wsUrl:
|
|
3142
|
+
baseUrl,
|
|
3143
|
+
wsUrl: baseUrl.replace(/^http/, "ws"),
|
|
3044
3144
|
actor,
|
|
3045
3145
|
triggerIds: this.triggerIds,
|
|
3046
3146
|
pendingUploads: this.pendingUploads
|
|
@@ -3059,6 +3159,7 @@ class SlackMock {
|
|
|
3059
3159
|
}
|
|
3060
3160
|
}
|
|
3061
3161
|
async handleUpload(req, fileId) {
|
|
3162
|
+
const baseUrl = this.publicBase(req);
|
|
3062
3163
|
const pending = this.pendingUploads.get(fileId);
|
|
3063
3164
|
if (!pending)
|
|
3064
3165
|
return new Response("unknown upload", { status: 404 });
|
|
@@ -3081,7 +3182,7 @@ class SlackMock {
|
|
|
3081
3182
|
name: pending.name,
|
|
3082
3183
|
user: pending.user,
|
|
3083
3184
|
bytes,
|
|
3084
|
-
baseUrl
|
|
3185
|
+
baseUrl
|
|
3085
3186
|
});
|
|
3086
3187
|
return new Response("OK");
|
|
3087
3188
|
}
|
|
@@ -3168,7 +3269,9 @@ class SlackMock {
|
|
|
3168
3269
|
refreshSec: Number.isFinite(refresh) && refresh > 0 ? refresh : undefined,
|
|
3169
3270
|
connections: this.hub.connectionCount,
|
|
3170
3271
|
panelWidth: panel ? /^\d+$/.test(panel) ? `${panel}%` : /^\d+(px|%|vw|rem)$/.test(panel) ? panel : undefined : undefined,
|
|
3171
|
-
threadView: url.searchParams.has("full") ? "full" : "panel"
|
|
3272
|
+
threadView: url.searchParams.has("full") ? "full" : "panel",
|
|
3273
|
+
live: url.searchParams.get("live") !== "0",
|
|
3274
|
+
writeGated: this.writeGated
|
|
3172
3275
|
};
|
|
3173
3276
|
let html;
|
|
3174
3277
|
if (path === "/" || path === "")
|
|
@@ -3184,6 +3287,53 @@ class SlackMock {
|
|
|
3184
3287
|
}
|
|
3185
3288
|
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
3186
3289
|
}
|
|
3290
|
+
handleEvents(channelId) {
|
|
3291
|
+
const enc = new TextEncoder;
|
|
3292
|
+
let unsubscribe = () => {};
|
|
3293
|
+
let ping;
|
|
3294
|
+
const stop = () => {
|
|
3295
|
+
unsubscribe();
|
|
3296
|
+
if (ping)
|
|
3297
|
+
clearInterval(ping);
|
|
3298
|
+
};
|
|
3299
|
+
const stream = new ReadableStream({
|
|
3300
|
+
start: (controller) => {
|
|
3301
|
+
const send = (event, data) => {
|
|
3302
|
+
try {
|
|
3303
|
+
controller.enqueue(enc.encode(`event: ${event}
|
|
3304
|
+
data: ${JSON.stringify(data)}
|
|
3305
|
+
|
|
3306
|
+
`));
|
|
3307
|
+
} catch {
|
|
3308
|
+
stop();
|
|
3309
|
+
}
|
|
3310
|
+
};
|
|
3311
|
+
send("hello", { channel: channelId });
|
|
3312
|
+
unsubscribe = this.store.onChange((change) => {
|
|
3313
|
+
if (change.kind === "api.call" || change.kind.startsWith("view."))
|
|
3314
|
+
return;
|
|
3315
|
+
const scoped = changeChannel(change);
|
|
3316
|
+
if (scoped && scoped !== channelId)
|
|
3317
|
+
return;
|
|
3318
|
+
send("change", {
|
|
3319
|
+
kind: change.kind,
|
|
3320
|
+
channel: scoped ?? null,
|
|
3321
|
+
ts: "message" in change ? change.message.ts : undefined
|
|
3322
|
+
});
|
|
3323
|
+
});
|
|
3324
|
+
ping = setInterval(() => send("ping", Date.now()), 25000);
|
|
3325
|
+
ping.unref?.();
|
|
3326
|
+
},
|
|
3327
|
+
cancel: stop
|
|
3328
|
+
});
|
|
3329
|
+
return new Response(stream, {
|
|
3330
|
+
headers: {
|
|
3331
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
3332
|
+
"cache-control": "no-cache, no-transform",
|
|
3333
|
+
"x-accel-buffering": "no"
|
|
3334
|
+
}
|
|
3335
|
+
});
|
|
3336
|
+
}
|
|
3187
3337
|
isSubscribed(type) {
|
|
3188
3338
|
return this.subscribed.has(type);
|
|
3189
3339
|
}
|
|
@@ -3318,9 +3468,16 @@ class SlackMock {
|
|
|
3318
3468
|
}
|
|
3319
3469
|
resolveMentions(text) {
|
|
3320
3470
|
const byName = new Map;
|
|
3321
|
-
for (const u of this.store.users.values())
|
|
3471
|
+
for (const u of this.store.users.values()) {
|
|
3472
|
+
if (u.deleted)
|
|
3473
|
+
continue;
|
|
3322
3474
|
byName.set(u.name.toLowerCase(), u.id);
|
|
3323
|
-
|
|
3475
|
+
if (u.real_name)
|
|
3476
|
+
byName.set(u.real_name.toLowerCase(), u.id);
|
|
3477
|
+
}
|
|
3478
|
+
const names = [...byName.keys(), "here", "channel", "everyone"].sort((a, b) => b.length - a.length).map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
3479
|
+
const re = new RegExp(`(^|[^<\\w])@(${names.join("|")})(?![\\w.-])`, "gi");
|
|
3480
|
+
return text.replace(re, (whole, lead, name) => {
|
|
3324
3481
|
const lower = name.toLowerCase();
|
|
3325
3482
|
if (lower === "here" || lower === "channel" || lower === "everyone")
|
|
3326
3483
|
return `${lead}<!${lower}>`;
|
|
@@ -3616,6 +3773,8 @@ class SlackMock {
|
|
|
3616
3773
|
const json = (body2, status = 200) => Response.json(body2, { status });
|
|
3617
3774
|
const body = req.method === "POST" ? await req.json().catch(() => ({})) : {};
|
|
3618
3775
|
try {
|
|
3776
|
+
if (path === "presenter")
|
|
3777
|
+
return json({ ok: true, role: this.authorizedAdmin(req) ? "admin" : "presenter" });
|
|
3619
3778
|
if (path === "state") {
|
|
3620
3779
|
return json({
|
|
3621
3780
|
team: this.store.team,
|
|
@@ -3689,5 +3848,30 @@ function findButton(blocks, actionId) {
|
|
|
3689
3848
|
}
|
|
3690
3849
|
return;
|
|
3691
3850
|
}
|
|
3851
|
+
function changeChannel(change) {
|
|
3852
|
+
if ("message" in change)
|
|
3853
|
+
return change.message.channel;
|
|
3854
|
+
if ("channel" in change)
|
|
3855
|
+
return typeof change.channel === "string" ? change.channel : change.channel.id;
|
|
3856
|
+
return;
|
|
3857
|
+
}
|
|
3858
|
+
function basicAuthMatches(req, expected) {
|
|
3859
|
+
const header = req.headers.get("authorization") ?? "";
|
|
3860
|
+
if (!header.toLowerCase().startsWith("basic "))
|
|
3861
|
+
return false;
|
|
3862
|
+
try {
|
|
3863
|
+
return Buffer.from(header.slice(6).trim(), "base64").toString("utf8") === expected;
|
|
3864
|
+
} catch {
|
|
3865
|
+
return false;
|
|
3866
|
+
}
|
|
3867
|
+
}
|
|
3868
|
+
function denied(req, path) {
|
|
3869
|
+
if (path.startsWith("/mock/") && req.headers.has("authorization"))
|
|
3870
|
+
return new Response("forbidden", { status: 403 });
|
|
3871
|
+
return new Response("authentication required", {
|
|
3872
|
+
status: 401,
|
|
3873
|
+
headers: { "www-authenticate": 'Basic realm="slack-mock"' }
|
|
3874
|
+
});
|
|
3875
|
+
}
|
|
3692
3876
|
|
|
3693
3877
|
export { SlackApiError, Store, SlackMock };
|
package/dist/index.js
CHANGED
package/dist/render/index.d.ts
CHANGED
|
@@ -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/dist/store.d.ts
CHANGED
|
@@ -115,7 +115,9 @@ export declare class Store {
|
|
|
115
115
|
addMessage(input: Omit<SlackMessage, "type" | "team" | "ts"> & {
|
|
116
116
|
ts?: string;
|
|
117
117
|
}): SlackMessage;
|
|
118
|
-
updateMessage(channelId: string, ts: string, patch: Partial<SlackMessage>, editor: string
|
|
118
|
+
updateMessage(channelId: string, ts: string, patch: Partial<SlackMessage>, editor: string, opts?: {
|
|
119
|
+
markEdited?: boolean;
|
|
120
|
+
}): SlackMessage;
|
|
119
121
|
deleteMessage(channelId: string, ts: string): SlackMessage;
|
|
120
122
|
addReaction(channelId: string, ts: string, name: string, userId: string): SlackMessage;
|
|
121
123
|
removeReaction(channelId: string, ts: string, name: string, userId: string): SlackMessage;
|
package/package.json
CHANGED
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]
|
|
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,
|
package/src/render/index.ts
CHANGED
|
@@ -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}
|
|
@@ -438,7 +455,13 @@ function renderMessage(
|
|
|
438
455
|
const isApp = Boolean(m.bot_id);
|
|
439
456
|
const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
|
|
440
457
|
const body: string[] = [];
|
|
441
|
-
if (
|
|
458
|
+
if (m.streaming_state !== undefined) {
|
|
459
|
+
// A streamed message (chat.startStream) keeps its Markdown body; the blocks handed to
|
|
460
|
+
// chat.stopStream are appended below it, like Slack does.
|
|
461
|
+
if (m.text)
|
|
462
|
+
body.push(`<div class="sm-text">${mrkdwnToHtml(markdownToMrkdwn(m.text), ctx)}</div>`);
|
|
463
|
+
if (blocks) body.push(renderBlocks(blocks, ctx));
|
|
464
|
+
} else if (blocks) body.push(renderBlocks(blocks, ctx));
|
|
442
465
|
else if (m.text) body.push(`<div class="sm-text">${mrkdwnToHtml(m.text, ctx)}</div>`);
|
|
443
466
|
if (m.edited) body.push(`<div class="sm-edited">(edited)</div>`);
|
|
444
467
|
if (m.attachments?.length) body.push(renderAttachments(m.attachments, ctx));
|
|
@@ -459,7 +482,28 @@ function renderMessage(
|
|
|
459
482
|
? `<span class="sm-stream" title="streaming">•••</span>`
|
|
460
483
|
: "";
|
|
461
484
|
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>`;
|
|
485
|
+
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>`;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Streamed messages carry Markdown (`markdown_text`), not mrkdwn. Convert the common
|
|
490
|
+
* constructs so the mrkdwn renderer shows them: **bold**, [label](url), headings and list
|
|
491
|
+
* bullets. Fenced code blocks pass through untouched.
|
|
492
|
+
*/
|
|
493
|
+
function markdownToMrkdwn(text: string): string {
|
|
494
|
+
return text
|
|
495
|
+
.split(/(```[\s\S]*?```)/)
|
|
496
|
+
.map((part, i) =>
|
|
497
|
+
i % 2 === 1
|
|
498
|
+
? part
|
|
499
|
+
: part
|
|
500
|
+
.replace(/\*\*(.+?)\*\*/g, "*$1*")
|
|
501
|
+
.replace(/__(.+?)__/g, "*$1*")
|
|
502
|
+
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, "<$2|$1>")
|
|
503
|
+
.replace(/^#{1,6}\s+(.+)$/gm, "*$1*")
|
|
504
|
+
.replace(/^(\s*)[-*]\s+/gm, "$1• "),
|
|
505
|
+
)
|
|
506
|
+
.join("");
|
|
463
507
|
}
|
|
464
508
|
|
|
465
509
|
function renderMessageList(
|
|
@@ -643,7 +687,11 @@ function composer(
|
|
|
643
687
|
.join("");
|
|
644
688
|
const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
|
|
645
689
|
const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
|
|
646
|
-
|
|
690
|
+
const gated = opts.writeGated ? ' data-gated="1"' : "";
|
|
691
|
+
const lock = opts.writeGated
|
|
692
|
+
? `<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>`
|
|
693
|
+
: "";
|
|
694
|
+
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
695
|
}
|
|
648
696
|
|
|
649
697
|
/** Mention targets for the composer autocomplete: every user, bots included. */
|
|
@@ -685,7 +733,31 @@ if(handle){
|
|
|
685
733
|
var raw=document.getElementById("sm-users");
|
|
686
734
|
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
735
|
function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&":c==="<"?"<":c===">"?">":"""})}
|
|
688
|
-
|
|
736
|
+
var GATED=${opts.writeGated ? "true" : "false"},LIVE=${opts.live !== false && !opts.refreshSec ? "true" : "false"},CK="sm-presenter";
|
|
737
|
+
function cred(){try{return localStorage.getItem(CK)||""}catch(e){return ""}}
|
|
738
|
+
function setCred(v){try{if(v)localStorage.setItem(CK,v);else localStorage.removeItem(CK)}catch(e){}}
|
|
739
|
+
(function(){var m=/[#&]presenter=([^&]+)/.exec(location.hash||"");if(m){setCred(btoa(decodeURIComponent(m[1])));history.replaceState(null,"",location.pathname+location.search)}})();
|
|
740
|
+
function authHeaders(h){var c=cred();if(c)h.authorization="Basic "+c;return h}
|
|
741
|
+
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>':""})}
|
|
742
|
+
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})}
|
|
743
|
+
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"))});
|
|
744
|
+
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"))}});
|
|
745
|
+
lockUi();
|
|
746
|
+
var pending=null;
|
|
747
|
+
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)}
|
|
748
|
+
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}
|
|
749
|
+
if(LIVE&&window.EventSource){
|
|
750
|
+
var box0=document.querySelector(".sm-composer"),pm=/^\\/c\\/([^/]+)/.exec(location.pathname),chan=box0?box0.dataset.channel:(pm?decodeURIComponent(pm[1]):null);
|
|
751
|
+
if(chan){
|
|
752
|
+
var h1=document.querySelector(".sm-top h1"),dot=null;
|
|
753
|
+
if(h1){dot=document.createElement("span");dot.className="sm-live";dot.textContent="● live";h1.appendChild(dot)}
|
|
754
|
+
var es=new EventSource("/c/"+encodeURIComponent(chan)+"/events"),down=false;
|
|
755
|
+
es.addEventListener("change",refresh);
|
|
756
|
+
es.onopen=function(){if(dot){dot.textContent="● live";dot.classList.remove("sm-live-off")}if(down){down=false;refresh()}};
|
|
757
|
+
es.onerror=function(){down=true;if(dot){dot.textContent="● reconnecting";dot.classList.add("sm-live-off")}};
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
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
761
|
document.querySelectorAll(".sm-composer").forEach(function(box){
|
|
690
762
|
var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
|
|
691
763
|
function close(){items=[];menu.style.display="none"}
|
|
@@ -705,6 +777,11 @@ document.querySelectorAll(".sm-composer").forEach(function(box){
|
|
|
705
777
|
ta.addEventListener("blur",function(){setTimeout(close,150)});
|
|
706
778
|
menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
|
|
707
779
|
ta.addEventListener("keydown",function(e){
|
|
780
|
+
if(e.key==="Backspace"&&ta.selectionStart===ta.selectionEnd&&ta.selectionStart>0){
|
|
781
|
+
var pos=ta.selectionStart,before=ta.value.slice(0,pos),hit="";
|
|
782
|
+
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}}
|
|
783
|
+
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}
|
|
784
|
+
}
|
|
708
785
|
if(items.length){
|
|
709
786
|
if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
|
|
710
787
|
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
|
-
|
|
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/"))
|
|
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
|
|
363
|
-
wsUrl:
|
|
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
|
|
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())
|
|
692
|
-
|
|
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
|
+
}
|
package/src/store.ts
CHANGED
|
@@ -421,10 +421,15 @@ export class Store {
|
|
|
421
421
|
ts: string,
|
|
422
422
|
patch: Partial<SlackMessage>,
|
|
423
423
|
editor: string,
|
|
424
|
+
opts: { markEdited?: boolean } = {},
|
|
424
425
|
): SlackMessage {
|
|
425
426
|
const message = this.message(channelId, ts);
|
|
426
427
|
const previous = structuredClone(message);
|
|
427
|
-
Object.assign(
|
|
428
|
+
Object.assign(
|
|
429
|
+
message,
|
|
430
|
+
patch,
|
|
431
|
+
opts.markEdited === false ? {} : { edited: { user: editor, ts: nextTs() } },
|
|
432
|
+
);
|
|
428
433
|
this.emit({ kind: "message.update", message, previous });
|
|
429
434
|
return message;
|
|
430
435
|
}
|
package/src/web-api.ts
CHANGED
|
@@ -242,11 +242,13 @@ export const handlers: Record<string, Handler> = {
|
|
|
242
242
|
const existing = ctx.store.message(channel.id, ts);
|
|
243
243
|
if (existing.streaming_state !== "in_progress")
|
|
244
244
|
throw new SlackApiError("message_not_in_streaming_state");
|
|
245
|
+
// Streaming appends are not edits: Slack shows no "(edited)" marker for them.
|
|
245
246
|
const message = ctx.store.updateMessage(
|
|
246
247
|
channel.id,
|
|
247
248
|
ts,
|
|
248
249
|
{ text: existing.text + streamText(args) },
|
|
249
250
|
ctx.actor.userId,
|
|
251
|
+
{ markEdited: false },
|
|
250
252
|
);
|
|
251
253
|
return { channel: channel.id, ts: message.ts };
|
|
252
254
|
},
|
|
@@ -262,7 +264,9 @@ export const handlers: Record<string, Handler> = {
|
|
|
262
264
|
text: existing.text + streamText(args),
|
|
263
265
|
};
|
|
264
266
|
if (Array.isArray(args.blocks)) patch.blocks = args.blocks as unknown[];
|
|
265
|
-
const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId
|
|
267
|
+
const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId, {
|
|
268
|
+
markEdited: false,
|
|
269
|
+
});
|
|
266
270
|
return { channel: channel.id, ts, message: wireMessage(message) };
|
|
267
271
|
},
|
|
268
272
|
|