create-tigra 3.2.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 +160 -44
- 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 +81 -21
- 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 +38 -19
- 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 +18 -4
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
- 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/features/auth/types/auth.types.ts +3 -0
- package/template/client/src/instrumentation-client.ts +9 -1
- package/template/client/src/instrumentation.ts +6 -0
- 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 +71 -0
- 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 +86 -1
- 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/security.ts +37 -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 -269
- package/template/server/.env.example.production +283 -236
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +181 -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 +19 -6
- package/template/server/prisma/seed.ts +13 -5
- 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 -335
- 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 -171
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
- 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 +81 -65
- 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 +168 -0
- 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 +113 -0
- 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 +59 -0
- 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 -0
- 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/account-status.ts +52 -0
- package/template/server/src/libs/auth.ts +51 -12
- 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 +91 -24
- 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 -220
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +131 -42
- package/template/server/src/libs/observability/sentry.ts +80 -0
- 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 +108 -18
- 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 +143 -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 +104 -83
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
- 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 +56 -13
- 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 +73 -7
- 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 +332 -49
- 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 +60 -42
- package/template/server/src/modules/auth/auth.schemas.ts +5 -2
- package/template/server/src/modules/auth/auth.service.ts +197 -109
- package/template/server/src/modules/auth/session.repo.ts +12 -12
- 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 +25 -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 +23 -8
- 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
|
@@ -7,58 +7,80 @@ initSentry();
|
|
|
7
7
|
import { env } from '@config/env.js';
|
|
8
8
|
import { logger } from '@libs/logger.js';
|
|
9
9
|
import { testDatabaseConnection, disconnectPrisma } from '@libs/prisma.js';
|
|
10
|
-
import { connectRedis, disconnectRedis } from '@libs/redis.js';
|
|
10
|
+
import { connectRedis, disconnectRedis, waitForRedisReady } from '@libs/redis.js';
|
|
11
|
+
import { createShutdown } from '@libs/shutdown.js';
|
|
11
12
|
import { buildApp } from './app.js';
|
|
12
13
|
|
|
14
|
+
/** How long a production start waits for Redis before refusing (see start()). */
|
|
15
|
+
const REDIS_BOOT_WAIT_MS = 10_000;
|
|
16
|
+
|
|
13
17
|
async function start(): Promise<void> {
|
|
14
18
|
let app: Awaited<ReturnType<typeof buildApp>> | null = null;
|
|
15
|
-
let isShuttingDown = false;
|
|
16
|
-
|
|
17
|
-
// Graceful shutdown
|
|
18
|
-
const shutdown = async (signal: string): Promise<void> => {
|
|
19
|
-
if (isShuttingDown) return; // Prevent multiple shutdown attempts
|
|
20
|
-
isShuttingDown = true;
|
|
21
19
|
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
// One shutdown for every way the process ends: exit 0 after a signal, 1 after
|
|
21
|
+
// a crash or a failed start, 1 if closing takes longer than 8 s (see libs/shutdown.ts).
|
|
22
|
+
const shutdown = createShutdown({
|
|
23
|
+
close: async () => {
|
|
24
24
|
if (app) {
|
|
25
25
|
await app.close();
|
|
26
26
|
}
|
|
27
27
|
await disconnectRedis();
|
|
28
28
|
await disconnectPrisma();
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
process.exit(1);
|
|
34
|
-
}
|
|
35
|
-
};
|
|
29
|
+
},
|
|
30
|
+
exit: (code) => process.exit(code),
|
|
31
|
+
logger,
|
|
32
|
+
});
|
|
36
33
|
|
|
37
34
|
// Register signal handlers early
|
|
38
|
-
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
39
|
-
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
35
|
+
process.on('SIGINT', () => void shutdown('SIGINT'));
|
|
36
|
+
process.on('SIGTERM', () => void shutdown('SIGTERM'));
|
|
40
37
|
process.on('uncaughtException', (error) => {
|
|
41
|
-
logger.fatal(error, '[SERVER] Uncaught exception');
|
|
42
|
-
shutdown('uncaughtException');
|
|
38
|
+
logger.fatal({ err: error }, '[SERVER] Uncaught exception');
|
|
39
|
+
void shutdown('uncaughtException');
|
|
43
40
|
});
|
|
44
41
|
process.on('unhandledRejection', (reason) => {
|
|
45
|
-
|
|
46
|
-
|
|
42
|
+
// { err } even for a non-Error reason: pino would read a bare string as the message.
|
|
43
|
+
logger.fatal({ err: reason }, '[SERVER] Unhandled rejection');
|
|
44
|
+
void shutdown('unhandledRejection');
|
|
47
45
|
});
|
|
48
46
|
|
|
49
47
|
try {
|
|
50
|
-
//
|
|
48
|
+
// The database check is only logged here: the Docker CMD already ran
|
|
49
|
+
// `prisma migrate deploy`, which fails the start when the database cannot
|
|
50
|
+
// be reached.
|
|
51
51
|
await testDatabaseConnection();
|
|
52
|
-
|
|
52
|
+
|
|
53
|
+
// Redis at boot. In production an unreachable Redis stops the start (exit
|
|
54
|
+
// 1): it is almost always a wrong REDIS_URL, and the app would otherwise
|
|
55
|
+
// run with rate limits, login lockout and IP blocks silently off. On
|
|
56
|
+
// Coolify the failed container never becomes healthy, so a rolling deploy
|
|
57
|
+
// keeps the old one serving. It may be just starting too (a server
|
|
58
|
+
// reboot), hence the wait. After boot, outages stay non-fatal
|
|
59
|
+
// (libs/redis.ts). Outside production the server starts without it.
|
|
60
|
+
const redisReady = await connectRedis();
|
|
61
|
+
if (env.NODE_ENV === 'production' && !redisReady) {
|
|
62
|
+
logger.info(`[SERVER] Waiting up to ${REDIS_BOOT_WAIT_MS / 1000}s for Redis`);
|
|
63
|
+
if (!(await waitForRedisReady(REDIS_BOOT_WAIT_MS))) {
|
|
64
|
+
// Never the URL: it carries the password.
|
|
65
|
+
logger.fatal(
|
|
66
|
+
'[SERVER] Redis is not reachable at boot: production refuses to start without it ' +
|
|
67
|
+
'(rate limits, login lockout and IP blocks would be off). Check REDIS_URL.',
|
|
68
|
+
);
|
|
69
|
+
await shutdown('startup-error');
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
53
73
|
|
|
54
74
|
app = await buildApp();
|
|
55
75
|
|
|
56
76
|
await app.listen({ port: env.PORT, host: env.HOST });
|
|
57
77
|
logger.info(`[SERVER] Started on http://${env.HOST}:${env.PORT} [${env.NODE_ENV}]`);
|
|
58
78
|
} catch (error) {
|
|
59
|
-
logger.fatal(error, '[SERVER] Failed to start');
|
|
79
|
+
logger.fatal({ err: error }, '[SERVER] Failed to start');
|
|
60
80
|
await shutdown('startup-error');
|
|
61
81
|
}
|
|
62
82
|
}
|
|
63
83
|
|
|
64
|
-
start()
|
|
84
|
+
// start() handles its own failures (it logs them and exits 1 through shutdown),
|
|
85
|
+
// so nothing waits on its promise.
|
|
86
|
+
void start();
|
|
@@ -1,12 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One wrong input field in a 422 VALIDATION_FAILED answer: where it is and
|
|
3
|
+
* why it was refused. Never the submitted value (see libs/validation-errors.ts).
|
|
4
|
+
*/
|
|
5
|
+
export interface FieldError {
|
|
6
|
+
/** Path inside the request part, dot-joined ("email", "address.city"), or the part itself ("body"). */
|
|
7
|
+
field: string;
|
|
8
|
+
message: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
1
11
|
export class AppError extends Error {
|
|
2
12
|
public readonly isAppError = true;
|
|
3
13
|
public readonly code: string;
|
|
4
14
|
public readonly statusCode: number;
|
|
15
|
+
/**
|
|
16
|
+
* Whole seconds until the caller may try again (rate limits, login lock, IP
|
|
17
|
+
* auto-block). Sent in the JSON body because the client runs on another
|
|
18
|
+
* origin and CORS does not expose the Retry-After header to it.
|
|
19
|
+
*/
|
|
20
|
+
public readonly retryAfterSeconds?: number;
|
|
21
|
+
/** The wrong fields, for validation failures only (sent as `error.fields`). */
|
|
22
|
+
public readonly fields?: FieldError[];
|
|
5
23
|
|
|
6
|
-
constructor(
|
|
24
|
+
constructor(
|
|
25
|
+
code: string,
|
|
26
|
+
message: string,
|
|
27
|
+
statusCode: number,
|
|
28
|
+
retryAfterSeconds?: number,
|
|
29
|
+
fields?: FieldError[],
|
|
30
|
+
) {
|
|
7
31
|
super(message);
|
|
8
32
|
this.code = code;
|
|
9
33
|
this.statusCode = statusCode;
|
|
34
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
35
|
+
this.fields = fields;
|
|
10
36
|
this.name = this.constructor.name;
|
|
11
37
|
Error.captureStackTrace(this, this.constructor);
|
|
12
38
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AppError } from './AppError.js';
|
|
1
|
+
import { AppError, type FieldError } from './AppError.js';
|
|
2
2
|
|
|
3
3
|
export class BadRequestError extends AppError {
|
|
4
4
|
constructor(message = 'Bad request', code = 'BAD_REQUEST') {
|
|
@@ -6,9 +6,14 @@ export class BadRequestError extends AppError {
|
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* 422. With `fields` it is the one shape for wrong input (VALIDATION_FAILED,
|
|
11
|
+
* built by libs/validation-errors.ts); without, a specific check such as an
|
|
12
|
+
* upload's FILE_* or IMAGE_* code.
|
|
13
|
+
*/
|
|
9
14
|
export class ValidationError extends AppError {
|
|
10
|
-
constructor(message = 'Validation failed', code = 'VALIDATION_FAILED') {
|
|
11
|
-
super(code, message, 422);
|
|
15
|
+
constructor(message = 'Validation failed', code = 'VALIDATION_FAILED', fields?: FieldError[]) {
|
|
16
|
+
super(code, message, 422, undefined, fields);
|
|
12
17
|
}
|
|
13
18
|
}
|
|
14
19
|
|
|
@@ -19,11 +24,33 @@ export class UnauthorizedError extends AppError {
|
|
|
19
24
|
}
|
|
20
25
|
|
|
21
26
|
export class ForbiddenError extends AppError {
|
|
22
|
-
constructor(message = 'Forbidden', code = 'FORBIDDEN') {
|
|
23
|
-
super(code, message, 403);
|
|
27
|
+
constructor(message = 'Forbidden', code = 'FORBIDDEN', retryAfterSeconds?: number) {
|
|
28
|
+
super(code, message, 403, retryAfterSeconds);
|
|
24
29
|
}
|
|
25
30
|
}
|
|
26
31
|
|
|
32
|
+
/**
|
|
33
|
+
* 429 with the wait time. Codes in use: RATE_LIMIT_EXCEEDED (a route limit),
|
|
34
|
+
* LOGIN_LOCKED (too many failed sign-ins for this email + IP) and
|
|
35
|
+
* EMAIL_RATE_LIMITED (too many emails to one address). See docs/rate-limits.md.
|
|
36
|
+
*/
|
|
37
|
+
export class TooManyRequestsError extends AppError {
|
|
38
|
+
constructor(message: string, code: string, retryAfterSeconds: number) {
|
|
39
|
+
super(code, message, 429, Math.max(1, Math.ceil(retryAfterSeconds)));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Human wait time for user-facing messages: "45 seconds", "1 minute", "15 minutes".
|
|
45
|
+
* Minutes round up, so the user is never told to retry too early.
|
|
46
|
+
*/
|
|
47
|
+
export function describeWait(seconds: number): string {
|
|
48
|
+
const s = Math.max(1, Math.ceil(seconds));
|
|
49
|
+
if (s < 60) return `${s} ${s === 1 ? 'second' : 'seconds'}`;
|
|
50
|
+
const m = Math.ceil(s / 60);
|
|
51
|
+
return `${m} ${m === 1 ? 'minute' : 'minutes'}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
27
54
|
export class NotFoundError extends AppError {
|
|
28
55
|
constructor(message = 'Resource not found', code = 'NOT_FOUND') {
|
|
29
56
|
super(code, message, 404);
|
|
@@ -36,6 +63,16 @@ export class ConflictError extends AppError {
|
|
|
36
63
|
}
|
|
37
64
|
}
|
|
38
65
|
|
|
66
|
+
/**
|
|
67
|
+
* 503: a feature that depends on something temporarily down (e.g. Redis for
|
|
68
|
+
* password-reset and verification tokens). The request was fine; retry later.
|
|
69
|
+
*/
|
|
70
|
+
export class ServiceUnavailableError extends AppError {
|
|
71
|
+
constructor(message = 'Service temporarily unavailable', code = 'SERVICE_UNAVAILABLE') {
|
|
72
|
+
super(code, message, 503);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
39
76
|
export class InternalError extends AppError {
|
|
40
77
|
constructor(message = 'Internal server error', code = 'INTERNAL_ERROR') {
|
|
41
78
|
super(code, message, 500);
|
|
@@ -6,12 +6,31 @@ export function successResponse<T>(message: string, data: T): {
|
|
|
6
6
|
return { success: true as const, message, data };
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
import type { FieldError } from '@shared/errors/AppError.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Error envelope. Optional members appear only when they apply:
|
|
13
|
+
* - `retryAfterSeconds` when the caller can retry after a known wait (429s and
|
|
14
|
+
* an automatic IP block); the client uses it to say "try again in N minutes";
|
|
15
|
+
* - `fields` on 422 VALIDATION_FAILED: each wrong input field and why, never
|
|
16
|
+
* the submitted value.
|
|
17
|
+
*/
|
|
18
|
+
export function errorResponse(
|
|
19
|
+
code: string,
|
|
20
|
+
message: string,
|
|
21
|
+
retryAfterSeconds?: number,
|
|
22
|
+
fields?: FieldError[],
|
|
23
|
+
): {
|
|
10
24
|
success: false;
|
|
11
|
-
error: { code: string; message: string };
|
|
25
|
+
error: { code: string; message: string; retryAfterSeconds?: number; fields?: FieldError[] };
|
|
12
26
|
} {
|
|
13
27
|
return {
|
|
14
28
|
success: false as const,
|
|
15
|
-
error: {
|
|
29
|
+
error: {
|
|
30
|
+
code,
|
|
31
|
+
message,
|
|
32
|
+
...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }),
|
|
33
|
+
...(fields && fields.length > 0 ? { fields } : {}),
|
|
34
|
+
},
|
|
16
35
|
};
|
|
17
36
|
}
|
|
@@ -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
|
+
}
|