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
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { FastifyInstance } from 'fastify';
|
|
2
|
+
import { env } from '@config/env.js';
|
|
3
|
+
import { RATE_LIMITS } from '@config/rate-limit.config.js';
|
|
4
|
+
import { isOriginAllowed } from '@libs/origin-check.js';
|
|
5
|
+
import { ForbiddenError } from '@shared/errors/errors.js';
|
|
6
|
+
import { successResponse } from '@shared/responses/successResponse.js';
|
|
7
|
+
import type { MetricCollector } from './metrics.collector.js';
|
|
8
|
+
import { readMetricBuckets } from './metrics.repo.js';
|
|
9
|
+
import { metricsQuerySchema, webVitalsSchema, type MetricsQuery, type WebVitalsInput } from './metrics.schemas.js';
|
|
10
|
+
|
|
11
|
+
const origins = new Set(env.CORS_ORIGINS);
|
|
12
|
+
|
|
13
|
+
export async function webVitalsRoutes(app: FastifyInstance, options: { collector?: MetricCollector }): Promise<void> {
|
|
14
|
+
app.post<{ Body: WebVitalsInput }>('/metrics/web-vitals', {
|
|
15
|
+
schema: { body: webVitalsSchema },
|
|
16
|
+
bodyLimit: 2048,
|
|
17
|
+
config: {
|
|
18
|
+
// A busy shared IP may hit this endpoint's limit. It must not earn
|
|
19
|
+
// IP-wide auto-block strikes from best-effort telemetry.
|
|
20
|
+
rateLimit: { ...RATE_LIMITS.METRICS_INGESTION, onExceeded: () => {} },
|
|
21
|
+
},
|
|
22
|
+
onRequest: async (request) => {
|
|
23
|
+
const origin = request.headers.origin;
|
|
24
|
+
if (!origin || origin === 'null' || !isOriginAllowed(origin, request.headers.host, origins, env.NODE_ENV === 'development')) {
|
|
25
|
+
throw new ForbiddenError('Origin not allowed', 'ORIGIN_NOT_ALLOWED');
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
}, async (request, reply) => {
|
|
29
|
+
for (const { kind, value } of request.body.samples) {
|
|
30
|
+
options.collector?.record(kind, request.body.page, value);
|
|
31
|
+
}
|
|
32
|
+
return reply.code(204).send();
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Mount inside adminRoutes, whose authentication and role hooks guard this
|
|
37
|
+
* read even when the collector is disabled. */
|
|
38
|
+
export function registerAdminMetricsRoute(app: FastifyInstance): void {
|
|
39
|
+
app.get<{ Querystring: MetricsQuery }>('/admin/metrics', {
|
|
40
|
+
schema: { querystring: metricsQuerySchema },
|
|
41
|
+
config: { rateLimit: RATE_LIMITS.ADMIN_DEFAULT },
|
|
42
|
+
}, async (request, reply) => {
|
|
43
|
+
reply.header('Cache-Control', 'no-store');
|
|
44
|
+
return successResponse('Metric buckets', await readMetricBuckets(request.query));
|
|
45
|
+
});
|
|
46
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { METRICS, type MetricKind } from './metrics.collector.js';
|
|
3
|
+
import { METRICS_PAGE_GROUPS } from './metrics.pages.js';
|
|
4
|
+
|
|
5
|
+
const sevenDays = 7 * 24 * 60 * 60_000;
|
|
6
|
+
const dateTime = z.iso.datetime({ offset: true }).transform((value) => new Date(value))
|
|
7
|
+
.pipe(z.date().min(new Date('1000-01-01T00:00:00Z')).max(new Date('9999-12-31T23:59:59.999Z')));
|
|
8
|
+
const metricKind = z.custom<MetricKind>(
|
|
9
|
+
(value) => typeof value === 'string' && Object.hasOwn(METRICS, value),
|
|
10
|
+
'Unknown metric kind',
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
// The cursor identifies a position, not a capability or a database query.
|
|
14
|
+
const cursorSchema = z.tuple([dateTime, z.string().regex(/^[a-f0-9]{64}$/)]);
|
|
15
|
+
const cursor = z.string().max(192).regex(/^[A-Za-z0-9_-]+$/).transform((value, ctx) => {
|
|
16
|
+
let decoded: unknown;
|
|
17
|
+
try { decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')); } catch { /* invalid cursor */ }
|
|
18
|
+
const result = cursorSchema.safeParse(decoded);
|
|
19
|
+
if (result.success) return result.data;
|
|
20
|
+
ctx.addIssue({ code: 'custom', message: 'Invalid metrics cursor' });
|
|
21
|
+
return z.NEVER;
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export const metricsQuerySchema = z.strictObject({
|
|
25
|
+
from: dateTime,
|
|
26
|
+
to: dateTime,
|
|
27
|
+
kind: metricKind.optional(),
|
|
28
|
+
limit: z.string().regex(/^\d{1,3}$/).transform(Number).pipe(z.number().int().min(1).max(100)).default(50),
|
|
29
|
+
cursor: cursor.optional(),
|
|
30
|
+
}).superRefine(({ from, to, cursor }, ctx) => {
|
|
31
|
+
// Zod can run refinements after a field check fails, with its original input.
|
|
32
|
+
if (!(from instanceof Date) || !(to instanceof Date)) return;
|
|
33
|
+
const range = to.getTime() - from.getTime();
|
|
34
|
+
if (range <= 0 || range > sevenDays) {
|
|
35
|
+
ctx.addIssue({ code: 'custom', path: ['to'], message: 'The interval must be positive and at most seven days' });
|
|
36
|
+
}
|
|
37
|
+
if (Array.isArray(cursor) && (cursor[0] < from || cursor[0] >= to)) {
|
|
38
|
+
ctx.addIssue({ code: 'custom', path: ['cursor'], message: 'The cursor must be inside the requested interval' });
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
export type MetricsQuery = z.output<typeof metricsQuerySchema>;
|
|
42
|
+
|
|
43
|
+
export const webVitalsSchema = z.strictObject({
|
|
44
|
+
page: z.enum(METRICS_PAGE_GROUPS),
|
|
45
|
+
samples: z.array(z.strictObject({
|
|
46
|
+
kind: z.enum(['lcp', 'inp', 'cls']),
|
|
47
|
+
value: z.number().finite().min(0).max(86_400_000),
|
|
48
|
+
})).min(1).max(3),
|
|
49
|
+
}).superRefine(({ samples }, ctx) => {
|
|
50
|
+
if (new Set(samples.map((sample) => sample.kind)).size !== samples.length) {
|
|
51
|
+
ctx.addIssue({ code: 'custom', path: ['samples'], message: 'Send each vital at most once per batch' });
|
|
52
|
+
}
|
|
53
|
+
if (samples.some(({ kind, value }) => kind === 'cls' && value > 100)) {
|
|
54
|
+
ctx.addIssue({ code: 'custom', path: ['samples'], message: 'CLS must not exceed 100' });
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
export type WebVitalsInput = z.output<typeof webVitalsSchema>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { monitorEventLoopDelay, performance } from 'node:perf_hooks';
|
|
2
|
+
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
|
3
|
+
import { env } from '@config/env.js';
|
|
4
|
+
import { startRecurringJob } from '@/jobs/schedule.js';
|
|
5
|
+
import { logger } from '@libs/logger.js';
|
|
6
|
+
import { MONITORING_PATHS } from '@libs/rate-limiting.js';
|
|
7
|
+
import { MetricCollector } from './metrics.collector.js';
|
|
8
|
+
import { persistMetricBuckets } from './metrics.repo.js';
|
|
9
|
+
|
|
10
|
+
const EXCLUDED = new Set([...MONITORING_PATHS, '/api/v1/metrics/web-vitals', '/api/v1/admin/metrics']);
|
|
11
|
+
let activeCollector: MetricCollector | undefined;
|
|
12
|
+
|
|
13
|
+
/** Time an explicitly named operation without changing its return or error
|
|
14
|
+
* behavior. Names must describe code paths, never individual resources. */
|
|
15
|
+
export async function measureOperation<T>(name: string, run: () => T | Promise<T>): Promise<T> {
|
|
16
|
+
const collector = activeCollector;
|
|
17
|
+
if (!collector || !/^[a-z][a-z0-9._-]{0,79}$/.test(name)) return run();
|
|
18
|
+
const start = performance.now();
|
|
19
|
+
try {
|
|
20
|
+
return await run();
|
|
21
|
+
} finally {
|
|
22
|
+
collector.record('operation', name, performance.now() - start);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function registerMetrics(app: FastifyInstance): MetricCollector | undefined {
|
|
27
|
+
if (!env.METRICS_ENABLED) return undefined;
|
|
28
|
+
const release = env.SOURCE_COMMIT?.trim();
|
|
29
|
+
const collector = new MetricCollector(persistMetricBuckets, {
|
|
30
|
+
release: release && /^[a-f0-9]{7,64}$/i.test(release) ? release.toLowerCase() : null,
|
|
31
|
+
});
|
|
32
|
+
activeCollector = collector;
|
|
33
|
+
const starts = new WeakMap<FastifyRequest, number>();
|
|
34
|
+
|
|
35
|
+
// Register at the root before route plugins so auth, validation and future
|
|
36
|
+
// routes are covered. A socket abort/timeout without a reply is excluded.
|
|
37
|
+
app.addHook('onRequest', async (request) => {
|
|
38
|
+
if (request.method === 'OPTIONS' || EXCLUDED.has(request.routeOptions.url ?? '')) return;
|
|
39
|
+
starts.set(request, performance.now());
|
|
40
|
+
});
|
|
41
|
+
app.addHook('onRequestAbort', async (request) => { starts.delete(request); });
|
|
42
|
+
app.addHook('onTimeout', async (request) => { starts.delete(request); });
|
|
43
|
+
app.addHook('onResponse', async (request) => {
|
|
44
|
+
const start = starts.get(request);
|
|
45
|
+
if (start === undefined) return;
|
|
46
|
+
starts.delete(request);
|
|
47
|
+
const route = request.is404 ? undefined : request.routeOptions.url;
|
|
48
|
+
const label = route && route.length <= 191 ? route : '(unmatched)';
|
|
49
|
+
collector.record('request', label, performance.now() - start, request.method);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const eventLoop = monitorEventLoopDelay({ resolution: 20 });
|
|
53
|
+
eventLoop.enable();
|
|
54
|
+
let cpu = process.cpuUsage();
|
|
55
|
+
let sampledAt = performance.now();
|
|
56
|
+
startRecurringJob(app, {
|
|
57
|
+
name: 'metrics-flush',
|
|
58
|
+
firstRunDelayMs: 5_000,
|
|
59
|
+
intervalMs: 15_000,
|
|
60
|
+
run: async () => {
|
|
61
|
+
const now = performance.now();
|
|
62
|
+
const spent = process.cpuUsage(cpu);
|
|
63
|
+
cpu = process.cpuUsage();
|
|
64
|
+
const memory = process.memoryUsage();
|
|
65
|
+
collector.record('rss', 'process', memory.rss);
|
|
66
|
+
collector.record('heap', 'process', memory.heapUsed);
|
|
67
|
+
collector.record('cpu', 'process', (spent.user + spent.system) / (10 * (now - sampledAt)));
|
|
68
|
+
// One mean-delay observation per sample period. This is not a histogram
|
|
69
|
+
// of individual event-loop ticks, and the units here are milliseconds.
|
|
70
|
+
collector.record('event-loop-delay', 'process', eventLoop.mean / 1_000_000);
|
|
71
|
+
eventLoop.reset();
|
|
72
|
+
sampledAt = now;
|
|
73
|
+
await collector.flush();
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
app.addHook('onClose', async () => {
|
|
78
|
+
eventLoop.disable();
|
|
79
|
+
if (activeCollector === collector) activeCollector = undefined;
|
|
80
|
+
// The collector shares the app's shutdown budget with Redis and Prisma.
|
|
81
|
+
// A stalled store must never keep the Fastify close hook waiting forever.
|
|
82
|
+
let deadline: ReturnType<typeof setTimeout> | undefined;
|
|
83
|
+
try {
|
|
84
|
+
await Promise.race([
|
|
85
|
+
collector.close(),
|
|
86
|
+
new Promise<never>((_resolve, reject) => {
|
|
87
|
+
deadline = setTimeout(() => reject(new Error('Metrics flush deadline')), 2_500);
|
|
88
|
+
}),
|
|
89
|
+
]);
|
|
90
|
+
} catch {
|
|
91
|
+
logger.warn('[METRICS] Final batch could not be persisted before shutdown');
|
|
92
|
+
} finally {
|
|
93
|
+
clearTimeout(deadline);
|
|
94
|
+
if (collector.droppedSamples) {
|
|
95
|
+
logger.warn({ droppedSamples: collector.droppedSamples }, '[METRICS] Samples dropped at buffer limit');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
return collector;
|
|
100
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-tigra",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.1.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Create a production-ready full-stack app with Next.js 16 + Fastify 5 + Prisma + Redis",
|
|
6
6
|
"bin": {
|
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
"bin",
|
|
11
11
|
"lib",
|
|
12
12
|
"modules",
|
|
13
|
-
"template"
|
|
13
|
+
"template",
|
|
14
|
+
"CHANGELOG.md"
|
|
14
15
|
],
|
|
15
16
|
"engines": {
|
|
16
17
|
"node": ">=22.12.0"
|
package/template/AGENTS.md
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
# Agent instructions
|
|
2
2
|
|
|
3
|
-
**Read the scoped
|
|
3
|
+
**Read the scoped rules before editing.** For `server/` work, read [server/AGENTS.md](server/AGENTS.md). For `client/` work, read [client/AGENTS.md](client/AGENTS.md). Read both for a change that crosses the API boundary.
|
|
4
|
+
|
|
5
|
+
## Architecture rules
|
|
6
|
+
|
|
7
|
+
- Keep the Next.js App Router client and Fastify API independently deployable. The server uses Prisma, MySQL, and Redis and owns authorization, business rules, and authoritative validation. The client owns presentation, interaction, and validation feedback.
|
|
8
|
+
- Extend the domain that already owns the behavior. Use the existing route, controller, service, and repository boundaries on the server. Keep client feature behavior in its domain and reuse shared components and theme tokens for UI.
|
|
9
|
+
- Use the existing shared contracts for API paths, responses, authentication, and security. Extend the owning code when behavior changes so all callers use the same policy.
|
|
10
|
+
- Use `server/prisma/schema.prisma` and Prisma migrations for database changes. Define environment variables in `server/src/config/env.ts` or `client/src/lib/env.ts` and update the corresponding examples without credentials.
|
|
11
|
+
- Treat changes to these boundaries as explicit project decisions. Record agreed exceptions and their reasons in **Project facts → Special rules** so later agents can follow them.
|
|
12
|
+
|
|
13
|
+
### Check for reuse before implementing
|
|
14
|
+
|
|
15
|
+
Before writing code, search across each side you touch (`client/` or `server/`) for the closest behavior, including features outside the directory you are editing. Follow imports and callers to find where that behavior is implemented and how it is used. Reuse or extend the component, hook, service, or helper that already owns the behavior when it fits. If nothing fits, follow the established pattern for the most similar behavior.
|
|
16
|
+
|
|
17
|
+
Shared behavior should have one owner so a change can be made once and reach every caller. This keeps the application consistent and maintainable as it grows.
|
|
18
|
+
|
|
19
|
+
Extract shared code when it has real callers that should change together. Keep code separate when the similarity is superficial, the callers need to evolve independently, or sharing would make them harder to understand. In your handoff, briefly name what you reused or explain why new code was needed.
|
|
4
20
|
|
|
5
21
|
## MUST FOLLOW — comment important code
|
|
6
22
|
|
|
@@ -22,15 +38,6 @@ Every implementation change MUST include a human-readability pass. Add or update
|
|
|
22
38
|
- **Special rules:** none
|
|
23
39
|
<!-- project-facts:end -->
|
|
24
40
|
|
|
25
|
-
## Architecture and sources of truth
|
|
26
|
-
|
|
27
|
-
- `client/` is a Next.js App Router application; `server/` is a Fastify API backed by Prisma/MySQL and Redis. They deploy independently.
|
|
28
|
-
- The server owns authorization, business rules, and security validation. Client validation exists for UX and is never a trust boundary.
|
|
29
|
-
- `server/prisma/schema.prisma` is the database-schema source of truth. Use Prisma migrations for schema changes.
|
|
30
|
-
- `server/src/config/env.ts` and `client/src/lib/env.ts` define valid environment variables. Keep the corresponding `.env.example` files synchronized without real credentials.
|
|
31
|
-
- Shared route/API constants, response helpers, and security middleware are canonical; extend them instead of creating competing shapes or duplicate policy.
|
|
32
|
-
- Client font preset tokens are declared on `:root`. Apply every referenced `next/font` variable class to `<html>`, never only to `<body>`, so the root-scoped Tailwind tokens can resolve it.
|
|
33
|
-
|
|
34
41
|
## Naming
|
|
35
42
|
|
|
36
43
|
- Use functional kebab-case for project names and anything surfaced in CLIs, logs, queues, jobs, or worker/process names.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# {{PROJECT_DISPLAY_NAME}}
|
|
2
|
+
|
|
3
|
+
A full-stack TypeScript app generated with [create-tigra](https://github.com/blessandsoul/create-tigra): a Fastify
|
|
4
|
+
API and a Next.js client that run and deploy separately.
|
|
5
|
+
|
|
6
|
+
```text
|
|
7
|
+
{{PROJECT_NAME}}/
|
|
8
|
+
├── server/ the API: Fastify 5, Prisma (MySQL 8.4), Redis 7 → server/README.md
|
|
9
|
+
├── client/ the web app: Next.js 16, React 19, Tailwind v4 → client/README.md
|
|
10
|
+
├── .github/ CI on every push, a weekly dependency audit, Dependabot
|
|
11
|
+
└── AGENTS.md the rules for changing this code (AI agents read it; so can you)
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Run it locally
|
|
15
|
+
|
|
16
|
+
You need Node.js 24+ with npm 11.19+ (`npm -v`), and Docker for MySQL and Redis.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
cd server
|
|
20
|
+
npm ci # the shipped lockfile, exactly
|
|
21
|
+
npm run docker:up # this project's MySQL and Redis
|
|
22
|
+
npm run prisma:generate
|
|
23
|
+
npm run prisma:migrate:dev # creates the tables from the first migration
|
|
24
|
+
npm run dev
|
|
25
|
+
|
|
26
|
+
# second terminal
|
|
27
|
+
cd client
|
|
28
|
+
npm ci
|
|
29
|
+
npm run dev
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
| What | Where |
|
|
33
|
+
|---|---|
|
|
34
|
+
| Web app | http://localhost:3000 |
|
|
35
|
+
| API | http://localhost:8000/api/v1 (health: `/api/v1/health`) |
|
|
36
|
+
| MySQL | `127.0.0.1:{{MYSQL_PORT}}`, database `{{DATABASE_NAME}}` |
|
|
37
|
+
| Redis | `127.0.0.1:{{REDIS_PORT}}` |
|
|
38
|
+
| phpMyAdmin / Redis Commander | http://localhost:{{PHPMYADMIN_PORT}} / http://localhost:{{REDIS_COMMANDER_PORT}}, after `npm run docker:tools` |
|
|
39
|
+
|
|
40
|
+
`server/.env` and `client/.env` were written with fresh secrets when the project was created; they are git-ignored.
|
|
41
|
+
Every setting is explained in `server/.env.example` and `client/.env.example`.
|
|
42
|
+
|
|
43
|
+
## Before you build features
|
|
44
|
+
|
|
45
|
+
- **The client has no pages yet, on purpose.** It ships the wiring (API client, sign-in flow, forms, security
|
|
46
|
+
headers) and you design the screens. Add pages at the paths in `client/src/lib/constants/routes.ts`: `/login`,
|
|
47
|
+
`/register`, `/reset-password`, `/dashboard`, `/profile`, `/admin`. The proxy and the emails already send people
|
|
48
|
+
there. See `client/README.md`.
|
|
49
|
+
- **The first admin:** sign up, then `npm run make-admin -- you@example.com` in `server/` (in production:
|
|
50
|
+
`node dist/scripts/make-admin.js you@example.com` in the server's terminal).
|
|
51
|
+
- **Emails** (password reset, and verification if it is on) need `RESEND_API_KEY` in `server/.env`.
|
|
52
|
+
|
|
53
|
+
## Before you push
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
cd server && npm run lint && npm run typecheck && npm run test:coverage && npm run test:integration && npm run build
|
|
57
|
+
cd client && npm run lint && npm run typecheck && npm run test:coverage && npm run build
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
CI (`.github/workflows/ci.yml`) runs the same on every push and pull request. The integration tests need Docker, or a
|
|
61
|
+
MySQL and Redis you already run (`server/docs/testing.md`).
|
|
62
|
+
|
|
63
|
+
## Deploy
|
|
64
|
+
|
|
65
|
+
Two Coolify applications from this repository, one per Dockerfile (`server/`, `client/`), plus a MySQL and a Redis.
|
|
66
|
+
Deploy the server first: it applies the migrations at start. The settings, the variables and what a deploy does:
|
|
67
|
+
`server/docs/deployment.md`, and the checklist in the
|
|
68
|
+
[create-tigra README](https://github.com/blessandsoul/create-tigra#deploying-to-coolify).
|
|
69
|
+
|
|
70
|
+
## Guides
|
|
71
|
+
|
|
72
|
+
| File | What it explains |
|
|
73
|
+
|---|---|
|
|
74
|
+
| `server/README.md`, `client/README.md` | each app's layout, commands and conventions |
|
|
75
|
+
| `server/docs/deployment.md` | what a deploy does, safe migrations, rollback |
|
|
76
|
+
| `server/docs/rate-limits.md` | rate limits, login lockout, IP blocks, email caps |
|
|
77
|
+
| `server/docs/testing.md` | unit and integration tests, CI, coverage |
|
|
78
|
+
| `server/docs/logging.md` | request logs, redaction, health checks |
|
|
79
|
+
| `AGENTS.md`, `server/AGENTS.md`, `client/AGENTS.md` | the rules for changing the code |
|
|
@@ -1,36 +1,107 @@
|
|
|
1
|
-
|
|
1
|
+
# Client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The web app: Next.js 16 (App Router, Server Components by default), React 19, TypeScript, Tailwind CSS v4 and
|
|
4
|
+
shadcn/ui, React Query for server data, Redux Toolkit for the signed-in user, Vitest.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
It ships the wiring, not the screens: a welcome page, error and not-found pages, the `/healthz` health check, and
|
|
7
|
+
everything your own pages need to talk to the API safely.
|
|
8
|
+
|
|
9
|
+
## Layout
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
client/src/
|
|
13
|
+
├── app/ routes: page.tsx (welcome), layout.tsx, providers.tsx, error, not-found, healthz/
|
|
14
|
+
│ ├── (auth)/ a centred layout for your sign-in pages
|
|
15
|
+
│ └── (main)/ the layout with Header and Footer for the rest
|
|
16
|
+
├── proxy.ts runs before every page: CSP nonce, security headers, protected-page redirect
|
|
17
|
+
├── features/
|
|
18
|
+
│ ├── auth/ useAuth, useCurrentUser, AuthInitializer, LoginForm, RegisterForm,
|
|
19
|
+
│ │ ForgotPasswordForm, LimitNotice, usePasswordReset, auth.service
|
|
20
|
+
│ └── admin/ hooks and a service for stats, users and sessions
|
|
21
|
+
├── components/ ui/ (shadcn), common/ (AppLink, SafeImage, ConfirmDialog, Pagination, …), layout/
|
|
22
|
+
├── lib/
|
|
23
|
+
│ ├── api/ axios.config.ts (the API client), session-events.ts
|
|
24
|
+
│ ├── constants/ routes.ts (every page path, PROTECTED_PATHS), api-endpoints.ts
|
|
25
|
+
│ └── utils/ error and field-error parsing, safe redirects, paths, the session marker, forms
|
|
26
|
+
├── store/ makeStore(): one Redux store per visitor
|
|
27
|
+
└── styles/ theme tokens (light and dark) and fonts
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Commands
|
|
6
31
|
|
|
7
32
|
```bash
|
|
8
|
-
npm run dev
|
|
9
|
-
#
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
33
|
+
npm run dev # http://localhost:3000, with fast refresh
|
|
34
|
+
npm test # unit tests
|
|
35
|
+
npm run test:coverage # with the coverage floor (vitest.config.mts)
|
|
36
|
+
npm run lint && npm run typecheck
|
|
37
|
+
npm run build # production build (standalone output, what the Docker image runs)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`NEXT_PUBLIC_API_BASE_URL` (in `.env`, written when the project was created) is the API address, for example
|
|
41
|
+
`http://localhost:8000/api/v1`. Every `NEXT_PUBLIC_*` value is public and is baked into the build.
|
|
42
|
+
|
|
43
|
+
## Adding your pages
|
|
44
|
+
|
|
45
|
+
Put them at the paths in `src/lib/constants/routes.ts`; the proxy, the API client and the server's emails already
|
|
46
|
+
send people there.
|
|
47
|
+
|
|
48
|
+
```tsx
|
|
49
|
+
// src/app/(auth)/login/page.tsx
|
|
50
|
+
import { LoginForm } from '@/features/auth/components/LoginForm';
|
|
51
|
+
|
|
52
|
+
export default function LoginPage() {
|
|
53
|
+
return <LoginForm />;
|
|
54
|
+
}
|
|
15
55
|
```
|
|
16
56
|
|
|
17
|
-
|
|
57
|
+
| Path | Page | Use |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| `/login` | sign in | `LoginForm`: reads `?from=` and returns there, but only to a page of this site |
|
|
60
|
+
| `/register` | sign up | `RegisterForm` |
|
|
61
|
+
| your choice | forgot password | `ForgotPasswordForm` |
|
|
62
|
+
| `/reset-password` | new password from the emailed `?token=` | `useResetPassword` |
|
|
63
|
+
| `/verify-account` | email verification (email module) | `useVerifyAccount`, `useSendVerification` |
|
|
64
|
+
| `/dashboard`, `/profile`, `/admin`, and below | signed-in areas | `useCurrentUser`, `useAuth`, the admin hooks |
|
|
65
|
+
|
|
66
|
+
The forms already show the server's "slow down" answers with the wait time (`LimitNotice`) and its field errors
|
|
67
|
+
under their fields (`applyFieldErrors`). Building your own form on `useAuth`? Do the same, as `LoginForm` does.
|
|
18
68
|
|
|
19
|
-
|
|
69
|
+
Pages that need a signed-in visitor are listed once, in `PROTECTED_PATHS` (`routes.ts`), and matched by whole path
|
|
70
|
+
segments: `/admin` covers `/admin/users`, never `/administrator`. Add your own areas there. The proxy only checks
|
|
71
|
+
that a session marker exists; the API decides what each user may see.
|
|
72
|
+
|
|
73
|
+
## How sign-in works
|
|
74
|
+
|
|
75
|
+
```text
|
|
76
|
+
sign in the API sets httpOnly cookies: access_token, refresh_token, and auth_session (a non-secret marker)
|
|
77
|
+
start-up AuthInitializer asks "who am I" (GET /auth/me), only when the auth_session marker is present;
|
|
78
|
+
anonymous visitors make no API calls at all
|
|
79
|
+
401 the API client refreshes once (parallel requests wait for that one refresh), then replays the request
|
|
80
|
+
lost race another tab refreshed first (401 REFRESH_TOKEN_ROTATED): its fresh cookies are already in the
|
|
81
|
+
browser, so the request is replayed and nobody is signed out
|
|
82
|
+
dead session the refresh is refused: the user is signed out and sent to /login
|
|
83
|
+
banned a call answers 403 ACCOUNT_DEACTIVATED: the client signs out through the logout route at once
|
|
84
|
+
```
|
|
20
85
|
|
|
21
|
-
|
|
86
|
+
Tokens never reach JavaScript. The signed-in user lives in Redux (`state.auth`); read it with `useAppSelector` or
|
|
87
|
+
`useAuth`. Server data belongs in React Query, page data in Server Components.
|
|
22
88
|
|
|
23
|
-
##
|
|
89
|
+
## Security headers
|
|
24
90
|
|
|
25
|
-
|
|
91
|
+
`src/proxy.ts` (Next 16's name for middleware) is the one place for them. Each request gets a fresh CSP nonce with
|
|
92
|
+
`strict-dynamic`; Next stamps it on its own scripts. Do not add a second CSP in `next.config.ts`. A script you add
|
|
93
|
+
inline needs the nonce from the `x-nonce` header (see `app/layout.tsx`).
|
|
26
94
|
|
|
27
|
-
|
|
28
|
-
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
|
95
|
+
## Tests
|
|
29
96
|
|
|
30
|
-
|
|
97
|
+
Unit tests sit next to the code in `__tests__/` folders: the API client's session rules, the proxy, redirect safety,
|
|
98
|
+
paths, the session marker, error parsing, the store. Keep logic in functions under `src/lib/` and test it there; a
|
|
99
|
+
test that needs `document` or `window` starts with `// @vitest-environment jsdom`. CI runs `npm run test:coverage`.
|
|
31
100
|
|
|
32
|
-
##
|
|
101
|
+
## Deploying
|
|
33
102
|
|
|
34
|
-
The
|
|
103
|
+
The `Dockerfile` builds the standalone server and runs it as a non-root user, with a health check on `/healthz`.
|
|
104
|
+
On Coolify, set `NEXT_PUBLIC_API_BASE_URL` with "Available at Buildtime" ticked: the build stops without it. The
|
|
105
|
+
full checklist is in the server's `docs/deployment.md` and the create-tigra README.
|
|
35
106
|
|
|
36
|
-
|
|
107
|
+
`AGENTS.md` in this folder has the rules for changing this code.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { describe, expect, it } from 'vitest';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Guard: focus rings show only for keyboard users. jsdom cannot evaluate `:focus-visible` or cascade layers, so this
|
|
7
|
+
* pins the wiring and the CSS (proven in a real browser on iAI, 2026-10-25); lib/input-modality.test.ts covers the
|
|
8
|
+
* mode switching itself.
|
|
9
|
+
*/
|
|
10
|
+
const src = join(__dirname, '..');
|
|
11
|
+
const read = (path: string): string => readFileSync(join(src, path), 'utf8').replace(/\r\n/g, '\n');
|
|
12
|
+
const globals = read('app/globals.css');
|
|
13
|
+
|
|
14
|
+
describe('focus rings are keyboard-only', () => {
|
|
15
|
+
it('the root layout starts in pointer mode and mounts the tracker', () => {
|
|
16
|
+
const layout = read('app/layout.tsx');
|
|
17
|
+
expect(layout).toMatch(/<html[^>]*data-input="pointer"/u);
|
|
18
|
+
expect(layout).toMatch(/<InputModalityTracker\s*\/>/u);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('Tailwind focus-visible utilities never fire in pointer mode, except on text fields', () => {
|
|
22
|
+
const variant = globals.match(/@custom-variant focus-visible \(([^\n]+)\);/u)?.[1] ?? '';
|
|
23
|
+
expect(variant).toContain('&:focus-visible');
|
|
24
|
+
expect(variant).toContain(":not([data-input='pointer'] *)");
|
|
25
|
+
for (const field of ['textarea', 'select', "[contenteditable]:not([contenteditable='false'])", 'input:not(']) {
|
|
26
|
+
expect(variant).toContain(field);
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('a global rule outside every cascade layer drops plain-CSS focus outlines in pointer mode', () => {
|
|
31
|
+
const rule = globals.match(/\nhtml\[data-input='pointer'\] :focus:not\([^{]+\{\s*outline: none !important;\s*\}/u);
|
|
32
|
+
expect(rule).not.toBeNull();
|
|
33
|
+
const before = globals.slice(0, rule!.index);
|
|
34
|
+
expect((before.match(/\{/gu) ?? []).length).toBe((before.match(/\}/gu) ?? []).length);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('keyboard focus is one style everywhere: a 1px accent edge on the element and a faint tint, never outside it', () => {
|
|
38
|
+
const rule = globals.match(/\nhtml\[data-input='keyboard'\] :focus-visible:not\(([^{]+)\) \{([^}]+)\}/u);
|
|
39
|
+
expect(rule).not.toBeNull();
|
|
40
|
+
const [, excluded, body] = rule!;
|
|
41
|
+
expect(body).toContain('outline: 1px solid var(--ring) !important;');
|
|
42
|
+
expect(body).toContain('outline-offset: -1px !important;');
|
|
43
|
+
// `transparent` first: Tailwind's build copies the FIRST colour of a color-mix() into a fallback for browsers
|
|
44
|
+
// without it; `var(--ring)` first would fill the whole control with the accent there.
|
|
45
|
+
expect(body).toMatch(/box-shadow: inset 0 0 0 100vmax color-mix\(in srgb, transparent \d+%, var\(--ring\)\) !important;/u);
|
|
46
|
+
// Menus and select options keep their highlight only; programmatic focus targets are not tab stops.
|
|
47
|
+
for (const part of ["[role='menuitem']", "[role='option']", "[tabindex='-1']", 'textarea']) expect(excluded).toContain(part);
|
|
48
|
+
const before = globals.slice(0, rule!.index);
|
|
49
|
+
expect((before.match(/\{/gu) ?? []).length).toBe((before.match(/\}/gu) ?? []).length);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('filled controls add a page-coloured line inside the edge instead of the tint', () => {
|
|
53
|
+
// The primary fill equals --ring here, so the accent edge alone would vanish on a primary button.
|
|
54
|
+
const filled = globals.match(/\nhtml\[data-input='keyboard'\] :is\(([^{]+)\):focus-visible \{([^}]+)\}/u);
|
|
55
|
+
expect(filled).not.toBeNull();
|
|
56
|
+
// Hand-styled fills count too (the welcome page's links are `bg-primary` anchors, not the UI kit's Button).
|
|
57
|
+
for (const part of ["[data-slot='button'][data-variant='default']", "[data-slot='button'][data-variant='destructive']",
|
|
58
|
+
'.bg-primary', '.bg-destructive']) {
|
|
59
|
+
expect(filled![1]).toContain(part);
|
|
60
|
+
}
|
|
61
|
+
expect(filled![2].trim()).toBe('box-shadow: inset 0 0 0 2px var(--background) !important;');
|
|
62
|
+
// Same specificity as the general rule, so it must come after it to win.
|
|
63
|
+
expect(filled!.index).toBeGreaterThan(globals.indexOf("\nhtml[data-input='keyboard'] :focus-visible:not("));
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('text fields show focus by their border turning accent, never a glow outside the field', () => {
|
|
67
|
+
// Text fields keep a focus look for mouse users too (you need to see where you type), so it follows the same
|
|
68
|
+
// "nothing outside the element" rule: accent border on focus, red border when invalid, no ring.
|
|
69
|
+
const input = read('components/ui/input.tsx');
|
|
70
|
+
expect(input).toContain('focus-visible:border-ring');
|
|
71
|
+
expect(input).toContain('aria-invalid:border-destructive');
|
|
72
|
+
expect(input).not.toMatch(/focus-visible:ring|aria-invalid:ring/u);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('a focused invalid field keeps its red border and gets a faint red tint, so focus stays visible', () => {
|
|
76
|
+
// The red border is the same with or without focus; without the old red glow, the tint is what marks focus.
|
|
77
|
+
const rule = globals.match(/\n:is\(([^{]+)\)\[aria-invalid='true'\]:focus-visible \{([^}]+)\}/u);
|
|
78
|
+
expect(rule).not.toBeNull();
|
|
79
|
+
for (const field of ['textarea', 'select', 'input:not(']) expect(rule![1]).toContain(field);
|
|
80
|
+
expect(rule![2]).toMatch(/box-shadow: inset 0 0 0 100vmax color-mix\(in srgb, transparent \d+%, var\(--destructive\)\) !important;/u);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('no UI kit component draws a ring on plain :focus (it would show on every mouse click)', () => {
|
|
84
|
+
const offenders = readdirSync(join(src, 'components/ui')).filter((file) => file.endsWith('.tsx'))
|
|
85
|
+
.filter((file) => /(^|[\s"'`])focus:(ring|outline-(?!hidden|none))/u.test(read(`components/ui/${file}`)));
|
|
86
|
+
expect(offenders).toEqual([]);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -29,6 +29,13 @@
|
|
|
29
29
|
|
|
30
30
|
@custom-variant dark (&:is(.dark *));
|
|
31
31
|
|
|
32
|
+
/* Focus rings are for keyboard users. Tailwind's own focus-visible variant is replaced so that every `focus-visible:`
|
|
33
|
+
* utility (rings, borders) stays off while the page is in pointer mode (`<html data-input>`, set by
|
|
34
|
+
* lib/input-modality.ts). Text fields keep their focus look in every mode: it shows where the visitor is typing.
|
|
35
|
+
* Static selection rings (a plain `ring-2`) are untouched; see "Focus rings" at the end of this file for plain-CSS
|
|
36
|
+
* outlines. */
|
|
37
|
+
@custom-variant focus-visible (&:focus-visible:where(:not([data-input='pointer'] *), textarea, select, [contenteditable]:not([contenteditable='false']), input:not([type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'], [type='file'], [type='color'], [type='image'])));
|
|
38
|
+
|
|
32
39
|
@theme inline {
|
|
33
40
|
--color-background: var(--background);
|
|
34
41
|
--color-foreground: var(--foreground);
|
|
@@ -105,3 +112,42 @@
|
|
|
105
112
|
min-height: var(--smooth-navigation-min-height);
|
|
106
113
|
}
|
|
107
114
|
}
|
|
115
|
+
|
|
116
|
+
/* Focus rings. Radix menus and selects move focus by script after a mouse click, and Chrome then reports
|
|
117
|
+
* `:focus-visible`, so keyboard-only rings appeared for mouse users. In pointer mode (lib/input-modality.ts) no focused
|
|
118
|
+
* element draws an outline, except text fields. Unlayered and !important on purpose: it must beat Tailwind's layered
|
|
119
|
+
* utilities and any CSS module's `:focus-visible { outline }`. Keyboard mode always shows focus (WCAG 2.4.7), in the
|
|
120
|
+
* one style defined below. */
|
|
121
|
+
html[data-input='pointer'] :focus:not(textarea, select, [contenteditable]:not([contenteditable='false']), input:not([type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'], [type='file'], [type='color'], [type='image'])) {
|
|
122
|
+
outline: none !important;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/* Keyboard focus: one style everywhere. A 1px accent line drawn exactly on the element's edge (it covers a 1px border,
|
|
126
|
+
* or hugs a borderless edge) and a faint accent tint painted under the content (an inset shadow, so backgrounds and
|
|
127
|
+
* images stay). Nothing grows outside the element. Replaces the browser's default ring and the UI kit's
|
|
128
|
+
* `focus-visible:ring-*` rings while the keyboard is in use.
|
|
129
|
+
* Not here: text fields (their border turns accent, components/ui/input.tsx), menu items and select options (their highlight is the focus), and
|
|
130
|
+
* focus targets that are not tab stops (tabindex -1: a main region after a skip link, menus, dialogs).
|
|
131
|
+
* `transparent` comes first in the color-mix() on purpose: Tailwind's build copies the first colour into a fallback for
|
|
132
|
+
* browsers without color-mix(), so those get no tint (just the edge) instead of a control filled with the accent. */
|
|
133
|
+
html[data-input='keyboard'] :focus-visible:not(textarea, select, [contenteditable]:not([contenteditable='false']), input:not([type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'], [type='file'], [type='color'], [type='image']), [role='menuitem'], [role='menuitemcheckbox'], [role='menuitemradio'], [role='option'], [tabindex='-1']) {
|
|
134
|
+
outline: 1px solid var(--ring) !important;
|
|
135
|
+
outline-offset: -1px !important;
|
|
136
|
+
box-shadow: inset 0 0 0 100vmax color-mix(in srgb, transparent 92%, var(--ring)) !important;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/* Filled controls (primary and destructive buttons, hand-styled `bg-primary` / `bg-destructive` links and buttons;
|
|
140
|
+
* shadcn checkboxes and switches once added): the primary fill is the ring colour, so the edge alone would vanish, and
|
|
141
|
+
* a tint does not show on a strong fill. They keep the edge above and get a 1px page-coloured line just inside it,
|
|
142
|
+
* which reads on any fill. Same specificity as the rule above, so it must stay after it. */
|
|
143
|
+
html[data-input='keyboard'] :is([data-slot='button'][data-variant='default'], [data-slot='button'][data-variant='destructive'], .bg-primary, .bg-destructive, [data-slot='checkbox'][data-state='checked'], [data-slot='switch'][data-state='checked']):focus-visible {
|
|
144
|
+
box-shadow: inset 0 0 0 2px var(--background) !important;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/* Text fields show focus on their own border (accent, components/ui/input.tsx), for mouse and keyboard alike. An
|
|
148
|
+
* invalid field's border stays red with or without focus, so a focused one also gets a faint red tint inside;
|
|
149
|
+
* otherwise a keyboard user could not see which field with an error they are in. `transparent` first for the same
|
|
150
|
+
* fallback reason as above. */
|
|
151
|
+
:is(textarea, select, input:not([type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'], [type='file'], [type='color'], [type='image']))[aria-invalid='true']:focus-visible {
|
|
152
|
+
box-shadow: inset 0 0 0 100vmax color-mix(in srgb, transparent 92%, var(--destructive)) !important;
|
|
153
|
+
}
|