Read Better Auth sessions from D1

This commit is contained in:
2026-05-09 03:44:00 -04:00
parent 130cf8ec83
commit 0c64a7721e
2 changed files with 121 additions and 9 deletions
+51 -1
View File
@@ -5,6 +5,11 @@ const AUTH_SESSION_CACHE_NAMESPACE = "auth_session_cache";
const BEARER_TOKEN_PATTERN = /^[A-Za-z0-9._~+/=-]{32,4096}$/;
const SUBJECT_ID_PATTERN = /^[a-zA-Z0-9._:-]{3,128}$/;
const DEVICE_ID_PATTERN = /^[a-zA-Z0-9._:-]{3,128}$/;
const BETTER_AUTH_SESSION_QUERY = `
SELECT id, userId, expiresAt
FROM better_auth_session
WHERE token = ?
`;
export interface AuthContext {
userId: string;
@@ -14,6 +19,12 @@ export interface AuthContext {
deviceId?: string;
}
interface BetterAuthSessionRow extends Record<string, unknown> {
id: unknown;
userId: unknown;
expiresAt: unknown;
}
export type AuthErrorCode =
| "authorization_missing"
| "authorization_invalid"
@@ -75,7 +86,7 @@ export async function readAuthContext(
const cacheKey = authSessionCacheKvKey(env.ELY_ENVIRONMENT, tokenHash);
const document = await env.ELY_KV.get(cacheKey);
if (document === null) {
throw new AuthError("session_not_found");
return readBetterAuthSessionContext(env, token, tokenHash, now);
}
const session = parseAuthSessionCacheDocument(document, tokenHash);
@@ -85,6 +96,31 @@ export async function readAuthContext(
return session;
}
async function readBetterAuthSessionContext(
env: Env,
token: string,
tokenHash: string,
now: Date,
): Promise<AuthContext> {
const row = await env.ELY_DB.prepare(BETTER_AUTH_SESSION_QUERY)
.bind(token)
.first<BetterAuthSessionRow>();
if (row === null) {
throw new AuthError("session_not_found");
}
const session: AuthContext = {
userId: subjectId(stringField(row, "userId"), "userId"),
sessionId: subjectId(stringField(row, "id"), "session_id"),
tokenHash,
expiresAt: timestampField(row, "expiresAt"),
};
if (Date.parse(session.expiresAt) <= now.getTime()) {
throw new AuthError("session_expired");
}
return session;
}
export async function authTokenHash(token: string): Promise<string> {
return sha256Hex(token);
}
@@ -156,6 +192,20 @@ function isoTimestamp(value: string, label: string): string {
return new Date(timestamp).toISOString();
}
function timestampField(value: Record<string, unknown>, field: string): string {
const fieldValue = value[field];
if (typeof fieldValue === "string" && fieldValue.trim() !== "") {
return isoTimestamp(fieldValue, field);
}
if (typeof fieldValue === "number" && Number.isFinite(fieldValue)) {
return new Date(fieldValue).toISOString();
}
if (fieldValue instanceof Date) {
return fieldValue.toISOString();
}
throw new AuthSessionCacheSchemaError(`${field}_required`);
}
function stringField(value: Record<string, unknown>, field: string): string {
const fieldValue = value[field];
if (typeof fieldValue !== "string" || fieldValue.trim() === "") {