Authentication Architecture
Complete authentication system using Ory Stack
Overview
Synap uses the Ory Stack for authentication:
- Ory Kratos: Identity management (users, sessions)
- Ory Hydra: OAuth2 server (API access, token exchange)
Architecture
User Authentication (Kratos)
Flow
- User logs in via Kratos UI
- Kratos creates session
- Client stores session cookie
- API validates session with Kratos
Implementation
// packages/auth/src/ory-kratos.ts
import { kratosPublic } from './ory-kratos.js';
export async function getSession(headers: Headers): Promise<Session | null> {
const cookie = headers.get('cookie');
if (!cookie) return null;
const { data } = await kratosPublic.toSession({
cookie,
});
return data;
}
API Key Authentication
For Programmatic Access
// Create API key
POST /trpc/apiKeys.create
{
"name": "My API Key",
"scopes": ["read:notes", "write:notes"]
}
// Use API key
GET /trpc/notes.list
Authorization: Bearer synap_xxx...
OAuth2 (Hydra)
Client Credentials Flow
For service-to-service authentication:
// External service requests token
POST /oauth2/token
{
"grant_type": "client_credentials",
"client_id": "service-id",
"client_secret": "service-secret"
}
// Use token
GET /trpc/notes.list
Authorization: Bearer oauth2-token
Token Exchange (RFC 8693)
For interoperability with other auth systems:
POST /auth/token-exchange
{
"subject_token": "external-token",
"subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
"audience": "synap-api"
}
Best Practices
- Use HTTPS - Always in production
- Secure cookies - HttpOnly, Secure, SameSite
- Token expiration - Short-lived tokens
- Rate limiting - Prevent brute force
- Audit logging - Log all auth events
Next: See Data Confidentiality for privacy details.