@ingram-tech/nk-dev 0.24.1 → 0.25.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/guide.md CHANGED
@@ -102,10 +102,16 @@ internal plumbing — forms included — under `/api/`.
102
102
  installed in PGlite automatically and in prod by one custom migration). So no
103
103
  `ids.x.decode(param)` before a query and no `ids.x.encode(row.id)` after one
104
104
  — `nextkit/no-id-codec-in-app-code` flags both; validate input with
105
- `ids.x.is(param)` instead. Session ids come in the same form from
106
- `createAuthHelpers(auth, { ids })` (and `backendJwtOptions({ ids })`), and
107
- `withRls*` decode a public `sub` before it reaches `auth.uid()`. At the
108
- shell, `bunx id758 decode inv_…`.
105
+ `ids.x.is(param)` instead. At the shell, `bunx id758 decode inv_…`.
106
+ - **Users and organizations are `usr_` / `org_` fleet-wide.** The prefixes are
107
+ `SHARED_ID_PREFIXES` from `@ingram-tech/nk-db/id`, and `createIdRegistry`
108
+ throws on any other prefix for `user` or `organization`, so a session or token
109
+ means the same thing in every app. Opt in with `createAuthHelpers(auth, { ids
110
+ })` (server reads), the `publicSessionIds({ ids })` Better Auth plugin (the
111
+ browser's `useSession()`), and `backendJwtOptions({ ids })` (bearer `sub`).
112
+ `withRls*` and `verifyBackendJwt` accept a raw-uuid or public `sub`, so tokens
113
+ issued before the switch keep working. A raw-SQL-heavy app may keep raw uuids
114
+ internally and skin only at its edges; the wire is the same.
109
115
  - **Migrations don't auto-apply on deploy.** Code ships ahead of the prod schema
110
116
  unless someone runs the migration against the target DB — a page that reads a
111
117
  newly-added column 500s in prod until then. Apply migrations with
@@ -180,14 +186,14 @@ tool instead). One-off single-file edits: just edit the file.
180
186
  nk-auth's migration chain, and the order on every site is bump, `db:migrate`
181
187
  against the target database, then deploy. `createAuthHelpers` refuses to
182
188
  serve a session while the recorded chain lags the installed package.
183
- Presets you spread into your own `betterAuth()` (mounts at `/auth` via `authBasePath`; org / JWT / passkey / pool / client helpers). Don't hand-roll session reads or auth middleware — bind `createAuthHelpers` (`getUser` / `requireUser` / `redirectIfAuthenticated`, from `@ingram-tech/nk-auth/server`) and gate routes with the loop-safe `createAuthMiddleware`. A site with its own proxy sets the `next`-preserving header with `withAuthPathHeader(request, requestHeaders)` instead (and `clearStaleSession` for the stale-cookie handshake); a site wrapping the guards redirects to `await signInTarget()` rather than the bare sign-in path
189
+ Presets you spread into your own `betterAuth()` (mounts at `/auth` via `authBasePath`; org / JWT / passkey / pool / client helpers). Don't hand-roll session reads or auth middleware — bind `createAuthHelpers` (`getUser` / `requireUser` / `redirectIfAuthenticated`, from `@ingram-tech/nk-auth/server`) and gate routes with the loop-safe `createAuthMiddleware`. A site with its own proxy sets the `next`-preserving header with `withAuthPathHeader(request, requestHeaders)` instead (and `clearStaleSession` for the stale-cookie handshake); a site wrapping the guards redirects to `await signInTarget()` rather than the bare sign-in path. Sign-in and security pages follow its "Password managers, passkeys and 2FA" section: `usePasskeyAutofill` + `PASSKEY_AUTOFILL_EMAIL`, `totpEnrollment` for 2FA setup, and the `/.well-known` handlers
184
190
  - `@ingram-tech/nk-db` — Postgres data layer: `createPool` (one TLS-aware pool) + `createQueries` (raw SQL) + `createDb` (Drizzle), the PGlite dev/test harness at `@ingram-tech/nk-db/pglite`, the prefixed-id codec (the standalone `id758` package) at `@ingram-tech/nk-db/id`, and the drift-aware migration runner at `@ingram-tech/nk-db/migrate`
185
191
  - `@ingram-tech/nk-api` — the standard HTTP API seam (Hono + `@hono/zod-openapi`): one `{ error, details? }` envelope, `createApiApp` / `createRouter`, auth + multi-tenant resource-scope middleware, pagination helpers, and an emitted OpenAPI/Swagger doc. Reach for it instead of hand-rolling route handlers
186
192
  - `@ingram-tech/nk-billing` — Stripe primitives: subscriptions, a Stripe-side wallet, and an optional Postgres credit ledger behind the `/credits` subpath. Prices resolve at runtime by Stripe `lookup_key` — **never hardcode a price id**, so test and live share one code path
187
193
  - `@ingram-tech/nk-forms` — the public contact/signup submission pipeline: `createFormsHandler` + `defineForm` (one registry at `/internal/forms/[form]`; each entry runs rate-limit → bot gate → validate → escaped-email deliver → uniform 200), `renderNotificationEmail`, and `useFormSubmit(formEndpoint(name))` / `HoneypotInput` (`/react`); `handleFormSubmission` / `mintFormToken` for a standalone route. It owns the invisible bot-protection layers too (honeypot + signed timing token + Vercel BotID); `verifyHuman` / `checkBot` are exported from the root for non-form endpoints
188
194
  - `@ingram-tech/nk-i18n` — type-safe, English-as-key i18n: the English source text *is* the key (no `en.json`), ICU MessageFormat, colocated JSON catalogs, plus **locale URL routing** (`defineLocaleRouting` + a fixed URL→account→cookie→`Accept-Language`→country precedence, wired to Next at `/next`). A URL that names a locale must serve it with a 200 — never redirect `?hl=fr` away, or every hreflang annotation on the site points at a URL that doesn't serve the language it claims. See `docs/i18n-routing.md`
189
195
  - `@ingram-tech/nk-marketing` — Postgres-backed marketing & lifecycle email: contacts + consent, newsletter broadcast audiences, and idempotent triggered campaigns, with RFC 8058 one-click unsubscribe
190
- - `@ingram-tech/nk-seo` — SEO toolkit: metadata factory, JSON-LD builders, sitemap/robots routes, hreflang + canonical links, and an OG image template
196
+ - `@ingram-tech/nk-seo` — SEO toolkit: metadata factory, JSON-LD builders, sitemap/robots/manifest routes, hreflang + canonical links, and an OG image template. Icons are files in `src/app` (`icon.svg`, a real `favicon.ico`, `apple-icon.png`) plus `createManifest`, never a `metadata.icons` block; `nk doctor` checks the set
191
197
  - `@ingram-tech/nk-blog` — file-indexed blog engine: frontmatter contract, limited-MDX rendering with a component vocabulary, RSS, blog SEO, GitHub publishing
192
198
  - `@ingram-tech/nk-dev` — the whole dev toolchain in one devDependency: the `nk` command (`nk dev` boots local PGlite via `@ingram-tech/nk-db` if installed, then Next; plus `nk format` / `lint` / `knip` / `check` / `type-check` / `test` / `build`), the shared oxlint + oxfmt / TypeScript / Vitest config, knip, the oxfmt format-on-commit hook, and this guide. `nk check` runs every fast checker (oxlint, oxfmt, knip) in one gate; `nk doctor --fix` reconciles a site back to the canonical toolchain. `nk init` scaffolds a site to use it all.
193
199
 
package/lib/doctor.js CHANGED
@@ -6,6 +6,7 @@ import { authNextFindings, authRenewalFindings } from "./auth-next.js";
6
6
  import { authShadowFindings } from "./auth-shadow.js";
7
7
  import { authVersionFindings } from "./auth-version.js";
8
8
  import { ogImageFindings } from "./og-image.js";
9
+ import { siteIconFindings } from "./site-icons.js";
9
10
  import { SUPERSEDED_DEPS } from "./drift.js";
10
11
  import {
11
12
  SEAL_FILE,
@@ -415,6 +416,10 @@ export function findings(cwd) {
415
416
  // 15. Routes live in src/app/, never a root app/.
416
417
  out.push(...appDirFindings(cwd, pkg));
417
418
 
419
+ // 16. The icon set: a real favicon.ico, an apple-icon, a manifest, and no
420
+ // hand-written `metadata.icons` duplicating the file conventions.
421
+ out.push(...siteIconFindings(cwd, pkg));
422
+
418
423
  return out;
419
424
  }
420
425
 
@@ -0,0 +1,100 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+
4
+ // The icon set a site needs is small and fixed (favicon.ico, icon.svg,
5
+ // apple-icon, a manifest), and Next serves each from a file convention in
6
+ // src/app. What goes wrong is silent: a zero-byte favicon.ico serves a 200 with
7
+ // nothing in it for a year, a missing apple-icon makes iOS screenshot the page
8
+ // for a home-screen tile, and a hand-written `metadata.icons` block next to the
9
+ // files emits every tag twice. None of that fails a build, so doctor checks it.
10
+
11
+ const ICO_MAGIC = Buffer.from([0, 0, 1, 0]);
12
+ const APPLE_ICON = /^apple-icon\d*\.(png|jpe?g|tsx|jsx|ts|js)$/;
13
+ const APP_ICON = /^(favicon\.ico|icon\d*\.(ico|png|jpe?g|svg|tsx|jsx|ts|js))$/;
14
+ const MANIFEST = /^manifest\.(ts|js|json|webmanifest)$/;
15
+ const ICONS_KEY = /\bicons\s*:/;
16
+
17
+ const dependsOnNext = (pkg) =>
18
+ Boolean(pkg.dependencies?.next ?? pkg.devDependencies?.next);
19
+
20
+ const listDir = (dir) => {
21
+ try {
22
+ return readdirSync(dir);
23
+ } catch {
24
+ return [];
25
+ }
26
+ };
27
+
28
+ /** Whether `path` holds an ICO file: the 4-byte header, not just the name. */
29
+ function isIco(path) {
30
+ try {
31
+ if (statSync(path).size < 6) return false;
32
+ return readFileSync(path).subarray(0, 4).equals(ICO_MAGIC);
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /** Findings for a site's icon set. Silent unless it is a Next site with src/app. */
39
+ export function siteIconFindings(cwd, pkg) {
40
+ const appDir = resolve(cwd, "src/app");
41
+ if (!dependsOnNext(pkg) || !existsSync(appDir)) return [];
42
+ const app = listDir(appDir);
43
+ const pub = listDir(resolve(cwd, "public"));
44
+ const out = [];
45
+
46
+ const favicon = ["src/app", "public"]
47
+ .map((dir) => `${dir}/favicon.ico`)
48
+ .find((rel) => existsSync(resolve(cwd, rel)));
49
+ if (!favicon) {
50
+ out.push({
51
+ id: "icons:favicon-missing",
52
+ level: "warn",
53
+ message:
54
+ 'no `favicon.ico`. Browsers, crawlers and feed readers request `/favicon.ico` whatever the `<link>` tags say. Add a 16/32/48 px ICO at `src/app/favicon.ico` (see the nk-seo README, "Site icons").',
55
+ });
56
+ } else if (!isIco(resolve(cwd, favicon))) {
57
+ out.push({
58
+ id: "icons:favicon-invalid",
59
+ level: "error",
60
+ message: `\`${favicon}\` is empty or not an ICO file, so every request for \`/favicon.ico\` gets a broken icon. Regenerate it from \`icon.svg\` (see the nk-seo README, "Site icons").`,
61
+ });
62
+ }
63
+
64
+ if (
65
+ !app.some((name) => APPLE_ICON.test(name)) &&
66
+ !pub.includes("apple-touch-icon.png")
67
+ ) {
68
+ out.push({
69
+ id: "icons:apple-icon-missing",
70
+ level: "warn",
71
+ message:
72
+ "no `src/app/apple-icon.png`. iOS uses a screenshot of the page for home-screen and favourites tiles, and password managers fall back to a letter. Add a 180×180 opaque PNG.",
73
+ });
74
+ }
75
+
76
+ if (!app.some((name) => MANIFEST.test(name))) {
77
+ out.push({
78
+ id: "icons:manifest-missing",
79
+ level: "warn",
80
+ message:
81
+ 'no `src/app/manifest.ts`. Android and Chrome have no icon for "Add to home screen". Export nk-seo\'s `createManifest` from it.',
82
+ });
83
+ }
84
+
85
+ const layout = ["layout.tsx", "layout.jsx", "layout.ts", "layout.js"].find((name) =>
86
+ app.includes(name),
87
+ );
88
+ if (layout && app.some((name) => APP_ICON.test(name))) {
89
+ const src = readFileSync(resolve(appDir, layout), "utf8");
90
+ if (ICONS_KEY.test(src)) {
91
+ out.push({
92
+ id: "icons:metadata-duplicates-files",
93
+ level: "warn",
94
+ message: `\`src/app/${layout}\` declares \`metadata.icons\` while icon files sit in \`src/app\`. Next already emits tags for the files, so the page carries both sets. Delete the \`icons\` block and let the file conventions speak.`,
95
+ });
96
+ }
97
+ }
98
+
99
+ return out;
100
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ingram-tech/nk-dev",
3
- "version": "0.24.1",
3
+ "version": "0.25.0",
4
4
  "description": "The nextkit dev toolchain in one package: the `nk` CLI plus shared oxlint/oxfmt, TypeScript, and Vitest config, the format-on-commit hook, and the AI agent guide. `nk init` scaffolds a site to use it.",
5
5
  "license": "MIT",
6
6
  "type": "module",