-
Notifications
You must be signed in to change notification settings - Fork 3.3k
feat(oauth): add CIMD support for client metadata discovery #3285
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
+201
−3
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5808c9d
feat(oauth): add CIMD support for client metadata discovery
waleedlatif1 be13a31
fix(oauth): add response size limit, redirect_uri and logo_uri valida…
waleedlatif1 2099037
fix(oauth): add explicit userId null for CIMD client insert
waleedlatif1 54066b9
fix(oauth): fix redirect_uri error handling, skip upsert on cache hit
waleedlatif1 f61ff70
fix(oauth): evict CIMD cache on upsert failure to allow retry
waleedlatif1 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| import { randomUUID } from 'node:crypto' | ||
| import { db } from '@sim/db' | ||
| import { oauthApplication } from '@sim/db/schema' | ||
| import { createLogger } from '@sim/logger' | ||
| import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server' | ||
|
|
||
| const logger = createLogger('cimd') | ||
|
|
||
| interface ClientMetadataDocument { | ||
| client_id: string | ||
| client_name: string | ||
| logo_uri?: string | ||
| redirect_uris: string[] | ||
| client_uri?: string | ||
| policy_uri?: string | ||
| tos_uri?: string | ||
| contacts?: string[] | ||
| scope?: string | ||
| } | ||
|
|
||
| export function isMetadataUrl(clientId: string): boolean { | ||
| return clientId.startsWith('https://') | ||
| } | ||
|
|
||
| async function fetchClientMetadata(url: string): Promise<ClientMetadataDocument> { | ||
| const parsed = new URL(url) | ||
| if (parsed.protocol !== 'https:') { | ||
| throw new Error('CIMD URL must use HTTPS') | ||
| } | ||
|
|
||
| const res = await secureFetchWithValidation(url, { | ||
| headers: { Accept: 'application/json' }, | ||
| timeout: 5000, | ||
| maxResponseBytes: 256 * 1024, | ||
| }) | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (!res.ok) { | ||
| throw new Error(`CIMD fetch failed: ${res.status} ${res.statusText}`) | ||
| } | ||
|
|
||
| const doc = (await res.json()) as ClientMetadataDocument | ||
|
|
||
| if (doc.client_id !== url) { | ||
| throw new Error(`CIMD client_id mismatch: document has "${doc.client_id}", expected "${url}"`) | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| if (!Array.isArray(doc.redirect_uris) || doc.redirect_uris.length === 0) { | ||
| throw new Error('CIMD document must contain at least one redirect_uri') | ||
| } | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| for (const uri of doc.redirect_uris) { | ||
| let parsed: URL | ||
| try { | ||
| parsed = new URL(uri) | ||
| } catch { | ||
| throw new Error(`Invalid redirect_uri: ${uri}`) | ||
| } | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') { | ||
| throw new Error(`Invalid redirect_uri scheme: ${parsed.protocol}`) | ||
| } | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (uri.includes(',')) { | ||
| throw new Error(`redirect_uri must not contain commas: ${uri}`) | ||
| } | ||
| } | ||
|
|
||
| if (doc.logo_uri) { | ||
| try { | ||
| const logoParsed = new URL(doc.logo_uri) | ||
| if (logoParsed.protocol !== 'https:') { | ||
| doc.logo_uri = undefined | ||
| } | ||
| } catch { | ||
| doc.logo_uri = undefined | ||
| } | ||
| } | ||
|
|
||
| if (!doc.client_name || typeof doc.client_name !== 'string') { | ||
| throw new Error('CIMD document must contain a client_name') | ||
| } | ||
|
|
||
| return doc | ||
| } | ||
|
|
||
| const CACHE_TTL_MS = 5 * 60 * 1000 | ||
| const NEGATIVE_CACHE_TTL_MS = 60 * 1000 | ||
| const cache = new Map<string, { doc: ClientMetadataDocument; expiresAt: number }>() | ||
| const failureCache = new Map<string, { error: string; expiresAt: number }>() | ||
| const inflight = new Map<string, Promise<ClientMetadataDocument>>() | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| interface ResolveResult { | ||
| metadata: ClientMetadataDocument | ||
| fromCache: boolean | ||
| } | ||
|
|
||
| export async function resolveClientMetadata(url: string): Promise<ResolveResult> { | ||
| const cached = cache.get(url) | ||
| if (cached && Date.now() < cached.expiresAt) { | ||
| return { metadata: cached.doc, fromCache: true } | ||
| } | ||
|
|
||
| const failed = failureCache.get(url) | ||
| if (failed && Date.now() < failed.expiresAt) { | ||
| throw new Error(failed.error) | ||
| } | ||
|
|
||
| const pending = inflight.get(url) | ||
| if (pending) { | ||
| return pending.then((doc) => ({ metadata: doc, fromCache: false })) | ||
| } | ||
|
|
||
| const promise = fetchClientMetadata(url) | ||
| .then((doc) => { | ||
| cache.set(url, { doc, expiresAt: Date.now() + CACHE_TTL_MS }) | ||
| failureCache.delete(url) | ||
| return doc | ||
| }) | ||
| .catch((err) => { | ||
| const message = err instanceof Error ? err.message : String(err) | ||
| failureCache.set(url, { error: message, expiresAt: Date.now() + NEGATIVE_CACHE_TTL_MS }) | ||
| throw err | ||
| }) | ||
| .finally(() => { | ||
| inflight.delete(url) | ||
| }) | ||
|
|
||
| inflight.set(url, promise) | ||
| return promise.then((doc) => ({ metadata: doc, fromCache: false })) | ||
| } | ||
|
|
||
| export function evictCachedMetadata(url: string): void { | ||
| cache.delete(url) | ||
| } | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| export async function upsertCimdClient(metadata: ClientMetadataDocument): Promise<void> { | ||
| const now = new Date() | ||
| const redirectURLs = metadata.redirect_uris.join(',') | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| await db | ||
| .insert(oauthApplication) | ||
| .values({ | ||
| id: randomUUID(), | ||
| clientId: metadata.client_id, | ||
| name: metadata.client_name, | ||
| icon: metadata.logo_uri ?? null, | ||
| redirectURLs, | ||
| type: 'public', | ||
| clientSecret: null, | ||
| userId: null, | ||
| createdAt: now, | ||
| updatedAt: now, | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }) | ||
| .onConflictDoUpdate({ | ||
| target: oauthApplication.clientId, | ||
| set: { | ||
| name: metadata.client_name, | ||
| icon: metadata.logo_uri ?? null, | ||
| redirectURLs, | ||
| type: 'public', | ||
| clientSecret: null, | ||
| updatedAt: now, | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }, | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }) | ||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| logger.info('Upserted CIMD client', { | ||
| clientId: metadata.client_id, | ||
| name: metadata.client_name, | ||
| }) | ||
| } | ||
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.