session

tcmts.atproto.session · #3gvzz7jp · function · runs in the browser

uses tcmts.atproto.keptAccount, which uses localStorage

The signed-in account's session in this browser, to act as them (Session: its records, fetch at its PDS, service-auth tokens), or undefined if no one is signed in, or their sign-in no longer works.

import { askedScope, configureBrowser, forget, keptAccount, sessionOver } from "#codebase/tcmts/atproto";
import type { Session } from "#codebase/tcmts/atproto";
import { deleteStoredSession, getSession, OAuthUserAgent } from "@atcute/oauth-browser-client";

export async function session(): Promise<Session | undefined> {
  const kept = keptAccount();
  if (!kept) return undefined;
  await configureBrowser(kept);
  let s: Awaited<ReturnType<typeof getSession>>;
  try {
    s = await getSession(kept.did as `did:${string}:${string}`, { allowStale: true });
  } catch {
    await forget(kept);
    return undefined;
  }
  const agent = new OAuthUserAgent(s);
  return sessionOver({
    did: kept.did,
    ...(kept.handle ? { handle: kept.handle } : {}),
    scope: askedScope(kept),
    send: (path, init) => agent.handle(path, init),
    signOut: async () => {
      await agent.signOut().catch(() => deleteStoredSession(kept.did as `did:${string}:${string}`));
      await forget(kept);
    },
  });
}

uses

used by