slopstream 0.0.0-stage → 0.2.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/.claude-plugin/marketplace.json +13 -0
- package/.claude-plugin/plugin.json +18 -0
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/PRIVACY.md +17 -0
- package/README.md +114 -2
- package/SECURITY.md +34 -0
- package/THREAT_MODEL.md +166 -0
- package/bridge/cli.js +433 -0
- package/bridge/config.js +28 -0
- package/bridge/demo.js +146 -0
- package/bridge/gate.js +152 -0
- package/bridge/http.js +18 -0
- package/bridge/init.js +132 -0
- package/bridge/login.js +51 -0
- package/bridge/net.js +89 -0
- package/bridge/server.js +365 -0
- package/bridge/simulate.js +78 -0
- package/bridge/status.js +54 -0
- package/commands/demo.md +15 -0
- package/commands/get-started.md +19 -0
- package/commands/init.md +17 -0
- package/commands/links.md +10 -0
- package/commands/status.md +14 -0
- package/package.json +57 -4
- package/product.md +163 -0
- package/relay/admin.js +31 -0
- package/relay/core.js +555 -0
- package/relay/html.js +44 -0
- package/relay/kv-file.js +41 -0
- package/relay/kv-mem.js +9 -0
- package/relay/server.js +93 -0
package/relay/core.js
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
// RelayCore: ALL protocol logic of the slopstream relay, platform-neutral.
|
|
2
|
+
// - authenticates users (token per user)
|
|
3
|
+
// - groups 2+ chats into one "link" (a shared group), approved by a human each time someone joins
|
|
4
|
+
// - delivers messages ONLY if the target's linked session is connected right now (no queueing)
|
|
5
|
+
// - rate limits, size caps, audit log
|
|
6
|
+
//
|
|
7
|
+
// Hosts (relay/server.js for Node, relay/cloudflare for Workers) only provide sockets, a KV store and a
|
|
8
|
+
// periodic sweep(). No ws, no fs, no timers in here, so the same code runs in both places.
|
|
9
|
+
// Wire format is A2A-shaped (contextId + parts[]) but this is NOT full A2A yet.
|
|
10
|
+
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import { invitePage, gonePage, landingPage } from './html.js';
|
|
13
|
+
|
|
14
|
+
export const PROTOCOL = 2;
|
|
15
|
+
const ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789'; // no i, l, o, 0, 1: hard to misread
|
|
16
|
+
const ZOMBIE_MS = 75000;
|
|
17
|
+
const AUTH_FAIL_MAX = 20;
|
|
18
|
+
const AUTH_FAIL_WINDOW_MS = 10 * 60 * 1000;
|
|
19
|
+
const ACCEPT_FAIL_MAX = 10;
|
|
20
|
+
const ACCEPT_FAIL_WINDOW_MS = 10 * 60 * 1000;
|
|
21
|
+
const NAME_RE = /^[a-zA-Z0-9._-]{1,40}$/;
|
|
22
|
+
const hashToken = (t) => crypto.createHash('sha256').update(t).digest('hex');
|
|
23
|
+
const json = (status, obj) => ({ status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, body: JSON.stringify(obj) });
|
|
24
|
+
const html = (status, body) => ({ status, body, headers: {
|
|
25
|
+
'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer',
|
|
26
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src https://avatars.githubusercontent.com" } });
|
|
27
|
+
const key = (user, chat) => `${user} ${chat}`;
|
|
28
|
+
const normCode = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
29
|
+
const displayCode = (c) => c.slice(0, 5) + '-' + c.slice(5);
|
|
30
|
+
|
|
31
|
+
const str = (v, d) => (v === undefined || v === null ? d : String(v).trim());
|
|
32
|
+
const num = (v, d) => (v === undefined || v === null || String(v).trim() === '' ? d : Number(v));
|
|
33
|
+
|
|
34
|
+
export function configFromEnv(env) {
|
|
35
|
+
return {
|
|
36
|
+
maxText: num(env.MAX_TEXT, 8000),
|
|
37
|
+
rateMax: num(env.RATE_MAX, 30), // msgs per link per window
|
|
38
|
+
rateWindowMs: num(env.RATE_WINDOW_MS, 10 * 60 * 1000),
|
|
39
|
+
maxGroupSize: num(env.MAX_GROUP_SIZE, 3), // how many chats can share one link
|
|
40
|
+
publicUrl: str(env.PUBLIC_URL, '').replace(/\/+$/, ''),
|
|
41
|
+
inviteTtlMs: num(env.INVITE_TTL_MS, 24 * 60 * 60 * 1000),
|
|
42
|
+
githubClientId: str(env.GITHUB_CLIENT_ID, ''),
|
|
43
|
+
githubBaseUrl: str(env.GITHUB_BASE_URL, 'https://github.com').replace(/\/+$/, ''),
|
|
44
|
+
githubApiUrl: str(env.GITHUB_API_URL, 'https://api.github.com').replace(/\/+$/, ''),
|
|
45
|
+
auditText: str(env.AUDIT_TEXT, '1') !== '0',
|
|
46
|
+
maxOpenInvites: num(env.MAX_OPEN_INVITES, 20),
|
|
47
|
+
maxDevices: num(env.MAX_DEVICES, 20),
|
|
48
|
+
maxLinks: num(env.MAX_LINKS, 50),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class RelayCore {
|
|
53
|
+
constructor({ kv, config, fetchImpl = globalThis.fetch, now = () => Date.now() }) {
|
|
54
|
+
this.kv = kv;
|
|
55
|
+
this.config = config;
|
|
56
|
+
this.fetch = (...a) => fetchImpl(...a); // not a bare method call: Workers throw "Illegal invocation" if fetch gets a foreign `this`
|
|
57
|
+
this.now = now;
|
|
58
|
+
// A "link" is a group of 2..maxGroupSize chats that have all agreed to be reachable from one another.
|
|
59
|
+
// { id, members: [{user, chat}, ...], createdAt }
|
|
60
|
+
this.links = kv.get('links') || [];
|
|
61
|
+
this.conns = new Map(); // conn id -> conn
|
|
62
|
+
this.online = new Map(); // "user chat" -> conn id (session connections only)
|
|
63
|
+
this.rate = new Map(); // linkId -> [timestamps]
|
|
64
|
+
this.authFails = new Map(); // ip -> [timestamps of failed hellos]
|
|
65
|
+
this.startsByIp = new Map(); // ip -> [timestamps of GitHub login starts]
|
|
66
|
+
this.acceptFails = new Map(); // user -> [timestamps of bad pair_accept codes]
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ---- host-facing API ----
|
|
70
|
+
openConn(conn, { ip = '' } = {}) {
|
|
71
|
+
conn.meta = { id: crypto.randomUUID(), openedAt: this.now(), ip, authed: false };
|
|
72
|
+
conn.saveMeta();
|
|
73
|
+
this.conns.set(conn.meta.id, conn);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// A Durable Object can wake up holding sockets the core has never seen; rebuild our in-memory index from meta.
|
|
77
|
+
restoreConn(conn) {
|
|
78
|
+
const m = conn.meta;
|
|
79
|
+
this.conns.set(m.id, conn);
|
|
80
|
+
if (m.mode === 'session') this.online.set(key(m.user, m.chat), m.id);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
onMessage(conn, raw) {
|
|
84
|
+
if (!this.conns.has(conn.meta.id)) this.restoreConn(conn);
|
|
85
|
+
if (raw.length > 65536) return conn.close(1009, 'too big');
|
|
86
|
+
let m; try { m = JSON.parse(raw); } catch { return; }
|
|
87
|
+
if (!m || typeof m !== 'object') return;
|
|
88
|
+
if (m.t === 'ping') return conn.send({ t: 'pong' });
|
|
89
|
+
conn.meta.lastMsgAt = this.now(); // roughly right is enough, so no saveMeta per frame
|
|
90
|
+
if (!conn.meta.authed) {
|
|
91
|
+
if (m.t !== 'hello') return conn.close(4002, 'hello first');
|
|
92
|
+
return this.handleHello(conn, m);
|
|
93
|
+
}
|
|
94
|
+
try { this.handle(conn, m); } catch (e) { conn.send({ t: 'error', code: 'internal', message: String(e.message || e) }); }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
onClose(conn) {
|
|
98
|
+
const meta = conn.meta;
|
|
99
|
+
if (!meta || !this.conns.has(meta.id)) return;
|
|
100
|
+
this.conns.delete(meta.id);
|
|
101
|
+
if (meta.mode === 'session') {
|
|
102
|
+
const k = key(meta.user, meta.chat);
|
|
103
|
+
if (this.online.get(k) === meta.id) {
|
|
104
|
+
this.online.delete(k);
|
|
105
|
+
const link = this.findLink(meta.user, meta.chat);
|
|
106
|
+
if (link) this.broadcastMembers(link);
|
|
107
|
+
this.audit({ ev: 'offline', user: meta.user, chat: meta.chat });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
sweep() {
|
|
113
|
+
const now = this.now();
|
|
114
|
+
for (const c of [...this.conns.values()]) {
|
|
115
|
+
if (!c.meta.authed && now - c.meta.openedAt > 10000) c.close(4001, 'hello timeout');
|
|
116
|
+
}
|
|
117
|
+
for (const [id, arr] of this.rate) {
|
|
118
|
+
const fresh = arr.filter(t => now - t < this.config.rateWindowMs);
|
|
119
|
+
if (fresh.length) this.rate.set(id, fresh); else this.rate.delete(id);
|
|
120
|
+
}
|
|
121
|
+
for (const [k, inv] of this.kv.list('invite:')) if (inv.exp < now) this.kv.del(k);
|
|
122
|
+
for (const [k, d] of this.kv.list('devauth:')) if (d.exp < now) this.kv.del(k);
|
|
123
|
+
for (const [ip, arr] of this.authFails) {
|
|
124
|
+
const fresh = arr.filter(t => now - t < AUTH_FAIL_WINDOW_MS);
|
|
125
|
+
if (fresh.length) this.authFails.set(ip, fresh); else this.authFails.delete(ip);
|
|
126
|
+
}
|
|
127
|
+
for (const [ip, arr] of this.startsByIp) {
|
|
128
|
+
const fresh = arr.filter(t => now - t < 3600000);
|
|
129
|
+
if (fresh.length) this.startsByIp.set(ip, fresh); else this.startsByIp.delete(ip);
|
|
130
|
+
}
|
|
131
|
+
for (const [u, arr] of this.acceptFails) {
|
|
132
|
+
const fresh = arr.filter(t => now - t < ACCEPT_FAIL_WINDOW_MS);
|
|
133
|
+
if (fresh.length) this.acceptFails.set(u, fresh); else this.acceptFails.delete(u);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// True while there is state a sweep must eventually clean up (the Durable Object keeps its alarm running for it).
|
|
138
|
+
hasPendingState() { return this.kv.list('invite:').length > 0 || this.kv.list('devauth:').length > 0; }
|
|
139
|
+
|
|
140
|
+
async handleHttp(req) {
|
|
141
|
+
const { method, path } = req;
|
|
142
|
+
if (method === 'GET' && path === '/healthz') return json(200, { ok: true, protocol: PROTOCOL });
|
|
143
|
+
if (method === 'GET' && path === '/v1/info') {
|
|
144
|
+
const c = this.config;
|
|
145
|
+
return json(200, { protocol: PROTOCOL, github: !!c.githubClientId, publicUrl: c.publicUrl, maxGroupSize: c.maxGroupSize, inviteTtlSec: c.inviteTtlMs / 1000 });
|
|
146
|
+
}
|
|
147
|
+
if (method === 'GET' && path.startsWith('/v1/invite/')) {
|
|
148
|
+
const inv = this.getInvite(decodeURIComponent(path.slice('/v1/invite/'.length)));
|
|
149
|
+
if (!inv) return json(404, { status: 'not_found' });
|
|
150
|
+
if (inv.requester) return json(200, { status: 'used' });
|
|
151
|
+
return json(200, { status: 'open', inviter: inv.user, inviterGithub: this.githubOf(inv.user), chat: inv.chat, kind: inv.kind, expiresAt: inv.exp });
|
|
152
|
+
}
|
|
153
|
+
if (method === 'GET' && path.startsWith('/j/')) {
|
|
154
|
+
let inv; try { inv = this.getInvite(decodeURIComponent(path.slice(3))); } catch { inv = undefined; }
|
|
155
|
+
if (!inv || inv.requester) return html(404, gonePage());
|
|
156
|
+
return html(200, invitePage({ inviter: inv.user, inviterGithub: this.githubOf(inv.user), code: displayCode(inv.code), expiresAt: inv.exp }));
|
|
157
|
+
}
|
|
158
|
+
if (method === 'GET' && path === '/') return html(200, landingPage());
|
|
159
|
+
if (method === 'POST' && (path === '/v1/auth/github/start' || path === '/v1/auth/github/poll')) {
|
|
160
|
+
let body = {};
|
|
161
|
+
try { body = req.body ? JSON.parse(req.body) : {}; } catch { return json(400, { status: 'error', code: 'bad_json' }); }
|
|
162
|
+
if (!body || typeof body !== 'object') body = {};
|
|
163
|
+
return path.endsWith('/start') ? this.githubStart(req, body) : this.githubPoll(body);
|
|
164
|
+
}
|
|
165
|
+
return { status: 404, headers: { 'content-type': 'text/plain' }, body: 'not found' };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---- GitHub device flow. The RELAY talks to GitHub, so a GitHub token never reaches the CLI and can only
|
|
169
|
+
// have been issued to OUR OAuth app (if the CLI sent us a token, one from some other app could be used to log in as that person).
|
|
170
|
+
async ghForm(url, fields) {
|
|
171
|
+
const r = await this.fetch(url, {
|
|
172
|
+
method: 'POST',
|
|
173
|
+
headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
|
|
174
|
+
body: new URLSearchParams(fields).toString(),
|
|
175
|
+
signal: AbortSignal.timeout(10000),
|
|
176
|
+
});
|
|
177
|
+
if (!r.ok) throw new Error('github http ' + r.status);
|
|
178
|
+
return r.json();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async githubStart(req, body) {
|
|
182
|
+
const c = this.config;
|
|
183
|
+
if (!c.githubClientId) return json(404, { status: 'error', code: 'github_disabled' });
|
|
184
|
+
const now = this.now();
|
|
185
|
+
const starts = (this.startsByIp.get(req.ip || '') || []).filter(t => now - t < 3600000);
|
|
186
|
+
if (starts.length >= 10) return json(429, { status: 'error', code: 'rate_limited' });
|
|
187
|
+
starts.push(now); this.startsByIp.set(req.ip || '', starts);
|
|
188
|
+
let gh;
|
|
189
|
+
try { gh = await this.ghForm(`${c.githubBaseUrl}/login/device/code`, { client_id: c.githubClientId }); } catch { gh = null; }
|
|
190
|
+
if (!gh || !gh.device_code) return json(502, { status: 'error', code: 'github_unavailable' });
|
|
191
|
+
const pollId = crypto.randomBytes(16).toString('base64url');
|
|
192
|
+
const interval = gh.interval || 5;
|
|
193
|
+
const label = String(body.label || '').replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 60) || 'unknown device';
|
|
194
|
+
this.kv.put('devauth:' + pollId, { deviceCode: gh.device_code, interval, exp: now + gh.expires_in * 1000, nextPollAt: now + interval * 1000, label, inFlightAt: 0 });
|
|
195
|
+
return json(200, { status: 'started', poll_id: pollId, user_code: gh.user_code, verification_uri: gh.verification_uri, expires_in: gh.expires_in, interval });
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async githubPoll(body) {
|
|
199
|
+
const c = this.config;
|
|
200
|
+
if (!c.githubClientId) return json(404, { status: 'error', code: 'github_disabled' });
|
|
201
|
+
const pollId = String(body.poll_id || '');
|
|
202
|
+
const key = 'devauth:' + pollId;
|
|
203
|
+
const d = pollId ? this.kv.get(key) : undefined;
|
|
204
|
+
const now = this.now();
|
|
205
|
+
if (!d || d.exp < now) { if (d) this.kv.del(key); return json(200, { status: 'expired' }); }
|
|
206
|
+
// Never call GitHub more often than it allows, and never twice concurrently (two polls must not create two devices).
|
|
207
|
+
if (now < d.nextPollAt || (d.inFlightAt && now - d.inFlightAt < 30000)) return json(200, { status: 'pending', interval: d.interval });
|
|
208
|
+
d.inFlightAt = now; this.kv.put(key, d);
|
|
209
|
+
const stillPending = (interval) => { d.interval = interval; d.nextPollAt = this.now() + interval * 1000; d.inFlightAt = 0; this.kv.put(key, d); return json(200, { status: 'pending', interval }); };
|
|
210
|
+
let gh;
|
|
211
|
+
try {
|
|
212
|
+
gh = await this.ghForm(`${c.githubBaseUrl}/login/oauth/access_token`, {
|
|
213
|
+
client_id: c.githubClientId, device_code: d.deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' });
|
|
214
|
+
} catch { gh = null; }
|
|
215
|
+
if (!gh) { d.inFlightAt = 0; this.kv.put(key, d); return json(502, { status: 'error', code: 'github_unavailable' }); }
|
|
216
|
+
if (gh.error === 'authorization_pending') return stillPending(d.interval);
|
|
217
|
+
if (gh.error === 'slow_down') return stillPending(gh.interval || d.interval + 5);
|
|
218
|
+
if (gh.error === 'expired_token') { this.kv.del(key); return json(200, { status: 'expired' }); }
|
|
219
|
+
if (gh.error === 'access_denied') { this.kv.del(key); return json(200, { status: 'denied' }); }
|
|
220
|
+
if (!gh.access_token) { d.inFlightAt = 0; this.kv.put(key, d); return json(502, { status: 'error', code: 'github_unavailable' }); }
|
|
221
|
+
|
|
222
|
+
// The GitHub token is used once, right here, to learn who the person is. It is never stored or logged.
|
|
223
|
+
let who;
|
|
224
|
+
try {
|
|
225
|
+
const r = await this.fetch(`${c.githubApiUrl}/user`, {
|
|
226
|
+
headers: { authorization: `Bearer ${gh.access_token}`, accept: 'application/vnd.github+json', 'user-agent': 'slopstream-relay', 'x-github-api-version': '2022-11-28' },
|
|
227
|
+
signal: AbortSignal.timeout(10000),
|
|
228
|
+
});
|
|
229
|
+
who = r.ok ? await r.json() : null;
|
|
230
|
+
} catch { who = null; }
|
|
231
|
+
if (!who || typeof who.id !== 'number' || !who.login) { d.inFlightAt = 0; this.kv.put(key, d); return json(502, { status: 'error', code: 'github_unavailable' }); }
|
|
232
|
+
|
|
233
|
+
let name = this.kv.get('gh:' + who.id);
|
|
234
|
+
if (!name) {
|
|
235
|
+
name = String(who.login).toLowerCase();
|
|
236
|
+
const users = this.kv.get('users') || {};
|
|
237
|
+
if (!NAME_RE.test(name) || this.kv.get('account:' + name) || Object.hasOwn(users, name)) {
|
|
238
|
+
this.kv.del(key);
|
|
239
|
+
return json(200, { status: 'error', code: 'name_taken', message: 'that username is already used on this relay' });
|
|
240
|
+
}
|
|
241
|
+
this.kv.put('account:' + name, { name, ghId: who.id, ghLogin: who.login, createdAt: now });
|
|
242
|
+
this.kv.put('gh:' + who.id, name);
|
|
243
|
+
} else {
|
|
244
|
+
// The relay username never changes after creation (links reference it), even if the person renames on GitHub.
|
|
245
|
+
const acc = this.kv.get('account:' + name);
|
|
246
|
+
if (acc) { acc.ghLogin = who.login; this.kv.put('account:' + name, acc); }
|
|
247
|
+
}
|
|
248
|
+
const mine = this.kv.list('device:').filter(([, dv]) => dv.user === name);
|
|
249
|
+
if (mine.length >= c.maxDevices) {
|
|
250
|
+
mine.sort((a, b) => a[1].lastSeenAt - b[1].lastSeenAt);
|
|
251
|
+
for (const [k] of mine.slice(0, mine.length - c.maxDevices + 1)) this.kv.del(k);
|
|
252
|
+
}
|
|
253
|
+
const token = 'sst_' + crypto.randomBytes(32).toString('base64url');
|
|
254
|
+
const deviceId = crypto.randomUUID();
|
|
255
|
+
this.kv.put('device:' + hashToken(token), { id: deviceId, user: name, label: d.label, createdAt: now, lastSeenAt: now });
|
|
256
|
+
this.kv.del(key);
|
|
257
|
+
this.audit({ ev: 'login', user: name, deviceId });
|
|
258
|
+
return json(200, { status: 'ok', user: name, token, device_id: deviceId });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ---- helpers ----
|
|
262
|
+
audit(o) {
|
|
263
|
+
if (o.ev === 'msg' && !this.config.auditText) { const { text, ...rest } = o; o = rest; }
|
|
264
|
+
this.kv.appendAudit({ ts: new Date(this.now()).toISOString(), ...o });
|
|
265
|
+
}
|
|
266
|
+
newCode() {
|
|
267
|
+
let c = '';
|
|
268
|
+
for (let i = 0; i < 10; i++) c += ALPHABET[crypto.randomInt(ALPHABET.length)];
|
|
269
|
+
return c;
|
|
270
|
+
}
|
|
271
|
+
// Returns the invite, or undefined if missing or expired (expired ones are deleted on the spot).
|
|
272
|
+
getInvite(code) {
|
|
273
|
+
const c = normCode(code);
|
|
274
|
+
const inv = c ? this.kv.get('invite:' + c) : undefined;
|
|
275
|
+
if (!inv) return undefined;
|
|
276
|
+
if (inv.exp < this.now()) { this.kv.del('invite:' + c); return undefined; }
|
|
277
|
+
return inv;
|
|
278
|
+
}
|
|
279
|
+
userInvites(user) { return this.kv.list('invite:').map(([, v]) => v).filter(v => v.user === user && v.exp >= this.now()); }
|
|
280
|
+
adminConnsOf(user) { return [...this.conns.values()].filter(c => c.meta.authed && c.meta.mode === 'admin' && c.meta.user === user); }
|
|
281
|
+
githubOf(user) { return this.kv.get('account:' + user)?.ghLogin || null; }
|
|
282
|
+
makeInvite(conn, chat, groupId) {
|
|
283
|
+
const user = conn.meta.user;
|
|
284
|
+
const { maxOpenInvites, inviteTtlMs, publicUrl } = this.config;
|
|
285
|
+
if (this.userInvites(user).length >= maxOpenInvites) { conn.send({ t: 'error', code: 'too_many_invites', message: `you already have ${maxOpenInvites} open invites; cancel some first` }); return; }
|
|
286
|
+
const code = this.newCode();
|
|
287
|
+
const createdAt = this.now();
|
|
288
|
+
this.kv.put('invite:' + code, { code, kind: groupId ? 'group' : 'pair', user, chat, groupId: groupId || null, createdAt, exp: createdAt + inviteTtlMs, requester: null });
|
|
289
|
+
conn.send({ t: 'pair_code', code: displayCode(code), url: `${publicUrl}/j/${displayCode(code)}`, expiresInSec: inviteTtlMs / 1000 });
|
|
290
|
+
}
|
|
291
|
+
connOf(user, chat) { const id = this.online.get(key(user, chat)); return id ? this.conns.get(id) : undefined; }
|
|
292
|
+
findLink(user, chat) { return this.links.find(l => l.members.some(m => m.user === user && m.chat === chat)); }
|
|
293
|
+
saveLinks() { this.kv.put('links', this.links); }
|
|
294
|
+
otherMembers(link, user, chat) {
|
|
295
|
+
return link.members
|
|
296
|
+
.filter(m => !(m.user === user && m.chat === chat))
|
|
297
|
+
.map(m => {
|
|
298
|
+
const w = this.connOf(m.user, m.chat);
|
|
299
|
+
return { user: m.user, chat: m.chat, online: !!w, agent: w ? w.meta.agent : null };
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
// Push each currently-online member of `link` a fresh list of everyone else in it (membership or presence changed).
|
|
303
|
+
broadcastMembers(link) {
|
|
304
|
+
for (const m of link.members) {
|
|
305
|
+
const w = this.connOf(m.user, m.chat);
|
|
306
|
+
if (w) w.send({ t: 'members', members: this.otherMembers(link, m.user, m.chat) });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
rateOk(linkId) {
|
|
310
|
+
const now = this.now();
|
|
311
|
+
const arr = (this.rate.get(linkId) || []).filter(t => now - t < this.config.rateWindowMs);
|
|
312
|
+
if (arr.length >= this.config.rateMax) { this.rate.set(linkId, arr); return false; }
|
|
313
|
+
arr.push(now); this.rate.set(linkId, arr); return true;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// ---- protocol ----
|
|
317
|
+
handleHello(conn, m) {
|
|
318
|
+
const meta = conn.meta;
|
|
319
|
+
const now = this.now();
|
|
320
|
+
// Per-IP limiter on failed logins, checked before looking at the token at all.
|
|
321
|
+
const ipFails = (this.authFails.get(meta.ip) || []).filter(t => now - t < AUTH_FAIL_WINDOW_MS);
|
|
322
|
+
this.authFails.set(meta.ip, ipFails);
|
|
323
|
+
if (meta.ip && ipFails.length >= AUTH_FAIL_MAX) return conn.close(4029, 'slow down');
|
|
324
|
+
const user = String(m.user || '');
|
|
325
|
+
const token = String(m.token || '');
|
|
326
|
+
const given = hashToken(token);
|
|
327
|
+
const fail = () => {
|
|
328
|
+
ipFails.push(now);
|
|
329
|
+
this.audit({ ev: 'auth_fail', user });
|
|
330
|
+
conn.send({ t: 'error', code: 'auth', message: 'bad user or token' });
|
|
331
|
+
return conn.close(4003, 'auth');
|
|
332
|
+
};
|
|
333
|
+
if (token.startsWith('sst_')) {
|
|
334
|
+
// Per-device token (GitHub login). Only its hash is stored, so a leaked relay database is not a leaked login.
|
|
335
|
+
const dev = this.kv.get('device:' + given);
|
|
336
|
+
if (!dev || (user && user !== dev.user)) return fail();
|
|
337
|
+
meta.user = dev.user; meta.deviceId = dev.id;
|
|
338
|
+
if (now - dev.lastSeenAt > 3600000) { dev.lastSeenAt = now; this.kv.put('device:' + given, dev); } // throttled: no write per connect
|
|
339
|
+
} else {
|
|
340
|
+
const users = this.kv.get('users') || {}; // legacy admin-created users; re-read on every hello so `admin add-user` works without a restart
|
|
341
|
+
const stored = Object.hasOwn(users, user) ? users[user] : undefined;
|
|
342
|
+
const ok = stored && stored.length === given.length &&
|
|
343
|
+
crypto.timingSafeEqual(Buffer.from(stored), Buffer.from(given));
|
|
344
|
+
if (!ok) return fail();
|
|
345
|
+
meta.user = user;
|
|
346
|
+
}
|
|
347
|
+
meta.authed = true;
|
|
348
|
+
// Which kind of agent is behind this session (claude, codex, console...). Informational only.
|
|
349
|
+
meta.agent = /^[a-z0-9_-]{1,20}$/.test(String(m.agent || '')) ? String(m.agent) : 'unknown';
|
|
350
|
+
meta.v = Number(m.v) || 1;
|
|
351
|
+
const welcomeBase = { t: 'welcome', user: meta.user, protocol: PROTOCOL };
|
|
352
|
+
|
|
353
|
+
if (!m.chat) { meta.mode = 'admin'; conn.saveMeta(); return conn.send({ ...welcomeBase, mode: 'admin' }); }
|
|
354
|
+
|
|
355
|
+
const chat = String(m.chat);
|
|
356
|
+
if (!NAME_RE.test(chat)) { conn.send({ t: 'error', code: 'bad_chat', message: 'invalid chat label' }); return conn.close(4004, 'bad chat'); }
|
|
357
|
+
const link = this.findLink(user, chat);
|
|
358
|
+
if (!link) { conn.send({ t: 'error', code: 'not_linked', message: `chat "${chat}" has no link; pair it with the slopstream CLI` }); return conn.close(4005, 'not linked'); }
|
|
359
|
+
const k = key(user, chat);
|
|
360
|
+
if (this.online.has(k)) {
|
|
361
|
+
// A half-dead socket (laptop slept, wifi changed) can hold the slot for minutes. If the old one has been silent for
|
|
362
|
+
// longer than any live client would be (heartbeat is 25 s), the new connection takes over.
|
|
363
|
+
const old = this.conns.get(this.online.get(k));
|
|
364
|
+
if (old && now - old.lastActivity() > ZOMBIE_MS) { old.close(4008, 'replaced'); this.onClose(old); }
|
|
365
|
+
else { conn.send({ t: 'error', code: 'duplicate', message: 'this chat is already connected elsewhere' }); return conn.close(4006, 'duplicate'); }
|
|
366
|
+
}
|
|
367
|
+
meta.mode = 'session'; meta.chat = chat; meta.linkId = link.id;
|
|
368
|
+
conn.saveMeta();
|
|
369
|
+
this.online.set(k, meta.id);
|
|
370
|
+
conn.send({ ...welcomeBase, mode: 'session', link: { id: link.id }, members: this.otherMembers(link, user, chat) });
|
|
371
|
+
this.broadcastMembers(link); // tell everyone else in the group this chat just came online
|
|
372
|
+
this.audit({ ev: 'online', user, chat, linkId: link.id });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
handle(conn, m) {
|
|
376
|
+
if (conn.meta.mode === 'admin') return this.handleAdmin(conn, m);
|
|
377
|
+
if (conn.meta.mode === 'session') return this.handleSession(conn, m);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
handleAdmin(conn, m) {
|
|
381
|
+
const user = conn.meta.user;
|
|
382
|
+
const { maxGroupSize } = this.config;
|
|
383
|
+
const err = (code, message) => conn.send({ t: 'error', code, message });
|
|
384
|
+
switch (m.t) {
|
|
385
|
+
case 'pair_create': {
|
|
386
|
+
const chat = String(m.chat || '');
|
|
387
|
+
if (!NAME_RE.test(chat)) return err('bad_chat', 'invalid chat label');
|
|
388
|
+
if (this.findLink(user, chat)) return err('already_linked', `chat "${chat}" is already linked`);
|
|
389
|
+
this.makeInvite(conn, chat, null);
|
|
390
|
+
return this.audit({ ev: 'pair_create', user, chat });
|
|
391
|
+
}
|
|
392
|
+
case 'invite_create': {
|
|
393
|
+
// Add a NEW chat to a group that already has at least one link, up to maxGroupSize.
|
|
394
|
+
const chat = String(m.chat || '');
|
|
395
|
+
if (!NAME_RE.test(chat)) return err('bad_chat', 'invalid chat label');
|
|
396
|
+
const link = this.findLink(user, chat);
|
|
397
|
+
if (!link) return err('not_linked', `chat "${chat}" is not linked yet; use pair-create first`);
|
|
398
|
+
if (link.members.length >= maxGroupSize) return err('group_full', `this group already has the maximum of ${maxGroupSize} chats`);
|
|
399
|
+
this.makeInvite(conn, chat, link.id);
|
|
400
|
+
return this.audit({ ev: 'invite_create', user, chat, linkId: link.id });
|
|
401
|
+
}
|
|
402
|
+
case 'pair_accept': {
|
|
403
|
+
const chat = String(m.chat || '');
|
|
404
|
+
if (!NAME_RE.test(chat)) return err('bad_chat', 'invalid chat label');
|
|
405
|
+
// Brute-force limiter: codes are ~49 bits, but nobody gets unlimited guesses.
|
|
406
|
+
const now = this.now();
|
|
407
|
+
const fails = (this.acceptFails.get(user) || []).filter(t => now - t < ACCEPT_FAIL_WINDOW_MS);
|
|
408
|
+
this.acceptFails.set(user, fails);
|
|
409
|
+
if (fails.length >= ACCEPT_FAIL_MAX) return err('too_many_attempts', 'too many wrong codes; try again in a few minutes');
|
|
410
|
+
const inv = this.getInvite(m.code);
|
|
411
|
+
if (!inv) { fails.push(now); return err('bad_code', 'unknown or expired code'); }
|
|
412
|
+
if (inv.user === user) return err('same_user', 'cannot pair with yourself');
|
|
413
|
+
if (this.findLink(user, chat)) return err('already_linked', `chat "${chat}" is already linked`);
|
|
414
|
+
if (inv.requester) return err('busy', 'code already in use');
|
|
415
|
+
if (inv.groupId) {
|
|
416
|
+
const group = this.links.find(l => l.id === inv.groupId);
|
|
417
|
+
if (!group) return err('gone', 'that group no longer exists');
|
|
418
|
+
if (group.members.length >= maxGroupSize) return err('group_full', `this group already has the maximum of ${maxGroupSize} chats`);
|
|
419
|
+
if (group.members.some(x => x.user === user)) return err('already_in_group', 'you already have a chat in this group');
|
|
420
|
+
}
|
|
421
|
+
inv.requester = { user, chat, at: now };
|
|
422
|
+
this.kv.put('invite:' + inv.code, inv);
|
|
423
|
+
const msg = { t: 'pair_request', code: displayCode(inv.code), from: { user, chat, github: this.githubOf(user) }, toChat: inv.chat };
|
|
424
|
+
for (const c of this.adminConnsOf(inv.user)) c.send(msg); // the inviter's human must approve
|
|
425
|
+
conn.send({ t: 'pair_waiting', code: displayCode(inv.code), message: `waiting for ${inv.user} to approve` });
|
|
426
|
+
this.audit({ ev: 'pair_request', from: user, fromChat: chat, to: inv.user, toChat: inv.chat });
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
case 'pair_decision': {
|
|
430
|
+
const inv = this.getInvite(m.code);
|
|
431
|
+
if (!inv || inv.user !== user || !inv.requester) return err('bad_code', 'no such pending request');
|
|
432
|
+
this.kv.del('invite:' + inv.code); // single use, even when denied
|
|
433
|
+
const dcode = displayCode(inv.code);
|
|
434
|
+
const req = inv.requester;
|
|
435
|
+
const toBoth = (o) => { for (const c of [...this.adminConnsOf(inv.user), ...this.adminConnsOf(req.user)]) c.send(o); };
|
|
436
|
+
if (!m.ok) { toBoth({ t: 'pair_denied', code: dcode }); this.audit({ ev: 'pair_denied', user: inv.user }); return; }
|
|
437
|
+
|
|
438
|
+
const countLinks = (u) => this.links.filter(l => l.members.some(x => x.user === u)).length;
|
|
439
|
+
const limited = inv.groupId ? [req.user] : [inv.user, req.user];
|
|
440
|
+
if (limited.some(u => countLinks(u) >= this.config.maxLinks)) return toBoth({ t: 'error', code: 'too_many_links', message: 'a user is at the maximum number of links' });
|
|
441
|
+
let link;
|
|
442
|
+
if (inv.groupId) {
|
|
443
|
+
link = this.links.find(l => l.id === inv.groupId);
|
|
444
|
+
if (!link) return toBoth({ t: 'error', code: 'gone', message: 'that group no longer exists' });
|
|
445
|
+
if (link.members.length >= maxGroupSize) return toBoth({ t: 'error', code: 'group_full', message: 'group is now full' });
|
|
446
|
+
link.members.push({ user: req.user, chat: req.chat });
|
|
447
|
+
} else {
|
|
448
|
+
link = { id: crypto.randomUUID(), members: [{ user: inv.user, chat: inv.chat }, { user: req.user, chat: req.chat }], createdAt: new Date(this.now()).toISOString() };
|
|
449
|
+
this.links.push(link);
|
|
450
|
+
}
|
|
451
|
+
this.saveLinks();
|
|
452
|
+
this.audit({ ev: inv.groupId ? 'member_added' : 'paired', linkId: link.id, by: user, added: { user: req.user, chat: req.chat } });
|
|
453
|
+
for (const c of this.adminConnsOf(inv.user)) c.send({ t: 'paired', code: dcode, link: { id: link.id }, members: this.otherMembers(link, inv.user, inv.chat) });
|
|
454
|
+
for (const c of this.adminConnsOf(req.user)) c.send({ t: 'paired', code: dcode, link: { id: link.id }, members: this.otherMembers(link, req.user, req.chat) });
|
|
455
|
+
this.broadcastMembers(link); // refresh anyone else already online in the group
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
case 'device_list': {
|
|
459
|
+
const devices = this.kv.list('device:').map(([, d]) => d).filter(d => d.user === user)
|
|
460
|
+
.map(d => ({ id: d.id, label: d.label, createdAt: d.createdAt, lastSeenAt: d.lastSeenAt, current: d.id === conn.meta.deviceId }));
|
|
461
|
+
return conn.send({ t: 'devices', devices });
|
|
462
|
+
}
|
|
463
|
+
case 'device_revoke': {
|
|
464
|
+
const id = String(m.id || '');
|
|
465
|
+
const entry = this.kv.list('device:').find(([, d]) => d.user === user && d.id === id);
|
|
466
|
+
if (!entry) return err('not_found', 'no such device');
|
|
467
|
+
this.kv.del(entry[0]);
|
|
468
|
+
for (const c of [...this.conns.values()]) {
|
|
469
|
+
if (c.meta.deviceId === id) { c.send({ t: 'error', code: 'auth', message: 'device revoked' }); c.close(4003, 'revoked'); }
|
|
470
|
+
}
|
|
471
|
+
this.audit({ ev: 'device_revoked', user, deviceId: id });
|
|
472
|
+
return conn.send({ t: 'device_revoked', id });
|
|
473
|
+
}
|
|
474
|
+
case 'list_requests': {
|
|
475
|
+
const invites = this.userInvites(user).map(v => ({
|
|
476
|
+
code: displayCode(v.code), kind: v.kind, chat: v.chat, expiresAt: v.exp,
|
|
477
|
+
requester: v.requester ? { user: v.requester.user, chat: v.requester.chat, github: this.githubOf(v.requester.user) } : null,
|
|
478
|
+
}));
|
|
479
|
+
return conn.send({ t: 'requests', invites });
|
|
480
|
+
}
|
|
481
|
+
case 'invite_cancel': {
|
|
482
|
+
const inv = this.getInvite(m.code);
|
|
483
|
+
if (!inv || inv.user !== user) return err('bad_code', 'no such invite');
|
|
484
|
+
this.kv.del('invite:' + inv.code);
|
|
485
|
+
return conn.send({ t: 'invite_cancelled', code: displayCode(inv.code) });
|
|
486
|
+
}
|
|
487
|
+
case 'list_links': {
|
|
488
|
+
// Presence of a link's members is visible to the people on that link, and nobody else.
|
|
489
|
+
const mine = this.links.filter(l => l.members.some(x => x.user === user))
|
|
490
|
+
.map(l => ({ id: l.id, createdAt: l.createdAt, members: l.members.map(x => ({ ...x, online: this.online.has(key(x.user, x.chat)) })) }));
|
|
491
|
+
return conn.send({ t: 'links', links: mine });
|
|
492
|
+
}
|
|
493
|
+
case 'unlink': {
|
|
494
|
+
// Leaving a group: if fewer than 2 chats would remain, the whole link is dissolved for everyone.
|
|
495
|
+
const chat = String(m.chat || '');
|
|
496
|
+
const link = this.findLink(user, chat);
|
|
497
|
+
if (!link) return err('not_linked', 'no such link');
|
|
498
|
+
const remaining = link.members.filter(x => !(x.user === user && x.chat === chat));
|
|
499
|
+
if (remaining.length < 2) {
|
|
500
|
+
this.links = this.links.filter(l => l.id !== link.id); this.saveLinks();
|
|
501
|
+
for (const side of link.members) {
|
|
502
|
+
const w = this.connOf(side.user, side.chat);
|
|
503
|
+
if (w) { w.send({ t: 'unlinked' }); w.close(4007, 'unlinked'); }
|
|
504
|
+
}
|
|
505
|
+
this.audit({ ev: 'unlinked', linkId: link.id, by: user });
|
|
506
|
+
} else {
|
|
507
|
+
link.members = remaining; this.saveLinks();
|
|
508
|
+
const w = this.connOf(user, chat); // the leaver's own SESSION, if any (this admin connection is separate)
|
|
509
|
+
if (w) { w.send({ t: 'unlinked' }); w.close(4007, 'unlinked'); }
|
|
510
|
+
this.broadcastMembers(link);
|
|
511
|
+
this.audit({ ev: 'left_group', linkId: link.id, by: user });
|
|
512
|
+
}
|
|
513
|
+
return conn.send({ t: 'unlinked_ok', chat });
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
handleSession(conn, m) {
|
|
519
|
+
const { user, chat } = conn.meta;
|
|
520
|
+
if (m.t === 'receipt') {
|
|
521
|
+
// Tells the ORIGINAL SENDER whether the receiving HUMAN let the message through ('accepted') or refused it ('declined').
|
|
522
|
+
// Fixed vocabulary only; never carries free text. `to` names the original sender (required once a group has >2 members).
|
|
523
|
+
const rlink = this.findLink(user, chat);
|
|
524
|
+
if (!rlink || !['accepted', 'declined'].includes(m.status)) return;
|
|
525
|
+
const others = this.otherMembers(rlink, user, chat);
|
|
526
|
+
const target = m.to ? others.find(o => o.user === String(m.to)) : (others.length === 1 ? others[0] : null);
|
|
527
|
+
if (!target) return;
|
|
528
|
+
const rw = this.connOf(target.user, target.chat);
|
|
529
|
+
this.audit({ ev: 'receipt', linkId: rlink.id, from: user, to: target.user, id: String(m.id || '').slice(0, 64), status: m.status });
|
|
530
|
+
if (rw) rw.send({ t: 'receipt', id: String(m.id || '').slice(0, 64), from: user, status: m.status });
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
if (m.t !== 'msg') return;
|
|
534
|
+
const link = this.findLink(user, chat);
|
|
535
|
+
const nack = (reason) => conn.send({ t: 'ack', id: m.id, delivered: false, reason });
|
|
536
|
+
if (!link) return nack('not_linked');
|
|
537
|
+
const text = m.parts && m.parts[0] && m.parts[0].kind === 'text' ? String(m.parts[0].text) : '';
|
|
538
|
+
if (!text) return nack('empty_or_non_text');
|
|
539
|
+
if (text.length > this.config.maxText) return nack(`too_long (max ${this.config.maxText} chars)`);
|
|
540
|
+
if (!this.rateOk(link.id)) { this.audit({ ev: 'rate_limited', user, linkId: link.id }); return nack('rate_limited'); }
|
|
541
|
+
|
|
542
|
+
const others = this.otherMembers(link, user, chat);
|
|
543
|
+
let target;
|
|
544
|
+
if (m.to) target = others.find(o => o.user === String(m.to));
|
|
545
|
+
else if (others.length === 1) target = others[0];
|
|
546
|
+
if (!target) return nack(others.length > 1 ? 'ambiguous_target' : 'unknown_recipient');
|
|
547
|
+
|
|
548
|
+
const pw = this.connOf(target.user, target.chat);
|
|
549
|
+
if (!pw) { this.audit({ ev: 'undelivered_offline', from: user, to: target.user, linkId: link.id }); return nack('peer_offline'); }
|
|
550
|
+
const out = { t: 'msg', id: m.id, from: user, fromChat: chat, fromAgent: conn.meta.agent, contextId: String(m.contextId || m.id), parts: [{ kind: 'text', text }] };
|
|
551
|
+
pw.send(out);
|
|
552
|
+
this.audit({ ev: 'msg', linkId: link.id, from: user, to: target.user, id: m.id, contextId: out.contextId, text });
|
|
553
|
+
conn.send({ t: 'ack', id: m.id, delivered: true, to: target.user });
|
|
554
|
+
}
|
|
555
|
+
}
|
package/relay/html.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// HTML for the join page and the landing page. Pure functions; every interpolated value goes through esc().
|
|
2
|
+
const REPO = 'https://github.com/mrlegendary25/slopstream';
|
|
3
|
+
|
|
4
|
+
export const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
5
|
+
|
|
6
|
+
const CSS = `
|
|
7
|
+
:root{color-scheme:light dark;--bg:#fafafa;--fg:#1a1a1a;--muted:#666;--card:#fff;--line:#ddd;--accent:#0b57d0}
|
|
8
|
+
@media (prefers-color-scheme:dark){:root{--bg:#141414;--fg:#eee;--muted:#9a9a9a;--card:#1e1e1e;--line:#333;--accent:#8ab4f8}}
|
|
9
|
+
body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,Segoe UI,sans-serif}
|
|
10
|
+
main{max-width:560px;margin:0 auto;padding:24px 16px}
|
|
11
|
+
h1{font-size:1.4rem;margin:0 0 8px}
|
|
12
|
+
.card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px 14px;margin:10px 0}
|
|
13
|
+
.cmd{display:flex;gap:8px;align-items:center;justify-content:space-between}
|
|
14
|
+
code{font:14px ui-monospace,Menlo,Consolas,monospace;word-break:break-all}
|
|
15
|
+
button{font:inherit;padding:4px 10px;border:1px solid var(--line);border-radius:6px;background:var(--bg);color:var(--fg);cursor:pointer}
|
|
16
|
+
.warn{border-color:#d9a400}.muted{color:var(--muted);font-size:.9rem}a{color:var(--accent)}
|
|
17
|
+
img{border-radius:50%;vertical-align:middle;margin-right:8px}`;
|
|
18
|
+
|
|
19
|
+
const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title><style>${CSS}</style></head><body><main>${body}</main></body></html>`;
|
|
20
|
+
|
|
21
|
+
const COPY_JS = `<script>document.querySelectorAll('button[data-c]').forEach(function(b){b.onclick=function(){navigator.clipboard.writeText(b.dataset.c).then(function(){b.textContent='Copied';setTimeout(function(){b.textContent='Copy'},1500)})}})</script>`;
|
|
22
|
+
|
|
23
|
+
const cmd = (c) => `<div class="card cmd"><code>${esc(c)}</code><button data-c="${esc(c)}">Copy</button></div>`;
|
|
24
|
+
|
|
25
|
+
export function invitePage({ inviter, inviterGithub, code, expiresAt }) {
|
|
26
|
+
const who = inviterGithub
|
|
27
|
+
? `<img src="https://avatars.githubusercontent.com/${esc(inviterGithub)}?s=64" width="32" height="32" alt=""><a href="https://github.com/${esc(inviterGithub)}">@${esc(inviter)}</a>`
|
|
28
|
+
: `@${esc(inviter)}`;
|
|
29
|
+
return page(`Link agents with @${inviter}`, `
|
|
30
|
+
<h1>${who} wants your agents to be able to ask each other</h1>
|
|
31
|
+
<p>Slopstream lets your agent consult @${esc(inviter)}'s agent directly (Claude Code, Codex), instead of you two copy-pasting between them. You approve every message.</p>
|
|
32
|
+
<ol>
|
|
33
|
+
<li>Install once (needs Node 20+):</li>${cmd('npm install -g slopstream')}
|
|
34
|
+
<li>Open a terminal <b>in the project folder</b> you want to link</li>
|
|
35
|
+
<li>Run:</li>${cmd(`slopstream join ${code}`)}
|
|
36
|
+
</ol>
|
|
37
|
+
<div class="card warn">Only continue if you know @${esc(inviter)}. Their agent will be able to send messages to your agent; you approve each one.</div>
|
|
38
|
+
<p class="muted">This link expires ${esc(new Date(expiresAt).toUTCString())} and works once. <a href="${REPO}">slopstream on GitHub</a> · <a href="${REPO}/blob/main/PRIVACY.md">Privacy</a></p>
|
|
39
|
+
${COPY_JS}`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const gonePage = () => page('Invite expired', `<h1>Invite not found</h1><p>This invite link has expired or was already used. Ask for a new one.</p><p class="muted"><a href="${REPO}">slopstream on GitHub</a></p>`);
|
|
43
|
+
|
|
44
|
+
export const landingPage = () => page('slopstream', `<h1>slopstream</h1><p>Your agent can ask mine. Let AI agents consult each other directly, with each person in control.</p>${cmd('npm install -g slopstream')}<p><a href="${REPO}">${REPO}</a></p>${COPY_JS}`);
|
package/relay/kv-file.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// KV store for the Node relay host: JSON files in DATA_DIR.
|
|
2
|
+
// users.json and links.json keep their historical format (relay/admin.js edits users.json while the relay runs,
|
|
3
|
+
// so `users` is re-read from disk on every get). Everything else lives in state.json.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const readJson = (f, d) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };
|
|
8
|
+
const writeJson = (f, v) => { fs.writeFileSync(f + '.tmp', JSON.stringify(v, null, 2)); fs.renameSync(f + '.tmp', f); };
|
|
9
|
+
|
|
10
|
+
export class FileKV {
|
|
11
|
+
constructor(dir) {
|
|
12
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
13
|
+
this.usersFile = path.join(dir, 'users.json');
|
|
14
|
+
this.linksFile = path.join(dir, 'links.json');
|
|
15
|
+
this.auditFile = path.join(dir, 'audit.jsonl');
|
|
16
|
+
this.stateFile = path.join(dir, 'state.json');
|
|
17
|
+
this.state = readJson(this.stateFile, {});
|
|
18
|
+
}
|
|
19
|
+
get(k) {
|
|
20
|
+
if (k === 'users') return readJson(this.usersFile, {});
|
|
21
|
+
if (k === 'links') return readJson(this.linksFile, []);
|
|
22
|
+
const v = this.state[k];
|
|
23
|
+
return v === undefined ? undefined : structuredClone(v);
|
|
24
|
+
}
|
|
25
|
+
put(k, v) {
|
|
26
|
+
if (k === 'users') return writeJson(this.usersFile, v);
|
|
27
|
+
if (k === 'links') return writeJson(this.linksFile, v);
|
|
28
|
+
this.state[k] = structuredClone(v);
|
|
29
|
+
writeJson(this.stateFile, this.state);
|
|
30
|
+
}
|
|
31
|
+
del(k) {
|
|
32
|
+
if (k === 'users') return writeJson(this.usersFile, {});
|
|
33
|
+
if (k === 'links') return writeJson(this.linksFile, []);
|
|
34
|
+
delete this.state[k];
|
|
35
|
+
writeJson(this.stateFile, this.state);
|
|
36
|
+
}
|
|
37
|
+
list(prefix) {
|
|
38
|
+
return Object.entries(this.state).filter(([k]) => k.startsWith(prefix)).map(([k, v]) => [k, structuredClone(v)]);
|
|
39
|
+
}
|
|
40
|
+
appendAudit(o) { fs.appendFileSync(this.auditFile, JSON.stringify(o) + '\n'); }
|
|
41
|
+
}
|
package/relay/kv-mem.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// In-memory KV for unit tests. Same contract as FileKV (see dev plan §2.1): synchronous, JSON values.
|
|
2
|
+
export class MemKV {
|
|
3
|
+
constructor(init = {}) { this.m = new Map(Object.entries(init)); this.audit = []; }
|
|
4
|
+
get(k) { const v = this.m.get(k); return v === undefined ? undefined : structuredClone(v); }
|
|
5
|
+
put(k, v) { this.m.set(k, structuredClone(v)); }
|
|
6
|
+
del(k) { this.m.delete(k); }
|
|
7
|
+
list(p) { return [...this.m].filter(([k]) => k.startsWith(p)).map(([k, v]) => [k, structuredClone(v)]); }
|
|
8
|
+
appendAudit(o) { this.audit.push(o); }
|
|
9
|
+
}
|