@michaelthielemann/kestrel 1.3.0 → 1.4.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/README.md CHANGED
@@ -36,7 +36,7 @@ static host. It is deliberately **not**:
36
36
  ## Features
37
37
 
38
38
  - **Runnable in one command** — `pnpm create kestrel` scaffolds a project that boots with a working
39
- `/admin`, prompting for the admin password and writing its hash; `kestrel init` does the same to an
39
+ `/admin`, asking you to choose the admin password and writing its hash; `kestrel init` does the same to an
40
40
  existing project without clobbering it, and `kestrel doctor` names whatever is still missing.
41
41
  - **Collection-driven** — declare collections + fields in TypeScript; Kestrel derives the SQLite tables, a
42
42
  typed CRUD REST API, and the full admin UI. The schema **migrates itself** (additive in dev; explicit
@@ -66,7 +66,7 @@ pnpm create kestrel my-site
66
66
  cd my-site && pnpm install && pnpm dev
67
67
  ```
68
68
 
69
- It asks for an admin password and writes a project that runs as-is: `nuxt.config.ts` extending the
69
+ It asks you to choose an admin password and writes a project that runs as-is: `nuxt.config.ts` extending the
70
70
  meta-layer, an `app.vue` that renders, a `.env` holding a fresh session secret and the scrypt hash of
71
71
  your password, and one example block. Sign in at <http://localhost:3000/admin>.
72
72
 
@@ -25,6 +25,11 @@ const props = defineProps<{
25
25
  const emit = defineEmits<{ update: [name: string, value: unknown] }>()
26
26
  const { t } = useT()
27
27
 
28
+ // A project with a single layout has nothing to choose, so the control stays out of the pane entirely
29
+ // rather than offering one dead option.
30
+ const layoutOptions = computed(() => layoutSelectOptions(useOfferableLayouts(), t('pageSettings.layoutDefault')))
31
+ const showLayout = computed(() => !!props.pageLike && layoutOptions.value.length > 1)
32
+
28
33
  // Live preview of the slug the server will auto-generate from the title while the field is left blank
29
34
  // (the server slugifies the title on save). Falls back to '/' when there is no title yet.
30
35
  const slugPlaceholder = computed(() => {
@@ -88,6 +93,26 @@ const slugPlaceholder = computed(() => {
88
93
  </template>
89
94
  </UiField>
90
95
 
96
+ <!-- Which layout renders this page (the `layout` system column). Empty = the `default` layout, so an
97
+ unset value keeps rendering exactly as a project without the column. -->
98
+ <UiField
99
+ v-if="showLayout"
100
+ class="page-settings__layout"
101
+ :label="t('pageSettings.layoutLabel')"
102
+ :hint="t('pageSettings.layoutHint')"
103
+ :error="errors.layout || null"
104
+ >
105
+ <template #default="f">
106
+ <UiSelect
107
+ :model-value="(values.layout as string) ?? ''"
108
+ :options="layoutOptions"
109
+ :disabled="disabled"
110
+ v-bind="f"
111
+ @update:model-value="(v) => emit('update', 'layout', v)"
112
+ />
113
+ </template>
114
+ </UiField>
115
+
91
116
  <!-- Page SEO (meta title/description/noindex + Google preview). The `seo` JSON system column. -->
92
117
  <SeoFields
93
118
  v-if="seo"
@@ -135,6 +135,8 @@ export function useEditForm(opts: UseEditFormOptions) {
135
135
  if (blocksEnabled.value) next.content = (source?.content as unknown[]) ?? []
136
136
  // `path` (the page slug) is a pageLike system column, likewise round-tripped explicitly.
137
137
  if (pageLike.value) next.path = (source?.path as string | null | undefined) ?? ''
138
+ // '' is the "no override" form the select binds to.
139
+ if (pageLike.value) next.layout = (source?.layout as string | null | undefined) ?? ''
138
140
  // `seo` is a JSON system column; default to an empty object so the editor can fill it in.
139
141
  if (hasSeo.value) next.seo = (source?.seo as Record<string, unknown> | undefined) ?? {}
140
142
  // `status` is a system column; a new record defaults to 'draft' (unpublished) — matches the DB default.
@@ -261,6 +263,9 @@ export function useEditForm(opts: UseEditFormOptions) {
261
263
  if (blocksEnabled.value) body.content = values.content
262
264
  // Send the slug as the routable path; a blank slug clears the route (stored as null, not "").
263
265
  if (pageLike.value) body.path = (values.path as string) ? values.path : null
266
+ // An unset layout is stored as NULL, never '': the render coalesces NULL to `default`, and a stored ''
267
+ // would be indistinguishable from a name that failed to save.
268
+ if (pageLike.value) body.layout = (values.layout as string) || null
264
269
  if (hasSeo.value) body.seo = values.seo ?? {}
265
270
  if (hasStatus.value) body.status = (values.status as string) ?? 'draft'
266
271
  // A new translatable multi record carries its locale, and links to a translation group when it is
@@ -0,0 +1,5 @@
1
+ import { kestrelLayouts } from '#build/kestrel-layouts.mjs'
2
+
3
+ export function useOfferableLayouts(): string[] {
4
+ return kestrelLayouts
5
+ }
@@ -0,0 +1,38 @@
1
+ /** The admin shell. Never offerable for a public record — a page rendered inside it would carry the
2
+ * admin chrome and its own `useHead`. */
3
+ export const ADMIN_LAYOUT = 'admin'
4
+
5
+ /** Nuxt's resolved `app.layouts` entry (`nuxt.options.app.layouts`, filled before the `app:resolve` hook). */
6
+ export interface ResolvedLayout { name: string, file: string }
7
+
8
+ /**
9
+ * The layout names a page may be assigned, from Nuxt's own resolved layout map. Nuxt has already done the
10
+ * layer-ordered, name-first dedup (a consumer's `default.vue` shadows the engine's), so this only filters
11
+ * and sorts — no directory scan of our own.
12
+ */
13
+ export function offerableLayouts(layouts: Record<string, ResolvedLayout | undefined>): string[] {
14
+ return Object.values(layouts)
15
+ .filter((l): l is ResolvedLayout => !!l && typeof l.file === 'string' && l.file.endsWith('.vue'))
16
+ .map((l) => l.name)
17
+ .filter((name) => name !== ADMIN_LAYOUT)
18
+ .sort()
19
+ }
20
+
21
+ export function renderLayoutRegistry(names: string[]): string {
22
+ return `export const kestrelLayouts = ${JSON.stringify(names)}\n`
23
+ }
24
+
25
+ /**
26
+ * Options for the page-layout select. The fallback is one entry with an EMPTY value — an unset column
27
+ * already renders `default`, so offering `default` as its own value would give the editor two controls for
28
+ * one outcome and pin the row to a name the consumer may later rename.
29
+ */
30
+ export function layoutSelectOptions(names: string[], fallbackLabel: string): { label: string, value: string }[] {
31
+ return [
32
+ { label: fallbackLabel, value: '' },
33
+ ...names.filter((n) => n !== DEFAULT_LAYOUT_NAME).map((n) => ({ label: n, value: n })),
34
+ ]
35
+ }
36
+
37
+ /** Mirrors `DEFAULT_LAYOUT` in the public layer; kept local so this util stays dependency-free. */
38
+ const DEFAULT_LAYOUT_NAME = 'default'
@@ -1,8 +1,9 @@
1
1
  import { existsSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
- import { addComponentsDir, addTypeTemplate, createResolver, defineNuxtModule } from '@nuxt/kit'
3
+ import { addComponentsDir, addTemplate, addTypeTemplate, createResolver, defineNuxtModule } from '@nuxt/kit'
4
4
  import { collectBlockSfcs, collectDefinitions, renderRegistry } from './scan'
5
5
  import { renderBlockRegistry } from './extract-block'
6
+ import { offerableLayouts, renderLayoutRegistry } from '../../app/utils/layouts'
6
7
 
7
8
  export default defineNuxtModule({
8
9
  meta: { name: 'kestrel-auto-discovery' },
@@ -22,6 +23,15 @@ export default defineNuxtModule({
22
23
  if (existsSync(dir)) addComponentsDir({ path: dir, prefix: 'Blocks', global: true, pathPrefix: false })
23
24
  }
24
25
 
26
+ // Layouts need no scan of our own: Nuxt already resolves `app/layouts/*.vue` across the layers with the
27
+ // same name-first, consumer-wins dedup, and fills `app.layouts` just before `app:resolve` — which runs
28
+ // inside `generateApp`, ahead of the templates being written, so the closure below is filled in time.
29
+ let layoutNames: string[] = []
30
+ nuxt.hook('app:resolve', (app) => { layoutNames = offerableLayouts(app.layouts ?? {}) })
31
+ // `write` so the resolved list is inspectable in `.nuxt/` — a virtual-only template makes "which layouts
32
+ // did the build actually find" unanswerable without a debugger.
33
+ addTemplate({ filename: 'kestrel-layouts.mjs', write: true, getContents: () => renderLayoutRegistry(layoutNames) })
34
+
25
35
  nuxt.hook('nitro:config', (nitro) => {
26
36
  nitro.virtual ||= {}
27
37
  // Consumer field types register as a side effect on import, and the schema engine builds a table the
@@ -10,3 +10,6 @@ declare module '#kestrel/schema-tables' {
10
10
  const tables: unknown[]
11
11
  export default tables
12
12
  }
13
+ declare module '#build/kestrel-layouts.mjs' {
14
+ export const kestrelLayouts: string[]
15
+ }
@@ -17,7 +17,7 @@ function reservedColumns(def: CollectionDef): { js: Set<string>; db: Set<string>
17
17
  if (def.translatable) add('locale', 'locale')
18
18
  if (def.mode === 'single') add('singletonKey', 'singleton_key')
19
19
  else if (def.translatable) add('translationGroup', 'translation_group')
20
- if (def.pageLike) add('path', 'path')
20
+ if (def.pageLike) { add('path', 'path'); add('layout', 'layout') }
21
21
  if (def.status) add('status', 'status')
22
22
  if (def.seo) add('seo', 'seo')
23
23
  if (def.blocks?.enabled) add('content', 'content')
@@ -67,7 +67,13 @@ export function buildTable(def: CollectionDef): SQLiteTable {
67
67
  if (def.translatable) cols.locale = text('locale').notNull()
68
68
  if (def.mode === 'single') cols.singletonKey = text('singleton_key').notNull()
69
69
  else if (def.translatable) cols.translationGroup = text('translation_group').notNull()
70
- if (def.pageLike) cols.path = text('path')
70
+ if (def.pageLike) {
71
+ cols.path = text('path')
72
+ // Nullable with no default: an editor's "inherit" must be distinguishable from an explicit `default`,
73
+ // and the render decides the fallback (see resolvePageLayout) so a deleted layout file degrades in one
74
+ // place instead of being frozen into every row.
75
+ cols.layout = text('layout')
76
+ }
71
77
  if (def.status) cols.status = text('status').notNull().default('draft')
72
78
  if (def.seo) cols.seo = text('seo', { mode: 'json' }).$type<SeoMeta>().notNull().default(sql`'{}'`)
73
79
  if (def.blocks?.enabled) cols.content = text('content', { mode: 'json' }).$type<Block[]>().notNull().default(sql`'[]'`)
@@ -1,6 +1,14 @@
1
1
  <script setup lang="ts">
2
+ import type { LayoutKey } from 'nuxt/app'
3
+
4
+ // The record decides its own layout, so route-meta resolution is opted out of and this page renders the
5
+ // `<NuxtLayout>` itself. Side effect worth knowing: the layout becomes a CHILD of the page, so it can read
6
+ // `usePublicPageState()` during SSR — as its parent it rendered before the page had written it.
7
+ definePageMeta({ layout: false })
8
+
2
9
  interface RenderedPage {
3
10
  title?: string
11
+ layout?: string | null
4
12
  seo?: {
5
13
  title?: string
6
14
  description?: string
@@ -36,6 +44,12 @@ const { data: resolved } = await useAsyncData(`page:${locale}:${path}`, () =>
36
44
  }),
37
45
  )
38
46
  const page = computed(() => resolved.value?.page ?? null)
47
+ // `fallback` below only rescues a truthy name that is missing from the layout map, so the empty cases have
48
+ // to be coalesced here — see resolvePageLayout. The cast is the one honest bridge in this file: the stored
49
+ // name is arbitrary editor data, while `NuxtLayout` types `name` as the union of layouts that existed at
50
+ // build time. Narrowing to that union is impossible for a value read from the DB, and `fallback` is exactly
51
+ // the runtime guard for a name outside it.
52
+ const pageLayout = computed(() => resolvePageLayout(page.value?.layout) as LayoutKey)
39
53
 
40
54
  // The layout (language menu & co.) needs the resolved record and its collection; pages and layouts share
41
55
  // no other channel, so mirror the fetch result into the shared state — reactively, so client-side
@@ -113,21 +127,23 @@ useSeoMeta({
113
127
  </script>
114
128
 
115
129
  <template>
116
- <article>
117
- <!-- Only ever shown to an authenticated admin previewing an unpublished page (drafts never resolve
118
- for anonymous visitors or the static render), so it never ships to the public/static site.
119
- Suppressed inside the editor preview iframe the editor's own status ampel covers it. -->
120
- <div v-if="isDraftPreview && !previewActive" class="kestrel-draft-badge" role="status">
121
- <span class="kestrel-draft-badge__dot" aria-hidden="true" />
122
- Draft preview not published
123
- </div>
124
- <!-- Editor preview: the bridge swaps in the editor's live (unsaved) tree over postMessage and makes
125
- blocks selectable; the saved content renders until the first message. Normal path unchanged. -->
126
- <LazyKestrelPreviewBridge v-if="previewActive" :blocks="(page?.content as any[]) ?? []" v-slot="{ blocks }">
127
- <BlockRenderer :blocks="(blocks as any[])" />
128
- </LazyKestrelPreviewBridge>
129
- <BlockRenderer v-else :blocks="(page?.content as any[]) ?? []" />
130
- </article>
130
+ <NuxtLayout :name="pageLayout" fallback="default">
131
+ <article>
132
+ <!-- Only ever shown to an authenticated admin previewing an unpublished page (drafts never resolve
133
+ for anonymous visitors or the static render), so it never ships to the public/static site.
134
+ Suppressed inside the editor preview iframe — the editor's own status ampel covers it. -->
135
+ <div v-if="isDraftPreview && !previewActive" class="kestrel-draft-badge" role="status">
136
+ <span class="kestrel-draft-badge__dot" aria-hidden="true" />
137
+ Draft preview — not published
138
+ </div>
139
+ <!-- Editor preview: the bridge swaps in the editor's live (unsaved) tree over postMessage and makes
140
+ blocks selectable; the saved content renders until the first message. Normal path unchanged. -->
141
+ <LazyKestrelPreviewBridge v-if="previewActive" :blocks="(page?.content as any[]) ?? []" v-slot="{ blocks }">
142
+ <BlockRenderer :blocks="(blocks as any[])" />
143
+ </LazyKestrelPreviewBridge>
144
+ <BlockRenderer v-else :blocks="(page?.content as any[]) ?? []" />
145
+ </article>
146
+ </NuxtLayout>
131
147
  </template>
132
148
 
133
149
  <style scoped>
@@ -0,0 +1,18 @@
1
+ /** The layout every page falls back to. Nuxt's own name for the unnamed layout, and the one the public
2
+ * layer ships (`layers/public/app/layouts/default.vue`), so it is always present. */
3
+ export const DEFAULT_LAYOUT = 'default'
4
+
5
+ /**
6
+ * The layout name to render a page in, from its stored `layout` column.
7
+ *
8
+ * Must never return an empty value. The catch-all declares `definePageMeta({ layout: false })` so the page
9
+ * owns its own `<NuxtLayout>`; that makes `route.meta.layout` the literal `false`, and NuxtLayout resolves
10
+ * `unref(props.name) ?? route.meta.layout ?? …` — `??` keeps `false`, which fails its `hasLayout` check and
11
+ * renders the page with NO layout wrapper. The `fallback` prop does not cover this: it only applies to a
12
+ * truthy name absent from the layout map. Coalescing here is what keeps an unset column rendering the
13
+ * normal site frame.
14
+ */
15
+ export function resolvePageLayout(stored: string | null | undefined): string {
16
+ const name = typeof stored === 'string' ? stored.trim() : ''
17
+ return name || DEFAULT_LAYOUT
18
+ }
@@ -133,6 +133,9 @@ export const de: Catalog = {
133
133
 
134
134
  'pageSettings.slugLabel': 'Slug',
135
135
  'pageSettings.slugHint': 'URL-Pfad, z. B. /about (leer = automatisch aus dem Titel)',
136
+ 'pageSettings.layoutLabel': 'Layout',
137
+ 'pageSettings.layoutHint': 'Mit welchem Layout diese Seite gerendert wird.',
138
+ 'pageSettings.layoutDefault': 'Standard (default)',
136
139
  'pageSettings.statusLabel': 'Status',
137
140
  'pageSettings.statusHint': 'Entwurf bleibt offline; Veröffentlicht rendert die Seite.',
138
141
  'pageSettings.statusDraft': 'Entwurf',
@@ -144,6 +144,9 @@ export const en: Catalog = {
144
144
  // page settings (system fields on pageLike collections)
145
145
  'pageSettings.slugLabel': 'Slug',
146
146
  'pageSettings.slugHint': 'URL path, e.g. /about (blank = auto-generated from the title)',
147
+ 'pageSettings.layoutLabel': 'Layout',
148
+ 'pageSettings.layoutHint': 'Which layout renders this page.',
149
+ 'pageSettings.layoutDefault': 'Standard (default)',
147
150
  'pageSettings.statusLabel': 'Status',
148
151
  'pageSettings.statusHint': 'Draft stays off the live site; Published renders it.',
149
152
  'pageSettings.statusDraft': 'Draft',
package/nuxt.config.ts CHANGED
@@ -83,22 +83,25 @@ export default defineNuxtConfig({
83
83
  vite: {
84
84
  build: { rollupOptions: { onwarn } },
85
85
  optimizeDeps: {
86
- // Nested "kestrel > dep" form: Vite resolves each dep from the `kestrel` PACKAGE's directory
87
- // rather than the (consumer) project root. Under pnpm these are kestrel's transitive deps and
88
- // are NOT hoisted into a consumer's top-level node_modules, so a bare specifier is
89
- // "Unresolvable" from the consumer root. In-repo `kestrel` is not a resolvable package name, so
90
- // Vite's nestedResolveBasedir falls back to the repo root where these deps ARE hoisted same
91
- // result. The runtime `import('@tiptap/...')` still reuses the pre-bundle (tryOptimizedResolve
92
- // matches the "> dep" id + src dir).
86
+ // Nested "<pkg> > dep" form: Vite resolves each dep from THIS package's directory rather than from
87
+ // the consumer's project root. It has to be the published name — under pnpm these are kestrel's
88
+ // transitive deps and are not hoisted into a consumer's top-level node_modules, so resolving from
89
+ // the root finds nothing. An unresolvable prefix is swallowed (`resolvePackageData(…)?.dir ||
90
+ // basedir`), and the entry then degrades to a bare lookup from the root: fine in-repo and for a
91
+ // hoisted npm/yarn consumer, silently unbundled for a pnpm one — which is why a stale prefix shows
92
+ // up only in a consumer's terminal. In-repo the name is likewise unresolvable and that same
93
+ // fallback lands on the repo root, where the deps ARE hoisted. The runtime `import('@tiptap/...')`
94
+ // still reuses the pre-bundle (tryOptimizedResolve matches the "> dep" id + src dir).
95
+ // `test/package.test.ts` pins the prefix to package.json's `name`.
93
96
  include: [
94
- 'kestrel > @internationalized/date',
95
- 'kestrel > @tiptap/extension-highlight',
96
- 'kestrel > @tiptap/extension-subscript',
97
- 'kestrel > @tiptap/extension-superscript',
98
- 'kestrel > @tiptap/extension-text-align',
99
- 'kestrel > @tiptap/starter-kit',
100
- 'kestrel > @tiptap/vue-3',
101
- 'kestrel > reka-ui',
97
+ '@michaelthielemann/kestrel > @internationalized/date',
98
+ '@michaelthielemann/kestrel > @tiptap/extension-highlight',
99
+ '@michaelthielemann/kestrel > @tiptap/extension-subscript',
100
+ '@michaelthielemann/kestrel > @tiptap/extension-superscript',
101
+ '@michaelthielemann/kestrel > @tiptap/extension-text-align',
102
+ '@michaelthielemann/kestrel > @tiptap/starter-kit',
103
+ '@michaelthielemann/kestrel > @tiptap/vue-3',
104
+ '@michaelthielemann/kestrel > reka-ui',
102
105
  ],
103
106
  },
104
107
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@michaelthielemann/kestrel",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "A slim, collection-driven Nuxt 4 CMS meta-layer with a runtime schema engine. Add `extends: ['@michaelthielemann/kestrel']`, define collections, and the database migrates itself.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Michael Thielemann <283621694+MichaelThielemann@users.noreply.github.com>",
@@ -13,11 +13,6 @@ const manifestPath = join(PKG, 'package.json')
13
13
 
14
14
  const clean = () => {
15
15
  for (const entry of GENERATED) rmSync(join(PKG, entry), { recursive: true, force: true })
16
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
17
- if (manifest['//engine']) {
18
- delete manifest['//engine']
19
- writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
20
- }
21
16
  }
22
17
 
23
18
  if (process.argv.includes('--clean')) {
@@ -42,11 +37,13 @@ if (process.argv.includes('--clean')) {
42
37
  if (existsSync(join(ROOT, file))) cpSync(join(ROOT, file), join(PKG, file))
43
38
  }
44
39
 
45
- // Stamped so the scaffolded manifest pins the ranges the engine actually resolves.
46
- manifest['//engine'] = {
40
+ // A generated file, not a key in the committed manifest: `postpack` is not guaranteed to run (a failed
41
+ // publish skips it), and a stamp left behind in package.json would be committed and then silently pin
42
+ // stale ranges. Deleting `lib/` removes this with everything else.
43
+ const stamp = {
47
44
  nuxt: engine.dependencies?.nuxt,
48
45
  typescript: engine.dependencies?.typescript,
49
46
  'vue-tsc': engine.devDependencies?.['vue-tsc'],
50
47
  }
51
- writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
48
+ writeFileSync(join(PKG, 'lib', 'engine-meta.mjs'), `export default ${JSON.stringify(stamp, null, 2)}\n`)
52
49
  }
@@ -1,5 +1,6 @@
1
1
  import { createInterface } from 'node:readline'
2
2
  import { hashPassword } from './lib/password.mjs'
3
+ import { Cancelled, promptPassword } from './lib/cli.mjs'
3
4
 
4
5
  // Not used at runtime: this prints a value an operator pastes into KESTREL_ADMIN_PASSWORD_HASH. Kept as a
5
6
  // standalone entry point because docs/consuming-kestrel.md tells consumers to run it straight out of
@@ -7,7 +8,18 @@ import { hashPassword } from './lib/password.mjs'
7
8
  const arg = process.argv[2]
8
9
  if (arg) {
9
10
  process.stdout.write(hashPassword(arg) + '\n')
11
+ } else if (process.stdin.isTTY) {
12
+ // Only the hash may reach stdout — an operator pipes it straight into a secret store.
13
+ try {
14
+ process.stdout.write(hashPassword(await promptPassword({ output: process.stderr })) + '\n')
15
+ } catch (err) {
16
+ if (!(err instanceof Cancelled)) throw err
17
+ process.stderr.write('cancelled\n')
18
+ process.exitCode = 1
19
+ }
10
20
  } else {
21
+ // `terminal: false` keeps the piped form (`echo pw | node hash-password.mjs`) working; it is only safe
22
+ // because stdin is not a tty here, so there is no line discipline echoing the password onto a screen.
11
23
  const rl = createInterface({ input: process.stdin, terminal: false })
12
24
  process.stderr.write('Enter password, then press Enter:\n')
13
25
  rl.on('line', (line) => {
@@ -2,7 +2,6 @@
2
2
  import { existsSync, mkdirSync, readFileSync } from 'node:fs'
3
3
  import { join, resolve, basename, relative } from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
- import { createInterface } from 'node:readline/promises'
6
5
  import { hashPassword, sessionSecret } from './lib/password.mjs'
7
6
  import { PACKAGE_NAME, diagnoseProject, mergeEnv, mergePackageJson, renderTemplate, targetName, toPackageName } from './lib/scaffold.mjs'
8
7
  import { Cancelled, MIN_PASSWORD_LENGTH, makePaint, out, parseArgs, promptPassword, readIf, readStdin, walk, write } from './lib/cli.mjs'
@@ -71,15 +70,12 @@ async function init(positional, flags) {
71
70
  out()
72
71
 
73
72
  if (password === undefined && !flags.yes && process.stdin.isTTY) {
74
- const rl = createInterface({ input: process.stdin, output: process.stdout })
75
73
  try {
76
- password = await promptPassword(rl, { warn: (m) => out(yellow(m)) })
74
+ password = await promptPassword({ warn: (m) => out(yellow(m)), note: (m) => out(dim(m)) })
77
75
  } catch (err) {
78
- rl.close()
79
76
  if (err instanceof Cancelled) fail('cancelled')
80
77
  throw err
81
78
  }
82
- rl.close()
83
79
  out()
84
80
  }
85
81
 
@@ -170,15 +166,14 @@ async function hashPasswordCommand(positional) {
170
166
  let password = positional[0]
171
167
  if (password === undefined) {
172
168
  if (process.stdin.isTTY) {
173
- const rl = createInterface({ input: process.stdin, output: process.stdout })
169
+ // Only the hash may reach stdout — an operator redirects it straight into a secret store.
170
+ const ask = (m) => process.stderr.write(`${m}\n`)
174
171
  try {
175
- password = await promptPassword(rl, { warn: (m) => out(yellow(m)) })
172
+ password = await promptPassword({ output: process.stderr, warn: (m) => ask(yellow(m)), note: (m) => ask(dim(m)) })
176
173
  } catch (err) {
177
- rl.close()
178
174
  if (err instanceof Cancelled) fail('cancelled')
179
175
  throw err
180
176
  }
181
- rl.close()
182
177
  } else password = await readStdin()
183
178
  }
184
179
  if (!password) fail('no password given')
@@ -1,5 +1,6 @@
1
1
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, chmodSync } from 'node:fs'
2
2
  import { dirname, join, relative } from 'node:path'
3
+ import { createInterface } from 'node:readline/promises'
3
4
 
4
5
  export const MIN_PASSWORD_LENGTH = 8
5
6
 
@@ -65,44 +66,58 @@ export function walk(dir, base = dir) {
65
66
  return found
66
67
  }
67
68
 
68
- /**
69
- * Reads a line with the echo suppressed. readline echoes before we see the data event, so the fix is to
70
- * repaint the prompt over whatever was written — unconditionally, because a pasted secret arrives as one
71
- * chunk that ends in a newline and would otherwise be left on screen and in the scrollback.
72
- */
73
- async function askHidden(rl, question) {
74
- const repaint = () => process.stdout.write(`\u001b[2K\u001b[200D${question}`)
75
- process.stdin.on('data', repaint)
69
+ /** Reads a line the interface is configured never to echo, so the prompt is ours to draw and to close. */
70
+ async function askHidden(rl, question, write) {
71
+ write(question)
76
72
  try {
77
- return (await rl.question(question)).trim()
73
+ return (await rl.question('')).trim()
78
74
  } finally {
79
- process.stdin.off('data', repaint)
80
- repaint()
81
- process.stdout.write('\n')
75
+ write('\n')
82
76
  }
83
77
  }
84
78
 
85
79
  export class Cancelled extends Error {}
86
80
 
87
- /** Throws `Cancelled` on Ctrl-C / Ctrl-D so a caller can exit cleanly instead of on an AbortError stack. */
88
- export async function promptPassword(rl, { warn = out } = {}) {
89
- for (;;) {
90
- let first
91
- try {
92
- first = await askHidden(rl, 'Admin password: ')
93
- if (first.length < MIN_PASSWORD_LENGTH) {
94
- warn(` at least ${MIN_PASSWORD_LENGTH} characters, please`)
95
- continue
96
- }
97
- if (first !== (await askHidden(rl, 'Repeat password: '))) {
98
- warn(' the two entries differ — try again')
99
- continue
81
+ /**
82
+ * Owns its readline interface, because the two options that keep the secret off the screen can only be
83
+ * set at construction: `output: null` makes readline write nothing at all, and `terminal: true` still
84
+ * gives it the keypress handling (backspace, Ctrl-C, Ctrl-D) that would otherwise fall to the tty's own
85
+ * echoing line discipline. Erasing readline's echo afterwards cannot match that — a pasted secret arrives
86
+ * as one chunk that is echoed AND newlined in a single write, stranding the cleartext on a line no
87
+ * repaint can still reach, and a redirected stdout leaves `terminal` false with nothing to suppress.
88
+ *
89
+ * Throws `Cancelled` on Ctrl-C / Ctrl-D so a caller can exit cleanly instead of on an AbortError stack.
90
+ */
91
+ export async function promptPassword({
92
+ input = process.stdin,
93
+ output = process.stdout,
94
+ warn = (m) => output.write(`${m}\n`),
95
+ note = (m) => output.write(`${m}\n`),
96
+ } = {}) {
97
+ const draw = (s) => output.write(s)
98
+ const rl = createInterface({ input, output: null, terminal: true })
99
+ note(`Choose a password for /admin — at least ${MIN_PASSWORD_LENGTH} characters, kept only as a scrypt hash.`)
100
+ try {
101
+ for (;;) {
102
+ let first
103
+ try {
104
+ first = await askHidden(rl, 'New admin password: ', draw)
105
+ if (first.length < MIN_PASSWORD_LENGTH) {
106
+ warn(` too short — at least ${MIN_PASSWORD_LENGTH} characters`)
107
+ continue
108
+ }
109
+ if (first !== (await askHidden(rl, 'Repeat password: ', draw))) {
110
+ warn(' the two entries differ — try again')
111
+ continue
112
+ }
113
+ } catch (err) {
114
+ throw err?.code === 'ABORT_ERR' ? new Cancelled() : err
100
115
  }
101
- } catch (err) {
102
- throw err?.code === 'ABORT_ERR' ? new Cancelled() : err
116
+ if (first === undefined) throw new Cancelled()
117
+ return first
103
118
  }
104
- if (first === undefined) throw new Cancelled()
105
- return first
119
+ } finally {
120
+ rl.close()
106
121
  }
107
122
  }
108
123
 
@@ -8,7 +8,7 @@ pnpm install
8
8
  pnpm dev
9
9
  ```
10
10
 
11
- Admin: <http://localhost:3000/admin> — sign in with the password you chose during `kestrel init`.
11
+ Admin: <http://localhost:3000/admin> — sign in with the password you chose while scaffolding.
12
12
  Forgot it? `pnpm hash-password` prints a fresh hash for `KESTREL_ADMIN_PASSWORD_HASH` in `.env`.
13
13
 
14
14
  ## What is here