24 lines
999 B
TypeScript
24 lines
999 B
TypeScript
import crypto from "crypto"
|
|||
|
|
|
||
|
|
// Signed OAuth `state` (HMAC-SHA256) — carries the initiating owner + provider
|
||
|
|
// and is tamper-proof, so the callback can't be forged/CSRF'd.
|
||
|
|
const SECRET = process.env.BETTER_AUTH_SECRET ?? "dev-secret"
|
||
|
|
|
||
|
|
export function signState(data: { ownerId: string; provider: string }): string {
|
||
|
|
const payload = Buffer.from(JSON.stringify(data)).toString("base64url")
|
||
|
|
const sig = crypto.createHmac("sha256", SECRET).update(payload).digest("base64url")
|
||
|
|
return `${payload}.${sig}`
|
||
|
|
}
|
||
|
|
|
||
|
|
export function verifyState(state: string): { ownerId: string; provider: string } | null {
|
||
|
|
const [payload, sig] = state.split(".")
|
||
|
|
if (!payload || !sig) return null
|
||
|
|
const expect = crypto.createHmac("sha256", SECRET).update(payload).digest("base64url")
|
||
|
|
if (sig.length !== expect.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null
|
||
|
|
try {
|
||
|
|
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"))
|
||
|
|
} catch {
|
||
|
|
return null
|
||
|
|
}
|
||
|
|
}
|