create-tigra 4.0.0 → 4.1.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/CHANGELOG.md +178 -0
- package/README.md +236 -82
- package/bin/create-tigra.js +74 -1
- package/lib/patchers/diagnostics.patcher.js +149 -0
- package/lib/patchers/metrics.patcher.js +145 -0
- package/modules/diagnostics/diagnostics.md +65 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/migration.sql +43 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +107 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +69 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +17 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- package/modules/metrics/client/WebVitalsReporter.tsx +35 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +65 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +75 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +130 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +46 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +100 -0
- package/package.json +3 -2
- package/template/AGENTS.md +17 -10
- package/template/README.md +79 -0
- package/template/client/README.md +92 -21
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -2
- package/template/client/src/lib/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -0
- package/template/server/README.md +108 -0
- package/template/server/docs/logging.md +16 -2
- package/template/server/docs/testing.md +20 -2
|
@@ -4,6 +4,7 @@ import type React from 'react';
|
|
|
4
4
|
import { Inter, JetBrains_Mono } from 'next/font/google';
|
|
5
5
|
|
|
6
6
|
import { Providers } from './providers';
|
|
7
|
+
import { InputModalityTracker } from '@/components/common/InputModalityTracker';
|
|
7
8
|
import { APP_NAME } from '@/lib/constants/app.constants';
|
|
8
9
|
import { SESSION_MARKER_COOKIE } from '@/lib/utils/session-marker';
|
|
9
10
|
import './globals.css';
|
|
@@ -49,13 +50,17 @@ export default async function RootLayout({
|
|
|
49
50
|
// The font preset consumes these next/font variables from :root. Keep the
|
|
50
51
|
// generated classes on <html>; variables introduced only on <body> cannot
|
|
51
52
|
// resolve the root-scoped Tailwind font tokens.
|
|
53
|
+
// data-input: focus rings are keyboard-only. The page starts in pointer mode, so nothing shows a ring before the
|
|
54
|
+
// first key press; InputModalityTracker switches it (lib/input-modality.ts, globals.css "Focus rings").
|
|
52
55
|
<html
|
|
53
56
|
lang="en"
|
|
54
57
|
className={`${inter.variable} ${jetbrainsMono.variable}`}
|
|
58
|
+
data-input="pointer"
|
|
55
59
|
suppressHydrationWarning
|
|
56
60
|
>
|
|
57
61
|
<body className="font-sans antialiased">
|
|
58
62
|
<Providers nonce={nonce} hasSession={hasSession}>{children}</Providers>
|
|
63
|
+
<InputModalityTracker />
|
|
59
64
|
</body>
|
|
60
65
|
</html>
|
|
61
66
|
);
|
|
@@ -56,7 +56,7 @@ export default function WelcomePage(): React.ReactElement {
|
|
|
56
56
|
href="https://github.com/blessandsoul/create-tigra"
|
|
57
57
|
target="_blank"
|
|
58
58
|
rel="noopener noreferrer"
|
|
59
|
-
className="inline-flex min-h-11 items-center justify-center rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all duration-200 active:scale-[0.97]
|
|
59
|
+
className="inline-flex min-h-11 items-center justify-center rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all duration-200 active:scale-[0.97] md:hover:brightness-110"
|
|
60
60
|
>
|
|
61
61
|
Documentation
|
|
62
62
|
</a>
|
|
@@ -64,7 +64,7 @@ export default function WelcomePage(): React.ReactElement {
|
|
|
64
64
|
href="https://github.com/blessandsoul/create-tigra/issues"
|
|
65
65
|
target="_blank"
|
|
66
66
|
rel="noopener noreferrer"
|
|
67
|
-
className="inline-flex min-h-11 items-center justify-center rounded-lg border border-border bg-secondary px-5 py-2.5 text-sm font-medium text-secondary-foreground transition-all duration-200 active:scale-[0.97]
|
|
67
|
+
className="inline-flex min-h-11 items-center justify-center rounded-lg border border-border bg-secondary px-5 py-2.5 text-sm font-medium text-secondary-foreground transition-all duration-200 active:scale-[0.97] md:hover:bg-accent"
|
|
68
68
|
>
|
|
69
69
|
Report an issue
|
|
70
70
|
</a>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useEffect } from 'react';
|
|
4
|
+
|
|
5
|
+
import { installInputModality } from '@/lib/input-modality';
|
|
6
|
+
|
|
7
|
+
/** Keeps `<html data-input>` current so focus rings show only for keyboard users (lib/input-modality.ts). Renders
|
|
8
|
+
* nothing; mounted once in the root layout, which also server-renders the starting "pointer" mode. */
|
|
9
|
+
export function InputModalityTracker(): null {
|
|
10
|
+
useEffect(() => installInputModality(document), []);
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
@@ -9,8 +9,9 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
|
|
9
9
|
data-slot="input"
|
|
10
10
|
className={cn(
|
|
11
11
|
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
|
12
|
-
|
|
13
|
-
"
|
|
12
|
+
// Focus and errors show on the field's own border, never as a glow outside it (globals.css "Focus rings").
|
|
13
|
+
"focus-visible:border-ring",
|
|
14
|
+
"aria-invalid:border-destructive",
|
|
14
15
|
className
|
|
15
16
|
)}
|
|
16
17
|
{...props}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { installInputModality } from './input-modality';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Focus rings are for keyboard users. Radix menus and selects move focus by script after a mouse click
|
|
8
|
+
* whose default they cancel, so Chrome reports `:focus-visible` and every keyboard ring showed for mouse users. The
|
|
9
|
+
* page records how the owner last interacted (`<html data-input>`) and the CSS hides focus rings in "pointer" mode.
|
|
10
|
+
*/
|
|
11
|
+
let uninstall: () => void;
|
|
12
|
+
const mode = (): string | null => document.documentElement.getAttribute('data-input');
|
|
13
|
+
const key = (target: Element, keyName: string, init: KeyboardEventInit = {}): void => {
|
|
14
|
+
target.dispatchEvent(new KeyboardEvent('keydown', { key: keyName, bubbles: true, ...init }));
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
document.body.innerHTML = '<button id="b">B</button><textarea id="t"></textarea><input id="i" type="text">'
|
|
19
|
+
+ '<input id="c" type="checkbox"><div id="e" contenteditable="true"></div>';
|
|
20
|
+
document.documentElement.removeAttribute('data-input');
|
|
21
|
+
uninstall = installInputModality(document);
|
|
22
|
+
});
|
|
23
|
+
afterEach(() => { uninstall(); });
|
|
24
|
+
|
|
25
|
+
describe('installInputModality', () => {
|
|
26
|
+
it('starts in pointer mode, so nothing shows a ring before the first key press', () => {
|
|
27
|
+
expect(mode()).toBe('pointer');
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('switches to keyboard on Tab and on navigation keys outside text fields', () => {
|
|
31
|
+
key(document.getElementById('b')!, 'Tab');
|
|
32
|
+
expect(mode()).toBe('keyboard');
|
|
33
|
+
document.getElementById('b')!.dispatchEvent(new Event('pointerdown', { bubbles: true }));
|
|
34
|
+
expect(mode()).toBe('pointer');
|
|
35
|
+
for (const name of ['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Escape']) {
|
|
36
|
+
document.documentElement.setAttribute('data-input', 'pointer');
|
|
37
|
+
key(document.getElementById('b')!, name);
|
|
38
|
+
expect(mode(), name).toBe('keyboard');
|
|
39
|
+
}
|
|
40
|
+
// A checkbox is not a text field: arrows there are focus navigation.
|
|
41
|
+
document.documentElement.setAttribute('data-input', 'pointer');
|
|
42
|
+
key(document.getElementById('c')!, 'ArrowDown');
|
|
43
|
+
expect(mode()).toBe('keyboard');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('typing, arrows and Enter inside a text field never switch to keyboard', () => {
|
|
47
|
+
for (const id of ['t', 'i', 'e']) {
|
|
48
|
+
for (const name of ['a', 'Enter', ' ', 'ArrowLeft', 'ArrowDown', 'Home', 'Escape', 'Backspace']) {
|
|
49
|
+
key(document.getElementById(id)!, name);
|
|
50
|
+
expect(mode(), `${id} ${name}`).toBe('pointer');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// Tab moves focus out of the field: that is keyboard navigation.
|
|
54
|
+
key(document.getElementById('t')!, 'Tab');
|
|
55
|
+
expect(mode()).toBe('keyboard');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('ignores shortcuts with Ctrl, Alt or Meta and lone modifier keys', () => {
|
|
59
|
+
for (const init of [{ ctrlKey: true }, { altKey: true }, { metaKey: true }]) {
|
|
60
|
+
key(document.getElementById('b')!, 'ArrowDown', init);
|
|
61
|
+
expect(mode()).toBe('pointer');
|
|
62
|
+
}
|
|
63
|
+
for (const name of ['Shift', 'Control', 'Alt', 'Meta']) key(document.getElementById('b')!, name);
|
|
64
|
+
expect(mode()).toBe('pointer');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('a pointer press anywhere returns to pointer mode (mouse, touch or pen)', () => {
|
|
68
|
+
key(document.getElementById('b')!, 'Tab');
|
|
69
|
+
document.body.dispatchEvent(new Event('pointerdown', { bubbles: true }));
|
|
70
|
+
expect(mode()).toBe('pointer');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('uninstall removes the listeners', () => {
|
|
74
|
+
uninstall();
|
|
75
|
+
key(document.getElementById('b')!, 'Tab');
|
|
76
|
+
expect(mode()).toBe('pointer');
|
|
77
|
+
uninstall = (): void => undefined;
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the visitor last interacted with the page, kept on `<html data-input="pointer" | "keyboard">`, so focus rings
|
|
3
|
+
* show only for keyboard users (globals.css "Focus rings").
|
|
4
|
+
*
|
|
5
|
+
* Why the browser's own `:focus-visible` is not enough: Radix menus and selects cancel the default of the mouse press
|
|
6
|
+
* on their trigger and then move focus by script (into the menu, then to the item under the pointer). Chrome then has
|
|
7
|
+
* no record of mouse use and reports `:focus-visible`, so every keyboard ring appeared for mouse users until their
|
|
8
|
+
* first ordinary click on the page (reproduced in Chrome, also on a blank page without Radix).
|
|
9
|
+
*
|
|
10
|
+
* Rules:
|
|
11
|
+
* - Any pointer press (mouse, touch, pen) means "pointer".
|
|
12
|
+
* - Tab means "keyboard" everywhere; arrows, Home/End, PageUp/PageDown and Escape mean "keyboard" outside text fields,
|
|
13
|
+
* where they navigate focus (menus, tabs, radio groups). Typing, Enter and caret keys in a text field do not: the
|
|
14
|
+
* owner is writing, not navigating. Shortcuts with Ctrl/Alt/Meta and lone modifier keys change nothing.
|
|
15
|
+
* - The server renders "pointer" (app/layout.tsx), so nothing shows a ring before the first key press; a keyboard
|
|
16
|
+
* user's first Tab switches the mode before focus moves (keydown precedes the focus change).
|
|
17
|
+
*/
|
|
18
|
+
export type InputModality = 'pointer' | 'keyboard';
|
|
19
|
+
|
|
20
|
+
const NAVIGATION_KEYS = new Set(['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Escape']);
|
|
21
|
+
/** Input types that are not text fields: arrows there move focus or a value, like any other control. */
|
|
22
|
+
const NON_TEXT_INPUTS = new Set(['button', 'submit', 'reset', 'checkbox', 'radio', 'range', 'file', 'color', 'image']);
|
|
23
|
+
|
|
24
|
+
/** True for elements where keys type or move a caret (they keep their focus look in every mode). */
|
|
25
|
+
function isTextField(target: EventTarget | null): boolean {
|
|
26
|
+
if (!(target instanceof Element)) return false;
|
|
27
|
+
if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;
|
|
28
|
+
if (target instanceof HTMLInputElement) return !NON_TEXT_INPUTS.has(target.type);
|
|
29
|
+
// The attribute, not `isContentEditable` (missing in jsdom); `closest` also covers keys from inside an editor.
|
|
30
|
+
return target.closest('[contenteditable]:not([contenteditable="false"])') !== null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Starts tracking on `doc` (capture phase, so a component that stops propagation cannot hide the interaction) and
|
|
34
|
+
* returns a function that stops it. Sets "pointer" at once. */
|
|
35
|
+
export function installInputModality(doc: Document): () => void {
|
|
36
|
+
const root = doc.documentElement;
|
|
37
|
+
const set = (mode: InputModality): void => {
|
|
38
|
+
if (root.getAttribute('data-input') !== mode) root.setAttribute('data-input', mode);
|
|
39
|
+
};
|
|
40
|
+
const onPointerDown = (): void => set('pointer');
|
|
41
|
+
const onKeyDown = (event: KeyboardEvent): void => {
|
|
42
|
+
if (event.ctrlKey || event.altKey || event.metaKey) return;
|
|
43
|
+
if (event.key === 'Tab' || (NAVIGATION_KEYS.has(event.key) && !isTextField(event.target))) set('keyboard');
|
|
44
|
+
};
|
|
45
|
+
set('pointer');
|
|
46
|
+
doc.addEventListener('pointerdown', onPointerDown, true);
|
|
47
|
+
doc.addEventListener('keydown', onKeyDown, true);
|
|
48
|
+
return () => {
|
|
49
|
+
doc.removeEventListener('pointerdown', onPointerDown, true);
|
|
50
|
+
doc.removeEventListener('keydown', onKeyDown, true);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Server
|
|
2
|
+
|
|
3
|
+
The API: Fastify 5 and TypeScript, Prisma 6 on MySQL 8.4, Redis 7 (ioredis), Zod, Pino, Vitest. Every route lives
|
|
4
|
+
under `/api/v1`.
|
|
5
|
+
|
|
6
|
+
## Layout
|
|
7
|
+
|
|
8
|
+
```text
|
|
9
|
+
server/
|
|
10
|
+
├── src/
|
|
11
|
+
│ ├── app.ts builds the app: plugins, security hooks, routes
|
|
12
|
+
│ ├── server.ts starts it: database, Redis, jobs, graceful shutdown
|
|
13
|
+
│ ├── config/ env.ts (every setting, validated at boot), rate-limit.config.ts (every limit)
|
|
14
|
+
│ ├── modules/<domain>/ auth, users, admin, files: routes → controller → service → repo (+ schemas)
|
|
15
|
+
│ ├── libs/ shared pieces: auth, cookies, client IP, rate limiting, IP blocks, email,
|
|
16
|
+
│ │ HTTP clients, storage, logging, health, shutdown, validation errors
|
|
17
|
+
│ ├── jobs/ background jobs and their scheduler
|
|
18
|
+
│ ├── scripts/ make-admin
|
|
19
|
+
│ ├── shared/ response helpers, error classes, shared types
|
|
20
|
+
│ └── test/ integration test setup and helpers
|
|
21
|
+
├── prisma/ schema.prisma and migrations/ (starting with 0_init)
|
|
22
|
+
├── docs/ deployment, rate limits, testing, logging
|
|
23
|
+
├── postman/ a collection of every route
|
|
24
|
+
├── uploads/ local uploads (a volume at /app/uploads in production)
|
|
25
|
+
├── docker-compose.yml local MySQL and Redis (+ phpMyAdmin and Redis Commander with --profile tools)
|
|
26
|
+
└── Dockerfile the production image
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Commands
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
npm run dev # the API with reload, on PORT (8000)
|
|
33
|
+
npm test # unit tests, no database
|
|
34
|
+
npm run test:coverage # unit tests with the coverage floor (vitest.config.ts)
|
|
35
|
+
npm run test:integration # every route against a real MySQL and Redis (docs/testing.md)
|
|
36
|
+
npm run lint && npm run typecheck
|
|
37
|
+
npm run build && npm start # production build, then run it
|
|
38
|
+
|
|
39
|
+
npm run prisma:migrate:dev # after changing schema.prisma: create and apply a migration
|
|
40
|
+
npm run prisma:studio # browse the database
|
|
41
|
+
npm run make-admin -- you@example.com
|
|
42
|
+
npm run docker:up | docker:tools | docker:down
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Routes
|
|
46
|
+
|
|
47
|
+
| Route | Who may call it |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `POST /auth/register`, `/auth/login`, `/auth/refresh`, `/auth/logout` | anyone |
|
|
50
|
+
| `POST /auth/forgot-password`, `/auth/reset-password` | anyone (the emailed link carries the token) |
|
|
51
|
+
| `GET /auth/me`, `GET /auth/sessions`, `POST /auth/logout-all` | signed in |
|
|
52
|
+
| `PATCH /users/me`, `PATCH /users/me/password`, `DELETE /users/me` | signed in |
|
|
53
|
+
| `POST /users/avatar`, `DELETE /users/avatar` | signed in |
|
|
54
|
+
| `PATCH /users/:userId`, `/users/:userId/password`, `DELETE /users/:userId`, `POST` and `DELETE /users/:userId/avatar` | the owner, or an admin |
|
|
55
|
+
| `GET /files/:filename` | the file's owner |
|
|
56
|
+
| `GET /admin/stats`, `/admin/health`, `/admin/client-ip` | admin |
|
|
57
|
+
| `GET /admin/users`, `GET /admin/users/:userId`, `PATCH /admin/users/:userId/status` and `/role`, `POST /admin/users/:userId/restore` | admin |
|
|
58
|
+
| `GET /admin/sessions`, `DELETE /admin/sessions/:sessionId` | admin |
|
|
59
|
+
| `GET /admin/blocked-ips`, `POST /admin/blocked-ips`, `DELETE /admin/blocked-ips/:ip` | admin |
|
|
60
|
+
| `GET /health`, `/ready`, `/live` | anyone (never rate limited) |
|
|
61
|
+
|
|
62
|
+
With the email-verification module: `POST /auth/send-verification` and `POST /auth/verify-account`. Public avatars are
|
|
63
|
+
served from `/uploads/`. `postman/collection.json` has every route with example bodies.
|
|
64
|
+
|
|
65
|
+
Every answer has one shape:
|
|
66
|
+
|
|
67
|
+
```json
|
|
68
|
+
{ "success": true, "message": "Profile updated", "data": { } }
|
|
69
|
+
{ "success": false, "error": { "code": "VALIDATION_FAILED", "message": "Please check these fields: email", "fields": [{ "field": "email", "message": "Invalid email address" }] } }
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Wrong input is always `422 VALIDATION_FAILED` with `fields`; "slow down" answers (429, and 403 `IP_BLOCKED`) carry
|
|
73
|
+
`retryAfterSeconds`; an unexpected error is a generic 500, logged in full here.
|
|
74
|
+
|
|
75
|
+
## Adding a feature
|
|
76
|
+
|
|
77
|
+
1. A module in `src/modules/<domain>/`: `<domain>.routes.ts` (paths and Zod schemas), `.controller.ts` (HTTP in and
|
|
78
|
+
out), `.service.ts` (business rules and who may do what), `.repo.ts` (Prisma queries only), `.schemas.ts`.
|
|
79
|
+
2. Register its routes in `src/app.ts` under the `/api/v1` prefix. A new route gets the default limit of 200 per
|
|
80
|
+
minute; give it a `RATE_LIMITS` entry in `src/config/rate-limit.config.ts` only when it needs another number.
|
|
81
|
+
3. A schema change: edit `prisma/schema.prisma`, then `npm run prisma:migrate:dev`. Migrations run while the old
|
|
82
|
+
version still serves, so never drop, rename, retype or tighten a column in the same deploy as the code that
|
|
83
|
+
stops using it (`docs/deployment.md`).
|
|
84
|
+
4. Tests: unit tests next to the code (`__tests__/`), and the route's contract (401/403, 422, success) in
|
|
85
|
+
`src/__tests__/routes.integration.test.ts`. That file fails when a registered route is never called.
|
|
86
|
+
5. Fetching a URL a user gave you: `safeHttpClient` (`src/libs/safe-http.ts`), never `fetch`. Recurring work:
|
|
87
|
+
`startRecurringJob` (`src/jobs/schedule.ts`), never `setInterval`.
|
|
88
|
+
|
|
89
|
+
`AGENTS.md` in this folder has the full set of rules.
|
|
90
|
+
|
|
91
|
+
## Configuration
|
|
92
|
+
|
|
93
|
+
`src/config/env.ts` validates every setting at boot and stops with the reason when one is wrong. `.env.example`
|
|
94
|
+
documents development, `.env.example.production` documents production. In production the server also refuses to
|
|
95
|
+
start:
|
|
96
|
+
|
|
97
|
+
- with a placeholder `JWT_SECRET`, or a `CORS_ORIGIN` that is not a list of bare origins;
|
|
98
|
+
- without `REDIS_URL`, or when Redis is not reachable within 10 s (the limits, the lockout and the IP blocks would
|
|
99
|
+
be off);
|
|
100
|
+
- without any migration in the image;
|
|
101
|
+
- with the placeholder Resend key or sender, when email is set up.
|
|
102
|
+
|
|
103
|
+
## Guides
|
|
104
|
+
|
|
105
|
+
- `docs/deployment.md`: what a deploy does, safe migrations, rollback, build time.
|
|
106
|
+
- `docs/rate-limits.md`: every limit, the login lockout, IP blocks, email caps, overrides, Redis outages.
|
|
107
|
+
- `docs/testing.md`: the unit and integration suites, writing tests, CI, coverage.
|
|
108
|
+
- `docs/logging.md`: request logs, redaction, health checks.
|
|
@@ -85,13 +85,27 @@ Redis is down or slow (so rate limits and IP blocks are off), or the heap is abo
|
|
|
85
85
|
|
|
86
86
|
The public answer never says which check failed. Admins get the full report at
|
|
87
87
|
`GET /api/v1/admin/health`: per check status and timing, memory (heap used and limit, RSS),
|
|
88
|
-
uptime, `checkedAt`, `version` (from `package.json`) and `commit` (
|
|
89
|
-
|
|
88
|
+
uptime, `checkedAt`, `version` (from `package.json`) and `commit` (the first 12 characters of
|
|
89
|
+
`SOURCE_COMMIT` when the environment provides it, otherwise `null`).
|
|
90
90
|
|
|
91
91
|
The database and Redis are checked at most once per 5 s; every probe in between gets the same
|
|
92
92
|
answer (`checkedAt` says when it was taken). A failing check logs the error at `error`
|
|
93
93
|
(database) or `warn` (Redis).
|
|
94
94
|
|
|
95
|
+
## Secrets never reach the logs
|
|
96
|
+
|
|
97
|
+
Pino's redaction (`src/libs/logger.ts`) removes these keys wherever they appear in a logged object, up to three
|
|
98
|
+
levels deep, and the secret headers of a logged request:
|
|
99
|
+
|
|
100
|
+
```text
|
|
101
|
+
keys password newPassword currentPassword passwordHash token accessToken refreshToken
|
|
102
|
+
access_token refresh_token secret clientSecret apiKey api_key authorization cookie
|
|
103
|
+
headers authorization cookie set-cookie proxy-authorization x-api-key x-origin-verify
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Request lines never contain the query string, outbound request logs show URLs without keys or `user:password@`,
|
|
107
|
+
and email addresses in email logs are masked. Logging a secret under another name is still on you: name it plainly.
|
|
108
|
+
|
|
95
109
|
## Configuration
|
|
96
110
|
|
|
97
111
|
### Development
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Testing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The server has two suites, both Vitest (the client's unit tests are at the end):
|
|
4
4
|
|
|
5
5
|
| Suite | Command | Needs | What it proves |
|
|
6
6
|
|---|---|---|---|
|
|
@@ -42,6 +42,15 @@ applies, so a migration that does not match the code fails here first.
|
|
|
42
42
|
`uploadAvatar()`, and `startEmailStub()`, a local stand-in for Resend that catches every email (nothing is sent).
|
|
43
43
|
- Every new route gets a row in `src/__tests__/routes.integration.test.ts`: who may call it (401/403), what wrong
|
|
44
44
|
input answers (422) and its success answer. Deeper behaviour goes in the area's own integration file.
|
|
45
|
+
- That file checks itself: its last test fails, naming the route, when a registered route is never called in it.
|
|
46
|
+
A route another file already tests goes in its `COVERED_ELSEWHERE` list with that file's name:
|
|
47
|
+
|
|
48
|
+
```text
|
|
49
|
+
× every registered route was called above, or is in COVERED_ELSEWHERE
|
|
50
|
+
+ "GET /api/v1/reports/:id"
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Run it on its own with `-t` and it skips itself (the other tests did not run).
|
|
45
54
|
- Import the app lazily, inside `beforeAll` (`const { buildApp } = await import('@/app.js')`): the environment is
|
|
46
55
|
set by `src/test/integration.setup.ts` and must be in place before `env.ts` is loaded.
|
|
47
56
|
- All files share one database and Redis and run one after another. Create your own data with unique emails; never
|
|
@@ -53,7 +62,7 @@ applies, so a migration that does not match the code fails here first.
|
|
|
53
62
|
|
|
54
63
|
`.github/workflows/ci.yml` (project root) runs on every push and pull request: typecheck, lint,
|
|
55
64
|
`npm run test:coverage`, the server build, `npm run test:integration` (Testcontainers on GitHub's Ubuntu runners)
|
|
56
|
-
and the client's typecheck, lint and build. It never deploys.
|
|
65
|
+
and the client's typecheck, lint, `npm run test:coverage` and build. It never deploys.
|
|
57
66
|
|
|
58
67
|
## Coverage
|
|
59
68
|
|
|
@@ -61,3 +70,12 @@ and the client's typecheck, lint and build. It never deploys.
|
|
|
61
70
|
thresholds in `vitest.config.ts`. They are a ratchet: the real numbers when they were set, rounded down. Raise them
|
|
62
71
|
when you add tests; never lower them to make a change pass. Routes and controllers are tested by the integration
|
|
63
72
|
suite, which the coverage gate does not count.
|
|
73
|
+
|
|
74
|
+
## Client tests
|
|
75
|
+
|
|
76
|
+
`client/` has its own Vitest unit suite (`npm test`, `npm run test:coverage` with its floor in
|
|
77
|
+
`client/vitest.config.mts`). It covers the logic under the screens: the API client's session rules (one refresh for
|
|
78
|
+
parallel 401s, a refresh race lost to another tab, a ban mid-session), the proxy's CSP and redirects, redirect
|
|
79
|
+
safety, path matching, the session marker, error and field-error parsing, and the store. The template ships no pages;
|
|
80
|
+
when you add them, keep their logic in functions under `client/src/lib/` and test it there.
|
|
81
|
+
|