torqvoice-com-standin.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. interval: String(result.interval),
  107. email: String(result.email),
  108. appUrl: String(result.appUrl),
  109. })
  110. }
  111. // The account link that signs a person in on the site.
  112. if (req.method === 'GET' && url.pathname === '/api/auth/sso/app-link') {
  113. const result = verify('tva1', url.searchParams.get('token') ?? '')
  114. if ('error' in result)
  115. return html(res, 400, 'Stand-in account refused', { reason: String(result.error) })
  116. return html(res, 200, 'Stand-in account', {
  117. sub: String(result.sub),
  118. email: String(result.email),
  119. emailVerified: String(result.emailVerified),
  120. })
  121. }
  122. // Where "Manage billing" lands.
  123. if (req.method === 'GET' && url.pathname.startsWith('/portal/')) {
  124. return html(res, 200, 'Stand-in billing portal', { org: url.pathname.slice('/portal/'.length) })
  125. }
  126. // The app-facing API.
  127. const api = url.pathname.match(/^\/api\/app\/subscription\/([a-z-]+)$/)
  128. if (req.method === 'POST' && api) {
  129. const path = api[1]
  130. const body = JSON.parse((await readBody(req)) || '{}') as Record<string, unknown>
  131. const authorized = req.headers.authorization === `Bearer ${SECRET}` && state.linked
  132. state.calls.push({ path, body, authorized, at: Date.now() })
  133. if (!authorized) return json(res, 401, { error: 'Unauthorized' })
  134. if (typeof body.appUrl !== 'string') return json(res, 400, { error: 'Invalid request body' })
  135. switch (path) {
  136. case 'ping':
  137. return json(res, 200, { linked: true, source: 'app' })
  138. case 'portal':
  139. return json(res, 200, { url: `http://127.0.0.1:${PORT}/portal/${body.organizationId}` })
  140. case 'cancel':
  141. return json(res, 200, { cancelAtPeriodEnd: true })
  142. case 'resume':
  143. return json(res, 200, { cancelAtPeriodEnd: false })
  144. case 'end':
  145. return json(res, 200, { ended: true })
  146. case 'upgrade-preview':
  147. return json(res, 200, {
  148. amountDue: 41,
  149. currency: 'usd',
  150. prorationDate: Math.floor(Date.now() / 1000),
  151. })
  152. case 'upgrade':
  153. return json(res, 200, { success: true })
  154. case 'sync':
  155. return json(res, 200, { checked: 1, synced: 0, errors: 0 })
  156. case 'prices':
  157. return json(res, 200, {
  158. prices: {
  159. pro: { month: { amount: 29, currency: 'usd' }, year: { amount: 290, currency: 'usd' } },
  160. enterprise: {
  161. month: { amount: 79, currency: 'usd' },
  162. year: { amount: 790, currency: 'usd' },
  163. },
  164. },
  165. })
  166. default:
  167. return json(res, 404, { error: 'Not found' })
  168. }
  169. }
  170. json(res, 404, { error: 'Not found' })
  171. })
  172. server.listen(PORT, '127.0.0.1', () => {
  173. console.log(`[torqvoice-com-standin] listening on http://127.0.0.1:${PORT}`)
  174. })