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
|
@@ -37,6 +37,7 @@ export async function applyEmailVerificationModule(targetDir) {
|
|
|
37
37
|
patchRateLimitConfig(project, targetDir);
|
|
38
38
|
patchAuthService(project, targetDir);
|
|
39
39
|
patchAuthRepo(project, targetDir);
|
|
40
|
+
patchVerificationDefault(targetDir);
|
|
40
41
|
|
|
41
42
|
// C) Patch client files via ts-morph
|
|
42
43
|
patchApiEndpoints(project, targetDir);
|
|
@@ -59,6 +60,12 @@ async function copyModuleFiles(targetDir) {
|
|
|
59
60
|
src: path.join(MODULES_DIR, 'server', 'verification.controller.ts'),
|
|
60
61
|
dest: path.join(targetDir, 'server', 'src', 'modules', 'auth', 'verification.controller.ts'),
|
|
61
62
|
},
|
|
63
|
+
// The module's integration tests ship with it (they need the patched
|
|
64
|
+
// routes, so they live here, not in the template).
|
|
65
|
+
{
|
|
66
|
+
src: path.join(MODULES_DIR, 'server', '__tests__', 'verification.integration.test.ts'),
|
|
67
|
+
dest: path.join(targetDir, 'server', 'src', 'modules', 'auth', '__tests__', 'verification.integration.test.ts'),
|
|
68
|
+
},
|
|
62
69
|
{
|
|
63
70
|
src: path.join(MODULES_DIR, 'client', 'services', 'verification.service.ts'),
|
|
64
71
|
dest: path.join(targetDir, 'client', 'src', 'features', 'auth', 'services', 'verification.service.ts'),
|
|
@@ -180,8 +187,8 @@ export type VerifyAccountInput = z.infer<typeof verifyAccountSchema>;`);
|
|
|
180
187
|
|
|
181
188
|
/**
|
|
182
189
|
* Patch 3: rate-limit.config.ts
|
|
183
|
-
* -
|
|
184
|
-
*
|
|
190
|
+
* - Append AUTH_SEND_VERIFICATION and AUTH_VERIFY_ACCOUNT (10 per 15 minutes each)
|
|
191
|
+
* to the RATE_LIMITS object, built with the routeLimit() helper
|
|
185
192
|
*/
|
|
186
193
|
function patchRateLimitConfig(project, targetDir) {
|
|
187
194
|
const filePath = path.join(targetDir, 'server', 'src', 'config', 'rate-limit.config.ts');
|
|
@@ -212,28 +219,101 @@ function patchRateLimitConfig(project, targetDir) {
|
|
|
212
219
|
// Check if already patched
|
|
213
220
|
if (objectLiteral.getProperty('AUTH_SEND_VERIFICATION')) return;
|
|
214
221
|
|
|
222
|
+
// The entries are built with the routeLimit(name, max, window) helper, which
|
|
223
|
+
// applies RATE_LIMIT_OVERRIDES and the multiplier. A project scaffolded by an
|
|
224
|
+
// older create-tigra has no such helper: stop with a clear message instead of
|
|
225
|
+
// writing code that does not compile.
|
|
226
|
+
if (!sourceFile.getFunction('routeLimit')) {
|
|
227
|
+
throw new Error(
|
|
228
|
+
'rate-limit.config.ts has no routeLimit() helper (project made by an older create-tigra). ' +
|
|
229
|
+
'Add AUTH_SEND_VERIFICATION and AUTH_VERIFY_ACCOUNT (10 per 15 minutes each) to RATE_LIMITS by hand.',
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
215
233
|
// Use text manipulation to insert after AUTH_RESET_PASSWORD block
|
|
216
234
|
// ts-morph's insertPropertyAssignment has quirks with index positioning,
|
|
217
235
|
// so we use the more reliable addPropertyAssignment which appends at end
|
|
218
236
|
// (position within the object doesn't matter for a config map)
|
|
219
237
|
objectLiteral.addPropertyAssignment({
|
|
220
238
|
name: 'AUTH_SEND_VERIFICATION',
|
|
221
|
-
initializer: `
|
|
239
|
+
initializer: `routeLimit('AUTH_SEND_VERIFICATION', 10, '15m')`,
|
|
222
240
|
});
|
|
223
241
|
|
|
224
242
|
objectLiteral.addPropertyAssignment({
|
|
225
243
|
name: 'AUTH_VERIFY_ACCOUNT',
|
|
226
|
-
initializer: `
|
|
244
|
+
initializer: `routeLimit('AUTH_VERIFY_ACCOUNT', 10, '15m')`,
|
|
227
245
|
});
|
|
228
246
|
|
|
229
247
|
sourceFile.saveSync();
|
|
230
248
|
}
|
|
231
249
|
|
|
250
|
+
/**
|
|
251
|
+
* Replace one exact text anchor, failing loudly when it is missing.
|
|
252
|
+
*
|
|
253
|
+
* Text anchors used to skip silently, which hid a real bug: the login resend
|
|
254
|
+
* anchor never matched the template, yet the CLI reported the file as patched.
|
|
255
|
+
* Now a missing anchor stops the patch with a clear error. `alreadyPatchedMarker`
|
|
256
|
+
* makes re-running the patcher a no-op. Anchors are written with "\n"; they are
|
|
257
|
+
* matched against CRLF files too (Windows checkouts with core.autocrlf).
|
|
258
|
+
*/
|
|
259
|
+
function replaceAnchor(content, { anchor, replacement, alreadyPatchedMarker, label, file }) {
|
|
260
|
+
if (content.includes(alreadyPatchedMarker)) return content;
|
|
261
|
+
const eol = content.includes('\r\n') ? '\r\n' : '\n';
|
|
262
|
+
const anchorText = anchor.split('\n').join(eol);
|
|
263
|
+
if (!content.includes(anchorText)) {
|
|
264
|
+
throw new Error(
|
|
265
|
+
`Could not find the ${label} in ${file} — file may have been modified. ` +
|
|
266
|
+
'Apply the email-verification change by hand or restore the template code.',
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
return content.replace(anchorText, replacement.split('\n').join(eol));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Turn email verification ON by default once this module is installed.
|
|
274
|
+
*
|
|
275
|
+
* Projects without the module default REQUIRE_USER_VERIFICATION to false: they
|
|
276
|
+
* have no verify route, so "on" would lock every new user out. With the module
|
|
277
|
+
* the default becomes true, in the code (env.ts) and in every server env file,
|
|
278
|
+
* so scaffold-time and `create-tigra add` end in the same state. An older
|
|
279
|
+
* project whose env.ts already defaults to true is left as it is.
|
|
280
|
+
*/
|
|
281
|
+
function patchVerificationDefault(targetDir) {
|
|
282
|
+
const envTsPath = path.join(targetDir, 'server', 'src', 'config', 'env.ts');
|
|
283
|
+
const content = fs.readFileSync(envTsPath, 'utf-8');
|
|
284
|
+
const alreadyOn =
|
|
285
|
+
content.includes('REQUIRE_USER_VERIFICATION: envBoolean(true)') ||
|
|
286
|
+
/REQUIRE_USER_VERIFICATION:[^\n]*default\('true'\)/.test(content);
|
|
287
|
+
if (!alreadyOn) {
|
|
288
|
+
const patched = replaceAnchor(content, {
|
|
289
|
+
anchor: 'REQUIRE_USER_VERIFICATION: envBoolean(false),',
|
|
290
|
+
replacement: 'REQUIRE_USER_VERIFICATION: envBoolean(true),',
|
|
291
|
+
alreadyPatchedMarker: 'REQUIRE_USER_VERIFICATION: envBoolean(true)',
|
|
292
|
+
label: 'REQUIRE_USER_VERIFICATION default',
|
|
293
|
+
file: 'server/src/config/env.ts',
|
|
294
|
+
});
|
|
295
|
+
fs.writeFileSync(envTsPath, patched, 'utf-8');
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// `KEY=false` lines only (quoted or not, any letter case); other values are the owner's choice.
|
|
299
|
+
for (const envFile of ['.env.example', '.env', '.env.example.production']) {
|
|
300
|
+
const envPath = path.join(targetDir, 'server', envFile);
|
|
301
|
+
if (!fs.existsSync(envPath)) continue;
|
|
302
|
+
const text = fs.readFileSync(envPath, 'utf-8');
|
|
303
|
+
const updated = text.replace(
|
|
304
|
+
/^REQUIRE_USER_VERIFICATION=(["']?)false\1(?=\s|$)/gim,
|
|
305
|
+
'REQUIRE_USER_VERIFICATION=$1true$1',
|
|
306
|
+
);
|
|
307
|
+
if (updated !== text) fs.writeFileSync(envPath, updated, 'utf-8');
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
232
311
|
/**
|
|
233
312
|
* Patch 4: auth.service.ts
|
|
234
313
|
* - Export sanitizeUser function, SanitizedUser interface, AuthResult interface
|
|
235
314
|
* so verification.service.ts can import them
|
|
236
|
-
* - Add import for sendVerification and call it during register (auto-send on
|
|
315
|
+
* - Add import for sendVerification and call it during register (auto-send on
|
|
316
|
+
* signup) and on a correct-password login of an unverified, non-banned account
|
|
237
317
|
*/
|
|
238
318
|
function patchAuthService(project, targetDir) {
|
|
239
319
|
const filePath = path.join(targetDir, 'server', 'src', 'modules', 'auth', 'auth.service.ts');
|
|
@@ -292,18 +372,44 @@ function patchAuthService(project, targetDir) {
|
|
|
292
372
|
let patched = content;
|
|
293
373
|
|
|
294
374
|
// Patch 1: Auto-send verification email on registration
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
375
|
+
patched = replaceAnchor(patched, {
|
|
376
|
+
file: 'auth.service.ts',
|
|
377
|
+
label: 'register verification branch',
|
|
378
|
+
// Prefix marker (no closing parenthesis): matches every version of the inserted call.
|
|
379
|
+
alreadyPatchedMarker: 'sendVerification(input.email',
|
|
380
|
+
anchor: ' if (requiresVerification) {\n return {\n user: sanitizeUser(user),\n requiresVerification: true,\n };\n }',
|
|
381
|
+
replacement:
|
|
382
|
+
' if (requiresVerification) {\n' +
|
|
383
|
+
" // Auto-send verification email on registration (best-effort, don't block registration).\n" +
|
|
384
|
+
' // Not charged to the per-address email cap: an address registers only once, so this\n' +
|
|
385
|
+
' // email cannot flood anyone, and strangers using up the cap must not stop it.\n' +
|
|
386
|
+
" sendVerification(input.email, { quota: 'none' }).catch((error) => logger.warn({ code: error?.code }, '[AUTH] Verification email not sent at register'));\n\n" +
|
|
387
|
+
' return {\n user: sanitizeUser(user),\n requiresVerification: true,\n };\n }',
|
|
388
|
+
});
|
|
300
389
|
|
|
301
|
-
// Patch 2:
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
390
|
+
// Patch 2: Re-send a fresh link when an unverified user logs in with the
|
|
391
|
+
// correct password. It runs after the password check, so an anonymous caller
|
|
392
|
+
// cannot trigger emails, and never for a banned account (verification cannot
|
|
393
|
+
// lift a ban). assertAccountCanSignIn then answers 403 EMAIL_NOT_VERIFIED.
|
|
394
|
+
patched = replaceAnchor(patched, {
|
|
395
|
+
file: 'auth.service.ts',
|
|
396
|
+
label: 'login account-state check',
|
|
397
|
+
alreadyPatchedMarker: 'sendVerification(user.email',
|
|
398
|
+
anchor:
|
|
399
|
+
' // Reveal account state only now that the password is proven, so an anonymous\n' +
|
|
400
|
+
' // caller cannot learn whether an email is banned or unverified.\n' +
|
|
401
|
+
' assertAccountCanSignIn(user);',
|
|
402
|
+
replacement:
|
|
403
|
+
' // Reveal account state only now that the password is proven, so an anonymous\n' +
|
|
404
|
+
' // caller cannot learn whether an email is banned or unverified.\n' +
|
|
405
|
+
' // Email-verification module: re-send a fresh link to an unverified (not banned) account.\n' +
|
|
406
|
+
" // Own 'sign-in' email counter: only the password holder gets here, so strangers who use up\n" +
|
|
407
|
+
' // the public counter (forgot-password, resend) can never block this link.\n' +
|
|
408
|
+
' if (user.isActive && env.REQUIRE_USER_VERIFICATION && !user.emailVerifiedAt) {\n' +
|
|
409
|
+
" sendVerification(user.email, { quota: 'sign-in' }).catch((error) => logger.warn({ code: error?.code }, '[AUTH] Verification email not re-sent at sign-in'));\n" +
|
|
410
|
+
' }\n' +
|
|
411
|
+
' assertAccountCanSignIn(user);',
|
|
412
|
+
});
|
|
307
413
|
|
|
308
414
|
if (patched !== content) {
|
|
309
415
|
fs.writeFileSync(filePath, patched, 'utf-8');
|
|
@@ -312,26 +418,35 @@ function patchAuthService(project, targetDir) {
|
|
|
312
418
|
|
|
313
419
|
/**
|
|
314
420
|
* Patch 5: auth.repo.ts
|
|
315
|
-
* - Add
|
|
421
|
+
* - Add markEmailVerified function at end of file
|
|
422
|
+
*
|
|
423
|
+
* It sets emailVerifiedAt only for an active, not-yet-verified, non-deleted
|
|
424
|
+
* account and never touches isActive (the admin ban switch). The conditional
|
|
425
|
+
* write means a ban that lands mid-verification still wins. Returns whether a
|
|
426
|
+
* row was updated.
|
|
316
427
|
*/
|
|
317
428
|
function patchAuthRepo(project, targetDir) {
|
|
318
429
|
const filePath = path.join(targetDir, 'server', 'src', 'modules', 'auth', 'auth.repo.ts');
|
|
319
430
|
const sourceFile = project.addSourceFileAtPath(filePath);
|
|
320
431
|
|
|
321
432
|
// Check if already patched
|
|
322
|
-
const existing = sourceFile.getFunction('
|
|
433
|
+
const existing = sourceFile.getFunction('markEmailVerified');
|
|
323
434
|
if (existing) return;
|
|
324
435
|
|
|
325
436
|
sourceFile.addFunction({
|
|
326
|
-
name: '
|
|
437
|
+
name: 'markEmailVerified',
|
|
327
438
|
isExported: true,
|
|
328
439
|
isAsync: true,
|
|
329
|
-
parameters: [
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
440
|
+
parameters: [
|
|
441
|
+
{ name: 'userId', type: 'string' },
|
|
442
|
+
{ name: 'verifiedAt', type: 'Date' },
|
|
443
|
+
],
|
|
444
|
+
returnType: 'Promise<boolean>',
|
|
445
|
+
statements: `const result = await prisma.user.updateMany({
|
|
446
|
+
where: { id: userId, isActive: true, emailVerifiedAt: null, deletedAt: null },
|
|
447
|
+
data: { emailVerifiedAt: verifiedAt },
|
|
448
|
+
});
|
|
449
|
+
return result.count === 1;`,
|
|
335
450
|
});
|
|
336
451
|
|
|
337
452
|
sourceFile.saveSync();
|
|
@@ -444,31 +559,32 @@ function patchErrorCodes(project, targetDir) {
|
|
|
444
559
|
|
|
445
560
|
/**
|
|
446
561
|
* Patch 8: useAuth.ts (client)
|
|
447
|
-
* - Redirect to /verify-account when login fails with
|
|
448
|
-
* (the server auto-resends the verification email on this error)
|
|
562
|
+
* - Redirect to /verify-account when login fails with EMAIL_NOT_VERIFIED
|
|
563
|
+
* (the server auto-resends the verification email on this error).
|
|
564
|
+
* Banned accounts (ACCOUNT_DEACTIVATED) are deliberately NOT sent there:
|
|
565
|
+
* verifying an email cannot lift a ban.
|
|
449
566
|
*/
|
|
450
567
|
function patchUseAuthHook(targetDir) {
|
|
451
568
|
const filePath = path.join(targetDir, 'client', 'src', 'features', 'auth', 'hooks', 'useAuth.ts');
|
|
452
|
-
if (!fs.pathExistsSync(filePath))
|
|
569
|
+
if (!fs.pathExistsSync(filePath)) {
|
|
570
|
+
throw new Error('Could not find client/src/features/auth/hooks/useAuth.ts — file may have been moved');
|
|
571
|
+
}
|
|
453
572
|
|
|
454
573
|
const content = fs.readFileSync(filePath, 'utf-8');
|
|
455
574
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
// Replace the toast message and add router.push right after it
|
|
466
|
-
const patched = content.replace(
|
|
467
|
-
anchorText,
|
|
468
|
-
"toast.error('Your account is not yet activated. Check your email for a verification link.');\n router.push(ROUTES.VERIFY_ACCOUNT);",
|
|
469
|
-
);
|
|
575
|
+
const patched = replaceAnchor(content, {
|
|
576
|
+
file: 'useAuth.ts',
|
|
577
|
+
label: 'EMAIL_NOT_VERIFIED login error toast',
|
|
578
|
+
alreadyPatchedMarker: 'We sent you a new verification link',
|
|
579
|
+
anchor: "toast.error('Please verify your email address before signing in.');",
|
|
580
|
+
replacement:
|
|
581
|
+
"toast.error('Please verify your email address. We sent you a new verification link.');\n" +
|
|
582
|
+
' router.push(ROUTES.VERIFY_ACCOUNT);',
|
|
583
|
+
});
|
|
470
584
|
|
|
471
|
-
|
|
585
|
+
if (patched !== content) {
|
|
586
|
+
fs.writeFileSync(filePath, patched, 'utf-8');
|
|
587
|
+
}
|
|
472
588
|
}
|
|
473
589
|
|
|
474
590
|
// ─── Postman Patch ──────────────────────────────────────────────
|
|
@@ -521,7 +637,7 @@ async function patchPostmanCollection(targetDir) {
|
|
|
521
637
|
path: ['auth', 'send-verification'],
|
|
522
638
|
},
|
|
523
639
|
description:
|
|
524
|
-
'Resend the verification email. Public endpoint — no authentication required. Always returns success to prevent email enumeration. A verification email is also sent automatically on registration. Rate limited to
|
|
640
|
+
'Resend the verification email. Public endpoint — no authentication required. Always returns success to prevent email enumeration. A verification email is also sent automatically on registration. Rate limited to 10 requests per 15 minutes per IP, and at most 3 emails per hour to one address (shared with forgot-password).',
|
|
525
641
|
},
|
|
526
642
|
response: [],
|
|
527
643
|
});
|
|
@@ -5,7 +5,7 @@ import { toast } from 'sonner';
|
|
|
5
5
|
|
|
6
6
|
import { useAppDispatch } from '@/store/hooks';
|
|
7
7
|
import { useAppRouter } from '@/hooks/useAppRouter';
|
|
8
|
-
import { getErrorMessage, isErrorCode, ERROR_CODES } from '@/lib/utils/error';
|
|
8
|
+
import { getErrorMessage, isErrorCode, isLimitError, ERROR_CODES } from '@/lib/utils/error';
|
|
9
9
|
import { ROUTES } from '@/lib/constants/routes';
|
|
10
10
|
import { verificationService } from '../services/verification.service';
|
|
11
11
|
import { setUser } from '../store/authSlice';
|
|
@@ -24,6 +24,8 @@ export const useSendVerification = (): UseSendVerificationReturn => {
|
|
|
24
24
|
toast.success('Verification email sent! Please check your inbox.');
|
|
25
25
|
},
|
|
26
26
|
onError: (error: unknown) => {
|
|
27
|
+
// Rate limit or the per-address email cap: the global toast already says how long to wait.
|
|
28
|
+
if (isLimitError(error)) return;
|
|
27
29
|
if (isErrorCode(error, ERROR_CODES.ALREADY_VERIFIED)) {
|
|
28
30
|
toast.info('Your account is already verified');
|
|
29
31
|
router.push(ROUTES.DASHBOARD);
|
|
@@ -56,6 +58,7 @@ export const useVerifyAccount = (): UseVerifyAccountReturn => {
|
|
|
56
58
|
router.push(ROUTES.DASHBOARD);
|
|
57
59
|
},
|
|
58
60
|
onError: (error: unknown) => {
|
|
61
|
+
if (isLimitError(error)) return; // the global toast already says how long to wait
|
|
59
62
|
toast.error(getErrorMessage(error));
|
|
60
63
|
if (isErrorCode(error, ERROR_CODES.INVALID_VERIFICATION_TOKEN)) {
|
|
61
64
|
router.push(ROUTES.LOGIN);
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Email verification (the email-verification module) against a real MySQL
|
|
3
|
+
* and Redis, with verification switched ON for this file. Emails go to an
|
|
4
|
+
* in-process Resend stub; nothing is sent.
|
|
5
|
+
* - Register does not sign in; signing in before verifying is refused
|
|
6
|
+
* (403 EMAIL_NOT_VERIFIED).
|
|
7
|
+
* - The emailed link verifies once and signs in; the same link again, or any
|
|
8
|
+
* other token, is 400 INVALID_VERIFICATION_TOKEN.
|
|
9
|
+
* - Verification tokens are stored by fingerprint only: no Redis key or value
|
|
10
|
+
* holds the raw token.
|
|
11
|
+
* - send-verification answers the same for every address (no account
|
|
12
|
+
* discovery) and emails a fresh link only to an unverified account.
|
|
13
|
+
*
|
|
14
|
+
* The generator copies this file into server/src/modules/auth/__tests__/
|
|
15
|
+
* (lib/patchers/email-verification.patcher.js); it runs with the rest of the
|
|
16
|
+
* integration suite.
|
|
17
|
+
*/
|
|
18
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
19
|
+
import type { FastifyInstance } from 'fastify';
|
|
20
|
+
import {
|
|
21
|
+
PASSWORD,
|
|
22
|
+
buildTestApp,
|
|
23
|
+
call,
|
|
24
|
+
CookieJar,
|
|
25
|
+
redis,
|
|
26
|
+
startEmailStub,
|
|
27
|
+
tokenOf,
|
|
28
|
+
uniqueEmail,
|
|
29
|
+
type EmailStub,
|
|
30
|
+
} from '@/test/integration-helpers.js';
|
|
31
|
+
|
|
32
|
+
let app: FastifyInstance;
|
|
33
|
+
let mail: EmailStub;
|
|
34
|
+
|
|
35
|
+
beforeAll(async () => {
|
|
36
|
+
process.env.REQUIRE_USER_VERIFICATION = 'true';
|
|
37
|
+
mail = await startEmailStub();
|
|
38
|
+
app = await buildTestApp();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
afterAll(async () => {
|
|
42
|
+
await app?.close();
|
|
43
|
+
await mail?.close();
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/** Registers an address and returns the raw token of the verification link it was emailed. */
|
|
47
|
+
async function registerUnverified(tag: string): Promise<{ email: string; token: string; registerJar: CookieJar }> {
|
|
48
|
+
const email = uniqueEmail(tag);
|
|
49
|
+
const registerJar = new CookieJar();
|
|
50
|
+
const r = await call(app, 'POST', '/auth/register', {
|
|
51
|
+
jar: registerJar,
|
|
52
|
+
payload: { email, password: PASSWORD, firstName: 'Veri', lastName: 'Fied' },
|
|
53
|
+
});
|
|
54
|
+
expect(r.status).toBe(201);
|
|
55
|
+
// The verification email goes out after register has answered: wait for it.
|
|
56
|
+
const sent = await mail.waitFor(email, (e) => /verify-account/.test(e.link ?? ''));
|
|
57
|
+
return { email, token: tokenOf(sent.at(-1)?.link ?? null), registerJar };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
describe('before verifying', () => {
|
|
61
|
+
it('register answers 201 without signing in, and sign-in is refused with 403 EMAIL_NOT_VERIFIED', async () => {
|
|
62
|
+
const { email, registerJar } = await registerUnverified('unverified');
|
|
63
|
+
expect(registerJar.get('access_token')).toBeUndefined();
|
|
64
|
+
const login = await call(app, 'POST', '/auth/login', { payload: { email, password: PASSWORD } });
|
|
65
|
+
expect([login.status, login.code]).toEqual([403, 'EMAIL_NOT_VERIFIED']);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe('the verification link', () => {
|
|
70
|
+
it('verifies once and signs in; the same link again is 400 INVALID_VERIFICATION_TOKEN', async () => {
|
|
71
|
+
const { token } = await registerUnverified('verify');
|
|
72
|
+
const jar = new CookieJar();
|
|
73
|
+
const ok = await call(app, 'POST', '/auth/verify-account', { jar, payload: { token } });
|
|
74
|
+
expect(ok.status).toBe(200);
|
|
75
|
+
expect((await call(app, 'GET', '/auth/me', { jar })).status).toBe(200);
|
|
76
|
+
const again = await call(app, 'POST', '/auth/verify-account', { payload: { token } });
|
|
77
|
+
expect([again.status, again.code]).toEqual([400, 'INVALID_VERIFICATION_TOKEN']);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('a token nobody was sent → 400 INVALID_VERIFICATION_TOKEN', async () => {
|
|
81
|
+
const r = await call(app, 'POST', '/auth/verify-account', { payload: { token: 'f'.repeat(64) } });
|
|
82
|
+
expect([r.status, r.code]).toEqual([400, 'INVALID_VERIFICATION_TOKEN']);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('no Redis key or value holds the raw token (stored by fingerprint only)', async () => {
|
|
86
|
+
const { token } = await registerUnverified('fingerprint');
|
|
87
|
+
const r = await redis();
|
|
88
|
+
const keys = await r.keys('verify*');
|
|
89
|
+
expect(keys.length).toBeGreaterThan(0);
|
|
90
|
+
expect(keys.join('\n')).not.toContain(token);
|
|
91
|
+
for (const key of keys) {
|
|
92
|
+
if ((await r.type(key)) === 'string') expect((await r.get(key)) ?? '').not.toContain(token);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
describe('send-verification', () => {
|
|
98
|
+
it('answers the same for an unknown address and an unverified account; only the account gets a new link', async () => {
|
|
99
|
+
const { email } = await registerUnverified('resend');
|
|
100
|
+
const before = mail.to(email).length;
|
|
101
|
+
const known = await call(app, 'POST', '/auth/send-verification', { payload: { email } });
|
|
102
|
+
const unknownEmail = uniqueEmail('nobody');
|
|
103
|
+
const unknown = await call(app, 'POST', '/auth/send-verification', { payload: { email: unknownEmail } });
|
|
104
|
+
expect(known.status).toBe(200);
|
|
105
|
+
expect(known.body).toEqual(unknown.body);
|
|
106
|
+
expect(await mail.waitFor(email, () => true, before + 1)).toHaveLength(before + 1);
|
|
107
|
+
expect(mail.to(unknownEmail)).toHaveLength(0);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('wrong input → 422 VALIDATION_FAILED (send-verification and verify-account)', async () => {
|
|
111
|
+
const a = await call(app, 'POST', '/auth/send-verification', { payload: { email: 'x' } });
|
|
112
|
+
const b = await call(app, 'POST', '/auth/verify-account', { payload: {} });
|
|
113
|
+
expect([a.status, a.code, b.status, b.code]).toEqual([422, 'VALIDATION_FAILED', 422, 'VALIDATION_FAILED']);
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { FastifyRequest, FastifyReply } from 'fastify';
|
|
2
2
|
import { successResponse } from '@shared/responses/successResponse.js';
|
|
3
3
|
import { setAuthCookies } from '@libs/cookies.js';
|
|
4
|
+
import { getClientIp } from '@libs/client-ip.js';
|
|
4
5
|
import * as verificationService from './verification.service.js';
|
|
5
6
|
|
|
6
7
|
import type { SendVerificationInput, VerifyAccountInput } from './auth.schemas.js';
|
|
@@ -19,7 +20,8 @@ export async function verifyAccount(
|
|
|
19
20
|
reply: FastifyReply,
|
|
20
21
|
): Promise<void> {
|
|
21
22
|
const deviceInfo = request.headers['user-agent'];
|
|
22
|
-
|
|
23
|
+
// Same verified address as login/register sessions (never request.ip or a raw header).
|
|
24
|
+
const ipAddress = getClientIp(request);
|
|
23
25
|
|
|
24
26
|
const result = await verificationService.verifyAccount(request.body.token, deviceInfo, ipAddress);
|
|
25
27
|
|
|
@@ -4,8 +4,13 @@ import { getRedis } from '@libs/redis.js';
|
|
|
4
4
|
import { sendEmail } from '@libs/email.js';
|
|
5
5
|
import { logger } from '@libs/logger.js';
|
|
6
6
|
import { env } from '@config/env.js';
|
|
7
|
+
import { ACCOUNT_DEACTIVATED } from '@libs/account-status.js';
|
|
8
|
+
import { consumeEmailQuota, type EmailQuotaBucket } from '@libs/email-quota.js';
|
|
9
|
+
import { assertRedisReady } from '@libs/redis-required.js';
|
|
10
|
+
import { hashToken } from '@libs/token-hash.js';
|
|
7
11
|
import {
|
|
8
12
|
BadRequestError,
|
|
13
|
+
ForbiddenError,
|
|
9
14
|
NotFoundError,
|
|
10
15
|
} from '@shared/errors/errors.js';
|
|
11
16
|
import * as authRepo from './auth.repo.js';
|
|
@@ -15,37 +20,67 @@ import { sanitizeUser } from './auth.service.js';
|
|
|
15
20
|
import type { AuthResult } from './auth.service.js';
|
|
16
21
|
|
|
17
22
|
const VERIFICATION_TTL = 3600; // 1 hour in seconds
|
|
23
|
+
// Stored by fingerprint only (libs/token-hash.ts): `verify:<sha256>` -> userId,
|
|
24
|
+
// `verify-user:<userId>` -> that sha256. The raw token exists only in the email.
|
|
18
25
|
const VERIFICATION_PREFIX = 'verify:';
|
|
19
26
|
const VERIFICATION_USER_PREFIX = 'verify-user:';
|
|
20
27
|
|
|
21
28
|
/**
|
|
22
29
|
* Send a verification email to a user.
|
|
23
30
|
* Public endpoint — accepts email, silent return if user not found (prevents enumeration).
|
|
24
|
-
* Also called internally by the register
|
|
31
|
+
* Also called internally by the register and login flows for auto-sending.
|
|
32
|
+
*
|
|
33
|
+
* Verification proves email ownership and nothing else: it sets
|
|
34
|
+
* `emailVerifiedAt` and never touches `isActive` (the admin ban switch).
|
|
25
35
|
*/
|
|
26
|
-
export async function sendVerification(
|
|
36
|
+
export async function sendVerification(
|
|
37
|
+
email: string,
|
|
38
|
+
{ quota = 'public' }: { quota?: EmailQuotaBucket | 'none' } = {},
|
|
39
|
+
): Promise<void> {
|
|
40
|
+
// Per-address email cap (libs/email-quota.ts), counted BEFORE the lookup so
|
|
41
|
+
// unknown, banned and already-verified addresses count the same and the 429
|
|
42
|
+
// reveals nothing. Which counter:
|
|
43
|
+
// - 'public' (default): the public resend endpoint, shared with forgot-password.
|
|
44
|
+
// Over the cap it answers 429 EMAIL_RATE_LIMITED with the wait.
|
|
45
|
+
// - 'sign-in': the resend after a correct password; its own counter, so
|
|
46
|
+
// strangers typing the address cannot use it up.
|
|
47
|
+
// - 'none': the one email sent at register (an address registers only once).
|
|
48
|
+
// Register and the sign-in resend call this fire-and-forget: over their cap
|
|
49
|
+
// the email is skipped and the caller logs it.
|
|
50
|
+
//
|
|
51
|
+
// Verification tokens live in Redis: without it, answer a clear 503 for every
|
|
52
|
+
// address (checked first, so it reveals nothing about the account).
|
|
53
|
+
assertRedisReady('Email verification');
|
|
54
|
+
if (quota !== 'none') {
|
|
55
|
+
await consumeEmailQuota(email, quota);
|
|
56
|
+
}
|
|
57
|
+
|
|
27
58
|
const user = await authRepo.findUserByEmail(email);
|
|
28
59
|
|
|
29
60
|
// Silent return if user not found — prevents email enumeration (same pattern as forgotPassword)
|
|
30
61
|
if (!user) return;
|
|
31
62
|
|
|
32
|
-
//
|
|
33
|
-
|
|
63
|
+
// No token for a banned account: a verify link must never lift an admin ban
|
|
64
|
+
// (that is exactly how a banned user used to re-activate themselves). No
|
|
65
|
+
// token either when the email is already verified. Both stay silent so the
|
|
66
|
+
// response does not reveal the account's status.
|
|
67
|
+
if (!user.isActive || user.emailVerifiedAt) return;
|
|
34
68
|
|
|
35
69
|
const redis = getRedis();
|
|
36
70
|
|
|
37
|
-
// Invalidate any existing verification token for this user
|
|
38
|
-
const
|
|
39
|
-
if (
|
|
40
|
-
await redis.del(`${VERIFICATION_PREFIX}${
|
|
71
|
+
// Invalidate any existing verification token for this user (the pointer holds its fingerprint)
|
|
72
|
+
const existingTokenHash = await redis.get(`${VERIFICATION_USER_PREFIX}${user.id}`);
|
|
73
|
+
if (existingTokenHash) {
|
|
74
|
+
await redis.del(`${VERIFICATION_PREFIX}${existingTokenHash}`);
|
|
41
75
|
await redis.del(`${VERIFICATION_USER_PREFIX}${user.id}`);
|
|
42
76
|
}
|
|
43
77
|
|
|
44
|
-
// Generate secure token
|
|
78
|
+
// Generate a secure token; only its fingerprint goes to Redis (1 hour TTL)
|
|
45
79
|
const token = crypto.randomBytes(32).toString('hex');
|
|
80
|
+
const tokenHash = hashToken(token);
|
|
46
81
|
|
|
47
|
-
await redis.set(`${VERIFICATION_PREFIX}${
|
|
48
|
-
await redis.set(`${VERIFICATION_USER_PREFIX}${user.id}`,
|
|
82
|
+
await redis.set(`${VERIFICATION_PREFIX}${tokenHash}`, user.id, 'EX', VERIFICATION_TTL);
|
|
83
|
+
await redis.set(`${VERIFICATION_USER_PREFIX}${user.id}`, tokenHash, 'EX', VERIFICATION_TTL);
|
|
49
84
|
|
|
50
85
|
// Build verification URL and send email
|
|
51
86
|
const verifyUrl = `${env.CLIENT_URL}/verify-account?token=${token}`;
|
|
@@ -104,10 +139,12 @@ export async function verifyAccount(
|
|
|
104
139
|
deviceInfo?: string,
|
|
105
140
|
ipAddress?: string,
|
|
106
141
|
): Promise<AuthResult> {
|
|
142
|
+
assertRedisReady('Email verification'); // the token is stored in Redis
|
|
107
143
|
const redis = getRedis();
|
|
108
144
|
|
|
109
145
|
// Atomic get-and-delete to prevent token reuse via concurrent requests
|
|
110
|
-
|
|
146
|
+
// ioredis exposes GETDEL as getdel (all lowercase); getDel does not exist.
|
|
147
|
+
const userId = await redis.getdel(`${VERIFICATION_PREFIX}${hashToken(token)}`);
|
|
111
148
|
if (!userId) {
|
|
112
149
|
throw new BadRequestError('Invalid or expired verification token', 'INVALID_VERIFICATION_TOKEN');
|
|
113
150
|
}
|
|
@@ -117,17 +154,34 @@ export async function verifyAccount(
|
|
|
117
154
|
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
118
155
|
}
|
|
119
156
|
|
|
120
|
-
//
|
|
121
|
-
await authRepo.activateUser(userId);
|
|
122
|
-
|
|
123
|
-
// Clean up the reverse-lookup key
|
|
157
|
+
// Clean up the reverse-lookup key (the token itself was consumed above)
|
|
124
158
|
await redis.del(`${VERIFICATION_USER_PREFIX}${userId}`);
|
|
125
159
|
|
|
160
|
+
// A token issued before a ban must not lift the ban or open a session.
|
|
161
|
+
if (!user.isActive) {
|
|
162
|
+
throw new ForbiddenError(
|
|
163
|
+
'This account has been deactivated. Contact support if you think this is a mistake.',
|
|
164
|
+
ACCOUNT_DEACTIVATED,
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Conditional write: only an active, not-yet-verified account is marked. If a
|
|
169
|
+
// ban lands between the read above and this write, the ban wins.
|
|
170
|
+
const verifiedAt = new Date();
|
|
171
|
+
const marked = await authRepo.markEmailVerified(userId, verifiedAt);
|
|
172
|
+
if (!marked) {
|
|
173
|
+
const current = await authRepo.findUserById(userId);
|
|
174
|
+
if (!current || !current.isActive) {
|
|
175
|
+
throw new ForbiddenError(
|
|
176
|
+
'This account has been deactivated. Contact support if you think this is a mistake.',
|
|
177
|
+
ACCOUNT_DEACTIVATED,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
throw new BadRequestError('This email address is already verified', 'ALREADY_VERIFIED');
|
|
181
|
+
}
|
|
182
|
+
|
|
126
183
|
// Generate tokens and create session (same pattern as login)
|
|
127
|
-
|
|
128
|
-
userId: user.id,
|
|
129
|
-
role: user.role,
|
|
130
|
-
});
|
|
184
|
+
// Session first: the access token carries its id (see authenticate()).
|
|
131
185
|
const refreshToken = generateRefreshToken();
|
|
132
186
|
const refreshTokenExpiresAt = getRefreshTokenExpiresAt();
|
|
133
187
|
|
|
@@ -138,6 +192,12 @@ export async function verifyAccount(
|
|
|
138
192
|
expiresAt: refreshTokenExpiresAt,
|
|
139
193
|
});
|
|
140
194
|
|
|
195
|
+
const accessToken = signAccessToken({
|
|
196
|
+
userId: user.id,
|
|
197
|
+
role: user.role,
|
|
198
|
+
sessionId: session.id,
|
|
199
|
+
});
|
|
200
|
+
|
|
141
201
|
await authRepo.createRefreshToken({
|
|
142
202
|
token: refreshToken,
|
|
143
203
|
userId: user.id,
|
|
@@ -183,7 +243,7 @@ export async function verifyAccount(
|
|
|
183
243
|
}
|
|
184
244
|
|
|
185
245
|
return {
|
|
186
|
-
user: sanitizeUser({ ...user,
|
|
246
|
+
user: sanitizeUser({ ...user, emailVerifiedAt: verifiedAt }),
|
|
187
247
|
accessToken,
|
|
188
248
|
refreshToken,
|
|
189
249
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-tigra",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Create a production-ready full-stack app with Next.js 16 + Fastify 5 + Prisma + Redis",
|
|
6
6
|
"bin": {
|
|
@@ -42,7 +42,8 @@
|
|
|
42
42
|
},
|
|
43
43
|
"homepage": "https://github.com/blessandsoul/create-tigra#readme",
|
|
44
44
|
"scripts": {
|
|
45
|
-
"create:test": "node -e \"import('fs').then(f=>f.rmSync('testapp',{recursive:true,force:true}))\" && node bin/create-tigra.js testapp"
|
|
45
|
+
"create:test": "node -e \"import('fs').then(f=>f.rmSync('testapp',{recursive:true,force:true}))\" && node bin/create-tigra.js testapp",
|
|
46
|
+
"check:init-migration": "node scripts/check-init-migration.mjs"
|
|
46
47
|
},
|
|
47
48
|
"dependencies": {
|
|
48
49
|
"chalk": "^5.4.1",
|