securerooms 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -11
- package/bridge.mjs +536 -45
- package/cli.mjs +7 -0
- package/hook.mjs +22 -12
- package/invite.mjs +67 -0
- package/package.json +22 -5
- package/revoke.mjs +77 -0
- package/src/attachments.js +60 -0
- package/src/history.js +53 -0
- package/src/inbox.js +27 -1
- package/src/revoke.js +110 -0
- package/src/token.js +74 -21
- package/src/watch.js +51 -0
- package/watch.mjs +36 -0
package/src/token.js
CHANGED
|
@@ -1,36 +1,82 @@
|
|
|
1
|
-
// Signed
|
|
1
|
+
// Signed credentials. Plain Web Crypto, so the Worker, the room and the Node mint script share it.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
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.
|
|
5
13
|
//
|
|
6
|
-
//
|
|
7
|
-
// and changing any character of it breaks the signature.
|
|
14
|
+
// Only someone holding ROOM_SECRET can make either, and changing any character breaks the signature.
|
|
8
15
|
|
|
9
|
-
|
|
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
|
+
};
|
|
10
24
|
export const MAX_TTL_SECONDS = 24 * 60 * 60; // the Worker refuses passes that live longer than a day
|
|
11
25
|
export const MIN_SECRET_LENGTH = 32; // e.g. `openssl rand -hex 32` gives 64 characters
|
|
12
|
-
const CLOCK_SKEW_SECONDS = 60;
|
|
26
|
+
export const CLOCK_SKEW_SECONDS = 60;
|
|
13
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));
|
|
14
32
|
|
|
15
|
-
|
|
16
|
-
|
|
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";
|
|
17
36
|
|
|
18
|
-
|
|
19
|
-
|
|
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.
|
|
20
41
|
const raw = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
21
|
-
const
|
|
42
|
+
const label = kind === "watch" ? WATCH_LABEL : KINDS[kind]?.label ?? kind;
|
|
43
|
+
const derived = await crypto.subtle.sign("HMAC", raw, enc.encode(label));
|
|
22
44
|
return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
|
23
45
|
}
|
|
24
46
|
|
|
25
|
-
|
|
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 }) {
|
|
26
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)`);
|
|
27
57
|
if (!/^[\w-]{1,64}$/.test(room)) throw new Error("room must be 1-64 letters, digits, - or _");
|
|
28
58
|
if (!/^[\w-]{1,32}$/.test(peer) || peer === "all") throw new Error("peer must be 1-32 letters, digits, - or _ (and not 'all')");
|
|
29
59
|
if (!(ttlSeconds > 0 && ttlSeconds <= MAX_TTL_SECONDS)) throw new Error(`ttl must be between 1s and ${MAX_TTL_SECONDS}s`);
|
|
30
|
-
|
|
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];
|
|
31
77
|
const body = b64url(enc.encode(JSON.stringify(claims)));
|
|
32
|
-
const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret), enc.encode(`${
|
|
33
|
-
return `${
|
|
78
|
+
const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret, kind), enc.encode(`${prefix}.${body}`));
|
|
79
|
+
return `${prefix}.${body}.${b64url(sig)}`;
|
|
34
80
|
}
|
|
35
81
|
|
|
36
82
|
// Reads the claims WITHOUT checking the signature. Only for showing a bridge its own expiry time.
|
|
@@ -42,11 +88,16 @@ export function peekToken(token) {
|
|
|
42
88
|
}
|
|
43
89
|
}
|
|
44
90
|
|
|
45
|
-
//
|
|
46
|
-
|
|
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.
|
|
47
97
|
export async function verifyToken(token, secrets, { room, peer, now = Math.floor(Date.now() / 1000) }) {
|
|
48
98
|
const parts = typeof token === "string" ? token.split(".") : [];
|
|
49
|
-
|
|
99
|
+
const kind = kindOf(token);
|
|
100
|
+
if (parts.length !== 3 || !kind) return { ok: false, reason: "malformed" };
|
|
50
101
|
|
|
51
102
|
let sig;
|
|
52
103
|
try {
|
|
@@ -57,16 +108,18 @@ export async function verifyToken(token, secrets, { room, peer, now = Math.floor
|
|
|
57
108
|
let signed = false;
|
|
58
109
|
for (const secret of secrets.filter(Boolean)) {
|
|
59
110
|
// crypto.subtle.verify compares in constant time.
|
|
60
|
-
if (await crypto.subtle.verify("HMAC", await hmacKey(secret), sig, enc.encode(`${
|
|
111
|
+
if (await crypto.subtle.verify("HMAC", await hmacKey(secret, kind), sig, enc.encode(`${parts[0]}.${parts[1]}`))) signed = true;
|
|
61
112
|
}
|
|
62
113
|
if (!signed) return { ok: false, reason: "bad_signature" };
|
|
63
114
|
|
|
64
115
|
const claims = peekToken(token);
|
|
65
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" };
|
|
66
118
|
if (claims.exp <= now) return { ok: false, reason: "expired" };
|
|
67
119
|
if (claims.iat > now + CLOCK_SKEW_SECONDS) return { ok: false, reason: "not_yet_valid" };
|
|
68
120
|
if (claims.exp - claims.iat > MAX_TTL_SECONDS) return { ok: false, reason: "ttl_too_long" };
|
|
69
121
|
if (claims.room !== room) return { ok: false, reason: "wrong_room" };
|
|
70
122
|
if (claims.peer !== peer) return { ok: false, reason: "wrong_peer" };
|
|
71
|
-
return { ok:
|
|
123
|
+
if (kind === "ticket" && typeof claims.tid !== "string") return { ok: false, reason: "malformed" };
|
|
124
|
+
return { ok: true, kind, claims };
|
|
72
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
|
+
}
|