@glw907/cairn-cms 0.50.0 → 0.52.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 (80) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/dist/components/EditPage.svelte +125 -16
  3. package/dist/components/EditPage.svelte.d.ts +4 -1
  4. package/dist/components/EditorToolbar.svelte +135 -10
  5. package/dist/components/EditorToolbar.svelte.d.ts +19 -2
  6. package/dist/components/MarkdownEditor.svelte +112 -6
  7. package/dist/components/MarkdownEditor.svelte.d.ts +4 -0
  8. package/dist/components/cairn-admin.css +69 -9
  9. package/dist/components/editor-highlight.d.ts +2 -0
  10. package/dist/components/editor-highlight.js +79 -15
  11. package/dist/components/editor-modes.d.ts +26 -0
  12. package/dist/components/editor-modes.js +92 -0
  13. package/dist/components/fonts/iAWriterMono-OFL.txt +100 -0
  14. package/dist/components/fonts/ia-writer-mono-latin-400-italic.woff2 +0 -0
  15. package/dist/components/fonts/ia-writer-mono-latin-400-normal.woff2 +0 -0
  16. package/dist/components/fonts/ia-writer-mono-latin-700-italic.woff2 +0 -0
  17. package/dist/components/fonts/ia-writer-mono-latin-700-normal.woff2 +0 -0
  18. package/dist/components/markdown-directives.d.ts +51 -0
  19. package/dist/components/markdown-directives.js +130 -1
  20. package/dist/components/preview-doc.d.ts +27 -0
  21. package/dist/components/preview-doc.js +64 -0
  22. package/dist/content/compose.js +1 -0
  23. package/dist/content/types.d.ts +33 -0
  24. package/dist/diagnostics/conditions.js +24 -0
  25. package/dist/doctor/bin.js +30 -12
  26. package/dist/doctor/check-floors.d.ts +15 -0
  27. package/dist/doctor/check-floors.js +107 -0
  28. package/dist/doctor/check-probe.d.ts +3 -0
  29. package/dist/doctor/check-probe.js +123 -0
  30. package/dist/doctor/checks-github.js +1 -1
  31. package/dist/doctor/checks-local.d.ts +1 -0
  32. package/dist/doctor/checks-local.js +28 -2
  33. package/dist/doctor/cloudflare-api.js +2 -2
  34. package/dist/doctor/index.d.ts +28 -3
  35. package/dist/doctor/index.js +47 -6
  36. package/dist/doctor/types.d.ts +2 -0
  37. package/dist/doctor/wrangler-config.d.ts +4 -0
  38. package/dist/doctor/wrangler-config.js +11 -0
  39. package/dist/env.d.ts +2 -1
  40. package/dist/env.js +9 -4
  41. package/dist/index.d.ts +1 -1
  42. package/dist/sveltekit/content-routes.d.ts +5 -1
  43. package/dist/sveltekit/content-routes.js +25 -17
  44. package/dist/sveltekit/guard.d.ts +8 -2
  45. package/dist/sveltekit/guard.js +3 -1
  46. package/dist/sveltekit/nav-routes.js +3 -9
  47. package/dist/vite/index.d.ts +16 -0
  48. package/dist/vite/index.js +57 -13
  49. package/package.json +2 -2
  50. package/src/lib/components/EditPage.svelte +125 -16
  51. package/src/lib/components/EditorToolbar.svelte +135 -10
  52. package/src/lib/components/MarkdownEditor.svelte +112 -6
  53. package/src/lib/components/cairn-admin.css +95 -5
  54. package/src/lib/components/editor-highlight.ts +91 -14
  55. package/src/lib/components/editor-modes.ts +106 -0
  56. package/src/lib/components/fonts/iAWriterMono-OFL.txt +100 -0
  57. package/src/lib/components/fonts/ia-writer-mono-latin-400-italic.woff2 +0 -0
  58. package/src/lib/components/fonts/ia-writer-mono-latin-400-normal.woff2 +0 -0
  59. package/src/lib/components/fonts/ia-writer-mono-latin-700-italic.woff2 +0 -0
  60. package/src/lib/components/fonts/ia-writer-mono-latin-700-normal.woff2 +0 -0
  61. package/src/lib/components/markdown-directives.ts +151 -1
  62. package/src/lib/components/preview-doc.ts +82 -0
  63. package/src/lib/content/compose.ts +1 -0
  64. package/src/lib/content/types.ts +32 -0
  65. package/src/lib/diagnostics/conditions.ts +24 -0
  66. package/src/lib/doctor/bin.ts +35 -10
  67. package/src/lib/doctor/check-floors.ts +124 -0
  68. package/src/lib/doctor/check-probe.ts +138 -0
  69. package/src/lib/doctor/checks-github.ts +3 -1
  70. package/src/lib/doctor/checks-local.ts +28 -2
  71. package/src/lib/doctor/cloudflare-api.ts +4 -2
  72. package/src/lib/doctor/index.ts +67 -6
  73. package/src/lib/doctor/types.ts +2 -0
  74. package/src/lib/doctor/wrangler-config.ts +11 -0
  75. package/src/lib/env.ts +9 -4
  76. package/src/lib/index.ts +2 -0
  77. package/src/lib/sveltekit/content-routes.ts +29 -17
  78. package/src/lib/sveltekit/guard.ts +4 -2
  79. package/src/lib/sveltekit/nav-routes.ts +3 -10
  80. package/src/lib/vite/index.ts +71 -17
@@ -154,6 +154,33 @@ export interface NavMenuConfig {
154
154
  maxDepth?: number;
155
155
  }
156
156
 
157
+ /**
158
+ * How the edit page's preview frame reproduces the live site's content styling. The admin
159
+ * deliberately never loads the site's CSS (chrome isolation), so a design-accurate preview needs
160
+ * the site to name its stylesheets for the preview frame; without this knob the preview renders
161
+ * unstyled markup. The frame's srcdoc pins a white body background as a deliberately overridable
162
+ * default, so a site whose ground is not white should state its body background in its own
163
+ * stylesheet.
164
+ */
165
+ export interface PreviewConfig {
166
+ /** Absolute or root-relative URLs of the site's compiled stylesheets, linked inside the
167
+ * preview document. A Vite `?url` import of the site's CSS resolves the hashed asset URL. */
168
+ stylesheets: string[];
169
+ /** Class list applied to the preview document's body, for theme or typography roots. */
170
+ bodyClass?: string;
171
+ /** Class list for a wrapper element around the rendered content, reproducing the site's
172
+ * content container (a prose or measure class). Omitted renders the content bare. */
173
+ containerClass?: string;
174
+ /** Per-concept overrides of bodyClass and containerClass, keyed by concept id. An entry's
175
+ * preview resolves the override for its concept over the top-level values; stylesheets are
176
+ * always shared. */
177
+ byConcept?: Record<string, { bodyClass?: string; containerClass?: string }>;
178
+ }
179
+
180
+ /** The flat preview shape `editLoad` ships to the edit page: the top-level `PreviewConfig`
181
+ * values with the entry's concept override applied, and no `byConcept` map. */
182
+ export type ResolvedPreview = Omit<PreviewConfig, 'byConcept'>;
183
+
157
184
  /** Reserved asset slot (seam 4). Typed and unused in the rebuild; R7/R9 read it later with no contract change. */
158
185
  export interface AssetConfig {
159
186
  /** Repo-relative asset roots, e.g. ["static/images"]. */
@@ -187,6 +214,9 @@ export interface CairnAdapter {
187
214
  /** The site's glyph name to SVG path-data map, for the admin icon picker and the renderer. */
188
215
  icons?: IconSet;
189
216
  navMenu?: NavMenuConfig;
217
+ /** The live site's content styling for the preview frame. The admin's chrome isolation keeps
218
+ * the site's CSS out of the admin document, so the preview frame links these instead. */
219
+ preview?: PreviewConfig;
190
220
  assets?: AssetConfig;
191
221
  }
192
222
 
@@ -285,6 +315,8 @@ export interface CairnRuntime {
285
315
  /** The site's glyph name to SVG path-data map, for the admin icon picker and the renderer. */
286
316
  icons?: IconSet;
287
317
  navMenu?: NavMenuConfig;
318
+ /** The live site's content styling for the preview frame; passed through from the adapter. */
319
+ preview?: PreviewConfig;
288
320
  assets?: AssetConfig;
289
321
  /** Admin panels contributed by extensions (Mode 2). Empty until Plan 09 wires the dispatch route. */
290
322
  adminPanels?: AdminPanel[];
@@ -101,6 +101,14 @@ export const REGISTRY: Record<string, CairnCondition> = {
101
101
  remediation: "Set csrf: { checkOrigin: false } in svelte.config.js and wire createAuthGuard into src/hooks.server.ts; cairn's guard owns the Origin and double-submit token checks.",
102
102
  docsAnchor: 'cloudflare-readiness.md#hand-cairn-the-csrf-authority',
103
103
  },
104
+ 'config.public-origin-invalid': {
105
+ id: 'config.public-origin-invalid',
106
+ severity: 'blocker',
107
+ title: 'PUBLIC_ORIGIN is missing or invalid',
108
+ why: 'PUBLIC_ORIGIN is unset, does not parse as a URL, or uses http on a non-local host. The magic-link confirmation links and the absolute feed URLs derive from it, config-only so a forged Host header cannot redirect a link, and sign-in cannot mint a usable link without it.',
109
+ remediation: "Set PUBLIC_ORIGIN to the site's canonical https origin in the wrangler config vars (with .dev.vars carrying the local http override), then re-deploy; http passes only on localhost or 127.0.0.1.",
110
+ docsAnchor: 'cloudflare-readiness.md#set-the-public-origin',
111
+ },
104
112
  'config.site-config-invalid': {
105
113
  id: 'config.site-config-invalid',
106
114
  severity: 'blocker',
@@ -109,6 +117,14 @@ export const REGISTRY: Record<string, CairnCondition> = {
109
117
  remediation: 'Correct site.config.yaml; the parse or validation error names the failing field or URL-policy rule.',
110
118
  docsAnchor: 'cloudflare-readiness.md#validate-the-site-config',
111
119
  },
120
+ 'config.dependency-floors-unmet': {
121
+ id: 'config.dependency-floors-unmet',
122
+ severity: 'blocker',
123
+ title: 'A framework dependency sits below the engine floor',
124
+ why: 'The lockfile resolves svelte or @sveltejs/kit below the range the engine declares as a peer. Consumer sites compile the shipped .svelte sources, so a below-floor compiler bites silently at build time; svelte 5.56.1 miscompiles parenthesized boolean groupings, which is why the svelte floor is ^5.56.3.',
125
+ remediation: "Raise the devDependency range in the site's package.json to the engine peer range and reinstall so the lockfile re-resolves, for example `npm install --save-dev svelte@^5.56.3`.",
126
+ docsAnchor: 'cloudflare-readiness.md#meet-the-dependency-floors',
127
+ },
112
128
  'edge.hsts-off': {
113
129
  id: 'edge.hsts-off',
114
130
  severity: 'warning',
@@ -134,6 +150,14 @@ export const REGISTRY: Record<string, CairnCondition> = {
134
150
  docsAnchor: 'cloudflare-readiness.md#install-the-github-app',
135
151
  logEvent: 'github.unreachable',
136
152
  },
153
+ 'admin.login-probe-failed': {
154
+ id: 'admin.login-probe-failed',
155
+ severity: 'blocker',
156
+ title: 'Live admin login probe failed',
157
+ why: 'A live request to the deployed admin did not answer with the working sign-in envelope (the login page, its CSRF cookie and hidden field, and the request action), so a real editor cannot sign in either. A probe failure has many possible causes; the detail line names the assertion that failed.',
158
+ remediation: 'Read the failed assertion in the detail line, run the full doctor against the same site, and work through the deploy guide; the other checks narrow the cause.',
159
+ docsAnchor: 'cloudflare-readiness.md#probe-the-deployed-admin',
160
+ },
137
161
  };
138
162
 
139
163
  // The registry is shared identity, never working state; freeze every entry and the map itself.
@@ -7,8 +7,17 @@
7
7
  // before the process ends.
8
8
  import { readFile } from 'node:fs/promises';
9
9
  import { resolve } from 'node:path';
10
+ import { liveProbeCheck } from './check-probe.js';
10
11
  import { liveSendCheck } from './check-send.js';
11
- import { contextFromEnv, defaultChecks, formatReport, parseArgs, runDoctor } from './index.js';
12
+ import { readWranglerConfig } from './wrangler-config.js';
13
+ import {
14
+ contextFromEnv,
15
+ defaultChecks,
16
+ deriveMissingInputs,
17
+ formatReport,
18
+ parseArgs,
19
+ runDoctor,
20
+ } from './index.js';
12
21
 
13
22
  async function main(): Promise<void> {
14
23
  let args: ReturnType<typeof parseArgs>;
@@ -21,21 +30,37 @@ async function main(): Promise<void> {
21
30
  }
22
31
 
23
32
  const cwd = process.cwd();
33
+ const readFileUnderCwd = async (relPath: string): Promise<string | null> => {
34
+ try {
35
+ return await readFile(resolve(cwd, relPath), 'utf8');
36
+ } catch (err) {
37
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
38
+ throw err;
39
+ }
40
+ };
41
+ // Fill inputs the flags and env left missing from the repo itself: from and repo off the
42
+ // adapter (through the vite arm, which exists only on this bin path, never in a Worker)
43
+ // and the account id off the wrangler config. The API token stays env-only.
44
+ const derived = await deriveMissingInputs(contextFromEnv(process.env, args, cwd), {
45
+ adapterFacts: async () => {
46
+ const { readAdapterFacts } = await import('../vite/index.js');
47
+ return readAdapterFacts(cwd);
48
+ },
49
+ wranglerAccountId: async () => (await readWranglerConfig(readFileUnderCwd))?.accountId,
50
+ });
24
51
  const ctx = {
25
- ...contextFromEnv(process.env, args, cwd),
52
+ ...derived,
26
53
  fetch: globalThis.fetch,
27
- readFile: async (relPath: string): Promise<string | null> => {
28
- try {
29
- return await readFile(resolve(cwd, relPath), 'utf8');
30
- } catch (err) {
31
- if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
32
- throw err;
33
- }
34
- },
54
+ readFile: readFileUnderCwd,
35
55
  };
36
56
 
37
57
  const checks = defaultChecks();
38
58
  if (args.sendTest) checks.push(liveSendCheck(args.sendTest));
59
+ // The probe is an opt-in network POST against a live site, so it joins only on --probe;
60
+ // the bare flag hands the URL resolution (the PUBLIC_ORIGIN input) to the check itself.
61
+ if (args.probe !== undefined) {
62
+ checks.push(liveProbeCheck(args.probe === true ? undefined : args.probe));
63
+ }
39
64
 
40
65
  const { results, failed } = await runDoctor(checks, ctx);
41
66
  console.log(formatReport(results));
@@ -0,0 +1,124 @@
1
+ // The dependency-floors check. The engine's peer ranges have teeth only when something reads
2
+ // the consumer's lockfile, where a transitively pinned svelte can sit below the floor while
3
+ // package.json looks fine (the ecxc retrofit shipped svelte 5.56.0 that way). The check compares
4
+ // the resolved svelte and @sveltejs/kit versions in package-lock.json against the peer ranges
5
+ // the installed @glw907/cairn-cms declares, read at runtime so the floors live in one place.
6
+ import { createRequire } from 'node:module';
7
+ import { fail, pass, skip } from './types.js';
8
+ import type { CheckResult, DoctorCheck, DoctorContext } from './types.js';
9
+
10
+ interface Version {
11
+ major: number;
12
+ minor: number;
13
+ patch: number;
14
+ }
15
+
16
+ // Plain x.y.z only. A prerelease or build tag returns null, so the check skips rather than
17
+ // guessing how a tagged build orders against the floor.
18
+ function parseVersion(text: string): Version | null {
19
+ const m = text.match(/^(\d+)\.(\d+)\.(\d+)$/);
20
+ if (!m) return null;
21
+ return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) };
22
+ }
23
+
24
+ // The engine's peers are simple caret ranges (^x.y.z, or ^x.y like the kit floor ^2.12), so
25
+ // this handles the caret form only; anything else returns null and the check skips for that
26
+ // dependency instead of approximating a full semver implementation.
27
+ function caretFloor(range: string): Version | null {
28
+ const m = range.match(/^\^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/);
29
+ if (!m) return null;
30
+ return { major: Number(m[1]), minor: Number(m[2] ?? 0), patch: Number(m[3] ?? 0) };
31
+ }
32
+
33
+ function compareVersions(a: Version, b: Version): number {
34
+ return a.major - b.major || a.minor - b.minor || a.patch - b.patch;
35
+ }
36
+
37
+ // A v2/v3 lockfile's packages map; v1 has none and the check skips.
38
+ interface LockPackages {
39
+ packages?: Record<string, { version?: unknown } | undefined>;
40
+ }
41
+
42
+ function lockedVersion(lock: LockPackages, dep: string): string | undefined {
43
+ const version = lock.packages?.[`node_modules/${dep}`]?.version;
44
+ return typeof version === 'string' ? version : undefined;
45
+ }
46
+
47
+ /**
48
+ * Judge a lockfile's resolved framework versions against the engine's peer ranges. Pure, so the
49
+ * tests drive it table-style; the check object wires in the real lockfile and the real peers.
50
+ * A below-range version fails; a lockfile or entry the check cannot read skips, since a pnpm or
51
+ * yarn consumer carries no package-lock.json at all.
52
+ */
53
+ export function dependencyFloorsResult(
54
+ lockText: string | null,
55
+ peers: Record<string, string>
56
+ ): CheckResult {
57
+ if (lockText === null) {
58
+ return skip('no package-lock.json found (a pnpm or yarn lockfile is not read)');
59
+ }
60
+ let lock: LockPackages;
61
+ try {
62
+ lock = JSON.parse(lockText) as LockPackages;
63
+ } catch {
64
+ // Like the wrangler reader: never echo file content into the report.
65
+ return fail('package-lock.json did not parse');
66
+ }
67
+ if (lock.packages === undefined) {
68
+ return skip('package-lock.json carries no packages map (lockfile v1; reinstall with a current npm)');
69
+ }
70
+ const failures: string[] = [];
71
+ const skips: string[] = [];
72
+ const passes: string[] = [];
73
+ for (const [dep, range] of Object.entries(peers)) {
74
+ const floor = caretFloor(range);
75
+ if (floor === null) {
76
+ skips.push(`${dep}: the engine range ${range} is not a simple caret range`);
77
+ continue;
78
+ }
79
+ const resolved = lockedVersion(lock, dep);
80
+ if (resolved === undefined) {
81
+ skips.push(`${dep}: no node_modules/${dep} entry in package-lock.json`);
82
+ continue;
83
+ }
84
+ const version = parseVersion(resolved);
85
+ if (version === null) {
86
+ skips.push(`${dep}: resolved ${resolved} is not a plain x.y.z version`);
87
+ continue;
88
+ }
89
+ // The caret bounds both ends: at or above the floor, same major. The engine's peers
90
+ // start at major 1 or higher, so the 0.x caret nuance never applies here.
91
+ if (compareVersions(version, floor) < 0) {
92
+ failures.push(`${dep} resolves to ${resolved}, below the engine floor ${range}`);
93
+ } else if (version.major !== floor.major) {
94
+ failures.push(`${dep} resolves to ${resolved}, outside the engine peer range ${range}`);
95
+ } else {
96
+ passes.push(`${dep} ${resolved}`);
97
+ }
98
+ }
99
+ if (failures.length > 0) return fail(failures.join('; '));
100
+ if (skips.length > 0) return skip(skips.join('; '));
101
+ return pass(`${passes.join(' and ')} satisfy the engine peer ranges`);
102
+ }
103
+
104
+ /**
105
+ * The engine's own declared peer ranges, read from the installed package.json at runtime so the
106
+ * floors are declared exactly once. The self-reference resolves through the consumer's
107
+ * node_modules in a real install and through the repo root during development.
108
+ */
109
+ export function readEnginePeers(): Record<string, string> {
110
+ const require = createRequire(import.meta.url);
111
+ const pkg = require('@glw907/cairn-cms/package.json') as {
112
+ peerDependencies?: Record<string, string>;
113
+ };
114
+ return pkg.peerDependencies ?? {};
115
+ }
116
+
117
+ export const configDependencyFloors: DoctorCheck = {
118
+ id: 'config.dependency-floors',
119
+ conditionId: 'config.dependency-floors-unmet',
120
+ title: 'Dependency floors',
121
+ async run(ctx: DoctorContext): Promise<CheckResult> {
122
+ return dependencyFloorsResult(await ctx.readFile('package-lock.json'), readEnginePeers());
123
+ },
124
+ };
@@ -0,0 +1,138 @@
1
+ // The doctor's opt-in live probe (--probe): one GET and one POST against a deployed admin,
2
+ // asserting the envelope a working sign-in presents. Zero side effects by construction: the
3
+ // POST submits a random non-editor address, and the engine's non-leak design answers a
4
+ // non-editor with the identical sent body while sending no email and minting no token, so the
5
+ // probe leaves nothing behind on the site. A factory rather than a check constant, the same
6
+ // shape as the live send: the check exists only when the bin receives --probe.
7
+ import { fail, pass, skip } from './types.js';
8
+ import type { CheckResult, DoctorCheck, DoctorContext } from './types.js';
9
+ import { csrfCookieName } from '../auth/crypto.js';
10
+ import { readWranglerConfig } from './wrangler-config.js';
11
+
12
+ const NO_URL: CheckResult = skip(
13
+ 'pass --probe <url>, set PUBLIC_ORIGIN in the wrangler vars, or set PUBLIC_ORIGIN in the environment'
14
+ );
15
+
16
+ /** Build the live-probe check. A missing url falls back to the PUBLIC_ORIGIN input at run time. */
17
+ export function liveProbeCheck(url?: string): DoctorCheck {
18
+ return {
19
+ id: 'admin.login-probe',
20
+ conditionId: 'admin.login-probe-failed',
21
+ title: 'Live admin login probe',
22
+ async run(ctx: DoctorContext): Promise<CheckResult> {
23
+ // The wrangler vars hold the value the deployed Worker reads, so they beat the local
24
+ // environment, the same precedence the public-origin check applies.
25
+ const base =
26
+ url ?? (await readWranglerConfig(ctx.readFile))?.publicOrigin ?? ctx.publicOrigin;
27
+ if (base === undefined) return NO_URL;
28
+ let origin: URL;
29
+ try {
30
+ origin = new URL(base);
31
+ } catch {
32
+ return fail(`probe URL does not parse: ${base}`);
33
+ }
34
+ try {
35
+ return await probe(ctx, origin);
36
+ } catch (err) {
37
+ return fail(String(err));
38
+ }
39
+ },
40
+ };
41
+ }
42
+
43
+ /** GET /admin/login and assert the sign-in envelope, then hand the harvested token pair on. */
44
+ async function probe(ctx: DoctorContext, origin: URL): Promise<CheckResult> {
45
+ const res = await ctx.fetch(String(new URL('/admin/login', origin)));
46
+ if (res.status !== 200) {
47
+ return fail(`GET /admin/login returned ${res.status}, expected 200`);
48
+ }
49
+ const cookieName = csrfCookieName(origin.protocol === 'https:');
50
+ const cookieValue = setCookieValue(res.headers.getSetCookie(), cookieName);
51
+ if (cookieValue === undefined) {
52
+ return fail(`GET /admin/login set no ${cookieName} cookie`);
53
+ }
54
+ const html = await res.text();
55
+ const field = csrfFieldValue(html);
56
+ if (field === undefined) {
57
+ return fail('the login page carries no name="csrf" hidden field with a value');
58
+ }
59
+ if (!/<form[^>]*action="[^"]*\?\/request"/.test(html)) {
60
+ return fail('the login page carries no form posting the ?/request action');
61
+ }
62
+ return postRequestAction(ctx, origin, `${cookieName}=${cookieValue}`, field);
63
+ }
64
+
65
+ /** The named cookie's value from the Set-Cookie lines, or undefined when no line names it. */
66
+ function setCookieValue(lines: string[], name: string): string | undefined {
67
+ for (const line of lines) {
68
+ const eq = line.indexOf('=');
69
+ if (eq === -1 || line.slice(0, eq).trim() !== name) continue;
70
+ const rest = line.slice(eq + 1);
71
+ const semi = rest.indexOf(';');
72
+ return semi === -1 ? rest : rest.slice(0, semi);
73
+ }
74
+ return undefined;
75
+ }
76
+
77
+ /** The csrf hidden field's value, tolerant of attribute order, or undefined when absent or empty. */
78
+ function csrfFieldValue(html: string): string | undefined {
79
+ const input = (html.match(/<input[^>]*>/g) ?? []).find((tag) => /name="csrf"/.test(tag));
80
+ if (input === undefined) return undefined;
81
+ return /value="([^"]+)"/.exec(input)?.[1];
82
+ }
83
+
84
+ /**
85
+ * POST the request action and read its serialized result. The address is random and non-editor
86
+ * at the reserved example.invalid domain, so even a delivery bug could send nothing anywhere,
87
+ * and the engine's non-leak design makes the response indistinguishable from a real send.
88
+ */
89
+ async function postRequestAction(
90
+ ctx: DoctorContext,
91
+ origin: URL,
92
+ cookie: string,
93
+ csrf: string
94
+ ): Promise<CheckResult> {
95
+ const email = `cairn-doctor-probe-${Math.random().toString(36).slice(2, 10)}@example.invalid`;
96
+ const res = await ctx.fetch(String(new URL('/admin/login?/request', origin)), {
97
+ method: 'POST',
98
+ headers: {
99
+ 'content-type': 'application/x-www-form-urlencoded',
100
+ cookie,
101
+ },
102
+ body: new URLSearchParams({ email, csrf }).toString(),
103
+ });
104
+ if (res.status !== 200) {
105
+ return fail(`POST ?/request returned ${res.status}, expected 200`);
106
+ }
107
+ // A no-Accept action POST answers with SvelteKit's serialized form-action JSON, shaped
108
+ // {"type":"success","status":200,"data":"<devalue array string>"}. The data field is a
109
+ // devalue encoding the probe reads by containment for the status literals, tolerant of
110
+ // encoding details it does not own, instead of pulling in a devalue parser.
111
+ let envelope: { type?: unknown; data?: unknown };
112
+ try {
113
+ envelope = (await res.json()) as { type?: unknown; data?: unknown };
114
+ } catch {
115
+ return fail('POST ?/request did not answer with the serialized action JSON');
116
+ }
117
+ if (envelope.type !== 'success') {
118
+ return fail(`POST ?/request answered type ${String(envelope.type)}, expected success`);
119
+ }
120
+ const data = typeof envelope.data === 'string' ? envelope.data : '';
121
+ if (data.includes('"send_error"')) {
122
+ return fail(
123
+ 'the request action answered send_error; the magic-link send path is failing (see the email checks and the auth.link.send_failed log records)'
124
+ );
125
+ }
126
+ // Every payload carries the "sent" field name, so the distinct status spellings go first.
127
+ if (data.includes('"throttled"')) {
128
+ return pass(
129
+ `sign-in envelope verified at ${origin.origin}; the request action answered throttled (a real cooldown window is active), which still proves the path`
130
+ );
131
+ }
132
+ if (data.includes('"sent"')) {
133
+ return pass(
134
+ `sign-in envelope verified at ${origin.origin}; the request action answered sent for a non-editor probe address`
135
+ );
136
+ }
137
+ return fail('POST ?/request answered success with an unrecognized payload');
138
+ }
@@ -22,7 +22,9 @@ export const githubApp: DoctorCheck = {
22
22
  );
23
23
  }
24
24
  if (!ctx.repo) {
25
- return skip('pass --repo or set GITHUB_REPO to run this check');
25
+ return skip(
26
+ 'pass --repo, set GITHUB_REPO, or configure the cairnManifest plugin so the doctor can read the adapter'
27
+ );
26
28
  }
27
29
  const creds = appCredentials(
28
30
  { appId: ctx.github.appId, installationId: ctx.github.installationId },
@@ -1,9 +1,10 @@
1
1
  // The doctor's local-config checks: the wrangler bindings, the observability sink, the
2
- // svelte.config CSRF handoff, and the site-config validation. Every read goes through the
3
- // injected ctx.readFile, so the tests pass fixtures and the bin passes node:fs.
2
+ // svelte.config CSRF handoff, the site-config validation, and the public origin. Every read
3
+ // goes through the injected ctx.readFile, so the tests pass fixtures and the bin passes node:fs.
4
4
  import { fail, pass, skip } from './types.js';
5
5
  import type { CheckResult, DoctorCheck, DoctorContext } from './types.js';
6
6
  import { readWranglerConfig } from './wrangler-config.js';
7
+ import { requireOrigin } from '../env.js';
7
8
  import { parseSiteConfig, urlPolicyFrom } from '../nav/site-config.js';
8
9
  import { normalizeConcepts } from '../content/concepts.js';
9
10
  import { defineFields } from '../content/schema.js';
@@ -85,6 +86,31 @@ export const configCsrfDisable: DoctorCheck = {
85
86
  },
86
87
  };
87
88
 
89
+ export const configPublicOrigin: DoctorCheck = {
90
+ id: 'config.public-origin',
91
+ conditionId: 'config.public-origin-invalid',
92
+ title: 'Public origin',
93
+ async run(ctx: DoctorContext): Promise<CheckResult> {
94
+ // The wrangler vars hold the value the deployed Worker reads, so they beat the local
95
+ // environment; the env fallback covers a dashboard-set var the file never carries.
96
+ const facts = await readWranglerConfig(ctx.readFile);
97
+ const fromVars = facts?.publicOrigin;
98
+ const origin = fromVars ?? ctx.publicOrigin;
99
+ if (facts === null && origin === undefined) {
100
+ return skip('no wrangler config found and PUBLIC_ORIGIN is not in the environment');
101
+ }
102
+ // requireOrigin is the runtime rule (unset, not a URL, http off localhost); reusing it
103
+ // keeps the doctor and the Worker on one judgment.
104
+ try {
105
+ requireOrigin({ PUBLIC_ORIGIN: origin });
106
+ } catch (err) {
107
+ return fail(err instanceof Error ? err.message : String(err));
108
+ }
109
+ const source = fromVars !== undefined ? 'wrangler vars' : 'environment';
110
+ return pass(`PUBLIC_ORIGIN is ${origin} (${source})`);
111
+ },
112
+ };
113
+
88
114
  // Where sites keep site.config.yaml. The adapter's configPath is TypeScript the CLI cannot
89
115
  // evaluate, so the check probes the conventional spots instead (the repo root and the two
90
116
  // src locations the production sites use).
@@ -9,10 +9,12 @@ export const CF_API = 'https://api.cloudflare.com/client/v4';
9
9
 
10
10
  export const NO_TOKEN: CheckResult = skip('set CLOUDFLARE_API_TOKEN to run this check');
11
11
 
12
- export const NO_FROM: CheckResult = skip('pass --from or set CAIRN_FROM to run this check');
12
+ export const NO_FROM: CheckResult = skip(
13
+ 'pass --from, set CAIRN_FROM, or configure the cairnManifest plugin so the doctor can read the adapter'
14
+ );
13
15
 
14
16
  export const NO_ACCOUNT: CheckResult = skip(
15
- 'set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID to run this check'
17
+ 'set CLOUDFLARE_API_TOKEN, and CLOUDFLARE_ACCOUNT_ID or a wrangler account_id, to run this check'
16
18
  );
17
19
 
18
20
  export function cfGet(ctx: DoctorContext, path: string): Promise<Response> {
@@ -7,22 +7,28 @@ import {
7
7
  configObservability,
8
8
  configCsrfDisable,
9
9
  configSiteConfig,
10
+ configPublicOrigin,
10
11
  } from './checks-local.js';
12
+ import { configDependencyFloors } from './check-floors.js';
11
13
  import { emailSenderOnboarded, edgeHttpsForced, edgeHsts, authStore } from './checks-cloudflare.js';
12
14
  import { githubApp } from './checks-github.js';
13
15
 
14
16
  export { runDoctor } from './run.js';
15
17
  export { formatReport } from './report.js';
16
18
 
17
- const USAGE = 'Usage: cairn-doctor [--from <address>] [--repo <owner/name>] [--send-test <address>]';
19
+ const USAGE =
20
+ 'Usage: cairn-doctor [--from <address>] [--repo <owner/name>] [--send-test <address>] [--probe [url]]';
18
21
 
19
22
  export interface DoctorArgs {
20
23
  from?: string;
21
24
  repo?: string;
22
25
  sendTest?: string;
26
+ /** The live admin probe: a URL when --probe carried one, true for the bare flag (probe the
27
+ * PUBLIC_ORIGIN input), absent when the flag never appeared (the probe does not run). */
28
+ probe?: string | true;
23
29
  }
24
30
 
25
- const FLAGS: Record<string, keyof DoctorArgs> = {
31
+ const FLAGS: Record<string, 'from' | 'repo' | 'sendTest'> = {
26
32
  '--from': 'from',
27
33
  '--repo': 'repo',
28
34
  '--send-test': 'sendTest',
@@ -31,8 +37,16 @@ const FLAGS: Record<string, keyof DoctorArgs> = {
31
37
  /** Parse the bin's argv (long flags only). Throws with a usage line on anything unexpected. */
32
38
  export function parseArgs(argv: string[]): DoctorArgs {
33
39
  const args: DoctorArgs = {};
34
- for (let i = 0; i < argv.length; i += 2) {
40
+ for (let i = 0; i < argv.length; ) {
35
41
  const flag = argv[i];
42
+ // --probe alone is meaningful (probe the PUBLIC_ORIGIN input), so its value is optional.
43
+ if (flag === '--probe') {
44
+ const value = argv[i + 1];
45
+ const bare = value === undefined || value.startsWith('--');
46
+ args.probe = bare ? true : value;
47
+ i += bare ? 1 : 2;
48
+ continue;
49
+ }
36
50
  const key = FLAGS[flag];
37
51
  if (!key) throw new Error(`unknown argument ${flag}\n${USAGE}`);
38
52
  const value = argv[i + 1];
@@ -40,6 +54,7 @@ export function parseArgs(argv: string[]): DoctorArgs {
40
54
  throw new Error(`${flag} needs a value\n${USAGE}`);
41
55
  }
42
56
  args[key] = value;
57
+ i += 2;
43
58
  }
44
59
  return args;
45
60
  }
@@ -62,6 +77,7 @@ export function contextFromEnv(
62
77
  repo: args.repo ?? env.GITHUB_REPO,
63
78
  cfToken: env.CLOUDFLARE_API_TOKEN,
64
79
  cfAccountId: env.CLOUDFLARE_ACCOUNT_ID,
80
+ publicOrigin: env.PUBLIC_ORIGIN,
65
81
  github:
66
82
  GITHUB_APP_ID && GITHUB_APP_INSTALLATION_ID && GITHUB_APP_PRIVATE_KEY_B64
67
83
  ? {
@@ -73,10 +89,53 @@ export function contextFromEnv(
73
89
  };
74
90
  }
75
91
 
92
+ /** The lazy derivation sources the bin wires up: the adapter read through the consumer's own
93
+ * Vite resolution and the wrangler config's account_id. Each runs only when an input it feeds
94
+ * is still missing, so a doctor run with full flags touches neither. */
95
+ export interface DerivationSources {
96
+ /** Returns { owner, repo, from } off the adapter, or null when nothing is derivable. */
97
+ adapterFacts: () => Promise<{ owner?: string; repo?: string; from?: string } | null>;
98
+ /** Returns the wrangler config's account_id, or undefined when none is declared. */
99
+ wranglerAccountId: () => Promise<string | undefined>;
100
+ }
101
+
102
+ /**
103
+ * Fill the context's missing inputs from the repo the doctor runs in: from and repo off the
104
+ * adapter, the account id off the wrangler config. An explicit flag or env value always wins
105
+ * (contextFromEnv already resolved those into ctx), each source runs lazily and only for
106
+ * inputs still missing, and a derivation failure leaves the input absent so its check skips
107
+ * with the usual remediation line instead of the doctor crashing. The API token is never
108
+ * derived; it stays env-only.
109
+ */
110
+ export async function deriveMissingInputs(
111
+ ctx: Omit<DoctorContext, 'fetch' | 'readFile'>,
112
+ sources: DerivationSources
113
+ ): Promise<Omit<DoctorContext, 'fetch' | 'readFile'>> {
114
+ const out = { ...ctx };
115
+ if (out.from === undefined || out.repo === undefined) {
116
+ const facts = await sources.adapterFacts().catch(() => null);
117
+ if (out.from === undefined && typeof facts?.from === 'string') {
118
+ out.from = facts.from;
119
+ }
120
+ if (
121
+ out.repo === undefined &&
122
+ typeof facts?.owner === 'string' &&
123
+ typeof facts?.repo === 'string'
124
+ ) {
125
+ out.repo = `${facts.owner}/${facts.repo}`;
126
+ }
127
+ }
128
+ if (out.cfAccountId === undefined) {
129
+ const accountId = await sources.wranglerAccountId().catch(() => undefined);
130
+ if (typeof accountId === 'string') out.cfAccountId = accountId;
131
+ }
132
+ return out;
133
+ }
134
+
76
135
  /**
77
- * The default registry: the four local-config checks, the four Cloudflare checks, and the
78
- * GitHub App chain. The live send is opt-in (--send-test) and never sits here; the bin appends
79
- * it. A fresh array per call, so that append mutates nothing shared.
136
+ * The default registry: the six local checks, the four Cloudflare checks, and the GitHub App
137
+ * chain. The live send is opt-in (--send-test) and never sits here; the bin appends it. A
138
+ * fresh array per call, so that append mutates nothing shared.
80
139
  */
81
140
  export function defaultChecks(): DoctorCheck[] {
82
141
  return [
@@ -84,6 +143,8 @@ export function defaultChecks(): DoctorCheck[] {
84
143
  configObservability,
85
144
  configCsrfDisable,
86
145
  configSiteConfig,
146
+ configPublicOrigin,
147
+ configDependencyFloors,
87
148
  emailSenderOnboarded,
88
149
  edgeHttpsForced,
89
150
  edgeHsts,
@@ -43,6 +43,8 @@ export interface DoctorContext {
43
43
  cfToken?: string;
44
44
  /** CLOUDFLARE_ACCOUNT_ID. */
45
45
  cfAccountId?: string;
46
+ /** PUBLIC_ORIGIN, the env fallback when the wrangler vars carry none. */
47
+ publicOrigin?: string;
46
48
  /** GITHUB_APP_ID / GITHUB_APP_INSTALLATION_ID / GITHUB_APP_PRIVATE_KEY_B64. */
47
49
  github?: { appId: string; installationId: string; privateKeyB64: string };
48
50
  /** Injected fetch for tests; defaults to global fetch. */
@@ -12,6 +12,10 @@ export interface WranglerFacts {
12
12
  authDbId?: string;
13
13
  /** observability.enabled is true. */
14
14
  observabilityEnabled: boolean;
15
+ /** vars.PUBLIC_ORIGIN, when declared; the public-origin check validates it. */
16
+ publicOrigin?: string;
17
+ /** The top-level account_id, when declared; a fallback for CLOUDFLARE_ACCOUNT_ID. */
18
+ accountId?: string;
15
19
  }
16
20
 
17
21
  export async function readWranglerConfig(
@@ -91,6 +95,9 @@ function factsFromJsonc(text: string): WranglerFacts {
91
95
  observabilityEnabled: observability?.enabled === true,
92
96
  };
93
97
  if (typeof authDb?.database_id === 'string') facts.authDbId = authDb.database_id;
98
+ const vars = config.vars as { PUBLIC_ORIGIN?: unknown } | undefined;
99
+ if (typeof vars?.PUBLIC_ORIGIN === 'string') facts.publicOrigin = vars.PUBLIC_ORIGIN;
100
+ if (typeof config.account_id === 'string') facts.accountId = config.account_id;
94
101
  return facts;
95
102
  }
96
103
 
@@ -135,6 +142,10 @@ function factsFromToml(text: string): WranglerFacts {
135
142
  if (key === 'database_id') d1Id = str;
136
143
  } else if (section === '[observability]' && key === 'enabled' && value.startsWith('true')) {
137
144
  facts.observabilityEnabled = true;
145
+ } else if (section === '[vars]' && key === 'PUBLIC_ORIGIN' && str !== undefined) {
146
+ facts.publicOrigin = str;
147
+ } else if (section === '' && key === 'account_id' && str !== undefined) {
148
+ facts.accountId = str;
138
149
  }
139
150
  }
140
151
  flushD1();