create-knit 0.5.0 → 0.7.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/index.mjs +3 -1
- package/package.json +1 -1
- package/template/base/.claude/skills/knit-add-model/SKILL.md +1 -1
- package/template/base/.claude/skills/knit-add-permission/SKILL.md +27 -0
- package/template/base/.claude/skills/knit-add-sign-in/SKILL.md +28 -0
- package/template/base/.claude/skills/knit-add-task/SKILL.md +25 -0
- package/template/base/.claude/skills/knit-add-translation/SKILL.md +22 -0
- package/template/base/.claude/skills/knit-deploy/SKILL.md +27 -0
- package/template/base/.claude/skills/knit-write-e2e-test/SKILL.md +26 -0
- package/template/base/AGENTS.md +18 -3
- package/template/base/CLAUDE.md +1 -1
- package/template/base/apps/web/.env.example +30 -0
- package/template/base/llms.txt +2 -0
- package/template/examples/layers/example-blog/admin.ts +5 -3
- package/template/examples/layers/example-blog/app/pages/blog/[slug].vue +1 -1
- package/template/examples/layers/example-blog/server/channels/comments.ts +4 -28
- package/template/examples/layers/example-blog/server/database/schema.ts +21 -3
- package/template/examples/layers/example-blog/server/resources/comments.ts +8 -14
- package/template/versions.json +1 -1
package/index.mjs
CHANGED
|
@@ -115,7 +115,7 @@ function writeProject(target, name, examples) {
|
|
|
115
115
|
vitest: versions.vitest,
|
|
116
116
|
},
|
|
117
117
|
// Project settings, read by the `knit` CLI and the core layer.
|
|
118
|
-
knit: { app: 'apps/web', layersDir: 'layers', migrationsDir: 'server/database/migrations' },
|
|
118
|
+
knit: { app: 'apps/web', layersDir: 'layers', migrationsDir: 'server/database/migrations', template: versions.knit },
|
|
119
119
|
}))
|
|
120
120
|
|
|
121
121
|
writeFileSync(join(target, 'pnpm-workspace.yaml'), [
|
|
@@ -129,6 +129,8 @@ function writeProject(target, name, examples) {
|
|
|
129
129
|
" '@parcel/watcher': true",
|
|
130
130
|
" '@tailwindcss/oxide': true",
|
|
131
131
|
' unrs-resolver: true',
|
|
132
|
+
' # Pulled in by OpenTelemetry\'s exporter (docs/observability.md); its script only prints a notice.',
|
|
133
|
+
' protobufjs: false',
|
|
132
134
|
...(local ? ['', '# Local @knit-framework packages (KNIT_CREATE_TARBALLS)', 'overrides:', ` '@knit-framework/core': '${local.core}'`, ` '@knit-framework/cli': '${local.cli}'`] : []),
|
|
133
135
|
'',
|
|
134
136
|
].join('\n'))
|
package/package.json
CHANGED
|
@@ -21,7 +21,7 @@ description: Add or change a model (Drizzle table) in a Knit app, end to end - s
|
|
|
21
21
|
- Then run `pnpm manage makemigrations --name <slug>`.
|
|
22
22
|
- If it says drizzle-kit must ask about a rename, split the change: add the new column, migrate, then drop the old one.
|
|
23
23
|
5. **Apply it** with `pnpm manage migrate`. This works while `pnpm dev` runs, and `pnpm dev` also applies migrations when it starts.
|
|
24
|
-
6. **Admin:** register the table in `layers/<app>/admin.ts` with `registerAdminModel(table, { listDisplay, searchFields, listFilter, ordering, readonlyFields })`, using field *keys* (camelCase JS names).
|
|
24
|
+
6. **Admin:** register the table in `layers/<app>/admin.ts` with `registerAdminModel(table, { listDisplay, searchFields, listFilter, ordering, readonlyFields })`, using field *keys* (camelCase JS names). A running `pnpm dev` picks up a new or changed `admin.ts` without a restart.
|
|
25
25
|
7. **Verify.**
|
|
26
26
|
- `pnpm -s manage check --json` (MCP: `knit_check`) has no errors. It catches unknown admin fields, missing prefixes and clashes.
|
|
27
27
|
- `pnpm typecheck` and `pnpm lint` pass.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: knit-add-permission
|
|
3
|
+
description: Add a custom permission to a Knit app, enforce it on the server and grant it to a group or user - customPermissions, requirePermission, resource rules, row-level policies, seeds and a denied-request test. Use when asked to restrict who can do something, add a role-like capability ("only editors can publish"), limit users to their own rows ("editors change only their own posts"), or grant permissions in a Knit project.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Add a permission and grant it
|
|
7
|
+
|
|
8
|
+
1. **Look first.**
|
|
9
|
+
- `knit_describe` with `section: "models"` lists each model's permissions (`<label>.view_<model>`, `add_`, `change_`, `delete_`).
|
|
10
|
+
- `knit_describe` with `section: "resources"` shows which rule guards each API action.
|
|
11
|
+
- The four model permissions may already be enough: use them before inventing a new one.
|
|
12
|
+
2. **Declare a custom permission** in `layers/<app>/admin.ts`: `registerAdminModel(table, { customPermissions: ['publish_post'] })`. Its full name is `<label>.publish_post`, the label being the app label (`knit.app` in the layer's `nuxt.config.ts`).
|
|
13
|
+
3. **Enforce it on the server.** The UI check `useAuth().can(perm)` only hides buttons.
|
|
14
|
+
- Server route: `await requirePermission(event, 'blog.publish_post')` in a route under `layers/<app>/server/api/` (auto-imported there).
|
|
15
|
+
- Resource: put the name in the action's rule, e.g. `permissions: { update: 'blog.publish_post' }` or `[isOwner('authorId'), 'blog.change_post']` (any rule allows).
|
|
16
|
+
- Only some rows ("their own posts", "their team's tickets"): a row-level policy on the model, in `layers/<app>/server/database/schema.ts` (`pnpm manage generate policy <app> <model>` writes a starting one): `defineModelMeta(table, { policy: { assignOwner: 'authorId', change: [isRowOwner('authorId'), 'blog.change_any_post'] } })`. The admin, resources and broadcasts all apply it; your own server code applies it with `useModel(table).as(await requestActor(event))`. Use `scope` only for rows a user must not see at all (it hides them from visitors too). Guide: `knit_docs { "topic": "permissions" }`.
|
|
17
|
+
4. **Create the permission rows.** The server creates them when it starts. A running `pnpm dev` reloads on the `admin.ts` change; restart it if the permission is still unknown. Granting before that fails with `KNIT_E1903` (`knit_docs { "topic": "errors/KNIT_E1903" }`).
|
|
18
|
+
5. **Grant it.**
|
|
19
|
+
- By hand: `/admin/auth/groups/:id` (a matrix per group) or `/admin/auth/users/:id`.
|
|
20
|
+
- In code (a seed or command): `permissionIds(db, [...])`, then `setGroupPermissions` and `addUserToGroup` from `@knit-framework/core/permissions`. The full seed is in the auth guide, "Grant a permission in code". Run it with `pnpm manage seed` (stop `pnpm dev` first on PGlite).
|
|
21
|
+
6. **Verify.**
|
|
22
|
+
- `pnpm -s manage check --json` (MCP: `knit_check`) has no errors; `pnpm typecheck` passes.
|
|
23
|
+
- `knit_resource` shows the new rule on the resource's endpoints.
|
|
24
|
+
- An e2e test with one allowed request and one denied: 403 for a signed-in user without the permission, 401 when signed out. Follow the `knit-write-e2e-test` skill.
|
|
25
|
+
- Sign in as a user in the group and as one outside it, and try the action.
|
|
26
|
+
|
|
27
|
+
Guides: `knit_docs { "topic": "auth" }` (or `node_modules/@knit-framework/core/docs/auth.md`), section "Groups & permissions"; `knit_docs { "topic": "permissions" }` for row-level rules.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: knit-add-sign-in
|
|
3
|
+
description: Add sign-in options to a Knit app - GitHub, Google or other social providers, a generic OpenID Connect provider (Keycloak, Okta, Entra ID, …), two-factor authentication (and requiring it for staff), passkeys - with the callback URL, settings, pages and a test. Use when asked for "sign in with GitHub/Google", SSO, OAuth, OIDC, 2FA, MFA, TOTP, authenticator apps, passkeys or WebAuthn in a Knit project.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Add a sign-in option
|
|
7
|
+
|
|
8
|
+
Sign-in options are settings, not code: Knit always runs BetterAuth's provider, two-factor and passkey plugins, and the account pages show whatever the settings turn on.
|
|
9
|
+
|
|
10
|
+
1. **Look first.**
|
|
11
|
+
- `pnpm -s manage describe --section settings` (MCP: `knit_describe` with `section: "settings"`) lists the enabled methods under `knit.auth.signInMethods`.
|
|
12
|
+
- `knit_reference { "symbol": "useSignInOptions" }` and `knit_docs { "topic": "auth" }`, section "Sign-in options", for the details.
|
|
13
|
+
2. **A social provider** (`github`, `google`, `microsoft`, `discord`, `gitlab`, `apple`):
|
|
14
|
+
- Register an OAuth app at the provider with the callback URL `<site>/api/auth/callback/<provider>`, e.g. `http://localhost:3000/api/auth/callback/github` in development and `https://example.com/api/auth/callback/github` in production.
|
|
15
|
+
- Put both values in `apps/web/.env` (production: the host's secrets): `NUXT_KNIT_AUTH_PROVIDERS_GITHUB_CLIENT_ID=…` and `NUXT_KNIT_AUTH_PROVIDERS_GITHUB_CLIENT_SECRET=…`. One without the other stops startup (`knit_docs { "topic": "errors/KNIT_E1002" }`).
|
|
16
|
+
- Production needs `NUXT_BETTER_AUTH_URL` set to the public URL, so the callback BetterAuth sends matches the registered one.
|
|
17
|
+
3. **A generic OpenID Connect provider** (one per site, provider id `oidc`): register a client with the redirect URI `<site>/api/auth/callback/oidc`, then set `NUXT_KNIT_AUTH_OIDC_DISCOVERY_URL` (the `.well-known/openid-configuration` URL), `NUXT_KNIT_AUTH_OIDC_CLIENT_ID`, `NUXT_KNIT_AUTH_OIDC_CLIENT_SECRET` (empty for a public client) and `NUXT_KNIT_AUTH_OIDC_LABEL` (the button text).
|
|
18
|
+
4. **Two-factor authentication:** `NUXT_KNIT_AUTH_TWO_FACTOR=optional` (default: users turn it on at `/accounts/security`), `staff` (staff and superusers must enrol before using the admin; the admin API answers 403 with `KNIT_E1908` until they do), or `off`. Use `staff` in production; `pnpm manage check --deploy` warns otherwise.
|
|
19
|
+
5. **Passkeys:** on by default; `NUXT_KNIT_AUTH_PASSKEYS=false` turns them off. The relying party is the host of `NUXT_KNIT_SITE_URL` or `NUXT_BETTER_AUTH_URL`, `localhost` in development (test at `http://localhost:3000`).
|
|
20
|
+
6. **Restart `pnpm dev`** (settings are read at startup). `/accounts/login`, `/accounts/signup` and `/admin/login` now show the buttons; `/accounts/security` manages two-factor, passkeys and connected accounts.
|
|
21
|
+
7. **Your own pages** (optional): `const { data: options } = await useSignInOptions()`, then `useSignInButtons(options, '/after-sign-in')` for `<UAuthForm :providers>`, or `useAuth().signInWith('github', '/after-sign-in')` and `useAuth().signInWithPasskey()`.
|
|
22
|
+
8. **Verify.**
|
|
23
|
+
- `pnpm -s manage check --json` (MCP: `knit_check`) has no errors.
|
|
24
|
+
- `curl http://localhost:3000/api/_knit/auth/options` lists the provider, the two-factor mode and passkeys.
|
|
25
|
+
- Sign in with the provider in a browser. A provider route for a provider that isn't configured answers 404 (`knit_docs { "topic": "errors/KNIT_E1909" }`).
|
|
26
|
+
- For two-factor, an e2e test (follow the `knit-write-e2e-test` skill): enrol with `POST /api/auth/two-factor/enable` and `verify-totp` using `totpCode(totpURI)` from `@knit-framework/core/testing`, then `client.signIn(email, password, { totp: totpURI })`. With `staff` mode, check `/api/_admin` answers 403 before enrolment and 200 after.
|
|
27
|
+
|
|
28
|
+
Guides: `knit_docs { "topic": "auth" }` (or `node_modules/@knit-framework/core/docs/auth.md`), section "Sign-in options"; `knit_docs { "topic": "configuration" }` for every `NUXT_KNIT_AUTH_*` setting.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: knit-add-task
|
|
3
|
+
description: Add a background or scheduled task to a Knit app - generate it, write run(), enqueue it, schedule it with cron, run it by hand and test it. Use when asked for background work, a job, a queue, a cron job, or "do X every night" in a Knit project.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Add a background or scheduled task
|
|
7
|
+
|
|
8
|
+
1. **Look first.**
|
|
9
|
+
- `knit_describe` with `section: "tasks"` (or `pnpm -s manage runtask --json`) lists the existing tasks and schedules.
|
|
10
|
+
- Note the backend: `NUXT_KNIT_TASKS_BACKEND` is `immediate` (default, runs in-process) or `database` (queued in a table, with retries).
|
|
11
|
+
2. **Generate the file.** `pnpm manage generate task <app> <name>` writes `layers/<app>/server/tasks/<name>.ts` with task `<label>.<name>`. A running `pnpm dev` picks it up.
|
|
12
|
+
3. **Write `run(payload, ctx)`.**
|
|
13
|
+
- Task files also run outside the server: no auto-imports. Import tables from `../database/schema` and use `ctx.db`.
|
|
14
|
+
- Write through `useModel(table, { db: ctx.db })` from `@knit-framework/core/models` so validators and signals run.
|
|
15
|
+
- Return something JSON-serialisable; throw to fail (the database backend retries up to `maxAttempts`).
|
|
16
|
+
- Scheduled work: add `schedule: '0 3 * * *'` (cron). It runs once per due time, however many processes run.
|
|
17
|
+
4. **Enqueue it** from server code: `await enqueue('<label>.<name>', payload)` (auto-imported, checked against the task's payload type). Inside another task, use `ctx.enqueue(taskObject, payload)`.
|
|
18
|
+
5. **Run it by hand.** `pnpm -s manage runtask <label>.<name> --payload '{"note":"hi"}' --json` prints `{ ok, result }` or `{ ok: false, error }`. On PGlite, stop `pnpm dev` first.
|
|
19
|
+
6. **Test it.** Add `layers/<app>/test/tasks.test.ts` with `createTestDatabase` and `configureTasks()` before `enqueue()`, passing the task object, not its name. Copy the sample from the tasks guide, "Test a task" (it explains `KNIT_E1701`).
|
|
20
|
+
7. **Verify.**
|
|
21
|
+
- `pnpm manage test --unit` and `pnpm typecheck` pass; `pnpm -s manage check --json` (MCP: `knit_check`) has no errors.
|
|
22
|
+
- `knit_describe` with `section: "tasks"` lists the task (and its schedule).
|
|
23
|
+
- With the database backend, the run appears in the queue table with status `succeeded` (the tasks guide, "Check that a task ran").
|
|
24
|
+
|
|
25
|
+
Guide: `knit_docs { "topic": "tasks" }` (or `node_modules/@knit-framework/core/docs/tasks.md`).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: knit-add-translation
|
|
3
|
+
description: Add or translate UI strings in a Knit app - t() in pages, layer locale files in every language, model and field labels for the admin, and a test that keeps the languages in step. Use when asked to translate a page or the admin, add a language, or add user-facing text in a Knit project.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Add or translate UI strings
|
|
7
|
+
|
|
8
|
+
1. **Look first.**
|
|
9
|
+
- List `layers/<app>/i18n/locales/`: `pnpm manage startapp` writes `en.json`, `de.json` and `es.json` with the same keys.
|
|
10
|
+
- `knit_describe` with `section: "models"` gives each model's admin slug, the key used for model labels.
|
|
11
|
+
2. **Use `t()` for every string** in pages and components: `const { t } = useI18n()`, then `t('shop.cart.title')`. Put your own keys under your app's namespace, never under `knit.*`. Plurals: `t('shop.cart.items', { count: n(items.length) }, items.length)`.
|
|
12
|
+
3. **Admin labels** go under `knit.models.<slug>` (`label`, `labelPlural`, `fields.<field>`, `help.<field>`) and `knit.groups.<group key>`. English already comes from `admin.ts`; add other languages there.
|
|
13
|
+
4. **Add the key to every locale file of the layer**, in the same place. A missing key silently falls back to English.
|
|
14
|
+
- A literal `{`, `}`, `@` or `|` breaks the whole language: write `{'@'}` for `@`.
|
|
15
|
+
- Pass sentence parts as named placeholders (`{model}`); don't glue fragments or lowercase in code.
|
|
16
|
+
5. **A new language** is a new file, e.g. `layers/<app>/i18n/locales/fr.json`. Restart `pnpm dev` after adding a file; that is the only change that needs a restart.
|
|
17
|
+
6. **Verify.**
|
|
18
|
+
- Add the key-parity test from the i18n guide ("Keep an app's languages in step") to `layers/<app>/test/locales.test.ts` if the layer has none, then run `pnpm manage test --unit`.
|
|
19
|
+
- `pnpm typecheck` passes.
|
|
20
|
+
- Open the page and the admin, switch the language in the user menu or with `<KnitLocaleSelect />`, and check that no English is left.
|
|
21
|
+
|
|
22
|
+
Guide: `knit_docs { "topic": "i18n" }` (or `node_modules/@knit-framework/core/docs/i18n.md`).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: knit-deploy
|
|
3
|
+
description: Deploy a Knit app to production - pick a host, set secrets, database, migrations, first admin, email and tasks, then verify with check --deploy and the health check. Use when asked to deploy, host, go live, ship to production, or prepare a Knit project for a server, Docker, Fly.io, Railway, Render, Vercel or Netlify.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Deploy to production
|
|
7
|
+
|
|
8
|
+
1. **Look first.**
|
|
9
|
+
- `knit_docs { "topic": "deployment" }` has the host table and the checklist this skill follows.
|
|
10
|
+
- `knit_describe` with `section: "settings"` shows the current settings; `knit_describe` with `section: "tasks"` and `section: "channels"` tell you whether you need a worker and WebSockets.
|
|
11
|
+
2. **Pick the host.** Long-running Node with a persistent disk works best (Docker, a VPS, Fly.io, Railway, Render). Vercel and Netlify have no WebSockets, worker or scheduled tasks. Read the host's page, e.g. `knit_docs { "topic": "deployment/fly" }`.
|
|
12
|
+
3. **Make sure the build is clean.** `pnpm manage makemigrations --check` (no forgotten migration), `pnpm typecheck`, `pnpm manage test`, then `pnpm build`.
|
|
13
|
+
4. **Set the production environment**, step by step from the guide's checklist:
|
|
14
|
+
- `NUXT_BETTER_AUTH_SECRET` (`openssl rand -base64 32`) and `NUXT_BETTER_AUTH_URL=https://your.domain`.
|
|
15
|
+
- Database: the embedded one for a single process with a persistent disk; otherwise `DATABASE_URL` (Postgres).
|
|
16
|
+
- Migrations: `NUXT_KNIT_AUTO_MIGRATE=always`, or `pnpm manage migrate` as a release step.
|
|
17
|
+
- `NUXT_MAIL_URL` and `NUXT_MAIL_FROM`; `NUXT_KNIT_TASKS_BACKEND=database` if there are tasks.
|
|
18
|
+
- Behind a TLS proxy: `NUXT_KNIT_SECURITY_TRUST_PROXY=true` and `NUXT_BETTER_AUTH_TRUST_PROXY=true`.
|
|
19
|
+
- Never commit secrets: set them in the host's settings, not in `apps/web/.env`.
|
|
20
|
+
5. **Check before going live.** With those variables set, `pnpm -s manage check --deploy --json` (MCP: `knit_check` with `deploy: true`) has no errors. An error code has a page: `knit_docs { "topic": "errors/<code>" }`.
|
|
21
|
+
6. **Deploy**, then create the first admin (the setup wizard is off in production): `KNIT_SUPERUSER_PASSWORD=… pnpm manage createsuperuser --no-input --email you@example.com`, where the CLI can reach the production database.
|
|
22
|
+
7. **Verify.**
|
|
23
|
+
- The host's health check points at `/api/_knit/health`, and `curl https://your.domain/api/_knit/health` returns `{ "ok": true }`.
|
|
24
|
+
- Sign in at `/admin`; request a password reset to see that email is delivered.
|
|
25
|
+
- With tasks: enqueue one and see it succeed in the logs.
|
|
26
|
+
|
|
27
|
+
Guide: `knit_docs { "topic": "deployment" }` (or `node_modules/@knit-framework/core/docs/deployment/index.md`); settings in `knit_docs { "topic": "configuration" }`.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: knit-write-e2e-test
|
|
3
|
+
description: Write an end-to-end test for a Knit app that boots the real server and calls it over HTTP with createTestClient - first admin, sign-in, sign-up, allowed and denied requests. Use when asked to test an API, a permission, a page response or a whole flow over HTTP in a Knit project.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Write an end-to-end test
|
|
7
|
+
|
|
8
|
+
1. **Look first.**
|
|
9
|
+
- `knit_routes` (or `pnpm -s manage routes --json`) lists the pages, API routes and resource endpoints to call.
|
|
10
|
+
- `knit_resource` with the slug gives the permission rule of each action: test one allowed and one denied request per rule.
|
|
11
|
+
- Logic without HTTP (a model, a task) belongs in a faster unit test: `pnpm manage generate test <app> <name> --table <export>`.
|
|
12
|
+
2. **Create `apps/web/test/e2e/<name>.test.ts`.** Copy the sample from the testing guide, "End-to-end tests". It is self-contained:
|
|
13
|
+
- Set `NUXT_KNIT_DATA_DIR=memory://`, `NUXT_KNIT_AUTO_MIGRATE=always`, `NUXT_KNIT_ALLOW_SETUP=always` and a random `NUXT_BETTER_AUTH_SECRET` before `setup()`.
|
|
14
|
+
- `await setup({ rootDir: fileURLToPath(new URL('../..', import.meta.url)), server: true, browser: false })` from `@nuxt/test-utils/e2e`.
|
|
15
|
+
3. **Make the users in `beforeAll`** (the server starts in `setup()`'s own hook):
|
|
16
|
+
- One `createTestClient(url('/'))` from `@knit-framework/core/testing` per user; each keeps its own cookies and sends the CSRF-safe `Origin`.
|
|
17
|
+
- First admin: `POST /api/_knit/setup` with `{ name, email, password }` (201), then `signIn(email, password)`. It is a superuser.
|
|
18
|
+
- Ordinary user: `POST /api/auth/sign-up/email` (200) also signs the client in.
|
|
19
|
+
4. **Write the cases.** Responses are `{ status, data }` and never throw.
|
|
20
|
+
- Allowed: 200 or 201 and the returned data.
|
|
21
|
+
- Denied: 403 signed in, 401 signed out. Validation errors: 422 with `data.data.issues`.
|
|
22
|
+
- Tests in one file share the server and its data: create what each test needs, or order them.
|
|
23
|
+
5. **Your schema changed?** Run `pnpm manage makemigrations --name <slug>` first: the server applies the migration files, not the schema.
|
|
24
|
+
6. **Verify.** `pnpm manage test --e2e` passes (it builds the app; the first run is slow), and `pnpm typecheck` passes. Break the rule on purpose once (e.g. allow the denied action) and check the test fails.
|
|
25
|
+
|
|
26
|
+
Guide: `knit_docs { "topic": "testing" }` (or `node_modules/@knit-framework/core/docs/testing.md`).
|
package/template/base/AGENTS.md
CHANGED
|
@@ -17,7 +17,8 @@ Don't read files to find out what exists. Ask Knit:
|
|
|
17
17
|
- `knit_migrations`, `knit_migration_plan`, `knit_pending_migration_sql`, `knit_sqlmigrate`.
|
|
18
18
|
- `knit_docs`: the guides, e.g. `{ "topic": "models" }`. Also as MCP resources: `knit://docs/{topic}`, `knit://describe`, `knit://agents`.
|
|
19
19
|
- **Error codes:** an error with a code (`KNIT_E1203`) has a page that says why and how to fix it: read it with `knit_docs { "topic": "errors/KNIT_E1203" }` before changing code.
|
|
20
|
-
-
|
|
20
|
+
- With `pnpm dev` running: `knit_errors` (recent server errors with hints and codes), `knit_outbox` (sent emails, e.g. a reset link), `knit_tasks` (task runs and the queue).
|
|
21
|
+
- Only when the server runs with `--allow-writes`: `knit_startapp`, `knit_generate`, `knit_makemigrations`, `knit_migrate`. Each takes `dryRun: true` to see what it would do first.
|
|
21
22
|
- **CLI:** `pnpm -s manage describe --json` (the same document; `--section <name>` for one part), `routes --json`, `openapi`, `check --json`, `showmigrations --json`, `runtask --json`. Commands that change things take `--json` too (`startapp`, `generate`, `makemigrations`, `migrate`, …). `-s` keeps pnpm's banner out of the JSON.
|
|
22
23
|
- **Library docs:** the `nuxt`, `nuxt-ui` and `better-auth` MCP servers. Use them instead of guessing APIs.
|
|
23
24
|
|
|
@@ -46,12 +47,26 @@ Don't edit `node_modules/@knit-framework/*`: override instead (a page, component
|
|
|
46
47
|
- **Writes go through `useModel(table)`** (validators, `clean()`, signals, one transaction). Raw `useDB()` is for reads and bulk work. In schema files, signal receivers and `clean()` must use the `db` they are given.
|
|
47
48
|
- **Cross-app references** import the table: `import { user } from '@knit-framework/core/schema'`.
|
|
48
49
|
- **Permissions on the server:** `requirePermission(event, 'shop.change_product')`. In the UI, `useAuth().can(perm)` is display-only.
|
|
50
|
+
- **Row-level rules** ("users change only their own rows") are a `policy` in the model's meta, not checks in each route. In your own routes, act as the user so it applies: `useModel(table).as(await requestActor(event))`; plain `useModel(table)` and `useDB()` skip it. See `node_modules/@knit-framework/core/docs/permissions.md`.
|
|
49
51
|
- **Resources default to deny for writes.** List `fields` explicitly for public APIs. Server-set values (e.g. `authorId`) belong in `beforeCreate`.
|
|
50
52
|
- **Files outside Nitro** (tasks, commands, seeds) don't get auto-imports: import from `@knit-framework/core/*` and use the `db`/`ctx.db` you are given.
|
|
51
53
|
- **UI strings** go through `t()`; a literal `{`, `}`, `@` or `|` in a locale message breaks the whole language.
|
|
52
54
|
- **Logging:** `useLogger('scope')` in server code, never `console.*`.
|
|
53
55
|
|
|
54
|
-
## 4.
|
|
56
|
+
## 4. Recipes
|
|
57
|
+
|
|
58
|
+
Step-by-step procedures for common jobs. Claude Code loads them as skills; any other agent can read and follow the file:
|
|
59
|
+
|
|
60
|
+
- Add or change a model: [`.claude/skills/knit-add-model/SKILL.md`](.claude/skills/knit-add-model/SKILL.md)
|
|
61
|
+
- Add a public API and forms: [`.claude/skills/knit-add-api/SKILL.md`](.claude/skills/knit-add-api/SKILL.md)
|
|
62
|
+
- Add a permission and grant it: [`.claude/skills/knit-add-permission/SKILL.md`](.claude/skills/knit-add-permission/SKILL.md)
|
|
63
|
+
- Add sign-in options (providers, OpenID Connect, two-factor, passkeys): [`.claude/skills/knit-add-sign-in/SKILL.md`](.claude/skills/knit-add-sign-in/SKILL.md)
|
|
64
|
+
- Add or translate UI strings: [`.claude/skills/knit-add-translation/SKILL.md`](.claude/skills/knit-add-translation/SKILL.md)
|
|
65
|
+
- Add a background or scheduled task: [`.claude/skills/knit-add-task/SKILL.md`](.claude/skills/knit-add-task/SKILL.md)
|
|
66
|
+
- Write an end-to-end test: [`.claude/skills/knit-write-e2e-test/SKILL.md`](.claude/skills/knit-write-e2e-test/SKILL.md)
|
|
67
|
+
- Deploy to production: [`.claude/skills/knit-deploy/SKILL.md`](.claude/skills/knit-deploy/SKILL.md)
|
|
68
|
+
|
|
69
|
+
## 5. Change → verify loop
|
|
55
70
|
|
|
56
71
|
```bash
|
|
57
72
|
pnpm -s manage check --json # schema, admin field names, settings, layers, migrations (or MCP: knit_check)
|
|
@@ -70,7 +85,7 @@ pnpm manage test --unit # fast; pnpm test runs e2e too (builds
|
|
|
70
85
|
- **Tests:** `createTestDatabase`, `defineFactory`, `createTestClient` from `@knit-framework/core/testing`; app tests in `layers/<app>/test/*.test.ts`. See `node_modules/@knit-framework/core/docs/testing.md`.
|
|
71
86
|
- **Admin or API changes:** sign in at `/admin` and try list, create (including a validation error), edit and delete.
|
|
72
87
|
|
|
73
|
-
##
|
|
88
|
+
## 6. Gotchas
|
|
74
89
|
|
|
75
90
|
- **Relational queries need `relations()`.** `with: { author: true }` fails without a relation named `author`.
|
|
76
91
|
- **Resources** must be *exported*. `_choices` for a foreign key goes through the target table's resource (no resource, no choices).
|
package/template/base/CLAUDE.md
CHANGED
|
@@ -6,4 +6,4 @@ Project MCP servers (`.mcp.json`):
|
|
|
6
6
|
- `knit`: this project's models, resources, routes, OpenAPI, checks, migrations and Knit's guides. Start with `knit_describe`. It only reads unless started with `--allow-writes`.
|
|
7
7
|
- `nuxt`, `nuxt-ui`, `better-auth`: library APIs; use them instead of guessing.
|
|
8
8
|
|
|
9
|
-
Skills in `.claude/skills/`: `knit-add-model`, `knit-add-api`. New files: `pnpm manage startapp <app>` and `pnpm manage generate <kind> <app> <name>`.
|
|
9
|
+
Skills in `.claude/skills/`: `knit-add-model`, `knit-add-api`, `knit-add-permission`, `knit-add-sign-in`, `knit-add-translation`, `knit-add-task`, `knit-write-e2e-test`, `knit-deploy`. New files: `pnpm manage startapp <app>` and `pnpm manage generate <kind> <app> <name>`.
|
|
@@ -41,6 +41,30 @@ NUXT_BETTER_AUTH_URL=
|
|
|
41
41
|
# Behind a reverse proxy, read the client IP from X-Forwarded-For: false (default) | true
|
|
42
42
|
# NUXT_BETTER_AUTH_TRUST_PROXY=false
|
|
43
43
|
|
|
44
|
+
# Sign-in options (docs/auth.md#sign-in-options). A provider is on when both its id and secret are
|
|
45
|
+
# set; register the callback URL <site>/api/auth/callback/<provider> at the provider.
|
|
46
|
+
# NUXT_KNIT_AUTH_PROVIDERS_GITHUB_CLIENT_ID=
|
|
47
|
+
# NUXT_KNIT_AUTH_PROVIDERS_GITHUB_CLIENT_SECRET=
|
|
48
|
+
# NUXT_KNIT_AUTH_PROVIDERS_GOOGLE_CLIENT_ID=
|
|
49
|
+
# NUXT_KNIT_AUTH_PROVIDERS_GOOGLE_CLIENT_SECRET=
|
|
50
|
+
# NUXT_KNIT_AUTH_PROVIDERS_MICROSOFT_CLIENT_ID=
|
|
51
|
+
# NUXT_KNIT_AUTH_PROVIDERS_MICROSOFT_CLIENT_SECRET=
|
|
52
|
+
# NUXT_KNIT_AUTH_PROVIDERS_DISCORD_CLIENT_ID=
|
|
53
|
+
# NUXT_KNIT_AUTH_PROVIDERS_DISCORD_CLIENT_SECRET=
|
|
54
|
+
# NUXT_KNIT_AUTH_PROVIDERS_GITLAB_CLIENT_ID=
|
|
55
|
+
# NUXT_KNIT_AUTH_PROVIDERS_GITLAB_CLIENT_SECRET=
|
|
56
|
+
# NUXT_KNIT_AUTH_PROVIDERS_APPLE_CLIENT_ID=
|
|
57
|
+
# NUXT_KNIT_AUTH_PROVIDERS_APPLE_CLIENT_SECRET=
|
|
58
|
+
# One generic OpenID Connect provider (Keycloak, Authentik, Okta, …), callback <site>/api/auth/callback/oidc
|
|
59
|
+
# NUXT_KNIT_AUTH_OIDC_DISCOVERY_URL=https://id.example.com/.well-known/openid-configuration
|
|
60
|
+
# NUXT_KNIT_AUTH_OIDC_CLIENT_ID=
|
|
61
|
+
# NUXT_KNIT_AUTH_OIDC_CLIENT_SECRET=
|
|
62
|
+
# NUXT_KNIT_AUTH_OIDC_LABEL=Single sign-on
|
|
63
|
+
# Two-factor authentication: off | optional (default) | staff (staff must enrol to use the admin)
|
|
64
|
+
# NUXT_KNIT_AUTH_TWO_FACTOR=optional
|
|
65
|
+
# Passkeys (WebAuthn): true (default) | false
|
|
66
|
+
# NUXT_KNIT_AUTH_PASSKEYS=true
|
|
67
|
+
|
|
44
68
|
# Email. Mailer: console (dev default, prints to the terminal) | smtp | memory (in-process outbox)
|
|
45
69
|
# Empty mailer = smtp when NUXT_MAIL_URL is set, otherwise console.
|
|
46
70
|
# NUXT_MAIL_MAILER=
|
|
@@ -64,6 +88,12 @@ NUXT_BETTER_AUTH_URL=
|
|
|
64
88
|
# Extra keys to redact, comma-separated (passwords, tokens, cookies… are always redacted)
|
|
65
89
|
# NUXT_KNIT_LOG_REDACT=ssn,card.number
|
|
66
90
|
|
|
91
|
+
# ── Telemetry (OpenTelemetry traces, docs/observability.md) ─────────────────────
|
|
92
|
+
# Needs: pnpm add -w @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http
|
|
93
|
+
# NUXT_KNIT_TELEMETRY_ENABLED=false
|
|
94
|
+
# NUXT_KNIT_TELEMETRY_SERVICE_NAME=knit
|
|
95
|
+
# OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
|
|
96
|
+
|
|
67
97
|
# ── Site ────────────────────────────────────────────────────────────────────────
|
|
68
98
|
# Public base URL for sitemaps and feeds (default: NUXT_BETTER_AUTH_URL, then the request)
|
|
69
99
|
# NUXT_KNIT_SITE_URL=https://example.com
|
package/template/base/llms.txt
CHANGED
|
@@ -19,6 +19,7 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
|
|
|
19
19
|
- [Rendering modes](node_modules/@knit-framework/core/docs/rendering.md): SSR by default; SPA per route, per path or per layer; prerender and caching
|
|
20
20
|
- [Admin](node_modules/@knit-framework/core/docs/admin.md): `registerAdminModel` options, filters, actions, inlines, history, user tools, REST API
|
|
21
21
|
- [Auth & permissions](node_modules/@knit-framework/core/docs/auth.md): Users, staff, superusers, groups, permissions, `/accounts/*` pages
|
|
22
|
+
- [Row-level permissions](node_modules/@knit-framework/core/docs/permissions.md): `defineModelMeta(table, { policy })`, `useModel(table).as(actor)`, what the admin, resources and realtime apply
|
|
22
23
|
- [Internationalization](node_modules/@knit-framework/core/docs/i18n.md): Translations, locales per layer, translating models, the language switcher
|
|
23
24
|
- [Email](node_modules/@knit-framework/core/docs/email.md): `sendMail()`, mailers, templates, auth emails
|
|
24
25
|
- [Background tasks](node_modules/@knit-framework/core/docs/tasks.md): `defineTask`, `enqueue`, the worker, cron schedules
|
|
@@ -26,6 +27,7 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
|
|
|
26
27
|
- [Files & uploads](node_modules/@knit-framework/core/docs/files.md): `fileColumn`, uploads, disk/S3 storage
|
|
27
28
|
- [Cache, messages & humanize](node_modules/@knit-framework/core/docs/utilities.md): `cached()`, flash messages, formatting helpers
|
|
28
29
|
- [Sitemaps & feeds](node_modules/@knit-framework/core/docs/sitemaps-and-feeds.md): `/sitemap.xml`, RSS and Atom
|
|
30
|
+
- [Observability](node_modules/@knit-framework/core/docs/observability.md): OpenTelemetry traces (NUXT_KNIT_TELEMETRY_ENABLED), what each span contains, `withSpan`
|
|
29
31
|
- [Logging](node_modules/@knit-framework/core/docs/logging.md): LogLayer: pretty dev output, JSON in production, request logs, redaction
|
|
30
32
|
- [Security](node_modules/@knit-framework/core/docs/security.md): CSRF, security headers, CSP
|
|
31
33
|
- [Testing](node_modules/@knit-framework/core/docs/testing.md): Test databases, factories, the HTTP client, `pnpm test`
|
|
@@ -26,6 +26,8 @@ registerAdminModel(category, {
|
|
|
26
26
|
|
|
27
27
|
registerAdminModel(post, {
|
|
28
28
|
icon: 'i-lucide-file-text',
|
|
29
|
+
// Editors change their own posts (the policy in schema.ts); this lets an editor-in-chief change any.
|
|
30
|
+
customPermissions: ['change_any_post'],
|
|
29
31
|
listDisplay: ['title', 'published', 'categoryId', 'publishedAt', 'updatedAt'],
|
|
30
32
|
listEditable: ['published'],
|
|
31
33
|
listFilter: ['published', 'categoryId', 'authorId', 'publishedAt'],
|
|
@@ -64,7 +66,7 @@ registerAdminModel(post, {
|
|
|
64
66
|
.set({ published: true, publishedAt: sql`coalesce(${post.publishedAt}, now())` })
|
|
65
67
|
.where(inArray(post.id, ids.map(Number)))
|
|
66
68
|
.returning({ id: post.id })
|
|
67
|
-
return { message: `Published ${rows.length} post${rows.length === 1 ? '' : 's'}
|
|
69
|
+
return { message: `Published ${rows.length} post${rows.length === 1 ? '' : 's'}`, params: { count: rows.length } }
|
|
68
70
|
},
|
|
69
71
|
},
|
|
70
72
|
{
|
|
@@ -75,7 +77,7 @@ registerAdminModel(post, {
|
|
|
75
77
|
confirm: 'Hide the selected posts from the site?',
|
|
76
78
|
async handler({ ids, db }) {
|
|
77
79
|
const rows = await db.update(post).set({ published: false }).where(inArray(post.id, ids.map(Number))).returning({ id: post.id })
|
|
78
|
-
return { message: `Unpublished ${rows.length} post${rows.length === 1 ? '' : 's'}
|
|
80
|
+
return { message: `Unpublished ${rows.length} post${rows.length === 1 ? '' : 's'}`, params: { count: rows.length } }
|
|
79
81
|
},
|
|
80
82
|
},
|
|
81
83
|
],
|
|
@@ -119,7 +121,7 @@ registerAdminModel(comment, {
|
|
|
119
121
|
await comments.update(id, { approved: true })
|
|
120
122
|
approved++
|
|
121
123
|
}
|
|
122
|
-
return { message: `Approved ${approved} comment${approved === 1 ? '' : 's'}
|
|
124
|
+
return { message: `Approved ${approved} comment${approved === 1 ? '' : 's'}`, params: { count: approved } }
|
|
123
125
|
},
|
|
124
126
|
},
|
|
125
127
|
],
|
|
@@ -24,7 +24,7 @@ const { items, total, refresh } = comments.list({
|
|
|
24
24
|
})
|
|
25
25
|
|
|
26
26
|
// Live updates: `broadcastModel(comment, …)` publishes every comment write on
|
|
27
|
-
// `comments:post:<id>` (
|
|
27
|
+
// `comments:post:<id>` (the comment model's policy decides who hears what); the list re-reads
|
|
28
28
|
// through the resource, so moderation and scoping apply exactly as on the first load.
|
|
29
29
|
const live = useRealtimeModel({ refresh }, () => (post.value ? `comments:post:${post.value.id}` : null))
|
|
30
30
|
|
|
@@ -2,39 +2,15 @@
|
|
|
2
2
|
* Live comments for one post.
|
|
3
3
|
* `server/database/schema.ts` broadcasts comment writes here with `broadcastModel`.
|
|
4
4
|
*
|
|
5
|
-
* Anyone may listen
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* them as `deleted` (just its id), so it disappears from their page too.
|
|
5
|
+
* Anyone may listen. Moderation is the comment model's row-level policy, which model broadcasts
|
|
6
|
+
* apply per subscriber: moderators get every event, authors their own pending comments, everyone
|
|
7
|
+
* else approved comments. A comment that is unapproved again reaches the others as `deleted` (just
|
|
8
|
+
* its id), so it disappears from their page too. No `filter` needed here.
|
|
10
9
|
*/
|
|
11
10
|
import { defineChannel } from '@knit-framework/core/realtime'
|
|
12
11
|
|
|
13
|
-
const MODERATE = 'blog.change_comment'
|
|
14
|
-
|
|
15
|
-
interface CommentEvent {
|
|
16
|
-
id: number
|
|
17
|
-
authorId: string
|
|
18
|
-
approved: boolean
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function isCommentEvent(value: unknown): value is CommentEvent {
|
|
22
|
-
if (typeof value !== 'object' || value === null) return false
|
|
23
|
-
const v: Partial<Record<keyof CommentEvent, unknown>> = value
|
|
24
|
-
return typeof v.id === 'number' && typeof v.authorId === 'string' && typeof v.approved === 'boolean'
|
|
25
|
-
}
|
|
26
|
-
|
|
27
12
|
export const postComments = defineChannel('comments:post:{id}', {
|
|
28
13
|
description: 'Comment created/updated/deleted events for one post',
|
|
29
14
|
// `ctx.params` is typed from the pattern: `{ id: string }`.
|
|
30
15
|
authorize: ctx => /^\d+$/.test(ctx.params.id),
|
|
31
|
-
filter(message, ctx) {
|
|
32
|
-
if (ctx.can(MODERATE)) return true
|
|
33
|
-
if (!isCommentEvent(message.data)) return false
|
|
34
|
-
const comment = message.data
|
|
35
|
-
if (comment.approved || (ctx.user && comment.authorId === ctx.user.id)) return true
|
|
36
|
-
// Never seen by this visitor while pending: nothing to announce.
|
|
37
|
-
if (message.event === 'created') return false
|
|
38
|
-
return { event: 'deleted', data: { id: comment.id } }
|
|
39
|
-
},
|
|
40
16
|
})
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { relations } from 'drizzle-orm'
|
|
1
|
+
import { eq, or, relations } from 'drizzle-orm'
|
|
2
2
|
import { boolean, index, integer, pgTable, serial, text, timestamp, uniqueIndex, varchar } from 'drizzle-orm/pg-core'
|
|
3
3
|
import { fileColumn } from '@knit-framework/core/fields'
|
|
4
|
-
import { defineModelMeta, signals, ValidationError } from '@knit-framework/core/models'
|
|
4
|
+
import { defineModelMeta, isRowOwner, signals, ValidationError } from '@knit-framework/core/models'
|
|
5
5
|
import { broadcastModel } from '@knit-framework/core/realtime'
|
|
6
6
|
import { user } from '@knit-framework/core/schema'
|
|
7
7
|
|
|
@@ -113,6 +113,14 @@ defineModelMeta(category, {
|
|
|
113
113
|
|
|
114
114
|
defineModelMeta(post, {
|
|
115
115
|
ordering: ['-createdAt'],
|
|
116
|
+
// Row-level permissions, respected by the admin, the posts API and broadcasts: editors change and
|
|
117
|
+
// delete their own posts; `blog.change_any_post` (registered in admin.ts) lifts that. A new post's
|
|
118
|
+
// author is the user who creates it. No `scope`: everyone may still read every post they could before.
|
|
119
|
+
policy: {
|
|
120
|
+
assignOwner: 'authorId',
|
|
121
|
+
change: [isRowOwner('authorId'), 'blog.change_any_post'],
|
|
122
|
+
delete: [isRowOwner('authorId'), 'blog.change_any_post'],
|
|
123
|
+
},
|
|
116
124
|
validators: {
|
|
117
125
|
slug: [slugValidator],
|
|
118
126
|
title: [value => (value !== undefined && value.trim().length < 3 ? 'At least 3 characters.' : undefined)],
|
|
@@ -128,6 +136,15 @@ defineModelMeta(post, {
|
|
|
128
136
|
|
|
129
137
|
defineModelMeta(comment, {
|
|
130
138
|
ordering: ['createdAt'],
|
|
139
|
+
// Moderation, declared once: the comments API, the admin and the live comments channel all apply it.
|
|
140
|
+
// Moderators (`blog.change_comment`) see every comment; signed-in users see approved comments and
|
|
141
|
+
// their own pending ones; visitors see approved comments. Authors edit and delete their own.
|
|
142
|
+
policy: {
|
|
143
|
+
scope: ctx => (ctx.can('blog.change_comment') ? undefined : ctx.user ? or(eq(comment.approved, true), eq(comment.authorId, ctx.user.id)) : { approved: true }),
|
|
144
|
+
assignOwner: 'authorId',
|
|
145
|
+
change: [isRowOwner('authorId'), 'blog.change_comment'],
|
|
146
|
+
delete: [isRowOwner('authorId'), 'blog.delete_comment'],
|
|
147
|
+
},
|
|
131
148
|
validators: {
|
|
132
149
|
body: [(value) => {
|
|
133
150
|
const length = value?.trim().length ?? 0
|
|
@@ -146,7 +163,8 @@ signals.preSave.connect(comment, ({ instance }) => {
|
|
|
146
163
|
})
|
|
147
164
|
|
|
148
165
|
// Realtime: every comment write through useModel (the site, the admin's "Approve selected", tasks) is published, after commit,
|
|
149
|
-
// on `comments:post:<id>`.
|
|
166
|
+
// on `comments:post:<id>`. Each subscriber receives only the comments the policy above lets them see; a comment that
|
|
167
|
+
// leaves their view (unapproved again) reaches them as `deleted` with just its id, so it disappears from their page.
|
|
150
168
|
broadcastModel(comment, {
|
|
151
169
|
channel: row => `comments:post:${row.postId}`,
|
|
152
170
|
// Ids only: the page re-reads the list through the `comments` resource, which applies moderation.
|
|
@@ -3,17 +3,16 @@
|
|
|
3
3
|
*
|
|
4
4
|
* - Anyone lists approved comments: `GET /api/r/comments?postId=3`.
|
|
5
5
|
* - Signed-in users comment; the author comes from the session and `approved` is read-only.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
*
|
|
7
|
+
* Who sees and changes which comment (authors their own pending ones, moderators everything) is
|
|
8
|
+
* the comment model's row-level policy, in `server/database/schema.ts`: this resource applies it.
|
|
8
9
|
*/
|
|
9
|
-
import { and, eq, inArray
|
|
10
|
+
import { and, eq, inArray } from 'drizzle-orm'
|
|
10
11
|
import { user } from '@knit-framework/core/schema'
|
|
11
12
|
import { ValidationError } from '@knit-framework/core/models'
|
|
12
|
-
import { defineResource
|
|
13
|
+
import { defineResource } from '@knit-framework/core/resources'
|
|
13
14
|
import { comment, post } from '../database/schema'
|
|
14
15
|
|
|
15
|
-
const MODERATE = 'blog.change_comment'
|
|
16
|
-
|
|
17
16
|
export default defineResource(comment, {
|
|
18
17
|
slug: 'comments',
|
|
19
18
|
fields: ['id', 'postId', 'authorId', 'body', 'approved', 'createdAt', 'updatedAt'],
|
|
@@ -28,14 +27,9 @@ export default defineResource(comment, {
|
|
|
28
27
|
list: 'public',
|
|
29
28
|
retrieve: 'public',
|
|
30
29
|
create: 'authenticated',
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
// Row-level scoping: visitors see approved comments, authors also their own pending ones.
|
|
36
|
-
scope(ctx) {
|
|
37
|
-
if (ctx.can(MODERATE)) return undefined
|
|
38
|
-
return ctx.user ? or(eq(comment.approved, true), eq(comment.authorId, ctx.user.id)) : { approved: true }
|
|
30
|
+
// Which comments: the model's policy (their own, or any for moderators).
|
|
31
|
+
update: 'authenticated',
|
|
32
|
+
delete: 'authenticated',
|
|
39
33
|
},
|
|
40
34
|
|
|
41
35
|
async beforeCreate(data, ctx) {
|
package/template/versions.json
CHANGED