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

422 lines
16 KiB
TypeScript

/**
* UPASS-01..06, UPROF-01..13, UDEL-01..09 — authenticated profile/password/
* delete-account flows on `user.auth`.
*
* All data is created through the API (`registerThrowawayUser`, addresses,
* orders); only rows this suite creates are ever deleted.
*/
import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api'
import { staffClient } from '../helpers/sessions'
import {
createCatalogOrderFixture,
placeOrder,
registerThrowawayUser,
} from '../helpers/fixtures'
jest.setTimeout(180_000)
function randomMobile(): string {
return `9${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`
}
function uniqueEmail(prefix = 'prof'): string {
return `${prefix}-${uniqueSuffix()}@example.com`
}
// Seeded by tests/seed-local.ts: a users row with NO user_creds row.
// Read-only.
const SEEDED_CREDSLESS_IDENTIFIER = 'e2e.nocreds@freshyo.test'
/* -------------------------------------------------------------------------- */
/* 6.4 user.auth.updatePassword */
/* -------------------------------------------------------------------------- */
describe('user.auth.updatePassword (UPASS-01..06)', () => {
it('UPASS-01: a new password makes the old one fail and the new one work', async () => {
const user = await registerThrowawayUser()
const newPassword = 'UpdatedPass!2026'
const res: any = await apiClient(user.token).user.auth.updatePassword.mutate({ password: newPassword })
expect(res.success).toBe(true)
await expectTrpcError(
() => apiClient().user.auth.login.mutate({ identifier: user.email, password: user.password }),
'UNAUTHORIZED'
)
const login: any = await apiClient().user.auth.login.mutate({
identifier: user.email,
password: newPassword,
})
expect(login.success).toBe(true)
})
it('UPASS-02: a password shorter than 6 characters is BAD_REQUEST', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(user.token).user.auth.updatePassword.mutate({ password: 'abc' }),
'BAD_REQUEST'
)
})
it('UPASS-03: no token is 401', async () => {
await expectTrpcError(
() => apiClient().user.auth.updatePassword.mutate({ password: 'FreshyoTest!2026' }),
'UNAUTHORIZED'
)
})
it('UPASS-04 (current): the "insert when no creds row" branch is unreachable via the API', async () => {
// `upsertUserAuthPassword` inserts a credentials row when one is missing, but
// no public endpoint issues a user token for an account without credentials:
// the only creator of such accounts is verifyOtp, which needs a delivered
// OTP. The seeded credentials-less account therefore cannot authenticate.
await expectTrpcError(
() =>
apiClient().user.auth.login.mutate({
identifier: SEEDED_CREDSLESS_IDENTIFIER,
password: 'anything',
}),
'UNAUTHORIZED',
'Account setup incomplete'
)
})
it('UPASS-05: a repeated update keeps the latest password', async () => {
const user = await registerThrowawayUser()
const first = 'FirstPass!2026'
const second = 'SecondPass!2026'
await apiClient(user.token).user.auth.updatePassword.mutate({ password: first })
await apiClient(user.token).user.auth.updatePassword.mutate({ password: second })
await expectTrpcError(
() => apiClient().user.auth.login.mutate({ identifier: user.email, password: first }),
'UNAUTHORIZED'
)
const login: any = await apiClient().user.auth.login.mutate({
identifier: user.email,
password: second,
})
expect(login.success).toBe(true)
})
it('UPASS-06 (current): a staff token hits a null user and returns 500', async () => {
// `updatePassword` is a `protectedProcedure`, so a staff token passes the
// guard, but the handler reads `ctx.user.userId` and `ctx.user` is null for
// staff → TypeError mapped to INTERNAL_SERVER_ERROR (not a clean 401/403).
const staff = await staffClient()
await expectTrpcError(
() => staff.user.auth.updatePassword.mutate({ password: 'FreshyoTest!2026' }),
'INTERNAL_SERVER_ERROR'
)
})
})
/* -------------------------------------------------------------------------- */
/* 6.5 user.auth.updateProfile */
/* -------------------------------------------------------------------------- */
describe('user.auth.updateProfile (UPROF-01..13)', () => {
it('UPROF-01: name/email/mobile are updated and reflected in the response', async () => {
const user = await registerThrowawayUser()
const newName = `Renamed ${uniqueSuffix()}`
const newEmail = uniqueEmail('renamed')
const newMobile = randomMobile()
const res: any = await apiClient(user.token).user.auth.updateProfile.mutate({
name: newName,
email: newEmail,
mobile: newMobile,
})
expect(res.success).toBe(true)
expect(res.data.user).toEqual(
expect.objectContaining({ name: newName, email: newEmail, mobile: newMobile })
)
const login: any = await apiClient().user.auth.login.mutate({
identifier: newEmail,
password: user.password,
})
expect(login.data.user.name).toBe(newName)
})
it('UPROF-02: an empty email leaves the stored email unchanged', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient(user.token).user.auth.updateProfile.mutate({ email: '' })
expect(res.data.user.email).toBe(user.email)
})
it('UPROF-03: an invalid email is 400', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(user.token).user.auth.updateProfile.mutate({ email: 'not-an-email' }),
'BAD_REQUEST',
'Invalid email format'
)
})
it('UPROF-04: a duplicate email is 409', async () => {
const a = await registerThrowawayUser()
const b = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(a.token).user.auth.updateProfile.mutate({ email: b.email }),
'CONFLICT',
'Email already registered'
)
})
it('UPROF-05: an invalid mobile is 400 and a duplicate mobile is 409', async () => {
const a = await registerThrowawayUser()
const b = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(a.token).user.auth.updateProfile.mutate({ mobile: '12345' }),
'BAD_REQUEST',
'Invalid mobile number'
)
await expectTrpcError(
() => apiClient(a.token).user.auth.updateProfile.mutate({ mobile: b.mobile }),
'CONFLICT',
'Mobile number already registered'
)
})
it('UPROF-06: a new password is hashed and the new password logs in', async () => {
const user = await registerThrowawayUser()
const newPassword = 'ProfilePass!2026'
await apiClient(user.token).user.auth.updateProfile.mutate({ password: newPassword })
await expectTrpcError(
() => apiClient().user.auth.login.mutate({ identifier: user.email, password: user.password }),
'UNAUTHORIZED'
)
const login: any = await apiClient().user.auth.login.mutate({
identifier: user.email,
password: newPassword,
})
expect(login.success).toBe(true)
})
it('UPROF-07: bio/dateOfBirth/gender/occupation round-trip through getSelfData', async () => {
const user = await registerThrowawayUser()
await apiClient(user.token).user.auth.updateProfile.mutate({
bio: 'Loves testing',
dateOfBirth: '1995-06-15',
gender: 'female',
occupation: 'engineer',
})
const self: any = await apiClient(user.token).user.user.getSelfData.query()
expect(self.data.user.bio).toBe('Loves testing')
expect(String(self.data.user.dateOfBirth)).toContain('1995-06-15')
expect(self.data.user.gender).toBe('female')
expect(self.data.user.occupation).toBe('engineer')
})
it('UPROF-08: profileImageUrl is returned as a signed URL', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient(user.token).user.auth.updateProfile.mutate({
profileImageUrl: 'https://example.com/profile.png',
})
expect(typeof res.data.user.profileImage).toBe('string')
expect(res.data.user.profileImage).toContain('X-Amz-')
})
it('UPROF-09: a partial update leaves omitted fields unchanged', async () => {
const user = await registerThrowawayUser()
const newName = `Partial ${uniqueSuffix()}`
const res: any = await apiClient(user.token).user.auth.updateProfile.mutate({ name: newName })
expect(res.data.user.name).toBe(newName)
expect(res.data.user.email).toBe(user.email)
expect(res.data.user.mobile).toBe(user.mobile)
})
it('UPROF-10: no token is 401', async () => {
await expectTrpcError(
() => apiClient().user.auth.updateProfile.mutate({ name: 'Nope' }),
'UNAUTHORIZED'
)
})
it("UPROF-11: another user's email/mobile is 409 and does not take over", async () => {
const a = await registerThrowawayUser()
const b = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(a.token).user.auth.updateProfile.mutate({ email: b.email }),
'CONFLICT'
)
await expectTrpcError(
() => apiClient(a.token).user.auth.updateProfile.mutate({ mobile: b.mobile }),
'CONFLICT'
)
// A keeps its own identity; B can still log in.
const self: any = await apiClient(a.token).user.user.getSelfData.query()
expect(self.data.user.email).toBe(a.email)
expect(self.data.user.mobile).toBe(a.mobile)
const bLogin: any = await apiClient().user.auth.login.mutate({
identifier: b.email,
password: b.password,
})
expect(bLogin.data.user.id).toBe(b.userId)
})
it('UPROF-12 (current): an invalid dateOfBirth surfaces as 500 Invalid time value', async () => {
// `new Date('not-a-date')` is an Invalid Date; persisting it throws while
// serialising to the DB column → INTERNAL_SERVER_ERROR rather than a 400.
const user = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(user.token).user.auth.updateProfile.mutate({ dateOfBirth: 'not-a-date' }),
'INTERNAL_SERVER_ERROR',
'Invalid time value'
)
})
it('UPROF-13: the response echoes the same bearer token', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient(user.token).user.auth.updateProfile.mutate({ name: 'Same Token' })
expect(res.data.token).toBe(user.token)
})
})
/* -------------------------------------------------------------------------- */
/* 6.6 user.auth.deleteAccount */
/* -------------------------------------------------------------------------- */
describe('user.auth.deleteAccount (UDEL-01..09)', () => {
it('UDEL-01: a matching mobile deletes the account and the user can no longer log in', async () => {
const user = await registerThrowawayUser()
const res: any = await apiClient(user.token).user.auth.deleteAccount.mutate({ mobile: user.mobile })
expect(res.success).toBe(true)
await expectTrpcError(
() => apiClient().user.auth.login.mutate({ identifier: user.email, password: user.password }),
'UNAUTHORIZED'
)
})
it('UDEL-02: a wrong mobile is 400', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(user.token).user.auth.deleteAccount.mutate({ mobile: '9000000000' }),
'BAD_REQUEST',
'does not match'
)
})
it('UDEL-03: formatting differences are cleaned so the digits match', async () => {
const user = await registerThrowawayUser()
const m = user.mobile
const formatted = `${m.slice(0, 2)} ${m.slice(2, 5)}-${m.slice(5)}`
const res: any = await apiClient(user.token).user.auth.deleteAccount.mutate({ mobile: formatted })
expect(res.success).toBe(true)
})
it('UDEL-04: a mobile shorter than 10 characters is BAD_REQUEST', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(user.token).user.auth.deleteAccount.mutate({ mobile: '123' }),
'BAD_REQUEST'
)
})
it('UDEL-05: no token is 401', async () => {
await expectTrpcError(
() => apiClient().user.auth.deleteAccount.mutate({ mobile: '9000000000' }),
'UNAUTHORIZED'
)
})
it('UDEL-06: a token for a nonexistent user is 404', async () => {
const user = await registerThrowawayUser()
await apiClient(user.token).user.auth.deleteAccount.mutate({ mobile: user.mobile })
// The token still authenticates the (now-deleted) identity, but the handler
// reloads the user row and rejects with 404.
await expectTrpcError(
() => apiClient(user.token).user.auth.deleteAccount.mutate({ mobile: user.mobile }),
'NOT_FOUND',
'User not found'
)
})
it("UDEL-07: another user's mobile is 400 and does not delete anyone", async () => {
const a = await registerThrowawayUser()
const b = await registerThrowawayUser()
await expectTrpcError(
() => apiClient(a.token).user.auth.deleteAccount.mutate({ mobile: b.mobile }),
'BAD_REQUEST',
'does not match'
)
// Both accounts survive.
const aLogin: any = await apiClient().user.auth.login.mutate({
identifier: a.email,
password: a.password,
})
const bLogin: any = await apiClient().user.auth.login.mutate({
identifier: b.email,
password: b.password,
})
expect(aLogin.data.user.id).toBe(a.userId)
expect(bLogin.data.user.id).toBe(b.userId)
})
it('UDEL-08 (current): the delete cascade is incomplete for a user that has an address', async () => {
// Intended: deleting the account removes addresses/orders and the user.
// Observed: `deleteUserAccount` never clears the `user_regions` row that
// `createAddress` writes, so the final `delete from users` violates the FK
// and the whole mutation returns 500. The local D1 transaction does NOT roll
// back on that error: creds/details/addresses/orders are already gone, while
// the `users` row (and the `user_regions` orphan) survive.
const fixture = await createCatalogOrderFixture({ price: 349 })
const client = apiClient(fixture.user.token)
const placed = await placeOrder(fixture.user.token, {
addressId: fixture.address.id,
skuId: fixture.product.skuId,
slotId: fixture.slot.slotId,
})
expect(placed.length).toBeGreaterThan(0)
const beforeAddresses: any = await client.user.address.getUserAddresses.query()
expect(beforeAddresses.data.length).toBeGreaterThan(0)
await expectTrpcError(
() => client.user.auth.deleteAccount.mutate({ mobile: fixture.user.mobile }),
'INTERNAL_SERVER_ERROR'
)
// Partial cascade that did happen before the FK failure.
await expectTrpcError(
() =>
apiClient().user.auth.login.mutate({
identifier: fixture.user.email,
password: fixture.user.password,
}),
'UNAUTHORIZED',
'Account setup incomplete'
)
const addresses: any = await client.user.address.getUserAddresses.query()
expect(addresses.data).toEqual([])
const orders: any = await client.user.order.getOrders.query({ page: 1, pageSize: 10 })
expect(orders.data).toEqual([])
})
it('UDEL-09: the token after deletion no longer resolves a profile', async () => {
const user = await registerThrowawayUser()
await apiClient(user.token).user.auth.deleteAccount.mutate({ mobile: user.mobile })
await expectTrpcError(
() => apiClient(user.token).user.user.getSelfData.query(),
'NOT_FOUND',
'User not found'
)
// The identity is gone: no credentials remain to mint a fresh session.
await expectTrpcError(
() => apiClient().user.auth.login.mutate({ identifier: user.email, password: user.password }),
'UNAUTHORIZED'
)
})
})