trails/apps/journal/app/routes/oauth.token.ts
Ullrich Schäfer 1ae406a8aa
Implement OAuth2 PKCE auth, discovery, and mobile API client
Journal server (Phase 1.4 + 1.5):
- Add oauth_clients, oauth_codes, oauth_tokens tables to journal schema
- Implement GET /oauth/authorize with PKCE flow and login redirect
- Implement POST /oauth/token (authorization_code + refresh_token grants)
- Add validateBearerToken() + getAuthenticatedUser() middleware
- Seed trails-cool-mobile as trusted OAuth client on server startup
- Add GET /.well-known/trails-cool discovery endpoint
- Add returnTo support to login page and magic link verify
- Add @trails-cool/api workspace dependency to journal

Mobile app (Phase 1.5 + 1.6):
- Login screen with server URL input and discovery validation
- OAuth2 PKCE login via expo-web-browser with expo-crypto for Hermes
- Token storage in expo-secure-store with auto-refresh on 401
- API client with bearer token injection and typed errors
- Server URL persistence with localhost default in dev mode
- API version compatibility check on app foreground
- Log out + switch server on Profile tab
- iOS ATS exception for local networking

Tests:
- PKCE crypto verification, OAuthError, token generation
- Discovery endpoint response shape
- API version semver compatibility
- API client error types

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 00:41:40 +02:00

70 lines
2.1 KiB
TypeScript

import type { Route } from "./+types/oauth.token";
import {
exchangeCodeForTokens,
refreshAccessToken,
OAuthError,
} from "../lib/oauth.server.ts";
/**
* POST /oauth/token
*
* OAuth2 token endpoint. Supports two grant types:
* - authorization_code: Exchange code + PKCE verifier for tokens
* - refresh_token: Exchange refresh token for new token pair
*/
export async function action({ request }: Route.ActionArgs) {
if (request.method !== "POST") {
return new Response(null, { status: 405 });
}
const body = await request.formData();
const grantType = body.get("grant_type") as string | null;
try {
if (grantType === "authorization_code") {
const code = body.get("code") as string | null;
const clientId = body.get("client_id") as string | null;
const redirectUri = body.get("redirect_uri") as string | null;
const codeVerifier = body.get("code_verifier") as string | null;
if (!code || !clientId || !redirectUri || !codeVerifier) {
return oauthErrorResponse("invalid_request", "Missing required parameters");
}
const tokens = await exchangeCodeForTokens({
code,
clientId,
redirectUri,
codeVerifier,
});
return Response.json(tokens);
}
if (grantType === "refresh_token") {
const refreshToken = body.get("refresh_token") as string | null;
const clientId = body.get("client_id") as string | null;
if (!refreshToken || !clientId) {
return oauthErrorResponse("invalid_request", "Missing required parameters");
}
const tokens = await refreshAccessToken({ refreshToken, clientId });
return Response.json(tokens);
}
return oauthErrorResponse("unsupported_grant_type", `Unsupported grant type: ${grantType}`);
} catch (err) {
if (err instanceof OAuthError) {
return oauthErrorResponse(err.code, err.message);
}
throw err;
}
}
function oauthErrorResponse(error: string, description: string) {
return Response.json(
{ error, error_description: description },
{ status: 400 },
);
}