@1agh/maude 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/apps/studio/access/request.ts +1 -0
  2. package/apps/studio/actions/agents.ts +27 -0
  3. package/apps/studio/actions/defs/app.ts +28 -1
  4. package/apps/studio/actions/defs/sync.ts +4 -0
  5. package/apps/studio/actions.manifest.json +60 -2
  6. package/apps/studio/actions.parity.json +13 -1
  7. package/apps/studio/bin/_curl-local.mjs +7 -4
  8. package/apps/studio/client/app.jsx +16 -4
  9. package/apps/studio/client/home/HomeAccountsRow.jsx +221 -0
  10. package/apps/studio/client/home/HomeConnection.jsx +111 -0
  11. package/apps/studio/client/home/home-accounts-model.js +110 -1
  12. package/apps/studio/client/home/home-api.js +6 -2
  13. package/apps/studio/client/home/home-app.jsx +74 -12
  14. package/apps/studio/client/home/home-model.js +40 -1
  15. package/apps/studio/client/home/home-where-model.js +105 -0
  16. package/apps/studio/client/home/home.css +233 -1
  17. package/apps/studio/client/hooks/use-palette-and-panels.jsx +3 -1
  18. package/apps/studio/client/hooks/use-tabs.jsx +11 -4
  19. package/apps/studio/client/panels/TeamProjects.jsx +137 -134
  20. package/apps/studio/client/share-link.js +12 -0
  21. package/apps/studio/client/styles/_index.css +4 -0
  22. package/apps/studio/client/v2/diagnostics/diagnostics-host.jsx +1 -0
  23. package/apps/studio/client/v2/diagnostics/diagnostics-model.js +32 -2
  24. package/apps/studio/client/v2/diagnostics/diagnostics-sheet.jsx +35 -8
  25. package/apps/studio/client/v2/diagnostics/diagnostics.css +34 -0
  26. package/apps/studio/client/v2/diagnostics/sync-details/sync-details-model.js +94 -3
  27. package/apps/studio/client/v2/diagnostics/sync-details/sync-details.jsx +187 -4
  28. package/apps/studio/client/v2/link-server/LinkServerDialog.jsx +492 -0
  29. package/apps/studio/client/v2/link-server/LinkServerHost.jsx +42 -0
  30. package/apps/studio/client/v2/link-server/link-server-api.js +142 -0
  31. package/apps/studio/client/v2/link-server/link-server-model.js +438 -0
  32. package/apps/studio/client/v2/link-server/link-server.css +109 -0
  33. package/apps/studio/client/v2/onboarding/AdvancedSheets.jsx +31 -86
  34. package/apps/studio/client/v2/onboarding/onboarding-model.js +1 -18
  35. package/apps/studio/client/v2/search/search-keywords.js +3 -2
  36. package/apps/studio/client/v2/settings/account.jsx +4 -2
  37. package/apps/studio/client/v2/settings/advanced-section.jsx +245 -148
  38. package/apps/studio/client/v2/settings/connection-row.jsx +3 -59
  39. package/apps/studio/client/v2/settings/connections-section.jsx +118 -425
  40. package/apps/studio/client/v2/settings/general-section.jsx +138 -43
  41. package/apps/studio/client/v2/settings/project-sync-settings.jsx +4 -3
  42. package/apps/studio/client/v2/settings/reset-section.jsx +14 -3
  43. package/apps/studio/client/v2/settings/settings-card.jsx +142 -0
  44. package/apps/studio/client/v2/settings/settings-cards.js +220 -0
  45. package/apps/studio/client/v2/settings/settings-handlers.js +7 -6
  46. package/apps/studio/client/v2/settings/settings-model.js +91 -31
  47. package/apps/studio/client/v2/settings/settings-sheet.jsx +25 -6
  48. package/apps/studio/client/v2/settings/settings.css +374 -64
  49. package/apps/studio/client/v2/settings/this-project-card.jsx +730 -0
  50. package/apps/studio/client/v2/settings/this-project-model.js +172 -0
  51. package/apps/studio/client/v2/settings/use-connections.js +3 -2
  52. package/apps/studio/client/v2/settings/use-open-card.js +37 -0
  53. package/apps/studio/client/v2/shell/connection-state.js +197 -0
  54. package/apps/studio/client/v2/shell/menu-runner.js +7 -2
  55. package/apps/studio/client/v2/shell/project-account-bus.js +36 -0
  56. package/apps/studio/client/v2/shell/project-account-card.jsx +357 -148
  57. package/apps/studio/client/v2/shell/project-account-model.js +272 -149
  58. package/apps/studio/client/v2/shell/project-account-toast.js +66 -0
  59. package/apps/studio/client/v2/shell/project-account.css +237 -0
  60. package/apps/studio/client/v2/shell/share-cluster-host.jsx +166 -83
  61. package/apps/studio/client/v2/shell/shell-parity.js +3 -2
  62. package/apps/studio/client/v2/shell/shell-parity.json +40 -26
  63. package/apps/studio/client/v2/shell/use-account.js +2 -0
  64. package/apps/studio/client/v2/signin/use-signin.js +1 -1
  65. package/apps/studio/cloud/endpoints.ts +29 -4
  66. package/apps/studio/dist/client.bundle.js +834 -834
  67. package/apps/studio/dist/styles.css +1 -1
  68. package/apps/studio/home/accounts.ts +30 -11
  69. package/apps/studio/home/cloud.ts +6 -1
  70. package/apps/studio/home/hub-health.ts +76 -0
  71. package/apps/studio/home/routes.ts +9 -3
  72. package/apps/studio/http.ts +8 -0
  73. package/apps/studio/migrate/hub.ts +8 -1
  74. package/apps/studio/routes/hub-link-folder.ts +334 -0
  75. package/apps/studio/routes/hub-signin.ts +78 -1
  76. package/apps/studio/routes/index.ts +4 -0
  77. package/apps/studio/routes/sync.ts +22 -4
  78. package/apps/studio/shell/api-key.ts +11 -0
  79. package/apps/studio/sync/accepted-cold-start.ts +144 -8
  80. package/apps/studio/sync/action-stage.ts +18 -1
  81. package/apps/studio/sync/ctl-heal.ts +58 -0
  82. package/apps/studio/sync/file-ledger.ts +38 -4
  83. package/apps/studio/sync/file-plane.ts +226 -19
  84. package/apps/studio/sync/held-deletes.ts +86 -5
  85. package/apps/studio/sync/hub-link.ts +8 -0
  86. package/apps/studio/sync/index.ts +68 -4
  87. package/apps/studio/sync/link-consent.ts +22 -75
  88. package/apps/studio/sync/link-survey.ts +252 -0
  89. package/apps/studio/sync/local-kernel.ts +16 -1
  90. package/apps/studio/sync/seed-progress.ts +12 -0
  91. package/apps/studio/sync/source-recovery.ts +18 -2
  92. package/apps/studio/sync/status.ts +11 -1
  93. package/apps/studio/sync/writer-registry.ts +5 -0
  94. package/apps/studio/whats-new.json +18 -0
  95. package/cli/lib/bash-guard.mjs +19 -0
  96. package/cli/lib/design-help.gen.mjs +1 -1
  97. package/package.json +9 -8
  98. package/apps/studio/client/v2/onboarding/HubSheet.jsx +0 -212
  99. package/apps/studio/client/v2/shell/account-card-model.js +0 -114
  100. package/apps/studio/client/v2/shell/account-card.jsx +0 -189
@@ -1,7 +1,9 @@
1
1
  // home/accounts.ts — 2.0.5 W4b: the accounts each profile on this Mac is signed in with, for Home's
2
2
  // avatar, and the per-account sign-outs it offers.
3
3
  //
4
- // GET /_home/accounts?profiles=a,b → { ok, profiles: [{ id, hubs: [{ url, account }] }] }
4
+ // GET /_home/accounts?profiles=a,b → { ok, profiles: [{ id, hubs: [{ url, account, state }] }] }
5
+ // `state` (2.1.1): ok · rejected · unreachable · unknown — whether
6
+ // that sign-in still works (hub-health.ts; cached, never a token)
5
7
  // POST /_home/hub/signout { profile, url } → forget that profile's sign-in for that server
6
8
  // POST /_home/cloud/signout { profile } → forget that profile's Maude Cloud sign-in
7
9
  //
@@ -17,6 +19,7 @@ import { existsSync, unlinkSync } from 'node:fs';
17
19
  import { deleteHubCredential } from '../sync/hub-link.ts';
18
20
  import { loadHubsConfig, normalizeUrl, safeAccount } from '../sync/hubs-config.ts';
19
21
  import { profileCloudPath, profileHubsPath } from './cloud.ts';
22
+ import { createHubHealth, type HubHealth, type HubState } from './hub-health.ts';
20
23
  import type { HomeAnswer } from './signin.ts';
21
24
 
22
25
  const MAX_PROFILES = 16;
@@ -24,11 +27,18 @@ const MAX_HUBS = 50;
24
27
 
25
28
  export interface ProfileHubs {
26
29
  id: string;
27
- hubs: Array<{ url: string; account: string | null }>;
30
+ hubs: Array<{ url: string; account: string | null; state: HubState }>;
28
31
  }
29
32
 
30
- /** Each named profile's team-server sign-ins (no tokens). Unknown / invalid ids are skipped. */
31
- export function profileAccounts(ids: string[]): ProfileHubs[] {
33
+ /**
34
+ * Each named profile's team-server sign-ins (no tokens), each with whether it still works. Unknown /
35
+ * invalid ids are skipped. The servers are asked together (and each answer is cached), so the call
36
+ * takes about one round trip, not one per server.
37
+ */
38
+ export async function profileAccounts(
39
+ ids: string[],
40
+ health: HubHealth = createHubHealth()
41
+ ): Promise<ProfileHubs[]> {
32
42
  const out: ProfileHubs[] = [];
33
43
  for (const id of [...new Set(ids)].slice(0, MAX_PROFILES)) {
34
44
  const file = profileHubsPath(id);
@@ -36,10 +46,16 @@ export function profileAccounts(ids: string[]): ProfileHubs[] {
36
46
  let hubs: ProfileHubs['hubs'] = [];
37
47
  try {
38
48
  const cfg = loadHubsConfig(file);
39
- hubs = Object.entries(cfg.hubs ?? {})
40
- .filter(([, rec]) => rec && typeof rec.token === 'string' && rec.token)
41
- .slice(0, MAX_HUBS)
42
- .map(([url, rec]) => ({ url, account: safeAccount(rec.account) }));
49
+ hubs = await Promise.all(
50
+ Object.entries(cfg.hubs ?? {})
51
+ .filter(([, rec]) => rec && typeof rec.token === 'string' && rec.token)
52
+ .slice(0, MAX_HUBS)
53
+ .map(async ([url, rec]) => ({
54
+ url,
55
+ account: safeAccount(rec.account),
56
+ state: await health.state(url, rec.token).catch(() => 'unknown' as const),
57
+ }))
58
+ );
43
59
  } catch {
44
60
  hubs = [];
45
61
  }
@@ -50,11 +66,14 @@ export function profileAccounts(ids: string[]): ProfileHubs[] {
50
66
 
51
67
  const bad = (error: string): HomeAnswer => ({ status: 400, body: { ok: false, error } });
52
68
 
53
- export function createHomeAccounts(deps: { forgetCloud?: (profile: string) => void } = {}) {
69
+ export function createHomeAccounts(
70
+ deps: { forgetCloud?: (profile: string) => void; hubHealth?: HubHealth } = {}
71
+ ) {
72
+ const health = deps.hubHealth ?? createHubHealth();
54
73
  return {
55
- list(param: string | null): HomeAnswer {
74
+ async list(param: string | null): Promise<HomeAnswer> {
56
75
  const ids = (param ?? '').split(',').filter(Boolean);
57
- return { status: 200, body: { ok: true, profiles: profileAccounts(ids) } };
76
+ return { status: 200, body: { ok: true, profiles: await profileAccounts(ids, health) } };
58
77
  },
59
78
 
60
79
  hubSignOut(b: Record<string, unknown>): HomeAnswer {
@@ -134,6 +134,11 @@ export interface CloudListing {
134
134
  signedIn: boolean;
135
135
  /** the control plane could not be reached — these rows are the last good answer (or empty) */
136
136
  offline?: boolean;
137
+ /**
138
+ * 2.1.1 — the control plane refused this profile's saved sign-in (401/403): the person is not signed
139
+ * out of their own accord, the sign-in stopped working. Absent when there is no credential at all.
140
+ */
141
+ rejected?: boolean;
137
142
  /** the control plane has no /api/home yet: projects only, no `shared` */
138
143
  fallback?: boolean;
139
144
  account: { email: string | null } | null;
@@ -214,7 +219,7 @@ export function createHomeCloud(opts: { now?: () => number } = {}): HomeCloud {
214
219
  }
215
220
  if (r.status === 401 || r.status === 403) {
216
221
  cache.delete(profile);
217
- return empty({ error: 'This device was disconnected. Sign in again.' });
222
+ return empty({ rejected: true, error: 'This device was disconnected. Sign in again.' });
218
223
  }
219
224
  if (r.status !== 200 || !r.body || typeof r.body !== 'object') {
220
225
  // offline / 5xx / garbage → the last good answer for THIS token, flagged
@@ -0,0 +1,76 @@
1
+ // home/hub-health.ts — 2.1.1 B4: is a saved team-server sign-in still accepted, or does the server not
2
+ // answer at all? Home's accounts row and every project row's connection badge read this.
3
+ //
4
+ // ok the server took the token
5
+ // rejected the server answered 401: the sign-in stopped working (the person signs in again)
6
+ // unreachable no answer, or a 5xx: the server's side, not the person's
7
+ // unknown the question could not be asked (an address that may not carry a token, an old server
8
+ // without the route, a refusal that says nothing about the token) — never drawn as broken
9
+ //
10
+ // One authenticated `GET /api/documents` per server — the listing the sync client itself uses, so it
11
+ // answers exactly what sync would. Cheap by construction: a result is kept per (address, token) for
12
+ // `ttlMs`, and concurrent asks for the same pair share one request. The token goes only to the address
13
+ // it was saved against (https, or http on loopback), with no redirect followed and no ambient
14
+ // credentials, and is never part of any answer.
15
+
16
+ import { createHash } from 'node:crypto';
17
+
18
+ import { hubAddress } from './hub.ts';
19
+
20
+ export type HubState = 'ok' | 'rejected' | 'unreachable' | 'unknown';
21
+
22
+ export interface HubHealth {
23
+ state(url: string, token: string): Promise<HubState>;
24
+ }
25
+
26
+ const TTL_MS = 60_000;
27
+ const TIMEOUT_MS = 4000;
28
+ const MAX_ENTRIES = 200;
29
+
30
+ export function createHubHealth(
31
+ opts: { fetchImpl?: typeof fetch; now?: () => number; ttlMs?: number } = {}
32
+ ): HubHealth {
33
+ const doFetch = opts.fetchImpl ?? ((...a: Parameters<typeof fetch>) => fetch(...a));
34
+ const now = opts.now ?? Date.now;
35
+ const ttl = opts.ttlMs ?? TTL_MS;
36
+ const done = new Map<string, { at: number; value: HubState }>();
37
+ const flying = new Map<string, Promise<HubState>>();
38
+
39
+ async function ask(base: string, token: string): Promise<HubState> {
40
+ try {
41
+ const res = await doFetch(`${base}/api/documents`, {
42
+ method: 'GET',
43
+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
44
+ signal: AbortSignal.timeout(TIMEOUT_MS),
45
+ redirect: 'error',
46
+ credentials: 'omit',
47
+ });
48
+ if (res.status === 200) return 'ok';
49
+ if (res.status === 401) return 'rejected';
50
+ if (res.status >= 500) return 'unreachable';
51
+ return 'unknown';
52
+ } catch {
53
+ return 'unreachable';
54
+ }
55
+ }
56
+
57
+ return {
58
+ async state(url, token) {
59
+ const a = hubAddress(url);
60
+ if (!a.ok || !token) return 'unknown';
61
+ const key = createHash('sha256').update(`${a.url}\n${token}`).digest('hex');
62
+ const hit = done.get(key);
63
+ if (hit && now() - hit.at < ttl) return hit.value;
64
+ const live = flying.get(key);
65
+ if (live) return live;
66
+ const p = ask(a.url, token).then((value) => {
67
+ flying.delete(key);
68
+ if (done.size >= MAX_ENTRIES) done.delete(done.keys().next().value as string);
69
+ done.set(key, { at: now(), value });
70
+ return value;
71
+ });
72
+ flying.set(key, p);
73
+ return p;
74
+ },
75
+ };
76
+ }
@@ -49,6 +49,7 @@ import type { HomeCloud } from './cloud.ts';
49
49
  import { checkLocationReason, createLocalProject } from './create-local.ts';
50
50
  import { createHomeGithub, type HomeGithub } from './github.ts';
51
51
  import { createHomeHub, type HomeHub } from './hub.ts';
52
+ import type { HubHealth } from './hub-health.ts';
52
53
  import { indexGcRequest } from './index-gc.ts';
53
54
  import { readHomeIndex, resolveProject, searchHome, thumbSource } from './index-reader.ts';
54
55
  import { createHomeInvite, type HomeInvite } from './invite.ts';
@@ -93,6 +94,8 @@ export interface HomeDeps {
93
94
  whatsNew?: HomeWhatsNew;
94
95
  /** S6.10 — the clone behind "From GitHub" (internal: Rust names the folder and the token) */
95
96
  github?: HomeGithub;
97
+ /** 2.1.1 — does each saved team-server sign-in still work (default: a cached real probe) */
98
+ hubHealth?: HubHealth;
96
99
  }
97
100
 
98
101
  const NO_STORE = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' };
@@ -282,7 +285,10 @@ export function homeRouteTable(deps: HomeDeps): HomeRoute[] {
282
285
  const cli = deps.cli ?? createHomeCli();
283
286
  const whatsNew = deps.whatsNew ?? createHomeWhatsNew();
284
287
  const github = deps.github ?? createHomeGithub();
285
- const accounts = createHomeAccounts({ forgetCloud: (p) => deps.cloud.forget(p) });
288
+ const accounts = createHomeAccounts({
289
+ forgetCloud: (p) => deps.cloud.forget(p),
290
+ hubHealth: deps.hubHealth,
291
+ });
286
292
  return [
287
293
  {
288
294
  method: 'GET',
@@ -494,8 +500,8 @@ export function homeRouteTable(deps: HomeDeps): HomeRoute[] {
494
500
  method: 'GET',
495
501
  path: '/_home/accounts',
496
502
  kind: 'home',
497
- handle: (_req, url) => {
498
- const r = accounts.list(url.searchParams.get('profiles'));
503
+ handle: async (_req, url) => {
504
+ const r = await accounts.list(url.searchParams.get('profiles'));
499
505
  return json(r.status, r.body);
500
506
  },
501
507
  },
@@ -2832,6 +2832,14 @@ export function createHttp(
2832
2832
  linkedHubUrl: () => ctx.cfg.linkedHub?.url,
2833
2833
  restartSync: () => ctx.syncControl?.restart(),
2834
2834
  },
2835
+ // 2.1.1 — POST /_api/hub/link-folder (routes/hub-link-folder.ts): main origin, window only, on the attach lane.
2836
+ hubLinkFolder: {
2837
+ designRoot: ctx.paths.designRoot,
2838
+ repoRoot: ctx.paths.repoRoot,
2839
+ canvasGroups: () => ctx.cfg.canvasGroups,
2840
+ localFormat: () => asFormat(ctx.cfg.formatVersion),
2841
+ attachStored: (url) => cloudApi.attachStored(url),
2842
+ },
2835
2843
  }).map(guardTableRoute);
2836
2844
  // p8-a1-claims — outside the gates: a write that names an AI chat answers inside its run's claim
2837
2845
  // (in place, so every consumer of the table — the mount, the local gate — sees the same specs)
@@ -81,7 +81,11 @@ export function createHubFormatClient(
81
81
  return {
82
82
  async health() {
83
83
  try {
84
- const res = await fetchImpl(`${base}/health`, { signal: AbortSignal.timeout(10_000) });
84
+ // 2.1.1 T8 — never follow a redirect off the server (every call below carries the bearer)
85
+ const res = await fetchImpl(`${base}/health`, {
86
+ redirect: 'manual',
87
+ signal: AbortSignal.timeout(10_000),
88
+ });
85
89
  if (!res.ok) return { ok: false };
86
90
  const j = (await res.json()) as {
87
91
  formatVersion?: unknown;
@@ -115,6 +119,7 @@ export function createHubFormatClient(
115
119
  try {
116
120
  const res = await fetchImpl(`${base}${MODE_PATH}`, {
117
121
  headers: { authorization: `Bearer ${hub.token}` },
122
+ redirect: 'manual',
118
123
  signal: AbortSignal.timeout(10_000),
119
124
  });
120
125
  const j = (await res.json().catch(() => null)) as {
@@ -149,6 +154,7 @@ export function createHubFormatClient(
149
154
  const res = await fetchImpl(`${base}${MODE_PATH}`, {
150
155
  method: 'POST',
151
156
  headers: { 'content-type': 'application/json', authorization: `Bearer ${hub.token}` },
157
+ redirect: 'manual',
152
158
  // #166 (2.0.4): a dry run here reads only the blockers, so it asks for them alone —
153
159
  // the hub's full preview imports (opens) every document. An older hub ignores the flag.
154
160
  body: JSON.stringify({
@@ -205,6 +211,7 @@ export function createHubFormatClient(
205
211
  formatVersion,
206
212
  ...(expectEpoch !== undefined ? { expectEpoch } : {}),
207
213
  }),
214
+ redirect: 'manual',
208
215
  signal: AbortSignal.timeout(20_000),
209
216
  });
210
217
  const j = (await res.json().catch(() => null)) as {
@@ -0,0 +1,334 @@
1
+ // 2.1.1 — "Link your server" in a project tab connects THIS folder to the person's own team server
2
+ // (decision maude/v2-2.1.1-b5-link-folder-confirm-before-merge).
3
+ //
4
+ // POST /_api/hub/link-folder { url } → { ok, state: 'linked', url, sync }
5
+ // | { ok, state: 'needs-confirm', confirm, counts, host }
6
+ // POST /_api/hub/link-folder { url, confirm } → { ok, state: 'linked', … } (the person said yes)
7
+ //
8
+ // The sign-in already happened on the server's own page (`/_api/hub-signin/*`), which stored this Mac's
9
+ // credential for it; this route only uses that credential. A self-hosted server holds ONE project:
10
+ //
11
+ // • (2.1.1 T8) a server this Mac never linked any folder to → ALWAYS the confirm below first, with
12
+ // what goes up (`empty: true` when the server holds nothing) — the server's survey is its word;
13
+ // • it holds nothing yet → link now: the folder's format marker goes up first (raise-only, V2-1.12
14
+ // §5.2, as Move to cloud), then the attach lane (`cloud/endpoints.ts` `attachStored` → `linkFolder`:
15
+ // linkedHub in config.json, the link recorded on this Mac, the live sync runtime cycled — whose
16
+ // seed-up uploads the folder);
17
+ // • it already holds work → NOTHING is written: the answer counts what only this Mac has, what only
18
+ // the server has and what differs (sync/link-survey.ts), with a one-time confirm code bound to that
19
+ // server. A second POST with the code links, exactly as above. Never a silent two-way merge.
20
+ //
21
+ // linkedHub is written only by the attach lane, only on success. A folder already linked to another
22
+ // server, a worktree tab, a server this Mac holds no sign-in for and a server on a newer format than
23
+ // this build are refused before anything moves.
24
+ //
25
+ // MAIN ORIGIN, WINDOW ONLY: it spends the team-server credential and uploads the project, so it is the
26
+ // person's act in the Maude window — the same gate as Move to cloud (`Sec-Fetch-Site: same-origin`,
27
+ // which a page cannot forge and the loopback helper refuses to send), plus PERSON_ONLY (shell/api-key.ts)
28
+ // and `guardTableRoute`'s CSRF + DNS-rebind gates. Never canvas-safe; a cell never serves it
29
+ // (apps/hub/src/studio-manifest.mjs: REFUSED — a cell holds no team-server credential of its own).
30
+ // No answer ever carries a credential.
31
+
32
+ import { randomBytes } from 'node:crypto';
33
+ import { readFileSync } from 'node:fs';
34
+ import { join } from 'node:path';
35
+
36
+ import type { CloudEndpointResult } from '../cloud/endpoints.ts';
37
+ import { SUPPORTED_FORMAT } from '../format.ts';
38
+ import { hubAddress } from '../home/hub.ts';
39
+ import { createHubFormatClient } from '../migrate/hub.ts';
40
+ import { worktreeOf } from '../shell/worktree.ts';
41
+ import type { CanvasGroupLike } from '../sync/file-membership.ts';
42
+ import { getHubRecord, normalizeUrl } from '../sync/hubs-config.ts';
43
+ import { hubEverLinked, linksPath, normHub, projectLinkOf } from '../sync/link-consent.ts';
44
+ import {
45
+ compareSurveys,
46
+ holdsWork,
47
+ type LinkComparison,
48
+ surveyHub,
49
+ surveyLocal,
50
+ } from '../sync/link-survey.ts';
51
+ import type { RouteSpec } from './table.ts';
52
+
53
+ export const HUB_LINK_FOLDER_PATH = '/_api/hub/link-folder';
54
+
55
+ export interface HubLinkFolderDeps {
56
+ designRoot: string;
57
+ /** config.json `canvasGroups` — the plane's walk classifies against them */
58
+ canvasGroups?: () => readonly CanvasGroupLike[] | undefined;
59
+ /** the folder's own format marker (config.json `formatVersion ?? 1`) */
60
+ localFormat: () => number;
61
+ /** the attach lane (cloud/endpoints.ts) — the one place linkedHub is written */
62
+ attachStored(hubUrl: string): Promise<CloudEndpointResult>;
63
+ /** this profile's hubs.json; absent = `hubsConfigPath()` */
64
+ hubsConfigPath?: string;
65
+ /** #206 §5 — the main project's name when this server serves a worktree tab */
66
+ worktreeOf?: () => string | null;
67
+ /** 2.1.1 T8 — the folder holding `.design/`: "already linked" is decided by THIS Mac's link record
68
+ * for it (sync/link-consent.ts), never by the committed config.json alone. Absent = the record is
69
+ * not consulted (the claim alone decides, as before). */
70
+ repoRoot?: string;
71
+ /** this Mac's link records (`project-links.json`); absent = `linksPath()` */
72
+ linksFile?: string;
73
+ /** seams for tests */
74
+ fetchImpl?: typeof fetch;
75
+ now?: () => number;
76
+ }
77
+
78
+ /** CONTRACT §3–§4 voice. Every refusal says nothing was linked. */
79
+ export const LINK_FOLDER_WORDS = {
80
+ windowOnly: 'Link your server from the Maude window.',
81
+ badAddress: 'That doesn’t look like a server address. Nothing was linked.',
82
+ signedOut: (host: string) => `Sign in to ${host} first. Nothing was linked.`,
83
+ offline: (host: string) =>
84
+ `${host} didn’t answer. Nothing was linked — try again when this Mac is online.`,
85
+ linkedElsewhere: (host: string) =>
86
+ `This project already syncs with ${host}. Unlink it there first. Nothing was linked.`,
87
+ worktree: (main: string) => `This folder syncs from ${main}. Link ${main} instead.`,
88
+ newer: (host: string) =>
89
+ `${host} runs a newer Maude than this one. Update Maude, then link again. Nothing was linked.`,
90
+ format: (host: string) =>
91
+ `${host} needs an update before this project can sync with it. Nothing was linked.`,
92
+ // 2.1.1 T14 — the server's software is current, but its project is still on the old format and only
93
+ // the project's OWNER can raise it: a member can do nothing about "needs an update"
94
+ formatOwner: (host: string) =>
95
+ `${host} is on an older format. Its owner needs to open it in Maude 2.1 once before this folder can sync. Nothing was linked.`,
96
+ expired: 'That confirmation expired. Press Link again to see what syncing would do.',
97
+ failed: 'Linking didn’t finish. Your work is still on this Mac.',
98
+ };
99
+
100
+ const CONFIRM_TTL_MS = 10 * 60_000;
101
+ const MAX_PENDING = 16;
102
+
103
+ const json = (status: number, body: unknown) =>
104
+ Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
105
+
106
+ const hostOf = (url: string) => {
107
+ try {
108
+ return new URL(url).host;
109
+ } catch {
110
+ return url;
111
+ }
112
+ };
113
+
114
+ class LinkRefusal extends Error {
115
+ constructor(
116
+ readonly status: number,
117
+ readonly reason: string,
118
+ message: string
119
+ ) {
120
+ super(message);
121
+ }
122
+ }
123
+
124
+ export function createHubLinkFolderRoutes(deps: HubLinkFolderDeps): RouteSpec[] {
125
+ const doFetch = deps.fetchImpl ?? fetch;
126
+ const now = deps.now ?? Date.now;
127
+ /** confirm code → the server it was shown for. One use; a restart forgets them (the safe way). */
128
+ const pending = new Map<string, { url: string; expires: number }>();
129
+ /** Serialises POSTs: two presses must not link twice or race the config write. */
130
+ let gate: Promise<unknown> = Promise.resolve();
131
+
132
+ const linksFile = () => deps.linksFile ?? linksPath();
133
+
134
+ /** The server this folder is linked to ON THIS MAC, or null. The committed `linkedHub` is a claim
135
+ * (a clone, a peer's edit): it counts only when this Mac's link record for the folder names the
136
+ * same server (gate-b-sec4). An unconfirmed claim is "not linked" — never "already linked", never
137
+ * "unlink it there first" pointing at a host the repo names. */
138
+ function linkedHub(): string | null {
139
+ let url: string;
140
+ try {
141
+ const cfg = JSON.parse(readFileSync(join(deps.designRoot, 'config.json'), 'utf8'));
142
+ const raw = cfg?.linkedHub?.url;
143
+ if (typeof raw !== 'string' || !raw) return null;
144
+ try {
145
+ url = normalizeUrl(raw);
146
+ } catch {
147
+ url = raw;
148
+ }
149
+ } catch {
150
+ return null;
151
+ }
152
+ if (deps.repoRoot === undefined) return url;
153
+ const rec = projectLinkOf(deps.repoRoot, linksFile());
154
+ return rec && rec.hub === normHub(url) ? url : null;
155
+ }
156
+
157
+ function mint(url: string): string {
158
+ const t = now();
159
+ for (const [k, v] of pending) if (v.expires <= t) pending.delete(k);
160
+ while (pending.size >= MAX_PENDING) {
161
+ const oldest = pending.keys().next().value;
162
+ if (oldest === undefined) break;
163
+ pending.delete(oldest);
164
+ }
165
+ const code = randomBytes(18).toString('base64url');
166
+ pending.set(code, { url, expires: t + CONFIRM_TTL_MS });
167
+ return code;
168
+ }
169
+
170
+ function redeem(code: string, url: string): boolean {
171
+ const row = pending.get(code);
172
+ if (!row) return false;
173
+ pending.delete(code); // one use, whatever the outcome
174
+ return row.url === url && row.expires > now();
175
+ }
176
+
177
+ /** V2-1.12 §5.2 — raise-only, before the first seed-up; a newer server is refused. */
178
+ async function checkFormat(url: string, token: string): Promise<void> {
179
+ const host = hostOf(url);
180
+ const client = createHubFormatClient({ url, token }, doFetch);
181
+ const health = await client.health();
182
+ if (!health.ok) throw new LinkRefusal(503, 'offline', LINK_FOLDER_WORDS.offline(host));
183
+ const hub = health.formatVersion ?? 1;
184
+ if (hub > SUPPORTED_FORMAT)
185
+ throw new LinkRefusal(409, 'format-newer', LINK_FOLDER_WORDS.newer(host));
186
+ const local = deps.localFormat();
187
+ if (!(local > 1) || hub >= local) return;
188
+ if (!health.capabilities.includes('format-v2'))
189
+ throw new LinkRefusal(409, 'format', LINK_FOLDER_WORDS.format(host));
190
+ const set = await client.setFormat(local === 2 ? 2 : 1);
191
+ if (!set.ok) {
192
+ if (set.status === 0) throw new LinkRefusal(503, 'offline', LINK_FOLDER_WORDS.offline(host));
193
+ // the owner's door: a member's bearer is refused there
194
+ if (set.status === 401 || set.status === 403)
195
+ throw new LinkRefusal(409, 'format-owner', LINK_FOLDER_WORDS.formatOwner(host));
196
+ throw new LinkRefusal(409, 'format', LINK_FOLDER_WORDS.format(host));
197
+ }
198
+ }
199
+
200
+ async function link(url: string, token: string): Promise<Response> {
201
+ await checkFormat(url, token);
202
+ const attached = await deps.attachStored(url);
203
+ const j = (attached.json ?? {}) as {
204
+ ok?: unknown;
205
+ url?: unknown;
206
+ sync?: unknown;
207
+ note?: unknown;
208
+ };
209
+ if (attached.status === 401)
210
+ throw new LinkRefusal(401, 'signed-out', LINK_FOLDER_WORDS.signedOut(hostOf(url)));
211
+ if (attached.status !== 200 || j.ok !== true || typeof j.url !== 'string')
212
+ throw new LinkRefusal(502, 'failed', LINK_FOLDER_WORDS.failed);
213
+ // the attach answer, minus anything but what the dialog reads (it carries no credential today;
214
+ // naming the fields keeps it that way if the lane's answer ever grows)
215
+ return json(200, {
216
+ ok: true,
217
+ state: 'linked',
218
+ url: j.url,
219
+ sync: j.sync ?? null,
220
+ ...(typeof j.note === 'string' ? { note: j.note } : {}),
221
+ });
222
+ }
223
+
224
+ async function handle(req: Request): Promise<Response> {
225
+ let body: { url?: unknown; confirm?: unknown } = {};
226
+ try {
227
+ const text = await req.text();
228
+ if (text.length > 4096) throw new Error('too long');
229
+ body = text.trim() ? JSON.parse(text) : {};
230
+ if (!body || typeof body !== 'object' || Array.isArray(body))
231
+ throw new Error('not an object');
232
+ } catch {
233
+ return json(400, { ok: false, reason: 'bad-request', error: LINK_FOLDER_WORDS.badAddress });
234
+ }
235
+ // 2.1.1 T8 — the one address grammar every other door uses: https, or http only on loopback (the
236
+ // credential and the whole folder never travel in clear to a remote host)
237
+ const addr = hubAddress(body.url);
238
+ if (!addr.ok)
239
+ return json(400, { ok: false, reason: 'bad-address', error: LINK_FOLDER_WORDS.badAddress });
240
+ const url = addr.url;
241
+ const host = hostOf(url);
242
+
243
+ const linked = linkedHub();
244
+ if (linked && linked === url)
245
+ return json(200, { ok: true, state: 'linked', url, already: true });
246
+ if (linked)
247
+ return json(409, {
248
+ ok: false,
249
+ reason: 'linked-elsewhere',
250
+ error: LINK_FOLDER_WORDS.linkedElsewhere(hostOf(linked)),
251
+ });
252
+
253
+ const rec = getHubRecord(url, deps.hubsConfigPath);
254
+ if (!rec?.token)
255
+ return json(401, {
256
+ ok: false,
257
+ reason: 'signed-out',
258
+ error: LINK_FOLDER_WORDS.signedOut(host),
259
+ });
260
+
261
+ try {
262
+ if (body.confirm !== undefined) {
263
+ if (typeof body.confirm !== 'string' || !redeem(body.confirm, url))
264
+ return json(409, {
265
+ ok: false,
266
+ reason: 'confirm-expired',
267
+ error: LINK_FOLDER_WORDS.expired,
268
+ });
269
+ return await link(url, rec.token);
270
+ }
271
+
272
+ const there = await surveyHub(url, rec.token, doFetch);
273
+ if (!there.ok) {
274
+ return there.reason === 'signed-out'
275
+ ? json(401, { ok: false, reason: 'signed-out', error: LINK_FOLDER_WORDS.signedOut(host) })
276
+ : json(503, { ok: false, reason: 'offline', error: LINK_FOLDER_WORDS.offline(host) });
277
+ }
278
+ // 2.1.1 T8 — the FIRST link to a server this Mac never linked always asks, with what goes up,
279
+ // whatever the server says it holds (its survey is the server's word, not the person's).
280
+ const first = !hubEverLinked(url, linksFile());
281
+ if (!holdsWork(there.survey) && !first) return await link(url, rec.token);
282
+
283
+ const counts: LinkComparison = compareSurveys(
284
+ surveyLocal(deps.designRoot, deps.canvasGroups?.()),
285
+ there.survey
286
+ );
287
+ return json(200, {
288
+ ok: true,
289
+ state: 'needs-confirm',
290
+ host,
291
+ counts,
292
+ confirm: mint(url),
293
+ // the server holds nothing: the dialog says what goes up, not what merges
294
+ ...(holdsWork(there.survey) ? {} : { empty: true }),
295
+ });
296
+ } catch (err) {
297
+ if (err instanceof LinkRefusal)
298
+ return json(err.status, { ok: false, reason: err.reason, error: err.message });
299
+ console.error(`[hub-link-folder] ${(err as Error)?.message}`);
300
+ return json(500, { ok: false, reason: 'failed', error: LINK_FOLDER_WORDS.failed });
301
+ }
302
+ }
303
+
304
+ return [
305
+ {
306
+ method: 'POST',
307
+ path: '/_api/hub/link-folder',
308
+ origin: 'main',
309
+ // the `session` class, like Move to cloud: linking your own folder is the owner's act on their own
310
+ // place; a folder already linked (the only one a hub role applies to) answers 409 first
311
+ readOnly: 'allowed',
312
+ handle(req) {
313
+ // the person's act in the Maude window: only a browser's own same-origin fetch carries this
314
+ if (req.headers.get('sec-fetch-site') !== 'same-origin')
315
+ return json(403, {
316
+ ok: false,
317
+ reason: 'window-only',
318
+ error: LINK_FOLDER_WORDS.windowOnly,
319
+ });
320
+ // #206 §5: a worktree tab syncs from its main project — linking it would make a second copy
321
+ const main = (deps.worktreeOf ?? worktreeOf)();
322
+ if (main)
323
+ return json(409, {
324
+ ok: false,
325
+ reason: 'worktree',
326
+ error: LINK_FOLDER_WORDS.worktree(main),
327
+ });
328
+ const next = gate.then(() => handle(req));
329
+ gate = next.catch(() => null);
330
+ return next;
331
+ },
332
+ },
333
+ ];
334
+ }