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
package/CHANGELOG.md ADDED
@@ -0,0 +1,21 @@
1
+ # Changelog
2
+
3
+ ## 0.2.1
4
+
5
+ - The package now ships compiled JavaScript (ES modules) with `.d.ts` declarations, declaration maps and source maps in `dist/`. `exports` point there, so Node 20 or later, Vitest and Node scripts can import it; Node refuses `.ts` files under `node_modules`. Wrangler and Bun are unaffected.
6
+ - `cogens-print-migration` runs under Node (`#!/usr/bin/env node`): `.js` and `.mjs` configs always, `.ts` configs on a Node that strips types. The printer moved from `scripts/print-migration.ts` to `src/migrations-tool/`; the `cogens/migrations-tool` import is unchanged, and `cogens/scripts/print-migration.ts` is gone.
7
+ - `scripts/build-admin-editor.ts` stays Bun-only and stays a shipped `.ts` script.
8
+ - `engines` gains `node >=20`.
9
+
10
+ ## 0.2.0
11
+
12
+ - Renamed from coauthcms to cogens. Publishable: README for a public audience, `LICENSE` and `NOTICE`, `hono` pinned to `~4.12.2`.
13
+ - Editor plugins receive the field's type and name and replace the built-in directive syntax; `createTestDb`; `migrations-tool` and `scripts` exports.
14
+
15
+ ## 0.1.1
16
+
17
+ - Sinfon's directive syntax applies only to notebook fields in the admin.
18
+
19
+ ## 0.1.0
20
+
21
+ - Extracted from Sinfon's `site/packages` (a multi-tenant fork of Koguma): content types, access rules, principals, the server-rendered admin and the session tables.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthew Eric Goodwin
4
+ Copyright (c) 2026 Vikram Rojo
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,25 @@
1
+ cogens
2
+
3
+ Copyright (c) 2026 Vikram Rojo
4
+ Licensed under the MIT License (LICENSE).
5
+
6
+ cogens is a fork of Koguma, a schema-driven headless CMS for Cloudflare
7
+ Workers, and keeps its notice:
8
+
9
+ Koguma
10
+ https://github.com/m4ttheweric/koguma
11
+ Copyright (c) 2026 Matthew Eric Goodwin
12
+ MIT License
13
+ Forked at commit 485dd0f6308e191c9ea565029ba48b52ba059eae (2026-08-03),
14
+ package version 2.3.11.
15
+
16
+ What derives from Koguma: the `entries` and `assets` tables, the content-type
17
+ and field definitions, the slug and publish handling, and the password
18
+ sign-in's behaviour. The access engine, the store's caller model, the admin
19
+ pages, the session tables and the rest were written for cogens; Koguma's
20
+ React dashboard, CLI and public content API are not part of it.
21
+
22
+ The admin's markdown editor, built by scripts/build-admin-editor.ts, bundles
23
+ Milkdown Crepe and the packages it depends on (each MIT, except DOMPurify,
24
+ which is MPL-2.0 or Apache-2.0 and used under Apache-2.0). The build writes
25
+ their licence texts beside the bundle (admin-editor.LICENSES.txt).
package/README.md CHANGED
@@ -1,3 +1,395 @@
1
- # Temporary Holding Version
1
+ # cogens
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A light multi-tenant content store for Cloudflare Workers (D1, R2, Hono). Every entry may have an owner, and every query passes an access check: you cannot write a read or a write without saying who is calling, and a read the caller may not make answers as a missing row.
4
+
5
+ It is a fork of [Koguma](https://github.com/m4ttheweric/koguma) (MIT). Koguma's database and config code is the starting point; the access engine, the principal model, the server-rendered admin and the session tables are new. See `NOTICE`.
6
+
7
+ One package, these entry points:
8
+
9
+ | Import | What it is | Runtime dependencies it uses |
10
+ | --- | --- | --- |
11
+ | `cogens` | The store: content types and fields, access rules, `createCms`, `content.as(principal)`, media, the policy test helper | `hono`, `@casl/ability`, `@cfworker/json-schema` |
12
+ | `cogens/admin` | The admin: server-rendered Hono pages that are an ordinary client of `content.as` | `hono` and core |
13
+ | `cogens/auth` | Sessions on D1 rows, one-time handoff tokens, the operator's password sign-in | `hono` |
14
+ | `cogens/testing` | The policy matrix helper (also exported from `cogens`) and `createTestDb`, a Miniflare D1 with the migrations applied | none; `createTestDb` needs `miniflare` in the host |
15
+ | `cogens/migrations-tool` | `migrationLines`, the function behind `cogens-print-migration` | core's types only |
16
+
17
+ The package's `dependencies` are those three and no more; a test (`test/boundary.test.ts`) fails if core imports a fourth, if admin imports anything of ours but core, if auth imports core or admin, or if anything outside `src/core/store` reaches the SQL layer. No React anywhere.
18
+
19
+ It is a library you embed in your own Worker. It is not a hosted service, a standalone CMS with its own sign-in for end users, or a React dashboard: you supply the sign-in and say who is calling; the package supplies the store, the access checks and a small server-rendered admin. It was written for [Sinfon](https://sinfon.app), the first host, and is used there.
20
+
21
+ Status: 0.2.1, pre-1.0. The API may change before 1.0.
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ bun add cogens
27
+ # or
28
+ npm install cogens
29
+ ```
30
+
31
+ It runs in Cloudflare Workers (Wrangler), Node 20 or later (scripts, Vitest, any bundler) and Bun. The package ships compiled ES modules with type declarations in `dist/`, so none of them needs a TypeScript loader. The types name Cloudflare's `D1Database` and `R2Bucket`, so a TypeScript host adds `@cloudflare/workers-types` to its `types`.
32
+
33
+ Two tools are not Node's: `scripts/build-admin-editor.ts` (the admin's editor bundle) uses `Bun.build` and runs under Bun only, and `cogens-print-migration` loads a `.ts` config only under Bun or a Node that strips types (see Migrations).
34
+
35
+ To use an unreleased commit, pin it: `bun add github:vikramrojo/cogens#<commit>`.
36
+
37
+ ## Quick start
38
+
39
+ Define one owned type and read an entry back as its owner. This walk-through uses [Bun](https://bun.sh) 1.4 or later to run a `.ts` file; the package itself needs only Node 20 or later (or Bun, or Workers).
40
+
41
+ ```sh
42
+ mkdir hello && cd hello
43
+ bun init -y
44
+ bun add cogens
45
+ bun add -d miniflare @cloudflare/workers-types
46
+ ```
47
+
48
+ Save as `hello.ts`:
49
+
50
+ ```ts
51
+ import { readFileSync } from 'node:fs';
52
+ import { Miniflare } from 'miniflare';
53
+ import { contentType, createCms, field, type AccessContext, type Principal } from 'cogens';
54
+
55
+ // Your own kind of caller. The store never reads a cookie; you decide who is calling.
56
+ interface Member { kind: 'member'; id: string }
57
+
58
+ // An owned type: each row has an owner, and the rules say what an owner may do.
59
+ const note = contentType({
60
+ id: 'note',
61
+ name: 'Notes',
62
+ displayField: 'title',
63
+ owned: true,
64
+ fields: {
65
+ title: field.text('Title').required(),
66
+ body: field.markdown('Body')
67
+ },
68
+ access(principal: Principal<Member>, { can }: AccessContext) {
69
+ if (principal.kind === 'member') {
70
+ can(['create', 'read', 'update', 'delete'], { where: { owner_id: principal.id } });
71
+ }
72
+ }
73
+ });
74
+
75
+ // An in-memory D1 with the package's migration applied (on Cloudflare, `wrangler d1 migrations apply` does this).
76
+ const mf = new Miniflare({ modules: true, script: 'export default {}', d1Databases: { DB: 'hello' } });
77
+ const db = (await mf.getD1Database('DB')) as unknown as D1Database;
78
+ const migration = readFileSync('node_modules/cogens/migrations/0001_entries.sql', 'utf8');
79
+ for (const statement of migration.split('\n').filter(l => !l.trim().startsWith('--')).join('\n').split(';')) {
80
+ if (statement.trim()) await db.prepare(statement).run();
81
+ }
82
+
83
+ const cms = createCms<Member>({ db, types: [note], probes: [{ kind: 'member', id: 'probe' }] });
84
+
85
+ const ada: Member = { kind: 'member', id: 'ada' };
86
+ const bob: Member = { kind: 'member', id: 'bob' };
87
+
88
+ await cms.content.as(ada).create('note', { title: 'Hello', body: 'First **note**', owner_id: 'ada' });
89
+
90
+ console.log('ada sees', (await cms.content.as(ada).list('note')).map(n => n.data.title));
91
+ console.log('bob sees', (await cms.content.as(bob).list('note')).map(n => n.data.title));
92
+ await mf.dispose();
93
+ ```
94
+
95
+ Run it:
96
+
97
+ ```sh
98
+ bun run hello.ts
99
+ ```
100
+
101
+ It prints `ada sees [ "Hello" ]` and `bob sees []`.
102
+
103
+ `probes` is one sample of each kind of caller you add. At startup the store runs every type's `access` against the built-in kinds and your probes and compiles what they grant, so a rule that cannot be turned into SQL stops the Worker before it serves a request.
104
+
105
+ The `examples/worker` folder in this repository is the same idea as a Worker: a `note` type, a `member` principal resolved from a session cookie, the admin at `/admin`, and two JSON routes. `bun test test/example.test.ts` runs it in Miniflare.
106
+
107
+ ## Content types
108
+
109
+ ```ts
110
+ contentType({
111
+ id: 'article', // lowercase letter first; letters, digits, - and _
112
+ name: 'Articles',
113
+ displayField: 'title',
114
+ owned: true, // entries have an owner_id; the type must then have `access`
115
+ uniqueSlug: true, // slug unique within the type (a partial unique index)
116
+ indexed: ['visibility'], // fields rules and `where` may name (see Migrations)
117
+ parent: 'series', // children of another type: parent_id, sort_key
118
+ mirrors: ['status'], // a child copies its parent's published state (below)
119
+ access(principal, { can }) { /* ... */ },
120
+ beforeWrite(ctx) { /* ... */ },
121
+ afterWrite(ctx) { /* ... */ },
122
+ fields: { title: field.text('Title').required().max(200), /* ... */ }
123
+ });
124
+ ```
125
+
126
+ Field builders: `text`, `longText`, `markdown`, `url`, `email`, `boolean`, `number`, `date`, `select(label, { options })`, `ref(type, label)`, `refs(type, label)`, `files`, `json`. A field may be `.required()`, `.default(v)`, `.min(n)`, `.max(n)` and `.system()` (written only by a grant that lists it). Values are checked with `@cfworker/json-schema`; a bad value is a `ValidationError`.
127
+
128
+ An entry has the type's fields in `data` and these built-in columns: `id`, `owner_id`, `slug`, `status` (`draft` or `published`), `parent_id`, `sort_key`, `parent_status`, `created_at`, `updated_at`. Their names are reserved as field names.
129
+
130
+ ## Principals and rules
131
+
132
+ A caller is a `Principal`: three built-in kinds and any you add.
133
+
134
+ ```ts
135
+ import { admin, anonymous, system } from 'cogens';
136
+
137
+ admin(); // { kind: 'admin' }; the operator
138
+ anonymous; // { kind: 'anonymous' }
139
+ system('job-name'); // background work, naming its job
140
+ // your own: { kind: 'member', id: 'ada' }, any object with a string `kind`
141
+ ```
142
+
143
+ No kind has built-in power: the default is deny for everyone, the admin and `system` included. A type that should be open to the operator says so in its rules.
144
+
145
+ `access(principal, { can })` runs once per call to `content.as(principal)` and grants operations:
146
+
147
+ ```ts
148
+ can('read', { where: { status: 'published', visibility: 'public' } }); // anyone
149
+ can('read', { bySlug: true, where: { status: 'published' } }); // a lookup by a slug the caller knows, not a list
150
+ can(['update', 'delete'], { where: { owner_id: principal.id }, fields: ['title', 'body'] });
151
+ can('create'); // every row, every field
152
+ ```
153
+
154
+ The operations are `create`, `read`, `update`, `delete` and `publish`. A `where` accepts equals, `in` (at most 90 values), `and` and `or`, over the built-in columns and the type's `indexed` fields; anything else throws when the store starts, not when a request arrives. `fields` limits what a create or update may write; a system field, `owner_id`, `slug`, `parent_id` or `sort_key`, is writable only when a grant lists it.
155
+
156
+ Each grant's `where` is compiled to a parameterised SQL condition, which the store ANDs into every `SELECT`, `UPDATE` and `DELETE`. CASL decides which fields are permitted; no export names a CASL type, so it can be replaced. Property tests compare the compiled SQL on a real D1 against CASL's in-memory answer for generated rows and rules.
157
+
158
+ ```ts
159
+ const api = cms.content.as(principal);
160
+ await api.create('note', { title, owner_id });
161
+ await api.get('note', id); // null when missing or not readable
162
+ await api.getBySlug('note', slug);
163
+ await api.list('note', { where: { f: 1 }, orderBy: 'created_at', direction: 'desc', limit: 50, offset: 0 });
164
+ await api.update('note', id, { title: 'New' });
165
+ await api.remove('note', id);
166
+ await api.publish('note', id); // and unpublish
167
+ ```
168
+
169
+ Refusals are typed: `Forbidden` (the caller may not), `ValidationError`, `Conflict`, `WriteRefused` (a hook refused), `TooManyEntries`, `TooManyChildren`, `ConfigError`, `ConditionError`.
170
+
171
+ ### `updateEach`: several entries in one write
172
+
173
+ ```ts
174
+ await api.updateEach('note', [
175
+ { id: a, patch: { sort_key: '1' } },
176
+ { id: b, patch: { sort_key: '2' } }
177
+ ]);
178
+ ```
179
+
180
+ All or nothing, in one D1 batch (one round trip): every row must be one the caller may update, each patch meets the rules `update` applies, and the hooks run per row. A row that moved out of reach between the read and the write fails the whole call as `Forbidden` and rolls the batch back. More than `maxUpdateEach` entries (500 by default) is `TooManyEntries`.
181
+
182
+ ### Conditional update
183
+
184
+ ```ts
185
+ const result = await api.update('note', id, { rev: 5 }, { when: { rev: { lt: 5 } } });
186
+ if (!result.applied) { /* result.reason === 'precondition' */ }
187
+ ```
188
+
189
+ `when` takes `{ field: { equals | lt | gt | isNull } }` and `{ or: [...] }`, compiled into the same `WHERE` as the access condition and checked in the same statement, so two racing writers leave the higher value. It reports whether it applied.
190
+
191
+ ### Mirrors
192
+
193
+ A type with `parent` and `mirrors: ['status']` copies its parent's status into `parent_status`. Publishing or unpublishing the parent runs as one `db.batch` (the parent, then one `UPDATE ... WHERE parent_id = ?` for all children), so a rule on `parent_status` makes the children readable the moment the parent is published. `maxMirrorChildren` (10,000 by default) caps the children one publish may change, checked before the batch.
194
+
195
+ ### Hooks
196
+
197
+ `beforeWrite(ctx)` and `afterWrite(ctx)` get `{ operation, type, principal, existing, input, content }` (`afterWrite` also gets `entry`). `ctx.content` is the store as the same caller. `ctx.refuse('message')` in `beforeWrite` stops the write with `WriteRefused`; nothing is stored. Use hooks for what rules cannot see, such as a value being written.
198
+
199
+ ### The public read API is off by default
200
+
201
+ `cms.publicApi` is a Hono app answering `GET /:type` and `GET /:type/:slugOrId`, as the `anonymous` caller, for the types named in `publicTypes`; with none named every route is a 404. Mount it where you like:
202
+
203
+ ```ts
204
+ const cms = createCms({ db, types, publicTypes: ['page'] });
205
+ app.route('/api/content', cms.publicApi);
206
+ ```
207
+
208
+ It answers only what the type's rules let an anonymous caller read.
209
+
210
+ ### Media
211
+
212
+ Pass `media: { bucket, access }` to `createCms` for upload, list and delete through `cms.media.as(principal)`, with an `access` function of its own over `owner_id` and `id`, and a size cap (`maxBytes`, 10 MB). With no `media` option there is none.
213
+
214
+ ### External collections and service types
215
+
216
+ A type declared `service: { readOnly: true }` is never stored in `entries`: it names a table of your own so the admin can show it (below).
217
+
218
+ ## The policy matrix
219
+
220
+ `policyMatrix` (from `cogens` or `cogens/testing`) is for your own tests. Name sample callers and what each should be able to do on each type; it asserts every operation on every type (anything unlisted must be denied) and that the rules packed for the browser (`cms.access.rulesFor`) agree with what the engine enforces, row by row.
221
+
222
+ ```ts
223
+ import { policyMatrix } from 'cogens/testing';
224
+
225
+ policyMatrix({
226
+ cms,
227
+ callers: { ada: { kind: 'member', id: 'ada' }, anon: anonymous },
228
+ expect: { ada: { note: ['create', 'read', 'lookup', 'update', 'delete'] }, anon: {} },
229
+ rows: { note: [{ owner_id: 'ada' }, { owner_id: 'bob' }] }
230
+ });
231
+ ```
232
+
233
+ It uses no test framework; it throws `PolicyMismatch` naming each caller, type and operation that disagrees. `lookup` is a read by slug.
234
+
235
+ ## The admin
236
+
237
+ ```ts
238
+ import { createAdmin } from 'cogens/admin';
239
+
240
+ const host = new Hono().route('/admin', createAdmin({
241
+ cms,
242
+ resolvePrincipal: c => /* your Principal, or null */,
243
+ mount: '/admin',
244
+ siteName: 'My site',
245
+ session // optional: draws a sign-in page and the sign-out forms
246
+ }));
247
+ ```
248
+
249
+ The pages (type list, entry list, entry view and edit, delete confirmation, external collection list and row) are Hono routes rendered with `hono/html`. The admin is an ordinary client of `content.as(principal)` for the principal you resolve, so it can do nothing the type's rules refuse that caller; it offers a button only if `cms.access.rulesFor` says the caller may press it. Writes are forms that POST and redirect with 303, refused unless they come from the admin's own origin (`hono/csrf`), under a content security policy (`hono/secure-headers`).
250
+
251
+ Options: `externalCollections` (read-only views over your own tables, with `list`, `get`, `actions` and `allow`), `typeActions` (extra buttons on a type's entries; an action with the id `unpublish` or `delete` replaces the page's own), `session` (`{ signIn, signOut, signOutEverywhere }` as functions that answer a `Response`), `unauthorized` (what to answer when there is no principal and no `session`), and `assets`.
252
+
253
+ Static files the admin links, which your Worker serves (default URLs in `DEFAULT_ASSETS`): Largen's `largen.css` and `largen-theme-dark.css` (the `largen` package; without them the pages are plain HTML), and the markdown editor: `admin-editor.js`, `admin-editor.css` and `admin-editor-dark.css`. The admin's own script and style are served by the admin itself at `<mount>/assets/`. If the editor does not load, a markdown field is a plain textarea.
254
+
255
+ Build the editor into your static folder (it needs `@milkdown/crepe`, an optional peer dependency):
256
+
257
+ ```sh
258
+ bun add -d @milkdown/crepe
259
+ bun run node_modules/cogens/scripts/build-admin-editor.ts public
260
+ ```
261
+
262
+ It writes `admin-editor.js`, `admin-editor.css`, `admin-editor-dark.css` and `admin-editor.LICENSES.txt`, the licence texts of the packages bundled (the module's banner names it; serve it beside the module). The editor has no syntax of its own beyond markdown; a host adds its own with a plugin module.
263
+
264
+ ### Editor plugins
265
+
266
+ `build-admin-editor.ts <outDir> --plugins <module>` bundles a host file into the editor. The module's default export is a function `(builder, context) => void | Promise<void>`. It is called once per editor with Crepe's builder (`builder.editor` is the Milkdown editor) and `context = { type, field }`, the content type id and the field name of the text area, before the editor is created, so it can add remark plugins, nodes and node views. The admin renders each markdown text area with `data-type` and `data-field` for this. A plugin's syntax applies to every markdown field unless it checks the context: a plugin that ignores the second argument keeps working, and an ordinary field's text is saved unchanged only if the syntax was not added to it.
267
+
268
+ `--plugins` paths resolve from the current working directory, not from the build script or the package. The module imports its own Milkdown packages (and any remark plugin) from the host's `node_modules`, so add them to the host (`bun add -d @milkdown/kit remark-directive`). Without `--plugins` the bundle contains none of this.
269
+
270
+ For example, `:mention[ada]` as a chip that saves as the same text:
271
+
272
+ ```js
273
+ // editor-plugin.js
274
+ import { remarkPluginsCtx } from '@milkdown/kit/core';
275
+ import { $node } from '@milkdown/kit/utils';
276
+ import remarkDirective from 'remark-directive';
277
+
278
+ const labelOf = node => (node.children || []).map(c => c.value ?? '').join('');
279
+
280
+ const mention = $node('mention', () => ({
281
+ group: 'inline',
282
+ inline: true,
283
+ atom: true,
284
+ attrs: { name: { default: '' } },
285
+ parseDOM: [{ tag: 'span[data-mention]', getAttrs: dom => ({ name: dom.getAttribute('data-mention') }) }],
286
+ toDOM: node => ['span', { 'data-mention': node.attrs.name, contenteditable: 'false' }, `@${node.attrs.name}`],
287
+ parseMarkdown: {
288
+ match: node => node.type === 'textDirective' && node.name === 'mention',
289
+ runner: (state, node, type) => { state.addNode(type, { name: labelOf(node) }); }
290
+ },
291
+ toMarkdown: {
292
+ match: node => node.type.name === 'mention',
293
+ runner: (state, node) => { state.addNode('textDirective', [{ type: 'text', value: node.attrs.name }], undefined, { name: 'mention', attributes: {} }); }
294
+ }
295
+ }));
296
+
297
+ export default function (builder, context) {
298
+ // Only the `note` type's `body` field has mentions; any other field keeps its text exactly as stored.
299
+ if (context.type !== 'note' || context.field !== 'body') return;
300
+ builder.editor
301
+ .config(ctx => ctx.update(remarkPluginsCtx, plugins => [...plugins, { plugin: remarkDirective, options: {} }]))
302
+ .use(mention);
303
+ }
304
+ ```
305
+
306
+ ```sh
307
+ bun run node_modules/cogens/scripts/build-admin-editor.ts public --plugins ./editor-plugin.js
308
+ ```
309
+
310
+ `remark-directive` also reads any other `:word` in prose as a directive, so a real plugin should turn the ones it does not own back into text, as `test/fixtures/mention-plugin.js` does. The editor module's `createEditor` returns `{ getMarkdown, editor }`.
311
+
312
+ ## The auth package
313
+
314
+ ```ts
315
+ import {
316
+ createPrincipalResolver, passwordRoutes, createSession, readSession, endSession, revokeSessions,
317
+ mintHandoffToken, exchangeHandoffToken, purgeExpiredSessions, purgeExpiredHandoffTokens, sha256Hex
318
+ } from 'cogens/auth';
319
+ ```
320
+
321
+ - **Sessions** are rows in `sessions` named by a signed cookie that holds only a random id. A row says whose session it is (`ownerId`, an opaque string, null for the operator), its `kind` (`admin`, or whatever you call it), its `method` (`password`, `handoff`) and when it ends. The signing key is at least 32 characters and is never a password. `revokeSessions(db, { ownerId, kind })` signs out everywhere and refuses to run with neither.
322
+ - **Handoff tokens** start a session somewhere else (an app, an email link) and give it to a browser: `mintHandoffToken(db, { ownerId, lifetimeSeconds })` returns the raw token once, only its SHA-256 is stored, and `exchangeHandoffToken(c, db, config, token, kind)` deletes the row with `DELETE ... RETURNING`, so a token starts at most one session even when two requests arrive together.
323
+ - **The operator's password sign-in** is `passwordRoutes()`, Hono routes to mount at `/api/auth` (`POST /login`, `/logout`, `/logout-all`, `GET /me`). The cookie is signed with its own key, the password is compared as fixed-length digests, failed attempts per `CF-Connecting-IP` are limited (5 in 15 minutes) through `auth_attempts`, and sign-out-everywhere deletes every `admin` session row. Defaults carried over from Koguma, all overridable in `PasswordOptions`: cookie `koguma_session`, env bindings `KOGUMA_SECRET` (the password), `KOGUMA_SESSION_KEY` (the signing key) and `DB`.
324
+ - **`createPrincipalResolver`** is the one function that learns who a request is: an admin session gives `{ kind: 'admin' }`; a session of another kind goes through your `SessionSource` (`config(env)` gives the cookie and key, `principal(session, env)` your principal or null); anything else is null, and you decide anonymous or 401.
325
+
326
+ The package never learns what an owner is. It imports neither core nor admin.
327
+
328
+ ## Testing with a database
329
+
330
+ `createTestDb` (from `cogens/testing`) starts a Miniflare D1 and R2 bucket, applies the package's own migrations (`0001_entries.sql`, `auth/0001_sessions.sql`) and then each SQL file you list (paths from the working directory), and returns `{ db, r2, dispose }`. Miniflare is an optional peer dependency, imported only when the function runs: `bun add -d miniflare`.
331
+
332
+ ```ts
333
+ import { createTestDb } from 'cogens/testing';
334
+ import { migrationLines } from 'cogens/migrations-tool';
335
+
336
+ const t = await createTestDb({ migrations: ['migrations/0002_my_types.sql'] });
337
+ const cms = createCms({ config, db: t.db });
338
+ // ...
339
+ await t.dispose();
340
+ ```
341
+
342
+ `migrationLines(types)` returns the SQL lines `cogens-print-migration` prints for a list of content types, so a test can compare them with your migration file. The editor build script resolves by name: `cogens/scripts/build-admin-editor.ts`.
343
+
344
+ ## Migrations
345
+
346
+ SQL files a host applies, in this order (copy them into your Wrangler `migrations_dir` under numbers that fit, as `examples/worker/migrations` does, or run them with `wrangler d1 execute`):
347
+
348
+ 1. `migrations/0001_entries.sql`: `entries` (Koguma's columns plus `owner_id`, `parent_id`, `sort_key`, `parent_status`), `assets` (plus `owner_id`) and their indexes.
349
+ 2. `migrations/auth/0001_sessions.sql`, only if you import `cogens/auth`: `sessions`, `handoff_tokens`, `identities`, `auth_attempts`, `auth_meta`.
350
+ 3. The lines for your own types' indexed fields, which `print-migration` prints for your config.
351
+
352
+ A rule or `where` may name only the built-in columns and a type's `indexed` fields; an indexed field is a virtual generated column over the entry's JSON (SQLite's `ALTER TABLE ADD COLUMN` allows only virtual ones, and they can be indexed), plus a partial unique index on `(content_type, slug)` for types with `uniqueSlug`. Print them from a config file whose default export is `{ contentTypes }` (what `defineConfig` returns):
353
+
354
+ ```sh
355
+ bunx --bun cogens-print-migration site.config.ts # Bun: any config file, .ts included
356
+ npx cogens-print-migration site.config.mjs # Node: a .js or .mjs config
357
+ ```
358
+
359
+ The command's shebang is `node`, so plain `bunx` also runs it under Node; `bunx --bun` runs it under Bun. Under Node the command imports the config as written. A `.js` or `.mjs` config always works; a `.ts` config works only on a Node that strips types (22.18 or later, and 24), in a project whose `package.json` has `"type": "module"`, and only if its own imports resolve there. Otherwise use `bunx --bun`, or compile the config. The same lines come from `migrationLines(contentTypes)` in `cogens/migrations-tool`.
360
+
361
+ Put the printed lines in a migration of your own. At startup, on first use, the store compares them with `PRAGMA table_xinfo(entries)` and fails naming the type and field if one is missing.
362
+
363
+ **A database that already has Koguma's `entries` and `assets`** (its own `0001`) must not apply `0001_entries.sql`, whose `CREATE TABLE IF NOT EXISTS` would skip the tables and leave the new columns missing. Apply `migrations/koguma-upgrade.sql` instead, which adds the four columns, `assets.owner_id` and the indexes. A host that already added those columns itself skips both. The auth tables are independent of either. Nothing in these files names any host's tables.
364
+
365
+ ## The import boundary
366
+
367
+ - `cogens` (core) imports `hono`, `@casl/ability` and `@cfworker/json-schema` and nothing else.
368
+ - `cogens/admin` imports core and `hono`.
369
+ - `cogens/auth` imports `hono` only.
370
+ - Only files under `src/core/store` import `src/core/store/sql.ts`, the one file that names the tables holding entries and assets, so a query without an access decision cannot be written from outside.
371
+ - Plain folders under `src/`, no workspaces. Your Worker's bundle includes only the entry points you import.
372
+
373
+ ## Development
374
+
375
+ ```sh
376
+ bun install
377
+ bun run build # src/ to dist/ (tsc, tsconfig.build.json); the tests import the package by name, so they need it
378
+ bun test # the package's tests, the example Worker in Miniflare included
379
+ bun run test # build, then test
380
+ bun run typecheck # src, the example, the scripts
381
+ ```
382
+
383
+ `dist/` is not committed. `npm publish` runs `prepublishOnly` (build, then test), so a published package always has a fresh build.
384
+
385
+ ## Contributing
386
+
387
+ Issues are welcome: bug reports, questions, and notes on where the access rules or the docs surprised you. Pull requests are welcome by arrangement: open an issue first to agree the change, since the package is small on purpose (see the import boundary above). Run `bun test` and `bun run typecheck` before sending anything.
388
+
389
+ ## Security
390
+
391
+ Please report a vulnerability privately through GitHub's private vulnerability reporting (the Security tab of this repository, "Report a vulnerability"), not in a public issue. The access engine and the session code are the parts where a flaw matters most.
392
+
393
+ ## Licence
394
+
395
+ MIT. Copyright (c) 2026 Matthew Eric Goodwin (Koguma) and Vikram Rojo. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,21 @@
1
+ /**
2
+ * createAdmin: the admin's routes as a Hono app for the host to mount where it
3
+ * likes. Every read and write of entries goes through `cms.content.as(principal)`
4
+ * for the principal the host resolved, so the admin can do nothing the type's
5
+ * rules refuse that caller; `cms.access.rulesFor` only decides what to draw.
6
+ *
7
+ * app.route('/admin2', createAdmin({ cms, resolvePrincipal, mount: '/admin2' }))
8
+ *
9
+ * Writes are forms that POST and answer 303. They are refused unless they are
10
+ * form posts from the admin's own origin (hono/csrf, plus a content-type check,
11
+ * since csrf looks only at form content types), and every page carries a content
12
+ * security policy that names the admin's script, the editor and the stylesheets.
13
+ */
14
+ import { Hono } from 'hono';
15
+ import { type HostPrincipal } from '../core/index.ts';
16
+ import type { AdminAssets, AdminOptions } from './types.ts';
17
+ export declare const DEFAULT_ASSETS: AdminAssets;
18
+ export declare function createAdmin<H extends HostPrincipal = never>(options: AdminOptions<H>): Hono<any>;
19
+ /** Mounts the admin on a host app: `mountAdmin(app, '/admin2', options)`. */
20
+ export declare function mountAdmin<H extends HostPrincipal = never>(host: Hono<any>, path: string, options: Omit<AdminOptions<H>, 'mount'>): void;
21
+ //# sourceMappingURL=app.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../../src/admin/app.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,IAAI,EAAgB,MAAM,MAAM,CAAC;AAI1C,OAAO,EAEyC,KAAK,aAAa,EACjE,MAAM,kBAAkB,CAAC;AAK1B,OAAO,KAAK,EAAe,WAAW,EAAE,YAAY,EAAmC,MAAM,YAAY,CAAC;AAM1G,eAAO,MAAM,cAAc,EAAE,WAM5B,CAAC;AAYF,wBAAgB,WAAW,CAAC,CAAC,SAAS,aAAa,GAAG,KAAK,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAyiBhG;AAED,6EAA6E;AAC7E,wBAAgB,UAAU,CAAC,CAAC,SAAS,aAAa,GAAG,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,IAAI,CAExI"}