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
6 changes: 6 additions & 0 deletions .changeset/mobile-social-signin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@glinr/theauth": minor
"@glinr/theauth-expo": minor
---

Native app social sign-in. The oauth plugin takes `mobile: { redirectUris }` and adds a PKCE code exchange at `POST /auth/oauth/mobile/exchange`, so a session token is never placed in a redirect URL. `@glinr/theauth-expo` gains `signInWithProvider` and `useSocialSignIn`, `createSecureStoreStorage`, and an `appState` option that refreshes the session when the app returns to the foreground. The oauth plugin now also creates the `theauth_one_time_tokens` table.
19 changes: 19 additions & 0 deletions docs/auth/oauth.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,22 @@ oauth({
Turn theAuth itself into an OpenID Connect identity provider.
</Card>
</CardGroup>

## Native app sign-in

Set `mobile.redirectUris` to let a native app finish the flow in the system browser (RFC 8252 with PKCE):

```typescript
oauth({
providers: { github: github({ clientId, clientSecret }) },
mobile: { redirectUris: ['myapp://auth/callback'] },
})
```

| Step | Request |
|---|---|
| 1 | App opens `GET /auth/oauth/authorize/:provider?mobile_redirect=<uri>&code_challenge=<S256>&code_challenge_method=S256` in the browser |
| 2 | After the provider callback, the browser is redirected to `<uri>?code=<one-time code>` (60 seconds, single use) |
| 3 | App calls `POST /auth/oauth/mobile/exchange` with `{ code, code_verifier }` and receives `{ data: { token, user, expiresAt } }` |

`mobile_redirect` must match an entry in `redirectUris` exactly, and the challenge is required. A wrong verifier burns the code. Failures are returned to the app as `?error=`, and a required second factor arrives as the usual `#gate=...` fragment on the app URI. The code is stored in `theauth_one_time_tokens`, which `createTheAuth` now creates whenever the oauth plugin is registered. The [Expo guide](/expo#social-sign-in) shows the client side.
73 changes: 56 additions & 17 deletions docs/expo.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -80,36 +80,73 @@ export function LoginScreen() {

## Secure token storage

For production apps, use `expo-secure-store` to encrypt the session token at rest:
For production apps, use `expo-secure-store` to keep the session token in the Keychain (iOS) or Keystore (Android):

```tsx
import * as SecureStore from 'expo-secure-store';
import { TheAuthExpoProvider } from '@glinr/theauth-expo';

const secureStorage = {
getItem: (key: string) => SecureStore.getItemAsync(key),
setItem: (key: string, value: string) => SecureStore.setItemAsync(key, value),
removeItem: (key: string) => SecureStore.deleteItemAsync(key),
};
import { TheAuthExpoProvider, createSecureStoreStorage } from '@glinr/theauth-expo';

<TheAuthExpoProvider config={{ basePath: '...', storage: secureStorage }}>
<TheAuthExpoProvider
config={{ basePath: 'https://api.myapp.com/api/theauth', storage: createSecureStoreStorage(SecureStore) }}
>
{children}
</TheAuthExpoProvider>
```

## OAuth (deep link redirect)
## Social sign-in

For OAuth flows in Expo, use the `oauth-proxy` plugin on your server alongside `Linking.openURL` on the client:
The app opens the provider in the system browser, and the server sends the browser back to your app with a single-use code. The app trades that code, together with a PKCE verifier that never left the device, for a session. The session token is never placed in a URL.

<Steps>
<Step title="Allow your app's redirect URI on the server">
```typescript
oauth({
providers: { github: github({ clientId, clientSecret }) },
mobile: { redirectUris: ['myapp://auth/callback'] },
})
```
Matching is exact. Without `mobile`, the mobile flow is off.
</Step>
<Step title="Configure the provider in the app">
```tsx
import { Linking } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import * as Crypto from 'expo-crypto';
import * as Linking from 'expo-linking';
import { AppState } from 'react-native';

const config = {
basePath: 'https://api.myapp.com/api/theauth',
storage: createSecureStoreStorage(SecureStore),
appState: AppState,
social: {
redirectUri: Linking.createURL('auth/callback'),
openAuthSession: (url, redirectUri) => WebBrowser.openAuthSessionAsync(url, redirectUri),
randomBytes: (n) => Crypto.getRandomBytesAsync(n),
sha256: async (input) =>
new Uint8Array(
await Crypto.digest(Crypto.CryptoDigestAlgorithm.SHA256, new TextEncoder().encode(input)),
),
},
};
```
</Step>
<Step title="Call the hook">
```tsx
import { useSocialSignIn } from '@glinr/theauth-expo';

async function signInWithGitHub() {
const authUrl = 'https://api.myapp.com/api/theauth/auth/oauth/github/authorize';
await Linking.openURL(authUrl);
// Handle the redirect via Linking.addEventListener or expo-linking
}
const { signInWithProvider, isLoading, error } = useSocialSignIn();
<Button title="Continue with GitHub" onPress={() => signInWithProvider('github')} />
```
</Step>
</Steps>

If the user has a required second factor, `signInWithProvider` returns a failure whose message names the gate (`two_factor_required`). Complete the factor, then sign in again.

The mount path in `basePath` must expose the OAuth plugin routes `/auth/oauth/authorize/:provider` and `/auth/oauth/mobile/exchange`. The OAuth provider's own redirect URI stays your server callback, not the app link.

### Refresh on foreground

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.

## Hooks reference

Expand Down Expand Up @@ -160,6 +197,8 @@ Manages agent identity records for the current user. Requires the full base URL
|---|---|---|
| `basePath` | `string` | Full URL to your theAuth mount point |
| `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 |

<Warning>
The default in-memory storage loses the session when the app restarts. Always pass a real storage adapter in production.
Expand Down
122 changes: 122 additions & 0 deletions packages/core/src/auth/oauth/mobile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/**
* Native app sign-in for the OAuth plugin (RFC 8252 with PKCE).
*
* The app opens the authorize route in the system browser with its own
* redirect URI and a PKCE challenge. The provider callback finishes in that
* browser, then redirects to the app with a short-lived single-use code. The
* session token never appears in a URL: the app trades the code, plus the
* PKCE verifier that never left the device, for the session at the exchange
* route.
*/

import { verifyS256 } from "../../mcp/utils.js";
import type { OneTimeTokenModule } from "../one-time-token.js";

export interface MobileOAuthConfig {
/**
* App redirect URIs the browser may be sent back to, matched exactly:
* a custom scheme (`myapp://auth/callback`) or an https app link. Without
* this the mobile flow is off.
*/
redirectUris: string[];
/** Seconds the exchange code stays valid. Default 60. */
codeTtlSeconds?: number;
}

export const MOBILE_COOKIE = "theauth_mobile_oauth";

const PENDING = "mobile-oauth:pending";
const EXCHANGE = "mobile-oauth:exchange";
const PENDING_TTL_SECONDS = 600;
const CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/;
const VERIFIER_RE = /^[A-Za-z0-9._~-]{43,128}$/;

export interface MobileFlow {
redirectUri: string;
challenge: string;
}

export interface MobileOAuth {
/** Validate the authorize parameters. Returns an error message when invalid. */
parseStart(params: URLSearchParams): { flow: MobileFlow } | { error: string } | null;
/** Remember the flow for the browser and return the cookie value to set. */
begin(flow: MobileFlow): Promise<string>;
/** Consume the cookie value at callback time. */
resume(cookieValue: string | null): Promise<MobileFlow | null>;
/** Mint the single-use code handed to the app. */
issueCode(flow: MobileFlow, userId: string): Promise<string>;
/** Redeem a code with the PKCE verifier. Returns the user id, or null. */
redeem(code: string, verifier: string): Promise<string | null>;
/** `redirectUri` with the given parameters appended to its query. */
redirectWith(redirectUri: string, params: Record<string, string>): string;
}

export function createMobileOAuth(
config: MobileOAuthConfig,
tokens: OneTimeTokenModule,
): MobileOAuth {
const allowed = new Set(config.redirectUris);
const codeTtl = config.codeTtlSeconds ?? 60;

return {
parseStart(params) {
const redirectUri = params.get("mobile_redirect");
if (redirectUri === null) return null;
if (!allowed.has(redirectUri)) return { error: "mobile_redirect is not allowed" };
const challenge = params.get("code_challenge") ?? "";
if (params.get("code_challenge_method") !== "S256" || !CHALLENGE_RE.test(challenge)) {
return { error: "code_challenge with code_challenge_method=S256 is required" };
}
return { flow: { redirectUri, challenge } };
},

async begin(flow) {
const made = await tokens.createToken({
purpose: "custom",
identifier: PENDING,
metadata: { ...flow },
ttlSeconds: PENDING_TTL_SECONDS,
});
if (!made.success) throw new Error("Could not start the mobile sign-in");
return made.data.token;
},

async resume(cookieValue) {
if (!cookieValue) return null;
const used = await tokens.validateToken(cookieValue, "custom");
if (!used.success || used.data.identifier !== PENDING) return null;
const { redirectUri, challenge } = used.data.metadata ?? {};
if (typeof redirectUri !== "string" || typeof challenge !== "string") return null;
// Re-check in case the allowlist changed while the flow was in flight.
return allowed.has(redirectUri) ? { redirectUri, challenge } : null;
},

async issueCode(flow, userId) {
const made = await tokens.createToken({
purpose: "custom",
identifier: EXCHANGE,
metadata: { userId, challenge: flow.challenge },
ttlSeconds: codeTtl,
});
if (!made.success) throw new Error("Could not issue the mobile sign-in code");
return made.data.token;
},

async redeem(code, verifier) {
if (!VERIFIER_RE.test(verifier)) return null;
// The code is consumed even when the verifier is wrong, so a stolen
// code cannot be retried with guesses.
const used = await tokens.validateToken(code, "custom");
if (!used.success || used.data.identifier !== EXCHANGE) return null;
const { userId, challenge } = used.data.metadata ?? {};
if (typeof userId !== "string" || typeof challenge !== "string") return null;
return (await verifyS256(verifier, challenge)) ? userId : null;
},

redirectWith(redirectUri, params) {
const url = new URL(redirectUri);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
return url.toString();
},
};
}
Loading
Loading