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
|
@@ -98,6 +98,25 @@ describe('dependency check cache (5 s, single-flight)', () => {
|
|
|
98
98
|
expect(results.at(-1)).toBe(true);
|
|
99
99
|
});
|
|
100
100
|
|
|
101
|
+
it('answers during a stalled check without adding more dependency work', async () => {
|
|
102
|
+
vi.useFakeTimers();
|
|
103
|
+
let finish!: (result: unknown) => void;
|
|
104
|
+
vi.mocked(prisma.$queryRaw).mockReturnValue(new Promise((resolve) => { finish = resolve; }) as never);
|
|
105
|
+
const ready = vi.fn();
|
|
106
|
+
void monitoring.checkReadiness().then(ready);
|
|
107
|
+
await vi.advanceTimersByTimeAsync(2000);
|
|
108
|
+
expect(ready).toHaveBeenCalledWith(false);
|
|
109
|
+
|
|
110
|
+
await vi.advanceTimersByTimeAsync(monitoring.DEPENDENCY_CHECK_TTL_MS);
|
|
111
|
+
expect((await monitoring.performHealthCheck()).status).toBe('unhealthy');
|
|
112
|
+
expect(prisma.$queryRaw).toHaveBeenCalledTimes(1);
|
|
113
|
+
expect(ping).toHaveBeenCalledTimes(1);
|
|
114
|
+
|
|
115
|
+
finish([{ 1: 1 }]);
|
|
116
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
117
|
+
expect(await monitoring.checkReadiness()).toBe(true);
|
|
118
|
+
});
|
|
119
|
+
|
|
101
120
|
it('/ready reuses the check /health just made, and a cached failure is not retried', async () => {
|
|
102
121
|
vi.mocked(prisma.$queryRaw).mockRejectedValue(new Error('down'));
|
|
103
122
|
expect((await monitoring.performHealthCheck()).status).toBe('unhealthy');
|
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Outbound calls from the real app (the layer 7 guarantees that need the
|
|
3
|
-
* whole app):
|
|
4
|
-
* gives the same answer, and gives it within about 10 s instead of holding the
|
|
5
|
-
* request open. The outbound guard itself (internal addresses, redirects,
|
|
6
|
-
* size cap, proxies, URL redaction) is pinned by safe-http.test.ts,
|
|
7
|
-
* http.test.ts and url-safety.test.ts with real local servers.
|
|
3
|
+
* whole app): forgot-password acknowledges work before provider delivery.
|
|
8
4
|
*/
|
|
9
5
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
10
6
|
import type { FastifyInstance } from 'fastify';
|
|
@@ -24,22 +20,23 @@ afterAll(async () => {
|
|
|
24
20
|
});
|
|
25
21
|
|
|
26
22
|
describe('forgot-password when the email provider misbehaves', () => {
|
|
27
|
-
it('
|
|
23
|
+
it('responds before the provider finishes delivery', async () => {
|
|
28
24
|
const u = await registerUser(app, 'hung');
|
|
29
|
-
mail.respond({ delayMs:
|
|
25
|
+
mail.respond({ delayMs: 5_000 });
|
|
30
26
|
const started = Date.now();
|
|
31
27
|
const r = await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } });
|
|
32
28
|
const seconds = (Date.now() - started) / 1000;
|
|
33
|
-
mail.respond({});
|
|
34
29
|
expect(r.status).toBe(200);
|
|
35
|
-
expect(seconds).
|
|
36
|
-
|
|
30
|
+
expect(seconds).toBeLessThan(4);
|
|
31
|
+
await mail.waitFor(u.email);
|
|
32
|
+
mail.respond({});
|
|
37
33
|
}, 30_000);
|
|
38
34
|
|
|
39
35
|
it('a provider that answers an error: still 200, the same answer as for any address', async () => {
|
|
40
36
|
const u = await registerUser(app, 'failing');
|
|
41
37
|
mail.respond({ status: 500 });
|
|
42
38
|
const failing = await call(app, 'POST', '/auth/forgot-password', { payload: { email: u.email } });
|
|
39
|
+
await mail.waitFor(u.email);
|
|
43
40
|
mail.respond({});
|
|
44
41
|
const unknown = await call(app, 'POST', '/auth/forgot-password', { payload: { email: `nobody-${Date.now()}@example.test` } });
|
|
45
42
|
expect(failing.status).toBe(200);
|
|
@@ -8,16 +8,16 @@
|
|
|
8
8
|
* address, and enough of them would block it automatically. The file deletes
|
|
9
9
|
* its limiter keys at the end, and checks the address was never blocked.
|
|
10
10
|
*/
|
|
11
|
-
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
11
|
+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
|
12
12
|
import type { FastifyInstance } from 'fastify';
|
|
13
|
-
import { buildTestApp, call, redis, startEmailStub, uniqueEmail, type EmailStub } from '@/test/integration-helpers.js';
|
|
13
|
+
import { buildTestApp, call, db, redis, registerAdmin, registerUser, startEmailStub, uniqueEmail, type EmailStub } from '@/test/integration-helpers.js';
|
|
14
14
|
|
|
15
15
|
let app: FastifyInstance;
|
|
16
16
|
let mail: EmailStub;
|
|
17
17
|
|
|
18
18
|
beforeAll(async () => {
|
|
19
19
|
process.env.RATE_LIMIT_ENABLED = 'true';
|
|
20
|
-
process.env.RATE_LIMIT_OVERRIDES = 'DEFAULT=5/1m';
|
|
20
|
+
process.env.RATE_LIMIT_OVERRIDES = 'DEFAULT=5/1m,ADMIN_DEFAULT=2/1m';
|
|
21
21
|
mail = await startEmailStub();
|
|
22
22
|
app = await buildTestApp();
|
|
23
23
|
});
|
|
@@ -31,6 +31,35 @@ afterAll(async () => {
|
|
|
31
31
|
});
|
|
32
32
|
|
|
33
33
|
describe('rate limits on', () => {
|
|
34
|
+
it('exempts a currently authorized admin after the anonymous quota is reached', async () => {
|
|
35
|
+
const admin = await registerAdmin(app, 'quota-admin');
|
|
36
|
+
const member = await registerUser(app, 'quota-member');
|
|
37
|
+
const url = '/admin/stats';
|
|
38
|
+
const unauthorized = [await call(app, 'GET', url), await call(app, 'GET', url, { jar: member.jar }), await call(app, 'GET', url)];
|
|
39
|
+
expect(unauthorized.map((result) => result.status)).toEqual([401, 403, 429]);
|
|
40
|
+
for (let request = 0; request < 3; request++) {
|
|
41
|
+
expect((await call(app, 'GET', url, { jar: admin.jar })).status).toBe(200);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('refreshes permanent blocks without a separate deletion of the active cache', async () => {
|
|
46
|
+
const database = await db();
|
|
47
|
+
const connection = await redis();
|
|
48
|
+
const ip = '198.51.100.72';
|
|
49
|
+
const { syncBlockedIpsToRedis } = await import('@libs/ip-block.js');
|
|
50
|
+
await database.blockedIp.create({ data: { ip } });
|
|
51
|
+
const separateDeletion = vi.spyOn(connection, 'del');
|
|
52
|
+
try {
|
|
53
|
+
await syncBlockedIpsToRedis();
|
|
54
|
+
expect(await connection.sismember('blocked_ips', ip)).toBe(1);
|
|
55
|
+
expect(separateDeletion).not.toHaveBeenCalledWith('blocked_ips');
|
|
56
|
+
} finally {
|
|
57
|
+
separateDeletion.mockRestore();
|
|
58
|
+
await database.blockedIp.delete({ where: { ip } });
|
|
59
|
+
await syncBlockedIpsToRedis();
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
34
63
|
it('the 4th forgot-password email to one address within the hour → 429', async () => {
|
|
35
64
|
const email = uniqueEmail('cap');
|
|
36
65
|
const statuses: number[] = [];
|
|
@@ -93,7 +93,7 @@ describe('the query never reaches a request log', () => {
|
|
|
93
93
|
|
|
94
94
|
describe('logRequestLine', () => {
|
|
95
95
|
const request = (url: string): FastifyRequest =>
|
|
96
|
-
({ method: 'GET', url, id: 'req-9', startTime: Date.now() - 5 }) as unknown as FastifyRequest;
|
|
96
|
+
({ method: 'GET', url, routeOptions: { url: requestPath(url) }, id: 'req-9', startTime: Date.now() - 5 }) as unknown as FastifyRequest;
|
|
97
97
|
const reply = (statusCode: number): FastifyReply =>
|
|
98
98
|
({ statusCode, raw: { statusMessage: 'Status' } }) as unknown as FastifyReply;
|
|
99
99
|
|
|
@@ -123,4 +123,12 @@ describe('logRequestLine', () => {
|
|
|
123
123
|
logRequestLine(request('/api/v1/auth/me?x=1'), reply(200), { color: false, fields: false });
|
|
124
124
|
expect(vi.mocked(logger.info).mock.calls[0]).toEqual([expect.stringMatching(/^GET {4}\/api\/v1\/auth\/me 200 /)]);
|
|
125
125
|
});
|
|
126
|
+
|
|
127
|
+
it('logs a registered template without the submitted path segment', () => {
|
|
128
|
+
const matched = { ...request('/api/v1/users/fixture-private'), routeOptions: { url: '/api/v1/users/:id' } } as FastifyRequest;
|
|
129
|
+
logRequestLine(matched, reply(422), { color: false, fields: true });
|
|
130
|
+
const entry = vi.mocked(logger.warn).mock.calls[0];
|
|
131
|
+
expect(entry[0]).toMatchObject({ path: '/api/v1/users/:id' });
|
|
132
|
+
expect(JSON.stringify(entry)).not.toContain('fixture-private');
|
|
133
|
+
});
|
|
126
134
|
});
|
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
import http from 'node:http';
|
|
8
8
|
import type { AddressInfo } from 'node:net';
|
|
9
9
|
import type { LookupAddress } from 'node:dns';
|
|
10
|
+
import { buffer } from 'node:stream/consumers';
|
|
11
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
10
12
|
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
|
11
13
|
import { createSafeHttpClient, safeHttpClient } from '../safe-http.js';
|
|
12
14
|
import { isForbiddenOutboundIp } from '../url-safety.js';
|
|
@@ -31,13 +33,17 @@ const server = http.createServer((req, res) => {
|
|
|
31
33
|
res.writeHead(200, { 'content-type': 'application/octet-stream' });
|
|
32
34
|
return res.end(Buffer.alloc(11 * 1024 * 1024, 1));
|
|
33
35
|
}
|
|
36
|
+
if (url.pathname === '/headers') {
|
|
37
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
38
|
+
return res.end(JSON.stringify(req.headers));
|
|
39
|
+
}
|
|
34
40
|
res.writeHead(200, { 'content-type': 'application/json' });
|
|
35
41
|
res.end(JSON.stringify({ ok: true }));
|
|
36
42
|
});
|
|
37
43
|
|
|
38
44
|
/** Test DNS: public.test → the local server, internal.test → 10.0.0.5, mixed.test → both. */
|
|
39
45
|
const resolve = async (hostname: string): Promise<LookupAddress[]> => {
|
|
40
|
-
if (hostname === 'public.test') return [{ address: '127.0.0.1', family: 4 }];
|
|
46
|
+
if (hostname === 'public.test' || hostname === 'other.test') return [{ address: '127.0.0.1', family: 4 }];
|
|
41
47
|
if (hostname === 'internal.test') return [{ address: '10.0.0.5', family: 4 }];
|
|
42
48
|
if (hostname === 'mixed.test') return [{ address: '127.0.0.1', family: 4 }, { address: '169.254.169.254', family: 4 }];
|
|
43
49
|
return [];
|
|
@@ -67,6 +73,13 @@ describe('safeHttpClient', () => {
|
|
|
67
73
|
expect(res.data).toEqual({ ok: true });
|
|
68
74
|
});
|
|
69
75
|
|
|
76
|
+
it('keeps the guarded adapter when a caller provides a different adapter', async () => {
|
|
77
|
+
const adapter = vi.fn().mockRejectedValue(new Error('fixture adapter should not run'));
|
|
78
|
+
const result = await client.get(`http://public.test:${port}/ok`, { adapter });
|
|
79
|
+
expect(result.data).toEqual({ ok: true });
|
|
80
|
+
expect(adapter).not.toHaveBeenCalled();
|
|
81
|
+
});
|
|
82
|
+
|
|
70
83
|
it.each([
|
|
71
84
|
['a hostname resolving to a private address', 'http://internal.test/'],
|
|
72
85
|
['a hostname where ONE answer is internal', 'http://mixed.test:PORT/ok'],
|
|
@@ -102,16 +115,65 @@ describe('safeHttpClient', () => {
|
|
|
102
115
|
expect(error).toBeInstanceOf(OutboundHttpError);
|
|
103
116
|
});
|
|
104
117
|
|
|
118
|
+
it('strips caller headers when a public redirect changes origin', async () => {
|
|
119
|
+
const headers = { Authorization: 'fixture', Cookie: 'fixture=1', 'X-Custom': 'fixture' };
|
|
120
|
+
const first = await client.get(`http://public.test:${port}/headers`, { headers });
|
|
121
|
+
expect(first.data).toMatchObject({ authorization: 'fixture', cookie: 'fixture=1', 'x-custom': 'fixture' });
|
|
122
|
+
const location = encodeURIComponent(`http://other.test:${port}/headers`);
|
|
123
|
+
const redirected = await client.get(`http://public.test:${port}/redirect?to=${location}`, { headers });
|
|
124
|
+
expect(redirected.data.host).toBe(`other.test:${port}`);
|
|
125
|
+
for (const name of ['authorization', 'cookie', 'x-custom']) expect(redirected.data).not.toHaveProperty(name);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('retains a custom header when a public redirect stays within its origin', async () => {
|
|
129
|
+
const redirected = await client.get(`http://public.test:${port}/redirect?to=/headers`, {
|
|
130
|
+
headers: { 'X-Custom': 'fixture-same-origin' },
|
|
131
|
+
});
|
|
132
|
+
expect(redirected.data['x-custom']).toBe('fixture-same-origin');
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('declines to forward a body to a different origin', async () => {
|
|
136
|
+
const location = encodeURIComponent(`http://other.test:${port}/headers`);
|
|
137
|
+
const before = hits.length;
|
|
138
|
+
const error = await failure(client.post(`http://public.test:${port}/redirect?to=${location}`, { file: 'fixture' }));
|
|
139
|
+
expect(error.kind).toBe('blocked');
|
|
140
|
+
expect(hits.length - before).toBe(1);
|
|
141
|
+
});
|
|
142
|
+
|
|
105
143
|
it('follows at most 3 redirects', async () => {
|
|
106
144
|
const before = hits.length;
|
|
107
|
-
const error = await failure(client.get(`http://public.test:${port}/loop
|
|
145
|
+
const error = await failure(client.get(`http://public.test:${port}/loop`, { maxRedirects: 20 }));
|
|
108
146
|
expect(error).toBeInstanceOf(OutboundHttpError);
|
|
109
147
|
expect(hits.length - before).toBe(4); // the first request + 3 redirects
|
|
110
148
|
});
|
|
111
149
|
|
|
112
150
|
it('stops a response over 10 MB (kind too-large)', async () => {
|
|
113
|
-
const error = await failure(client.get(`http://public.test:${port}/big`, { responseType: 'arraybuffer' }));
|
|
151
|
+
const error = await failure(client.get(`http://public.test:${port}/big`, { responseType: 'arraybuffer', maxContentLength: -1 }));
|
|
152
|
+
expect(error.kind).toBe('too-large');
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it('reports a capped stream failure without exposing the transport request', async () => {
|
|
156
|
+
const response = await client.get(`http://public.test:${port}/big`, {
|
|
157
|
+
responseType: 'stream', maxContentLength: 128,
|
|
158
|
+
});
|
|
159
|
+
const error = await failure(buffer(response.data));
|
|
160
|
+
expect(error).toBeInstanceOf(OutboundHttpError);
|
|
114
161
|
expect(error.kind).toBe('too-large');
|
|
162
|
+
for (const field of ['cause', 'request', 'config']) expect(error).not.toHaveProperty(field);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('includes DNS resolution in the deadline', async () => {
|
|
166
|
+
const slow = createSafeHttpClient({
|
|
167
|
+
resolve: async (hostname) => {
|
|
168
|
+
await delay(250);
|
|
169
|
+
return resolve(hostname);
|
|
170
|
+
},
|
|
171
|
+
isForbidden: (ip) => ip !== '127.0.0.1',
|
|
172
|
+
});
|
|
173
|
+
const before = hits.length;
|
|
174
|
+
const error = await failure(slow.get(`http://public.test:${port}/ok`, { timeout: 50 }));
|
|
175
|
+
expect(error.kind).toBe('timeout');
|
|
176
|
+
expect(hits.length).toBe(before);
|
|
115
177
|
});
|
|
116
178
|
|
|
117
179
|
it('ignores an HTTP_PROXY from the environment (a proxy would fetch the target for us)', async () => {
|
|
@@ -36,8 +36,8 @@ describe('scrubSentryEvent', () => {
|
|
|
36
36
|
expect(serialized).not.toContain('token=abc');
|
|
37
37
|
// Useful, non-secret context survives
|
|
38
38
|
expect(scrubbed.request?.method).toBe('POST');
|
|
39
|
-
expect(scrubbed.request?.url).toBe('https://api.example.test
|
|
40
|
-
expect(scrubbed.request?.headers
|
|
39
|
+
expect(scrubbed.request?.url).toBe('https://api.example.test');
|
|
40
|
+
expect(scrubbed.request?.headers).toEqual({});
|
|
41
41
|
});
|
|
42
42
|
|
|
43
43
|
it('strips tokens from the Referer header, trace data, span attributes and the transaction name', () => {
|
|
@@ -72,11 +72,27 @@ describe('scrubSentryEvent', () => {
|
|
|
72
72
|
for (const secret of ['txn-secret', 'referer-secret', 'trace-secret', 'trace-ref-secret', 'trace-query-secret', 'span-secret']) {
|
|
73
73
|
expect(serialized).not.toContain(secret);
|
|
74
74
|
}
|
|
75
|
-
expect(serialized).toContain('https://app.example.test
|
|
75
|
+
expect(serialized).toContain('https://app.example.test');
|
|
76
76
|
});
|
|
77
77
|
|
|
78
|
-
it('
|
|
79
|
-
const event: Event = { message: 'boom' };
|
|
80
|
-
expect(scrubSentryEvent(event)).toEqual({
|
|
78
|
+
it('preserves event severity without forwarding a free-form message', () => {
|
|
79
|
+
const event: Event = { message: 'boom', level: 'error' };
|
|
80
|
+
expect(scrubSentryEvent(event)).toEqual({ level: 'error' });
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('keeps error structure and discards free-form private values', () => {
|
|
84
|
+
const secret = 'fixture-private-diagnostic-data';
|
|
85
|
+
const event: Event = {
|
|
86
|
+
request: { url: `https://api.example.test/files/${secret}`, headers: { 'X-Custom-Credential': secret } },
|
|
87
|
+
transaction: `GET /files/${secret}`,
|
|
88
|
+
extra: { result: { password: secret } },
|
|
89
|
+
user: { email: secret },
|
|
90
|
+
exception: { values: [{ type: 'TypeError', value: secret }] },
|
|
91
|
+
breadcrumbs: [{ category: 'console', message: secret, data: { payload: { token: secret } } }],
|
|
92
|
+
spans: [{ trace_id: 'trace', span_id: 'span', start_timestamp: 1, description: secret, data: { 'db.statement': secret } }],
|
|
93
|
+
};
|
|
94
|
+
expect(JSON.stringify(scrubSentryEvent(event))).not.toContain(secret);
|
|
95
|
+
expect(event.exception?.values?.[0]).toMatchObject({ type: 'TypeError' });
|
|
96
|
+
expect(event.spans?.[0]).toMatchObject({ trace_id: 'trace', span_id: 'span' });
|
|
81
97
|
});
|
|
82
98
|
});
|
|
@@ -27,6 +27,8 @@ describe('redactUrl', () => {
|
|
|
27
27
|
it('strips credentials from the authority', () => {
|
|
28
28
|
expect(redactUrl('https://user:pa55@api.example.com/v1/x')).toBe('https://api.example.com/v1/x');
|
|
29
29
|
expect(redactUrl('http://token@example.com/')).toBe('http://example.com/');
|
|
30
|
+
expect(redactUrl('https://user:fake@password@api.example.com/x')).toBe('https://api.example.com/x');
|
|
31
|
+
expect(redactUrl('//user:fake@api.example.com/x')).toBe('//api.example.com/x');
|
|
30
32
|
});
|
|
31
33
|
|
|
32
34
|
it('leaves a normal URL unchanged', () => {
|
|
@@ -109,7 +111,7 @@ describe('isForbiddenOutboundIp — only public unicast is a valid destination',
|
|
|
109
111
|
'2002:a00:5::1', // 6to4 embedding 10.0.0.5
|
|
110
112
|
'224.0.0.1', '240.0.0.1', '255.255.255.255', '198.18.0.1', '192.0.0.1',
|
|
111
113
|
'192.0.2.1', '198.51.100.1', '203.0.113.1', '2001:db8::1',
|
|
112
|
-
'ff02::1', 'fec0::1', '100::1', '2001::1',
|
|
114
|
+
'ff02::1', 'fec0::1', '100::1', '2001::1', '3fff::1', '5f00::1',
|
|
113
115
|
])('forbids %s', (addr) => {
|
|
114
116
|
expect(isForbiddenOutboundIp(addr)).toBe(true);
|
|
115
117
|
});
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Prisma, User } from '@prisma/client';
|
|
2
|
+
import { env } from '@config/env.js';
|
|
3
|
+
import { assertAccountCanSignIn, needsEmailVerification } from '@libs/account-status.js';
|
|
4
|
+
import { isPrismaWriteConflict, prisma } from '@libs/prisma.js';
|
|
5
|
+
import { ConflictError, ForbiddenError, ServiceUnavailableError, UnauthorizedError } from '@shared/errors/errors.js';
|
|
6
|
+
import type { JwtPayload, UserRole } from '@shared/types/index.js';
|
|
7
|
+
|
|
8
|
+
export type MutationActor = Pick<JwtPayload, 'userId' | 'sessionId'>;
|
|
9
|
+
type AccountState = Pick<User, 'id' | 'role' | 'isActive' | 'deletedAt' | 'emailVerifiedAt'>;
|
|
10
|
+
|
|
11
|
+
/** A retry repeats every authorization and eligibility read before writing. */
|
|
12
|
+
export async function runAccountMutation<T>(write: (tx: Prisma.TransactionClient) => Promise<T>): Promise<T> {
|
|
13
|
+
for (let attempt = 1; ; attempt++) {
|
|
14
|
+
try {
|
|
15
|
+
return await prisma.$transaction(write, { isolationLevel: 'Serializable' });
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (!isPrismaWriteConflict(error)) throw error;
|
|
18
|
+
if (attempt === 3) {
|
|
19
|
+
throw new ServiceUnavailableError('Account changes are busy. Please try again.');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Lock reads inside the transaction keep an actor valid through the write. */
|
|
26
|
+
export async function assertMutationActor(
|
|
27
|
+
tx: Prisma.TransactionClient,
|
|
28
|
+
actor: MutationActor,
|
|
29
|
+
requiredRole?: UserRole,
|
|
30
|
+
): Promise<void> {
|
|
31
|
+
const account = await tx.user.findUnique({
|
|
32
|
+
where: { id: actor.userId, deletedAt: null },
|
|
33
|
+
select: { role: true, isActive: true, emailVerifiedAt: true },
|
|
34
|
+
});
|
|
35
|
+
if (!account) throw new UnauthorizedError('Session ended', 'SESSION_EXPIRED');
|
|
36
|
+
assertAccountCanSignIn(account);
|
|
37
|
+
const session = await tx.session.findFirst({
|
|
38
|
+
where: { id: actor.sessionId, userId: actor.userId, expiresAt: { gt: new Date() } },
|
|
39
|
+
select: { id: true },
|
|
40
|
+
});
|
|
41
|
+
if (!session) throw new UnauthorizedError('Session ended', 'SESSION_EXPIRED');
|
|
42
|
+
if (requiredRole && account.role !== requiredRole) throw new ForbiddenError('Insufficient permissions');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Check only removals of eligible admins. Bootstrap and repair can add one. */
|
|
46
|
+
export async function assertAnotherSignInAdmin(tx: Prisma.TransactionClient, account: AccountState): Promise<void> {
|
|
47
|
+
if (account.role !== 'ADMIN' || !account.isActive || account.deletedAt || needsEmailVerification(account)) return;
|
|
48
|
+
// Serializable InnoDB reads protect the matching admin set until commit,
|
|
49
|
+
// including against writers on another API replica.
|
|
50
|
+
const others = await tx.user.count({
|
|
51
|
+
where: {
|
|
52
|
+
id: { not: account.id },
|
|
53
|
+
role: 'ADMIN',
|
|
54
|
+
isActive: true,
|
|
55
|
+
deletedAt: null,
|
|
56
|
+
...(env.REQUIRE_USER_VERIFICATION ? { emailVerifiedAt: { not: null } } : {}),
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
if (others === 0) {
|
|
60
|
+
throw new ConflictError('Keep at least one admin who can sign in before making this change.', 'LAST_ADMIN');
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Session-bound rows cascade. Legacy refresh credentials can have no session. */
|
|
65
|
+
export async function revokeAccountCredentials(
|
|
66
|
+
tx: Prisma.TransactionClient, userId: string, keepSessionId?: string,
|
|
67
|
+
): Promise<number> {
|
|
68
|
+
const { count } = await tx.session.deleteMany({
|
|
69
|
+
where: keepSessionId ? { userId, id: { not: keepSessionId } } : { userId },
|
|
70
|
+
});
|
|
71
|
+
await tx.refreshToken.deleteMany({
|
|
72
|
+
where: keepSessionId
|
|
73
|
+
? { userId, OR: [{ sessionId: null }, { sessionId: { not: keepSessionId } }] }
|
|
74
|
+
: { userId },
|
|
75
|
+
});
|
|
76
|
+
return count;
|
|
77
|
+
}
|
|
@@ -6,6 +6,7 @@ import { UnauthorizedError, ForbiddenError, BadRequestError } from '@shared/erro
|
|
|
6
6
|
import { clearAuthCookies } from '@libs/cookies.js';
|
|
7
7
|
import { assertAccountCanSignIn } from '@libs/account-status.js';
|
|
8
8
|
import { parseDurationMs } from '@libs/duration.js';
|
|
9
|
+
import { preventPrivateCaching } from '@libs/private-cache.js';
|
|
9
10
|
import type { JwtPayload, UserRole } from '@shared/types/index.js';
|
|
10
11
|
|
|
11
12
|
// Re-export so existing consumers of `parseDurationMs` from '@libs/auth.js'
|
|
@@ -37,15 +38,16 @@ export function generateRefreshToken(): string {
|
|
|
37
38
|
return uuidv4();
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
export function getRefreshTokenExpiresAt(): Date {
|
|
41
|
+
export function getRefreshTokenExpiresAt(now: Date = new Date()): Date {
|
|
41
42
|
const ms = parseDurationMs(env.JWT_REFRESH_EXPIRY, 7 * 24 * 60 * 60 * 1000);
|
|
42
|
-
return new Date(
|
|
43
|
+
return new Date(now.getTime() + ms);
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
export async function authenticate(
|
|
46
47
|
request: FastifyRequest,
|
|
47
48
|
reply: FastifyReply,
|
|
48
49
|
): Promise<void> {
|
|
50
|
+
preventPrivateCaching(reply);
|
|
49
51
|
try {
|
|
50
52
|
await request.jwtVerify();
|
|
51
53
|
} catch {
|
|
@@ -112,13 +114,15 @@ export async function authenticate(
|
|
|
112
114
|
*/
|
|
113
115
|
export async function optionalAuth(
|
|
114
116
|
request: FastifyRequest,
|
|
115
|
-
|
|
117
|
+
reply: FastifyReply,
|
|
116
118
|
): Promise<void> {
|
|
117
119
|
try {
|
|
118
120
|
await request.jwtVerify();
|
|
119
121
|
} catch {
|
|
120
122
|
// Not authenticated — that's okay for optional auth
|
|
123
|
+
return;
|
|
121
124
|
}
|
|
125
|
+
preventPrivateCaching(reply);
|
|
122
126
|
}
|
|
123
127
|
|
|
124
128
|
export function authorize(...roles: UserRole[]) {
|
|
@@ -136,6 +140,36 @@ export function authorize(...roles: UserRole[]) {
|
|
|
136
140
|
};
|
|
137
141
|
}
|
|
138
142
|
|
|
143
|
+
type AdminAuthorization = { allowed: true } | { allowed: false; error: unknown };
|
|
144
|
+
const adminAuthorization = new WeakMap<FastifyRequest, AdminAuthorization>();
|
|
145
|
+
|
|
146
|
+
/** A request qualifies only after the admin scope verifies its live session and current role. */
|
|
147
|
+
export function isAuthorizedAdminRequest(request: FastifyRequest): boolean {
|
|
148
|
+
return adminAuthorization.get(request)?.allowed === true;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Install only inside the admin route plugin, including its optional routes. */
|
|
152
|
+
export function registerAdminAuthorization(app: FastifyInstance): void {
|
|
153
|
+
const requireAdmin = authorize('ADMIN');
|
|
154
|
+
// Scoped onRequest hooks run before route-level rate limiting. Save failures
|
|
155
|
+
// until preValidation so denied requests still go through the existing quota.
|
|
156
|
+
app.addHook('onRequest', async (request, reply) => {
|
|
157
|
+
try {
|
|
158
|
+
await authenticate(request, reply);
|
|
159
|
+
await requireAdmin(request, reply);
|
|
160
|
+
adminAuthorization.set(request, { allowed: true });
|
|
161
|
+
} catch (error) {
|
|
162
|
+
adminAuthorization.set(request, { allowed: false, error });
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
app.addHook('preValidation', async (request) => {
|
|
167
|
+
const decision = adminAuthorization.get(request);
|
|
168
|
+
if (!decision) throw new UnauthorizedError('Authentication required');
|
|
169
|
+
if (!decision.allowed) throw decision.error;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
139
173
|
/**
|
|
140
174
|
* Middleware: resolves targetUserId from the authenticated user's JWT.
|
|
141
175
|
* Used for /users/me routes.
|
|
@@ -2,6 +2,7 @@ import type { FastifyReply } from 'fastify';
|
|
|
2
2
|
import { env } from '@config/env.js';
|
|
3
3
|
import { parseDurationMs } from '@libs/duration.js';
|
|
4
4
|
import { logger } from '@libs/logger.js';
|
|
5
|
+
import { preventPrivateCaching } from '@libs/private-cache.js';
|
|
5
6
|
|
|
6
7
|
const isProduction = env.NODE_ENV === 'production';
|
|
7
8
|
|
|
@@ -71,14 +72,27 @@ const REFRESH_TOKEN_PATH = '/api/v1/auth';
|
|
|
71
72
|
* Older versions of this template scoped the token cookies to COOKIE_DOMAIN.
|
|
72
73
|
* Browsers that still hold those would send two access_token cookies after an
|
|
73
74
|
* upgrade (the old domain-wide one can win and break auth), so whenever we set
|
|
74
|
-
* or clear tokens we also expire
|
|
75
|
-
*
|
|
75
|
+
* or clear tokens we also expire domain-wide copies on scopes that the API host
|
|
76
|
+
* can serve. Configured previous domains cover changes to COOKIE_DOMAIN.
|
|
76
77
|
*/
|
|
77
78
|
function expireLegacyDomainTokenCookies(reply: FastifyReply): void {
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
79
|
+
const host = reply.request.hostname.toLowerCase();
|
|
80
|
+
const current = sessionIndicatorDomain?.toLowerCase().replace(/^\./, '');
|
|
81
|
+
const domains = [...(sessionIndicatorDomain ? [sessionIndicatorDomain] : []), ...env.COOKIE_LEGACY_DOMAINS];
|
|
82
|
+
const seen = new Set<string>();
|
|
83
|
+
for (const domain of domains) {
|
|
84
|
+
const normalized = domain.toLowerCase().replace(/^\./, '');
|
|
85
|
+
if (seen.has(normalized) || (host !== normalized && !host.endsWith('.' + normalized))) continue;
|
|
86
|
+
seen.add(normalized);
|
|
87
|
+
const legacy = { httpOnly: true, secure: isProduction, sameSite: TOKEN_SAME_SITE, domain };
|
|
88
|
+
reply.clearCookie('access_token', { ...legacy, path: ACCESS_TOKEN_PATH });
|
|
89
|
+
reply.clearCookie('refresh_token', { ...legacy, path: REFRESH_TOKEN_PATH });
|
|
90
|
+
if (normalized !== current) clearSessionMarker(reply, domain);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function clearSessionMarker(reply: FastifyReply, domain?: string): void {
|
|
95
|
+
reply.clearCookie('auth_session', { secure: isProduction, sameSite: SESSION_SAME_SITE, domain, path: '/' });
|
|
82
96
|
}
|
|
83
97
|
|
|
84
98
|
export function setAuthCookies(
|
|
@@ -86,6 +100,7 @@ export function setAuthCookies(
|
|
|
86
100
|
accessToken: string,
|
|
87
101
|
refreshToken: string,
|
|
88
102
|
): void {
|
|
103
|
+
preventPrivateCaching(reply);
|
|
89
104
|
warnIfPlainHttp(reply);
|
|
90
105
|
expireLegacyDomainTokenCookies(reply);
|
|
91
106
|
|
|
@@ -107,6 +122,7 @@ export function setAuthCookies(
|
|
|
107
122
|
|
|
108
123
|
// Non-sensitive session indicator visible to the Next.js proxy and client JS.
|
|
109
124
|
// Lets the proxy distinguish "never logged in" from "access token expired but session alive."
|
|
125
|
+
if (sessionIndicatorDomain) clearSessionMarker(reply);
|
|
110
126
|
reply.setCookie('auth_session', '1', {
|
|
111
127
|
httpOnly: false,
|
|
112
128
|
secure: isProduction,
|
|
@@ -118,6 +134,7 @@ export function setAuthCookies(
|
|
|
118
134
|
}
|
|
119
135
|
|
|
120
136
|
export function clearAuthCookies(reply: FastifyReply): void {
|
|
137
|
+
preventPrivateCaching(reply);
|
|
121
138
|
expireLegacyDomainTokenCookies(reply);
|
|
122
139
|
|
|
123
140
|
reply.clearCookie('access_token', {
|
|
@@ -134,11 +151,6 @@ export function clearAuthCookies(reply: FastifyReply): void {
|
|
|
134
151
|
path: REFRESH_TOKEN_PATH,
|
|
135
152
|
});
|
|
136
153
|
|
|
137
|
-
reply
|
|
138
|
-
|
|
139
|
-
secure: isProduction,
|
|
140
|
-
sameSite: SESSION_SAME_SITE,
|
|
141
|
-
domain: sessionIndicatorDomain,
|
|
142
|
-
path: '/',
|
|
143
|
-
});
|
|
154
|
+
clearSessionMarker(reply);
|
|
155
|
+
if (sessionIndicatorDomain) clearSessionMarker(reply, sessionIndicatorDomain);
|
|
144
156
|
}
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* Rules that keep it from leaking which accounts exist:
|
|
20
20
|
* - Call it BEFORE looking the user up, so unknown addresses are counted exactly
|
|
21
21
|
* like real ones and the 429 says nothing about the account.
|
|
22
|
-
* - The counter key is a SHA-256 of the address, so
|
|
22
|
+
* - The counter key is a SHA-256 of the address, so quota keys hold no raw emails.
|
|
23
23
|
*
|
|
24
24
|
* Redis down → the email is allowed (fail open), like the other limiters.
|
|
25
25
|
*/
|
|
@@ -41,6 +41,15 @@ export function emailQuotaKey(email: string, bucket: EmailQuotaBucket = 'public'
|
|
|
41
41
|
return EMAIL_QUOTA_PREFIX[bucket] + createHash('sha256').update(email.trim().toLowerCase()).digest('hex');
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
export function emailQuotaExceeded(ttlMs: number): TooManyRequestsError {
|
|
45
|
+
const seconds = Math.max(1, Math.ceil(ttlMs / 1000));
|
|
46
|
+
return new TooManyRequestsError(
|
|
47
|
+
`Too many emails were sent to this address. Try again in ${describeWait(seconds)}.`,
|
|
48
|
+
'EMAIL_RATE_LIMITED',
|
|
49
|
+
seconds,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
44
53
|
/**
|
|
45
54
|
* Count one email to `email` in `bucket`. Throws 429 EMAIL_RATE_LIMITED (with
|
|
46
55
|
* retryAfterSeconds) once that counter is over its quota for the window.
|
|
@@ -65,10 +74,5 @@ export async function consumeEmailQuota(email: string, bucket: EmailQuotaBucket
|
|
|
65
74
|
logger.warn('[EMAIL-QUOTA] Redis unavailable, sending without the per-address cap');
|
|
66
75
|
return;
|
|
67
76
|
}
|
|
68
|
-
|
|
69
|
-
throw new TooManyRequestsError(
|
|
70
|
-
`Too many emails were sent to this address. Try again in ${describeWait(seconds)}.`,
|
|
71
|
-
'EMAIL_RATE_LIMITED',
|
|
72
|
-
seconds,
|
|
73
|
-
);
|
|
77
|
+
throw emailQuotaExceeded(ttlMs);
|
|
74
78
|
}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Sending email through Resend.
|
|
3
3
|
*
|
|
4
|
-
* - A send gives up after 10 s.
|
|
5
|
-
*
|
|
6
|
-
* for it) open for Node's ~5 minute default. Callers catch and log failures.
|
|
4
|
+
* - A send gives up after 10 s. Callers catch and log failures. Recovery
|
|
5
|
+
* runs in a background job and uses a provider deduplication key.
|
|
7
6
|
* - Recipient addresses are logged masked ('an***@example.com'): enough to
|
|
8
7
|
* trace one email while debugging, never the full address in the logs.
|
|
9
8
|
* - RESEND_BASE_URL (read by the SDK) points sends at a local stub in tests.
|
|
@@ -43,12 +42,14 @@ interface SendEmailOptions {
|
|
|
43
42
|
to: string;
|
|
44
43
|
subject: string;
|
|
45
44
|
html: string;
|
|
45
|
+
idempotencyKey?: string;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
class EmailTimeout extends Error {}
|
|
49
49
|
|
|
50
|
-
export async function sendEmail({ to, subject, html }: SendEmailOptions): Promise<void> {
|
|
50
|
+
export async function sendEmail({ to, subject, html, idempotencyKey }: SendEmailOptions): Promise<void> {
|
|
51
51
|
const client = getResendClient();
|
|
52
|
+
const recipient = idempotencyKey ? {} : { to: maskEmail(to) };
|
|
52
53
|
let timer: NodeJS.Timeout | undefined;
|
|
53
54
|
const timeout = new Promise<never>((_, reject) => {
|
|
54
55
|
timer = setTimeout(() => reject(new EmailTimeout()), SEND_TIMEOUT_MS);
|
|
@@ -57,10 +58,12 @@ export async function sendEmail({ to, subject, html }: SendEmailOptions): Promis
|
|
|
57
58
|
let result: Awaited<ReturnType<typeof client.emails.send>>;
|
|
58
59
|
try {
|
|
59
60
|
// The fetch may still finish in the background; we stop waiting for it.
|
|
60
|
-
|
|
61
|
+
const message = { from: env.RESEND_FROM_EMAIL, to, subject, html };
|
|
62
|
+
const delivery = idempotencyKey ? client.emails.send(message, { idempotencyKey }) : client.emails.send(message);
|
|
63
|
+
result = await Promise.race([delivery, timeout]);
|
|
61
64
|
} catch (error) {
|
|
62
65
|
if (error instanceof EmailTimeout) {
|
|
63
|
-
logger.error({
|
|
66
|
+
logger.error({ ...recipient, timeoutMs: SEND_TIMEOUT_MS }, '[EMAIL] Sending timed out');
|
|
64
67
|
throw new InternalError('Email send timed out');
|
|
65
68
|
}
|
|
66
69
|
throw error;
|
|
@@ -69,9 +72,9 @@ export async function sendEmail({ to, subject, html }: SendEmailOptions): Promis
|
|
|
69
72
|
}
|
|
70
73
|
|
|
71
74
|
if (result.error) {
|
|
72
|
-
logger.error(
|
|
75
|
+
logger.error(recipient, '[EMAIL] Failed to send email');
|
|
73
76
|
throw new InternalError('Failed to send email');
|
|
74
77
|
}
|
|
75
78
|
|
|
76
|
-
logger.info(
|
|
79
|
+
logger.info(recipient, '[EMAIL] Email sent successfully');
|
|
77
80
|
}
|