import type { INestApplication } from '@nestjs/common'; import { api, clerkUsers, createApp, otherKeys, resetDatabase, sessionToken, signIn, sql } from './helpers.js'; describe('Users (e2e)', () => { let app: INestApplication; beforeAll(async () => { app = await createApp(); }); afterAll(() => app.close()); beforeEach(resetDatabase); it('creates the account on the first request with 5 free tries', async () => { const response = await api(app).get('/api/me').set(await signIn('user_new', 'new@example.com', 'New Person')).expect(200); expect(response.body).toEqual({ success: true, data: { user: { id: expect.any(String), email: 'new@example.com', name: 'New Person', role: 'user', createdAt: expect.any(String) }, usage: { plan: 'free', limit: 5, used: 0, remaining: 5, renewsAt: null }, }, }); }); it('finds the same account on every later sign-in', async () => { const headers = await signIn('user_a'); const first = await api(app).get('/api/me').set(headers); const again = await api(app) .get('/api/me') .set({ Authorization: `Bearer ${await sessionToken('user_a', { sid: 'sess_other_device' })}` }); expect(again.body.data.user.id).toBe(first.body.data.user.id); }); it('creates a single account when first requests arrive together', async () => { const headers = await signIn('user_race'); const responses = await Promise.all(Array.from({ length: 5 }, () => api(app).get('/api/me').set(headers))); expect(responses.map((response) => response.status)).toEqual([200, 200, 200, 200, 200]); expect(new Set(responses.map((response) => response.body.data.user.id)).size).toBe(1); }); it('keeps a soft-deleted account closed', async () => { const me = await api(app).get('/api/me').set(await signIn('user_gone', 'gone@example.com')); await sql('UPDATE users SET deleted_at = now() WHERE id = $1', [me.body.data.user.id]); const again = await api(app).get('/api/me').set(await signIn('user_gone_2', 'gone@example.com')).expect(403); expect(again.body).toEqual({ success: false, error: { code: 'ACCOUNT_DISABLED', message: expect.any(String) } }); }); it.each([ ['forged', () => sessionToken('user_x', { key: otherKeys.privateKey })], ['another site', () => sessionToken('user_x', { azp: 'https://evil.test' })], ['expired', () => sessionToken('user_x', { expiresIn: -120 })], ['malformed', async () => 'not-a-jwt'], ])('refuses a %s Clerk token', async (_, token) => { clerkUsers.set('user_x', { email: 'x@example.com', name: null }); const response = await api(app).get('/api/me').set('Authorization', `Bearer ${await token()}`).expect(401); expect(response.body.error.code).toBe('UNAUTHENTICATED'); }); it.each([ ['get', '/api/me'], ['get', '/api/tiles'], ['get', '/api/tiles/facets'], ['get', '/api/tiles/marble'], ['post', '/api/processing-token'], ] as const)('requires sign-in for %s %s', async (method, path) => { await api(app)[method](path).expect(401); }); });