tinyzoo 0.3.0 → 0.4.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/cli/generate.ts CHANGED
@@ -31,7 +31,8 @@ export interface GenerateOptions {
31
31
  error?: (line: string) => void
32
32
  }
33
33
 
34
- const journalTags = (dir: string): string[] => {
34
+ /** The migrations a folder's drizzle journal lists, by tag (file name without `.sql`). */
35
+ export const journalTags = (dir: string): string[] => {
35
36
  const file = join(dir, 'meta/_journal.json')
36
37
  return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')).entries as { tag: string }[]).map((e) => e.tag) : []
37
38
  }
package/cli/index.ts CHANGED
@@ -120,7 +120,7 @@ switch (cmd) {
120
120
  case 'generate': process.exit(await generate()); break
121
121
  case 'up': process.exit(await up(cwd)); break
122
122
  case 'status': process.exit(await status(cwd)); break
123
- case 'upgrade': process.exit(await upgrade(cwd, resolve(dirname(fileURLToPath(import.meta.url)), '..'), { generate })); break
123
+ case 'upgrade': process.exit(await upgrade(cwd, resolve(dirname(fileURLToPath(import.meta.url)), '..'), { generate, migrationsDir: resolve(cwd, 'server/db/migrations') })); break
124
124
  case 'client': await client(); break
125
125
  case 'openapi': await openapi(); break
126
126
  case 'content:migrate': await (await import('./content-migrate')).contentMigrateCommand(await loadConfig(), process.argv.slice(3)); break
package/cli/upgrade.ts CHANGED
@@ -7,12 +7,15 @@ import { docsUrl } from '../src/docs'
7
7
  import { execFileSync } from 'node:child_process'
8
8
  import { existsSync, readFileSync } from 'node:fs'
9
9
  import { join } from 'node:path'
10
+ import { journalTags } from './generate'
10
11
  import { checkVersions } from './versions'
11
12
  import { status } from './status'
12
13
 
13
14
  export interface UpgradeDeps {
14
15
  /** Emit schema.ts and generate the migration (with the guard). Returns an exit code. */
15
16
  generate: () => Promise<number>
17
+ /** The site's migrations folder (default `server/db/migrations`), to tell whether `generate` wrote one. */
18
+ migrationsDir?: string
16
19
  }
17
20
 
18
21
  /** Returns the process exit code. */
@@ -22,12 +25,14 @@ export async function upgrade(cwd: string, pkgDir: string, deps: UpgradeDeps): P
22
25
 
23
26
  console.log('1. Versions')
24
27
  const problems = checkVersions(cwd, own)
25
- if (!problems.length) console.log(' ✓ nuxt, @nuxt/ui, drizzle-orm and zod fit this tinyzoo')
28
+ if (!problems.length) console.log(' ✓ nuxt, @nuxt/ui, nuxt-auth-utils, drizzle-orm and zod fit this tinyzoo')
26
29
  for (const p of problems) {
27
30
  console.warn(` ⚠ ${p.name}: ${p.installed ? `${p.installed} is installed` : 'not installed'}, tinyzoo ${own.version} wants ${p.wanted} — update it (\`pnpm up ${p.name}\`) before deploying`)
28
31
  }
29
32
 
30
33
  console.log('\n2. Schema and migration')
34
+ const migrationsDir = deps.migrationsDir ?? join(cwd, 'server/db/migrations')
35
+ const before = new Set(journalTags(migrationsDir))
31
36
  const code = await deps.generate()
32
37
  if (code !== 0) {
33
38
  console.error('\n✗ Stopped: fix the above and run `tinyzoo upgrade` again.')
@@ -51,10 +56,23 @@ export async function upgrade(cwd: string, pkgDir: string, deps: UpgradeDeps): P
51
56
  const statusCode = await status(cwd)
52
57
  if (statusCode === 2) console.log(' (Could not check the database from here. Run `tinyzoo status` where DATABASE_URL points at it.)')
53
58
 
54
- console.log(`\nNext:
55
- 1. Read the new migration in server/db/migrations — that is the change your database will get.
56
- 2. pnpm typecheck, then commit the migration, schema.ts and the typed client together with the package update.
57
- 3. Deploy. The app migrates itself at start (NUXT_CMS_MIGRATIONS_ON_START=true), or run \`tinyzoo up\` yourself.
58
- Details: ${docsUrl('upgrading')}`)
59
+ const added = journalTags(migrationsDir).filter((t) => !before.has(t))
60
+ console.log(`\n${nextSteps(added)}\n Details: ${docsUrl('upgrading')}`)
59
61
  return 0
60
62
  }
63
+
64
+ /** What to do after `tinyzoo upgrade`: with a new migration, read and commit it; without one, there is none to read. */
65
+ export function nextSteps(added: string[]): string {
66
+ const deploy = '3. Deploy. The app migrates itself at start (NUXT_CMS_MIGRATIONS_ON_START=true), or run `tinyzoo up` yourself.'
67
+ if (!added.length) {
68
+ return `Next:
69
+ 1. No new migration: this update changes nothing in your database schema (step 4 shows whether earlier migrations are still waiting).
70
+ 2. pnpm typecheck, then commit schema.ts and the typed client (if they changed) together with the package update.
71
+ ${deploy}`
72
+ }
73
+ const files = added.map((t) => `server/db/migrations/${t}.sql`).join(', ')
74
+ return `Next:
75
+ 1. Read the new migration (${files}): that is the change your database will get.
76
+ 2. pnpm typecheck, then commit the migration, schema.ts and the typed client together with the package update.
77
+ ${deploy}`
78
+ }
package/cli/versions.ts CHANGED
@@ -1,8 +1,8 @@
1
- /** Version checks for `tinyzoo upgrade`: does the site's own nuxt, @nuxt/ui, drizzle-orm and zod fit? */
1
+ /** Version checks for `tinyzoo upgrade`: does the site's own nuxt, @nuxt/ui, nuxt-auth-utils, drizzle-orm and zod fit? */
2
2
  import { existsSync, readFileSync } from 'node:fs'
3
3
  import { dirname, join, parse } from 'node:path'
4
4
 
5
- export const CHECKED_PACKAGES = ['nuxt', '@nuxt/ui', 'drizzle-orm', 'zod'] as const
5
+ export const CHECKED_PACKAGES = ['nuxt', '@nuxt/ui', 'nuxt-auth-utils', 'drizzle-orm', 'zod'] as const
6
6
 
7
7
  const parseVersion = (v: string): [number, number, number] | null => {
8
8
  const m = /^[v=\s]*(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?/.exec(v)
package/forms/index.ts CHANGED
@@ -198,6 +198,3 @@ export function formsPlugin(): CmsPlugin {
198
198
  },
199
199
  })
200
200
  }
201
-
202
- /** The registration the deprecated `defineForm` / `defineFormSettings` of `tinyzoo` leave to the plugin. */
203
- export const IMPLICIT_FORMS_REQUIREMENT: CmsPluginRequirement = { ...FORMS_REQUIREMENT, create: formsPlugin }
package/module.ts CHANGED
@@ -3,6 +3,7 @@ import { dirname, resolve } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import { addComponentsDir, addServerHandler, addServerPlugin, addTypeTemplate, defineNuxtModule, extendPages } from '@nuxt/kit'
5
5
  import { createJiti } from 'jiti'
6
+ import { appSecretFallbackCode, NITRO_CONFIG_MODULE, planAppSecretFallback, prependedLinesMap } from './src/appSecret'
6
7
  import { collectPlugins, planPlugins, type CmsPlugin } from './src/plugin'
7
8
 
8
9
  const layerDir = dirname(fileURLToPath(import.meta.url))
@@ -201,6 +202,22 @@ function sitemapPaths(paths: (string | Record<string, string>)[] | undefined): (
201
202
  return paths ?? []
202
203
  }
203
204
 
205
+ /**
206
+ * NUXT_SESSION_PASSWORD (or a nuxt.config `runtimeConfig.session.password`) standing in for
207
+ * NUXT_APP_SECRET until 0.5: the lines of src/appSecret.ts put at the top of Nitro's runtime
208
+ * config module, before Nitro reads the environment.
209
+ */
210
+ function appSecretFallback(code: string, onInstalled: () => void) {
211
+ return {
212
+ name: 'tinyzoo:app-secret-fallback',
213
+ transform(source: string, id: string) {
214
+ if (!NITRO_CONFIG_MODULE.test(id.split('?')[0]!)) return null
215
+ onInstalled()
216
+ return { code: code + source, map: prependedLinesMap(code, source, id) }
217
+ },
218
+ }
219
+ }
220
+
204
221
  export default defineNuxtModule<CmsModuleOptions>({
205
222
  meta: { name: 'tinyzoo', configKey: 'cms' },
206
223
  defaults: { config: 'cms.config.ts' },
@@ -214,15 +231,22 @@ export default defineNuxtModule<CmsModuleOptions>({
214
231
  nuxt.options.alias['#cms/config'] = configPath
215
232
  // Bundle the host's migrations as server assets so they ship with .output.
216
233
  const migrationsDir = resolve(nuxt.options.rootDir, options.migrations?.dir || 'server/db/migrations')
234
+ // NUXT_SESSION_PASSWORD as the app secret while a site has not set NUXT_APP_SECRET yet
235
+ // (src/appSecret.ts).
236
+ nuxt.hook('nitro:init', (nitro) => {
237
+ const plan = planAppSecretFallback(nitro.options.runtimeConfig as any)
238
+ if (!plan.install) return
239
+ let installed = false
240
+ nitro.hooks.hook('rollup:before', (_nitro, rollupConfig) => {
241
+ const plugins = (rollupConfig.plugins ||= []) as any[]
242
+ plugins.push(appSecretFallback(appSecretFallbackCode(plan.envPrefix, plan.fromConfig), () => { installed = true }))
243
+ })
244
+ // After the server is built, whichever bundler built it: was the module found?
245
+ nitro.hooks.hook('compiled', () => {
246
+ if (!installed) console.warn('[tinyzoo] Nitro\'s runtime config module was not found in the server bundle, so NUXT_SESSION_PASSWORD will not stand in for NUXT_APP_SECRET: set NUXT_APP_SECRET.')
247
+ })
248
+ })
217
249
  nuxt.hook('nitro:config', (nitro) => {
218
- // nuxt-auth-utils adds a Nitro plugin when WebSockets are on (the admin's live socket
219
- // is one) that reads the session on EVERY request: for a visitor without one that
220
- // *creates* it and sets a cookie on every response, public pages, content API and
221
- // media included, so no CDN caches them. The admin socket checks the session itself
222
- // (admitAdminSocket) and only when the request carries one, so that plugin goes.
223
- if (Array.isArray(nitro.plugins)) {
224
- nitro.plugins = nitro.plugins.filter((p) => !/nuxt-auth-utils[\\/]dist[\\/]runtime[\\/]server[\\/]plugins[\\/]ws(\.|$)/.test(String(p)))
225
- }
226
250
  if (existsSync(migrationsDir)) {
227
251
  nitro.serverAssets = nitro.serverAssets || []
228
252
  nitro.serverAssets.push({ baseName: 'cms-migrations', dir: migrationsDir })
@@ -253,7 +277,7 @@ export default defineNuxtModule<CmsModuleOptions>({
253
277
  locale: string | null
254
278
  }
255
279
  interface UserSession {
256
- cms?: { uid: string; sv: number }
280
+ cms?: { uid: string; sv: number; iat: number }
257
281
  }
258
282
  }
259
283
  declare module 'nitropack/types' {
package/nuxt.config.ts CHANGED
@@ -19,9 +19,10 @@ export default defineNuxtConfig({
19
19
  // Admin design tokens, scoped to html[data-cms-admin] so the host site's own
20
20
  // theme is untouched (see app/assets/css/cms-admin.css).
21
21
  css: [join(layerDir, 'app/assets/css/cms-admin.css')],
22
- // Admin sessions end after 14 days at the latest (sign in again). Without a maxAge
23
- // a copied session cookie would stay valid until the account changes. Hosts can
24
- // override with runtimeConfig.session.maxAge / NUXT_SESSION_MAX_AGE.
22
+ // Admin sessions end 14 days after signing in: sign in again. Changing one's name, language,
23
+ // email or password writes the session again but keeps the time of the sign-in (cms.iat,
24
+ // checked in activeAccountOf), so a copied session cookie cannot be kept alive past it.
25
+ // Hosts can override with runtimeConfig.session.maxAge / NUXT_SESSION_MAX_AGE (seconds).
25
26
  runtimeConfig: {
26
27
  session: { maxAge: 60 * 60 * 24 * 14 },
27
28
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tinyzoo",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Code-first, distributable CMS for Nuxt 4 (Layer + Module).",
6
6
  "license": "UNLICENSED",
@@ -54,7 +54,7 @@
54
54
  "@hocuspocus/extension-redis": "^4.8.0",
55
55
  "@hocuspocus/provider": "^4.8.0",
56
56
  "@hocuspocus/server": "^4.8.0",
57
- "@nuxt/kit": "^4.0.0",
57
+ "@nuxt/kit": "^4.6.4",
58
58
  "@tiptap/core": "^3.34.0",
59
59
  "@tiptap/extension-collaboration": "^3.34.0",
60
60
  "@tiptap/extension-collaboration-caret": "3.34.0",
@@ -85,8 +85,8 @@
85
85
  "peerDependencies": {
86
86
  "@internationalized/date": "^3.12.2",
87
87
  "@nuxt/ui": "^4.9.0",
88
- "nuxt": "^4.4.0",
89
- "nuxt-auth-utils": "^0.5.29"
88
+ "nuxt": "^4.6.4",
89
+ "nuxt-auth-utils": "^0.6.2"
90
90
  },
91
91
  "bin": {
92
92
  "tinyzoo": "./cli/index.ts"
@@ -63,7 +63,7 @@ export default defineEventHandler(async (event) => {
63
63
  }
64
64
 
65
65
  const sameAccount = getCmsSession(event)?.id === updated.id
66
- if (sameAccount) await startCmsSession(event, updated)
66
+ if (sameAccount) await continueCmsSession(event, updated) // the sign-in time stays
67
67
  await audit(event, 'account.email', { userId: updated.id, meta: { email: updated.email, previousEmail: before.email } })
68
68
 
69
69
  const locale = updated.locale || requestLocale(event)
@@ -26,7 +26,7 @@ export default defineEventHandler(async (event) => {
26
26
  await clearUserSession(event)
27
27
  throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
28
28
  }
29
- await startCmsSession(event, u)
29
+ await continueCmsSession(event, u) // the sign-in time stays: this does not make the session last longer
30
30
  await audit(event, 'account.update', { meta: { fields: Object.keys(data) } })
31
31
  return { user: sessionUser(u) }
32
32
  })
@@ -23,7 +23,7 @@ export default defineEventHandler(async (event) => {
23
23
  await clearUserSession(event)
24
24
  throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
25
25
  }
26
- await startCmsSession(event, updated)
26
+ await continueCmsSession(event, updated) // the sign-in time stays
27
27
  await audit(event, 'account.password')
28
28
  return { ok: true }
29
29
  })
@@ -65,7 +65,7 @@ export default defineWebSocketHandler({
65
65
  socketsByUser.set(user.id, mine)
66
66
  const server = await useCollabServer()
67
67
  if (state.closed) return // gone while the server started
68
- const connection = server.handleConnection(peer.websocket, peer.request, { user, sv: peer.context.cmsSessionVersion })
68
+ const connection = server.handleConnection(peer.websocket, peer.request, { user, sv: peer.context.cmsSessionVersion, iat: peer.context.cmsSignedInAt })
69
69
  state.connection = connection
70
70
  ws.on('pong', () => connection.touch())
71
71
  state.ping = setInterval(() => {
@@ -16,7 +16,7 @@ export default defineWebSocketHandler({
16
16
  // (the `ws` default is 100 MiB). crossws-private, so only when it is there.
17
17
  const ws = peer._internal?.ws
18
18
  if (ws?._receiver && typeof ws._receiver._maxPayload === 'number') ws._receiver._maxPayload = 16 * 1024
19
- liveOpen(peer, user, peer.context.cmsSessionVersion)
19
+ liveOpen(peer, user, peer.context.cmsSessionVersion, peer.context.cmsSignedInAt)
20
20
  },
21
21
  message(peer: any, message: any) {
22
22
  return liveMessage(peer, message.text())
@@ -38,4 +38,6 @@ export default defineEventHandler(async (event) => {
38
38
  // The version this request was authorised with; writes that re-sign the session
39
39
  // must not upgrade a session past a concurrent password change (see me.patch).
40
40
  event.context.cmsSessionVersion = u.sessionVersion
41
+ // When this browser signed in: a session written again keeps it (continueCmsSession).
42
+ event.context.cmsSignedInAt = session.cms.iat
41
43
  })
@@ -1,11 +1,16 @@
1
+ import { cmsDeprecated } from 'tinyzoo'
2
+
1
3
  // Check the settings a production server cannot work without, when it starts: the platform
2
4
  // then shows a start that failed with the variable's name, instead of a server that
3
5
  // answers "ready" and fails the first sign-in (or the first request) with a bare 500.
4
- // - NUXT_SESSION_PASSWORD: at least 32 characters (it seals the session cookie);
6
+ // - NUXT_APP_SECRET: at least 32 characters (nuxt-auth-utils seals the session cookie with
7
+ // a key derived from it). Until 0.5, NUXT_SESSION_PASSWORD (or nuxt.config's
8
+ // runtimeConfig.session.password) stands in for it when it is not set (src/appSecret.ts),
9
+ // with a deprecation warning;
5
10
  // - a database address: NUXT_CMS_DATABASE_URL or DATABASE_URL;
6
11
  // - NUXT_CMS_PUBLIC_URL: not fatal, but the sitemap and the links in emails need it — one warning.
7
- // Development keeps its defaults (nuxt-auth-utils makes a password, the dev database is
8
- // in .env); a prerender during the build has no runtime settings either.
12
+ // Development keeps its defaults (Nuxt generates an app secret, the dev database is in
13
+ // .env); a prerender during the build has no runtime settings either.
9
14
  export default defineNitroPlugin(() => {
10
15
  if (process.env.NODE_ENV !== 'production' || import.meta.prerender) return
11
16
  const config = useRuntimeConfig()
@@ -13,10 +18,30 @@ export default defineNitroPlugin(() => {
13
18
 
14
19
  const problems: string[] = []
15
20
  if (cmsAuthMode() === 'builtin') {
16
- const password = String(process.env.NUXT_SESSION_PASSWORD || (config.session as any)?.password || '')
17
- if (password.length < 32) {
18
- problems.push(`NUXT_SESSION_PASSWORD is ${password ? 'only ' + password.length + ' characters long' : 'not set'}; it must be at least 32 characters `
19
- + '(it seals the session cookie). Make one with: openssl rand -base64 32')
21
+ const secret = (config as any).appSecret
22
+ // The variable Nitro read the app secret from: NITRO_APP_SECRET when it is there (even
23
+ // empty), otherwise the site's prefix (NUXT_, or nitro.envPrefix).
24
+ const prefix = String((config as any).nitro?.envPrefix || 'NUXT_')
25
+ const secretVar = process.env.NITRO_APP_SECRET !== undefined ? 'NITRO_APP_SECRET' : `${prefix}APP_SECRET`
26
+ // What stood in for it (src/appSecret.ts): NUXT_SESSION_PASSWORD, or nuxt.config's runtimeConfig.session.password.
27
+ const from = (globalThis as any)[Symbol.for('tinyzoo.appSecretFrom')] as string | undefined
28
+ const name = from ? `${from} (used because ${secretVar} is not set)` : secretVar
29
+ if (secret !== undefined && secret !== null && secret !== '' && typeof secret !== 'string') {
30
+ const kind = Array.isArray(secret) ? 'a list' : typeof secret === 'object' ? 'an object' : `a ${typeof secret}`
31
+ problems.push(`${name} was read as ${kind}, not as text (the environment is parsed as JSON where it can be). `
32
+ + 'Make one with: openssl rand -base64 32')
33
+ }
34
+ else if (String(secret ?? '').length < 32) {
35
+ problems.push(`${name} is ${secret ? 'only ' + String(secret).length + ' characters long' : 'not set'}; it must be at least 32 characters `
36
+ + '(the sign-in cookie is sealed with a key derived from it). Make one with: openssl rand -base64 32')
37
+ }
38
+ else if (from) {
39
+ const move = from === 'runtimeConfig.session.password'
40
+ ? `Move the value to ${prefix}APP_SECRET in the environment and remove it from nuxt.config`
41
+ : `Rename the variable to ${prefix}APP_SECRET`
42
+ cmsDeprecated('env:NUXT_SESSION_PASSWORD', `${from} is used as the app secret because ${secretVar} is not set: nuxt-auth-utils 0.6 `
43
+ + `no longer reads it. ${move}; with the same value nobody is signed out again. Until then, nuxt-auth-utils' own warning `
44
+ + 'that it "is not used anymore" can be ignored: tinyzoo uses it.', { removeIn: '0.5.0' })
20
45
  }
21
46
  }
22
47
  if (!(process.env.NUXT_CMS_DATABASE_URL || process.env.DATABASE_URL || cms.databaseUrl)) {
@@ -90,9 +90,34 @@ export function sessionUser(u: any) {
90
90
  return { id: u.id as string, email: u.email as string, name: (u.name as string) || u.email, role: u.role as string, locale: (u.locale as string | null) ?? null }
91
91
  }
92
92
 
93
- /** Sign the person in on this browser (replaces any previous session). */
93
+ /**
94
+ * Sign the person in on this browser (replaces any previous session). The session keeps the
95
+ * time of the sign-in (`cms.iat`, ms): it ends `runtimeConfig.session.maxAge` after it
96
+ * (activeAccountOf), however often it is written again since. nuxt-auth-utils 0.6 only
97
+ * counts its own age from the last write, so without this a stolen cookie that keeps
98
+ * changing something (a name, the language) would never end.
99
+ */
94
100
  export async function startCmsSession(event: any, u: any): Promise<void> {
95
- await replaceUserSession(event, { user: sessionUser(u), cms: { uid: u.id as string, sv: u.sessionVersion as number } } as any)
101
+ await sealCmsSession(event, u, Date.now())
102
+ }
103
+
104
+ /**
105
+ * Write the session of the person already signed in on this browser again (a changed name,
106
+ * language, password or email), keeping the time they signed in: no later than `maxAge`
107
+ * after that, they sign in again. Without that time (not signed in on this request) nothing
108
+ * is written: 401.
109
+ */
110
+ export async function continueCmsSession(event: any, u: any): Promise<void> {
111
+ const signedInAt = event.context?.cmsSignedInAt
112
+ if (typeof signedInAt !== 'number' || event.context?.cmsUser?.id !== u.id) {
113
+ await clearUserSession(event)
114
+ throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
115
+ }
116
+ await sealCmsSession(event, u, signedInAt)
117
+ }
118
+
119
+ async function sealCmsSession(event: any, u: any, iat: number): Promise<void> {
120
+ await replaceUserSession(event, { user: sessionUser(u), cms: { uid: u.id as string, sv: u.sessionVersion as number, iat } } as any)
96
121
  }
97
122
 
98
123
  // ── links in emails ────────────────────────────────────────────────────────────
@@ -28,6 +28,8 @@ interface CollabContext {
28
28
  /** The one Yjs client this connection may speak for in cursor (awareness) updates. */
29
29
  clientId?: number
30
30
  sv: number
31
+ /** When the session this socket was admitted with was signed in (it ends with that session). */
32
+ iat: number
31
33
  epoch: string
32
34
  access: 'write' | 'read'
33
35
  checkedAt: number
@@ -118,7 +120,7 @@ function dropSocket(ws: any, code = 4401, reason = 'Not permitted') {
118
120
 
119
121
  /** Is this account still allowed this document, and with which access? */
120
122
  async function recheck(ctx: CollabContext): Promise<'write' | 'read' | null> {
121
- const u = await activeAccountOf({ cms: { uid: ctx.user.id, sv: ctx.sv } })
123
+ const u = await activeAccount(ctx.user.id, ctx.sv, ctx.iat)
122
124
  if (!u || u.role !== ctx.user.role) return null
123
125
  const target = parseCollabName(collabName(ctx.target.entityName, ctx.target.id, ctx.target.locale))
124
126
  return target ? collabAccess({ ...ctx.user, role: u.role }, target) : null
@@ -236,7 +238,7 @@ async function startCollabServer(): Promise<Hocuspocus> {
236
238
  // Only the canonical spelling of a name.
237
239
  if (!target || target.name !== documentName) throw new Error('Unknown document')
238
240
  // The account as it is now (disabled, demoted, signed out everywhere?).
239
- const u = await activeAccountOf({ cms: { uid: socketUser.id, sv: context.sv } })
241
+ const u = await activeAccount(socketUser.id, context.sv, context.iat)
240
242
  if (!u) throw new Error('Session no longer valid')
241
243
  const user: CmsUser = { ...socketUser, role: u.role, name: u.name || socketUser.name }
242
244
  const access = await collabAccess(user, target)
@@ -265,7 +267,7 @@ async function startCollabServer(): Promise<Hocuspocus> {
265
267
  docs.add(documentName)
266
268
  docsBySocket.set(socketId, docs)
267
269
  if (access === 'read') connectionConfig.readOnly = true
268
- return { user, displayName: displayName(u.name, u.email), sv: context.sv, epoch: row.epoch, access, checkedAt: Date.now(), target: { entityName: target.entity.name, id: target.id, locale: target.locale } } satisfies CollabContext
270
+ return { user, displayName: displayName(u.name, u.email), sv: context.sv, iat: context.iat, epoch: row.epoch, access, checkedAt: Date.now(), target: { entityName: target.entity.name, id: target.id, locale: target.locale } } satisfies CollabContext
269
271
  },
270
272
 
271
273
  async onLoadDocument({ documentName, document, context }) {
@@ -44,6 +44,8 @@ interface LocalPeer {
44
44
  socket: LiveSocket
45
45
  user: CmsUser
46
46
  sv: number
47
+ /** When the session this socket was admitted with was signed in (it ends with that session). */
48
+ iat: number
47
49
  topics: Map<string, Watch>
48
50
  /** Messages are handled one at a time, in order. */
49
51
  queue: Promise<void>
@@ -111,7 +113,7 @@ export function stopLive(): void {
111
113
 
112
114
  // ── connections ──
113
115
 
114
- export function liveOpen(socket: LiveSocket, user: CmsUser, sv: number): void {
116
+ export function liveOpen(socket: LiveSocket, user: CmsUser, sv: number, iat: number): void {
115
117
  const mine = [...local.values()].filter((p) => p.user.id === user.id)
116
118
  if (mine.length >= MAX_SOCKETS_PER_USER) {
117
119
  // Too many tabs: the oldest one gives way.
@@ -120,7 +122,7 @@ export function liveOpen(socket: LiveSocket, user: CmsUser, sv: number): void {
120
122
  liveClose(oldest.socket)
121
123
  }
122
124
  const now = Date.now()
123
- local.set(socket.id, { socket, user, sv, topics: new Map(), queue: Promise.resolve(), openedAt: now, seenAt: now, burst: { at: now, n: 0 } })
125
+ local.set(socket.id, { socket, user, sv, iat, topics: new Map(), queue: Promise.resolve(), openedAt: now, seenAt: now, burst: { at: now, n: 0 } })
124
126
  start()
125
127
  }
126
128
 
@@ -332,8 +334,9 @@ async function recheckAccounts(): Promise<void> {
332
334
  const byId = new Map(rows.map((r) => [r.id, r]))
333
335
  for (const p of [...local.values()]) {
334
336
  const u = byId.get(p.user.id)
335
- // A changed role reconnects too, so watches are re-authorised under the new one.
336
- if (!u || u.status !== 'active' || u.sv !== p.sv || u.role !== p.user.role) {
337
+ // A changed role reconnects too, so watches are re-authorised under the new one; a
338
+ // session past its 14 days (from its sign-in) ends here as it does over HTTP.
339
+ if (!u || u.status !== 'active' || u.sv !== p.sv || u.role !== p.user.role || !signedInRecently({ cms: { iat: p.iat } })) {
337
340
  p.socket.close(4401, 'Session no longer valid')
338
341
  liveClose(p.socket)
339
342
  }
@@ -15,9 +15,14 @@ export interface CmsUser {
15
15
  * middleware (server/middleware/cms-session.ts) sets it from the session after
16
16
  * checking the account in the database; with `cms.auth.mode: 'external'` the host does.
17
17
  */
18
- /** The name of the session cookie (nuxt-auth-utils: `nuxt-session`, or `runtimeConfig.session.name`). */
18
+ /**
19
+ * The name of the session cookie: nuxt-auth-utils' `nuxt-auth-session`, or
20
+ * `runtimeConfig.session.name` (NUXT_SESSION_NAME). nuxt-auth-utils refuses
21
+ * `nuxt-session` (the cookie of Nuxt's own `useSession()`) and uses its default instead.
22
+ */
19
23
  export function sessionCookieName(): string {
20
- return String((useRuntimeConfig().session as any)?.name || 'nuxt-session')
24
+ const name = String((useRuntimeConfig().session as any)?.name || 'nuxt-auth-session')
25
+ return name === 'nuxt-session' ? 'nuxt-auth-session' : name
21
26
  }
22
27
 
23
28
  /**
@@ -45,33 +50,61 @@ export function requireCmsUser(event: any): CmsUser {
45
50
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
46
51
 
47
52
  /**
48
- * The account a sealed session belongs to, if it may still be used: it exists, is
49
- * active, and the session was issued for its current session version (a password
50
- * change or "sign out everywhere" bumps it). Null otherwise.
53
+ * Was the session signed in less than `runtimeConfig.session.maxAge` ago (NUXT_SESSION_MAX_AGE,
54
+ * seconds; 14 days by default)? From `cms.iat`, the time of the sign-in that a session written
55
+ * again keeps (cmsAuth.ts, startCmsSession). A session without it was not made by this version:
56
+ * not in time. Without a maxAge only that is checked.
57
+ */
58
+ export function signedInRecently(session: any, now = Date.now()): boolean {
59
+ const iat = session?.cms?.iat
60
+ if (typeof iat !== 'number' || !Number.isFinite(iat) || iat > now + 60_000) return false
61
+ const maxAge = Number((useRuntimeConfig().session as any)?.maxAge)
62
+ return !(maxAge > 0) || now - iat < maxAge * 1000
63
+ }
64
+
65
+ /**
66
+ * The account a sealed session belongs to, if it may still be used: signed in less than
67
+ * `maxAge` ago (signedInRecently), and the account exists, is active, and the session was
68
+ * issued for its current session version (a password change or "sign out everywhere"
69
+ * bumps it). Null otherwise.
51
70
  */
52
71
  export async function activeAccountOf(session: any): Promise<any | null> {
53
- const id = session?.cms?.uid
72
+ return activeAccount(session?.cms?.uid, session?.cms?.sv, session?.cms?.iat)
73
+ }
74
+
75
+ /**
76
+ * The account, if the session it was admitted with was signed in at `iat` less than
77
+ * `maxAge` ago, and the account is active and still at session version `sv`: for a socket
78
+ * admitted earlier with a session (activeAccountOf), checked again while it stays open, so
79
+ * an open socket ends with its session too instead of outliving the 14 days.
80
+ */
81
+ export async function activeAccount(id: unknown, sv: unknown, iat: unknown): Promise<any | null> {
82
+ if (!signedInRecently({ cms: { iat } })) return null
54
83
  if (typeof id !== 'string' || !UUID.test(id)) return null
55
84
  const { db, reg } = useCms()
56
85
  const [u] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.id, id))
57
- if (!u || u.status !== 'active' || u.sessionVersion !== session?.cms?.sv) return null
86
+ if (!u || u.status !== 'active' || u.sessionVersion !== sv) return null
58
87
  return u
59
88
  }
60
89
 
61
90
  /**
62
91
  * Admit a WebSocket upgrade for the admin (realtime, shared editing): it must come
63
92
  * from this site's own pages and carry a valid built-in session for an active
64
- * account. Puts the account on `request.context` (cmsUser, cmsSessionVersion), which
65
- * the socket's peer then carries. Throws a Response to refuse.
93
+ * account. Puts the account on `request.context` (cmsUser, cmsSessionVersion and
94
+ * cmsSignedInAt, the session's sign-in time), which the socket's peer then carries.
95
+ * Throws a Response to refuse.
66
96
  */
67
97
  export async function admitAdminSocket(request: any): Promise<void> {
68
98
  if (cmsAuthMode() !== 'builtin') throw new Response('Needs the built-in sign-in', { status: 404 })
69
99
  if (!sameOrigin(request)) throw new Response('Forbidden', { status: 403 })
100
+ // Only read: in a WebSocket handler nuxt-auth-utils cannot write the session (there is no
101
+ // response to carry the cookie), so a stale cookie is refused here, not cleared.
70
102
  const session: any = hasSessionCookie(request) ? await getUserSession(request).catch(() => null) : null
71
103
  const u = await activeAccountOf(session)
72
104
  if (!u) throw new Response('Unauthorized', { status: 401 })
73
105
  request.context.cmsUser = { id: u.id, email: u.email, name: u.name || u.email, role: u.role, locale: u.locale }
74
106
  request.context.cmsSessionVersion = u.sessionVersion
107
+ request.context.cmsSignedInAt = session.cms.iat
75
108
  }
76
109
 
77
110
  /**
@@ -0,0 +1,88 @@
1
+ /**
2
+ * NUXT_SESSION_PASSWORD standing in for NUXT_APP_SECRET (deprecated, removed in 0.5).
3
+ *
4
+ * nuxt-auth-utils 0.6 seals the sign-in cookie with a key Nuxt derives from its app secret
5
+ * (`NUXT_APP_SECRET`) and no longer reads `NUXT_SESSION_PASSWORD`. So that a site deployed
6
+ * with only the old variable keeps starting (and signing people in) after the update, the
7
+ * server takes the session password as the app secret when no app secret is set at all.
8
+ * A set app secret always wins, whatever else uses it (signed image URLs…).
9
+ *
10
+ * Nitro reads the environment into its runtime config once, when its config module is
11
+ * evaluated, and freezes it; a Nitro plugin runs too late to change it. So the copy is put
12
+ * at the top of that module in the server bundle (module.ts), before the environment is
13
+ * read. The start-up check (server/plugins/cms-0-config-check.ts) then warns that the old
14
+ * name is deprecated, or refuses to start when there is no secret at all.
15
+ *
16
+ * Build-time only; kept apart from module.ts so it can be tested on its own.
17
+ */
18
+
19
+ /** Where the start-up check finds the name of what stood in for the app secret (the same string there). */
20
+ export const APP_SECRET_FROM = 'tinyzoo.appSecretFrom'
21
+
22
+ /** The runtime config path a 0.3 site may have set the password at in nuxt.config (the same string in the start-up check). */
23
+ export const CONFIG_SESSION_PASSWORD = 'runtimeConfig.session.password'
24
+
25
+ /** Nitro's runtime config module, the one the fallback is put at the top of. */
26
+ export const NITRO_CONFIG_MODULE = /[\\/]nitropack[\\/]dist[\\/]runtime[\\/]internal[\\/]config\.mjs$/
27
+
28
+ export interface AppSecretPlan {
29
+ /** Put the fallback into the server bundle. */
30
+ install: boolean
31
+ /** `runtimeConfig.session.password` (nuxt.config) was taken as the build's app secret. */
32
+ fromConfig: boolean
33
+ envPrefix: string
34
+ }
35
+
36
+ /**
37
+ * What to do for a build, from Nitro's runtime config. Mutates `runtimeConfig`: when a site
38
+ * set `runtimeConfig.session.password` in its nuxt.config (tinyzoo 0.3 accepted it) and no
39
+ * app secret, that value becomes the build's `appSecret`. It is in the built runtime config
40
+ * already (as `session.password`), so nothing new is written into the bundle, and a
41
+ * NUXT_APP_SECRET set at runtime still wins over it.
42
+ */
43
+ export function planAppSecretFallback(runtimeConfig: Record<string, any>): AppSecretPlan {
44
+ const envPrefix = String(runtimeConfig.nitro?.envPrefix || 'NUXT_')
45
+ // Set in nuxt.config, or generated for `nuxt dev`: nothing to stand in for.
46
+ if (runtimeConfig.appSecret) return { install: false, fromConfig: false, envPrefix }
47
+ const password = runtimeConfig.session?.password
48
+ const fromConfig = typeof password === 'string' && password.length > 0
49
+ if (fromConfig) runtimeConfig.appSecret = password
50
+ return { install: true, fromConfig, envPrefix }
51
+ }
52
+
53
+ /**
54
+ * The lines put at the top of Nitro's config module. When neither `<prefix>APP_SECRET` nor
55
+ * `NITRO_APP_SECRET` is set, `<prefix>SESSION_PASSWORD` (or `NITRO_SESSION_PASSWORD`) is
56
+ * copied to the app secret variable Nitro reads first, and the name of what stood in is
57
+ * left for the start-up check. Carries no secret.
58
+ */
59
+ export function appSecretFallbackCode(envPrefix: string, fromConfig: boolean): string {
60
+ const prefix = JSON.stringify(envPrefix)
61
+ return `;(() => {
62
+ const env = globalThis.process?.env
63
+ if (!env || env[${prefix} + 'APP_SECRET'] || env.NITRO_APP_SECRET) return
64
+ const from = [${prefix} + 'SESSION_PASSWORD', 'NITRO_SESSION_PASSWORD'].find((name) => env[name])
65
+ const mark = (name) => { globalThis[Symbol.for(${JSON.stringify(APP_SECRET_FROM)})] = name }
66
+ if (!from) {
67
+ ${fromConfig ? `mark(${JSON.stringify(CONFIG_SESSION_PASSWORD)})` : ''}
68
+ return
69
+ }
70
+ // Nitro reads NITRO_APP_SECRET first, even when it is empty.
71
+ env[env.NITRO_APP_SECRET !== undefined ? 'NITRO_APP_SECRET' : ${prefix} + 'APP_SECRET'] = env[from]
72
+ mark(from)
73
+ })();
74
+ `
75
+ }
76
+
77
+ /**
78
+ * The source map of `code + source` when `code` is whole lines put in front: the added lines
79
+ * map to nothing, every line of `source` to itself (line by line, which is all a stack trace
80
+ * needs). Saves a dependency for one prepend.
81
+ */
82
+ export function prependedLinesMap(code: string, source: string, file: string) {
83
+ const added = code.split('\n').length - 1
84
+ const lines = source.split('\n').length
85
+ // Per line: generated column 0, source 0, the next source line (+1, "C"; the first is +0, "A"), column 0.
86
+ const mappings = ';'.repeat(added) + Array.from({ length: lines }, (_, i) => (i ? 'AACA' : 'AAAA')).join(';')
87
+ return { version: 3, file, sources: [file], sourcesContent: [source], names: [], mappings }
88
+ }
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  export { defineEntity, defineSingleton, buildRegistry, propOf, editorLayout, listLayout } from './entity'
3
3
  export type { CmsEntity, CmsRegistry, ContentConfig, PublishConfig, EntityDef, Entity, Junction, Row, Insert, Update, CmsEditorLayout, CmsListLayout, CmsFormSection } from './entity'
4
4
  export { f, snake, camel, pascal, buildColumn, serializeColumn, type CmsGalleryValue, type CmsListValue } from './fields'
5
- export { seo, linkBlock, definePages, defineNavigation, defineRedirects, defineForm, defineFormSettings, FORM_FIELD_TYPES, type FormOptions } from './presets'
5
+ export { seo, linkBlock, definePages, defineNavigation, defineRedirects, FORM_FIELD_TYPES, type FormOptions } from './presets'
6
6
  export { defineBlock, blocksSchema, mediaIdsInBlocks, mediaIdsInFields, blockMediaKeys, BLOCK_FIELD_TYPES, blockVersion, storedBlockVersion, upgradeBlock, upgradeBlocks, upgradeListItems, upgradeStoredRow, logUpgradeFailure, UPGRADE_FAILED_KEY, UNKNOWN_BLOCK_TYPE, type UpgradeIssue, type UpgradeOptions, type BlockDef, type BlockValue, type BlocksValue, type GroupValue, type CmsBlock } from './blocks'
7
7
  export { resolveText, type LocalizedText } from './i18n'
8
8
  export { defineLocales, type LocalesDef } from './locales'
package/src/presets.ts CHANGED
@@ -5,7 +5,6 @@ import { f } from './fields'
5
5
  import type { LocalizedText } from './i18n'
6
6
  import type { PathTemplate } from './paths'
7
7
  import { cmsDeprecated } from './deprecate'
8
- import { defineForm as formsDefineForm, defineFormSettings as formsDefineFormSettings, IMPLICIT_FORMS_REQUIREMENT } from '../forms'
9
8
  import { TREE_DEFAULT_MAX_DEPTH } from './tree'
10
9
 
11
10
  const SEO_GROUP = { en: 'Search & sharing', cs: 'Vyhledávače a sdílení', de: 'Suche & Teilen' }
@@ -195,36 +194,5 @@ export function defineRedirects(opts: { name?: string } = {}) {
195
194
  return e
196
195
  }
197
196
 
198
- // ── forms: moved to the forms plugin (`tinyzoo/forms`); these keep old sites working ──
197
+ // ── forms: in the forms plugin (`tinyzoo/forms`); the field types and options stay importable from here ──
199
198
  export { FORM_FIELD_TYPES, type FormOptions } from '../forms'
200
-
201
- /**
202
- * @deprecated Import `defineForm` from `tinyzoo/forms` and register `formsPlugin()` in
203
- * `export const plugins = [...]`. Still works (it registers the plugin by itself), same
204
- * tables and endpoints. Removed in 0.4.
205
- */
206
- export function defineForm<F extends Record<string, any>>(name: string, opts: import('../forms').FormOptions<F>) {
207
- cmsDeprecated(
208
- 'defineForm',
209
- '`defineForm()` from "tinyzoo" is replaced by `defineForm()` from "tinyzoo/forms" with `export const plugins = [formsPlugin()]` in cms.config.ts.',
210
- { removeIn: '0.4.0' },
211
- )
212
- const e = formsDefineForm(name, opts)
213
- ;(e as any).requiresPlugin = IMPLICIT_FORMS_REQUIREMENT
214
- return e
215
- }
216
-
217
- /**
218
- * @deprecated Import `defineFormSettings` from `tinyzoo/forms` and register `formsPlugin()`.
219
- * Still works (it registers the plugin by itself). Removed in 0.4.
220
- */
221
- export function defineFormSettings(opts: Parameters<typeof formsDefineFormSettings>[0] = {}) {
222
- cmsDeprecated(
223
- 'defineFormSettings',
224
- '`defineFormSettings()` from "tinyzoo" is replaced by `defineFormSettings()` from "tinyzoo/forms" with `export const plugins = [formsPlugin()]` in cms.config.ts.',
225
- { removeIn: '0.4.0' },
226
- )
227
- const e = formsDefineFormSettings(opts)
228
- ;(e as any).requiresPlugin = IMPLICIT_FORMS_REQUIREMENT
229
- return e
230
- }
@@ -1,7 +1,8 @@
1
1
  # Copy to .env for development.
2
2
  DATABASE_URL=postgres://site:site@localhost:5433/site
3
- # At least 32 characters; signs the admin's sessions.
4
- NUXT_SESSION_PASSWORD=change-me-to-a-long-random-string-32-chars-min
3
+ # At least 32 characters (openssl rand -base64 32); the admin's sign-in cookie is sealed with a key derived from it.
4
+ # Production needs one; in development Nuxt makes one when it is not set.
5
+ NUXT_APP_SECRET=change-me-to-a-long-random-string-32-chars-min
5
6
  # The website's address (emails, sitemap). In development it comes from the request.
6
7
  # NUXT_CMS_PUBLIC_URL=https://www.example.cz
7
8
  # Who hears about new form messages when nobody is set in the admin.
@@ -18,8 +18,8 @@
18
18
  "@nuxt/ui": "^4.0.0",
19
19
  "@tinyzoo/client": "workspace:*",
20
20
  "drizzle-orm": "^0.45.4",
21
- "nuxt": "^4.0.0",
22
- "nuxt-auth-utils": "^0.5.29",
21
+ "nuxt": "^4.6.4",
22
+ "nuxt-auth-utils": "^0.6.2",
23
23
  "pg": "^8.16.3",
24
24
  "tailwindcss": "^4.3.1",
25
25
  "tinyzoo": "workspace:*",