@blueshed/joined 0.0.0-stage → 0.1.20
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/skills/joined/SKILL.md +17 -0
- package/.claude/skills/joined/reference.md +768 -0
- package/LICENSE +19 -0
- package/README.md +115 -2
- package/docs/design.md +148 -0
- package/docs/introduction.md +193 -0
- package/docs/learning.md +76 -0
- package/docs/stories.md +82 -0
- package/examples/app.css +27 -0
- package/examples/cafe/books.html +38 -0
- package/examples/cafe/books.json +13 -0
- package/examples/cafe/books.ts +64 -0
- package/examples/cafe/cafe.css +512 -0
- package/examples/cafe/front.html +115 -0
- package/examples/cafe/front.ts +7 -0
- package/examples/cafe/generated/books.elements.ts +52 -0
- package/examples/cafe/generated/books.queries.ts +11 -0
- package/examples/cafe/generated/books.rules.ts +42 -0
- package/examples/cafe/generated/kitchen.elements.ts +87 -0
- package/examples/cafe/generated/kitchen.queries.ts +47 -0
- package/examples/cafe/generated/kitchen.rules.ts +98 -0
- package/examples/cafe/generated/menu.elements.ts +61 -0
- package/examples/cafe/generated/menu.queries.ts +28 -0
- package/examples/cafe/generated/menu.rules.ts +65 -0
- package/examples/cafe/generated/order.elements.ts +87 -0
- package/examples/cafe/generated/order.queries.ts +47 -0
- package/examples/cafe/generated/order.rules.ts +95 -0
- package/examples/cafe/generated/staff.elements.ts +55 -0
- package/examples/cafe/generated/staff.queries.ts +27 -0
- package/examples/cafe/generated/staff.rules.ts +59 -0
- package/examples/cafe/generated/supplies.elements.ts +62 -0
- package/examples/cafe/generated/supplies.queries.ts +43 -0
- package/examples/cafe/generated/supplies.rules.ts +84 -0
- package/examples/cafe/generated/till.elements.ts +93 -0
- package/examples/cafe/generated/till.queries.ts +57 -0
- package/examples/cafe/generated/till.rules.ts +113 -0
- package/examples/cafe/index.html +70 -0
- package/examples/cafe/kitchen.css +107 -0
- package/examples/cafe/kitchen.html +39 -0
- package/examples/cafe/kitchen.ts +125 -0
- package/examples/cafe/menu.html +55 -0
- package/examples/cafe/menu.json +41 -0
- package/examples/cafe/menu.ts +84 -0
- package/examples/cafe/migrations/001-cafe.ts +11 -0
- package/examples/cafe/order.html +37 -0
- package/examples/cafe/order.ts +45 -0
- package/examples/cafe/rail-drag.ts +30 -0
- package/examples/cafe/routes.ts +32 -0
- package/examples/cafe/staff.json +20 -0
- package/examples/cafe/stories.jsonl +43 -0
- package/examples/cafe/supplies.html +77 -0
- package/examples/cafe/supplies.json +33 -0
- package/examples/cafe/supplies.ts +170 -0
- package/examples/cafe/till.json +95 -0
- package/examples/cafe/till.ts +122 -0
- package/examples/cafe/trust.ts +20 -0
- package/examples/cafe/views.ts +171 -0
- package/examples/docs.ts +28 -0
- package/examples/film.jpg +0 -0
- package/examples/hello/generated/elements.ts +45 -0
- package/examples/hello/generated/queries.ts +24 -0
- package/examples/hello/generated/rules.ts +45 -0
- package/examples/hello/hello.css +27 -0
- package/examples/hello/hello.json +1 -0
- package/examples/hello/index.html +32 -0
- package/examples/hello/migrations/001-hello.ts +6 -0
- package/examples/hello/page.ts +49 -0
- package/examples/hello/routes.ts +6 -0
- package/examples/hello/stories.jsonl +3 -0
- package/examples/index.html +146 -0
- package/examples/page.ts +11 -0
- package/examples/people/adding.ts +20 -0
- package/examples/people/generated/elements.ts +68 -0
- package/examples/people/generated/queries.ts +28 -0
- package/examples/people/generated/rules.ts +85 -0
- package/examples/people/links.ts +124 -0
- package/examples/people/migrations/001-people.ts +6 -0
- package/examples/people/migrations/002-add-people-member-and-guard-people.ts +7 -0
- package/examples/people/migrations/003-add-people-rank-and-guard-people.ts +7 -0
- package/examples/people/order.ts +61 -0
- package/examples/people/people.css +65 -0
- package/examples/people/people.json +26 -0
- package/examples/people/routes.ts +12 -0
- package/examples/people/stories.jsonl +20 -0
- package/examples/people/trust.ts +14 -0
- package/examples/people/view.ts +115 -0
- package/examples/routes.ts +11 -0
- package/examples/trip/answer-rows.ts +70 -0
- package/examples/trip/answers.ts +11 -0
- package/examples/trip/bar.ts +89 -0
- package/examples/trip/calendar-map.css +709 -0
- package/examples/trip/calendar-map.ts +249 -0
- package/examples/trip/drags.ts +143 -0
- package/examples/trip/drawer.ts +250 -0
- package/examples/trip/event-form.ts +199 -0
- package/examples/trip/generated/elements.ts +144 -0
- package/examples/trip/generated/queries.ts +46 -0
- package/examples/trip/generated/rules.ts +239 -0
- package/examples/trip/holding.ts +61 -0
- package/examples/trip/ics.ts +117 -0
- package/examples/trip/index.html +82 -0
- package/examples/trip/line-stops.ts +92 -0
- package/examples/trip/line-words.ts +79 -0
- package/examples/trip/line.ts +121 -0
- package/examples/trip/map.ts +234 -0
- package/examples/trip/mercator.ts +28 -0
- package/examples/trip/migrations/001-trip.ts +7 -0
- package/examples/trip/migrations/002-add-events-zone-and-guard-events.ts +7 -0
- package/examples/trip/migrations/003-guard-events-and-create-events_asked-and-more.ts +9 -0
- package/examples/trip/migrations/004-create-stays.ts +6 -0
- package/examples/trip/migrations/005-guard-events-and-create-events_arrives-and-more.ts +8 -0
- package/examples/trip/month.ts +87 -0
- package/examples/trip/other-weeks.ts +67 -0
- package/examples/trip/page.ts +121 -0
- package/examples/trip/peek.ts +71 -0
- package/examples/trip/people-chips.ts +74 -0
- package/examples/trip/place-search.ts +51 -0
- package/examples/trip/places.ts +34 -0
- package/examples/trip/routes.ts +27 -0
- package/examples/trip/shell.ts +39 -0
- package/examples/trip/stays.css +51 -0
- package/examples/trip/stays.ts +68 -0
- package/examples/trip/stories.jsonl +72 -0
- package/examples/trip/time.ts +46 -0
- package/examples/trip/told.ts +48 -0
- package/examples/trip/trip.json +69 -0
- package/examples/trip/trust.ts +51 -0
- package/examples/trip/week.ts +237 -0
- package/examples/trip/words.ts +4 -0
- package/examples/trip/writes.ts +91 -0
- package/examples/trip/zones.ts +16 -0
- package/examples/trips/card.ts +149 -0
- package/examples/trips/generated/elements.ts +60 -0
- package/examples/trips/generated/queries.ts +28 -0
- package/examples/trips/generated/rules.ts +62 -0
- package/examples/trips/index.html +47 -0
- package/examples/trips/map.ts +52 -0
- package/examples/trips/migrations/001-trips.ts +8 -0
- package/examples/trips/new-trip.ts +46 -0
- package/examples/trips/page.ts +9 -0
- package/examples/trips/routes.ts +7 -0
- package/examples/trips/stories.jsonl +12 -0
- package/examples/trips/trips.css +183 -0
- package/examples/trips/trips.json +7 -0
- package/examples/weeks/derive.ts +23 -0
- package/examples/weeks/generated/elements.ts +52 -0
- package/examples/weeks/generated/rules.ts +33 -0
- package/examples/weeks/routes.ts +4 -0
- package/examples/weeks/weeks.json +1 -0
- package/examples/welcome.css +299 -0
- package/package.json +55 -4
- package/src/attachment.ts +70 -0
- package/src/cli.ts +52 -0
- package/src/client.ts +98 -0
- package/src/compile.ts +2034 -0
- package/src/css.d.ts +5 -0
- package/src/definitions.ts +268 -0
- package/src/demo.css +29 -0
- package/src/demo.ts +42 -0
- package/src/draft.ts +69 -0
- package/src/engine.ts +288 -0
- package/src/file-value.ts +13 -0
- package/src/files.ts +187 -0
- package/src/follow.ts +56 -0
- package/src/hues.ts +3 -0
- package/src/icon-names.ts +77 -0
- package/src/icon.png +0 -0
- package/src/icons.ts +32 -0
- package/src/keep.ts +33 -0
- package/src/link.ts +31 -0
- package/src/mcp.ts +252 -0
- package/src/members/demo.ts +53 -0
- package/src/members/generated/elements.ts +68 -0
- package/src/members/generated/queries.ts +29 -0
- package/src/members/generated/rules.ts +65 -0
- package/src/members/group.ts +294 -0
- package/src/members/keys.ts +221 -0
- package/src/members/members.json +9 -0
- package/src/members/migrations/001-members.ts +6 -0
- package/src/members/migrations/002-guard-members.ts +11 -0
- package/src/members/migrations/003-add-members-act-and-guard-members.ts +7 -0
- package/src/members/panel.css +208 -0
- package/src/members/panel.ts +398 -0
- package/src/members/routes.ts +4 -0
- package/src/members/stories.jsonl +27 -0
- package/src/members/trust.ts +116 -0
- package/src/migrate.ts +597 -0
- package/src/migrations/001-joined.ts +13 -0
- package/src/migrations/002-group-keys.ts +16 -0
- package/src/migrations/003-change-inverse.ts +10 -0
- package/src/migrations/004-change-followed.ts +6 -0
- package/src/ops.ts +61 -0
- package/src/page.css +79 -0
- package/src/page.ts +413 -0
- package/src/parts.css +471 -0
- package/src/parts.ts +152 -0
- package/src/server.ts +862 -0
- package/src/settings.ts +94 -0
- package/src/starter.ts +89 -0
- package/src/store.ts +815 -0
- package/src/stories.ts +387 -0
- package/src/toast.ts +52 -0
- package/src/together.ts +167 -0
- package/src/tokens.css +85 -0
- package/src/tokens.json +457 -0
- package/src/upkeep.ts +86 -0
- package/src/visitors.ts +43 -0
- package/src/write.ts +567 -0
- package/starter/CLAUDE.md +37 -0
- package/starter/gitignore +3 -0
- package/starter/tests/hello-page.test.ts +14 -0
- package/starter/tests/hello.test.ts +8 -0
- package/starter/tsconfig.json +17 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// The group: sign-in by link and the trust network, as the server's doors (the skill's reference, §11). The
|
|
2
|
+
// server knows nothing of members: it asks the group who a request is, whether a write may go and
|
|
3
|
+
// what it brings and leaves behind, what a page asks besides ops, and to guard an app's edges.
|
|
4
|
+
//
|
|
5
|
+
// A link is who you are. Opening it signs a browser in, with a cookie for a year, on every device
|
|
6
|
+
// it's opened on, until someone replaces it in the page. Root's link is ROOT_TOKEN, from .env, and
|
|
7
|
+
// never changes. A member holds their own link and the links of the people they invited, to give
|
|
8
|
+
// them again; the BDFL holds everyone's, for when an inviter is away. An agent's link signs in its
|
|
9
|
+
// maker, for the agent, and holds none of their keys. A removed member's link opens once more, to
|
|
10
|
+
// show them why, and then never. Without ROOT_TOKEN the group is open: anyone may read and write,
|
|
11
|
+
// and only the network's shape (who moves up) is kept.
|
|
12
|
+
|
|
13
|
+
import type { Engine } from "../engine.ts";
|
|
14
|
+
import { demoRoutes } from "./demo.ts";
|
|
15
|
+
import { parts, type Op } from "../ops.ts";
|
|
16
|
+
import { openKeys, type Agent } from "./keys.ts";
|
|
17
|
+
import { doc as OWN } from "./generated/rules.ts";
|
|
18
|
+
import { bdflOf, mayAsk, mayWrite, trust, withMovesUp, type Asked, type Member } from "./trust.ts";
|
|
19
|
+
|
|
20
|
+
/** A route's answer: given who asks, where it's an app's edge on a group (none where it's open). */
|
|
21
|
+
type Handler = (req: Request, who?: Who) => Response | Promise<Response>;
|
|
22
|
+
/** Who a request or a socket is: a member, by the token it came with, and the agent's link if it came by one. */
|
|
23
|
+
export type Who = { member: number; token: string; agent?: Agent };
|
|
24
|
+
/** A page's socket, as the server keeps it: the documents it subscribes to, who it is, and the site it came from. */
|
|
25
|
+
export type Data = { docs: Set<string>; who: Who | null; origin: string };
|
|
26
|
+
type Socket = Bun.ServerWebSocket<Data>;
|
|
27
|
+
/** A write the group lets go: its ops, with what they bring, and what follows them. */
|
|
28
|
+
/** A write the group lets go: its ops, with what they bring; what must land with them, in the write's own
|
|
29
|
+
* transaction (`within`: the keys of a member removed, a notice); and what follows once it has (`after`:
|
|
30
|
+
* pages told, or closed). */
|
|
31
|
+
type Write =
|
|
32
|
+
{ refused: string } | { ops: Op[]; within?: (applied: Op[]) => void; after: (applied: Op[]) => Promise<void> };
|
|
33
|
+
|
|
34
|
+
const COOKIE = "joined";
|
|
35
|
+
/** A year, in seconds: how long a link signs a browser in. */
|
|
36
|
+
const YEAR = 60 * 60 * 24 * 365;
|
|
37
|
+
const linkTo = (origin: string, token: string) => `${origin}/auth/${token}`;
|
|
38
|
+
/** An agent's link, as its agent uses it: the MCP door's address (src/mcp.ts), as an agent uses no page. Its token
|
|
39
|
+
* signs a page in at /auth/ too, for a script on the page's socket. */
|
|
40
|
+
const doorTo = (origin: string, token: string) => `${origin}/mcp/${token}`;
|
|
41
|
+
/** A message to a page. */
|
|
42
|
+
export const say = (ws: Socket, m: object) => void ws.send(JSON.stringify(m));
|
|
43
|
+
const farewellPage = (
|
|
44
|
+
words: string,
|
|
45
|
+
) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>joined</title>
|
|
46
|
+
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem;color:#222;background:#fff}</style></head>
|
|
47
|
+
<body><h1>You've been removed from the group</h1><p>${Bun.escapeHTML(words)}</p><p>This link won't open again.</p></body></html>`;
|
|
48
|
+
|
|
49
|
+
/** The group's doors, for a server that reads its documents by name and keeps them in `db`, where the
|
|
50
|
+
* keys are too (a keys file from before the database, `keysFile`, is brought in once). */
|
|
51
|
+
export async function groupOf({
|
|
52
|
+
rootToken,
|
|
53
|
+
db,
|
|
54
|
+
keysFile,
|
|
55
|
+
lasts = true,
|
|
56
|
+
read,
|
|
57
|
+
accepted,
|
|
58
|
+
demo,
|
|
59
|
+
holds,
|
|
60
|
+
}: {
|
|
61
|
+
/** The documents a member may hold, told to their pages with who they are: a link to a page they can't is hidden. */
|
|
62
|
+
holds?: (member: number) => string[];
|
|
63
|
+
/** A demo on this machine (never live): anyone here may be any member, without their link (/as); whether a
|
|
64
|
+
* request is from this machine. */
|
|
65
|
+
demo?: (req: Request) => boolean;
|
|
66
|
+
/** In by their link: what follows for them (the act their invitation names). */
|
|
67
|
+
accepted?: (who: Who) => Promise<void>;
|
|
68
|
+
rootToken?: string;
|
|
69
|
+
db: Engine;
|
|
70
|
+
keysFile?: string;
|
|
71
|
+
/** Whether the database lasts (a file, not memory): only then is the keys file renamed once brought in. */
|
|
72
|
+
lasts?: boolean;
|
|
73
|
+
read: (doc: string) => Record<string, unknown>;
|
|
74
|
+
}) {
|
|
75
|
+
const members = () => read(OWN).members as Member[];
|
|
76
|
+
const open = {
|
|
77
|
+
routes: {},
|
|
78
|
+
at: async (_req: Request): Promise<Who | null | Response> => null,
|
|
79
|
+
edge: (answer: Handler) => answer,
|
|
80
|
+
admit: (_ws: Socket) => {},
|
|
81
|
+
opened: async (_ws: Socket, _doc: string) => {},
|
|
82
|
+
left: (_ws: Socket) => {},
|
|
83
|
+
write: (doc: string, ops: Op[], _who: Who | null, _why?: string): Write => ({
|
|
84
|
+
ops: doc === OWN ? withMovesUp(ops, members()) : ops,
|
|
85
|
+
after: async () => {},
|
|
86
|
+
}),
|
|
87
|
+
asked: async (_ws: Socket, m: Asked & { id: number }): Promise<object> => ({
|
|
88
|
+
refused: m.id,
|
|
89
|
+
why: "sign in with your link first",
|
|
90
|
+
}),
|
|
91
|
+
tokenOf: async (_member: number): Promise<string | null> => null,
|
|
92
|
+
whoIs: async (_token: string): Promise<Who | null> => null,
|
|
93
|
+
};
|
|
94
|
+
if (!rootToken) return open;
|
|
95
|
+
|
|
96
|
+
const keys = await openKeys(db, rootToken, { from: keysFile, rename: lasts });
|
|
97
|
+
const bdfl = () => bdflOf(members())!.id;
|
|
98
|
+
const nameOf = (id: number) => members().find((m) => m.id === id)?.name ?? "someone";
|
|
99
|
+
keys.keepOnly(members().map((m) => m.id));
|
|
100
|
+
// a link for each member who has none; a key this ROOT_TOKEN can't open is left as it is, and said
|
|
101
|
+
for (const m of members()) if (m.id !== bdfl() && !keys.kept(m.id)) await keys.tokenOf(m.id);
|
|
102
|
+
const shut = keys.unopened();
|
|
103
|
+
if (shut)
|
|
104
|
+
console.warn(
|
|
105
|
+
`${shut} member${shut === 1 ? "'s link doesn't" : "s' links don't"} open with this ROOT_TOKEN (it was replaced, or this is the wrong .env): each is replaced only when it's next asked for`,
|
|
106
|
+
);
|
|
107
|
+
const tokenOf = async (member: number) => (member === bdfl() ? rootToken : await keys.tokenOf(member));
|
|
108
|
+
|
|
109
|
+
const cookie = (req: Request, value: string, maxAge: number) =>
|
|
110
|
+
new Bun.Cookie(COOKIE, value, {
|
|
111
|
+
path: "/",
|
|
112
|
+
httpOnly: true,
|
|
113
|
+
sameSite: "lax",
|
|
114
|
+
secure: new URL(req.url).protocol === "https:" || req.headers.get("x-forwarded-proto") === "https",
|
|
115
|
+
maxAge,
|
|
116
|
+
}).serialize();
|
|
117
|
+
/** Home, this browser signed in by a token, for a year. */
|
|
118
|
+
const signedIn = (req: Request, token: string) =>
|
|
119
|
+
new Response(null, { status: 302, headers: { location: "/", "set-cookie": cookie(req, token, YEAR) } });
|
|
120
|
+
const tokenIn = (req: Request) => new Bun.CookieMap(req.headers.get("cookie") ?? "").get(COOKIE) ?? undefined;
|
|
121
|
+
async function whoIs(token: string | undefined): Promise<Who | null> {
|
|
122
|
+
if (!token) return null;
|
|
123
|
+
if (token === rootToken) return { member: bdfl(), token };
|
|
124
|
+
const who = await keys.whoIs(token);
|
|
125
|
+
return who && members().some((m) => m.id === who.member) ? { ...who, token } : null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// The pages open, to tell each member what's theirs, and to close what no longer opens.
|
|
129
|
+
const sockets = new Set<Socket>();
|
|
130
|
+
/** Each signed-in page holding the members (or these pages alone) is told who it is and the links it
|
|
131
|
+
* holds, as they are now. */
|
|
132
|
+
async function tell(pages: Iterable<Socket> = sockets) {
|
|
133
|
+
for (const ws of pages) {
|
|
134
|
+
const { docs, who, origin } = ws.data;
|
|
135
|
+
if (!docs.has(OWN) || !who) continue;
|
|
136
|
+
const mine = !who.agent && (await held(who.member, origin)); // an agent holds none of its maker's keys
|
|
137
|
+
say(ws, {
|
|
138
|
+
doc: OWN,
|
|
139
|
+
me: who.member,
|
|
140
|
+
bdfl: bdfl(),
|
|
141
|
+
holds: holds?.(who.member) ?? [],
|
|
142
|
+
agent: who.agent?.label ?? null,
|
|
143
|
+
links: mine ? mine.links : {},
|
|
144
|
+
agents: mine ? mine.agents : [],
|
|
145
|
+
notice: (!who.agent && keys.notice(who.member)) || null,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async function held(member: number, origin: string) {
|
|
150
|
+
const links: Record<number, string> = {};
|
|
151
|
+
for (const m of members())
|
|
152
|
+
if (m.id === member || m.inviter === member || member === bdfl())
|
|
153
|
+
links[m.id] = linkTo(origin, await tokenOf(m.id));
|
|
154
|
+
return {
|
|
155
|
+
links,
|
|
156
|
+
agents: keys.agents(member).map((a) => ({ id: a.id, label: a.label, link: doorTo(origin, a.token) })),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
const close = (gone: (who: Who) => boolean, why: object, code: number) => {
|
|
160
|
+
for (const ws of sockets)
|
|
161
|
+
if (ws.data.who && gone(ws.data.who)) (say(ws, { doc: OWN, ...why }), ws.close(code, "signed out"));
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
routes: {
|
|
166
|
+
// A link signs this browser in; a removed member's opens once, to show them why.
|
|
167
|
+
"/auth/:token": async (req: Bun.BunRequest<"/auth/:token">) => {
|
|
168
|
+
const token = req.params.token;
|
|
169
|
+
const who = await whoIs(token);
|
|
170
|
+
if (who) {
|
|
171
|
+
if (!who.agent) await accepted?.(who);
|
|
172
|
+
return signedIn(req, token);
|
|
173
|
+
}
|
|
174
|
+
const words = await keys.farewell(token);
|
|
175
|
+
if (words !== null)
|
|
176
|
+
return new Response(farewellPage(words), {
|
|
177
|
+
headers: { "content-type": "text/html; charset=utf-8", "set-cookie": cookie(req, "", 0) },
|
|
178
|
+
});
|
|
179
|
+
return new Response(null, { status: 302, headers: { location: "/?link=invalid" } });
|
|
180
|
+
},
|
|
181
|
+
// This browser forgets who it was; the link still works.
|
|
182
|
+
"/out": {
|
|
183
|
+
POST: (req: Request) =>
|
|
184
|
+
new Response(null, { status: 303, headers: { location: "/", "set-cookie": cookie(req, "", 0) } }),
|
|
185
|
+
},
|
|
186
|
+
// a demo's, on this machine alone (./demo.ts): be anyone, their link never shown
|
|
187
|
+
...(demo &&
|
|
188
|
+
demoRoutes({
|
|
189
|
+
here: demo,
|
|
190
|
+
members,
|
|
191
|
+
bdfl,
|
|
192
|
+
me: async (req) => (await whoIs(tokenIn(req)))?.member ?? null,
|
|
193
|
+
signIn: async (req, member) => signedIn(req, await tokenOf(member)),
|
|
194
|
+
})),
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
/** Who a request is, or the refusal of someone who hasn't signed in. */
|
|
198
|
+
async at(req: Request): Promise<Who | null | Response> {
|
|
199
|
+
return (await whoIs(tokenIn(req))) ?? new Response("sign in with your link", { status: 401 });
|
|
200
|
+
},
|
|
201
|
+
|
|
202
|
+
/** An app's edge, which hands out a document: a member's alone, given who they are, to read it as they see it.
|
|
203
|
+
* (A page is anyone's: it shows a stranger the note.) */
|
|
204
|
+
edge:
|
|
205
|
+
(answer: Handler): Handler =>
|
|
206
|
+
async (req) => {
|
|
207
|
+
const who = await whoIs(tokenIn(req));
|
|
208
|
+
return who ? answer(req, who) : new Response("sign in with your link", { status: 401 });
|
|
209
|
+
},
|
|
210
|
+
|
|
211
|
+
/** A page opening: closed, if who it's for has gone since it knocked. */
|
|
212
|
+
admit(ws: Socket) {
|
|
213
|
+
const who = ws.data.who;
|
|
214
|
+
if (who && !members().some((m) => m.id === who.member)) return void ws.close(4003, "removed");
|
|
215
|
+
sockets.add(ws);
|
|
216
|
+
},
|
|
217
|
+
/** A document a page subscribes to, and sent it: a page holding the members is told what's its (and
|
|
218
|
+
* only it: nothing of anyone else's has changed). */
|
|
219
|
+
async opened(ws: Socket, doc: string) {
|
|
220
|
+
if (doc === OWN) await tell([ws]);
|
|
221
|
+
},
|
|
222
|
+
left: (ws: Socket) => void sockets.delete(ws),
|
|
223
|
+
|
|
224
|
+
/** A write, as the network allows it: refused, or its ops (a removal bringing those who move up) and what follows. */
|
|
225
|
+
write(doc: string, ops: Op[], who: Who | null, why?: string): Write {
|
|
226
|
+
if (!who) return { refused: "sign in with your link first" };
|
|
227
|
+
const refused =
|
|
228
|
+
mayWrite(who, members(), doc === OWN) ??
|
|
229
|
+
(doc === OWN ? (ops.map((o) => trust(o, who.member, members(), why)).find((r) => r !== null) ?? null) : null);
|
|
230
|
+
if (refused) return { refused };
|
|
231
|
+
if (doc !== OWN) return { ops, after: async () => {} };
|
|
232
|
+
const before = structuredClone(members()),
|
|
233
|
+
by = nameOf(who.member);
|
|
234
|
+
const removed = (o: Op) => o.op === "remove" && parts(o.path).field === undefined;
|
|
235
|
+
const farewell = `${by} removed you from the group: ${why}`;
|
|
236
|
+
return {
|
|
237
|
+
ops: withMovesUp(ops, members()),
|
|
238
|
+
// with the write: a farewell for those removed, their keys gone; a notice for whoever was made
|
|
239
|
+
// read-only or given it back. (A new member's link is made when it's first asked for: an id is
|
|
240
|
+
// never handed out twice, so no old one can be waiting for it.)
|
|
241
|
+
within(applied: Op[]) {
|
|
242
|
+
for (const o of applied) {
|
|
243
|
+
const { key, field } = parts(o.path),
|
|
244
|
+
them = Number(key);
|
|
245
|
+
if (removed(o)) keys.remove(them, farewell);
|
|
246
|
+
// (made read-only by another when they are already is no news to them)
|
|
247
|
+
else if (
|
|
248
|
+
field === "readonly" &&
|
|
249
|
+
(o.op === "replace") !== (before.find((m) => m.id === them)?.readonly !== undefined)
|
|
250
|
+
)
|
|
251
|
+
keys.tell(them, { kind: o.op === "replace" ? "read-only" : "restored", why: why ?? "", by });
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
// once it has: the pages of those removed told why, and closed; every page holding the members told
|
|
255
|
+
async after(applied: Op[]) {
|
|
256
|
+
for (const o of applied.filter(removed))
|
|
257
|
+
close((w) => w.member === Number(parts(o.path).key), { farewell }, 4003);
|
|
258
|
+
await tell();
|
|
259
|
+
},
|
|
260
|
+
};
|
|
261
|
+
},
|
|
262
|
+
|
|
263
|
+
/** What a page asks besides ops. A member replacing their own link is told the new one, on the page
|
|
264
|
+
* that asked alone, which then closes as every page signed in with the old one does:
|
|
265
|
+
* whoever else holds the old link never hears the new. */
|
|
266
|
+
async asked(ws: Socket, m: Asked & { id: number }): Promise<object> {
|
|
267
|
+
const who = ws.data.who,
|
|
268
|
+
no = (why: string) => ({ refused: m.id, why });
|
|
269
|
+
if (!who) return no("sign in with your link first");
|
|
270
|
+
const refused = mayAsk(m, who, members(), keys.agents(who.member).length);
|
|
271
|
+
if (refused) return no(refused);
|
|
272
|
+
if (m.closeNotice) keys.closeNotice(who.member);
|
|
273
|
+
else if (m.relink !== undefined) {
|
|
274
|
+
const link = linkTo(ws.data.origin, await keys.replace(m.relink));
|
|
275
|
+
// your own: the new link told to this page alone, before the page is closed with the rest
|
|
276
|
+
if (m.relink === who.member) say(ws, { doc: OWN, link });
|
|
277
|
+
close((w) => w.member === m.relink && !w.agent, { replaced: true }, 4001);
|
|
278
|
+
} else if (m.agent !== undefined) await keys.makeAgent(who.member, m.agent);
|
|
279
|
+
else if (m.takeBack !== undefined) {
|
|
280
|
+
if (!keys.agents(who.member).some((a) => a.id === m.takeBack))
|
|
281
|
+
return no("that's not one of your agents' links");
|
|
282
|
+
keys.takeBack(m.takeBack);
|
|
283
|
+
close((w) => w.agent?.id === m.takeBack, { takenBack: true }, 4002);
|
|
284
|
+
} else return no("nothing asked");
|
|
285
|
+
await tell();
|
|
286
|
+
return { done: m.id };
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
/** A member's link token, for the terminal and the tests. */
|
|
290
|
+
tokenOf,
|
|
291
|
+
/** Who a link's token is (a member, and the agent's link if it's one), or no one: a removed member's, or none. */
|
|
292
|
+
whoIs,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// The members' keys, kept apart from the members document in tables of their own, in the same
|
|
2
|
+
// database (src/migrations/002-group-keys.ts), each link encrypted with a key made from ROOT_TOKEN: a
|
|
3
|
+
// copy of the database without .env opens nothing. Each member's link is its token, which works on
|
|
4
|
+
// every device until someone replaces it in the page. Root's token is ROOT_TOKEN itself, and is never
|
|
5
|
+
// kept. A token is found by its hash. A removed member's token keeps their farewell, shown once. A
|
|
6
|
+
// notice (made read-only, or given it back) waits for its member until they close it. An agent's link
|
|
7
|
+
// is a member's, with a label. What needs no encryption is synchronous, so a member removed and their
|
|
8
|
+
// keys go in one transaction.
|
|
9
|
+
|
|
10
|
+
import type { Engine } from "../engine.ts";
|
|
11
|
+
import { existsSync, renameSync } from "node:fs";
|
|
12
|
+
import { nextId } from "../migrate.ts";
|
|
13
|
+
|
|
14
|
+
export type Notice = { kind: "read-only" | "restored"; why: string; by: string };
|
|
15
|
+
export type Agent = { id: string; member: number; label: string };
|
|
16
|
+
type Box = { iv: string; data: string };
|
|
17
|
+
/** The keys as a file kept them, before the database: brought in once, as they were sealed. */
|
|
18
|
+
type Kept = {
|
|
19
|
+
members: Record<string, { hash: string; box: Box }>;
|
|
20
|
+
agents: Record<string, Agent & { hash: string; box: Box }>;
|
|
21
|
+
farewells: Record<string, string>;
|
|
22
|
+
notices: Record<string, Notice>;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const bytes = (s: string) => new TextEncoder().encode(s);
|
|
26
|
+
const hex = (b: ArrayBuffer) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
27
|
+
const b64 = (b: ArrayBuffer | Uint8Array) =>
|
|
28
|
+
Buffer.from(b instanceof Uint8Array ? b : new Uint8Array(b)).toString("base64");
|
|
29
|
+
const hash = async (token: string) => hex(await crypto.subtle.digest("SHA-256", bytes(token)));
|
|
30
|
+
const fresh = () => crypto.randomUUID().replaceAll("-", "");
|
|
31
|
+
|
|
32
|
+
/** The keys in a database, opened with ROOT_TOKEN; a keys file from before the database is brought in
|
|
33
|
+
* first, if the tables are empty, and then renamed (never deleted), unless `rename` is false: a
|
|
34
|
+
* database in memory doesn't last, and the file is still the keys. */
|
|
35
|
+
export async function openKeys(
|
|
36
|
+
db: Engine,
|
|
37
|
+
rootToken: string,
|
|
38
|
+
{ from, rename = true }: { from?: string; rename?: boolean } = {},
|
|
39
|
+
) {
|
|
40
|
+
const key = await crypto.subtle.importKey(
|
|
41
|
+
"raw",
|
|
42
|
+
await crypto.subtle.digest("SHA-256", bytes(`joined keys: ${rootToken}`)),
|
|
43
|
+
"AES-GCM",
|
|
44
|
+
false,
|
|
45
|
+
["encrypt", "decrypt"],
|
|
46
|
+
);
|
|
47
|
+
const seal = async (token: string): Promise<Box> => {
|
|
48
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
49
|
+
return { iv: b64(iv), data: b64(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, bytes(token))) };
|
|
50
|
+
};
|
|
51
|
+
const unseal = async (box: Box) =>
|
|
52
|
+
new TextDecoder().decode(
|
|
53
|
+
await crypto.subtle.decrypt(
|
|
54
|
+
{ name: "AES-GCM", iv: Buffer.from(box.iv, "base64") },
|
|
55
|
+
key,
|
|
56
|
+
Buffer.from(box.data, "base64"),
|
|
57
|
+
),
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
if (from && existsSync(from) && !db.query("SELECT 1 FROM member_keys").get()) {
|
|
61
|
+
const kept: Kept = await Bun.file(from).json();
|
|
62
|
+
db.transaction(() => {
|
|
63
|
+
for (const [m, k] of Object.entries(kept.members))
|
|
64
|
+
db.run("INSERT INTO member_keys (id, hash, box) VALUES (?, ?, ?)", [Number(m), k.hash, JSON.stringify(k.box)]);
|
|
65
|
+
for (const a of Object.values(kept.agents))
|
|
66
|
+
db.run("INSERT INTO agents (id, member, label, hash, box) VALUES (?, ?, ?, ?, ?)", [
|
|
67
|
+
Number(a.id),
|
|
68
|
+
a.member,
|
|
69
|
+
a.label,
|
|
70
|
+
a.hash,
|
|
71
|
+
JSON.stringify(a.box),
|
|
72
|
+
]);
|
|
73
|
+
for (const [h, words] of Object.entries(kept.farewells))
|
|
74
|
+
db.run("INSERT INTO farewells (id, hash, words) VALUES (?, ?, ?)", [nextId(db, "farewells"), h, words]);
|
|
75
|
+
for (const [m, n] of Object.entries(kept.notices))
|
|
76
|
+
db.run("INSERT INTO notices (id, kind, why, said_by) VALUES (?, ?, ?, ?)", [Number(m), n.kind, n.why, n.by]);
|
|
77
|
+
})();
|
|
78
|
+
if (rename) renameSync(from, `${from}.imported`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// the tokens, opened: one sealed with another ROOT_TOKEN can't be, and opening never deletes or
|
|
82
|
+
// replaces it (a command, or a start, with the wrong .env would lose every link): it signs in nobody,
|
|
83
|
+
// and is replaced only when its member's link is next asked for, as a rotated ROOT_TOKEN means
|
|
84
|
+
const tokens = new Map<number, string>(),
|
|
85
|
+
agentTokens = new Map<string, string>();
|
|
86
|
+
for (const r of db.query("SELECT id, box FROM member_keys").all() as { id: number; box: string }[])
|
|
87
|
+
await unseal(JSON.parse(r.box)).then(
|
|
88
|
+
(t) => tokens.set(r.id, t),
|
|
89
|
+
() => {},
|
|
90
|
+
);
|
|
91
|
+
for (const r of db.query("SELECT id, box FROM agents").all() as { id: number; box: string }[])
|
|
92
|
+
await unseal(JSON.parse(r.box)).then(
|
|
93
|
+
(t) => agentTokens.set(String(r.id), t),
|
|
94
|
+
() => {},
|
|
95
|
+
);
|
|
96
|
+
const making = new Map<number, Promise<string>>();
|
|
97
|
+
const agentsOf = (member: number) =>
|
|
98
|
+
(
|
|
99
|
+
db.query("SELECT id, label FROM agents WHERE member = ? ORDER BY id").all(member) as {
|
|
100
|
+
id: number;
|
|
101
|
+
label: string;
|
|
102
|
+
}[]
|
|
103
|
+
).filter((a) => agentTokens.has(String(a.id)));
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
/** A member's token: their link's, made if they have none. */
|
|
107
|
+
async tokenOf(member: number): Promise<string> {
|
|
108
|
+
if (tokens.has(member)) return tokens.get(member)!;
|
|
109
|
+
// one made at a time: two asking at once (two pages told) are both given the one link
|
|
110
|
+
const made = making.get(member) ?? this.replace(member).finally(() => making.delete(member));
|
|
111
|
+
making.set(member, made);
|
|
112
|
+
return made;
|
|
113
|
+
},
|
|
114
|
+
/** Whether a member has a key kept, opened or not. */
|
|
115
|
+
kept: (member: number) => !!db.query("SELECT 1 FROM member_keys WHERE id = ?").get(member),
|
|
116
|
+
/** How many keys are kept that this ROOT_TOKEN can't open. */
|
|
117
|
+
unopened: () => (db.query("SELECT COUNT(*) AS n FROM member_keys").get() as { n: number }).n - tokens.size,
|
|
118
|
+
/** Keys for these members alone: anyone else's (the document and the keys out of step) are dropped. */
|
|
119
|
+
keepOnly(ids: number[]) {
|
|
120
|
+
// (0 is no one's: a list with none in it is still a list)
|
|
121
|
+
const kept = [0, ...ids.map(Number)].join(", ");
|
|
122
|
+
db.run(`DELETE FROM member_keys WHERE id NOT IN (${kept})`);
|
|
123
|
+
db.run(`DELETE FROM notices WHERE id NOT IN (${kept})`);
|
|
124
|
+
db.run(`DELETE FROM agents WHERE member NOT IN (${kept})`);
|
|
125
|
+
for (const m of tokens.keys()) if (!ids.includes(m)) tokens.delete(m);
|
|
126
|
+
for (const id of agentTokens.keys())
|
|
127
|
+
if (!db.query("SELECT 1 FROM agents WHERE id = ?").get(Number(id))) agentTokens.delete(id);
|
|
128
|
+
},
|
|
129
|
+
/** A member's token if they have one, making none. */
|
|
130
|
+
peek: (member: number) => tokens.get(member),
|
|
131
|
+
/** A new link for a member: the old one stops opening. */
|
|
132
|
+
async replace(member: number) {
|
|
133
|
+
const token = fresh(),
|
|
134
|
+
sealed = [await hash(token), JSON.stringify(await seal(token))];
|
|
135
|
+
db.run(
|
|
136
|
+
"INSERT INTO member_keys (id, hash, box) VALUES (?, ?, ?) ON CONFLICT (id) DO UPDATE SET hash = excluded.hash, box = excluded.box",
|
|
137
|
+
[member, ...sealed],
|
|
138
|
+
);
|
|
139
|
+
tokens.set(member, token);
|
|
140
|
+
return token;
|
|
141
|
+
},
|
|
142
|
+
/** Who a token signs in: a member by their link, or by an agent's link they made; or nobody. */
|
|
143
|
+
async whoIs(token: string): Promise<{ member: number; agent?: Agent } | null> {
|
|
144
|
+
const h = await hash(token);
|
|
145
|
+
const m = db.query("SELECT id FROM member_keys WHERE hash = ?").get(h) as { id: number } | null;
|
|
146
|
+
if (m && tokens.has(m.id)) return { member: m.id };
|
|
147
|
+
const a = db.query("SELECT id, member, label FROM agents WHERE hash = ?").get(h) as {
|
|
148
|
+
id: number;
|
|
149
|
+
member: number;
|
|
150
|
+
label: string;
|
|
151
|
+
} | null;
|
|
152
|
+
return a && agentTokens.has(String(a.id))
|
|
153
|
+
? { member: a.member, agent: { id: String(a.id), member: a.member, label: a.label } }
|
|
154
|
+
: null;
|
|
155
|
+
},
|
|
156
|
+
/** A member gone: their link keeps the words left for them, shown once; their agents' links go. */
|
|
157
|
+
remove(member: number, farewell: string) {
|
|
158
|
+
const k = db.query("SELECT hash FROM member_keys WHERE id = ?").get(member) as { hash: string } | null;
|
|
159
|
+
if (k)
|
|
160
|
+
db.run("INSERT INTO farewells (id, hash, words) VALUES (?, ?, ?)", [nextId(db, "farewells"), k.hash, farewell]);
|
|
161
|
+
db.run("DELETE FROM member_keys WHERE id = ?", [member]);
|
|
162
|
+
db.run("DELETE FROM notices WHERE id = ?", [member]);
|
|
163
|
+
for (const a of agentsOf(member)) agentTokens.delete(String(a.id));
|
|
164
|
+
db.run("DELETE FROM agents WHERE member = ?", [member]);
|
|
165
|
+
tokens.delete(member);
|
|
166
|
+
},
|
|
167
|
+
/** The words left for whoever held this token, once: after this, it opens nothing. */
|
|
168
|
+
async farewell(token: string) {
|
|
169
|
+
const h = await hash(token);
|
|
170
|
+
const f = db.query("SELECT words FROM farewells WHERE hash = ?").get(h) as { words: string } | null;
|
|
171
|
+
if (!f) return null;
|
|
172
|
+
db.run("DELETE FROM farewells WHERE hash = ?", [h]);
|
|
173
|
+
return f.words;
|
|
174
|
+
},
|
|
175
|
+
notice(member: number): Notice | undefined {
|
|
176
|
+
const n = db.query("SELECT kind, why, said_by FROM notices WHERE id = ?").get(member) as {
|
|
177
|
+
kind: Notice["kind"];
|
|
178
|
+
why: string;
|
|
179
|
+
said_by: string;
|
|
180
|
+
} | null;
|
|
181
|
+
return n ? { kind: n.kind, why: n.why, by: n.said_by } : undefined;
|
|
182
|
+
},
|
|
183
|
+
tell(member: number, notice: Notice) {
|
|
184
|
+
db.run(
|
|
185
|
+
"INSERT INTO notices (id, kind, why, said_by) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET kind = excluded.kind, why = excluded.why, said_by = excluded.said_by",
|
|
186
|
+
[member, notice.kind, notice.why, notice.by],
|
|
187
|
+
);
|
|
188
|
+
},
|
|
189
|
+
closeNotice(member: number) {
|
|
190
|
+
db.run("DELETE FROM notices WHERE id = ?", [member]);
|
|
191
|
+
},
|
|
192
|
+
/** An agent's link for a member, labelled for its via. */
|
|
193
|
+
async makeAgent(member: number, label: string) {
|
|
194
|
+
const token = fresh(),
|
|
195
|
+
sealed = [await hash(token), JSON.stringify(await seal(token))];
|
|
196
|
+
const id = nextId(db, "agents");
|
|
197
|
+
db.run("INSERT INTO agents (id, member, label, hash, box) VALUES (?, ?, ?, ?, ?)", [
|
|
198
|
+
id,
|
|
199
|
+
member,
|
|
200
|
+
label,
|
|
201
|
+
...sealed,
|
|
202
|
+
]);
|
|
203
|
+
agentTokens.set(String(id), token);
|
|
204
|
+
return String(id);
|
|
205
|
+
},
|
|
206
|
+
/** A member's agents' links, with their tokens. */
|
|
207
|
+
agents: (member: number) =>
|
|
208
|
+
agentsOf(member).map(({ id, label }) => ({ id: String(id), label, token: agentTokens.get(String(id))! })),
|
|
209
|
+
/** An agent's link taken back: it opens nothing. */
|
|
210
|
+
takeBack(id: string) {
|
|
211
|
+
const a = db.query("SELECT id, member, label FROM agents WHERE id = ?").get(Number(id)) as {
|
|
212
|
+
id: number;
|
|
213
|
+
member: number;
|
|
214
|
+
label: string;
|
|
215
|
+
} | null;
|
|
216
|
+
db.run("DELETE FROM agents WHERE id = ?", [Number(id)]);
|
|
217
|
+
agentTokens.delete(id);
|
|
218
|
+
return a ? { id: String(a.id), member: a.member, label: a.label } : null;
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Made by `bun run compile` from the stories: what they say beyond the migrations before it.
|
|
2
|
+
import { createTable } from "joined/migrate";
|
|
3
|
+
|
|
4
|
+
export const changes = [
|
|
5
|
+
createTable("members", { columns: { name: { type: "text", is: { type: "string", said: "name is a string" } }, inviter: { type: "integer", nullable: true, is: { type: "integer", said: "inviter is a whole number" } }, readonly: { type: "boolean", nullable: true, is: { type: "boolean", said: "readonly is a boolean" } } }, strict: true, needs: { columns: ["name", "inviter"], said: "a member needs name (string), inviter (integer); may have readonly (boolean)" } }),
|
|
6
|
+
];
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Made by `bun run compile` from the stories, its type by hand: a member's readonly is who made them
|
|
2
|
+
// read-only, no longer whether they are. Until now only the BDFL could, so a read-only member is the
|
|
3
|
+
// BDFL's, and one given it back (false) is none.
|
|
4
|
+
import { guardTable, type Up } from "joined/migrate";
|
|
5
|
+
|
|
6
|
+
export const changes = [
|
|
7
|
+
guardTable("members", { columns: { name: { type: "text", is: { type: "string", said: "name is a string" } }, inviter: { type: "integer", is: { type: "integer", said: "inviter is a whole number" }, nullable: true }, readonly: { type: "integer", is: { type: "integer", said: "readonly is a whole number" }, nullable: true } }, strict: true, needs: { columns: ["name", "inviter"], said: "a member needs name (string), inviter (integer); may have readonly (integer)" } }),
|
|
8
|
+
];
|
|
9
|
+
|
|
10
|
+
export const up: Up = (db) =>
|
|
11
|
+
db.run(`UPDATE members SET readonly = CASE readonly WHEN 1 THEN (SELECT id FROM members WHERE inviter IS NULL) END`);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Made by `bun run compile` from the stories: what they say beyond the migrations before it.
|
|
2
|
+
import { addColumn, guardTable } from "joined/migrate";
|
|
3
|
+
|
|
4
|
+
export const changes = [
|
|
5
|
+
addColumn("members", "act", { type: "text", nullable: true, is: { type: "string", said: "act is a string" } }),
|
|
6
|
+
guardTable("members", { columns: { name: { type: "text", is: { type: "string", said: "name is a string" } }, inviter: { type: "integer", is: { type: "integer", said: "inviter is a whole number" }, nullable: true }, act: { type: "text", is: { type: "string", said: "act is a string" }, nullable: true }, readonly: { type: "integer", is: { type: "integer", said: "readonly is a whole number" }, nullable: true } }, strict: true, needs: { columns: ["name", "inviter"], said: "a member needs name (string), inviter (integer); may have act (string), readonly (integer)" } }),
|
|
7
|
+
];
|