47 lines
1.3 KiB
TypeScript
47 lines
1.3 KiB
TypeScript
import { authStorageKey, secureGetItem } from "@/lib/auth-storage"
|
|
|
|
const JWT_STORAGE_KEY = "__convexAuthJWT"
|
|
const REFRESH_STORAGE_KEY = "__convexAuthRefreshToken"
|
|
|
|
function isConvexAuthLocalHost(host: string) {
|
|
return /(localhost|127\.0\.0\.1):\d+/.test(host)
|
|
}
|
|
|
|
function authCookieNames(serverUrl: string) {
|
|
const host = new URL(serverUrl).host
|
|
const prefix = isConvexAuthLocalHost(host) ? "" : "__Host-"
|
|
return {
|
|
jwt: `${prefix}${JWT_STORAGE_KEY}`,
|
|
refresh: `${prefix}${REFRESH_STORAGE_KEY}`,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Cookies that sign a request to the server in. Pass `refresh: false` for
|
|
* requests that may run after the JWT expires (iOS background downloads): the
|
|
* server would spend the refresh token, and the app's next refresh of the same
|
|
* token would then end the session.
|
|
*/
|
|
export async function getAuthCookieHeader(
|
|
serverUrl: string,
|
|
convexUrl: string,
|
|
{ refresh = true }: { refresh?: boolean } = {}
|
|
): Promise<string | null> {
|
|
const [jwt, refreshToken] = await Promise.all([
|
|
secureGetItem(authStorageKey(JWT_STORAGE_KEY, convexUrl)),
|
|
secureGetItem(authStorageKey(REFRESH_STORAGE_KEY, convexUrl)),
|
|
])
|
|
|
|
if (!jwt) {
|
|
return null
|
|
}
|
|
|
|
const names = authCookieNames(serverUrl)
|
|
const parts = [`${names.jwt}=${jwt}`]
|
|
if (refresh && refreshToken) {
|
|
parts.push(`${names.refresh}=${refreshToken}`)
|
|
}
|
|
|
|
return parts.join("; ")
|
|
}
|