same-origin.ts 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * Whether a state-changing request came from another site.
  3. *
  4. * The cookie-authenticated API under /api/protected is called by our own
  5. * pages, so a write arriving from someone else's origin is never legitimate.
  6. * SameSite=Lax cookies already keep a cross-site POST from carrying the
  7. * session, so this is a second wall, and one a security scanner can see.
  8. *
  9. * Reads are left alone, as are requests that carry neither header: native
  10. * clients and server-to-server callers send no Origin, and they are not the
  11. * problem a cross-site request forgery poses.
  12. */
  13. const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
  14. export function isCrossSiteWrite(input: {
  15. method: string
  16. header: (name: string) => string | null
  17. }): boolean {
  18. if (SAFE_METHODS.has(input.method.toUpperCase())) return false
  19. const site = input.header('sec-fetch-site')
  20. if (site === 'cross-site') return true
  21. const origin = input.header('origin')
  22. if (!origin || origin === 'null') return origin === 'null'
  23. const host = input.header('x-forwarded-host') ?? input.header('host')
  24. if (!host) return false
  25. try {
  26. return new URL(origin).host.toLowerCase() !== host.split(',')[0].trim().toLowerCase()
  27. } catch {
  28. return true
  29. }
  30. }