Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/expo-passkeys-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@glinr/theauth-expo": minor
---

Passkeys for the Expo client. `signInWithPasskey`, `registerPasskey` and the `usePasskeys` hook take a platform authenticator (`react-native-passkey` works as is) through `config.passkeys`. A new `config.fetch` routes every request through your own fetch, for DPoP proofs or certificate pinning.
5 changes: 5 additions & 0 deletions .changeset/stateless-legacy-cookies-off.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@glinr/theauth": minor
---

`createStatelessSessions` now refuses token cookies written before the identity binding by default (`acceptLegacyTokenCookies` was `true`). Set it to `true` for one cookie lifetime when upgrading with live sessions; otherwise affected users sign in again once.
32 changes: 32 additions & 0 deletions docs/expo.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,36 @@ The mount path in `basePath` must expose the OAuth plugin routes `/auth/oauth/au

Pass React Native's `AppState` as `appState` and the session is re-checked every time the app comes back to the foreground, so a session revoked elsewhere signs the user out.

## Passkeys

Pass a platform authenticator and the provider can sign users in with a passkey and add one to a signed-in account. The server's passkey routes already return WebAuthn JSON options and a session token, so [`react-native-passkey`](https://github.com/f-23/react-native-passkey) works as is:

```tsx
import { Passkey } from 'react-native-passkey';
import { usePasskeys } from '@glinr/theauth-expo';

const config = { basePath: '...', passkeys: Passkey };

const { signInWithPasskey, registerPasskey, isLoading, error } = usePasskeys();
<Button title="Sign in with a passkey" onPress={() => signInWithPasskey()} />
<Button title="Add a passkey" onPress={() => registerPasskey('My phone')} />
```

`registerPasskey` needs a session, so call it after another sign-in method. Your app's associated domains (iOS) and Digital Asset Links (Android) must list the relying party ID the server uses. A required second factor comes back as a failure naming the gate, the same as social sign-in.

## Custom fetch (DPoP, pinning)

Every request the provider makes goes through `config.fetch` when set. Pass a DPoP client's `fetch` from `@glinr/theauth-client` to attach proofs, or your own pinned-certificate implementation:

```tsx
import { createDPoPClient } from '@glinr/theauth-client';

const dpop = createDPoPClient({ keyPair }); // needs a WebCrypto implementation
const config = { basePath: '...', fetch: dpop.fetch };
```

React Native has no `crypto.subtle` by default, so supply one (for example `react-native-quick-crypto`) and generate the key pair with it. Session tokens are plain bearer tokens on the server today, so proofs are useful for OAuth and MCP access tokens you also send through this fetch.

## Hooks reference

### `useSession`
Expand Down Expand Up @@ -199,6 +229,8 @@ Manages agent identity records for the current user. Requires the full base URL
| `storage` | `AuthStorage?` | Token persistence adapter. Defaults to in-memory |
| `social` | `SocialSignInConfig?` | Enables `signInWithProvider`. See Social sign-in |
| `appState` | `AppStateLike?` | React Native `AppState`. Refreshes the session on foreground |
| `passkeys` | `PasskeyAuthenticator?` | Enables `signInWithPasskey` and `registerPasskey` |
| `fetch` | `typeof fetch?` | Used for every request, for DPoP or certificate pinning |

<Warning>
The default in-memory storage loses the session when the app restarts. Always pass a real storage adapter in production.
Expand Down
4 changes: 4 additions & 0 deletions docs/session-hardening.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@ createTheAuth({ baseUrl: "https://app.example.com", allowedHosts: ["app.example.
## Stateless sessions and federated logout

`createStatelessSessions` keeps an IdP identity in signed cookies and the IdP tokens in an encrypted cookie, with no database. Sessions cannot be revoked server side, so pair it with `isRevoked` and `createBackChannelLogoutReceiver`, which verifies OIDC logout tokens (issuer, audience, `jti` replay) and calls your `onLogout`. `createEndSessionHandler` and `buildEndSessionUrl` cover RP-initiated logout.

### Token cookie binding

The encrypted token cookie is bound to the identity cookie, so one user's token cookie cannot be swapped into another user's session. Cookies written before the binding existed (no `v2:` prefix) are refused by default. If you upgrade with live sessions and want to keep them, set `acceptLegacyTokenCookies: true` for one cookie lifetime (`maxAge`). Legacy cookies are re-sealed in the bound format as they are read, and `onDeprecation` reports each one. Users whose cookie is refused sign in again once.
13 changes: 7 additions & 6 deletions packages/core/src/session/stateless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,11 @@ export interface StatelessSessionsConfig {
/** Optional revocation check, e.g. a denylist keyed by `sub` or `sid`. */
isRevoked?: (identity: StatelessIdentity) => Promise<boolean>;
/**
* Read token cookies written before the AAD binding existed (default: true,
* for one release). A legacy cookie is not bound to the identity cookie, so
* a token cookie from another user sealed under the same secret would be
* accepted. Set to false once old cookies have aged out (`maxAge`).
* Read token cookies written before the AAD binding existed (default: false).
* A legacy cookie is not bound to the identity cookie, so a token cookie from
* another user sealed under the same secret would be accepted. Turn this on
* only while old cookies age out (`maxAge`); affected users otherwise sign in
* again once.
*/
acceptLegacyTokenCookies?: boolean;
/**
Expand Down Expand Up @@ -226,7 +227,7 @@ export function createStatelessSessions(config: StatelessSessionsConfig): Statel
): Promise<{ value: T; legacy: boolean } | null> {
if (!value) return null;
const legacy = !value.startsWith(TOKEN_FORMAT_V2);
if (legacy && config.acceptLegacyTokenCookies === false) return null;
if (legacy && config.acceptLegacyTokenCookies !== true) return null;
const parts = (legacy ? value : value.slice(TOKEN_FORMAT_V2.length)).split(".");
if (parts.length !== 2) return null;
try {
Expand Down Expand Up @@ -334,7 +335,7 @@ export function createStatelessSessions(config: StatelessSessionsConfig): Statel
let upgrade: string[] = [];
if (opened.legacy) {
config.onDeprecation?.(
"StatelessSessions: read a legacy token cookie that is not bound to the identity cookie. It was re-sealed in the bound format; set acceptLegacyTokenCookies: false once old cookies have expired.",
"StatelessSessions: read a legacy token cookie that is not bound to the identity cookie. It was re-sealed in the bound format; remove acceptLegacyTokenCookies once old cookies have expired.",
);
const remainingLegacy = Math.max(Math.floor((session.expiresAt - Date.now()) / 1000), 1);
const rewritten = serializeChunkedCookie(
Expand Down
12 changes: 8 additions & 4 deletions packages/core/tests/session-stateless-binding.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,13 @@ describe("legacy token cookies", () => {
return jar;
}

it("are read, upgraded to v2 and reported once per read", async () => {
it("are read, upgraded to v2 and reported once per read when opted in", async () => {
const onDeprecation = vi.fn();
const s = createStatelessSessions({ secret: SECRET, onDeprecation });
const s = createStatelessSessions({
secret: SECRET,
onDeprecation,
acceptLegacyTokenCookies: true,
});
const r = await s.getAccessToken(toHeader(await legacyJar()));
expect(r.success).toBe(true);
if (!r.success) return;
Expand All @@ -108,8 +112,8 @@ describe("legacy token cookies", () => {
expect(decodeURIComponent(upgraded ?? "").startsWith("v2:")).toBe(true);
});

it("are refused when acceptLegacyTokenCookies is false", async () => {
const s = createStatelessSessions({ secret: SECRET, acceptLegacyTokenCookies: false });
it("are refused by default", async () => {
const s = createStatelessSessions({ secret: SECRET });
const r = await s.getAccessToken(toHeader(await legacyJar()));
expect(r.success).toBe(false);
if (!r.success) expect(r.error.code).toBe("NO_TOKENS");
Expand Down
32 changes: 32 additions & 0 deletions packages/expo/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,38 @@ export function useSocialSignIn() {
return { signInWithProvider: execute, isLoading, error };
}

// usePasskeys

/**
* Passkey sign-in and registration with local loading and error state.
* Needs `passkeys` in the provider config.
*/
export function usePasskeys() {
const { signInWithPasskey, registerPasskey } = useRequiredContext("usePasskeys");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

const run = useCallback(async (action: () => Promise<ActionResult>): Promise<ActionResult> => {
setIsLoading(true);
setError(null);
const result = await action();
if (!result.success) setError(result.error);
setIsLoading(false);
return result;
}, []);

const signIn = useCallback(
(userId?: string) => run(() => signInWithPasskey(userId)),
[run, signInWithPasskey],
);
const register = useCallback(
(deviceName?: string) => run(() => registerPasskey(deviceName)),
[run, registerPasskey],
);

return { signInWithPasskey: signIn, registerPasskey: register, isLoading, error };
}

// useSignUp

/**
Expand Down
3 changes: 3 additions & 0 deletions packages/expo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
// Hooks
export {
useAgents,
usePasskeys,
useSession,
useSignIn,
useSignOut,
useSignUp,
useSocialSignIn,
useUser,
} from "./hooks.js";
export { runPasskeyRegistration, runPasskeySignIn } from "./passkey.js";
export type {
AuthExpoProviderProps,
TheAuthExpoProviderProps,
Expand Down Expand Up @@ -38,6 +40,7 @@ export type {
AuthStorage,
AuthUser,
CreateAgentInput,
PasskeyAuthenticator,
SocialSignInConfig,
TheAuthAgent,
TheAuthContextValue,
Expand Down
137 changes: 137 additions & 0 deletions packages/expo/src/passkey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import type { ActionResult, PasskeyAuthenticator, TheAuthSession } from "./types.js";

type FetchFn = typeof fetch;

interface ErrorBody {
error?: string | { message?: string; code?: string };
challenge?: string;
gate?: string;
}

function messageOf(body: ErrorBody | null, fallback: string): string {
const err = body?.error;
if (typeof err === "string") return err;
return err?.message ?? fallback;
}

async function readJson<T>(res: Response): Promise<T | null> {
try {
return (await res.json()) as T;
} catch {
return null;
}
}

/**
* Sign in with a passkey: fetch the challenge, let the platform authenticator
* sign it, and trade the assertion for a session.
*/
export async function runPasskeySignIn(
base: string,
authenticator: PasskeyAuthenticator,
fetchFn: FetchFn,
userId?: string,
): Promise<ActionResult<TheAuthSession>> {
try {
const optionsRes = await fetchFn(`${base}/auth/passkey/authenticate/options`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(userId ? { userId } : {}),
});
const options = await readJson<Record<string, unknown> & ErrorBody>(optionsRes);
if (!optionsRes.ok || !options) {
return { success: false, error: messageOf(options, "Could not start passkey sign-in") };
}

let assertion: Record<string, unknown>;
try {
assertion = await authenticator.get(options);
} catch (err) {
return {
success: false,
error: err instanceof Error ? err.message : "Passkey sign-in was cancelled",
};
}

const verifyRes = await fetchFn(`${base}/auth/passkey/authenticate/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ response: assertion }),
});
const body = await readJson<
{
user?: { id: string };
session?: { token: string; expiresAt?: string };
} & ErrorBody
>(verifyRes);
if (!verifyRes.ok || !body?.session || !body.user) {
const gated = body?.gate ?? (body?.challenge ? "verification" : null);
if (gated) return { success: false, error: `Additional verification required (${gated})` };
return {
success: false,
error: messageOf(body, `Passkey sign-in failed (${verifyRes.status})`),
};
}
return {
success: true,
data: {
token: body.session.token,
user: { id: body.user.id },
expiresAt: body.session.expiresAt,
},
};
} catch (err) {
return { success: false, error: err instanceof Error ? err.message : "Network error" };
}
}

/** Add a passkey to the signed-in user. */
export async function runPasskeyRegistration(
base: string,
authenticator: PasskeyAuthenticator,
fetchFn: FetchFn,
sessionToken: string,
deviceName?: string,
): Promise<ActionResult> {
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${sessionToken}`,
};
try {
const optionsRes = await fetchFn(`${base}/auth/passkey/register/options`, {
method: "POST",
headers,
body: "{}",
});
const options = await readJson<Record<string, unknown> & ErrorBody>(optionsRes);
if (!optionsRes.ok || !options) {
return { success: false, error: messageOf(options, "Could not start passkey setup") };
}

let attestation: Record<string, unknown>;
try {
attestation = await authenticator.create(options);
} catch (err) {
return {
success: false,
error: err instanceof Error ? err.message : "Passkey setup was cancelled",
};
}

const verifyRes = await fetchFn(`${base}/auth/passkey/register/verify`, {
method: "POST",
headers,
body: JSON.stringify({ response: { ...attestation, ...(deviceName ? { deviceName } : {}) } }),
});
if (!verifyRes.ok) {
const body = await readJson<ErrorBody>(verifyRes);
return {
success: false,
error: messageOf(body, `Passkey setup failed (${verifyRes.status})`),
};
}
return { success: true, data: undefined };
} catch (err) {
return { success: false, error: err instanceof Error ? err.message : "Network error" };
}
}
Loading
Loading