easel-canvas 0.5.0 → 0.6.0
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 +27 -1
- package/bin/server.mjs +3 -2
- package/dist/assets/index-DE0ohrot.js +75 -0
- package/dist/assets/{index-0pl9ILre.css → index-yigh_b3W.css} +1 -1
- package/dist/favicon.svg +1 -0
- package/dist/index.html +3 -2
- package/package.json +3 -2
- package/server/args.mjs +4 -2
- package/server/export.mjs +10 -3
- package/server/index.mjs +20 -1
- package/server/live/dispatch.mjs +168 -0
- package/server/live/inventory.mjs +101 -0
- package/server/live/live.mjs +366 -0
- package/server/live/proto.mjs +101 -0
- package/server/live/routes.mjs +49 -0
- package/server/routes.mjs +16 -3
- package/dist/assets/index-BRuM-YIO.js +0 -75
- package/dist/viewer/viewer.css +0 -1
- package/dist/viewer/viewer.js +0 -56
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-12-05, reviewed by Hyun Park
|
|
2
|
+
// Live share, the owner's side: one outbound WebSocket to the relay, one link (and key) per role, guests' frames opened with the
|
|
3
|
+
// key of the link they came by, their requests answered by the allow-list dispatcher (dispatch.mjs), a few canvas events and the
|
|
4
|
+
// people's cursors passed on. Everything here is in memory: closing Easel or pressing Stop ends the room; links never touch disk.
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import zlib from "node:zlib";
|
|
7
|
+
|
|
8
|
+
import { WebSocket } from "ws";
|
|
9
|
+
|
|
10
|
+
import { dispatch, guestEvent } from "./dispatch.mjs";
|
|
11
|
+
import { CHUNK, CLOSE, KIND, b64u, deriveLink, frame, linkFragment, open, randomBytes, seal, untext, unframe } from "./proto.mjs";
|
|
12
|
+
|
|
13
|
+
/** Where owners connect when nothing else is configured: the production relay (see docs/live-share-deploy.md) */
|
|
14
|
+
export const DEFAULT_RELAY = "wss://easel.d-t-it.com/live/ws";
|
|
15
|
+
/** Roles a link can carry in this stage (edit comes with stage 2) */
|
|
16
|
+
export const ROLES = ["view", "comment"];
|
|
17
|
+
export const LIMITS = {
|
|
18
|
+
/** Requests a guest may have in flight; more wait in a queue of QUEUE, beyond that 429 */
|
|
19
|
+
concurrent: 8,
|
|
20
|
+
queue: 64,
|
|
21
|
+
/** Token bucket per guest: requests per second and burst */
|
|
22
|
+
rate: 50,
|
|
23
|
+
burst: 100,
|
|
24
|
+
/** Cursor updates per second per guest (more are dropped) */
|
|
25
|
+
presence: 20,
|
|
26
|
+
/** Bytes the relay socket may hold before the owner waits */
|
|
27
|
+
buffered: 4 * 1024 * 1024,
|
|
28
|
+
/** A request body (comments) */
|
|
29
|
+
body: 64 * 1024,
|
|
30
|
+
/** Owner start: how long to wait for the relay's welcome */
|
|
31
|
+
connectMs: 6000,
|
|
32
|
+
/** A guest that says nothing after HELLO this long is dropped */
|
|
33
|
+
helloMs: 10000,
|
|
34
|
+
};
|
|
35
|
+
/** Guest cursor and avatar colours, by order of arrival (the owner is the selection blue) */
|
|
36
|
+
export const COLORS = ["#7a5af8", "#0e9384", "#c11574", "#b54708", "#155eef", "#4e5ba6", "#099250", "#dd2590"];
|
|
37
|
+
|
|
38
|
+
/** Text the owner deflates before sealing (images, fonts and other packed formats go as they are) */
|
|
39
|
+
const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|manifest\+json)|image\/svg\+xml)/i;
|
|
40
|
+
/** Smaller bodies are not worth a compressed frame */
|
|
41
|
+
const COMPRESS_MIN = 1024;
|
|
42
|
+
const deflate = promisify(zlib.deflateRaw);
|
|
43
|
+
|
|
44
|
+
const cleanName = (s) =>
|
|
45
|
+
String(s ?? "")
|
|
46
|
+
.replace(/[\u0000-\u001f\u007f--]/g, "")
|
|
47
|
+
.trim()
|
|
48
|
+
.slice(0, 40);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* ctx: the app server's context (store, broadcast, …). relay: wss URL of the relay (…/live/ws). WS: WebSocket class (tests).
|
|
52
|
+
* The app sees changes as { type: "live" } (read GET /api/live) and { type: "live-presence", peers } on its own socket.
|
|
53
|
+
*/
|
|
54
|
+
export function createLive(ctx, { relay = DEFAULT_RELAY, WS = WebSocket, limits = LIMITS } = {}) {
|
|
55
|
+
let st = fresh();
|
|
56
|
+
function fresh() {
|
|
57
|
+
return { status: "off", error: null, room: null, token: null, links: {}, guestUrl: null, guests: new Map(), owner: "", sock: null, retry: 0, timer: null, ownerCursor: null, reconnecting: false };
|
|
58
|
+
}
|
|
59
|
+
const notify = () => ctx.broadcast({ type: "live" });
|
|
60
|
+
|
|
61
|
+
/** One link per role: a 16-byte secret only ever in the link's fragment, its key and the id the relay sees */
|
|
62
|
+
async function makeLink(role) {
|
|
63
|
+
const secret = randomBytes(16);
|
|
64
|
+
const { key, linkId } = await deriveLink(secret, st.room);
|
|
65
|
+
st.links[role] = { role, secret, key, linkId };
|
|
66
|
+
}
|
|
67
|
+
const linkById = (id) => Object.values(st.links).find((l) => l.linkId === id) ?? null;
|
|
68
|
+
const linkUrl = (role) => (st.guestUrl && st.links[role] ? `${st.guestUrl}#${linkFragment(st.room, st.links[role].secret)}` : null);
|
|
69
|
+
|
|
70
|
+
function publicState() {
|
|
71
|
+
return {
|
|
72
|
+
status: st.status,
|
|
73
|
+
error: st.error,
|
|
74
|
+
/** On, but the relay connection dropped: guests see the last state until it is back */
|
|
75
|
+
reconnecting: st.status === "on" && st.reconnecting,
|
|
76
|
+
relay,
|
|
77
|
+
links: st.status === "on" ? Object.fromEntries(ROLES.map((r) => [r, linkUrl(r)])) : {},
|
|
78
|
+
guests: [...st.guests.values()].filter((g) => g.link && g.name).map((g) => ({ id: g.conn, name: g.name, role: g.link.role, color: g.color })),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function sendTo(g, hdr, body) {
|
|
83
|
+
if (!st.sock || st.sock.readyState !== 1 || !g.link) return;
|
|
84
|
+
const ct = await seal(g.link.key, st.room, "o2g", hdr, body);
|
|
85
|
+
while (st.sock && st.sock.bufferedAmount > limits.buffered) await new Promise((r) => setTimeout(r, 10));
|
|
86
|
+
st.sock?.send(frame(KIND.DATA, g.conn, ct));
|
|
87
|
+
}
|
|
88
|
+
const ready = () => [...st.guests.values()].filter((g) => g.link);
|
|
89
|
+
const people = () => [
|
|
90
|
+
{ id: 0, name: st.owner || "", owner: true, color: "owner" },
|
|
91
|
+
...ready()
|
|
92
|
+
.filter((g) => g.name)
|
|
93
|
+
.map((g) => ({ id: g.conn, name: g.name, role: g.link.role, color: g.color })),
|
|
94
|
+
];
|
|
95
|
+
const sendPeople = () => {
|
|
96
|
+
for (const g of ready()) void sendTo(g, { t: "people", people: people() });
|
|
97
|
+
notify();
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
let presTimer = null;
|
|
101
|
+
/** Cursors go out at most every 50 ms, batched (Cloudflare bills incoming messages; batching keeps both sides cheap) */
|
|
102
|
+
function schedulePresence() {
|
|
103
|
+
if (presTimer) return;
|
|
104
|
+
presTimer = setTimeout(() => {
|
|
105
|
+
presTimer = null;
|
|
106
|
+
const peers = ready()
|
|
107
|
+
.filter((g) => g.name && g.cursor)
|
|
108
|
+
.map((g) => ({ id: g.conn, name: g.name, color: g.color, ...g.cursor }));
|
|
109
|
+
ctx.broadcast({ type: "live-presence", peers });
|
|
110
|
+
const all = st.ownerCursor ? [{ id: 0, name: st.owner, color: "owner", ...st.ownerCursor }, ...peers] : peers;
|
|
111
|
+
for (const g of ready()) void sendTo(g, { t: "pres", peers: all.filter((p) => p.id !== g.conn) });
|
|
112
|
+
}, 50);
|
|
113
|
+
presTimer.unref?.();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Guest requests: a token bucket, at most `concurrent` in flight, a short queue, then 429 */
|
|
117
|
+
function admit(g) {
|
|
118
|
+
const now = Date.now();
|
|
119
|
+
g.tokens = Math.min(limits.burst, g.tokens + ((now - g.at) / 1000) * limits.rate);
|
|
120
|
+
g.at = now;
|
|
121
|
+
if (g.tokens < 1) return false;
|
|
122
|
+
g.tokens -= 1;
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
async function runRequest(g, hdr, body, queued = false) {
|
|
126
|
+
// A queued request was admitted when it arrived: it is not charged again (and so always runs, keeping the queue moving)
|
|
127
|
+
if (!queued && !admit(g)) return reply(g, hdr.id, { status: 429, type: "text/plain", body: new TextEncoder().encode("slow down") });
|
|
128
|
+
if (!queued && g.inflight >= limits.concurrent) {
|
|
129
|
+
if (g.queue.length >= limits.queue) return reply(g, hdr.id, { status: 429, type: "text/plain", body: new TextEncoder().encode("too many requests") });
|
|
130
|
+
return void g.queue.push([hdr, body]);
|
|
131
|
+
}
|
|
132
|
+
g.inflight++;
|
|
133
|
+
try {
|
|
134
|
+
const res = await dispatch(ctx, { role: g.link.role, name: g.name, key: `${g.link.linkId}:${g.conn}` }, { m: hdr.m, p: hdr.p, body: body.length > limits.body ? null : body, tooBig: body.length > limits.body });
|
|
135
|
+
await reply(g, hdr.id, res);
|
|
136
|
+
} catch (e) {
|
|
137
|
+
await reply(g, hdr.id, { status: 500, type: "text/plain", body: new TextEncoder().encode("error") });
|
|
138
|
+
if (process.env.EASEL_DEBUG) console.error(e);
|
|
139
|
+
} finally {
|
|
140
|
+
g.inflight--;
|
|
141
|
+
const next = g.queue.shift();
|
|
142
|
+
if (next) void runRequest(g, ...next, true);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async function reply(g, id, res) {
|
|
146
|
+
let body = res.body ?? new Uint8Array(0);
|
|
147
|
+
// Text is deflated before it is sealed (sealed bytes do not compress): the guest shell inflates it once all chunks are in
|
|
148
|
+
let z;
|
|
149
|
+
if (body.length >= COMPRESS_MIN && COMPRESSIBLE.test(res.type ?? "")) {
|
|
150
|
+
const packed = await deflate(body);
|
|
151
|
+
if (packed.length < body.length) (body = new Uint8Array(packed.buffer, packed.byteOffset, packed.length)), (z = "deflate-raw");
|
|
152
|
+
}
|
|
153
|
+
for (let off = 0, seq = 0; off < body.length || seq === 0; off += CHUNK, seq++) {
|
|
154
|
+
await sendTo(g, { t: "res", id, status: res.status, type: res.type, size: body.length, ...(z && { z }), seq, last: off + CHUNK >= body.length }, body.subarray(off, off + CHUNK));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function onGuestFrame(f) {
|
|
159
|
+
const g = st.guests.get(f.conn);
|
|
160
|
+
if (f.kind === KIND.JOIN) {
|
|
161
|
+
if (g) return; // the relay lists who is still here after we reconnect: they keep their link and name
|
|
162
|
+
const n = st.guests.size;
|
|
163
|
+
const entry = { conn: f.conn, link: null, name: "", color: COLORS[n % COLORS.length], cursor: null, tokens: limits.burst, at: Date.now(), inflight: 0, queue: [], pres: { n: 0, t: 0 } };
|
|
164
|
+
entry.helloTimer = setTimeout(() => !entry.link && kick(f.conn), limits.helloMs);
|
|
165
|
+
entry.helloTimer.unref?.();
|
|
166
|
+
st.guests.set(f.conn, entry);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (!g) return;
|
|
170
|
+
if (f.kind === KIND.LEAVE) {
|
|
171
|
+
clearTimeout(g.helloTimer);
|
|
172
|
+
st.guests.delete(f.conn);
|
|
173
|
+
if (g.link) {
|
|
174
|
+
sendPeople();
|
|
175
|
+
schedulePresence();
|
|
176
|
+
}
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (f.kind === KIND.HELLO) {
|
|
180
|
+
const link = linkById(untext(f.payload));
|
|
181
|
+
if (!link) return kick(f.conn);
|
|
182
|
+
g.link = link;
|
|
183
|
+
clearTimeout(g.helloTimer);
|
|
184
|
+
await sendTo(g, { t: "hello", role: link.role, owner: st.owner, title: (await ctx.store.readBoard().catch(() => ({}))).title ?? "", you: { id: g.conn, color: g.color } });
|
|
185
|
+
await sendTo(g, { t: "people", people: people() });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (f.kind !== KIND.DATA || !g.link) return;
|
|
189
|
+
let msg;
|
|
190
|
+
try {
|
|
191
|
+
msg = await open(g.link.key, st.room, "g2o", f.payload);
|
|
192
|
+
} catch {
|
|
193
|
+
return; // not sealed with this guest's link key: dropped
|
|
194
|
+
}
|
|
195
|
+
const h = msg.hdr ?? {};
|
|
196
|
+
if (h.t === "req" && Number.isInteger(h.id)) return runRequest(g, h, msg.body);
|
|
197
|
+
if (h.t === "join") {
|
|
198
|
+
const name = cleanName(h.name);
|
|
199
|
+
if (!name) return;
|
|
200
|
+
g.name = name;
|
|
201
|
+
return sendPeople();
|
|
202
|
+
}
|
|
203
|
+
if (h.t === "pres") {
|
|
204
|
+
const now = Date.now();
|
|
205
|
+
if (now - g.pres.t > 1000) g.pres = { n: 0, t: now };
|
|
206
|
+
if (++g.pres.n > limits.presence) return;
|
|
207
|
+
g.cursor = h.at && Number.isFinite(h.at.x) && Number.isFinite(h.at.y) ? { x: Math.round(h.at.x), y: Math.round(h.at.y) } : null;
|
|
208
|
+
schedulePresence();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function kick(conn) {
|
|
213
|
+
st.guests.delete(conn);
|
|
214
|
+
if (st.sock?.readyState === 1) st.sock.send(frame(KIND.KICK, conn));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Opens (or reopens) the relay socket. Resolves once the relay welcomed us, rejects when it cannot be reached */
|
|
218
|
+
function connect() {
|
|
219
|
+
return new Promise((resolve, reject) => {
|
|
220
|
+
let settled = false;
|
|
221
|
+
const sock = new WS(`${relay}/${st.room}?as=owner&token=${st.token}`);
|
|
222
|
+
sock.binaryType = "nodebuffer";
|
|
223
|
+
st.sock = sock;
|
|
224
|
+
const fail = (why) => {
|
|
225
|
+
if (settled) return;
|
|
226
|
+
settled = true;
|
|
227
|
+
clearTimeout(t);
|
|
228
|
+
try {
|
|
229
|
+
sock.terminate?.() ?? sock.close();
|
|
230
|
+
} catch {
|
|
231
|
+
/* gone */
|
|
232
|
+
}
|
|
233
|
+
reject(new Error(why));
|
|
234
|
+
};
|
|
235
|
+
const t = setTimeout(() => fail("The live share relay did not answer"), limits.connectMs);
|
|
236
|
+
sock.on("error", (e) => fail(e?.message || "The live share relay cannot be reached"));
|
|
237
|
+
sock.on("message", (data) => {
|
|
238
|
+
const f = unframe(new Uint8Array(data));
|
|
239
|
+
if (!f) return;
|
|
240
|
+
if (f.kind === KIND.WELCOME) {
|
|
241
|
+
let url = "";
|
|
242
|
+
let freshRoom = false;
|
|
243
|
+
try {
|
|
244
|
+
const w = JSON.parse(untext(f.payload));
|
|
245
|
+
url = w.guestUrl ?? "";
|
|
246
|
+
freshRoom = w.fresh === true;
|
|
247
|
+
} catch {
|
|
248
|
+
/* none */
|
|
249
|
+
}
|
|
250
|
+
// Back on a relay that had to make the room anew (it restarted, or we were away past the grace period): the guests we knew
|
|
251
|
+
// are not on it; they come back as new connections, and their old entries would be ghosts in the people list
|
|
252
|
+
if (freshRoom && st.guests.size) {
|
|
253
|
+
for (const g of st.guests.values()) clearTimeout(g.helloTimer);
|
|
254
|
+
st.guests.clear();
|
|
255
|
+
sendPeople();
|
|
256
|
+
schedulePresence();
|
|
257
|
+
}
|
|
258
|
+
// Links must point at https, or at a loopback page for a local relay
|
|
259
|
+
st.guestUrl = /^https:\/\/|^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?\//.test(url) ? url : null;
|
|
260
|
+
if (!settled) {
|
|
261
|
+
settled = true;
|
|
262
|
+
clearTimeout(t);
|
|
263
|
+
if (!st.guestUrl) return reject(new Error("The relay did not say where guests open links"));
|
|
264
|
+
resolve();
|
|
265
|
+
}
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
void onGuestFrame(f).catch(() => {});
|
|
269
|
+
});
|
|
270
|
+
sock.on("close", (code) => {
|
|
271
|
+
if (!settled) return fail(`The live share relay closed the connection (${code})`);
|
|
272
|
+
if (st.sock !== sock || st.status !== "on") return;
|
|
273
|
+
// Dropped: try again (the relay keeps the room for 30 s and tells guests to wait; after that they keep the last state and retry)
|
|
274
|
+
st.sock = null;
|
|
275
|
+
if (!st.reconnecting) (st.reconnecting = true), notify();
|
|
276
|
+
const wait = Math.min(30000, 1000 * 2 ** st.retry++);
|
|
277
|
+
st.timer = setTimeout(() => {
|
|
278
|
+
if (st.status !== "on") return;
|
|
279
|
+
connect().then(
|
|
280
|
+
() => {
|
|
281
|
+
st.retry = 0;
|
|
282
|
+
st.reconnecting = false;
|
|
283
|
+
notify();
|
|
284
|
+
},
|
|
285
|
+
() => {},
|
|
286
|
+
);
|
|
287
|
+
}, wait);
|
|
288
|
+
st.timer.unref?.();
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return {
|
|
294
|
+
state: publicState,
|
|
295
|
+
/** Starts a room (or returns the one that is on). owner: the name guests see */
|
|
296
|
+
async start({ owner } = {}) {
|
|
297
|
+
if (st.status === "on" || st.status === "connecting") return publicState();
|
|
298
|
+
st = fresh();
|
|
299
|
+
st.status = "connecting";
|
|
300
|
+
st.owner = cleanName(owner);
|
|
301
|
+
st.room = b64u(randomBytes(12));
|
|
302
|
+
st.token = b64u(randomBytes(16));
|
|
303
|
+
for (const r of ROLES) await makeLink(r);
|
|
304
|
+
notify();
|
|
305
|
+
try {
|
|
306
|
+
await connect();
|
|
307
|
+
st.status = "on";
|
|
308
|
+
} catch (e) {
|
|
309
|
+
st = { ...fresh(), status: "unavailable", error: String(e.message ?? e) };
|
|
310
|
+
}
|
|
311
|
+
notify();
|
|
312
|
+
return publicState();
|
|
313
|
+
},
|
|
314
|
+
/** Ends the room: every guest sees "ended" at once */
|
|
315
|
+
stop() {
|
|
316
|
+
if (st.sock?.readyState === 1) st.sock.send(frame(KIND.BYE));
|
|
317
|
+
const s = st.sock;
|
|
318
|
+
clearTimeout(st.timer);
|
|
319
|
+
st = fresh();
|
|
320
|
+
st.sock = null;
|
|
321
|
+
try {
|
|
322
|
+
s?.close(1000, "stopped");
|
|
323
|
+
} catch {
|
|
324
|
+
/* gone */
|
|
325
|
+
}
|
|
326
|
+
ctx.broadcast({ type: "live-presence", peers: [] });
|
|
327
|
+
notify();
|
|
328
|
+
return publicState();
|
|
329
|
+
},
|
|
330
|
+
/** The name guests see, changed while on: they get it in the next people list (the shell and canvas take the owner's entry) */
|
|
331
|
+
rename(owner) {
|
|
332
|
+
const name = cleanName(owner);
|
|
333
|
+
if (st.status === "on" && name !== st.owner) {
|
|
334
|
+
st.owner = name;
|
|
335
|
+
sendPeople();
|
|
336
|
+
}
|
|
337
|
+
return publicState();
|
|
338
|
+
},
|
|
339
|
+
/** A new link for this role: the old one stops working now and the guests who came by it are closed */
|
|
340
|
+
async rotate(role) {
|
|
341
|
+
if (st.status !== "on" || !ROLES.includes(role)) return publicState();
|
|
342
|
+
const old = st.links[role];
|
|
343
|
+
await makeLink(role);
|
|
344
|
+
for (const g of [...st.guests.values()]) if (g.link === old) kick(g.conn);
|
|
345
|
+
sendPeople();
|
|
346
|
+
return publicState();
|
|
347
|
+
},
|
|
348
|
+
/** A canvas event: passed on (filtered, see dispatch.mjs guestEvent) to every guest */
|
|
349
|
+
forward(msg) {
|
|
350
|
+
if (st.status !== "on") return;
|
|
351
|
+
const ev = guestEvent(msg);
|
|
352
|
+
if (ev) for (const g of ready()) void sendTo(g, { t: "ev", ev });
|
|
353
|
+
},
|
|
354
|
+
/** The owner's own cursor on the canvas (world coordinates), from the app's socket; null when it leaves the canvas */
|
|
355
|
+
ownerCursor(at) {
|
|
356
|
+
if (st.status !== "on") return;
|
|
357
|
+
st.ownerCursor = at && Number.isFinite(at.x) && Number.isFinite(at.y) ? { x: Math.round(at.x), y: Math.round(at.y) } : null;
|
|
358
|
+
schedulePresence();
|
|
359
|
+
},
|
|
360
|
+
close() {
|
|
361
|
+
if (st.status === "on") this.stop();
|
|
362
|
+
},
|
|
363
|
+
/** Tests: the guest frames' close codes */
|
|
364
|
+
CLOSE,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-12-05, reviewed by Hyun Park
|
|
2
|
+
// Live share wire protocol, shared by the owner's connector (server/live/live.mjs), the relays (relay/) and the guest shell
|
|
3
|
+
// (copied next to it by the build). Plain ESM with Web Crypto only, so it runs in Node 20+, Workers and browsers unchanged.
|
|
4
|
+
//
|
|
5
|
+
// Wire frame, what the relay sees: [kind u8][conn u32 big-endian][payload]
|
|
6
|
+
// DATA 1 payload = iv(12) ‖ AES-GCM-256(plaintext), AAD "easel-live:<room>:<g2o|o2g>"; owner→relay: conn = the guest
|
|
7
|
+
// JOIN 2 relay→owner: a guest connected (no payload)
|
|
8
|
+
// LEAVE 3 relay→owner: a guest left
|
|
9
|
+
// HELLO 4 guest→relay→owner: payload = link id (ascii, clear): which link key opens this guest's frames
|
|
10
|
+
// BYE 5 owner→relay: the owner ended the room; every guest is closed with CLOSE.ENDED (and drops what it saw)
|
|
11
|
+
// (an owner that stays away past the grace period closes guests with CLOSE.GONE instead: they keep the last view and retry)
|
|
12
|
+
// KICK 6 owner→relay: close guest `conn` with CLOSE.LINK (unknown or rotated link)
|
|
13
|
+
// WELCOME 7 relay→owner: payload = JSON {guestUrl}: where guests open links on this relay
|
|
14
|
+
// AWAY 8 relay→guest: the owner's connection dropped; the room waits GRACE_MS for it
|
|
15
|
+
// BACK 9 relay→guest: the owner is back
|
|
16
|
+
// Plaintext inside DATA: [header length u32][header JSON][body bytes]
|
|
17
|
+
export const KIND = { DATA: 1, JOIN: 2, LEAVE: 3, HELLO: 4, BYE: 5, KICK: 6, WELCOME: 7, AWAY: 8, BACK: 9 };
|
|
18
|
+
/** WebSocket close codes the guest page tells apart */
|
|
19
|
+
export const CLOSE = { ENDED: 4001, GONE: 4002, LINK: 4003, NO_ROOM: 4004, FULL: 4005, SLOW: 4008 };
|
|
20
|
+
/** Largest wire frame either side accepts (Cloudflare takes up to 32 MiB; we stay far below) */
|
|
21
|
+
export const MAX_FRAME = 1 << 20;
|
|
22
|
+
/** Body bytes per DATA frame */
|
|
23
|
+
export const CHUNK = 256 * 1024;
|
|
24
|
+
/** How long a room waits for an owner whose connection dropped without BYE */
|
|
25
|
+
export const GRACE_MS = 30000;
|
|
26
|
+
/** How long the relay remembers that a room was ended (its id and when, nothing else), so a guest who was away at the time gets ENDED */
|
|
27
|
+
export const ENDED_MS = 24 * 60 * 60 * 1000;
|
|
28
|
+
export const MAX_GUESTS = 20;
|
|
29
|
+
/** Room ids: 12 random bytes, base64url (16 characters) */
|
|
30
|
+
export const ROOM_RE = /^[A-Za-z0-9_-]{16}$/;
|
|
31
|
+
|
|
32
|
+
const enc = new TextEncoder();
|
|
33
|
+
const dec = new TextDecoder();
|
|
34
|
+
const subtle = () => globalThis.crypto.subtle;
|
|
35
|
+
|
|
36
|
+
export const randomBytes = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
|
|
37
|
+
|
|
38
|
+
export function b64u(bytes) {
|
|
39
|
+
let s = "";
|
|
40
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
41
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
42
|
+
}
|
|
43
|
+
export function unb64u(s) {
|
|
44
|
+
const b = atob(String(s).replace(/-/g, "+").replace(/_/g, "/"));
|
|
45
|
+
return Uint8Array.from(b, (c) => c.charCodeAt(0));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A link: https://<guest page>#<room>.<secret>. Both parts base64url, so "." cannot occur in them */
|
|
49
|
+
export function linkFragment(room, secret) {
|
|
50
|
+
return `${room}.${b64u(secret)}`;
|
|
51
|
+
}
|
|
52
|
+
export function parseFragment(hash) {
|
|
53
|
+
const m = /^#?([A-Za-z0-9_-]{16})\.([A-Za-z0-9_-]{22})$/.exec(String(hash ?? ""));
|
|
54
|
+
return m ? { room: m[1], secret: unb64u(m[2]) } : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** secret (16 bytes, only ever in the fragment) → { key: AES-GCM-256, linkId: 16 hex characters the relay may see } */
|
|
58
|
+
export async function deriveLink(secret, room) {
|
|
59
|
+
const base = await subtle().importKey("raw", secret, "HKDF", false, ["deriveKey", "deriveBits"]);
|
|
60
|
+
const salt = enc.encode(`easel-live:${room}`);
|
|
61
|
+
const key = await subtle().deriveKey({ name: "HKDF", hash: "SHA-256", salt, info: enc.encode("enc v1") }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
|
|
62
|
+
const bits = new Uint8Array(await subtle().deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: enc.encode("link id v1") }, base, 64));
|
|
63
|
+
return { key, linkId: [...bits].map((b) => b.toString(16).padStart(2, "0")).join("") };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function frame(kind, conn = 0, payload = new Uint8Array(0)) {
|
|
67
|
+
const out = new Uint8Array(5 + payload.length);
|
|
68
|
+
out[0] = kind;
|
|
69
|
+
new DataView(out.buffer).setUint32(1, conn >>> 0);
|
|
70
|
+
out.set(payload, 5);
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
export function unframe(data) {
|
|
74
|
+
const u = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
75
|
+
if (u.length < 5) return null;
|
|
76
|
+
return { kind: u[0], conn: new DataView(u.buffer, u.byteOffset, u.byteLength).getUint32(1), payload: u.subarray(5) };
|
|
77
|
+
}
|
|
78
|
+
export const text = (s) => enc.encode(s);
|
|
79
|
+
export const untext = (b) => dec.decode(b);
|
|
80
|
+
|
|
81
|
+
/** dir: "g2o" (guest to owner) or "o2g". The AAD binds a frame to its room and direction */
|
|
82
|
+
export async function seal(key, room, dir, hdr, body = new Uint8Array(0)) {
|
|
83
|
+
const h = enc.encode(JSON.stringify(hdr));
|
|
84
|
+
const plain = new Uint8Array(4 + h.length + body.length);
|
|
85
|
+
new DataView(plain.buffer).setUint32(0, h.length);
|
|
86
|
+
plain.set(h, 4);
|
|
87
|
+
plain.set(body, 4 + h.length);
|
|
88
|
+
const iv = randomBytes(12);
|
|
89
|
+
const ct = new Uint8Array(await subtle().encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(`easel-live:${room}:${dir}`) }, key, plain));
|
|
90
|
+
const out = new Uint8Array(12 + ct.length);
|
|
91
|
+
out.set(iv);
|
|
92
|
+
out.set(ct, 12);
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
/** Throws when the frame was not sealed with this key, for this room and direction */
|
|
96
|
+
export async function open(key, room, dir, data) {
|
|
97
|
+
const plain = new Uint8Array(await subtle().decrypt({ name: "AES-GCM", iv: data.subarray(0, 12), additionalData: enc.encode(`easel-live:${room}:${dir}`) }, key, data.subarray(12)));
|
|
98
|
+
const n = new DataView(plain.buffer).getUint32(0);
|
|
99
|
+
if (n > plain.length - 4) throw new Error("bad header length");
|
|
100
|
+
return { hdr: JSON.parse(dec.decode(plain.subarray(4, 4 + n))), body: plain.subarray(4 + n) };
|
|
101
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-12-05, reviewed by Hyun Park
|
|
2
|
+
// The owner's live-share controls, for the canvas page only: state (links included, so the Host must be local even for GET),
|
|
3
|
+
// start, stop and a new link for a role. Never reachable by guests (inventory.mjs: owner).
|
|
4
|
+
import { originAllowed, readBody, sendJson } from "../index.mjs";
|
|
5
|
+
|
|
6
|
+
/** POSTs need the page's own Origin (like the one-click update): no other site and no plain script starts a room */
|
|
7
|
+
const fromPage = (req) => !!req.headers.origin && originAllowed(req.headers);
|
|
8
|
+
|
|
9
|
+
export function liveRoutes() {
|
|
10
|
+
return [
|
|
11
|
+
["GET", "/api/live", async (req, res, url, ctx) => (originAllowed(req.headers) ? sendJson(res, 200, ctx.live?.state() ?? { status: "off", links: {}, guests: [] }) : sendJson(res, 403, { error: "Only the canvas page" }))],
|
|
12
|
+
[
|
|
13
|
+
"POST",
|
|
14
|
+
"/api/live/start",
|
|
15
|
+
async (req, res, url, ctx) => {
|
|
16
|
+
if (!fromPage(req)) return sendJson(res, 403, { error: "Only the canvas page can start live share" });
|
|
17
|
+
const b = await readBody(req);
|
|
18
|
+
sendJson(res, 200, await ctx.live.start({ owner: b.owner }));
|
|
19
|
+
},
|
|
20
|
+
],
|
|
21
|
+
[
|
|
22
|
+
"POST",
|
|
23
|
+
"/api/live/stop",
|
|
24
|
+
async (req, res, url, ctx) => {
|
|
25
|
+
if (!fromPage(req)) return sendJson(res, 403, { error: "Only the canvas page can stop live share" });
|
|
26
|
+
await readBody(req);
|
|
27
|
+
sendJson(res, 200, ctx.live.stop());
|
|
28
|
+
},
|
|
29
|
+
],
|
|
30
|
+
[
|
|
31
|
+
"POST",
|
|
32
|
+
"/api/live/owner",
|
|
33
|
+
async (req, res, url, ctx) => {
|
|
34
|
+
if (!fromPage(req)) return sendJson(res, 403, { error: "Only the canvas page can change the name" });
|
|
35
|
+
const b = await readBody(req);
|
|
36
|
+
sendJson(res, 200, ctx.live.rename(b.owner));
|
|
37
|
+
},
|
|
38
|
+
],
|
|
39
|
+
[
|
|
40
|
+
"POST",
|
|
41
|
+
"/api/live/rotate",
|
|
42
|
+
async (req, res, url, ctx) => {
|
|
43
|
+
if (!fromPage(req)) return sendJson(res, 403, { error: "Only the canvas page can change a link" });
|
|
44
|
+
const b = await readBody(req);
|
|
45
|
+
sendJson(res, 200, await ctx.live.rotate(String(b.role ?? "")));
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
];
|
|
49
|
+
}
|
package/server/routes.mjs
CHANGED
|
@@ -18,6 +18,8 @@ import { contentHash, livePatch } from "./livePatch.mjs";
|
|
|
18
18
|
import { readBody, safeJoin, sendJson } from "./index.mjs";
|
|
19
19
|
import { requestRoutes, undoState } from "./requests.mjs";
|
|
20
20
|
import { watchDesign } from "./watch.mjs";
|
|
21
|
+
import { createLive, DEFAULT_RELAY } from "./live/live.mjs";
|
|
22
|
+
import { liveRoutes } from "./live/routes.mjs";
|
|
21
23
|
|
|
22
24
|
const OUTER_LIMIT = 4096;
|
|
23
25
|
let selection = null;
|
|
@@ -38,7 +40,7 @@ async function readScreen(ctx, file) {
|
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
/* ---------- Comments (docs/design/comments.json) ---------- */
|
|
41
|
-
async function readComments(ctx) {
|
|
43
|
+
export async function readComments(ctx) {
|
|
42
44
|
try {
|
|
43
45
|
const d = JSON.parse(await fs.readFile(path.join(ctx.dir, "comments.json"), "utf8"));
|
|
44
46
|
return Array.isArray(d.comments) ? d.comments : [];
|
|
@@ -46,7 +48,7 @@ async function readComments(ctx) {
|
|
|
46
48
|
return [];
|
|
47
49
|
}
|
|
48
50
|
}
|
|
49
|
-
async function writeComments(ctx, comments) {
|
|
51
|
+
export async function writeComments(ctx, comments) {
|
|
50
52
|
await writeAtomic(path.join(ctx.dir, "comments.json"), JSON.stringify({ comments }, null, 1) + "\n");
|
|
51
53
|
ctx.broadcast({ type: "comments-changed" });
|
|
52
54
|
}
|
|
@@ -234,6 +236,7 @@ export const extraRoutes = [
|
|
|
234
236
|
],
|
|
235
237
|
...snapshotRoutes(),
|
|
236
238
|
...exportRoutes(),
|
|
239
|
+
...liveRoutes(),
|
|
237
240
|
// Assets: list and upload docs/design/assets/ (images, fonts). Screens reference them as ../assets/<name>
|
|
238
241
|
[
|
|
239
242
|
"GET",
|
|
@@ -458,11 +461,21 @@ export const extraRoutes = [
|
|
|
458
461
|
];
|
|
459
462
|
|
|
460
463
|
/** Things to attach after the server starts (file watching etc.) */
|
|
461
|
-
export async function attach(app) {
|
|
464
|
+
export async function attach(app, { relay } = {}) {
|
|
462
465
|
app.ctx.busy = chat.busy; // the one-click update waits while an Easel AI run is going
|
|
466
|
+
// Live share: off until the owner turns it on. Every app event also goes to the connector, which
|
|
467
|
+
// passes only the guest-safe ones (dispatch.mjs guestEvent) to the room.
|
|
468
|
+
const live = createLive(app.ctx, { relay: relay || process.env.EASEL_RELAY || DEFAULT_RELAY });
|
|
469
|
+
app.ctx.live = live;
|
|
470
|
+
const broadcast = app.ctx.broadcast;
|
|
471
|
+
app.ctx.broadcast = (msg) => {
|
|
472
|
+
broadcast(msg);
|
|
473
|
+
live.forward(msg);
|
|
474
|
+
};
|
|
463
475
|
const stop = watchDesign(app.ctx);
|
|
464
476
|
const close = app.close;
|
|
465
477
|
app.close = async () => {
|
|
478
|
+
live.close(); // closing Easel ends the room
|
|
466
479
|
chat.close(); // open permission requests are denied, so a waiting agent does not hang
|
|
467
480
|
await stop();
|
|
468
481
|
await closeBrowser();
|