cogens 0.0.0-stage → 0.2.1

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 (192) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +25 -0
  4. package/README.md +394 -2
  5. package/dist/admin/app.d.ts +21 -0
  6. package/dist/admin/app.d.ts.map +1 -0
  7. package/dist/admin/app.js +561 -0
  8. package/dist/admin/app.js.map +1 -0
  9. package/dist/admin/assets.d.ts +17 -0
  10. package/dist/admin/assets.d.ts.map +1 -0
  11. package/dist/admin/assets.js +51 -0
  12. package/dist/admin/assets.js.map +1 -0
  13. package/dist/admin/fields.d.ts +27 -0
  14. package/dist/admin/fields.d.ts.map +1 -0
  15. package/dist/admin/fields.js +128 -0
  16. package/dist/admin/fields.js.map +1 -0
  17. package/dist/admin/forms.d.ts +18 -0
  18. package/dist/admin/forms.d.ts.map +1 -0
  19. package/dist/admin/forms.js +53 -0
  20. package/dist/admin/forms.js.map +1 -0
  21. package/dist/admin/index.d.ts +15 -0
  22. package/dist/admin/index.d.ts.map +1 -0
  23. package/dist/admin/index.js +13 -0
  24. package/dist/admin/index.js.map +1 -0
  25. package/dist/admin/rules.d.ts +24 -0
  26. package/dist/admin/rules.d.ts.map +1 -0
  27. package/dist/admin/rules.js +51 -0
  28. package/dist/admin/rules.js.map +1 -0
  29. package/dist/admin/types.d.ts +96 -0
  30. package/dist/admin/types.d.ts.map +1 -0
  31. package/dist/admin/types.js +2 -0
  32. package/dist/admin/types.js.map +1 -0
  33. package/dist/admin/views.d.ts +109 -0
  34. package/dist/admin/views.d.ts.map +1 -0
  35. package/dist/admin/views.js +202 -0
  36. package/dist/admin/views.js.map +1 -0
  37. package/dist/auth/handoff.d.ts +27 -0
  38. package/dist/auth/handoff.d.ts.map +1 -0
  39. package/dist/auth/handoff.js +41 -0
  40. package/dist/auth/handoff.js.map +1 -0
  41. package/dist/auth/index.d.ts +10 -0
  42. package/dist/auth/index.d.ts.map +1 -0
  43. package/dist/auth/index.js +10 -0
  44. package/dist/auth/index.js.map +1 -0
  45. package/dist/auth/password.d.ts +48 -0
  46. package/dist/auth/password.d.ts.map +1 -0
  47. package/dist/auth/password.js +154 -0
  48. package/dist/auth/password.js.map +1 -0
  49. package/dist/auth/principal.d.ts +30 -0
  50. package/dist/auth/principal.d.ts.map +1 -0
  51. package/dist/auth/principal.js +30 -0
  52. package/dist/auth/principal.js.map +1 -0
  53. package/dist/auth/session.d.ts +68 -0
  54. package/dist/auth/session.d.ts.map +1 -0
  55. package/dist/auth/session.js +92 -0
  56. package/dist/auth/session.js.map +1 -0
  57. package/dist/core/access/ability.d.ts +24 -0
  58. package/dist/core/access/ability.d.ts.map +1 -0
  59. package/dist/core/access/ability.js +64 -0
  60. package/dist/core/access/ability.js.map +1 -0
  61. package/dist/core/access/can.d.ts +41 -0
  62. package/dist/core/access/can.d.ts.map +1 -0
  63. package/dist/core/access/can.js +38 -0
  64. package/dist/core/access/can.js.map +1 -0
  65. package/dist/core/access/compile.d.ts +12 -0
  66. package/dist/core/access/compile.d.ts.map +1 -0
  67. package/dist/core/access/compile.js +53 -0
  68. package/dist/core/access/compile.js.map +1 -0
  69. package/dist/core/access/permits.d.ts +24 -0
  70. package/dist/core/access/permits.d.ts.map +1 -0
  71. package/dist/core/access/permits.js +29 -0
  72. package/dist/core/access/permits.js.map +1 -0
  73. package/dist/core/access/when.d.ts +6 -0
  74. package/dist/core/access/when.d.ts.map +1 -0
  75. package/dist/core/access/when.js +64 -0
  76. package/dist/core/access/when.js.map +1 -0
  77. package/dist/core/access/where.d.ts +25 -0
  78. package/dist/core/access/where.d.ts.map +1 -0
  79. package/dist/core/access/where.js +81 -0
  80. package/dist/core/access/where.js.map +1 -0
  81. package/dist/core/columns.d.ts +6 -0
  82. package/dist/core/columns.d.ts.map +1 -0
  83. package/dist/core/columns.js +6 -0
  84. package/dist/core/columns.js.map +1 -0
  85. package/dist/core/config/define.d.ts +101 -0
  86. package/dist/core/config/define.d.ts.map +1 -0
  87. package/dist/core/config/define.js +97 -0
  88. package/dist/core/config/define.js.map +1 -0
  89. package/dist/core/config/field.d.ts +71 -0
  90. package/dist/core/config/field.d.ts.map +1 -0
  91. package/dist/core/config/field.js +64 -0
  92. package/dist/core/config/field.js.map +1 -0
  93. package/dist/core/errors.d.ts +66 -0
  94. package/dist/core/errors.d.ts.map +1 -0
  95. package/dist/core/errors.js +94 -0
  96. package/dist/core/errors.js.map +1 -0
  97. package/dist/core/index.d.ts +31 -0
  98. package/dist/core/index.d.ts.map +1 -0
  99. package/dist/core/index.js +20 -0
  100. package/dist/core/index.js.map +1 -0
  101. package/dist/core/media/index.d.ts +36 -0
  102. package/dist/core/media/index.d.ts.map +1 -0
  103. package/dist/core/media/index.js +99 -0
  104. package/dist/core/media/index.js.map +1 -0
  105. package/dist/core/principal.d.ts +28 -0
  106. package/dist/core/principal.d.ts.map +1 -0
  107. package/dist/core/principal.js +25 -0
  108. package/dist/core/principal.js.map +1 -0
  109. package/dist/core/store/assets.d.ts +3 -0
  110. package/dist/core/store/assets.d.ts.map +1 -0
  111. package/dist/core/store/assets.js +3 -0
  112. package/dist/core/store/assets.js.map +1 -0
  113. package/dist/core/store/cms.d.ts +53 -0
  114. package/dist/core/store/cms.d.ts.map +1 -0
  115. package/dist/core/store/cms.js +154 -0
  116. package/dist/core/store/cms.js.map +1 -0
  117. package/dist/core/store/content.d.ts +57 -0
  118. package/dist/core/store/content.d.ts.map +1 -0
  119. package/dist/core/store/content.js +455 -0
  120. package/dist/core/store/content.js.map +1 -0
  121. package/dist/core/store/sql.d.ts +88 -0
  122. package/dist/core/store/sql.d.ts.map +1 -0
  123. package/dist/core/store/sql.js +149 -0
  124. package/dist/core/store/sql.js.map +1 -0
  125. package/dist/core/store/types.d.ts +107 -0
  126. package/dist/core/store/types.d.ts.map +1 -0
  127. package/dist/core/store/types.js +2 -0
  128. package/dist/core/store/types.js.map +1 -0
  129. package/dist/core/testing/index.d.ts +27 -0
  130. package/dist/core/testing/index.d.ts.map +1 -0
  131. package/dist/core/testing/index.js +60 -0
  132. package/dist/core/testing/index.js.map +1 -0
  133. package/dist/migrations-tool/bin.d.ts +3 -0
  134. package/dist/migrations-tool/bin.d.ts.map +1 -0
  135. package/dist/migrations-tool/bin.js +40 -0
  136. package/dist/migrations-tool/bin.js.map +1 -0
  137. package/dist/migrations-tool/index.d.ts +16 -0
  138. package/dist/migrations-tool/index.d.ts.map +1 -0
  139. package/dist/migrations-tool/index.js +24 -0
  140. package/dist/migrations-tool/index.js.map +1 -0
  141. package/dist/testing/db.d.ts +16 -0
  142. package/dist/testing/db.d.ts.map +1 -0
  143. package/dist/testing/db.js +43 -0
  144. package/dist/testing/db.js.map +1 -0
  145. package/dist/testing/index.d.ts +10 -0
  146. package/dist/testing/index.d.ts.map +1 -0
  147. package/dist/testing/index.js +8 -0
  148. package/dist/testing/index.js.map +1 -0
  149. package/editor/editor-dark.css +2 -0
  150. package/editor/editor.css +9 -0
  151. package/editor/entry.js +28 -0
  152. package/migrations/0001_entries.sql +43 -0
  153. package/migrations/auth/0001_sessions.sql +50 -0
  154. package/migrations/koguma-upgrade.sql +13 -0
  155. package/package.json +108 -4
  156. package/scripts/build-admin-editor.ts +155 -0
  157. package/src/admin/app.ts +608 -0
  158. package/src/admin/assets.ts +52 -0
  159. package/src/admin/fields.ts +172 -0
  160. package/src/admin/forms.ts +64 -0
  161. package/src/admin/index.ts +16 -0
  162. package/src/admin/rules.ts +63 -0
  163. package/src/admin/types.ts +99 -0
  164. package/src/admin/views.ts +360 -0
  165. package/src/auth/handoff.ts +56 -0
  166. package/src/auth/index.ts +29 -0
  167. package/src/auth/password.ts +201 -0
  168. package/src/auth/principal.ts +40 -0
  169. package/src/auth/session.ts +143 -0
  170. package/src/core/access/ability.ts +86 -0
  171. package/src/core/access/can.ts +66 -0
  172. package/src/core/access/compile.ts +62 -0
  173. package/src/core/access/permits.ts +45 -0
  174. package/src/core/access/when.ts +59 -0
  175. package/src/core/access/where.ts +95 -0
  176. package/src/core/columns.ts +7 -0
  177. package/src/core/config/define.ts +206 -0
  178. package/src/core/config/field.ts +119 -0
  179. package/src/core/errors.ts +99 -0
  180. package/src/core/index.ts +44 -0
  181. package/src/core/media/index.ts +132 -0
  182. package/src/core/principal.ts +49 -0
  183. package/src/core/store/assets.ts +2 -0
  184. package/src/core/store/cms.ts +199 -0
  185. package/src/core/store/content.ts +453 -0
  186. package/src/core/store/sql.ts +239 -0
  187. package/src/core/store/types.ts +100 -0
  188. package/src/core/testing/index.ts +75 -0
  189. package/src/migrations-tool/bin.ts +34 -0
  190. package/src/migrations-tool/index.ts +37 -0
  191. package/src/testing/db.ts +53 -0
  192. package/src/testing/index.ts +9 -0
@@ -0,0 +1,360 @@
1
+ /**
2
+ * The pages, as functions from plain data to HTML. Nothing here reads a request
3
+ * or calls the store; the routes do that and pass what the page shows. Styling
4
+ * is Largen's (elements, `data-tone`, `data-variant`, the layout utilities).
5
+ */
6
+ import { html } from 'hono/html';
7
+ import type { ContentType, Entry, FieldMeta } from '../core/index.ts';
8
+ import { renderField, type Html, type ResolveRef } from './fields.ts';
9
+ import type { AdminAction, AdminAssets, ExternalCollection, ExternalRow } from './types.ts';
10
+
11
+ export interface Shell {
12
+ mount: string;
13
+ /** The admin's first page: the mount itself (a route mounted at a path answers there, with no trailing slash). */
14
+ home: string;
15
+ siteName: string;
16
+ assets: AdminAssets;
17
+ /** The host gave a sign-in: pages carry Sign out and Sign out everywhere. */
18
+ session?: boolean;
19
+ }
20
+
21
+ const NOTICES: Record<string, string> = {
22
+ saved: 'Saved.',
23
+ created: 'Created.',
24
+ published: 'Published.',
25
+ unpublished: 'Unpublished.',
26
+ deleted: 'Deleted.',
27
+ done: 'Done.'
28
+ };
29
+ export const noticeText = (key: string | undefined) => (key === undefined ? undefined : NOTICES[key]);
30
+
31
+ export interface PageInput {
32
+ title: string;
33
+ body: Html;
34
+ /** The page has a markdown field to edit: it links the editor's styles and names its module. */
35
+ editor?: boolean;
36
+ crumbs?: { label: string; href?: string }[];
37
+ notice?: string;
38
+ problems?: string[];
39
+ /** A page for someone who is not signed in: no sign-out forms. */
40
+ signedOut?: boolean;
41
+ }
42
+
43
+ export function page(shell: Shell, input: PageInput): Html {
44
+ const { mount, assets } = shell;
45
+ return html`<!doctype html>
46
+ <html lang="en">
47
+ <head>
48
+ <meta charset="utf-8">
49
+ <meta name="viewport" content="width=device-width, initial-scale=1">
50
+ <meta name="robots" content="noindex">
51
+ <title>${input.title} · ${shell.siteName}</title>
52
+ <link rel="icon" href="data:,">
53
+ <link rel="stylesheet" href="${assets.largen}">
54
+ <link rel="stylesheet" href="${assets.largenDark}" media="(prefers-color-scheme: dark)">
55
+ <link rel="stylesheet" href="${mount}/assets/admin.css">${
56
+ input.editor
57
+ ? html`
58
+ <link rel="stylesheet" href="${assets.editorStyles}">
59
+ <link rel="stylesheet" href="${assets.editorStylesDark}" media="(prefers-color-scheme: dark)">`
60
+ : ''
61
+ }
62
+ </head>
63
+ <body>
64
+ <main class="center stack">
65
+ <header class="stack">
66
+ <nav class="cluster" aria-label="Breadcrumb"><a href="${shell.home}">${shell.siteName}</a>${(input.crumbs ?? []).map(
67
+ c => html`<span aria-hidden="true">/</span>${c.href ? html`<a href="${c.href}">${c.label}</a>` : html`<span>${c.label}</span>`}`
68
+ )}</nav>
69
+ <h1>${input.title}</h1>
70
+ </header>${input.notice ? html`
71
+ <p role="status" data-tone="success" data-variant="soft">${input.notice}</p>` : ''}${
72
+ input.problems && input.problems.length > 0
73
+ ? html`
74
+ <div role="alert" data-tone="danger" data-variant="soft"><p>Nothing was changed.</p><ul>${input.problems.map(p => html`<li>${p}</li>`)}</ul></div>`
75
+ : ''
76
+ }
77
+ ${input.body}${shell.session && !input.signedOut ? html`
78
+ <footer class="cluster"><form method="post" action="${mount}/sign-out"><button type="submit" data-variant="ghost">Sign out</button></form><form method="post" action="${mount}/sign-out-everywhere"><button type="submit" data-variant="ghost">Sign out everywhere</button></form></footer>` : ''}
79
+ </main>
80
+ <script defer src="${mount}/assets/admin.js"${input.editor ? html` data-editor="${assets.editor}"` : ''}></script>
81
+ </body>
82
+ </html>`;
83
+ }
84
+
85
+ export function messagePage(shell: Shell, title: string, message: string, back?: { label: string; href: string }): Html {
86
+ return page(shell, {
87
+ title,
88
+ body: html`<p>${message}</p>${back ? html`<p><a href="${back.href}">${back.label}</a></p>` : ''}`
89
+ });
90
+ }
91
+
92
+ /** The sign-in page: a password form that posts to the admin and works with JavaScript off. */
93
+ export function signInPage(shell: Shell, next: string, error?: string): Html {
94
+ return page(shell, {
95
+ title: 'Sign in',
96
+ signedOut: true,
97
+ body: html`${error ? html`<p role="alert" data-tone="danger" data-variant="soft">${error}</p>` : ''}
98
+ <form method="post" action="${shell.mount}/sign-in" class="stack">
99
+ <input type="hidden" name="next" value="${next}">
100
+ <label>Password <input type="password" name="password" autocomplete="current-password" required autofocus></label>
101
+ <p><button type="submit">Sign in</button></p>
102
+ </form>`
103
+ });
104
+ }
105
+
106
+ // ── The type list ───────────────────────────────────────────────────
107
+
108
+ export function typeListPage(shell: Shell, stored: { id: string; name: string }[], external: { id: string; name: string }[]): Html {
109
+ const { mount } = shell;
110
+ const list = (items: { id: string; name: string }[], base: string) =>
111
+ html`<ul class="stack">${items.map(t => html`<li><a href="${mount}/${base}/${t.id}">${t.name}</a></li>`)}</ul>`;
112
+ return page(shell, {
113
+ title: 'Content',
114
+ body:
115
+ stored.length === 0 && external.length === 0
116
+ ? html`<p>There is nothing here you may read.</p>`
117
+ : html`${stored.length > 0 ? html`<section class="stack"><h2>Types</h2>${list(stored, 't')}</section>` : ''}${
118
+ external.length > 0 ? html`<section class="stack"><h2>Tables</h2>${list(external, 'x')}</section>` : ''
119
+ }`
120
+ });
121
+ }
122
+
123
+ // ── An entry list ───────────────────────────────────────────────────
124
+
125
+ export interface ListInput {
126
+ type: ContentType<any>;
127
+ entries: Entry[];
128
+ q: string;
129
+ status: string;
130
+ owner: string;
131
+ offset: number;
132
+ limit: number;
133
+ hasNext: boolean;
134
+ canCreate: boolean;
135
+ notice?: string;
136
+ }
137
+
138
+ function query(params: Record<string, string | number>): string {
139
+ const search = new URLSearchParams();
140
+ for (const [k, v] of Object.entries(params)) if (v !== '' && v !== 0) search.set(k, String(v));
141
+ const text = search.toString();
142
+ return text ? `?${text}` : '';
143
+ }
144
+
145
+ export function entryListPage(shell: Shell, input: ListInput): Html {
146
+ const { mount } = shell;
147
+ const { type } = input;
148
+ const base = `${mount}/t/${type.id}`;
149
+ const title = (e: Entry) => String(e.data[type.displayField] ?? '') || e.slug || e.id;
150
+ const filters = { q: input.q, status: input.status, owner: input.owner };
151
+ return page(shell, {
152
+ title: type.name,
153
+ crumbs: [],
154
+ notice: input.notice,
155
+ body: html`
156
+ <form method="get" action="${base}" class="cluster" role="search">
157
+ <input type="search" name="q" value="${input.q}" placeholder="Slug" aria-label="Search by slug">
158
+ <select name="status" aria-label="Status" data-autosubmit><option value="">Any status</option><option value="published"${input.status === 'published' ? ' selected' : ''}>Published</option><option value="draft"${input.status === 'draft' ? ' selected' : ''}>Draft</option></select>${
159
+ type.owned ? html`<input type="text" name="owner" value="${input.owner}" placeholder="Owner id" aria-label="Owner">` : ''
160
+ }
161
+ <button type="submit" data-variant="outline">Filter</button>${
162
+ input.q || input.status || input.owner ? html`<a href="${base}">Clear</a>` : ''
163
+ }${input.canCreate ? html`<a href="${base}/new">New ${type.name.replace(/s$/, '')}</a>` : ''}
164
+ </form>${
165
+ input.entries.length === 0
166
+ ? html`<p>No entries.</p>`
167
+ : html`
168
+ <table>
169
+ <thead><tr><th scope="col">${type.fieldMeta[type.displayField]?.label ?? 'Title'}</th><th scope="col">Slug</th><th scope="col">Status</th>${type.owned ? html`<th scope="col">Owner</th>` : ''}<th scope="col">Updated</th></tr></thead>
170
+ <tbody>${input.entries.map(
171
+ e => html`<tr><td><a href="${base}/${e.id}">${title(e)}</a></td><td>${e.slug ?? ''}</td><td>${statusBadge(e.status)}</td>${type.owned ? html`<td>${e.owner_id ?? ''}</td>` : ''}<td>${e.updated_at}</td></tr>`
172
+ )}</tbody>
173
+ </table>`
174
+ }
175
+ <nav class="cluster" aria-label="Pages">${
176
+ input.offset > 0 ? html`<a href="${base}${query({ ...filters, offset: Math.max(input.offset - input.limit, 0) })}">Previous</a>` : ''
177
+ }${input.hasNext ? html`<a href="${base}${query({ ...filters, offset: input.offset + input.limit })}">Next</a>` : ''}</nav>`
178
+ });
179
+ }
180
+
181
+ export function statusBadge(status: string | undefined): Html {
182
+ if (status === undefined || status === '') return html``;
183
+ const live = status === 'published';
184
+ return html`<span data-tone="${live ? 'success' : 'secondary'}" data-variant="soft">${status}</span>`;
185
+ }
186
+
187
+ // ── One entry ───────────────────────────────────────────────────────
188
+
189
+ export interface Row {
190
+ name: string;
191
+ meta: FieldMeta;
192
+ value: unknown;
193
+ editable: boolean;
194
+ error?: string;
195
+ }
196
+
197
+ export interface Column {
198
+ label: string;
199
+ name: string;
200
+ value: string | null;
201
+ editable: boolean;
202
+ }
203
+
204
+ /** The label and control (or text) of each row, as a definition list the form's layout styles. */
205
+ function fieldRows(rows: Row[], columns: Column[], refs: ResolveRef, type?: string): Html {
206
+ return html`<dl class="fields">${columns.map(col =>
207
+ col.editable
208
+ ? html`<dt><label for="f-${col.name}">${col.label}</label></dt><dd><input id="f-${col.name}" type="text" name="${col.name}" value="${col.value ?? ''}"></dd>`
209
+ : html`<dt>${col.label}</dt><dd>${col.value === null || col.value === '' ? html`<span data-tone="secondary" data-variant="ghost">—</span>` : html`<span>${col.value}</span>`}</dd>`
210
+ )}${rows.map(row => {
211
+ const error = row.error ? html`<small data-tone="danger" data-variant="ghost">${row.name} ${row.error}</small>` : '';
212
+ return row.editable
213
+ ? html`<dt><label for="f-${row.name}">${row.meta.label}</label></dt><dd>${renderField({ name: row.name, type, meta: row.meta, value: row.value, refs }, 'edit')}${error}</dd>`
214
+ : html`<dt>${row.meta.label}</dt><dd>${renderField({ name: row.name, meta: row.meta, value: row.value, refs }, 'read')}${error}</dd>`;
215
+ })}</dl>`;
216
+ }
217
+
218
+ export interface EntryInput {
219
+ type: ContentType<any>;
220
+ /** Absent for a new entry. */
221
+ entry?: Entry;
222
+ columns: Column[];
223
+ rows: Row[];
224
+ refs: ResolveRef;
225
+ /** The save button: some field may be written. */
226
+ canSave: boolean;
227
+ canPublish: boolean;
228
+ canUnpublish: boolean;
229
+ canDelete: boolean;
230
+ actions: AdminAction<any>[];
231
+ notice?: string;
232
+ problems?: string[];
233
+ }
234
+
235
+ export function entryPage(shell: Shell, input: EntryInput): Html {
236
+ const { mount } = shell;
237
+ const { type, entry } = input;
238
+ const base = `${mount}/t/${type.id}`;
239
+ const title = entry ? String(entry.data[type.displayField] ?? '') || entry.slug || entry.id : `New ${type.name.replace(/s$/, '')}`;
240
+ const action = entry ? `${base}/${entry.id}` : base;
241
+ const fields = fieldRows(input.rows, input.columns, input.refs, type.id);
242
+ const markdown = input.rows.some(r => r.editable && r.meta.fieldType === 'markdown');
243
+ return page(shell, {
244
+ title,
245
+ editor: markdown,
246
+ crumbs: [{ label: type.name, href: base }, { label: title }],
247
+ notice: input.notice,
248
+ problems: input.problems,
249
+ body: html`${
250
+ input.canSave
251
+ ? html`<form method="post" action="${action}" class="stack">${fields}<div class="cluster"><button type="submit" data-tone="primary" data-variant="solid">${entry ? 'Save' : 'Create'}</button></div></form>`
252
+ : fields
253
+ }${
254
+ entry
255
+ ? html`<section class="cluster" aria-label="Actions">${
256
+ entry.status === 'published'
257
+ ? input.canUnpublish
258
+ ? html`<form method="post" action="${base}/${entry.id}/unpublish"><button type="submit" data-variant="outline">Unpublish</button></form>`
259
+ : ''
260
+ : input.canPublish
261
+ ? html`<form method="post" action="${base}/${entry.id}/publish"><button type="submit" data-tone="success" data-variant="solid">Publish</button></form>`
262
+ : ''
263
+ }${input.actions.map(
264
+ a => html`<form method="get" action="${base}/${entry.id}/do/${a.id}"><button type="submit" data-tone="${a.destructive ? 'danger' : 'secondary'}" data-variant="${a.destructive ? 'outline' : 'solid'}">${a.label}</button></form>`
265
+ )}${
266
+ input.canDelete
267
+ ? html`<form method="get" action="${base}/${entry.id}/delete"><button type="submit" data-tone="danger" data-variant="outline">Delete</button></form>`
268
+ : ''
269
+ }</section>`
270
+ : ''
271
+ }`
272
+ });
273
+ }
274
+
275
+ // ── Confirmation ────────────────────────────────────────────────────
276
+
277
+ export interface ConfirmInput {
278
+ title: string;
279
+ question: string;
280
+ action: string;
281
+ confirmLabel: string;
282
+ destructive: boolean;
283
+ cancel: string;
284
+ /** A picker for the action's target. */
285
+ target?: { label: string; options: { id: string; label: string }[] };
286
+ crumbs?: { label: string; href?: string }[];
287
+ }
288
+
289
+ export function confirmPage(shell: Shell, input: ConfirmInput): Html {
290
+ return page(shell, {
291
+ title: input.title,
292
+ crumbs: input.crumbs,
293
+ body: html`<form method="post" action="${input.action}" class="stack">
294
+ <p>${input.question}</p>${
295
+ input.target
296
+ ? html`<label class="stack">${input.target.label}<select name="target" required><option value="">Choose…</option>${input.target.options.map(
297
+ o => html`<option value="${o.id}">${o.label}</option>`
298
+ )}</select></label>`
299
+ : ''
300
+ }
301
+ <div class="cluster"><button type="submit" data-tone="${input.destructive ? 'danger' : 'primary'}" data-variant="solid">${input.confirmLabel}</button><a href="${input.cancel}">Cancel</a></div>
302
+ </form>`
303
+ });
304
+ }
305
+
306
+ // ── External collections ────────────────────────────────────────────
307
+
308
+ export function externalListPage(
309
+ shell: Shell,
310
+ collection: ExternalCollection<any>,
311
+ rows: ExternalRow[],
312
+ offset: number,
313
+ limit: number,
314
+ hasNext: boolean
315
+ ): Html {
316
+ const base = `${shell.mount}/x/${collection.id}`;
317
+ const label = (r: ExternalRow) => String(r[collection.displayField] ?? '') || r.id;
318
+ return page(shell, {
319
+ title: collection.name,
320
+ body: html`${
321
+ rows.length === 0
322
+ ? html`<p>No rows.</p>`
323
+ : html`<table><thead><tr><th scope="col">${collection.fields[collection.displayField]?.meta.label ?? 'Name'}</th><th scope="col">State</th></tr></thead><tbody>${rows.map(
324
+ r => html`<tr><td><a href="${base}/${r.id}">${label(r)}</a></td><td>${statusBadge(typeof r.state === 'string' ? r.state : r.status)}</td></tr>`
325
+ )}</tbody></table>`
326
+ }<nav class="cluster" aria-label="Pages">${offset > 0 ? html`<a href="${base}${query({ offset: Math.max(offset - limit, 0) })}">Previous</a>` : ''}${
327
+ hasNext ? html`<a href="${base}${query({ offset: offset + limit })}">Next</a>` : ''
328
+ }</nav>`
329
+ });
330
+ }
331
+
332
+ export function externalRowPage(
333
+ shell: Shell,
334
+ collection: ExternalCollection<any>,
335
+ row: ExternalRow,
336
+ refs: ResolveRef,
337
+ actions: AdminAction<any>[],
338
+ notice?: string
339
+ ): Html {
340
+ const base = `${shell.mount}/x/${collection.id}`;
341
+ const title = String(row[collection.displayField] ?? '') || row.id;
342
+ const rows: Row[] = Object.entries(collection.fields).map(([name, builder]) => ({
343
+ name,
344
+ meta: builder.meta,
345
+ value: row[name],
346
+ editable: false
347
+ }));
348
+ return page(shell, {
349
+ title,
350
+ notice,
351
+ crumbs: [{ label: collection.name, href: base }, { label: title }],
352
+ body: html`${fieldRows(rows, [], refs)}${
353
+ actions.length > 0
354
+ ? html`<section class="cluster" aria-label="Actions">${actions.map(
355
+ a => html`<form method="get" action="${base}/${row.id}/do/${a.id}"><button type="submit" data-tone="${a.destructive ? 'danger' : 'secondary'}" data-variant="${a.destructive ? 'outline' : 'solid'}">${a.label}</button></form>`
356
+ )}</section>`
357
+ : ''
358
+ }`
359
+ });
360
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Handoff tokens: a session started somewhere else (an app, an email) given to a
3
+ * browser. Only the SHA-256 of a token is stored; an exchange deletes the row
4
+ * with `DELETE ... RETURNING`, so a token starts one session at most, even when
5
+ * two requests arrive together.
6
+ */
7
+ import type { Context } from 'hono';
8
+ import { clock, createSession, randomToken, type Session, type SessionConfig } from './session.ts';
9
+
10
+ export async function sha256Hex(text: string): Promise<string> {
11
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
12
+ return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
13
+ }
14
+
15
+ /** Mints a token for an owner. The raw token is returned here and never again. */
16
+ export async function mintHandoffToken(
17
+ db: D1Database,
18
+ init: { ownerId: string; lifetimeSeconds: number; now?: () => number }
19
+ ): Promise<{ token: string; expiresAt: number }> {
20
+ if (!init.ownerId) throw new TypeError('A handoff token is for an owner.');
21
+ if (!(init.lifetimeSeconds > 0)) throw new TypeError('A handoff token needs a positive lifetime.');
22
+ const token = randomToken();
23
+ const expiresAt = clock(init) + init.lifetimeSeconds * 1000;
24
+ await db
25
+ .prepare('INSERT INTO handoff_tokens (token_hash, owner_id, expires_at) VALUES (?, ?, ?)')
26
+ .bind(await sha256Hex(token), init.ownerId, expiresAt)
27
+ .run();
28
+ return { token, expiresAt };
29
+ }
30
+
31
+ /** Deletes the tokens past their lifetime that were never exchanged. Returns how many. */
32
+ export async function purgeExpiredHandoffTokens(db: D1Database, now: number = Date.now()): Promise<number> {
33
+ const result = await db.prepare('DELETE FROM handoff_tokens WHERE expires_at <= ?').bind(now).run();
34
+ return result.meta?.changes ?? 0;
35
+ }
36
+
37
+ /**
38
+ * Exchanges a token for a session of `kind`, method `handoff`. Null when the
39
+ * token is unknown, already used, or past its lifetime (an expired one is
40
+ * consumed too).
41
+ */
42
+ export async function exchangeHandoffToken(
43
+ c: Context,
44
+ db: D1Database,
45
+ config: SessionConfig,
46
+ token: string,
47
+ kind: string
48
+ ): Promise<Session | null> {
49
+ if (typeof token !== 'string' || token === '') return null;
50
+ const row = await db
51
+ .prepare('DELETE FROM handoff_tokens WHERE token_hash = ? RETURNING owner_id, expires_at')
52
+ .bind(await sha256Hex(token))
53
+ .first<{ owner_id: string; expires_at: number }>();
54
+ if (!row || row.expires_at <= clock(config)) return null;
55
+ return createSession(c, db, config, { ownerId: row.owner_id, kind, method: 'handoff' });
56
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * cogens/auth: sessions, handoff tokens and the operator's password sign-in.
3
+ * Imports neither `cogens` core nor
4
+ * `cogens/admin`; it gives the host a principal and the store takes it.
5
+ */
6
+ export {
7
+ clearSessionCookie,
8
+ createSession,
9
+ endSession,
10
+ purgeExpiredSessions,
11
+ readSession,
12
+ revokeSessions,
13
+ type NewSession,
14
+ type RequestSource,
15
+ type Session,
16
+ type SessionConfig,
17
+ type SessionRead
18
+ } from './session.ts';
19
+ export { exchangeHandoffToken, mintHandoffToken, purgeExpiredHandoffTokens, sha256Hex } from './handoff.ts';
20
+ export {
21
+ ADMIN_KIND,
22
+ PASSWORD_METHOD,
23
+ passwordRoutes,
24
+ requireAdmin,
25
+ resolveAdmin,
26
+ resolveAdminSession,
27
+ type PasswordOptions
28
+ } from './password.ts';
29
+ export { createPrincipalResolver, type PrincipalOptions, type SessionSource } from './principal.ts';
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The operator's password sign-in, as Hono routes a host mounts, on session rows.
3
+ * It keeps the behaviour reviewed in the README's "The auth package" section: the cookie is
4
+ * signed with its own key (never the password), the password is compared as
5
+ * fixed-length digests, failed attempts per Cloudflare-reported address are
6
+ * limited through `auth_attempts`, and signing out everywhere deletes every
7
+ * `admin` session row.
8
+ */
9
+ import { Hono, type Context, type Next } from 'hono';
10
+ import {
11
+ clearSessionCookie,
12
+ createSession,
13
+ endSession,
14
+ hasKey,
15
+ readSession,
16
+ revokeSessions,
17
+ type RequestSource,
18
+ type Session,
19
+ type SessionConfig
20
+ } from './session.ts';
21
+
22
+ export const ADMIN_KIND = 'admin';
23
+ export const PASSWORD_METHOD = 'password';
24
+
25
+ export interface PasswordOptions {
26
+ /** Cookie name; Koguma's was `koguma_session`. */
27
+ cookieName?: string;
28
+ /** Session lifetime in seconds (24 hours). */
29
+ lifetimeSeconds?: number;
30
+ /** Failed attempts allowed per address within the window. */
31
+ maxAttempts?: number;
32
+ /** Names of the env bindings. */
33
+ envNames?: { password?: string; sessionKey?: string; db?: string };
34
+ now?: () => number;
35
+ }
36
+
37
+ interface Resolved {
38
+ cookieName: string;
39
+ lifetimeSeconds: number;
40
+ maxAttempts: number;
41
+ password: string;
42
+ sessionKey: string;
43
+ db: string;
44
+ now?: () => number;
45
+ }
46
+
47
+ const RETRY_AFTER_SECONDS = 15 * 60; // the "-15 minutes" window in the SQL below
48
+
49
+ function resolve(options: PasswordOptions): Resolved {
50
+ return {
51
+ cookieName: options.cookieName ?? 'koguma_session',
52
+ lifetimeSeconds: options.lifetimeSeconds ?? 24 * 60 * 60,
53
+ maxAttempts: options.maxAttempts ?? 5,
54
+ password: options.envNames?.password ?? 'KOGUMA_SECRET',
55
+ sessionKey: options.envNames?.sessionKey ?? 'KOGUMA_SESSION_KEY',
56
+ db: options.envNames?.db ?? 'DB',
57
+ ...(options.now ? { now: options.now } : {})
58
+ };
59
+ }
60
+
61
+ const env = (c: { env?: unknown }): Record<string, unknown> => (c.env ?? {}) as Record<string, unknown>;
62
+
63
+ function configFor(r: Resolved, envBag: Record<string, unknown>): SessionConfig {
64
+ const key = envBag[r.sessionKey];
65
+ return {
66
+ cookieName: r.cookieName,
67
+ secret: typeof key === 'string' ? key : '',
68
+ lifetimeSeconds: r.lifetimeSeconds,
69
+ ...(r.now ? { now: r.now } : {})
70
+ };
71
+ }
72
+
73
+ const dbOf = (r: Resolved, envBag: Record<string, unknown>) => envBag[r.db] as D1Database | undefined;
74
+
75
+ /** Equal-length digests of both strings, compared without an early exit. */
76
+ async function passwordsMatch(given: string, secret: string): Promise<boolean> {
77
+ const encoder = new TextEncoder();
78
+ const salt = crypto.getRandomValues(new Uint8Array(32));
79
+ const digest = async (value: string) => {
80
+ const key = await crypto.subtle.importKey('raw', salt, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
81
+ return new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(value)));
82
+ };
83
+ const [a, b] = await Promise.all([digest(given), digest(secret)]);
84
+ let diff = 0;
85
+ for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;
86
+ return diff === 0;
87
+ }
88
+
89
+ async function recentAttempts(db: D1Database, ip: string): Promise<number> {
90
+ const row = await db
91
+ .prepare(`SELECT COUNT(*) AS n FROM auth_attempts WHERE ip = ? AND attempted_at > datetime('now','-15 minutes')`)
92
+ .bind(ip)
93
+ .first<{ n: number }>();
94
+ return row?.n ?? 0;
95
+ }
96
+
97
+ async function clearAttempts(db: D1Database, ip: string): Promise<void> {
98
+ await db.prepare('DELETE FROM auth_attempts WHERE ip = ?').bind(ip).run();
99
+ await db.prepare(`DELETE FROM auth_attempts WHERE attempted_at <= datetime('now','-15 minutes')`).run();
100
+ }
101
+
102
+ /** The admin session of a request, with the reason for none. Never writes. */
103
+ export async function resolveAdminSession(
104
+ source: RequestSource,
105
+ envBag: Record<string, unknown>,
106
+ options: PasswordOptions = {}
107
+ ): Promise<{ session: Session; reason?: undefined } | { session: null; reason: string; clear: boolean }> {
108
+ const r = resolve(options);
109
+ const config = configFor(r, envBag);
110
+ if (!hasKey(config)) return { session: null, reason: `${r.sessionKey} not configured`, clear: false };
111
+ const read = await readSession(source, dbOf(r, envBag), config);
112
+ if (read.session === null) {
113
+ const reason = read.reason === 'missing' ? 'Not authenticated' : read.reason === 'expired' ? 'Session expired' : read.reason === 'gone' ? 'Session revoked' : 'Invalid session';
114
+ return { session: null, reason, clear: read.clear };
115
+ }
116
+ if (read.session.kind !== ADMIN_KIND) return { session: null, reason: 'Invalid session', clear: false };
117
+ return { session: read.session };
118
+ }
119
+
120
+ /** `{ kind: 'admin' }` when the request carries a live admin session, else null. */
121
+ export async function resolveAdmin(c: Context | RequestSource, options: PasswordOptions = {}): Promise<{ kind: 'admin' } | null> {
122
+ const got = await resolveAdminSession(c as RequestSource, env(c as { env?: unknown }), options);
123
+ return got.session ? { kind: 'admin' } : null;
124
+ }
125
+
126
+ /** Refuses with 401 anyone without an admin session. */
127
+ export function requireAdmin(options: PasswordOptions = {}) {
128
+ const r = resolve(options);
129
+ return async (c: Context, next: Next): Promise<Response | void> => {
130
+ const envBag = env(c);
131
+ if (!envBag[r.password]) return c.json({ error: `${r.password} not configured` }, 500);
132
+ const got = await resolveAdminSession(c, envBag, options);
133
+ if (!got.session) {
134
+ if (got.clear) clearSessionCookie(c, configFor(r, envBag));
135
+ return c.json({ error: got.reason }, 401);
136
+ }
137
+ c.set('principal' as never, { kind: 'admin' } as never);
138
+ await next();
139
+ };
140
+ }
141
+
142
+ /**
143
+ * The routes, to mount at `/api/auth` as Koguma's were:
144
+ * POST /login, POST /logout, POST /logout-all (admin only), GET /me (admin only).
145
+ */
146
+ export function passwordRoutes(options: PasswordOptions = {}): Hono {
147
+ const r = resolve(options);
148
+ const app = new Hono();
149
+
150
+ app.post('/login', async c => {
151
+ const envBag = env(c);
152
+ const secret = envBag[r.password];
153
+ const config = configFor(r, envBag);
154
+ const db = dbOf(r, envBag);
155
+ if (typeof secret !== 'string' || !secret || !hasKey(config) || !db) {
156
+ return c.json({ error: `${r.password} and ${r.sessionKey} (32+ characters) must be configured` }, 500);
157
+ }
158
+ // Only Cloudflare's own header: X-Forwarded-For is client-supplied.
159
+ const ip = c.req.header('CF-Connecting-IP') ?? 'unknown';
160
+
161
+ if ((await recentAttempts(db, ip)) >= r.maxAttempts) {
162
+ c.header('Retry-After', String(RETRY_AFTER_SECONDS));
163
+ return c.json({ error: 'Too many login attempts. Try again later.' }, 429);
164
+ }
165
+
166
+ let body: { password?: unknown };
167
+ try {
168
+ body = await c.req.json<{ password?: unknown }>();
169
+ } catch {
170
+ return c.json({ error: 'Password required' }, 400);
171
+ }
172
+ if (typeof body.password !== 'string' || !body.password) return c.json({ error: 'Password required' }, 400);
173
+
174
+ if (!(await passwordsMatch(body.password, secret))) {
175
+ await db.prepare('INSERT INTO auth_attempts (ip) VALUES (?)').bind(ip).run();
176
+ return c.json({ error: 'Invalid password' }, 401);
177
+ }
178
+ await clearAttempts(db, ip);
179
+ await createSession(c, db, config, { ownerId: null, kind: ADMIN_KIND, method: PASSWORD_METHOD });
180
+ return c.json({ ok: true });
181
+ });
182
+
183
+ app.post('/logout', async c => {
184
+ const envBag = env(c);
185
+ const db = dbOf(r, envBag);
186
+ if (db) await endSession(c, db, configFor(r, envBag));
187
+ else clearSessionCookie(c, configFor(r, envBag));
188
+ return c.json({ ok: true });
189
+ });
190
+
191
+ app.post('/logout-all', requireAdmin(options), async c => {
192
+ const envBag = env(c);
193
+ await revokeSessions(dbOf(r, envBag)!, { kind: ADMIN_KIND });
194
+ clearSessionCookie(c, configFor(r, envBag));
195
+ return c.json({ ok: true });
196
+ });
197
+
198
+ app.get('/me', requireAdmin(options), c => c.json({ authenticated: true }));
199
+
200
+ return app;
201
+ }