@1agh/maude 0.58.2 → 0.58.3

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 (105) hide show
  1. package/apps/studio/annotations-bindings.ts +83 -4
  2. package/apps/studio/api.ts +6 -1
  3. package/apps/studio/bin/_fetch-asset.mjs +169 -5
  4. package/apps/studio/bin/_import-asset.mjs +72 -0
  5. package/apps/studio/bin/_import-figma.mjs +1121 -0
  6. package/apps/studio/bin/_video-playwright.mjs +86 -3
  7. package/apps/studio/bin/import-figma.sh +38 -0
  8. package/apps/studio/bin/read-annotations.mjs +11 -1
  9. package/apps/studio/bun.lock +16 -22
  10. package/apps/studio/canvas-edit.ts +29 -5
  11. package/apps/studio/client/app.jsx +44 -1
  12. package/apps/studio/client/export-center.jsx +42 -4
  13. package/apps/studio/client/panels/CloudBar.jsx +92 -1
  14. package/apps/studio/client/panels/FigmaImportPanel.jsx +264 -0
  15. package/apps/studio/client/panels/GitPanel.jsx +26 -6
  16. package/apps/studio/client/panels/SettingsPanel.jsx +181 -0
  17. package/apps/studio/client/panels/SetupChecklist.jsx +26 -2
  18. package/apps/studio/client/panels/TimelinePanel.jsx +2 -2
  19. package/apps/studio/client/panels/timeline-parse.js +3 -3
  20. package/apps/studio/client/styles/3-shell-maude.css +7 -0
  21. package/apps/studio/client/styles/4-components.css +134 -0
  22. package/apps/studio/clip-ops.ts +93 -17
  23. package/apps/studio/cloud/endpoints.ts +78 -10
  24. package/apps/studio/cloud/renew.ts +183 -0
  25. package/apps/studio/context.ts +2 -1
  26. package/apps/studio/dist/client.bundle.js +1261 -1261
  27. package/apps/studio/dist/runtime/@remotion_media.js +56 -136
  28. package/apps/studio/dist/runtime/@remotion_player.js +18 -18
  29. package/apps/studio/dist/runtime/@remotion_transitions.js +9 -9
  30. package/apps/studio/dist/runtime/@remotion_transitions_clock-wipe.js +1 -1
  31. package/apps/studio/dist/runtime/remotion.js +12 -12
  32. package/apps/studio/dist/styles.css +1 -1
  33. package/apps/studio/exporters/_browser-bundles.ts +20 -6
  34. package/apps/studio/exporters/_runtime.ts +19 -0
  35. package/apps/studio/exporters/degraded.ts +92 -0
  36. package/apps/studio/exporters/index.ts +5 -0
  37. package/apps/studio/exporters/jobs.ts +19 -0
  38. package/apps/studio/exporters/unsupported-media.ts +170 -0
  39. package/apps/studio/exporters/video-encode-lib.ts +27 -1
  40. package/apps/studio/exporters/video-render-lib.ts +6 -0
  41. package/apps/studio/exporters/video.ts +62 -1
  42. package/apps/studio/figma/assets.test.ts +372 -0
  43. package/apps/studio/figma/assets.ts +398 -0
  44. package/apps/studio/figma/client.test.ts +395 -0
  45. package/apps/studio/figma/client.ts +513 -0
  46. package/apps/studio/figma/comments-to-strokes.test.ts +194 -0
  47. package/apps/studio/figma/comments-to-strokes.ts +173 -0
  48. package/apps/studio/figma/endpoints.ts +200 -0
  49. package/apps/studio/figma/sanitize.test.ts +256 -0
  50. package/apps/studio/figma/sanitize.ts +315 -0
  51. package/apps/studio/figma/style-map.ts +352 -0
  52. package/apps/studio/figma/to-artboard.test.ts +808 -0
  53. package/apps/studio/figma/to-artboard.ts +701 -0
  54. package/apps/studio/figma/to-render.test.ts +180 -0
  55. package/apps/studio/figma/to-render.ts +306 -0
  56. package/apps/studio/figma/to-strokes-roundtrip.test.ts +152 -0
  57. package/apps/studio/figma/to-strokes.test.ts +705 -0
  58. package/apps/studio/figma/to-strokes.ts +749 -0
  59. package/apps/studio/figma/to-tokens.test.ts +321 -0
  60. package/apps/studio/figma/to-tokens.ts +305 -0
  61. package/apps/studio/figma/types.ts +539 -0
  62. package/apps/studio/figma/url.test.ts +167 -0
  63. package/apps/studio/figma/url.ts +160 -0
  64. package/apps/studio/http.ts +129 -0
  65. package/apps/studio/sync/asset-push.ts +124 -0
  66. package/apps/studio/sync/connection-state.ts +11 -0
  67. package/apps/studio/sync/hub-link.ts +63 -7
  68. package/apps/studio/sync/hubs-config.ts +31 -3
  69. package/apps/studio/sync/index.ts +276 -26
  70. package/apps/studio/sync/migrate-flat-fallback.ts +121 -0
  71. package/apps/studio/sync/presentation.ts +45 -1
  72. package/apps/studio/sync/supervisor.ts +5 -1
  73. package/apps/studio/sync/workspace-signin.ts +7 -3
  74. package/apps/studio/test/annotations-bindings.test.ts +150 -12
  75. package/apps/studio/test/canvas-create-api.test.ts +4 -1
  76. package/apps/studio/test/canvas-origin-gate.test.ts +13 -0
  77. package/apps/studio/test/capture-determinism-shape.test.ts +135 -0
  78. package/apps/studio/test/clip-addressing.test.ts +6 -1
  79. package/apps/studio/test/clip-ops.test.ts +5 -1
  80. package/apps/studio/test/cloud-endpoints.test.ts +96 -0
  81. package/apps/studio/test/cloud-renew.test.ts +205 -0
  82. package/apps/studio/test/cloud-shell-surfaces.test.ts +11 -2
  83. package/apps/studio/test/exporters/degraded-propagation.test.ts +123 -0
  84. package/apps/studio/test/exporters/unsupported-media.test.ts +123 -0
  85. package/apps/studio/test/fetch-asset-gate.test.ts +189 -0
  86. package/apps/studio/test/figma-provenance.test.ts +108 -0
  87. package/apps/studio/test/figma-routes.test.ts +294 -0
  88. package/apps/studio/test/git-cloud-posture.test.ts +50 -0
  89. package/apps/studio/test/hub-link.test.ts +11 -0
  90. package/apps/studio/test/import-figma.test.ts +479 -0
  91. package/apps/studio/test/sync-asset-push.test.ts +124 -0
  92. package/apps/studio/test/sync-connection-state.test.ts +13 -0
  93. package/apps/studio/test/sync-hubs-config.test.ts +5 -0
  94. package/apps/studio/test/sync-migrate-flat-fallback.test.ts +98 -0
  95. package/apps/studio/test/sync-path-pull.test.ts +63 -0
  96. package/apps/studio/test/sync-presentation.test.ts +77 -0
  97. package/apps/studio/test/sync-runtime.test.ts +316 -1
  98. package/apps/studio/test/video-comp.test.ts +23 -1
  99. package/apps/studio/test/workspace-containment.test.ts +1 -0
  100. package/apps/studio/video-comp.tsx +70 -6
  101. package/apps/studio/whats-new.json +27 -0
  102. package/apps/studio/workspace-mode.ts +4 -0
  103. package/cli/commands/design.mjs +8 -0
  104. package/package.json +8 -8
  105. package/plugins/flow/.claude-plugin/config.schema.json +3 -3
@@ -0,0 +1,189 @@
1
+ // `_fetch-asset.mjs` — the gate's pure decision functions, plus the three
2
+ // DDR-216 additions. Standing tests, not optional hardening: DDR-216's
3
+ // Consequences names each of these by hand because this is a SHARED,
4
+ // security-reviewed helper whose OTHER caller (the DDR-147 moodboard lane) has
5
+ // no host allowlist at all.
6
+
7
+ import { describe, expect, test } from 'bun:test';
8
+
9
+ import { mkdtempSync, rmSync } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { join } from 'node:path';
12
+
13
+ import {
14
+ FetchAssetError,
15
+ fetchAsset,
16
+ parseHttpsTarget,
17
+ sniffImageExt,
18
+ sniffStagedKind,
19
+ } from '../bin/_fetch-asset.mjs';
20
+
21
+ const FIGMA_HOSTS = ['figma.com', 'figma-alpha-api.s3.us-west-2.amazonaws.com'];
22
+
23
+ const png = () => Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]);
24
+ const svg = (s = '<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>') => Buffer.from(s, 'utf8');
25
+
26
+ describe('the host allowlist is exact-or-dotted-suffix, never endsWith', () => {
27
+ test.each([
28
+ ['the apex', 'https://figma.com/x'],
29
+ ['a real subdomain', 'https://www.figma.com/x'],
30
+ ['a deep subdomain', 'https://a.b.figma.com/x'],
31
+ ['the render bucket, exactly', 'https://figma-alpha-api.s3.us-west-2.amazonaws.com/x'],
32
+ ])('admits %s', (_label, url) => {
33
+ expect(() => parseHttpsTarget(url, { allowHosts: FIGMA_HOSTS })).not.toThrow();
34
+ });
35
+
36
+ test.each([
37
+ // The classic suffix bug: a bare endsWith('figma.com') admits this.
38
+ ['a suffix look-alike', 'https://evil-figma.com/x'],
39
+ ['figma.com as a prefix of another domain', 'https://figma.com.evil.tld/x'],
40
+ ['an unrelated host', 'https://evil.tld/x'],
41
+ // A bare endsWith('.amazonaws.com') would admit EVERY S3 bucket on earth.
42
+ ['a different S3 bucket', 'https://attacker-bucket.s3.us-west-2.amazonaws.com/x'],
43
+ ['the bare bucket parent', 'https://s3.us-west-2.amazonaws.com/x'],
44
+ ])('refuses %s', (_label, url) => {
45
+ expect(() => parseHttpsTarget(url, { allowHosts: FIGMA_HOSTS })).toThrow(FetchAssetError);
46
+ });
47
+
48
+ test("an absent allowlist keeps today's unrestricted behaviour", () => {
49
+ // The moodboard/research lane passes no allowlist and must be untouched.
50
+ expect(() => parseHttpsTarget('https://upload.wikimedia.org/x.png')).not.toThrow();
51
+ expect(parseHttpsTarget('https://anything.example/x').host).toBe('anything.example');
52
+ });
53
+
54
+ test('a refusal names the host as a charset-validated token, never raw (D10)', () => {
55
+ try {
56
+ parseHttpsTarget('https://evil.tld/x', { allowHosts: FIGMA_HOSTS });
57
+ throw new Error('expected a rejection');
58
+ } catch (err) {
59
+ expect((err as Error).message).toMatch(/^host not in this lane's allowlist: [a-z0-9.-]+$/);
60
+ }
61
+ });
62
+ });
63
+
64
+ describe('port pinning is opt-in, and is new logic', () => {
65
+ test('the default still accepts any valid port (unchanged behaviour)', () => {
66
+ expect(parseHttpsTarget('https://example.test:8443/x').port).toBe(8443);
67
+ });
68
+
69
+ test('the pinned lane refuses a non-443 port', () => {
70
+ expect(() => parseHttpsTarget('https://figma.com:8443/x', { pinPort443: true })).toThrow(
71
+ FetchAssetError
72
+ );
73
+ });
74
+
75
+ test('the pinned lane accepts 443, explicit or implicit', () => {
76
+ expect(parseHttpsTarget('https://figma.com/x', { pinPort443: true }).port).toBe(443);
77
+ expect(parseHttpsTarget('https://figma.com:443/x', { pinPort443: true }).port).toBe(443);
78
+ });
79
+ });
80
+
81
+ describe('the allowlist NARROWS the gate — it never replaces the rest of it', () => {
82
+ test.each([
83
+ ['non-https', 'http://figma.com/x'],
84
+ ['embedded credentials', 'https://user:pw@figma.com/x'],
85
+ ['a file URL', 'file:///etc/passwd'],
86
+ ])('%s is still refused even on an allowlisted host', (_label, url) => {
87
+ expect(() => parseHttpsTarget(url, { allowHosts: FIGMA_HOSTS })).toThrow(FetchAssetError);
88
+ });
89
+ });
90
+
91
+ describe('sniffImageExt is NOT widened — the moodboard lane depends on it', () => {
92
+ test.each([
93
+ ['an SVG', svg()],
94
+ ['an XML-prologue SVG', svg('<?xml version="1.0"?><svg></svg>')],
95
+ ['an SVG comment prologue', svg('<!-- c --><svg></svg>')],
96
+ ['HTML', Buffer.from('<!doctype html><html></html>', 'utf8')],
97
+ ['a script', Buffer.from('alert(1)', 'utf8')],
98
+ ])('still returns null for %s', (_label, bytes) => {
99
+ // DDR-216 D11 step 6: this is THE test that makes the tempting two-line
100
+ // "just add svg to the sniff" fix fail CI. If it ever goes green for SVG,
101
+ // arbitrary remote vectors can land in the versioned, peer-synced assets/
102
+ // tree of a lane this feature never touches.
103
+ expect(sniffImageExt(bytes)).toBeNull();
104
+ });
105
+
106
+ test('still accepts a real raster', () => {
107
+ expect(sniffImageExt(png())).toBe('png');
108
+ });
109
+ });
110
+
111
+ describe('sniffStagedKind — the --raw-out accept set', () => {
112
+ test('accepts everything sniffImageExt accepts', () => {
113
+ expect(sniffStagedKind(png())).toBe('png');
114
+ });
115
+
116
+ test('additionally accepts SVG, which is the whole point of the mode', () => {
117
+ expect(sniffStagedKind(svg())).toBe('svg');
118
+ expect(sniffStagedKind(svg('<?xml version="1.0"?><svg></svg>'))).toBe('svg');
119
+ });
120
+
121
+ test('still REFUSES the things a bypass would let through', () => {
122
+ // `--raw-out` must never mean "skip the type gate" — that would turn the one
123
+ // reviewable downloader into an unsniffed one for the next caller.
124
+ expect(sniffStagedKind(Buffer.from('<!doctype html><html></html>', 'utf8'))).toBeNull();
125
+ expect(sniffStagedKind(Buffer.from('alert(1)', 'utf8'))).toBeNull();
126
+ expect(sniffStagedKind(Buffer.from('PKzipbytes', 'utf8'))).toBeNull();
127
+ expect(sniffStagedKind(Buffer.from('', 'utf8'))).toBeNull();
128
+ });
129
+
130
+ test('only the HEAD is probed — a late `<svg` does not rescue a blob', () => {
131
+ const late = Buffer.concat([Buffer.alloc(512, 0x41), svg()]);
132
+ expect(sniffStagedKind(late)).toBeNull();
133
+ });
134
+ });
135
+
136
+ describe('--raw-out containment survives an OS-symlinked temp root', () => {
137
+ test('a legitimate staging path under os.tmpdir() is ACCEPTED', async () => {
138
+ // The bug this pins: `realpathSync` on the root but not the target compares
139
+ // `/private/var/…` against `/var/…` on macOS (both `/var` and `/tmp` are
140
+ // OS-level symlinks) and rejects every legitimate path. It shipped, and the
141
+ // first real import skipped all 29 of its assets with a generic
142
+ // "download or sanitize failed". Same trap DDR-172 Decision 1 documents.
143
+ const dir = mkdtempSync(join(tmpdir(), 'raw-out-probe-'));
144
+ try {
145
+ const out = join(dir, 'staged.png');
146
+ // Reaches the network gate rather than the containment check: any throw
147
+ // must NOT be the containment one.
148
+ let err: unknown;
149
+ try {
150
+ await fetchAsset({
151
+ url: 'https://figma.com/definitely-not-real.png',
152
+ root: dir,
153
+ rawOut: out,
154
+ rawRoot: dir,
155
+ allowHosts: FIGMA_HOSTS,
156
+ maxTime: 1,
157
+ });
158
+ } catch (e) {
159
+ err = e;
160
+ }
161
+ expect((err as Error | undefined)?.message ?? '').not.toContain('--raw-out must resolve');
162
+ } finally {
163
+ rmSync(dir, { recursive: true, force: true });
164
+ }
165
+ });
166
+
167
+ test('a path OUTSIDE the declared root is still refused', async () => {
168
+ const dir = mkdtempSync(join(tmpdir(), 'raw-out-probe-'));
169
+ try {
170
+ await expect(
171
+ fetchAsset({
172
+ url: 'https://figma.com/x.png',
173
+ root: dir,
174
+ rawOut: join(dir, '..', 'escaped.png'),
175
+ rawRoot: dir,
176
+ allowHosts: FIGMA_HOSTS,
177
+ })
178
+ ).rejects.toThrow(/--raw-out must resolve inside/);
179
+ } finally {
180
+ rmSync(dir, { recursive: true, force: true });
181
+ }
182
+ });
183
+
184
+ test('--raw-out without --raw-root is refused outright', async () => {
185
+ await expect(
186
+ fetchAsset({ url: 'https://figma.com/x.png', root: '/tmp', rawOut: '/tmp/x.png' })
187
+ ).rejects.toThrow(/requires --raw-root/);
188
+ });
189
+ });
@@ -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,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
+ });