auth.oauth-sign-in
Sign users in with OpenID Connect or GitHub (authorisation code + PKCE), and keep them in a signed session cookie.
Integration · does I/O It talks to oidc or github, reads 3 secrets from the environment, and is tested by contract tests on recorded exchanges, offline. Providers and environment.
TypeScript only A Python or Rust project cannot use it.
1.0.0 · published 2026-10-09 by charlie · Anterra
Pinned by 54 contract tests on recorded exchanges, offline, run in TypeScript · per provider: oidc 15, github 10.beginSignIn 11 · completeSignIn 15 · createSession 10 · readSession 10 · sessionCookie 8
What it does
Sign users in with an OpenID Connect issuer (Google, Microsoft Entra ID, Auth0, Okta, Keycloak) or with GitHub, using the OAuth 2.0 authorisation-code flow with PKCE (RFC 7636, S256), and keep them signed in with a session cookie signed by `SESSION_SECRET`. No database is needed for either cookie.
`AUTH_PROVIDER` picks the provider:
The functions
A group: 5 functions that work together, each in its own file, each pinned by its own tests. A project can install only the ones it calls.
- beginSignIn async fn beginSignIn(redirectUri: string, returnTo: string? = null) -> SignInStart
- completeSignIn async fn completeSignIn(callbackUrl: string, signInCookie: string) -> SignedInUser
- createSession (user: SessionUser, maxAgeSeconds: int = 2592000) -> string
- readSession (cookie: string?) -> SessionUser?
- sessionCookie (value: string, maxAgeSeconds: int = 2592000) -> string
The types it declares, generated into your project
/** Where to send the browser, and the state to keep until it comes back. */
export interface SignInStart {
/** redirect the browser here (302) */
readonly url: string;
/** the sealed sign-in state: state, PKCE verifier, nonce and returnTo, valid 10 minutes */
readonly cookie: string;
/** cookie as a Set-Cookie header value, fune_signin, HttpOnly, Secure, SameSite=Lax */
readonly setCookie: string;
}
/** Who signed in, as the provider vouched for them. */
export interface SignedInUser {
/** oidc or github */
readonly provider: string;
/** the provider's stable id for the user; key accounts on provider and subject, not email */
readonly subject: string;
/** their email, when the provider shared one */
readonly email: string | null;
/** whether the provider says the email is verified */
readonly emailVerified: boolean;
readonly name: string | null;
/** the path beginSignIn was given */
readonly returnTo: string | null;
}
/** Who a session belongs to. */
export interface SessionUser {
readonly provider: string;
readonly subject: string;
readonly email: string | null;
readonly name: string | null;
}
Once installed, your code imports each one from the group's module.
beginSignIn throws on bad input 11 tests
async function beginSignIn(redirectUri: string, returnTo: string | null = null): Promise<SignInStart>
| redirectUri | string | your callback URL, registered with the provider: https://, or http://localhost while developing |
| returnTo | string? | where to send the user afterwards: a path on this site, such as /dashboard |
| returns | SignInStart | the provider's URL to redirect the browser to, and the sign-in cookie to set first |
For example
beginSignIn(https://app.acme.example/auth/callback, /dashboard)→ url https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=fune-test-client.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fapp.acme.example%2Fauth%2Fcall… oidc: discovers Google and builds the authorisation URL with PKCE and a noncebeginSignIn(http://localhost:3000/callback)→ url https://id.acme.example/realms/acme/protocol/openid-connect/auth?kc_idp_hint=staff&response_type=code&client_id=acme-web&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&… oidc: a public Keycloak client, its own scopes, an endpoint that already has a querybeginSignIn(https://app.acme.example/auth/callback, /settings?tab=profile)→ url https://github.com/login/oauth/authorize?client_id=Iv1.fune0test0client&redirect_uri=https%3A%2F%2Fapp.acme.example%2Fauth%2Fcallback&scope=read%3Auser%20user%3Aemail&state=AA… github: the authorisation URL needs no request
import { beginSignIn } from "#fune/auth.oauth-sign-in@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { chooseProvider, io } from "./funeio.ts";
import type { SignInStart } from "./auth_oauth_sign_in_types.ts";
import { seal } from "./auth_oauth_sign_in_create_session.ts"; ← createSession, another function of this group · built into the same file, even by a slim install
import { sha256 } from "./crypto_sha256.ts"; ← from crypto.sha256 ^1.0.0 · built alongside by fune
import { base64UrlEncode } from "./encoding_base64.ts"; ← from encoding.base64 ^1.0.0 · built alongside by fune
import { utf8Encode } from "./encoding_utf8.ts"; ← from encoding.utf8 ^1.0.0 · built alongside by fune
import { oidcAuthorizeUrl } from "./auth_oauth_sign_in_adapter_oidc.ts";
import { githubAuthorizeUrl } from "./auth_oauth_sign_in_adapter_github.ts";
/** The providers this integration has, in the order AUTH_PROVIDER names them. */
export const SIGN_IN_PROVIDERS = ["oidc", "github"];
// How long a sign-in may take, from the redirect to the callback.
const SIGN_IN_SECONDS = 600;
/** A path on this site, never another site (an open redirect). */
export function checkReturnTo(returnTo: string | null): void {
if (returnTo === null || returnTo === undefined) return;
if (typeof returnTo !== "string" || !returnTo.startsWith("/") || returnTo.startsWith("//") || returnTo.includes("\\")) {
throw new Error(`returnTo is a path on this site, like /dashboard, not ${JSON.stringify(returnTo)}`);
}
}
/**
* Start a sign-in: a fresh state, PKCE verifier (RFC 7636, S256) and nonce,
* sealed into the sign-in cookie, and the provider's authorisation URL. Set
* the cookie, then redirect the browser to url.
*/
export async function beginSignIn(redirectUri: string, returnTo: string | null = null): Promise<SignInStart> {
if (typeof redirectUri !== "string" || !/^(https:\/\/[^\s/]+|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)(\/[^\s]*)?$/.test(redirectUri)) {
throw new Error(`redirectUri is your callback's full URL over https (http only on localhost), not ${JSON.stringify(redirectUri)}`);
}
checkReturnTo(returnTo);
const provider = chooseProvider("AUTH_PROVIDER", SIGN_IN_PROVIDERS);
const state = base64UrlEncode(io().randomBytes(16));
const verifier = base64UrlEncode(io().randomBytes(32));
const nonce = base64UrlEncode(io().randomBytes(16));
const challenge = base64UrlEncode(sha256(utf8Encode(verifier)));
const exp = Math.floor(io().now() / 1000) + SIGN_IN_SECONDS;
const cookie = seal({ t: "signin", p: provider, st: state, v: verifier, n: nonce, u: redirectUri, r: returnTo, exp });
const params = { redirectUri, state, nonce, challenge };
const url = provider === "oidc" ? await oidcAuthorizeUrl(params) : await githubAuthorizeUrl(params);
return { url, cookie, setCookie: `fune_signin=${cookie}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SIGN_IN_SECONDS}` };
}completeSignIn throws on bad input 15 tests
async function completeSignIn(callbackUrl: string, signInCookie: string): Promise<SignedInUser>
| callbackUrl | string | the full URL the provider redirected back to, with its code and state |
| signInCookie | string | the fune_signin cookie beginSignIn set |
| returns | SignedInUser | who signed in, checked: state, PKCE, and for OIDC the id_token's issuer, audience, nonce and expiry |
For example
completeSignIn(https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLC…)→ provider oidc, subject 110169484474386276334, email ada@example.com, email verified true, name Ada Lovelace, return to /dashboard oidc: Google, a confidential client: the code, the verifier and the id_token's claimscompleteSignIn(https://app.acme.example/auth/callback?session_state=abc&state=c3RhdGUtZm9yLXRlc3Rz&code=kc-code-1, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLCJzdCI6ImMzUmhkR1V0Wm05eUxYUmxjM1J6IiwidiI6ImR…)→ provider oidc, subject f1b2c3d4-0000-4000-8000-000000000001, email grace@acme.example, email verified false, name —, return to — oidc: a public client, aud as a list, no email_verified or namecompleteSignIn(https://app.acme.example/auth/callback?code=ghcode123&state=c3RhdGUtZm9yLXRlc3Rz, eyJ0Ijoic2lnbmluIiwicCI6ImdpdGh1YiIsInN0IjoiYzNSaGRHVXRabTl5TFhSbGMzUnoiLCJ2IjoiZG1WeWFXWnBaWEl0W…)→ provider github, subject 583231, email octocat@github.com, email verified true, name The Octocat, return to /settings github: the token, the user and their primary verified email
import { completeSignIn } from "#fune/auth.oauth-sign-in@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { chooseProvider } from "./funeio.ts";
import type { SignedInUser } from "./auth_oauth_sign_in_types.ts";
import { unseal } from "./auth_oauth_sign_in_create_session.ts"; ← createSession, another function of this group · built into the same file, even by a slim install
import { SIGN_IN_PROVIDERS } from "./auth_oauth_sign_in_begin_sign_in.ts"; ← beginSignIn, another function of this group · built into the same file, even by a slim install
import { oidcExchange } from "./auth_oauth_sign_in_adapter_oidc.ts";
import { githubExchange } from "./auth_oauth_sign_in_adapter_github.ts";
// The query parameters of a URL, decoded ("+" is a space).
function queryOf(url: string): Record<string, string> {
const at = url.indexOf("?");
const out: Record<string, string> = {};
if (at < 0) return out;
const query = url.slice(at + 1).split("#")[0];
for (const part of query.split("&")) {
if (!part) continue;
const eq = part.indexOf("=");
const name = decodeURIComponent((eq < 0 ? part : part.slice(0, eq)).replace(/\+/g, " "));
const value = eq < 0 ? "" : decodeURIComponent(part.slice(eq + 1).replace(/\+/g, " "));
out[name] = value;
}
return out;
}
/**
* Finish a sign-in on the callback: the sign-in cookie must be ours, unexpired
* and for this provider, the state must match it, and the code is exchanged
* with its PKCE verifier. Returns who signed in; make them a session with
* createSession, and clear the fune_signin cookie.
*/
export async function completeSignIn(callbackUrl: string, signInCookie: string): Promise<SignedInUser> {
const provider = chooseProvider("AUTH_PROVIDER", SIGN_IN_PROVIDERS);
const query = queryOf(String(callbackUrl));
if (query.error === "access_denied") throw new Error("the user declined to sign in (access_denied)");
if (query.error) throw new Error(`the provider refused the sign-in (${query.error})${query.error_description ? `: ${query.error_description}` : ""}`);
const saved = signInCookie ? unseal(signInCookie, "signin") : null;
if (!saved) throw new Error("the sign-in cookie is missing, expired or not signed by SESSION_SECRET; start again with beginSignIn");
if (saved.p !== provider) throw new Error(`this sign-in began with ${String(saved.p)}, but AUTH_PROVIDER is ${provider}; start again with beginSignIn`);
if (!query.state || query.state !== saved.st) throw new Error("the state in the callback does not match the sign-in cookie: a forged or stale callback");
if (!query.code) throw new Error("the callback has no code");
const params = { code: query.code, verifier: String(saved.v), redirectUri: String(saved.u), nonce: String(saved.n) };
const user = provider === "oidc" ? await oidcExchange(params) : await githubExchange(params);
return { ...user, returnTo: typeof saved.r === "string" ? saved.r : null };
}createSession throws on bad input 10 tests
export function createSession(user: SessionUser, maxAgeSeconds: number = 2592000): string
| user | SessionUser | who is signed in |
| maxAgeSeconds | int | how long the session lasts; 30 days unless you say |
| returns | string | the signed session cookie value; set it with sessionCookie |
For example
createSession(provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace)→ eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.qvfebz… a 30-day session by defaultcreateSession(provider github, subject 583231, email —, name The Octocat, 3,600)→ eyJ0Ijoic2Vzc2lvbiIsInAiOiJnaXRodWIiLCJzIjoiNTgzMjMxIiwiZSI6bnVsbCwibiI6IlRoZSBPY3RvY2F0IiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3NjcyMjkyMDB9.KAKaMhIhDK4HNrIqoK4ep77xBJnxhBTXIVHg3Lxpiqk an hourcreateSession(provider github, subject 1, email —, name —, 60)→ eyJ0Ijoic2Vzc2lvbiIsInAiOiJnaXRodWIiLCJzIjoiMSIsImUiOm51bGwsIm4iOm51bGwsImlhdCI6MTc2NzIyNTYwMCwiZXhwIjoxNzY3MjI1NjYwfQ.VWB1PBfNPy0h4BysG59jAbCZepEOy6p9fTVKQscW2FE no email or name
import { createSession } from "#fune/auth.oauth-sign-in@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { io, requireEnv } from "./funeio.ts";
import type { SessionUser } from "./auth_oauth_sign_in_types.ts";
import { constantTimeEqual } from "./crypto_constant_time_equal.ts"; ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
import { hmacSha256 } from "./crypto_hmac_sha256.ts"; ← from crypto.hmac-sha256 ^1.0.0 · built alongside by fune
import { base64UrlDecode, base64UrlEncode } from "./encoding_base64.ts"; ← from encoding.base64 ^1.0.0 · built alongside by fune
import { utf8Decode, utf8Encode } from "./encoding_utf8.ts"; ← from encoding.utf8 ^1.0.0 · built alongside by fune
/** SESSION_SECRET as key bytes, refused when it is too short to resist guessing. */
export function sessionKey(): readonly number[] {
const secret = requireEnv("SESSION_SECRET");
if (secret.length < 32) throw new Error(`SESSION_SECRET is ${secret.length} characters; it needs at least 32 (openssl rand -base64 32)`);
return utf8Encode(secret);
}
/** A JSON payload, signed: base64url(payload) "." base64url(HMAC-SHA256 of that text). */
export function seal(payload: Record<string, unknown>): string {
const body = base64UrlEncode(utf8Encode(JSON.stringify(payload)));
return `${body}.${base64UrlEncode(hmacSha256(sessionKey(), utf8Encode(body)))}`;
}
/**
* A sealed payload of the given type ("signin" or "session"), or null when
* it is malformed, signed with another key, of another type or expired.
*/
export function unseal(value: string, type: string): Record<string, unknown> | null {
const key = sessionKey();
const parts = value.split(".");
if (parts.length !== 2 || !/^[A-Za-z0-9_-]+$/.test(parts[0]) || !/^[A-Za-z0-9_-]+$/.test(parts[1])) return null;
let given: readonly number[];
let payload: unknown;
try {
given = base64UrlDecode(parts[1]);
payload = JSON.parse(utf8Decode(base64UrlDecode(parts[0])));
} catch {
return null;
}
if (!constantTimeEqual(given, hmacSha256(key, utf8Encode(parts[0])))) return null;
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
const p = payload as Record<string, unknown>;
if (p.t !== type || typeof p.exp !== "number" || p.exp * 1000 <= io().now()) return null;
return p;
}
/**
* A signed session cookie value for a user, valid for maxAgeSeconds. It
* holds the user's provider, subject, email and name, readable but not
* forgeable: keep anything secret out of it.
*/
export function createSession(user: SessionUser, maxAgeSeconds: number = 2592000): string {
if (!user || typeof user.subject !== "string" || !user.subject) throw new Error("a session needs the user's subject");
if (typeof user.provider !== "string" || !user.provider) throw new Error("a session needs the user's provider");
if (!Number.isInteger(maxAgeSeconds) || maxAgeSeconds <= 0) throw new Error(`maxAgeSeconds is a whole number of seconds above 0, not ${maxAgeSeconds}`);
const iat = Math.floor(io().now() / 1000);
return seal({ t: "session", p: user.provider, s: user.subject, e: user.email ?? null, n: user.name ?? null, iat, exp: iat + maxAgeSeconds });
}readSession throws on bad input 10 tests
export function readSession(cookie: string | null): SessionUser | null
| cookie | string? | the fune_session cookie as the request sent it, or null |
| returns | SessionUser? | who is signed in, or null when the cookie is missing, tampered with, expired or not a session |
For example
readSession(eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.qvfebz…)→ provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace a valid sessionreadSession(eyJ0Ijoic2Vzc2lvbiIsInAiOiJnaXRodWIiLCJzIjoiNTgzMjMxIiwiZSI6bnVsbCwibiI6IlRoZSBPY3RvY2F0IiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3NjcyMjkyMDB9.KAKaMhIhDK4HNrIqoK4ep77xBJnxhBTXIVHg3Lxpiqk)→ provider github, subject 583231, email —, name The Octocat a session one second before it expiresreadSession(eyJ0Ijoic2Vzc2lvbiIsInAiOiJnaXRodWIiLCJzIjoiNTgzMjMxIiwiZSI6bnVsbCwibiI6IlRoZSBPY3RvY2F0IiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3NjcyMjkyMDB9.KAKaMhIhDK4HNrIqoK4ep77xBJnxhBTXIVHg3Lxpiqk)→ — an expired session
import { readSession } from "#fune/auth.oauth-sign-in@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import type { SessionUser } from "./auth_oauth_sign_in_types.ts";
import { unseal } from "./auth_oauth_sign_in_create_session.ts"; ← createSession, another function of this group · built into the same file, even by a slim install
/**
* Who a session cookie belongs to, or null: no cookie, a value not signed
* with SESSION_SECRET, a sign-in cookie, or one past its expiry. Rotating
* SESSION_SECRET signs everyone out.
*/
export function readSession(cookie: string | null): SessionUser | null {
if (cookie === null || cookie === undefined || cookie === "") return null;
const p = unseal(cookie, "session");
if (!p || typeof p.p !== "string" || typeof p.s !== "string") return null;
return {
provider: p.p,
subject: p.s,
email: typeof p.e === "string" ? p.e : null,
name: typeof p.n === "string" ? p.n : null,
};
}sessionCookie throws on bad input 8 tests
export function sessionCookie(value: string, maxAgeSeconds: number = 2592000): string
| value | string | a session value from createSession; "" with maxAgeSeconds 0 signs the user out |
| maxAgeSeconds | int | the same lifetime the session was created with |
| returns | string | the Set-Cookie header value: HttpOnly, Secure, SameSite=Lax, Path=/ |
For example
sessionCookie(eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.qvfebz…)→ fune_session=eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MT… a 30-day cookie by defaultsessionCookie(abc.def, 3,600)→ fune_session=abc.def; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600 an hoursessionCookie(, 0)→ fune_session=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0 signing out
import { sessionCookie } from "#fune/auth.oauth-sign-in@^1";
/**
* The Set-Cookie header value for a session: HttpOnly so scripts cannot
* read it, Secure so it never crosses plain HTTP, SameSite=Lax so another
* site cannot post with it. An empty value and 0 seconds sign the user out.
*/
export function sessionCookie(value: string, maxAgeSeconds: number = 2592000): string {
if (typeof value !== "string" || !/^[A-Za-z0-9._-]*$/.test(value)) throw new Error("a session cookie value is what createSession returned: letters, digits, '.', '-' and '_'");
if (!Number.isInteger(maxAgeSeconds) || maxAgeSeconds < 0) throw new Error(`maxAgeSeconds is a whole number of seconds, 0 or more, not ${maxAgeSeconds}`);
if (value === "" && maxAgeSeconds !== 0) throw new Error("an empty session cookie only signs out: give maxAgeSeconds 0");
return `fune_session=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAgeSeconds}`;
}Providers and environment
An integration is one interface with a provider behind it for each service it can use; each provider is an adapter file in the package. AUTH_PROVIDER picks the provider at run time. Its code reaches the outside only through funeio, which fune build writes beside it. Values are never part of a package: set them in the environment.
| Provider | What it is |
|---|---|
| oidc | Any OpenID Connect issuer, found by discovery: Google, Microsoft Entra ID, Auth0, Okta, Keycloak |
| github | GitHub OAuth apps (github.com/settings/developers): the user's id, login, name and primary verified email |
| Variable | Kind | Needed | Read by | What it is |
|---|---|---|---|---|
| AUTH_PROVIDER | config · picks the provider | required | every provider | which provider signs users in: oidc or github |
| SESSION_SECRET | secret | required | every provider | at least 32 random characters; signs the sign-in and session cookies (openssl rand -base64 32) |
| OIDC_ISSUER | config | required | oidc only | the issuer URL, such as https://accounts.google.com |
| OIDC_CLIENT_ID | config | required | oidc only | the client id the issuer gave this app |
| OIDC_CLIENT_SECRET | secret | optional | oidc only | the client secret; leave unset for a public client (PKCE alone) |
| OIDC_SCOPES | config | optional (default "openid email profile") | oidc only | the scopes to ask for, space-separated; openid is required |
| GITHUB_CLIENT_ID | config | required | github only | the OAuth app's client id |
| GITHUB_CLIENT_SECRET | secret | required | github only | the OAuth app's client secret |
Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 5 dependencies, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add auth.oauth-sign-in
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add auth.oauth-sign-in --only beginSignIn
An integration reads its settings and secrets from the environment. fune build writes every variable it reads, with what each is, to .fune/build/.env.example; fune secrets says which are set (never their values), and fune secrets --check fails a deploy step when one is missing.
fune secrets --check
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./auth.oauth-sign-in-1.0.0-typescript.fune, or fetch it from a terminal with fune pull auth.oauth-sign-in@1.0.0:typescript.
It is TypeScript only, so there is no package for Python or Rust. The full package is one file too: auth.oauth-sign-in-1.0.0.fune, 84,566 bytes, sha256 0f0e6316714ccee7c71e0d7e22a63ea973decabfe7627d34da634a87e088c60e.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before auth.oauth-sign-in.beginSignIn
// fune: before auth.oauth-sign-in.completeSignIn
// fune: before auth.oauth-sign-in.createSession
// fune: before auth.oauth-sign-in.readSession
// fune: before auth.oauth-sign-in.sessionCookie
after — your function gets the result and the arguments, and returns the final result.
// fune: after auth.oauth-sign-in.beginSignIn
// fune: after auth.oauth-sign-in.completeSignIn
// fune: after auth.oauth-sign-in.createSession
// fune: after auth.oauth-sign-in.readSession
// fune: after auth.oauth-sign-in.sessionCookie
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
// fune: replace crypto.constant-time-equal in auth.oauth-sign-in
// fune: replace crypto.hmac-sha256 in auth.oauth-sign-in
// fune: replace crypto.sha256 in auth.oauth-sign-in
// fune: replace encoding.base64 in auth.oauth-sign-in
// fune: replace encoding.utf8 in auth.oauth-sign-in
step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show auth.oauth-sign-in --steps.
// fune: step auth.oauth-sign-in.<fn> after <n|label>
Contract tests
These are contract tests on recorded exchanges, offline: each case runs the interface through one provider with fake credentials and a fixed clock, and the funeio seam serves the HTTP exchanges or socket dialogue it recorded. A request that differs from the recording, or a recorded exchange never made, fails the case. They prove the integration speaks the protocol as recorded and handles what the service answers; they do not reach the service. Every function needs at least 8, every provider at least 2, and every function that does I/O a case through each provider. fune verify runs them in a project, and the registry ran them in its sandbox, which has no network. Cases per provider: oidc 15, github 10. The exact JSON is contracts.json.
beginSignIn 11 contract tests
| Case | Arguments | Expected | |
|---|---|---|---|
| oidc oidc: discovers Google and builds the authorisation URL with PKCE and a nonce | https://app.acme.example/auth/callback, /dashboard | → | url https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=fune-test-client.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fapp.acme.example%2Fauth%2Fcall… |
| oidc oidc: a public Keycloak client, its own scopes, an endpoint that already has a query | http://localhost:3000/callback | → | url https://id.acme.example/realms/acme/protocol/openid-connect/auth?kc_idp_hint=staff&response_type=code&client_id=acme-web&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&… |
| github github: the authorisation URL needs no request | https://app.acme.example/auth/callback, /settings?tab=profile | → | url https://github.com/login/oauth/authorize?client_id=Iv1.fune0test0client&redirect_uri=https%3A%2F%2Fapp.acme.example%2Fauth%2Fcallback&scope=read%3Auser%20user%3Aemail&state=AA… |
| oidc oidc: an issuer with no discovery document | https://app.acme.example/auth/callback | → | error: oidc: https://login.acme.example/.well-known/openid-configuration answered 404; is OIDC_ISSUER right? |
| oidc oidc: a discovery document for another issuer is refused | https://app.acme.example/auth/callback | → | error: oidc: the discovery document is for issuer https://accounts.google.com, not OIDC_ISSUER https://accounts.google.example |
| oidc oidc: scopes without openid | https://app.acme.example/auth/callback | → | error: OIDC_SCOPES is "email profile"; it must include openid |
| github a callback over plain http on a real host is refused | http://app.acme.example/callback | → | error: redirectUri is your callback's full URL over https |
| github returnTo to another site is refused (open redirect) | https://app.acme.example/auth/callback, //evil.example/steal | → | error: returnTo is a path on this site |
| no provider chosen | https://app.acme.example/auth/callback | → | error: AUTH_PROVIDER is not set; set it to one of oidc, github |
| github a short SESSION_SECRET is refused | https://app.acme.example/auth/callback | → | error: SESSION_SECRET is 9 characters; it needs at least 32 |
Show the other 1 test
| Case | Arguments | Expected | |
|---|---|---|---|
| github github: no client id | https://app.acme.example/auth/callback | → | error: GITHUB_CLIENT_ID is not set |
completeSignIn 15 contract tests
| Case | Arguments | Expected | |
|---|---|---|---|
| oidc oidc: Google, a confidential client: the code, the verifier and the id_token's claims | https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLC… | → | provider oidc, subject 110169484474386276334, email ada@example.com, email verified true, name Ada Lovelace, return to /dashboard |
| oidc oidc: a public client, aud as a list, no email_verified or name | https://app.acme.example/auth/callback?session_state=abc&state=c3RhdGUtZm9yLXRlc3Rz&code=kc-code-1, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLCJzdCI6ImMzUmhkR1V0Wm05eUxYUmxjM1J6IiwidiI6ImR… | → | provider oidc, subject f1b2c3d4-0000-4000-8000-000000000001, email grace@acme.example, email verified false, name —, return to — |
| oidc oidc: a used or expired code is thrown with the issuer's reason | https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLC… | → | error: oidc: the token endpoint refused the code (400 invalid_grant): Bad Request |
| oidc oidc: an id_token minted for another sign-in (nonce) is refused | https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLC… | → | error: oidc: the id_token's nonce does not match this sign-in |
| oidc oidc: an expired id_token is refused | https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLC… | → | error: oidc: the id_token has expired |
| oidc oidc: an id_token for another client is refused | https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLC… | → | error: oidc: the id_token is not for OIDC_CLIENT_ID (aud) |
| github github: the token, the user and their primary verified email | https://app.acme.example/auth/callback?code=ghcode123&state=c3RhdGUtZm9yLXRlc3Rz, eyJ0Ijoic2lnbmluIiwicCI6ImdpdGh1YiIsInN0IjoiYzNSaGRHVXRabTl5TFhSbGMzUnoiLCJ2IjoiZG1WeWFXWnBaWEl0W… | → | provider github, subject 583231, email octocat@github.com, email verified true, name The Octocat, return to /settings |
| github github: no verified email, and no name but the login | https://app.acme.example/auth/callback?code=ghcode123&state=c3RhdGUtZm9yLXRlc3Rz, eyJ0Ijoic2lnbmluIiwicCI6ImdpdGh1YiIsInN0IjoiYzNSaGRHVXRabTl5TFhSbGMzUnoiLCJ2IjoiZG1WeWFXWnBaWEl0W… | → | provider github, subject 583231, email —, email verified false, name octocat, return to /dashboard |
| github github: a bad code comes back as status 200 with an error | https://app.acme.example/auth/callback?code=ghcode123&state=c3RhdGUtZm9yLXRlc3Rz, eyJ0Ijoic2lnbmluIiwicCI6ImdpdGh1YiIsInN0IjoiYzNSaGRHVXRabTl5TFhSbGMzUnoiLCJ2IjoiZG1WeWFXWnBaWEl0W… | → | error: github: the token endpoint refused the code (200 bad_verification_code): The code passed is incorrect or expired. |
| github the user declined | https://app.acme.example/auth/callback?error=access_denied&error_description=The+user+has+denied+your+application+access.&state=c3RhdGUtZm9yLXRlc3Rz, eyJ0Ijoic2lnbmluIiwicCI6Imdpd… | → | error: the user declined to sign in (access_denied) |
Show the other 5 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| oidc a callback whose state is not the cookie's is refused before any request | https://app.acme.example/auth/callback?state=forged&code=x, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLCJzdCI6ImMzUmhkR1V0Wm05eUxYUmxjM1J6IiwidiI6ImRtVnlhV1pwWlhJdFptOXlMV0V0ZEdWemRDMTBhR0Y… | → | error: the state in the callback does not match the sign-in cookie |
| github a sign-in cookie older than ten minutes | https://app.acme.example/auth/callback?code=ghcode123&state=c3RhdGUtZm9yLXRlc3Rz, eyJ0Ijoic2lnbmluIiwicCI6ImdpdGh1YiIsInN0IjoiYzNSaGRHVXRabTl5TFhSbGMzUnoiLCJ2IjoiZG1WeWFXWnBaWEl0W… | → | error: the sign-in cookie is missing, expired or not signed by SESSION_SECRET |
| oidc a sign-in cookie signed with another secret | https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLC… | → | error: the sign-in cookie is missing, expired or not signed by SESSION_SECRET |
| oidc a session cookie is not a sign-in cookie | https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIi… | → | error: the sign-in cookie is missing, expired or not signed by SESSION_SECRET |
| oidc a sign-in begun with another provider | https://app.acme.example/auth/callback?state=c3RhdGUtZm9yLXRlc3Rz&code=4%2F0AfJohXtestcode&scope=email+profile+openid&authuser=0&prompt=consent, eyJ0Ijoic2lnbmluIiwicCI6ImdpdGh1Yi… | → | error: this sign-in began with github, but AUTH_PROVIDER is oidc |
createSession 10 contract tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a 30-day session by default | provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace | → | eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.qvfebz… |
| an hour | provider github, subject 583231, email —, name The Octocat, 3,600 | → | eyJ0Ijoic2Vzc2lvbiIsInAiOiJnaXRodWIiLCJzIjoiNTgzMjMxIiwiZSI6bnVsbCwibiI6IlRoZSBPY3RvY2F0IiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3NjcyMjkyMDB9.KAKaMhIhDK4HNrIqoK4ep77xBJnxhBTXIVHg3Lxpiqk |
| no email or name | provider github, subject 1, email —, name —, 60 | → | eyJ0Ijoic2Vzc2lvbiIsInAiOiJnaXRodWIiLCJzIjoiMSIsImUiOm51bGwsIm4iOm51bGwsImlhdCI6MTc2NzIyNTYwMCwiZXhwIjoxNzY3MjI1NjYwfQ.VWB1PBfNPy0h4BysG59jAbCZepEOy6p9fTVKQscW2FE |
| issued at the clock's time | provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace, 86,400 | → | eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzgyODYzOTk5LCJleHAiOjE3ODI5NTAzOTl9.aU7PoQ… |
| a different secret signs differently | provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace | → | eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.zP8b0q… |
| no lifetime | provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace, 0 | → | error: maxAgeSeconds is a whole number of seconds above 0, not 0 |
| a fractional lifetime | provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace, 1.5 | → | error: maxAgeSeconds is a whole number of seconds above 0, not 1.5 |
| no subject | provider oidc, subject , email —, name — | → | error: a session needs the user's subject |
| no secret | provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace | → | error: SESSION_SECRET is not set |
| a short secret | provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace | → | error: SESSION_SECRET is 31 characters; it needs at least 32 |
readSession 10 contract tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a valid session | eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.qvfebz… | → | provider oidc, subject 110169484474386276334, email ada@example.com, name Ada Lovelace |
| a session one second before it expires | eyJ0Ijoic2Vzc2lvbiIsInAiOiJnaXRodWIiLCJzIjoiNTgzMjMxIiwiZSI6bnVsbCwibiI6IlRoZSBPY3RvY2F0IiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3NjcyMjkyMDB9.KAKaMhIhDK4HNrIqoK4ep77xBJnxhBTXIVHg3Lxpiqk | → | provider github, subject 583231, email —, name The Octocat |
| an expired session | eyJ0Ijoic2Vzc2lvbiIsInAiOiJnaXRodWIiLCJzIjoiNTgzMjMxIiwiZSI6bnVsbCwibiI6IlRoZSBPY3RvY2F0IiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3NjcyMjkyMDB9.KAKaMhIhDK4HNrIqoK4ep77xBJnxhBTXIVHg3Lxpiqk | → | — |
| no cookie | — | → | — |
| an empty cookie | → | — | |
| an edited payload (someone made themselves another user) | eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6ImFkbWluIiwiZSI6bnVsbCwibiI6bnVsbCwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3NjcyMjU2NjB9.qvfebzx5jhjLQTrp6bf69WQQGV8dXD6g_Z9yHGuYXig | → | — |
| signed with another secret | eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.zP8b0q… | → | — |
| a sign-in cookie is not a session | eyJ0Ijoic2lnbmluIiwicCI6Im9pZGMiLCJzdCI6ImMzUmhkR1V0Wm05eUxYUmxjM1J6IiwidiI6ImRtVnlhV1pwWlhJdFptOXlMV0V0ZEdWemRDMTBhR0YwTFdsekxXeHZibWN0Wlc1dmRXZG8iLCJuIjoiYm05dVkyVXRabTl5TFhSbGM… | → | — |
| not a sealed value at all | hello; world | → | — |
| no secret is an error, not a signed-out user | eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.qvfebz… | → | error: SESSION_SECRET is not set |
sessionCookie 8 contract tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a 30-day cookie by default | eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MTc2MDB9.qvfebz… | → | fune_session=eyJ0Ijoic2Vzc2lvbiIsInAiOiJvaWRjIiwicyI6IjExMDE2OTQ4NDQ3NDM4NjI3NjMzNCIsImUiOiJhZGFAZXhhbXBsZS5jb20iLCJuIjoiQWRhIExvdmVsYWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3Njk4MT… |
| an hour | abc.def, 3,600 | → | fune_session=abc.def; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600 |
| signing out | , 0 | → | fune_session=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0 |
| zero seconds with a value expires it at once | abc.def, 0 | → | fune_session=abc.def; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0 |
| a value that would inject an attribute | abc; Domain=evil.example | → | error: a session cookie value is what createSession returned |
| a negative lifetime | abc.def, -1 | → | error: maxAgeSeconds is a whole number of seconds, 0 or more, not -1 |
| a fractional lifetime | abc.def, 2.5 | → | error: maxAgeSeconds is a whole number of seconds, 0 or more, not 2.5 |
| an empty value that would last | , 60 | → | error: an empty session cookie only signs out: give maxAgeSeconds 0 |
Verification
Verified by the operator, not the sandbox 54 test vectors declared; none run by the registry.
Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.
Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON
More from the author
- **oidc** finds the issuer's endpoints by discovery (`OIDC_ISSUER/.well-known/openid-configuration`), checks the document is for that issuer, and asks for `OIDC_SCOPES` (`openid email profile` unless you say). A confidential client sends `OIDC_CLIENT_SECRET` (client_secret_post); a public client leaves it unset and relies on PKCE. The user comes from the id_token's claims: its issuer, audience, nonce and expiry are checked. Its signature is not, because it came straight from the token endpoint over TLS (OpenID Connect Core 1.0, section 3.1.3.7); never pass this function an id_token you received any other way. - **github** uses a GitHub OAuth app (`GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`) with PKCE, then reads `/user` and the primary verified address from `/user/emails`. GitHub reports a bad code with status 200 and an `error` field; that is thrown like any other refusal.
## Wiring it up
// app/login/route.ts (Next.js)
import { beginSignIn } from "#fune/auth.oauth-sign-in@^1";
export async function GET() {
const start = await beginSignIn("https://app.example.com/callback", "/dashboard");
return new Response(null, { status: 302, headers: { location: start.url, "set-cookie": start.setCookie } });
}
// app/callback/route.ts
import { completeSignIn, createSession, sessionCookie } from "#fune/auth.oauth-sign-in@^1";
import { cookies } from "next/headers";
export async function GET(request: Request) {
const signIn = (await cookies()).get("fune_signin")?.value ?? "";
const user = await completeSignIn(request.url, signIn);
// find or create the account by (user.provider, user.subject) here
const headers = new Headers({ location: user.returnTo ?? "/" });
headers.append("set-cookie", sessionCookie(createSession(user)));
headers.append("set-cookie", "fune_signin=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0");
return new Response(null, { status: 302, headers });
}
// anywhere: who is this?
const me = readSession((await cookies()).get("fune_session")?.value ?? null);In Express it is the same three calls: `res.cookie`/`res.append('Set-Cookie', ...)` for the headers, `req.protocol + '://' + req.get('host') + req.originalUrl` for the callback URL. Signing out is `sessionCookie("", 0)`.
## What it checks, and what it leaves to you
- The sign-in cookie holds the state, the PKCE verifier, the nonce, the callback URL and `returnTo`, signed and valid for ten minutes. The callback must carry the same state, and must come back to the provider that began it. `returnTo` must be a path on your site, so it cannot become an open redirect. - A session is the user's provider, subject, email and name, signed, with an expiry. It is readable by whoever holds it, so put nothing secret in it. It cannot be revoked one at a time: rotating `SESSION_SECRET` signs everyone out. If you need per-session revocation, store a session id in your database and keep it in the session's subject lookup. - Key accounts on `provider` and `subject`, never on the email: emails change, and an unverified one (`emailVerified: false`) proves nothing. - It does not fetch userinfo, refresh tokens, or call the provider's APIs on the user's behalf, and it does not do CSRF protection for your own forms (SameSite=Lax on the session cookie helps; it is not a token).
## Where the contract tests come from
The exchanges follow the providers' documentation: Google's published discovery document and token response, Keycloak's endpoint layout, GitHub's OAuth app flow (including its `bad_verification_code` error body) and its `/user` and `/user/emails` shapes. Every client id and secret in them is a fake. The PKCE challenges and the cookie signatures in the expected results were computed independently with Node's crypto module. Before going live, sign in once against the real provider from a staging deployment.