@kaaarel/auth
Docs: Sessions
View .md

Sessions

Read the user

const user = await auth.user();             // User | null
const current = await auth.session();       // { user, session, scopes? } | null
const signedIn = await auth.requireUser();  // redirects to pages.signIn?next=<this page> when signed out
await auth.requireUser({ next: "/app" });   // give next yourself where the framework cannot tell the page
type User = {
  id: string; email: string; emailVerified: boolean;
  name: string | null; image: string | null;
  hasPassword: boolean; createdAt: Date;
};

type Session = {
  id: string; userId: string;
  method: "password" | "google" | "github" | "email_link" | "dev" | "token";
  workspaceId: string | null;
  ip: string | null; userAgent: string | null;
  createdAt: Date; lastSeenAt: Date; expiresAt: Date;
};

The package reads the session once per request, so several calls cost one query.

Sign out

<form method="post" action="/auth/sign-out"><button>Sign out</button></form>

The route redirects to pages.afterSignOut. Send Accept: application/json to get 204 instead. From a POST server function: await auth.signOut().

Devices

These need a browser session; API tokens get forbidden.

const sessions = await auth.sessions.list();   // each has `current: boolean`
await auth.sessions.revoke({ id });
await auth.sessions.revokeOthers();            // "sign out everywhere else"
  • Name __Host-auth_session on https, auth_session on http.
  • HttpOnly, Secure (https), SameSite=Lax, Path=/, no Domain.
  • The value is 32 random bytes. The database stores its SHA-256 hash, so a database leak gives no usable sessions.
  • 30 days by default (session.days). A session used in its second half gets a full new period.

Cross-site requests

Functions that change something (sign-in, sign-up, settings, …) answer forbidden_origin when:

  • the request is a GET or HEAD (SameSite=Lax cookies still go with cross-site links, so changes must be POST);
  • its Origin is not url or one of trustedOrigins;
  • it has Sec-Fetch-Site: cross-site.

POST requests without an Origin header (server to server) pass.