2026-07-02 13:42:34 -04:00
|
|
|
import crypto from "crypto"
|
|
|
|
|
|
2026-07-03 04:45:24 -04:00
|
|
|
// Signed OAuth `state` (HMAC-SHA256) — carries the initiating owner + provider,
|
|
|
|
|
// a random nonce (bound to a cookie by the connect route for CSRF protection),
|
|
|
|
|
// and an issued-at timestamp so a leaked state can't be replayed indefinitely.
|
2026-07-02 13:42:34 -04:00
|
|
|
|
2026-07-03 04:45:24 -04:00
|
|
|
const STATE_TTL_MS = 10 * 60 * 1000 // 10 minutes
|
|
|
|
|
|
|
|
|
|
// Short-lived httpOnly cookie the connect route sets and the callback verifies
|
|
|
|
|
// against the state's nonce (binds the OAuth round-trip to the initiating browser).
|
|
|
|
|
export const OAUTH_NONCE_COOKIE = "acct_oauth_nonce"
|
|
|
|
|
|
|
|
|
|
// No insecure fallback: signing/verifying state without the real secret would
|
|
|
|
|
// let anyone forge a state for any owner, so we fail closed (mirrors lib/crypto.ts).
|
|
|
|
|
function secret(): string {
|
|
|
|
|
const s = process.env.BETTER_AUTH_SECRET
|
|
|
|
|
if (!s) throw new Error("BETTER_AUTH_SECRET is not set — required to sign OAuth state")
|
|
|
|
|
return s
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export type OAuthState = { ownerId: string; provider: string; nonce: string }
|
|
|
|
|
|
|
|
|
|
export function signState(data: OAuthState): string {
|
|
|
|
|
const payload = Buffer.from(JSON.stringify({ ...data, iat: Date.now() })).toString("base64url")
|
|
|
|
|
const sig = crypto.createHmac("sha256", secret()).update(payload).digest("base64url")
|
2026-07-02 13:42:34 -04:00
|
|
|
return `${payload}.${sig}`
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-03 04:45:24 -04:00
|
|
|
export function verifyState(state: string): OAuthState | null {
|
2026-07-02 13:42:34 -04:00
|
|
|
const [payload, sig] = state.split(".")
|
|
|
|
|
if (!payload || !sig) return null
|
2026-07-03 04:45:24 -04:00
|
|
|
const expect = crypto.createHmac("sha256", secret()).update(payload).digest("base64url")
|
2026-07-02 13:42:34 -04:00
|
|
|
if (sig.length !== expect.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null
|
|
|
|
|
try {
|
2026-07-03 04:45:24 -04:00
|
|
|
const obj = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as OAuthState & { iat?: number }
|
|
|
|
|
if (!obj.iat || Date.now() - obj.iat > STATE_TTL_MS) return null
|
|
|
|
|
if (!obj.ownerId || !obj.provider || !obj.nonce) return null
|
|
|
|
|
return { ownerId: obj.ownerId, provider: obj.provider, nonce: obj.nonce }
|
2026-07-02 13:42:34 -04:00
|
|
|
} catch {
|
|
|
|
|
return null
|
|
|
|
|
}
|
|
|
|
|
}
|