create-tigra 4.1.0 → 5.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.
Files changed (140) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +4 -1
  3. package/bin/create-tigra.js +68 -73
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +33 -59
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +18 -18
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +10 -0
  10. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  11. package/modules/diagnostics/prisma/migration.sql +1 -24
  12. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
  13. package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
  14. package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
  15. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  16. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  17. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  18. package/modules/email-verification/server/verification.service.ts +102 -157
  19. package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
  20. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
  21. package/modules/metrics/performance.md +2 -2
  22. package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
  23. package/modules/metrics/server/metrics.collector.ts +6 -3
  24. package/modules/metrics/server/metrics.routes.ts +1 -2
  25. package/modules/metrics/server/metrics.service.ts +6 -2
  26. package/package.json +1 -1
  27. package/template/AGENTS.md +4 -3
  28. package/template/client/.dockerignore +2 -5
  29. package/template/client/gitignore +43 -0
  30. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  31. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  32. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  33. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  34. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  35. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  36. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  37. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  38. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  39. package/template/client/src/lib/api/axios.config.ts +24 -6
  40. package/template/client/src/lib/api/session-events.ts +54 -0
  41. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  42. package/template/client/src/store/__tests__/store.test.ts +1 -0
  43. package/template/gitignore +3 -2
  44. package/template/server/.dockerignore +2 -5
  45. package/template/server/.env.example +1 -0
  46. package/template/server/.env.example.production +1 -0
  47. package/template/server/README.md +7 -2
  48. package/template/server/docs/deployment.md +66 -0
  49. package/template/server/docs/logging.md +9 -8
  50. package/template/server/docs/rate-limits.md +6 -4
  51. package/template/server/gitignore +33 -0
  52. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  53. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  54. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  55. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  56. package/template/server/prisma/schema.prisma +25 -1
  57. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  58. package/template/server/src/app.ts +14 -5
  59. package/template/server/src/config/env.ts +8 -0
  60. package/template/server/src/config/rate-limit.config.ts +1 -1
  61. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  62. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  63. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  64. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  65. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  66. package/template/server/src/jobs/index.ts +8 -2
  67. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  68. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  69. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  70. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  71. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  72. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  73. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  74. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  75. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  76. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  77. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  78. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  79. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  80. package/template/server/src/libs/account-mutation.ts +77 -0
  81. package/template/server/src/libs/auth.ts +37 -3
  82. package/template/server/src/libs/cookies.ts +25 -13
  83. package/template/server/src/libs/email-quota.ts +11 -7
  84. package/template/server/src/libs/email.ts +11 -8
  85. package/template/server/src/libs/error-handler.ts +16 -12
  86. package/template/server/src/libs/http.ts +37 -13
  87. package/template/server/src/libs/ip-block.ts +56 -34
  88. package/template/server/src/libs/logger.ts +23 -8
  89. package/template/server/src/libs/monitoring.ts +57 -31
  90. package/template/server/src/libs/observability/sentry.ts +65 -49
  91. package/template/server/src/libs/prisma.ts +1 -1
  92. package/template/server/src/libs/private-cache.ts +6 -0
  93. package/template/server/src/libs/rate-limiting.ts +4 -0
  94. package/template/server/src/libs/requestLogger.ts +3 -3
  95. package/template/server/src/libs/safe-http.ts +58 -18
  96. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  97. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  98. package/template/server/src/libs/storage/file-validator.ts +2 -1
  99. package/template/server/src/libs/url-safety.ts +10 -2
  100. package/template/server/src/libs/validation-errors.ts +11 -8
  101. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  102. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  103. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  104. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  105. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  106. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  107. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  108. package/template/server/src/modules/admin/admin.service.ts +61 -62
  109. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  110. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  111. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  112. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  113. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  114. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  115. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  116. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  117. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  118. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  119. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  120. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  121. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  122. package/template/server/src/modules/auth/auth.service.ts +33 -237
  123. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  124. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  125. package/template/server/src/modules/auth/session.repo.ts +5 -4
  126. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  127. package/template/server/src/modules/files/files.controller.ts +2 -2
  128. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  129. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  130. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  131. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  132. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  133. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  134. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  135. package/template/server/src/modules/users/users.controller.ts +28 -25
  136. package/template/server/src/modules/users/users.repo.ts +12 -51
  137. package/template/server/src/modules/users/users.service.ts +109 -234
  138. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  139. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  140. package/template/server/src/test/setup.ts +4 -0
@@ -1,6 +1,8 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { installModule } from '../installer-transaction.js';
5
+ import { nextModuleMigration } from '../project-files.js';
4
6
 
5
7
  const payload = fileURLToPath(new URL('../../modules/diagnostics/', import.meta.url));
6
8
  const moduleDir = 'server/src/modules/diagnostics';
@@ -28,8 +30,9 @@ const transforms = {
28
30
  [' };\n\n const firstRun', ' });\n\n const firstRun'],
29
31
  ],
30
32
  'server/src/modules/admin/admin.routes.ts': [
31
- ["import { authenticate, authorize } from '@libs/auth.js';", "import { authenticate, authorize } from '@libs/auth.js';\nimport { registerAdminDiagnosticsRoute } from '@modules/diagnostics/diagnostics.routes.js';"],
32
- [" fastify.addHook('preValidation', authorize('ADMIN'));", " fastify.addHook('preValidation', authorize('ADMIN'));\n registerAdminDiagnosticsRoute(fastify);"],
33
+ ["import { RATE_LIMITS } from '@config/rate-limit.config.js';", "import { registerAdminDiagnosticsRoute } from '@modules/diagnostics/diagnostics.routes.js';", true],
34
+ // Keep retrofits compatible with apps that still use the original admin hooks.
35
+ [[" registerAdminAuthorization(fastify);", " fastify.addHook('preValidation', authorize('ADMIN'));"], ' registerAdminDiagnosticsRoute(fastify);', true],
33
36
  ],
34
37
  'server/src/__tests__/routes.integration.test.ts': [
35
38
  ['const COVERED_ELSEWHERE: Record<string, string> = {', "const COVERED_ELSEWHERE: Record<string, string> = {\n 'GET /api/v1/admin/diagnostics': 'src/modules/diagnostics/__tests__/diagnostics.integration.test.ts',"],
@@ -42,35 +45,23 @@ const transforms = {
42
45
  function patch(file, content, edits) {
43
46
  const newline = content.includes('\r\n') ? '\r\n' : '\n';
44
47
  let patched = content.replaceAll('\r\n', '\n');
45
- for (const [anchor, replacement] of edits) {
46
- const index = patched.indexOf(anchor);
47
- if (index === -1 || patched.indexOf(anchor, index + anchor.length) !== -1) {
48
+ for (const [anchors, replacement, append] of edits) {
49
+ const matches = [anchors].flat().filter((anchor) => patched.includes(anchor));
50
+ const [anchor] = matches;
51
+ if (matches.length !== 1 || patched.indexOf(anchor, patched.indexOf(anchor) + anchor.length) !== -1) {
48
52
  throw new Error(`Cannot install diagnostics: expected one integration point in ${file}.`);
49
53
  }
50
- patched = patched.replace(anchor, replacement);
54
+ patched = patched.replace(anchor, append ? `${anchor}\n${replacement}` : replacement);
51
55
  }
52
56
  return patched.replaceAll('\n', newline);
53
57
  }
54
58
 
55
- function migrationName(existing) {
56
- const timestamp = (date) => date.toISOString().slice(0, 19).replace(/\D/g, '');
57
- const now = new Date();
58
- let name = `${timestamp(now)}_diagnostics`;
59
- const last = existing.at(-1);
60
- if (!last || last < name) return name;
61
- const date = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_/.exec(last);
62
- if (date) {
63
- const [, year, month, day, hour, minute, second] = date;
64
- const lastTime = Date.parse(`${year}-${month}-${day}T${hour}:${minute}:${second}Z`);
65
- if (Number.isFinite(lastTime)) name = `${timestamp(new Date(lastTime + 1_000))}_diagnostics`;
66
- }
67
- if (last >= name) throw new Error('Cannot place the diagnostics migration after the existing migrations.');
68
- return name;
59
+ export function applyDiagnosticsModule(root) {
60
+ return installModule(root, planDiagnostics);
69
61
  }
70
62
 
71
- export async function applyDiagnosticsModule(root) {
72
- const at = (file) => path.join(root, file);
73
- const read = (file) => fs.readFile(at(file), 'utf8');
63
+ async function planDiagnostics({ read: readFile, exists, list }) {
64
+ const read = (file) => readFile(file, 'utf8');
74
65
  const originalSchema = await read(schema);
75
66
  const agents = await read('AGENTS.md');
76
67
  const serverPayload = path.join(payload, 'server');
@@ -82,8 +73,8 @@ export async function applyDiagnosticsModule(root) {
82
73
  });
83
74
  sources.push([path.join(payload, 'diagnostics.md'), guide]);
84
75
 
85
- if (await fs.pathExists(at(marker))) {
86
- const { migration } = await fs.readJson(at(marker));
76
+ if (await exists(marker)) {
77
+ const { migration } = JSON.parse(await read(marker));
87
78
  const expected = typeof migration === 'string' && /^\d{14}_diagnostics$/.test(migration);
88
79
  const installedFiles = [...sources.map(([, file]) => file), `${migrations}/${migration}/migration.sql`];
89
80
  const integrations = await Promise.all(Object.entries(transforms).map(async ([file, edits]) => {
@@ -92,58 +83,41 @@ export async function applyDiagnosticsModule(root) {
92
83
  return edits.every(([, replacement]) => replacement.split('\n').every((line) => content.includes(line)));
93
84
  }));
94
85
  if (!expected || !originalSchema.includes('model DiagnosticBucket') || !agents.includes(heading) ||
95
- !integrations.every(Boolean) || !(await Promise.all(installedFiles.map((file) => fs.pathExists(at(file))))).every(Boolean)) {
86
+ !integrations.every(Boolean) || !(await Promise.all(installedFiles.map((file) => exists(file)))).every(Boolean)) {
96
87
  throw new Error('The diagnostics installation is incomplete. Restore the missing integration or pre-install state.');
97
88
  }
98
89
  return false;
99
90
  }
100
91
 
101
- const existing = (await fs.readdir(at(migrations), { withFileTypes: true }))
92
+ const existing = (await list(migrations))
102
93
  .filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
103
94
  if (!/provider\s*=\s*"mysql"/.test(originalSchema) || /DiagnosticBucket|diagnostic_buckets/.test(originalSchema) ||
104
- agents.includes(heading) || await fs.pathExists(at(moduleDir)) || existing.some((name) => name.endsWith('_diagnostics'))) {
95
+ agents.includes(heading) || await exists(moduleDir) || existing.some((name) => name.endsWith('_diagnostics'))) {
105
96
  throw new Error('Diagnostics requires a compatible MySQL Tigra project with no partial diagnostics installation.');
106
97
  }
107
98
 
108
- // Prepare the full change before writing any file. If a write fails, restore
109
- // the original files in reverse order and leave the completion marker absent.
110
- const migration = migrationName(existing);
111
- sources.push([path.join(payload, 'prisma/migration.sql'), `${migrations}/${migration}/migration.sql`]);
112
- const writes = [];
99
+ const migration = nextModuleMigration(await list(migrations), 'diagnostics');
100
+ const migrationFile = `${migrations}/${migration}/migration.sql`;
101
+ sources.push([path.join(payload, 'prisma/migration.sql'), migrationFile]);
102
+ const writes = new Map();
113
103
  for (const [source, file] of sources) {
114
- if (await fs.pathExists(at(file))) throw new Error(`Cannot install diagnostics: ${file} already exists.`);
115
- writes.push({ file, next: await fs.readFile(source) });
104
+ if (await exists(file)) throw new Error(`Cannot install diagnostics: ${file} already exists.`);
105
+ writes.set(file, await fs.readFile(source));
116
106
  }
107
+ // Keep the view SQL usable on its own for projects with an applied migration.
108
+ const view = await fs.readFile(path.join(payload, 'prisma/diagnostic-hourly-view.sql'));
109
+ writes.set(migrationFile, Buffer.concat([writes.get(migrationFile), Buffer.from('\n'), view]));
117
110
  for (const [file, edits] of Object.entries(transforms)) {
118
111
  const original = await read(file);
119
112
  if (original.includes('@modules/diagnostics/') || original.includes('GET /api/v1/admin/diagnostics')) {
120
113
  throw new Error(`Cannot install over partial diagnostics integration in ${file}.`);
121
114
  }
122
- writes.push({ file, original, next: patch(file, original, edits) });
115
+ writes.set(file, patch(file, original, edits));
123
116
  }
124
117
  const model = await fs.readFile(path.join(payload, 'prisma/diagnostic-bucket.prisma'), 'utf8');
125
- writes.push({ file: schema, original: originalSchema, next: `${originalSchema.trimEnd()}\n\n${model}` });
126
- writes.push({ file: 'AGENTS.md', original: agents, next: `${agents.trimEnd()}\n\n${instruction}` });
127
- writes.push({ file: marker, next: `${JSON.stringify({ migration }, null, 2)}\n` });
118
+ writes.set(schema, `${originalSchema.trimEnd()}\n\n${model}`);
119
+ writes.set('AGENTS.md', `${agents.trimEnd()}\n\n${instruction}`);
120
+ writes.set(marker, `${JSON.stringify({ migration }, null, 2)}\n`);
128
121
 
129
- // An exclusive directory creation keeps two diagnostics installers from
130
- // writing the same checkout after both complete preflight.
131
- await fs.mkdir(at(moduleDir));
132
- const attempted = [];
133
- try {
134
- for (const write of writes) {
135
- attempted.push(write);
136
- await fs.outputFile(at(write.file), write.next);
137
- }
138
- } catch (error) {
139
- for (const { file, original } of attempted.reverse()) {
140
- if (original === undefined) await fs.unlink(at(file)).catch((failure) => { if (failure.code !== 'ENOENT') throw failure; });
141
- else await fs.writeFile(at(file), original);
142
- }
143
- for (const file of [`${moduleDir}/__tests__`, moduleDir, `${migrations}/${migration}`]) {
144
- await fs.rmdir(at(file)).catch(() => {}); // Only empty directories created by this installer.
145
- }
146
- throw error;
147
- }
148
- return true;
122
+ return writes;
149
123
  }
@@ -10,76 +10,89 @@ import { Project, SyntaxKind } from 'ts-morph';
10
10
  import fs from 'fs-extra';
11
11
  import path from 'path';
12
12
  import { fileURLToPath } from 'url';
13
+ import { installModule } from '../installer-transaction.js';
13
14
 
14
15
  const __filename = fileURLToPath(import.meta.url);
15
16
  const __dirname = path.dirname(__filename);
16
17
  const ROOT_DIR = path.join(__dirname, '..', '..');
17
18
  const MODULES_DIR = path.join(ROOT_DIR, 'modules', 'email-verification');
18
19
 
19
- /**
20
- * Apply the email verification module to a generated project.
21
- * Copies module files and patches existing files via ts-morph AST transforms.
22
- *
23
- * @param {string} targetDir - Path to the generated project root
24
- */
25
- export async function applyEmailVerificationModule(targetDir) {
26
- // A) Copy module files
27
- await copyModuleFiles(targetDir);
28
-
29
- // B) Patch server files via ts-morph
30
- const project = new Project({
31
- useInMemoryFileSystem: false,
32
- skipAddingFilesFromTsConfig: true,
33
- });
34
-
35
- patchAuthRoutes(project, targetDir);
36
- patchAuthSchemas(project, targetDir);
37
- patchRateLimitConfig(project, targetDir);
38
- patchAuthService(project, targetDir);
39
- patchAuthRepo(project, targetDir);
40
- patchVerificationDefault(targetDir);
41
-
42
- // C) Patch client files via ts-morph
43
- patchApiEndpoints(project, targetDir);
44
- patchErrorCodes(project, targetDir);
45
- patchUseAuthHook(targetDir);
46
-
47
- // D) Patch Postman collection (JSON, not ts-morph)
48
- await patchPostmanCollection(targetDir);
49
- }
50
-
51
- // ─── File Copy ──────────────────────────────────────────────────
20
+ const auth = 'server/src/modules/auth';
21
+ const frontend = 'client/src/features/auth';
22
+ const payload = new Map([
23
+ ['server/verification.service.ts', `${auth}/verification.service.ts`],
24
+ ['server/verification.controller.ts', `${auth}/verification.controller.ts`],
25
+ ['server/__tests__/verification.integration.test.ts', `${auth}/__tests__/verification.integration.test.ts`],
26
+ ['server/__tests__/verification.service.test.ts', `${auth}/__tests__/verification.service.test.ts`],
27
+ ['client/services/verification.service.ts', `${frontend}/services/verification.service.ts`],
28
+ ['client/hooks/useVerification.ts', `${frontend}/hooks/useVerification.ts`],
29
+ ]);
30
+ const integration = new Map([
31
+ [`${auth}/auth.routes.ts`, ["'/auth/send-verification'", "'/auth/verify-account'", 'handler: verificationController.sendVerification', 'handler: verificationController.verifyAccount']],
32
+ [`${auth}/auth.schemas.ts`, ['sendVerificationSchema', 'verifyAccountSchema']],
33
+ [`${auth}/auth.service.ts`, ['sendVerification(input.email', 'sendVerification(user.email']],
34
+ ['server/src/config/rate-limit.config.ts', ['AUTH_SEND_VERIFICATION', 'AUTH_VERIFY_ACCOUNT']],
35
+ ['server/src/config/env.ts', ['REQUIRE_USER_VERIFICATION: envBoolean(true)']],
36
+ ['server/src/jobs/index.ts', ['startEmailVerificationJob(app)']],
37
+ ['client/src/lib/constants/api-endpoints.ts', ['SEND_VERIFICATION', 'VERIFY_ACCOUNT']],
38
+ ['client/src/lib/utils/error.ts', ['ALREADY_VERIFIED', 'INVALID_VERIFICATION_TOKEN']],
39
+ [`${frontend}/hooks/useAuth.ts`, ['router.push(ROUTES.VERIFY_ACCOUNT)']],
40
+ ]);
41
+ const legacyMarker = `${auth}/verification.service.ts`;
42
+ const patchFiles = [
43
+ ...integration.keys(), ...payload.values(), 'server/.env', 'server/.env.example',
44
+ 'server/.env.example.production', 'server/postman/collection.json',
45
+ ];
46
+
47
+ export function applyEmailVerificationModule(root) {
48
+ return installModule(root, async ({ read, exists, stage }) => {
49
+ // A checkout built before the auth and browser-session changes needs a
50
+ // retrofit first. Keep that compatibility check inside the project lock.
51
+ for (const file of [
52
+ `${auth}/auth-mail-queue.ts`, `${auth}/auth-link-store.ts`,
53
+ 'server/src/libs/account-mutation.ts', `${frontend}/hooks/useSessionTransition.ts`,
54
+ ]) {
55
+ if (!await exists(file)) {
56
+ throw new Error('This project needs the current Tigra auth infrastructure before installing email verification. See the account verification upgrade guide.');
57
+ }
58
+ }
59
+ const present = await Promise.all([...payload.values()].map(exists));
60
+ const states = await Promise.all([...integration].map(async ([file, markers]) => {
61
+ const content = await read(file, 'utf8');
62
+ return markers.map((marker) => content.includes(marker));
63
+ }));
64
+ // A few client errors/endpoints may already exist with the module off.
65
+ const dedicatedIntegrations = states.slice(0, 6);
66
+ if (present.some(Boolean) || dedicatedIntegrations.flat().some(Boolean)) {
67
+ if (present.every(Boolean) && states.flat().every(Boolean)) return null;
68
+ throw new Error('The email verification installation is incomplete. Restore the missing integration or pre-install state.');
69
+ }
52
70
 
53
- async function copyModuleFiles(targetDir) {
54
- const copies = [
55
- {
56
- src: path.join(MODULES_DIR, 'server', 'verification.service.ts'),
57
- dest: path.join(targetDir, 'server', 'src', 'modules', 'auth', 'verification.service.ts'),
58
- },
59
- {
60
- src: path.join(MODULES_DIR, 'server', 'verification.controller.ts'),
61
- dest: path.join(targetDir, 'server', 'src', 'modules', 'auth', 'verification.controller.ts'),
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
- },
69
- {
70
- src: path.join(MODULES_DIR, 'client', 'services', 'verification.service.ts'),
71
- dest: path.join(targetDir, 'client', 'src', 'features', 'auth', 'services', 'verification.service.ts'),
72
- },
73
- {
74
- src: path.join(MODULES_DIR, 'client', 'hooks', 'useVerification.ts'),
75
- dest: path.join(targetDir, 'client', 'src', 'features', 'auth', 'hooks', 'useVerification.ts'),
76
- },
77
- ];
71
+ const writes = await stage(patchFiles, async (targetDir) => {
72
+ for (const [source, relative] of payload) {
73
+ const dest = path.join(targetDir, relative);
74
+ await fs.ensureDir(path.dirname(dest));
75
+ await fs.copyFile(path.join(MODULES_DIR, source), dest);
76
+ }
77
+ const project = new Project({ useInMemoryFileSystem: false, skipAddingFilesFromTsConfig: true });
78
+ patchAuthRoutes(project, targetDir);
79
+ patchAuthSchemas(project, targetDir);
80
+ patchRateLimitConfig(project, targetDir);
81
+ patchAuthService(project, targetDir);
82
+ patchVerificationJob(project, targetDir);
83
+ patchVerificationDefault(targetDir);
84
+ patchApiEndpoints(project, targetDir);
85
+ patchErrorCodes(project, targetDir);
86
+ patchUseAuthHook(targetDir);
87
+ await patchPostmanCollection(targetDir);
88
+ });
78
89
 
79
- for (const { src, dest } of copies) {
80
- await fs.ensureDir(path.dirname(dest));
81
- await fs.copy(src, dest);
82
- }
90
+ // Older callers recognize this file as the email module's installation marker.
91
+ const service = writes.get(legacyMarker);
92
+ writes.delete(legacyMarker);
93
+ writes.set(legacyMarker, service);
94
+ return writes;
95
+ });
83
96
  }
84
97
 
85
98
  // ─── Server Patches ─────────────────────────────────────────────
@@ -417,38 +430,19 @@ function patchAuthService(project, targetDir) {
417
430
  }
418
431
 
419
432
  /**
420
- * Patch 5: auth.repo.ts
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.
433
+ * Patch 5: register the verification worker only in projects with the module.
427
434
  */
428
- function patchAuthRepo(project, targetDir) {
429
- const filePath = path.join(targetDir, 'server', 'src', 'modules', 'auth', 'auth.repo.ts');
435
+ function patchVerificationJob(project, targetDir) {
436
+ const filePath = path.join(targetDir, 'server', 'src', 'jobs', 'index.ts');
430
437
  const sourceFile = project.addSourceFileAtPath(filePath);
431
-
432
- // Check if already patched
433
- const existing = sourceFile.getFunction('markEmailVerified');
434
- if (existing) return;
435
-
436
- sourceFile.addFunction({
437
- name: 'markEmailVerified',
438
- isExported: true,
439
- isAsync: true,
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;`,
450
- });
451
-
438
+ const registry = sourceFile.getFunctionOrThrow('registerJobs');
439
+ const worker = '@modules/auth/verification.service.js';
440
+ if (!sourceFile.getImportDeclaration(worker)) {
441
+ sourceFile.addImportDeclaration({ moduleSpecifier: worker, namedImports: ['startEmailVerificationJob'] });
442
+ }
443
+ if (!registry.getBodyOrThrow().getText().includes('startEmailVerificationJob(app)')) {
444
+ registry.addStatements('startEmailVerificationJob(app);');
445
+ }
452
446
  sourceFile.saveSync();
453
447
  }
454
448
 
@@ -1,6 +1,8 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { installModule } from '../installer-transaction.js';
5
+ import { nextModuleMigration } from '../project-files.js';
4
6
 
5
7
  const payload = fileURLToPath(new URL('../../modules/metrics/', import.meta.url));
6
8
  const server = 'server/src/modules/metrics';
@@ -24,8 +26,9 @@ const transforms = {
24
26
  [" await app.register(adminRoutes, { prefix: '/api/v1' });", "\n await app.register(webVitalsRoutes, { prefix: '/api/v1', collector: metrics });"],
25
27
  ],
26
28
  'server/src/modules/admin/admin.routes.ts': [
27
- ["import { authenticate, authorize } from '@libs/auth.js';", "\nimport { registerAdminMetricsRoute } from '@modules/metrics/metrics.routes.js';"],
28
- [" fastify.addHook('preValidation', authorize('ADMIN'));", '\n registerAdminMetricsRoute(fastify);'],
29
+ ["import { RATE_LIMITS } from '@config/rate-limit.config.js';", "\nimport { registerAdminMetricsRoute } from '@modules/metrics/metrics.routes.js';"],
30
+ // Older generated apps still register the individual preValidation hooks.
31
+ [[" registerAdminAuthorization(fastify);", " fastify.addHook('preValidation', authorize('ADMIN'));"], '\n registerAdminMetricsRoute(fastify);'],
29
32
  ],
30
33
  'server/src/config/env.ts': [
31
34
  ['const envSchema = z.object({', '\n METRICS_ENABLED: envBoolean(true),'],
@@ -62,18 +65,22 @@ async function payloadFiles(source, target) {
62
65
  }))).flat();
63
66
  }
64
67
 
65
- function patchAnchor(content, file, anchor, addition) {
66
- const index = content.indexOf(anchor);
67
- if (index === -1 || content.indexOf(anchor, index + anchor.length) !== -1) {
68
+ function patchAnchor(content, file, anchors, addition) {
69
+ const matches = [anchors].flat().filter((anchor) => content.includes(anchor));
70
+ const [anchor] = matches;
71
+ if (matches.length !== 1 || content.indexOf(anchor, content.indexOf(anchor) + anchor.length) !== -1) {
68
72
  throw new Error(`Cannot install metrics: expected one integration anchor in ${file}. Review the module guide and integrate that customization manually.`);
69
73
  }
70
74
  const newline = content.includes('\r\n') ? '\r\n' : '\n';
71
75
  return content.replace(anchor, anchor + addition.replaceAll('\n', newline));
72
76
  }
73
77
 
74
- export async function applyMetricsModule(root) {
75
- const read = (file) => fs.readFile(path.join(root, file), 'utf8');
76
- const exists = (file) => fs.pathExists(path.join(root, file));
78
+ export function applyMetricsModule(root) {
79
+ return installModule(root, planMetrics);
80
+ }
81
+
82
+ async function planMetrics({ read: readFile, exists, list }) {
83
+ const read = (file) => readFile(file, 'utf8');
77
84
  const copies = [
78
85
  ...await payloadFiles('server', server),
79
86
  ...await payloadFiles('client', client),
@@ -105,12 +112,7 @@ export async function applyMetricsModule(root) {
105
112
 
106
113
  // Build the entire write set first. A missing/ambiguous anchor or migration
107
114
  // collision must not leave a customized app half patched.
108
- const existingMigrations = (await fs.readdir(path.join(root, migrations), { withFileTypes: true }))
109
- .filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
110
- const migration = `${new Date().toISOString().slice(0, 19).replace(/\D/g, '')}_metrics`;
111
- if (existingMigrations.some((name) => name.endsWith('_metrics') || name >= migration)) {
112
- throw new Error('Cannot place the metrics migration after the existing migrations. Check the migration history.');
113
- }
115
+ const migration = nextModuleMigration(await list(migrations), 'metrics');
114
116
  copies.push(['prisma/migration.sql', `${migrations}/${migration}/migration.sql`]);
115
117
  const writes = new Map();
116
118
  for (const [source, target] of copies) {
@@ -138,8 +140,6 @@ export async function applyMetricsModule(root) {
138
140
  writes.set(file, `${content.trimEnd()}\n\n# Optional performance metrics\n${setting}\n`);
139
141
  }
140
142
  }
141
- for (const [file, content] of writes) await fs.outputFile(path.join(root, file), content);
142
- // Only a finished installation gets a completion marker.
143
- await fs.outputJson(path.join(root, marker), { migration }, { spaces: 2 });
144
- return true;
143
+ writes.set(marker, JSON.stringify({ migration }, null, 2) + '\n');
144
+ return writes;
145
145
  }
@@ -0,0 +1,99 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, lstat, mkdir, readdir, realpath, rename, rmdir, rm } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ // Existing Tigra checkouts already ignore .env.*.local. Recovery can contain
6
+ // original dotenv bytes and must be private there before a scaffold upgrade.
7
+ export const INSTALL_PREFIX = '.env.create-tigra-install';
8
+ export const INSTALL_STATE = `${INSTALL_PREFIX}.local`;
9
+
10
+ export function privateInstallerPath(root, label) {
11
+ return path.join(root, `${INSTALL_PREFIX}-${label}-${randomUUID()}.local`);
12
+ }
13
+
14
+ export function pathParts(relative) {
15
+ const parts = relative.split(/[\\/]/);
16
+ if (parts.some((part) => !part || part === '.' || part === '..' || /[:\0]/.test(part) ||
17
+ (process.platform === 'win32' && (/[. ]$/.test(part) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))))) {
18
+ throw new Error('Invalid project-relative path');
19
+ }
20
+ return parts;
21
+ }
22
+
23
+ export function nextModuleMigration(entries, module, now = new Date()) {
24
+ const names = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
25
+ const suffix = `_${module}`;
26
+ const latest = names.at(-1);
27
+ if (names.some((name) => name.endsWith(suffix))) throw new Error(`A ${module} migration already exists.`);
28
+ const prefix = (date) => date.toISOString().slice(0, 19).replace(/\D/g, '');
29
+ let candidate = `${prefix(now)}${suffix}`;
30
+ const date = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_/.exec(latest ?? '');
31
+ if (date && date[0].slice(0, -1) >= prefix(now)) {
32
+ const [, year, month, day, hour, minute, second] = date;
33
+ const previous = Date.parse(`${year}-${month}-${day}T${hour}:${minute}:${second}Z`);
34
+ if (Number.isFinite(previous)) candidate = `${prefix(new Date(previous + 1000))}${suffix}`;
35
+ }
36
+ if (latest && latest >= candidate) throw new Error(`Cannot place the ${module} migration after the existing migrations.`);
37
+ return candidate;
38
+ }
39
+
40
+ /** Inspect every existing component, including the leaf, without following links. */
41
+ export async function projectPath(root, relative, kind) {
42
+ const parts = pathParts(relative);
43
+ let current = root;
44
+ for (const [index, part] of parts.entries()) {
45
+ current = path.join(current, part);
46
+ const leaf = index === parts.length - 1;
47
+ const stat = await lstat(current).catch((error) => {
48
+ if (error.code !== 'ENOENT') throw error;
49
+ return null;
50
+ });
51
+ if (!stat) return { file: path.join(root, ...parts), stat: null };
52
+ const valid = leaf && kind !== 'directory'
53
+ ? (stat.isFile() && stat.nlink === 1) || (!kind && stat.isDirectory())
54
+ : stat.isDirectory();
55
+ if (stat.isSymbolicLink() || !valid) throw new Error(`Unsafe project path: ${relative}`);
56
+ if (leaf) return { file: current, stat };
57
+ }
58
+ }
59
+
60
+ export async function createParents(root, relative) {
61
+ const parts = pathParts(relative);
62
+ for (let length = 1; length < parts.length; length++) {
63
+ const dir = await projectPath(root, parts.slice(0, length).join('/'), 'directory');
64
+ if (!dir.stat) await mkdir(dir.file);
65
+ }
66
+ }
67
+
68
+ /** Keep failed generation private. A nonempty destination always wins a competing rename. */
69
+ export async function stageScaffold(parent, name, generate) {
70
+ const root = await realpath(parent);
71
+ const target = await projectPath(root, name, 'directory');
72
+ if (target.stat && (await readdir(target.file)).length) {
73
+ throw new Error(`Directory "${name}" already exists and is not empty.`);
74
+ }
75
+ const stage = privateInstallerPath(root, 'scaffold');
76
+ await mkdir(stage, { mode: 0o700 });
77
+ try {
78
+ await generate(stage);
79
+ const current = await projectPath(root, name, 'directory');
80
+ if (current.stat && (!target.stat || current.stat.dev !== target.stat.dev || current.stat.ino !== target.stat.ino)) {
81
+ throw new Error(`Directory "${name}" changed during generation.`);
82
+ }
83
+ // Keep the scratch tree private until publication and give the finished
84
+ // checkout the same directory permissions as an ordinary scaffold.
85
+ await chmod(stage, (current.stat?.mode ?? (0o777 & ~process.umask())) & 0o777);
86
+ if (current.stat) {
87
+ // rmdir refuses a directory another process has populated while we generated.
88
+ await rmdir(current.file);
89
+ }
90
+ try {
91
+ await rename(stage, target.file);
92
+ } catch (error) {
93
+ if (current.stat) await mkdir(target.file).catch(() => {});
94
+ throw error;
95
+ }
96
+ } finally {
97
+ await rm(stage, { recursive: true, force: true });
98
+ }
99
+ }
@@ -24,6 +24,14 @@ Sort returned rows by `group_rank`. Use `severity=warning` for warnings. The
24
24
  view returns at most ten groups for each exact hour and severity. Use the
25
25
  admin API for custom intervals and for groups outside the hourly top ten.
26
26
 
27
+ The shared toolkit's existing reader has schema-wide read access. For a
28
+ diagnostics-only SQL principal, grant `SELECT` on `diagnostic_hourly_top`
29
+ alone. Its fixed projection runs as the app's stable migration account. Use
30
+ the bundled `modules/diagnostics/prisma/diagnostic-hourly-view.sql` as a new
31
+ migration when retrofitting an installed diagnostics view. Keep the applied
32
+ migration and run the new one with a schema-scoped account that will retain
33
+ read access to `diagnostic_buckets`.
34
+
27
35
  ## Read with an existing admin session
28
36
 
29
37
  Use the project's existing admin session cookie jar. Do not print or copy the
@@ -41,6 +49,8 @@ and `nextCursor` for more results with the same filters. `from` is inclusive,
41
49
  `to` is exclusive, and both must identify five-minute boundaries with an
42
50
  explicit timezone. A range can span up to seven days. Counts can change if
43
51
  more batches arrive between requests. A valid empty range returns no groups.
52
+ MySQL can cancel a read at 1.5 seconds. On `503 DIAGNOSTICS_QUERY_TIMEOUT`,
53
+ retry with a narrower interval or a specific `groupId`.
44
54
 
45
55
  Read `label`, `code`, `message`, and the first entry in `frames`. Open that
46
56
  application-relative source file and inspect the function and line when known.
@@ -0,0 +1,24 @@
1
+ -- The fixed projection lets a read-only principal hold SELECT on the view
2
+ -- alone. Run under the application's stable, schema-scoped migration account.
3
+ -- Both equality filters are window partition columns so MySQL can push them
4
+ -- down into the indexed aggregation. The sample tie breaks on immutable ID.
5
+ CREATE OR REPLACE SQL SECURITY DEFINER VIEW `diagnostic_hourly_top` AS
6
+ WITH summaries AS (
7
+ SELECT hour_start, severity, group_id,
8
+ CAST(SUM(occurrences) AS UNSIGNED) AS occurrence_count,
9
+ MIN(first_seen) AS first_seen, MAX(last_seen) AS last_seen,
10
+ MAX(CONCAT(DATE_FORMAT(last_seen, '%Y%m%d%H%i%s%f'), id)) AS sample_position
11
+ FROM diagnostic_buckets
12
+ GROUP BY hour_start, severity, group_id
13
+ ), ranked AS (
14
+ SELECT summaries.*, ROW_NUMBER() OVER (
15
+ PARTITION BY hour_start, severity ORDER BY occurrence_count DESC, group_id ASC
16
+ ) AS group_rank
17
+ FROM summaries
18
+ )
19
+ SELECT ranked.hour_start, ranked.severity, ranked.group_rank, ranked.group_id,
20
+ ranked.occurrence_count, ranked.first_seen, ranked.last_seen,
21
+ sample.source, sample.label, sample.code, sample.message, sample.frames, sample.release
22
+ FROM ranked
23
+ JOIN diagnostic_buckets AS sample ON sample.id = RIGHT(ranked.sample_position, 64)
24
+ WHERE ranked.group_rank <= 10;
@@ -17,27 +17,4 @@ CREATE TABLE `diagnostic_buckets` (
17
17
  INDEX `diagnostic_buckets_hour_start_severity_group_id_idx`(`hour_start`, `severity`, `group_id`),
18
18
  INDEX `diagnostic_buckets_group_id_bucket_start_idx`(`group_id`, `bucket_start`),
19
19
  PRIMARY KEY (`id`)
20
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
21
-
22
- -- Both equality filters are window partition columns so MySQL can push them
23
- -- down into the indexed aggregation. The sample tie breaks on immutable ID.
24
- CREATE SQL SECURITY INVOKER VIEW `diagnostic_hourly_top` AS
25
- WITH summaries AS (
26
- SELECT hour_start, severity, group_id,
27
- CAST(SUM(occurrences) AS UNSIGNED) AS occurrence_count,
28
- MIN(first_seen) AS first_seen, MAX(last_seen) AS last_seen,
29
- MAX(CONCAT(DATE_FORMAT(last_seen, '%Y%m%d%H%i%s%f'), id)) AS sample_position
30
- FROM diagnostic_buckets
31
- GROUP BY hour_start, severity, group_id
32
- ), ranked AS (
33
- SELECT summaries.*, ROW_NUMBER() OVER (
34
- PARTITION BY hour_start, severity ORDER BY occurrence_count DESC, group_id ASC
35
- ) AS group_rank
36
- FROM summaries
37
- )
38
- SELECT ranked.hour_start, ranked.severity, ranked.group_rank, ranked.group_id,
39
- ranked.occurrence_count, ranked.first_seen, ranked.last_seen,
40
- sample.source, sample.label, sample.code, sample.message, sample.frames, sample.release
41
- FROM ranked
42
- JOIN diagnostic_buckets AS sample ON sample.id = RIGHT(ranked.sample_position, 64)
43
- WHERE ranked.group_rank <= 10;
20
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;