Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

12.7 KB
Raw Blame
import { beforeEach, describe, expect, it, vi } from 'vitest'

const findUnique = vi.hoisted(() => vi.fn())
const create = vi.hoisted(() => vi.fn())
const update = vi.hoisted(() => vi.fn())
const remove = vi.hoisted(() => vi.fn())
const updateManyDevices = vi.hoisted(() => vi.fn())
const transaction = vi.hoisted(() => vi.fn())
const signInsChanged = vi.hoisted(() => vi.fn(async () => {}))

vi.mock('../lib/prisma.js', () => ({
  prisma: {
    user: { findUnique, create, update, delete: remove },
    deviceBinding: { updateMany: updateManyDevices },
    $transaction: transaction,
  },
}))
vi.mock('../config/env.js', () => ({ ADMIN_EMAILS: new Set<string>(['[email protected]']) }))
vi.mock('../lib/password.js', () => ({ hashPassword: (p: string) => `hashed:${p}` }))
vi.mock('../lib/harnessAuthCache.js', () => ({ signInsChanged }))

import {
  isProvisionalUserEmail,
  normalizeUserEmail,
  provisionalEmailForExternalId,
  userService,
} from './UserService.js'

const row = (over: Record<string, unknown> = {}): Record<string, unknown> => ({
  id: 'u1',
  email: '[email protected]',
  externalId: 'prod-sub-1',
  stagExternalId: null,
  name: 'A',
  role: 'user',
  autonomousEnv: 'prod',
  ...over,
})

beforeEach(() => {
  vi.clearAllMocks()
  create.mockImplementation(({ data }: { data: Record<string, unknown> }) => ({ id: 'new', ...data }))
  update.mockImplementation(({ data }: { data: Record<string, unknown> }) => row(data))
  remove.mockResolvedValue({})
  updateManyDevices.mockResolvedValue({ count: 1 })
  transaction.mockImplementation(async (operations: Array<Promise<unknown>>) => Promise.all(operations))
})

describe('SSO user identity', () => {
  it('normalizes email and uses it as the lookup key', async () => {
    findUnique.mockResolvedValue(row())

    const user = await userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: ' [email protected] ',
      autonomousEnv: 'prod',
    })

    expect(findUnique).toHaveBeenCalledWith({ where: { email: '[email protected]' } })
    expect(update).not.toHaveBeenCalled()
    expect(user).toMatchObject({ id: 'u1' })
  })

  it('stores the SSO subject in stagExternalId for staging', async () => {
    findUnique.mockResolvedValue(row({ autonomousEnv: 'stag' }))

    await userService.upsertFromSso({
      externalId: 'stag-sub-1',
      email: '[email protected]',
      autonomousEnv: 'stag',
    })

    expect(update).toHaveBeenCalledWith(expect.objectContaining({
      data: { stagExternalId: 'stag-sub-1' },
    }))
  })

  it('claims a prod device provisional row by externalId', async () => {
    const provisional = row({
      email: provisionalEmailForExternalId('prod-sub-1'),
      name: null,
    })
    findUnique.mockResolvedValueOnce(null).mockResolvedValueOnce(provisional)

    await userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: '[email protected]',
      autonomousEnv: 'prod',
      name: 'Owner',
    })

    expect(update).toHaveBeenCalledWith(expect.objectContaining({
      where: { id: 'u1' },
      data: { email: '[email protected]', name: 'Owner' },
    }))
  })

  it('merges a conflicting provisional device row into the email user', async () => {
    const actual = row({ id: 'real', externalId: 'local-prod-real' })
    const provisional = row({
      id: 'pending',
      email: provisionalEmailForExternalId('prod-sub-1'),
    })
    findUnique.mockResolvedValueOnce(actual).mockResolvedValueOnce(provisional)

    await userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: '[email protected]',
      autonomousEnv: 'prod',
    })

    expect(updateManyDevices).toHaveBeenCalledWith({
      where: { userId: 'pending' },
      data: { userId: 'real' },
    })
    expect(remove).toHaveBeenCalledWith({ where: { id: 'pending' } })
    expect(update).toHaveBeenCalledWith(expect.objectContaining({
      where: { id: 'real' },
      // A new production subject forgets the Google subject learned under the old one (lib/googleSubject.ts).
      data: { externalId: 'prod-sub-1', googleSub: null, googleSubCheckedAt: null },
    }))
  })

  it('promotes to admin from the ADMIN_EMAILS allowlist', async () => {
    findUnique.mockResolvedValue(row({ email: '[email protected]' }))

    await userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: '[email protected]',
      autonomousEnv: 'prod',
    })

    expect(update).toHaveBeenCalledWith(expect.objectContaining({ data: { role: 'admin' } }))
  })

  it('creates a staging user with a local prod placeholder', async () => {
    findUnique.mockResolvedValue(null)

    const user = await userService.upsertFromSso({
      externalId: 'stag-sub-1',
      email: '[email protected]',
      autonomousEnv: 'stag',
    })

    expect(user).toMatchObject({
      email: '[email protected]',
      stagExternalId: 'stag-sub-1',
      autonomousEnv: 'stag',
    })
    expect(String((user as Record<string, unknown>).externalId)).toMatch(/^local-prod-[0-9a-f-]{36}$/)
  })

  it('does not adopt a prod subject already owned by another real email', async () => {
    const other = row({ id: 'other', email: '[email protected]' })
    findUnique
      .mockResolvedValueOnce(null)
      .mockResolvedValueOnce(other)
      .mockResolvedValueOnce(null)
      .mockResolvedValueOnce(other)
    create.mockRejectedValueOnce(Object.assign(new Error('Unique constraint failed'), { code: 'P2002' }))

    await expect(userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: '[email protected]',
      autonomousEnv: 'prod',
    })).rejects.toThrow(/assigned to another email/i)
  })
})

describe('sign-in attribution', () => {
  const tags = { source: 'newsletter', campaign: 'oct', rid: 'r-123' }

  it('keeps the tags of the sign-in that creates the account as its acquisition', async () => {
    findUnique.mockResolvedValue(null)

    await userService.upsertFromSso({
      externalId: 'prod-sub-new',
      email: '[email protected]',
      autonomousEnv: 'prod',
      signUpAttribution: tags,
    })

    expect(create).toHaveBeenCalledWith({
      data: expect.objectContaining({
        signUpAttribution: { ...tags, recordedAt: expect.any(Date) },
      }),
    })
  })

  it('creates an untagged account with no acquisition', async () => {
    findUnique.mockResolvedValue(null)

    await userService.upsertFromSso({ externalId: 'prod-sub-new', email: '[email protected]', autonomousEnv: 'prod' })

    expect(create.mock.calls[0][0].data).not.toHaveProperty('signUpAttribution')
  })

  it('never gives an existing account an acquisition from a later tagged sign-in', async () => {
    findUnique.mockResolvedValue(row({ name: null }))

    await userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: '[email protected]',
      autonomousEnv: 'prod',
      name: 'Named',
      signUpAttribution: tags,
    })

    expect(update).toHaveBeenCalledWith({ where: { id: 'u1' }, data: { name: 'Named' } })
  })

  it('takes the SSO name once: a later sign-in with another name leaves the stored one', async () => {
    findUnique.mockResolvedValue(row({ name: 'Elvis' }))

    const user = await userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: '[email protected]',
      autonomousEnv: 'prod',
      name: 'Nguyen Phan Thuy',
    })

    expect(update).not.toHaveBeenCalled()
    expect(user.name).toBe('Elvis')
  })

  it('stays off the write path for a current account even when the sign-in is tagged', async () => {
    findUnique.mockResolvedValue(row())

    await userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: '[email protected]',
      autonomousEnv: 'prod',
      signUpAttribution: tags,
    })

    expect(update).not.toHaveBeenCalled()
  })

  it("keeps the tags of the owner's first sign-in when it claims a device's provisional row", async () => {
    findUnique.mockResolvedValueOnce(null).mockResolvedValueOnce(row({ email: provisionalEmailForExternalId('prod-sub-1') }))

    await userService.upsertFromSso({
      externalId: 'prod-sub-1',
      email: '[email protected]',
      autonomousEnv: 'prod',
      signUpAttribution: tags,
    })

    expect(update).toHaveBeenCalledWith({
      where: { id: 'u1' },
      data: { email: '[email protected]', signUpAttribution: { ...tags, recordedAt: expect.any(Date) } },
    })
  })

  it('records a tagged sign-in only as the latest', async () => {
    await userService.recordSignInAttribution('u1', tags)

    expect(update).toHaveBeenCalledOnce()
    expect(update).toHaveBeenCalledWith({
      where: { id: 'u1' },
      data: { lastAttribution: { ...tags, recordedAt: expect.any(Date) } },
    })
  })
})

describe('provisional identity helpers', () => {
  it('builds a deterministic non-deliverable email', () => {
    expect(provisionalEmailForExternalId('ABC123')).toBe('[email protected]')
    expect(isProvisionalUserEmail('[email protected]')).toBe(true)
    expect(isProvisionalUserEmail('[email protected]')).toBe(false)
    expect(normalizeUserEmail(' [email protected] ')).toBe('[email protected]')
  })

  it('creates one prod provisional identity and returns the race winner', async () => {
    findUnique.mockResolvedValueOnce(null)
    create.mockResolvedValueOnce(row({
      id: 'pending',
      email: provisionalEmailForExternalId('prod-sub-1'),
    }))

    await expect(userService.findOrCreateProdProvisional('prod-sub-1')).resolves.toMatchObject({
      id: 'pending',
      email: provisionalEmailForExternalId('prod-sub-1'),
    })
  })
})

describe('campaign device identity', () => {
  it('creates an email-keyed prod user before the first SSO login', async () => {
    findUnique.mockResolvedValue(null)

    await userService.findOrCreateProdDeviceOwner('prod-sub-1', ' [email protected] ')

    expect(findUnique).toHaveBeenCalledWith({ where: { email: '[email protected]' } })
    expect(create).toHaveBeenCalledWith({
      data: {
        email: '[email protected]',
        externalId: 'prod-sub-1',
        name: undefined,
        role: 'user',
        autonomousEnv: 'prod',
      },
    })
  })
})

describe('create — locally-created accounts', () => {
  it('uses normalized unique email and a namespaced prod externalId', async () => {
    findUnique.mockResolvedValue(null)

    await userService.create({ email: ' [email protected] ', password: 'pw' })

    const data = create.mock.calls[0][0].data as Record<string, unknown>
    expect(String(data.externalId)).toMatch(/^local-[0-9a-f-]{36}$/)
    expect(data.email).toBe('[email protected]')
    expect(data.passwordHash).toBe('hashed:pw')
  })

  it('rejects an existing email through the unique lookup', async () => {
    findUnique.mockResolvedValue(row())

    await expect(userService.create({ email: '[email protected]', password: 'pw' })).rejects.toThrow(/already exists/i)
    expect(findUnique).toHaveBeenCalledWith({ where: { email: '[email protected]' } })
  })
})

describe('a change to what a sign-in answers ends every pod\'s remembered sign-in (#3041)', () => {
  const after = (write: { mock: { invocationCallOrder: number[] } }): void => {
    expect(signInsChanged.mock.invocationCallOrder.at(-1)).toBeGreaterThan(write.mock.invocationCallOrder.at(-1)!)
  }

  it('an SSO sign-in that rewrites the email or the role, after the write', async () => {
    findUnique.mockResolvedValue(row({ email: '[email protected]' }))
    await userService.upsertFromSso({ externalId: 'prod-sub-1', email: '[email protected]', autonomousEnv: 'prod' })
    expect(signInsChanged).toHaveBeenCalledWith('u1')
    after(update)
  })

  it('an account already current writes nothing and moves nothing: SSO auth runs on every request', async () => {
    findUnique.mockResolvedValue(row())
    await userService.upsertFromSso({ externalId: 'prod-sub-1', email: '[email protected]', autonomousEnv: 'prod' })
    expect(signInsChanged).not.toHaveBeenCalled()
  })

  it('a provisional row merged away, after it is deleted', async () => {
    findUnique.mockResolvedValueOnce(row({ id: 'real', externalId: 'local-prod-real' }))
      .mockResolvedValueOnce(row({ id: 'pending', email: provisionalEmailForExternalId('prod-sub-1') }))
    await userService.upsertFromSso({ externalId: 'prod-sub-1', email: '[email protected]', autonomousEnv: 'prod' })
    expect(signInsChanged).toHaveBeenCalledWith('pending')
    expect(signInsChanged.mock.invocationCallOrder[0]).toBeGreaterThan(remove.mock.invocationCallOrder[0]!)
  })

  it('an update of the role or the plane, after the write', async () => {
    findUnique.mockResolvedValue(row())
    await userService.update('u1', { role: 'admin', autonomousEnv: 'stag' })
    expect(signInsChanged).toHaveBeenCalledWith('u1')
    after(update)
  })

  it('removing an account, after the delete', async () => {
    findUnique.mockResolvedValue(row())
    await userService.remove('u1')
    expect(signInsChanged).toHaveBeenCalledWith('u1')
    after(remove)
  })
})