@behavioral-agentic-design-system/core 0.40.0 → 0.45.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 (148) hide show
  1. package/README.md +2 -0
  2. package/package.json +41 -9
  3. package/scripts/a11y-lint.cjs +66 -3
  4. package/scripts/check-spec.mjs +73 -0
  5. package/scripts/deal-directions.mjs +186 -0
  6. package/scripts/health-report.mjs +23 -3
  7. package/scripts/lib/counted-lint.mjs +100 -0
  8. package/scripts/lib/marketing-library.mjs +129 -0
  9. package/scripts/lib/on-system.mjs +249 -0
  10. package/scripts/lib/random.mjs +22 -0
  11. package/scripts/lib/spec-parse.d.mts +25 -0
  12. package/scripts/lib/spec-parse.mjs +188 -0
  13. package/scripts/lib/tells.mjs +128 -0
  14. package/scripts/lint-css-vars.mjs +175 -0
  15. package/scripts/lint-html-nesting.mjs +116 -0
  16. package/scripts/lint-live-ctas.mjs +138 -0
  17. package/scripts/lint-slop.mjs +25 -1
  18. package/scripts/on-system-score.mjs +95 -0
  19. package/scripts/slop-rules.mjs +1 -1
  20. package/scripts/source-images.mjs +180 -0
  21. package/scripts/ux-tells.mjs +78 -0
  22. package/scripts/wcag-audit.cjs +72 -5
  23. package/src/api/brand-colors.ts +3 -0
  24. package/src/api/brand-fonts.ts +3 -0
  25. package/src/api/brand-mark.ts +6 -1
  26. package/src/api/dev-write-guard.ts +53 -0
  27. package/src/api/layers/file.ts +7 -4
  28. package/src/api/onboarding-extract.ts +85 -30
  29. package/src/api/onboarding.ts +3 -0
  30. package/src/api/save-tokens.ts +3 -0
  31. package/src/app/layout.tsx +6 -0
  32. package/src/app/opengraph-image.tsx +5 -0
  33. package/src/app/preview/canvas/page.tsx +12 -0
  34. package/src/app/preview/components/page.tsx +2003 -2
  35. package/src/app/preview/studio/blank-screen.tsx +143 -0
  36. package/src/app/preview/studio/page.tsx +7 -0
  37. package/src/app/shell.tsx +168 -49
  38. package/src/components/Foundations/Motion.stories.tsx +1 -0
  39. package/src/components/canvas/canvas.tsx +458 -0
  40. package/src/components/canvas/layout.ts +72 -0
  41. package/src/components/canvas/parse-canvas.ts +32 -0
  42. package/src/components/canvas/sample.ts +90 -0
  43. package/src/components/canvas/spec-frame.tsx +43 -0
  44. package/src/components/canvas/types.ts +33 -0
  45. package/src/components/customize/design-controls.tsx +16 -1
  46. package/src/components/docs-tab.tsx +7 -7
  47. package/src/components/home-recent.tsx +73 -0
  48. package/src/components/home-tab.tsx +13 -13
  49. package/src/components/layers-tab.tsx +2 -2
  50. package/src/components/markdown-preview.tsx +60 -12
  51. package/src/components/studio/control-panel.tsx +299 -0
  52. package/src/components/studio/control-row.tsx +77 -0
  53. package/src/components/studio/preview-frame.tsx +165 -0
  54. package/src/components/studio/preview-pane.tsx +247 -0
  55. package/src/components/studio/studio.tsx +158 -0
  56. package/src/components/studio/types.ts +218 -0
  57. package/src/components/studio/use-studio-tweaks.ts +128 -0
  58. package/src/components/studio/use-studio-view-state.ts +72 -0
  59. package/src/components/ui/anchor.tsx +37 -3
  60. package/src/components/ui/attachment.tsx +211 -0
  61. package/src/components/ui/autocomplete.tsx +1 -1
  62. package/src/components/ui/chart.tsx +3 -0
  63. package/src/components/ui/code.tsx +1 -1
  64. package/src/components/ui/color-picker.tsx +21 -5
  65. package/src/components/ui/data-table.tsx +64 -3
  66. package/src/components/ui/date-field.tsx +1 -1
  67. package/src/components/ui/editable.tsx +1 -0
  68. package/src/components/ui/faceted-filter.tsx +187 -0
  69. package/src/components/ui/gauge-chart.tsx +252 -0
  70. package/src/components/ui/heatmap.tsx +256 -0
  71. package/src/components/ui/index.ts +9 -0
  72. package/src/components/ui/infinite-scroll.tsx +103 -0
  73. package/src/components/ui/inline-edit.tsx +175 -0
  74. package/src/components/ui/json-input.tsx +351 -0
  75. package/src/components/ui/month-picker.tsx +1 -1
  76. package/src/components/ui/navigation-progress.tsx +281 -0
  77. package/src/components/ui/number-input.tsx +27 -7
  78. package/src/components/ui/otp-input.tsx +208 -0
  79. package/src/components/ui/password-input.tsx +2 -1
  80. package/src/components/ui/password-strength-input.tsx +288 -0
  81. package/src/components/ui/phone-input.tsx +274 -0
  82. package/src/components/ui/pill.tsx +140 -0
  83. package/src/components/ui/popover.tsx +27 -4
  84. package/src/components/ui/scroll-progress.tsx +100 -0
  85. package/src/components/ui/search-input.tsx +1 -1
  86. package/src/components/ui/snackbar.tsx +393 -0
  87. package/src/components/ui/sortable-list.tsx +342 -0
  88. package/src/components/ui/squircle.tsx +1 -1
  89. package/src/components/ui/table.tsx +1 -1
  90. package/src/components/ui/tags-input.tsx +1 -1
  91. package/src/components/ui/timer.tsx +1 -0
  92. package/src/components/ui/tour.tsx +1 -3
  93. package/src/components/ui/transfer-list.tsx +13 -26
  94. package/src/components/ui/week-picker.tsx +1 -1
  95. package/src/components/ui/year-picker.tsx +1 -1
  96. package/src/data/component-added.json +958 -0
  97. package/src/data/docs-index.ts +36 -0
  98. package/src/hooks/use-global-mono-font.ts +1 -0
  99. package/src/hooks/use-global-primary-color.ts +1 -0
  100. package/src/hooks/use-global-sans-font.ts +1 -0
  101. package/src/hooks/use-global-serif-font.ts +1 -0
  102. package/src/hooks/use-global-type-scale.ts +17 -2
  103. package/src/hooks/use-mobile.ts +2 -0
  104. package/src/hooks/use-sync-type-scale.ts +7 -11
  105. package/src/lib/clamp.ts +2 -0
  106. package/src/lib/spec-parse.ts +4 -0
  107. package/src/lib/svg-sanitize.ts +19 -9
  108. package/src/stories/Anchor.stories.tsx +54 -0
  109. package/src/stories/Attachment.stories.tsx +189 -0
  110. package/src/stories/Autocomplete.stories.tsx +2 -0
  111. package/src/stories/Canvas.stories.tsx +45 -0
  112. package/src/stories/Chart.stories.tsx +4 -0
  113. package/src/stories/Code.stories.tsx +1 -0
  114. package/src/stories/ColorPicker.stories.tsx +41 -0
  115. package/src/stories/DataTable.stories.tsx +30 -0
  116. package/src/stories/DateField.stories.tsx +21 -0
  117. package/src/stories/Editable.stories.tsx +2 -0
  118. package/src/stories/FacetedFilter.stories.tsx +197 -0
  119. package/src/stories/GaugeChart.stories.tsx +169 -0
  120. package/src/stories/Heatmap.stories.tsx +172 -0
  121. package/src/stories/InfiniteScroll.stories.tsx +225 -0
  122. package/src/stories/InlineEdit.stories.tsx +106 -0
  123. package/src/stories/JsonInput.stories.tsx +212 -0
  124. package/src/stories/MarkdownPreview.stories.tsx +53 -0
  125. package/src/stories/MonthPicker.stories.tsx +21 -0
  126. package/src/stories/NavigationProgress.stories.tsx +159 -0
  127. package/src/stories/NumberInput.stories.tsx +26 -0
  128. package/src/stories/OtpInput.stories.tsx +110 -0
  129. package/src/stories/PasswordInput.stories.tsx +4 -0
  130. package/src/stories/PasswordStrengthInput.stories.tsx +211 -0
  131. package/src/stories/PhoneInput.stories.tsx +127 -0
  132. package/src/stories/Pill.stories.tsx +201 -0
  133. package/src/stories/Popover.stories.tsx +29 -1
  134. package/src/stories/Portal.stories.tsx +3 -1
  135. package/src/stories/ScrollProgress.stories.tsx +117 -0
  136. package/src/stories/SearchInput.stories.tsx +2 -0
  137. package/src/stories/Snackbar.stories.tsx +315 -0
  138. package/src/stories/SortableList.stories.tsx +263 -0
  139. package/src/stories/Squircle.stories.tsx +1 -0
  140. package/src/stories/Table.stories.tsx +1 -0
  141. package/src/stories/TagsInput.stories.tsx +2 -0
  142. package/src/stories/Timer.stories.tsx +26 -0
  143. package/src/stories/Tour.stories.tsx +1 -0
  144. package/src/stories/TransferList.stories.tsx +4 -0
  145. package/src/stories/WeekPicker.stories.tsx +21 -0
  146. package/src/stories/YearPicker.stories.tsx +21 -0
  147. package/src/stories/story-groups.json +33 -16
  148. package/src/tokens.json +82 -54
@@ -236,13 +236,49 @@ function toHex([r, g, b]) {
236
236
 
237
237
  const tokens = JSON.parse(fs.readFileSync(TOKENS, 'utf8'));
238
238
 
239
- function resolveValue(value, modeTokens) {
239
+ // Walk a dotted DTCG path ("theme.light.card", "color.semantic.action.primary")
240
+ // against the FULL tokens tree, not just the current mode — an alias can
241
+ // point anywhere in tokens.json, e.g. a dark-mode slot aliasing back to
242
+ // {theme.light.card}, or either mode aliasing a {color.semantic.*} value.
243
+ // Returns the node at that path (which may itself carry a $value to resolve
244
+ // further), or undefined if the path doesn't exist.
245
+ function resolveDottedPath(dotted) {
246
+ let node = tokens;
247
+ for (const part of dotted.split('.')) {
248
+ if (node == null || typeof node !== 'object') return undefined;
249
+ node = node[part];
250
+ }
251
+ return node;
252
+ }
253
+
254
+ // resolveValue is recursive (var(--x) can point at another var(--x); a
255
+ // {dotted.path} alias can point at another alias). A cycle in a broken
256
+ // consumer's tokens.json would recurse forever without a depth guard — this
257
+ // isn't a hypothetical, it's exactly the kind of malformed input a
258
+ // third-party fork's tokens.json can contain, and this script is not a
259
+ // build-time gate a bad tokens.json would ever get caught by first.
260
+ function resolveValue(value, modeTokens, depth) {
261
+ depth = depth || 0;
262
+ if (depth > 10) return null;
240
263
  if (typeof value !== 'string') return null;
241
264
  // var(--name) — look up in same-mode tokens
242
265
  const varMatch = value.match(/^var\(--([^)]+)\)$/);
243
266
  if (varMatch) {
244
267
  const ref = modeTokens[varMatch[1]];
245
- return ref ? resolveValue(ref.$value, modeTokens) : null;
268
+ return ref ? resolveValue(ref.$value, modeTokens, depth + 1) : null;
269
+ }
270
+ // {dotted.path} — DTCG alias syntax (see e.g. tokens.composites.surface.card.background
271
+ // -> {theme.light.card} for the convention already used elsewhere in tokens.json).
272
+ // theme.light/theme.dark never used this themselves in upstream BADS, which is exactly
273
+ // why this branch didn't exist until a consumer fork's tokens.json used one directly in
274
+ // a theme slot and every pair depending on it silently vanished from the audit instead
275
+ // of failing or being counted as skipped (found 2026-09-15, from a real client fork).
276
+ const aliasMatch = value.match(/^\{([\w.-]+)\}$/);
277
+ if (aliasMatch) {
278
+ const node = resolveDottedPath(aliasMatch[1]);
279
+ if (node === undefined) return null;
280
+ const nextValue = node && typeof node === 'object' ? node.$value : node;
281
+ return resolveValue(nextValue, modeTokens, depth + 1);
246
282
  }
247
283
  // oklch(from var(--x) calc(l + 0.1) c h) etc — too complex to evaluate, skip.
248
284
  if (value.includes('oklch(from')) return null;
@@ -321,7 +357,10 @@ function audit(modeName, modeTokens) {
321
357
  for (const [fgKey, bgKey, label, opts] of PAIRS) {
322
358
  const fgTok = modeTokens[fgKey];
323
359
  const bgTok = modeTokens[bgKey];
324
- if (!fgTok || !bgTok) continue;
360
+ if (!fgTok || !bgTok) {
361
+ results.push({ mode: modeName, fgKey, bgKey, label, status: 'skipped', reason: 'missing-token' });
362
+ continue;
363
+ }
325
364
  const fgRaw = resolveValue(fgTok.$value, modeTokens);
326
365
  const bgRaw = resolveValue(bgTok.$value, modeTokens);
327
366
  if (!fgRaw || !bgRaw) {
@@ -352,10 +391,23 @@ function audit(modeName, modeTokens) {
352
391
  for (const [fgKey, bgKey, label, opts] of NON_TEXT_PAIRS) {
353
392
  const fgTok = modeTokens[fgKey];
354
393
  const bgTok = modeTokens[bgKey];
355
- if (!fgTok || !bgTok) continue;
394
+ if (!fgTok || !bgTok) {
395
+ results.push({ mode: modeName, fgKey, bgKey, label, kind: 'non-text', status: 'skipped', reason: 'missing-token' });
396
+ continue;
397
+ }
356
398
  const fgRaw = resolveValue(fgTok.$value, modeTokens);
357
399
  const bgRaw = resolveValue(bgTok.$value, modeTokens);
358
- if (!fgRaw || !bgRaw) continue;
400
+ if (!fgRaw || !bgRaw) {
401
+ // Previously a bare `continue` here — non-text pairs (border/ring/chart
402
+ // colors) vanished from the report with NO trace at all when a value
403
+ // failed to resolve, unlike the PAIRS loop above which at least counted
404
+ // it as "skipped". This is the more severe half of the bug: not
405
+ // miscounted, just gone. Found 2026-09-15 alongside the {token.reference}
406
+ // alias-resolution gap — the two compounded, since an unresolved alias in
407
+ // a non-text slot (e.g. a border color) produced zero signal anywhere.
408
+ results.push({ mode: modeName, fgKey, bgKey, label, kind: 'non-text', status: 'skipped', reason: 'unresolvable' });
409
+ continue;
410
+ }
359
411
  const bg = flattenOver(bgRaw, [1, 1, 1]);
360
412
  const fg = flattenOver(fgRaw, bg);
361
413
  const ratio = contrast(fg, bg);
@@ -537,6 +589,21 @@ if (json) {
537
589
  for (const mode of ['light', 'dark']) {
538
590
  console.log(`▸ ${mode}`);
539
591
  for (const r of all.filter((x) => x.mode === mode)) {
592
+ // A skipped row never computed ratio/fgHex/bgHex — printing it through
593
+ // the normal line format below would render literal "undefined"s, which
594
+ // reads as broken output rather than as the diagnostic it should be.
595
+ // This was the second half of the {token.reference} bug: even the ONE
596
+ // loop that did push a `skipped` row (PAIRS) rendered it as garbage, so
597
+ // the tally at the bottom was the only intact signal — found 2026-09-15.
598
+ if (r.status === 'skipped') {
599
+ const kind = r.kind === 'non-text' ? ' [non-text]' : '';
600
+ const why = r.reason === 'missing-token'
601
+ ? `token "${r.fgKey}" or "${r.bgKey}" not found in this mode`
602
+ : `"${r.fgKey}" or "${r.bgKey}" has a value this script can't resolve to a color ` +
603
+ `(check for a {dotted.path} alias pointing at a missing token, or an unsupported value shape)`;
604
+ console.log(` · ${r.label.padEnd(34)} skipped — ${why}${kind}`);
605
+ continue;
606
+ }
540
607
  const mark =
541
608
  r.status === 'pass' ? '✓' :
542
609
  r.status === 'exception' ? '!' :
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { NextResponse } from "next/server";
4
+ import { refuseUnsafeWrite } from "./dev-write-guard";
4
5
 
5
6
  const COLORS_PATH = path.join(process.cwd(), "brand-colors.json");
6
7
 
@@ -63,6 +64,8 @@ export async function POST(request: Request) {
63
64
  if (process.env.NODE_ENV !== "development") {
64
65
  return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
65
66
  }
67
+ const refused = refuseUnsafeWrite(request);
68
+ if (refused) return refused;
66
69
 
67
70
  let op: Op;
68
71
  try {
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { spawn } from "node:child_process";
4
4
  import { NextResponse } from "next/server";
5
+ import { refuseUnsafeWrite } from "./dev-write-guard";
5
6
 
6
7
  const FONTS_PATH = path.join(process.cwd(), "brand-fonts.json");
7
8
  // Canonical location — ships with the npm package via the `./fonts/*` export.
@@ -120,6 +121,8 @@ export async function POST(request: Request) {
120
121
  if (process.env.NODE_ENV !== "development") {
121
122
  return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
122
123
  }
124
+ const refused = refuseUnsafeWrite(request);
125
+ if (refused) return refused;
123
126
 
124
127
  const contentType = request.headers.get("content-type") ?? "";
125
128
 
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { NextResponse } from "next/server";
4
4
  import { sanitizeSvg } from "@behavioral-agentic-design-system/core/lib/svg-sanitize";
5
+ import { refuseUnsafeWrite } from "./dev-write-guard";
5
6
 
6
7
  const MARK_PATH = path.join(process.cwd(), "brand-mark.json");
7
8
  const PUBLIC_PATH = path.join(process.cwd(), "public", "brand-mark.svg");
@@ -58,6 +59,8 @@ export async function POST(request: Request) {
58
59
  if (process.env.NODE_ENV !== "development") {
59
60
  return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
60
61
  }
62
+ const refused = refuseUnsafeWrite(request);
63
+ if (refused) return refused;
61
64
 
62
65
  let body: { svg?: string };
63
66
  try {
@@ -116,10 +119,12 @@ export async function POST(request: Request) {
116
119
  });
117
120
  }
118
121
 
119
- export async function DELETE() {
122
+ export async function DELETE(request: Request) {
120
123
  if (process.env.NODE_ENV !== "development") {
121
124
  return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
122
125
  }
126
+ const refused = refuseUnsafeWrite(request);
127
+ if (refused) return refused;
123
128
 
124
129
  let existing: MarkFile;
125
130
  try {
@@ -0,0 +1,53 @@
1
+ // Who may call a dev-only write route.
2
+ //
3
+ // WHY THIS EXISTS. These routes write files on your computer (tokens, docs, fonts, the brand mark) and one of
4
+ // them runs `git commit`. A page open in the same browser can send requests to localhost, and a hostile name
5
+ // that points at 127.0.0.1 (DNS rebinding) reaches the dev server as if it were local. The NODE_ENV check alone
6
+ // answers neither. This is the same Host / Origin / content-type reasoning as tools/comments/server/comments-guard.mjs,
7
+ // without that guard's custom header, so the app's own same-origin fetches keep working unchanged.
8
+ //
9
+ // 1. Host must be localhost, 127.0.0.1 or [::1]. A rebound name arrives with its own name here and is refused.
10
+ // 2. Origin when present (every request a web page makes carries one) must be the same origin as Host.
11
+ // 3. Fetch Sec-Fetch-Site, when present, must be same-origin or none.
12
+ // 4. Type a body must be application/json or multipart/form-data. A cross-site form post cannot send JSON.
13
+ //
14
+ // A request from curl has no Origin and passes gates 2 and 3, so local tools still work.
15
+ //
16
+ // KEEP IN SYNC with app/api/_lib/dev-write-guard.ts: app/api routes are inlined copies of these handlers
17
+ // (see app/api/layers/file/route.ts for why), so they cannot import across the workspace.
18
+
19
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/;
20
+ const BODY_TYPE = /^(application\/json|multipart\/form-data)\s*(;|$)/i;
21
+
22
+ /** A 403/415 Response when the request may not write, or null when it may go on. */
23
+ export function refuseUnsafeWrite(request: Request): Response | null {
24
+ const h = request.headers;
25
+ const host = h.get("host") ?? "";
26
+ if (!LOCAL_HOST.test(host)) return deny(403, "This route only answers requests addressed to localhost.");
27
+
28
+ const origin = h.get("origin");
29
+ if (origin !== null) {
30
+ let originHost = "";
31
+ try {
32
+ originHost = new URL(origin).host;
33
+ } catch {
34
+ // An unparseable Origin (including the literal "null") is never a local page.
35
+ }
36
+ if (originHost !== host) return deny(403, "This route only answers pages served from this server.");
37
+ }
38
+
39
+ const site = h.get("sec-fetch-site");
40
+ if (site !== null && site !== "same-origin" && site !== "none") {
41
+ return deny(403, "This route only answers pages served from this server.");
42
+ }
43
+
44
+ const hasBody = request.method === "POST" || request.method === "PUT" || request.method === "PATCH";
45
+ if (hasBody && !BODY_TYPE.test(h.get("content-type") ?? "")) {
46
+ return deny(415, "Send application/json.");
47
+ }
48
+ return null;
49
+ }
50
+
51
+ function deny(status: number, error: string): Response {
52
+ return Response.json({ ok: false, error }, { status });
53
+ }
@@ -1,9 +1,10 @@
1
- import { exec } from "node:child_process";
1
+ import { execFile } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { promisify } from "node:util";
5
+ import { refuseUnsafeWrite } from "../dev-write-guard";
5
6
 
6
- const execAsync = promisify(exec);
7
+ const execFileAsync = promisify(execFile);
7
8
  const ROOT = process.cwd();
8
9
 
9
10
  // Read allowlist. Reads are public (open-source docs) so we expand freely to
@@ -78,6 +79,8 @@ export async function POST(request: Request) {
78
79
  if (process.env.NODE_ENV !== "development") {
79
80
  return Response.json({ error: "dev-only" }, { status: 403 });
80
81
  }
82
+ const refused = refuseUnsafeWrite(request);
83
+ if (refused) return refused;
81
84
  try {
82
85
  const body = (await request.json()) as {
83
86
  path: string;
@@ -93,10 +96,10 @@ export async function POST(request: Request) {
93
96
 
94
97
  if (body.commit !== false) {
95
98
  const message = body.message?.trim() || `docs: edit ${body.path}`;
96
- await execAsync(`git add ${JSON.stringify(body.path)}`, { cwd: ROOT });
99
+ await execFileAsync("git", ["add", "--", body.path], { cwd: ROOT });
97
100
  // --allow-empty so saves with no diff don't error; precommit hook still runs.
98
101
  try {
99
- await execAsync(`git commit -m ${JSON.stringify(message)}`, { cwd: ROOT });
102
+ await execFileAsync("git", ["commit", "-m", message], { cwd: ROOT });
100
103
  } catch (e) {
101
104
  // No diff is fine. Anything else surfaces as an error.
102
105
  const msg = e instanceof Error ? e.message : String(e);
@@ -1,5 +1,9 @@
1
1
  import { NextResponse } from "next/server";
2
+ import { lookup } from "node:dns/promises";
3
+ import { isIP } from "node:net";
2
4
  import { load, type CheerioAPI } from "cheerio";
5
+ import { refuseUnsafeWrite } from "./dev-write-guard";
6
+ import { sanitizeSvg } from "../lib/svg-sanitize";
3
7
 
4
8
  const FETCH_TIMEOUT_MS = 12_000;
5
9
  const USER_AGENT = "Mozilla/5.0 (compatible; BADS-Onboarding/1.0)";
@@ -40,39 +44,82 @@ export type ExtractResult = {
40
44
  warnings: string[];
41
45
  };
42
46
 
43
- // SSRF defense-in-depth: reject URLs that point at private, internal, or
44
- // loopback targets so a user-supplied URL can't be used to probe internal
45
- // services or the cloud metadata endpoint. This is hostname-literal checking
46
- // only (it inspects the string the user typed) and is NOT full DNS-rebinding
47
- // protection — a hostname that resolves to a private IP at fetch time still
48
- // gets through. Strip the brackets IPv6 hosts arrive wrapped in before testing.
47
+ // SSRF defence: refuse private, internal and loopback targets, whether typed, resolved by DNS, or reached by a
48
+ // redirect. Literal IPv4/IPv6 forms are parsed with node:net rather than matched by prefix.
49
49
  function isBlockedHost(hostname: string): boolean {
50
- const host = hostname.trim().toLowerCase().replace(/^\[|\]$/g, "");
50
+ const host = hostname.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
51
51
  if (!host) return true;
52
52
 
53
53
  // localhost and internal-only TLD suffixes
54
- if (host === "localhost") return true;
55
- if (/\.local$/.test(host) || /\.internal$/.test(host)) return true;
54
+ if (host === "localhost" || host.endsWith(".localhost")) return true;
55
+ if (/\.(local|internal|localdomain|home\.arpa)$/.test(host)) return true;
56
56
 
57
- // IPv6 loopback, unique-local (fc00::/7 → fc/fd) and link-local (fe80::)
58
- if (host === "::1") return true;
59
- if (/^f[cd][0-9a-f]*:/.test(host)) return true;
60
- if (/^fe80:/.test(host)) return true;
61
-
62
- // IPv4 unspecified, loopback 127.0.0.0/8, and link-local 169.254.0.0/16
63
- // (covers the 169.254.169.254 cloud metadata IP)
64
- if (host === "0.0.0.0") return true;
65
- if (/^127\./.test(host)) return true;
66
- if (/^169\.254\./.test(host)) return true;
57
+ const family = isIP(host);
58
+ if (family === 6) return isBlockedIPv6(host);
59
+ if (family === 4) return isBlockedIPv4(host);
60
+ return false;
61
+ }
67
62
 
68
- // IPv4 private ranges: 10/8, 172.16-31/12, 192.168/16
69
- if (/^10\./.test(host)) return true;
70
- if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(host)) return true;
71
- if (/^192\.168\./.test(host)) return true;
63
+ function isBlockedIPv4(ip: string): boolean {
64
+ const [a, b] = ip.split(".").map(Number);
65
+ if (a === 0 || a === 10 || a === 127) return true; // this-network, private, loopback
66
+ if (a === 169 && b === 254) return true; // link-local, incl. the 169.254.169.254 metadata IP
67
+ if (a === 172 && b >= 16 && b <= 31) return true;
68
+ if (a === 192 && b === 168) return true;
69
+ if (a === 100 && b >= 64 && b <= 127) return true; // carrier-grade NAT, also used for internal clouds
70
+ if (a >= 224) return true; // multicast, reserved, broadcast
71
+ return false;
72
+ }
72
73
 
74
+ function isBlockedIPv6(ip: string): boolean {
75
+ if (ip === "::" || ip === "::1") return true;
76
+ if (/^f[cd]/.test(ip) || /^fe[89ab]/.test(ip)) return true; // unique-local fc00::/7, link-local fe80::/10
77
+ // IPv4-mapped (::ffff:a.b.c.d, or ::ffff:7f00:1 once the URL parser has normalized it) and other embeddings
78
+ // of an IPv4 address. Refuse them all rather than decode each form.
79
+ if (/^(0:){0,5}:?ffff:/.test(ip) || /^::ffff:/.test(ip) || /^64:ff9b:/.test(ip) || /^::\d+\.\d+/.test(ip)) return true;
73
80
  return false;
74
81
  }
75
82
 
83
+ // A public-looking name can resolve to a private address (an attacker-owned A record pointing at 127.0.0.1 or
84
+ // 169.254.169.254). Resolve first and refuse if ANY answer is private. A name that resolves between this check
85
+ // and the fetch (a rebinding race) is not covered; closing that needs a pinned-IP agent.
86
+ async function resolvesToPublicAddress(hostname: string): Promise<boolean> {
87
+ const host = hostname.replace(/^\[|\]$/g, "");
88
+ if (isIP(host)) return !isBlockedHost(host);
89
+ try {
90
+ const answers = await lookup(host, { all: true });
91
+ return answers.length > 0 && answers.every((a) => !isBlockedHost(a.address));
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ const MAX_REDIRECTS = 5;
98
+
99
+ // fetch() that checks every hop. The default redirect: "follow" re-requests whatever Location says, so a public
100
+ // page could 302 to http://169.254.169.254/ and the first-URL check would never see it. Stylesheet and logo URLs
101
+ // come from the fetched page, so they go through here too.
102
+ async function safeFetch(
103
+ url: string,
104
+ init: RequestInit,
105
+ ): Promise<{ res: Response; finalUrl: string }> {
106
+ let current = url;
107
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
108
+ const u = new URL(current);
109
+ if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error("Only http(s) URLs can be fetched");
110
+ if (isBlockedHost(u.hostname) || !(await resolvesToPublicAddress(u.hostname))) {
111
+ throw new Error("That address points at a private or internal network");
112
+ }
113
+ const res = await fetch(current, { ...init, redirect: "manual" });
114
+ if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
115
+ current = new URL(res.headers.get("location") as string, current).toString();
116
+ continue;
117
+ }
118
+ return { res, finalUrl: current };
119
+ }
120
+ throw new Error("Too many redirects");
121
+ }
122
+
76
123
  function normalizeUrl(input: string): string | null {
77
124
  const trimmed = input.trim();
78
125
  if (!trimmed) return null;
@@ -91,20 +138,19 @@ async function fetchHtml(url: string): Promise<{ html: string; finalUrl: string
91
138
  const controller = new AbortController();
92
139
  const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
93
140
  try {
94
- const res = await fetch(url, {
141
+ const { res, finalUrl: resolvedUrl } = await safeFetch(url, {
95
142
  headers: {
96
143
  "User-Agent": USER_AGENT,
97
144
  Accept: "text/html,application/xhtml+xml",
98
145
  "Accept-Language": "en-US,en;q=0.9",
99
146
  },
100
- redirect: "follow",
101
147
  signal: controller.signal,
102
148
  });
103
149
  if (!res.ok) {
104
150
  throw new Error(`Fetch failed: ${res.status} ${res.statusText}`);
105
151
  }
106
152
  const html = await res.text();
107
- return { html, finalUrl: res.url || url };
153
+ return { html, finalUrl: resolvedUrl };
108
154
  } finally {
109
155
  clearTimeout(timer);
110
156
  }
@@ -117,7 +163,7 @@ async function fetchStylesheet(url: string): Promise<string | null> {
117
163
  try {
118
164
  const controller = new AbortController();
119
165
  const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
120
- const res = await fetch(url, {
166
+ const { res, finalUrl: resolvedUrl } = await safeFetch(url, {
121
167
  headers: { "User-Agent": USER_AGENT, Accept: "text/css,*/*;q=0.1" },
122
168
  signal: controller.signal,
123
169
  });
@@ -302,7 +348,7 @@ async function fetchSvg(url: string): Promise<string | null> {
302
348
  try {
303
349
  const controller = new AbortController();
304
350
  const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
305
- const res = await fetch(url, {
351
+ const { res, finalUrl: resolvedUrl } = await safeFetch(url, {
306
352
  headers: { "User-Agent": USER_AGENT },
307
353
  signal: controller.signal,
308
354
  });
@@ -324,7 +370,8 @@ async function extractLogo($: CheerioAPI, baseUrl: string): Promise<ExtractedLog
324
370
  if (headerSvg.length) {
325
371
  const html = $.html(headerSvg);
326
372
  if (html && html.length < 16 * 1024) {
327
- return { kind: "svg", svg: html };
373
+ const clean = sanitizeSvg(html);
374
+ if (clean.ok) return { kind: "svg", svg: clean.svg };
328
375
  }
329
376
  }
330
377
 
@@ -337,7 +384,8 @@ async function extractLogo($: CheerioAPI, baseUrl: string): Promise<ExtractedLog
337
384
  const abs = new URL(src, baseUrl).toString();
338
385
  if (abs.endsWith(".svg")) {
339
386
  const svg = await fetchSvg(abs);
340
- if (svg) return { kind: "svg", svg };
387
+ const clean = svg ? sanitizeSvg(svg) : null;
388
+ if (clean?.ok) return { kind: "svg", svg: clean.svg };
341
389
  }
342
390
  return { kind: "image", url: abs };
343
391
  } catch {}
@@ -403,6 +451,13 @@ function extractCopy($: CheerioAPI): {
403
451
  }
404
452
 
405
453
  export async function POST(request: Request) {
454
+ // Fetching an arbitrary URL from the server is only for the local onboarding wizard. On a deployed site it
455
+ // would be an open proxy.
456
+ if (process.env.NODE_ENV !== "development") {
457
+ return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
458
+ }
459
+ const refused = refuseUnsafeWrite(request);
460
+ if (refused) return refused;
406
461
  let payload: { url?: string };
407
462
  try {
408
463
  payload = (await request.json()) as { url?: string };
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { NextResponse } from "next/server";
4
+ import { refuseUnsafeWrite } from "./dev-write-guard";
4
5
 
5
6
  const ONBOARDING_PATH = path.join(process.cwd(), "onboarding-brief.json");
6
7
 
@@ -38,6 +39,8 @@ export async function POST(request: Request) {
38
39
  if (process.env.NODE_ENV !== "development") {
39
40
  return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
40
41
  }
42
+ const refused = refuseUnsafeWrite(request);
43
+ if (refused) return refused;
41
44
 
42
45
  let payload: SavePayload;
43
46
  try {
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  import { NextResponse } from "next/server";
6
+ import { refuseUnsafeWrite } from "./dev-write-guard";
6
7
 
7
8
  const execAsync = promisify(exec);
8
9
  const TOKENS_PATH = path.join(process.cwd(), "packages/core/src/tokens.json");
@@ -89,6 +90,8 @@ export async function POST(request: Request) {
89
90
  { status: 403 },
90
91
  );
91
92
  }
93
+ const refused = refuseUnsafeWrite(request);
94
+ if (refused) return refused;
92
95
 
93
96
  let payload: SavePayload;
94
97
  try {
@@ -262,6 +262,12 @@ export default function RootLayout({
262
262
  if (typeof t.ratio === "number") ratio = t.ratio;
263
263
  } catch (e) {}
264
264
  }
265
+ // Enforce the 14px text-xs floor (WCAG 1.4.4) on the persisted
266
+ // value too. Mirrors applyScale() in use-global-type-scale.ts;
267
+ // without it base 18 / ratio 1.4 booted text-xs at ~9.18px
268
+ // until a slider moved. Lower ratio first, then raise base.
269
+ ratio = Math.max(1.05, Math.min(ratio, 1.4, Math.sqrt(base / 14)));
270
+ base = Math.min(22, Math.max(base, 14 * ratio * ratio));
265
271
  for (var name in STEPS) {
266
272
  var step = STEPS[name];
267
273
  var size = base * Math.pow(ratio, step);
@@ -30,6 +30,8 @@ export default function OpengraphImage() {
30
30
  return new ImageResponse(
31
31
  (
32
32
  <div
33
+ // allow-inline-style: Satori (next/og) can't resolve var(--token) —
34
+ // see the file-header note above. Literal colors are deliberate.
33
35
  style={{
34
36
  height: "100%",
35
37
  width: "100%",
@@ -51,6 +53,7 @@ export default function OpengraphImage() {
51
53
  background: accent,
52
54
  }}
53
55
  />
56
+ {/* allow-inline-style: Satori rendering context, see the note above */}
54
57
  <div
55
58
  style={{
56
59
  fontSize: "28px",
@@ -70,10 +73,12 @@ export default function OpengraphImage() {
70
73
  gap: "28px",
71
74
  }}
72
75
  >
76
+ {/* allow-inline-style: Satori rendering context, see the note above */}
73
77
  <div style={{ fontSize: "116px", lineHeight: 1, color: "#ffffff" }}>
74
78
  {brand.name}
75
79
  </div>
76
80
  {description ? (
81
+ // allow-inline-style: Satori rendering context, see the note above
77
82
  <div
78
83
  style={{
79
84
  fontSize: "40px",
@@ -0,0 +1,12 @@
1
+ "use client";
2
+
3
+ import { Canvas } from "../../../components/canvas/canvas";
4
+ import { SAMPLE_CANVAS, SAMPLE_SPEC, sampleResolveView } from "../../../components/canvas/sample";
5
+
6
+ export default function CanvasPreviewPage() {
7
+ return (
8
+ <main className="h-screen p-4">
9
+ <Canvas doc={SAMPLE_CANVAS} docs={{ "spec.md": SAMPLE_SPEC }} resolveView={sampleResolveView} />
10
+ </main>
11
+ );
12
+ }