@1agh/maude 0.58.2 → 0.59.0

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 (140) hide show
  1. package/apps/studio/annotations-bindings.ts +83 -4
  2. package/apps/studio/annotations-layer.tsx +49 -15
  3. package/apps/studio/api.ts +6 -1
  4. package/apps/studio/bin/_fetch-asset.mjs +169 -5
  5. package/apps/studio/bin/_import-asset.mjs +90 -0
  6. package/apps/studio/bin/_import-figma.mjs +1775 -0
  7. package/apps/studio/bin/_perf-probe-safari.mjs +332 -0
  8. package/apps/studio/bin/_perf-probe.mjs +228 -0
  9. package/apps/studio/bin/_perf-shared.mjs +345 -0
  10. package/apps/studio/bin/_video-playwright.mjs +103 -7
  11. package/apps/studio/bin/import-figma.sh +47 -0
  12. package/apps/studio/bin/perf.sh +228 -0
  13. package/apps/studio/bin/read-annotations.mjs +11 -1
  14. package/apps/studio/bin/smoke.sh +49 -5
  15. package/apps/studio/bun.lock +16 -22
  16. package/apps/studio/canvas-edit.ts +29 -5
  17. package/apps/studio/canvas-lib.tsx +148 -6
  18. package/apps/studio/client/app.jsx +196 -38
  19. package/apps/studio/client/export-center.jsx +42 -4
  20. package/apps/studio/client/panels/CloudBar.jsx +92 -1
  21. package/apps/studio/client/panels/FigmaImportPanel.jsx +264 -0
  22. package/apps/studio/client/panels/GitPanel.jsx +26 -6
  23. package/apps/studio/client/panels/SettingsPanel.jsx +181 -0
  24. package/apps/studio/client/panels/SetupChecklist.jsx +26 -2
  25. package/apps/studio/client/panels/SyncPanel.jsx +229 -0
  26. package/apps/studio/client/panels/TimelinePanel.jsx +31 -3
  27. package/apps/studio/client/panels/timeline-comp-target.js +101 -0
  28. package/apps/studio/client/panels/timeline-parse.js +3 -3
  29. package/apps/studio/client/styles/3-shell-maude.css +37 -0
  30. package/apps/studio/client/styles/4-components.css +134 -0
  31. package/apps/studio/clip-ops.ts +93 -17
  32. package/apps/studio/cloud/endpoints.ts +78 -10
  33. package/apps/studio/cloud/renew.ts +183 -0
  34. package/apps/studio/context.ts +2 -1
  35. package/apps/studio/dist/client.bundle.js +1231 -1231
  36. package/apps/studio/dist/runtime/@remotion_media.js +56 -136
  37. package/apps/studio/dist/runtime/@remotion_player.js +18 -18
  38. package/apps/studio/dist/runtime/@remotion_transitions.js +9 -9
  39. package/apps/studio/dist/runtime/@remotion_transitions_clock-wipe.js +1 -1
  40. package/apps/studio/dist/runtime/remotion.js +12 -12
  41. package/apps/studio/dist/styles.css +1 -1
  42. package/apps/studio/exporters/_browser-bundles.ts +20 -6
  43. package/apps/studio/exporters/_runtime.ts +19 -0
  44. package/apps/studio/exporters/degraded.ts +92 -0
  45. package/apps/studio/exporters/index.ts +5 -0
  46. package/apps/studio/exporters/jobs.ts +19 -0
  47. package/apps/studio/exporters/unsupported-media.ts +170 -0
  48. package/apps/studio/exporters/video-encode-lib.ts +35 -6
  49. package/apps/studio/exporters/video-render-lib.ts +6 -0
  50. package/apps/studio/exporters/video.ts +72 -1
  51. package/apps/studio/figma/assets.test.ts +464 -0
  52. package/apps/studio/figma/assets.ts +452 -0
  53. package/apps/studio/figma/client.test.ts +395 -0
  54. package/apps/studio/figma/client.ts +513 -0
  55. package/apps/studio/figma/codegen-client.test.ts +276 -0
  56. package/apps/studio/figma/codegen-client.ts +509 -0
  57. package/apps/studio/figma/codegen-fonts.test.ts +103 -0
  58. package/apps/studio/figma/codegen-fonts.ts +195 -0
  59. package/apps/studio/figma/codegen-values.test.ts +179 -0
  60. package/apps/studio/figma/codegen-values.ts +270 -0
  61. package/apps/studio/figma/comments-to-strokes.test.ts +194 -0
  62. package/apps/studio/figma/comments-to-strokes.ts +173 -0
  63. package/apps/studio/figma/endpoints.ts +273 -0
  64. package/apps/studio/figma/fig-decode.test.ts +702 -0
  65. package/apps/studio/figma/fig-decode.ts +617 -0
  66. package/apps/studio/figma/fig-kiwi.ts +410 -0
  67. package/apps/studio/figma/fig-zip.ts +270 -0
  68. package/apps/studio/figma/from-codegen.test.ts +408 -0
  69. package/apps/studio/figma/from-codegen.ts +1103 -0
  70. package/apps/studio/figma/sanitize.test.ts +325 -0
  71. package/apps/studio/figma/sanitize.ts +407 -0
  72. package/apps/studio/figma/style-map.ts +352 -0
  73. package/apps/studio/figma/tailwind-map.test.ts +142 -0
  74. package/apps/studio/figma/tailwind-map.ts +545 -0
  75. package/apps/studio/figma/to-artboard.test.ts +808 -0
  76. package/apps/studio/figma/to-artboard.ts +701 -0
  77. package/apps/studio/figma/to-render.test.ts +180 -0
  78. package/apps/studio/figma/to-render.ts +328 -0
  79. package/apps/studio/figma/to-strokes-roundtrip.test.ts +152 -0
  80. package/apps/studio/figma/to-strokes.test.ts +705 -0
  81. package/apps/studio/figma/to-strokes.ts +749 -0
  82. package/apps/studio/figma/to-tokens.test.ts +321 -0
  83. package/apps/studio/figma/to-tokens.ts +305 -0
  84. package/apps/studio/figma/types.ts +544 -0
  85. package/apps/studio/figma/url.test.ts +167 -0
  86. package/apps/studio/figma/url.ts +160 -0
  87. package/apps/studio/http.ts +176 -0
  88. package/apps/studio/sync/asset-push.ts +432 -0
  89. package/apps/studio/sync/connection-state.ts +82 -3
  90. package/apps/studio/sync/hub-link.ts +63 -7
  91. package/apps/studio/sync/hubs-config.ts +31 -3
  92. package/apps/studio/sync/index.ts +286 -27
  93. package/apps/studio/sync/migrate-flat-fallback.ts +121 -0
  94. package/apps/studio/sync/presentation.ts +45 -1
  95. package/apps/studio/sync/status.ts +18 -0
  96. package/apps/studio/sync/supervisor.ts +5 -1
  97. package/apps/studio/sync/workspace-signin.ts +7 -3
  98. package/apps/studio/test/annotations-bindings.test.ts +150 -12
  99. package/apps/studio/test/canvas-create-api.test.ts +4 -1
  100. package/apps/studio/test/canvas-origin-gate.test.ts +17 -0
  101. package/apps/studio/test/capture-determinism-shape.test.ts +135 -0
  102. package/apps/studio/test/clip-addressing.test.ts +6 -1
  103. package/apps/studio/test/clip-ops.test.ts +5 -1
  104. package/apps/studio/test/cloud-endpoints.test.ts +96 -0
  105. package/apps/studio/test/cloud-renew.test.ts +205 -0
  106. package/apps/studio/test/cloud-shell-surfaces.test.ts +11 -2
  107. package/apps/studio/test/exporters/degraded-propagation.test.ts +123 -0
  108. package/apps/studio/test/exporters/unsupported-media.test.ts +123 -0
  109. package/apps/studio/test/fetch-asset-gate.test.ts +189 -0
  110. package/apps/studio/test/figma-explode.test.ts +438 -0
  111. package/apps/studio/test/figma-provenance.test.ts +108 -0
  112. package/apps/studio/test/figma-routes.test.ts +294 -0
  113. package/apps/studio/test/fixtures/perf-canvas.mjs +201 -0
  114. package/apps/studio/test/git-cloud-posture.test.ts +50 -0
  115. package/apps/studio/test/hub-link.test.ts +11 -0
  116. package/apps/studio/test/import-figma.test.ts +667 -0
  117. package/apps/studio/test/sync-asset-push.test.ts +567 -0
  118. package/apps/studio/test/sync-connection-state.test.ts +79 -0
  119. package/apps/studio/test/sync-hubs-config.test.ts +5 -0
  120. package/apps/studio/test/sync-migrate-flat-fallback.test.ts +98 -0
  121. package/apps/studio/test/sync-panel-surface.test.ts +90 -0
  122. package/apps/studio/test/sync-path-pull.test.ts +63 -0
  123. package/apps/studio/test/sync-presentation.test.ts +77 -0
  124. package/apps/studio/test/sync-runtime.test.ts +316 -1
  125. package/apps/studio/test/sync-status.test.ts +28 -0
  126. package/apps/studio/test/timeline-comp-target.test.ts +139 -0
  127. package/apps/studio/test/video-comp.test.ts +104 -2
  128. package/apps/studio/test/video-encode-lib.test.ts +63 -0
  129. package/apps/studio/test/workspace-containment.test.ts +1 -0
  130. package/apps/studio/use-artboard-drag.tsx +37 -3
  131. package/apps/studio/video-comp.tsx +121 -6
  132. package/apps/studio/whats-new.json +98 -0
  133. package/apps/studio/workspace-mode.ts +4 -0
  134. package/cli/commands/design.mjs +15 -0
  135. package/cli/commands/kg.mjs +8 -1
  136. package/cli/commands/kg.test.mjs +24 -0
  137. package/cli/lib/figma-codegen-reachability.test.mjs +104 -0
  138. package/cli/lib/figma-import-controls.test.mjs +70 -0
  139. package/package.json +8 -8
  140. package/plugins/flow/.claude-plugin/config.schema.json +3 -3
@@ -0,0 +1,108 @@
1
+ // Provenance for an imported canvas (DDR-216 D7 / T9).
2
+ //
3
+ // The plan flags this exact prop-threading as having silently no-opped once
4
+ // before: a badge shipped prop-threaded-but-never-stored, so `.meta.json` said
5
+ // one thing and the tree showed nothing. So this asserts the SERVER half
6
+ // end-to-end against a live `/_index-data` — that `kind` actually survives
7
+ // `loadCanvasMeta` → `NOTABLE_KINDS` → the wire — rather than unit-testing a
8
+ // constant that a missing wire would leave green.
9
+
10
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
11
+ import { mkdirSync, writeFileSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import type { Subprocess } from 'bun';
14
+
15
+ import { bootServer, killProc, makeSandbox, nextPort } from './_helpers.ts';
16
+
17
+ let proc: Subprocess;
18
+ let base: string;
19
+ let designRoot: string;
20
+
21
+ const CANVAS = `import { DCArtboard, DesignCanvas } from '@maude/canvas-lib';
22
+ export default function Canvas() {
23
+ return (
24
+ <DesignCanvas>
25
+ <DCArtboard id="node-2-23" label="Imported" width={400} height={300} kind="digital" />
26
+ </DesignCanvas>
27
+ );
28
+ }
29
+ `;
30
+
31
+ beforeAll(async () => {
32
+ const sandbox = makeSandbox();
33
+ designRoot = sandbox.designRoot;
34
+ mkdirSync(join(designRoot, 'ui'), { recursive: true });
35
+
36
+ // An imported canvas: `kind` + a source block carrying IDENTIFIERS ONLY.
37
+ writeFileSync(join(designRoot, 'ui', 'imported.tsx'), CANVAS);
38
+ writeFileSync(
39
+ join(designRoot, 'ui', 'imported.meta.json'),
40
+ JSON.stringify({
41
+ kind: 'imported-figma',
42
+ source: {
43
+ fileKey: 'dGNzRC2kmrmGnOxaBa0RI7',
44
+ nodeId: '2:23',
45
+ importedAt: '2026-08-09T00:00:00.000Z',
46
+ },
47
+ layout: { artboards: [{ id: 'node-2-23', x: 0, y: 0 }] },
48
+ })
49
+ );
50
+
51
+ // A hand-authored canvas alongside it — the badge must NOT appear on this one.
52
+ writeFileSync(join(designRoot, 'ui', 'handmade.tsx'), CANVAS);
53
+ writeFileSync(join(designRoot, 'ui', 'handmade.meta.json'), JSON.stringify({ layout: {} }));
54
+
55
+ const port = nextPort();
56
+ base = `http://localhost:${port}`;
57
+ proc = await bootServer(sandbox.root, port);
58
+ });
59
+
60
+ afterAll(async () => {
61
+ await killProc(proc);
62
+ });
63
+
64
+ async function indexData(): Promise<Record<string, unknown>> {
65
+ const res = await fetch(`${base}/_index-data`);
66
+ expect(res.status).toBe(200);
67
+ return (await res.json()) as Record<string, unknown>;
68
+ }
69
+
70
+ describe('the imported-figma kind reaches the tree', () => {
71
+ test('canvasKinds carries it for the imported canvas', async () => {
72
+ const data = await indexData();
73
+ const kinds = data.canvasKinds as Record<string, string>;
74
+ const entry = Object.entries(kinds).find(([p]) => p.endsWith('imported.tsx'));
75
+ expect(entry).toBeDefined();
76
+ expect(entry?.[1]).toBe('imported-figma');
77
+ });
78
+
79
+ test('a hand-authored canvas gets NO kind — the badge means something', async () => {
80
+ const data = await indexData();
81
+ const kinds = data.canvasKinds as Record<string, string>;
82
+ expect(Object.keys(kinds).some((p) => p.endsWith('handmade.tsx'))).toBe(false);
83
+ });
84
+ });
85
+
86
+ describe('provenance carries identifiers only (D7)', () => {
87
+ test('no Figma NAME or node text is anywhere on the wire', async () => {
88
+ // `.meta.json` and `config.json` are versioned, peer-synced (DDR-054) AND
89
+ // read into multiple agents' context. DDR-172 Decision 8 traced exactly
90
+ // this class and ELIMINATED the free-text sink rather than bounding it;
91
+ // D7 applies the same elimination here.
92
+ const raw = JSON.stringify(await indexData());
93
+ expect(raw).not.toContain('Karta');
94
+ expect(raw).not.toContain('žluť');
95
+ expect(raw).not.toContain('<script');
96
+ });
97
+
98
+ test('the recorded source fields are charset-constrained shapes', async () => {
99
+ const meta = JSON.parse(
100
+ await Bun.file(join(designRoot, 'ui', 'imported.meta.json')).text()
101
+ ) as { source: { fileKey: string; nodeId: string; importedAt: string } };
102
+ expect(meta.source.fileKey).toMatch(/^[A-Za-z0-9]{10,64}$/);
103
+ expect(meta.source.nodeId).toMatch(/^[0-9]+:[0-9]+$/);
104
+ expect(Number.isNaN(Date.parse(meta.source.importedAt))).toBe(false);
105
+ // Exactly three fields — no room for a name, a title or a description.
106
+ expect(Object.keys(meta.source).sort()).toEqual(['fileKey', 'importedAt', 'nodeId']);
107
+ });
108
+ });
@@ -0,0 +1,294 @@
1
+ // `/_api/figma/*` — the MAIN-origin half of DDR-216 D3.
2
+ //
3
+ // canvas-origin-gate.test.ts already asserts these routes are unreachable from
4
+ // the segregated canvas origin. That proves the wrong property on its own: the
5
+ // MAIN origin is reachable from any website the user visits while the dev
6
+ // server is up. Round 1 of the DDR-216 security review found the first draft
7
+ // named no CSRF / DNS-rebind guard at all, with a working PoC — a CORS-simple
8
+ // POST that plants an attacker's PAT (`connect`) or spends the user's on an
9
+ // attacker-chosen key (`probe`), opaque response, real side effect.
10
+ //
11
+ // So this file asserts the complementary half:
12
+ // • cross-site → 403 (Sec-Fetch-Site, the `sameOriginWrite` guard)
13
+ // • foreign Host header → 403 (the DNS-rebinding `isTrustedRequestHost` guard)
14
+ // • the stored key is NEVER echoed on ANY response path
15
+ // • `probe` is gated as a WRITE even though it stores nothing — it spends the
16
+ // credential and reaches the network.
17
+
18
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
19
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
20
+ import { tmpdir } from 'node:os';
21
+ import { join } from 'node:path';
22
+ import type { Subprocess } from 'bun';
23
+
24
+ import { bootServer, killProc, makeSandbox, nextPort } from './_helpers.ts';
25
+
26
+ const TOKEN = 'figd_ROUTECANARY_0123456789abcdef';
27
+
28
+ let proc: Subprocess;
29
+ let port: number;
30
+ let base: string;
31
+ let keysPath: string;
32
+ let keysDir: string;
33
+
34
+ beforeAll(async () => {
35
+ const { root } = makeSandbox();
36
+ keysDir = mkdtempSync(join(tmpdir(), 'maude-figma-routes-keys-'));
37
+ keysPath = join(keysDir, 'keys.json');
38
+ writeFileSync(keysPath, JSON.stringify({ keys: {} }), { mode: 0o600 });
39
+ port = nextPort();
40
+ base = `http://localhost:${port}`;
41
+ proc = await bootServer(root, port, { MAUDE_GEN_KEYS_PATH: keysPath });
42
+ });
43
+
44
+ afterAll(async () => {
45
+ await killProc(proc);
46
+ rmSync(keysDir, { recursive: true, force: true });
47
+ });
48
+
49
+ function storedToken(): string | undefined {
50
+ try {
51
+ return JSON.parse(readFileSync(keysPath, 'utf8')).keys?.figma;
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ // The WRITE guard in this codebase is `sameOriginWrite`, which keys on `Origin`
58
+ // — the header a browser stamps unspoofably on every cross-origin POST/DELETE.
59
+ // (`Sec-Fetch-Site` is what `sameOriginRead` uses, for the GET case below where
60
+ // browsers do NOT reliably send Origin.) These tests therefore send a real
61
+ // cross-origin `Origin`, which is what an attacker page actually produces.
62
+ describe('cross-origin writes are refused (the CSRF guard)', () => {
63
+ const EVIL = 'https://evil.example';
64
+ const PLANTED = 'figd_ATTACKER_PLANTED_0123456789';
65
+
66
+ test('POST /_api/figma/connect cross-origin is 403 and stores nothing', async () => {
67
+ const res = await fetch(`${base}/_api/figma/connect`, {
68
+ method: 'POST',
69
+ headers: { 'Content-Type': 'application/json', Origin: EVIL },
70
+ body: JSON.stringify({ token: PLANTED }),
71
+ });
72
+ expect(res.status).toBe(403);
73
+ expect(storedToken()).toBeUndefined();
74
+ });
75
+
76
+ test('POST /_api/figma/probe cross-origin is 403 — probe spends the credential', async () => {
77
+ const res = await fetch(`${base}/_api/figma/probe`, {
78
+ method: 'POST',
79
+ headers: { Origin: EVIL },
80
+ });
81
+ expect(res.status).toBe(403);
82
+ });
83
+
84
+ test('DELETE /_api/figma/connect cross-origin is 403', async () => {
85
+ const res = await fetch(`${base}/_api/figma/connect`, {
86
+ method: 'DELETE',
87
+ headers: { Origin: EVIL },
88
+ });
89
+ expect(res.status).toBe(403);
90
+ });
91
+
92
+ test('a CORS-simple POST (no preflight, text/plain) is still refused', async () => {
93
+ // The PoC shape from the DDR-216 review: a simple content type means no
94
+ // preflight and the page cannot read the response — but the side effect
95
+ // would land if the server allowed it. Origin is still stamped.
96
+ const res = await fetch(`${base}/_api/figma/connect`, {
97
+ method: 'POST',
98
+ headers: { 'Content-Type': 'text/plain', Origin: EVIL },
99
+ body: JSON.stringify({ token: PLANTED }),
100
+ });
101
+ expect(res.status).toBe(403);
102
+ expect(storedToken()).toBeUndefined();
103
+ });
104
+ });
105
+
106
+ describe('cross-site reads are refused (Sec-Fetch-Site, the GET case)', () => {
107
+ test('GET /_api/figma/status with Sec-Fetch-Site: cross-site is 403', async () => {
108
+ // A no-cors GET from an attacker page passes the loopback guard and may omit
109
+ // Origin entirely, so `sameOriginWrite` cannot see it. Without the read
110
+ // guard this leaks whether the user has Figma connected.
111
+ const res = await fetch(`${base}/_api/figma/status`, {
112
+ headers: { 'Sec-Fetch-Site': 'cross-site' },
113
+ });
114
+ expect(res.status).toBe(403);
115
+ });
116
+ });
117
+
118
+ describe('a foreign Host header is refused (the DNS-rebinding guard)', () => {
119
+ for (const [label, host] of [
120
+ ['an attacker-controlled name', 'evil.example'],
121
+ ['a rebinding service name', 'figma.127.0.0.1.nip.io'],
122
+ ]) {
123
+ test(`GET /_api/figma/status with Host: ${label} is 403`, async () => {
124
+ const res = await fetch(`${base}/_api/figma/status`, { headers: { Host: host } });
125
+ expect(res.status).toBe(403);
126
+ });
127
+ }
128
+ });
129
+
130
+ describe('method gating', () => {
131
+ test('GET /_api/figma/connect is 405', async () => {
132
+ expect((await fetch(`${base}/_api/figma/connect`)).status).toBe(405);
133
+ });
134
+
135
+ test('GET /_api/figma/probe is 405 — probe is a write', async () => {
136
+ expect((await fetch(`${base}/_api/figma/probe`)).status).toBe(405);
137
+ });
138
+
139
+ test('POST /_api/figma/status is 405', async () => {
140
+ expect((await fetch(`${base}/_api/figma/status`, { method: 'POST' })).status).toBe(405);
141
+ });
142
+ });
143
+
144
+ describe('same-origin happy path — and the key never comes back out', () => {
145
+ test('status reports presence only, plus the granular scope to ask for', async () => {
146
+ const res = await fetch(`${base}/_api/figma/status`, {
147
+ headers: { 'Sec-Fetch-Site': 'same-origin' },
148
+ });
149
+ expect(res.status).toBe(200);
150
+ const body = (await res.json()) as Record<string, unknown>;
151
+ expect(body.configured).toBe(false);
152
+ // The blanket `files:read` scope is deprecated — the UI must never name it.
153
+ expect(body.requiredScope).toBe('file_content:read');
154
+ expect(JSON.stringify(body)).not.toContain('figd_');
155
+ });
156
+
157
+ test('connect stores the key and returns presence only — never the value', async () => {
158
+ const res = await fetch(`${base}/_api/figma/connect`, {
159
+ method: 'POST',
160
+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' },
161
+ body: JSON.stringify({ token: TOKEN }),
162
+ });
163
+ expect(res.status).toBe(200);
164
+ const raw = await res.text();
165
+ expect(JSON.parse(raw)).toEqual({ configured: true });
166
+ expect(raw).not.toContain(TOKEN);
167
+ expect(raw).not.toContain('ROUTECANARY');
168
+ // It really did store it — the assertion above is about the RESPONSE, not
169
+ // about the write silently failing.
170
+ expect(storedToken()).toBe(TOKEN);
171
+ });
172
+
173
+ test('status still never echoes the value once one is configured', async () => {
174
+ const res = await fetch(`${base}/_api/figma/status`, {
175
+ headers: { 'Sec-Fetch-Site': 'same-origin' },
176
+ });
177
+ const raw = await res.text();
178
+ expect(JSON.parse(raw).configured).toBe(true);
179
+ expect(raw).not.toContain('ROUTECANARY');
180
+ });
181
+
182
+ test('a malformed token is refused with a message that does not echo it', async () => {
183
+ const junk = 'not a token REFLECTION_CANARY';
184
+ const res = await fetch(`${base}/_api/figma/connect`, {
185
+ method: 'POST',
186
+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' },
187
+ body: JSON.stringify({ token: junk }),
188
+ });
189
+ expect(res.status).toBe(400);
190
+ const raw = await res.text();
191
+ expect(raw).not.toContain('REFLECTION_CANARY');
192
+ // The previously-stored good token is untouched by a failed write.
193
+ expect(storedToken()).toBe(TOKEN);
194
+ });
195
+
196
+ test('probe surfaces a typed failure without leaking the token', async () => {
197
+ // No network stub here — the real api.figma.com will reject this canary
198
+ // token (or the call fails to connect in CI). Either way the response must
199
+ // be a typed reason with a code-owned message and no credential in it.
200
+ const res = await fetch(`${base}/_api/figma/probe`, {
201
+ method: 'POST',
202
+ headers: { 'Sec-Fetch-Site': 'same-origin' },
203
+ });
204
+ const raw = await res.text();
205
+ expect(raw).not.toContain('ROUTECANARY');
206
+ expect(raw).not.toContain('figd_');
207
+ const body = JSON.parse(raw) as { ok: boolean; reason?: string };
208
+ if (!body.ok) {
209
+ expect(['unauthorized', 'forbidden', 'network', 'bad_response', 'rate_limited']).toContain(
210
+ body.reason
211
+ );
212
+ }
213
+ });
214
+
215
+ test('disconnect clears the key', async () => {
216
+ const res = await fetch(`${base}/_api/figma/connect`, {
217
+ method: 'DELETE',
218
+ headers: { 'Sec-Fetch-Site': 'same-origin' },
219
+ });
220
+ expect(res.status).toBe(200);
221
+ expect(await res.json()).toEqual({ configured: false });
222
+ expect(storedToken()).toBeUndefined();
223
+ });
224
+ });
225
+
226
+ describe('/_api/figma/import — same gate, and a validated body', () => {
227
+ test('cross-origin is 403 — it spends the PAT and writes to disk', async () => {
228
+ const res = await fetch(`${base}/_api/figma/import`, {
229
+ method: 'POST',
230
+ headers: { 'Content-Type': 'application/json', Origin: 'https://evil.example' },
231
+ body: JSON.stringify({ mode: 'board', url: 'https://www.figma.com/board/AAAAAAAAAA/x' }),
232
+ });
233
+ expect(res.status).toBe(403);
234
+ });
235
+
236
+ test('a foreign Host is 403', async () => {
237
+ const res = await fetch(`${base}/_api/figma/import`, {
238
+ method: 'POST',
239
+ headers: { Host: 'evil.example' },
240
+ body: '{}',
241
+ });
242
+ expect(res.status).toBe(403);
243
+ });
244
+
245
+ test('GET is 405', async () => {
246
+ expect((await fetch(`${base}/_api/figma/import`)).status).toBe(405);
247
+ });
248
+
249
+ test.each([
250
+ ['no body', {}],
251
+ ['unknown mode', { mode: 'everything', url: 'https://www.figma.com/board/AAAAAAAAAA/x' }],
252
+ ['missing url', { mode: 'board' }],
253
+ ['empty url', { mode: 'board', url: '' }],
254
+ ])('a malformed request is 400 (%s)', async (_label, body) => {
255
+ const res = await fetch(`${base}/_api/figma/import`, {
256
+ method: 'POST',
257
+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' },
258
+ body: JSON.stringify(body),
259
+ });
260
+ expect(res.status).toBe(400);
261
+ });
262
+
263
+ test('a caller cannot choose an output path', async () => {
264
+ // The body shape is fixed: {mode, url, dryRun}. A slug/path/into field is
265
+ // simply not read — the same "the producer never picks its own target"
266
+ // discipline DDR-174 applies to its authoring agent.
267
+ const res = await fetch(`${base}/_api/figma/import`, {
268
+ method: 'POST',
269
+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' },
270
+ body: JSON.stringify({
271
+ mode: 'board',
272
+ url: 'https://www.figma.com/board/AAAAAAAAAA/x',
273
+ slug: '../../etc/passwd',
274
+ into: '/etc/passwd',
275
+ }),
276
+ });
277
+ // It gets past validation (the url is well-formed) and fails on the
278
+ // credential instead — the point is that the path fields were ignored.
279
+ const raw = await res.text();
280
+ expect(raw).not.toContain('etc/passwd');
281
+ expect([400, 502]).toContain(res.status);
282
+ });
283
+
284
+ test('a failure never echoes an upstream string', async () => {
285
+ const res = await fetch(`${base}/_api/figma/import`, {
286
+ method: 'POST',
287
+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' },
288
+ body: JSON.stringify({ mode: 'board', url: 'https://www.figma.com/board/AAAAAAAAAA/x' }),
289
+ });
290
+ const raw = await res.text();
291
+ expect(raw).not.toContain('figd_');
292
+ expect(raw).not.toContain('ROUTECANARY');
293
+ });
294
+ });
@@ -0,0 +1,201 @@
1
+ // perf-canvas.mjs — deterministic large-canvas fixture generator.
2
+ //
3
+ // Produces the synthetic worst-case the render-performance work is measured
4
+ // against: N artboards on one world plane plus M annotation stickies, with NO
5
+ // filters, blends or feTurbulence. That absence is the point — the earlier
6
+ // moodboard RCA (.ai/archive/logs/rca/issue-canvas-pan-zoom-jank-large-
7
+ // moodboard.md) covered the expensive-paint regime; the failures this fixture
8
+ // reproduces (a 128-artboard onboarding flow, a sticky-dense FigJam board) are
9
+ // the opposite shape: cheap paint, huge node count. Mixing filters back in
10
+ // would re-measure the case that is already fixed.
11
+ //
12
+ // Written as .mjs rather than the .ts the plan named, because the probe
13
+ // (`_perf-probe.mjs`) runs under plain node and imports this module directly;
14
+ // bun tests import .mjs identically, so nothing is lost.
15
+ //
16
+ // Deterministic by construction — no Date.now(), no Math.random(). Two runs
17
+ // produce byte-identical files, so a re-measured baseline compares like with
18
+ // like.
19
+
20
+ import { mkdirSync, writeFileSync } from 'node:fs';
21
+ import { dirname, join } from 'node:path';
22
+
23
+ /** Grid geometry — mirrors DesignCanvas's own default grid vocabulary. */
24
+ const BOARD_W = 1280;
25
+ const BOARD_H = 800;
26
+ const GUTTER = 80;
27
+ const COLS = 8;
28
+
29
+ /** Sticky geometry, matching the imported-FigJam shape (240px square, r=8). */
30
+ const STICKY = 240;
31
+ const STICKY_GAP = 40;
32
+ const STICKY_COLS = 12;
33
+
34
+ // Fixed word pool — index-addressed, never shuffled, so labels stay stable
35
+ // across regenerations.
36
+ const WORDS = [
37
+ 'Onboarding',
38
+ 'Signup',
39
+ 'Paywall',
40
+ 'Empty state',
41
+ 'Error',
42
+ 'Success',
43
+ 'Profile',
44
+ 'Settings',
45
+ 'Search',
46
+ 'Detail',
47
+ 'Checkout',
48
+ 'Review',
49
+ ];
50
+
51
+ const STICKY_TEXT = [
52
+ 'Ship the import path',
53
+ 'Cut the cold start',
54
+ 'Fewer modal steps',
55
+ 'Copy is too long',
56
+ 'Needs an empty state',
57
+ 'Great onboarding',
58
+ 'Slow on mobile',
59
+ 'Loved the polish',
60
+ ];
61
+
62
+ /** Deterministic pseudo-shuffle: a fixed odd stride over the pool. */
63
+ function pick(pool, i) {
64
+ return pool[(i * 7) % pool.length];
65
+ }
66
+
67
+ /**
68
+ * Body markup for one artboard. Deliberately ~35 DOM nodes — a realistic mock,
69
+ * not an empty box. An empty artboard would understate reconciliation cost and
70
+ * flatter every measurement taken against this fixture.
71
+ */
72
+ function artboardBody(i) {
73
+ const rows = Array.from(
74
+ { length: 6 },
75
+ (_, r) => `
76
+ <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
77
+ <div style={{ width: 32, height: 32, borderRadius: 6, background: 'var(--bg-2, #e8e3d8)' }} />
78
+ <div style={{ flex: 1 }}>
79
+ <div style={{ height: 10, width: '${40 + ((i + r) % 5) * 10}%', borderRadius: 3, background: 'var(--bg-3, #ddd6c8)' }} />
80
+ <div style={{ height: 8, width: '${25 + ((i + r) % 4) * 8}%', marginTop: 6, borderRadius: 3, background: 'var(--bg-2, #e8e3d8)' }} />
81
+ </div>
82
+ <div style={{ width: 56, height: 24, borderRadius: 4, background: 'var(--accent, #6b5bd6)', opacity: 0.18 }} />
83
+ </div>`
84
+ ).join('');
85
+
86
+ return `
87
+ <div style={{ padding: 32, display: 'flex', flexDirection: 'column', gap: 16 }}>
88
+ <h2 style={{ margin: 0, font: '600 24px/1.2 var(--font-sans, system-ui)' }}>${pick(WORDS, i)} ${i}</h2>
89
+ <p style={{ margin: 0, font: '400 14px/1.5 var(--font-sans, system-ui)', opacity: 0.7 }}>
90
+ Synthetic perf fixture board ${i} — no filters, no blends, cheap paint.
91
+ </p>${rows}
92
+ </div>`;
93
+ }
94
+
95
+ /** Build the canvas .tsx source for `boards` artboards. */
96
+ export function renderCanvasSource(boards) {
97
+ const items = Array.from({ length: boards }, (_, i) => {
98
+ const col = i % COLS;
99
+ const row = Math.floor(i / COLS);
100
+ const x = col * (BOARD_W + GUTTER);
101
+ const y = row * (BOARD_H + GUTTER);
102
+ return ` <DCArtboard
103
+ id="b${i}"
104
+ label="${pick(WORDS, i)} ${i}"
105
+ width={${BOARD_W}}
106
+ height={${BOARD_H}}
107
+ x={${x}}
108
+ y={${y}}
109
+ fixed
110
+ >${artboardBody(i)}
111
+ </DCArtboard>`;
112
+ }).join('\n');
113
+
114
+ return `// GENERATED by apps/studio/test/fixtures/perf-canvas.mjs — do not hand-edit.
115
+ // Synthetic render-performance fixture: ${boards} artboards, no filters/blends.
116
+ import { DCArtboard, DesignCanvas } from '@maude/canvas-lib';
117
+
118
+ export default function Canvas() {
119
+ return (
120
+ <DesignCanvas>
121
+ ${items}
122
+ </DesignCanvas>
123
+ );
124
+ }
125
+ `;
126
+ }
127
+
128
+ /** Build the `.meta.json` sidecar carrying the artboard grid positions. */
129
+ export function renderMeta(boards) {
130
+ const artboards = Array.from({ length: boards }, (_, i) => ({
131
+ id: `b${i}`,
132
+ x: (i % COLS) * (BOARD_W + GUTTER),
133
+ y: Math.floor(i / COLS) * (BOARD_H + GUTTER),
134
+ }));
135
+ return {
136
+ title: `Perf fixture (${boards} boards)`,
137
+ subtitle: 'Generated render-performance fixture — safe to delete.',
138
+ tags: ['perf-fixture'],
139
+ status: 'draft',
140
+ layout: { artboards },
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Build the annotations SVG carrying `strokes` stickies. Shape copied from a
146
+ * real imported-FigJam board so the layer exercises the same code path
147
+ * (`data-mdcc-annotations`, `data-tool="sticky"`, rect + body text per group).
148
+ */
149
+ export function renderAnnotations(strokes) {
150
+ if (strokes <= 0) return null;
151
+ const nodes = Array.from({ length: strokes }, (_, i) => {
152
+ const col = i % STICKY_COLS;
153
+ const row = Math.floor(i / STICKY_COLS);
154
+ const x = col * (STICKY + STICKY_GAP);
155
+ // Park the sticky field below the artboard grid so the two layers are
156
+ // measurable together without overlapping hit-test surfaces.
157
+ const y = 100000 + row * (STICKY + STICKY_GAP);
158
+ return (
159
+ `<g data-id="perf_${i}" data-tool="sticky" data-r="8" data-fs="14" fill="#cfc4ec">` +
160
+ `<rect x="${x}" y="${y}" width="${STICKY}" height="${STICKY}" rx="8" ry="8"/>` +
161
+ `<text data-sticky-body="1" x="${x + 12}" y="${y + 12}" font-size="14" fill="#1a1a1a" dominant-baseline="hanging">` +
162
+ `${pick(STICKY_TEXT, i)} ${i}</text></g>`
163
+ );
164
+ }).join('');
165
+ return `<svg xmlns="http://www.w3.org/2000/svg" data-mdcc-annotations="1">${nodes}</svg>`;
166
+ }
167
+
168
+ /**
169
+ * Write the fixture into a design root.
170
+ *
171
+ * @param {object} opts
172
+ * @param {string} opts.designRoot Absolute path to a `.design/` directory.
173
+ * @param {number} [opts.boards] Artboard count (default 128 — the SPKIE repro).
174
+ * @param {number} [opts.strokes] Sticky count (default 150 — the Team Retro repro).
175
+ * @param {string} [opts.slug] Canvas basename (default `perf-fixture`).
176
+ * @returns {{canvasPath: string, metaPath: string, annotationsPath: string|null, canvasRel: string}}
177
+ */
178
+ export function writePerfCanvas({
179
+ designRoot,
180
+ boards = 128,
181
+ strokes = 150,
182
+ slug = 'perf-fixture',
183
+ }) {
184
+ const canvasPath = join(designRoot, 'ui', `${slug}.tsx`);
185
+ const metaPath = join(designRoot, 'ui', `${slug}.meta.json`);
186
+ mkdirSync(dirname(canvasPath), { recursive: true });
187
+
188
+ writeFileSync(canvasPath, renderCanvasSource(boards), 'utf8');
189
+ writeFileSync(metaPath, `${JSON.stringify(renderMeta(boards), null, 2)}\n`, 'utf8');
190
+
191
+ // Annotations live at the design root under the flattened `<dir>-<slug>`
192
+ // naming the annotations API uses, NOT beside the canvas.
193
+ let annotationsPath = null;
194
+ const svg = renderAnnotations(strokes);
195
+ if (svg) {
196
+ annotationsPath = join(designRoot, `ui-${slug.replace(/-/g, '_')}.annotations.svg`);
197
+ writeFileSync(annotationsPath, svg, 'utf8');
198
+ }
199
+
200
+ return { canvasPath, metaPath, annotationsPath, canvasRel: `ui/${slug}.tsx` };
201
+ }
@@ -0,0 +1,50 @@
1
+ // DDR-218 (fix 8, sync RCA 2026-08-10) — the cloud-managed GitPanel posture.
2
+ //
3
+ // Source-level assertions, the cloud-shell-surfaces pattern: what these pin is
4
+ // exactly what would regress — someone gating the withdrawal on `historyOnly`
5
+ // alone (dropping the desktop half), breaking the live connect/disconnect
6
+ // reaction, or wiring `cloudManaged` from something other than the
7
+ // CORROBORATED link (`credentialed` — config.json alone is attacker-authorable,
8
+ // B2).
9
+
10
+ import { describe, expect, test } from 'bun:test';
11
+ import { readFileSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+
14
+ const STUDIO = join(import.meta.dir, '..');
15
+ const APP = readFileSync(join(STUDIO, 'client', 'app.jsx'), 'utf8');
16
+ const GIT_PANEL = readFileSync(join(STUDIO, 'client', 'panels', 'GitPanel.jsx'), 'utf8');
17
+ const CLOUD_BAR = readFileSync(join(STUDIO, 'client', 'panels', 'CloudBar.jsx'), 'utf8');
18
+
19
+ describe('a cloud-linked repo shows ONE save mechanism (DDR-218)', () => {
20
+ test('cloudManaged withdraws exactly like the cell-side historyOnly', () => {
21
+ expect(GIT_PANEL).toContain('const withdrawn = historyOnly || cloudManaged;');
22
+ // Every render gate the working-tree half hides behind must read the
23
+ // merged flag — a `!historyOnly` guard reintroduces the desktop leak.
24
+ expect(GIT_PANEL).toMatch(/\{!withdrawn && \(\s*<div className="gp-tabs"/);
25
+ expect(GIT_PANEL).toContain("{tab === 'changes' && !withdrawn ? (");
26
+ });
27
+
28
+ test('the posture reacts LIVE to connect/disconnect, not only at mount', () => {
29
+ // The initial useState alone would leave a freshly-linked panel on Changes.
30
+ expect(GIT_PANEL).toMatch(/useEffect\(\(\) => \{\s*if \(withdrawn\) setTab\('history'\);/);
31
+ });
32
+
33
+ test('the note names the active mechanism, and only in the desktop posture', () => {
34
+ expect(GIT_PANEL).toContain('data-testid="git-cloud-managed"');
35
+ expect(GIT_PANEL).toMatch(/\{cloudManaged && \(\s*<div className="gp-cloud-note"/);
36
+ expect(GIT_PANEL).toContain('Cloud is saving');
37
+ });
38
+
39
+ test('the app gate is the CORROBORATED link, and the cell posture is untouched', () => {
40
+ expect(APP).toContain('cloudManaged={!cfg.cloud && !!cloudLinkedHub?.credentialed}');
41
+ expect(APP).toContain('historyOnly={!!cfg.cloud}');
42
+ });
43
+
44
+ test('CloudBar lifts every link change the posture depends on', () => {
45
+ // status resolve + attach + detach — the three places the link changes.
46
+ const lifts = CLOUD_BAR.match(/onLinkedHub\?\.\(/g) ?? [];
47
+ expect(lifts.length).toBeGreaterThanOrEqual(3);
48
+ expect(APP).toContain('onLinkedHub={setCloudLinkedHub}');
49
+ });
50
+ });
@@ -67,3 +67,14 @@ test('a second credential for the same hub replaces the token (per-machine key)'
67
67
  // Trust is not duplicated.
68
68
  expect(cfg.trusted.filter((u: string) => u === 'https://hub.example.dev')).toHaveLength(1);
69
69
  });
70
+
71
+ test('role + expiresAt round-trip through the store (the renewal deadline survives)', () => {
72
+ saveHubCredential('https://hub.example.dev', 'mau_secret', 'member', 1786400000000);
73
+ const cfg = JSON.parse(readFileSync(process.env.HUBS_CONFIG_PATH as string, 'utf8'));
74
+ expect(cfg.hubs['https://hub.example.dev'].role).toBe('member');
75
+ expect(cfg.hubs['https://hub.example.dev'].expiresAt).toBe(1786400000000);
76
+ // Absent stays absent — a self-hosted hub's credential carries no deadline.
77
+ saveHubCredential('https://hub.example.dev', 'mau_secret2');
78
+ const cfg2 = JSON.parse(readFileSync(process.env.HUBS_CONFIG_PATH as string, 'utf8'));
79
+ expect(cfg2.hubs['https://hub.example.dev'].expiresAt).toBeUndefined();
80
+ });