@undefineds.co/xpod 0.3.70 → 0.3.71-rc.13

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.
Files changed (172) hide show
  1. package/config/cloud.json +3 -0
  2. package/config/local.json +3 -0
  3. package/config/resolver.json +7 -0
  4. package/config/xpod.base.json +20 -0
  5. package/dist/agents/ClaudeExecutor.js +1 -1
  6. package/dist/agents/ClaudeExecutor.js.map +1 -1
  7. package/dist/agents/types.d.ts +5 -5
  8. package/dist/agents/types.js.map +1 -1
  9. package/dist/api/ai-gateway/AiGatewayService.d.ts +5 -16
  10. package/dist/api/ai-gateway/AiGatewayService.js +13 -35
  11. package/dist/api/ai-gateway/AiGatewayService.js.map +1 -1
  12. package/dist/api/ai-gateway/auth/AiConnectionInvocationKeyIssuer.d.ts +3 -2
  13. package/dist/api/ai-gateway/auth/AiConnectionInvocationKeyIssuer.js +37 -12
  14. package/dist/api/ai-gateway/auth/AiConnectionInvocationKeyIssuer.js.map +1 -1
  15. package/dist/api/ai-gateway/auth/GatewayPrincipal.d.ts +2 -16
  16. package/dist/api/ai-gateway/auth/GatewayPrincipal.js +3 -33
  17. package/dist/api/ai-gateway/auth/GatewayPrincipal.js.map +1 -1
  18. package/dist/api/ai-gateway/auth/InvocationTokenAuthenticator.d.ts +23 -0
  19. package/dist/api/ai-gateway/auth/InvocationTokenAuthenticator.js +81 -0
  20. package/dist/api/ai-gateway/auth/InvocationTokenAuthenticator.js.map +1 -0
  21. package/dist/api/ai-gateway/auth/InvocationTokenCodec.d.ts +7 -4
  22. package/dist/api/ai-gateway/auth/InvocationTokenCodec.js.map +1 -1
  23. package/dist/api/ai-gateway/connect/index.d.ts +7 -26
  24. package/dist/api/ai-gateway/connect/index.js +40 -67
  25. package/dist/api/ai-gateway/connect/index.js.map +1 -1
  26. package/dist/api/ai-gateway/credentials/PlaintextCredentialPayload.d.ts +17 -0
  27. package/dist/api/ai-gateway/credentials/PlaintextCredentialPayload.js +65 -0
  28. package/dist/api/ai-gateway/credentials/PlaintextCredentialPayload.js.map +1 -0
  29. package/dist/api/ai-gateway/pod/HostedPodDataAccess.d.ts +24 -0
  30. package/dist/api/ai-gateway/pod/HostedPodDataAccess.js +149 -0
  31. package/dist/api/ai-gateway/pod/HostedPodDataAccess.js.map +1 -0
  32. package/dist/api/ai-gateway/quota/ProviderQuotaAdapter.d.ts +13 -5
  33. package/dist/api/ai-gateway/quota/ProviderQuotaAdapter.js +16 -19
  34. package/dist/api/ai-gateway/quota/ProviderQuotaAdapter.js.map +1 -1
  35. package/dist/api/ai-gateway/service-access/AiConnectionServiceAccess.d.ts +1 -1
  36. package/dist/api/ai-gateway/service-access/AiConnectionServiceAccess.js +0 -2
  37. package/dist/api/ai-gateway/service-access/AiConnectionServiceAccess.js.map +1 -1
  38. package/dist/api/auth/AuthContext.d.ts +1 -12
  39. package/dist/api/auth/AuthContext.js +0 -11
  40. package/dist/api/auth/AuthContext.js.map +1 -1
  41. package/dist/api/auth/ClientCredentialsAuthenticator.js +4 -11
  42. package/dist/api/auth/ClientCredentialsAuthenticator.js.map +1 -1
  43. package/dist/api/chatkit/default-agent.d.ts +2 -2
  44. package/dist/api/chatkit/default-agent.js +4 -4
  45. package/dist/api/chatkit/default-agent.js.map +1 -1
  46. package/dist/api/chatkit/runtime/AcpAgentRuntime.js +1 -1
  47. package/dist/api/chatkit/runtime/AcpAgentRuntime.js.map +1 -1
  48. package/dist/api/container/common.js +28 -69
  49. package/dist/api/container/common.js.map +1 -1
  50. package/dist/api/container/index.js +5 -6
  51. package/dist/api/container/index.js.map +1 -1
  52. package/dist/api/container/routes.js +2 -5
  53. package/dist/api/container/routes.js.map +1 -1
  54. package/dist/api/container/types.d.ts +8 -10
  55. package/dist/api/container/types.js.map +1 -1
  56. package/dist/api/handlers/AiClientConfigurationHandler.js +3 -3
  57. package/dist/api/handlers/AiClientConfigurationHandler.js.map +1 -1
  58. package/dist/api/handlers/AiGatewayHandler.js +2 -2
  59. package/dist/api/handlers/AiGatewayHandler.js.map +1 -1
  60. package/dist/api/handlers/AiGatewayManagementHandler.d.ts +2 -10
  61. package/dist/api/handlers/AiGatewayManagementHandler.js +4 -154
  62. package/dist/api/handlers/AiGatewayManagementHandler.js.map +1 -1
  63. package/dist/api/handlers/NetworkSettingsHandler.js +0 -3
  64. package/dist/api/handlers/NetworkSettingsHandler.js.map +1 -1
  65. package/dist/api/handlers/PodSettingsHandler.d.ts +5 -2
  66. package/dist/api/handlers/PodSettingsHandler.js +3 -3
  67. package/dist/api/handlers/PodSettingsHandler.js.map +1 -1
  68. package/dist/api/runs/AgentRuntimeTypes.d.ts +3 -3
  69. package/dist/api/runs/AgentRuntimeTypes.js +10 -10
  70. package/dist/api/runs/AgentRuntimeTypes.js.map +1 -1
  71. package/dist/api/runs/InngestRunExecutionBackend.d.ts +15 -9
  72. package/dist/api/runs/InngestRunExecutionBackend.js +25 -10
  73. package/dist/api/runs/InngestRunExecutionBackend.js.map +1 -1
  74. package/dist/api/runs/PiAgentRuntimeDriver.js +2 -2
  75. package/dist/api/runs/PiAgentRuntimeDriver.js.map +1 -1
  76. package/dist/api/runs/RunStateCenter.js +1 -1
  77. package/dist/api/runs/RunStateCenter.js.map +1 -1
  78. package/dist/api/service/AiClientConfigurationService.d.ts +2 -2
  79. package/dist/api/service/AiClientConfigurationService.js +11 -11
  80. package/dist/api/service/AiClientConfigurationService.js.map +1 -1
  81. package/dist/api/tasks/InngestTaskScheduler.d.ts +16 -10
  82. package/dist/api/tasks/InngestTaskScheduler.js +24 -12
  83. package/dist/api/tasks/InngestTaskScheduler.js.map +1 -1
  84. package/dist/cli/commands/start.js +7 -7
  85. package/dist/cli/commands/start.js.map +1 -1
  86. package/dist/components/components.jsonld +1 -0
  87. package/dist/components/context.jsonld +36 -0
  88. package/dist/http/InternalPodDataHttpHandler.d.ts +32 -0
  89. package/dist/http/InternalPodDataHttpHandler.js +258 -0
  90. package/dist/http/InternalPodDataHttpHandler.js.map +1 -0
  91. package/dist/http/InternalPodDataHttpHandler.jsonld +201 -0
  92. package/dist/index.d.ts +2 -1
  93. package/dist/index.js +4 -2
  94. package/dist/index.js.map +1 -1
  95. package/dist/main.js +13 -13
  96. package/dist/main.js.map +1 -1
  97. package/dist/runtime/GatewayAdminProxyAuth.d.ts +15 -1
  98. package/dist/runtime/GatewayAdminProxyAuth.js +57 -2
  99. package/dist/runtime/GatewayAdminProxyAuth.js.map +1 -1
  100. package/dist/runtime/bootstrap.js +3 -0
  101. package/dist/runtime/bootstrap.js.map +1 -1
  102. package/dist/runtime/css-process.d.ts +1 -1
  103. package/dist/runtime/css-process.js +4 -1
  104. package/dist/runtime/css-process.js.map +1 -1
  105. package/dist/runtime/runner/node/CommunitySolidServerCssRunner.d.ts +2 -0
  106. package/dist/runtime/runner/node/CommunitySolidServerCssRunner.js +50 -0
  107. package/dist/runtime/runner/node/CommunitySolidServerCssRunner.js.map +1 -1
  108. package/node_modules/@undefineds.co/ai-connection/dist/AiClientConfigurationSection.d.ts +5 -5
  109. package/node_modules/@undefineds.co/ai-connection/dist/AiClientConfigurationSection.js +7 -7
  110. package/node_modules/@undefineds.co/ai-connection/dist/AiConnectionMain.js +1 -1
  111. package/node_modules/@undefineds.co/ai-connection/dist/AiConnectionPanel.d.ts +3 -1
  112. package/node_modules/@undefineds.co/ai-connection/dist/AiConnectionPanel.js +74 -60
  113. package/node_modules/@undefineds.co/ai-connection/dist/ai-connection-client.d.ts +0 -21
  114. package/node_modules/@undefineds.co/ai-connection/dist/ai-connection-client.js +0 -41
  115. package/node_modules/@undefineds.co/ai-connection/dist/client-config/base-adapter.d.ts +1 -0
  116. package/node_modules/@undefineds.co/ai-connection/dist/client-config/base-adapter.js +7 -2
  117. package/node_modules/@undefineds.co/ai-connection/dist/client-config/codex.js +3 -3
  118. package/node_modules/@undefineds.co/ai-connection/dist/client-config/index.cjs +15 -9
  119. package/node_modules/@undefineds.co/ai-connection/dist/client-config/json-env-adapter.js +4 -4
  120. package/node_modules/@undefineds.co/ai-connection/dist/client-config/pi.js +3 -3
  121. package/node_modules/@undefineds.co/ai-connection/dist/client-config/types.d.ts +1 -1
  122. package/node_modules/@undefineds.co/ai-connection/dist/controller.d.ts +2 -1
  123. package/node_modules/@undefineds.co/ai-connection/dist/controller.js +1 -0
  124. package/node_modules/@undefineds.co/ai-connection/dist/service-access.js +0 -1
  125. package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +22 -1
  126. package/package.json +3 -3
  127. package/static/app/assets/main.js +7 -7
  128. package/static/dashboard/assets/NetworkPage-CXjiUMR1.js +2 -0
  129. package/static/dashboard/assets/{PaneListHeader-57nvMwH6.js → PaneListHeader-BSipfl0W.js} +1 -1
  130. package/static/dashboard/assets/PodPage-Bd3Xhmp-.js +2 -0
  131. package/static/dashboard/assets/ServicesPage-CI3jWZGe.js +1 -0
  132. package/static/dashboard/assets/{card-B9Zjf_2p.js → card-z5BV5hTo.js} +1 -1
  133. package/static/dashboard/assets/{dashboard-8C6o666W.js → dashboard-CSrqAv2L.js} +2 -2
  134. package/static/dashboard/assets/{database-DPh9wDY9.js → database-Ct5ZPe6L.js} +1 -1
  135. package/static/dashboard/assets/{external-link-VbMQvVMz.js → external-link-B7wD1hkm.js} +1 -1
  136. package/static/dashboard/assets/index-tOBaUnM1.js +44 -0
  137. package/static/dashboard/assets/{refresh-cw-BxVxNxNr.js → refresh-cw-CFDZPaE8.js} +1 -1
  138. package/static/dashboard/assets/{services-status-context-DKmJ7ISr.js → services-status-context-DN1Icg4A.js} +1 -1
  139. package/static/dashboard/dashboard.html +1 -1
  140. package/static/settings/assets/ModelsPage-03NPWzoX.js +1 -0
  141. package/static/settings/assets/{PaneListHeader-Bgaze006.js → PaneListHeader-DMD8OJef.js} +1 -1
  142. package/static/settings/assets/PodPage-DT4EMYhL.js +2 -0
  143. package/static/settings/assets/ServicesPage-CJ0ub6IH.js +1 -0
  144. package/static/settings/assets/SettingsPage-BkR7ZK18.js +41 -0
  145. package/static/settings/assets/{card-B_bXSIn-.js → card-Cjsia0_V.js} +1 -1
  146. package/static/settings/assets/{services-status-context-DiX-AbrP.js → services-status-context-CkuKmH5h.js} +1 -1
  147. package/static/settings/assets/{settings-B30oMfZq.js → settings-Cyyv6-SD.js} +2 -2
  148. package/static/settings/assets/{workspace-layout-Dv1Yn9Ci.js → workspace-layout-B47luv6r.js} +1 -1
  149. package/static/settings/settings.html +1 -1
  150. package/dist/api/ai-gateway/auth/ClientCredentialsInternalPodAccessTokenProvider.d.ts +0 -25
  151. package/dist/api/ai-gateway/auth/ClientCredentialsInternalPodAccessTokenProvider.js +0 -91
  152. package/dist/api/ai-gateway/auth/ClientCredentialsInternalPodAccessTokenProvider.js.map +0 -1
  153. package/dist/api/ai-gateway/auth/GatewayApiKey.d.ts +0 -28
  154. package/dist/api/ai-gateway/auth/GatewayApiKey.js +0 -162
  155. package/dist/api/ai-gateway/auth/GatewayApiKey.js.map +0 -1
  156. package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.d.ts +0 -56
  157. package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.js +0 -143
  158. package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.js.map +0 -1
  159. package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.d.ts +0 -26
  160. package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.js +0 -97
  161. package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.js.map +0 -1
  162. package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.d.ts +0 -54
  163. package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.js +0 -152
  164. package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.js.map +0 -1
  165. package/static/dashboard/assets/NetworkPage-Brt79fuQ.js +0 -2
  166. package/static/dashboard/assets/PodPage-CM6do1vB.js +0 -2
  167. package/static/dashboard/assets/ServicesPage-BUNxGJRz.js +0 -1
  168. package/static/dashboard/assets/index-RfiFckzb.js +0 -51
  169. package/static/settings/assets/ModelsPage-D_IH7AH3.js +0 -1
  170. package/static/settings/assets/PodPage-Cy1VNObw.js +0 -2
  171. package/static/settings/assets/ServicesPage-BsFaxVWC.js +0 -1
  172. package/static/settings/assets/SettingsPage-UafNWE_p.js +0 -48
@@ -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;AAK/B,oEAA6E;AAsK7E,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,CAAC,KAK1B;QACC,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAC1E,MAAM,EAAE,GAAG,4BAAmB,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACnD,MAAM,GAAG,GAAG,MAAM,EAAE,CAAC,QAAQ,CAA0B,UAAU,EAAE,EAAE,CAAC,CAAC;QACvE,MAAM,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,uBAAuB,CAAC,GAAG,CAAC,CAAC,CAAC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AAC,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 { EncryptedCredentialSecret } from '../credentials/KeyWrapper';\nimport type { CredentialVault, GatewayPrincipal, ProviderSecret } from '../credentials/CredentialVault';\nimport type { GatewayDeployment } from '../auth/GatewayApiKey';\nimport type { ProviderRegistry } from '../providers/ProviderRegistry';\nimport { DEFAULT_PROVIDER_DESCRIPTORS } from '../providers/ProviderRegistry';\nimport type { AuthContext } from '../../auth/AuthContext';\nimport type { InternalPodAccessTokenProvider } from '../auth/PodGatewayAccessKeyRepository';\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 encryptedSecret: EncryptedCredentialSecret;\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 rewrapCredential?(input: {\n webId: string;\n deployment: GatewayDeployment;\n credentialId: string;\n expectedVersion?: number;\n encryptedSecret: EncryptedCredentialSecret;\n auth?: AuthContext;\n }): Promise<boolean>;\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) : 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 encryptedSecret: EncryptedCredentialSecret;\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(recordFromCredentialRow)\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 encryptedSecret: record.encryptedSecret,\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);\n }\n await db.insert(credential).values(row).execute();\n return recordFromCredentialRow(row);\n }\n\n public async rewrapCredential(input: {\n webId: string;\n deployment: GatewayDeployment;\n credentialId: string;\n expectedVersion?: number;\n encryptedSecret: EncryptedCredentialSecret;\n auth?: AuthContext;\n }): Promise<boolean> {\n const { db, credential } = await this.dbForOwner(input.webId, input.auth);\n const existing = await db.findById<Record<string, unknown>>(credential, input.credentialId);\n if (!existing) {\n return false;\n }\n const current = recordFromCredentialRow(existing);\n if (current.webId !== input.webId || current.deployment !== input.deployment) {\n return false;\n }\n const currentVersion = versionFromRow(existing);\n if (input.expectedVersion === undefined || currentVersion !== input.expectedVersion) {\n return false;\n }\n const updated = await db.update(credential)\n .set({\n encryptedSecret: JSON.stringify(input.encryptedSecret),\n wrappedDataKey: input.encryptedSecret.wrappedDek,\n encryptionAlgorithm: input.encryptedSecret.algorithm,\n keyVersion: String(currentVersion + 1),\n })\n .where(and(\n eq(credential.id, input.credentialId),\n eq(credential.keyVersion, String(input.expectedVersion)),\n ))\n .returning()\n .execute();\n return updated.length === 1;\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) : 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) : 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);\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): Promise<typeof fetch> {\n const trustedFetch = await this.internalPodAccess?.getTrustedFetch(owner);\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 vault: CredentialVault;\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 vault: CredentialVault;\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.vault = options.vault;\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 encryptedSecret = await this.vault.seal(\n principal(input.webId),\n credentialIri,\n this.provider,\n { type: 'apiKey', apiKey: input.apiKey },\n );\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 encryptedSecret,\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 const encryptedSecret = await this.vault.seal(principal(input.webId), credentialIri, 'kimi', secret);\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 encryptedSecret,\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 vault?: CredentialVault;\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 vault?: CredentialVault;\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 this.vault = options.vault;\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 || !this.vault) {\n throw new Error('CredentialVault and PodCredentialRepository are 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 = await this.vault.open(\n { webId: input.webId },\n current.credentialIri,\n normalizeProvider(input.provider),\n current.encryptedSecret,\n );\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 encryptedSecret: JSON.stringify(record.encryptedSecret),\n wrappedDataKey: record.encryptedSecret.wrappedDek,\n encryptionAlgorithm: record.encryptedSecret.algorithm,\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>): ConnectCredentialRecord {\n const encrypted = parseEncryptedSecret(row.encryptedSecret);\n const id = stringFrom(row.id);\n const provider = providerFromRelation(stringFrom(row.provider))\n || providerFromCredentialId(id);\n const deployment = deploymentFromCredentialId(id);\n const webId = encrypted.webId;\n return {\n id,\n credentialIri: encrypted.credentialIri,\n webId,\n provider,\n deployment,\n authMode: stringFrom(row.authMode) === 'deviceCodeOAuth' ? 'deviceCodeOAuth' : 'apiKey',\n encryptedSecret: encrypted,\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 parseEncryptedSecret(value: unknown): EncryptedCredentialSecret {\n if (typeof value !== 'string' || !value.trim()) {\n throw new Error('Credential row is missing encrypted secret payload');\n }\n const parsed = JSON.parse(value);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Credential row encrypted secret payload is invalid');\n }\n return parsed as EncryptedCredentialSecret;\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\nfunction principal(webId: string): GatewayPrincipal {\n return { webId };\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,0FAImD;AAGnD,oEAA6E;AA+J7E,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;QACj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S,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"]}
@@ -0,0 +1,17 @@
1
+ import type { ProviderSecret } from './CredentialVault';
2
+ export declare const PLAINTEXT_CREDENTIAL_STORAGE_MODE = "plaintext-v1";
3
+ export declare const SECRET_CELL_CREDENTIAL_STORAGE_MODE = "secret-cell-v1";
4
+ export type PlaintextCredentialStorageMode = typeof PLAINTEXT_CREDENTIAL_STORAGE_MODE;
5
+ export interface PlaintextCredentialRow {
6
+ storageMode?: unknown;
7
+ secretPayload?: unknown;
8
+ encryptedSecret?: unknown;
9
+ wrappedDataKey?: unknown;
10
+ encryptionAlgorithm?: unknown;
11
+ }
12
+ export declare class UnsupportedCredentialStorageModeError extends Error {
13
+ readonly storageMode: string;
14
+ constructor(storageMode: string);
15
+ }
16
+ export declare function encodePlaintextCredential(secret: ProviderSecret): string;
17
+ export declare function decodePlaintextCredential(row: PlaintextCredentialRow): ProviderSecret;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UnsupportedCredentialStorageModeError = exports.SECRET_CELL_CREDENTIAL_STORAGE_MODE = exports.PLAINTEXT_CREDENTIAL_STORAGE_MODE = void 0;
4
+ exports.encodePlaintextCredential = encodePlaintextCredential;
5
+ exports.decodePlaintextCredential = decodePlaintextCredential;
6
+ exports.PLAINTEXT_CREDENTIAL_STORAGE_MODE = 'plaintext-v1';
7
+ exports.SECRET_CELL_CREDENTIAL_STORAGE_MODE = 'secret-cell-v1';
8
+ class UnsupportedCredentialStorageModeError extends Error {
9
+ constructor(storageMode) {
10
+ super(`Unsupported credential storage mode: ${storageMode}`);
11
+ this.name = 'UnsupportedCredentialStorageModeError';
12
+ this.storageMode = storageMode;
13
+ }
14
+ }
15
+ exports.UnsupportedCredentialStorageModeError = UnsupportedCredentialStorageModeError;
16
+ function encodePlaintextCredential(secret) {
17
+ if (!isValidProviderSecret(secret)) {
18
+ throw new UnsupportedCredentialStorageModeError(exports.PLAINTEXT_CREDENTIAL_STORAGE_MODE);
19
+ }
20
+ return JSON.stringify(secret);
21
+ }
22
+ function decodePlaintextCredential(row) {
23
+ const storageMode = storageModeFromRow(row);
24
+ if (storageMode !== exports.PLAINTEXT_CREDENTIAL_STORAGE_MODE) {
25
+ throw new UnsupportedCredentialStorageModeError(storageMode);
26
+ }
27
+ if (typeof row.secretPayload !== 'string' || !row.secretPayload.trim()) {
28
+ throw new UnsupportedCredentialStorageModeError(storageMode);
29
+ }
30
+ let parsed;
31
+ try {
32
+ parsed = JSON.parse(row.secretPayload);
33
+ }
34
+ catch {
35
+ throw new UnsupportedCredentialStorageModeError(storageMode);
36
+ }
37
+ if (!isValidProviderSecret(parsed)) {
38
+ throw new UnsupportedCredentialStorageModeError(storageMode);
39
+ }
40
+ return parsed;
41
+ }
42
+ function storageModeFromRow(row) {
43
+ if (row.encryptedSecret !== undefined
44
+ || row.wrappedDataKey !== undefined
45
+ || row.encryptionAlgorithm !== undefined) {
46
+ return exports.SECRET_CELL_CREDENTIAL_STORAGE_MODE;
47
+ }
48
+ if (typeof row.storageMode === 'string' && row.storageMode.trim()) {
49
+ return row.storageMode.trim();
50
+ }
51
+ return 'missing';
52
+ }
53
+ function isPlainObject(value) {
54
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
55
+ }
56
+ function isValidProviderSecret(value) {
57
+ if (!isPlainObject(value)) {
58
+ return false;
59
+ }
60
+ return ['apiKey', 'accessToken', 'refreshToken', 'token'].some((field) => {
61
+ const token = value[field];
62
+ return typeof token === 'string' && token.trim().length > 0;
63
+ });
64
+ }
65
+ //# sourceMappingURL=PlaintextCredentialPayload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PlaintextCredentialPayload.js","sourceRoot":"","sources":["../../../../src/api/ai-gateway/credentials/PlaintextCredentialPayload.ts"],"names":[],"mappings":";;;AAyBA,8DAKC;AAED,8DAkBC;AAhDY,QAAA,iCAAiC,GAAG,cAAc,CAAC;AACnD,QAAA,mCAAmC,GAAG,gBAAgB,CAAC;AAYpE,MAAa,qCAAsC,SAAQ,KAAK;IAG9D,YAAmB,WAAmB;QACpC,KAAK,CAAC,wCAAwC,WAAW,EAAE,CAAC,CAAC;QAC7D,IAAI,CAAC,IAAI,GAAG,uCAAuC,CAAC;QACpD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AARD,sFAQC;AAED,SAAgB,yBAAyB,CAAC,MAAsB;IAC9D,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,EAAE,CAAC;QACnC,MAAM,IAAI,qCAAqC,CAAC,yCAAiC,CAAC,CAAC;IACrF,CAAC;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED,SAAgB,yBAAyB,CAAC,GAA2B;IACnE,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,WAAW,KAAK,yCAAiC,EAAE,CAAC;QACtD,MAAM,IAAI,qCAAqC,CAAC,WAAW,CAAC,CAAC;IAC/D,CAAC;IACD,IAAI,OAAO,GAAG,CAAC,aAAa,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,CAAC;QACvE,MAAM,IAAI,qCAAqC,CAAC,WAAW,CAAC,CAAC;IAC/D,CAAC;IACD,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IACzC,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,I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const PLAINTEXT_CREDENTIAL_STORAGE_MODE = 'plaintext-v1';\nexport const SECRET_CELL_CREDENTIAL_STORAGE_MODE = 'secret-cell-v1';\n\nexport type PlaintextCredentialStorageMode = typeof PLAINTEXT_CREDENTIAL_STORAGE_MODE;\n\nexport interface PlaintextCredentialRow {\n storageMode?: unknown;\n secretPayload?: unknown;\n encryptedSecret?: unknown;\n wrappedDataKey?: unknown;\n encryptionAlgorithm?: unknown;\n}\n\nexport class UnsupportedCredentialStorageModeError extends Error {\n public readonly storageMode: string;\n\n public constructor(storageMode: string) {\n super(`Unsupported credential storage mode: ${storageMode}`);\n this.name = 'UnsupportedCredentialStorageModeError';\n this.storageMode = storageMode;\n }\n}\n\nexport function encodePlaintextCredential(secret: ProviderSecret): string {\n if (!isValidProviderSecret(secret)) {\n throw new UnsupportedCredentialStorageModeError(PLAINTEXT_CREDENTIAL_STORAGE_MODE);\n }\n return JSON.stringify(secret);\n}\n\nexport function decodePlaintextCredential(row: PlaintextCredentialRow): ProviderSecret {\n const storageMode = storageModeFromRow(row);\n if (storageMode !== PLAINTEXT_CREDENTIAL_STORAGE_MODE) {\n throw new UnsupportedCredentialStorageModeError(storageMode);\n }\n if (typeof row.secretPayload !== 'string' || !row.secretPayload.trim()) {\n throw new UnsupportedCredentialStorageModeError(storageMode);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(row.secretPayload);\n } catch {\n throw new UnsupportedCredentialStorageModeError(storageMode);\n }\n if (!isValidProviderSecret(parsed)) {\n throw new UnsupportedCredentialStorageModeError(storageMode);\n }\n return parsed;\n}\n\nfunction storageModeFromRow(row: PlaintextCredentialRow): string {\n if (\n row.encryptedSecret !== undefined\n || row.wrappedDataKey !== undefined\n || row.encryptionAlgorithm !== undefined\n ) {\n return SECRET_CELL_CREDENTIAL_STORAGE_MODE;\n }\n if (typeof row.storageMode === 'string' && row.storageMode.trim()) {\n return row.storageMode.trim();\n }\n return 'missing';\n}\n\nfunction isPlainObject(value: unknown): value is ProviderSecret {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isValidProviderSecret(value: unknown): value is ProviderSecret {\n if (!isPlainObject(value)) {\n return false;\n }\n return ['apiKey', 'accessToken', 'refreshToken', 'token'].some((field) => {\n const token = value[field];\n return typeof token === 'string' && token.trim().length > 0;\n });\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import type { AuthContext } from '../../auth/AuthContext';
2
+ export interface InternalPodAccessTokenProvider {
3
+ getTrustedFetch(owner: string, auth?: InternalPodAccessAuthContext): Promise<typeof fetch | undefined>;
4
+ }
5
+ export type InternalPodAccessAuthContext = AuthContext | undefined;
6
+ export interface HostedPodDataAccessOptions {
7
+ cssBaseUrl: string;
8
+ gatewayAdminProxyAuthSecret?: string;
9
+ fetch?: typeof fetch;
10
+ now?: () => number;
11
+ nonce?: () => string;
12
+ }
13
+ export declare class HostedPodDataAccess implements InternalPodAccessTokenProvider {
14
+ private readonly cssBaseUrl;
15
+ private readonly gatewayAdminProxyAuthSecret?;
16
+ private readonly fetch;
17
+ private readonly now;
18
+ private readonly nonce;
19
+ constructor(options: HostedPodDataAccessOptions);
20
+ getTrustedFetch(owner: string, auth?: InternalPodAccessAuthContext): Promise<typeof fetch | undefined>;
21
+ private authorize;
22
+ private assertHostedAllowedResource;
23
+ private headersForLoopback;
24
+ }