create-tigra 3.3.0 → 4.0.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/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +72 -10
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +44 -13
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +81 -0
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -270
- package/template/server/.env.example.production +283 -242
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +176 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +0 -3
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -346
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -182
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +98 -7
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +38 -2
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/auth.ts +39 -10
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +53 -14
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -221
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +127 -41
- package/template/server/src/libs/observability/sentry.ts +1 -1
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +27 -1
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +94 -84
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +49 -10
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +66 -4
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +44 -44
- package/template/server/src/modules/auth/auth.schemas.ts +4 -2
- package/template/server/src/modules/auth/auth.service.ts +167 -96
- package/template/server/src/modules/auth/session.repo.ts +12 -0
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +23 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +3 -10
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -5,6 +5,13 @@ export type UserRole = 'USER' | 'ADMIN';
|
|
|
5
5
|
export interface JwtPayload {
|
|
6
6
|
userId: string;
|
|
7
7
|
role: UserRole;
|
|
8
|
+
/**
|
|
9
|
+
* The login session this access token belongs to. authenticate() rejects the
|
|
10
|
+
* token as soon as that session is gone (logout, logout-all, password change
|
|
11
|
+
* or reset, admin revoke), instead of letting it live until it expires.
|
|
12
|
+
* Tokens signed before this field existed lack it and are rejected.
|
|
13
|
+
*/
|
|
14
|
+
sessionId: string;
|
|
8
15
|
}
|
|
9
16
|
|
|
10
17
|
declare module '@fastify/jwt' {
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The integration-test service rules (../integration-services.ts): which mode
|
|
3
|
+
* runs, and the guards that keep the tests (which drop every table and flush
|
|
4
|
+
* Redis) away from a database that could hold real data. No URL may appear in
|
|
5
|
+
* an error: it carries a password.
|
|
6
|
+
*/
|
|
7
|
+
import { describe, expect, it } from 'vitest';
|
|
8
|
+
import { databaseName, pickIntegrationMode, redisDatabaseIndex } from '../integration-services.js';
|
|
9
|
+
|
|
10
|
+
const DB = 'mysql://tester:s3cret-pw@127.0.0.1:3306/app_test';
|
|
11
|
+
const REDIS = 'redis://:r3dis-pw@127.0.0.1:6379/15';
|
|
12
|
+
|
|
13
|
+
describe('pickIntegrationMode', () => {
|
|
14
|
+
it('neither variable → Testcontainers', () => {
|
|
15
|
+
expect(pickIntegrationMode({})).toEqual({ kind: 'containers' });
|
|
16
|
+
expect(pickIntegrationMode({ INTEGRATION_DATABASE_URL: ' ', INTEGRATION_REDIS_URL: '' })).toEqual({ kind: 'containers' });
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('both variables, disposable → external services', () => {
|
|
20
|
+
expect(pickIntegrationMode({ INTEGRATION_DATABASE_URL: DB, INTEGRATION_REDIS_URL: REDIS })).toEqual({
|
|
21
|
+
kind: 'external',
|
|
22
|
+
databaseUrl: DB,
|
|
23
|
+
redisUrl: REDIS,
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('only one of the two → refused, not a silent fallback to containers', () => {
|
|
28
|
+
expect(() => pickIntegrationMode({ INTEGRATION_DATABASE_URL: DB })).toThrow(/both/);
|
|
29
|
+
expect(() => pickIntegrationMode({ INTEGRATION_REDIS_URL: REDIS })).toThrow(/both/);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it.each([
|
|
33
|
+
['a database not ending in _test', 'mysql://u:s3cret-pw@127.0.0.1:3306/app', REDIS, /_test/],
|
|
34
|
+
['a database named test but not ending in _test', 'mysql://u:s3cret-pw@127.0.0.1:3306/test_app', REDIS, /_test/],
|
|
35
|
+
['no database name', 'mysql://u:s3cret-pw@127.0.0.1:3306', REDIS, /_test/],
|
|
36
|
+
['a malformed database URL', 'not a url', REDIS, /_test/],
|
|
37
|
+
['Redis database 0', DB, 'redis://:r3dis-pw@127.0.0.1:6379/0', /1 to 15/],
|
|
38
|
+
['Redis without a database number', DB, 'redis://:r3dis-pw@127.0.0.1:6379', /1 to 15/],
|
|
39
|
+
['Redis database 16', DB, 'redis://:r3dis-pw@127.0.0.1:6379/16', /1 to 15/],
|
|
40
|
+
])('refuses %s, and the message never holds the URL or its password', (_label, databaseUrl, redisUrl, rule) => {
|
|
41
|
+
let message = '';
|
|
42
|
+
try {
|
|
43
|
+
pickIntegrationMode({ INTEGRATION_DATABASE_URL: databaseUrl, INTEGRATION_REDIS_URL: redisUrl });
|
|
44
|
+
} catch (error) {
|
|
45
|
+
message = (error as Error).message;
|
|
46
|
+
}
|
|
47
|
+
expect(message).toMatch(rule);
|
|
48
|
+
for (const secret of ['s3cret-pw', 'r3dis-pw', '127.0.0.1', databaseUrl, redisUrl]) {
|
|
49
|
+
expect(message).not.toContain(secret);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
describe('URL parts', () => {
|
|
55
|
+
it('databaseName decodes the path, empty when missing', () => {
|
|
56
|
+
expect(databaseName('mysql://u:p@h:3306/my%5Fapp_test')).toBe('my_app_test');
|
|
57
|
+
expect(databaseName('mysql://u:p@h:3306/')).toBe('');
|
|
58
|
+
expect(databaseName('::')).toBe('');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('redisDatabaseIndex reads the number, null otherwise', () => {
|
|
62
|
+
expect(redisDatabaseIndex('redis://h:6379/7')).toBe(7);
|
|
63
|
+
expect(redisDatabaseIndex('redis://h:6379/x')).toBeNull();
|
|
64
|
+
expect(redisDatabaseIndex('redis://h:6379')).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helpers for the `*.integration.test.ts` files: boot the real app,
|
|
3
|
+
* sign users in, carry their cookies between requests, read the database and
|
|
4
|
+
* Redis, and catch emails in an in-process stand-in for Resend.
|
|
5
|
+
*
|
|
6
|
+
* Everything that touches the app, Prisma or Redis is imported lazily (inside
|
|
7
|
+
* the functions), never at the top: env.ts must not load before
|
|
8
|
+
* src/test/integration.setup.ts has set the environment, and a test file may
|
|
9
|
+
* still change process.env (rate limits on, an email stub) before its first
|
|
10
|
+
* buildTestApp().
|
|
11
|
+
*/
|
|
12
|
+
import http from 'node:http';
|
|
13
|
+
import type { AddressInfo } from 'node:net';
|
|
14
|
+
import type { FastifyInstance, LightMyRequestResponse, RouteOptions, onRequestHookHandler } from 'fastify';
|
|
15
|
+
import type { BuildAppOptions } from '@/app.js';
|
|
16
|
+
|
|
17
|
+
/** The password every helper-made account uses. */
|
|
18
|
+
export const PASSWORD = 'Integration-Passw0rd!';
|
|
19
|
+
|
|
20
|
+
let sequence = 0;
|
|
21
|
+
/** An address no other test (or earlier run) has used. */
|
|
22
|
+
export function uniqueEmail(tag: string): string {
|
|
23
|
+
sequence += 1;
|
|
24
|
+
return `it-${Date.now().toString(36)}-${process.pid}-${sequence}-${tag}@example.test`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The real app, ready for app.inject(). Close it in afterAll.
|
|
29
|
+
*
|
|
30
|
+
* Starts like server.ts: Redis is connected first (non-fatal, as in
|
|
31
|
+
* production), so a file's very first request does not find Redis still
|
|
32
|
+
* connecting, which the Redis-dependent routes answer with 503.
|
|
33
|
+
*/
|
|
34
|
+
export async function buildTestApp(options: BuildAppOptions = {}): Promise<FastifyInstance> {
|
|
35
|
+
const { connectRedis } = await import('@/libs/redis.js');
|
|
36
|
+
await connectRedis();
|
|
37
|
+
const { buildApp } = await import('@/app.js');
|
|
38
|
+
const app = await buildApp(options);
|
|
39
|
+
await app.ready();
|
|
40
|
+
return app;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** "METHOD /path/:param", the way a route is registered (prefix included). */
|
|
44
|
+
type RouteKey = string;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Which registered routes a test file actually called. Pass `onRoute` to
|
|
48
|
+
* buildTestApp(); then `uncalled(elsewhere)` lists every route that was
|
|
49
|
+
* registered but never reached by a request in this file, minus the routes
|
|
50
|
+
* another file tests (`elsewhere`, keyed like "GET /api/v1/live").
|
|
51
|
+
*
|
|
52
|
+
* A route counts as called once a request reaches its own hooks, whatever the
|
|
53
|
+
* answer (a 401 or 422 counts too). The hit is recorded by an onRequest hook put
|
|
54
|
+
* first on each route as it registers, so it runs before the route's sign-in
|
|
55
|
+
* and role checks; a request the app-wide hooks stop earlier (an IP block, a
|
|
56
|
+
* cross-site origin, a rate limit) does not count. HEAD and OPTIONS are skipped:
|
|
57
|
+
* Fastify adds a HEAD twin to every GET and CORS answers OPTIONS for every path,
|
|
58
|
+
* so neither is a route anyone wrote.
|
|
59
|
+
*/
|
|
60
|
+
export function routeCoverage(): {
|
|
61
|
+
onRoute: (route: RouteOptions) => void;
|
|
62
|
+
uncalled: (elsewhere?: Record<RouteKey, string>) => RouteKey[];
|
|
63
|
+
} {
|
|
64
|
+
const registered = new Set<RouteKey>();
|
|
65
|
+
const called = new Set<RouteKey>();
|
|
66
|
+
return {
|
|
67
|
+
onRoute(route): void {
|
|
68
|
+
const methods = (Array.isArray(route.method) ? route.method : [route.method]).filter(
|
|
69
|
+
(m) => m !== 'HEAD' && m !== 'OPTIONS',
|
|
70
|
+
);
|
|
71
|
+
if (methods.length === 0) return;
|
|
72
|
+
for (const m of methods) registered.add(`${m} ${route.url}`);
|
|
73
|
+
const record: onRequestHookHandler = (request, _reply, done) => {
|
|
74
|
+
called.add(`${request.method} ${route.url}`);
|
|
75
|
+
done();
|
|
76
|
+
};
|
|
77
|
+
// Keep the route's own onRequest hooks (none, one, or a list) and run ours first.
|
|
78
|
+
const own = route.onRequest;
|
|
79
|
+
route.onRequest = own === undefined ? [record] : [record, ...(Array.isArray(own) ? own : [own])];
|
|
80
|
+
},
|
|
81
|
+
uncalled(elsewhere = {}): RouteKey[] {
|
|
82
|
+
return [...registered].filter((key) => !called.has(key) && !(key in elsewhere)).sort();
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The app's Prisma client (lazy, see the file header). */
|
|
88
|
+
export async function db(): Promise<typeof import('@/libs/prisma.js')['prisma']> {
|
|
89
|
+
return (await import('@/libs/prisma.js')).prisma;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The app's Redis connection (lazy, see the file header). */
|
|
93
|
+
export async function redis(): Promise<ReturnType<typeof import('@/libs/redis.js')['getRedis']>> {
|
|
94
|
+
return (await import('@/libs/redis.js')).getRedis();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const setCookiesOf = (res: LightMyRequestResponse): string[] => ([] as string[]).concat(res.headers['set-cookie'] ?? []);
|
|
98
|
+
|
|
99
|
+
/** Whether the response tells the browser to delete at least one cookie. */
|
|
100
|
+
export function clearsCookies(res: LightMyRequestResponse): boolean {
|
|
101
|
+
return setCookiesOf(res).some((c) => /max-age=0/i.test(c) || /expires=thu, 01 jan 1970/i.test(c));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The cookies of one browser ("device"): absorbs Set-Cookie, sends them back. */
|
|
105
|
+
export class CookieJar {
|
|
106
|
+
private readonly cookies = new Map<string, string>();
|
|
107
|
+
|
|
108
|
+
absorb(res: LightMyRequestResponse): this {
|
|
109
|
+
for (const header of setCookiesOf(res)) {
|
|
110
|
+
const [pair, ...attributes] = header.split(';');
|
|
111
|
+
const eq = pair.indexOf('=');
|
|
112
|
+
const name = pair.slice(0, eq).trim();
|
|
113
|
+
const value = pair.slice(eq + 1).trim();
|
|
114
|
+
const expired = attributes.some((a) => /max-age=0/i.test(a) || /expires=thu, 01 jan 1970/i.test(a));
|
|
115
|
+
if (expired || value === '') this.cookies.delete(name);
|
|
116
|
+
else this.cookies.set(name, value);
|
|
117
|
+
}
|
|
118
|
+
return this;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
get(name: string): string | undefined {
|
|
122
|
+
return this.cookies.get(name);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The Cookie header for a request. */
|
|
126
|
+
header(): string {
|
|
127
|
+
return [...this.cookies].map(([k, v]) => `${k}=${v}`).join('; ');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A second jar holding the same cookies (two tabs, or a stolen copy). */
|
|
131
|
+
copy(): CookieJar {
|
|
132
|
+
const jar = new CookieJar();
|
|
133
|
+
for (const [k, v] of this.cookies) jar.cookies.set(k, v);
|
|
134
|
+
return jar;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface CallOptions {
|
|
139
|
+
/** Sends this jar's cookies and keeps what the answer sets. */
|
|
140
|
+
jar?: CookieJar;
|
|
141
|
+
/** A raw Cookie header instead of a jar (it is not updated). */
|
|
142
|
+
cookie?: string;
|
|
143
|
+
payload?: unknown;
|
|
144
|
+
headers?: Record<string, string>;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface CallResult {
|
|
148
|
+
res: LightMyRequestResponse;
|
|
149
|
+
status: number;
|
|
150
|
+
/** error.code of an error answer. */
|
|
151
|
+
code: string | undefined;
|
|
152
|
+
body: { success?: boolean; data?: any; error?: { code?: string; fields?: { field: string }[] } } | null; // eslint-disable-line @typescript-eslint/no-explicit-any
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** One request through app.inject(), answered as { status, code, body }. */
|
|
156
|
+
export async function call(
|
|
157
|
+
app: FastifyInstance,
|
|
158
|
+
method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE',
|
|
159
|
+
url: string,
|
|
160
|
+
options: CallOptions = {},
|
|
161
|
+
): Promise<CallResult> {
|
|
162
|
+
const headers: Record<string, string> = { ...options.headers };
|
|
163
|
+
const cookie = options.cookie ?? options.jar?.header();
|
|
164
|
+
if (cookie) headers.cookie = cookie;
|
|
165
|
+
const res = await app.inject({
|
|
166
|
+
method,
|
|
167
|
+
url: url.startsWith('/api/') || url.startsWith('/uploads/') ? url : `/api/v1${url}`,
|
|
168
|
+
headers,
|
|
169
|
+
...(options.payload === undefined ? {} : { payload: options.payload as string | object }),
|
|
170
|
+
});
|
|
171
|
+
options.jar?.absorb(res);
|
|
172
|
+
let body: CallResult['body'] = null;
|
|
173
|
+
try {
|
|
174
|
+
body = res.json();
|
|
175
|
+
} catch {
|
|
176
|
+
// not JSON (a file, an empty body)
|
|
177
|
+
}
|
|
178
|
+
return { res, status: res.statusCode, code: body?.error?.code, body };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface TestUser {
|
|
182
|
+
id: string;
|
|
183
|
+
email: string;
|
|
184
|
+
/** Signed in: holds the cookies register set. */
|
|
185
|
+
jar: CookieJar;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Registers a new USER (verification is off in this suite, so register signs in). */
|
|
189
|
+
export async function registerUser(
|
|
190
|
+
app: FastifyInstance,
|
|
191
|
+
tag: string,
|
|
192
|
+
names: { firstName?: string; lastName?: string } = {},
|
|
193
|
+
): Promise<TestUser> {
|
|
194
|
+
const email = uniqueEmail(tag);
|
|
195
|
+
const jar = new CookieJar();
|
|
196
|
+
const r = await call(app, 'POST', '/auth/register', {
|
|
197
|
+
jar,
|
|
198
|
+
payload: { email, password: PASSWORD, firstName: names.firstName ?? 'Test', lastName: names.lastName ?? 'User' },
|
|
199
|
+
});
|
|
200
|
+
if (r.status !== 201) throw new Error(`register ${tag}: ${r.status} ${r.code}`);
|
|
201
|
+
return { id: r.body?.data?.user?.id as string, email, jar };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Signs in again (a new device): a fresh jar. */
|
|
205
|
+
export async function signIn(app: FastifyInstance, email: string, password = PASSWORD): Promise<CookieJar> {
|
|
206
|
+
const jar = new CookieJar();
|
|
207
|
+
const r = await call(app, 'POST', '/auth/login', { jar, payload: { email, password } });
|
|
208
|
+
if (r.status !== 200) throw new Error(`login: ${r.status} ${r.code}`);
|
|
209
|
+
return jar;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Makes an account ADMIN (and verified) in the database; the role is read on every request. */
|
|
213
|
+
export async function makeAdmin(userId: string): Promise<void> {
|
|
214
|
+
await (await db()).user.update({ where: { id: userId }, data: { role: 'ADMIN', emailVerifiedAt: new Date() } });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A registered user turned ADMIN, still signed in. */
|
|
218
|
+
export async function registerAdmin(app: FastifyInstance, tag: string): Promise<TestUser> {
|
|
219
|
+
const user = await registerUser(app, tag);
|
|
220
|
+
await makeAdmin(user.id);
|
|
221
|
+
return user;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** A small image of the given format, made by sharp. */
|
|
225
|
+
export async function image(
|
|
226
|
+
format: 'jpeg' | 'png' | 'webp' | 'avif',
|
|
227
|
+
width = 64,
|
|
228
|
+
height = 48,
|
|
229
|
+
): Promise<Buffer> {
|
|
230
|
+
const sharp = (await import('sharp')).default;
|
|
231
|
+
return sharp({ create: { width, height, channels: 3, background: '#3a7bd5' } })[format]().toBuffer();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** A multipart body with one file field named "file", for app.inject(). */
|
|
235
|
+
export function multipartFile(
|
|
236
|
+
bytes: Buffer,
|
|
237
|
+
{ filename = 'blob', type = 'application/octet-stream' }: { filename?: string; type?: string } = {},
|
|
238
|
+
): { payload: Buffer; headers: Record<string, string> } {
|
|
239
|
+
const boundary = `----integration${Date.now().toString(16)}`;
|
|
240
|
+
const head = Buffer.from(
|
|
241
|
+
`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${filename}"\r\nContent-Type: ${type}\r\n\r\n`,
|
|
242
|
+
);
|
|
243
|
+
const tail = Buffer.from(`\r\n--${boundary}--\r\n`);
|
|
244
|
+
return { payload: Buffer.concat([head, bytes, tail]), headers: { 'content-type': `multipart/form-data; boundary=${boundary}` } };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Uploads bytes as the signed-in user's avatar (or another path). */
|
|
248
|
+
export async function uploadAvatar(
|
|
249
|
+
app: FastifyInstance,
|
|
250
|
+
jar: CookieJar,
|
|
251
|
+
bytes: Buffer,
|
|
252
|
+
options: { filename?: string; type?: string; url?: string } = {},
|
|
253
|
+
): Promise<CallResult> {
|
|
254
|
+
const { payload, headers } = multipartFile(bytes, options);
|
|
255
|
+
return call(app, 'POST', options.url ?? '/users/avatar', { jar, payload, headers });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** An email the stub received. `link` is the first verify/reset link in it. */
|
|
259
|
+
export interface CaughtEmail {
|
|
260
|
+
to: string;
|
|
261
|
+
subject: string;
|
|
262
|
+
html: string;
|
|
263
|
+
link: string | null;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export interface EmailStub {
|
|
267
|
+
sent: CaughtEmail[];
|
|
268
|
+
/** The emails sent to one address, newest last. */
|
|
269
|
+
to(address: string): CaughtEmail[];
|
|
270
|
+
/**
|
|
271
|
+
* Waits (up to 5 s) until `count` emails to the address match, for emails
|
|
272
|
+
* the app sends after it has answered (the verification email on register).
|
|
273
|
+
*/
|
|
274
|
+
waitFor(address: string, match?: (email: CaughtEmail) => boolean, count?: number): Promise<CaughtEmail[]>;
|
|
275
|
+
/** How later sends are answered: after `delayMs`, with `status` (default 200 after 0 ms). */
|
|
276
|
+
respond(how: { delayMs?: number; status?: number }): void;
|
|
277
|
+
close(): Promise<void>;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* A local stand-in for the Resend API: every send is recorded and answered
|
|
282
|
+
* like Resend does, so tests read the links the app emails without sending
|
|
283
|
+
* anything. Sets RESEND_API_KEY and RESEND_BASE_URL (read by the Resend SDK
|
|
284
|
+
* when it loads), so call it BEFORE buildTestApp() in that file.
|
|
285
|
+
*/
|
|
286
|
+
export async function startEmailStub(): Promise<EmailStub> {
|
|
287
|
+
const sent: CaughtEmail[] = [];
|
|
288
|
+
let answer = { delayMs: 0, status: 200 };
|
|
289
|
+
const server = http.createServer((req, res) => {
|
|
290
|
+
let raw = '';
|
|
291
|
+
req.on('data', (chunk: Buffer) => (raw += chunk.toString('utf8')));
|
|
292
|
+
req.on('end', () => {
|
|
293
|
+
let body: { to?: string | string[]; subject?: string; html?: string } = {};
|
|
294
|
+
try {
|
|
295
|
+
body = JSON.parse(raw);
|
|
296
|
+
} catch {
|
|
297
|
+
// not JSON
|
|
298
|
+
}
|
|
299
|
+
const html = String(body.html ?? '');
|
|
300
|
+
sent.push({
|
|
301
|
+
to: Array.isArray(body.to) ? body.to.join(',') : String(body.to ?? ''),
|
|
302
|
+
subject: String(body.subject ?? ''),
|
|
303
|
+
html,
|
|
304
|
+
link: /href="([^"]*(?:verify-account|reset-password)\?token=[^"]+)"/.exec(html)?.[1] ?? null,
|
|
305
|
+
});
|
|
306
|
+
const { delayMs, status } = answer;
|
|
307
|
+
const reply = (): void => {
|
|
308
|
+
if (res.destroyed) return; // the app gave up waiting
|
|
309
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
310
|
+
res.end(JSON.stringify(status === 200 ? { id: `stub_${sent.length}` } : { name: 'application_error', message: 'stub failure' }));
|
|
311
|
+
};
|
|
312
|
+
if (delayMs > 0) setTimeout(reply, delayMs).unref();
|
|
313
|
+
else reply();
|
|
314
|
+
});
|
|
315
|
+
});
|
|
316
|
+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
317
|
+
process.env.RESEND_API_KEY = 're_integration_stub_key';
|
|
318
|
+
process.env.RESEND_BASE_URL = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
319
|
+
return {
|
|
320
|
+
sent,
|
|
321
|
+
to: (address) => sent.filter((e) => e.to.includes(address)),
|
|
322
|
+
waitFor: async (address, match = (): boolean => true, count = 1): Promise<CaughtEmail[]> => {
|
|
323
|
+
const found = (): CaughtEmail[] => sent.filter((e) => e.to.includes(address) && match(e));
|
|
324
|
+
for (let waited = 0; found().length < count && waited < 5_000; waited += 50) {
|
|
325
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
326
|
+
}
|
|
327
|
+
return found();
|
|
328
|
+
},
|
|
329
|
+
respond: ({ delayMs = 0, status = 200 }): void => {
|
|
330
|
+
answer = { delayMs, status };
|
|
331
|
+
},
|
|
332
|
+
close: (): Promise<void> => {
|
|
333
|
+
server.closeAllConnections();
|
|
334
|
+
return new Promise<void>((resolve) => server.close(() => resolve()));
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** The token in an emailed link. */
|
|
340
|
+
export function tokenOf(link: string | null): string {
|
|
341
|
+
if (!link) throw new Error('no link in the email');
|
|
342
|
+
return new URL(link).searchParams.get('token') ?? '';
|
|
343
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the integration tests get MySQL and Redis from, and the guards that
|
|
3
|
+
* keep them away from real data. Pure (no I/O), so the rules are unit-tested
|
|
4
|
+
* (src/test/__tests__/integration-services.test.ts); integration.setup.ts
|
|
5
|
+
* applies them.
|
|
6
|
+
*
|
|
7
|
+
* Two modes:
|
|
8
|
+
* - "containers" (neither variable set): Testcontainers starts a throwaway
|
|
9
|
+
* MySQL and Redis. What CI uses; needs Docker.
|
|
10
|
+
* - "external" (both set): INTEGRATION_DATABASE_URL and INTEGRATION_REDIS_URL
|
|
11
|
+
* point at services that already run, for machines where starting
|
|
12
|
+
* containers is not wanted. The tests DROP every table in that database and
|
|
13
|
+
* FLUSH that Redis database, so both must be visibly disposable: the
|
|
14
|
+
* database name ends in "_test" and the Redis URL names a database 1-15.
|
|
15
|
+
*
|
|
16
|
+
* Error messages name the rule and never the URL: it carries a password.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export type IntegrationMode =
|
|
20
|
+
| { kind: 'containers' }
|
|
21
|
+
| { kind: 'external'; databaseUrl: string; redisUrl: string };
|
|
22
|
+
|
|
23
|
+
/** The database name in a mysql:// URL, decoded; '' when there is none or the URL is malformed. */
|
|
24
|
+
export function databaseName(url: string): string {
|
|
25
|
+
try {
|
|
26
|
+
return decodeURIComponent(new URL(url).pathname.replace(/^\//, ''));
|
|
27
|
+
} catch {
|
|
28
|
+
return '';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The Redis database number in a redis:// URL path (redis://host:6379/15), or null when missing or not a number. */
|
|
33
|
+
export function redisDatabaseIndex(url: string): number | null {
|
|
34
|
+
try {
|
|
35
|
+
const path = new URL(url).pathname.replace(/^\//, '');
|
|
36
|
+
return /^\d+$/.test(path) ? Number(path) : null;
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Picks the mode from the environment. One variable without the other is a
|
|
44
|
+
* mistake (half a setup), so it is refused instead of silently falling back to
|
|
45
|
+
* containers.
|
|
46
|
+
*/
|
|
47
|
+
export function pickIntegrationMode(env: NodeJS.ProcessEnv): IntegrationMode {
|
|
48
|
+
const databaseUrl = env.INTEGRATION_DATABASE_URL?.trim() || undefined;
|
|
49
|
+
const redisUrl = env.INTEGRATION_REDIS_URL?.trim() || undefined;
|
|
50
|
+
if (!databaseUrl && !redisUrl) return { kind: 'containers' };
|
|
51
|
+
if (!databaseUrl || !redisUrl) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
'Set both INTEGRATION_DATABASE_URL and INTEGRATION_REDIS_URL to use existing services, or neither to use Testcontainers.',
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
assertDisposable(databaseUrl, redisUrl);
|
|
57
|
+
return { kind: 'external', databaseUrl, redisUrl };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Refuses services that could hold real data, before anything connects to them. */
|
|
61
|
+
export function assertDisposable(databaseUrl: string, redisUrl: string): void {
|
|
62
|
+
if (!databaseName(databaseUrl).endsWith('_test')) {
|
|
63
|
+
throw new Error(
|
|
64
|
+
'INTEGRATION_DATABASE_URL must name a database ending in "_test": the integration tests drop every table in it.',
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
const index = redisDatabaseIndex(redisUrl);
|
|
68
|
+
if (index === null || index < 1 || index > 15) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
'INTEGRATION_REDIS_URL must end with a Redis database number from 1 to 15 (for example redis://localhost:6379/15): ' +
|
|
71
|
+
'the integration tests flush that database, and database 0 (the default) is refused.',
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration tests, once per run: get MySQL and Redis ready and hand their
|
|
3
|
+
* addresses to every test file (vitest.integration.config.ts → globalSetup).
|
|
4
|
+
* Runs in Vitest's main process before any test file; each file then reads
|
|
5
|
+
* the addresses with `inject('integration')` (src/test/integration.setup.ts).
|
|
6
|
+
*
|
|
7
|
+
* ── Where MySQL and Redis come from (rules in ./integration-services.ts) ───
|
|
8
|
+
* - Neither INTEGRATION_DATABASE_URL nor INTEGRATION_REDIS_URL set:
|
|
9
|
+
* Testcontainers starts a throwaway MySQL 8.4 and Redis 7. This is what CI
|
|
10
|
+
* does; it needs Docker.
|
|
11
|
+
* - Both set: those already-running services are used and no container is
|
|
12
|
+
* started. Every table in that database is dropped and that Redis database
|
|
13
|
+
* is flushed first, so the database name must end in "_test" and the Redis
|
|
14
|
+
* URL must name a database 1-15; anything else stops the run before it
|
|
15
|
+
* connects.
|
|
16
|
+
*
|
|
17
|
+
* ── The schema comes from the shipped migrations ───────────────────────────
|
|
18
|
+
* `prisma migrate deploy` applies prisma/migrations, exactly what the
|
|
19
|
+
* production container runs at start, so a migration that does not match the
|
|
20
|
+
* code fails here. (It used to be `prisma db push`, which tested the schema
|
|
21
|
+
* file but never the migrations a project actually ships.) The tables are
|
|
22
|
+
* dropped by emptyDatabase below, not by `prisma migrate reset`: Prisma
|
|
23
|
+
* refuses that command when an AI agent runs it, and agents run these tests.
|
|
24
|
+
*
|
|
25
|
+
* All test files share this one database and Redis, so each test creates its
|
|
26
|
+
* own uniquely named data, and the files run one after another.
|
|
27
|
+
*/
|
|
28
|
+
import { execSync } from 'node:child_process';
|
|
29
|
+
import { fileURLToPath } from 'node:url';
|
|
30
|
+
import path from 'node:path';
|
|
31
|
+
import os from 'node:os';
|
|
32
|
+
import { Redis } from 'ioredis';
|
|
33
|
+
import type { TestProject } from 'vitest/node';
|
|
34
|
+
import { pickIntegrationMode } from './integration-services.js';
|
|
35
|
+
|
|
36
|
+
/** What every integration test file receives (see integration.setup.ts). */
|
|
37
|
+
export interface IntegrationContext {
|
|
38
|
+
mode: 'containers' | 'external';
|
|
39
|
+
databaseUrl: string;
|
|
40
|
+
redisUrl: string;
|
|
41
|
+
uploadPublicDir: string;
|
|
42
|
+
uploadPrivateDir: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
declare module 'vitest' {
|
|
46
|
+
export interface ProvidedContext {
|
|
47
|
+
integration: IntegrationContext;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
52
|
+
|
|
53
|
+
/** Starts a throwaway MySQL and Redis. Imported lazily so the external mode never loads Docker code. */
|
|
54
|
+
async function startContainers(): Promise<{ databaseUrl: string; redisUrl: string; stop: () => Promise<void> }> {
|
|
55
|
+
const [{ MySqlContainer }, { RedisContainer }] = await Promise.all([
|
|
56
|
+
import('@testcontainers/mysql'),
|
|
57
|
+
import('@testcontainers/redis'),
|
|
58
|
+
]);
|
|
59
|
+
const mysql = await new MySqlContainer('mysql:8.4')
|
|
60
|
+
.withDatabase('test_db')
|
|
61
|
+
.withUsername('test')
|
|
62
|
+
.withUserPassword('test')
|
|
63
|
+
.withRootPassword('rootpass')
|
|
64
|
+
.start();
|
|
65
|
+
const redis = await new RedisContainer('redis:7-alpine').start();
|
|
66
|
+
return {
|
|
67
|
+
// MySqlContainer.getConnectionUri() returns `mysql://user:pass@host:port/db`
|
|
68
|
+
// — exactly Prisma's DATABASE_URL shape.
|
|
69
|
+
databaseUrl: mysql.getConnectionUri(),
|
|
70
|
+
redisUrl: redis.getConnectionUrl(),
|
|
71
|
+
stop: async (): Promise<void> => {
|
|
72
|
+
await Promise.allSettled([redis.stop(), mysql.stop()]);
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Drops every table in the guarded database, `_prisma_migrations` included,
|
|
79
|
+
* so migrate deploy starts from nothing. The interactive transaction pins one
|
|
80
|
+
* connection, which the session-level FOREIGN_KEY_CHECKS switch needs.
|
|
81
|
+
*/
|
|
82
|
+
async function emptyDatabase(databaseUrl: string): Promise<void> {
|
|
83
|
+
const { PrismaClient } = await import('@prisma/client');
|
|
84
|
+
const client = new PrismaClient({ datasourceUrl: databaseUrl });
|
|
85
|
+
try {
|
|
86
|
+
await client.$transaction(async (tx) => {
|
|
87
|
+
const tables = await tx.$queryRaw<{ name: string }[]>`
|
|
88
|
+
SELECT TABLE_NAME AS name FROM information_schema.TABLES
|
|
89
|
+
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'`;
|
|
90
|
+
if (tables.length === 0) return;
|
|
91
|
+
const list = tables.map(({ name }) => `\`${name.replace(/`/g, '``')}\``).join(', ');
|
|
92
|
+
await tx.$executeRawUnsafe('SET FOREIGN_KEY_CHECKS = 0');
|
|
93
|
+
await tx.$executeRawUnsafe(`DROP TABLE ${list}`);
|
|
94
|
+
await tx.$executeRawUnsafe('SET FOREIGN_KEY_CHECKS = 1');
|
|
95
|
+
});
|
|
96
|
+
} finally {
|
|
97
|
+
await client.$disconnect();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Empties the guarded Redis database. */
|
|
102
|
+
async function flushRedis(redisUrl: string): Promise<void> {
|
|
103
|
+
const redis = new Redis(redisUrl, { lazyConnect: true, maxRetriesPerRequest: 1 });
|
|
104
|
+
try {
|
|
105
|
+
await redis.connect();
|
|
106
|
+
await redis.flushdb();
|
|
107
|
+
} finally {
|
|
108
|
+
redis.disconnect();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export default async function setup(project: TestProject): Promise<() => Promise<void>> {
|
|
113
|
+
// Throws (with the rule, never the URL) on half a setup or services that do
|
|
114
|
+
// not look disposable, before anything connects.
|
|
115
|
+
const mode = pickIntegrationMode(process.env);
|
|
116
|
+
const services =
|
|
117
|
+
mode.kind === 'external'
|
|
118
|
+
? { databaseUrl: mode.databaseUrl, redisUrl: mode.redisUrl, stop: async (): Promise<void> => {} }
|
|
119
|
+
: await startContainers();
|
|
120
|
+
|
|
121
|
+
if (mode.kind === 'external') {
|
|
122
|
+
await emptyDatabase(services.databaseUrl);
|
|
123
|
+
await flushRedis(services.redisUrl);
|
|
124
|
+
}
|
|
125
|
+
// Prisma prints the host and database name, never the password.
|
|
126
|
+
execSync('npx prisma migrate deploy', {
|
|
127
|
+
cwd: serverRoot,
|
|
128
|
+
env: { ...process.env, DATABASE_URL: services.databaseUrl },
|
|
129
|
+
stdio: 'inherit',
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
const uploadsRoot = path.join(os.tmpdir(), `create-tigra-uploads-${process.pid}`);
|
|
133
|
+
project.provide('integration', {
|
|
134
|
+
mode: mode.kind,
|
|
135
|
+
databaseUrl: services.databaseUrl,
|
|
136
|
+
redisUrl: services.redisUrl,
|
|
137
|
+
uploadPublicDir: path.join(uploadsRoot, 'public'),
|
|
138
|
+
uploadPrivateDir: path.join(uploadsRoot, 'private'),
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
// Teardown: stop the containers this run started; existing services keep
|
|
142
|
+
// the test data until the next run empties them.
|
|
143
|
+
return services.stop;
|
|
144
|
+
}
|