[READ-ONLY] Mirror of https://github.com/flo-bit/svelte-cloudflare-statusphere.
statusphere.atmo.tools
atproto
cloudflare-workers
oauth
svelte
1.5 kB
53 lines
1import type { Cookies } from '@sveltejs/kit';
2import { Client } from '@atcute/client';
3import type { Did } from '@atcute/lexicons';
4import type { OAuthSession } from '@atcute/oauth-node-client';
5import { createOAuthClient } from './oauth';
6import { getSignedCookie } from './signed-cookie';
7import { scope } from '../metadata';
8
9export type SessionLocals = {
10 session: OAuthSession | null;
11 client: Client | null;
12 did: Did | null;
13};
14
15/**
16 * Restores an OAuth session from the signed `did` cookie.
17 * Returns session locals to be assigned to `event.locals`.
18 * Deletes the cookie if the session can't be restored.
19 */
20export async function restoreSession(
21 cookies: Cookies,
22 env?: App.Platform['env']
23): Promise<SessionLocals> {
24 const did = getSignedCookie(cookies, 'did') as Did | null;
25
26 if (!did) {
27 return { session: null, client: null, did: null };
28 }
29
30 // If permissions changed since login, invalidate the session
31 const savedScope = getSignedCookie(cookies, 'scope');
32 if (savedScope !== null && savedScope !== scope) {
33 cookies.delete('did', { path: '/' });
34 cookies.delete('scope', { path: '/' });
35 return { session: null, client: null, did: null };
36 }
37
38 try {
39 const oauth = createOAuthClient(env);
40 const session = await oauth.restore(did);
41
42 return {
43 session,
44 client: new Client({ handler: session }),
45 did
46 };
47 } catch (e) {
48 console.error('Failed to restore session:', e);
49 cookies.delete('did', { path: '/' });
50 cookies.delete('scope', { path: '/' });
51 return { session: null, client: null, did: null };
52 }
53}