create-knit 0.6.1 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-knit",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Create a Knit project: `pnpm create knit my-app`. Knit is the batteries-included full-stack framework for TypeScript, on Nuxt.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,6 +1,6 @@
1
1
  ---
2
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, seeds and a denied-request test. Use when asked to restrict who can do something, add a role-like capability ("only editors can publish"), or grant permissions in a Knit project.
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
4
  ---
5
5
 
6
6
  # Add a permission and grant it
@@ -13,6 +13,7 @@ description: Add a custom permission to a Knit app, enforce it on the server and
13
13
  3. **Enforce it on the server.** The UI check `useAuth().can(perm)` only hides buttons.
14
14
  - Server route: `await requirePermission(event, 'blog.publish_post')` in a route under `layers/<app>/server/api/` (auto-imported there).
15
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" }`.
16
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" }`).
17
18
  5. **Grant it.**
18
19
  - By hand: `/admin/auth/groups/:id` (a matrix per group) or `/admin/auth/users/:id`.
@@ -23,4 +24,4 @@ description: Add a custom permission to a Knit app, enforce it on the server and
23
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.
24
25
  - Sign in as a user in the group and as one outside it, and try the action.
25
26
 
26
- Guide: `knit_docs { "topic": "auth" }` (or `node_modules/@knit-framework/core/docs/auth.md`), section "Groups & permissions".
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.
@@ -47,6 +47,7 @@ Don't edit `node_modules/@knit-framework/*`: override instead (a page, component
47
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.
48
48
  - **Cross-app references** import the table: `import { user } from '@knit-framework/core/schema'`.
49
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`.
50
51
  - **Resources default to deny for writes.** List `fields` explicitly for public APIs. Server-set values (e.g. `authorId`) belong in `beforeCreate`.
51
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.
52
53
  - **UI strings** go through `t()`; a literal `{`, `}`, `@` or `|` in a locale message breaks the whole language.
@@ -59,6 +60,7 @@ Step-by-step procedures for common jobs. Claude Code loads them as skills; any o
59
60
  - Add or change a model: [`.claude/skills/knit-add-model/SKILL.md`](.claude/skills/knit-add-model/SKILL.md)
60
61
  - Add a public API and forms: [`.claude/skills/knit-add-api/SKILL.md`](.claude/skills/knit-add-api/SKILL.md)
61
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)
62
64
  - Add or translate UI strings: [`.claude/skills/knit-add-translation/SKILL.md`](.claude/skills/knit-add-translation/SKILL.md)
63
65
  - Add a background or scheduled task: [`.claude/skills/knit-add-task/SKILL.md`](.claude/skills/knit-add-task/SKILL.md)
64
66
  - Write an end-to-end test: [`.claude/skills/knit-write-e2e-test/SKILL.md`](.claude/skills/knit-write-e2e-test/SKILL.md)
@@ -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`, `knit-add-permission`, `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>`.
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=
@@ -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 +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>` (server/channels/comments.ts decides who hears what); the list re-reads
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, but moderation still applies to what each subscriber receives:
6
- * - moderators (`blog.change_comment`) get every event;
7
- * - authors get events about their own pending comments;
8
- * - everyone else only hears about approved comments. A comment that is unapproved again reaches
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>`. Who receives what is decided by `server/channels/comments.ts`.
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
- * - Authors see their own comments while they await moderation, and may edit or delete them.
7
- * - Moderators (`blog.change_comment`) see everything.
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, or } from 'drizzle-orm'
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, isOwner } from '@knit-framework/core/resources'
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
- update: [isOwner('authorId'), MODERATE],
32
- delete: [isOwner('authorId'), 'blog.delete_comment'],
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) {
@@ -1,5 +1,5 @@
1
1
  {
2
- "knit": "0.6.1",
2
+ "knit": "0.7.0",
3
3
  "nuxt": "^4.7.0",
4
4
  "drizzleOrm": "^0.45.4",
5
5
  "typescript": "^6.0.3",