create-tigra 4.0.1 → 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.
- package/CHANGELOG.md +43 -0
- package/README.md +21 -3
- package/bin/create-tigra.js +131 -65
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +123 -0
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +145 -0
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +75 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +20 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +37 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +133 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +45 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +104 -0
- package/package.json +1 -1
- package/template/AGENTS.md +18 -10
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -43,7 +43,7 @@ if (env.NODE_ENV === 'production') {
|
|
|
43
43
|
// Log all queries in development for debugging
|
|
44
44
|
if (env.NODE_ENV === 'development') {
|
|
45
45
|
baseClient.$on('query' as never, (e: { duration: number; query: string }) => {
|
|
46
|
-
logger.debug({ duration: e.duration
|
|
46
|
+
logger.debug({ duration: e.duration }, 'Database query');
|
|
47
47
|
});
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -16,6 +16,7 @@ import rateLimit from '@fastify/rate-limit';
|
|
|
16
16
|
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
|
17
17
|
import type { Redis } from 'ioredis';
|
|
18
18
|
import { DEFAULT_LIMIT, RATE_LIMIT_ENABLED } from '@config/rate-limit.config.js';
|
|
19
|
+
import { isAuthorizedAdminRequest } from '@libs/auth.js';
|
|
19
20
|
import { getClientIp } from '@libs/client-ip.js';
|
|
20
21
|
import { isAuthPath } from '@libs/auth-path.js';
|
|
21
22
|
import { recordRateLimitViolation } from '@libs/ip-block.js';
|
|
@@ -66,6 +67,9 @@ export async function registerRateLimiting(app: FastifyInstance, options: RateLi
|
|
|
66
67
|
timeWindow: DEFAULT_LIMIT.timeWindow,
|
|
67
68
|
...(options.redis ? { redis: options.redis, nameSpace: 'rl:' } : {}),
|
|
68
69
|
skipOnError: true,
|
|
70
|
+
// Only routes in the authenticated admin scope can set this decision. The
|
|
71
|
+
// allowlist skips both the quota and its onExceeded strike for those requests.
|
|
72
|
+
allowList: isAuthorizedAdminRequest,
|
|
69
73
|
// Key on the verified visitor address (one counter per real visitor, and never an
|
|
70
74
|
// address the visitor wrote itself) — see src/libs/client-ip.ts.
|
|
71
75
|
keyGenerator: (request: FastifyRequest) => getClientIp(request),
|
|
@@ -73,8 +73,8 @@ export interface RequestLineParts {
|
|
|
73
73
|
/**
|
|
74
74
|
* The URL without its query string or fragment. Queries carry search terms,
|
|
75
75
|
* email addresses and the like (`/admin/users?search=jane@example.com`), and
|
|
76
|
-
* links in emails carry tokens
|
|
77
|
-
* stay
|
|
76
|
+
* links in emails carry tokens. Request logs use registered route templates
|
|
77
|
+
* so submitted path segments stay out of the log as well.
|
|
78
78
|
*/
|
|
79
79
|
export function requestPath(url: string): string {
|
|
80
80
|
const end = url.search(/[?#]/);
|
|
@@ -149,7 +149,7 @@ export function logRequestLine(
|
|
|
149
149
|
const statusCode = reply.statusCode;
|
|
150
150
|
const parts: RequestLineParts = {
|
|
151
151
|
method: request.method,
|
|
152
|
-
url: request.url,
|
|
152
|
+
url: request.routeOptions.url ?? '(unmatched)',
|
|
153
153
|
statusCode,
|
|
154
154
|
statusMessage: reply.raw.statusMessage || '',
|
|
155
155
|
durationMs: request.startTime ? Date.now() - request.startTime : 0,
|
|
@@ -12,18 +12,21 @@
|
|
|
12
12
|
* is not public, and the socket then connects to exactly the addresses that
|
|
13
13
|
* were checked: a DNS answer cannot change between the check and the
|
|
14
14
|
* connection (DNS rebinding);
|
|
15
|
-
* - redirects: at most 3, each hop checked the same way
|
|
15
|
+
* - redirects: at most 3, each hop checked the same way. A different origin
|
|
16
|
+
* receives no caller-supplied headers and only bodyless GET/HEAD requests;
|
|
16
17
|
* - environment proxies are ignored (with a proxy the lookup would check the
|
|
17
18
|
* proxy, and the proxy would fetch the internal target for us);
|
|
18
|
-
* - 10 s
|
|
19
|
+
* - a 10 s total deadline and a 10 MB body cap, which callers may lower.
|
|
19
20
|
*
|
|
20
21
|
* A refused request throws OutboundHttpError with kind 'blocked' (a generic 500
|
|
21
22
|
* unless the caller handles it, e.g. as "this link is not allowed").
|
|
22
23
|
*/
|
|
23
24
|
import dns, { type LookupAddress } from 'node:dns';
|
|
25
|
+
import { Agent as HttpAgent } from 'node:http';
|
|
26
|
+
import { Agent as HttpsAgent } from 'node:https';
|
|
24
27
|
import { isIP } from 'node:net';
|
|
25
28
|
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
|
|
26
|
-
import { createHttpClient, OutboundHttpError, OUTBOUND_BLOCKED } from '@libs/http.js';
|
|
29
|
+
import { createHttpClient, MAX_BODY_BYTES, OutboundHttpError, OUTBOUND_BLOCKED } from '@libs/http.js';
|
|
27
30
|
import { isForbiddenOutboundIp } from '@libs/url-safety.js';
|
|
28
31
|
|
|
29
32
|
const SAFE_TIMEOUT_MS = 10_000;
|
|
@@ -47,12 +50,16 @@ function literalIp(hostname: string): string | null {
|
|
|
47
50
|
}
|
|
48
51
|
|
|
49
52
|
/** Whether a target (protocol + hostname) may be connected to, before any DNS. */
|
|
50
|
-
function isAllowedTarget(
|
|
51
|
-
if (protocol !== 'http:' && protocol !== 'https:') return false;
|
|
52
|
-
const ip = literalIp(hostname);
|
|
53
|
+
function isAllowedTarget(target: URL, isForbidden: (ip: string) => boolean): boolean {
|
|
54
|
+
if ((target.protocol !== 'http:' && target.protocol !== 'https:') || target.username || target.password) return false;
|
|
55
|
+
const ip = literalIp(target.hostname);
|
|
53
56
|
return ip === null || !isForbidden(ip);
|
|
54
57
|
}
|
|
55
58
|
|
|
59
|
+
function boundedLimit(value: number | undefined, ceiling: number, minimum = 0): number {
|
|
60
|
+
return value !== undefined && Number.isSafeInteger(value) && value >= minimum ? Math.min(value, ceiling) : ceiling;
|
|
61
|
+
}
|
|
62
|
+
|
|
56
63
|
export interface SafeHttpOptions {
|
|
57
64
|
/** DNS resolver (tests inject one). */
|
|
58
65
|
resolve?: Resolve;
|
|
@@ -71,26 +78,59 @@ export function createSafeHttpClient({
|
|
|
71
78
|
return answers;
|
|
72
79
|
};
|
|
73
80
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
lookup,
|
|
79
|
-
// Redirect hops: an IP literal skips the lookup, so check it (and the protocol) here.
|
|
80
|
-
beforeRedirect: (options) => {
|
|
81
|
-
if (!isAllowedTarget(String(options.protocol), String(options.hostname), isForbidden)) throw blocked();
|
|
82
|
-
},
|
|
83
|
-
});
|
|
81
|
+
// Explicit agents also avoid Node's opt-in proxy-aware global agents.
|
|
82
|
+
const httpAgent = new HttpAgent();
|
|
83
|
+
const httpsAgent = new HttpsAgent();
|
|
84
|
+
const client = createHttpClient({ timeout: SAFE_TIMEOUT_MS, maxRedirects: MAX_REDIRECTS });
|
|
84
85
|
|
|
85
86
|
// First hop: refuse before anything is sent (an IP literal never reaches the lookup).
|
|
86
87
|
client.interceptors.request.use((config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
|
|
87
88
|
let target: URL;
|
|
88
89
|
try {
|
|
89
|
-
target = new URL(
|
|
90
|
+
target = new URL(client.getUri(config));
|
|
90
91
|
} catch {
|
|
91
92
|
throw new OutboundHttpError('blocked');
|
|
92
93
|
}
|
|
93
|
-
if (!isAllowedTarget(target
|
|
94
|
+
if (!isAllowedTarget(target, isForbidden)) throw new OutboundHttpError('blocked');
|
|
95
|
+
|
|
96
|
+
// The URL validated here is the one handed to the adapter. The transport
|
|
97
|
+
// and ceilings are policy, even when a caller changes Axios options.
|
|
98
|
+
config.url = target.href;
|
|
99
|
+
config.baseURL = undefined;
|
|
100
|
+
config.params = undefined;
|
|
101
|
+
config.adapter = 'http';
|
|
102
|
+
config.httpVersion = 1;
|
|
103
|
+
config.transport = undefined;
|
|
104
|
+
config.socketPath = undefined;
|
|
105
|
+
config.proxy = false;
|
|
106
|
+
config.httpAgent = httpAgent;
|
|
107
|
+
config.httpsAgent = httpsAgent;
|
|
108
|
+
config.lookup = lookup;
|
|
109
|
+
config.family = undefined;
|
|
110
|
+
config.headers.delete('Host');
|
|
111
|
+
config.maxRedirects = boundedLimit(config.maxRedirects, MAX_REDIRECTS);
|
|
112
|
+
config.maxBodyLength = boundedLimit(config.maxBodyLength, MAX_BODY_BYTES);
|
|
113
|
+
config.maxContentLength = boundedLimit(config.maxContentLength, MAX_BODY_BYTES);
|
|
114
|
+
config.timeout = boundedLimit(config.timeout, SAFE_TIMEOUT_MS, 1);
|
|
115
|
+
|
|
116
|
+
// Apply a wall-clock deadline as well as Axios's transport timeout. The
|
|
117
|
+
// signal starts before lookup and stays active across redirects and reads.
|
|
118
|
+
const deadline = AbortSignal.timeout(config.timeout);
|
|
119
|
+
config.signal = config.signal instanceof AbortSignal ? AbortSignal.any([config.signal, deadline]) : deadline;
|
|
120
|
+
|
|
121
|
+
let origin = target.origin;
|
|
122
|
+
const canRedirectAcrossOrigins = ['get', 'head'].includes(config.method?.toLowerCase() ?? 'get') && config.data == null;
|
|
123
|
+
config.beforeRedirect = (options): void => {
|
|
124
|
+
// IP literals bypass DNS, so reapply the destination policy at each hop.
|
|
125
|
+
const next = new URL(String(options.href));
|
|
126
|
+
if (!isAllowedTarget(next, isForbidden)) throw blocked();
|
|
127
|
+
if (next.origin !== origin) {
|
|
128
|
+
if (!canRedirectAcrossOrigins) throw blocked();
|
|
129
|
+
options.headers = {};
|
|
130
|
+
options.auth = undefined;
|
|
131
|
+
}
|
|
132
|
+
origin = next.origin;
|
|
133
|
+
};
|
|
94
134
|
return config;
|
|
95
135
|
});
|
|
96
136
|
|
|
@@ -4,11 +4,24 @@
|
|
|
4
4
|
* production, only inside a Docker container, and only when the folder is on
|
|
5
5
|
* the container's own disk (same device as "/") rather than a mounted volume.
|
|
6
6
|
*/
|
|
7
|
-
import
|
|
8
|
-
import {
|
|
7
|
+
import fs from 'fs/promises';
|
|
8
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
9
|
+
import { type DiskProbe, fileStorageService, uploadDirsOnContainerDisk } from '../file-storage.service.js';
|
|
9
10
|
|
|
10
11
|
const DIRS = ['/app/uploads/public', '/app/uploads/private'];
|
|
11
12
|
|
|
13
|
+
it('reports a storage error to the purge worker instead of treating the directory as absent', async () => {
|
|
14
|
+
const denied = Object.assign(new Error('cannot access media'), { code: 'EACCES' });
|
|
15
|
+
const stat = vi.spyOn(fs, 'stat').mockRejectedValue(denied);
|
|
16
|
+
const remove = vi.spyOn(fs, 'rm').mockRejectedValue(denied);
|
|
17
|
+
try {
|
|
18
|
+
await expect(fileStorageService.deleteUserMedia('a-local-fixture')).rejects.toMatchObject({ code: 'FILE_DELETE_FAILED' });
|
|
19
|
+
} finally {
|
|
20
|
+
stat.mockRestore();
|
|
21
|
+
remove.mockRestore();
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
|
|
12
25
|
/** A fake disk: "/" is device 1; `mounted` folders live on device 2. */
|
|
13
26
|
function disk({ container = true, mounted = [] as string[], broken = [] as string[] } = {}): DiskProbe {
|
|
14
27
|
return {
|
|
@@ -18,10 +18,9 @@
|
|
|
18
18
|
*
|
|
19
19
|
* ── Public files never change under the same name ──────────────────────────
|
|
20
20
|
* Every new avatar gets a NEW random filename, so a URL always means the same
|
|
21
|
-
* bytes.
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* tier must follow the same rule: new content, new name.
|
|
21
|
+
* bytes. Publishing under a fresh URL also lets replicas remove the previous
|
|
22
|
+
* file without touching its replacement. Other public assets use immutable
|
|
23
|
+
* caching and must follow the same rule: new content, new name.
|
|
25
24
|
*/
|
|
26
25
|
|
|
27
26
|
import { randomBytes } from 'node:crypto';
|
|
@@ -32,6 +31,27 @@ import { env } from '@config/env.js';
|
|
|
32
31
|
import { logger } from '@libs/logger.js';
|
|
33
32
|
import { InternalError } from '@shared/errors/errors.js';
|
|
34
33
|
|
|
34
|
+
export interface AvatarFile {
|
|
35
|
+
userId: string;
|
|
36
|
+
filename: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function avatarFileUrl({ userId, filename }: AvatarFile): string {
|
|
40
|
+
return `/uploads/users/${userId}/avatar/${filename}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function validAvatarFilename(filename: string): boolean {
|
|
44
|
+
return /^[\p{L}\p{N}_-][\p{L}\p{N}_.-]*\.webp$/u.test(filename);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Only accept the stored URL for an exact avatar file owned by this account. */
|
|
48
|
+
export function avatarFileFromUrl(userId: string, url: string | null): AvatarFile | null {
|
|
49
|
+
if (!url) return null;
|
|
50
|
+
const filename = path.posix.basename(url);
|
|
51
|
+
const file = { userId, filename };
|
|
52
|
+
return validAvatarFilename(filename) && url === avatarFileUrl(file) ? file : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
35
55
|
/** How uploadDirsOnContainerDisk looks at the disk (injectable for tests). */
|
|
36
56
|
export interface DiskProbe {
|
|
37
57
|
exists(p: string): boolean;
|
|
@@ -131,74 +151,41 @@ class FileStorageService {
|
|
|
131
151
|
return path.join(this.getUserDir(userId), 'avatar');
|
|
132
152
|
}
|
|
133
153
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
* It never overwrites or deletes anything: the old avatar keeps serving until
|
|
138
|
-
* the database points at the new one, and the caller then removes exactly
|
|
139
|
-
* the file it replaced (see usersService.uploadAvatar). The name carries no
|
|
140
|
-
* personal data (no user name) and is unique per upload.
|
|
141
|
-
*
|
|
142
|
-
* @param userId - User's unique ID
|
|
143
|
-
* @param buffer - Optimized image buffer (always WebP)
|
|
144
|
-
* @returns Filename and public URL, e.g. /uploads/users/{userId}/avatar/avatar-3f9c0a1b2c3d4e5f.webp
|
|
145
|
-
*/
|
|
146
|
-
async saveAvatar(userId: string, buffer: Buffer): Promise<{ filename: string; url: string }> {
|
|
147
|
-
try {
|
|
148
|
-
const avatarDir = this.getUserAvatarDir(userId);
|
|
149
|
-
await this.ensureDirectoryExists(avatarDir);
|
|
150
|
-
|
|
151
|
-
const filename = `avatar-${randomBytes(8).toString('hex')}.webp`;
|
|
152
|
-
await fs.writeFile(path.join(avatarDir, filename), buffer);
|
|
153
|
-
|
|
154
|
-
const url = `/uploads/users/${userId}/avatar/${filename}`;
|
|
155
|
-
|
|
156
|
-
logger.info({
|
|
157
|
-
msg: 'Avatar saved successfully',
|
|
158
|
-
userId,
|
|
159
|
-
filename,
|
|
160
|
-
fileSize: buffer.length,
|
|
161
|
-
});
|
|
154
|
+
allocateAvatar(userId: string): AvatarFile {
|
|
155
|
+
return { userId, filename: `avatar-${randomBytes(8).toString('hex')}.webp` };
|
|
156
|
+
}
|
|
162
157
|
|
|
163
|
-
|
|
158
|
+
/** Rename only a complete optimized image, on the same volume as its final URL. */
|
|
159
|
+
async publishAvatar(file: AvatarFile, buffer: Buffer): Promise<void> {
|
|
160
|
+
const { image, temporary, dir } = this.avatarPaths(file);
|
|
161
|
+
try {
|
|
162
|
+
await this.ensureDirectoryExists(dir);
|
|
163
|
+
await fs.writeFile(temporary, buffer, { flag: 'wx' });
|
|
164
|
+
await fs.rename(temporary, image);
|
|
164
165
|
} catch (error) {
|
|
165
|
-
logger.error({ err: error, msg: 'Failed to
|
|
166
|
+
logger.error({ err: error, userId: file.userId, msg: 'Failed to publish avatar' });
|
|
166
167
|
throw new InternalError('Failed to save avatar file', 'FILE_SAVE_FAILED');
|
|
167
168
|
}
|
|
168
169
|
}
|
|
169
170
|
|
|
170
|
-
/**
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
*
|
|
176
|
-
* @example
|
|
177
|
-
* ```typescript
|
|
178
|
-
* await fileStorageService.deleteAvatar(userId);
|
|
179
|
-
* ```
|
|
180
|
-
*/
|
|
181
|
-
async deleteAvatar(userId: string): Promise<void> {
|
|
171
|
+
/** Only the queued file and its temporary sibling belong to this operation. */
|
|
172
|
+
async removeAvatarFile(file: AvatarFile): Promise<void> {
|
|
173
|
+
const { image, temporary, dir } = this.avatarPaths(file);
|
|
174
|
+
await fs.rm(image, { force: true });
|
|
175
|
+
await fs.rm(temporary, { force: true });
|
|
182
176
|
try {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
// Check if directory exists
|
|
186
|
-
const exists = await this.directoryExists(avatarDir);
|
|
187
|
-
if (!exists) {
|
|
188
|
-
logger.info({ msg: 'Avatar directory does not exist, nothing to delete', userId });
|
|
189
|
-
return;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// Delete avatar directory and contents
|
|
193
|
-
await fs.rm(avatarDir, { recursive: true, force: true });
|
|
194
|
-
|
|
195
|
-
logger.info({ msg: 'Avatar deleted successfully', userId });
|
|
177
|
+
await fs.rmdir(dir);
|
|
196
178
|
} catch (error) {
|
|
197
|
-
|
|
198
|
-
throw new InternalError('Failed to delete avatar file', 'FILE_DELETE_FAILED');
|
|
179
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error;
|
|
199
180
|
}
|
|
200
181
|
}
|
|
201
182
|
|
|
183
|
+
private avatarPaths(file: AvatarFile): { image: string; temporary: string; dir: string } {
|
|
184
|
+
if (!validAvatarFilename(file.filename)) throw new Error('Invalid stored avatar filename');
|
|
185
|
+
const dir = this.getUserAvatarDir(file.userId);
|
|
186
|
+
return { dir, image: path.join(dir, file.filename), temporary: path.join(dir, `.${file.filename}.tmp`) };
|
|
187
|
+
}
|
|
188
|
+
|
|
202
189
|
/**
|
|
203
190
|
* Deletes all media for a user: the public directory (avatars) AND the
|
|
204
191
|
* private directory (owner-only files).
|
|
@@ -218,9 +205,9 @@ class FileStorageService {
|
|
|
218
205
|
async deleteUserMedia(userId: string): Promise<void> {
|
|
219
206
|
try {
|
|
220
207
|
for (const dir of [this.getUserDir(userId), this.getUserPrivateDir(userId)]) {
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}
|
|
208
|
+
// force tolerates missing media. Other filesystem errors must reach
|
|
209
|
+
// the purge worker so it keeps the retry record in MySQL.
|
|
210
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
224
211
|
}
|
|
225
212
|
|
|
226
213
|
logger.info({ msg: 'User media deleted successfully', userId });
|
|
@@ -230,24 +217,6 @@ class FileStorageService {
|
|
|
230
217
|
}
|
|
231
218
|
}
|
|
232
219
|
|
|
233
|
-
/**
|
|
234
|
-
* Removes ONE avatar file of this user. Best effort: never throws, because it
|
|
235
|
-
* runs while cleaning up (the replaced file after a new upload, or the new
|
|
236
|
-
* file after a failed one). A miss is logged; the account purge removes any
|
|
237
|
-
* leftover with the whole folder.
|
|
238
|
-
*
|
|
239
|
-
* Only the basename is used, so whatever a stored URL says, the path stays
|
|
240
|
-
* inside this user's avatar folder.
|
|
241
|
-
*/
|
|
242
|
-
async removeAvatarFile(userId: string, filename: string): Promise<void> {
|
|
243
|
-
const safeName = path.basename(filename);
|
|
244
|
-
try {
|
|
245
|
-
await fs.rm(path.join(this.getUserAvatarDir(userId), safeName), { force: true });
|
|
246
|
-
} catch (error) {
|
|
247
|
-
logger.error({ err: error, msg: 'Failed to remove avatar file', userId, filename: safeName });
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
220
|
/**
|
|
252
221
|
* Sanitizes a single-segment filename for safe disk storage.
|
|
253
222
|
*
|
|
@@ -256,21 +225,17 @@ class FileStorageService {
|
|
|
256
225
|
* escape the user's private directory. This is a storage-side guard; the
|
|
257
226
|
* files route applies its OWN validation + path-containment check on read.
|
|
258
227
|
*
|
|
259
|
-
*
|
|
228
|
+
* Returns null for an unusable name so reads can answer 404.
|
|
260
229
|
*/
|
|
261
|
-
private sanitizePrivateFilename(filename: string): string {
|
|
230
|
+
private sanitizePrivateFilename(filename: string): string | null {
|
|
262
231
|
// Reject obvious traversal/separator/null-byte input up front.
|
|
263
232
|
if (!filename || filename.includes('\0') || filename.includes('/') || filename.includes('\\')) {
|
|
264
|
-
|
|
233
|
+
return null;
|
|
265
234
|
}
|
|
266
235
|
// Collapse to the basename and drop any leading dots so `..`/`.` can't slip
|
|
267
236
|
// through; keep a conservative allowlist (letters, digits, . _ -).
|
|
268
237
|
const base = path.basename(filename).replace(/^\.+/, '');
|
|
269
|
-
|
|
270
|
-
if (!cleaned) {
|
|
271
|
-
throw new InternalError('Invalid private filename', 'INVALID_FILENAME');
|
|
272
|
-
}
|
|
273
|
-
return cleaned;
|
|
238
|
+
return base.replace(/[^a-zA-Z0-9._-]/g, '') || null;
|
|
274
239
|
}
|
|
275
240
|
|
|
276
241
|
/**
|
|
@@ -292,6 +257,7 @@ class FileStorageService {
|
|
|
292
257
|
): Promise<{ filename: string; path: string }> {
|
|
293
258
|
try {
|
|
294
259
|
const safeName = this.sanitizePrivateFilename(filename);
|
|
260
|
+
if (!safeName) throw new InternalError('Invalid private filename', 'INVALID_FILENAME');
|
|
295
261
|
const userDir = this.getUserPrivateDir(userId);
|
|
296
262
|
await this.ensureDirectoryExists(userDir);
|
|
297
263
|
|
|
@@ -323,11 +289,11 @@ class FileStorageService {
|
|
|
323
289
|
*
|
|
324
290
|
* @param userId - User's unique ID (the owner)
|
|
325
291
|
* @param filename - File name within the user's private directory
|
|
326
|
-
* @returns
|
|
292
|
+
* @returns An owner-scoped absolute path, or null for an unusable name
|
|
327
293
|
*/
|
|
328
|
-
getPrivateFilePath(userId: string, filename: string): string {
|
|
294
|
+
getPrivateFilePath(userId: string, filename: string): string | null {
|
|
329
295
|
const safeName = this.sanitizePrivateFilename(filename);
|
|
330
|
-
return path.join(this.getUserPrivateDir(userId), safeName);
|
|
296
|
+
return safeName ? path.join(this.getUserPrivateDir(userId), safeName) : null;
|
|
331
297
|
}
|
|
332
298
|
|
|
333
299
|
/**
|
|
@@ -346,22 +312,6 @@ class FileStorageService {
|
|
|
346
312
|
}
|
|
347
313
|
}
|
|
348
314
|
|
|
349
|
-
/**
|
|
350
|
-
* Checks if a directory exists
|
|
351
|
-
*
|
|
352
|
-
* @param dirPath - Directory path
|
|
353
|
-
* @returns True if directory exists
|
|
354
|
-
* @private
|
|
355
|
-
*/
|
|
356
|
-
private async directoryExists(dirPath: string): Promise<boolean> {
|
|
357
|
-
try {
|
|
358
|
-
const stats = await fs.stat(dirPath);
|
|
359
|
-
return stats.isDirectory();
|
|
360
|
-
} catch {
|
|
361
|
-
return false;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
|
|
365
315
|
/**
|
|
366
316
|
* Initializes the upload directory structure
|
|
367
317
|
*
|
|
@@ -31,7 +31,8 @@ export const FILE_UPLOAD_CONSTANTS = {
|
|
|
31
31
|
* is free) can send that to the avatar upload. Proven live: 300 fields of 1 MB
|
|
32
32
|
* grew the server by 429 MB. These caps bound it to about 2 MB:
|
|
33
33
|
* - more fields or parts than allowed: 413 MULTIPART_LIMIT (libs/error-handler.ts);
|
|
34
|
-
* - a field longer than fieldSize is truncated, never buffered whole.
|
|
34
|
+
* - a field longer than fieldSize is truncated, never buffered whole. The
|
|
35
|
+
* avatar handler rejects a truncated field before publishing an image.
|
|
35
36
|
* Raise them only for a route that really sends many or large fields.
|
|
36
37
|
*/
|
|
37
38
|
export const MULTIPART_LIMITS = {
|
|
@@ -43,7 +43,7 @@ export function redactUrl(url: string): string {
|
|
|
43
43
|
|
|
44
44
|
// Drop the query string (and fragment) — may hold API keys or signed tokens —
|
|
45
45
|
// and credentials in the authority (https://user:password@host/).
|
|
46
|
-
const noQuery = url.split(/[?#]/, 1)[0].replace(/^([a-z][a-z0-9+.-]
|
|
46
|
+
const noQuery = url.split(/[?#]/, 1)[0].replace(/^((?:[a-z][a-z0-9+.-]*:)?\/\/)[^/]*@/i, '$1');
|
|
47
47
|
|
|
48
48
|
// Rewrite Telegram bot-token path segments. The token charset is [A-Za-z0-9_-]
|
|
49
49
|
// plus the ':' separating bot-id from secret, e.g. 123456:AAH...
|
|
@@ -87,10 +87,16 @@ for (const [net, prefix] of [
|
|
|
87
87
|
['2001::', 23], // IETF protocol assignments (incl. Teredo)
|
|
88
88
|
['2001:db8::', 32], // documentation
|
|
89
89
|
['2002::', 16], // 6to4: embeds an IPv4 address
|
|
90
|
+
['3fff::', 20], // documentation (RFC 9637)
|
|
90
91
|
['fec0::', 10], // site-local (deprecated)
|
|
91
92
|
['ff00::', 8], // multicast
|
|
92
93
|
] as const) NOT_PUBLIC.addSubnet(net, prefix, 'ipv6');
|
|
93
94
|
|
|
95
|
+
// IANA's global unicast allocation. Special-purpose blocks inside it still
|
|
96
|
+
// need the exclusions above. IPv4-mapped addresses are classified as IPv4.
|
|
97
|
+
const IPV6_GLOBAL_UNICAST = new BlockList();
|
|
98
|
+
IPV6_GLOBAL_UNICAST.addSubnet('2000::', 3, 'ipv6');
|
|
99
|
+
|
|
94
100
|
/** Canonical address and its family, or undefined for anything that is not an IP literal. */
|
|
95
101
|
function parse(addr: unknown): { ip: string; family: 'ipv4' | 'ipv6' } | undefined {
|
|
96
102
|
if (typeof addr !== 'string') return undefined;
|
|
@@ -123,5 +129,7 @@ export function isPrivateOrReservedIp(addr: string): boolean {
|
|
|
123
129
|
export function isForbiddenOutboundIp(addr: string): boolean {
|
|
124
130
|
const parsed = parse(addr);
|
|
125
131
|
if (!parsed) return true;
|
|
126
|
-
return
|
|
132
|
+
return (parsed.family === 'ipv6' && !IPV6_GLOBAL_UNICAST.check(parsed.ip, 'ipv6'))
|
|
133
|
+
|| INTERNAL.check(parsed.ip, parsed.family)
|
|
134
|
+
|| NOT_PUBLIC.check(parsed.ip, parsed.family);
|
|
127
135
|
}
|
|
@@ -7,11 +7,8 @@
|
|
|
7
7
|
* message: 'Please check these fields: email, password',
|
|
8
8
|
* fields: [{ field: 'email', message: 'Invalid email address' }, ...] } }
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* drops an issue's `input` unless `reportInput` is set, which nothing here
|
|
13
|
-
* does. Keep it that way: a value in a validation answer can leak a password
|
|
14
|
-
* into logs, screenshots or a support ticket.
|
|
10
|
+
* Keep messages about the rule. Strict-object validators can include submitted
|
|
11
|
+
* key names, so replace that message before exposing it to an API caller.
|
|
15
12
|
*
|
|
16
13
|
* Malformed JSON is not "wrong input" but an unreadable request; it stays a
|
|
17
14
|
* 400 BAD_REQUEST in libs/error-handler.ts.
|
|
@@ -28,6 +25,7 @@ export const MAX_FIELD_ERRORS = 20;
|
|
|
28
25
|
interface IssueLike {
|
|
29
26
|
path: ReadonlyArray<PropertyKey>;
|
|
30
27
|
message: string;
|
|
28
|
+
code?: string;
|
|
31
29
|
}
|
|
32
30
|
|
|
33
31
|
/** Fastify's names for the request parts, shown when the whole part is wrong. */
|
|
@@ -37,11 +35,16 @@ function partName(context: string | undefined): string {
|
|
|
37
35
|
return (context && PART_NAMES[context]) ?? 'input';
|
|
38
36
|
}
|
|
39
37
|
|
|
38
|
+
function safeMessage(code: string | undefined, message: string | undefined): string {
|
|
39
|
+
if (code === 'unrecognized_keys' || code === 'additionalProperties') return 'Unexpected fields';
|
|
40
|
+
return message ?? 'Invalid value';
|
|
41
|
+
}
|
|
42
|
+
|
|
40
43
|
/** Zod issues (from `.parse()` / `.safeParse()`) as field errors. */
|
|
41
44
|
export function fieldsFromZodIssues(issues: ReadonlyArray<IssueLike>, context?: string): FieldError[] {
|
|
42
45
|
return issues.slice(0, MAX_FIELD_ERRORS).map((issue) => ({
|
|
43
46
|
field: issue.path.length > 0 ? issue.path.map(String).join('.') : partName(context),
|
|
44
|
-
message: issue.message,
|
|
47
|
+
message: safeMessage(issue.code, issue.message),
|
|
45
48
|
}));
|
|
46
49
|
}
|
|
47
50
|
|
|
@@ -52,12 +55,12 @@ export function fieldsFromZodIssues(issues: ReadonlyArray<IssueLike>, context?:
|
|
|
52
55
|
* params, body, querystring, headers in that order and stops at the first).
|
|
53
56
|
*/
|
|
54
57
|
export function fieldsFromSchemaValidation(
|
|
55
|
-
validation: ReadonlyArray<{ instancePath?: string; message?: string }>,
|
|
58
|
+
validation: ReadonlyArray<{ instancePath?: string; message?: string; keyword?: string }>,
|
|
56
59
|
context?: string,
|
|
57
60
|
): FieldError[] {
|
|
58
61
|
return validation.slice(0, MAX_FIELD_ERRORS).map((item) => {
|
|
59
62
|
const path = (item.instancePath ?? '').split('/').filter(Boolean).join('.');
|
|
60
|
-
return { field: path || partName(context), message: item.message
|
|
63
|
+
return { field: path || partName(context), message: safeMessage(item.keyword, item.message) };
|
|
61
64
|
});
|
|
62
65
|
}
|
|
63
66
|
|
|
@@ -10,7 +10,7 @@ import { adminRepository } from '../admin.repo.js';
|
|
|
10
10
|
vi.mock('@libs/prisma.js', () => ({
|
|
11
11
|
prisma: {
|
|
12
12
|
user: { findMany: vi.fn(), findUnique: vi.fn(), count: vi.fn(), updateMany: vi.fn() },
|
|
13
|
-
session: { findFirst: vi.fn() },
|
|
13
|
+
session: { findFirst: vi.fn(), deleteMany: vi.fn() },
|
|
14
14
|
},
|
|
15
15
|
isPrismaNotFound: (): boolean => false,
|
|
16
16
|
}));
|
|
@@ -34,16 +34,33 @@ describe('adminRepository', () => {
|
|
|
34
34
|
expect(vi.mocked(prisma.user.findMany).mock.calls[0]?.[0]?.where).toMatchObject({ deletedAt: { not: null } });
|
|
35
35
|
});
|
|
36
36
|
|
|
37
|
+
it('searches for literal characters in name and email filters', async () => {
|
|
38
|
+
await adminRepository.getUsers({ ...list, search: '100%_complete' });
|
|
39
|
+
const contains = '100\\%\\_complete';
|
|
40
|
+
const where = { OR: [{ email: { contains } }, { firstName: { contains } }, { lastName: { contains } }] };
|
|
41
|
+
expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining(where) }));
|
|
42
|
+
expect(prisma.user.count).toHaveBeenCalledWith({ where: expect.objectContaining(where) });
|
|
43
|
+
});
|
|
44
|
+
|
|
37
45
|
it('restore is one conditional update that touches only a deleted row', async () => {
|
|
38
46
|
vi.mocked(prisma.user.updateMany).mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
|
|
39
|
-
await expect(adminRepository.restoreUser('u1')).resolves.toBe(true);
|
|
40
|
-
await expect(adminRepository.restoreUser('u1')).resolves.toBe(false);
|
|
47
|
+
await expect(adminRepository.restoreUser(prisma, 'u1')).resolves.toBe(true);
|
|
48
|
+
await expect(adminRepository.restoreUser(prisma, 'u1')).resolves.toBe(false);
|
|
41
49
|
expect(prisma.user.updateMany).toHaveBeenCalledWith({
|
|
42
|
-
where: { id: 'u1', deletedAt: { not: null } },
|
|
50
|
+
where: { id: 'u1', deletedAt: { not: null }, purgeStartedAt: null },
|
|
43
51
|
data: { deletedAt: null, isActive: true },
|
|
44
52
|
});
|
|
45
53
|
});
|
|
46
54
|
|
|
55
|
+
it('reports deletion only when the selected session is still live', async () => {
|
|
56
|
+
vi.mocked(prisma.session.deleteMany).mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
|
|
57
|
+
await expect(adminRepository.deleteLiveSession(prisma, 's1')).resolves.toBe(true);
|
|
58
|
+
await expect(adminRepository.deleteLiveSession(prisma, 's1')).resolves.toBe(false);
|
|
59
|
+
expect(prisma.session.deleteMany).toHaveBeenCalledWith({
|
|
60
|
+
where: { id: 's1', expiresAt: { gt: expect.any(Date) } },
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
47
64
|
it('user detail reports lastActiveAt (the latest still-existing session), not lastLogin', async () => {
|
|
48
65
|
const seen = new Date('2026-10-19T08:00:00Z');
|
|
49
66
|
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'u1', _count: { sessions: 2 } } as never);
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* from the first parse failed the "true"/"false" check of the second).
|
|
6
6
|
*/
|
|
7
7
|
import { describe, expect, it } from 'vitest';
|
|
8
|
+
import { paginatedResponse } from '@shared/responses/paginatedResponse.js';
|
|
8
9
|
import { getSessionsQuerySchema, getUsersQuerySchema } from '../admin.schemas.js';
|
|
9
10
|
|
|
10
11
|
const twice = <T>(schema: { parse: (v: unknown) => T }, input: unknown): { once: T; again: T } => {
|
|
@@ -35,4 +36,14 @@ describe('admin query schemas survive the second parse', () => {
|
|
|
35
36
|
const { once, again } = twice(getSessionsQuerySchema, { page: '3', userId: '22222222-2222-4222-8222-222222222222' });
|
|
36
37
|
expect(again).toEqual(once);
|
|
37
38
|
});
|
|
39
|
+
|
|
40
|
+
it.each([getUsersQuerySchema, getSessionsQuerySchema])('bounds admin list pages', (schema) => {
|
|
41
|
+
expect(schema.safeParse({ page: '1000', limit: '100' }).success).toBe(true);
|
|
42
|
+
expect(schema.safeParse({ page: '1001', limit: '100' }).success).toBe(false);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('reports the last accessible page while keeping the complete result count', () => {
|
|
46
|
+
const { pagination } = paginatedResponse('Fixture', [], 1000, 10, 10_001).data;
|
|
47
|
+
expect(pagination).toMatchObject({ totalItems: 10_001, totalPages: 1000, hasNextPage: false });
|
|
48
|
+
});
|
|
38
49
|
});
|