google-standin-preload.mjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Points the app server's calls to Google at the stand-in, and nothing else.
  3. *
  4. * Loaded into the app under test through NODE_OPTIONS=--import, and only in
  5. * the cloud-mode run: better-auth's Google provider has its endpoints written
  6. * into it, so there is no setting to change, and the app's own code is left
  7. * exactly as it ships. Every other request goes where it was going.
  8. *
  9. * Inert unless E2E_GOOGLE_STANDIN_URL is set.
  10. */
  11. const standin = process.env.E2E_GOOGLE_STANDIN_URL?.replace(/\/+$/, '')
  12. if (standin) {
  13. const rewrites = [
  14. ['https://oauth2.googleapis.com/token', `${standin}/token`],
  15. ['https://www.googleapis.com/oauth2/v3/certs', `${standin}/oauth2/v3/certs`],
  16. ]
  17. const original = globalThis.fetch
  18. globalThis.fetch = function fetchThroughStandin(input, init) {
  19. const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input?.url
  20. for (const [from, to] of rewrites) {
  21. if (url?.startsWith(from)) {
  22. const target = to + url.slice(from.length)
  23. if (typeof input === 'string' || input instanceof URL) {
  24. return original.call(this, target, init)
  25. }
  26. return original.call(this, new Request(target, input), init)
  27. }
  28. }
  29. return original.call(this, input, init)
  30. }
  31. console.log(`[google-standin] Google token calls from this server go to ${standin}`)
  32. }