freshyo/apps/backend/tests/api/user-auth.test.ts
2026-10-20 00:31:05 +05:30

247 lines
8.6 KiB
TypeScript

/**
* UAUTH-01..15 — `user.auth.login`.
*
* Live HTTP suite against the running backend (`wrangler dev`). Only the
* `AppRouter` type is imported; every call goes over the wire.
*/
import { apiClient, expectTrpcError, rawMutation } from '../helpers/api'
import { staffClient } from '../helpers/sessions'
import { registerThrowawayUser } from '../helpers/fixtures'
jest.setTimeout(180_000)
/** A JWT must have header.payload.signature (we do not verify the signature here). */
function tokenParts(token: string): string[] {
return token.split('.')
}
/** Decode the JWT payload without adding a `jwt-decode` dependency. */
function decodeJwtPayload(token: string): any {
const parts = token.split('.')
return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'))
}
// Seeded by tests/seed-local.ts: a users row with NO user_creds row.
// Read-only.
const SEEDED_CREDSLESS_IDENTIFIER = 'e2e.nocreds@freshyo.test'
describe('user.auth.login (UAUTH-01..15)', () => {
it('UAUTH-01: email + password returns a token and the user payload', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient().user.auth.login.mutate({
identifier: user.email,
password: user.password,
})
expect(res.success).toBe(true)
expect(tokenParts(res.data.token)).toHaveLength(3)
expect(res.data.user).toEqual(
expect.objectContaining({
id: user.userId,
email: user.email,
mobile: user.mobile,
name: user.name,
})
)
})
it('UAUTH-02: mobile + password returns a token and the user', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient().user.auth.login.mutate({
identifier: user.mobile,
password: user.password,
})
expect(res.success).toBe(true)
expect(tokenParts(res.data.token)).toHaveLength(3)
expect(Number(res.data.user.id)).toBe(user.userId)
expect(res.data.user.mobile).toBe(user.mobile)
})
it('UAUTH-03: an uppercase email is looked up case-insensitively', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient().user.auth.login.mutate({
identifier: user.email.toUpperCase(),
password: user.password,
})
expect(res.success).toBe(true)
expect(Number(res.data.user.id)).toBe(user.userId)
})
it('UAUTH-04 (current): surrounding whitespace in the identifier is NOT trimmed', async () => {
// The handler lowercases but never trims the identifier before lookup, so
// " email " misses the stored row and the login is rejected as
// "Invalid credentials" (401). Intended behaviour would be to trim.
const user = await registerThrowawayUser()
await expectTrpcError(
() =>
apiClient().user.auth.login.mutate({
identifier: ` ${user.email} `,
password: user.password,
}),
'UNAUTHORIZED',
'Invalid credentials'
)
})
it('UAUTH-05 (current): a country-code prefixed mobile is matched by raw identifier only', async () => {
// The mobile fallback looks up the raw identifier, so "+91<mobile>" does not
// match the stored digit-only mobile and login is rejected (401).
const user = await registerThrowawayUser()
await expectTrpcError(
() =>
apiClient().user.auth.login.mutate({
identifier: `+91${user.mobile}`,
password: user.password,
}),
'UNAUTHORIZED',
'Invalid credentials'
)
})
it('UAUTH-06: an unknown identifier is 401 Invalid credentials', async () => {
await expectTrpcError(
() =>
apiClient().user.auth.login.mutate({
identifier: `nobody-${Date.now()}@example.com`,
password: 'whatever',
}),
'UNAUTHORIZED',
'Invalid credentials'
)
})
it('UAUTH-07: a wrong password is 401', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() => apiClient().user.auth.login.mutate({ identifier: user.email, password: 'definitely-wrong' }),
'UNAUTHORIZED',
'Invalid credentials'
)
})
it('UAUTH-08: missing identifier or password is BAD_REQUEST', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
// @ts-expect-error deliberately malformed input
() => apiClient().user.auth.login.mutate({ password: user.password }),
'BAD_REQUEST'
)
await expectTrpcError(
// @ts-expect-error deliberately malformed input
() => apiClient().user.auth.login.mutate({ identifier: user.email }),
'BAD_REQUEST'
)
})
it('UAUTH-09: an account without credentials is 401 Account setup incomplete', async () => {
// Login finds the user row but `user_creds` has no row for it, so the
// handler rejects with the dedicated message instead of "Invalid credentials".
await expectTrpcError(
() =>
apiClient().user.auth.login.mutate({
identifier: SEEDED_CREDSLESS_IDENTIFIER,
password: 'anything',
}),
'UNAUTHORIZED',
'Account setup incomplete'
)
})
it('UAUTH-10: a profile image is returned as a signed URL', async () => {
const suffix = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
const email = `img-${suffix}@example.com`
const mobile = `9${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`
await apiClient().user.auth.register.mutate({
name: `Img ${suffix}`,
email,
mobile,
password: 'FreshyoTest!2026',
profileImageUrl: 'https://example.com/me.jpg',
})
const res: any = await apiClient().user.auth.login.mutate({
identifier: email,
password: 'FreshyoTest!2026',
})
expect(typeof res.data.user.profileImage).toBe('string')
// Signed R2 URL (generateSignedUrlFromS3Url); a bare stored path is not.
expect(res.data.user.profileImage).toContain('X-Amz-')
})
it('UAUTH-11: a `web` caller receives an auth cookie', async () => {
const user = await registerThrowawayUser()
const res = await rawMutation(
'user.auth.login',
{ identifier: user.email, password: user.password },
{ headers: { 'caller-interface': 'web' } }
)
expect(res.status).toBe(200)
const cookie = res.headers.get('set-cookie')
expect(cookie).toEqual(expect.any(String))
expect(cookie).toContain('auth_token=')
expect(cookie).toContain('HttpOnly')
})
it('UAUTH-12: a non-web (mobile) caller receives no cookie', async () => {
const user = await registerThrowawayUser()
const res = await rawMutation('user.auth.login', {
identifier: user.email,
password: user.password,
})
expect(res.status).toBe(200)
expect(res.headers.get('set-cookie')).toBeNull()
})
it('UAUTH-13 (current): a suspended user can still log in and call protected endpoints', async () => {
// `createContext` throws FORBIDDEN for a suspended user, but that throw is
// swallowed by the surrounding try/catch, so `ctx.user` stays populated.
// Login is public and always succeeds; protected calls are NOT blocked.
const user = await registerThrowawayUser()
const admin = await staffClient()
await admin.admin.user.updateUserSuspension.mutate({ userId: user.userId, isSuspended: true })
try {
const login: any = await apiClient().user.auth.login.mutate({
identifier: user.email,
password: user.password,
})
expect(login.success).toBe(true)
expect(tokenParts(login.data.token)).toHaveLength(3)
// (current) suspension is not enforced on subsequent requests
const self: any = await apiClient(login.data.token).user.user.getSelfData.query()
expect(Number(self.data.user.id)).toBe(user.userId)
} finally {
await admin.admin.user.updateUserSuspension.mutate({ userId: user.userId, isSuspended: false })
}
})
it('UAUTH-14: the token is a JWT carrying the userId claim', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient().user.auth.login.mutate({
identifier: user.email,
password: user.password,
})
const payload = decodeJwtPayload(res.data.token)
expect(Number(payload.userId)).toBe(user.userId)
expect(payload.exp).toEqual(expect.any(Number))
})
it('UAUTH-15: the token is present in the response body', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient().user.auth.login.mutate({
identifier: user.email,
password: user.password,
})
expect(typeof res.data.token).toBe('string')
expect(res.data.token.length).toBeGreaterThan(20)
expect(tokenParts(res.data.token)).toHaveLength(3)
})
})