securerooms 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/revoke.js ADDED
@@ -0,0 +1,110 @@
1
+ // Revoking one room pass, without changing ROOM_SECRET for everyone.
2
+ //
3
+ // Two parts:
4
+ // 1. Admin requests. Proof that a revoke came from whoever holds ROOM_SECRET (the same person who mints passes).
5
+ // Format: sra1.<base64url(JSON claims)>.<base64url(HMAC-SHA256)>, signed with a different key label from room
6
+ // passes, so a pass can never be used as an admin request or the other way round.
7
+ // Claims: { room, action: "revoke", jti? | peer?, iat, exp } (lives 5 minutes)
8
+ // or: { room, action: "reset_owner", iat, exp } (forget the room's owner; see src/lobby.js)
9
+ // 2. The blocklist each room keeps in its own Durable Object storage. Each entry deletes itself once every pass it
10
+ // could block has expired anyway (a pass lives at most a day), so the list stays tiny.
11
+ import { hmacKey, b64url, fromB64url, MAX_TTL_SECONDS } from "./token.js";
12
+
13
+ const PREFIX = "sra1";
14
+ const LABEL = "securerooms admin request v1";
15
+ export const ADMIN_TTL_SECONDS = 5 * 60;
16
+ const CLOCK_SKEW_SECONDS = 60;
17
+ const enc = new TextEncoder();
18
+ const ROOM_RE = /^[\w-]{1,64}$/;
19
+ const PEER_RE = /^[\w-]{1,32}$/;
20
+ const JTI_RE = /^[\w-]{1,64}$/;
21
+
22
+ // Exactly one target: one pass (by its id) or every pass for one agent name made before now.
23
+ function target({ jti, peer }) {
24
+ if (jti !== undefined && peer === undefined && JTI_RE.test(jti)) return { jti };
25
+ if (peer !== undefined && jti === undefined && PEER_RE.test(peer)) return { peer };
26
+ return null;
27
+ }
28
+
29
+ export async function mintAdminRequest(secret, { room, jti, peer, resetOwner = false, now = Math.floor(Date.now() / 1000) }) {
30
+ if (!ROOM_RE.test(room)) throw new Error("room must be 1-64 letters, digits, - or _");
31
+ const what = target({ jti, peer });
32
+ if (resetOwner ? jti !== undefined || peer !== undefined : !what) throw new Error("revoke needs exactly one of: a pass id, a peer name, or the owner reset");
33
+ const claims = resetOwner
34
+ ? { room, action: "reset_owner", iat: now, exp: now + ADMIN_TTL_SECONDS }
35
+ : { room, action: "revoke", ...what, iat: now, exp: now + ADMIN_TTL_SECONDS };
36
+ const body = b64url(enc.encode(JSON.stringify(claims)));
37
+ const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret, LABEL), enc.encode(`${PREFIX}.${body}`));
38
+ return `${PREFIX}.${body}.${b64url(sig)}`;
39
+ }
40
+
41
+ // Only the current ROOM_SECRET is accepted. A retired ROOM_SECRET_PREVIOUS may still let agents join during a
42
+ // rotation, but it has no admin power.
43
+ export async function verifyAdminRequest(token, secret, { room, now = Math.floor(Date.now() / 1000) }) {
44
+ const parts = typeof token === "string" ? token.split(".") : [];
45
+ if (parts.length !== 3 || parts[0] !== PREFIX) return { ok: false, reason: "malformed" };
46
+ let sig, claims;
47
+ try {
48
+ sig = fromB64url(parts[2]);
49
+ } catch {
50
+ return { ok: false, reason: "malformed" };
51
+ }
52
+ if (!(await crypto.subtle.verify("HMAC", await hmacKey(secret, LABEL), sig, enc.encode(`${PREFIX}.${parts[1]}`)))) {
53
+ return { ok: false, reason: "bad_signature" };
54
+ }
55
+ try {
56
+ claims = JSON.parse(new TextDecoder().decode(fromB64url(parts[1])));
57
+ } catch {
58
+ return { ok: false, reason: "malformed" };
59
+ }
60
+ if (!["revoke", "reset_owner"].includes(claims.action) || typeof claims.exp !== "number" || typeof claims.iat !== "number") return { ok: false, reason: "malformed" };
61
+ if (claims.exp <= now) return { ok: false, reason: "expired" };
62
+ if (claims.iat > now + CLOCK_SKEW_SECONDS || claims.exp - claims.iat > ADMIN_TTL_SECONDS) return { ok: false, reason: "bad_lifetime" };
63
+ if (claims.room !== room) return { ok: false, reason: "wrong_room" };
64
+ if (claims.action === "reset_owner") {
65
+ // No target allowed: an owner reset that also names a pass or a peer is not something this code ever makes.
66
+ if (claims.jti !== undefined || claims.peer !== undefined) return { ok: false, reason: "malformed" };
67
+ return { ok: true, action: "reset_owner", at: claims.iat };
68
+ }
69
+ const what = target(claims);
70
+ if (!what) return { ok: false, reason: "malformed" };
71
+ // `at` is the request's own signed issue time. A peer cutoff is pinned to it, so replaying the request later
72
+ // can never move the cutoff forward and catch a replacement pass.
73
+ return { ok: true, action: "revoke", target: what, at: claims.iat };
74
+ }
75
+
76
+ // The room's blocklist, kept under one storage key: { jtis: { [jti]: until }, peers: { [peer]: { before, until } } }
77
+ // Times are Unix seconds. `before` is the signed issue time of the revoke request: passes for this name issued at
78
+ // or before that second are revoked (passes only have whole-second times, so the same second counts as before).
79
+ // Fail-closed: a pass minted in the very same second as the revoke is revoked too; mint the replacement after.
80
+ const KEY = "blocklist";
81
+
82
+ export class Blocklist {
83
+ constructor(storage) {
84
+ this.storage = storage;
85
+ }
86
+
87
+ async read() {
88
+ return (this.list ??= (await this.storage.get(KEY)) || { jtis: {}, peers: {} });
89
+ }
90
+
91
+ // Is this pass revoked? `iat` is when the pass was made.
92
+ async has({ jti, peer, iat, now = Math.floor(Date.now() / 1000) }) {
93
+ const list = await this.read();
94
+ if (list.jtis[jti] > now) return true;
95
+ const cut = list.peers[peer];
96
+ return Boolean(cut && cut.until > now && iat <= cut.before);
97
+ }
98
+
99
+ // Adds an entry, drops ones that can no longer match anything, and saves. Revoking twice is harmless.
100
+ async add(what, at = Math.floor(Date.now() / 1000), now = Math.floor(Date.now() / 1000)) {
101
+ const list = await this.read();
102
+ // No pass that exists now can outlive this: the longest lifetime, plus the clock skew a pass is allowed to have.
103
+ const until = now + MAX_TTL_SECONDS + CLOCK_SKEW_SECONDS * 2;
104
+ if (what.jti) list.jtis[what.jti] = until;
105
+ if (what.peer) list.peers[what.peer] = { before: Math.max(list.peers[what.peer]?.before ?? 0, at), until };
106
+ for (const [k, t] of Object.entries(list.jtis)) if (t <= now) delete list.jtis[k];
107
+ for (const [k, c] of Object.entries(list.peers)) if (c.until <= now) delete list.peers[k];
108
+ await this.storage.put(KEY, list);
109
+ }
110
+ }
package/src/token.js ADDED
@@ -0,0 +1,125 @@
1
+ // Signed credentials. Plain Web Crypto, so the Worker, the room and the Node mint script share it.
2
+ //
3
+ // Two kinds, each with its own prefix and its own signing key, so one can never be passed off as the other:
4
+ // pass ar1.<claims>.<sig> made by a human with mint.mjs or the mint page. Works ONCE: the room swaps it
5
+ // for a ticket.
6
+ // ticket art1.<claims>.<sig> made by the room on every join, for the next reconnect. Also works once.
7
+ // Pass claims: { room, peer, iat, exp, jti, by? } (times are Unix seconds)
8
+ // Ticket claims: the same, plus tid (random ticket id). jti stays the pass's id, so the room knows it is the
9
+ // same agent, and exp is never later than the pass's.
10
+ // `by` is only on passes made by the mint page: a short tag for the signed-in person who made it (see minterTag).
11
+ // Passes made with ROOM_SECRET itself (mint.mjs) have none. It is inside the signed part, so it can't be changed,
12
+ // and a ticket carries its pass's tag along.
13
+ //
14
+ // Only someone holding ROOM_SECRET can make either, and changing any character breaks the signature.
15
+
16
+ // The WebSocket subprotocol clients offer next to their credential. The room answers with this name only,
17
+ // so a pass or ticket is never echoed back in the handshake response (where proxies and Logpush can see it).
18
+ export const PROTOCOL = "securerooms.v1";
19
+
20
+ const KINDS = {
21
+ pass: { prefix: "ar1", label: "agent-room join token v1" },
22
+ ticket: { prefix: "art1", label: "agent-room ticket v1" },
23
+ };
24
+ export const MAX_TTL_SECONDS = 24 * 60 * 60; // the Worker refuses passes that live longer than a day
25
+ export const MIN_SECRET_LENGTH = 32; // e.g. `openssl rand -hex 32` gives 64 characters
26
+ export const CLOCK_SKEW_SECONDS = 60;
27
+ const enc = new TextEncoder();
28
+ const BY_RE = /^[\w-]{16,64}$/;
29
+
30
+ export const b64url = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
31
+ export const fromB64url = (s) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
32
+
33
+ // The human viewer page's watch passes (src/watch.js) sign with their own key but are deliberately NOT in KINDS,
34
+ // so nothing that verifies agent passes or tickets can ever accept one.
35
+ const WATCH_LABEL = "agent-room watch token v1";
36
+
37
+ // `kind` is "pass", "ticket" or "watch". Anything else is taken as a label of its own (the revoke admin request uses
38
+ // one), so each kind of signed thing gets its own key and can never be accepted as another.
39
+ export async function hmacKey(secret, kind) {
40
+ // Domain-separated: each kind's signing key is derived from ROOM_SECRET, never the raw secret itself.
41
+ const raw = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
42
+ const label = kind === "watch" ? WATCH_LABEL : KINDS[kind]?.label ?? kind;
43
+ const derived = await crypto.subtle.sign("HMAC", raw, enc.encode(label));
44
+ return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
45
+ }
46
+
47
+ // The tag that goes in a pass's `by` claim: a fingerprint of who made the pass, for one room. It lets the room
48
+ // tell "the same person made this pass" without the pass carrying anyone's email address. Not a secret and not a
49
+ // key: its only job is to be the same for the same person and room, and it is covered by the pass's signature.
50
+ export async function minterTag(room, identity) {
51
+ const digest = await crypto.subtle.digest("SHA-256", enc.encode(`securerooms minter v1\n${room}\n${String(identity).toLowerCase()}`));
52
+ return b64url(digest.slice(0, 16));
53
+ }
54
+
55
+ export async function mintToken(secret, { room, peer, ttlSeconds = 8 * 60 * 60, now = Math.floor(Date.now() / 1000), by }) {
56
+ if (!secret || secret.length < MIN_SECRET_LENGTH) throw new Error(`ROOM_SECRET must be at least ${MIN_SECRET_LENGTH} characters (use openssl rand -hex 32)`);
57
+ if (!/^[\w-]{1,64}$/.test(room)) throw new Error("room must be 1-64 letters, digits, - or _");
58
+ if (!/^[\w-]{1,32}$/.test(peer) || peer === "all") throw new Error("peer must be 1-32 letters, digits, - or _ (and not 'all')");
59
+ if (!(ttlSeconds > 0 && ttlSeconds <= MAX_TTL_SECONDS)) throw new Error(`ttl must be between 1s and ${MAX_TTL_SECONDS}s`);
60
+ checkBy(by);
61
+ return sign(secret, "pass", { room, peer, iat: now, exp: now + ttlSeconds, jti: crypto.randomUUID(), ...(by && { by }) });
62
+ }
63
+
64
+ // Made by the room, never by a human: the credential for this agent's next reconnect. `by` is copied from the
65
+ // pass it stands in for, so the room still knows who made that pass.
66
+ export async function mintTicket(secret, { room, peer, exp, jti, by, tid = crypto.randomUUID(), now = Math.floor(Date.now() / 1000) }) {
67
+ checkBy(by);
68
+ return sign(secret, "ticket", { room, peer, iat: now, exp, jti, tid, ...(by && { by }) });
69
+ }
70
+
71
+ function checkBy(by) {
72
+ if (by !== undefined && (typeof by !== "string" || !BY_RE.test(by))) throw new Error("by must be a minter tag (see minterTag)");
73
+ }
74
+
75
+ async function sign(secret, kind, claims) {
76
+ const { prefix } = KINDS[kind];
77
+ const body = b64url(enc.encode(JSON.stringify(claims)));
78
+ const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret, kind), enc.encode(`${prefix}.${body}`));
79
+ return `${prefix}.${body}.${b64url(sig)}`;
80
+ }
81
+
82
+ // Reads the claims WITHOUT checking the signature. Only for showing a bridge its own expiry time.
83
+ export function peekToken(token) {
84
+ try {
85
+ return JSON.parse(new TextDecoder().decode(fromB64url(token.split(".")[1])));
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ // Which kind a credential claims to be ("pass", "ticket"), from its prefix alone. Not a check.
92
+ export const kindOf = (token) => Object.keys(KINDS).find((k) => token?.startsWith?.(`${KINDS[k].prefix}.`)) || null;
93
+
94
+ // Returns { ok: true, kind, claims } or { ok: false, reason }. Accepts a pass or a ticket. `secrets` lists the
95
+ // current secret first, then an optional previous one, so a secret can be rotated without kicking everyone.
96
+ // Whether a pass or ticket was already used is not known here: only the room remembers that.
97
+ export async function verifyToken(token, secrets, { room, peer, now = Math.floor(Date.now() / 1000) }) {
98
+ const parts = typeof token === "string" ? token.split(".") : [];
99
+ const kind = kindOf(token);
100
+ if (parts.length !== 3 || !kind) return { ok: false, reason: "malformed" };
101
+
102
+ let sig;
103
+ try {
104
+ sig = fromB64url(parts[2]);
105
+ } catch {
106
+ return { ok: false, reason: "malformed" };
107
+ }
108
+ let signed = false;
109
+ for (const secret of secrets.filter(Boolean)) {
110
+ // crypto.subtle.verify compares in constant time.
111
+ if (await crypto.subtle.verify("HMAC", await hmacKey(secret, kind), sig, enc.encode(`${parts[0]}.${parts[1]}`))) signed = true;
112
+ }
113
+ if (!signed) return { ok: false, reason: "bad_signature" };
114
+
115
+ const claims = peekToken(token);
116
+ if (!claims || typeof claims.exp !== "number" || typeof claims.iat !== "number") return { ok: false, reason: "malformed" };
117
+ if (claims.by !== undefined && (typeof claims.by !== "string" || !BY_RE.test(claims.by))) return { ok: false, reason: "malformed" };
118
+ if (claims.exp <= now) return { ok: false, reason: "expired" };
119
+ if (claims.iat > now + CLOCK_SKEW_SECONDS) return { ok: false, reason: "not_yet_valid" };
120
+ if (claims.exp - claims.iat > MAX_TTL_SECONDS) return { ok: false, reason: "ttl_too_long" };
121
+ if (claims.room !== room) return { ok: false, reason: "wrong_room" };
122
+ if (claims.peer !== peer) return { ok: false, reason: "wrong_peer" };
123
+ if (kind === "ticket" && typeof claims.tid !== "string") return { ok: false, reason: "malformed" };
124
+ return { ok: true, kind, claims };
125
+ }
package/src/watch.js ADDED
@@ -0,0 +1,51 @@
1
+ // "Watch passes" for the human viewer page. A different pass type from agent room passes, so neither can be
2
+ // used for the other's job: a different prefix AND a different signing key (derived with another label).
3
+ //
4
+ // Format: arw1.<base64url(JSON claims)>.<base64url(HMAC-SHA256 signature)>
5
+ // Claims: { room, stop, iat, exp, jti } stop = true lets the holder press Stop
6
+ import { b64url, fromB64url, hmacKey, MAX_TTL_SECONDS, MIN_SECRET_LENGTH, CLOCK_SKEW_SECONDS } from "./token.js";
7
+
8
+ const PREFIX = "arw1";
9
+ const enc = new TextEncoder();
10
+
11
+ export async function mintWatchToken(secret, { room, canStop = true, ttlSeconds = 8 * 60 * 60, now = Math.floor(Date.now() / 1000) }) {
12
+ if (!secret || secret.length < MIN_SECRET_LENGTH) throw new Error(`ROOM_SECRET must be at least ${MIN_SECRET_LENGTH} characters (use openssl rand -hex 32)`);
13
+ if (!/^[\w-]{1,64}$/.test(room)) throw new Error("room must be 1-64 letters, digits, - or _");
14
+ if (!(ttlSeconds > 0 && ttlSeconds <= MAX_TTL_SECONDS)) throw new Error(`ttl must be between 1s and ${MAX_TTL_SECONDS}s`);
15
+ const claims = { room, stop: !!canStop, iat: now, exp: now + ttlSeconds, jti: crypto.randomUUID() };
16
+ const body = b64url(enc.encode(JSON.stringify(claims)));
17
+ const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret, "watch"), enc.encode(`${PREFIX}.${body}`));
18
+ return `${PREFIX}.${body}.${b64url(sig)}`;
19
+ }
20
+
21
+ // Reads the claims WITHOUT checking the signature. Only for showing the viewer page what room it is for.
22
+ export function peekWatchToken(token) {
23
+ try {
24
+ return JSON.parse(new TextDecoder().decode(fromB64url(token.split(".")[1])));
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ export async function verifyWatchToken(token, secrets, { room, now = Math.floor(Date.now() / 1000) }) {
31
+ const parts = typeof token === "string" ? token.split(".") : [];
32
+ if (parts.length !== 3 || parts[0] !== PREFIX) return { ok: false, reason: "malformed" };
33
+ let sig;
34
+ try {
35
+ sig = fromB64url(parts[2]);
36
+ } catch {
37
+ return { ok: false, reason: "malformed" };
38
+ }
39
+ let signed = false;
40
+ for (const secret of secrets.filter(Boolean)) {
41
+ if (await crypto.subtle.verify("HMAC", await hmacKey(secret, "watch"), sig, enc.encode(`${PREFIX}.${parts[1]}`))) signed = true;
42
+ }
43
+ if (!signed) return { ok: false, reason: "bad_signature" };
44
+ const claims = peekWatchToken(token);
45
+ if (!claims || typeof claims.exp !== "number" || typeof claims.iat !== "number") return { ok: false, reason: "malformed" };
46
+ if (claims.exp <= now) return { ok: false, reason: "expired" };
47
+ if (claims.iat > now + CLOCK_SKEW_SECONDS) return { ok: false, reason: "not_yet_valid" };
48
+ if (claims.exp - claims.iat > MAX_TTL_SECONDS) return { ok: false, reason: "ttl_too_long" };
49
+ if (claims.room !== room) return { ok: false, reason: "wrong_room" };
50
+ return { ok: true, claims: { ...claims, stop: claims.stop === true } };
51
+ }
package/watch.mjs ADDED
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ // Make a link for the human watch page: node watch.mjs <room> [hours] [--read-only] [--local]
3
+ // Reads ROOM_SECRET from the environment (or .dev.vars with --local). Set AGENT_ROOM_HTTP=https://<worker> to
4
+ // print a ready-to-open link; otherwise only the pass is printed.
5
+ import fs from "node:fs";
6
+ import { parseEnv } from "node:util";
7
+ import { mintWatchToken } from "./src/watch.js";
8
+ import { MAX_TTL_SECONDS } from "./src/token.js";
9
+
10
+ const args = process.argv.slice(2);
11
+ const flag = (f) => args.includes(f);
12
+ const [room, hours = "8"] = args.filter((a) => !a.startsWith("--"));
13
+ if (!room) {
14
+ console.error("Usage: node watch.mjs <room> [hours, default 8, max 24] [--read-only] [--local]");
15
+ process.exit(1);
16
+ }
17
+ let secret = process.env.ROOM_SECRET;
18
+ if (!secret && flag("--local") && fs.existsSync(".dev.vars")) secret = parseEnv(fs.readFileSync(".dev.vars", "utf8")).ROOM_SECRET;
19
+ if (!secret) {
20
+ console.error("Set ROOM_SECRET (or pass --local for wrangler dev).");
21
+ process.exit(1);
22
+ }
23
+ const ttlSeconds = Math.round(Number(hours) * 3600);
24
+ if (!(ttlSeconds > 0 && ttlSeconds <= MAX_TTL_SECONDS)) {
25
+ console.error("hours must be more than 0 and at most 24");
26
+ process.exit(1);
27
+ }
28
+ try {
29
+ const pass = await mintWatchToken(secret, { room, canStop: !flag("--read-only"), ttlSeconds });
30
+ const base = process.env.AGENT_ROOM_HTTP?.replace(/\/$/, "");
31
+ // The pass goes after the # so browsers never send it to the server or put it in logs.
32
+ console.log(base ? `${base}/watch#${pass}` : pass);
33
+ } catch (e) {
34
+ console.error(e.message);
35
+ process.exit(1);
36
+ }