-
Notifications
You must be signed in to change notification settings - Fork 6
feat(developer-api): Add API key creation flow with OAuth billing provider auth #124
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
d7c5446
feat(developer-api): add projects and billing-providers endpoints
eliteprox 9a6ad79
feat(developer-api): add request ID handling and project sorting logic
eliteprox a6ec52b
refactor(developer-api): remove billing providers endpoint and relate…
eliteprox 8e48072
feat(developer-api): implement billing provider authentication flow
eliteprox b269e22
fix(prisma.schema): revert changes to binaryTargets
eliteprox 8b7b530
feat(developer-api): refactor project ID resolution logic
eliteprox 73d0b3a
feat(developer-api): enhance DeveloperView with project filtering and…
eliteprox fb20d59
Update apps/web-next/src/app/api/v1/auth/providers/[providerSlug]/cal…
eliteprox 8e7f334
feat(auth): implement billing provider OAuth session management
eliteprox 6bba3e0
refactor(developer-api): update key lookup ID generation logic
eliteprox 587cc38
feat(auth): handle session expiration in OAuth callback
eliteprox 1efa482
fix(developer-api): update status check for key revocation in Develop…
eliteprox ab82e57
fix(developer-api): sanitize error response details in server error h…
eliteprox bbfa3ef
Merge branch 'main' into feat/api-key-generation
eliteprox e139303
fix(developer-api): address P0/P1 code review issues on PR 124
seanhanca File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
156 changes: 156 additions & 0 deletions
156
apps/web-next/src/app/api/v1/auth/providers/[providerSlug]/callback/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| /** | ||
| * GET /api/v1/auth/providers/:providerSlug/callback | ||
| * Provider redirects the browser here after user authentication. | ||
| */ | ||
|
|
||
| import { NextRequest, NextResponse } from 'next/server'; | ||
| import { prisma } from '@/lib/db'; | ||
| import { encryptToken } from '@naap/database'; | ||
|
|
||
| const DAYDREAM_API_BASE = process.env.DAYDREAM_API_BASE || 'https://api.daydream.live'; | ||
|
|
||
| function escapeHtml(value: string): string { | ||
| return value | ||
| .replace(/&/g, '&') | ||
| .replace(/</g, '<') | ||
| .replace(/>/g, '>') | ||
| .replace(/"/g, '"') | ||
| .replace(/'/g, '''); | ||
| } | ||
|
|
||
| async function exchangeTokenForApiKey(providerSlug: string, token: string): Promise<string> { | ||
| if (providerSlug !== 'daydream') { | ||
| throw new Error(`Unsupported billing provider for OAuth callback: ${providerSlug}`); | ||
| } | ||
|
|
||
| const controller = new AbortController(); | ||
| const timeoutId = setTimeout(() => controller.abort(), 10_000); | ||
| let response: Response; | ||
| try { | ||
| response = await fetch(`${DAYDREAM_API_BASE}/v1/api-key`, { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| Authorization: `Bearer ${token}`, | ||
| }, | ||
| body: JSON.stringify({ name: 'dd_naap_linked' }), | ||
| signal: controller.signal, | ||
| }); | ||
| } catch (err) { | ||
| if ((err as { name?: string })?.name === 'AbortError') { | ||
| throw new Error('Daydream token exchange timed out'); | ||
| } | ||
| throw err; | ||
| } finally { | ||
| clearTimeout(timeoutId); | ||
| } | ||
|
|
||
| if (!response.ok) { | ||
| const text = await response.text(); | ||
| throw new Error(`Daydream token exchange failed: ${response.status} ${text}`); | ||
| } | ||
|
|
||
| const result = await response.json(); | ||
| const apiKey = result.api_key || result.apiKey || result.key; | ||
| if (!apiKey) { | ||
| throw new Error('Daydream token exchange failed: no API key in response'); | ||
| } | ||
| return apiKey; | ||
| } | ||
|
|
||
| export async function GET( | ||
| request: NextRequest, | ||
| { params }: { params: Promise<{ providerSlug: string }> } | ||
| ): Promise<NextResponse> { | ||
| const { providerSlug } = await params; | ||
| const searchParams = request.nextUrl.searchParams; | ||
| const token = searchParams.get('token'); | ||
| const state = searchParams.get('state'); | ||
|
|
||
| const htmlResponse = (title: string, message: string, isError = false) => { | ||
| const safeTitle = escapeHtml(title); | ||
| const safeMessage = escapeHtml(message); | ||
| return new NextResponse( | ||
| `<!DOCTYPE html> | ||
| <html><head><title>${safeTitle}</title> | ||
| <style> | ||
| body { font-family: system-ui, sans-serif; display: flex; justify-content: center; | ||
| align-items: center; min-height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa; } | ||
| .card { text-align: center; padding: 2rem; border-radius: 1rem; | ||
| background: #1a1a1a; border: 1px solid ${isError ? '#ef4444' : '#22c55e'}; max-width: 400px; } | ||
| h1 { font-size: 1.25rem; margin-bottom: 0.5rem; color: ${isError ? '#ef4444' : '#22c55e'}; } | ||
| p { color: #a1a1aa; font-size: 0.9rem; } | ||
| </style> | ||
| ${!isError ? '<script>setTimeout(function(){ window.close(); }, 3000);</script>' : ''} | ||
| </head> | ||
| <body><div class="card"><h1>${safeTitle}</h1><p>${safeMessage}</p></div></body></html>`, | ||
| { status: isError ? 400 : 200, headers: { 'Content-Type': 'text/html' } } | ||
| ); | ||
| }; | ||
|
|
||
| if (!token || !state) { | ||
| return htmlResponse( | ||
| 'Authentication Failed', | ||
| 'Missing token or state parameter from billing provider.', | ||
| true | ||
| ); | ||
| } | ||
|
|
||
| const session = await prisma.billingProviderOAuthSession.findUnique({ | ||
| where: { state }, | ||
| }); | ||
| if (!session) { | ||
| return htmlResponse( | ||
| 'Session Expired', | ||
| 'The login session has expired or was already used. Please try again from NaaP.', | ||
| true | ||
| ); | ||
| } | ||
|
|
||
| if (session.providerSlug !== providerSlug) { | ||
| return htmlResponse('Authentication Failed', 'Provider/session mismatch detected.', true); | ||
| } | ||
|
|
||
| if (Date.now() >= new Date(session.expiresAt).getTime()) { | ||
| await prisma.billingProviderOAuthSession | ||
| .updateMany({ | ||
| where: { | ||
| loginSessionId: session.loginSessionId, | ||
| status: 'pending', | ||
| }, | ||
| data: { status: 'expired' }, | ||
| }) | ||
| .catch(() => null); | ||
|
|
||
| return htmlResponse( | ||
| 'Session Expired', | ||
| 'The login session has expired or was already used. Please try again from NaaP.', | ||
| true | ||
| ); | ||
| } | ||
|
|
||
| try { | ||
| const apiKey = await exchangeTokenForApiKey(providerSlug, token); | ||
|
|
||
| await prisma.billingProviderOAuthSession.update({ | ||
| where: { loginSessionId: session.loginSessionId }, | ||
| data: { | ||
| status: 'complete', | ||
| accessToken: encryptToken(apiKey), | ||
| }, | ||
| }); | ||
|
|
||
|
eliteprox marked this conversation as resolved.
|
||
| console.log( | ||
| `[billing-auth:${providerSlug}] Callback complete for session ${session.loginSessionId.slice(0, 8)}...` | ||
| ); | ||
|
|
||
| return htmlResponse('Authentication Complete', 'You can close this tab and return to NaaP.'); | ||
| } catch (err) { | ||
| console.error(`[billing-auth:${providerSlug}] Callback error:`, err); | ||
| return htmlResponse( | ||
| 'Authentication Failed', | ||
| err instanceof Error ? err.message : 'Failed to authenticate with billing provider.', | ||
| true | ||
| ); | ||
| } | ||
| } | ||
120 changes: 120 additions & 0 deletions
120
apps/web-next/src/app/api/v1/auth/providers/[providerSlug]/result/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| /** | ||
| * GET /api/v1/auth/providers/:providerSlug/result?login_session_id=... | ||
| * Poll the status of a brokered billing-provider authentication session. | ||
| */ | ||
|
|
||
| import { NextRequest, NextResponse } from 'next/server'; | ||
| import { validateSession } from '@/lib/api/auth'; | ||
| import { success, errors, getAuthToken } from '@/lib/api/response'; | ||
| import { prisma } from '@/lib/db'; | ||
| import { decryptToken } from '@naap/database'; | ||
|
|
||
| let lastCleanup = 0; | ||
| const CLEANUP_INTERVAL_MS = 5 * 60_000; | ||
|
|
||
| async function cleanupExpiredSessions(): Promise<void> { | ||
| const now = Date.now(); | ||
| if (now - lastCleanup < CLEANUP_INTERVAL_MS) return; | ||
| lastCleanup = now; | ||
| try { | ||
| const { count } = await prisma.billingProviderOAuthSession.deleteMany({ | ||
| where: { expiresAt: { lt: new Date() } }, | ||
| }); | ||
| if (count > 0) { | ||
| console.log(`[billing-auth] Cleaned up ${count} expired OAuth sessions`); | ||
| } | ||
| } catch { | ||
| // non-critical | ||
| } | ||
| } | ||
|
|
||
| export async function GET( | ||
| request: NextRequest, | ||
| { params }: { params: Promise<{ providerSlug: string }> } | ||
| ): Promise<NextResponse> { | ||
| const { providerSlug } = await params; | ||
| const loginSessionId = request.nextUrl.searchParams.get('login_session_id'); | ||
|
|
||
| if (!loginSessionId) { | ||
| return errors.badRequest('login_session_id is required'); | ||
| } | ||
|
|
||
| const now = new Date(); | ||
| const session = await prisma.billingProviderOAuthSession.findUnique({ | ||
| where: { loginSessionId }, | ||
| }); | ||
|
|
||
| if (!session) { | ||
| const response = success({ status: 'expired' }); | ||
| response.headers.set('Cache-Control', 'no-store'); | ||
| return response; | ||
| } | ||
|
|
||
| if (session.expiresAt <= now) { | ||
| await prisma.billingProviderOAuthSession.delete({ | ||
| where: { loginSessionId }, | ||
| }).catch(() => null); | ||
| const response = success({ status: 'expired' }); | ||
| response.headers.set('Cache-Control', 'no-store'); | ||
| return response; | ||
| } | ||
|
|
||
| if (session.providerSlug !== providerSlug) { | ||
| return errors.forbidden('Session does not belong to this billing provider'); | ||
| } | ||
|
|
||
| if (session.naapUserId) { | ||
| const authToken = getAuthToken(request); | ||
| const authenticatedUser = authToken ? await validateSession(authToken) : null; | ||
| if (authenticatedUser?.id !== session.naapUserId) { | ||
| return errors.forbidden('Session does not belong to this user'); | ||
| } | ||
| } | ||
|
|
||
| if (session.status === 'complete') { | ||
| if (session.redeemedAt) { | ||
| const response = success({ status: 'redeemed' }); | ||
| response.headers.set('Cache-Control', 'no-store'); | ||
| return response; | ||
| } | ||
|
|
||
| const [redeemResult] = await prisma.$transaction([ | ||
| prisma.billingProviderOAuthSession.updateMany({ | ||
| where: { | ||
| loginSessionId, | ||
| redeemedAt: null, | ||
| status: 'complete', | ||
| expiresAt: { gt: now }, | ||
| }, | ||
| data: { redeemedAt: now }, | ||
| }), | ||
| ]); | ||
|
|
||
| if (redeemResult.count !== 1) { | ||
| const response = success({ status: 'redeemed' }); | ||
| response.headers.set('Cache-Control', 'no-store'); | ||
| return response; | ||
| } | ||
|
|
||
| const accessToken = session.accessToken ? decryptToken(session.accessToken) : null; | ||
| if (!accessToken) { | ||
| return errors.internal('Failed to retrieve access token'); | ||
| } | ||
|
|
||
| const response = success({ | ||
| status: 'complete', | ||
| access_token: accessToken, | ||
| user_id: session.providerUserId, | ||
| expires_in: Math.max(0, Math.floor((session.expiresAt.getTime() - Date.now()) / 1000)), | ||
| }); | ||
| response.headers.set('Cache-Control', 'no-store'); | ||
| return response; | ||
| } | ||
|
|
||
| // Opportunistic cleanup of expired sessions (non-blocking) | ||
| cleanupExpiredSessions().catch(() => null); | ||
|
|
||
| const response = success({ status: session.status }); | ||
| response.headers.set('Cache-Control', 'no-store'); | ||
| return response; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.