@glw907/cairn-cms 0.5.0 → 0.6.0-rc.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 (216) hide show
  1. package/dist/auth/crypto.d.ts +13 -0
  2. package/dist/auth/crypto.d.ts.map +1 -0
  3. package/dist/auth/crypto.js +31 -0
  4. package/dist/auth/store.d.ts +41 -0
  5. package/dist/auth/store.d.ts.map +1 -0
  6. package/dist/auth/store.js +115 -0
  7. package/dist/auth/types.d.ts +25 -0
  8. package/dist/auth/types.d.ts.map +1 -0
  9. package/dist/auth/types.js +1 -0
  10. package/dist/components/AdminLayout.svelte +58 -108
  11. package/dist/components/AdminLayout.svelte.d.ts +14 -9
  12. package/dist/components/AdminLayout.svelte.d.ts.map +1 -1
  13. package/dist/components/ComponentPalette.svelte +50 -0
  14. package/dist/components/ComponentPalette.svelte.d.ts +16 -0
  15. package/dist/components/ComponentPalette.svelte.d.ts.map +1 -0
  16. package/dist/components/ConceptList.svelte +81 -0
  17. package/dist/components/ConceptList.svelte.d.ts +13 -0
  18. package/dist/components/ConceptList.svelte.d.ts.map +1 -0
  19. package/dist/components/ConfirmPage.svelte +23 -20
  20. package/dist/components/ConfirmPage.svelte.d.ts +6 -0
  21. package/dist/components/ConfirmPage.svelte.d.ts.map +1 -1
  22. package/dist/components/EditPage.svelte +160 -103
  23. package/dist/components/EditPage.svelte.d.ts +17 -7
  24. package/dist/components/EditPage.svelte.d.ts.map +1 -1
  25. package/dist/components/LoginPage.svelte +42 -52
  26. package/dist/components/LoginPage.svelte.d.ts +12 -0
  27. package/dist/components/LoginPage.svelte.d.ts.map +1 -1
  28. package/dist/components/ManageEditors.svelte +81 -0
  29. package/dist/components/ManageEditors.svelte.d.ts +24 -0
  30. package/dist/components/ManageEditors.svelte.d.ts.map +1 -0
  31. package/dist/components/MarkdownEditor.svelte +81 -0
  32. package/dist/components/MarkdownEditor.svelte.d.ts +20 -0
  33. package/dist/components/MarkdownEditor.svelte.d.ts.map +1 -0
  34. package/dist/components/NavTree.svelte +138 -0
  35. package/dist/components/NavTree.svelte.d.ts +17 -0
  36. package/dist/components/NavTree.svelte.d.ts.map +1 -0
  37. package/dist/components/cairn-admin.css +42 -0
  38. package/dist/components/index.d.ts +5 -2
  39. package/dist/components/index.d.ts.map +1 -1
  40. package/dist/components/index.js +7 -4
  41. package/dist/content/compose.d.ts +7 -0
  42. package/dist/content/compose.d.ts.map +1 -0
  43. package/dist/content/compose.js +32 -0
  44. package/dist/content/concepts.d.ts +17 -0
  45. package/dist/content/concepts.d.ts.map +1 -0
  46. package/dist/content/concepts.js +41 -0
  47. package/dist/content/frontmatter.d.ts +18 -0
  48. package/dist/content/frontmatter.d.ts.map +1 -0
  49. package/dist/content/frontmatter.js +58 -0
  50. package/dist/content/ids.d.ts +17 -0
  51. package/dist/content/ids.d.ts.map +1 -0
  52. package/dist/content/ids.js +33 -0
  53. package/dist/content/types.d.ts +210 -0
  54. package/dist/content/types.d.ts.map +1 -0
  55. package/dist/content/types.js +1 -0
  56. package/dist/content/validate.d.ts +13 -0
  57. package/dist/content/validate.d.ts.map +1 -0
  58. package/dist/content/validate.js +45 -0
  59. package/dist/email.d.ts +25 -12
  60. package/dist/email.d.ts.map +1 -1
  61. package/dist/email.js +24 -24
  62. package/dist/env.d.ts +24 -0
  63. package/dist/env.d.ts.map +1 -0
  64. package/dist/env.js +29 -0
  65. package/dist/github/credentials.d.ts +12 -0
  66. package/dist/github/credentials.d.ts.map +1 -0
  67. package/dist/github/credentials.js +11 -0
  68. package/dist/github/repo.d.ts +49 -0
  69. package/dist/github/repo.d.ts.map +1 -0
  70. package/dist/github/repo.js +123 -0
  71. package/dist/github/signing.d.ts +17 -0
  72. package/dist/github/signing.d.ts.map +1 -0
  73. package/dist/github/signing.js +79 -0
  74. package/dist/github/types.d.ts +35 -0
  75. package/dist/github/types.d.ts.map +1 -0
  76. package/dist/github/types.js +19 -0
  77. package/dist/index.d.ts +27 -6
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js +21 -8
  80. package/dist/nav/site-config.d.ts +50 -0
  81. package/dist/nav/site-config.d.ts.map +1 -0
  82. package/dist/nav/site-config.js +100 -0
  83. package/dist/render/glyph.d.ts +1 -1
  84. package/dist/render/glyph.d.ts.map +1 -1
  85. package/dist/render/index.d.ts +5 -5
  86. package/dist/render/index.d.ts.map +1 -1
  87. package/dist/render/index.js +6 -6
  88. package/dist/render/pipeline.d.ts +3 -3
  89. package/dist/render/pipeline.d.ts.map +1 -1
  90. package/dist/render/pipeline.js +4 -4
  91. package/dist/render/registry.d.ts +6 -4
  92. package/dist/render/registry.d.ts.map +1 -1
  93. package/dist/render/registry.js +8 -6
  94. package/dist/render/rehype-dispatch.d.ts +1 -1
  95. package/dist/render/rehype-dispatch.d.ts.map +1 -1
  96. package/dist/render/remark-directives.d.ts +1 -1
  97. package/dist/render/remark-directives.d.ts.map +1 -1
  98. package/dist/render/sanitize.d.ts +8 -0
  99. package/dist/render/sanitize.d.ts.map +1 -0
  100. package/dist/render/sanitize.js +26 -0
  101. package/dist/sveltekit/auth-routes.d.ts +23 -0
  102. package/dist/sveltekit/auth-routes.d.ts.map +1 -0
  103. package/dist/sveltekit/auth-routes.js +85 -0
  104. package/dist/sveltekit/content-routes.d.ts +80 -0
  105. package/dist/sveltekit/content-routes.d.ts.map +1 -0
  106. package/dist/sveltekit/content-routes.js +183 -0
  107. package/dist/sveltekit/editors-routes.d.ts +24 -0
  108. package/dist/sveltekit/editors-routes.d.ts.map +1 -0
  109. package/dist/sveltekit/editors-routes.js +73 -0
  110. package/dist/sveltekit/guard.d.ts +9 -0
  111. package/dist/sveltekit/guard.d.ts.map +1 -0
  112. package/dist/sveltekit/guard.js +43 -0
  113. package/dist/sveltekit/health.d.ts +19 -0
  114. package/dist/sveltekit/health.d.ts.map +1 -0
  115. package/dist/sveltekit/health.js +12 -0
  116. package/dist/sveltekit/index.d.ts +9 -83
  117. package/dist/sveltekit/index.d.ts.map +1 -1
  118. package/dist/sveltekit/index.js +8 -149
  119. package/dist/sveltekit/nav-routes.d.ts +30 -0
  120. package/dist/sveltekit/nav-routes.d.ts.map +1 -0
  121. package/dist/sveltekit/nav-routes.js +103 -0
  122. package/dist/sveltekit/types.d.ts +32 -0
  123. package/dist/sveltekit/types.d.ts.map +1 -0
  124. package/dist/sveltekit/types.js +1 -0
  125. package/package.json +38 -58
  126. package/src/lib/auth/crypto.ts +37 -0
  127. package/src/lib/auth/store.ts +158 -0
  128. package/src/lib/auth/types.ts +27 -0
  129. package/src/lib/components/AdminLayout.svelte +58 -108
  130. package/src/lib/components/ComponentPalette.svelte +50 -0
  131. package/src/lib/components/ConceptList.svelte +81 -0
  132. package/src/lib/components/ConfirmPage.svelte +23 -20
  133. package/src/lib/components/EditPage.svelte +160 -103
  134. package/src/lib/components/LoginPage.svelte +42 -52
  135. package/src/lib/components/ManageEditors.svelte +81 -0
  136. package/src/lib/components/MarkdownEditor.svelte +81 -0
  137. package/src/lib/components/NavTree.svelte +138 -0
  138. package/src/lib/components/cairn-admin.css +42 -0
  139. package/src/lib/components/index.ts +7 -4
  140. package/src/lib/content/compose.ts +39 -0
  141. package/src/lib/content/concepts.ts +57 -0
  142. package/src/lib/content/frontmatter.ts +71 -0
  143. package/src/lib/content/ids.ts +38 -0
  144. package/src/lib/content/types.ts +235 -0
  145. package/src/lib/content/validate.ts +51 -0
  146. package/src/lib/email.ts +52 -38
  147. package/src/lib/env.ts +32 -0
  148. package/src/lib/github/credentials.ts +27 -0
  149. package/src/lib/github/repo.ts +138 -0
  150. package/src/lib/github/signing.ts +97 -0
  151. package/src/lib/github/types.ts +46 -0
  152. package/src/lib/index.ts +86 -8
  153. package/src/lib/nav/site-config.ts +124 -0
  154. package/src/lib/render/glyph.ts +6 -6
  155. package/src/lib/render/index.ts +6 -6
  156. package/src/lib/render/pipeline.ts +22 -22
  157. package/src/lib/render/registry.ts +33 -26
  158. package/src/lib/render/rehype-dispatch.ts +47 -47
  159. package/src/lib/render/remark-directives.ts +46 -46
  160. package/src/lib/render/sanitize.ts +27 -0
  161. package/src/lib/sveltekit/auth-routes.ts +107 -0
  162. package/src/lib/sveltekit/content-routes.ts +261 -0
  163. package/src/lib/sveltekit/editors-routes.ts +82 -0
  164. package/src/lib/sveltekit/guard.ts +47 -0
  165. package/src/lib/sveltekit/health.ts +24 -0
  166. package/src/lib/sveltekit/index.ts +19 -235
  167. package/src/lib/sveltekit/nav-routes.ts +139 -0
  168. package/src/lib/sveltekit/types.ts +33 -0
  169. package/dist/adapter.d.ts +0 -69
  170. package/dist/adapter.d.ts.map +0 -1
  171. package/dist/adapter.js +0 -30
  172. package/dist/auth/admins.d.ts +0 -33
  173. package/dist/auth/admins.d.ts.map +0 -1
  174. package/dist/auth/admins.js +0 -90
  175. package/dist/auth/config.d.ts +0 -2097
  176. package/dist/auth/config.d.ts.map +0 -1
  177. package/dist/auth/config.js +0 -78
  178. package/dist/auth/guard.d.ts +0 -34
  179. package/dist/auth/guard.d.ts.map +0 -1
  180. package/dist/auth/guard.js +0 -47
  181. package/dist/auth/index.d.ts +0 -4
  182. package/dist/auth/index.d.ts.map +0 -1
  183. package/dist/auth/index.js +0 -6
  184. package/dist/auth/schema.d.ts +0 -750
  185. package/dist/auth/schema.d.ts.map +0 -1
  186. package/dist/auth/schema.js +0 -93
  187. package/dist/carta.d.ts +0 -39
  188. package/dist/carta.d.ts.map +0 -1
  189. package/dist/carta.js +0 -30
  190. package/dist/components/AdminList.svelte +0 -33
  191. package/dist/components/AdminList.svelte.d.ts +0 -10
  192. package/dist/components/AdminList.svelte.d.ts.map +0 -1
  193. package/dist/components/ManageAdmins.svelte +0 -84
  194. package/dist/components/ManageAdmins.svelte.d.ts +0 -10
  195. package/dist/components/ManageAdmins.svelte.d.ts.map +0 -1
  196. package/dist/content.d.ts +0 -3
  197. package/dist/content.d.ts.map +0 -1
  198. package/dist/content.js +0 -10
  199. package/dist/github.d.ts +0 -72
  200. package/dist/github.d.ts.map +0 -1
  201. package/dist/github.js +0 -171
  202. package/dist/utils.d.ts +0 -3
  203. package/dist/utils.d.ts.map +0 -1
  204. package/dist/utils.js +0 -11
  205. package/src/lib/adapter.ts +0 -119
  206. package/src/lib/auth/admins.ts +0 -106
  207. package/src/lib/auth/config.ts +0 -108
  208. package/src/lib/auth/guard.ts +0 -60
  209. package/src/lib/auth/index.ts +0 -6
  210. package/src/lib/auth/schema.ts +0 -112
  211. package/src/lib/carta.ts +0 -59
  212. package/src/lib/components/AdminList.svelte +0 -33
  213. package/src/lib/components/ManageAdmins.svelte +0 -84
  214. package/src/lib/content.ts +0 -11
  215. package/src/lib/github.ts +0 -220
  216. package/src/lib/utils.ts +0 -12
@@ -1,84 +0,0 @@
1
- <script lang="ts">
2
- // Owner-gated editor management: list the allowlist, change roles, remove editors, add new
3
- // ones. Reuses the same neutral DaisyUI chrome as the rest of the admin (panels, alerts,
4
- // table, buttons). Data comes from `adminsLoad` merged with `adminLayoutLoad` (siteName);
5
- // mutations post to the page's named form actions (`?/add`, `?/remove`, `?/setRole`).
6
- import type { AdminsData } from '../auth';
7
-
8
- interface Props {
9
- data: AdminsData & { siteName: string };
10
- }
11
- let { data }: Props = $props();
12
- </script>
13
-
14
- <svelte:head>
15
- <title>Editors · {data.siteName} CMS</title>
16
- </svelte:head>
17
-
18
- <div>
19
- <h1 class="text-2xl font-bold">Editors</h1>
20
- <p class="text-sm opacity-60">Who can sign in to {data.siteName} CMS.</p>
21
- </div>
22
-
23
- {#if data.saved}
24
- <div class="alert alert-success mt-6"><span>Allowlist updated.</span></div>
25
- {:else if data.error}
26
- <div class="alert alert-error mt-6"><span>{data.error}</span></div>
27
- {/if}
28
-
29
- <div class="mt-6 overflow-x-auto rounded-box border border-base-300 bg-base-100">
30
- <table class="table">
31
- <thead>
32
- <tr><th>Name</th><th>Email</th><th>Role</th><th class="text-right">Actions</th></tr>
33
- </thead>
34
- <tbody>
35
- {#each data.admins as admin (admin.email)}
36
- {@const isSelf = admin.email === data.self}
37
- <tr>
38
- <td class="font-medium">{admin.name}</td>
39
- <td class="opacity-70">{admin.email}{#if isSelf}<span class="ml-1 opacity-50">(you)</span>{/if}</td>
40
- <td>
41
- <span class="badge {admin.role === 'owner' ? 'badge-primary' : 'badge-ghost'}">{admin.role}</span>
42
- </td>
43
- <td>
44
- <div class="flex justify-end gap-2">
45
- <!-- Flip role. Disabled for yourself so you can't demote the last owner out. -->
46
- <form method="POST" action="?/setRole">
47
- <input type="hidden" name="email" value={admin.email} />
48
- <input type="hidden" name="role" value={admin.role === 'owner' ? 'editor' : 'owner'} />
49
- <button type="submit" class="btn btn-ghost btn-xs" disabled={isSelf}>
50
- Make {admin.role === 'owner' ? 'editor' : 'owner'}
51
- </button>
52
- </form>
53
- <form method="POST" action="?/remove">
54
- <input type="hidden" name="email" value={admin.email} />
55
- <button type="submit" class="btn btn-ghost btn-xs text-error" disabled={isSelf}>Remove</button>
56
- </form>
57
- </div>
58
- </td>
59
- </tr>
60
- {/each}
61
- </tbody>
62
- </table>
63
- </div>
64
-
65
- <form method="POST" action="?/add"
66
- class="mt-8 grid gap-4 rounded-box border border-base-300 bg-base-100 p-6 sm:grid-cols-[1fr_1fr_auto_auto] sm:items-end">
67
- <label class="flex flex-col gap-1">
68
- <span class="text-sm font-medium">Email</span>
69
- <input type="email" name="email" required autocomplete="off" placeholder="you@example.com"
70
- class="input w-full" />
71
- </label>
72
- <label class="flex flex-col gap-1">
73
- <span class="text-sm font-medium">Name</span>
74
- <input type="text" name="name" required placeholder="Display name" class="input w-full" />
75
- </label>
76
- <label class="flex flex-col gap-1">
77
- <span class="text-sm font-medium">Role</span>
78
- <select name="role" class="select">
79
- <option value="editor">editor</option>
80
- <option value="owner">owner</option>
81
- </select>
82
- </label>
83
- <button type="submit" class="btn btn-primary">Add editor</button>
84
- </form>
@@ -1,11 +0,0 @@
1
- // cairn-core: reassemble a markdown file from frontmatter + body for committing.
2
- //
3
- // The inverse of the gray-matter parse the edit loader does on read. Kept as its own seam
4
- // so a site adapter can own the on-disk serialization contract (quoting, key order)
5
- // without the save endpoint reaching for gray-matter directly.
6
- import matter from 'gray-matter';
7
-
8
- /** Serialize frontmatter data + markdown body back into a file string. */
9
- export function serializeMarkdown(frontmatter: object, body: string): string {
10
- return matter.stringify(body, frontmatter);
11
- }
package/src/lib/github.ts DELETED
@@ -1,220 +0,0 @@
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, as 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
- * A concurrent edit lost the SHA race (C3): the file changed between the read and the PUT,
162
- * from another editor or the site's own CI. Thrown so callers can fail safe (re-fetch and ask
163
- * the editor to reapply) instead of surfacing a raw 409. Defined and caught inside the package
164
- * so `instanceof` is reliable (no peer-boundary identity split, unlike kit's `redirect`/`error`).
165
- */
166
- export class CommitConflictError extends Error {
167
- constructor(public readonly path: string) {
168
- super(`Commit conflict on ${path}: it changed since it was opened`);
169
- this.name = 'CommitConflictError';
170
- }
171
- }
172
-
173
- /**
174
- * Commit `content` to `path` on the configured branch via the contents API. Author is the
175
- * editor; committer is omitted so GitHub attributes it to the App (cairn-cms[bot]). Updates
176
- * the file in place when it exists (passing its sha), creates it otherwise. Returns the
177
- * commit sha. A stale-sha 409 (someone committed in between) becomes a `CommitConflictError`.
178
- */
179
- export async function commitFile(
180
- repo: RepoRef,
181
- path: string,
182
- content: string,
183
- opts: { message: string; author: CommitAuthor },
184
- token: string,
185
- ): Promise<string> {
186
- const sha = await fileSha(repo, path, token);
187
- const url = `${API}/repos/${repo.owner}/${repo.repo}/contents/${path.replace(/^\/+|\/+$/g, '')}`;
188
- const res = await fetch(url, {
189
- method: 'PUT',
190
- headers: { ...ghHeaders('application/vnd.github+json', token), 'Content-Type': 'application/json' },
191
- body: JSON.stringify({
192
- message: opts.message,
193
- content: toBase64(content),
194
- branch: repo.branch,
195
- author: opts.author,
196
- ...(sha ? { sha } : {}),
197
- }),
198
- });
199
- // 409 = the blob sha we read is no longer current. Fail safe: the caller re-fetches and the
200
- // editor reapplies. (Full three-way merge stays out of scope; see ARCHITECTURE §5.)
201
- if (res.status === 409) throw new CommitConflictError(path);
202
- if (!res.ok) throw new Error(`GitHub commit ${path} failed: ${res.status} ${await res.text()}`);
203
- return ((await res.json()) as { commit: { sha: string } }).commit.sha;
204
- }
205
-
206
- /**
207
- * Deploy-time self-test for the GitHub App signer (M2): sign a dummy JWT with the configured
208
- * private key. Exercises the brittle PKCS#1→PKCS#8 conversion + Web Crypto import/sign without
209
- * any network call or secret in the result, so `/admin/healthz` catches a bad/rotated key
210
- * before an editor's save fails. Returns `{ ok: false, detail }` rather than throwing.
211
- */
212
- export async function signingSelfTest(appId: string, privateKeyB64: string): Promise<{ ok: boolean; detail?: string }> {
213
- try {
214
- const jwt = await appJwt(appId, atob(privateKeyB64));
215
- if (jwt.split('.').length !== 3) return { ok: false, detail: 'malformed JWT' };
216
- return { ok: true };
217
- } catch (err) {
218
- return { ok: false, detail: err instanceof Error ? err.message : 'sign failed' };
219
- }
220
- }
package/src/lib/utils.ts DELETED
@@ -1,12 +0,0 @@
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
- }