create-knit 0.8.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/base/.claude/skills/knit-add-permission/SKILL.md +2 -1
- package/template/base/apps/web/.env.example +13 -1
- package/template/base/llms.txt +2 -0
- package/template/examples/layers/example-blog/server/api/blog/insights.get.ts +4 -2
- package/template/examples/layers/example-blog/server/resources/comments.ts +2 -2
- package/template/examples/layers/example-blog/server/tasks/blog.ts +2 -2
- package/template/examples/layers/example-blog/test/blog.test.ts +20 -0
- package/template/versions.json +1 -1
package/package.json
CHANGED
|
@@ -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, 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.
|
|
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 (incl. organization-scoped rows), 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 their organization's rows ("each team sees only its projects"), or grant permissions in a Knit project.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Add a permission and grant it
|
|
@@ -14,6 +14,7 @@ description: Add a custom permission to a Knit app, enforce it on the server and
|
|
|
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
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
|
+
- Rows that belong to an organization ("each customer sees only their company's projects"): turn on organizations (`NUXT_KNIT_AUTH_ORGANIZATIONS_ENABLED=true`), give the model an `organizationId` column referencing `organization.id` from `@knit-framework/core/schema`, and run `pnpm manage generate policy <app> <model> --organization`: `scope: inActiveOrganization('organizationId')`, `assignOrganization: 'organizationId'`, and `hasOrganizationRole('owner', 'admin')` for what only the organization's admins may do. `ctx.organization` (`{ id, role }` or `null`) is in every rule. In tests, `createTestClient().switchOrganization(id)`. Guide: `knit_docs { "topic": "organizations" }`.
|
|
17
18
|
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
19
|
5. **Grant it.**
|
|
19
20
|
- By hand: `/admin/auth/groups/:id` (a matrix per group) or `/admin/auth/users/:id`.
|
|
@@ -67,6 +67,14 @@ NUXT_BETTER_AUTH_URL=
|
|
|
67
67
|
# NUXT_KNIT_AUTH_TWO_FACTOR=optional
|
|
68
68
|
# Passkeys (WebAuthn): true (default) | false
|
|
69
69
|
# NUXT_KNIT_AUTH_PASSKEYS=true
|
|
70
|
+
# Organizations (docs/organizations.md): users create them, invite members and switch the active one
|
|
71
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_ENABLED=false
|
|
72
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_ALLOW_USER_TO_CREATE=true
|
|
73
|
+
# Creator's role: always owner (admin is refused: the creator could not delete the organization)
|
|
74
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_CREATOR_ROLE=owner
|
|
75
|
+
# Invitation lifetime in seconds (default 48 hours)
|
|
76
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_INVITATION_EXPIRES_IN=172800
|
|
77
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_MEMBERSHIP_LIMIT=100
|
|
70
78
|
|
|
71
79
|
# Email. Mailer: console (dev default, prints to the terminal) | smtp | memory (in-process outbox)
|
|
72
80
|
# Empty mailer = smtp when NUXT_MAIL_URL is set, otherwise console.
|
|
@@ -100,9 +108,13 @@ NUXT_BETTER_AUTH_URL=
|
|
|
100
108
|
# ── Site ────────────────────────────────────────────────────────────────────────
|
|
101
109
|
# Public base URL for sitemaps and feeds (default: NUXT_BETTER_AUTH_URL, then the request)
|
|
102
110
|
# NUXT_KNIT_SITE_URL=https://example.com
|
|
111
|
+
# Development only: more host names the Knit DevTools page works under (default: localhost,
|
|
112
|
+
# *.localhost, 127.0.0.1 and [::1], from this machine). Comma-separated; .name covers subdomains.
|
|
113
|
+
# NUXT_KNIT_DEV_ALLOWED_HOSTS=myapp.test
|
|
103
114
|
|
|
104
115
|
# ── Security (headers, CSRF, CSP) ───────────────────────────────────────────────
|
|
105
|
-
# Origin-based CSRF guard for cookie-authenticated POST/PUT/PATCH/DELETE to /api/**
|
|
116
|
+
# Origin-based CSRF guard for cookie-authenticated POST/PUT/PATCH/DELETE to /api/** and to
|
|
117
|
+
# defineEndpoint() routes outside it (default true)
|
|
106
118
|
# NUXT_KNIT_SECURITY_CSRF=true
|
|
107
119
|
# Extra origins allowed to make state-changing requests, comma-separated
|
|
108
120
|
# NUXT_KNIT_SECURITY_TRUSTED_ORIGINS=https://app.example.com
|
package/template/base/llms.txt
CHANGED
|
@@ -21,6 +21,7 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
|
|
|
21
21
|
- [Admin](node_modules/@knit-framework/core/docs/admin.md): `registerAdminModel` options, filters, actions, inlines, history, user tools, REST API
|
|
22
22
|
- [Auth & permissions](node_modules/@knit-framework/core/docs/auth.md): Users, staff, superusers, groups, permissions, `/accounts/*` pages
|
|
23
23
|
- [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
|
|
24
|
+
- [Organizations](node_modules/@knit-framework/core/docs/organizations.md): `NUXT_KNIT_AUTH_ORGANIZATIONS_ENABLED`, invitations, roles, `inActiveOrganization` / `hasOrganizationRole` / `assignOrganization`, `useOrganization()`, `switchOrganization()` in tests
|
|
24
25
|
- [Internationalization](node_modules/@knit-framework/core/docs/i18n.md): Translations, locales per layer, translating models, the language switcher
|
|
25
26
|
- [Email](node_modules/@knit-framework/core/docs/email.md): `sendMail()`, mailers, templates, auth emails
|
|
26
27
|
- [Background tasks](node_modules/@knit-framework/core/docs/tasks.md): `defineTask`, `enqueue`, the worker, cron schedules
|
|
@@ -32,6 +33,7 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
|
|
|
32
33
|
- [Logging](node_modules/@knit-framework/core/docs/logging.md): LogLayer: pretty dev output, JSON in production, request logs, redaction
|
|
33
34
|
- [Security](node_modules/@knit-framework/core/docs/security.md): CSRF, security headers, CSP
|
|
34
35
|
- [Testing](node_modules/@knit-framework/core/docs/testing.md): Test databases, factories, the HTTP client, `pnpm test`
|
|
36
|
+
- [Knit in Nuxt DevTools](node_modules/@knit-framework/core/docs/devtools.md): the dev-only Knit tab (models, routes, tasks, mail, realtime, errors, migrations), its actions and who may read it
|
|
35
37
|
- [`manage` CLI](node_modules/@knit-framework/core/docs/cli.md): Every command, `startapp` and `generate`, JSON output for scripts and agents, seeds, custom commands
|
|
36
38
|
- [Configuration](node_modules/@knit-framework/core/docs/configuration.md): Every environment variable and setting
|
|
37
39
|
- [Deployment](node_modules/@knit-framework/core/docs/deployment/index.md): production checklist, what Knit needs from a host, and one page per host (Docker, VPS with systemd and Caddy, Fly.io, Railway, Render; Vercel and Netlify with limits; Cloudflare not supported)
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { count, desc, eq } from 'drizzle-orm'
|
|
1
|
+
import { and, count, desc, eq } from 'drizzle-orm'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Data for the admin's Insights page (app/pages/admin/blog-insights.vue): the most commented posts
|
|
5
5
|
* and posts per category. The page is linked only for `blog.view_post`; the endpoint checks it too.
|
|
6
|
+
* Raw reads of a soft-delete model: `notDeletedWhere(post)` keeps posts in the trash out of both.
|
|
6
7
|
*/
|
|
7
8
|
export default defineEventHandler(async (event) => {
|
|
8
9
|
await requirePermission(event, 'blog.view_post')
|
|
@@ -12,12 +13,13 @@ export default defineEventHandler(async (event) => {
|
|
|
12
13
|
db.select({ id: post.id, title: post.title, comments: count(comment.id) })
|
|
13
14
|
.from(post)
|
|
14
15
|
.leftJoin(comment, eq(comment.postId, post.id))
|
|
16
|
+
.where(notDeletedWhere(post))
|
|
15
17
|
.groupBy(post.id)
|
|
16
18
|
.orderBy(desc(count(comment.id)), desc(post.id))
|
|
17
19
|
.limit(5),
|
|
18
20
|
db.select({ id: category.id, name: category.name, posts: count(post.id) })
|
|
19
21
|
.from(category)
|
|
20
|
-
.leftJoin(post, eq(post.categoryId, category.id))
|
|
22
|
+
.leftJoin(post, and(eq(post.categoryId, category.id), notDeletedWhere(post)))
|
|
21
23
|
.groupBy(category.id)
|
|
22
24
|
.orderBy(desc(count(post.id)), category.name),
|
|
23
25
|
])
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { and, eq, inArray } from 'drizzle-orm'
|
|
11
11
|
import { user } from '@knit-framework/core/schema'
|
|
12
|
-
import { ValidationError } from '@knit-framework/core/models'
|
|
12
|
+
import { notDeletedWhere, ValidationError } from '@knit-framework/core/models'
|
|
13
13
|
import { defineResource } from '@knit-framework/core/resources'
|
|
14
14
|
import { comment, post } from '../database/schema'
|
|
15
15
|
|
|
@@ -37,7 +37,7 @@ export default defineResource(comment, {
|
|
|
37
37
|
const postId = Number(data.postId)
|
|
38
38
|
if (Number.isInteger(postId)) {
|
|
39
39
|
const [target] = await ctx.db.select({ id: post.id }).from(post)
|
|
40
|
-
.where(and(eq(post.id, postId), eq(post.published, true)))
|
|
40
|
+
.where(and(eq(post.id, postId), eq(post.published, true), notDeletedWhere(post)))
|
|
41
41
|
if (!target) throw new ValidationError({ postId: 'Comments are only open on published posts.' })
|
|
42
42
|
}
|
|
43
43
|
return { ...data, authorId: ctx.user.id }
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* enqueue('blog.word-count', { postId: 1 }) // from any server route
|
|
6
6
|
* pnpm manage runtask blog.word-count --payload '{"postId":1}'
|
|
7
7
|
*/
|
|
8
|
-
import { count, eq } from 'drizzle-orm'
|
|
8
|
+
import { and, count, eq } from 'drizzle-orm'
|
|
9
9
|
import { notDeletedWhere } from '@knit-framework/core/models'
|
|
10
10
|
import { defineTask } from '@knit-framework/core/tasks'
|
|
11
11
|
import { post } from '../database/schema'
|
|
@@ -21,7 +21,7 @@ export const wordCount = defineTask({
|
|
|
21
21
|
const [row] = await ctx.db
|
|
22
22
|
.select({ title: post.title, body: post.body })
|
|
23
23
|
.from(post)
|
|
24
|
-
.where(eq(post.id, payload.postId))
|
|
24
|
+
.where(and(eq(post.id, payload.postId), notDeletedWhere(post)))
|
|
25
25
|
if (!row) throw new Error(`Post ${payload.postId} does not exist.`)
|
|
26
26
|
const words = row.body.trim().split(/\s+/).filter(Boolean).length
|
|
27
27
|
ctx.log(`"${row.title}" has ${words} word(s)`)
|
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
* Example app test. Copy this pattern into your own layers:
|
|
3
3
|
* a fresh in-memory database per file, typed factories, and plain Drizzle queries.
|
|
4
4
|
*/
|
|
5
|
+
import { useModel, ValidationError } from '@knit-framework/core/models'
|
|
5
6
|
import * as coreSchema from '@knit-framework/core/schema'
|
|
6
7
|
import { createTestDatabase, defineFactory, type TestDatabase } from '@knit-framework/core/testing'
|
|
7
8
|
import { eq } from 'drizzle-orm'
|
|
8
9
|
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
|
|
9
10
|
import * as blogSchema from '../server/database/schema'
|
|
11
|
+
import comments from '../server/resources/comments'
|
|
12
|
+
import { wordCount } from '../server/tasks/blog'
|
|
10
13
|
|
|
11
14
|
const schema = { ...coreSchema, ...blogSchema }
|
|
12
15
|
const categories = defineFactory(blogSchema.category, n => ({ name: `Category ${n}`, slug: `category-${n}` }))
|
|
@@ -43,4 +46,21 @@ describe('blog', () => {
|
|
|
43
46
|
const [reloaded] = await t.db.select().from(blogSchema.post).where(eq(blogSchema.post.id, post.id))
|
|
44
47
|
expect(reloaded?.categoryId).toBeNull()
|
|
45
48
|
})
|
|
49
|
+
|
|
50
|
+
// Posts are a soft-delete model: raw reads narrow themselves with `notDeletedWhere(post)`.
|
|
51
|
+
it('a post in the trash is gone for the word-count task and closed for comments', async () => {
|
|
52
|
+
const post = await posts.create(t.db, { title: 'Trashed', body: 'three little words', published: true })
|
|
53
|
+
const context = { db: t.db, log: () => {} } as unknown as Parameters<typeof wordCount.definition.run>[1]
|
|
54
|
+
const commenting = { db: t.db, user: { id: 'reader' } } as unknown as Parameters<NonNullable<typeof comments.options.beforeCreate>>[1]
|
|
55
|
+
const comment = (): unknown => comments.options.beforeCreate!({ postId: post.id, body: 'Nice post' }, commenting)
|
|
56
|
+
|
|
57
|
+
expect(await wordCount.definition.run({ postId: post.id }, context)).toMatchObject({ words: 3 })
|
|
58
|
+
expect(await comment()).toMatchObject({ postId: post.id, authorId: 'reader' })
|
|
59
|
+
|
|
60
|
+
await useModel(blogSchema.post, { db: t.db }).delete(post.id)
|
|
61
|
+
await expect(wordCount.definition.run({ postId: post.id }, context)).rejects.toThrow(/does not exist/)
|
|
62
|
+
const error = await Promise.resolve().then(comment).catch((e: unknown) => e)
|
|
63
|
+
expect(error).toBeInstanceOf(ValidationError)
|
|
64
|
+
expect((error as ValidationError).fieldErrors['postId']).toBeDefined()
|
|
65
|
+
})
|
|
46
66
|
})
|
package/template/versions.json
CHANGED