@undefineds.co/xpod 0.3.71-rc.8 → 0.3.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/ai-gateway/connect/index.d.ts +2 -0
- package/dist/api/ai-gateway/connect/index.js +87 -24
- package/dist/api/ai-gateway/connect/index.js.map +1 -1
- package/dist/api/ai-gateway/pod/HostedPodDataAccess.js +2 -2
- package/dist/api/ai-gateway/pod/HostedPodDataAccess.js.map +1 -1
- package/dist/api/container/common.js +1 -1
- package/dist/api/container/common.js.map +1 -1
- package/dist/api/container/routes.js +1 -1
- package/dist/api/container/routes.js.map +1 -1
- package/dist/api/handlers/AiGatewayManagementHandler.js +28 -12
- package/dist/api/handlers/AiGatewayManagementHandler.js.map +1 -1
- package/dist/api/handlers/PodSettingsHandler.d.ts +12 -19
- package/dist/api/handlers/PodSettingsHandler.js +12 -51
- package/dist/api/handlers/PodSettingsHandler.js.map +1 -1
- package/dist/http/InternalPodDataHttpHandler.d.ts +3 -1
- package/dist/http/InternalPodDataHttpHandler.js +48 -7
- package/dist/http/InternalPodDataHttpHandler.js.map +1 -1
- package/dist/http/InternalPodDataHttpHandler.jsonld +10 -2
- package/dist/runtime/GatewayAdminProxyAuth.d.ts +1 -1
- package/dist/runtime/GatewayAdminProxyAuth.js +1 -1
- package/dist/runtime/GatewayAdminProxyAuth.js.map +1 -1
- package/dist/runtime/Proxy.d.ts +1 -0
- package/dist/runtime/Proxy.js +22 -0
- package/dist/runtime/Proxy.js.map +1 -1
- package/package.json +1 -1
- package/static/dashboard/assets/{NetworkPage-CXjiUMR1.js → NetworkPage-CsERgA2D.js} +1 -1
- package/static/dashboard/assets/{PaneListHeader-BSipfl0W.js → PaneListHeader-WJWFvTKY.js} +1 -1
- package/static/dashboard/assets/{PodPage-Bd3Xhmp-.js → PodPage-Bo_NbnK1.js} +1 -1
- package/static/dashboard/assets/{ServicesPage-CI3jWZGe.js → ServicesPage-CrNDXQlg.js} +1 -1
- package/static/dashboard/assets/{card-z5BV5hTo.js → card-Cjax171A.js} +1 -1
- package/static/dashboard/assets/{dashboard-CSrqAv2L.js → dashboard-CaE1mRUL.js} +4 -4
- package/static/dashboard/assets/{database-Ct5ZPe6L.js → database-B0sGiSz2.js} +1 -1
- package/static/dashboard/assets/{external-link-B7wD1hkm.js → external-link-C_ANDdCY.js} +1 -1
- package/static/dashboard/assets/{index-tOBaUnM1.js → index-CDoxbvUP.js} +1 -1
- package/static/dashboard/assets/{refresh-cw-CFDZPaE8.js → refresh-cw-DHzHxCme.js} +1 -1
- package/static/dashboard/assets/{services-status-context-DN1Icg4A.js → services-status-context-ukghtkFD.js} +1 -1
- package/static/dashboard/dashboard.html +1 -1
- package/static/settings/assets/ModelsPage-ClTKzRGm.js +1 -0
- package/static/settings/assets/{PaneListHeader-BtON8Z5Q.js → PaneListHeader-DTVY4Ig2.js} +1 -1
- package/static/settings/assets/{PodPage-9LGuOloQ.js → PodPage-L_JAOD-r.js} +1 -1
- package/static/settings/assets/{ServicesPage-ZoT9-B_0.js → ServicesPage-BwLxrSWw.js} +1 -1
- package/static/settings/assets/{SettingsPage-Bj4lB3mq.js → SettingsPage-DUGHDPQx.js} +1 -1
- package/static/settings/assets/{card-CCGngjas.js → card-BZF0jSa_.js} +1 -1
- package/static/settings/assets/{services-status-context-CBfImxL_.js → services-status-context-BnbZHZnu.js} +1 -1
- package/static/settings/assets/{settings-yUyFIJxi.js → settings-BN7FyntE.js} +4 -4
- package/static/settings/assets/{workspace-layout-B0wJpPze.js → workspace-layout-jzYHoh3_.js} +1 -1
- package/static/settings/settings.html +1 -1
- package/static/settings/assets/ModelsPage-D87RrLB0.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/api/ai-gateway/connect/index.ts"],"names":[],"mappings":";;;AAAA,6CAAsG;AACtG,gEAAuE;AACvE,kDAI+B;AAE/B,0FAImD;AAGnD,oEAA6E;AA+J7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,kBAAkB,CAAC,IAA6B,EAAE,KAAa;IACtE,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,QAAQ,IAAI,CAAE,IAAI,CAAC,KAAK,CAAY,CAAC,IAAI,EAAE,EAAE,CAAC;QACvE,MAAM,IAAI,KAAK,CAAC,6CAA6C,KAAK,EAAE,CAAC,CAAC;IACxE,CAAC;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc;IACvC,OAAO,KAAK,YAAY,KAAK,IAAI,+CAA+C,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACvG,CAAC;AAED,SAAS,gBAAgB,CAAC,OAAe;IACvC,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;QAC/E,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;IACnE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["import { createHash, createHmac, randomBytes as nodeRandomBytes, timingSafeEqual } from 'node:crypto';\nimport { alias, and, drizzle, eq } from '@undefineds.co/drizzle-solid';\nimport {\n aiProviderResource,\n aiRuntimeRepository,\n credentialResource,\n} from '@undefineds.co/models';\nimport type { ProviderSecret } from '../credentials/CredentialVault';\nimport {\n decodePlaintextCredential,\n encodePlaintextCredential,\n PLAINTEXT_CREDENTIAL_STORAGE_MODE,\n} from '../credentials/PlaintextCredentialPayload';\nimport type { GatewayDeployment } from '../auth/InvocationTokenCodec';\nimport type { ProviderRegistry } from '../providers/ProviderRegistry';\nimport { DEFAULT_PROVIDER_DESCRIPTORS } from '../providers/ProviderRegistry';\nimport type { AuthContext } from '../../auth/AuthContext';\nimport type { InternalPodAccessTokenProvider } from '../pod/HostedPodDataAccess';\n\nexport type ConnectMode = 'browserAssistedApiKey' | 'deviceCodeOAuth' | 'connectUnsupported';\nexport type ConnectAttemptStatus =\n | 'pending'\n | 'authorization_pending'\n | 'slow_down'\n | 'completed'\n | 'expired'\n | 'unsupported';\n\nexport interface ConnectBeginInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n requestedMode: ConnectMode;\n expectedCredentialVersion?: number;\n auth?: AuthContext;\n}\n\nexport interface ConnectBeginResult {\n mode: ConnectMode;\n status: ConnectAttemptStatus;\n provider: string;\n deployment: GatewayDeployment;\n attemptId?: string;\n state?: string;\n signature?: string;\n expiresAt?: string;\n authorizationUrl?: string;\n pkceChallenge?: string;\n deviceCode?: string;\n userCode?: string;\n verificationUri?: string;\n verificationUriComplete?: string;\n intervalSeconds?: number;\n apiKeyManagementSupported?: boolean;\n credentialId?: string;\n message?: string;\n}\n\nexport interface CompleteApiKeyInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n attemptId: string;\n state: string;\n signature: string;\n apiKey: string;\n accountLabel?: string;\n auth?: AuthContext;\n}\n\nexport interface PollDeviceInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n attemptId: string;\n state: string;\n signature: string;\n auth?: AuthContext;\n}\n\nexport interface RefreshInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n auth?: AuthContext;\n}\n\nexport interface DisconnectInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n auth?: AuthContext;\n}\n\nexport interface ConnectCredentialRecord {\n id: string;\n credentialIri: string;\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n authMode: 'apiKey' | 'deviceCodeOAuth';\n storageMode: 'plaintext-v1';\n secretPayload: string;\n status: 'active' | 'revoked';\n accountLabel?: string;\n expiresAt?: Date;\n scopes?: string[];\n expectedVersion?: number;\n version?: number;\n reauthRequired?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nexport interface PodCredentialRepository {\n getCredential?(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined>;\n getActiveCredential(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined>;\n upsertConnectedCredential(\n record: ConnectCredentialRecord,\n context?: { auth?: AuthContext },\n ): Promise<ConnectCredentialRecord>;\n markReauthRequired(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n reason: string;\n expectedVersion?: number;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined>;\n disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined>;\n}\n\ntype ConnectedCredentialDb = {\n init?: (...resources: unknown[]) => Promise<void>;\n insert(resource: typeof credentialResource): {\n values(value: unknown): { execute(): Promise<unknown[]> };\n };\n select(): {\n from(resource: typeof credentialResource): {\n where(condition: unknown): { execute(): Promise<Record<string, unknown>[]> };\n };\n };\n findById<TRow>(resource: typeof credentialResource, id: string): Promise<TRow | null>;\n updateById<TRow>(resource: typeof credentialResource, id: string, patch: unknown): Promise<TRow | null>;\n update(resource: typeof credentialResource): {\n set(patch: unknown): {\n where(condition: unknown): {\n returning(): { execute(): Promise<Record<string, unknown>[]> };\n };\n };\n };\n};\n\nexport interface PodConnectedCredentialRepositoryOptions {\n internalPodAccess?: InternalPodAccessTokenProvider;\n providerIds?: string[];\n dbFactory?: (input: {\n owner: string;\n auth?: AuthContext;\n fetch: typeof fetch;\n credential?: typeof credentialResource;\n aiProvider?: typeof aiProviderResource;\n }) => Promise<ConnectedCredentialDb>;\n}\n\nexport class PodConnectedCredentialRepository implements PodCredentialRepository {\n private readonly dbFactory: NonNullable<PodConnectedCredentialRepositoryOptions['dbFactory']>;\n private readonly internalPodAccess?: InternalPodAccessTokenProvider;\n private readonly providerIds: string[];\n private readonly credentialTemplate: typeof credentialResource;\n private readonly aiProviderTemplate: typeof aiProviderResource;\n\n public constructor(options: PodConnectedCredentialRepositoryOptions = {}) {\n this.internalPodAccess = options.internalPodAccess;\n this.providerIds = options.providerIds\n ?? DEFAULT_PROVIDER_DESCRIPTORS.map((provider) => provider.id);\n this.dbFactory = options.dbFactory ?? createDefaultConnectedCredentialDb;\n this.credentialTemplate = alias(credentialResource, 'credentialTemplate');\n this.aiProviderTemplate = alias(aiProviderResource, 'aiProviderTemplate');\n }\n\n public async getCredential(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const id = aiRuntimeRepository.credentialId(input);\n const row = await db.findById<Record<string, unknown>>(credential, id);\n const record = row ? recordFromCredentialRow(row, input.webId) : undefined;\n if (!record) {\n return undefined;\n }\n return record;\n }\n\n public async getActiveCredential(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined> {\n const record = await this.getCredential(input);\n return record?.status === 'active' && !record.reauthRequired ? record : undefined;\n }\n\n public async listCredentials(input: {\n webId: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<Array<{\n id: string;\n credentialIri: string;\n provider: string;\n authMode: 'apiKey' | 'deviceCodeOAuth';\n enabled: boolean;\n priority?: number;\n models?: string[];\n defaultModel?: string;\n health?: 'healthy' | 'reauthRequired' | 'disabled' | 'error';\n quota?: { status: 'available' | 'unsupported' | 'exhausted' | 'error' };\n storageMode: 'plaintext-v1';\n secretPayload: string;\n version?: number;\n runtimeCredential?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n }>> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const rows = (await Promise.all(\n this.providerIds.map(async (provider) => {\n try {\n return await db.findById<Record<string, unknown>>(\n credential,\n aiRuntimeRepository.credentialId({ deployment: input.deployment, provider }),\n );\n } catch (error) {\n if (isPodResourceNotFound(error)) {\n return null;\n }\n throw error;\n }\n }),\n )).filter((row): row is Record<string, unknown> => row !== null);\n return rows\n .map((row) => recordFromCredentialRow(row, input.webId))\n .filter((record) => record.webId === input.webId)\n .filter((record) => record.deployment === input.deployment)\n .filter((record) => record.status === 'active')\n .map((record) => ({\n id: record.id,\n credentialIri: record.credentialIri,\n provider: record.provider,\n authMode: record.authMode,\n enabled: !record.reauthRequired,\n models: modelsFromMetadata(record.metadata),\n defaultModel: defaultModelFromMetadata(record.metadata),\n priority: priorityFromMetadata(record.metadata),\n health: record.reauthRequired ? 'reauthRequired' : 'healthy',\n quota: { status: 'available' },\n storageMode: record.storageMode,\n secretPayload: record.secretPayload,\n version: record.version,\n runtimeCredential: runtimeCredentialFromMetadata(record.metadata),\n metadata: record.metadata,\n }));\n }\n\n public async upsertConnectedCredential(\n record: ConnectCredentialRecord,\n context?: { auth?: AuthContext },\n ): Promise<ConnectCredentialRecord> {\n const { db, credential } = await this.dbForOwner(record.webId, context?.auth);\n const existing = await db.findById<Record<string, unknown>>(credential, record.id);\n const existingVersion = existing ? versionFromRow(existing) : 0;\n if (record.expectedVersion !== undefined && record.expectedVersion !== existingVersion) {\n throw new Error('credential_version_conflict');\n }\n const nextVersion = existingVersion + 1;\n const row = credentialRowFromRecord({\n ...record,\n version: nextVersion,\n });\n if (existing) {\n const updated = await db.updateById<Record<string, unknown>>(credential, record.id, row);\n return recordFromCredentialRow(updated ?? row, record.webId);\n }\n await db.insert(credential).values(row).execute();\n return recordFromCredentialRow(row, record.webId);\n }\n\n public async markReauthRequired(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n reason: string;\n expectedVersion?: number;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const id = aiRuntimeRepository.credentialId(input);\n const existing = await db.findById<Record<string, unknown>>(credential, id);\n if (!existing) {\n return undefined;\n }\n const existingVersion = versionFromRow(existing);\n if (input.expectedVersion !== undefined && input.expectedVersion !== existingVersion) {\n throw new Error('credential_version_conflict');\n }\n const updated = await db.updateById<Record<string, unknown>>(credential, id, {\n reauthRequired: true,\n status: 'active',\n keyVersion: String(existingVersion + 1),\n });\n return updated ? recordFromCredentialRow(updated, input.webId) : undefined;\n }\n\n public async disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const id = aiRuntimeRepository.credentialId(input);\n const existing = await db.findById<Record<string, unknown>>(credential, id);\n if (!existing) {\n return undefined;\n }\n const updated = await db.updateById<Record<string, unknown>>(credential, id, {\n status: 'revoked',\n keyVersion: String(versionFromRow(existing) + 1),\n });\n return updated ? recordFromCredentialRow(updated, input.webId) : undefined;\n }\n\n private async dbForOwner(owner: string, auth?: AuthContext): Promise<{\n db: ConnectedCredentialDb;\n credential: typeof credentialResource;\n }> {\n const trustedFetch = await this.resolveTrustedFetch(owner, auth);\n const credential = alias(this.credentialTemplate, 'credential');\n const aiProvider = alias(this.aiProviderTemplate, 'aiProvider');\n const db = await this.dbFactory({ owner, auth, fetch: trustedFetch, credential, aiProvider });\n await db.init?.(credential, aiProvider);\n return { db, credential };\n }\n\n private async resolveTrustedFetch(owner: string, auth?: AuthContext): Promise<typeof fetch> {\n const trustedFetch = await this.internalPodAccess?.getTrustedFetch(owner, auth);\n if (!trustedFetch) {\n throw new Error('AI Connection service identity is not configured');\n }\n return async (input, init) => {\n const response = await trustedFetch(input, init);\n if (response.status === 403) {\n throw new Error('service_access_missing');\n }\n return response;\n };\n }\n}\n\nexport interface ProviderConnectAdapter {\n readonly provider: string;\n begin(input: ConnectBeginInput): Promise<ConnectBeginResult>;\n status?(input: PollDeviceInput): Promise<ConnectBeginResult>;\n completeApiKey?(input: CompleteApiKeyInput): Promise<ConnectBeginResult>;\n pollDevice?(input: PollDeviceInput): Promise<ConnectBeginResult>;\n refresh?(\n input: RefreshInput,\n current: ConnectCredentialRecord,\n secret: ProviderSecret,\n ): Promise<ConnectCredentialRecord | undefined>;\n disconnect?(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined>;\n}\n\ninterface ConnectAttempt {\n id: string;\n provider: string;\n deployment: GatewayDeployment;\n webId: string;\n mode: ConnectMode;\n state: string;\n signature: string;\n expiresAt: Date;\n consumedAt?: Date;\n expectedCredentialVersion?: number;\n codeVerifier?: string;\n deviceCode?: string;\n intervalSeconds?: number;\n currentPollIntervalSeconds?: number;\n nextPollAt?: Date;\n pollClaimedAt?: Date;\n lastPollStatus?: ConnectAttemptStatus;\n}\n\ninterface PollClaimResult {\n attempt: ConnectAttempt;\n claimed: boolean;\n}\n\nexport class InMemoryConnectAttemptStore {\n private readonly attempts = new Map<string, ConnectAttempt>();\n private readonly maxAttempts = 1_000;\n\n public async create(attempt: ConnectAttempt): Promise<ConnectAttempt> {\n this.pruneExpired(new Date());\n this.attempts.set(attempt.id, cloneAttempt(attempt));\n this.pruneBounded();\n return cloneAttempt(attempt);\n }\n\n public async get(id: string, now?: Date): Promise<ConnectAttempt | undefined> {\n this.pruneExpired(now ?? new Date(), id);\n const attempt = this.attempts.get(id);\n if (attempt && now && attempt.expiresAt.getTime() <= now.getTime()) {\n this.attempts.delete(id);\n }\n return attempt ? cloneAttempt(attempt) : undefined;\n }\n\n public async consume(id: string, now: Date): Promise<ConnectAttempt> {\n this.pruneExpired(now, id);\n const attempt = this.attempts.get(id);\n if (!attempt) {\n throw new Error('Connect attempt not found');\n }\n if (attempt.consumedAt) {\n throw new Error('Connect attempt already consumed');\n }\n if (attempt.expiresAt.getTime() <= now.getTime()) {\n this.attempts.delete(id);\n throw new Error('Connect attempt expired');\n }\n attempt.consumedAt = new Date(now);\n return cloneAttempt(attempt);\n }\n\n public async claimPoll(id: string, now: Date): Promise<PollClaimResult> {\n this.pruneExpired(now, id);\n const attempt = this.attempts.get(id);\n if (!attempt) {\n throw new Error('Connect attempt not found');\n }\n if (attempt.consumedAt) {\n throw new Error('Connect attempt already consumed');\n }\n if (attempt.expiresAt.getTime() <= now.getTime()) {\n this.attempts.delete(id);\n throw new Error('Connect attempt expired');\n }\n if (attempt.nextPollAt && attempt.nextPollAt.getTime() > now.getTime()) {\n return { attempt: cloneAttempt(attempt), claimed: false };\n }\n if (attempt.pollClaimedAt) {\n return { attempt: cloneAttempt(attempt), claimed: false };\n }\n attempt.pollClaimedAt = new Date(now);\n return { attempt: cloneAttempt(attempt), claimed: true };\n }\n\n public async updatePollSchedule(\n id: string,\n patch: {\n intervalSeconds: number;\n nextPollAt: Date;\n lastPollStatus: ConnectAttemptStatus;\n },\n ): Promise<ConnectAttempt | undefined> {\n const attempt = this.attempts.get(id);\n if (!attempt || attempt.consumedAt) {\n return undefined;\n }\n attempt.intervalSeconds = patch.intervalSeconds;\n attempt.currentPollIntervalSeconds = patch.intervalSeconds;\n attempt.nextPollAt = new Date(patch.nextPollAt);\n attempt.lastPollStatus = patch.lastPollStatus;\n attempt.pollClaimedAt = undefined;\n return cloneAttempt(attempt);\n }\n\n public async releasePollClaim(id: string): Promise<void> {\n const attempt = this.attempts.get(id);\n if (attempt) {\n attempt.pollClaimedAt = undefined;\n }\n }\n\n private pruneExpired(now: Date, exceptId?: string): void {\n for (const [id, attempt] of this.attempts) {\n if (id !== exceptId && attempt.expiresAt.getTime() <= now.getTime()) {\n this.attempts.delete(id);\n }\n }\n }\n\n private pruneBounded(): void {\n while (this.attempts.size > this.maxAttempts) {\n const oldest = this.attempts.keys().next().value;\n if (typeof oldest !== 'string') {\n return;\n }\n this.attempts.delete(oldest);\n }\n }\n}\n\nexport interface BrowserAssistedApiKeyConnectAdapterOptions {\n provider: string;\n consoleUrl: string;\n attempts: InMemoryConnectAttemptStore;\n credentialRepository: PodCredentialRepository;\n deployment: GatewayDeployment;\n now?: () => Date;\n randomBytes?: (bytes: number) => Buffer;\n signingSecret: string;\n}\n\nexport class BrowserAssistedApiKeyConnectAdapter implements ProviderConnectAdapter {\n public readonly provider: string;\n private readonly consoleUrl: string;\n protected readonly attempts: InMemoryConnectAttemptStore;\n protected readonly credentialRepository: PodCredentialRepository;\n protected readonly deployment: GatewayDeployment;\n protected readonly now: () => Date;\n protected readonly randomBytes: (bytes: number) => Buffer;\n private readonly signingSecret: string;\n\n public constructor(options: BrowserAssistedApiKeyConnectAdapterOptions) {\n this.provider = normalizeProvider(options.provider);\n this.consoleUrl = options.consoleUrl;\n this.attempts = options.attempts;\n this.credentialRepository = options.credentialRepository;\n this.deployment = options.deployment;\n this.now = options.now ?? (() => new Date());\n this.randomBytes = options.randomBytes ?? nodeRandomBytes;\n this.signingSecret = options.signingSecret;\n }\n\n public async begin(input: ConnectBeginInput): Promise<ConnectBeginResult> {\n this.assertInput(input, 'browserAssistedApiKey');\n const now = this.now();\n const expiresAt = new Date(now.getTime() + 5 * 60 * 1000);\n const attempt = await this.createAttempt(input, expiresAt);\n const url = new URL(this.consoleUrl);\n url.searchParams.set('xpod_connect_attempt', attempt.id);\n url.searchParams.set('xpod_provider', this.provider);\n\n return {\n mode: 'browserAssistedApiKey',\n status: 'pending',\n provider: this.provider,\n deployment: this.deployment,\n attemptId: attempt.id,\n state: attempt.state,\n signature: attempt.signature,\n expiresAt: expiresAt.toISOString(),\n authorizationUrl: url.toString(),\n };\n }\n\n public async completeApiKey(input: CompleteApiKeyInput): Promise<ConnectBeginResult> {\n if (!input.apiKey.trim()) {\n throw new Error('API key is required');\n }\n const attempt = await this.loadConsumableAttempt(input, 'browserAssistedApiKey');\n const consumed = await this.attempts.consume(input.attemptId, this.now());\n const credentialIri = aiRuntimeRepository.credentialIri(input.webId, {\n deployment: input.deployment,\n provider: this.provider,\n });\n const secretPayload = encodePlaintextCredential({ type: 'apiKey', apiKey: input.apiKey });\n const record = await this.credentialRepository.upsertConnectedCredential({\n id: aiRuntimeRepository.credentialId({ deployment: input.deployment, provider: this.provider }),\n credentialIri,\n webId: input.webId,\n provider: this.provider,\n deployment: input.deployment,\n authMode: 'apiKey',\n storageMode: PLAINTEXT_CREDENTIAL_STORAGE_MODE,\n secretPayload,\n status: 'active',\n accountLabel: input.accountLabel,\n expectedVersion: consumed.expectedCredentialVersion,\n }, { auth: input.auth });\n\n return {\n mode: 'browserAssistedApiKey',\n status: 'completed',\n provider: this.provider,\n deployment: input.deployment,\n attemptId: attempt.id,\n credentialId: record.id,\n };\n }\n\n public async status(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const attempt = await this.loadAttemptForStatus(input, 'browserAssistedApiKey');\n return {\n mode: attempt.mode,\n status: this.statusForAttempt(attempt),\n provider: this.provider,\n deployment: input.deployment,\n attemptId: attempt.id,\n expiresAt: attempt.expiresAt.toISOString(),\n };\n }\n\n public async disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined> {\n return this.credentialRepository.disconnect({\n webId: input.webId,\n provider: this.provider,\n deployment: input.deployment,\n auth: input.auth,\n });\n }\n\n protected async createAttempt(input: ConnectBeginInput, expiresAt: Date, extra: Partial<ConnectAttempt> = {}): Promise<ConnectAttempt> {\n const attemptWithoutSignature: Omit<ConnectAttempt, 'signature'> = {\n id: token(this.randomBytes),\n provider: this.provider,\n deployment: input.deployment,\n webId: input.webId,\n mode: input.requestedMode,\n state: token(this.randomBytes),\n expiresAt,\n expectedCredentialVersion: input.expectedCredentialVersion,\n ...extra,\n };\n const signature = signAttempt(attemptWithoutSignature, this.signingSecret);\n return this.attempts.create({ ...attemptWithoutSignature, signature });\n }\n\n protected async loadAttemptForStatus(input: PollDeviceInput, mode: ConnectMode): Promise<ConnectAttempt> {\n const attempt = await this.attempts.get(input.attemptId, this.now());\n if (!attempt) {\n throw new Error('Connect attempt not found');\n }\n if (attempt.webId !== input.webId) {\n throw new Error('Connect attempt is bound to a different WebID');\n }\n if (attempt.deployment !== input.deployment) {\n throw new Error('Connect attempt is bound to a different deployment');\n }\n if (attempt.provider !== normalizeProvider(input.provider)) {\n throw new Error('Connect attempt is bound to a different provider');\n }\n if (attempt.mode !== mode) {\n throw new Error('Connect attempt mode mismatch');\n }\n if (attempt.state !== input.state) {\n throw new Error('Invalid Connect attempt state');\n }\n if (!signatureMatches(input.signature, signAttempt(attempt, this.signingSecret))) {\n throw new Error('Invalid Connect attempt signature');\n }\n return attempt;\n }\n\n protected async loadConsumableAttempt(input: PollDeviceInput, mode: ConnectMode): Promise<ConnectAttempt> {\n const attempt = await this.loadAttemptForStatus(input, mode);\n if (attempt.expiresAt.getTime() <= this.now().getTime()) {\n throw new Error('Connect attempt expired');\n }\n if (attempt.consumedAt) {\n throw new Error('Connect attempt already consumed');\n }\n return attempt;\n }\n\n protected statusForAttempt(attempt: ConnectAttempt): ConnectAttemptStatus {\n if (attempt.expiresAt.getTime() <= this.now().getTime()) {\n return 'expired';\n }\n return attempt.consumedAt ? 'completed' : 'pending';\n }\n\n protected assertInput(input: ConnectBeginInput, mode: ConnectMode): void {\n if (normalizeProvider(input.provider) !== this.provider) {\n throw new Error('Connect provider mismatch');\n }\n if (input.deployment !== this.deployment) {\n throw new Error('Connect deployment mismatch');\n }\n if (input.requestedMode !== mode) {\n throw new Error('Unsupported Connect mode');\n }\n if (!input.webId) {\n throw new Error('Connect WebID is required');\n }\n }\n}\n\nexport interface KimiDeviceCodeConnectAdapterOptions extends Omit<BrowserAssistedApiKeyConnectAdapterOptions, 'provider' | 'consoleUrl'> {\n fetch?: typeof fetch;\n clientId: string;\n deviceAuthorizationEndpoint?: string;\n tokenEndpoint?: string;\n}\n\nexport class KimiDeviceCodeConnectAdapter extends BrowserAssistedApiKeyConnectAdapter {\n private readonly fetchImpl: typeof fetch;\n private readonly clientId: string;\n private readonly deviceAuthorizationEndpoint: string;\n private readonly tokenEndpoint: string;\n\n public constructor(options: KimiDeviceCodeConnectAdapterOptions) {\n super({\n ...options,\n provider: 'kimi',\n consoleUrl: 'https://kimi.moonshot.cn/device',\n });\n this.fetchImpl = options.fetch ?? fetch;\n this.clientId = options.clientId;\n this.deviceAuthorizationEndpoint = options.deviceAuthorizationEndpoint ?? 'https://auth.kimi.com/api/oauth/device_authorization';\n this.tokenEndpoint = options.tokenEndpoint ?? 'https://auth.kimi.com/api/oauth/token';\n assertKimiEndpoint(this.deviceAuthorizationEndpoint, '/api/oauth/device_authorization');\n assertKimiEndpoint(this.tokenEndpoint, '/api/oauth/token');\n }\n\n public override async begin(input: ConnectBeginInput): Promise<ConnectBeginResult> {\n this.assertInput(input, 'deviceCodeOAuth');\n const now = this.now();\n const verifier = token(this.randomBytes);\n const challenge = codeChallenge(verifier);\n const response = await this.fetchImpl(this.deviceAuthorizationEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n client_id: this.clientId,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n }),\n });\n const body = await safeJson(response);\n if (!response.ok) {\n throw new Error(`Kimi device authorization failed: ${safeProviderError(body)}`);\n }\n requireStringField(body, 'device_code');\n requireStringField(body, 'user_code');\n requireStringField(body, 'verification_uri_complete');\n const expiresIn = numberFrom(body.expires_in, 300);\n const attempt = await this.createAttempt(input, new Date(now.getTime() + expiresIn * 1000), {\n mode: 'deviceCodeOAuth',\n codeVerifier: verifier,\n deviceCode: stringFrom(body.device_code),\n intervalSeconds: numberFrom(body.interval, 5),\n currentPollIntervalSeconds: numberFrom(body.interval, 5),\n nextPollAt: new Date(now.getTime() + numberFrom(body.interval, 5) * 1000),\n });\n return {\n mode: 'deviceCodeOAuth',\n status: 'pending',\n provider: 'kimi',\n deployment: input.deployment,\n attemptId: attempt.id,\n state: attempt.state,\n signature: attempt.signature,\n expiresAt: attempt.expiresAt.toISOString(),\n pkceChallenge: challenge,\n deviceCode: attempt.deviceCode,\n userCode: stringFrom(body.user_code),\n verificationUri: stringFrom(body.verification_uri),\n verificationUriComplete: stringFrom(body.verification_uri_complete),\n intervalSeconds: attempt.intervalSeconds,\n };\n }\n\n public async pollDevice(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const attempt = await this.loadConsumableAttempt(input, 'deviceCodeOAuth');\n const now = this.nowForConsume();\n const claim = await this.attempts.claimPoll(input.attemptId, now);\n if (!claim.claimed) {\n return pendingResult(\n input,\n claim.attempt.lastPollStatus === 'slow_down' ? 'slow_down' : 'authorization_pending',\n claim.attempt.currentPollIntervalSeconds ?? claim.attempt.intervalSeconds,\n );\n }\n try {\n const response = await this.fetchImpl(this.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: attempt.deviceCode ?? '',\n client_id: this.clientId,\n code_verifier: attempt.codeVerifier ?? '',\n }),\n });\n const body = await safeJson(response);\n if (!response.ok) {\n if (body.error === 'authorization_pending' || body.error === 'slow_down') {\n const status = body.error;\n const intervalSeconds = status === 'slow_down'\n ? (attempt.currentPollIntervalSeconds ?? attempt.intervalSeconds ?? 5) + 5\n : (attempt.currentPollIntervalSeconds ?? attempt.intervalSeconds ?? 5);\n await this.attempts.updatePollSchedule(input.attemptId, {\n intervalSeconds,\n nextPollAt: new Date(now.getTime() + intervalSeconds * 1000),\n lastPollStatus: status,\n });\n return pendingResult(input, status, intervalSeconds);\n }\n if (body.error === 'expired_token') {\n await this.attempts.consume(input.attemptId, this.nowForConsume());\n return pendingResult(input, 'expired');\n }\n throw new Error(`Kimi device token failed: ${safeProviderError(body)}`);\n }\n await this.attempts.consume(input.attemptId, this.nowForConsume());\n requireStringField(body, 'access_token');\n requireStringField(body, 'refresh_token');\n const record = await this.storeOAuthCredential(input, body, attempt.expectedCredentialVersion);\n return {\n mode: 'deviceCodeOAuth',\n status: 'completed',\n provider: 'kimi',\n deployment: input.deployment,\n attemptId: input.attemptId,\n credentialId: record.id,\n };\n } catch (error) {\n await this.attempts.releasePollClaim(input.attemptId);\n throw error;\n }\n }\n\n public override async status(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const attempt = await this.loadAttemptForStatus(input, 'deviceCodeOAuth');\n return {\n mode: 'deviceCodeOAuth',\n status: this.statusForAttempt(attempt),\n provider: 'kimi',\n deployment: input.deployment,\n attemptId: attempt.id,\n expiresAt: attempt.expiresAt.toISOString(),\n deviceCode: attempt.deviceCode,\n intervalSeconds: attempt.currentPollIntervalSeconds ?? attempt.intervalSeconds,\n };\n }\n\n public async refresh(\n input: RefreshInput,\n current: ConnectCredentialRecord,\n secret: ProviderSecret,\n ): Promise<ConnectCredentialRecord | undefined> {\n const refreshToken = stringFrom(secret.refreshToken);\n if (!refreshToken) {\n return this.credentialRepository.markReauthRequired({\n webId: input.webId,\n provider: 'kimi',\n deployment: input.deployment,\n reason: 'missing_refresh_token',\n expectedVersion: current.version,\n auth: input.auth,\n });\n }\n const response = await this.fetchImpl(this.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: this.clientId,\n }),\n });\n const body = await safeJson(response);\n if (!response.ok) {\n return this.credentialRepository.markReauthRequired({\n webId: input.webId,\n provider: 'kimi',\n deployment: input.deployment,\n reason: safeProviderError(body),\n expectedVersion: current.version,\n auth: input.auth,\n });\n }\n requireStringField(body, 'access_token');\n requireStringField(body, 'refresh_token');\n return this.storeOAuthCredential(input, body, current.version);\n }\n\n public override async disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined> {\n return this.credentialRepository.disconnect({\n webId: input.webId,\n provider: 'kimi',\n deployment: input.deployment,\n auth: input.auth,\n });\n }\n\n private nowForConsume(): Date {\n return this.now();\n }\n\n private async storeOAuthCredential(\n input: { webId: string; deployment: GatewayDeployment; auth?: AuthContext },\n body: Record<string, unknown>,\n expectedVersion?: number,\n ): Promise<ConnectCredentialRecord> {\n const credentialIri = aiRuntimeRepository.credentialIri(input.webId, {\n deployment: input.deployment,\n provider: 'kimi',\n });\n const expiresAt = expiresAtFrom(body.expires_in, this.now());\n const secret: ProviderSecret = {\n type: 'deviceCodeOAuth',\n accessToken: stringFrom(body.access_token),\n refreshToken: stringFrom(body.refresh_token),\n expiresAt: expiresAt?.toISOString(),\n scope: stringFrom(body.scope),\n idToken: stringFrom(body.id_token),\n };\n return this.credentialRepository.upsertConnectedCredential({\n id: aiRuntimeRepository.credentialId({ deployment: input.deployment, provider: 'kimi' }),\n credentialIri,\n webId: input.webId,\n provider: 'kimi',\n deployment: input.deployment,\n authMode: 'deviceCodeOAuth',\n storageMode: PLAINTEXT_CREDENTIAL_STORAGE_MODE,\n secretPayload: encodePlaintextCredential(secret),\n status: 'active',\n expiresAt,\n expectedVersion,\n metadata: {\n authoritativeSubject: decodeJwtSubject(stringFrom(body.id_token)),\n },\n }, { auth: input.auth });\n }\n}\n\nexport class DeepSeekConnectAdapter implements ProviderConnectAdapter {\n public readonly provider = 'deepseek';\n\n public async begin(input: ConnectBeginInput): Promise<ConnectBeginResult> {\n if (normalizeProvider(input.provider) !== this.provider) {\n throw new Error('Connect provider mismatch');\n }\n return {\n mode: 'connectUnsupported',\n status: 'unsupported',\n provider: 'deepseek',\n deployment: input.deployment,\n apiKeyManagementSupported: true,\n message: 'DeepSeek does not expose a supported third-party browser Connect flow; use authenticated API key management.',\n };\n }\n}\n\nexport interface ProviderConnectServiceOptions {\n registry: ProviderRegistry;\n adapters: ProviderConnectAdapter[];\n credentialRepository?: PodCredentialRepository;\n}\n\nexport interface ProviderConnectionSummary {\n provider: string;\n status: 'connected' | 'disconnected' | 'reauthRequired';\n authMode?: 'apiKey' | 'deviceCodeOAuth';\n accountLabel?: string;\n expiresAt?: string;\n reauthRequired?: boolean;\n credentialIri?: string;\n version?: number;\n connect: {\n modes: string[];\n configured: boolean;\n message?: string;\n };\n}\n\nexport class ProviderConnectService {\n private readonly registry: ProviderRegistry;\n private readonly credentialRepository?: PodCredentialRepository;\n private readonly adapters = new Map<string, ProviderConnectAdapter>();\n\n public constructor(options: ProviderConnectServiceOptions) {\n this.registry = options.registry;\n this.credentialRepository = options.credentialRepository;\n for (const adapter of options.adapters) {\n this.adapters.set(normalizeProvider(adapter.provider), adapter);\n }\n }\n\n public begin(input: ConnectBeginInput): Promise<ConnectBeginResult> {\n const descriptor = this.registry.requireProvider(input.provider);\n if (descriptor.connect?.mode !== input.requestedMode) {\n throw new Error('Requested Connect mode does not match provider capability');\n }\n if (descriptor.connect?.configured === false) {\n return Promise.resolve({\n mode: descriptor.connect.mode,\n status: 'unsupported',\n provider: normalizeProvider(input.provider),\n deployment: input.deployment,\n apiKeyManagementSupported: descriptor.connect.apiKeyManagementSupported,\n message: descriptor.connect.notes?.join(' '),\n });\n }\n return this.requireAdapter(input.provider).begin(input);\n }\n\n public async listProviders(input: {\n webId: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ProviderConnectionSummary[]> {\n return Promise.all(this.registry.listProviders().map(async (descriptor) => {\n const credential = this.credentialRepository?.getCredential\n ? await this.credentialRepository.getCredential({\n ...input,\n provider: descriptor.id,\n })\n : await this.credentialRepository?.getActiveCredential({\n ...input,\n provider: descriptor.id,\n });\n const active = credential?.status === 'active';\n const reauthRequired = active && credential.reauthRequired === true;\n const modes = Array.from(new Set([\n ...descriptor.authModes.filter((mode) => mode !== 'connectUnsupported'),\n ...(descriptor.connect?.apiKeyManagementSupported ? ['apiKey'] : []),\n ]));\n return {\n provider: descriptor.id,\n status: reauthRequired\n ? 'reauthRequired' as const\n : active\n ? 'connected' as const\n : 'disconnected' as const,\n authMode: active ? credential.authMode : undefined,\n accountLabel: active ? credential.accountLabel : undefined,\n expiresAt: active ? credential.expiresAt?.toISOString() : undefined,\n reauthRequired: reauthRequired || undefined,\n credentialIri: active ? credential.credentialIri : undefined,\n version: active ? credential.version : undefined,\n connect: {\n modes,\n configured: descriptor.connect?.configured !== false,\n message: descriptor.connect?.notes?.join(' ') || undefined,\n },\n };\n }));\n }\n\n public completeApiKey(input: CompleteApiKeyInput): Promise<ConnectBeginResult> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.completeApiKey) {\n throw new Error('Provider does not support API key Connect completion');\n }\n return adapter.completeApiKey(input);\n }\n\n public pollDevice(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.pollDevice) {\n throw new Error('Provider does not support device-code polling');\n }\n return adapter.pollDevice(input);\n }\n\n public status(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.status) {\n throw new Error('Provider does not support Connect status');\n }\n return adapter.status(input);\n }\n\n public refresh(input: RefreshInput): Promise<ConnectCredentialRecord | undefined> {\n return this.refreshWithRetry(input, 2);\n }\n\n private async refreshWithRetry(\n input: RefreshInput,\n remainingAttempts: number,\n ): Promise<ConnectCredentialRecord | undefined> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.refresh) {\n throw new Error('Provider does not support refresh');\n }\n if (!this.credentialRepository) {\n throw new Error('PodCredentialRepository is required for provider refresh');\n }\n const current = await this.credentialRepository.getActiveCredential(input);\n if (!current) {\n throw new Error('Active provider credential not found');\n }\n const secret = decodePlaintextCredential(current);\n try {\n return await adapter.refresh(input, current, secret);\n } catch (error) {\n if (remainingAttempts > 0 && isVersionConflict(error)) {\n const latest = await this.credentialRepository.getActiveCredential(input);\n if (latest && latest.version !== current.version && !latest.reauthRequired) {\n return latest;\n }\n return this.refreshWithRetry(input, remainingAttempts - 1);\n }\n throw error;\n }\n }\n\n public disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.disconnect) {\n throw new Error('Provider does not support disconnect');\n }\n return adapter.disconnect(input);\n }\n\n private requireAdapter(provider: string): ProviderConnectAdapter {\n const adapter = this.adapters.get(normalizeProvider(provider));\n if (!adapter) {\n throw new Error(`No Connect adapter registered for ${provider}`);\n }\n return adapter;\n }\n}\n\nfunction token(randomBytes: (bytes: number) => Buffer): string {\n return randomBytes(32).toString('base64url');\n}\n\nfunction createDefaultConnectedCredentialDb(input: {\n owner: string;\n auth?: AuthContext;\n fetch: typeof fetch;\n credential?: typeof credentialResource;\n aiProvider?: typeof aiProviderResource;\n}): Promise<ConnectedCredentialDb> {\n const credential = input.credential ?? credentialResource;\n const aiProvider = input.aiProvider ?? aiProviderResource;\n return Promise.resolve(drizzle(\n {\n fetch: input.fetch,\n info: { webId: input.owner, isLoggedIn: true },\n } as any,\n {\n schema: {\n credential,\n aiProvider,\n },\n },\n ) as unknown as ConnectedCredentialDb);\n}\n\nfunction credentialRowFromRecord(record: ConnectCredentialRecord): Record<string, unknown> {\n return {\n id: record.id,\n provider: aiProviderResource.buildId({ id: normalizeProvider(record.provider) }),\n service: 'ai',\n authMode: record.authMode,\n status: record.status,\n storageMode: record.storageMode,\n secretPayload: record.secretPayload,\n keyVersion: String(record.version ?? 1),\n scopes: record.scopes ?? [],\n expiresAt: record.expiresAt,\n accountLabel: record.accountLabel,\n label: record.accountLabel,\n reauthRequired: record.reauthRequired ?? false,\n lastRefreshAt: new Date(),\n };\n}\n\nfunction recordFromCredentialRow(row: Record<string, unknown>, owner: string): ConnectCredentialRecord {\n const storageMode = stringFrom(row.storageMode) === PLAINTEXT_CREDENTIAL_STORAGE_MODE\n ? PLAINTEXT_CREDENTIAL_STORAGE_MODE\n : stringFrom(row.storageMode);\n const secretPayload = typeof row.secretPayload === 'string' ? row.secretPayload : '';\n decodePlaintextCredential({\n storageMode,\n secretPayload,\n encryptedSecret: row.encryptedSecret,\n wrappedDataKey: row.wrappedDataKey,\n encryptionAlgorithm: row.encryptionAlgorithm,\n });\n const id = stringFrom(row.id);\n const provider = providerFromRelation(stringFrom(row.provider))\n || providerFromCredentialId(id);\n const deployment = deploymentFromCredentialId(id);\n const credentialIri = stringFrom(row.credentialIri)\n || aiRuntimeRepository.credentialIri(owner, { deployment, provider });\n return {\n id,\n credentialIri,\n webId: owner,\n provider,\n deployment,\n authMode: stringFrom(row.authMode) === 'deviceCodeOAuth' ? 'deviceCodeOAuth' : 'apiKey',\n storageMode: PLAINTEXT_CREDENTIAL_STORAGE_MODE,\n secretPayload,\n status: stringFrom(row.status) === 'revoked' ? 'revoked' : 'active',\n accountLabel: stringFrom(row.accountLabel) || stringFrom(row.label) || undefined,\n expiresAt: dateFrom(row.expiresAt),\n scopes: Array.isArray(row.scopes) ? row.scopes.map(String) : undefined,\n version: versionFromRow(row),\n reauthRequired: row.reauthRequired === true || row.reauthRequired === 'true',\n metadata: metadataFromRow(row),\n };\n}\n\nfunction providerFromRelation(value: string): string | undefined {\n if (!value) {\n return undefined;\n }\n const withoutFragment = value.split('#', 1)[0] ?? value;\n const fileName = withoutFragment.split('/').filter(Boolean).at(-1) ?? withoutFragment;\n const provider = fileName.replace(/\\.ttl$/u, '');\n return provider ? normalizeProvider(provider) : undefined;\n}\n\nfunction isPodResourceNotFound(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n return /\\b404\\b|not found/i.test(error.message);\n}\n\nfunction metadataFromRow(row: Record<string, unknown>): Record<string, unknown> | undefined {\n const value = row.metadata;\n if (!value) {\n return undefined;\n }\n if (typeof value === 'object' && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n if (typeof value === 'string') {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : undefined;\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\nfunction modelsFromMetadata(metadata: Record<string, unknown> | undefined): string[] | undefined {\n const value = metadata?.models;\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : undefined;\n}\n\nfunction defaultModelFromMetadata(metadata: Record<string, unknown> | undefined): string | undefined {\n const value = metadata?.defaultModel;\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction priorityFromMetadata(metadata: Record<string, unknown> | undefined): number | undefined {\n const value = metadata?.priority;\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction runtimeCredentialFromMetadata(metadata: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n const value = metadata?.runtimeCredential;\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined;\n}\n\nfunction versionFromRow(row: Record<string, unknown>): number {\n const value = row.keyVersion;\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string' && value.trim()) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : 0;\n }\n return 0;\n}\n\nfunction providerFromCredentialId(id: string): string {\n const match = /\\/([^/#]+)\\.ttl#/u.exec(id);\n return match?.[1] ?? '';\n}\n\nfunction deploymentFromCredentialId(id: string): GatewayDeployment {\n return id.includes('#cloud-') ? 'cloud' : 'local';\n}\n\nfunction dateFrom(value: unknown): Date | undefined {\n if (value instanceof Date) {\n return value;\n }\n if (typeof value === 'string' || typeof value === 'number') {\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n }\n return undefined;\n}\n\nfunction signAttempt(\n attempt: Pick<ConnectAttempt, 'id' | 'provider' | 'deployment' | 'webId' | 'mode' | 'state' | 'expiresAt'>,\n secret: string,\n): string {\n return createHmac('sha256', secret)\n .update(JSON.stringify({\n id: attempt.id,\n provider: attempt.provider,\n deployment: attempt.deployment,\n webId: attempt.webId,\n mode: attempt.mode,\n state: attempt.state,\n expiresAt: attempt.expiresAt.toISOString(),\n }))\n .digest('base64url');\n}\n\nfunction signatureMatches(actual: string, expected: string): boolean {\n const actualBuffer = Buffer.from(actual, 'utf8');\n const expectedBuffer = Buffer.from(expected, 'utf8');\n return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);\n}\n\nfunction codeChallenge(verifier: string): string {\n return createHash('sha256').update(verifier).digest('base64url');\n}\n\n\nfunction cloneAttempt(attempt: ConnectAttempt): ConnectAttempt {\n return {\n ...attempt,\n expiresAt: new Date(attempt.expiresAt),\n consumedAt: attempt.consumedAt ? new Date(attempt.consumedAt) : undefined,\n nextPollAt: attempt.nextPollAt ? new Date(attempt.nextPollAt) : undefined,\n pollClaimedAt: attempt.pollClaimedAt ? new Date(attempt.pollClaimedAt) : undefined,\n };\n}\n\nfunction normalizeProvider(provider: string): string {\n return provider.trim().toLowerCase();\n}\n\nasync function safeJson(response: Response): Promise<Record<string, unknown>> {\n const text = await response.text();\n if (!text) {\n if (response.ok) {\n throw new Error('Provider returned an empty JSON response');\n }\n return {};\n }\n try {\n const parsed = JSON.parse(text);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n if (response.ok) {\n throw new Error('Provider returned a non-object JSON response');\n }\n return {};\n }\n return parsed as Record<string, unknown>;\n } catch {\n if (response.ok) {\n throw new Error('Provider returned invalid JSON');\n }\n return {};\n }\n}\n\nfunction stringFrom(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction numberFrom(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback;\n}\n\nfunction expiresAtFrom(expiresIn: unknown, now: Date): Date | undefined {\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn)) {\n return undefined;\n }\n return new Date(now.getTime() + expiresIn * 1000);\n}\n\nfunction safeProviderError(body: Record<string, unknown>): string {\n const code = stringFrom(body.error);\n if (SAFE_PROVIDER_ERROR_CODES.has(code)) {\n return code;\n }\n if (!code) {\n return 'provider_error';\n }\n if (code.endsWith('_error')) {\n return 'provider_error';\n }\n return 'provider_error';\n}\n\nconst SAFE_PROVIDER_ERROR_CODES = new Set([\n 'authorization_pending',\n 'slow_down',\n 'expired_token',\n 'access_denied',\n 'invalid_grant',\n 'invalid_client',\n]);\n\nfunction pendingResult(\n input: PollDeviceInput,\n status: ConnectAttemptStatus,\n intervalSeconds?: number,\n): ConnectBeginResult {\n return {\n mode: 'deviceCodeOAuth',\n status,\n provider: 'kimi',\n deployment: input.deployment,\n attemptId: input.attemptId,\n intervalSeconds,\n };\n}\n\nfunction assertKimiEndpoint(endpoint: string, pathname: string): void {\n const url = new URL(endpoint);\n if (\n url.origin !== 'https://auth.kimi.com'\n || url.pathname !== pathname\n || url.search\n || url.hash\n || url.username\n || url.password\n ) {\n throw new Error('Kimi Connect endpoint is not allowlisted');\n }\n}\n\nfunction requireStringField(body: Record<string, unknown>, field: string): void {\n if (typeof body[field] !== 'string' || !(body[field] as string).trim()) {\n throw new Error(`Provider response missing required field: ${field}`);\n }\n}\n\nfunction isVersionConflict(error: unknown): boolean {\n return error instanceof Error && /version_conflict|credential_version_conflict/u.test(error.message);\n}\n\nfunction decodeJwtSubject(idToken: string): string | undefined {\n const payload = idToken.split('.')[1];\n if (!payload) {\n return undefined;\n }\n try {\n const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));\n return typeof decoded.sub === 'string' ? decoded.sub : undefined;\n } catch {\n return undefined;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/api/ai-gateway/connect/index.ts"],"names":[],"mappings":";;;AAAA,6CAAsG;AACtG,gEAAuE;AACvE,kDAI+B;AAE/B,0FAKmD;AAGnD,oEAA6E;AAiK7E,MAAa,gCAAgC;IAO3C,YAAmB,UAAmD,EAAE;QACtE,IAAI,CAAC,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC;QACnD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW;eACjC,+CAA4B,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACjE,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,kCAAkC,CAAC;QACzE,IAAI,CAAC,kBAAkB,GAAG,IAAA,qBAAK,EAAC,2BAAkB,EAAE,oBAAoB,CAAC,CAAC;QAC1E,IAAI,CAAC,kBAAkB,GAAG,IAAA,qBAAK,EAAC,2BAAkB,EAAE,oBAAoB,CAAC,CAAC;IAC5E,CAAC;IAEM,KAAK,CAAC,aAAa,CA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esContent":["import { createHash, createHmac, randomBytes as nodeRandomBytes, timingSafeEqual } from 'node:crypto';\nimport { alias, and, drizzle, eq } from '@undefineds.co/drizzle-solid';\nimport {\n aiProviderResource,\n aiRuntimeRepository,\n credentialResource,\n} from '@undefineds.co/models';\nimport type { ProviderSecret } from '../credentials/CredentialVault';\nimport {\n decodePlaintextCredential,\n encodePlaintextCredential,\n PLAINTEXT_CREDENTIAL_STORAGE_MODE,\n UnsupportedCredentialStorageModeError,\n} from '../credentials/PlaintextCredentialPayload';\nimport type { GatewayDeployment } from '../auth/InvocationTokenCodec';\nimport type { ProviderRegistry } from '../providers/ProviderRegistry';\nimport { DEFAULT_PROVIDER_DESCRIPTORS } from '../providers/ProviderRegistry';\nimport type { AuthContext } from '../../auth/AuthContext';\nimport type { InternalPodAccessTokenProvider } from '../pod/HostedPodDataAccess';\n\nexport type ConnectMode = 'browserAssistedApiKey' | 'deviceCodeOAuth' | 'connectUnsupported';\nexport type ConnectAttemptStatus =\n | 'pending'\n | 'authorization_pending'\n | 'slow_down'\n | 'completed'\n | 'expired'\n | 'unsupported';\n\nexport interface ConnectBeginInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n requestedMode: ConnectMode;\n expectedCredentialVersion?: number;\n auth?: AuthContext;\n}\n\nexport interface ConnectBeginResult {\n mode: ConnectMode;\n status: ConnectAttemptStatus;\n provider: string;\n deployment: GatewayDeployment;\n attemptId?: string;\n state?: string;\n signature?: string;\n expiresAt?: string;\n authorizationUrl?: string;\n pkceChallenge?: string;\n deviceCode?: string;\n userCode?: string;\n verificationUri?: string;\n verificationUriComplete?: string;\n intervalSeconds?: number;\n apiKeyManagementSupported?: boolean;\n credentialId?: string;\n message?: string;\n}\n\nexport interface CompleteApiKeyInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n attemptId: string;\n state: string;\n signature: string;\n apiKey: string;\n accountLabel?: string;\n auth?: AuthContext;\n}\n\nexport interface PollDeviceInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n attemptId: string;\n state: string;\n signature: string;\n auth?: AuthContext;\n}\n\nexport interface RefreshInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n auth?: AuthContext;\n}\n\nexport interface DisconnectInput {\n webId: string;\n deployment: GatewayDeployment;\n provider: string;\n auth?: AuthContext;\n}\n\nexport interface ConnectCredentialRecord {\n id: string;\n credentialIri: string;\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n authMode: 'apiKey' | 'deviceCodeOAuth';\n storageMode: 'plaintext-v1';\n secretPayload: string;\n status: 'active' | 'revoked';\n accountLabel?: string;\n expiresAt?: Date;\n scopes?: string[];\n expectedVersion?: number;\n version?: number;\n reauthRequired?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nexport interface PodCredentialRepository {\n getCredential?(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined>;\n getActiveCredential(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined>;\n upsertConnectedCredential(\n record: ConnectCredentialRecord,\n context?: { auth?: AuthContext },\n ): Promise<ConnectCredentialRecord>;\n markReauthRequired(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n reason: string;\n expectedVersion?: number;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined>;\n disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined>;\n}\n\ntype ConnectedCredentialDb = {\n init?: (...resources: unknown[]) => Promise<void>;\n insert(resource: typeof credentialResource): {\n values(value: unknown): { execute(): Promise<unknown[]> };\n };\n select(): {\n from(resource: typeof credentialResource): {\n where(condition: unknown): { execute(): Promise<Record<string, unknown>[]> };\n };\n };\n findById<TRow>(resource: typeof credentialResource, id: string): Promise<TRow | null>;\n deleteById(resource: typeof credentialResource, id: string): Promise<boolean>;\n updateById<TRow>(resource: typeof credentialResource, id: string, patch: unknown): Promise<TRow | null>;\n update(resource: typeof credentialResource): {\n set(patch: unknown): {\n where(condition: unknown): {\n returning(): { execute(): Promise<Record<string, unknown>[]> };\n };\n };\n };\n};\n\nexport interface PodConnectedCredentialRepositoryOptions {\n internalPodAccess?: InternalPodAccessTokenProvider;\n providerIds?: string[];\n dbFactory?: (input: {\n owner: string;\n podUrl: string;\n auth?: AuthContext;\n fetch: typeof fetch;\n credential?: typeof credentialResource;\n aiProvider?: typeof aiProviderResource;\n }) => Promise<ConnectedCredentialDb>;\n}\n\nexport class PodConnectedCredentialRepository implements PodCredentialRepository {\n private readonly dbFactory: NonNullable<PodConnectedCredentialRepositoryOptions['dbFactory']>;\n private readonly internalPodAccess?: InternalPodAccessTokenProvider;\n private readonly providerIds: string[];\n private readonly credentialTemplate: typeof credentialResource;\n private readonly aiProviderTemplate: typeof aiProviderResource;\n\n public constructor(options: PodConnectedCredentialRepositoryOptions = {}) {\n this.internalPodAccess = options.internalPodAccess;\n this.providerIds = options.providerIds\n ?? DEFAULT_PROVIDER_DESCRIPTORS.map((provider) => provider.id);\n this.dbFactory = options.dbFactory ?? createDefaultConnectedCredentialDb;\n this.credentialTemplate = alias(credentialResource, 'credentialTemplate');\n this.aiProviderTemplate = alias(aiProviderResource, 'aiProviderTemplate');\n }\n\n public async getCredential(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const id = aiRuntimeRepository.credentialId(input);\n const row = await db.findById<Record<string, unknown>>(credential, id);\n const record = row ? recordFromCredentialRow(row, input.webId) : undefined;\n if (!record) {\n return undefined;\n }\n return record;\n }\n\n public async getActiveCredential(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined> {\n const record = await this.getCredential(input);\n return record?.status === 'active' && !record.reauthRequired ? record : undefined;\n }\n\n public async listCredentials(input: {\n webId: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<Array<{\n id: string;\n credentialIri: string;\n provider: string;\n authMode: 'apiKey' | 'deviceCodeOAuth';\n enabled: boolean;\n priority?: number;\n models?: string[];\n defaultModel?: string;\n health?: 'healthy' | 'reauthRequired' | 'disabled' | 'error';\n quota?: { status: 'available' | 'unsupported' | 'exhausted' | 'error' };\n storageMode: 'plaintext-v1';\n secretPayload: string;\n version?: number;\n runtimeCredential?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n }>> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const rows = (await Promise.all(\n this.providerIds.map(async (provider) => {\n try {\n return await db.findById<Record<string, unknown>>(\n credential,\n aiRuntimeRepository.credentialId({ deployment: input.deployment, provider }),\n );\n } catch (error) {\n if (isPodResourceNotFound(error)) {\n return null;\n }\n throw error;\n }\n }),\n )).filter((row): row is Record<string, unknown> => row !== null);\n return rows\n .flatMap((row) => {\n try {\n return [recordFromCredentialRow(row, input.webId)];\n } catch (error) {\n if (error instanceof UnsupportedCredentialStorageModeError) {\n return [];\n }\n throw error;\n }\n })\n .filter((record) => record.webId === input.webId)\n .filter((record) => record.deployment === input.deployment)\n .filter((record) => record.status === 'active')\n .map((record) => ({\n id: record.id,\n credentialIri: record.credentialIri,\n provider: record.provider,\n authMode: record.authMode,\n enabled: !record.reauthRequired,\n models: modelsFromMetadata(record.metadata),\n defaultModel: defaultModelFromMetadata(record.metadata),\n priority: priorityFromMetadata(record.metadata),\n health: record.reauthRequired ? 'reauthRequired' : 'healthy',\n quota: { status: 'available' },\n storageMode: record.storageMode,\n secretPayload: record.secretPayload,\n version: record.version,\n runtimeCredential: runtimeCredentialFromMetadata(record.metadata),\n metadata: record.metadata,\n }));\n }\n\n public async upsertConnectedCredential(\n record: ConnectCredentialRecord,\n context?: { auth?: AuthContext },\n ): Promise<ConnectCredentialRecord> {\n const { db, credential } = await this.dbForOwner(record.webId, context?.auth);\n const existing = await db.findById<Record<string, unknown>>(credential, record.id);\n const existingVersion = existing ? versionFromRow(existing) : 0;\n const replacesUnsupportedRecord = Boolean(existing)\n && stringFrom(existing?.storageMode) !== PLAINTEXT_CREDENTIAL_STORAGE_MODE;\n if (!replacesUnsupportedRecord\n && record.expectedVersion !== undefined\n && record.expectedVersion !== existingVersion) {\n throw new Error('credential_version_conflict');\n }\n const nextVersion = existingVersion + 1;\n const row = credentialRowFromRecord({\n ...record,\n version: nextVersion,\n });\n if (existing) {\n try {\n const deleted = await db.deleteById(credential, record.id);\n if (!deleted) {\n throw new Error('exact credential resource was not deleted');\n }\n } catch (error) {\n throw credentialPersistenceError('replace-delete', error);\n }\n try {\n await db.insert(credential).values(row).execute();\n } catch (error) {\n try {\n await db.insert(credential).values(existing).execute();\n } catch (rollbackError) {\n throw credentialPersistenceError('replace-insert-rollback', rollbackError);\n }\n throw credentialPersistenceError('replace-insert', error);\n }\n return recordFromCredentialRow(row, record.webId);\n }\n try {\n await db.insert(credential).values(row).execute();\n } catch (error) {\n throw credentialPersistenceError('insert', error);\n }\n return recordFromCredentialRow(row, record.webId);\n }\n\n public async markReauthRequired(input: {\n webId: string;\n provider: string;\n deployment: GatewayDeployment;\n reason: string;\n expectedVersion?: number;\n auth?: AuthContext;\n }): Promise<ConnectCredentialRecord | undefined> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const id = aiRuntimeRepository.credentialId(input);\n const existing = await db.findById<Record<string, unknown>>(credential, id);\n if (!existing) {\n return undefined;\n }\n const existingVersion = versionFromRow(existing);\n if (input.expectedVersion !== undefined && input.expectedVersion !== existingVersion) {\n throw new Error('credential_version_conflict');\n }\n const updated = await db.updateById<Record<string, unknown>>(credential, id, {\n reauthRequired: true,\n status: 'active',\n keyVersion: String(existingVersion + 1),\n });\n return updated ? recordFromCredentialRow(updated, input.webId) : undefined;\n }\n\n public async disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const id = aiRuntimeRepository.credentialId(input);\n const existing = await db.findById<Record<string, unknown>>(credential, id);\n if (!existing) {\n return undefined;\n }\n const updated = await db.updateById<Record<string, unknown>>(credential, id, {\n status: 'revoked',\n keyVersion: String(versionFromRow(existing) + 1),\n });\n return updated ? recordFromCredentialRow(updated, input.webId) : undefined;\n }\n\n private async dbForOwner(owner: string, auth?: AuthContext): Promise<{\n db: ConnectedCredentialDb;\n credential: typeof credentialResource;\n }> {\n const trustedFetch = await this.resolveTrustedFetch(owner, auth);\n const credential = alias(this.credentialTemplate, 'credential');\n const aiProvider = alias(this.aiProviderTemplate, 'aiProvider');\n const podUrl = podUrlFromHostedWebId(owner);\n const db = await this.dbFactory({ owner, podUrl, auth, fetch: trustedFetch, credential, aiProvider });\n await db.init?.(credential, aiProvider);\n return { db, credential };\n }\n\n private async resolveTrustedFetch(owner: string, auth?: AuthContext): Promise<typeof fetch> {\n const trustedFetch = await this.internalPodAccess?.getTrustedFetch(owner, auth);\n if (!trustedFetch) {\n throw new Error('AI Connection service identity is not configured');\n }\n return async (input, init) => {\n const response = await trustedFetch(input, init);\n if (response.status === 403) {\n throw new Error('service_access_missing');\n }\n return response;\n };\n }\n}\n\nexport interface ProviderConnectAdapter {\n readonly provider: string;\n begin(input: ConnectBeginInput): Promise<ConnectBeginResult>;\n status?(input: PollDeviceInput): Promise<ConnectBeginResult>;\n completeApiKey?(input: CompleteApiKeyInput): Promise<ConnectBeginResult>;\n pollDevice?(input: PollDeviceInput): Promise<ConnectBeginResult>;\n refresh?(\n input: RefreshInput,\n current: ConnectCredentialRecord,\n secret: ProviderSecret,\n ): Promise<ConnectCredentialRecord | undefined>;\n disconnect?(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined>;\n}\n\ninterface ConnectAttempt {\n id: string;\n provider: string;\n deployment: GatewayDeployment;\n webId: string;\n mode: ConnectMode;\n state: string;\n signature: string;\n expiresAt: Date;\n consumedAt?: Date;\n expectedCredentialVersion?: number;\n codeVerifier?: string;\n deviceCode?: string;\n intervalSeconds?: number;\n currentPollIntervalSeconds?: number;\n nextPollAt?: Date;\n pollClaimedAt?: Date;\n lastPollStatus?: ConnectAttemptStatus;\n}\n\ninterface PollClaimResult {\n attempt: ConnectAttempt;\n claimed: boolean;\n}\n\nexport class InMemoryConnectAttemptStore {\n private readonly attempts = new Map<string, ConnectAttempt>();\n private readonly maxAttempts = 1_000;\n\n public async create(attempt: ConnectAttempt): Promise<ConnectAttempt> {\n this.pruneExpired(new Date());\n this.attempts.set(attempt.id, cloneAttempt(attempt));\n this.pruneBounded();\n return cloneAttempt(attempt);\n }\n\n public async get(id: string, now?: Date): Promise<ConnectAttempt | undefined> {\n this.pruneExpired(now ?? new Date(), id);\n const attempt = this.attempts.get(id);\n if (attempt && now && attempt.expiresAt.getTime() <= now.getTime()) {\n this.attempts.delete(id);\n }\n return attempt ? cloneAttempt(attempt) : undefined;\n }\n\n public async consume(id: string, now: Date): Promise<ConnectAttempt> {\n this.pruneExpired(now, id);\n const attempt = this.attempts.get(id);\n if (!attempt) {\n throw new Error('Connect attempt not found');\n }\n if (attempt.consumedAt) {\n throw new Error('Connect attempt already consumed');\n }\n if (attempt.expiresAt.getTime() <= now.getTime()) {\n this.attempts.delete(id);\n throw new Error('Connect attempt expired');\n }\n attempt.consumedAt = new Date(now);\n return cloneAttempt(attempt);\n }\n\n public async claimPoll(id: string, now: Date): Promise<PollClaimResult> {\n this.pruneExpired(now, id);\n const attempt = this.attempts.get(id);\n if (!attempt) {\n throw new Error('Connect attempt not found');\n }\n if (attempt.consumedAt) {\n throw new Error('Connect attempt already consumed');\n }\n if (attempt.expiresAt.getTime() <= now.getTime()) {\n this.attempts.delete(id);\n throw new Error('Connect attempt expired');\n }\n if (attempt.nextPollAt && attempt.nextPollAt.getTime() > now.getTime()) {\n return { attempt: cloneAttempt(attempt), claimed: false };\n }\n if (attempt.pollClaimedAt) {\n return { attempt: cloneAttempt(attempt), claimed: false };\n }\n attempt.pollClaimedAt = new Date(now);\n return { attempt: cloneAttempt(attempt), claimed: true };\n }\n\n public async updatePollSchedule(\n id: string,\n patch: {\n intervalSeconds: number;\n nextPollAt: Date;\n lastPollStatus: ConnectAttemptStatus;\n },\n ): Promise<ConnectAttempt | undefined> {\n const attempt = this.attempts.get(id);\n if (!attempt || attempt.consumedAt) {\n return undefined;\n }\n attempt.intervalSeconds = patch.intervalSeconds;\n attempt.currentPollIntervalSeconds = patch.intervalSeconds;\n attempt.nextPollAt = new Date(patch.nextPollAt);\n attempt.lastPollStatus = patch.lastPollStatus;\n attempt.pollClaimedAt = undefined;\n return cloneAttempt(attempt);\n }\n\n public async releasePollClaim(id: string): Promise<void> {\n const attempt = this.attempts.get(id);\n if (attempt) {\n attempt.pollClaimedAt = undefined;\n }\n }\n\n private pruneExpired(now: Date, exceptId?: string): void {\n for (const [id, attempt] of this.attempts) {\n if (id !== exceptId && attempt.expiresAt.getTime() <= now.getTime()) {\n this.attempts.delete(id);\n }\n }\n }\n\n private pruneBounded(): void {\n while (this.attempts.size > this.maxAttempts) {\n const oldest = this.attempts.keys().next().value;\n if (typeof oldest !== 'string') {\n return;\n }\n this.attempts.delete(oldest);\n }\n }\n}\n\nexport interface BrowserAssistedApiKeyConnectAdapterOptions {\n provider: string;\n consoleUrl: string;\n attempts: InMemoryConnectAttemptStore;\n credentialRepository: PodCredentialRepository;\n deployment: GatewayDeployment;\n now?: () => Date;\n randomBytes?: (bytes: number) => Buffer;\n signingSecret: string;\n}\n\nexport class BrowserAssistedApiKeyConnectAdapter implements ProviderConnectAdapter {\n public readonly provider: string;\n private readonly consoleUrl: string;\n protected readonly attempts: InMemoryConnectAttemptStore;\n protected readonly credentialRepository: PodCredentialRepository;\n protected readonly deployment: GatewayDeployment;\n protected readonly now: () => Date;\n protected readonly randomBytes: (bytes: number) => Buffer;\n private readonly signingSecret: string;\n\n public constructor(options: BrowserAssistedApiKeyConnectAdapterOptions) {\n this.provider = normalizeProvider(options.provider);\n this.consoleUrl = options.consoleUrl;\n this.attempts = options.attempts;\n this.credentialRepository = options.credentialRepository;\n this.deployment = options.deployment;\n this.now = options.now ?? (() => new Date());\n this.randomBytes = options.randomBytes ?? nodeRandomBytes;\n this.signingSecret = options.signingSecret;\n }\n\n public async begin(input: ConnectBeginInput): Promise<ConnectBeginResult> {\n this.assertInput(input, 'browserAssistedApiKey');\n const now = this.now();\n const expiresAt = new Date(now.getTime() + 5 * 60 * 1000);\n const attempt = await this.createAttempt(input, expiresAt);\n const url = new URL(this.consoleUrl);\n url.searchParams.set('xpod_connect_attempt', attempt.id);\n url.searchParams.set('xpod_provider', this.provider);\n\n return {\n mode: 'browserAssistedApiKey',\n status: 'pending',\n provider: this.provider,\n deployment: this.deployment,\n attemptId: attempt.id,\n state: attempt.state,\n signature: attempt.signature,\n expiresAt: expiresAt.toISOString(),\n authorizationUrl: url.toString(),\n };\n }\n\n public async completeApiKey(input: CompleteApiKeyInput): Promise<ConnectBeginResult> {\n if (!input.apiKey.trim()) {\n throw new Error('API key is required');\n }\n const attempt = await this.loadConsumableAttempt(input, 'browserAssistedApiKey');\n const consumed = await this.attempts.consume(input.attemptId, this.now());\n const credentialIri = aiRuntimeRepository.credentialIri(input.webId, {\n deployment: input.deployment,\n provider: this.provider,\n });\n const secretPayload = encodePlaintextCredential({ type: 'apiKey', apiKey: input.apiKey });\n const record = await this.credentialRepository.upsertConnectedCredential({\n id: aiRuntimeRepository.credentialId({ deployment: input.deployment, provider: this.provider }),\n credentialIri,\n webId: input.webId,\n provider: this.provider,\n deployment: input.deployment,\n authMode: 'apiKey',\n storageMode: PLAINTEXT_CREDENTIAL_STORAGE_MODE,\n secretPayload,\n status: 'active',\n accountLabel: input.accountLabel,\n expectedVersion: consumed.expectedCredentialVersion,\n }, { auth: input.auth });\n\n return {\n mode: 'browserAssistedApiKey',\n status: 'completed',\n provider: this.provider,\n deployment: input.deployment,\n attemptId: attempt.id,\n credentialId: record.id,\n };\n }\n\n public async status(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const attempt = await this.loadAttemptForStatus(input, 'browserAssistedApiKey');\n return {\n mode: attempt.mode,\n status: this.statusForAttempt(attempt),\n provider: this.provider,\n deployment: input.deployment,\n attemptId: attempt.id,\n expiresAt: attempt.expiresAt.toISOString(),\n };\n }\n\n public async disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined> {\n return this.credentialRepository.disconnect({\n webId: input.webId,\n provider: this.provider,\n deployment: input.deployment,\n auth: input.auth,\n });\n }\n\n protected async createAttempt(input: ConnectBeginInput, expiresAt: Date, extra: Partial<ConnectAttempt> = {}): Promise<ConnectAttempt> {\n const attemptWithoutSignature: Omit<ConnectAttempt, 'signature'> = {\n id: token(this.randomBytes),\n provider: this.provider,\n deployment: input.deployment,\n webId: input.webId,\n mode: input.requestedMode,\n state: token(this.randomBytes),\n expiresAt,\n expectedCredentialVersion: input.expectedCredentialVersion,\n ...extra,\n };\n const signature = signAttempt(attemptWithoutSignature, this.signingSecret);\n return this.attempts.create({ ...attemptWithoutSignature, signature });\n }\n\n protected async loadAttemptForStatus(input: PollDeviceInput, mode: ConnectMode): Promise<ConnectAttempt> {\n const attempt = await this.attempts.get(input.attemptId, this.now());\n if (!attempt) {\n throw new Error('Connect attempt not found');\n }\n if (attempt.webId !== input.webId) {\n throw new Error('Connect attempt is bound to a different WebID');\n }\n if (attempt.deployment !== input.deployment) {\n throw new Error('Connect attempt is bound to a different deployment');\n }\n if (attempt.provider !== normalizeProvider(input.provider)) {\n throw new Error('Connect attempt is bound to a different provider');\n }\n if (attempt.mode !== mode) {\n throw new Error('Connect attempt mode mismatch');\n }\n if (attempt.state !== input.state) {\n throw new Error('Invalid Connect attempt state');\n }\n if (!signatureMatches(input.signature, signAttempt(attempt, this.signingSecret))) {\n throw new Error('Invalid Connect attempt signature');\n }\n return attempt;\n }\n\n protected async loadConsumableAttempt(input: PollDeviceInput, mode: ConnectMode): Promise<ConnectAttempt> {\n const attempt = await this.loadAttemptForStatus(input, mode);\n if (attempt.expiresAt.getTime() <= this.now().getTime()) {\n throw new Error('Connect attempt expired');\n }\n if (attempt.consumedAt) {\n throw new Error('Connect attempt already consumed');\n }\n return attempt;\n }\n\n protected statusForAttempt(attempt: ConnectAttempt): ConnectAttemptStatus {\n if (attempt.expiresAt.getTime() <= this.now().getTime()) {\n return 'expired';\n }\n return attempt.consumedAt ? 'completed' : 'pending';\n }\n\n protected assertInput(input: ConnectBeginInput, mode: ConnectMode): void {\n if (normalizeProvider(input.provider) !== this.provider) {\n throw new Error('Connect provider mismatch');\n }\n if (input.deployment !== this.deployment) {\n throw new Error('Connect deployment mismatch');\n }\n if (input.requestedMode !== mode) {\n throw new Error('Unsupported Connect mode');\n }\n if (!input.webId) {\n throw new Error('Connect WebID is required');\n }\n }\n}\n\nexport interface KimiDeviceCodeConnectAdapterOptions extends Omit<BrowserAssistedApiKeyConnectAdapterOptions, 'provider' | 'consoleUrl'> {\n fetch?: typeof fetch;\n clientId: string;\n deviceAuthorizationEndpoint?: string;\n tokenEndpoint?: string;\n}\n\nexport class KimiDeviceCodeConnectAdapter extends BrowserAssistedApiKeyConnectAdapter {\n private readonly fetchImpl: typeof fetch;\n private readonly clientId: string;\n private readonly deviceAuthorizationEndpoint: string;\n private readonly tokenEndpoint: string;\n\n public constructor(options: KimiDeviceCodeConnectAdapterOptions) {\n super({\n ...options,\n provider: 'kimi',\n consoleUrl: 'https://kimi.moonshot.cn/device',\n });\n this.fetchImpl = options.fetch ?? fetch;\n this.clientId = options.clientId;\n this.deviceAuthorizationEndpoint = options.deviceAuthorizationEndpoint ?? 'https://auth.kimi.com/api/oauth/device_authorization';\n this.tokenEndpoint = options.tokenEndpoint ?? 'https://auth.kimi.com/api/oauth/token';\n assertKimiEndpoint(this.deviceAuthorizationEndpoint, '/api/oauth/device_authorization');\n assertKimiEndpoint(this.tokenEndpoint, '/api/oauth/token');\n }\n\n public override async begin(input: ConnectBeginInput): Promise<ConnectBeginResult> {\n this.assertInput(input, 'deviceCodeOAuth');\n const now = this.now();\n const verifier = token(this.randomBytes);\n const challenge = codeChallenge(verifier);\n const response = await this.fetchImpl(this.deviceAuthorizationEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n client_id: this.clientId,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n }),\n });\n const body = await safeJson(response);\n if (!response.ok) {\n throw new Error(`Kimi device authorization failed: ${safeProviderError(body)}`);\n }\n requireStringField(body, 'device_code');\n requireStringField(body, 'user_code');\n requireStringField(body, 'verification_uri_complete');\n const expiresIn = numberFrom(body.expires_in, 300);\n const attempt = await this.createAttempt(input, new Date(now.getTime() + expiresIn * 1000), {\n mode: 'deviceCodeOAuth',\n codeVerifier: verifier,\n deviceCode: stringFrom(body.device_code),\n intervalSeconds: numberFrom(body.interval, 5),\n currentPollIntervalSeconds: numberFrom(body.interval, 5),\n nextPollAt: new Date(now.getTime() + numberFrom(body.interval, 5) * 1000),\n });\n return {\n mode: 'deviceCodeOAuth',\n status: 'pending',\n provider: 'kimi',\n deployment: input.deployment,\n attemptId: attempt.id,\n state: attempt.state,\n signature: attempt.signature,\n expiresAt: attempt.expiresAt.toISOString(),\n pkceChallenge: challenge,\n deviceCode: attempt.deviceCode,\n userCode: stringFrom(body.user_code),\n verificationUri: stringFrom(body.verification_uri),\n verificationUriComplete: stringFrom(body.verification_uri_complete),\n intervalSeconds: attempt.intervalSeconds,\n };\n }\n\n public async pollDevice(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const attempt = await this.loadConsumableAttempt(input, 'deviceCodeOAuth');\n const now = this.nowForConsume();\n const claim = await this.attempts.claimPoll(input.attemptId, now);\n if (!claim.claimed) {\n return pendingResult(\n input,\n claim.attempt.lastPollStatus === 'slow_down' ? 'slow_down' : 'authorization_pending',\n claim.attempt.currentPollIntervalSeconds ?? claim.attempt.intervalSeconds,\n );\n }\n try {\n const response = await this.fetchImpl(this.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: attempt.deviceCode ?? '',\n client_id: this.clientId,\n code_verifier: attempt.codeVerifier ?? '',\n }),\n });\n const body = await safeJson(response);\n if (!response.ok) {\n if (body.error === 'authorization_pending' || body.error === 'slow_down') {\n const status = body.error;\n const intervalSeconds = status === 'slow_down'\n ? (attempt.currentPollIntervalSeconds ?? attempt.intervalSeconds ?? 5) + 5\n : (attempt.currentPollIntervalSeconds ?? attempt.intervalSeconds ?? 5);\n await this.attempts.updatePollSchedule(input.attemptId, {\n intervalSeconds,\n nextPollAt: new Date(now.getTime() + intervalSeconds * 1000),\n lastPollStatus: status,\n });\n return pendingResult(input, status, intervalSeconds);\n }\n if (body.error === 'expired_token') {\n await this.attempts.consume(input.attemptId, this.nowForConsume());\n return pendingResult(input, 'expired');\n }\n throw new Error(`Kimi device token failed: ${safeProviderError(body)}`);\n }\n await this.attempts.consume(input.attemptId, this.nowForConsume());\n requireStringField(body, 'access_token');\n requireStringField(body, 'refresh_token');\n const record = await this.storeOAuthCredential(input, body, attempt.expectedCredentialVersion);\n return {\n mode: 'deviceCodeOAuth',\n status: 'completed',\n provider: 'kimi',\n deployment: input.deployment,\n attemptId: input.attemptId,\n credentialId: record.id,\n };\n } catch (error) {\n await this.attempts.releasePollClaim(input.attemptId);\n throw error;\n }\n }\n\n public override async status(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const attempt = await this.loadAttemptForStatus(input, 'deviceCodeOAuth');\n return {\n mode: 'deviceCodeOAuth',\n status: this.statusForAttempt(attempt),\n provider: 'kimi',\n deployment: input.deployment,\n attemptId: attempt.id,\n expiresAt: attempt.expiresAt.toISOString(),\n deviceCode: attempt.deviceCode,\n intervalSeconds: attempt.currentPollIntervalSeconds ?? attempt.intervalSeconds,\n };\n }\n\n public async refresh(\n input: RefreshInput,\n current: ConnectCredentialRecord,\n secret: ProviderSecret,\n ): Promise<ConnectCredentialRecord | undefined> {\n const refreshToken = stringFrom(secret.refreshToken);\n if (!refreshToken) {\n return this.credentialRepository.markReauthRequired({\n webId: input.webId,\n provider: 'kimi',\n deployment: input.deployment,\n reason: 'missing_refresh_token',\n expectedVersion: current.version,\n auth: input.auth,\n });\n }\n const response = await this.fetchImpl(this.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: this.clientId,\n }),\n });\n const body = await safeJson(response);\n if (!response.ok) {\n return this.credentialRepository.markReauthRequired({\n webId: input.webId,\n provider: 'kimi',\n deployment: input.deployment,\n reason: safeProviderError(body),\n expectedVersion: current.version,\n auth: input.auth,\n });\n }\n requireStringField(body, 'access_token');\n requireStringField(body, 'refresh_token');\n return this.storeOAuthCredential(input, body, current.version);\n }\n\n public override async disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined> {\n return this.credentialRepository.disconnect({\n webId: input.webId,\n provider: 'kimi',\n deployment: input.deployment,\n auth: input.auth,\n });\n }\n\n private nowForConsume(): Date {\n return this.now();\n }\n\n private async storeOAuthCredential(\n input: { webId: string; deployment: GatewayDeployment; auth?: AuthContext },\n body: Record<string, unknown>,\n expectedVersion?: number,\n ): Promise<ConnectCredentialRecord> {\n const credentialIri = aiRuntimeRepository.credentialIri(input.webId, {\n deployment: input.deployment,\n provider: 'kimi',\n });\n const expiresAt = expiresAtFrom(body.expires_in, this.now());\n const secret: ProviderSecret = {\n type: 'deviceCodeOAuth',\n accessToken: stringFrom(body.access_token),\n refreshToken: stringFrom(body.refresh_token),\n expiresAt: expiresAt?.toISOString(),\n scope: stringFrom(body.scope),\n idToken: stringFrom(body.id_token),\n };\n return this.credentialRepository.upsertConnectedCredential({\n id: aiRuntimeRepository.credentialId({ deployment: input.deployment, provider: 'kimi' }),\n credentialIri,\n webId: input.webId,\n provider: 'kimi',\n deployment: input.deployment,\n authMode: 'deviceCodeOAuth',\n storageMode: PLAINTEXT_CREDENTIAL_STORAGE_MODE,\n secretPayload: encodePlaintextCredential(secret),\n status: 'active',\n expiresAt,\n expectedVersion,\n metadata: {\n authoritativeSubject: decodeJwtSubject(stringFrom(body.id_token)),\n },\n }, { auth: input.auth });\n }\n}\n\nexport class DeepSeekConnectAdapter implements ProviderConnectAdapter {\n public readonly provider = 'deepseek';\n\n public async begin(input: ConnectBeginInput): Promise<ConnectBeginResult> {\n if (normalizeProvider(input.provider) !== this.provider) {\n throw new Error('Connect provider mismatch');\n }\n return {\n mode: 'connectUnsupported',\n status: 'unsupported',\n provider: 'deepseek',\n deployment: input.deployment,\n apiKeyManagementSupported: true,\n message: 'DeepSeek does not expose a supported third-party browser Connect flow; use authenticated API key management.',\n };\n }\n}\n\nexport interface ProviderConnectServiceOptions {\n registry: ProviderRegistry;\n adapters: ProviderConnectAdapter[];\n credentialRepository?: PodCredentialRepository;\n}\n\nexport interface ProviderConnectionSummary {\n provider: string;\n status: 'connected' | 'disconnected' | 'reauthRequired';\n authMode?: 'apiKey' | 'deviceCodeOAuth';\n accountLabel?: string;\n expiresAt?: string;\n reauthRequired?: boolean;\n credentialIri?: string;\n version?: number;\n connect: {\n modes: string[];\n configured: boolean;\n message?: string;\n };\n}\n\nexport class ProviderConnectService {\n private readonly registry: ProviderRegistry;\n private readonly credentialRepository?: PodCredentialRepository;\n private readonly adapters = new Map<string, ProviderConnectAdapter>();\n\n public constructor(options: ProviderConnectServiceOptions) {\n this.registry = options.registry;\n this.credentialRepository = options.credentialRepository;\n for (const adapter of options.adapters) {\n this.adapters.set(normalizeProvider(adapter.provider), adapter);\n }\n }\n\n public begin(input: ConnectBeginInput): Promise<ConnectBeginResult> {\n const descriptor = this.registry.requireProvider(input.provider);\n if (descriptor.connect?.mode !== input.requestedMode) {\n throw new Error('Requested Connect mode does not match provider capability');\n }\n if (descriptor.connect?.configured === false) {\n return Promise.resolve({\n mode: descriptor.connect.mode,\n status: 'unsupported',\n provider: normalizeProvider(input.provider),\n deployment: input.deployment,\n apiKeyManagementSupported: descriptor.connect.apiKeyManagementSupported,\n message: descriptor.connect.notes?.join(' '),\n });\n }\n return this.requireAdapter(input.provider).begin(input);\n }\n\n public async listProviders(input: {\n webId: string;\n deployment: GatewayDeployment;\n auth?: AuthContext;\n }): Promise<ProviderConnectionSummary[]> {\n return Promise.all(this.registry.listProviders().map(async (descriptor) => {\n let credential: ConnectCredentialRecord | undefined;\n try {\n credential = this.credentialRepository?.getCredential\n ? await this.credentialRepository.getCredential({\n ...input,\n provider: descriptor.id,\n })\n : await this.credentialRepository?.getActiveCredential({\n ...input,\n provider: descriptor.id,\n });\n } catch (error) {\n if (!(error instanceof UnsupportedCredentialStorageModeError)) {\n throw error;\n }\n }\n const activeCredential = credential?.status === 'active' ? credential : undefined;\n const reauthRequired = activeCredential?.reauthRequired === true;\n const modes = Array.from(new Set([\n ...descriptor.authModes.filter((mode) => mode !== 'connectUnsupported'),\n ...(descriptor.connect?.apiKeyManagementSupported ? ['apiKey'] : []),\n ]));\n return {\n provider: descriptor.id,\n status: reauthRequired\n ? 'reauthRequired' as const\n : activeCredential\n ? 'connected' as const\n : 'disconnected' as const,\n authMode: activeCredential?.authMode,\n accountLabel: activeCredential?.accountLabel,\n expiresAt: activeCredential?.expiresAt?.toISOString(),\n reauthRequired: reauthRequired || undefined,\n credentialIri: activeCredential?.credentialIri,\n version: activeCredential?.version,\n connect: {\n modes,\n configured: descriptor.connect?.configured !== false,\n message: descriptor.connect?.notes?.join(' ') || undefined,\n },\n };\n }));\n }\n\n public completeApiKey(input: CompleteApiKeyInput): Promise<ConnectBeginResult> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.completeApiKey) {\n throw new Error('Provider does not support API key Connect completion');\n }\n return adapter.completeApiKey(input);\n }\n\n public pollDevice(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.pollDevice) {\n throw new Error('Provider does not support device-code polling');\n }\n return adapter.pollDevice(input);\n }\n\n public status(input: PollDeviceInput): Promise<ConnectBeginResult> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.status) {\n throw new Error('Provider does not support Connect status');\n }\n return adapter.status(input);\n }\n\n public refresh(input: RefreshInput): Promise<ConnectCredentialRecord | undefined> {\n return this.refreshWithRetry(input, 2);\n }\n\n private async refreshWithRetry(\n input: RefreshInput,\n remainingAttempts: number,\n ): Promise<ConnectCredentialRecord | undefined> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.refresh) {\n throw new Error('Provider does not support refresh');\n }\n if (!this.credentialRepository) {\n throw new Error('PodCredentialRepository is required for provider refresh');\n }\n const current = await this.credentialRepository.getActiveCredential(input);\n if (!current) {\n throw new Error('Active provider credential not found');\n }\n const secret = decodePlaintextCredential(current);\n try {\n return await adapter.refresh(input, current, secret);\n } catch (error) {\n if (remainingAttempts > 0 && isVersionConflict(error)) {\n const latest = await this.credentialRepository.getActiveCredential(input);\n if (latest && latest.version !== current.version && !latest.reauthRequired) {\n return latest;\n }\n return this.refreshWithRetry(input, remainingAttempts - 1);\n }\n throw error;\n }\n }\n\n public disconnect(input: DisconnectInput): Promise<ConnectCredentialRecord | undefined> {\n const adapter = this.requireAdapter(input.provider);\n if (!adapter.disconnect) {\n throw new Error('Provider does not support disconnect');\n }\n return adapter.disconnect(input);\n }\n\n private requireAdapter(provider: string): ProviderConnectAdapter {\n const adapter = this.adapters.get(normalizeProvider(provider));\n if (!adapter) {\n throw new Error(`No Connect adapter registered for ${provider}`);\n }\n return adapter;\n }\n}\n\nfunction token(randomBytes: (bytes: number) => Buffer): string {\n return randomBytes(32).toString('base64url');\n}\n\nfunction createDefaultConnectedCredentialDb(input: {\n owner: string;\n podUrl: string;\n auth?: AuthContext;\n fetch: typeof fetch;\n credential?: typeof credentialResource;\n aiProvider?: typeof aiProviderResource;\n}): Promise<ConnectedCredentialDb> {\n const credential = input.credential ?? credentialResource;\n const aiProvider = input.aiProvider ?? aiProviderResource;\n return Promise.resolve(drizzle(\n {\n fetch: input.fetch,\n info: { webId: input.owner, podUrl: input.podUrl, isLoggedIn: true },\n } as any,\n {\n schema: {\n credential,\n aiProvider,\n },\n podUrl: input.podUrl,\n },\n ) as unknown as ConnectedCredentialDb);\n}\n\nfunction podUrlFromHostedWebId(webId: string): string {\n const ownerUrl = new URL(webId);\n if (ownerUrl.hash !== '#me' || !ownerUrl.pathname.endsWith('/profile/card')) {\n throw new Error('hosted_pod_owner_url_invalid');\n }\n const podPath = ownerUrl.pathname.slice(0, -'profile/card'.length);\n if (!podPath || !podPath.endsWith('/')) {\n throw new Error('hosted_pod_owner_url_invalid');\n }\n return new URL(podPath, ownerUrl.origin).href;\n}\n\nfunction credentialRowFromRecord(record: ConnectCredentialRecord): Record<string, unknown> {\n return {\n id: record.id,\n provider: aiProviderResource.buildId({ id: normalizeProvider(record.provider) }),\n service: 'ai',\n authMode: record.authMode,\n status: record.status,\n storageMode: record.storageMode,\n secretPayload: record.secretPayload,\n keyVersion: String(record.version ?? 1),\n scopes: record.scopes ?? [],\n expiresAt: record.expiresAt,\n accountLabel: record.accountLabel,\n label: record.accountLabel,\n reauthRequired: record.reauthRequired ?? false,\n lastRefreshAt: new Date(),\n };\n}\n\nfunction recordFromCredentialRow(row: Record<string, unknown>, owner: string): ConnectCredentialRecord {\n const storageMode = stringFrom(row.storageMode) === PLAINTEXT_CREDENTIAL_STORAGE_MODE\n ? PLAINTEXT_CREDENTIAL_STORAGE_MODE\n : stringFrom(row.storageMode);\n const secretPayload = typeof row.secretPayload === 'string' ? row.secretPayload : '';\n decodePlaintextCredential({\n storageMode,\n secretPayload,\n encryptedSecret: row.encryptedSecret,\n wrappedDataKey: row.wrappedDataKey,\n encryptionAlgorithm: row.encryptionAlgorithm,\n });\n const id = stringFrom(row.id);\n const provider = providerFromRelation(stringFrom(row.provider))\n || providerFromCredentialId(id);\n const deployment = deploymentFromCredentialId(id);\n const credentialIri = stringFrom(row.credentialIri)\n || aiRuntimeRepository.credentialIri(owner, { deployment, provider });\n return {\n id,\n credentialIri,\n webId: owner,\n provider,\n deployment,\n authMode: stringFrom(row.authMode) === 'deviceCodeOAuth' ? 'deviceCodeOAuth' : 'apiKey',\n storageMode: PLAINTEXT_CREDENTIAL_STORAGE_MODE,\n secretPayload,\n status: stringFrom(row.status) === 'revoked' ? 'revoked' : 'active',\n accountLabel: stringFrom(row.accountLabel) || stringFrom(row.label) || undefined,\n expiresAt: dateFrom(row.expiresAt),\n scopes: Array.isArray(row.scopes) ? row.scopes.map(String) : undefined,\n version: versionFromRow(row),\n reauthRequired: row.reauthRequired === true || row.reauthRequired === 'true',\n metadata: metadataFromRow(row),\n };\n}\n\nfunction providerFromRelation(value: string): string | undefined {\n if (!value) {\n return undefined;\n }\n const withoutFragment = value.split('#', 1)[0] ?? value;\n const fileName = withoutFragment.split('/').filter(Boolean).at(-1) ?? withoutFragment;\n const provider = fileName.replace(/\\.ttl$/u, '');\n return provider ? normalizeProvider(provider) : undefined;\n}\n\nfunction credentialPersistenceError(stage: string, cause: unknown): Error {\n return new Error(`credential_persistence_failed:${stage}`, { cause });\n}\n\nfunction isPodResourceNotFound(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n return /\\b404\\b|not found/i.test(error.message);\n}\n\nfunction metadataFromRow(row: Record<string, unknown>): Record<string, unknown> | undefined {\n const value = row.metadata;\n if (!value) {\n return undefined;\n }\n if (typeof value === 'object' && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n if (typeof value === 'string') {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : undefined;\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\nfunction modelsFromMetadata(metadata: Record<string, unknown> | undefined): string[] | undefined {\n const value = metadata?.models;\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : undefined;\n}\n\nfunction defaultModelFromMetadata(metadata: Record<string, unknown> | undefined): string | undefined {\n const value = metadata?.defaultModel;\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction priorityFromMetadata(metadata: Record<string, unknown> | undefined): number | undefined {\n const value = metadata?.priority;\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction runtimeCredentialFromMetadata(metadata: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n const value = metadata?.runtimeCredential;\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined;\n}\n\nfunction versionFromRow(row: Record<string, unknown>): number {\n const value = row.keyVersion;\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string' && value.trim()) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : 0;\n }\n return 0;\n}\n\nfunction providerFromCredentialId(id: string): string {\n const match = /\\/([^/#]+)\\.ttl#/u.exec(id);\n return match?.[1] ?? '';\n}\n\nfunction deploymentFromCredentialId(id: string): GatewayDeployment {\n return id.includes('#cloud-') ? 'cloud' : 'local';\n}\n\nfunction dateFrom(value: unknown): Date | undefined {\n if (value instanceof Date) {\n return value;\n }\n if (typeof value === 'string' || typeof value === 'number') {\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n }\n return undefined;\n}\n\nfunction signAttempt(\n attempt: Pick<ConnectAttempt, 'id' | 'provider' | 'deployment' | 'webId' | 'mode' | 'state' | 'expiresAt'>,\n secret: string,\n): string {\n return createHmac('sha256', secret)\n .update(JSON.stringify({\n id: attempt.id,\n provider: attempt.provider,\n deployment: attempt.deployment,\n webId: attempt.webId,\n mode: attempt.mode,\n state: attempt.state,\n expiresAt: attempt.expiresAt.toISOString(),\n }))\n .digest('base64url');\n}\n\nfunction signatureMatches(actual: string, expected: string): boolean {\n const actualBuffer = Buffer.from(actual, 'utf8');\n const expectedBuffer = Buffer.from(expected, 'utf8');\n return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);\n}\n\nfunction codeChallenge(verifier: string): string {\n return createHash('sha256').update(verifier).digest('base64url');\n}\n\n\nfunction cloneAttempt(attempt: ConnectAttempt): ConnectAttempt {\n return {\n ...attempt,\n expiresAt: new Date(attempt.expiresAt),\n consumedAt: attempt.consumedAt ? new Date(attempt.consumedAt) : undefined,\n nextPollAt: attempt.nextPollAt ? new Date(attempt.nextPollAt) : undefined,\n pollClaimedAt: attempt.pollClaimedAt ? new Date(attempt.pollClaimedAt) : undefined,\n };\n}\n\nfunction normalizeProvider(provider: string): string {\n return provider.trim().toLowerCase();\n}\n\nasync function safeJson(response: Response): Promise<Record<string, unknown>> {\n const text = await response.text();\n if (!text) {\n if (response.ok) {\n throw new Error('Provider returned an empty JSON response');\n }\n return {};\n }\n try {\n const parsed = JSON.parse(text);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n if (response.ok) {\n throw new Error('Provider returned a non-object JSON response');\n }\n return {};\n }\n return parsed as Record<string, unknown>;\n } catch {\n if (response.ok) {\n throw new Error('Provider returned invalid JSON');\n }\n return {};\n }\n}\n\nfunction stringFrom(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction numberFrom(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback;\n}\n\nfunction expiresAtFrom(expiresIn: unknown, now: Date): Date | undefined {\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn)) {\n return undefined;\n }\n return new Date(now.getTime() + expiresIn * 1000);\n}\n\nfunction safeProviderError(body: Record<string, unknown>): string {\n const code = stringFrom(body.error);\n if (SAFE_PROVIDER_ERROR_CODES.has(code)) {\n return code;\n }\n if (!code) {\n return 'provider_error';\n }\n if (code.endsWith('_error')) {\n return 'provider_error';\n }\n return 'provider_error';\n}\n\nconst SAFE_PROVIDER_ERROR_CODES = new Set([\n 'authorization_pending',\n 'slow_down',\n 'expired_token',\n 'access_denied',\n 'invalid_grant',\n 'invalid_client',\n]);\n\nfunction pendingResult(\n input: PollDeviceInput,\n status: ConnectAttemptStatus,\n intervalSeconds?: number,\n): ConnectBeginResult {\n return {\n mode: 'deviceCodeOAuth',\n status,\n provider: 'kimi',\n deployment: input.deployment,\n attemptId: input.attemptId,\n intervalSeconds,\n };\n}\n\nfunction assertKimiEndpoint(endpoint: string, pathname: string): void {\n const url = new URL(endpoint);\n if (\n url.origin !== 'https://auth.kimi.com'\n || url.pathname !== pathname\n || url.search\n || url.hash\n || url.username\n || url.password\n ) {\n throw new Error('Kimi Connect endpoint is not allowlisted');\n }\n}\n\nfunction requireStringField(body: Record<string, unknown>, field: string): void {\n if (typeof body[field] !== 'string' || !(body[field] as string).trim()) {\n throw new Error(`Provider response missing required field: ${field}`);\n }\n}\n\nfunction isVersionConflict(error: unknown): boolean {\n return error instanceof Error && /version_conflict|credential_version_conflict/u.test(error.message);\n}\n\nfunction decodeJwtSubject(idToken: string): string | undefined {\n const payload = idToken.split('.')[1];\n if (!payload) {\n return undefined;\n }\n try {\n const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));\n return typeof decoded.sub === 'string' ? decoded.sub : undefined;\n } catch {\n return undefined;\n }\n}\n"]}
|
|
@@ -34,7 +34,7 @@ class HostedPodDataAccess {
|
|
|
34
34
|
method,
|
|
35
35
|
resourceUrl,
|
|
36
36
|
principalKind: authorization.principalKind,
|
|
37
|
-
scopes: [method === 'GET' ? 'ai:credentials:read' : 'ai:credentials:write'],
|
|
37
|
+
scopes: [method === 'GET' || method === 'HEAD' ? 'ai:credentials:read' : 'ai:credentials:write'],
|
|
38
38
|
});
|
|
39
39
|
return this.fetch(loopbackUrl, {
|
|
40
40
|
method,
|
|
@@ -110,7 +110,7 @@ class HostedPodDataAccess {
|
|
|
110
110
|
exports.HostedPodDataAccess = HostedPodDataAccess;
|
|
111
111
|
function normalizeMethod(method) {
|
|
112
112
|
const upper = (method ?? 'GET').toUpperCase();
|
|
113
|
-
if (upper === 'GET' || upper === 'PUT' || upper === 'PATCH' || upper === 'DELETE') {
|
|
113
|
+
if (upper === 'GET' || upper === 'HEAD' || upper === 'PUT' || upper === 'PATCH' || upper === 'DELETE') {
|
|
114
114
|
return upper;
|
|
115
115
|
}
|
|
116
116
|
throw new Error('hosted_pod_method_not_allowed');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HostedPodDataAccess.js","sourceRoot":"","sources":["../../../../src/api/ai-gateway/pod/HostedPodDataAccess.ts"],"names":[],"mappings":";;;AAAA,6CAAyC;AACzC,uCAAgC;AAChC,2FAA8F;AAE9F,kFAIgD;AAkBhD,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;AACrD,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAAC;IACtC,eAAe;IACf,MAAM;IACN,QAAQ;CACT,CAAC,CAAC;AAEH,MAAa,mBAAmB;IAO9B,YAAmB,OAAmC;QACpD,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAC9C,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAClD,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;QACtD,CAAC;QACD,IAAI,CAAC,2BAA2B,GAAG,OAAO,CAAC,2BAA2B,IAAI,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC;QAC3H,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;QACpC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC;QACnC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,wBAAU,CAAC;IAC3C,CAAC;IAEM,KAAK,CAAC,eAAe,CAAC,KAAa,EAAE,IAAmC;QAC7E,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;YAC3B,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACzC,MAAM,MAAM,GAAG,eAAe,CAAC,OAA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EAAE,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IACnE,IAAI,UAAU,KAAK,WAAW,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,IAAA,eAAI,EAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,UAAU,KAAK,KAAK,CAAC;AAC9B,CAAC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { isIP } from 'node:net';\nimport { createAiConnectionServiceAccess } from '../service-access/AiConnectionServiceAccess';\nimport type { AuthContext, SolidAuthContext } from '../../auth/AuthContext';\nimport {\n createGatewayAdminProxyHeaders,\n GATEWAY_ADMIN_PROXY_HEADERS,\n type GatewayAdminProxyIntent,\n} from '../../../runtime/GatewayAdminProxyAuth';\n\nexport interface InternalPodAccessTokenProvider {\n getTrustedFetch(owner: string, auth?: InternalPodAccessAuthContext): Promise<typeof fetch | undefined>;\n}\n\nexport type InternalPodAccessAuthContext = AuthContext | undefined;\n\nexport interface HostedPodDataAccessOptions {\n cssBaseUrl: string;\n gatewayAdminProxyAuthSecret?: string;\n fetch?: typeof fetch;\n now?: () => number;\n nonce?: () => string;\n}\n\ntype InternalPodDataMethod = 'GET' | 'PUT' | 'PATCH' | 'DELETE';\n\nconst INTERNAL_POD_DATA_PATH = '/.internal/pod-data';\nconst STRIPPED_CALLER_HEADERS = new Set([\n 'authorization',\n 'dpop',\n 'cookie',\n]);\n\nexport class HostedPodDataAccess implements InternalPodAccessTokenProvider {\n private readonly cssBaseUrl: URL;\n private readonly gatewayAdminProxyAuthSecret?: string;\n private readonly fetch: typeof fetch;\n private readonly now: () => number;\n private readonly nonce: () => string;\n\n public constructor(options: HostedPodDataAccessOptions) {\n this.cssBaseUrl = new URL(options.cssBaseUrl);\n if (!isLoopbackHostname(this.cssBaseUrl.hostname)) {\n throw new Error('hosted_pod_css_loopback_required');\n }\n this.gatewayAdminProxyAuthSecret = options.gatewayAdminProxyAuthSecret ?? process.env.XPOD_GATEWAY_ADMIN_PROXY_AUTH_SECRET;\n this.fetch = options.fetch ?? fetch;\n this.now = options.now ?? Date.now;\n this.nonce = options.nonce ?? randomUUID;\n }\n\n public async getTrustedFetch(owner: string, auth?: InternalPodAccessAuthContext): Promise<typeof fetch | undefined> {\n return async (input, init) => {\n const request = new Request(input, init);\n const method = normalizeMethod(request.method);\n const resourceUrl = normalizeResourceUrl(request.url);\n const authorization = this.authorize({ owner, auth, method, resourceUrl });\n const loopbackUrl = new URL(INTERNAL_POD_DATA_PATH, this.cssBaseUrl);\n const headers = this.headersForLoopback(request.headers, {\n ownerWebId: owner,\n method,\n resourceUrl,\n principalKind: authorization.principalKind,\n scopes: [method === 'GET' ? 'ai:credentials:read' : 'ai:credentials:write'],\n });\n\n return this.fetch(loopbackUrl, {\n method,\n headers,\n body: request.body,\n signal: init?.signal ?? request.signal,\n ...(request.body ? { duplex: 'half' } : {}),\n } as RequestInit);\n };\n }\n\n private authorize(input: {\n owner: string;\n auth?: InternalPodAccessAuthContext;\n method: InternalPodDataMethod;\n resourceUrl: string;\n }): { principalKind: GatewayAdminProxyIntent['principalKind'] } {\n this.assertHostedAllowedResource(input.owner, input.resourceUrl);\n\n if (!input.auth) {\n throw new Error('hosted_pod_auth_required');\n }\n if (input.auth.type !== 'solid') {\n throw new Error('hosted_pod_solid_principal_required');\n }\n if (input.auth.webId !== input.owner) {\n throw new Error('hosted_pod_owner_mismatch');\n }\n return { principalKind: 'solid-user' };\n }\n\n private assertHostedAllowedResource(owner: string, resourceUrl: string): void {\n const resource = parseUrl(resourceUrl, 'hosted_pod_resource_url_invalid');\n const ownerUrl = parseUrl(owner, 'hosted_pod_owner_url_invalid');\n const podRoot = hostedPodRootFromOwner(ownerUrl);\n if (!podRoot || resource.origin !== podRoot.origin || !resource.pathname.startsWith(podRoot.pathname)) {\n throw new Error('hosted_pod_remote_resource');\n }\n if (resource.hash || resource.search) {\n throw new Error('hosted_pod_resource_not_allowed');\n }\n\n const allowed = createAiConnectionServiceAccess({\n ownerWebId: owner,\n serviceWebId: owner,\n }).resources.map((entry) => entry.url);\n if (!allowed.includes(resource.href)) {\n throw new Error('hosted_pod_resource_not_allowed');\n }\n }\n\n private headersForLoopback(headers: Headers, intent: GatewayAdminProxyIntent): Headers {\n const next = new Headers();\n headers.forEach((value, key) => {\n const normalized = key.toLowerCase();\n if (\n STRIPPED_CALLER_HEADERS.has(normalized)\n || GATEWAY_ADMIN_PROXY_HEADERS.includes(normalized as typeof GATEWAY_ADMIN_PROXY_HEADERS[number])\n || normalized.startsWith('x-xpod-admin-proxy-')\n ) {\n return;\n }\n next.set(key, value);\n });\n\n if (!this.gatewayAdminProxyAuthSecret) {\n throw new Error('XPOD_GATEWAY_ADMIN_PROXY_AUTH_SECRET is required for hosted Pod data access');\n }\n const marker = createGatewayAdminProxyHeaders({\n secret: this.gatewayAdminProxyAuthSecret,\n method: intent.method,\n url: INTERNAL_POD_DATA_PATH,\n originalClientLoopback: true,\n issuedAt: this.now(),\n nonce: this.nonce(),\n intent,\n });\n for (const [key, value] of Object.entries(marker)) {\n if (value !== undefined) {\n next.set(key, Array.isArray(value) ? value.join(', ') : String(value));\n }\n }\n return next;\n }\n}\n\nfunction normalizeMethod(method: string | undefined): InternalPodDataMethod {\n const upper = (method ?? 'GET').toUpperCase();\n if (upper === 'GET' || upper === 'PUT' || upper === 'PATCH' || upper === 'DELETE') {\n return upper;\n }\n throw new Error('hosted_pod_method_not_allowed');\n}\n\nfunction normalizeResourceUrl(value: string): string {\n return new URL(value).href;\n}\n\nfunction parseUrl(value: string, errorCode: string): URL {\n try {\n return new URL(value);\n } catch {\n throw new Error(errorCode);\n }\n}\n\nfunction hostedPodRootFromOwner(ownerUrl: URL): URL | undefined {\n if (ownerUrl.hash !== '#me' || !ownerUrl.pathname.endsWith('/profile/card')) {\n return undefined;\n }\n const podPath = ownerUrl.pathname.slice(0, -'profile/card'.length);\n if (!podPath || !podPath.endsWith('/')) {\n return undefined;\n }\n return new URL(podPath, ownerUrl.origin);\n}\n\nfunction isLoopbackHostname(hostname: string): boolean {\n const normalized = hostname.replace(/^\\[|\\]$/gu, '').toLowerCase();\n if (normalized === 'localhost') {\n return true;\n }\n if (isIP(normalized) === 4) {\n return normalized.startsWith('127.');\n }\n return normalized === '::1';\n}\n"]}
|
|
1
|
+
{"version":3,"file":"HostedPodDataAccess.js","sourceRoot":"","sources":["../../../../src/api/ai-gateway/pod/HostedPodDataAccess.ts"],"names":[],"mappings":";;;AAAA,6CAAyC;AACzC,uCAAgC;AAChC,2FAA8F;AAE9F,kFAIgD;AAkBhD,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;AACrD,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAAC;IACtC,eAAe;IACf,MAAM;IACN,QAAQ;CACT,CAAC,CAAC;AAEH,MAAa,mBAAmB;IAO9B,YAAmB,OAAmC;QACpD,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAC9C,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAClD,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;QACtD,CAAC;QACD,IAAI,CAAC,2BAA2B,GAAG,OAAO,CAAC,2BAA2B,IAAI,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC;QAC3H,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC;QACpC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC;QACnC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,wBAAU,CAAC;IAC3C,CAAC;IAEM,KAAK,CAAC,eAAe,CAAC,KAAa,EAAE,IAAmC;QAC7E,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI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ACD,OAAO,IAAI,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,kBAAkB,CAAC,QAAgB;IAC1C,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IACnE,IAAI,UAAU,KAAK,WAAW,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,IAAA,eAAI,EAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,UAAU,KAAK,KAAK,CAAC;AAC9B,CAAC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { isIP } from 'node:net';\nimport { createAiConnectionServiceAccess } from '../service-access/AiConnectionServiceAccess';\nimport type { AuthContext, SolidAuthContext } from '../../auth/AuthContext';\nimport {\n createGatewayAdminProxyHeaders,\n GATEWAY_ADMIN_PROXY_HEADERS,\n type GatewayAdminProxyIntent,\n} from '../../../runtime/GatewayAdminProxyAuth';\n\nexport interface InternalPodAccessTokenProvider {\n getTrustedFetch(owner: string, auth?: InternalPodAccessAuthContext): Promise<typeof fetch | undefined>;\n}\n\nexport type InternalPodAccessAuthContext = AuthContext | undefined;\n\nexport interface HostedPodDataAccessOptions {\n cssBaseUrl: string;\n gatewayAdminProxyAuthSecret?: string;\n fetch?: typeof fetch;\n now?: () => number;\n nonce?: () => string;\n}\n\ntype InternalPodDataMethod = 'GET' | 'HEAD' | 'PUT' | 'PATCH' | 'DELETE';\n\nconst INTERNAL_POD_DATA_PATH = '/.internal/pod-data';\nconst STRIPPED_CALLER_HEADERS = new Set([\n 'authorization',\n 'dpop',\n 'cookie',\n]);\n\nexport class HostedPodDataAccess implements InternalPodAccessTokenProvider {\n private readonly cssBaseUrl: URL;\n private readonly gatewayAdminProxyAuthSecret?: string;\n private readonly fetch: typeof fetch;\n private readonly now: () => number;\n private readonly nonce: () => string;\n\n public constructor(options: HostedPodDataAccessOptions) {\n this.cssBaseUrl = new URL(options.cssBaseUrl);\n if (!isLoopbackHostname(this.cssBaseUrl.hostname)) {\n throw new Error('hosted_pod_css_loopback_required');\n }\n this.gatewayAdminProxyAuthSecret = options.gatewayAdminProxyAuthSecret ?? process.env.XPOD_GATEWAY_ADMIN_PROXY_AUTH_SECRET;\n this.fetch = options.fetch ?? fetch;\n this.now = options.now ?? Date.now;\n this.nonce = options.nonce ?? randomUUID;\n }\n\n public async getTrustedFetch(owner: string, auth?: InternalPodAccessAuthContext): Promise<typeof fetch | undefined> {\n return async (input, init) => {\n const request = new Request(input, init);\n const method = normalizeMethod(request.method);\n const resourceUrl = normalizeResourceUrl(request.url);\n const authorization = this.authorize({ owner, auth, method, resourceUrl });\n const loopbackUrl = new URL(INTERNAL_POD_DATA_PATH, this.cssBaseUrl);\n const headers = this.headersForLoopback(request.headers, {\n ownerWebId: owner,\n method,\n resourceUrl,\n principalKind: authorization.principalKind,\n scopes: [method === 'GET' || method === 'HEAD' ? 'ai:credentials:read' : 'ai:credentials:write'],\n });\n\n return this.fetch(loopbackUrl, {\n method,\n headers,\n body: request.body,\n signal: init?.signal ?? request.signal,\n ...(request.body ? { duplex: 'half' } : {}),\n } as RequestInit);\n };\n }\n\n private authorize(input: {\n owner: string;\n auth?: InternalPodAccessAuthContext;\n method: InternalPodDataMethod;\n resourceUrl: string;\n }): { principalKind: GatewayAdminProxyIntent['principalKind'] } {\n this.assertHostedAllowedResource(input.owner, input.resourceUrl);\n\n if (!input.auth) {\n throw new Error('hosted_pod_auth_required');\n }\n if (input.auth.type !== 'solid') {\n throw new Error('hosted_pod_solid_principal_required');\n }\n if (input.auth.webId !== input.owner) {\n throw new Error('hosted_pod_owner_mismatch');\n }\n return { principalKind: 'solid-user' };\n }\n\n private assertHostedAllowedResource(owner: string, resourceUrl: string): void {\n const resource = parseUrl(resourceUrl, 'hosted_pod_resource_url_invalid');\n const ownerUrl = parseUrl(owner, 'hosted_pod_owner_url_invalid');\n const podRoot = hostedPodRootFromOwner(ownerUrl);\n if (!podRoot || resource.origin !== podRoot.origin || !resource.pathname.startsWith(podRoot.pathname)) {\n throw new Error('hosted_pod_remote_resource');\n }\n if (resource.hash || resource.search) {\n throw new Error('hosted_pod_resource_not_allowed');\n }\n\n const allowed = createAiConnectionServiceAccess({\n ownerWebId: owner,\n serviceWebId: owner,\n }).resources.map((entry) => entry.url);\n if (!allowed.includes(resource.href)) {\n throw new Error('hosted_pod_resource_not_allowed');\n }\n }\n\n private headersForLoopback(headers: Headers, intent: GatewayAdminProxyIntent): Headers {\n const next = new Headers();\n headers.forEach((value, key) => {\n const normalized = key.toLowerCase();\n if (\n STRIPPED_CALLER_HEADERS.has(normalized)\n || GATEWAY_ADMIN_PROXY_HEADERS.includes(normalized as typeof GATEWAY_ADMIN_PROXY_HEADERS[number])\n || normalized.startsWith('x-xpod-admin-proxy-')\n ) {\n return;\n }\n next.set(key, value);\n });\n\n if (!this.gatewayAdminProxyAuthSecret) {\n throw new Error('XPOD_GATEWAY_ADMIN_PROXY_AUTH_SECRET is required for hosted Pod data access');\n }\n const marker = createGatewayAdminProxyHeaders({\n secret: this.gatewayAdminProxyAuthSecret,\n method: intent.method,\n url: INTERNAL_POD_DATA_PATH,\n originalClientLoopback: true,\n issuedAt: this.now(),\n nonce: this.nonce(),\n intent,\n });\n for (const [key, value] of Object.entries(marker)) {\n if (value !== undefined) {\n next.set(key, Array.isArray(value) ? value.join(', ') : String(value));\n }\n }\n return next;\n }\n}\n\nfunction normalizeMethod(method: string | undefined): InternalPodDataMethod {\n const upper = (method ?? 'GET').toUpperCase();\n if (upper === 'GET' || upper === 'HEAD' || upper === 'PUT' || upper === 'PATCH' || upper === 'DELETE') {\n return upper;\n }\n throw new Error('hosted_pod_method_not_allowed');\n}\n\nfunction normalizeResourceUrl(value: string): string {\n return new URL(value).href;\n}\n\nfunction parseUrl(value: string, errorCode: string): URL {\n try {\n return new URL(value);\n } catch {\n throw new Error(errorCode);\n }\n}\n\nfunction hostedPodRootFromOwner(ownerUrl: URL): URL | undefined {\n if (ownerUrl.hash !== '#me' || !ownerUrl.pathname.endsWith('/profile/card')) {\n return undefined;\n }\n const podPath = ownerUrl.pathname.slice(0, -'profile/card'.length);\n if (!podPath || !podPath.endsWith('/')) {\n return undefined;\n }\n return new URL(podPath, ownerUrl.origin);\n}\n\nfunction isLoopbackHostname(hostname: string): boolean {\n const normalized = hostname.replace(/^\\[|\\]$/gu, '').toLowerCase();\n if (normalized === 'localhost') {\n return true;\n }\n if (isIP(normalized) === 4) {\n return normalized.startsWith('127.');\n }\n return normalized === '::1';\n}\n"]}
|
|
@@ -55,7 +55,7 @@ function resolveCssServiceBaseUrl() {
|
|
|
55
55
|
return 'http://localhost:3000/';
|
|
56
56
|
}
|
|
57
57
|
function resolveHostedPodCssBaseUrl() {
|
|
58
|
-
return process.env.
|
|
58
|
+
return `http://127.0.0.1:${process.env.XPOD_MAIN_PORT ?? '3000'}/`;
|
|
59
59
|
}
|
|
60
60
|
function resolveAiConnectionBaseUrl(config) {
|
|
61
61
|
const origin = config.publicUrl
|