@kitcms/core 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +200 -2
- package/bin/kitcms.js +10 -0
- package/package.json +89 -3
- package/src/access/engine.ts +304 -0
- package/src/access/entitlements.ts +46 -0
- package/src/admin/form.ts +167 -0
- package/src/admin/panel.ts +93 -0
- package/src/admin/types.ts +202 -0
- package/src/api/cache.ts +315 -0
- package/src/api/local.ts +1034 -0
- package/src/api/populate.ts +70 -0
- package/src/api/types.ts +266 -0
- package/src/auth/better-auth.ts +133 -0
- package/src/auth/cookies.ts +37 -0
- package/src/auth/guard.ts +51 -0
- package/src/auth/module-admin.ts +119 -0
- package/src/auth/module.ts +61 -0
- package/src/auth/rate-limit.ts +105 -0
- package/src/auth/session.ts +28 -0
- package/src/auth/users.ts +280 -0
- package/src/cli/__fixtures__/app/src/kitcms.config.ts +10 -0
- package/src/cli/__fixtures__/app/wrangler.jsonc +5 -0
- package/src/cli/args.ts +124 -0
- package/src/cli/cli.tsconfig.json +6 -0
- package/src/cli/commands.ts +160 -0
- package/src/cli/generate-types.ts +157 -0
- package/src/cli/index.ts +1 -0
- package/src/cli/load-config.ts +47 -0
- package/src/cli/run.ts +61 -0
- package/src/cli/seed.ts +132 -0
- package/src/client.ts +18 -0
- package/src/config/collection.ts +411 -0
- package/src/config/fields.ts +371 -0
- package/src/config/hooks.ts +186 -0
- package/src/config/infer.ts +84 -0
- package/src/config/plugin.ts +183 -0
- package/src/config/sanitize.ts +1186 -0
- package/src/config/sanitized.ts +272 -0
- package/src/config/where.ts +78 -0
- package/src/db/adapter.ts +162 -0
- package/src/db/d1.ts +463 -0
- package/src/db/session.ts +39 -0
- package/src/db/where.ts +258 -0
- package/src/email/index.ts +147 -0
- package/src/errors.ts +97 -0
- package/src/fields/defaults.ts +117 -0
- package/src/fields/test-fixtures.ts +41 -0
- package/src/fields/traverse.ts +82 -0
- package/src/fields/validate.ts +264 -0
- package/src/hooks/run.ts +52 -0
- package/src/index.ts +49 -0
- package/src/order/key.ts +129 -0
- package/src/refs/extract.ts +31 -0
- package/src/richtext/html.ts +171 -0
- package/src/richtext/index.ts +3 -0
- package/src/richtext/valid.ts +37 -0
- package/src/rpc/index.ts +357 -0
- package/src/runtime.ts +63 -0
- package/src/schema/codegen.ts +66 -0
- package/src/schema/drizzle.ts +80 -0
- package/src/schema/spec.ts +99 -0
- package/src/schema/tables.ts +170 -0
- package/src/seed.ts +214 -0
- package/src/storage/adapter.ts +40 -0
- package/src/storage/r2.ts +51 -0
- package/src/sveltekit/admin.ts +714 -0
- package/src/sveltekit/api.ts +205 -0
- package/src/sveltekit/base.ts +28 -0
- package/src/sveltekit/index.ts +177 -0
- package/src/sveltekit/paths.ts +33 -0
- package/src/sveltekit/plugins.ts +180 -0
- package/src/sveltekit/rest.ts +263 -0
- package/src/ulid.ts +11 -0
- package/src/upload/handler.ts +125 -0
- package/src/upload/serve.ts +102 -0
- package/src/upload/sniff.ts +187 -0
- package/src/vite/index.ts +181 -0
- package/src/vite/tsconfig.json +5 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kitcms contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,201 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kitcms/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Config, field definitions, the Local API, access rules, hooks, D1 storage, R2 uploads, Better Auth, the SvelteKit integration, the Service Binding RPC entrypoint and the `kitcms` CLI. You define collections in code; kitcms creates the D1 schema from that code and serves them through `locals.cms` and the admin UI.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm add @kitcms/core @kitcms/ui
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Pair it with `@sveltejs/kit` (v3), `@sveltejs/adapter-cloudflare`, `@sveltejs/vite-plugin-svelte`, `vite`, `wrangler` and `@cloudflare/vite-plugin`. `pnpm create kitcms@latest` sets all of this up.
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
Define the config (`src/kitcms.config.ts`, from `templates/blank`):
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { collection, defineConfig, fields as f } from '@kitcms/core';
|
|
17
|
+
|
|
18
|
+
export default defineConfig({
|
|
19
|
+
admin: { title: 'My site' },
|
|
20
|
+
collections: [
|
|
21
|
+
collection({
|
|
22
|
+
slug: 'media',
|
|
23
|
+
upload: { mimeTypes: ['image/*', 'application/pdf'] },
|
|
24
|
+
access: { read: () => true },
|
|
25
|
+
fields: { alt: f.text() },
|
|
26
|
+
}),
|
|
27
|
+
collection({
|
|
28
|
+
slug: 'pages',
|
|
29
|
+
admin: { useAsTitle: 'title', defaultColumns: ['title', 'slug', 'status', 'updatedAt'] },
|
|
30
|
+
access: {
|
|
31
|
+
// Published pages are public; signed-in users also see drafts.
|
|
32
|
+
read: ({ req }) => (req.user ? true : { status: { equals: 'published' } }),
|
|
33
|
+
},
|
|
34
|
+
fields: {
|
|
35
|
+
title: f.text({ required: true }),
|
|
36
|
+
slug: f.slug({ from: 'title', unique: true, admin: { position: 'sidebar' } }),
|
|
37
|
+
status: f.select({
|
|
38
|
+
options: ['draft', 'published'],
|
|
39
|
+
defaultValue: 'draft',
|
|
40
|
+
required: true,
|
|
41
|
+
admin: { position: 'sidebar' },
|
|
42
|
+
}),
|
|
43
|
+
body: f.textarea(),
|
|
44
|
+
},
|
|
45
|
+
}),
|
|
46
|
+
],
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Fields: `text`, `textarea`, `email`, `slug`, `number`, `checkbox`, `select`, `date`, `richText`, `json`, `relationship`, `upload`, `group`, `array`, `blocks`, plus the layout-only `row`, `collapsible` and `tabs`.
|
|
51
|
+
|
|
52
|
+
Register the config type and wire the Worker (`src/app.d.ts`, `src/hooks.server.ts`):
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
// src/app.d.ts
|
|
56
|
+
import type config from './kitcms.config';
|
|
57
|
+
|
|
58
|
+
declare module '@kitcms/core' {
|
|
59
|
+
interface Register {
|
|
60
|
+
config: typeof config;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
// src/hooks.server.ts
|
|
67
|
+
import { kitcms } from '@kitcms/core/sveltekit';
|
|
68
|
+
import config from './kitcms.config';
|
|
69
|
+
|
|
70
|
+
export const handle = kitcms({ config }).handle;
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
After that, `locals.cms` is typed and runs every read as the request's user:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
// src/routes/+page.server.ts
|
|
77
|
+
import type { PageServerLoad } from './$types';
|
|
78
|
+
|
|
79
|
+
export const load: PageServerLoad = async ({ locals }) => {
|
|
80
|
+
const { docs } = await locals.cms.find('pages', { sort: '-updatedAt', limit: 20 });
|
|
81
|
+
return { pages: docs };
|
|
82
|
+
};
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Build with the Vite plugin and the Cloudflare adapter (`vite.config.ts`):
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { sveltekit } from '@sveltejs/kit/vite';
|
|
89
|
+
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
|
|
90
|
+
import { kitcms, kitcmsAdapter } from '@kitcms/core/vite';
|
|
91
|
+
import { defineConfig } from 'vite';
|
|
92
|
+
|
|
93
|
+
export default defineConfig({
|
|
94
|
+
plugins: [sveltekit({ preprocess: vitePreprocess(), adapter: kitcmsAdapter() }), kitcms()],
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The RPC entrypoint lives in `src/kitcms.rpc.ts`. It is only needed for headless consumers (see `@kitcms/client`):
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { createKitcmsRPC } from '@kitcms/core/rpc';
|
|
102
|
+
import config from './kitcms.config';
|
|
103
|
+
|
|
104
|
+
export class KitcmsRPC extends createKitcmsRPC(config) {}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Drafts and versions
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
collection({ slug: 'pages', versions: { drafts: { autosave: true }, max: 20 }, fields: { /* ... */ } });
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
- The table holds the **published** state. Reads without `draft: true` only return published documents (also when populating relationships); `draft: true` needs a signed-in user or `overrideAccess`.
|
|
114
|
+
- `cms.update(..., { draft: true })` saves a draft version; `cms.update(...)` without it publishes the latest draft merged with `data`. `cms.unpublish(collection, id)` takes a document offline.
|
|
115
|
+
- `cms.findVersions`, `findVersionByID`, `restoreVersion` (and the `...Global...` variants) need read **and** update access to the document.
|
|
116
|
+
- `versions: true` keeps history only (no drafts, no `_status`).
|
|
117
|
+
|
|
118
|
+
## Admin branding
|
|
119
|
+
|
|
120
|
+
`admin.branding` white-labels the admin. Everything is optional and validated when the config loads:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
admin: {
|
|
124
|
+
title: 'My site',
|
|
125
|
+
branding: {
|
|
126
|
+
logo: 'https://cdn.example.com/logo.svg', // https://, a /-relative path, or a base64 data:image/ URL
|
|
127
|
+
colors: { accent: '#0b7285', accentText: '#ffffff' }, // CSS colors: hex, rgb(), hsl(), oklch(), oklab() or a named color
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- `colors.accent` and `colors.accentText` are set as the `--kc-accent` and `--kc-accent-text` CSS variables on the admin root. Set both or neither. Hover and focus states follow the accent. Without them the default theme is used, including dark mode.
|
|
133
|
+
- `logo` is shown in the admin header (next to the title) and above the sign-in and first-user forms. The title is always shown as text.
|
|
134
|
+
|
|
135
|
+
## REST API
|
|
136
|
+
|
|
137
|
+
A JSON fallback for browsers and third parties that can't use a Service Binding. On Cloudflare, prefer Service Binding RPC (`@kitcms/client`) (no public surface, no auth round trip). It is served by the generated `src/routes/(kitcms)/api/[...path]/+server.ts` (`export { GET, POST, PATCH, DELETE } from '@kitcms/core/sveltekit/api'`; re-run the scaffold or add `PATCH, DELETE` to existing apps).
|
|
138
|
+
|
|
139
|
+
| Route | Action |
|
|
140
|
+
|---|---|
|
|
141
|
+
| `GET /api/collections/:slug` | `find` (paginated) |
|
|
142
|
+
| `POST /api/collections/:slug` | `create` (201). Not for `upload` or auth collections (405) |
|
|
143
|
+
| `GET / PATCH / DELETE /api/collections/:slug/:id` | `findByID` (404 when missing) / `update` / `delete` |
|
|
144
|
+
| `POST /api/collections/:slug/:id/move` | body `{ "before": id }` or `{ "after": id }` (orderable collections) |
|
|
145
|
+
| `POST /api/collections/:slug/:id/unpublish` | take a published doc offline (drafts) |
|
|
146
|
+
| `GET / PATCH /api/globals/:slug` | `findGlobal` / `updateGlobal` |
|
|
147
|
+
|
|
148
|
+
Read params: `where` (JSON object, same syntax as the Local API), `sort` (`-createdAt`), `limit`, `page`, `depth` (0-2), `pagination=false`, `draft=true` (signed-in only). Numbers must be plain integers, or the response is `400`. Write params: `depth`, `draft=true` (save as draft). Bodies must be `application/json` (415), at most 1 MiB (413) and a JSON object (400).
|
|
149
|
+
|
|
150
|
+
Auth: the caller is the session user (Better Auth cookie) or anonymous. It goes through the same access rules, hooks and validation as the Local API, and nothing in the request can bypass them. Anonymous writes reach the pipeline and are denied by the default rules. Every `POST`/`PATCH`/`DELETE` also needs a same-origin `Origin` header (CSRF), or the response is `403`.
|
|
151
|
+
|
|
152
|
+
Errors are `{ "error": string, "code": string, "errors"?: FieldError[], "references"?: [...] }` with the kitcms status (validation 400, forbidden 403, not found 404, still referenced 409). Unexpected failures return `500 { "error": "Internal error" }`. Responses send `cache-control: no-store`.
|
|
153
|
+
|
|
154
|
+
Turn it off with `defineConfig({ rest: false })`: every `/api/collections/*` and `/api/globals/*` route then returns 404 (admin, upload and media routes are unaffected).
|
|
155
|
+
|
|
156
|
+
## Edge cache (optional)
|
|
157
|
+
|
|
158
|
+
`defineConfig({ cache: { ttl: 60 } })` caches anonymous published reads of the Local API (`find`, `findOne`, `findByID`, `count`, `findGlobal`) in the Workers Cache API, per data centre. This covers public pages, anonymous RPC and anonymous REST. Signed-in users, drafts, `overrideAccess` and calls that pass `req` or `context` are never cached.
|
|
159
|
+
|
|
160
|
+
Every write (from any caller) replaces a generation token, so the data centre that handled the write serves fresh content immediately. Other data centres keep their entries until `ttl` seconds pass. Keys include a fingerprint of your schema, so a deploy with a changed schema never reads old entries.
|
|
161
|
+
|
|
162
|
+
The Cache API does nothing on `*.workers.dev`; use a custom domain. If the cache is unavailable, reads fall back to D1.
|
|
163
|
+
|
|
164
|
+
## D1 read replication (optional)
|
|
165
|
+
|
|
166
|
+
kitcms already uses the D1 Sessions API on every request, so read replication works without code changes. Turn it on for your database in the Cloudflare dashboard (**D1 → your database → Settings → Read replication**).
|
|
167
|
+
|
|
168
|
+
- Anonymous requests (public pages, anonymous REST and RPC reads) read from the nearest replica.
|
|
169
|
+
- Signed-in users carry a bookmark in an `HttpOnly` cookie (`kitcms-d1`), so editors always see their own saves.
|
|
170
|
+
- RPC calls with `as: 'system'` start on the primary, since they may write and then read.
|
|
171
|
+
|
|
172
|
+
With replication off, every session reads from the primary, the same as before. Replication mainly helps visitors far from the primary when the edge cache misses. The templates also enable Smart Placement (`"placement": { "mode": "smart" }` in `wrangler.jsonc`), which can run the Worker near the database when that is faster.
|
|
173
|
+
|
|
174
|
+
## CLI
|
|
175
|
+
|
|
176
|
+
The `kitcms` bin (from `@kitcms/core`) runs these commands. Each one reads the config from `src/kitcms.config.ts` or `kitcms.config.ts`, or from `--config <path>`:
|
|
177
|
+
|
|
178
|
+
```
|
|
179
|
+
Usage: kitcms <command> [options]
|
|
180
|
+
|
|
181
|
+
Commands:
|
|
182
|
+
generate:schema Write drizzle/schema.ts from the kitcms config
|
|
183
|
+
generate:types [--out <path>] Write kitcms-types.d.ts (document types for @kitcms/client)
|
|
184
|
+
migrate:create <name> Generate schema, then create a SQL migration in ./migrations
|
|
185
|
+
migrate [--remote] Apply migrations with wrangler (local D1 by default)
|
|
186
|
+
migrate:status [--remote] List migrations with wrangler
|
|
187
|
+
info Show config, collections, bindings and migrations_dir check
|
|
188
|
+
|
|
189
|
+
Options:
|
|
190
|
+
--config <path> Path to the kitcms config (default: src/kitcms.config.ts or kitcms.config.ts)
|
|
191
|
+
--out <path> Output file for generate:types (default: kitcms-types.d.ts)
|
|
192
|
+
--remote Target the remote D1 database (migrate, migrate:status)
|
|
193
|
+
--help, -h Show this help
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## Notes
|
|
197
|
+
|
|
198
|
+
- Workers Paid is required. Password hashing (scrypt) uses more CPU than the free plan allows.
|
|
199
|
+
- Don't set `declaration` in the app's tsconfig. With large configs `declaration: true` fails with TS7056.
|
|
200
|
+
|
|
201
|
+
Status: pre-release (0.x), Cloudflare Workers + D1 + R2 only.
|
package/bin/kitcms.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The package ships TypeScript sources (no build step), and Node does not strip types inside
|
|
3
|
+
// node_modules. Vite's module runner (already required to load the user's config) transpiles
|
|
4
|
+
// the CLI on the fly, so this works from node_modules with no extra dependency.
|
|
5
|
+
import { runnerImport } from 'vite';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const entry = fileURLToPath(new URL('../src/cli/index.ts', import.meta.url));
|
|
9
|
+
const { module } = await runnerImport(entry, { root: process.cwd(), configFile: false, logLevel: 'error' });
|
|
10
|
+
process.exitCode = await module.run(process.argv.slice(2), process.cwd());
|
package/package.json
CHANGED
|
@@ -1,6 +1,92 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kitcms/core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/Norden-Tenzin/kitcms.git",
|
|
8
|
+
"directory": "packages/core"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://kitcms.dev",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/Norden-Tenzin/kitcms/issues"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./src/index.ts",
|
|
19
|
+
"default": "./src/index.ts"
|
|
20
|
+
},
|
|
21
|
+
"./sveltekit": {
|
|
22
|
+
"types": "./src/sveltekit/index.ts",
|
|
23
|
+
"default": "./src/sveltekit/index.ts"
|
|
24
|
+
},
|
|
25
|
+
"./rpc": {
|
|
26
|
+
"types": "./src/rpc/index.ts",
|
|
27
|
+
"default": "./src/rpc/index.ts"
|
|
28
|
+
},
|
|
29
|
+
"./sveltekit/admin": {
|
|
30
|
+
"types": "./src/sveltekit/admin.ts",
|
|
31
|
+
"default": "./src/sveltekit/admin.ts"
|
|
32
|
+
},
|
|
33
|
+
"./client": {
|
|
34
|
+
"types": "./src/client.ts",
|
|
35
|
+
"default": "./src/client.ts"
|
|
36
|
+
},
|
|
37
|
+
"./sveltekit/api": {
|
|
38
|
+
"types": "./src/sveltekit/api.ts",
|
|
39
|
+
"default": "./src/sveltekit/api.ts"
|
|
40
|
+
},
|
|
41
|
+
"./richtext": {
|
|
42
|
+
"types": "./src/richtext/index.ts",
|
|
43
|
+
"default": "./src/richtext/index.ts"
|
|
44
|
+
},
|
|
45
|
+
"./vite": {
|
|
46
|
+
"types": "./src/vite/index.ts",
|
|
47
|
+
"default": "./src/vite/index.ts"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"bin": {
|
|
51
|
+
"kitcms": "./bin/kitcms.js"
|
|
52
|
+
},
|
|
53
|
+
"files": [
|
|
54
|
+
"src",
|
|
55
|
+
"bin",
|
|
56
|
+
"!src/**/*.test.ts"
|
|
57
|
+
],
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"@sveltejs/adapter-cloudflare": "^8",
|
|
60
|
+
"@sveltejs/kit": "^3",
|
|
61
|
+
"@sveltejs/vite-plugin-svelte": "^7",
|
|
62
|
+
"vite": "^8",
|
|
63
|
+
"wrangler": "^4",
|
|
64
|
+
"@cloudflare/vite-plugin": "^1.69.0"
|
|
65
|
+
},
|
|
66
|
+
"devDependencies": {
|
|
67
|
+
"@cloudflare/vite-plugin": "^1.69.1",
|
|
68
|
+
"@sveltejs/adapter-cloudflare": "^8.0.2",
|
|
69
|
+
"@sveltejs/kit": "^3.2.0",
|
|
70
|
+
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
|
71
|
+
"@types/node": "^26.6.6",
|
|
72
|
+
"miniflare": "5.20261113.0-beta",
|
|
73
|
+
"vite": "^8.3.8",
|
|
74
|
+
"wrangler": "^4.162.0"
|
|
75
|
+
},
|
|
76
|
+
"dependencies": {
|
|
77
|
+
"better-auth": "^1.7.25",
|
|
78
|
+
"drizzle-kit": "^0.31.11",
|
|
79
|
+
"drizzle-orm": "^0.45.4"
|
|
80
|
+
},
|
|
81
|
+
"peerDependenciesMeta": {
|
|
82
|
+
"wrangler": {
|
|
83
|
+
"optional": true
|
|
84
|
+
},
|
|
85
|
+
"@cloudflare/vite-plugin": {
|
|
86
|
+
"optional": true
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"scripts": {
|
|
90
|
+
"typecheck": "tsc --noEmit && tsc -p test/tsconfig.json && tsc -p src/cli/cli.tsconfig.json && tsc -p src/vite/tsconfig.json"
|
|
91
|
+
}
|
|
6
92
|
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// Access-control engine (plan §4.6). SECURITY-CRITICAL: changes need Opus review and tests.
|
|
2
|
+
//
|
|
3
|
+
// Rules:
|
|
4
|
+
// - Fail closed. A rule that returns anything other than `true`, `false` or a plain `where`
|
|
5
|
+
// object denies. A rule that throws fails the operation. `create` and `admin` rules must
|
|
6
|
+
// return booleans (a `where` there denies).
|
|
7
|
+
// - Defaults when a rule is omitted (Decision 22): signed-in users only. The auth collection has
|
|
8
|
+
// stricter defaults: create/delete admin-only, update admin or self, and its `role` and
|
|
9
|
+
// `emailVerified` fields are writable by admins only.
|
|
10
|
+
// - A `where` from a rule is ANDed with the caller's `where` as a separate group (`mergeWhere`),
|
|
11
|
+
// so nothing the caller passes can widen it.
|
|
12
|
+
// - `overrideAccess` skips collection AND field rules. It is never derived from client input.
|
|
13
|
+
// - `admin.locked` collections and globals deny create/delete to everyone but `overrideAccess`.
|
|
14
|
+
// - Upload built-in fields (filename, key, ...) are writable only through the upload endpoint,
|
|
15
|
+
// which marks its `req` with `markUploadWrite` (an unforgeable WeakSet entry, not a context key).
|
|
16
|
+
|
|
17
|
+
import type { KitcmsReq, KitcmsUser, Operation } from '../config/hooks';
|
|
18
|
+
import type { SanitizedCollection, SanitizedConfig, SanitizedField } from '../config/sanitized';
|
|
19
|
+
import type { WhereInput } from '../config/where';
|
|
20
|
+
import { ForbiddenError } from '../errors';
|
|
21
|
+
import { collectionEntitled } from './entitlements';
|
|
22
|
+
|
|
23
|
+
/** `true` (allow all), `false` (deny), or a filter the documents must match. */
|
|
24
|
+
export type AccessDecision = boolean | WhereInput;
|
|
25
|
+
|
|
26
|
+
export const ADMIN_ROLE = 'admin';
|
|
27
|
+
|
|
28
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
29
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
30
|
+
const proto: unknown = Object.getPrototypeOf(value);
|
|
31
|
+
return proto === Object.prototype || proto === null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Normalizes a rule's return value. Anything unexpected denies. */
|
|
35
|
+
export function normalizeDecision(result: unknown, allowWhere: boolean): AccessDecision {
|
|
36
|
+
if (result === true) return true;
|
|
37
|
+
if (allowWhere && isPlainObject(result)) return result as WhereInput;
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function isAdmin(user: KitcmsUser | null): boolean {
|
|
42
|
+
return user !== null && user.role === ADMIN_ROLE;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function signedIn({ req }: { req: KitcmsReq }): boolean {
|
|
46
|
+
return req.user !== null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The defaults applied when a collection omits a rule. */
|
|
50
|
+
function defaultRule(
|
|
51
|
+
collection: SanitizedCollection,
|
|
52
|
+
operation: Operation,
|
|
53
|
+
req: KitcmsReq,
|
|
54
|
+
): AccessDecision {
|
|
55
|
+
if (!collection.auth) return signedIn({ req });
|
|
56
|
+
const user = req.user;
|
|
57
|
+
switch (operation) {
|
|
58
|
+
case 'read':
|
|
59
|
+
return user !== null;
|
|
60
|
+
case 'create':
|
|
61
|
+
case 'delete':
|
|
62
|
+
return isAdmin(user);
|
|
63
|
+
case 'update':
|
|
64
|
+
if (isAdmin(user)) return true;
|
|
65
|
+
return user !== null ? { id: { equals: user.id } } : false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface AccessArgsInput {
|
|
70
|
+
req: KitcmsReq;
|
|
71
|
+
id?: string;
|
|
72
|
+
data?: Record<string, unknown>;
|
|
73
|
+
overrideAccess?: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Evaluates a collection-level rule. */
|
|
77
|
+
export async function collectionAccess(
|
|
78
|
+
collection: SanitizedCollection,
|
|
79
|
+
operation: Operation,
|
|
80
|
+
args: AccessArgsInput,
|
|
81
|
+
): Promise<AccessDecision> {
|
|
82
|
+
if (args.overrideAccess) return true;
|
|
83
|
+
// Runtime add-on gate (Decision 34): an add-on that is off denies everything but trusted code.
|
|
84
|
+
if (collection.entitlement !== undefined && !(await collectionEntitled(collection))) {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
// Locked collections (§13.3) and globals: no create/delete, whatever the rules say. Checked
|
|
88
|
+
// before the rule, so a permissive `create`/`delete` rule can't re-open them.
|
|
89
|
+
if ((operation === 'create' || operation === 'delete') && (collection.admin.locked || collection.kind === 'global')) {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
const rule = collection.access[operation] as
|
|
93
|
+
| ((a: { req: KitcmsReq; id?: string; data?: Record<string, unknown> }) => unknown)
|
|
94
|
+
| undefined;
|
|
95
|
+
if (!rule) return defaultRule(collection, operation, args.req);
|
|
96
|
+
const result = await rule({ req: args.req, id: args.id, data: args.data });
|
|
97
|
+
return normalizeDecision(result, operation !== 'create');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** ANDs an access `where` onto the caller's filter. `false` must be handled by the caller first. */
|
|
101
|
+
export function mergeWhere(
|
|
102
|
+
callerWhere: WhereInput | undefined,
|
|
103
|
+
decision: Exclude<AccessDecision, false>,
|
|
104
|
+
): WhereInput | undefined {
|
|
105
|
+
if (decision === true) return callerWhere;
|
|
106
|
+
if (!callerWhere || Object.keys(callerWhere).length === 0) return { and: [decision] };
|
|
107
|
+
return { and: [callerWhere, decision] };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* May this user use the admin panel? The auth collection's `access.admin`, or by default: the
|
|
112
|
+
* user's role is one of the `role` field's options.
|
|
113
|
+
*/
|
|
114
|
+
export async function adminAccess(config: SanitizedConfig, req: KitcmsReq): Promise<boolean> {
|
|
115
|
+
const user = req.user;
|
|
116
|
+
if (user === null) return false;
|
|
117
|
+
const auth = config.collectionsBySlug[config.authCollection];
|
|
118
|
+
if (!auth) return false;
|
|
119
|
+
if (auth.access.admin) {
|
|
120
|
+
return normalizeDecision(await auth.access.admin({ req }), false) === true;
|
|
121
|
+
}
|
|
122
|
+
const role = auth.fields.find((f) => f.name === 'role');
|
|
123
|
+
if (role?.type !== 'select') return false;
|
|
124
|
+
return role.options.some((o) => o.value === user.role);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ---------------------------------------------------------------------------------------------
|
|
128
|
+
// Field-level access
|
|
129
|
+
// ---------------------------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
const uploadWrites = new WeakSet<KitcmsReq>();
|
|
132
|
+
|
|
133
|
+
/** Marks a request as the upload endpoint's own write (allows writing upload built-in fields). */
|
|
134
|
+
export function markUploadWrite(req: KitcmsReq): void {
|
|
135
|
+
uploadWrites.add(req);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export const UPLOAD_FIELDS = ['filename', 'mimeType', 'filesize', 'width', 'height', 'key'] as const;
|
|
139
|
+
const ADMIN_ONLY_AUTH_FIELDS = ['role', 'emailVerified'] as const;
|
|
140
|
+
|
|
141
|
+
type FieldRule = (args: {
|
|
142
|
+
req: KitcmsReq;
|
|
143
|
+
id?: string;
|
|
144
|
+
data?: Record<string, unknown>;
|
|
145
|
+
siblingData?: Record<string, unknown>;
|
|
146
|
+
}) => unknown;
|
|
147
|
+
|
|
148
|
+
/** The write rule for a top-level built-in field, or undefined. */
|
|
149
|
+
function builtInWriteRule(
|
|
150
|
+
collection: SanitizedCollection,
|
|
151
|
+
field: SanitizedField,
|
|
152
|
+
operation: 'create' | 'update',
|
|
153
|
+
): FieldRule | undefined {
|
|
154
|
+
if (collection.upload && (UPLOAD_FIELDS as readonly string[]).includes(field.name)) {
|
|
155
|
+
return ({ req }) => uploadWrites.has(req);
|
|
156
|
+
}
|
|
157
|
+
if (
|
|
158
|
+
collection.auth &&
|
|
159
|
+
(ADMIN_ONLY_AUTH_FIELDS as readonly string[]).includes(field.name) &&
|
|
160
|
+
!field.access?.[operation]
|
|
161
|
+
) {
|
|
162
|
+
return ({ req }) => isAdmin(req.user);
|
|
163
|
+
}
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function allowed(rule: FieldRule | undefined, args: Parameters<FieldRule>[0]) {
|
|
168
|
+
if (!rule) return true;
|
|
169
|
+
return (await rule(args)) === true;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Removes fields the user may not read, recursively (mutates `doc`). Denied containers are
|
|
174
|
+
* removed whole.
|
|
175
|
+
*/
|
|
176
|
+
export async function filterReadableFields(
|
|
177
|
+
fields: readonly SanitizedField[],
|
|
178
|
+
doc: Record<string, unknown>,
|
|
179
|
+
req: KitcmsReq,
|
|
180
|
+
id: string | undefined,
|
|
181
|
+
root: Record<string, unknown> = doc,
|
|
182
|
+
): Promise<void> {
|
|
183
|
+
for (const field of fields) {
|
|
184
|
+
if (!(field.name in doc)) continue;
|
|
185
|
+
const rule = field.access?.read as FieldRule | undefined;
|
|
186
|
+
if (!(await allowed(rule, { req, id, data: root, siblingData: doc }))) {
|
|
187
|
+
delete doc[field.name];
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
await forEachChildContainer(field, doc[field.name], (childFields, child) =>
|
|
191
|
+
filterReadableFields(childFields, child, req, id, root),
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Applies field create/update access to incoming data (mutates `data`). A denied value is
|
|
198
|
+
* dropped on create (so the default applies) and reset to the stored value on update (rows are
|
|
199
|
+
* matched to stored rows by `id`; a denied field in a new row is dropped).
|
|
200
|
+
* `original` is the stored counterpart of `data` at this level (undefined on create / new rows).
|
|
201
|
+
*/
|
|
202
|
+
export async function applyWriteFieldAccess(
|
|
203
|
+
collection: SanitizedCollection,
|
|
204
|
+
fields: readonly SanitizedField[],
|
|
205
|
+
data: Record<string, unknown>,
|
|
206
|
+
operation: 'create' | 'update',
|
|
207
|
+
ctx: { req: KitcmsReq; id?: string; root: Record<string, unknown>; topLevel: boolean },
|
|
208
|
+
original: Record<string, unknown> | undefined,
|
|
209
|
+
): Promise<void> {
|
|
210
|
+
for (const field of fields) {
|
|
211
|
+
if (!(field.name in data)) continue;
|
|
212
|
+
const custom = field.access?.[operation] as FieldRule | undefined;
|
|
213
|
+
const builtIn = ctx.topLevel ? builtInWriteRule(collection, field, operation) : undefined;
|
|
214
|
+
const args = { req: ctx.req, id: ctx.id, data: ctx.root, siblingData: data };
|
|
215
|
+
const ok = (await allowed(builtIn, args)) && (await allowed(custom, args));
|
|
216
|
+
if (!ok) {
|
|
217
|
+
if (original && field.name in original) data[field.name] = structuredClone(original[field.name]);
|
|
218
|
+
else delete data[field.name];
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const value = data[field.name];
|
|
222
|
+
const stored = original?.[field.name];
|
|
223
|
+
const childCtx = { ...ctx, topLevel: false };
|
|
224
|
+
if (field.type === 'group' && isPlainObject(value)) {
|
|
225
|
+
await applyWriteFieldAccess(collection, field.fields, value, operation, childCtx,
|
|
226
|
+
isPlainObject(stored) ? stored : undefined);
|
|
227
|
+
} else if ((field.type === 'array' || field.type === 'blocks') && Array.isArray(value)) {
|
|
228
|
+
const storedRows = new Map<string, Record<string, unknown>>();
|
|
229
|
+
if (Array.isArray(stored)) {
|
|
230
|
+
for (const r of stored) if (isPlainObject(r) && typeof r.id === 'string') storedRows.set(r.id, r);
|
|
231
|
+
}
|
|
232
|
+
for (const row of value) {
|
|
233
|
+
if (!isPlainObject(row)) continue;
|
|
234
|
+
const childFields =
|
|
235
|
+
field.type === 'array' ? field.fields : field.blocks.find((b) => b.slug === row.blockType)?.fields;
|
|
236
|
+
if (!childFields) continue;
|
|
237
|
+
const match = typeof row.id === 'string' ? storedRows.get(row.id) : undefined;
|
|
238
|
+
// A stored row only counts as the same row if it is the same block type.
|
|
239
|
+
const prev = match && (field.type === 'array' || match.blockType === row.blockType) ? match : undefined;
|
|
240
|
+
await applyWriteFieldAccess(collection, childFields, row, operation, childCtx, prev);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function forEachChildContainer(
|
|
247
|
+
field: SanitizedField,
|
|
248
|
+
value: unknown,
|
|
249
|
+
fn: (fields: readonly SanitizedField[], child: Record<string, unknown>) => Promise<void>,
|
|
250
|
+
): Promise<void> {
|
|
251
|
+
if (field.type === 'group' && isPlainObject(value)) {
|
|
252
|
+
await fn(field.fields, value);
|
|
253
|
+
} else if (field.type === 'array' && Array.isArray(value)) {
|
|
254
|
+
for (const row of value) if (isPlainObject(row)) await fn(field.fields, row);
|
|
255
|
+
} else if (field.type === 'blocks' && Array.isArray(value)) {
|
|
256
|
+
for (const row of value) {
|
|
257
|
+
if (!isPlainObject(row)) continue;
|
|
258
|
+
const block = field.blocks.find((b) => b.slug === row.blockType);
|
|
259
|
+
if (block) await fn(block.fields, row);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---------------------------------------------------------------------------------------------
|
|
265
|
+
// Query access: no filtering or sorting on fields the caller can't read
|
|
266
|
+
// ---------------------------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
/** Top-level field names a caller's `where` references (recursing through and/or). */
|
|
269
|
+
export function whereFields(where: WhereInput | undefined, out = new Set<string>(), depth = 0): Set<string> {
|
|
270
|
+
if (!where || typeof where !== 'object' || depth > 16) return out;
|
|
271
|
+
for (const [key, value] of Object.entries(where)) {
|
|
272
|
+
if ((key === 'and' || key === 'or') && Array.isArray(value)) {
|
|
273
|
+
for (const w of value) whereFields(w as WhereInput, out, depth + 1);
|
|
274
|
+
} else {
|
|
275
|
+
out.add(key);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Throws `ForbiddenError` when the caller filters or sorts on a field whose read access denies
|
|
283
|
+
* them: otherwise `where` would be an oracle for values they can't read (filter on `secret`, see
|
|
284
|
+
* which documents come back). Field rules are evaluated without a document. Only the CALLER's
|
|
285
|
+
* `where` is checked; `where` filters from access rules are trusted code.
|
|
286
|
+
*/
|
|
287
|
+
export async function assertQueryable(
|
|
288
|
+
collection: SanitizedCollection,
|
|
289
|
+
where: WhereInput | undefined,
|
|
290
|
+
sort: string[],
|
|
291
|
+
req: KitcmsReq,
|
|
292
|
+
overrideAccess: boolean | undefined,
|
|
293
|
+
): Promise<void> {
|
|
294
|
+
if (overrideAccess) return;
|
|
295
|
+
const names = whereFields(where);
|
|
296
|
+
for (const s of sort) names.add(s.startsWith('-') ? s.slice(1) : s);
|
|
297
|
+
for (const name of names) {
|
|
298
|
+
const field = collection.fields.find((f) => f.name === name);
|
|
299
|
+
const rule = field?.access?.read as FieldRule | undefined;
|
|
300
|
+
if (rule && !(await allowed(rule, { req }))) {
|
|
301
|
+
throw new ForbiddenError(`You may not query the field "${name}".`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|