@1agh/maude 2.0.3 → 2.0.6

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 (242) hide show
  1. package/README.md +6 -5
  2. package/apps/hub/src/project-transactions/kernel.mjs +10 -1
  3. package/apps/studio/access/filters.ts +12 -5
  4. package/apps/studio/access/known-canvases.ts +24 -1
  5. package/apps/studio/access/refused-inputs.ts +89 -0
  6. package/apps/studio/access/request.ts +0 -1
  7. package/apps/studio/acp/adapter-stderr.ts +43 -13
  8. package/apps/studio/acp/background-tasks.ts +155 -0
  9. package/apps/studio/acp/bridge.ts +44 -5
  10. package/apps/studio/acp/connected-fact.ts +15 -4
  11. package/apps/studio/acp/index.ts +14 -5
  12. package/apps/studio/actions/agents.ts +10 -0
  13. package/apps/studio/actions/defs/app.ts +12 -0
  14. package/apps/studio/actions/defs/view.ts +12 -0
  15. package/apps/studio/actions.manifest.json +25 -1
  16. package/apps/studio/actions.parity.json +13 -1
  17. package/apps/studio/annotations/ui/element-node.tsx +139 -54
  18. package/apps/studio/annotations/ui/lod.tsx +1 -1
  19. package/apps/studio/annotations/ui/text-style.ts +1 -1
  20. package/apps/studio/annotations-layer.tsx +0 -12
  21. package/apps/studio/api.ts +73 -24
  22. package/apps/studio/artboard-live-gate.tsx +267 -0
  23. package/apps/studio/artboard-live.ts +336 -0
  24. package/apps/studio/artboard-webgl.ts +668 -0
  25. package/apps/studio/bin/_agent-browser-bin.mjs +8 -0
  26. package/apps/studio/bin/_agent-browser-safe.mjs +2 -1
  27. package/apps/studio/bin/_canvas-reasons.mjs +34 -0
  28. package/apps/studio/bin/_ds-check-live.mjs +37 -0
  29. package/apps/studio/bin/_ds-check.mjs +4 -1
  30. package/apps/studio/bin/_ds-prove-judge.mjs +167 -0
  31. package/apps/studio/bin/_ds-prove-playwright.mjs +183 -105
  32. package/apps/studio/bin/_import-asset.mjs +2 -1
  33. package/apps/studio/bin/_perf-probe.mjs +2 -1
  34. package/apps/studio/bin/_png-playwright.mjs +10 -1
  35. package/apps/studio/bin/_pw-launch.mjs +14 -0
  36. package/apps/studio/bin/_studio-verb.mjs +24 -3
  37. package/apps/studio/bin/_thumb-blank.mjs +70 -0
  38. package/apps/studio/bin/_thumb-cover.mjs +35 -0
  39. package/apps/studio/bin/_thumbs-playwright.mjs +93 -13
  40. package/apps/studio/bin/ds-check.sh +5 -1
  41. package/apps/studio/bin/perf.sh +11 -1
  42. package/apps/studio/bin/server-up.sh +7 -2
  43. package/apps/studio/bin/smoke.sh +19 -0
  44. package/apps/studio/boot-progress.ts +31 -0
  45. package/apps/studio/canvas-build-sandbox.ts +275 -42
  46. package/apps/studio/canvas-build-worker.ts +10 -0
  47. package/apps/studio/canvas-create.ts +24 -0
  48. package/apps/studio/canvas-lib.tsx +131 -12
  49. package/apps/studio/canvas-module-cache.ts +93 -0
  50. package/apps/studio/canvas-source/errors.ts +39 -0
  51. package/apps/studio/canvas-source/waiting.ts +290 -0
  52. package/apps/studio/client/actions/shell-key-handlers.js +5 -0
  53. package/apps/studio/client/app.jsx +19 -9
  54. package/apps/studio/client/canvas-url.js +13 -0
  55. package/apps/studio/client/github.js +23 -3
  56. package/apps/studio/client/home/HomeAccounts.jsx +262 -0
  57. package/apps/studio/client/home/Shelves.jsx +4 -3
  58. package/apps/studio/client/home/home-accounts-model.js +121 -0
  59. package/apps/studio/client/home/home-api.js +36 -19
  60. package/apps/studio/client/home/home-app.jsx +141 -40
  61. package/apps/studio/client/home/home-model.js +172 -6
  62. package/apps/studio/client/home/home.css +169 -5
  63. package/apps/studio/client/home/shell-mode.js +8 -1
  64. package/apps/studio/client/hooks/use-git-actions.jsx +2 -1
  65. package/apps/studio/client/hooks/use-project-data.jsx +2 -0
  66. package/apps/studio/client/hooks/use-shell-core.jsx +3 -0
  67. package/apps/studio/client/hooks/use-tabs.jsx +64 -35
  68. package/apps/studio/client/index-loader.ts +23 -3
  69. package/apps/studio/client/panels/ChatPanel.jsx +49 -57
  70. package/apps/studio/client/panels/CreateProject.jsx +19 -5
  71. package/apps/studio/client/panels/DiffView.jsx +314 -248
  72. package/apps/studio/client/panels/TeamProjects.jsx +119 -69
  73. package/apps/studio/client/panels/acp-runtime.js +25 -0
  74. package/apps/studio/client/panels/caps-cache.js +46 -0
  75. package/apps/studio/client/panels/chat-finish.js +66 -0
  76. package/apps/studio/client/shell/frame-cap.js +53 -0
  77. package/apps/studio/client/shell/viewport.jsx +45 -8
  78. package/apps/studio/client/styles/_index.css +2 -0
  79. package/apps/studio/client/tree/tree.jsx +48 -21
  80. package/apps/studio/client/v2/access/access-client.js +2 -0
  81. package/apps/studio/client/v2/access/access-host.jsx +12 -1
  82. package/apps/studio/client/v2/access/trashed-banner.jsx +6 -3
  83. package/apps/studio/client/v2/ai/Advanced.jsx +12 -0
  84. package/apps/studio/client/v2/ai/BackgroundStrip.jsx +120 -0
  85. package/apps/studio/client/v2/ai/Composer.jsx +27 -10
  86. package/apps/studio/client/v2/ai/StoppedDivider.jsx +2 -1
  87. package/apps/studio/client/v2/ai/ai-run.css +87 -3
  88. package/apps/studio/client/v2/ai/background-model.js +113 -0
  89. package/apps/studio/client/v2/ai/needs-you-store.js +2 -1
  90. package/apps/studio/client/v2/ai/run-api.js +7 -3
  91. package/apps/studio/client/v2/ai/runs-store.js +2 -1
  92. package/apps/studio/client/v2/annotations/vote-store.js +11 -5
  93. package/apps/studio/client/v2/assets/asset-state-lane.js +6 -3
  94. package/apps/studio/client/v2/assets/assets-bus.js +10 -8
  95. package/apps/studio/client/v2/assets/browse-view.jsx +2 -0
  96. package/apps/studio/client/v2/assets/ds-library-view.jsx +47 -0
  97. package/apps/studio/client/v2/assets/spotlight-model.js +75 -0
  98. package/apps/studio/client/v2/assets/spotlight.css +153 -0
  99. package/apps/studio/client/v2/assets/spotlight.jsx +199 -0
  100. package/apps/studio/client/v2/assets/tile-menu.jsx +3 -1
  101. package/apps/studio/client/v2/assets/tile.jsx +3 -0
  102. package/apps/studio/client/v2/assets/use-assets.js +2 -1
  103. package/apps/studio/client/v2/canvases/canvases-panel.jsx +13 -2
  104. package/apps/studio/client/v2/canvases/covers.js +11 -5
  105. package/apps/studio/client/v2/canvases/folder-ask.js +139 -0
  106. package/apps/studio/client/v2/canvases/folder-dialogs.jsx +150 -0
  107. package/apps/studio/client/v2/canvases/trash-canvas.js +10 -2
  108. package/apps/studio/client/v2/canvases/trash-queue.js +152 -0
  109. package/apps/studio/client/v2/canvases/use-canvas-index.js +42 -18
  110. package/apps/studio/client/v2/canvases/use-pins.js +2 -1
  111. package/apps/studio/client/v2/code/canvas-error-card.jsx +70 -5
  112. package/apps/studio/client/v2/code/canvas-imports-card.jsx +15 -14
  113. package/apps/studio/client/v2/code/canvas-imports-words.js +44 -0
  114. package/apps/studio/client/v2/code/canvas-waiting-card.jsx +128 -0
  115. package/apps/studio/client/v2/code/canvas-waiting.js +164 -0
  116. package/apps/studio/client/v2/code/code-bus.js +5 -0
  117. package/apps/studio/client/v2/code/code.css +67 -0
  118. package/apps/studio/client/v2/code/use-canvas-source.js +19 -4
  119. package/apps/studio/client/v2/create/NameDialog.jsx +4 -2
  120. package/apps/studio/client/v2/create/name-dialog.css +10 -0
  121. package/apps/studio/client/v2/ds/advanced-host.jsx +11 -23
  122. package/apps/studio/client/v2/ds/ds-refresh.js +161 -0
  123. package/apps/studio/client/v2/ds/library-host.jsx +45 -45
  124. package/apps/studio/client/v2/ds/make-host.jsx +13 -12
  125. package/apps/studio/client/v2/ds/off-system-host.jsx +18 -16
  126. package/apps/studio/client/v2/ds/review-host.jsx +7 -1
  127. package/apps/studio/client/v2/ds/truth-host.jsx +15 -14
  128. package/apps/studio/client/v2/ds/upgrade-host.jsx +26 -10
  129. package/apps/studio/client/v2/empty/arriving.jsx +29 -12
  130. package/apps/studio/client/v2/empty/empty-host.jsx +8 -2
  131. package/apps/studio/client/v2/empty/not-local.jsx +31 -1
  132. package/apps/studio/client/v2/empty/use-empty-canvas.js +10 -1
  133. package/apps/studio/client/v2/export/last-finished.js +2 -1
  134. package/apps/studio/client/v2/history/branch-actions.js +13 -9
  135. package/apps/studio/client/v2/history/git-advanced.jsx +8 -1
  136. package/apps/studio/client/v2/history/git-model.js +21 -5
  137. package/apps/studio/client/v2/history/git-parts.jsx +76 -43
  138. package/apps/studio/client/v2/history/history.css +6 -0
  139. package/apps/studio/client/v2/left-panel/assets-panel.jsx +87 -10
  140. package/apps/studio/client/v2/left-panel/use-trash.js +2 -1
  141. package/apps/studio/client/v2/onboarding/AdvancedSheets.jsx +100 -33
  142. package/apps/studio/client/v2/onboarding/HubSheet.jsx +51 -83
  143. package/apps/studio/client/v2/onboarding/onboarding-model.js +10 -6
  144. package/apps/studio/client/v2/presence/faces.jsx +42 -14
  145. package/apps/studio/client/v2/present/order-notes-artboards.js +2 -1
  146. package/apps/studio/client/v2/search/search-recent.js +3 -1
  147. package/apps/studio/client/v2/search/search-remote.js +6 -4
  148. package/apps/studio/client/v2/settings/connections-model.js +1 -1
  149. package/apps/studio/client/v2/shell/account-card.jsx +10 -4
  150. package/apps/studio/client/v2/shell/canvas-crash-guard.js +137 -0
  151. package/apps/studio/client/v2/shell/github-signin-host.jsx +42 -0
  152. package/apps/studio/client/v2/shell/menu-runner.js +12 -0
  153. package/apps/studio/client/v2/shell/occlusion-insets.js +14 -2
  154. package/apps/studio/client/v2/shell/project-account-card.jsx +203 -0
  155. package/apps/studio/client/v2/shell/project-account-model.js +182 -0
  156. package/apps/studio/client/v2/shell/recovery-store.js +2 -1
  157. package/apps/studio/client/v2/shell/served-routes.js +120 -0
  158. package/apps/studio/client/v2/shell/share-cluster-host.jsx +139 -11
  159. package/apps/studio/client/v2/shell/share-cluster.css +58 -0
  160. package/apps/studio/client/v2/shell/share-cluster.jsx +26 -7
  161. package/apps/studio/client/v2/shell/shell-activity.js +19 -0
  162. package/apps/studio/client/v2/shell/team-switch.js +94 -0
  163. package/apps/studio/client/v2/shell/too-heavy-card.jsx +38 -0
  164. package/apps/studio/client/v2/shell/use-account.js +8 -1
  165. package/apps/studio/client/v2/shell/use-occluded-insets.js +3 -0
  166. package/apps/studio/client/v2/sync-states/conflict-card.jsx +7 -2
  167. package/apps/studio/client/v2/undo/use-undo-projection.jsx +3 -1
  168. package/apps/studio/cloud/endpoints.ts +23 -1
  169. package/apps/studio/collab/persistence.ts +9 -1
  170. package/apps/studio/collab/registry.ts +32 -0
  171. package/apps/studio/collab/room.ts +8 -0
  172. package/apps/studio/config-reload-wire.ts +53 -0
  173. package/apps/studio/dist/client.bundle.js +1098 -1102
  174. package/apps/studio/dist/styles.css +1 -1
  175. package/apps/studio/ds/board/specimen.tsx +12 -1
  176. package/apps/studio/ds/canvas-cli.ts +58 -2
  177. package/apps/studio/ds/check.ts +26 -1
  178. package/apps/studio/ds/cli.ts +7 -3
  179. package/apps/studio/ds/convert.ts +34 -6
  180. package/apps/studio/ds/ds-verb.ts +13 -0
  181. package/apps/studio/ds/post-build.ts +38 -0
  182. package/apps/studio/ds/upgrade-apply.ts +27 -5
  183. package/apps/studio/ds/upgrade-cli.ts +22 -2
  184. package/apps/studio/ds/upgrade-prove.ts +198 -15
  185. package/apps/studio/ds/upgrade-stage.ts +4 -1
  186. package/apps/studio/editing/minimap-context.tsx +3 -3
  187. package/apps/studio/editing/page-activity.ts +251 -0
  188. package/apps/studio/editing/rotate-handle.tsx +9 -5
  189. package/apps/studio/editing/sticky-name.tsx +4 -4
  190. package/apps/studio/history/restore-artboard-action.ts +40 -0
  191. package/apps/studio/history/trash.ts +6 -0
  192. package/apps/studio/home/accounts.ts +87 -0
  193. package/apps/studio/home/hub.ts +77 -175
  194. package/apps/studio/home/index-reader.ts +24 -2
  195. package/apps/studio/home/routes.ts +66 -8
  196. package/apps/studio/http.ts +131 -68
  197. package/apps/studio/index-flight.ts +40 -0
  198. package/apps/studio/managed-projects.ts +52 -24
  199. package/apps/studio/migrate/hub.ts +7 -1
  200. package/apps/studio/routes/canvas-source.ts +44 -2
  201. package/apps/studio/routes/ds-convert.ts +18 -0
  202. package/apps/studio/routes/history.ts +28 -5
  203. package/apps/studio/routes/hub-signin.ts +115 -0
  204. package/apps/studio/routes/index.ts +4 -0
  205. package/apps/studio/routes/table.ts +7 -0
  206. package/apps/studio/routes/trash.ts +19 -1
  207. package/apps/studio/server.ts +19 -10
  208. package/apps/studio/sync/accepted-cold-start.ts +54 -16
  209. package/apps/studio/sync/accepted-link.ts +9 -4
  210. package/apps/studio/sync/asset-push.ts +146 -23
  211. package/apps/studio/sync/asset-state.ts +3 -2
  212. package/apps/studio/sync/code-module-consent.ts +74 -0
  213. package/apps/studio/sync/file-ledger.ts +35 -0
  214. package/apps/studio/sync/file-membership.ts +28 -3
  215. package/apps/studio/sync/file-plane.ts +483 -86
  216. package/apps/studio/sync/file-pull.ts +304 -33
  217. package/apps/studio/sync/hub-browser-signin.ts +377 -0
  218. package/apps/studio/sync/hub-link.ts +1 -2
  219. package/apps/studio/sync/hub-text-undo.ts +30 -10
  220. package/apps/studio/sync/index.ts +381 -161
  221. package/apps/studio/sync/journal-client.ts +94 -5
  222. package/apps/studio/sync/pending-deletes.ts +100 -0
  223. package/apps/studio/sync/projection.ts +121 -14
  224. package/apps/studio/sync/pull-pacer.ts +160 -0
  225. package/apps/studio/sync/pull-priority.ts +119 -0
  226. package/apps/studio/sync/seed-progress.ts +58 -3
  227. package/apps/studio/sync/status.ts +3 -1
  228. package/apps/studio/sync/transaction-client.ts +71 -6
  229. package/apps/studio/sync/workspace-signin.ts +6 -256
  230. package/apps/studio/sync/writer-registry.ts +5 -1
  231. package/apps/studio/thumbs/service.ts +12 -2
  232. package/apps/studio/thumbs/validate.ts +7 -0
  233. package/apps/studio/ui-prefs-migrate.ts +4 -0
  234. package/apps/studio/video-comp.tsx +23 -0
  235. package/apps/studio/video-links-overlay.tsx +3 -2
  236. package/apps/studio/whats-new.json +126 -0
  237. package/cli/lib/bash-guard.mjs +13 -1
  238. package/cli/lib/design-help.gen.mjs +1 -1
  239. package/cli/lib/design-hook.mjs +20 -0
  240. package/cli/lib/studio-locate.mjs +35 -10
  241. package/cli/lib/workspace-plan.mjs +14 -0
  242. package/package.json +8 -8
@@ -0,0 +1,377 @@
1
+ // Sign in to a team server in the browser — issue #204 (Maude 2.0.4).
2
+ //
3
+ // Michal's decision (`maude/v2-michal-team-server-signin-via-hub-page`): the desktop owns NO
4
+ // login method for a team server. "Sign in" opens the hub's OWN page (`/studio/signin`), which
5
+ // offers whatever that hub offers — a password, "Sign in with <issuer>" (OIDC), … — and the hub
6
+ // sends the browser back to THIS server's loopback return route with a one-time code
7
+ // (apps/hub/src/desktop-signin.mjs has the hub half and the flow drawing).
8
+ //
9
+ // start(url) tokenless /health probe (a Maude hub that says `desktop-signin-v1`), then a
10
+ // fresh attempt: `state` (32 hex) + PKCE `verifier`, both kept HERE, in memory;
11
+ // answers the hub page URL the client opens in the browser.
12
+ // onReturn() the browser lands on `/_api/hub-signin/return?code&state` (or `&error`): the
13
+ // state must name a live attempt of THIS process, once. The code + verifier go to
14
+ // `<hub>/auth/desktop/exchange` (POST, no redirect followed); the token that comes
15
+ // back is stored through `saveHubCredential` — the same per-profile hubs.json slot
16
+ // the email/password sign-in used, never a new store.
17
+ // poll(id) the client waits on the attempt: pending · signed in · why not.
18
+ //
19
+ // The token never travels in a URL and never reaches the page: only this process sees it. The
20
+ // code that does travel is single use, a minute long, and worthless without the verifier, which
21
+ // never left this process — so a code read from browser history, a log or another app that
22
+ // grabbed the loopback hop cannot be redeemed by anyone else.
23
+
24
+ import { createHash, randomBytes } from 'node:crypto';
25
+ import { saveHubCredential } from './hub-link.ts';
26
+ import { normalizeUrl, safeAccount } from './hubs-config.ts';
27
+
28
+ /** The hub's `/health` capability word for this flow (apps/hub/src/desktop-signin.mjs). */
29
+ export const DESKTOP_SIGNIN_CAPABILITY = 'desktop-signin-v1';
30
+ /** The loopback path the hub may send the browser back to (the hub allows exactly this one). */
31
+ export const HUB_SIGNIN_RETURN_PATH = '/_api/hub-signin/return';
32
+ /** As long as the hub keeps the request (DESKTOP_TXN_TTL_MS). */
33
+ export const ATTEMPT_TTL_MS = 10 * 60_000;
34
+ /** Attempts alive at once — each one is a browser tab somebody opened. */
35
+ const MAX_ATTEMPTS = 5;
36
+ const PROBE_TIMEOUT_MS = 4000;
37
+ const EXCHANGE_TIMEOUT_MS = 15_000;
38
+
39
+ /** Plain words for every way this ends (CONTRACT §3/§4: no token, no OAuth, no code). */
40
+ export const HUB_SIGNIN_WORDS = {
41
+ badAddress: "That doesn't look like a team server address.",
42
+ notHttps: 'The team server address must start with https://.',
43
+ unreachable:
44
+ "Couldn't reach that team server. Check the address, or ask whoever runs it whether it's online.",
45
+ notMaude: "That address answered, but it isn't a Maude team server. Check the address.",
46
+ // what happened · what is safe · one verb (CONTRACT §4); the version is the one thing an admin needs
47
+ needsUpdate: (version: string | null) =>
48
+ `This team server${version ? ` runs ${version}, which` : ''} is too old to sign in from here. Nothing was sent to it. Ask whoever runs it to update it to 2.0.4 or newer.`,
49
+ tooMany: 'Too many sign-ins are open. Finish or cancel one first.',
50
+ expired: 'The sign-in took too long. Start it again.',
51
+ pending:
52
+ 'You signed in, but nobody has given your account access to this team server yet. Ask whoever runs it to approve you.',
53
+ denied: 'This account cannot sign in to this team server.',
54
+ refused: 'The team server did not accept the sign-in. Start it again.',
55
+ exchangeUnreachable: "Couldn't reach the team server to finish signing in. Start it again.",
56
+ update:
57
+ 'This team server needs a newer Maude to give this account access. Update Maude, then sign in again.',
58
+ browserOnly:
59
+ 'This account can only view this project, and viewing works in the browser. Ask whoever runs the team server for edit access.',
60
+ saveFailed: "Couldn't save the sign-in on this computer.",
61
+ badInvite: "That doesn't look like an invite link or key.",
62
+ unknown: "This sign-in wasn't started in this Maude window, or it's already finished.",
63
+ } as const;
64
+
65
+ type Attempt = {
66
+ id: string;
67
+ url: string;
68
+ verifier: string;
69
+ createdAt: number;
70
+ save: SaveCredential;
71
+ phase: 'waiting' | 'exchanging' | 'done' | 'failed';
72
+ result?:
73
+ | { ok: true; url: string; user: { email: string; role: string } }
74
+ | { ok: false; error: string };
75
+ };
76
+
77
+ export type StartAnswer =
78
+ | { ok: true; id: string; signInUrl: string; expiresIn: number }
79
+ | { ok: false; error: string; status: number; reason?: 'needs-update' };
80
+
81
+ export type PollAnswer =
82
+ | { ok: true; pending: true }
83
+ | { ok: true; url: string; user: { email: string; role: string } }
84
+ | { ok: false; error: string };
85
+
86
+ /** Where an attempt's credential goes — the same call the email/password sign-in made. */
87
+ export type SaveCredential = (
88
+ url: string,
89
+ token: string,
90
+ role?: string,
91
+ expiresAt?: number,
92
+ account?: string
93
+ ) => void;
94
+
95
+ /** A Maude invite key (apps/hub invites.mjs) — the only thing `start({invite})` puts in a path. */
96
+ const INVITE_RE = /^inv_[A-Za-z0-9_-]{16,200}$/;
97
+ const VERSION_RE = /^[0-9A-Za-z.+-]{1,32}$/;
98
+
99
+ export interface StartOptions {
100
+ /**
101
+ * This attempt's credential store. Home (K2) signs in for a named PROFILE, so each attempt
102
+ * carries that profile's hubs.json; a project tab uses the flow-wide default.
103
+ */
104
+ save?: SaveCredential;
105
+ /**
106
+ * #204 K2 — accept this invite (an `inv_…` key) on the hub's own invite page `/join/<key>`
107
+ * instead of its sign-in page; the desktop request is the same, so is the return.
108
+ */
109
+ invite?: string;
110
+ }
111
+
112
+ export interface HubBrowserSignInDeps {
113
+ fetchImpl?: typeof fetch;
114
+ /** Where the credential goes by default — the same call the email/password sign-in made. */
115
+ save?: SaveCredential;
116
+ /** After a credential is stored: e.g. cycle sync when it renews the linked team server's. */
117
+ onSignedIn?: (url: string) => void | Promise<void>;
118
+ now?: () => number;
119
+ }
120
+
121
+ const isLoopbackHostname = (h: string) =>
122
+ h === 'localhost' || h === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(h);
123
+
124
+ /** The one address grammar this flow sends anything to: https, or http only on loopback. */
125
+ export function teamServerAddress(
126
+ raw: unknown
127
+ ): { ok: true; url: string } | { ok: false; error: string } {
128
+ if (typeof raw !== 'string' || !raw.trim() || raw.length > 2048)
129
+ return { ok: false, error: HUB_SIGNIN_WORDS.badAddress };
130
+ let u: URL;
131
+ let norm: string;
132
+ try {
133
+ norm = normalizeUrl(raw.trim());
134
+ u = new URL(norm);
135
+ } catch {
136
+ return { ok: false, error: HUB_SIGNIN_WORDS.badAddress };
137
+ }
138
+ if (u.username || u.password) return { ok: false, error: HUB_SIGNIN_WORDS.badAddress };
139
+ if (u.protocol === 'http:' && !isLoopbackHostname(u.hostname))
140
+ return { ok: false, error: HUB_SIGNIN_WORDS.notHttps };
141
+ if (u.protocol !== 'https:' && u.protocol !== 'http:')
142
+ return { ok: false, error: HUB_SIGNIN_WORDS.badAddress };
143
+ return { ok: true, url: norm };
144
+ }
145
+
146
+ /** The return target for a request that reached this server on `origin` (loopback http only). */
147
+ export function returnUriFor(origin: string): string | null {
148
+ try {
149
+ const u = new URL(origin);
150
+ if (u.protocol !== 'http:' || !isLoopbackHostname(u.hostname) || !u.port) return null;
151
+ return `${u.protocol}//${u.host}${HUB_SIGNIN_RETURN_PATH}`;
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
156
+
157
+ export function createHubBrowserSignIn(deps: HubBrowserSignInDeps = {}) {
158
+ const doFetch = deps.fetchImpl ?? fetch;
159
+ const now = deps.now ?? Date.now;
160
+ const save =
161
+ deps.save ??
162
+ ((u: string, t: string, r?: string, e?: number, a?: string) =>
163
+ saveHubCredential(u, t, r, e, undefined, a));
164
+ const attempts = new Map<string, Attempt>();
165
+
166
+ const sweep = () => {
167
+ const t = now();
168
+ for (const [k, a] of attempts) if (t - a.createdAt > ATTEMPT_TTL_MS) attempts.delete(k);
169
+ };
170
+
171
+ type Probe = { kind: 'ok' | 'unreachable' | 'not-maude' | 'old'; version: string | null };
172
+ async function probe(url: string): Promise<Probe> {
173
+ try {
174
+ const res = await doFetch(`${url}/health`, {
175
+ redirect: 'manual',
176
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
177
+ });
178
+ if (!res.ok) return { kind: 'not-maude', version: null };
179
+ const j = (await res.json().catch(() => null)) as {
180
+ ok?: unknown;
181
+ version?: unknown;
182
+ capabilities?: unknown;
183
+ } | null;
184
+ if (j?.ok !== true) return { kind: 'not-maude', version: null };
185
+ const version =
186
+ typeof j.version === 'string' && VERSION_RE.test(j.version) ? j.version : null;
187
+ return {
188
+ kind:
189
+ Array.isArray(j.capabilities) && j.capabilities.includes(DESKTOP_SIGNIN_CAPABILITY)
190
+ ? 'ok'
191
+ : 'old',
192
+ version,
193
+ };
194
+ } catch {
195
+ return { kind: 'unreachable', version: null };
196
+ }
197
+ }
198
+
199
+ /** A new attempt for `rawUrl`; `origin` is where the browser comes back (this server). */
200
+ async function start(
201
+ rawUrl: unknown,
202
+ origin: string,
203
+ opts: StartOptions = {}
204
+ ): Promise<StartAnswer> {
205
+ const addr = teamServerAddress(rawUrl);
206
+ if (!addr.ok) return { ok: false, error: addr.error, status: 400 };
207
+ if (opts.invite !== undefined && !INVITE_RE.test(opts.invite))
208
+ return { ok: false, error: HUB_SIGNIN_WORDS.badInvite, status: 400 };
209
+ const redirectUri = returnUriFor(origin);
210
+ if (!redirectUri) return { ok: false, error: HUB_SIGNIN_WORDS.unknown, status: 403 };
211
+ sweep();
212
+ const live = [...attempts.values()].filter((a) => a.phase === 'waiting');
213
+ if (live.length >= MAX_ATTEMPTS)
214
+ return { ok: false, error: HUB_SIGNIN_WORDS.tooMany, status: 429 };
215
+ const p = await probe(addr.url);
216
+ if (p.kind === 'unreachable')
217
+ return { ok: false, error: HUB_SIGNIN_WORDS.unreachable, status: 502 };
218
+ if (p.kind === 'not-maude') return { ok: false, error: HUB_SIGNIN_WORDS.notMaude, status: 502 };
219
+ if (p.kind === 'old')
220
+ return {
221
+ ok: false,
222
+ error: HUB_SIGNIN_WORDS.needsUpdate(p.version),
223
+ status: 409,
224
+ reason: 'needs-update',
225
+ };
226
+ const id = randomBytes(16).toString('hex');
227
+ const verifier = randomBytes(32).toString('base64url');
228
+ const challenge = createHash('sha256').update(verifier).digest('base64url');
229
+ attempts.set(id, {
230
+ id,
231
+ url: addr.url,
232
+ verifier,
233
+ createdAt: now(),
234
+ save: opts.save ?? save,
235
+ phase: 'waiting',
236
+ });
237
+ const q = new URLSearchParams({
238
+ client: 'desktop',
239
+ state: id,
240
+ code_challenge: challenge,
241
+ code_challenge_method: 'S256',
242
+ redirect_uri: redirectUri,
243
+ });
244
+ return {
245
+ ok: true,
246
+ id,
247
+ // the invite key is the hub's own invite link path (GET there only looks, never spends)
248
+ signInUrl: `${addr.url}${opts.invite ? `/join/${opts.invite}` : '/studio/signin'}?${q.toString()}`,
249
+ expiresIn: ATTEMPT_TTL_MS / 1000,
250
+ };
251
+ }
252
+
253
+ const fail = (a: Attempt, error: string) => {
254
+ a.phase = 'failed';
255
+ a.result = { ok: false, error };
256
+ };
257
+
258
+ /**
259
+ * The browser came back. Returns what the return page says. A state this process did not
260
+ * start, or one already used, changes nothing (an unrequested or replayed callback).
261
+ */
262
+ async function onReturn(params: URLSearchParams): Promise<{ ok: boolean; message: string }> {
263
+ sweep();
264
+ const state = params.get('state') ?? '';
265
+ const a = /^[0-9a-f]{32}$/.test(state) ? attempts.get(state) : undefined;
266
+ if (!a || a.phase !== 'waiting') return { ok: false, message: HUB_SIGNIN_WORDS.unknown };
267
+ a.phase = 'exchanging'; // single use from here on, whatever happens next
268
+ const error = params.get('error');
269
+ if (error) {
270
+ fail(a, error === 'pending' ? HUB_SIGNIN_WORDS.pending : HUB_SIGNIN_WORDS.denied);
271
+ return {
272
+ ok: false,
273
+ message: a.result?.ok === false ? a.result.error : HUB_SIGNIN_WORDS.denied,
274
+ };
275
+ }
276
+ const code = params.get('code') ?? '';
277
+ if (!code || code.length > 128) {
278
+ fail(a, HUB_SIGNIN_WORDS.refused);
279
+ return { ok: false, message: HUB_SIGNIN_WORDS.refused };
280
+ }
281
+ let res: Response;
282
+ try {
283
+ res = await doFetch(`${a.url}/auth/desktop/exchange`, {
284
+ method: 'POST',
285
+ redirect: 'manual',
286
+ headers: { 'content-type': 'application/json' },
287
+ body: JSON.stringify({ code, code_verifier: a.verifier }),
288
+ signal: AbortSignal.timeout(EXCHANGE_TIMEOUT_MS),
289
+ });
290
+ } catch {
291
+ fail(a, HUB_SIGNIN_WORDS.exchangeUnreachable);
292
+ return { ok: false, message: HUB_SIGNIN_WORDS.exchangeUnreachable };
293
+ }
294
+ const body = (await res.json().catch(() => null)) as {
295
+ token?: unknown;
296
+ expiresAt?: unknown;
297
+ user?: { email?: unknown; role?: unknown };
298
+ reason?: unknown;
299
+ } | null;
300
+ if (!res.ok || typeof body?.token !== 'string' || !body.token) {
301
+ const words =
302
+ res.status === 426
303
+ ? HUB_SIGNIN_WORDS.update
304
+ : res.status === 409
305
+ ? HUB_SIGNIN_WORDS.browserOnly
306
+ : res.status === 401
307
+ ? HUB_SIGNIN_WORDS.denied
308
+ : HUB_SIGNIN_WORDS.refused;
309
+ fail(a, words);
310
+ return { ok: false, message: words };
311
+ }
312
+ const role = typeof body.user?.role === 'string' ? body.user.role : 'member';
313
+ const email = safeAccount(body.user?.email) ?? '';
314
+ const expiresAt = typeof body.expiresAt === 'number' ? body.expiresAt : undefined;
315
+ try {
316
+ a.save(a.url, body.token, role, expiresAt, email || undefined);
317
+ } catch {
318
+ fail(a, HUB_SIGNIN_WORDS.saveFailed);
319
+ return { ok: false, message: HUB_SIGNIN_WORDS.saveFailed };
320
+ }
321
+ a.phase = 'done';
322
+ a.result = { ok: true, url: a.url, user: { email, role } };
323
+ try {
324
+ await deps.onSignedIn?.(a.url);
325
+ } catch (err) {
326
+ console.error('[hub-signin] after sign-in:', err);
327
+ }
328
+ return { ok: true, message: 'Signed in. You can close this tab and go back to Maude.' };
329
+ }
330
+
331
+ /** The client's wait. A finished attempt answers once, then is forgotten. */
332
+ function poll(id: unknown): PollAnswer {
333
+ sweep();
334
+ const a = typeof id === 'string' ? attempts.get(id) : undefined;
335
+ if (!a) return { ok: false, error: HUB_SIGNIN_WORDS.expired };
336
+ if (a.phase === 'waiting' || a.phase === 'exchanging') return { ok: true, pending: true };
337
+ attempts.delete(a.id);
338
+ return a.result ?? { ok: false, error: HUB_SIGNIN_WORDS.refused };
339
+ }
340
+
341
+ /** Cancel: the attempt is gone, so a later return for it changes nothing. */
342
+ function cancel(id: unknown): void {
343
+ if (typeof id === 'string') attempts.delete(id);
344
+ }
345
+
346
+ return { start, onReturn, poll, cancel, size: () => attempts.size };
347
+ }
348
+
349
+ export type HubBrowserSignIn = ReturnType<typeof createHubBrowserSignIn>;
350
+
351
+ /** The page the browser shows after the hop back — this server's own words, nothing echoed. */
352
+ export function returnPage(r: { ok: boolean; message: string }): Response {
353
+ const title = r.ok ? 'Signed in' : 'Not signed in';
354
+ const esc = (s: string) =>
355
+ s.replace(
356
+ /[&<>"']/g,
357
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c] as string
358
+ );
359
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8">
360
+ <meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)} — Maude</title>
361
+ <style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0e1014;color:#e9ecf3;
362
+ font:15px/1.6 -apple-system,system-ui,sans-serif;padding:24px}main{width:min(24rem,100%)}
363
+ h1{font-size:1.3rem;margin:0 0 .5rem}p{color:#c3c9d6}</style></head>
364
+ <body><main><h1>${esc(title)}</h1><p>${esc(r.message)}</p></main></body></html>`;
365
+ return new Response(html, {
366
+ status: r.ok ? 200 : 400,
367
+ headers: {
368
+ 'content-type': 'text/html; charset=utf-8',
369
+ 'cache-control': 'no-store',
370
+ 'referrer-policy': 'no-referrer',
371
+ 'x-content-type-options': 'nosniff',
372
+ 'x-frame-options': 'DENY',
373
+ 'content-security-policy':
374
+ "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
375
+ },
376
+ });
377
+ }
@@ -202,8 +202,7 @@ export function saveHubCredential(
202
202
  * for the same reason the save is: the file holds EVERY hub credential on the
203
203
  * machine, so a torn write drops them all.
204
204
  */
205
- export function deleteHubCredential(normUrl: string): void {
206
- const path = hubsConfigPath();
205
+ export function deleteHubCredential(normUrl: string, path: string = hubsConfigPath()): void {
207
206
  if (!existsSync(path)) return;
208
207
  let cfg: HubsFile;
209
208
  try {
@@ -42,10 +42,14 @@ export interface HubTextUndoReads {
42
42
  action(actionId: string): Promise<{ effects: HubEffect[]; revision?: number } | null>;
43
43
  /** p8-fix-d F12 — "Undo this chat": the ids the route will undo (the person's own `ai` runs). */
44
44
  chat?(chatId: string): Promise<string[] | null>;
45
- /** A lane body by its hash; null = unavailable. */
46
- blob(hash: string): Promise<string | null>;
47
- /** The doc's annotations lane body at the hub head ('' = empty); null = unavailable. */
48
- head(doc: string): Promise<string | null>;
45
+ /**
46
+ * A lane body by its hash; null = unavailable. #166 R3: `signal` aborts at the check's deadline
47
+ * and once the check has answered — a read still in flight then ends instead of running to its
48
+ * own transport timeout.
49
+ */
50
+ blob(hash: string, signal?: AbortSignal): Promise<string | null>;
51
+ /** The doc's annotations lane body at the hub head ('' = empty); null = unavailable. Same `signal`. */
52
+ head(doc: string, signal?: AbortSignal): Promise<string | null>;
49
53
  }
50
54
 
51
55
  const HASH_RE = /^[0-9a-f]{64}$/;
@@ -64,6 +68,12 @@ const HASH_RE = /^[0-9a-f]{64}$/;
64
68
  export const HUB_UNDO_CHECK_DEADLINE_MS = 2000;
65
69
  export const HUB_UNDO_MAX_EFFECTS = 64;
66
70
  export const HUB_UNDO_MAX_BODY_BYTES = MAX_BOARD_BYTES;
71
+ /**
72
+ * #166 R3 — the transport cap on one blob / head read (its JSON envelope, so a body at the board
73
+ * limit plus its escaping fits): enforced while the bytes stream in, past it the read is cancelled
74
+ * and answers unreadable (fail open, as every other bound here).
75
+ */
76
+ export const HUB_UNDO_READ_MAX_BYTES = 2 * HUB_UNDO_MAX_BODY_BYTES + 64 * 1024;
67
77
 
68
78
  export interface HubTextUndoLimits {
69
79
  deadlineMs?: number;
@@ -72,10 +82,14 @@ export interface HubTextUndoLimits {
72
82
  }
73
83
 
74
84
  /** A lane body by an effect's hash: none → '' (the lane's "no value"), a bad hash → null. */
75
- async function bodyOf(hash: string | null | undefined, reads: HubTextUndoReads) {
85
+ async function bodyOf(
86
+ hash: string | null | undefined,
87
+ reads: HubTextUndoReads,
88
+ signal: AbortSignal
89
+ ) {
76
90
  if (hash === null || hash === undefined || hash === '') return '';
77
91
  if (!HASH_RE.test(hash)) return null;
78
- return reads.blob(hash);
92
+ return reads.blob(hash, signal);
79
93
  }
80
94
 
81
95
  /** Over the byte cap → unreadable (null). `length` first: UTF-8 is never shorter. */
@@ -93,9 +107,13 @@ export async function hubTextUndoConflict(
93
107
  ): Promise<boolean> {
94
108
  let expired = false;
95
109
  let timer: ReturnType<typeof setTimeout> | undefined;
110
+ // #166 R3 — one signal for every hub read under the check: aborted at the deadline, and in the
111
+ // finally once the check answered (a read nobody waits for any more ends there).
112
+ const reading = new AbortController();
96
113
  const deadline = new Promise<false>((resolve) => {
97
114
  timer = setTimeout(() => {
98
115
  expired = true;
116
+ reading.abort();
99
117
  resolve(false);
100
118
  }, limits.deadlineMs ?? HUB_UNDO_CHECK_DEADLINE_MS);
101
119
  });
@@ -105,11 +123,13 @@ export async function hubTextUndoConflict(
105
123
  maxEffects: limits.maxEffects ?? HUB_UNDO_MAX_EFFECTS,
106
124
  maxBodyBytes: limits.maxBodyBytes ?? HUB_UNDO_MAX_BODY_BYTES,
107
125
  expired: () => expired,
126
+ signal: reading.signal,
108
127
  }),
109
128
  deadline,
110
129
  ]);
111
130
  } finally {
112
131
  clearTimeout(timer);
132
+ reading.abort();
113
133
  }
114
134
  }
115
135
 
@@ -131,7 +151,7 @@ async function targetIds(target: UndoTarget, reads: HubTextUndoReads): Promise<s
131
151
  async function check(
132
152
  target: UndoTarget,
133
153
  reads: HubTextUndoReads,
134
- o: { maxEffects: number; maxBodyBytes: number; expired: () => boolean }
154
+ o: { maxEffects: number; maxBodyBytes: number; expired: () => boolean; signal: AbortSignal }
135
155
  ): Promise<boolean> {
136
156
  const ids = await targetIds(target, reads);
137
157
  if (!ids) return false;
@@ -153,11 +173,11 @@ async function check(
153
173
  if (o.expired()) return false;
154
174
  if (e?.lane !== 'annotations' || !e.doc || blind.has(e.doc)) continue;
155
175
  if (++examined > o.maxEffects) return false;
156
- const before = capped(await bodyOf(e.beforeHash, reads), o.maxBodyBytes);
176
+ const before = capped(await bodyOf(e.beforeHash, reads, o.signal), o.maxBodyBytes);
157
177
  const after =
158
178
  before === null || o.expired()
159
179
  ? null
160
- : capped(await bodyOf(e.afterHash, reads), o.maxBodyBytes);
180
+ : capped(await bodyOf(e.afterHash, reads, o.signal), o.maxBodyBytes);
161
181
  if (before === null || after === null) {
162
182
  blind.add(e.doc);
163
183
  chains.delete(e.doc);
@@ -170,7 +190,7 @@ async function check(
170
190
  }
171
191
  for (const [doc, steps] of chains) {
172
192
  if (o.expired()) return false;
173
- const now = capped(await reads.head(doc), o.maxBodyBytes);
193
+ const now = capped(await reads.head(doc, o.signal), o.maxBodyBytes);
174
194
  if (now === null || o.expired()) continue;
175
195
  if (textRevertChainCollides(steps, now)) return true;
176
196
  }