create-tigra 3.1.1 → 3.3.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.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/bin/create-tigra.js +6 -5
  3. package/lib/patchers/email-verification.patcher.js +93 -39
  4. package/modules/email-verification/server/verification.service.ts +38 -9
  5. package/package.json +1 -1
  6. package/template/.claude/skills/security-audit/SKILL.md +10 -0
  7. package/template/AGENTS.md +18 -2
  8. package/template/CLAUDE.md +1 -0
  9. package/template/client/CLAUDE.md +1 -0
  10. package/template/client/src/features/auth/components/AuthInitializer.tsx +4 -2
  11. package/template/client/src/features/auth/components/LoginForm.tsx +5 -2
  12. package/template/client/src/features/auth/hooks/useAuth.ts +16 -6
  13. package/template/client/src/features/auth/types/auth.types.ts +3 -0
  14. package/template/client/src/instrumentation-client.ts +9 -1
  15. package/template/client/src/instrumentation.ts +6 -0
  16. package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
  17. package/template/client/src/lib/utils/error.ts +5 -1
  18. package/template/client/src/lib/utils/security.ts +37 -0
  19. package/template/server/.env.example +5 -4
  20. package/template/server/.env.example.production +14 -8
  21. package/template/server/CLAUDE.md +1 -0
  22. package/template/server/Dockerfile +5 -0
  23. package/template/server/prisma/schema.prisma +19 -3
  24. package/template/server/prisma/seed.ts +13 -5
  25. package/template/server/src/app.ts +11 -0
  26. package/template/server/src/config/env.ts +17 -6
  27. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +58 -0
  28. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +72 -58
  29. package/template/server/src/libs/__tests__/auth.test.ts +77 -0
  30. package/template/server/src/libs/__tests__/cookies.test.ts +62 -0
  31. package/template/server/src/libs/__tests__/redis.test.ts +23 -0
  32. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +80 -0
  33. package/template/server/src/libs/account-status.ts +52 -0
  34. package/template/server/src/libs/auth.ts +15 -5
  35. package/template/server/src/libs/cookies.ts +40 -12
  36. package/template/server/src/libs/ip-block.ts +3 -2
  37. package/template/server/src/libs/monitoring.ts +4 -1
  38. package/template/server/src/libs/observability/sentry.ts +80 -0
  39. package/template/server/src/libs/redis.ts +82 -18
  40. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +84 -0
  41. package/template/server/src/libs/storage/file-storage.service.ts +21 -10
  42. package/template/server/src/libs/storage/image-optimizer.service.ts +67 -72
  43. package/template/server/src/modules/admin/admin.repo.ts +7 -3
  44. package/template/server/src/modules/admin/admin.service.ts +7 -3
  45. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +136 -13
  46. package/template/server/src/modules/auth/auth.controller.ts +1 -1
  47. package/template/server/src/modules/auth/auth.repo.ts +20 -2
  48. package/template/server/src/modules/auth/auth.schemas.ts +1 -0
  49. package/template/server/src/modules/auth/auth.service.ts +30 -13
  50. package/template/server/src/modules/auth/session.repo.ts +0 -12
  51. package/template/server/src/modules/users/users.repo.ts +2 -0
  52. package/template/server/src/test/setup.ts +22 -0
package/README.md CHANGED
@@ -40,7 +40,7 @@ npx create-tigra my-app
40
40
 
41
41
  ### Codex Development
42
42
 
43
- Includes concise Codex-native `AGENTS.md` guidance at the project root and scoped guidance inside `client/` and `server/`. Generated projects also include Cloudflare's MIT-licensed `security-audit` repository skill. Meaningful server changes must use its focused guidance and, when the Codex Security plugin is installed, complete a `security-diff-scan` of the working-tree patch before completion.
43
+ Includes concise `AGENTS.md` guidance at the project root and scoped guidance inside `client/` and `server/`, with matching `CLAUDE.md` files that import them so Claude Code reads the same rules. Generated projects also include Cloudflare's MIT-licensed `security-audit` repository skill (in `.agents/skills/` for Codex, with a thin pointer in `.claude/skills/` for Claude Code). Meaningful server changes must use its focused guidance and, before completion, scan the working-tree patch: `security-diff-scan` when the Codex Security plugin is installed, or `/security-review` in Claude Code.
44
44
 
45
45
  The security workflow falls back to the bundled skill when Codex Security is unavailable, while full or deep repository audits remain explicit operations rather than an automatic cost on every edit.
46
46
 
@@ -23,6 +23,7 @@ const JWT_SECRET_PLACEHOLDER = 'CHANGE_ME_generate_with_openssl_rand_hex_48';
23
23
 
24
24
  // Files that contain template variables and need replacement
25
25
  const FILES_TO_REPLACE = [
26
+ 'AGENTS.md',
26
27
  'server/package.json',
27
28
  'server/.env.example',
28
29
  'server/docker-compose.yml',
@@ -104,10 +105,10 @@ async function copyTemplate(templateDir, targetDir) {
104
105
  continue;
105
106
  }
106
107
 
107
- // The repository stores the gitignore without a leading dot so npm reliably
108
- // includes it in the published template; generated projects receive the dotfile.
109
- let destName = entry.name;
110
- if (entry.name === 'gitignore') destName = '.gitignore';
108
+ // The repository stores the gitignore without a leading dot so npm reliably
109
+ // includes it in the published template; generated projects receive the dotfile.
110
+ let destName = entry.name;
111
+ if (entry.name === 'gitignore') destName = '.gitignore';
111
112
 
112
113
  const destPath = path.join(targetDir, destName);
113
114
 
@@ -404,7 +405,7 @@ async function main() {
404
405
  }
405
406
  }
406
407
 
407
- spinner.succeed('Project scaffolded successfully!');
408
+ spinner.succeed('Project scaffolded successfully!');
408
409
  } catch (error) {
409
410
  spinner.fail('Failed to scaffold project');
410
411
  console.error(chalk.red(`\n ${error.message}\n`));
@@ -229,11 +229,34 @@ function patchRateLimitConfig(project, targetDir) {
229
229
  sourceFile.saveSync();
230
230
  }
231
231
 
232
+ /**
233
+ * Replace one exact text anchor, failing loudly when it is missing.
234
+ *
235
+ * Text anchors used to skip silently, which hid a real bug: the login resend
236
+ * anchor never matched the template, yet the CLI reported the file as patched.
237
+ * Now a missing anchor stops the patch with a clear error. `alreadyPatchedMarker`
238
+ * makes re-running the patcher a no-op. Anchors are written with "\n"; they are
239
+ * matched against CRLF files too (Windows checkouts with core.autocrlf).
240
+ */
241
+ function replaceAnchor(content, { anchor, replacement, alreadyPatchedMarker, label, file }) {
242
+ if (content.includes(alreadyPatchedMarker)) return content;
243
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
244
+ const anchorText = anchor.split('\n').join(eol);
245
+ if (!content.includes(anchorText)) {
246
+ throw new Error(
247
+ `Could not find the ${label} in ${file} — file may have been modified. ` +
248
+ 'Apply the email-verification change by hand or restore the template code.',
249
+ );
250
+ }
251
+ return content.replace(anchorText, replacement.split('\n').join(eol));
252
+ }
253
+
232
254
  /**
233
255
  * Patch 4: auth.service.ts
234
256
  * - Export sanitizeUser function, SanitizedUser interface, AuthResult interface
235
257
  * so verification.service.ts can import them
236
- * - Add import for sendVerification and call it during register (auto-send on signup)
258
+ * - Add import for sendVerification and call it during register (auto-send on
259
+ * signup) and on a correct-password login of an unverified, non-banned account
237
260
  */
238
261
  function patchAuthService(project, targetDir) {
239
262
  const filePath = path.join(targetDir, 'server', 'src', 'modules', 'auth', 'auth.service.ts');
@@ -292,18 +315,39 @@ function patchAuthService(project, targetDir) {
292
315
  let patched = content;
293
316
 
294
317
  // Patch 1: Auto-send verification email on registration
295
- const registerAnchor = 'if (!isActive) {\n return {\n user: sanitizeUser(user),\n requiresVerification: true,\n };\n }';
296
- if (patched.includes(registerAnchor) && !patched.includes('sendVerification(input.email)')) {
297
- const registerReplacement = `if (!isActive) {\n // Auto-send verification email on registration (best-effort, don't block registration)\n sendVerification(input.email).catch(() => {});\n\n return {\n user: sanitizeUser(user),\n requiresVerification: true,\n };\n }`;
298
- patched = patched.replace(registerAnchor, registerReplacement);
299
- }
318
+ patched = replaceAnchor(patched, {
319
+ file: 'auth.service.ts',
320
+ label: 'register verification branch',
321
+ alreadyPatchedMarker: 'sendVerification(input.email)',
322
+ anchor: ' if (requiresVerification) {\n return {\n user: sanitizeUser(user),\n requiresVerification: true,\n };\n }',
323
+ replacement:
324
+ ' if (requiresVerification) {\n' +
325
+ " // Auto-send verification email on registration (best-effort, don't block registration)\n" +
326
+ ' sendVerification(input.email).catch(() => {});\n\n' +
327
+ ' return {\n user: sanitizeUser(user),\n requiresVerification: true,\n };\n }',
328
+ });
300
329
 
301
- // Patch 2: Auto-resend verification email when inactive user tries to log in
302
- const loginAnchor = " if (!user.isActive) {\n throw new ForbiddenError('Account is not activated. Please verify your account.', 'ACCOUNT_NOT_ACTIVE');\n }";
303
- if (patched.includes(loginAnchor) && !patched.includes('sendVerification(user.email)')) {
304
- const loginReplacement = " if (!user.isActive) {\n // Auto-resend verification email so user gets a fresh link\n sendVerification(user.email).catch(() => {});\n\n throw new ForbiddenError('Account is not activated. Please verify your account.', 'ACCOUNT_NOT_ACTIVE');\n }";
305
- patched = patched.replace(loginAnchor, loginReplacement);
306
- }
330
+ // Patch 2: Re-send a fresh link when an unverified user logs in with the
331
+ // correct password. It runs after the password check, so an anonymous caller
332
+ // cannot trigger emails, and never for a banned account (verification cannot
333
+ // lift a ban). assertAccountCanSignIn then answers 403 EMAIL_NOT_VERIFIED.
334
+ patched = replaceAnchor(patched, {
335
+ file: 'auth.service.ts',
336
+ label: 'login account-state check',
337
+ alreadyPatchedMarker: 'sendVerification(user.email)',
338
+ anchor:
339
+ ' // Reveal account state only now that the password is proven, so an anonymous\n' +
340
+ ' // caller cannot learn whether an email is banned or unverified.\n' +
341
+ ' assertAccountCanSignIn(user);',
342
+ replacement:
343
+ ' // Reveal account state only now that the password is proven, so an anonymous\n' +
344
+ ' // caller cannot learn whether an email is banned or unverified.\n' +
345
+ ' // Email-verification module: re-send a fresh link to an unverified (not banned) account.\n' +
346
+ ' if (user.isActive && env.REQUIRE_USER_VERIFICATION && !user.emailVerifiedAt) {\n' +
347
+ ' sendVerification(user.email).catch(() => {});\n' +
348
+ ' }\n' +
349
+ ' assertAccountCanSignIn(user);',
350
+ });
307
351
 
308
352
  if (patched !== content) {
309
353
  fs.writeFileSync(filePath, patched, 'utf-8');
@@ -312,26 +356,35 @@ function patchAuthService(project, targetDir) {
312
356
 
313
357
  /**
314
358
  * Patch 5: auth.repo.ts
315
- * - Add activateUser function at end of file
359
+ * - Add markEmailVerified function at end of file
360
+ *
361
+ * It sets emailVerifiedAt only for an active, not-yet-verified, non-deleted
362
+ * account and never touches isActive (the admin ban switch). The conditional
363
+ * write means a ban that lands mid-verification still wins. Returns whether a
364
+ * row was updated.
316
365
  */
317
366
  function patchAuthRepo(project, targetDir) {
318
367
  const filePath = path.join(targetDir, 'server', 'src', 'modules', 'auth', 'auth.repo.ts');
319
368
  const sourceFile = project.addSourceFileAtPath(filePath);
320
369
 
321
370
  // Check if already patched
322
- const existing = sourceFile.getFunction('activateUser');
371
+ const existing = sourceFile.getFunction('markEmailVerified');
323
372
  if (existing) return;
324
373
 
325
374
  sourceFile.addFunction({
326
- name: 'activateUser',
375
+ name: 'markEmailVerified',
327
376
  isExported: true,
328
377
  isAsync: true,
329
- parameters: [{ name: 'userId', type: 'string' }],
330
- returnType: 'Promise<void>',
331
- statements: `await prisma.user.update({
332
- where: { id: userId },
333
- data: { isActive: true },
334
- });`,
378
+ parameters: [
379
+ { name: 'userId', type: 'string' },
380
+ { name: 'verifiedAt', type: 'Date' },
381
+ ],
382
+ returnType: 'Promise<boolean>',
383
+ statements: `const result = await prisma.user.updateMany({
384
+ where: { id: userId, isActive: true, emailVerifiedAt: null, deletedAt: null },
385
+ data: { emailVerifiedAt: verifiedAt },
386
+ });
387
+ return result.count === 1;`,
335
388
  });
336
389
 
337
390
  sourceFile.saveSync();
@@ -444,31 +497,32 @@ function patchErrorCodes(project, targetDir) {
444
497
 
445
498
  /**
446
499
  * Patch 8: useAuth.ts (client)
447
- * - Redirect to /verify-account when login fails with ACCOUNT_NOT_ACTIVE
448
- * (the server auto-resends the verification email on this error)
500
+ * - Redirect to /verify-account when login fails with EMAIL_NOT_VERIFIED
501
+ * (the server auto-resends the verification email on this error).
502
+ * Banned accounts (ACCOUNT_DEACTIVATED) are deliberately NOT sent there:
503
+ * verifying an email cannot lift a ban.
449
504
  */
450
505
  function patchUseAuthHook(targetDir) {
451
506
  const filePath = path.join(targetDir, 'client', 'src', 'features', 'auth', 'hooks', 'useAuth.ts');
452
- if (!fs.pathExistsSync(filePath)) return;
507
+ if (!fs.pathExistsSync(filePath)) {
508
+ throw new Error('Could not find client/src/features/auth/hooks/useAuth.ts — file may have been moved');
509
+ }
453
510
 
454
511
  const content = fs.readFileSync(filePath, 'utf-8');
455
512
 
456
- // Check if already patched — look for the specific replacement text
457
- if (content.includes('Check your email for a verification link')) return;
458
-
459
- // Find the ACCOUNT_NOT_ACTIVE error handler and add redirect + update message.
460
- // Match regardless of exact indentation by searching for the key content.
461
- const anchorText = "toast.error('Your account is not yet activated. Please verify your account to continue.');";
462
-
463
- if (!content.includes(anchorText)) return; // File may have been modified
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
- );
513
+ const patched = replaceAnchor(content, {
514
+ file: 'useAuth.ts',
515
+ label: 'EMAIL_NOT_VERIFIED login error toast',
516
+ alreadyPatchedMarker: 'We sent you a new verification link',
517
+ anchor: "toast.error('Please verify your email address before signing in.');",
518
+ replacement:
519
+ "toast.error('Please verify your email address. We sent you a new verification link.');\n" +
520
+ ' router.push(ROUTES.VERIFY_ACCOUNT);',
521
+ });
470
522
 
471
- fs.writeFileSync(filePath, patched, 'utf-8');
523
+ if (patched !== content) {
524
+ fs.writeFileSync(filePath, patched, 'utf-8');
525
+ }
472
526
  }
473
527
 
474
528
  // ─── Postman Patch ──────────────────────────────────────────────
@@ -4,8 +4,10 @@ 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';
7
8
  import {
8
9
  BadRequestError,
10
+ ForbiddenError,
9
11
  NotFoundError,
10
12
  } from '@shared/errors/errors.js';
11
13
  import * as authRepo from './auth.repo.js';
@@ -21,7 +23,10 @@ const VERIFICATION_USER_PREFIX = 'verify-user:';
21
23
  /**
22
24
  * Send a verification email to a user.
23
25
  * Public endpoint — accepts email, silent return if user not found (prevents enumeration).
24
- * Also called internally by the register flow for auto-sending.
26
+ * Also called internally by the register and login flows for auto-sending.
27
+ *
28
+ * Verification proves email ownership and nothing else: it sets
29
+ * `emailVerifiedAt` and never touches `isActive` (the admin ban switch).
25
30
  */
26
31
  export async function sendVerification(email: string): Promise<void> {
27
32
  const user = await authRepo.findUserByEmail(email);
@@ -29,8 +34,11 @@ export async function sendVerification(email: string): Promise<void> {
29
34
  // Silent return if user not found — prevents email enumeration (same pattern as forgotPassword)
30
35
  if (!user) return;
31
36
 
32
- // Silent return if already verified — no need to reveal account status
33
- if (user.isActive) return;
37
+ // No token for a banned account: a verify link must never lift an admin ban
38
+ // (that is exactly how a banned user used to re-activate themselves). No
39
+ // token either when the email is already verified. Both stay silent so the
40
+ // response does not reveal the account's status.
41
+ if (!user.isActive || user.emailVerifiedAt) return;
34
42
 
35
43
  const redis = getRedis();
36
44
 
@@ -107,7 +115,8 @@ export async function verifyAccount(
107
115
  const redis = getRedis();
108
116
 
109
117
  // Atomic get-and-delete to prevent token reuse via concurrent requests
110
- const userId = await redis.getDel(`${VERIFICATION_PREFIX}${token}`);
118
+ // ioredis exposes GETDEL as getdel (all lowercase); getDel does not exist.
119
+ const userId = await redis.getdel(`${VERIFICATION_PREFIX}${token}`);
111
120
  if (!userId) {
112
121
  throw new BadRequestError('Invalid or expired verification token', 'INVALID_VERIFICATION_TOKEN');
113
122
  }
@@ -117,12 +126,32 @@ export async function verifyAccount(
117
126
  throw new NotFoundError('User not found', 'USER_NOT_FOUND');
118
127
  }
119
128
 
120
- // Activate the user account
121
- await authRepo.activateUser(userId);
122
-
123
- // Clean up the reverse-lookup key
129
+ // Clean up the reverse-lookup key (the token itself was consumed above)
124
130
  await redis.del(`${VERIFICATION_USER_PREFIX}${userId}`);
125
131
 
132
+ // A token issued before a ban must not lift the ban or open a session.
133
+ if (!user.isActive) {
134
+ throw new ForbiddenError(
135
+ 'This account has been deactivated. Contact support if you think this is a mistake.',
136
+ ACCOUNT_DEACTIVATED,
137
+ );
138
+ }
139
+
140
+ // Conditional write: only an active, not-yet-verified account is marked. If a
141
+ // ban lands between the read above and this write, the ban wins.
142
+ const verifiedAt = new Date();
143
+ const marked = await authRepo.markEmailVerified(userId, verifiedAt);
144
+ if (!marked) {
145
+ const current = await authRepo.findUserById(userId);
146
+ if (!current || !current.isActive) {
147
+ throw new ForbiddenError(
148
+ 'This account has been deactivated. Contact support if you think this is a mistake.',
149
+ ACCOUNT_DEACTIVATED,
150
+ );
151
+ }
152
+ throw new BadRequestError('This email address is already verified', 'ALREADY_VERIFIED');
153
+ }
154
+
126
155
  // Generate tokens and create session (same pattern as login)
127
156
  const accessToken = signAccessToken({
128
157
  userId: user.id,
@@ -183,7 +212,7 @@ export async function verifyAccount(
183
212
  }
184
213
 
185
214
  return {
186
- user: sanitizeUser({ ...user, isActive: true }),
215
+ user: sanitizeUser({ ...user, emailVerifiedAt: verifiedAt }),
187
216
  accessToken,
188
217
  refreshToken,
189
218
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-tigra",
3
- "version": "3.1.1",
3
+ "version": "3.3.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": {
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: security-audit
3
+ description: Security guidance and vulnerability review for codebases, APIs, services, CLI tools, libraries, and daemons. Use for security questions, focused reviews, vulnerability research, security audits, or pen tests. Run the complete workflow only for explicit codebase audit or pen-test requests, full/comprehensive/end-to-end reviews, or requested report artifacts.
4
+ ---
5
+
6
+ # Security Audit (pointer)
7
+
8
+ This is a thin pointer so Claude Code discovers the skill. The real skill is shared with Codex and lives in `.agents/skills/security-audit/` (vendored from Cloudflare's `security-audit-skill`; see its `SOURCE.md`). Do not copy it here, so the two agents never drift.
9
+
10
+ Read `.agents/skills/security-audit/SKILL.md` in full and follow it exactly. Resolve every relative file it references (for example `HUNTING.md`, `report-schema.json`, the `validate-*.cjs` scripts) against `.agents/skills/security-audit/`, not this directory. Its "Task tool" is Claude Code's subagent mechanism.
@@ -4,6 +4,22 @@
4
4
 
5
5
  Every implementation change MUST include a human-readability pass. Add or update concise comments or doc comments for important functionality and for non-obvious contracts, invariants, edge cases, business rules, security boundaries, deployment constraints, performance choices, and workarounds. Explain why and what must remain true; do not narrate obvious syntax. Keep comments accurate and remove stale ones.
6
6
 
7
+ <!-- project-facts:start -->
8
+ ## Project facts
9
+
10
+ > Maintained by the `seed-project-facts` skill: run it once to fill the TODOs. This section is the source of truth for this project: keep it true. If your work changes any line (deployment, URLs, hosting, databases, Redis, integrations, rules), update it and the seed-plugins registry row in the same change. If it conflicts with reality, trust reality, fix it, and tell Tornike. No secrets here.
11
+
12
+ - **Name:** {{PROJECT_NAME}}
13
+ - **Purpose:** TODO
14
+ - **Production:** TODO (client URL / server URL, or "not deployed")
15
+ - **Hosting:** TODO (Coolify instance, or none)
16
+ - **Local MySQL:** `{{DATABASE_NAME}}` on TODO (central-mysql | per-project container)
17
+ - **Production MySQL:** TODO (`db` on shared MySQL on <instance> | dedicated Coolify MySQL | none)
18
+ - **Redis:** TODO (local yes/no / production yes/no)
19
+ - **Talks to:** TODO
20
+ - **Special rules:** none
21
+ <!-- project-facts:end -->
22
+
7
23
  ## Architecture and sources of truth
8
24
 
9
25
  - `client/` is a Next.js App Router application; `server/` is a Fastify API backed by Prisma/MySQL and Redis. They deploy independently.
@@ -36,8 +52,8 @@ Every implementation change MUST include a human-readability pass. Add or update
36
52
  ## Required server security workflow
37
53
 
38
54
  - For every meaningful server implementation, bug fix, refactor, dependency update, or configuration change, use the repository-local `security-audit` skill in guidance mode while designing and reviewing the change. Treat authentication, authorization, validation, database access, outbound requests, uploads, cookies, CORS/origin handling, rate limits, environment configuration, and deployment behavior as security-sensitive surfaces.
39
- - Before completion, use the Codex Security plugin's `codex-security:security-diff-scan` skill to review the current working-tree patch when that plugin skill is available. Scope the review to the changed server behavior and the supporting code needed to establish impact; do not expand it into an unrelated repository audit.
40
- - If Codex Security is unavailable, perform an equivalent focused patch review with the bundled `security-audit` skill and explicitly report that the plugin scan was unavailable. Do not skip the security gate silently.
55
+ - Before completion, review the current working-tree patch with the agent's own security scan when available: in Codex use the Codex Security plugin's `codex-security:security-diff-scan` skill; in Claude Code run `/security-review`. Scope the review to the changed server behavior and the supporting code needed to establish impact; do not expand it into an unrelated repository audit.
56
+ - If that scan is unavailable, perform an equivalent focused patch review with the bundled `security-audit` skill and explicitly report that the scan was unavailable. Do not skip the security gate silently.
41
57
  - A full or deep repository audit remains explicit work: do not start one merely because ordinary server code changed. Fix confirmed in-scope findings, rerun affected checks, and disclose any unresolved or unverified security concern before claiming completion.
42
58
  - Documentation-only, comment-only, and formatting-only changes may skip the patch scan when they cannot affect runtime behavior, permissions, deployment, or security policy.
43
59
 
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -57,8 +57,10 @@ export const AuthInitializer = ({ children }: AuthInitializerProps): React.React
57
57
 
58
58
  const status = (error as HttpLikeError)?.response?.status;
59
59
  if (status === 401 || status === 403) {
60
- if (isErrorCode(error, ERROR_CODES.ACCOUNT_NOT_ACTIVE)) {
61
- toast.error('Your account is not yet activated. Please verify your account.');
60
+ if (isErrorCode(error, ERROR_CODES.ACCOUNT_DEACTIVATED)) {
61
+ toast.error('This account has been deactivated. Contact support if you think this is a mistake.');
62
+ } else if (isErrorCode(error, ERROR_CODES.EMAIL_NOT_VERIFIED)) {
63
+ toast.error('Please verify your email address before signing in.');
62
64
  }
63
65
  router.push(ROUTES.LOGIN);
64
66
  }
@@ -16,6 +16,7 @@ import { AppLink } from '@/components/common/AppLink';
16
16
  import { useAuth } from '../hooks/useAuth';
17
17
  import { ROUTES } from '@/lib/constants/routes';
18
18
  import { cn } from '@/lib/utils';
19
+ import { getSafeRedirectPath } from '@/lib/utils/security';
19
20
 
20
21
  const loginSchema = z.object({
21
22
  email: z.string().min(1, 'Email is required').email('Invalid email address'),
@@ -27,8 +28,10 @@ type LoginFormData = z.infer<typeof loginSchema>;
27
28
  const LoginFormInner = (): React.ReactElement => {
28
29
  const { login, isLoggingIn } = useAuth();
29
30
  const searchParams = useSearchParams();
30
- const from = searchParams.get('from');
31
- const redirectTo = from && from.startsWith('/') && !from.startsWith('//') ? from : undefined;
31
+ // `from` is attacker-controllable (anyone can send a /login?from=… link), so
32
+ // only a same-site path is accepted — see getSafeRedirectPath for why a
33
+ // simple prefix check let `/\evil.com` through.
34
+ const redirectTo = getSafeRedirectPath(searchParams.get('from'));
32
35
 
33
36
  const {
34
37
  register,
@@ -9,6 +9,7 @@ import { useAppDispatch, useAppSelector } from '@/store/hooks';
9
9
  import { useAppRouter } from '@/hooks/useAppRouter';
10
10
  import { getErrorMessage, isErrorCode, ERROR_CODES } from '@/lib/utils/error';
11
11
  import { ROUTES } from '@/lib/constants/routes';
12
+ import { getSafeRedirectPath } from '@/lib/utils/security';
12
13
  import { authService } from '../services/auth.service';
13
14
  import { setUser, setLoggingOut, logout as logoutAction } from '../store/authSlice';
14
15
 
@@ -42,8 +43,12 @@ export const useAuth = (): UseAuthReturn => {
42
43
  router.push(pendingRedirectRef.current);
43
44
  },
44
45
  onError: (error) => {
45
- if (isErrorCode(error, ERROR_CODES.ACCOUNT_NOT_ACTIVE)) {
46
- toast.error('Your account is not yet activated. Please verify your account to continue.');
46
+ if (isErrorCode(error, ERROR_CODES.ACCOUNT_DEACTIVATED)) {
47
+ toast.error('This account has been deactivated. Contact support if you think this is a mistake.');
48
+ return;
49
+ }
50
+ if (isErrorCode(error, ERROR_CODES.EMAIL_NOT_VERIFIED)) {
51
+ toast.error('Please verify your email address before signing in.');
47
52
  return;
48
53
  }
49
54
  toast.error(getErrorMessage(error));
@@ -53,8 +58,10 @@ export const useAuth = (): UseAuthReturn => {
53
58
  const registerMutation = useMutation({
54
59
  mutationFn: (data: IRegisterRequest) => authService.register(data),
55
60
  onSuccess: (data) => {
56
- if (!data.user.isActive) {
57
- toast.success('Account created! Please verify your account to continue.');
61
+ // No session is issued until the email is verified (server returns the
62
+ // user with emailVerifiedAt = null when verification is required).
63
+ if (!data.user.emailVerifiedAt) {
64
+ toast.success('Account created! Please verify your email address to continue.');
58
65
  router.push(ROUTES.VERIFY_ACCOUNT);
59
66
  return;
60
67
  }
@@ -86,8 +93,11 @@ export const useAuth = (): UseAuthReturn => {
86
93
  isAuthenticated,
87
94
  isInitializing,
88
95
  login: (data: ILoginRequest, redirectTo?: string) => {
89
- if (redirectTo) {
90
- pendingRedirectRef.current = redirectTo;
96
+ // Validate again at the sink: whatever a caller passes, router.push after
97
+ // login only ever receives a same-site path.
98
+ const safeRedirect = getSafeRedirectPath(redirectTo);
99
+ if (safeRedirect) {
100
+ pendingRedirectRef.current = safeRedirect;
91
101
  }
92
102
  loginMutation.mutate(data);
93
103
  },
@@ -4,7 +4,10 @@ export interface IUser {
4
4
  firstName: string;
5
5
  lastName: string;
6
6
  role: UserRole;
7
+ /** Admin ban switch: false = deactivated by an admin. */
7
8
  isActive: boolean;
9
+ /** ISO timestamp of email verification; null while unverified. */
10
+ emailVerifiedAt: string | null;
8
11
  avatarUrl: string | null;
9
12
  createdAt: string;
10
13
  updatedAt: string;
@@ -15,12 +15,20 @@ let sentryPromise: Promise<SentryNext> | null = null;
15
15
  function loadSentry(): Promise<SentryNext | null> {
16
16
  if (!sentryEnabled || !dsn) return Promise.resolve(null);
17
17
 
18
- sentryPromise ??= import('@sentry/nextjs').then((Sentry) => {
18
+ sentryPromise ??= Promise.all([
19
+ import('@sentry/nextjs'),
20
+ import('./lib/observability/sentry-scrub'),
21
+ ]).then(([Sentry, { scrubSentryEvent }]) => {
19
22
  Sentry.init({
20
23
  dsn,
21
24
  tracesSampleRate: process.env.NEXT_PUBLIC_SENTRY_TRACES_SAMPLE_RATE
22
25
  ? Number(process.env.NEXT_PUBLIC_SENTRY_TRACES_SAMPLE_RATE)
23
26
  : 0.1,
27
+ sendDefaultPii: false,
28
+ // Page URLs like /reset-password?token=… and /verify-account?token=…
29
+ // carry credentials: strip query strings and cookies from every event.
30
+ beforeSend: (event) => scrubSentryEvent(event),
31
+ beforeSendTransaction: (event) => scrubSentryEvent(event),
24
32
  });
25
33
 
26
34
  return Sentry;
@@ -27,10 +27,16 @@ export async function register(): Promise<void> {
27
27
  if (!Sentry || !dsn) return;
28
28
 
29
29
  if (process.env.NEXT_RUNTIME === 'nodejs' || process.env.NEXT_RUNTIME === 'edge') {
30
+ const { scrubSentryEvent } = await import('./lib/observability/sentry-scrub');
30
31
  Sentry.init({
31
32
  dsn,
32
33
  tracesSampleRate,
33
34
  environment: process.env.SENTRY_ENVIRONMENT ?? process.env.NODE_ENV,
35
+ sendDefaultPii: false,
36
+ // captureRequestError attaches request headers (incl. Cookie): strip
37
+ // cookies, auth headers and token query strings before anything is sent.
38
+ beforeSend: (event) => scrubSentryEvent(event),
39
+ beforeSendTransaction: (event) => scrubSentryEvent(event),
34
40
  });
35
41
  }
36
42
  }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Privacy filter for Sentry events sent from the Next.js app (browser and the
3
+ * Node/Edge server runtime). Mirrors the API server's scrubber
4
+ * (server/src/libs/observability/sentry.ts) — keep the two in step.
5
+ *
6
+ * Why it exists: Next's `captureRequestError` attaches the incoming request's
7
+ * headers (including the Cookie header), and the browser SDK attaches the page
8
+ * URL and the Referer, both as request headers and as span/trace attributes.
9
+ * Page URLs such as /reset-password?token=… and /verify-account?token=… carry
10
+ * credentials, so every URL-like value loses its query string and fragment,
11
+ * and cookie/auth headers are dropped, before anything is sent.
12
+ *
13
+ * Kept dependency-free (type-only import) so it never pulls @sentry/nextjs into
14
+ * a bundle by itself.
15
+ */
16
+ import type { Event } from '@sentry/nextjs';
17
+
18
+ const SECRET_HEADERS = new Set(['cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key']);
19
+ const URL_HEADERS = new Set(['referer', 'referrer']);
20
+
21
+ /** Drop the query string and fragment: tokens travel there. */
22
+ function withoutQuery(url: string): string {
23
+ const cut = url.search(/[?#]/);
24
+ return cut === -1 ? url : url.slice(0, cut);
25
+ }
26
+
27
+ /**
28
+ * Clean a free-form attribute bag (breadcrumb data, span data, trace data):
29
+ * strip queries from anything URL-like, drop query/cookie/auth attributes.
30
+ */
31
+ function scrubData(data: Record<string, unknown> | undefined): void {
32
+ if (!data) return;
33
+ for (const key of Object.keys(data)) {
34
+ const lower = key.toLowerCase();
35
+ if (lower.includes('query') || lower.includes('cookie') || lower.includes('authorization')) {
36
+ delete data[key];
37
+ continue;
38
+ }
39
+ const value = data[key];
40
+ if (
41
+ typeof value === 'string' &&
42
+ (lower.includes('url') || lower.includes('referer') || lower.includes('target') || lower === 'from' || lower === 'to')
43
+ ) {
44
+ data[key] = withoutQuery(value);
45
+ }
46
+ }
47
+ }
48
+
49
+ export function scrubSentryEvent<T extends Event>(event: T): T {
50
+ const request = event.request;
51
+ if (request) {
52
+ delete request.data;
53
+ delete request.cookies;
54
+ delete request.query_string;
55
+ if (request.url) request.url = withoutQuery(request.url);
56
+ if (request.headers) {
57
+ for (const name of Object.keys(request.headers)) {
58
+ const lower = name.toLowerCase();
59
+ if (SECRET_HEADERS.has(lower)) delete request.headers[name];
60
+ else if (URL_HEADERS.has(lower)) request.headers[name] = withoutQuery(request.headers[name]);
61
+ }
62
+ }
63
+ }
64
+
65
+ if (event.transaction) event.transaction = withoutQuery(event.transaction);
66
+ for (const crumb of event.breadcrumbs ?? []) scrubData(crumb.data as Record<string, unknown> | undefined);
67
+ for (const span of event.spans ?? []) scrubData(span.data as Record<string, unknown> | undefined);
68
+ scrubData(event.contexts?.trace?.data as Record<string, unknown> | undefined);
69
+
70
+ return event;
71
+ }
@@ -31,6 +31,10 @@ export const isErrorCode = (error: unknown, code: string): boolean => {
31
31
  return getErrorCode(error) === code;
32
32
  };
33
33
 
34
+ // Account-state codes from the server (src/libs/account-status.ts). They are
35
+ // separate on purpose: a deactivated (banned) account must never be steered to
36
+ // email verification, because verifying cannot lift a ban.
34
37
  export const ERROR_CODES = {
35
- ACCOUNT_NOT_ACTIVE: 'ACCOUNT_NOT_ACTIVE',
38
+ ACCOUNT_DEACTIVATED: 'ACCOUNT_DEACTIVATED',
39
+ EMAIL_NOT_VERIFIED: 'EMAIL_NOT_VERIFIED',
36
40
  } as const;