Skip to content
Open
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
17 changes: 17 additions & 0 deletions functions/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ export interface AuthContext {
scopes: string[];
}

const OAUTH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // 90 days

function timestampToMillis(value: unknown): number | undefined {
if (typeof (value as { toMillis?: unknown } | undefined)?.toMillis === 'function') {
return (value as { toMillis: () => number }).toMillis();
}
return undefined;
}

/**
* Resolves the authenticated user and their scopes from the request.
*
Expand Down Expand Up @@ -48,6 +57,14 @@ export async function resolveUser(req: Request): Promise<AuthContext> {
const oauthDoc = await admin.firestore().doc(`oauthTokens/${token}`).get();
if (oauthDoc.exists) {
const data = oauthDoc.data()!;
const createdAtMs = timestampToMillis(data.createdAt);
const expiresAtMs = timestampToMillis(data.expiresAt)
?? (createdAtMs !== undefined ? createdAtMs + OAUTH_TOKEN_TTL_MS : undefined);
if (expiresAtMs !== undefined && Date.now() >= expiresAtMs) {
await oauthDoc.ref.delete();
throw new Error('Invalid credentials');
}

let scopes = (data.scope as string || 'profile:read workout:read').split(' ');

// If Claude requested the generic 'claudeai' scope, grant full workout access
Expand Down
46 changes: 45 additions & 1 deletion functions/src/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,26 @@ const FIREBASE_CONFIG = {
};

const CODE_TTL_MS = 5 * 60 * 1000; // 5 minutes
const TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // 90 days

function isRedirectUriAllowed(clientData: Record<string, unknown>, redirectUri: string): boolean {
const redirectUris = clientData.redirectUris;
return Array.isArray(redirectUris) && redirectUris.includes(redirectUri);
}

function isTimingSafeMatch(storedSecret: unknown, providedSecret: unknown): boolean {
if (typeof storedSecret !== 'string' || typeof providedSecret !== 'string') {
return false;
}

const storedBuffer = Buffer.from(storedSecret);
const providedBuffer = Buffer.from(providedSecret);
if (storedBuffer.length !== providedBuffer.length) {
return false;
}

return crypto.timingSafeEqual(storedBuffer, providedBuffer);
}

function loginPage(clientId: string, redirectUri: string, state: string, scope: string): string {
const apiKey = FIREBASE_API_KEY.value();
Expand Down Expand Up @@ -146,6 +166,11 @@ export async function handleOAuthRequest(req: any, res: any) {
res.status(400).json({ error: 'Invalid client_id' });
return;
}
const clientData = clientDoc.data() as Record<string, unknown>;
if (!isRedirectUriAllowed(clientData, redirect_uri)) {
res.status(400).json({ error: 'Invalid redirect_uri' });
return;
}

const params = new URLSearchParams({
client_id,
Expand All @@ -166,6 +191,17 @@ export async function handleOAuthRequest(req: any, res: any) {
return;
}

const clientDoc = await admin.firestore().doc(`oauthClients/${client_id}`).get();
if (!clientDoc.exists) {
res.status(400).json({ error: 'Invalid client_id' });
return;
}
const clientData = clientDoc.data() as Record<string, unknown>;
if (!isRedirectUriAllowed(clientData, redirect_uri)) {
res.status(400).json({ error: 'Invalid redirect_uri' });
return;
}

const html = loginPage(client_id, redirect_uri, state, scope || '');
res.status(200).send(html);
return;
Expand All @@ -185,6 +221,11 @@ export async function handleOAuthRequest(req: any, res: any) {
res.status(400).json({ error: 'Invalid client_id' });
return;
}
const clientData = clientDoc.data() as Record<string, unknown>;
if (!isRedirectUriAllowed(clientData, redirectUri)) {
res.status(400).json({ error: 'Invalid redirect_uri' });
return;
}

// Verify Firebase ID token
let userId: string;
Expand Down Expand Up @@ -229,7 +270,8 @@ export async function handleOAuthRequest(req: any, res: any) {

// Validate client credentials
const clientDoc = await admin.firestore().doc(`oauthClients/${client_id}`).get();
if (!clientDoc.exists || clientDoc.data()!.secret !== client_secret) {
const clientData = clientDoc.data() as Record<string, unknown> | undefined;
if (!clientDoc.exists || !clientData || !isTimingSafeMatch(clientData.secret, client_secret)) {
res.status(401).json({ error: 'invalid_client' });
return;
}
Expand Down Expand Up @@ -268,6 +310,7 @@ export async function handleOAuthRequest(req: any, res: any) {
clientId: client_id,
scope: codeData.scope, // Inherit scope from authorization code
createdAt: admin.firestore.FieldValue.serverTimestamp(),
expiresAt: admin.firestore.Timestamp.fromMillis(Date.now() + TOKEN_TTL_MS),
});

// Delete used code
Expand All @@ -276,6 +319,7 @@ export async function handleOAuthRequest(req: any, res: any) {
res.status(200).json({
access_token: accessToken,
token_type: 'Bearer',
expires_in: Math.floor(TOKEN_TTL_MS / 1000),
scope: codeData.scope,
});
return;
Expand Down