22 lines
1.2 KiB
TypeScript
22 lines
1.2 KiB
TypeScript
// Shared with Edge middleware. Only signed, expiring sessions grant editor access.
|
|
export const COOKIE = 'atlas_editor';
|
|
const enc = new TextEncoder();
|
|
async function key() {
|
|
const secret = process.env.EDITOR_SESSION_SECRET;
|
|
if (!secret || secret.length < 32) throw new Error('Editor session secret is not configured');
|
|
return crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
|
|
}
|
|
export async function signSession(value: string) {
|
|
return Array.from(new Uint8Array(await crypto.subtle.sign('HMAC', await key(), enc.encode(value)))).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
}
|
|
export async function validSession(token?: string) {
|
|
if (!token) return false;
|
|
const [expires, nonce, signature, extra] = token.split('.');
|
|
if (extra || !/^\d+$/.test(expires) || !/^[a-f0-9]{32}$/.test(nonce) || !/^[a-f0-9]{64}$/.test(signature)) return false;
|
|
if (Number(expires) < Date.now() || Number(expires) > Date.now() + 8 * 3600_000) return false;
|
|
try {
|
|
const bytes = new Uint8Array(signature.match(/../g)!.map(h => parseInt(h, 16)));
|
|
return await crypto.subtle.verify('HMAC', await key(), bytes, enc.encode(`${expires}.${nonce}`));
|
|
} catch { return false; }
|
|
}
|