Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

6.3 KB
Raw Blame
import { generateKeyPairSync, verify } from 'node:crypto'
import { OAUTH_PROVIDERS } from './oauth-providers'

const callback = 'https://api.example.test/auth/callback/'
const credentials = { clientId: 'customer', clientSecret: 'test-secret' }
const identity = (claims: object) =>
  'header.' + Buffer.from(JSON.stringify(claims)).toString('base64url') + '.signature'

describe('App sign-in provider adapters', () => {
  it.each([
    ['github', 'github.com'],
    ['google', 'accounts.google.com'],
    ['apple', 'appleid.apple.com'],
    ['microsoft', 'login.microsoftonline.com'],
    ['facebook', 'www.facebook.com'],
    ['x', 'x.com'],
  ])('sends the registered callback and state to %s', (name, host) => {
    const location = new URL(
      OAUTH_PROVIDERS[name].authorizeUrl({
        creds: credentials,
        redirectUri: callback + name,
        state: 'test-state',
        codeChallenge: 'challenge',
      }),
    )
    expect(location.hostname).toBe(host)
    expect(location.searchParams.get('redirect_uri')).toBe(callback + name)
    expect(location.searchParams.get('state')).toBe('test-state')
    expect(location.searchParams.get('client_id')).toBe(credentials.clientId)
  })
  it.each([
    [
      'google',
      [
        { access_token: 'google-token' },
        { sub: 'g-1', email: '[email protected]', email_verified: true, name: 'Visitor' },
      ],
      'g-1',
      '[email protected]',
    ],
    [
      'google',
      [{ access_token: 'google-token' }, { sub: 'g-1', email: '[email protected]', email_verified: false }],
      'g-1',
      null,
    ],
    [
      'microsoft',
      [{ id_token: identity({ sub: 'm-1', email: '[email protected]', name: 'Visitor', xms_edov: true }) }],
      'm-1',
      '[email protected]',
    ],
    [
      'microsoft',
      [{ id_token: identity({ sub: 'm-2', email: '[email protected]', tid: 'work-tenant' }) }],
      'm-2',
      null,
    ],
    [
      'facebook',
      [
        { access_token: 'token' },
        {
          id: 'f-1',
          email: '[email protected]',
          name: 'Visitor',
          picture: { data: { url: 'https://example.test/a.jpg' } },
        },
      ],
      'f-1',
      '[email protected]',
    ],
    ['x', [{ access_token: 'token' }, { data: { id: 'x-1', username: 'visitor', name: 'Visitor' } }], 'x-1', null],
  ] as const)('maps %s responses to the end-user profile', async (name, replies, id, email) => {
    const responses = [...replies]
    const fetch = jest.fn(async () => Response.json(responses.shift()))
    const profile = await OAUTH_PROVIDERS[name].signIn({
      creds: credentials,
      redirectUri: callback + name,
      code: 'sample',
      codeVerifier: 'sample-verifier',
      fetch,
    })
    expect(profile).toMatchObject({ id, email })
    expect(responses).toEqual([])
  })
  it('signs the Apple token request with the configured App key', async () => {
    const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' })
    const secret = {
      teamId: 'TEAM123456',
      keyId: 'KEY1234567',
      privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(),
    }
    const creds = { clientId: 'com.example.site', clientSecret: JSON.stringify(secret) }
    const fetch: typeof globalThis.fetch = async (url, init) => {
      expect(String(url)).toBe('https://appleid.apple.com/auth/token')
      const form = new URLSearchParams(String(init!.body))
      const [header, claims, signature] = form.get('client_secret')!.split('.')
      expect(JSON.parse(Buffer.from(header, 'base64url').toString()).kid).toBe(secret.keyId)
      expect(JSON.parse(Buffer.from(claims, 'base64url').toString())).toMatchObject({
        iss: secret.teamId,
        sub: creds.clientId,
        aud: 'https://appleid.apple.com',
      })
      expect(
        verify(
          'sha256',
          Buffer.from(header + '.' + claims),
          { key: publicKey, dsaEncoding: 'ieee-p1363' },
          Buffer.from(signature, 'base64url'),
        ),
      ).toBe(true)
      return Response.json({
        id_token: identity({ sub: 'apple-account', email: '[email protected]', email_verified: 'true' }),
      })
    }
    expect(
      await OAUTH_PROVIDERS.apple.signIn({
        creds,
        redirectUri: callback + 'apple',
        code: 'sample',
        codeVerifier: '',
        fetch,
      }),
    ).toMatchObject({ id: 'apple-account', email: '[email protected]' })
  })
  it.each(Object.keys(OAUTH_PROVIDERS))('reports a refused exchange from %s', async (name) => {
    const fetch = jest.fn(async () => Response.json({ error: 'invalid_grant' }, { status: 400 }))
    await expect(
      OAUTH_PROVIDERS[name].signIn({
        creds: credentials,
        redirectUri: callback + name,
        code: 'expired',
        codeVerifier: '',
        fetch,
      }),
    ).rejects.toThrow()
  })
})
it.each([
  ['github', [{ error_description: 'code expired' }], 'code expired'],
  ['github', [{}], 'no access_token'],
  ['google', [{}], 'no access_token'],
  ['microsoft', [{}], 'no id_token'],
  ['microsoft', [{ id_token: 'not.a_token' }], 'unreadable id_token'],
  ['microsoft', [{ id_token: identity({}) }], 'no subject'],
  ['x', [{}], 'no access_token'],
  ['x', [{ access_token: 'token' }, {}], 'no user'],
  ['facebook', [{}], 'no access_token'],
] as const)('explains incomplete %s provider responses', async (name, replies, reason) => {
  const responses = [...replies]
  const fetch = jest.fn(async () => Response.json(responses.shift()))
  await expect(
    OAUTH_PROVIDERS[name].signIn({
      creds: credentials,
      redirectUri: callback + name,
      code: 'test-code',
      codeVerifier: 'v',
      fetch,
    }),
  ).rejects.toThrow(reason)
})
it('accepts GitHub users without public email or display name', async () => {
  for (const [emails, email] of [
    [[], null],
    [[{ email: '[email protected]', primary: false, verified: true }], '[email protected]'],
  ] as const) {
    const replies = [{ access_token: 'token' }, { id: 123, login: 'casey' }, emails]
    const fetch = jest.fn(async () => Response.json(replies.shift()))
    expect(
      await OAUTH_PROVIDERS.github.signIn({
        creds: credentials,
        redirectUri: callback + 'github',
        code: 'test-code',
        codeVerifier: 'v',
        fetch,
      }),
    ).toMatchObject({ name: 'casey', email })
  }
})