@glw907/cairn-cms 0.1.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -0
  3. package/dist/adapter.d.ts +60 -0
  4. package/dist/adapter.d.ts.map +1 -0
  5. package/dist/adapter.js +30 -0
  6. package/dist/auth.d.ts +16 -0
  7. package/dist/auth.d.ts.map +1 -0
  8. package/dist/auth.js +93 -0
  9. package/dist/carta.d.ts +39 -0
  10. package/dist/carta.d.ts.map +1 -0
  11. package/dist/carta.js +30 -0
  12. package/dist/components/AdminLayout.svelte +18 -0
  13. package/dist/components/AdminLayout.svelte.d.ts +8 -0
  14. package/dist/components/AdminLayout.svelte.d.ts.map +1 -0
  15. package/dist/components/AdminList.svelte +41 -0
  16. package/dist/components/AdminList.svelte.d.ts +13 -0
  17. package/dist/components/AdminList.svelte.d.ts.map +1 -0
  18. package/dist/components/EditPage.svelte +125 -0
  19. package/dist/components/EditPage.svelte.d.ts +13 -0
  20. package/dist/components/EditPage.svelte.d.ts.map +1 -0
  21. package/dist/components/LoginPage.svelte +47 -0
  22. package/dist/components/LoginPage.svelte.d.ts +11 -0
  23. package/dist/components/LoginPage.svelte.d.ts.map +1 -0
  24. package/dist/components/index.d.ts +5 -0
  25. package/dist/components/index.d.ts.map +1 -0
  26. package/dist/components/index.js +6 -0
  27. package/dist/content.d.ts +3 -0
  28. package/dist/content.d.ts.map +1 -0
  29. package/dist/content.js +10 -0
  30. package/dist/email.d.ts +14 -0
  31. package/dist/email.d.ts.map +1 -0
  32. package/dist/email.js +17 -0
  33. package/dist/github.d.ts +52 -0
  34. package/dist/github.d.ts.map +1 -0
  35. package/dist/github.js +136 -0
  36. package/dist/index.d.ts +7 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +7 -0
  39. package/dist/sveltekit/index.d.ts +91 -0
  40. package/dist/sveltekit/index.d.ts.map +1 -0
  41. package/dist/sveltekit/index.js +163 -0
  42. package/dist/utils.d.ts +3 -0
  43. package/dist/utils.d.ts.map +1 -0
  44. package/dist/utils.js +11 -0
  45. package/package.json +79 -0
  46. package/src/lib/adapter.ts +110 -0
  47. package/src/lib/auth.ts +130 -0
  48. package/src/lib/carta.ts +59 -0
  49. package/src/lib/components/AdminLayout.svelte +18 -0
  50. package/src/lib/components/AdminList.svelte +41 -0
  51. package/src/lib/components/EditPage.svelte +125 -0
  52. package/src/lib/components/LoginPage.svelte +47 -0
  53. package/src/lib/components/index.ts +6 -0
  54. package/src/lib/content.ts +11 -0
  55. package/src/lib/email.ts +35 -0
  56. package/src/lib/github.ts +188 -0
  57. package/src/lib/index.ts +7 -0
  58. package/src/lib/sveltekit/index.ts +272 -0
  59. package/src/lib/utils.ts +12 -0
@@ -0,0 +1,188 @@
1
+ // cairn-core: read and write repository content through the GitHub API.
2
+ //
3
+ // Reads (Pass B) list a collection directory and fetch a file's raw markdown; the token
4
+ // is optional because ecnordic's repo is public. Writes (Pass C) mint a short-lived
5
+ // GitHub App installation token — App JWT (RS256) signed with Web Crypto, no octokit
6
+ // dependency — and commit through the contents API with author = editor, committer = the
7
+ // App (cairn-cms[bot]). The same token also lifts reads to the authenticated rate limit
8
+ // and unlocks private repos (e.g. 907-life).
9
+
10
+ import { bytesToB64url } from './utils';
11
+
12
+ export interface RepoRef {
13
+ owner: string;
14
+ repo: string;
15
+ branch: string;
16
+ }
17
+
18
+ /** A markdown file in a collection directory. `id` is the slug (filename without `.md`). */
19
+ export interface RepoFile {
20
+ id: string;
21
+ name: string;
22
+ path: string;
23
+ }
24
+
25
+ const API = 'https://api.github.com';
26
+
27
+ function ghHeaders(accept: string, token?: string): Record<string, string> {
28
+ const headers: Record<string, string> = {
29
+ Accept: accept,
30
+ 'User-Agent': 'cairn-cms',
31
+ 'X-GitHub-Api-Version': '2022-11-28',
32
+ };
33
+ if (token) headers.Authorization = `Bearer ${token}`;
34
+ return headers;
35
+ }
36
+
37
+ /** Build the contents-API URL for a repo path, pinned to the configured branch. */
38
+ export function contentsUrl(repo: RepoRef, path: string): string {
39
+ const clean = path.replace(/^\/+|\/+$/g, '');
40
+ return `${API}/repos/${repo.owner}/${repo.repo}/contents/${clean}?ref=${encodeURIComponent(repo.branch)}`;
41
+ }
42
+
43
+ interface ContentsEntry {
44
+ name: string;
45
+ path: string;
46
+ type: string;
47
+ }
48
+
49
+ /** Keep only markdown files from a contents-API directory listing, newest id first. */
50
+ export function markdownFiles(entries: ContentsEntry[]): RepoFile[] {
51
+ return entries
52
+ .filter((entry) => entry.type === 'file' && entry.name.endsWith('.md'))
53
+ .map((entry) => ({ id: entry.name.replace(/\.md$/, ''), name: entry.name, path: entry.path }))
54
+ .sort((a, b) => b.id.localeCompare(a.id));
55
+ }
56
+
57
+ /** List the markdown files in a collection directory. */
58
+ export async function listMarkdown(repo: RepoRef, dir: string, token?: string): Promise<RepoFile[]> {
59
+ const res = await fetch(contentsUrl(repo, dir), { headers: ghHeaders('application/vnd.github+json', token) });
60
+ if (!res.ok) throw new Error(`GitHub list ${dir} failed: ${res.status}`);
61
+ return markdownFiles((await res.json()) as ContentsEntry[]);
62
+ }
63
+
64
+ /** Fetch a file's raw markdown, or null if it does not exist. */
65
+ export async function readRaw(repo: RepoRef, path: string, token?: string): Promise<string | null> {
66
+ const res = await fetch(contentsUrl(repo, path), { headers: ghHeaders('application/vnd.github.raw', token) });
67
+ if (res.status === 404) return null;
68
+ if (!res.ok) throw new Error(`GitHub read ${path} failed: ${res.status}`);
69
+ return res.text();
70
+ }
71
+
72
+ // --- Write path: GitHub App auth + commit (Pass C) -------------------------------------
73
+
74
+ const encoder = new TextEncoder();
75
+
76
+ // TextEncoder/atob produce Uint8Arrays whose generic buffer type no longer satisfies
77
+ // Web Crypto's BufferSource under strict lib types; hand the underlying ArrayBuffer over.
78
+ function buf(bytes: Uint8Array): ArrayBuffer {
79
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
80
+ }
81
+
82
+ /** DER length octets for a value of `n` bytes (short form < 128, else long form). */
83
+ function derLength(n: number): number[] {
84
+ if (n < 0x80) return [n];
85
+ const out: number[] = [];
86
+ for (let v = n; v > 0; v >>= 8) out.unshift(v & 0xff);
87
+ return [0x80 | out.length, ...out];
88
+ }
89
+
90
+ // AlgorithmIdentifier for rsaEncryption (OID 1.2.840.113549.1.1.1) with NULL parameters.
91
+ const RSA_ALG_ID = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00];
92
+
93
+ /** Wrap a PKCS#1 RSAPrivateKey (DER) as PKCS#8 — the only RSA form Web Crypto importKey takes. */
94
+ function pkcs1ToPkcs8(pkcs1: Uint8Array): Uint8Array {
95
+ const octet = [0x04, ...derLength(pkcs1.length), ...pkcs1];
96
+ const body = [0x02, 0x01, 0x00, ...RSA_ALG_ID, ...octet];
97
+ return Uint8Array.from([0x30, ...derLength(body.length), ...body]);
98
+ }
99
+
100
+ /** Decode a PEM private key to PKCS#8 DER, converting from PKCS#1 (GitHub's format) if needed. */
101
+ function pemToPkcs8(pem: string): Uint8Array {
102
+ const b64 = pem.replace(/-----[^-]+-----/g, '').replace(/\s+/g, '');
103
+ const der = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
104
+ return pem.includes('RSA PRIVATE KEY') ? pkcs1ToPkcs8(der) : der;
105
+ }
106
+
107
+ /** Mint a GitHub App JWT (RS256), valid ~9 min, with `iat` backdated for clock skew. */
108
+ export async function appJwt(appId: string, privateKeyPem: string): Promise<string> {
109
+ const now = Math.floor(Date.now() / 1000);
110
+ const header = bytesToB64url(encoder.encode(JSON.stringify({ alg: 'RS256', typ: 'JWT' })));
111
+ const payload = bytesToB64url(encoder.encode(JSON.stringify({ iat: now - 60, exp: now + 540, iss: appId })));
112
+ const signingInput = `${header}.${payload}`;
113
+ const key = await crypto.subtle.importKey(
114
+ 'pkcs8',
115
+ buf(pemToPkcs8(privateKeyPem)),
116
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
117
+ false,
118
+ ['sign'],
119
+ );
120
+ const sig = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, buf(encoder.encode(signingInput)));
121
+ return `${signingInput}.${bytesToB64url(new Uint8Array(sig))}`;
122
+ }
123
+
124
+ export interface AppCredentials {
125
+ appId: string;
126
+ installationId: string;
127
+ /** The stored GITHUB_APP_PRIVATE_KEY_B64 — base64 of the PEM, single line. */
128
+ privateKeyB64: string;
129
+ }
130
+
131
+ /** Exchange the App JWT for a short-lived installation access token. */
132
+ export async function installationToken(creds: AppCredentials): Promise<string> {
133
+ const jwt = await appJwt(creds.appId, atob(creds.privateKeyB64));
134
+ const res = await fetch(`${API}/app/installations/${creds.installationId}/access_tokens`, {
135
+ method: 'POST',
136
+ headers: ghHeaders('application/vnd.github+json', jwt),
137
+ });
138
+ if (!res.ok) throw new Error(`GitHub installation token failed: ${res.status}`);
139
+ return ((await res.json()) as { token: string }).token;
140
+ }
141
+
142
+ /** Standard (padded) base64 of UTF-8 text — the encoding the contents API expects. */
143
+ function toBase64(text: string): string {
144
+ return btoa(Array.from(encoder.encode(text), (b) => String.fromCharCode(b)).join(''));
145
+ }
146
+
147
+ /** The current blob sha for a path, or null if the file does not yet exist. */
148
+ export async function fileSha(repo: RepoRef, path: string, token: string): Promise<string | null> {
149
+ const res = await fetch(contentsUrl(repo, path), { headers: ghHeaders('application/vnd.github+json', token) });
150
+ if (res.status === 404) return null;
151
+ if (!res.ok) throw new Error(`GitHub stat ${path} failed: ${res.status}`);
152
+ return ((await res.json()) as { sha: string }).sha;
153
+ }
154
+
155
+ export interface CommitAuthor {
156
+ name: string;
157
+ email: string;
158
+ }
159
+
160
+ /**
161
+ * Commit `content` to `path` on the configured branch via the contents API. Author is the
162
+ * editor; committer is omitted so GitHub attributes it to the App (cairn-cms[bot]). Updates
163
+ * the file in place when it exists (passing its sha), creates it otherwise. Returns the
164
+ * commit sha.
165
+ */
166
+ export async function commitFile(
167
+ repo: RepoRef,
168
+ path: string,
169
+ content: string,
170
+ opts: { message: string; author: CommitAuthor },
171
+ token: string,
172
+ ): Promise<string> {
173
+ const sha = await fileSha(repo, path, token);
174
+ const url = `${API}/repos/${repo.owner}/${repo.repo}/contents/${path.replace(/^\/+|\/+$/g, '')}`;
175
+ const res = await fetch(url, {
176
+ method: 'PUT',
177
+ headers: { ...ghHeaders('application/vnd.github+json', token), 'Content-Type': 'application/json' },
178
+ body: JSON.stringify({
179
+ message: opts.message,
180
+ content: toBase64(content),
181
+ branch: repo.branch,
182
+ author: opts.author,
183
+ ...(sha ? { sha } : {}),
184
+ }),
185
+ });
186
+ if (!res.ok) throw new Error(`GitHub commit ${path} failed: ${res.status} ${await res.text()}`);
187
+ return ((await res.json()) as { commit: { sha: string } }).commit.sha;
188
+ }
@@ -0,0 +1,7 @@
1
+ // cairn-cms public API. Consumers import everything from 'cairn-cms'.
2
+ export * from './auth';
3
+ export * from './email';
4
+ export * from './github';
5
+ export * from './carta';
6
+ export * from './content';
7
+ export * from './adapter';
@@ -0,0 +1,272 @@
1
+ // cairn-core: the SvelteKit route server logic, extracted so each site's `admin/**` route
2
+ // files are thin shims (`export const load = (event) => editLoad(event, cairn)`).
3
+ //
4
+ // SvelteKit's filesystem routing requires the route *files* to live in each site's
5
+ // `src/routes/`, but their bodies are identical across sites — only the adapter differs.
6
+ // These functions take the SvelteKit event (typed structurally, to avoid depending on the
7
+ // site-generated `App.*` ambient types) plus the site `CairnAdapter`, and throw
8
+ // `redirect`/`error` from `@sveltejs/kit`. That `@sveltejs/kit` is a peer dependency so the
9
+ // thrown objects share class identity with the host's runtime (else the redirect 500s).
10
+ import { redirect, error, type Cookies } from '@sveltejs/kit';
11
+ import type { KVNamespace } from '@cloudflare/workers-types';
12
+ import matter from 'gray-matter';
13
+ import {
14
+ createMagicLink,
15
+ redeemMagicToken,
16
+ createSession,
17
+ lookupEditor,
18
+ SESSION_COOKIE,
19
+ SESSION_MAX_AGE,
20
+ type Editor,
21
+ } from '../auth';
22
+ import { sendMagicLink, type EmailSender } from '../email';
23
+ import { listMarkdown, readRaw, commitFile, installationToken, type RepoFile } from '../github';
24
+ import { serializeMarkdown } from '../content';
25
+ import { findCollection, frontmatterFromForm, type CairnAdapter, type CairnField } from '../adapter';
26
+
27
+ /** The `platform.env` bindings the admin routes read. All optional — the handlers guard. */
28
+ export interface AdminEnv {
29
+ AUTH_KV?: KVNamespace;
30
+ MAGIC_LINK_SECRET?: string;
31
+ SESSION_SECRET?: string;
32
+ EMAIL?: EmailSender;
33
+ /** Overrides `url.origin` for the magic-link base (set in dev, unset in prod). */
34
+ PUBLIC_ORIGIN?: string;
35
+ GITHUB_APP_ID?: string;
36
+ GITHUB_APP_INSTALLATION_ID?: string;
37
+ GITHUB_APP_PRIVATE_KEY_B64?: string;
38
+ }
39
+
40
+ interface PlatformEvent {
41
+ platform?: { env?: AdminEnv };
42
+ }
43
+
44
+ const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
45
+
46
+ // ── /admin layout ──────────────────────────────────────────────────────────
47
+
48
+ export interface AdminLayoutData {
49
+ editor: Editor | null;
50
+ siteName: string;
51
+ }
52
+
53
+ /**
54
+ * Branding + session for every admin page. `siteName` flows from the adapter without pulling
55
+ * its plugin graph into client bundles — the import stays server-side in the layout load.
56
+ */
57
+ export function adminLayoutLoad(
58
+ event: { locals: { editor: Editor | null } },
59
+ adapter: CairnAdapter,
60
+ ): AdminLayoutData {
61
+ return { editor: event.locals.editor, siteName: adapter.siteName };
62
+ }
63
+
64
+ // ── /admin (content list) ────────────────────────────────────────────────────
65
+
66
+ export interface AdminCollectionList {
67
+ type: string;
68
+ label: string;
69
+ files: RepoFile[];
70
+ error?: string;
71
+ }
72
+
73
+ /** List every collection's markdown files. A failed listing degrades to an inline error. */
74
+ export async function adminListLoad(adapter: CairnAdapter): Promise<{ collections: AdminCollectionList[] }> {
75
+ const collections = await Promise.all(
76
+ adapter.collections.map(async ({ type, label, dir }): Promise<AdminCollectionList> => {
77
+ try {
78
+ return { type, label, files: await listMarkdown(adapter.backend, dir) };
79
+ } catch (err) {
80
+ // A failed listing (rate limit, network) shouldn't 500 the whole admin.
81
+ return { type, label, files: [], error: err instanceof Error ? err.message : 'Failed to load' };
82
+ }
83
+ }),
84
+ );
85
+ return { collections };
86
+ }
87
+
88
+ // ── /admin/login ──────────────────────────────────────────────────────────────
89
+
90
+ export interface LoginData {
91
+ sent: boolean;
92
+ error: string | null;
93
+ }
94
+
95
+ export function loginLoad(event: { url: URL }): LoginData {
96
+ return {
97
+ sent: event.url.searchParams.get('sent') === '1',
98
+ error: event.url.searchParams.get('error'),
99
+ };
100
+ }
101
+
102
+ // ── /admin/edit/[type]/[id] ─────────────────────────────────────────────────
103
+
104
+ export interface EditData {
105
+ type: string;
106
+ id: string;
107
+ label: string;
108
+ fields: CairnField[];
109
+ path: string;
110
+ body: string;
111
+ frontmatter: Record<string, unknown>;
112
+ title: string;
113
+ saved: boolean;
114
+ error: string | null;
115
+ }
116
+
117
+ export async function editLoad(
118
+ event: { params: { type: string; id: string }; url: URL },
119
+ adapter: CairnAdapter,
120
+ ): Promise<EditData> {
121
+ const collection = findCollection(adapter, event.params.type);
122
+ if (!collection) throw error(404, 'Unknown collection');
123
+
124
+ // Anonymous read — repos are public; the GitHub App token is commit-only (see saveCommit).
125
+ const path = `${collection.dir}/${event.params.id}.md`;
126
+ const raw = await readRaw(adapter.backend, path);
127
+ if (raw === null) throw error(404, 'Content not found');
128
+
129
+ // Split frontmatter from body server-side; the editor form binds to the frontmatter and
130
+ // the Carta editor binds to the body, and /admin/save reassembles them on commit.
131
+ const { data: frontmatter, content: body } = matter(raw);
132
+
133
+ return {
134
+ type: event.params.type,
135
+ id: event.params.id,
136
+ label: collection.label,
137
+ fields: collection.fields,
138
+ path,
139
+ body,
140
+ frontmatter,
141
+ title: typeof frontmatter.title === 'string' ? frontmatter.title : event.params.id,
142
+ saved: event.url.searchParams.get('saved') === '1',
143
+ error: event.url.searchParams.get('error'),
144
+ };
145
+ }
146
+
147
+ // ── /admin/auth/request (POST) ──────────────────────────────────────────────
148
+
149
+ export async function authRequest(
150
+ event: PlatformEvent & { request: Request; url: URL },
151
+ adapter: CairnAdapter,
152
+ ): Promise<never> {
153
+ const env = event.platform?.env;
154
+ if (!env?.AUTH_KV || !env.MAGIC_LINK_SECRET || !env.EMAIL) {
155
+ throw redirect(303, '/admin/login?error=config');
156
+ }
157
+
158
+ const form = await event.request.formData();
159
+ const email = String(form.get('email') ?? '').trim().toLowerCase();
160
+ if (!EMAIL_RE.test(email)) {
161
+ throw redirect(303, '/admin/login?error=invalid');
162
+ }
163
+
164
+ const editor = await lookupEditor(email, env.AUTH_KV);
165
+ if (!editor) {
166
+ throw redirect(303, '/admin/login?error=denied');
167
+ }
168
+
169
+ const token = await createMagicLink(email, env.MAGIC_LINK_SECRET, env.AUTH_KV);
170
+ // PUBLIC_ORIGIN overrides url.origin for local dev (where wrangler's custom-domain
171
+ // route makes url.origin the production host); unset in prod → url.origin is correct.
172
+ const origin = env.PUBLIC_ORIGIN || event.url.origin;
173
+ const link = `${origin}/admin/auth/callback?token=${encodeURIComponent(token)}`;
174
+ try {
175
+ await sendMagicLink(env.EMAIL, email, link, adapter.siteName, adapter.sender);
176
+ } catch (err) {
177
+ console.error('magic-link send failed:', err);
178
+ throw redirect(303, '/admin/login?error=config');
179
+ }
180
+
181
+ throw redirect(303, '/admin/login?sent=1');
182
+ }
183
+
184
+ // ── /admin/auth/callback (GET) ──────────────────────────────────────────────
185
+
186
+ export async function authCallback(
187
+ event: PlatformEvent & { url: URL; cookies: Cookies },
188
+ ): Promise<never> {
189
+ const env = event.platform?.env;
190
+ if (!env?.AUTH_KV || !env.MAGIC_LINK_SECRET || !env.SESSION_SECRET) {
191
+ throw redirect(303, '/admin/login?error=config');
192
+ }
193
+
194
+ const token = event.url.searchParams.get('token') ?? '';
195
+ const email = await redeemMagicToken(token, env.MAGIC_LINK_SECRET, env.AUTH_KV);
196
+ if (!email) {
197
+ throw redirect(303, '/admin/login?error=expired');
198
+ }
199
+
200
+ // Re-check the allowlist at redemption — membership may have changed since issue.
201
+ const editor = await lookupEditor(email, env.AUTH_KV);
202
+ if (!editor) {
203
+ throw redirect(303, '/admin/login?error=denied');
204
+ }
205
+
206
+ const session = await createSession(editor, env.SESSION_SECRET);
207
+ event.cookies.set(SESSION_COOKIE, session, {
208
+ path: '/',
209
+ httpOnly: true,
210
+ secure: event.url.protocol === 'https:',
211
+ sameSite: 'lax',
212
+ maxAge: SESSION_MAX_AGE,
213
+ });
214
+
215
+ throw redirect(303, '/admin');
216
+ }
217
+
218
+ // ── /admin/auth/logout (POST) ───────────────────────────────────────────────
219
+
220
+ export function logout(event: { cookies: Cookies }): never {
221
+ event.cookies.delete(SESSION_COOKIE, { path: '/' });
222
+ throw redirect(303, '/admin/login');
223
+ }
224
+
225
+ // ── /admin/save (POST) ──────────────────────────────────────────────────────
226
+
227
+ export async function saveCommit(
228
+ event: PlatformEvent & { request: Request; locals: { editor: Editor | null } },
229
+ adapter: CairnAdapter,
230
+ ): Promise<never> {
231
+ const editor = event.locals.editor;
232
+ if (!editor) throw error(401, 'Not signed in');
233
+
234
+ const env = event.platform?.env;
235
+ if (!env?.GITHUB_APP_ID || !env.GITHUB_APP_INSTALLATION_ID || !env.GITHUB_APP_PRIVATE_KEY_B64) {
236
+ throw error(500, 'GitHub App is not configured');
237
+ }
238
+
239
+ const form = await event.request.formData();
240
+ const type = String(form.get('type') ?? '');
241
+ const id = String(form.get('id') ?? '');
242
+ const body = String(form.get('body') ?? '');
243
+ const collection = findCollection(adapter, type);
244
+ if (!collection || !id) throw error(400, 'Bad request');
245
+
246
+ // Build frontmatter from the posted fields and validate against the collection's schema; a
247
+ // bad field bounces back to the editor with the validator's message rather than 500ing.
248
+ let frontmatter: object;
249
+ try {
250
+ frontmatter = collection.validate(frontmatterFromForm(collection, form), `${id}.md`);
251
+ } catch (err) {
252
+ const message = err instanceof Error ? err.message : 'Invalid frontmatter';
253
+ throw redirect(303, `/admin/edit/${type}/${id}?error=${encodeURIComponent(message)}`);
254
+ }
255
+
256
+ const markdown = serializeMarkdown(frontmatter, body);
257
+ const token = await installationToken({
258
+ appId: env.GITHUB_APP_ID,
259
+ installationId: env.GITHUB_APP_INSTALLATION_ID,
260
+ privateKeyB64: env.GITHUB_APP_PRIVATE_KEY_B64,
261
+ });
262
+
263
+ await commitFile(
264
+ adapter.backend,
265
+ `${collection.dir}/${id}.md`,
266
+ markdown,
267
+ { message: `Update ${collection.label.toLowerCase()}: ${id}`, author: { name: editor.name, email: editor.email } },
268
+ token,
269
+ );
270
+
271
+ throw redirect(303, `/admin/edit/${type}/${id}?saved=1`);
272
+ }
@@ -0,0 +1,12 @@
1
+ // cairn-core: internal encoding helpers shared across modules.
2
+ //
3
+ // Deliberately NOT re-exported from index.ts — these are implementation details of the
4
+ // auth/github crypto, not part of the public API (auth.ts signs tokens, github.ts builds
5
+ // the App JWT; both need base64url). Keeping them here stops bytesToB64url leaking through
6
+ // the `export *` barrel.
7
+
8
+ /** Encode bytes as unpadded base64url (RFC 4648 §5) — the JWT/token wire format. */
9
+ export function bytesToB64url(bytes: Uint8Array): string {
10
+ const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join('');
11
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
12
+ }