@blueshed/joined 0.2.2 → 0.3.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.
Files changed (237) hide show
  1. package/.claude/skills/joined/SKILL.md +9 -1
  2. package/.claude/skills/joined/reference.md +316 -63
  3. package/.claude/skills/joined-door/SKILL.md +57 -0
  4. package/README.md +19 -50
  5. package/docs/design.md +158 -37
  6. package/docs/introduction.md +27 -27
  7. package/docs/light-and-shadow.svg +2 -1
  8. package/docs/links-and-trust.svg +1 -0
  9. package/docs/stories-to-code.svg +2 -1
  10. package/docs/wire-op.svg +1 -0
  11. package/examples/README.md +20 -0
  12. package/examples/account/account.json +1 -0
  13. package/examples/account/derive.ts +41 -0
  14. package/examples/account/generated/elements.ts +52 -0
  15. package/examples/account/generated/rows.ts +22 -0
  16. package/examples/account/generated/rules.ts +32 -0
  17. package/examples/account/routes.ts +5 -0
  18. package/examples/app.css +11 -1
  19. package/examples/cafe/books.html +2 -2
  20. package/examples/cafe/cafe.css +96 -85
  21. package/examples/cafe/generated/books.rows.ts +22 -0
  22. package/examples/cafe/generated/books.rules.ts +3 -2
  23. package/examples/cafe/generated/kitchen.rows.ts +27 -0
  24. package/examples/cafe/generated/kitchen.rules.ts +11 -1
  25. package/examples/cafe/generated/menu.rows.ts +22 -0
  26. package/examples/cafe/generated/menu.rules.ts +3 -2
  27. package/examples/cafe/generated/order.rows.ts +27 -0
  28. package/examples/cafe/generated/order.rules.ts +11 -1
  29. package/examples/cafe/generated/staff.elements.ts +7 -2
  30. package/examples/cafe/generated/staff.rows.ts +22 -0
  31. package/examples/cafe/generated/staff.rules.ts +9 -1
  32. package/examples/cafe/generated/supplies.queries.ts +4 -2
  33. package/examples/cafe/generated/supplies.rows.ts +22 -0
  34. package/examples/cafe/generated/supplies.rules.ts +17 -1
  35. package/examples/cafe/generated/till.queries.ts +2 -0
  36. package/examples/cafe/generated/till.rows.ts +27 -0
  37. package/examples/cafe/generated/till.rules.ts +11 -1
  38. package/examples/cafe/index.html +14 -15
  39. package/examples/cafe/kitchen.css +11 -19
  40. package/examples/cafe/kitchen.ts +7 -3
  41. package/examples/cafe/look.ts +30 -0
  42. package/examples/cafe/menu.html +10 -26
  43. package/examples/cafe/menu.ts +8 -80
  44. package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
  45. package/examples/cafe/order.html +8 -7
  46. package/examples/cafe/order.ts +6 -2
  47. package/examples/cafe/routes.ts +0 -1
  48. package/examples/cafe/staff.json +5 -0
  49. package/examples/cafe/stories.jsonl +6 -2
  50. package/examples/cafe/supplies.html +35 -34
  51. package/examples/cafe/supplies.ts +59 -39
  52. package/examples/cafe/till.ts +19 -11
  53. package/examples/cafe/views.ts +7 -5
  54. package/examples/chart/arches.ts +150 -0
  55. package/examples/chart/chart.css +11 -0
  56. package/examples/chart/chart.json +87 -0
  57. package/examples/chart/generated/elements.ts +105 -0
  58. package/examples/chart/generated/queries.ts +36 -0
  59. package/examples/chart/generated/rows.ts +27 -0
  60. package/examples/chart/generated/rules.ts +111 -0
  61. package/examples/chart/grid.ts +118 -0
  62. package/examples/chart/index.html +78 -0
  63. package/examples/chart/migrations/001-chart.ts +6 -0
  64. package/examples/chart/migrations/002-create-conditions.ts +6 -0
  65. package/examples/chart/page.ts +20 -0
  66. package/examples/chart/routes.ts +7 -0
  67. package/examples/chart/stories.jsonl +14 -0
  68. package/examples/chart/teeth.ts +57 -0
  69. package/examples/desk/desk.css +6 -10
  70. package/examples/desk/generated/elements.ts +1 -1
  71. package/examples/desk/generated/rows.ts +22 -0
  72. package/examples/desk/generated/rules.ts +34 -1
  73. package/examples/desk/index.html +10 -3
  74. package/examples/desk/lanes.css +21 -19
  75. package/examples/desk/routes.ts +0 -2
  76. package/examples/desk/stories.jsonl +4 -3
  77. package/examples/desk/tally.css +1 -1
  78. package/examples/desk/thumbs.ts +2 -2
  79. package/examples/docs.ts +7 -4
  80. package/examples/hello/generated/elements.ts +2 -2
  81. package/examples/hello/generated/rules.ts +3 -2
  82. package/examples/hello/hello.css +2 -4
  83. package/examples/hello/index.html +10 -3
  84. package/examples/hello/page.ts +4 -4
  85. package/examples/index.html +20 -12
  86. package/examples/notes/generated/elements.ts +112 -0
  87. package/examples/notes/generated/queries.ts +42 -0
  88. package/examples/notes/generated/rows.ts +27 -0
  89. package/examples/notes/generated/rules.ts +133 -0
  90. package/examples/notes/index.html +32 -0
  91. package/examples/notes/look.ts +41 -0
  92. package/examples/notes/migrations/001-notes.ts +7 -0
  93. package/examples/notes/notes.json +78 -0
  94. package/examples/notes/page.ts +21 -0
  95. package/examples/notes/routes.ts +6 -0
  96. package/examples/notes/stories.jsonl +24 -0
  97. package/examples/page.ts +9 -2
  98. package/examples/people/generated/rows.ts +22 -0
  99. package/examples/people/generated/rules.ts +11 -1
  100. package/examples/people/links.ts +8 -9
  101. package/examples/people/people.css +1 -1
  102. package/examples/people/routes.ts +1 -3
  103. package/examples/people/stories.jsonl +1 -0
  104. package/examples/people/view.ts +5 -2
  105. package/examples/trip/generated/elements.ts +5 -3
  106. package/examples/trip/generated/queries.ts +12 -1
  107. package/examples/trip/generated/rows.ts +27 -0
  108. package/examples/trip/generated/rules.ts +56 -2
  109. package/examples/trip/index.html +58 -12
  110. package/examples/trip/line.css +186 -0
  111. package/examples/trip/line.ts +51 -40
  112. package/examples/trip/page.ts +65 -71
  113. package/examples/trip/routes.ts +9 -5
  114. package/examples/trip/stays.css +13 -13
  115. package/examples/trip/stays.ts +15 -10
  116. package/examples/trip/stories.jsonl +2 -0
  117. package/examples/trip/told.ts +3 -26
  118. package/examples/trip/trip.css +16 -0
  119. package/examples/trips/generated/elements.ts +1 -1
  120. package/examples/trips/generated/rows.ts +22 -0
  121. package/examples/trips/generated/rules.ts +9 -1
  122. package/examples/trips/index.html +10 -10
  123. package/examples/trips/map.ts +3 -14
  124. package/examples/trips/new-trip.ts +14 -16
  125. package/examples/trips/trips.css +24 -23
  126. package/examples/weeks/generated/elements.ts +1 -1
  127. package/examples/weeks/generated/queries.ts +11 -0
  128. package/examples/weeks/generated/rows.ts +22 -0
  129. package/examples/weeks/generated/rules.ts +11 -5
  130. package/examples/weeks/routes.ts +3 -2
  131. package/examples/weeks/stories.jsonl +1 -0
  132. package/examples/welcome.css +43 -33
  133. package/package.json +8 -2
  134. package/src/attachment.ts +17 -2
  135. package/src/awesome.ts +103 -0
  136. package/src/board.css +76 -0
  137. package/src/board.ts +173 -0
  138. package/src/cli.ts +28 -3
  139. package/src/compile.ts +821 -109
  140. package/src/definitions.ts +113 -27
  141. package/src/demo.css +2 -5
  142. package/src/draft.ts +48 -27
  143. package/src/drawer.ts +248 -0
  144. package/src/engine.ts +253 -170
  145. package/src/fields.ts +341 -0
  146. package/src/file-value.ts +12 -2
  147. package/src/files.ts +113 -33
  148. package/src/ground.ts +110 -0
  149. package/src/icon-names.ts +19 -2
  150. package/src/keep.ts +16 -3
  151. package/src/kit.ts +51 -0
  152. package/src/link.ts +3 -3
  153. package/src/map.css +140 -0
  154. package/src/map.ts +200 -0
  155. package/src/mcp.ts +129 -24
  156. package/src/members/demo.ts +13 -12
  157. package/src/members/generated/rows.ts +22 -0
  158. package/src/members/generated/rules.ts +3 -2
  159. package/src/members/group.ts +105 -55
  160. package/src/members/keys.ts +95 -79
  161. package/src/members/panel.css +40 -35
  162. package/src/members/panel.ts +58 -37
  163. package/src/migrate.ts +178 -125
  164. package/src/migrations/005-change-kept.ts +7 -0
  165. package/src/month.css +129 -0
  166. package/src/month.ts +179 -0
  167. package/src/ops.ts +40 -1
  168. package/src/page.css +11 -2
  169. package/src/page.ts +68 -17
  170. package/src/parts.css +614 -230
  171. package/src/parts.ts +259 -36
  172. package/src/plane.css +61 -0
  173. package/src/plane.ts +153 -0
  174. package/src/postgres-server.ts +60 -0
  175. package/src/reading.css +73 -0
  176. package/src/reading.ts +238 -0
  177. package/src/rows.css +289 -0
  178. package/src/rows.ts +864 -0
  179. package/src/search.css +80 -0
  180. package/src/search.ts +130 -0
  181. package/src/server.ts +355 -137
  182. package/src/settings.ts +9 -4
  183. package/src/sheet.ts +116 -0
  184. package/src/skill.ts +40 -0
  185. package/src/slots.css +90 -0
  186. package/src/slots.ts +213 -0
  187. package/src/specs.ts +38 -0
  188. package/src/starter.ts +19 -2
  189. package/src/store.ts +224 -161
  190. package/src/stories.ts +43 -11
  191. package/src/surface.ts +164 -0
  192. package/src/time.ts +2 -0
  193. package/src/timeline.css +111 -0
  194. package/src/timeline.ts +235 -0
  195. package/src/toast.ts +21 -48
  196. package/src/together.ts +15 -24
  197. package/src/tokens.css +89 -3
  198. package/src/tokens.json +287 -7
  199. package/src/tool.ts +210 -0
  200. package/src/upkeep.ts +47 -22
  201. package/src/views.css +43 -0
  202. package/src/views.ts +111 -0
  203. package/src/week.css +150 -0
  204. package/src/week.ts +254 -0
  205. package/src/write.ts +326 -78
  206. package/starter/CHANGELOG.md +8 -0
  207. package/starter/CLAUDE.md +9 -3
  208. package/starter/bunfig +5 -0
  209. package/starter/githooks/pre-commit +13 -0
  210. package/starter/prettierignore +5 -0
  211. package/starter/tests/hello.test.ts +2 -0
  212. package/starter/tests/records.test.ts +40 -0
  213. package/starter/todo.jsonl +0 -0
  214. package/docs/learning.md +0 -76
  215. package/examples/cafe/trust.ts +0 -20
  216. package/examples/desk/trust.ts +0 -24
  217. package/examples/people/trust.ts +0 -14
  218. package/examples/trip/answer-rows.ts +0 -70
  219. package/examples/trip/bar.ts +0 -89
  220. package/examples/trip/calendar-map.css +0 -711
  221. package/examples/trip/calendar-map.ts +0 -249
  222. package/examples/trip/drags.ts +0 -143
  223. package/examples/trip/drawer.ts +0 -250
  224. package/examples/trip/event-form.ts +0 -200
  225. package/examples/trip/holding.ts +0 -61
  226. package/examples/trip/map.ts +0 -234
  227. package/examples/trip/month.ts +0 -87
  228. package/examples/trip/other-weeks.ts +0 -67
  229. package/examples/trip/peek.ts +0 -71
  230. package/examples/trip/people-chips.ts +0 -74
  231. package/examples/trip/shell.ts +0 -39
  232. package/examples/trip/trust.ts +0 -51
  233. package/examples/trip/week.ts +0 -237
  234. package/examples/trip/writes.ts +0 -91
  235. package/examples/trip/zones.ts +0 -16
  236. package/examples/weeks/derive.ts +0 -23
  237. package/src/scrim.ts +0 -81
@@ -10,6 +10,7 @@
10
10
  // show them why, and then never. Without ROOT_TOKEN the group is open: anyone may read and write,
11
11
  // and only the network's shape (who moves up) is kept.
12
12
 
13
+ import { timingSafeEqual } from "node:crypto";
13
14
  import type { Engine } from "../engine.ts";
14
15
  import { demoRoutes } from "./demo.ts";
15
16
  import { parts, type Op } from "../ops.ts";
@@ -24,14 +25,22 @@ export type Who = { member: number; token: string; agent?: Agent };
24
25
  /** A page's socket, as the server keeps it: the documents it subscribes to, who it is, and the site it came from. */
25
26
  /** A page's socket's own: the documents it holds, who it is, where it's from, and the changes a stranger's page made
26
27
  * (`<doc> <version>`), which only it may undo. */
27
- export type Data = { docs: Set<string>; who: Who | null; origin: string; made?: Set<string> };
28
+ export type Data = {
29
+ docs: Set<string>;
30
+ who: Who | null;
31
+ origin: string;
32
+ made?: Set<string>;
33
+ /** Its messages, answered in turn. */
34
+ queue?: Promise<unknown>;
35
+ };
28
36
  type Socket = Bun.ServerWebSocket<Data>;
29
37
  /** A write the group lets go: its ops, with what they bring, and what follows them. */
30
38
  /** A write the group lets go: its ops, with what they bring; what must land with them, in the write's own
31
39
  * transaction (`within`: the keys of a member removed, a notice); and what follows once it has (`after`:
32
40
  * pages told, or closed). */
33
41
  type Write =
34
- { refused: string } | { ops: Op[]; within?: (applied: Op[]) => void; after: (applied: Op[]) => Promise<void> };
42
+ | { refused: string }
43
+ | { ops: Op[]; within?: (applied: Op[]) => Promise<void>; after: (applied: Op[]) => Promise<void> };
35
44
 
36
45
  const COOKIE = "joined";
37
46
  /** A year, in seconds: how long a link signs a browser in. */
@@ -46,7 +55,10 @@ const farewellPage = (
46
55
  words: string,
47
56
  ) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>joined</title>
48
57
  <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>
49
- <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>`;
58
+ <body><h1>You've been removed from the group</h1><p>${Bun.escapeHTML(words)}</p><p>This link won't open again.</p>
59
+ <script>fetch(location.pathname, { method: "POST" })</script></body></html>`;
60
+ /** What a sign-in's answer says of where it came from: nothing, so its link (its token) never leaves in a Referer. */
61
+ const NO_REFERRER = { "referrer-policy": "no-referrer" };
50
62
 
51
63
  /** The group's doors, for a server that reads its documents by name and keeps them in `db`, where the
52
64
  * keys are too (a keys file from before the database, `keysFile`, is brought in once). */
@@ -61,7 +73,7 @@ export async function groupOf({
61
73
  holds,
62
74
  }: {
63
75
  /** The documents a member may hold, told to their pages with who they are: a link to a page they can't is hidden. */
64
- holds?: (member: number) => string[];
76
+ holds?: (member: number) => Promise<string[]>;
65
77
  /** A demo on this machine (never live): anyone here may be any member, without their link (/as); whether a
66
78
  * request is from this machine. */
67
79
  demo?: (req: Request) => boolean;
@@ -72,18 +84,18 @@ export async function groupOf({
72
84
  keysFile?: string;
73
85
  /** Whether the database lasts (a file, not memory): only then is the keys file renamed once brought in. */
74
86
  lasts?: boolean;
75
- read: (doc: string) => Record<string, unknown>;
87
+ read: (doc: string) => Promise<Record<string, unknown>>;
76
88
  }) {
77
- const members = () => read(OWN).members as Member[];
89
+ const members = async () => (await read(OWN)).members as Member[];
78
90
  const open = {
79
91
  routes: {},
80
92
  at: async (_req: Request): Promise<Who | null | Response> => null,
81
93
  edge: (answer: Handler) => answer,
82
- admit: (_ws: Socket) => {},
94
+ admit: async (_ws: Socket) => {},
83
95
  opened: async (_ws: Socket, _doc: string) => {},
84
96
  left: (_ws: Socket) => {},
85
- write: (doc: string, ops: Op[], _who: Who | null, _why?: string): Write => ({
86
- ops: doc === OWN ? withMovesUp(ops, members()) : ops,
97
+ write: async (doc: string, ops: Op[], _who: Who | null, _why?: string): Promise<Write> => ({
98
+ ops: doc === OWN ? withMovesUp(ops, await members()) : ops,
87
99
  after: async () => {},
88
100
  }),
89
101
  asked: async (_ws: Socket, m: Asked & { id: number }): Promise<object> => ({
@@ -92,21 +104,22 @@ export async function groupOf({
92
104
  }),
93
105
  tokenOf: async (_member: number): Promise<string | null> => null,
94
106
  whoIs: async (_token: string): Promise<Who | null> => null,
107
+ heard: async () => {},
95
108
  };
96
109
  if (!rootToken) return open;
97
110
 
98
111
  const keys = await openKeys(db, rootToken, { from: keysFile, rename: lasts });
99
- const bdfl = () => bdflOf(members())!.id;
100
- const nameOf = (id: number) => members().find((m) => m.id === id)?.name ?? "someone";
101
- keys.keepOnly(members().map((m) => m.id));
112
+ const bdfl = async () => bdflOf(await members())!.id;
113
+ const nameOf = async (id: number) => (await members()).find((m) => m.id === id)?.name ?? "someone";
114
+ await keys.keepOnly((await members()).map((m) => m.id));
102
115
  // a link for each member who has none; a key this ROOT_TOKEN can't open is left as it is, and said
103
- for (const m of members()) if (m.id !== bdfl() && !keys.kept(m.id)) await keys.tokenOf(m.id);
104
- const shut = keys.unopened();
116
+ for (const m of await members()) if (m.id !== (await bdfl()) && !(await keys.kept(m.id))) await keys.tokenOf(m.id);
117
+ const shut = await keys.unopened();
105
118
  if (shut)
106
119
  console.warn(
107
120
  `${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`,
108
121
  );
109
- const tokenOf = async (member: number) => (member === bdfl() ? rootToken : await keys.tokenOf(member));
122
+ const tokenOf = async (member: number) => (member === (await bdfl()) ? rootToken : await keys.tokenOf(member));
110
123
 
111
124
  const cookie = (req: Request, value: string, maxAge: number) =>
112
125
  new Bun.Cookie(COOKIE, value, {
@@ -118,13 +131,21 @@ export async function groupOf({
118
131
  }).serialize();
119
132
  /** Home, this browser signed in by a token, for a year. */
120
133
  const signedIn = (req: Request, token: string) =>
121
- new Response(null, { status: 302, headers: { location: "/", "set-cookie": cookie(req, token, YEAR) } });
134
+ new Response(null, {
135
+ status: 302,
136
+ headers: { location: "/", "set-cookie": cookie(req, token, YEAR), ...NO_REFERRER },
137
+ });
138
+ /** Whether a token is ROOT_TOKEN, asked in the same time whatever it is (=== stops at the first that differs). */
139
+ const same = (token: string, root: string) => {
140
+ const [a, b] = [Buffer.from(token), Buffer.from(root)];
141
+ return a.length === b.length && root !== "" && timingSafeEqual(a, b);
142
+ };
122
143
  const tokenIn = (req: Request) => new Bun.CookieMap(req.headers.get("cookie") ?? "").get(COOKIE) ?? undefined;
123
144
  async function whoIs(token: string | undefined): Promise<Who | null> {
124
145
  if (!token) return null;
125
- if (token === rootToken) return { member: bdfl(), token };
146
+ if (rootToken && same(token, rootToken)) return { member: await bdfl(), token };
126
147
  const who = await keys.whoIs(token);
127
- return who && members().some((m) => m.id === who.member) ? { ...who, token } : null;
148
+ return who && (await members()).some((m) => m.id === who.member) ? { ...who, token } : null;
128
149
  }
129
150
 
130
151
  // The pages open, to tell each member what's theirs, and to close what no longer opens.
@@ -139,23 +160,23 @@ export async function groupOf({
139
160
  say(ws, {
140
161
  doc: OWN,
141
162
  me: who.member,
142
- bdfl: bdfl(),
143
- holds: holds?.(who.member) ?? [],
163
+ bdfl: await bdfl(),
164
+ holds: (await holds?.(who.member)) ?? [],
144
165
  agent: who.agent?.label ?? null,
145
166
  links: mine ? mine.links : {},
146
167
  agents: mine ? mine.agents : [],
147
- notice: (!who.agent && keys.notice(who.member)) || null,
168
+ notice: (!who.agent && (await keys.notice(who.member))) || null,
148
169
  });
149
170
  }
150
171
  }
151
172
  async function held(member: number, origin: string) {
152
173
  const links: Record<number, string> = {};
153
- for (const m of members())
154
- if (m.id === member || m.inviter === member || member === bdfl())
155
- links[m.id] = linkTo(origin, await tokenOf(m.id));
174
+ const top = await bdfl();
175
+ for (const m of await members())
176
+ if (m.id === member || m.inviter === member || member === top) links[m.id] = linkTo(origin, await tokenOf(m.id));
156
177
  return {
157
178
  links,
158
- agents: keys.agents(member).map((a) => ({ id: a.id, label: a.label, link: doorTo(origin, a.token) })),
179
+ agents: (await keys.agents(member)).map((a) => ({ id: a.id, label: a.label, link: doorTo(origin, a.token) })),
159
180
  };
160
181
  }
161
182
  const close = (gone: (who: Who) => boolean, why: object, code: number) => {
@@ -165,20 +186,30 @@ export async function groupOf({
165
186
 
166
187
  return {
167
188
  routes: {
168
- // A link signs this browser in; a removed member's opens once, to show them why.
169
- "/auth/:token": async (req: Bun.BunRequest<"/auth/:token">) => {
170
- const token = req.params.token;
171
- const who = await whoIs(token);
172
- if (who) {
173
- if (!who.agent) await accepted?.(who);
174
- return signedIn(req, token);
175
- }
176
- const words = await keys.farewell(token);
177
- if (words !== null)
178
- return new Response(farewellPage(words), {
179
- headers: { "content-type": "text/html; charset=utf-8", "set-cookie": cookie(req, "", 0) },
180
- });
181
- return new Response(null, { status: 302, headers: { location: "/?link=invalid" } });
189
+ // A link signs this browser in, and does nothing else: a chat's preview of it fetches it too, so what an
190
+ // invitation does is done as its page opens (admit). A removed member's shows them why, until their page says
191
+ // they've seen it (its script, POST), which a preview never runs.
192
+ "/auth/:token": {
193
+ GET: async (req: Bun.BunRequest<"/auth/:token">) => {
194
+ try {
195
+ const token = req.params.token;
196
+ if (await whoIs(token)) return signedIn(req, token);
197
+ const words = await keys.farewell(token, false);
198
+ if (words !== null)
199
+ return new Response(farewellPage(words), {
200
+ headers: {
201
+ "content-type": "text/html; charset=utf-8",
202
+ "set-cookie": cookie(req, "", 0),
203
+ ...NO_REFERRER,
204
+ },
205
+ });
206
+ } catch (e) {
207
+ console.error("a sign-in failed:", e);
208
+ }
209
+ return new Response(null, { status: 302, headers: { location: "/?link=invalid", ...NO_REFERRER } });
210
+ },
211
+ POST: async (req: Bun.BunRequest<"/auth/:token">) =>
212
+ new Response(null, { status: (await keys.farewell(req.params.token, true)) === null ? 404 : 204 }),
182
213
  },
183
214
  // This browser forgets who it was; the link still works.
184
215
  "/out": {
@@ -211,10 +242,12 @@ export async function groupOf({
211
242
  },
212
243
 
213
244
  /** A page opening: closed, if who it's for has gone since it knocked. */
214
- admit(ws: Socket) {
245
+ async admit(ws: Socket) {
215
246
  const who = ws.data.who;
216
- if (who && !members().some((m) => m.id === who.member)) return void ws.close(4003, "removed");
217
247
  sockets.add(ws);
248
+ if (who && !(await members()).some((m) => m.id === who.member)) (sockets.delete(ws), ws.close(4003, "removed"));
249
+ // in by their link, their page open: the act their invitation names, done for them as them, once
250
+ else if (who && !who.agent) void accepted?.(who);
218
251
  },
219
252
  /** A document a page subscribes to, and sent it: a page holding the members is told what's its (and
220
253
  * only it: nothing of anyone else's has changed). */
@@ -224,33 +257,34 @@ export async function groupOf({
224
257
  left: (ws: Socket) => void sockets.delete(ws),
225
258
 
226
259
  /** A write, as the network allows it: refused, or its ops (a removal bringing those who move up) and what follows. */
227
- write(doc: string, ops: Op[], who: Who | null, why?: string): Write {
260
+ async write(doc: string, ops: Op[], who: Who | null, why?: string): Promise<Write> {
228
261
  if (!who) return { refused: "sign in with your link first" };
262
+ const all = await members();
229
263
  const refused =
230
- mayWrite(who, members(), doc === OWN) ??
231
- (doc === OWN ? (ops.map((o) => trust(o, who.member, members(), why)).find((r) => r !== null) ?? null) : null);
264
+ mayWrite(who, all, doc === OWN) ??
265
+ (doc === OWN ? (ops.map((o) => trust(o, who.member, all, why)).find((r) => r !== null) ?? null) : null);
232
266
  if (refused) return { refused };
233
267
  if (doc !== OWN) return { ops, after: async () => {} };
234
- const before = structuredClone(members()),
235
- by = nameOf(who.member);
268
+ const before = structuredClone(all),
269
+ by = await nameOf(who.member);
236
270
  const removed = (o: Op) => o.op === "remove" && parts(o.path).field === undefined;
237
271
  const farewell = `${by} removed you from the group: ${why}`;
238
272
  return {
239
- ops: withMovesUp(ops, members()),
273
+ ops: withMovesUp(ops, all),
240
274
  // with the write: a farewell for those removed, their keys gone; a notice for whoever was made
241
275
  // read-only or given it back. (A new member's link is made when it's first asked for: an id is
242
276
  // never handed out twice, so no old one can be waiting for it.)
243
- within(applied: Op[]) {
277
+ async within(applied: Op[]) {
244
278
  for (const o of applied) {
245
279
  const { key, field } = parts(o.path),
246
280
  them = Number(key);
247
- if (removed(o)) keys.remove(them, farewell);
281
+ if (removed(o)) await keys.remove(them, farewell);
248
282
  // (made read-only by another when they are already is no news to them)
249
283
  else if (
250
284
  field === "readonly" &&
251
285
  (o.op === "replace") !== (before.find((m) => m.id === them)?.readonly !== undefined)
252
286
  )
253
- keys.tell(them, { kind: o.op === "replace" ? "read-only" : "restored", why: why ?? "", by });
287
+ await keys.tell(them, { kind: o.op === "replace" ? "read-only" : "restored", why: why ?? "", by });
254
288
  }
255
289
  },
256
290
  // once it has: the pages of those removed told why, and closed; every page holding the members told
@@ -269,25 +303,41 @@ export async function groupOf({
269
303
  const who = ws.data.who,
270
304
  no = (why: string) => ({ refused: m.id, why });
271
305
  if (!who) return no("sign in with your link first");
272
- const refused = mayAsk(m, who, members(), keys.agents(who.member).length);
306
+ const refused = mayAsk(m, who, await members(), (await keys.agents(who.member)).length);
273
307
  if (refused) return no(refused);
274
- if (m.closeNotice) keys.closeNotice(who.member);
308
+ let closing = false;
309
+ if (m.closeNotice) await keys.closeNotice(who.member);
275
310
  else if (m.relink !== undefined) {
276
311
  const link = linkTo(ws.data.origin, await keys.replace(m.relink));
277
312
  // your own: the new link told to this page alone, before the page is closed with the rest
278
313
  if (m.relink === who.member) say(ws, { doc: OWN, link });
279
- close((w) => w.member === m.relink && !w.agent, { replaced: true }, 4001);
314
+ // (the page that asked, once it has its answer)
315
+ const gone = (w: Who) => w.member === m.relink && !w.agent;
316
+ close((w) => gone(w) && w !== who, { replaced: true }, 4001);
317
+ closing = gone(who);
280
318
  } else if (m.agent !== undefined) await keys.makeAgent(who.member, m.agent);
281
319
  else if (m.takeBack !== undefined) {
282
- if (!keys.agents(who.member).some((a) => a.id === m.takeBack))
320
+ if (!(await keys.agents(who.member)).some((a) => a.id === m.takeBack))
283
321
  return no("that's not one of your agents' links");
284
- keys.takeBack(m.takeBack);
322
+ await keys.takeBack(m.takeBack);
285
323
  close((w) => w.agent?.id === m.takeBack, { takenBack: true }, 4002);
286
324
  } else return no("nothing asked");
287
325
  await tell();
326
+ // the page that asked closed once it has its answer: a turn on, as the answer goes first
327
+ if (closing)
328
+ setTimeout(() => sockets.has(ws) && (say(ws, { doc: OWN, replaced: true }), ws.close(4001, "signed out")));
288
329
  return { done: m.id };
289
330
  },
290
331
 
332
+ /** The members changed on another server on the database: each page whose link no longer opens (its member
333
+ * removed, its link replaced or taken back) closed, and every page holding the members told. */
334
+ async heard() {
335
+ const gone = new Set<Socket>();
336
+ for (const ws of sockets) if (ws.data.who && !(await whoIs(ws.data.who.token))) gone.add(ws);
337
+ for (const ws of gone)
338
+ (say(ws, { doc: OWN, farewell: "This link no longer opens." }), ws.close(4003, "signed out"));
339
+ await tell();
340
+ },
291
341
  /** A member's link token, for the terminal and the tests. */
292
342
  tokenOf,
293
343
  /** 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. */
@@ -4,8 +4,8 @@
4
4
  // every device until someone replaces it in the page. Root's token is ROOT_TOKEN itself, and is never
5
5
  // kept. A token is found by its hash. A removed member's token keeps their farewell, shown once. A
6
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.
7
+ // is a member's, with a label. The database is all there is of them: nothing is held in memory, so every server on
8
+ // one database (Postgres) signs in the same links, and a member removed is gone from all of them at once.
9
9
 
10
10
  import type { Engine } from "../engine.ts";
11
11
  import { existsSync, renameSync } from "node:fs";
@@ -57,13 +57,17 @@ export async function openKeys(
57
57
  ),
58
58
  );
59
59
 
60
- if (from && existsSync(from) && !db.query("SELECT 1 FROM member_keys").get()) {
60
+ if (from && existsSync(from) && !(await db.query("SELECT 1 FROM member_keys").get())) {
61
61
  const kept: Kept = await Bun.file(from).json();
62
- db.transaction(() => {
62
+ await db.transaction(async () => {
63
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)]);
64
+ await db.run("INSERT INTO member_keys (id, hash, box) VALUES (?, ?, ?)", [
65
+ Number(m),
66
+ k.hash,
67
+ JSON.stringify(k.box),
68
+ ]);
65
69
  for (const a of Object.values(kept.agents))
66
- db.run("INSERT INTO agents (id, member, label, hash, box) VALUES (?, ?, ?, ?, ?)", [
70
+ await db.run("INSERT INTO agents (id, member, label, hash, box) VALUES (?, ?, ?, ?, ?)", [
67
71
  Number(a.id),
68
72
  a.member,
69
73
  a.label,
@@ -71,150 +75,162 @@ export async function openKeys(
71
75
  JSON.stringify(a.box),
72
76
  ]);
73
77
  for (const [h, words] of Object.entries(kept.farewells))
74
- db.run("INSERT INTO farewells (id, hash, words) VALUES (?, ?, ?)", [nextId(db, "farewells"), h, words]);
78
+ await db.run("INSERT INTO farewells (id, hash, words) VALUES (?, ?, ?)", [
79
+ await nextId(db, "farewells"),
80
+ h,
81
+ words,
82
+ ]);
75
83
  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
- })();
84
+ await db.run("INSERT INTO notices (id, kind, why, said_by) VALUES (?, ?, ?, ?)", [
85
+ Number(m),
86
+ n.kind,
87
+ n.why,
88
+ n.by,
89
+ ]);
90
+ });
78
91
  if (rename) renameSync(from, `${from}.imported`);
79
92
  }
80
93
 
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
- );
94
+ // a token sealed with another ROOT_TOKEN can't be opened, and opening never deletes or replaces it (a command, or a
95
+ // start, with the wrong .env would lose every link): it signs in nobody, and is replaced only when its member's link
96
+ // is next asked for, as a rotated ROOT_TOKEN means
97
+ const opened = (box: string) => unseal(JSON.parse(box)).catch(() => null);
98
+ const tokenAt = async (member: number) => {
99
+ const r = (await db.query("SELECT box FROM member_keys WHERE id = ?").get(member)) as { box: string } | null;
100
+ return r ? opened(r.box) : null;
101
+ };
96
102
  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)));
103
+ /** A member's agents' links, each with its token: one this ROOT_TOKEN can't open is none. */
104
+ const agentsOf = async (member: number) => {
105
+ const rows = (await db.query("SELECT id, label, box FROM agents WHERE member = ? ORDER BY id").all(member)) as {
106
+ id: number;
107
+ label: string;
108
+ box: string;
109
+ }[];
110
+ const all: { id: string; label: string; token: string }[] = [];
111
+ for (const r of rows) {
112
+ const token = await opened(r.box);
113
+ if (token) all.push({ id: String(r.id), label: r.label, token });
114
+ }
115
+ return all;
116
+ };
104
117
 
105
118
  return {
106
- /** A member's token: their link's, made if they have none. */
119
+ /** A member's token: their link's, made if they have none (or one this ROOT_TOKEN can't open). */
107
120
  async tokenOf(member: number): Promise<string> {
108
- if (tokens.has(member)) return tokens.get(member)!;
121
+ const had = await tokenAt(member);
122
+ if (had) return had;
109
123
  // one made at a time: two asking at once (two pages told) are both given the one link
110
124
  const made = making.get(member) ?? this.replace(member).finally(() => making.delete(member));
111
125
  making.set(member, made);
112
126
  return made;
113
127
  },
114
128
  /** 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),
129
+ kept: async (member: number) => !!(await db.query("SELECT 1 FROM member_keys WHERE id = ?").get(member)),
116
130
  /** 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,
131
+ async unopened() {
132
+ let n = 0;
133
+ for (const r of (await db.query("SELECT box FROM member_keys").all()) as { box: string }[])
134
+ if (!(await opened(r.box))) n++;
135
+ return n;
136
+ },
118
137
  /** Keys for these members alone: anyone else's (the document and the keys out of step) are dropped. */
119
- keepOnly(ids: number[]) {
138
+ async keepOnly(ids: number[]) {
120
139
  // (0 is no one's: a list with none in it is still a list)
121
140
  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);
141
+ await db.run(`DELETE FROM member_keys WHERE id NOT IN (${kept})`);
142
+ await db.run(`DELETE FROM notices WHERE id NOT IN (${kept})`);
143
+ await db.run(`DELETE FROM agents WHERE member NOT IN (${kept})`);
128
144
  },
129
145
  /** A member's token if they have one, making none. */
130
- peek: (member: number) => tokens.get(member),
146
+ peek: (member: number) => tokenAt(member),
131
147
  /** A new link for a member: the old one stops opening. */
132
148
  async replace(member: number) {
133
149
  const token = fresh(),
134
150
  sealed = [await hash(token), JSON.stringify(await seal(token))];
135
- db.run(
151
+ await db.run(
136
152
  "INSERT INTO member_keys (id, hash, box) VALUES (?, ?, ?) ON CONFLICT (id) DO UPDATE SET hash = excluded.hash, box = excluded.box",
137
153
  [member, ...sealed],
138
154
  );
139
- tokens.set(member, token);
140
155
  return token;
141
156
  },
142
157
  /** Who a token signs in: a member by their link, or by an agent's link they made; or nobody. */
143
158
  async whoIs(token: string): Promise<{ member: number; agent?: Agent } | null> {
144
159
  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 {
160
+ const m = (await db.query("SELECT id, box FROM member_keys WHERE hash = ?").get(h)) as {
161
+ id: number;
162
+ box: string;
163
+ } | null;
164
+ if (m && (await opened(m.box))) return { member: m.id };
165
+ const a = (await db.query("SELECT id, member, label, box FROM agents WHERE hash = ?").get(h)) as {
148
166
  id: number;
149
167
  member: number;
150
168
  label: string;
169
+ box: string;
151
170
  } | null;
152
- return a && agentTokens.has(String(a.id))
171
+ return a && (await opened(a.box))
153
172
  ? { member: a.member, agent: { id: String(a.id), member: a.member, label: a.label } }
154
173
  : null;
155
174
  },
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;
175
+ /** A member gone: their link keeps the words left for them, shown once; their agents' links go. In the write
176
+ * that removes them, as a database's alone: nothing else holds a key. */
177
+ async remove(member: number, farewell: string) {
178
+ const k = (await db.query("SELECT hash FROM member_keys WHERE id = ?").get(member)) as { hash: string } | null;
159
179
  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);
180
+ await db.run("INSERT INTO farewells (id, hash, words) VALUES (?, ?, ?)", [
181
+ await nextId(db, "farewells"),
182
+ k.hash,
183
+ farewell,
184
+ ]);
185
+ await db.run("DELETE FROM member_keys WHERE id = ?", [member]);
186
+ await db.run("DELETE FROM notices WHERE id = ?", [member]);
187
+ await db.run("DELETE FROM agents WHERE member = ?", [member]);
166
188
  },
167
- /** The words left for whoever held this token, once: after this, it opens nothing. */
168
- async farewell(token: string) {
189
+ /** The words left for whoever held this token; `seen`, and they're let go: after this, it opens nothing. */
190
+ async farewell(token: string, seen: boolean) {
169
191
  const h = await hash(token);
170
- const f = db.query("SELECT words FROM farewells WHERE hash = ?").get(h) as { words: string } | null;
192
+ const f = (await db.query("SELECT words FROM farewells WHERE hash = ?").get(h)) as { words: string } | null;
171
193
  if (!f) return null;
172
- db.run("DELETE FROM farewells WHERE hash = ?", [h]);
194
+ if (seen) await db.run("DELETE FROM farewells WHERE hash = ?", [h]);
173
195
  return f.words;
174
196
  },
175
- notice(member: number): Notice | undefined {
176
- const n = db.query("SELECT kind, why, said_by FROM notices WHERE id = ?").get(member) as {
197
+ async notice(member: number): Promise<Notice | undefined> {
198
+ const n = (await db.query("SELECT kind, why, said_by FROM notices WHERE id = ?").get(member)) as {
177
199
  kind: Notice["kind"];
178
200
  why: string;
179
201
  said_by: string;
180
202
  } | null;
181
203
  return n ? { kind: n.kind, why: n.why, by: n.said_by } : undefined;
182
204
  },
183
- tell(member: number, notice: Notice) {
205
+ tell: (member: number, notice: Notice) =>
184
206
  db.run(
185
207
  "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
208
  [member, notice.kind, notice.why, notice.by],
187
- );
188
- },
189
- closeNotice(member: number) {
190
- db.run("DELETE FROM notices WHERE id = ?", [member]);
191
- },
209
+ ),
210
+ closeNotice: (member: number) => db.run("DELETE FROM notices WHERE id = ?", [member]),
192
211
  /** An agent's link for a member, labelled for its via. */
193
212
  async makeAgent(member: number, label: string) {
194
213
  const token = fresh(),
195
214
  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 (?, ?, ?, ?, ?)", [
215
+ const id = await nextId(db, "agents");
216
+ await db.run("INSERT INTO agents (id, member, label, hash, box) VALUES (?, ?, ?, ?, ?)", [
198
217
  id,
199
218
  member,
200
219
  label,
201
220
  ...sealed,
202
221
  ]);
203
- agentTokens.set(String(id), token);
204
222
  return String(id);
205
223
  },
206
224
  /** 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))! })),
225
+ agents: agentsOf,
209
226
  /** 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 {
227
+ async takeBack(id: string) {
228
+ const a = (await db.query("SELECT id, member, label FROM agents WHERE id = ?").get(Number(id))) as {
212
229
  id: number;
213
230
  member: number;
214
231
  label: string;
215
232
  } | null;
216
- db.run("DELETE FROM agents WHERE id = ?", [Number(id)]);
217
- agentTokens.delete(id);
233
+ await db.run("DELETE FROM agents WHERE id = ?", [Number(id)]);
218
234
  return a ? { id: String(a.id), member: a.member, label: a.label } : null;
219
235
  },
220
236
  };