@glw907/cairn-cms 0.34.0 → 0.36.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 (64) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/auth/crypto.d.ts +4 -0
  3. package/dist/auth/crypto.js +10 -0
  4. package/dist/components/AdminLayout.svelte +8 -1
  5. package/dist/components/ConceptList.svelte +3 -0
  6. package/dist/components/ConfirmPage.svelte +4 -2
  7. package/dist/components/ConfirmPage.svelte.d.ts +2 -1
  8. package/dist/components/CsrfField.svelte +20 -0
  9. package/dist/components/CsrfField.svelte.d.ts +12 -0
  10. package/dist/components/DeleteDialog.svelte +2 -0
  11. package/dist/components/EditPage.svelte +2 -0
  12. package/dist/components/LoginPage.svelte +4 -2
  13. package/dist/components/LoginPage.svelte.d.ts +2 -1
  14. package/dist/components/ManageEditors.svelte +4 -0
  15. package/dist/components/NavTree.svelte +2 -0
  16. package/dist/components/RenameDialog.svelte +3 -0
  17. package/dist/components/csrf-context.d.ts +2 -0
  18. package/dist/components/csrf-context.js +2 -0
  19. package/dist/components/index.d.ts +1 -0
  20. package/dist/components/index.js +1 -0
  21. package/dist/log/emit.d.ts +14 -0
  22. package/dist/log/emit.js +18 -0
  23. package/dist/log/events.d.ts +1 -0
  24. package/dist/log/events.js +1 -0
  25. package/dist/log/index.d.ts +3 -0
  26. package/dist/log/index.js +1 -0
  27. package/dist/sveltekit/auth-routes.d.ts +2 -0
  28. package/dist/sveltekit/auth-routes.js +22 -5
  29. package/dist/sveltekit/content-routes.d.ts +6 -4
  30. package/dist/sveltekit/content-routes.js +23 -0
  31. package/dist/sveltekit/csrf-required-page.d.ts +2 -0
  32. package/dist/sveltekit/csrf-required-page.js +25 -0
  33. package/dist/sveltekit/csrf.d.ts +18 -0
  34. package/dist/sveltekit/csrf.js +60 -0
  35. package/dist/sveltekit/guard.js +35 -6
  36. package/dist/sveltekit/https-required-page.js +10 -191
  37. package/dist/sveltekit/nav-routes.js +5 -0
  38. package/dist/sveltekit/static-admin-page.d.ts +11 -0
  39. package/dist/sveltekit/static-admin-page.js +195 -0
  40. package/package.json +1 -1
  41. package/src/lib/auth/crypto.ts +13 -0
  42. package/src/lib/components/AdminLayout.svelte +8 -1
  43. package/src/lib/components/ConceptList.svelte +3 -0
  44. package/src/lib/components/ConfirmPage.svelte +4 -2
  45. package/src/lib/components/CsrfField.svelte +20 -0
  46. package/src/lib/components/DeleteDialog.svelte +2 -0
  47. package/src/lib/components/EditPage.svelte +2 -0
  48. package/src/lib/components/LoginPage.svelte +4 -2
  49. package/src/lib/components/ManageEditors.svelte +4 -0
  50. package/src/lib/components/NavTree.svelte +2 -0
  51. package/src/lib/components/RenameDialog.svelte +3 -0
  52. package/src/lib/components/csrf-context.ts +2 -0
  53. package/src/lib/components/index.ts +1 -0
  54. package/src/lib/log/emit.ts +42 -0
  55. package/src/lib/log/events.ts +13 -0
  56. package/src/lib/log/index.ts +3 -0
  57. package/src/lib/sveltekit/auth-routes.ts +25 -7
  58. package/src/lib/sveltekit/content-routes.ts +29 -2
  59. package/src/lib/sveltekit/csrf-required-page.ts +26 -0
  60. package/src/lib/sveltekit/csrf.ts +61 -0
  61. package/src/lib/sveltekit/guard.ts +43 -6
  62. package/src/lib/sveltekit/https-required-page.ts +10 -194
  63. package/src/lib/sveltekit/nav-routes.ts +5 -0
  64. package/src/lib/sveltekit/static-admin-page.ts +200 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,43 @@
2
2
 
3
3
  All notable changes to this project are recorded here, most recent first.
4
4
 
5
+ ## 0.36.0
6
+
7
+ cairn now emits structured diagnostic events. The engine had three bare `console.error` calls and no
8
+ queryable diagnostics. An internal logger assembles a JSON record for each event, with an envelope
9
+ (`level`, `event`, `timestamp`) and event-specific fields, and writes it to `console`. Cloudflare
10
+ Workers Logs ingests and indexes those records when a site sets `observability.enabled = true`, so
11
+ each field filters. The event vocabulary covers the auth flow, the commit pipeline, and the admin
12
+ guard's pre-resolve refusals. The records carry an editor's email for attribution and never carry a
13
+ magic-link token, a session id, or a magic-link's contents; a standing redaction test pins that.
14
+
15
+ The event names are a stable contract, so renaming one is a breaking change later. The full list, with
16
+ each event's level, trigger, and fields, is in the new [log events reference](docs/reference/log-events.md),
17
+ and the [read cairn's logs guide](docs/guides/read-cairn-logs.md) covers the one setup line and the
18
+ dashboard query.
19
+
20
+ Consumers may: set `observability.enabled = true` in `wrangler.jsonc` to read the events in Workers
21
+ Logs. The change is otherwise additive and needs no action.
22
+
23
+ ## 0.35.0
24
+
25
+ cairn now owns CSRF for the admin. A consuming site disables SvelteKit's global `checkOrigin`, and
26
+ cairn's guard becomes the single authority. Every unsafe admin form POST must carry a valid
27
+ `__Host-cairn_csrf` double-submit token (the cookie name is `cairn_csrf` bare on local http). The
28
+ token is issued lazily and stably by the login, confirm, and admin shell loads, rendered as a hidden
29
+ `csrf` field by the new `CsrfField` export, and validated centrally in the guard. A failed check
30
+ serves a branded 403 page in place of the framework's raw text. The session cookie stays a second
31
+ layer. The token tolerates a missing `Origin`, so the JS-free magic-link sign-in works from a
32
+ browser that omits the header. The guard restores the strict `Origin === url.origin` check for the
33
+ site's own non-admin form POSTs, so handing cairn the admin authority is not a net loss elsewhere.
34
+
35
+ The `CsrfField` component is a new export from `@glw907/cairn-cms/components`. The `LoginPage` and
36
+ `ConfirmPage` data now carries `csrf`, and `AdminLayout`'s `LayoutData` now carries `csrf`, which the
37
+ shell provides to its descendant forms through context.
38
+
39
+ Consumers must: set `csrf: { checkOrigin: false }` in `kit` in `svelte.config.js`. Without it the
40
+ framework's global check rejects the JS-free auth POST and the admin sign-in fails.
41
+
5
42
  ## 0.34.0
6
43
 
7
44
  A deployed admin request that arrives over http now gets a clear, branded help page instead of the
@@ -4,6 +4,8 @@
4
4
  * dev the prefix is dropped, since __Host- requires Secure and the dev cookie cannot set it.
5
5
  */
6
6
  export declare function sessionCookieName(secure: boolean): string;
7
+ /** The CSRF cookie name, mirroring sessionCookieName: __Host- on https, bare on local http. */
8
+ export declare function csrfCookieName(secure: boolean): string;
7
9
  /** Magic-link tokens live 10 minutes. */
8
10
  export declare const TOKEN_TTL_MS: number;
9
11
  /** Sessions live 30 days. */
@@ -14,5 +16,7 @@ export declare const SEND_COOLDOWN_MS: number;
14
16
  export declare function generateToken(): string;
15
17
  /** A fresh 256-bit session id, url-safe. */
16
18
  export declare function generateSessionId(): string;
19
+ /** A fresh 256-bit double-submit token, url-safe. */
20
+ export declare function generateCsrfToken(): string;
17
21
  /** The lowercase hex SHA-256 of a token, for storage and lookup. */
18
22
  export declare function hashToken(token: string): Promise<string>;
@@ -11,6 +11,12 @@ const COOKIE_BASE = 'cairn_session';
11
11
  export function sessionCookieName(secure) {
12
12
  return secure ? `__Host-${COOKIE_BASE}` : COOKIE_BASE;
13
13
  }
14
+ /** The CSRF double-submit cookie base name, __Host- prefixed when the cookie is Secure. */
15
+ const CSRF_COOKIE_BASE = 'cairn_csrf';
16
+ /** The CSRF cookie name, mirroring sessionCookieName: __Host- on https, bare on local http. */
17
+ export function csrfCookieName(secure) {
18
+ return secure ? `__Host-${CSRF_COOKIE_BASE}` : CSRF_COOKIE_BASE;
19
+ }
14
20
  /** Magic-link tokens live 10 minutes. */
15
21
  export const TOKEN_TTL_MS = 10 * 60 * 1000;
16
22
  /** Sessions live 30 days. */
@@ -33,6 +39,10 @@ export function generateToken() {
33
39
  export function generateSessionId() {
34
40
  return randomBase64Url(32);
35
41
  }
42
+ /** A fresh 256-bit double-submit token, url-safe. */
43
+ export function generateCsrfToken() {
44
+ return randomBase64Url(32);
45
+ }
36
46
  /** The lowercase hex SHA-256 of a token, for storage and lookup. */
37
47
  export async function hashToken(token) {
38
48
  const data = new TextEncoder().encode(token);
@@ -7,8 +7,10 @@ flipped by the topbar toggle) and imports the self-contained Warm Stone theme, s
7
7
  identical on every host regardless of the site's own theme.
8
8
  -->
9
9
  <script lang="ts">
10
- import { onMount, untrack, type Component, type Snippet } from 'svelte';
10
+ import { onMount, setContext, untrack, type Component, type Snippet } from 'svelte';
11
11
  import type { LayoutData } from '../sveltekit/content-routes.js';
12
+ import CsrfField from './CsrfField.svelte';
13
+ import { CSRF_CONTEXT_KEY } from './csrf-context.js';
12
14
  import { MenuIcon, LogOutIcon, SunIcon, MoonIcon, ChevronRightIcon, SearchIcon } from './admin-icons.js';
13
15
  import CairnLogo from './CairnLogo.svelte';
14
16
  import { cairnFaviconHref } from './cairn-favicon.js';
@@ -30,6 +32,10 @@ identical on every host regardless of the site's own theme.
30
32
 
31
33
  let { data, children }: Props = $props();
32
34
 
35
+ // Hand descendant forms a live getter for the CSRF token layoutLoad issued, so the field stays
36
+ // correct even if the token ever rotates mid-session.
37
+ setContext(CSRF_CONTEXT_KEY, () => data.csrf);
38
+
33
39
  // Persist an admin preference for a year, path-scoped to /admin so the cookie never reaches the
34
40
  // host's own pages.
35
41
  function writeAdminCookie(name: string, value: string) {
@@ -397,6 +403,7 @@ identical on every host regardless of the site's own theme.
397
403
  </div>
398
404
  </div>
399
405
  <form method="POST" action="/admin/auth/logout" class="mt-4">
406
+ <CsrfField token={data.csrf} />
400
407
  <button type="submit" class="btn btn-ghost btn-sm btn-block justify-start">
401
408
  <LogOutIcon class="h-4 w-4" /> Sign out
402
409
  </button>
@@ -9,6 +9,7 @@ content sizes. The header New button opens a dialog holding the create form.
9
9
  import { slugify } from '../content/ids.js';
10
10
  import type { EntrySummary, ListData } from '../sveltekit/content-routes.js';
11
11
  import type { InboundLink } from '../content/manifest.js';
12
+ import CsrfField from './CsrfField.svelte';
12
13
  import DeleteDialog from './DeleteDialog.svelte';
13
14
  import CairnLogo from './CairnLogo.svelte';
14
15
  import { SearchIcon, ArrowUpIcon, ArrowDownIcon, ChevronsUpDownIcon, ChevronLeftIcon, ChevronRightIcon, PlusIcon, Trash2Icon } from './admin-icons.js';
@@ -202,6 +203,7 @@ content sizes. The header New button opens a dialog holding the create form.
202
203
  <DeleteDialog conceptId={data.conceptId} id={entry.id} label={data.label} inboundLinks={deleteRefused.inboundLinks} />
203
204
  {:else}
204
205
  <form method="POST" action="?/delete">
206
+ <CsrfField />
205
207
  <input type="hidden" name="id" value={entry.id} />
206
208
  <button type="submit" class="btn btn-ghost btn-sm" aria-label="Delete {entry.title}">
207
209
  <Trash2Icon class="h-4 w-4 text-error" />
@@ -246,6 +248,7 @@ content sizes. The header New button opens a dialog holding the create form.
246
248
  <button type="button" class="btn btn-ghost btn-sm" aria-label="Close" onclick={() => createDialog?.close()}>✕</button>
247
249
  </div>
248
250
  <form method="POST" action="?/create" onsubmit={() => (creating = true)} class="flex flex-col gap-3">
251
+ <CsrfField />
249
252
  <label class="flex flex-col gap-1">
250
253
  <span class="text-sm font-medium">Title</span>
251
254
  <input class="input w-full" name="title" bind:value={title} required />
@@ -6,11 +6,12 @@ in a hidden field and consumes nothing; only the explicit POST verifies (spec §
6
6
  <script lang="ts">
7
7
  import './cairn-admin.css';
8
8
  import CairnLogo from './CairnLogo.svelte';
9
+ import CsrfField from './CsrfField.svelte';
9
10
  import { cairnFaviconHref } from './cairn-favicon.js';
10
11
 
11
12
  interface Props {
12
- /** The confirm load's data: the token to submit, the site name, and an optional error. */
13
- data: { token: string; siteName: string; error: string | null };
13
+ /** The confirm load's data: the token to submit, the site name, an optional error, the CSRF token. */
14
+ data: { token: string; siteName: string; error: string | null; csrf: string };
14
15
  }
15
16
 
16
17
  let { data }: Props = $props();
@@ -41,6 +42,7 @@ in a hidden field and consumes nothing; only the explicit POST verifies (spec §
41
42
  <p class="mt-1 mb-5 text-sm text-[var(--color-muted)]">Confirm to finish signing in to {data.siteName}.</p>
42
43
  <form method="POST">
43
44
  <input type="hidden" name="token" value={data.token} />
45
+ <CsrfField token={data.csrf} />
44
46
  <button type="submit" class="btn btn-primary btn-block">Confirm sign-in</button>
45
47
  </form>
46
48
  {/if}
@@ -1,10 +1,11 @@
1
1
  import './cairn-admin.css';
2
2
  interface Props {
3
- /** The confirm load's data: the token to submit, the site name, and an optional error. */
3
+ /** The confirm load's data: the token to submit, the site name, an optional error, the CSRF token. */
4
4
  data: {
5
5
  token: string;
6
6
  siteName: string;
7
7
  error: string | null;
8
+ csrf: string;
8
9
  };
9
10
  }
10
11
  /**
@@ -0,0 +1,20 @@
1
+ <!--
2
+ @component
3
+ A hidden CSRF double-submit field for an admin form. Pass `token` directly (the pre-auth pages do),
4
+ or omit it inside the authed shell, where AdminLayout provides the token through context. A form that
5
+ omits this field fails the guard's token check, which is the intended fail-closed signal.
6
+ -->
7
+ <script lang="ts">
8
+ import { getContext } from 'svelte';
9
+ import { CSRF_CONTEXT_KEY } from './csrf-context.js';
10
+
11
+ interface Props {
12
+ /** The CSRF token. Falls back to the admin context when omitted. */
13
+ token?: string;
14
+ }
15
+ let { token }: Props = $props();
16
+ const fromContext = getContext<(() => string) | undefined>(CSRF_CONTEXT_KEY);
17
+ const value = $derived(token ?? fromContext?.() ?? '');
18
+ </script>
19
+
20
+ <input type="hidden" name="csrf" value={value} />
@@ -0,0 +1,12 @@
1
+ interface Props {
2
+ /** The CSRF token. Falls back to the admin context when omitted. */
3
+ token?: string;
4
+ }
5
+ /**
6
+ * A hidden CSRF double-submit field for an admin form. Pass `token` directly (the pre-auth pages do),
7
+ * or omit it inside the authed shell, where AdminLayout provides the token through context. A form that
8
+ * omits this field fails the guard's token check, which is the intended fail-closed signal.
9
+ */
10
+ declare const CsrfField: import("svelte").Component<Props, {}, "">;
11
+ type CsrfField = ReturnType<typeof CsrfField>;
12
+ export default CsrfField;
@@ -6,6 +6,7 @@ each linking to its edit page, so the author repoints or removes those links fir
6
6
  <dialog>, following the LinkPicker a11y conventions.
7
7
  -->
8
8
  <script lang="ts">
9
+ import CsrfField from './CsrfField.svelte';
9
10
  import type { InboundLink } from '../content/manifest.js';
10
11
 
11
12
  interface Props {
@@ -68,6 +69,7 @@ each linking to its edit page, so the author repoints or removes those links fir
68
69
  {:else}
69
70
  <p class="mb-3 text-sm">This cannot be undone.</p>
70
71
  <form method="POST" action="?/delete" class="flex justify-end gap-2">
72
+ <CsrfField />
71
73
  <input type="hidden" name="concept" value={conceptId} />
72
74
  <input type="hidden" name="id" value={id} />
73
75
  <button type="button" class="btn btn-sm" onclick={close}>Cancel</button>
@@ -6,6 +6,7 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
6
6
  -->
7
7
  <script lang="ts">
8
8
  import { untrack } from 'svelte';
9
+ import CsrfField from './CsrfField.svelte';
9
10
  import MarkdownEditor from './MarkdownEditor.svelte';
10
11
  import ComponentInsertDialog from './ComponentInsertDialog.svelte';
11
12
  import LinkPicker from './LinkPicker.svelte';
@@ -221,6 +222,7 @@ markdown editor and a live, design-accurate preview. The whole surface is one fo
221
222
  {/if}
222
223
 
223
224
  <form method="POST" action="?/save" onsubmit={() => (saving = true)} class="lg:grid lg:grid-cols-[1fr_20rem] lg:gap-6">
225
+ <CsrfField />
224
226
  {#if data.isNew}<input type="hidden" name="new" value="1" />{/if}
225
227
 
226
228
  <div class="lg:order-1">
@@ -8,12 +8,13 @@ the allowlist, so the page never leaks membership (spec §7.1).
8
8
  import './cairn-admin.css';
9
9
  import { onMount } from 'svelte';
10
10
  import CairnLogo from './CairnLogo.svelte';
11
+ import CsrfField from './CsrfField.svelte';
11
12
  import { cairnFaviconHref } from './cairn-favicon.js';
12
13
  import { warnIfChromeWrapped } from './chrome-guard.js';
13
14
 
14
15
  interface Props {
15
- /** The login load's data: the site name and an optional error. */
16
- data: { siteName: string; error: string | null };
16
+ /** The login load's data: the site name, an optional error, and the CSRF token. */
17
+ data: { siteName: string; error: string | null; csrf: string };
17
18
  /** The action result: `sent` is true once a request was accepted. */
18
19
  form: { sent?: boolean } | null;
19
20
  }
@@ -54,6 +55,7 @@ the allowlist, so the page never leaks membership (spec §7.1).
54
55
  <div role="alert" class="alert alert-error mb-3 text-sm">That link expired. Request a new one below.</div>
55
56
  {/if}
56
57
  <form method="POST" class="flex flex-col gap-3">
58
+ <CsrfField token={data.csrf} />
57
59
  <label class="flex flex-col gap-1">
58
60
  <span class="text-sm font-medium">Email</span>
59
61
  <input
@@ -1,9 +1,10 @@
1
1
  import './cairn-admin.css';
2
2
  interface Props {
3
- /** The login load's data: the site name and an optional error. */
3
+ /** The login load's data: the site name, an optional error, and the CSRF token. */
4
4
  data: {
5
5
  siteName: string;
6
6
  error: string | null;
7
+ csrf: string;
7
8
  };
8
9
  /** The action result: `sent` is true once a request was accepted. */
9
10
  form: {
@@ -6,6 +6,7 @@ last-owner anti-lockout rule itself is enforced server-side (editors-routes). Ac
6
6
  named `?/setRole`, `?/remove`, and `?/add` actions.
7
7
  -->
8
8
  <script lang="ts">
9
+ import CsrfField from './CsrfField.svelte';
9
10
  import type { Editor } from '../auth/types.js';
10
11
 
11
12
  interface Props {
@@ -45,6 +46,7 @@ named `?/setRole`, `?/remove`, and `?/add` actions.
45
46
  </td>
46
47
  <td class="flex justify-end gap-2">
47
48
  <form method="POST" action="?/setRole">
49
+ <CsrfField />
48
50
  <input type="hidden" name="email" value={editor.email} />
49
51
  <input type="hidden" name="role" value={editor.role === 'owner' ? 'editor' : 'owner'} />
50
52
  <button type="submit" class="btn btn-ghost btn-xs" disabled={isSelf} aria-label={`Toggle role for ${editor.displayName}`}>
@@ -52,6 +54,7 @@ named `?/setRole`, `?/remove`, and `?/add` actions.
52
54
  </button>
53
55
  </form>
54
56
  <form method="POST" action="?/remove">
57
+ <CsrfField />
55
58
  <input type="hidden" name="email" value={editor.email} />
56
59
  <button type="submit" class="btn btn-ghost btn-xs text-error" disabled={isSelf} aria-label={`Remove ${editor.displayName}`}>
57
60
  Remove
@@ -65,6 +68,7 @@ named `?/setRole`, `?/remove`, and `?/add` actions.
65
68
  </div>
66
69
 
67
70
  <form method="POST" action="?/add" class="rounded-box border border-[var(--cairn-card-border)] bg-base-100 grid gap-3 p-4 shadow-[var(--cairn-shadow)] sm:grid-cols-[1fr_1fr_auto_auto] sm:items-end">
71
+ <CsrfField />
68
72
  <label class="flex flex-col gap-1">
69
73
  <span class="text-sm font-medium">Name</span>
70
74
  <input class="input" name="name" aria-label="Name" required />
@@ -8,6 +8,7 @@ validates on save.
8
8
  -->
9
9
  <script lang="ts">
10
10
  import { untrack } from 'svelte';
11
+ import CsrfField from './CsrfField.svelte';
11
12
  import { SortableList, sortItems } from '@rodrigodagostino/svelte-sortable-list';
12
13
  import type { SortableList as SortableListNS } from '@rodrigodagostino/svelte-sortable-list';
13
14
  import '@rodrigodagostino/svelte-sortable-list/styles.css';
@@ -98,6 +99,7 @@ validates on save.
98
99
  {/if}
99
100
 
100
101
  <form method="POST" action="?/save">
102
+ <CsrfField />
101
103
  <input type="hidden" name="tree" value={treeJson} />
102
104
 
103
105
  <div class="mb-2">
@@ -6,6 +6,8 @@ dated post keeps its date; only the slug changes. Built on a native <dialog>, fo
6
6
  DeleteDialog a11y conventions.
7
7
  -->
8
8
  <script lang="ts">
9
+ import CsrfField from './CsrfField.svelte';
10
+
9
11
  interface Props {
10
12
  /** The concept this entry belongs to, e.g. "posts". Posted with the confirm. */
11
13
  conceptId: string;
@@ -50,6 +52,7 @@ DeleteDialog a11y conventions.
50
52
  <button type="button" class="btn btn-ghost btn-sm" aria-label="Close" onclick={close}>✕</button>
51
53
  </div>
52
54
  <form method="POST" action="?/rename" class="flex flex-col gap-3">
55
+ <CsrfField />
53
56
  <input type="hidden" name="concept" value={conceptId} />
54
57
  <input type="hidden" name="id" value={id} />
55
58
  <label class="flex flex-col gap-1">
@@ -0,0 +1,2 @@
1
+ /** The Svelte context key AdminLayout uses to hand a CSRF-token getter to descendant admin forms. */
2
+ export declare const CSRF_CONTEXT_KEY = "cairn:csrf";
@@ -0,0 +1,2 @@
1
+ /** The Svelte context key AdminLayout uses to hand a CSRF-token getter to descendant admin forms. */
2
+ export const CSRF_CONTEXT_KEY = 'cairn:csrf';
@@ -1,6 +1,7 @@
1
1
  export { default as AdminLayout } from './AdminLayout.svelte';
2
2
  export { default as LoginPage } from './LoginPage.svelte';
3
3
  export { default as ConfirmPage } from './ConfirmPage.svelte';
4
+ export { default as CsrfField } from './CsrfField.svelte';
4
5
  export { default as ConceptList } from './ConceptList.svelte';
5
6
  export { default as EditPage } from './EditPage.svelte';
6
7
  export { default as ManageEditors } from './ManageEditors.svelte';
@@ -3,6 +3,7 @@
3
3
  export { default as AdminLayout } from './AdminLayout.svelte';
4
4
  export { default as LoginPage } from './LoginPage.svelte';
5
5
  export { default as ConfirmPage } from './ConfirmPage.svelte';
6
+ export { default as CsrfField } from './CsrfField.svelte';
6
7
  export { default as ConceptList } from './ConceptList.svelte';
7
8
  export { default as EditPage } from './EditPage.svelte';
8
9
  export { default as ManageEditors } from './ManageEditors.svelte';
@@ -0,0 +1,14 @@
1
+ import type { CairnLogEvent } from './events.js';
2
+ export type LogLevel = 'info' | 'warn' | 'error';
3
+ export interface LogRecord {
4
+ level: LogLevel;
5
+ event: CairnLogEvent;
6
+ timestamp: string;
7
+ [field: string]: unknown;
8
+ }
9
+ export interface Logger {
10
+ info(event: CairnLogEvent, fields?: Record<string, unknown>): void;
11
+ warn(event: CairnLogEvent, fields?: Record<string, unknown>): void;
12
+ error(event: CairnLogEvent, fields?: Record<string, unknown>): void;
13
+ }
14
+ export declare const log: Logger;
@@ -0,0 +1,18 @@
1
+ const sinkByLevel = {
2
+ info: (record) => console.log(record),
3
+ warn: (record) => console.warn(record),
4
+ error: (record) => console.error(record),
5
+ };
6
+ function buildRecord(level, event, fields) {
7
+ // The envelope keys are written last, so a stray field named level/event/timestamp cannot
8
+ // corrupt the record shape a subscriber relies on.
9
+ return { ...fields, level, event, timestamp: new Date().toISOString() };
10
+ }
11
+ function emit(level, event, fields = {}) {
12
+ sinkByLevel[level](buildRecord(level, event, fields));
13
+ }
14
+ export const log = {
15
+ info: (event, fields) => emit('info', event, fields),
16
+ warn: (event, fields) => emit('warn', event, fields),
17
+ error: (event, fields) => emit('error', event, fields),
18
+ };
@@ -0,0 +1 @@
1
+ export type CairnLogEvent = 'auth.link.requested' | 'auth.link.send_failed' | 'auth.token.minted' | 'auth.token.confirmed' | 'auth.session.created' | 'auth.session.destroyed' | 'commit.succeeded' | 'commit.failed' | 'guard.rejected';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export { log } from './emit.js';
2
+ export type { Logger, LogLevel, LogRecord } from './emit.js';
3
+ export type { CairnLogEvent } from './events.js';
@@ -0,0 +1 @@
1
+ export { log } from './emit.js';
@@ -8,6 +8,7 @@ export declare function createAuthRoutes(config: AuthRoutesConfig): {
8
8
  loginLoad: (event: RequestContext) => {
9
9
  siteName: string;
10
10
  error: string | null;
11
+ csrf: string;
11
12
  };
12
13
  requestAction: (event: RequestContext) => Promise<{
13
14
  sent: true;
@@ -16,6 +17,7 @@ export declare function createAuthRoutes(config: AuthRoutesConfig): {
16
17
  token: string;
17
18
  siteName: string;
18
19
  error: string | null;
20
+ csrf: string;
19
21
  };
20
22
  confirmAction: (event: RequestContext) => Promise<never>;
21
23
  logoutAction: (event: RequestContext) => Promise<never>;
@@ -6,6 +6,8 @@ import { requireOrigin, requireDb } from '../env.js';
6
6
  import { generateToken, generateSessionId, hashToken, TOKEN_TTL_MS, SESSION_TTL_MS, SEND_COOLDOWN_MS, sessionCookieName, } from '../auth/crypto.js';
7
7
  import { findEditor, issueToken, consumeToken, createSession, deleteSession, recentlyIssued } from '../auth/store.js';
8
8
  import { buildMagicLinkMessage, cloudflareSend } from '../email.js';
9
+ import { issueCsrfToken } from './csrf.js';
10
+ import { log } from '../log/index.js';
9
11
  export function createAuthRoutes(config) {
10
12
  const send = config.send ?? cloudflareSend;
11
13
  /**
@@ -19,6 +21,10 @@ export function createAuthRoutes(config) {
19
21
  const db = requireDb(env);
20
22
  const form = await event.request.formData();
21
23
  const email = String(form.get('email') ?? '').trim().toLowerCase();
24
+ // `email` here is unvalidated request input logged before the allowlist check, so bound the
25
+ // logged value to the RFC 5321 maximum to cap an abusive record's size. A real editor's address
26
+ // fits well under this; only a junk payload is truncated.
27
+ log.info('auth.link.requested', { email: email.slice(0, 320) });
22
28
  const editor = email ? await findEditor(db, email) : null;
23
29
  if (editor) {
24
30
  const now = Date.now();
@@ -28,12 +34,13 @@ export function createAuthRoutes(config) {
28
34
  if (!(await recentlyIssued(db, email, now - SEND_COOLDOWN_MS))) {
29
35
  const token = generateToken();
30
36
  await issueToken(db, email, await hashToken(token), now + TOKEN_TTL_MS, now);
37
+ log.info('auth.token.minted', { email, expiresAt: now + TOKEN_TTL_MS });
31
38
  const link = `${origin}/admin/auth/confirm?token=${encodeURIComponent(token)}`;
32
39
  // The token row is the security-critical write the email depends on, so it is awaited. The
33
40
  // send is a post-response side effect, handed to waitUntil so a slow email provider does not
34
41
  // hold the response. An absent waitUntil (local dev, tests) falls back to await. A send
35
42
  // failure is logged so observability survives a backgrounded send.
36
- const sending = send(env, buildMagicLinkMessage({ to: email, branding: config.branding, link })).catch((err) => console.error('cairn: magic-link send failed', err));
43
+ const sending = send(env, buildMagicLinkMessage({ to: email, branding: config.branding, link })).catch((err) => log.error('auth.link.send_failed', { email, error: String(err) }));
37
44
  // adapter-cloudflare exposes the ExecutionContext as platform.ctx; platform.context is a
38
45
  // deprecated alias kept as a fallback so an adapter that drops it keeps backgrounding.
39
46
  const ctx = event.platform?.ctx ?? event.platform?.context;
@@ -45,13 +52,18 @@ export function createAuthRoutes(config) {
45
52
  }
46
53
  return { sent: true };
47
54
  }
48
- /** GET /admin/login. Public. Carries the site name and an optional `?error` for the form. */
55
+ /** GET /admin/login. Public. Carries the site name, an optional `?error`, and the CSRF token. */
49
56
  function loginLoad(event) {
50
- return { siteName: config.branding.siteName, error: event.url.searchParams.get('error') };
57
+ return {
58
+ siteName: config.branding.siteName,
59
+ error: event.url.searchParams.get('error'),
60
+ csrf: issueCsrfToken(event),
61
+ };
51
62
  }
52
63
  /**
53
64
  * GET /admin/auth/confirm. Renders the confirm page and consumes nothing; only the POST
54
- * verifies. Sets Referrer-Policy: no-referrer so the token does not leak to a referrer.
65
+ * verifies. Sets Referrer-Policy: no-referrer so the token does not leak to a referrer, and
66
+ * issues the CSRF token so the confirm form can render the hidden field.
55
67
  */
56
68
  function confirmLoad(event) {
57
69
  event.setHeaders({ 'Referrer-Policy': 'no-referrer' });
@@ -59,6 +71,7 @@ export function createAuthRoutes(config) {
59
71
  token: event.url.searchParams.get('token') ?? '',
60
72
  siteName: config.branding.siteName,
61
73
  error: event.url.searchParams.get('error'),
74
+ csrf: issueCsrfToken(event),
62
75
  };
63
76
  }
64
77
  /**
@@ -76,8 +89,10 @@ export function createAuthRoutes(config) {
76
89
  const email = await consumeToken(db, await hashToken(token), now);
77
90
  if (!email)
78
91
  throw redirect(303, '/admin/login?error=expired');
92
+ log.info('auth.token.confirmed', { email });
79
93
  const id = generateSessionId();
80
94
  await createSession(db, id, email, now + SESSION_TTL_MS, now);
95
+ log.info('auth.session.created', { email });
81
96
  const secure = event.url.protocol === 'https:';
82
97
  event.cookies.set(sessionCookieName(secure), id, {
83
98
  path: '/',
@@ -94,8 +109,10 @@ export function createAuthRoutes(config) {
94
109
  const db = requireDb(event.platform?.env ?? {});
95
110
  const name = sessionCookieName(event.url.protocol === 'https:');
96
111
  const id = event.cookies.get(name);
97
- if (id)
112
+ if (id) {
98
113
  await deleteSession(db, id);
114
+ log.info('auth.session.destroyed');
115
+ }
99
116
  event.cookies.delete(name, { path: '/' });
100
117
  throw redirect(303, '/admin/login');
101
118
  }
@@ -1,6 +1,7 @@
1
1
  import { fail } from '@sveltejs/kit';
2
2
  import { type GithubKeyEnv } from '../github/credentials.js';
3
3
  import { type LinkTarget, type InboundLink } from '../content/manifest.js';
4
+ import type { CookieJar } from './types.js';
4
5
  import type { CairnRuntime, FrontmatterField } from '../content/types.js';
5
6
  import type { Editor, Role } from '../auth/types.js';
6
7
  /** A sidebar concept entry: just enough to render the nav without shipping validators to the client. */
@@ -26,6 +27,8 @@ export interface LayoutData {
26
27
  /** The nav group labels the user has collapsed, from the persisted cookie. Read at SSR so a
27
28
  * collapsed group renders collapsed with no flash. Empty when none are collapsed. */
28
29
  collapsedNav: string[];
30
+ /** The session's CSRF double-submit token, rendered as a hidden field in every admin form. */
31
+ csrf: string;
29
32
  }
30
33
  /** One row in a concept's list view. */
31
34
  export interface EntrySummary {
@@ -78,10 +81,9 @@ export interface ContentEvent {
78
81
  platform?: {
79
82
  env?: GithubKeyEnv;
80
83
  };
81
- /** SvelteKit's cookie jar; the layout load reads the persisted admin theme. Optional for non-route callers. */
82
- cookies?: {
83
- get(name: string): string | undefined;
84
- };
84
+ /** SvelteKit's cookie jar. The layout load reads the persisted admin theme and issues the CSRF
85
+ * token. Optional for non-route callers. */
86
+ cookies?: CookieJar;
85
87
  }
86
88
  /** Injectable dependencies; tests stub the token mint to avoid signing a real key. */
87
89
  export interface ContentRoutesDeps {