torqvoice-com-standin.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import { createHmac, timingSafeEqual } from 'node:crypto'
  2. import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
  3. /**
  4. * torqvoice.com as far as the app can tell.
  5. *
  6. * Plans are sold on the real site, which cannot be part of a test run: it
  7. * has its own database, Stripe keys and deploy. This stands in for the
  8. * three things the app asks of it, with the same shapes the site answers
  9. * with: the bearer-secret API under /api/app/subscription/*, the checkout
  10. * page a handoff lands on, and the account link that signs a person in.
  11. * The app is pointed here by NEXT_PUBLIC_TORQVOICE_COM_URL and shares
  12. * E2E_SERVICE_SECRET with it as TORQVOICE_SERVICE_SECRET.
  13. *
  14. * Tokens are verified exactly as the site verifies them, so a spec that
  15. * lands on the checkout page has proved the signature, the prefix and the
  16. * expiry, not just that a redirect happened. Everything the app sent is
  17. * kept and handed back over /state; POST /state with {linked:false} makes
  18. * the stand-in refuse the app, the way the site refuses a wrong secret.
  19. * Run on its own with `npx tsx e2e/torqvoice-com-standin.ts`.
  20. */
  21. const PORT = Number(process.env.E2E_TORQVOICE_COM_PORT ?? 8028)
  22. const SECRET = process.env.E2E_SERVICE_SECRET ?? 'e2e-service-secret-0123456789abcdef'
  23. interface Call {
  24. path: string
  25. body: Record<string, unknown>
  26. authorized: boolean
  27. /** ms since the epoch, for reading a spec's timeline afterwards */
  28. at: number
  29. }
  30. const state = {
  31. linked: true,
  32. calls: [] as Call[],
  33. }
  34. function json(res: ServerResponse, status: number, body: unknown): void {
  35. res.writeHead(status, { 'content-type': 'application/json' })
  36. res.end(JSON.stringify(body))
  37. }
  38. function html(
  39. res: ServerResponse,
  40. status: number,
  41. title: string,
  42. rows: Record<string, string>
  43. ): void {
  44. const items = Object.entries(rows)
  45. .map(
  46. ([key, value]) => `<li>${key}: <code data-testid="${key}">${escapeHtml(value)}</code></li>`
  47. )
  48. .join('')
  49. res.writeHead(status, { 'content-type': 'text/html; charset=utf-8' })
  50. res.end(
  51. `<!doctype html><title>${escapeHtml(title)}</title><h1>${escapeHtml(title)}</h1><ul>${items}</ul>`
  52. )
  53. }
  54. function escapeHtml(value: string): string {
  55. return value.replace(
  56. /[&<>"]/g,
  57. (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c
  58. )
  59. }
  60. async function readBody(req: IncomingMessage): Promise<string> {
  61. const chunks: Buffer[] = []
  62. for await (const chunk of req) chunks.push(chunk as Buffer)
  63. return Buffer.concat(chunks).toString('utf8')
  64. }
  65. /** The site's verification, byte for byte: HMAC-SHA256 over `${prefix}.${payload}`. */
  66. function verify(prefix: string, token: string): Record<string, unknown> | { error: string } {
  67. const parts = token.split('.')
  68. if (parts.length !== 3 || parts[0] !== prefix) return { error: 'malformed' }
  69. const expected = createHmac('sha256', SECRET).update(`${prefix}.${parts[1]}`).digest('base64url')
  70. const a = Buffer.from(expected)
  71. const b = Buffer.from(parts[2])
  72. if (a.length !== b.length || !timingSafeEqual(a, b)) return { error: 'signature' }
  73. let payload: Record<string, unknown>
  74. try {
  75. payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'))
  76. } catch {
  77. return { error: 'payload' }
  78. }
  79. const now = Math.floor(Date.now() / 1000)
  80. if (typeof payload.exp !== 'number' || payload.exp <= now) return { error: 'expired' }
  81. return payload
  82. }
  83. const server = createServer(async (req, res) => {
  84. const url = new URL(req.url ?? '/', `http://127.0.0.1:${PORT}`)
  85. if (url.pathname === '/health') return json(res, 200, { ok: true })
  86. if (url.pathname === '/state') {
  87. if (req.method === 'POST') {
  88. const body = JSON.parse((await readBody(req)) || '{}')
  89. if (typeof body.linked === 'boolean') {
  90. state.linked = body.linked
  91. console.log(`[torqvoice-com-standin] ${Date.now()} linked=${state.linked}`)
  92. }
  93. if (body.reset) state.calls = []
  94. return json(res, 200, state)
  95. }
  96. return json(res, 200, state)
  97. }
  98. // The checkout page a handoff lands on.
  99. if (req.method === 'GET' && url.pathname === '/checkout') {
  100. const result = verify('tvh1', url.searchParams.get('token') ?? '')
  101. if ('error' in result)
  102. return html(res, 400, 'Stand-in checkout refused', { reason: String(result.error) })
  103. return html(res, 200, 'Stand-in checkout', {
  104. org: String(result.org),
  105. plan: String(result.plan),
  106. email: String(result.email),
  107. appUrl: String(result.appUrl),
  108. })
  109. }
  110. // The account link that signs a person in on the site.
  111. if (req.method === 'GET' && url.pathname === '/api/auth/sso/app-link') {
  112. const result = verify('tva1', url.searchParams.get('token') ?? '')
  113. if ('error' in result)
  114. return html(res, 400, 'Stand-in account refused', { reason: String(result.error) })
  115. return html(res, 200, 'Stand-in account', {
  116. sub: String(result.sub),
  117. email: String(result.email),
  118. emailVerified: String(result.emailVerified),
  119. })
  120. }
  121. // Where "Manage billing" lands.
  122. if (req.method === 'GET' && url.pathname.startsWith('/portal/')) {
  123. return html(res, 200, 'Stand-in billing portal', { org: url.pathname.slice('/portal/'.length) })
  124. }
  125. // The app-facing API.
  126. const api = url.pathname.match(/^\/api\/app\/subscription\/([a-z-]+)$/)
  127. if (req.method === 'POST' && api) {
  128. const path = api[1]
  129. const body = JSON.parse((await readBody(req)) || '{}') as Record<string, unknown>
  130. const authorized = req.headers.authorization === `Bearer ${SECRET}` && state.linked
  131. state.calls.push({ path, body, authorized, at: Date.now() })
  132. if (!authorized) return json(res, 401, { error: 'Unauthorized' })
  133. if (typeof body.appUrl !== 'string') return json(res, 400, { error: 'Invalid request body' })
  134. switch (path) {
  135. case 'ping':
  136. return json(res, 200, { linked: true, source: 'app' })
  137. case 'portal':
  138. return json(res, 200, { url: `http://127.0.0.1:${PORT}/portal/${body.organizationId}` })
  139. case 'cancel':
  140. return json(res, 200, { cancelAtPeriodEnd: true })
  141. case 'resume':
  142. return json(res, 200, { cancelAtPeriodEnd: false })
  143. case 'end':
  144. return json(res, 200, { ended: true })
  145. case 'upgrade-preview':
  146. return json(res, 200, {
  147. amountDue: 41,
  148. currency: 'usd',
  149. prorationDate: Math.floor(Date.now() / 1000),
  150. })
  151. case 'upgrade':
  152. return json(res, 200, { success: true })
  153. case 'sync':
  154. return json(res, 200, { checked: 1, synced: 0, errors: 0 })
  155. default:
  156. return json(res, 404, { error: 'Not found' })
  157. }
  158. }
  159. json(res, 404, { error: 'Not found' })
  160. })
  161. server.listen(PORT, '127.0.0.1', () => {
  162. console.log(`[torqvoice-com-standin] listening on http://127.0.0.1:${PORT}`)
  163. })