auth-origin-hint.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /**
  2. * A readable reason for better-auth's "Invalid origin".
  3. *
  4. * better-auth refuses any request whose Origin header is not on its trusted
  5. * list, and says only "Invalid origin". On a self-hosted install that
  6. * nearly always means NEXT_PUBLIC_APP_URL differs from the address in the
  7. * browser, so the refusal is rewritten to say which two addresses disagree
  8. * and which variable to set. The refusal itself is left alone: same status,
  9. * same headers, nothing gets through that was refused before.
  10. *
  11. * What the message names is already public. The address the person used is
  12. * their own address bar, and the configured one ships to every browser in
  13. * the bundle as NEXT_PUBLIC_APP_URL. The full trusted list, which can hold
  14. * development and app origins, is not repeated.
  15. */
  16. export const INVALID_ORIGIN_CODE = 'INVALID_ORIGIN'
  17. const BETTER_AUTH_MESSAGE = 'Invalid origin'
  18. const MAX_ORIGIN_LENGTH = 200
  19. /** Scheme, host and port only; anything unparseable is dropped, not echoed. */
  20. function toOrigin(raw: string | null | undefined): string | null {
  21. if (!raw) return null
  22. try {
  23. const { origin } = new URL(raw)
  24. if (origin === 'null' || origin.length > MAX_ORIGIN_LENGTH) return null
  25. return origin
  26. } catch {
  27. return null
  28. }
  29. }
  30. /** The origin the browser sent, the same way better-auth reads it. */
  31. export function requestOrigin(headers: Headers): string | null {
  32. return toOrigin(headers.get('origin') || headers.get('referer'))
  33. }
  34. export function configuredOrigin(): string | null {
  35. return toOrigin(process.env.NEXT_PUBLIC_APP_URL)
  36. }
  37. export function invalidOriginMessage(origin: string | null, configured: string | null): string {
  38. const fix =
  39. 'Set NEXT_PUBLIC_APP_URL to the exact address you use in the browser, then restart Torqvoice.'
  40. if (origin && configured)
  41. return `You opened Torqvoice at ${origin}, but it is configured for ${configured}. ${fix}`
  42. if (origin)
  43. return `You opened Torqvoice at ${origin}, which is not the address it is configured for. ${fix}`
  44. return `The address you opened Torqvoice at is not the one it is configured for. ${fix}`
  45. }
  46. interface RefusalBody {
  47. code?: unknown
  48. message?: unknown
  49. }
  50. /**
  51. * The same 403, with a body that says why. Any other response, and any 403
  52. * that is not better-auth's origin refusal, passes through untouched.
  53. */
  54. export async function explainInvalidOrigin(
  55. request: Request,
  56. response: Response
  57. ): Promise<Response> {
  58. if (response.status !== 403) return response
  59. if (!(response.headers.get('content-type') ?? '').includes('application/json')) return response
  60. let body: RefusalBody | null
  61. try {
  62. body = (await response.clone().json()) as RefusalBody | null
  63. } catch {
  64. return response
  65. }
  66. if (body?.code !== INVALID_ORIGIN_CODE && body?.message !== BETTER_AUTH_MESSAGE) return response
  67. const origin = requestOrigin(request.headers)
  68. const configured = configuredOrigin()
  69. const headers = new Headers(response.headers)
  70. headers.delete('content-length')
  71. headers.set('content-type', 'application/json')
  72. return new Response(
  73. JSON.stringify({
  74. code: INVALID_ORIGIN_CODE,
  75. message: invalidOriginMessage(origin, configured),
  76. origin,
  77. configured,
  78. }),
  79. { status: response.status, statusText: response.statusText, headers }
  80. )
  81. }
  82. /**
  83. * Said once at startup, since the mismatch itself only shows when someone
  84. * tries to sign in. Both cases are the ones support sees.
  85. */
  86. export function warnAboutAppUrl(): void {
  87. const raw = process.env.NEXT_PUBLIC_APP_URL
  88. if (!raw) {
  89. console.warn(
  90. '[auth] NEXT_PUBLIC_APP_URL is not set. Set it to the address people use in the browser, or sign-in is refused with "Invalid origin" and links in emails have no address.'
  91. )
  92. return
  93. }
  94. const origin = toOrigin(raw)
  95. if (!origin) {
  96. console.warn(
  97. `[auth] NEXT_PUBLIC_APP_URL is not a valid URL. Set it to the full address people use in the browser, such as https://torqvoice.example.com.`
  98. )
  99. return
  100. }
  101. const { hostname } = new URL(origin)
  102. if (
  103. process.env.NODE_ENV === 'production' &&
  104. (hostname === 'localhost' || hostname === '127.0.0.1')
  105. ) {
  106. console.warn(
  107. `[auth] NEXT_PUBLIC_APP_URL is ${origin}. Signing in from any other address is refused with "Invalid origin"; set it to the address people use in the browser.`
  108. )
  109. }
  110. }