create-tigra 3.3.0 → 4.0.1

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 (207) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/README.md +264 -56
  3. package/bin/create-tigra.js +497 -472
  4. package/lib/patchers/email-verification.patcher.js +72 -10
  5. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  6. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  7. package/modules/email-verification/server/verification.controller.ts +3 -1
  8. package/modules/email-verification/server/verification.service.ts +44 -13
  9. package/package.json +5 -3
  10. package/template/.github/dependabot.yml +47 -0
  11. package/template/.github/workflows/audit.yml +36 -0
  12. package/template/.github/workflows/ci.yml +79 -0
  13. package/template/AGENTS.md +18 -9
  14. package/template/README.md +79 -0
  15. package/template/client/.dockerignore +1 -0
  16. package/template/client/.env.example.production +13 -2
  17. package/template/client/AGENTS.md +13 -5
  18. package/template/client/Dockerfile +186 -14
  19. package/template/client/README.md +92 -21
  20. package/template/client/next.config.ts +1 -1
  21. package/template/client/package-lock.json +15983 -14181
  22. package/template/client/package.json +56 -48
  23. package/template/client/scripts/check-sharp.mjs +53 -0
  24. package/template/client/scripts/next-dev.cjs +5 -1
  25. package/template/client/src/__tests__/proxy.test.ts +92 -0
  26. package/template/client/src/app/healthz/route.ts +16 -0
  27. package/template/client/src/app/layout.tsx +9 -3
  28. package/template/client/src/app/page.tsx +2 -2
  29. package/template/client/src/app/providers.tsx +23 -4
  30. package/template/client/src/components/layout/Header.tsx +7 -3
  31. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  32. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  33. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  34. package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
  35. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  36. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  37. package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
  38. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  39. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  40. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  41. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  42. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  43. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  44. package/template/client/src/lib/api/api.types.ts +14 -0
  45. package/template/client/src/lib/api/axios.config.ts +101 -15
  46. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  47. package/template/client/src/lib/api/session-events.ts +29 -0
  48. package/template/client/src/lib/constants/routes.ts +12 -0
  49. package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
  50. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  51. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  52. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  53. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  54. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  55. package/template/client/src/lib/utils/error.ts +81 -0
  56. package/template/client/src/lib/utils/form.ts +31 -0
  57. package/template/client/src/lib/utils/paths.ts +18 -0
  58. package/template/client/src/lib/utils/session-marker.ts +24 -0
  59. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  60. package/template/client/src/store/__tests__/store.test.ts +44 -0
  61. package/template/client/src/store/index.ts +26 -8
  62. package/template/client/vitest.config.mts +48 -0
  63. package/template/server/.env.example +280 -270
  64. package/template/server/.env.example.production +283 -242
  65. package/template/server/AGENTS.md +13 -4
  66. package/template/server/Dockerfile +176 -14
  67. package/template/server/README.md +108 -0
  68. package/template/server/docker-compose.yml +4 -2
  69. package/template/server/docs/deployment.md +63 -0
  70. package/template/server/docs/logging.md +66 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +81 -0
  73. package/template/server/eslint.config.mjs +19 -0
  74. package/template/server/package-lock.json +8784 -8743
  75. package/template/server/package.json +79 -75
  76. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  77. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  78. package/template/server/prisma/schema.prisma +0 -3
  79. package/template/server/scripts/check-heic.mjs +40 -0
  80. package/template/server/scripts/check-sharp.mjs +53 -0
  81. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  82. package/template/server/src/app.ts +248 -346
  83. package/template/server/src/config/__tests__/env.test.ts +219 -0
  84. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  85. package/template/server/src/config/env.ts +326 -182
  86. package/template/server/src/config/rate-limit.config.ts +157 -106
  87. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  88. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  89. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  90. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  91. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  92. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  93. package/template/server/src/jobs/index.ts +12 -2
  94. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  95. package/template/server/src/jobs/schedule.ts +50 -0
  96. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  97. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  98. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  99. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  100. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  101. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  102. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  103. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  104. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  105. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  106. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  107. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  108. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  109. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  110. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  111. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  112. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  113. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  114. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  115. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  116. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  117. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  118. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  119. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  120. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  121. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  122. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  123. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  124. package/template/server/src/libs/auth.ts +39 -10
  125. package/template/server/src/libs/client-ip.ts +158 -77
  126. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  127. package/template/server/src/libs/cookies.ts +53 -14
  128. package/template/server/src/libs/email-quota.ts +74 -0
  129. package/template/server/src/libs/email.ts +46 -9
  130. package/template/server/src/libs/error-handler.ts +111 -0
  131. package/template/server/src/libs/health-routes.ts +53 -0
  132. package/template/server/src/libs/http.ts +139 -47
  133. package/template/server/src/libs/ip-address.ts +37 -0
  134. package/template/server/src/libs/ip-block.ts +284 -221
  135. package/template/server/src/libs/logger.ts +41 -12
  136. package/template/server/src/libs/monitoring.ts +127 -41
  137. package/template/server/src/libs/observability/sentry.ts +1 -1
  138. package/template/server/src/libs/origin-check.ts +9 -7
  139. package/template/server/src/libs/prisma.ts +47 -4
  140. package/template/server/src/libs/query-counter.ts +71 -59
  141. package/template/server/src/libs/rate-limiting.ts +110 -0
  142. package/template/server/src/libs/redis-required.ts +28 -0
  143. package/template/server/src/libs/redis.ts +27 -1
  144. package/template/server/src/libs/request-id.ts +18 -0
  145. package/template/server/src/libs/requestLogger.ts +112 -17
  146. package/template/server/src/libs/safe-http.ts +101 -0
  147. package/template/server/src/libs/shutdown.ts +87 -0
  148. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  149. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  150. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  151. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  152. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  153. package/template/server/src/libs/storage/file-validator.ts +48 -46
  154. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  155. package/template/server/src/libs/token-hash.ts +18 -0
  156. package/template/server/src/libs/url-safety.ts +127 -121
  157. package/template/server/src/libs/validation-errors.ts +86 -0
  158. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  159. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  160. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  161. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  162. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  163. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  164. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  165. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  166. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  167. package/template/server/src/modules/admin/admin.service.ts +66 -4
  168. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  170. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  171. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  172. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  173. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  174. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  175. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  176. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  177. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  178. package/template/server/src/modules/auth/auth.service.ts +167 -96
  179. package/template/server/src/modules/auth/session.repo.ts +12 -0
  180. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  181. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  182. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  183. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  184. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  185. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  186. package/template/server/src/modules/users/users.controller.ts +9 -38
  187. package/template/server/src/modules/users/users.repo.ts +23 -7
  188. package/template/server/src/modules/users/users.routes.ts +3 -22
  189. package/template/server/src/modules/users/users.schemas.ts +15 -9
  190. package/template/server/src/modules/users/users.service.ts +105 -93
  191. package/template/server/src/scripts/make-admin.ts +48 -0
  192. package/template/server/src/server.ts +48 -26
  193. package/template/server/src/shared/errors/AppError.ts +27 -1
  194. package/template/server/src/shared/errors/errors.ts +42 -5
  195. package/template/server/src/shared/responses/successResponse.ts +22 -3
  196. package/template/server/src/shared/types/index.ts +7 -0
  197. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  198. package/template/server/src/test/integration-helpers.ts +343 -0
  199. package/template/server/src/test/integration-services.ts +74 -0
  200. package/template/server/src/test/integration.global-setup.ts +144 -0
  201. package/template/server/src/test/integration.setup.ts +35 -158
  202. package/template/server/src/test/setup.ts +3 -10
  203. package/template/server/tsconfig.build.json +1 -1
  204. package/template/server/tsconfig.json +1 -0
  205. package/template/server/vitest.config.ts +17 -4
  206. package/template/server/vitest.integration.config.ts +18 -13
  207. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -1,50 +1,58 @@
1
- {
2
- "name": "{{PROJECT_NAME}}-client",
3
- "version": "0.1.0",
4
- "private": true,
5
- "scripts": {
1
+ {
2
+ "name": "{{PROJECT_NAME}}-client",
3
+ "version": "0.1.0",
4
+ "engines": {
5
+ "node": ">=24"
6
+ },
7
+ "private": true,
8
+ "scripts": {
6
9
  "dev": "node ./scripts/next-dev.cjs",
7
- "build": "next build",
8
- "start": "next start",
9
- "lint": "eslint src/",
10
- "typecheck": "tsc --noEmit",
11
- "audit": "npm audit --audit-level=high",
12
- "generate:env": "node -e \"import('fs').then(f=>{if(f.existsSync('.env'))console.log('.env already exists, skipping');else{f.copyFileSync('.env.example','.env');console.log('.env created from .env.example')}})\""
13
- },
14
- "dependencies": {
15
- "@hookform/resolvers": "^5.2.2",
16
- "@reduxjs/toolkit": "^2.11.2",
17
- "@sentry/nextjs": "^10.62.0",
18
- "@tanstack/react-query": "^5.90.21",
10
+ "build": "next build",
11
+ "start": "next start",
12
+ "lint": "eslint src/",
13
+ "typecheck": "tsc --noEmit",
14
+ "test": "vitest run",
15
+ "test:watch": "vitest",
16
+ "test:coverage": "vitest run --coverage",
17
+ "audit": "npm audit --audit-level=high",
18
+ "generate:env": "node -e \"import('fs').then(f=>{if(f.existsSync('.env'))console.log('.env already exists, skipping');else{f.copyFileSync('.env.example','.env');console.log('.env created from .env.example')}})\""
19
+ },
20
+ "dependencies": {
21
+ "@hookform/resolvers": "^5.2.2",
22
+ "@reduxjs/toolkit": "^2.11.2",
23
+ "@sentry/nextjs": "^10.62.0",
24
+ "@tanstack/react-query": "^5.90.21",
19
25
  "axios": "^1.20.0",
20
- "class-variance-authority": "^0.7.1",
21
- "clsx": "^2.1.1",
22
- "lucide-react": "^0.563.0",
23
- "next": "16.3.5",
24
- "next-themes": "^0.4.6",
25
- "radix-ui": "^1.4.3",
26
- "react": "19.2.3",
27
- "react-dom": "19.2.3",
28
- "react-hook-form": "^7.71.1",
29
- "react-redux": "^9.2.0",
30
- "sonner": "^2.0.7",
31
- "tailwind-merge": "^3.4.0",
32
- "tailwindcss-animate": "^1.0.7",
33
- "zod": "^4.3.6"
34
- },
35
- "overrides": {
36
- "minimatch": ">=10.2.1"
37
- },
38
- "devDependencies": {
39
- "@tailwindcss/postcss": "^4",
40
- "@types/node": "^20",
41
- "@types/react": "^19",
42
- "@types/react-dom": "^19",
43
- "eslint": "^9",
44
- "eslint-config-next": "16.3.5",
45
- "shadcn": "^3.8.4",
46
- "tailwindcss": "^4",
47
- "tw-animate-css": "^1.4.0",
48
- "typescript": "^5"
49
- }
50
- }
26
+ "class-variance-authority": "^0.7.1",
27
+ "clsx": "^2.1.1",
28
+ "lucide-react": "^0.563.0",
29
+ "next": "16.3.8",
30
+ "next-themes": "^0.4.6",
31
+ "radix-ui": "^1.4.3",
32
+ "react": "19.2.3",
33
+ "react-dom": "19.2.3",
34
+ "react-hook-form": "^7.71.1",
35
+ "react-redux": "^9.2.0",
36
+ "sonner": "^2.0.7",
37
+ "tailwind-merge": "^3.4.0",
38
+ "zod": "^4.3.6"
39
+ },
40
+ "overrides": {
41
+ "minimatch": ">=10.2.1"
42
+ },
43
+ "devDependencies": {
44
+ "@tailwindcss/postcss": "^4",
45
+ "@types/node": "^24",
46
+ "@types/react": "^19",
47
+ "@types/react-dom": "^19",
48
+ "@vitest/coverage-v8": "^4.1.11",
49
+ "eslint": "^9",
50
+ "eslint-config-next": "16.3.8",
51
+ "jsdom": "^29.1.1",
52
+ "shadcn": "^3.8.4",
53
+ "tailwindcss": "^4",
54
+ "tw-animate-css": "^1.4.0",
55
+ "typescript": "^5",
56
+ "vitest": "^4.1.11"
57
+ }
58
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Build-time proof that sharp works in the final Docker image. The Dockerfile
3
+ * runs it as the runtime user after everything is copied in; any failure
4
+ * fails the image build, so an image whose sharp cannot load never ships.
5
+ * It needs no env, network, database or application code.
6
+ *
7
+ * Why the addon file is loaded directly first: when our source-built addon
8
+ * fails to load, sharp silently falls back to its prebuilt addon. On a build
9
+ * host with a newer (x86-64-v2) CPU that fallback works, hides the broken
10
+ * build, and the image then crashes on an older production CPU. Requiring our
11
+ * own file first turns a missing library into a build error here.
12
+ *
13
+ * Keep this file identical in server/scripts and client/scripts.
14
+ */
15
+ import assert from 'node:assert/strict';
16
+ import { execFileSync } from 'node:child_process';
17
+ import { readFileSync } from 'node:fs';
18
+ import { createRequire } from 'node:module';
19
+
20
+ const require = createRequire(import.meta.url);
21
+ const { version } = require('../node_modules/sharp/package.json');
22
+ require(`../node_modules/sharp/src/build/Release/sharp-linuxmusl-${process.arch}-${version}.node`);
23
+
24
+ // The libvips the Dockerfile compiled. sharp must report this one, not the
25
+ // libvips bundled with its prebuilt addon.
26
+ const pc = readFileSync('/opt/vips/lib/pkgconfig/vips-cpp.pc', 'utf8');
27
+ const shipped = /^Version:\s*(\S+)/m.exec(pc)?.[1];
28
+
29
+ const { default: sharp } = await import('sharp');
30
+ assert.equal(sharp.versions.vips, shipped, 'sharp is not using the libvips built into this image');
31
+
32
+ // The work the apps do: decode, auto-orient, resize, encode WebP and drop
33
+ // metadata (avatars on the server, /_next/image on the client).
34
+ const jpeg = await sharp({ create: { width: 16, height: 16, channels: 3, background: '#3366cc' } })
35
+ .jpeg()
36
+ .withExif({ IFD0: { Copyright: 'check-sharp' } })
37
+ .toBuffer();
38
+ assert.ok((await sharp(jpeg).metadata()).exif, 'the test JPEG should carry EXIF');
39
+ const png = await sharp({ create: { width: 16, height: 16, channels: 4, background: '#00000000' } }).png().toBuffer();
40
+
41
+ for (const [name, input] of [['jpeg', jpeg], ['png', png]]) {
42
+ const { data, info } = await sharp(input).autoOrient().resize(8, 8).webp().toBuffer({ resolveWithObject: true });
43
+ assert.equal(info.format, 'webp', `${name}: output format`);
44
+ assert.equal(info.width, 8, `${name}: resize width`);
45
+ assert.equal((await sharp(data).metadata()).exif, undefined, `${name}: metadata must be stripped`);
46
+ }
47
+
48
+ // HEIC/HEIF input (phone photos) is accepted by the server's avatar upload.
49
+ assert.equal(sharp.format.heif.input.buffer, true, 'HEIF input support missing');
50
+
51
+ // Also prove which runtime the image ships (the deploy log shows this line).
52
+ const npmVersion = execFileSync('npm', ['-v'], { encoding: 'utf8' }).trim();
53
+ console.log(`check-sharp: sharp ${version} works with libvips ${sharp.versions.vips} on Node ${process.version}, npm ${npmVersion}`);
@@ -3,7 +3,11 @@
3
3
 
4
4
  const { spawn } = require("node:child_process");
5
5
 
6
- const DEFAULT_MAX_OLD_SPACE_SIZE = "768";
6
+ // Heap cap for the dev server, in MB. Webpack dev keeps every compiled route in
7
+ // memory, so the old 768 MB cap ran out after a handful of pages and the server
8
+ // crashed. 2048 leaves room for a normal app; set NEXT_DEV_MAX_OLD_SPACE_SIZE
9
+ // (or --max-old-space-size in NODE_OPTIONS) to change it per machine.
10
+ const DEFAULT_MAX_OLD_SPACE_SIZE = "2048";
7
11
  const nextBin = require.resolve("next/dist/bin/next");
8
12
 
9
13
  function applyOldSpaceLimit(nodeOptions, sizeMb) {
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The proxy (src/proxy.ts): the per-request CSP, the security headers, the
3
+ * protected-page redirect and the matcher that leaves /healthz alone.
4
+ */
5
+ import { NextRequest } from 'next/server';
6
+ import { afterEach, describe, expect, it, vi } from 'vitest';
7
+
8
+ import { config, proxy } from '../proxy';
9
+
10
+ const request = (path: string, cookie?: string): NextRequest =>
11
+ new NextRequest(`http://localhost:3000${path}`, cookie ? { headers: { cookie } } : undefined);
12
+
13
+ const directive = (csp: string | null, name: string): string =>
14
+ (csp ?? '').split(';').map((d) => d.trim()).find((d) => d.startsWith(`${name} `)) ?? '';
15
+
16
+ afterEach(() => {
17
+ vi.unstubAllEnvs();
18
+ });
19
+
20
+ describe('content security policy', () => {
21
+ it('production: a fresh nonce per request, strict-dynamic, no eval', () => {
22
+ vi.stubEnv('NODE_ENV', 'production');
23
+ const a = proxy(request('/')).headers.get('content-security-policy');
24
+ const b = proxy(request('/')).headers.get('content-security-policy');
25
+ const script = directive(a, 'script-src');
26
+ expect(script).toMatch(/'nonce-[A-Za-z0-9+/=]+'/);
27
+ expect(script).toContain("'strict-dynamic'");
28
+ expect(script).not.toContain("'unsafe-eval'");
29
+ expect(directive(a, 'script-src')).not.toBe(directive(b, 'script-src'));
30
+ expect(a).toContain("frame-ancestors 'none'");
31
+ expect(a).toContain("object-src 'none'");
32
+ expect(directive(a, 'connect-src')).toContain('http://localhost:8000');
33
+ });
34
+
35
+ it("development adds 'unsafe-eval' for hot reload", () => {
36
+ vi.stubEnv('NODE_ENV', 'development');
37
+ expect(directive(proxy(request('/')).headers.get('content-security-policy'), 'script-src')).toContain("'unsafe-eval'");
38
+ });
39
+
40
+ it('every page also gets the static security headers', () => {
41
+ const res = proxy(request('/about'));
42
+ expect(res.headers.get('x-content-type-options')).toBe('nosniff');
43
+ expect(res.headers.get('x-frame-options')).toBe('DENY');
44
+ expect(res.headers.get('referrer-policy')).toBe('strict-origin-when-cross-origin');
45
+ });
46
+ });
47
+
48
+ describe('protected pages', () => {
49
+ it('no session marker: sent to sign-in with where they were going, still with the CSP', () => {
50
+ const res = proxy(request('/dashboard'));
51
+ expect(res.status).toBe(307);
52
+ const location = new URL(res.headers.get('location') ?? '');
53
+ expect(`${location.pathname}${location.search}`).toBe('/login?from=%2Fdashboard');
54
+ expect(res.headers.get('content-security-policy')).toBeTruthy();
55
+ });
56
+
57
+ it('pages under a protected area are protected too', () => {
58
+ expect(proxy(request('/admin/users')).status).toBe(307);
59
+ });
60
+
61
+ it('a page that only starts with the same letters is not', () => {
62
+ for (const path of ['/administrator', '/profile-public', '/dashboards']) {
63
+ expect(proxy(request(path)).headers.get('location')).toBeNull();
64
+ }
65
+ });
66
+
67
+ it('with the session marker the visitor passes (the client refreshes an expired token)', () => {
68
+ const res = proxy(request('/dashboard', 'auth_session=1'));
69
+ expect(res.headers.get('location')).toBeNull();
70
+ expect(res.headers.get('x-middleware-next')).toBe('1');
71
+ });
72
+
73
+ it('an expired access token on a protected page is dropped so the client refreshes it', () => {
74
+ const expired = `x.${Buffer.from(JSON.stringify({ exp: 1 })).toString('base64url')}.y`;
75
+ const res = proxy(request('/dashboard', `auth_session=1; access_token=${expired}`));
76
+ expect(res.headers.get('set-cookie') ?? '').toMatch(/access_token=;.*(Max-Age=0|Expires=Thu, 01 Jan 1970)/i);
77
+ });
78
+ });
79
+
80
+ describe('matcher', () => {
81
+ // Next treats the matcher as a path pattern; this one is plain regex syntax.
82
+ const runsOn = (path: string): boolean => new RegExp(`^${config.matcher[0]}$`).test(path);
83
+
84
+ it('runs on pages, never on static assets or the health check', () => {
85
+ expect(runsOn('/')).toBe(true);
86
+ expect(runsOn('/dashboard')).toBe(true);
87
+ expect(runsOn('/healthz')).toBe(false);
88
+ expect(runsOn('/_next/static/chunk.js')).toBe(false);
89
+ expect(runsOn('/_next/image')).toBe(false);
90
+ expect(runsOn('/favicon.ico')).toBe(false);
91
+ });
92
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * GET /healthz: the container health check (client/Dockerfile HEALTHCHECK,
3
+ * which Coolify also uses to decide when a rolling deploy may switch over).
4
+ *
5
+ * Answers 200 without rendering a page, reading cookies or calling the API,
6
+ * so it says only "this Next.js server is up". The check used to request `/`,
7
+ * which fails as soon as a project makes its home page redirect (to /login,
8
+ * /dashboard, a locale...): the container never became healthy and every
9
+ * deploy failed. Excluded from the proxy (src/proxy.ts matcher), so
10
+ * no auth redirect or CSP work runs for it; it returns no data.
11
+ */
12
+ export const dynamic = 'force-dynamic';
13
+
14
+ export function GET(): Response {
15
+ return Response.json({ status: 'ok' }, { headers: { 'Cache-Control': 'no-store' } });
16
+ }
@@ -1,10 +1,11 @@
1
- import { headers } from 'next/headers';
1
+ import { cookies, headers } from 'next/headers';
2
2
  import type { Metadata, Viewport } from 'next';
3
3
  import type React from 'react';
4
4
  import { Inter, JetBrains_Mono } from 'next/font/google';
5
5
 
6
6
  import { Providers } from './providers';
7
7
  import { APP_NAME } from '@/lib/constants/app.constants';
8
+ import { SESSION_MARKER_COOKIE } from '@/lib/utils/session-marker';
8
9
  import './globals.css';
9
10
 
10
11
  const inter = Inter({
@@ -33,11 +34,16 @@ export default async function RootLayout({
33
34
  }: Readonly<{
34
35
  children: React.ReactNode;
35
36
  }>): Promise<React.ReactElement> {
36
- // Read the per-request nonce set by middleware. next-themes injects an inline
37
+ // Read the per-request nonce set by the proxy (src/proxy.ts). next-themes injects an inline
37
38
  // anti-FOUC <script> via dangerouslySetInnerHTML that Next does NOT auto-nonce,
38
39
  // so under our 'strict-dynamic' CSP it must be passed the nonce explicitly or
39
40
  // the browser refuses it (causing a flash / hydration mismatch).
40
41
  const nonce = (await headers()).get('x-nonce') ?? undefined;
42
+ // Whether this request carries the server's session marker, so the first
43
+ // render already knows "signed out" from "not known yet" (store/index.ts).
44
+ // Every page is already rendered per request (the nonce above), so reading a
45
+ // cookie here changes no caching.
46
+ const hasSession = Boolean((await cookies()).get(SESSION_MARKER_COOKIE)?.value);
41
47
 
42
48
  return (
43
49
  // The font preset consumes these next/font variables from :root. Keep the
@@ -49,7 +55,7 @@ export default async function RootLayout({
49
55
  suppressHydrationWarning
50
56
  >
51
57
  <body className="font-sans antialiased">
52
- <Providers nonce={nonce}>{children}</Providers>
58
+ <Providers nonce={nonce} hasSession={hasSession}>{children}</Providers>
53
59
  </body>
54
60
  </html>
55
61
  );
@@ -53,7 +53,7 @@ export default function WelcomePage(): React.ReactElement {
53
53
 
54
54
  <div className="mt-6 flex flex-col gap-3 sm:flex-row sm:gap-4">
55
55
  <a
56
- href="https://github.com/BehzodKarimov/create-tigra"
56
+ href="https://github.com/blessandsoul/create-tigra"
57
57
  target="_blank"
58
58
  rel="noopener noreferrer"
59
59
  className="inline-flex min-h-11 items-center justify-center rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all duration-200 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 md:hover:brightness-110"
@@ -61,7 +61,7 @@ export default function WelcomePage(): React.ReactElement {
61
61
  Documentation
62
62
  </a>
63
63
  <a
64
- href="https://github.com/BehzodKarimov/create-tigra/issues"
64
+ href="https://github.com/blessandsoul/create-tigra/issues"
65
65
  target="_blank"
66
66
  rel="noopener noreferrer"
67
67
  className="inline-flex min-h-11 items-center justify-center rounded-lg border border-border bg-secondary px-5 py-2.5 text-sm font-medium text-secondary-foreground transition-all duration-200 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 md:hover:bg-accent"
@@ -9,18 +9,31 @@ import { ThemeProvider } from 'next-themes';
9
9
  import { Toaster } from 'sonner';
10
10
 
11
11
  import { SmoothNavigationProvider } from '@/components/common/SmoothNavigationProvider';
12
- import { store } from '@/store';
12
+ import { makeStore } from '@/store';
13
13
  import { AuthInitializer } from '@/features/auth/components/AuthInitializer';
14
+ import { ERROR_CODES, isErrorCode, isLimitError } from '@/lib/utils/error';
14
15
 
15
16
  export function Providers({
16
17
  children,
17
18
  nonce,
19
+ hasSession = false,
18
20
  }: {
19
21
  children: React.ReactNode;
20
- // Per-request CSP nonce from middleware (via the root layout). Forwarded to
22
+ // Per-request CSP nonce from the proxy (src/proxy.ts, via the root layout). Forwarded to
21
23
  // next-themes so its inline anti-FOUC script is allowed under 'strict-dynamic'.
22
24
  nonce?: string;
25
+ // The request carried the session marker (read by the root layout): seeds the
26
+ // store so the first render, on the server too, is right (store/index.ts).
27
+ hasSession?: boolean;
23
28
  }): React.ReactElement {
29
+ // Made once per visitor, never shared between requests (store/index.ts).
30
+ const [store] = useState(() => makeStore({ hasSession }));
31
+ // The state the server rendered with. react-redux hydrates from it, so a user
32
+ // who arrives (the "who am I" answer) before part of the page has hydrated
33
+ // cannot make that part disagree with the server HTML: without this a second
34
+ // tab hit "Hydration failed: signed out vs signed in" (seen live). After
35
+ // hydration the components re-render with the real state.
36
+ const [serverState] = useState(() => store.getState());
24
37
  const [queryClient] = useState(
25
38
  () =>
26
39
  new QueryClient({
@@ -30,14 +43,20 @@ export function Providers({
30
43
  gcTime: 5 * 60 * 1000,
31
44
  refetchOnWindowFocus: true,
32
45
  refetchOnMount: true,
33
- retry: 1,
46
+ // One retry for flaky networks, but never for a "slow down" answer
47
+ // (429 / IP_BLOCKED): a retry would only earn another strike toward
48
+ // the server's IP auto-block. Nor for wrong input (422
49
+ // VALIDATION_FAILED): the same request fails the same way.
50
+ // Mutations never retry (React Query default).
51
+ retry: (failureCount, error) =>
52
+ !isLimitError(error) && !isErrorCode(error, ERROR_CODES.VALIDATION_FAILED) && failureCount < 1,
34
53
  },
35
54
  },
36
55
  })
37
56
  );
38
57
 
39
58
  return (
40
- <ReduxProvider store={store}>
59
+ <ReduxProvider store={store} serverState={serverState}>
41
60
  <QueryClientProvider client={queryClient}>
42
61
  <ThemeProvider
43
62
  attribute="class"
@@ -15,7 +15,11 @@ import { ROUTES } from '@/lib/constants/routes';
15
15
 
16
16
  export const Header = (): React.ReactElement => {
17
17
  const { theme, setTheme } = useTheme();
18
- const { isAuthenticated, user } = useAppSelector((state) => state.auth);
18
+ // While the session is still being read (a session marker is present but the
19
+ // "who am I" check has not answered), the sign-in area shows nothing: never
20
+ // the wrong state first. A visitor without a marker is known to be signed out
21
+ // from the first render, server rendering included (store/index.ts).
22
+ const { isAuthenticated, isInitializing, user } = useAppSelector((state) => state.auth);
19
23
  const { logout, isLoggingOut } = useAuth();
20
24
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
21
25
  const menuToggleRef = useRef<HTMLButtonElement>(null);
@@ -58,7 +62,7 @@ export const Header = (): React.ReactElement => {
58
62
  </AppLink>
59
63
 
60
64
  <nav className="hidden items-center gap-2 md:flex">
61
- {isAuthenticated ? (
65
+ {isInitializing ? null : isAuthenticated ? (
62
66
  <>
63
67
  <Button variant="ghost" size="sm" asChild>
64
68
  <AppLink href={ROUTES.DASHBOARD}>Dashboard</AppLink>
@@ -131,7 +135,7 @@ export const Header = (): React.ReactElement => {
131
135
  {isMobileMenuOpen && (
132
136
  <div id="mobile-menu" className="border-t border-border/50 bg-background px-4 py-4 md:hidden">
133
137
  <nav className="flex flex-col gap-2">
134
- {isAuthenticated ? (
138
+ {isInitializing ? null : isAuthenticated ? (
135
139
  <>
136
140
  <Button variant="ghost" className="w-full justify-start" asChild>
137
141
  <AppLink href={ROUTES.DASHBOARD} onClick={closeMobileMenu}>
@@ -4,7 +4,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
4
4
  import { toast } from 'sonner';
5
5
 
6
6
  import { useAppRouter } from '@/hooks/useAppRouter';
7
- import { getErrorMessage } from '@/lib/utils/error';
7
+ import { getErrorMessage, isLimitError } from '@/lib/utils/error';
8
8
  import { adminService } from '../services/admin.service';
9
9
  import { adminKeys } from './useAdminUsers';
10
10
 
@@ -60,6 +60,7 @@ export const useForceExpireSession = (): UseForceExpireSessionReturn => {
60
60
  router.refresh();
61
61
  },
62
62
  onError: (error) => {
63
+ if (isLimitError(error)) return; // the global toast already says how long to wait
63
64
  toast.error(getErrorMessage(error));
64
65
  },
65
66
  });
@@ -4,7 +4,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
4
4
  import { toast } from 'sonner';
5
5
 
6
6
  import { useAppRouter } from '@/hooks/useAppRouter';
7
- import { getErrorMessage } from '@/lib/utils/error';
7
+ import { getErrorMessage, isLimitError } from '@/lib/utils/error';
8
8
  import { adminService } from '../services/admin.service';
9
9
 
10
10
  import type { IAdminUser, IAdminUserDetail, IGetUsersParams, IGetSessionsParams } from '../types/admin.types';
@@ -95,6 +95,7 @@ export const useUpdateUserStatus = (): UseUpdateUserStatusReturn => {
95
95
  router.refresh();
96
96
  },
97
97
  onError: (error) => {
98
+ if (isLimitError(error)) return; // the global toast already says how long to wait
98
99
  toast.error(getErrorMessage(error));
99
100
  },
100
101
  });
@@ -126,6 +127,7 @@ export const useUpdateUserRole = (): UseUpdateUserRoleReturn => {
126
127
  router.refresh();
127
128
  },
128
129
  onError: (error) => {
130
+ if (isLimitError(error)) return; // the global toast already says how long to wait
129
131
  toast.error(getErrorMessage(error));
130
132
  },
131
133
  });
@@ -5,13 +5,12 @@ import type { PaginationParams } from '@/lib/api/api.types';
5
5
 
6
6
  export interface IAdminUser extends IUser {
7
7
  deletedAt: string | null;
8
- failedLoginAttempts: number;
9
- lockedUntil: string | null;
10
8
  }
11
9
 
12
10
  export interface IAdminUserDetail extends IAdminUser {
13
11
  sessionCount: number;
14
- lastLogin: string | null;
12
+ /** Latest activity of a session that still exists; null once all sessions ended. */
13
+ lastActiveAt: string | null;
15
14
  }
16
15
 
17
16
  // ─── Admin Session ──────────────────────────────────────────────────────────
@@ -7,31 +7,29 @@ import { usePathname } from 'next/navigation';
7
7
 
8
8
  import { toast } from 'sonner';
9
9
 
10
- import { useAppSelector } from '@/store/hooks';
10
+ import { useAppDispatch, useAppSelector } from '@/store/hooks';
11
11
  import { useAppRouter } from '@/hooks/useAppRouter';
12
+ import { onSessionEnded } from '@/lib/api/session-events';
12
13
  import { ROUTES } from '@/lib/constants/routes';
13
- import { isErrorCode, ERROR_CODES } from '@/lib/utils/error';
14
+ import { isErrorCode, isLimitError, ERROR_CODES } from '@/lib/utils/error';
15
+ import { isAuthPath, isProtectedPath } from '@/lib/utils/paths';
16
+ import { hasSessionMarker } from '@/lib/utils/session-marker';
14
17
  import { useCurrentUser } from '../hooks/useCurrentUser';
18
+ import { logout } from '../store/authSlice';
15
19
 
16
- const PROTECTED_PATHS: string[] = [ROUTES.DASHBOARD, ROUTES.PROFILE, '/admin'];
20
+ const DEACTIVATED_MESSAGE = 'This account has been deactivated. Contact support if you think this is a mistake.';
21
+ // One toast however many places notice the ban at once.
22
+ const DEACTIVATED_TOAST_ID = 'account-deactivated';
17
23
 
18
- // Auth pages where getMe() should never fire — there is no session to hydrate
19
- // on login/register/reset-password, and calling getMe() here would trigger the
20
- // 401 → refresh → fail → redirect chain for no reason.
21
- const AUTH_PATHS: string[] = [ROUTES.LOGIN, ROUTES.REGISTER, ROUTES.RESET_PASSWORD, ROUTES.VERIFY_ACCOUNT];
24
+ // Protected pages and sign-in pages: one list each, shared with the proxy
25
+ // (lib/constants/routes.ts), matched by whole path segments (lib/utils/paths.ts).
26
+ // On sign-in pages getMe() never fires: there is no session to hydrate yet, and
27
+ // it would only start the 401 → refresh → fail chain.
22
28
 
23
29
  interface AuthInitializerProps {
24
30
  children: React.ReactNode;
25
31
  }
26
32
 
27
- function isProtectedPath(pathname: string): boolean {
28
- return PROTECTED_PATHS.some((path) => pathname.startsWith(path));
29
- }
30
-
31
- function isAuthPage(pathname: string): boolean {
32
- return AUTH_PATHS.some((path) => pathname.startsWith(path));
33
- }
34
-
35
33
  interface HttpLikeError {
36
34
  response?: { status?: number };
37
35
  }
@@ -39,26 +37,45 @@ interface HttpLikeError {
39
37
  export const AuthInitializer = ({ children }: AuthInitializerProps): React.ReactElement => {
40
38
  const pathname = usePathname();
41
39
  const router = useAppRouter();
40
+ const dispatch = useAppDispatch();
42
41
  const { isLoggingOut } = useAppSelector((state) => state.auth);
43
42
 
44
- // Skip getMe() on auth pages and during logout.
43
+ // The API client reports a session that ended (expired, absent at start-up,
44
+ // or the account banned mid-session; lib/api/session-events.ts). Clear the
45
+ // signed-in user so every screen shows the signed-out state at once.
46
+ useEffect(
47
+ () =>
48
+ onSessionEnded((reason) => {
49
+ dispatch(logout());
50
+ if (reason === 'deactivated') toast.error(DEACTIVATED_MESSAGE, { id: DEACTIVATED_TOAST_ID });
51
+ }),
52
+ [dispatch]
53
+ );
54
+
55
+ // Skip getMe() on auth pages, during logout, and whenever this browser holds
56
+ // no session marker: then there is no session to ask about, and an anonymous
57
+ // visitor would pay two failing calls (me 401, refresh 401) per page view
58
+ // and window focus, enough on a shared IP to hit the refresh rate limit.
45
59
  // React Query handles deduping, refetch-on-focus, and invalidation —
46
60
  // any mutation that touches the current user (profile update, role change,
47
61
  // avatar upload, email verification) should call:
48
62
  // queryClient.invalidateQueries({ queryKey: authKeys.me() })
49
63
  // to refresh Redux state automatically.
50
- const enabled = !isAuthPage(pathname) && !isLoggingOut;
64
+ const enabled = !isAuthPath(pathname) && !isLoggingOut && hasSessionMarker();
51
65
 
52
66
  const { error } = useCurrentUser({ enabled });
53
67
 
54
68
  useEffect(() => {
55
69
  if (!error) return;
56
70
  if (!isProtectedPath(pathname)) return;
71
+ // Rate limited or network blocked: the session may be fine, so stay put. The
72
+ // global toast already says how long to wait (lib/api/axios.config.ts).
73
+ if (isLimitError(error)) return;
57
74
 
58
75
  const status = (error as HttpLikeError)?.response?.status;
59
76
  if (status === 401 || status === 403) {
60
77
  if (isErrorCode(error, ERROR_CODES.ACCOUNT_DEACTIVATED)) {
61
- toast.error('This account has been deactivated. Contact support if you think this is a mistake.');
78
+ toast.error(DEACTIVATED_MESSAGE, { id: DEACTIVATED_TOAST_ID });
62
79
  } else if (isErrorCode(error, ERROR_CODES.EMAIL_NOT_VERIFIED)) {
63
80
  toast.error('Please verify your email address before signing in.');
64
81
  }