@opengeni/db 6.0.1 → 6.0.3-canary.36199476632001
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser-sessions.d.ts +42 -1
- package/dist/canonical-human-identities.js +3 -3
- package/dist/capability-reconciliation.js +2 -2
- package/dist/{chunk-PGIFHEBA.js → chunk-2ECQTYFE.js} +2 -2
- package/dist/{chunk-GSB4ISHE.js → chunk-6PRATKUO.js} +7 -1
- package/dist/chunk-6PRATKUO.js.map +1 -0
- package/dist/{chunk-I7HQL6FK.js → chunk-6TNYHO5J.js} +3 -3
- package/dist/{chunk-CSVHCF3R.js → chunk-BUU6E72R.js} +11 -4
- package/dist/{chunk-CSVHCF3R.js.map → chunk-BUU6E72R.js.map} +1 -1
- package/dist/{chunk-6ORJPCYW.js → chunk-EVLC5YYT.js} +2 -2
- package/dist/{chunk-LO6BVXXH.js → chunk-GOS25XY6.js} +2 -2
- package/dist/{chunk-4CCFFLDZ.js → chunk-JEKW3C74.js} +13 -2
- package/dist/chunk-JEKW3C74.js.map +1 -0
- package/dist/{chunk-MAMBI2HR.js → chunk-JPYN5XKV.js} +39 -3
- package/dist/chunk-JPYN5XKV.js.map +1 -0
- package/dist/{chunk-RXH5CFG3.js → chunk-NO53BF7E.js} +12 -8
- package/dist/{chunk-RXH5CFG3.js.map → chunk-NO53BF7E.js.map} +1 -1
- package/dist/chunk-OYD7FLKH.js +796 -0
- package/dist/chunk-OYD7FLKH.js.map +1 -0
- package/dist/{chunk-JILAWE26.js → chunk-PIVVJPQ3.js} +2 -2
- package/dist/{chunk-FULLE5CF.js → chunk-RUEJOEIC.js} +3 -3
- package/dist/{chunk-H7BC444C.js → chunk-SRAMNVHT.js} +17 -1
- package/dist/chunk-SRAMNVHT.js.map +1 -0
- package/dist/{chunk-4RDUZ5UV.js → chunk-VNNQAS7Y.js} +2 -2
- package/dist/{chunk-XK6HXON2.js → chunk-YDBISTFL.js} +2 -2
- package/dist/{chunk-LSLNMENV.js → chunk-YKSJABR2.js} +4 -4
- package/dist/code-search-policy.d.ts +3 -0
- package/dist/connect-attempts.js +3 -3
- package/dist/connection-token-resolver.d.ts +4 -1
- package/dist/database.d.ts +8 -0
- package/dist/editable-artifact-durable-export.js +2 -2
- package/dist/editable-artifacts.js +3 -3
- package/dist/index.d.ts +81 -21
- package/dist/index.js +2052 -2292
- package/dist/index.js.map +1 -1
- package/dist/knowledge-entries.d.ts +2 -0
- package/dist/knowledge-indexing.d.ts +17 -0
- package/dist/managed-auth-session-sets.js +3 -3
- package/dist/managed-user-setup.d.ts +1 -0
- package/dist/mcp-operations.js +2 -2
- package/dist/migrate.d.ts +10 -1
- package/dist/migrate.js +3 -1
- package/dist/new-session-drafts.d.ts +8 -0
- package/dist/organization-integration-policy.js +3 -3
- package/dist/organization-membership-lifecycle.d.ts +1 -0
- package/dist/provision-roles.js +1 -1
- package/dist/retained-provider-commands.d.ts +4 -2
- package/dist/retained-provider-commands.js +6 -6
- package/dist/runtime-posture.d.ts +1 -1
- package/dist/schema.d.ts +44 -10
- package/dist/schema.js +1 -1
- package/dist/session-background-commands.js +4 -4
- package/dist/session-command-output.js +5 -5
- package/dist/session-event-slices.js +3 -3
- package/dist/session-mcp-credential-rotation.d.ts +15 -4
- package/dist/session-mcp-credential-rotation.js +38 -7
- package/dist/session-mcp-credential-rotation.js.map +1 -1
- package/dist/session-tenancy.js +3 -3
- package/dist/video-generation.js +3 -3
- package/dist/workspace-tool-defaults.js +4 -4
- package/dist/xai-subscription.d.ts +9 -0
- package/drizzle/0508_deadline_command_workspace_capture.sql +75 -0
- package/drizzle/0509_verified_signup_trial_credits.sql +76 -0
- package/drizzle/0510_knowledge_index_funding_wait.sql +174 -0
- package/drizzle/0511_knowledge_visible_index_status.sql +56 -0
- package/drizzle/0512_insights_fact_reads_hash_join.sql +31 -0
- package/drizzle/0513_message_fork_prefix_compaction.sql +85 -0
- package/drizzle/0514_failed_session_variable_set_attach.sql +25 -0
- package/drizzle/0515_autonomous_learning_defaults.sql +35 -0
- package/drizzle/0516_member_connection_read.sql +105 -0
- package/drizzle/0517_member_connection_read_backfill_index.sql +21 -0
- package/drizzle/0518_member_connection_read_backfill.sql +37 -0
- package/drizzle/0519_session_recovery_backlog_excludes_paused.sql +167 -0
- package/drizzle/0520_session_code_search_frozen.sql +6 -0
- package/package.json +6 -6
- package/src/browser-sessions.ts +161 -6
- package/src/code-search-policy.ts +25 -0
- package/src/connection-token-resolver.ts +16 -1
- package/src/database.ts +18 -0
- package/src/index.ts +759 -257
- package/src/insights.ts +44 -36
- package/src/knowledge-entries.ts +43 -2
- package/src/knowledge-indexing.ts +79 -1
- package/src/managed-user-setup.ts +18 -1
- package/src/migrate.ts +58 -1
- package/src/new-session-drafts.ts +25 -1
- package/src/organization-membership-lifecycle.ts +11 -0
- package/src/provision-roles.ts +12 -0
- package/src/retained-provider-commands.ts +16 -6
- package/src/runtime-posture.ts +4 -0
- package/src/schema.ts +6 -0
- package/src/session-mcp-credential-rotation.ts +57 -9
- package/src/xai-subscription.ts +14 -1
- package/dist/chunk-4CCFFLDZ.js.map +0 -1
- package/dist/chunk-GSB4ISHE.js.map +0 -1
- package/dist/chunk-H7BC444C.js.map +0 -1
- package/dist/chunk-MAMBI2HR.js.map +0 -1
- /package/dist/{chunk-PGIFHEBA.js.map → chunk-2ECQTYFE.js.map} +0 -0
- /package/dist/{chunk-I7HQL6FK.js.map → chunk-6TNYHO5J.js.map} +0 -0
- /package/dist/{chunk-6ORJPCYW.js.map → chunk-EVLC5YYT.js.map} +0 -0
- /package/dist/{chunk-LO6BVXXH.js.map → chunk-GOS25XY6.js.map} +0 -0
- /package/dist/{chunk-JILAWE26.js.map → chunk-PIVVJPQ3.js.map} +0 -0
- /package/dist/{chunk-FULLE5CF.js.map → chunk-RUEJOEIC.js.map} +0 -0
- /package/dist/{chunk-4RDUZ5UV.js.map → chunk-VNNQAS7Y.js.map} +0 -0
- /package/dist/{chunk-XK6HXON2.js.map → chunk-YDBISTFL.js.map} +0 -0
- /package/dist/{chunk-LSLNMENV.js.map → chunk-YKSJABR2.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/connection-token-resolver.ts","../src/connection-refresh-lock.ts","../src/connection-scopes.ts"],"sourcesContent":["import {\n environmentsEncryptionKeyBytes,\n type McpServerConnectionRef,\n type Settings,\n} from \"@opengeni/config\";\nimport type {\n ConnectionCredentialPlacement,\n ConnectionKind,\n ConnectionStatus,\n ConnectionMetadata,\n McpConnectionResourceScope,\n McpCredentialAuthNeededReason,\n} from \"@opengeni/contracts\";\n\nimport { type ConnectionUseAttribution } from \"@opengeni/contracts/connection-authority\";\nimport {\n PERSONAL_GITHUB_REQUESTED_SCOPES,\n PERSONAL_GITHUB_PROVIDER_DOMAIN,\n PERSONAL_GITHUB_TOKEN_URL,\n PersonalGitHubConnectionMetadata,\n} from \"@opengeni/contracts/personal-github\";\nimport { createHash } from \"node:crypto\";\nimport {\n OAUTH_MAX_RESPONSE_BYTES,\n pinnedFetch,\n readResponseJsonBounded,\n undiciFetch,\n validateHttpUrl,\n type DnsLookup,\n type FetchLike,\n} from \"@opengeni/network\";\nexport { isPrivateAddress } from \"@opengeni/network\";\nimport { Buffer } from \"node:buffer\";\nimport { encryptEnvironmentValue } from \"./environment-crypto\";\nimport type { Database } from \"./database\";\nimport { withConnectionRefreshLock } from \"./connection-refresh-lock\";\nimport type {\n AcceptedConnectionUseContext,\n AcceptedConnectionUseResolution,\n} from \"./connection-authority\";\nimport { connectionScopeKey } from \"./connection-scopes\";\n\nconst MAX_CREDENTIAL_PLACEMENTS = 32;\nconst MAX_CREDENTIAL_NAME_BYTES = 256;\nconst MAX_CREDENTIAL_VALUE_BYTES = 16_384;\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;\nconst QUERY_NAME_PATTERN = /^[A-Za-z0-9._~-]+$/;\nconst COOKIE_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nconst FORBIDDEN_CREDENTIAL_HEADERS = new Set([\n \"connection\",\n \"content-length\",\n \"host\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\nexport type ConnectionCredentialForBroker = {\n id: string;\n accountId: string;\n workspaceId: string;\n subjectId: string | null;\n providerDomain: string;\n kind: ConnectionKind;\n status: ConnectionStatus;\n credential: Record<string, unknown>;\n grantedScopes: string[];\n expiresAt: Date | null;\n lastRefreshAt: Date | null;\n version: number;\n /** Immutable execution authority generation; distinct from token refresh version. */\n authorityGeneration?: number;\n metadata: Record<string, unknown>;\n};\n\nexport type ConnectionCredentialLookupInput = {\n workspaceId: string;\n connectionId?: string;\n providerDomain: string;\n kind?: ConnectionKind;\n subjectId?: string | null;\n allowSubjectOwned?: boolean;\n expectedAuthorityGeneration?: number;\n};\n\nexport type ConnectionTokenRefreshInput = {\n id: string;\n version: number;\n workspaceId: string;\n credentialEncrypted: string;\n expiresAt: Date | null;\n grantedScopes?: string[];\n metadata?: Record<string, unknown>;\n lastRefreshAt: Date;\n subjectId?: string | null;\n};\n\nexport type ConnectionStatusGuard = {\n id: string;\n version: number;\n subjectId?: string | null;\n};\n\nexport type ResolveConnectionCredentialResult =\n | {\n status: \"ok\";\n headers: Record<string, string>;\n /** Credential authority is owned by the embedding host, not the native connection store. */\n authoritySource?: \"host\";\n /** Present when the credential bundle or embedding host supplied explicit placements. */\n placements?: ConnectionCredentialPlacement[];\n connectionId: string;\n /** Exact durable version when the credential came from the local connection store. */\n connectionVersion?: number;\n /** Metadata-only owner attribution from the immediate pre-use fence. */\n connectionUseAttribution?: ConnectionUseAttribution;\n /** Metadata-only equality key from current live authority; never credentials or authorization. */\n operationAuthorityDigest?: string;\n /**\n * Revalidate the exact accepted attempt immediately before one target\n * provider request. Credential lookup/refresh is a separate audited\n * boundary and must not manufacture a provider-request fact by itself.\n */\n authorizeProviderRequest?: () => Promise<boolean>;\n expiresAt?: Date | null;\n }\n | {\n status: \"auth_needed\";\n reason: McpCredentialAuthNeededReason;\n providerDomain: string;\n /** Credential authority is owned by the embedding host, not the native connection store. */\n authoritySource?: \"host\";\n provider?: string;\n connectionId?: string;\n scopes?: string[];\n resource?: string;\n selectedResources?: McpConnectionResourceScope[];\n authorizationUrl?: string;\n };\ntype AuthNeededReason = Extract<\n ResolveConnectionCredentialResult,\n { status: \"auth_needed\" }\n>[\"reason\"];\n\nexport type ResolveConnectionCredentialInput = {\n workspaceId: string;\n subjectId?: string;\n serverId: string;\n toolName?: string;\n /** @deprecated Use toolName. Retained for the API's pre-existing broker call shape. */\n toolId?: string;\n connectionRef: McpServerConnectionRef;\n /** Exact MCP destination whose request would receive the resolved headers. */\n destinationUrl: string;\n /** Defaults to header-only MCP transport. */\n credentialTarget?: \"mcp\" | \"http_api\";\n forceRefresh?: boolean;\n /** Internal lookup mode. Preflight must not refresh credentials or record provider usage. */\n credentialResolutionMode?: \"execution\" | \"preflight\";\n /** Frozen provider authority generation captured by the calling integration/catalog. */\n expectedAuthorityGeneration?: number;\n /** Attribution already authorized for forwarding to a host resolver; never authorizes local use. */\n hostConnectionUseAttribution?: ConnectionUseAttribution;\n /** Exact accepted attempt plus one stable physical-provider request id. */\n connectionUseContext?: AcceptedConnectionUseContext;\n};\n\nconst OFFICIAL_GMAIL_MCP_RESOURCE = \"https://gmailmcp.googleapis.com/mcp/v1\";\nconst OFFICIAL_GMAIL_REST_HOST = \"gmail.googleapis.com\";\n\n/**\n * The Gmail bridge reuses the exact OAuth grant created for the official\n * hosted Gmail MCP resource, executing every tool against Gmail's REST API\n * instead of Google's Developer Preview MCP endpoint. Keep this exception\n * narrower than ordinary provider-domain binding: HTTPS only, Google's\n * canonical Gmail API host, and the authenticated `users/me` path.\n */\nfunction isOfficialGmailRestDestination(\n destinationUrl: string,\n ref: McpServerConnectionRef,\n): boolean {\n if (\n ref.providerDomain.toLowerCase() !== \"gmailmcp.googleapis.com\" ||\n ref.kind !== \"oauth2\" ||\n ref.subjectScope !== \"subject\"\n ) {\n return false;\n }\n const destination = new URL(destinationUrl);\n return (\n destination.protocol === \"https:\" &&\n destination.hostname.toLowerCase() === OFFICIAL_GMAIL_REST_HOST &&\n (destination.pathname === \"/gmail/v1/users/me\" ||\n destination.pathname.startsWith(\"/gmail/v1/users/me/\"))\n );\n}\n\n/**\n * Adapts the public embedding credential port to the runtime's connection\n * resolver contract. Scope echoes are checked before credential headers can\n * reach a request; the returned object is a fresh copy so a host cannot mutate\n * headers after resolution.\n */\n\nfunction copySelectedResources(\n resources: McpConnectionResourceScope[],\n): McpConnectionResourceScope[] {\n if (resources.length === 0 || resources.length > 256) {\n throw new Error(\"connection credential returned an invalid selected resource count\");\n }\n const seen = new Set<string>();\n return resources.map((resource) => {\n if (\n resource.kind !== \"repository\" ||\n typeof resource.id !== \"string\" ||\n resource.id.length === 0 ||\n resource.id.length > 512\n ) {\n throw new Error(\"connection credential returned an invalid selected resource\");\n }\n const key = `${resource.kind}\\0${resource.id}`;\n if (seen.has(key)) {\n throw new Error(\"connection credential returned duplicate selected resources\");\n }\n seen.add(key);\n return { kind: resource.kind, id: resource.id };\n });\n}\n\nexport function normalizedCredentialHeaders(\n headers: Record<string, string>,\n allowEmpty = false,\n): Record<string, string> {\n const entries = Object.entries(headers);\n if ((!allowEmpty && entries.length === 0) || entries.length > 32) {\n throw new Error(\"connection credential returned an invalid header count\");\n }\n const normalized: Record<string, string> = {};\n for (const [name, value] of entries) {\n if (\n name.length > 256 ||\n !HEADER_NAME_PATTERN.test(name) ||\n value.length === 0 ||\n value.length > 16_384 ||\n /[\\r\\n\\0]/.test(value) ||\n FORBIDDEN_CREDENTIAL_HEADERS.has(name.toLowerCase()) ||\n name.toLowerCase().startsWith(\"sec-\")\n ) {\n throw new Error(\"connection credential returned an invalid header\");\n }\n if (Object.keys(normalized).some((existing) => existing.toLowerCase() === name.toLowerCase())) {\n throw new Error(\"connection credential returned duplicate headers\");\n }\n normalized[name] = value;\n }\n return normalized;\n}\n\nfunction normalizedCredentialPlacements(value: unknown): ConnectionCredentialPlacement[] {\n if (!Array.isArray(value) || value.length === 0 || value.length > MAX_CREDENTIAL_PLACEMENTS) {\n throw new Error(\"connection credential returned an invalid placement count\");\n }\n const seen = new Set<string>();\n return value.map((raw) => {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(\"connection credential returned an invalid placement\");\n }\n const record = raw as Record<string, unknown>;\n if (\n Object.keys(record).some(\n (key) => key !== \"carrier\" && key !== \"name\" && key !== \"value\" && key !== \"prefix\",\n )\n ) {\n throw new Error(\"connection credential returned an invalid placement\");\n }\n const carrier = record.carrier;\n const name = record.name;\n const credentialValue = record.value;\n const prefix = record.prefix;\n if (\n (carrier !== \"header\" && carrier !== \"query\" && carrier !== \"cookie\") ||\n typeof name !== \"string\" ||\n name.length === 0 ||\n Buffer.byteLength(name) > MAX_CREDENTIAL_NAME_BYTES ||\n typeof credentialValue !== \"string\" ||\n credentialValue.length === 0 ||\n (typeof prefix !== \"undefined\" && typeof prefix !== \"string\") ||\n /[\\r\\n\\0]/.test(name) ||\n /[\\r\\n\\0]/.test(credentialValue) ||\n (typeof prefix === \"string\" && /[\\r\\n\\0]/.test(prefix)) ||\n Buffer.byteLength(`${typeof prefix === \"string\" ? prefix : \"\"}${credentialValue}`) >\n MAX_CREDENTIAL_VALUE_BYTES\n ) {\n throw new Error(\"connection credential returned an invalid placement\");\n }\n const normalizedName = carrier === \"header\" ? name.toLowerCase() : name;\n if (\n (carrier === \"header\" &&\n (!HEADER_NAME_PATTERN.test(name) ||\n FORBIDDEN_CREDENTIAL_HEADERS.has(normalizedName) ||\n normalizedName.startsWith(\"sec-\"))) ||\n (carrier === \"query\" && !QUERY_NAME_PATTERN.test(name)) ||\n (carrier === \"cookie\" &&\n (!COOKIE_NAME_PATTERN.test(name) || /;/.test(`${prefix ?? \"\"}${credentialValue}`)))\n ) {\n throw new Error(\"connection credential returned an invalid placement\");\n }\n const key = `${carrier}\\0${normalizedName}`;\n if (seen.has(key)) {\n throw new Error(\"connection credential returned duplicate placements\");\n }\n seen.add(key);\n return {\n carrier,\n name,\n value: credentialValue,\n ...(typeof prefix === \"string\" && prefix.length > 0 ? { prefix } : {}),\n };\n });\n}\n\nfunction headerMapForPlacements(\n placements: readonly ConnectionCredentialPlacement[],\n): Record<string, string> {\n const headers: Record<string, string> = {};\n for (const placement of placements) {\n if (placement.carrier === \"header\") {\n headers[placement.name] = `${placement.prefix ?? \"\"}${placement.value}`;\n }\n }\n return headers;\n}\n\nexport type ConnectionBrokerDeps = {\n loadCredential: (\n db: Database,\n settings: Settings,\n input: ConnectionCredentialLookupInput,\n ) => Promise<ConnectionCredentialForBroker | null>;\n recordRefresh: (db: Database, input: ConnectionTokenRefreshInput) => Promise<boolean>;\n setStatus: (\n db: Database,\n workspaceId: string,\n status: ConnectionStatus,\n lastError: string | null,\n guard: ConnectionStatusGuard,\n ) => Promise<boolean>;\n recordUsed: (\n db: Database,\n workspaceId: string,\n connectionId: string,\n subjectId?: string | null,\n ) => Promise<void>;\n refresh: typeof refreshOAuthConnectionCredential;\n /** Test/adapter seam; standalone defaults to the database-backed refresh lock. */\n withRefreshLock?: typeof withConnectionRefreshLock;\n encrypt: typeof encryptEnvironmentValue;\n keyBytes: typeof environmentsEncryptionKeyBytes;\n now: () => Date;\n authorizeAcceptedUse?: (\n db: Database,\n input: AcceptedConnectionUseContext & {\n serverId: string;\n connectionId?: string;\n providerDomain: string;\n connectionKind?: ConnectionKind;\n subjectScope?: \"workspace\" | \"subject\";\n ownerSubjectId?: string;\n },\n ) => Promise<AcceptedConnectionUseResolution>;\n};\n\nexport type PermanentConnectionRefreshFailure = {\n workspaceId: string;\n connectionId: string;\n connectionVersion: number;\n subjectId: string | null;\n providerDomain: string;\n httpStatus: number;\n oauthErrorCode: string | null;\n};\n\nexport type ConnectionTokenResolverOptions = {\n /** Provider-aware transport override used by local/integration adapters. */\n refreshTransport?: RefreshTransportOptions;\n /**\n * Optional provider adapter for an atomic, metadata-aware permanent refresh\n * transition. Returning true means the adapter owned the transition (even if\n * its CAS lost to newer truth); false falls back to generic needs_reauth.\n */\n transitionPermanentRefreshFailure?: (\n failure: PermanentConnectionRefreshFailure,\n ) => Promise<boolean>;\n};\n\nexport type RefreshTransportOptions = {\n fetchImpl?: FetchLike;\n dnsLookup?: DnsLookup;\n};\n\nconst inflight = new Map<string, Promise<ConnectionCredentialForBroker>>();\nconst REFRESH_WINDOW_MS = 60_000;\nconst CONNECTION_REFRESH_TIMEOUT_MS = 10_000;\n\nexport function buildConnectionTokenResolver(\n db: Database,\n settings: Settings,\n deps: ConnectionBrokerDeps,\n options: ConnectionTokenResolverOptions = {},\n): (input: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult> {\n type CredentialLookupInput = Pick<\n ResolveConnectionCredentialInput,\n \"workspaceId\" | \"connectionRef\" | \"subjectId\"\n > & { expectedAuthorityGeneration?: number };\n const load = async (\n input: CredentialLookupInput,\n lookupDb: Database = db,\n ): Promise<ConnectionCredentialForBroker | null> => {\n const subjectOwned = input.connectionRef.subjectScope === \"subject\";\n if (subjectOwned && !input.subjectId) {\n return null;\n }\n const request: ConnectionCredentialLookupInput = {\n workspaceId: input.workspaceId,\n providerDomain: input.connectionRef.providerDomain,\n allowSubjectOwned: subjectOwned,\n ...(subjectOwned ? { subjectId: input.subjectId! } : {}),\n ...(input.expectedAuthorityGeneration !== undefined\n ? { expectedAuthorityGeneration: input.expectedAuthorityGeneration }\n : {}),\n };\n if (input.connectionRef.connectionId !== undefined) {\n request.connectionId = input.connectionRef.connectionId;\n }\n if (input.connectionRef.kind !== undefined) {\n request.kind = input.connectionRef.kind;\n }\n const credential = await deps.loadCredential(lookupDb, settings, request);\n if (!credential) return null;\n if (\n input.expectedAuthorityGeneration !== undefined &&\n credential.authorityGeneration !== input.expectedAuthorityGeneration\n ) {\n return null;\n }\n if (subjectOwned) {\n return credential.subjectId === input.subjectId ? credential : null;\n }\n return credential.subjectId === null ? credential : null;\n };\n\n const snapshot = async (\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n destinationUrl: string,\n inputCredentialTarget: \"mcp\" | \"http_api\",\n connectionUseAttribution?: ConnectionUseAttribution,\n recordUsage = true,\n ): Promise<ResolveConnectionCredentialResult> => {\n if (cred.status !== \"active\") {\n return authNeededForStatus(cred, ref);\n }\n if (!connectionBindingMatches(cred, ref, destinationUrl)) {\n return authNeeded(ref, \"missing_connection\", cred.id);\n }\n const missingScopes = missingRequestedScopes(\n ref.scopes,\n cred.grantedScopes,\n cred.providerDomain,\n );\n if (missingScopes.length > 0) {\n return {\n status: \"auth_needed\",\n reason: \"insufficient_scope\",\n providerDomain: ref.providerDomain,\n ...(ref.provider ? { provider: ref.provider } : {}),\n connectionId: cred.id,\n scopes: missingScopes,\n ...(ref.resource ? { resource: ref.resource } : {}),\n ...(ref.selectedResources\n ? { selectedResources: copySelectedResources(ref.selectedResources) }\n : {}),\n };\n }\n const material = credentialMaterialForConnection(cred, inputCredentialTarget);\n if (material.status !== \"ok\") {\n return {\n status: \"auth_needed\",\n reason: material.status === \"unsupported\" ? \"unsupported_auth\" : \"refresh_failed\",\n providerDomain: ref.providerDomain,\n ...(ref.provider ? { provider: ref.provider } : {}),\n connectionId: cred.id,\n ...(ref.scopes ? { scopes: ref.scopes } : {}),\n ...(ref.resource ? { resource: ref.resource } : {}),\n ...(ref.selectedResources\n ? { selectedResources: copySelectedResources(ref.selectedResources) }\n : {}),\n };\n }\n if (recordUsage) {\n await deps.recordUsed(db, cred.workspaceId, cred.id, cred.subjectId);\n }\n return {\n status: \"ok\",\n headers: material.headers,\n ...(material.placements ? { placements: material.placements } : {}),\n connectionId: cred.id,\n connectionVersion: cred.version,\n ...(connectionUseAttribution ? { connectionUseAttribution } : {}),\n expiresAt: cred.expiresAt,\n };\n };\n\n const performRefresh = async (\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n lockedDb: Database,\n ): Promise<ConnectionCredentialForBroker> => {\n const key = deps.keyBytes(settings);\n if (!key) {\n throw new Error(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is not configured\");\n }\n const refreshed = await deps.refresh(cred, ref, settings, options.refreshTransport);\n const refreshRecord: ConnectionTokenRefreshInput = {\n id: cred.id,\n version: cred.version,\n workspaceId: cred.workspaceId,\n credentialEncrypted: deps.encrypt(key, JSON.stringify(refreshed.credential)),\n expiresAt: refreshed.expiresAt,\n lastRefreshAt: deps.now(),\n subjectId: cred.subjectId,\n };\n if (refreshed.grantedScopes !== undefined) {\n refreshRecord.grantedScopes = refreshed.grantedScopes;\n }\n if (refreshed.metadata !== undefined) {\n refreshRecord.metadata = refreshed.metadata;\n }\n const persisted = await deps.recordRefresh(lockedDb, refreshRecord);\n if (persisted) {\n const current = await load(\n {\n workspaceId: cred.workspaceId,\n connectionRef: { ...ref, connectionId: cred.id },\n ...(cred.subjectId ? { subjectId: cred.subjectId } : {}),\n },\n lockedDb,\n );\n if (current) {\n return current;\n }\n }\n const winner = await load(\n {\n workspaceId: cred.workspaceId,\n connectionRef: { ...ref, connectionId: cred.id },\n ...(cred.subjectId ? { subjectId: cred.subjectId } : {}),\n },\n lockedDb,\n );\n if (winner?.status === \"active\") {\n return winner;\n }\n throw new Error(\"connection credential changed during token refresh\");\n };\n\n const refreshSingleFlight = (\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n ): Promise<ConnectionCredentialForBroker> => {\n const key = `${cred.subjectId ?? \"workspace\"}:${cred.id}:${cred.version}`;\n const existing = inflight.get(key);\n if (existing) {\n return existing;\n }\n const promise = (deps.withRefreshLock ?? withConnectionRefreshLock)(\n db,\n cred,\n async (lockedDb) => {\n // A different worker may have rotated while this request waited. Never\n // exchange the old token again, or switch to another authority generation.\n const current = await load(\n {\n workspaceId: cred.workspaceId,\n connectionRef: { ...ref, connectionId: cred.id },\n ...(cred.subjectId ? { subjectId: cred.subjectId } : {}),\n },\n lockedDb,\n );\n if (!current || current.authorityGeneration !== cred.authorityGeneration)\n throw new Error(\"Connection authority changed before token refresh\");\n if (current.status !== \"active\" || current.version !== cred.version) return current;\n return performRefresh(current, ref, lockedDb);\n },\n ).finally(() => {\n if (inflight.get(key) === promise) {\n inflight.delete(key);\n }\n });\n inflight.set(key, promise);\n return promise;\n };\n\n return async (input) => {\n const credentialResolutionMode = input.credentialResolutionMode ?? \"execution\";\n let ref = input.connectionRef;\n let subjectId = input.subjectId;\n let credentialWorkspaceId = input.workspaceId;\n let expectedAuthorityGeneration = input.expectedAuthorityGeneration;\n let connectionUseAttribution: ConnectionUseAttribution | undefined;\n if (ref.authoritySource === \"host\") {\n return authNeeded(ref, \"unsupported_auth\", ref.connectionId);\n }\n // Repository-scoped provider bindings require a broker that can prove the\n // selected-resource boundary. The generic standalone credential store has\n // no provider-specific containment adapter, so it must fail closed instead\n // of handing an account-wide token to the configured endpoint.\n if (ref.selectedResources) {\n return authNeeded(ref, \"resource_scope_unavailable\", ref.connectionId);\n }\n if (input.connectionUseContext !== undefined) {\n if (!deps.authorizeAcceptedUse) {\n return authNeeded(\n ref,\n ref.subjectScope === \"subject\" ? \"personal_authority_unavailable\" : \"missing_connection\",\n ref.connectionId,\n );\n }\n const authorization = await deps.authorizeAcceptedUse(db, {\n ...input.connectionUseContext,\n serverId: input.serverId,\n ...(ref.connectionId ? { connectionId: ref.connectionId } : {}),\n providerDomain: ref.providerDomain,\n ...(ref.kind ? { connectionKind: ref.kind } : {}),\n subjectScope: ref.subjectScope === \"subject\" ? \"subject\" : \"workspace\",\n // An owner binding belongs only to the personal lanes. Interactive\n // turns stamp the initiating human's subjectId on every credential\n // request regardless of ref scope; forwarding it for a workspace ref\n // would make the 0279 workspace lane deny the ambient shared row.\n ...(ref.subjectScope === \"subject\" && subjectId ? { ownerSubjectId: subjectId } : {}),\n });\n if (authorization.status === \"denied\") {\n return authNeeded(\n ref,\n ref.subjectScope === \"subject\" ? \"personal_authority_unavailable\" : \"missing_connection\",\n ref.connectionId,\n );\n }\n if (\n expectedAuthorityGeneration !== undefined &&\n authorization.attribution.connectionGeneration !== expectedAuthorityGeneration\n ) {\n return authNeeded(\n ref,\n authorityReasonForScope(ref.subjectScope === \"subject\"),\n ref.connectionId,\n );\n }\n connectionUseAttribution = authorization.attribution;\n expectedAuthorityGeneration = authorization.attribution.connectionGeneration;\n const expectedPersonal = authorization.attribution.scope !== \"workspace\";\n credentialWorkspaceId = authorization.originWorkspaceId;\n subjectId = authorization.attribution.ownerSubjectId ?? undefined;\n ref = {\n ...ref,\n connectionId: authorization.attribution.connectionId,\n kind: authorization.connectionKind,\n subjectScope: expectedPersonal ? \"subject\" : \"workspace\",\n };\n }\n if (ref.subjectScope === \"subject\" && !subjectId) {\n return authNeeded(ref, \"personal_authority_unavailable\", ref.connectionId);\n }\n let cred: ConnectionCredentialForBroker | null;\n try {\n cred = await load({\n workspaceId: credentialWorkspaceId,\n connectionRef: ref,\n ...(subjectId ? { subjectId } : {}),\n ...(expectedAuthorityGeneration !== undefined ? { expectedAuthorityGeneration } : {}),\n });\n } catch {\n return authNeeded(ref, \"refresh_failed\");\n }\n if (!cred) {\n return authNeeded(ref, \"missing_connection\");\n }\n if (cred.status !== \"active\") {\n return authNeededForStatus(cred, ref);\n }\n // Reject an audience/destination mismatch before any provider-side refresh\n // or usage update. Refreshing first would still create an unauthorized\n // external side effect even though the token was never sent to the target.\n if (!connectionBindingMatches(cred, ref, input.destinationUrl)) {\n return authNeeded(ref, \"missing_connection\", cred.id);\n }\n const now = deps.now();\n if (\n credentialResolutionMode === \"preflight\" &&\n cred.kind === \"oauth2\" &&\n (input.forceRefresh === true ||\n (cred.expiresAt !== null && cred.expiresAt.getTime() <= now.getTime()))\n ) {\n return authNeeded(ref, \"refresh_failed\", cred.id);\n }\n if (\n credentialResolutionMode === \"execution\" &&\n shouldRefresh(cred, input.forceRefresh === true, now)\n ) {\n try {\n cred = await refreshSingleFlight(cred, ref);\n } catch (error) {\n // Only a rejected grant may poison the connection; transient failures\n // (network errors, AS 5xx) leave it active so the next resolve retries.\n if (isPermanentRefreshError(error)) {\n let handled = false;\n if (options.transitionPermanentRefreshFailure) {\n try {\n handled = await options.transitionPermanentRefreshFailure({\n workspaceId: cred.workspaceId,\n connectionId: cred.id,\n connectionVersion: cred.version,\n subjectId: cred.subjectId,\n providerDomain: cred.providerDomain,\n httpStatus: error.httpStatus,\n oauthErrorCode: error.oauthErrorCode,\n });\n } catch {\n handled = false;\n }\n }\n if (!handled) {\n await deps\n // A personal credential may originate outside the workspace\n // consuming it. Apply the CAS to the same row we refreshed.\n .setStatus(db, cred.workspaceId, \"needs_reauth\", error.message, {\n id: cred.id,\n version: cred.version,\n subjectId: cred.subjectId,\n })\n .catch(() => undefined);\n }\n }\n return authNeeded(ref, \"refresh_failed\", cred.id);\n }\n }\n if (\n expectedAuthorityGeneration !== undefined &&\n cred.authorityGeneration !== expectedAuthorityGeneration\n ) {\n return authNeeded(ref, authorityReasonForScope(ref.subjectScope === \"subject\"), cred.id);\n }\n return await snapshot(\n cred,\n ref,\n input.destinationUrl,\n input.credentialTarget ?? \"mcp\",\n connectionUseAttribution,\n credentialResolutionMode === \"execution\",\n );\n };\n}\n\nfunction authorityReasonForScope(personal: boolean): AuthNeededReason {\n return personal ? \"personal_authority_unavailable\" : \"missing_connection\";\n}\n\nfunction connectionBindingMatches(\n cred: Pick<ConnectionCredentialForBroker, \"providerDomain\" | \"kind\" | \"credential\" | \"metadata\">,\n ref: McpServerConnectionRef,\n destinationUrl: string,\n): boolean {\n if (cred.providerDomain.toLowerCase() !== ref.providerDomain.toLowerCase()) return false;\n if (ref.kind && cred.kind !== ref.kind) return false;\n\n const credential = cred.credential as Record<string, unknown>;\n const metadata = cred.metadata as Record<string, unknown>;\n const boundMcpUrl = stringValue(credential.mcp_url) ?? stringValue(metadata.mcpUrl);\n const destination = canonicalHttpUrl(destinationUrl);\n if (!destination) return false;\n if (boundMcpUrl) {\n const binding = canonicalHttpUrl(boundMcpUrl);\n if (\n !binding ||\n (destination !== binding &&\n !(\n binding === canonicalHttpUrl(OFFICIAL_GMAIL_MCP_RESOURCE) &&\n isOfficialGmailRestDestination(destination, ref)\n ))\n ) {\n return false;\n }\n } else if (!destinationHostMatchesProvider(destination, cred.providerDomain)) {\n // Legacy/manual API-key rows may predate mcpUrl metadata. They are still\n // host-bound to their canonical provider domain, never usable as an\n // arbitrary bearer/header source for an unrelated MCP destination.\n return false;\n }\n if (cred.kind !== \"oauth2\") return true;\n const boundResource = stringValue(credential.resource) ?? stringValue(metadata.resource);\n if (ref.resource) {\n if (!boundResource) return false;\n if (canonicalResource(ref.resource) !== canonicalResource(boundResource)) return false;\n }\n return true;\n}\n\n/** Credential-free preflight only. Physical requests still resolve credentials\n * and enforce their binding, current status and accepted-use authority. */\nexport function connectionMetadataMatchesBinding(\n connection: ConnectionMetadata,\n ref: McpServerConnectionRef,\n destinationUrl: string,\n): boolean {\n return (\n connectionBindingMatches({ ...connection, credential: {} }, ref, destinationUrl) &&\n missingRequestedScopes(ref.scopes, connection.grantedScopes, connection.providerDomain)\n .length === 0\n );\n}\n\nfunction destinationHostMatchesProvider(destinationUrl: string, providerDomain: string): boolean {\n const destinationHost = new URL(destinationUrl).hostname.toLowerCase();\n const provider = providerDomain\n .trim()\n .toLowerCase()\n .replace(/^\\.+|\\.+$/g, \"\");\n return (\n Boolean(provider) && (destinationHost === provider || destinationHost.endsWith(`.${provider}`))\n );\n}\n\nfunction canonicalHttpUrl(value: string): string | null {\n try {\n const url = new URL(value);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return null;\n url.hash = \"\";\n url.hostname = url.hostname.toLowerCase();\n if (\n (url.protocol === \"https:\" && url.port === \"443\") ||\n (url.protocol === \"http:\" && url.port === \"80\")\n ) {\n url.port = \"\";\n }\n url.pathname = url.pathname.replace(/\\/+$/, \"\") || \"/\";\n return url.toString();\n } catch {\n return null;\n }\n}\n\nfunction canonicalResource(value: string): string {\n return canonicalHttpUrl(value) ?? value.trim();\n}\n\nexport class ConnectionRefreshHttpError extends Error {\n readonly httpStatus: number;\n readonly oauthErrorCode: string | null;\n\n constructor(httpStatus: number, oauthErrorCode: string | null = null) {\n super(`connection refresh failed with HTTP ${httpStatus}`);\n this.name = \"ConnectionRefreshHttpError\";\n this.httpStatus = httpStatus;\n this.oauthErrorCode = oauthErrorCode;\n }\n}\n\n// The token endpoint rejecting the grant itself means re-auth is the only way\n// forward. 429 (throttling) and 408 are transient despite being 4xx; network\n// failures and AS 5xx are likewise retryable.\nfunction isPermanentRefreshError(error: unknown): error is ConnectionRefreshHttpError {\n return (\n error instanceof ConnectionRefreshHttpError &&\n error.httpStatus >= 400 &&\n error.httpStatus < 500 &&\n error.httpStatus !== 408 &&\n error.httpStatus !== 429\n );\n}\n\nfunction shouldRefresh(cred: ConnectionCredentialForBroker, force: boolean, now: Date): boolean {\n if (cred.kind !== \"oauth2\") {\n return false;\n }\n if (force) {\n return true;\n }\n if (!cred.expiresAt) {\n return false;\n }\n return cred.expiresAt.getTime() <= now.getTime() + REFRESH_WINDOW_MS;\n}\n\nfunction authNeeded(\n ref: McpServerConnectionRef,\n reason: AuthNeededReason,\n connectionId?: string,\n): ResolveConnectionCredentialResult {\n return {\n status: \"auth_needed\",\n reason,\n providerDomain: ref.providerDomain,\n ...(ref.provider ? { provider: ref.provider } : {}),\n ...(connectionId ? { connectionId } : {}),\n ...(ref.scopes ? { scopes: ref.scopes } : {}),\n ...(ref.resource ? { resource: ref.resource } : {}),\n ...(ref.selectedResources\n ? { selectedResources: copySelectedResources(ref.selectedResources) }\n : {}),\n };\n}\n\nfunction authNeededForStatus(\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n): ResolveConnectionCredentialResult {\n if (cred.status === \"revoked\") {\n return authNeeded(ref, \"missing_connection\", cred.id);\n }\n return authNeeded(\n ref,\n cred.expiresAt && cred.expiresAt.getTime() <= Date.now() ? \"expired\" : \"refresh_failed\",\n cred.id,\n );\n}\n\nfunction missingRequestedScopes(\n requested: string[] | undefined,\n granted: string[],\n providerDomain: string,\n): string[] {\n if (!requested?.length) {\n return [];\n }\n const grantedSet = new Set(granted.map((scope) => connectionScopeKey(providerDomain, scope)));\n return requested.filter((scope) => !grantedSet.has(connectionScopeKey(providerDomain, scope)));\n}\n\n/**\n * Normalizes an OAuth token_type into the Authorization scheme to send. RFC 6750\n * says the scheme is case-insensitive, but some MCP servers (e.g. Linear) reject\n * a lowercase `bearer` — so a `bearer`/`BEARER` (or absent) token_type is sent as\n * the canonical `Bearer`. A non-bearer scheme is passed through unchanged.\n */\nexport function normalizeBearerScheme(tokenType: string | null | undefined): string {\n return !tokenType || /^bearer$/i.test(tokenType) ? \"Bearer\" : tokenType;\n}\n\ntype ConnectionCredentialMaterial =\n | {\n status: \"ok\";\n headers: Record<string, string>;\n placements?: ConnectionCredentialPlacement[];\n }\n | { status: \"invalid\" | \"unsupported\" };\n\nfunction credentialMaterialForConnection(\n cred: ConnectionCredentialForBroker,\n target: \"mcp\" | \"http_api\",\n): ConnectionCredentialMaterial {\n if (cred.kind === \"oauth2\") {\n const accessToken = stringValue((cred.credential as { access_token?: unknown }).access_token);\n if (!accessToken) {\n return { status: \"invalid\" };\n }\n return {\n status: \"ok\",\n headers: {\n authorization: `${normalizeBearerScheme(stringValue((cred.credential as { token_type?: unknown }).token_type))} ${accessToken}`,\n },\n };\n }\n const rawPlacements = (cred.credential as { placements?: unknown }).placements;\n if (rawPlacements !== undefined) {\n let placements: ConnectionCredentialPlacement[];\n try {\n placements = normalizedCredentialPlacements(rawPlacements);\n } catch {\n return { status: \"invalid\" };\n }\n if (target !== \"http_api\" && placements.some((placement) => placement.carrier !== \"header\")) {\n return { status: \"unsupported\" };\n }\n return {\n status: \"ok\",\n headers: headerMapForPlacements(placements),\n placements,\n };\n }\n try {\n const headers = normalizedCredentialHeaders(\n stringRecord((cred.credential as { headers?: unknown }).headers) ?? {},\n );\n return { status: \"ok\", headers };\n } catch {\n return { status: \"invalid\" };\n }\n}\n\nexport async function refreshOAuthConnectionCredential(\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n settings: Settings,\n transportOptions: RefreshTransportOptions = {},\n): Promise<{\n credential: Record<string, unknown>;\n expiresAt: Date | null;\n grantedScopes?: string[];\n metadata?: Record<string, unknown>;\n}> {\n if (cred.kind !== \"oauth2\") {\n return {\n credential: cred.credential,\n expiresAt: cred.expiresAt,\n grantedScopes: cred.grantedScopes,\n };\n }\n const refreshToken = stringValue((cred.credential as { refresh_token?: unknown }).refresh_token);\n const personalGitHubMetadata = PersonalGitHubConnectionMetadata.safeParse(cred.metadata);\n const personalGitHub =\n cred.providerDomain.toLowerCase() === PERSONAL_GITHUB_PROVIDER_DOMAIN &&\n personalGitHubMetadata.success;\n const storedTokenEndpoint =\n stringValue((cred.credential as { token_endpoint?: unknown }).token_endpoint) ??\n stringValue((cred.metadata as { tokenEndpoint?: unknown }).tokenEndpoint) ??\n stringValue((cred.metadata as { token_endpoint?: unknown }).token_endpoint);\n const tokenEndpoint = personalGitHub ? PERSONAL_GITHUB_TOKEN_URL : storedTokenEndpoint;\n if (!refreshToken || !tokenEndpoint) {\n throw new Error(\"connection has no refresh token endpoint\");\n }\n if (personalGitHub && storedTokenEndpoint !== PERSONAL_GITHUB_TOKEN_URL) {\n throw new ConnectionRefreshHttpError(401, \"client_unavailable\");\n }\n let validatedTokenEndpoint: string;\n try {\n validatedTokenEndpoint = validateHttpUrl(tokenEndpoint, {\n label: \"OAuth refresh token endpoint\",\n allowLoopbackHttp: settings.environment === \"local\" || settings.environment === \"test\",\n });\n } catch {\n throw new Error(\"connection has an invalid refresh token endpoint\");\n }\n const body = new URLSearchParams();\n body.set(\"grant_type\", \"refresh_token\");\n body.set(\"refresh_token\", refreshToken);\n // Public clients (token_endpoint_auth_method \"none\") must identify themselves\n // in the token request body (RFC 6749 §3.2.1); grant flows persist the\n // client_id they authorized with into the bundle/metadata.\n const clientId =\n stringValue((cred.credential as { client_id?: unknown }).client_id) ??\n stringValue((cred.metadata as { clientId?: unknown }).clientId) ??\n stringValue((cred.metadata as { client_id?: unknown }).client_id);\n const clientSecret = personalGitHub\n ? settings.githubPersonalOauthClientSecret\n : stringValue((cred.credential as { client_secret?: unknown }).client_secret);\n const authMethod =\n stringValue(\n (cred.credential as { token_endpoint_auth_method?: unknown }).token_endpoint_auth_method,\n ) ?? \"none\";\n if (\n personalGitHub &&\n (!settings.githubPersonalOauthEnabled ||\n !clientId ||\n clientId !== settings.githubPersonalOauthClientId ||\n personalGitHubMetadata.data.oauthEnvironment !== settings.environment ||\n personalGitHubMetadata.data.oauthClientMarker !==\n createHash(\"sha256\").update(clientId).digest(\"hex\").slice(0, 32) ||\n !clientSecret)\n ) {\n throw new ConnectionRefreshHttpError(401, \"client_unavailable\");\n }\n if (clientId) {\n body.set(\"client_id\", clientId);\n }\n const tokenRequestEncoding =\n stringValue(\n (cred.credential as { token_request_encoding?: unknown }).token_request_encoding,\n ) === \"json\"\n ? \"json\"\n : \"form\";\n const headers: Record<string, string> = {\n \"content-type\":\n tokenRequestEncoding === \"json\" ? \"application/json\" : \"application/x-www-form-urlencoded\",\n };\n if (clientSecret && authMethod === \"client_secret_post\") {\n body.set(\"client_secret\", clientSecret);\n } else if (clientId && clientSecret && authMethod === \"client_secret_basic\") {\n headers.authorization = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString(\"base64\")}`;\n }\n const resource =\n ref.resource ?? stringValue((cred.credential as { resource?: unknown }).resource);\n const resourceParameterSupported =\n (cred.credential as { resource_parameter_supported?: unknown }).resource_parameter_supported !==\n false;\n if (resource && resourceParameterSupported) {\n body.set(\"resource\", resource);\n }\n const scopeParameterSupported =\n (cred.credential as { scope_parameter_supported?: unknown }).scope_parameter_supported !==\n false;\n if (ref.scopes?.length && scopeParameterSupported) {\n body.set(\"scope\", ref.scopes.join(\" \"));\n }\n const requestBody: BodyInit =\n tokenRequestEncoding === \"json\" ? JSON.stringify(Object.fromEntries(body.entries())) : body;\n const response = await pinnedFetch(\n validatedTokenEndpoint,\n {\n method: \"POST\",\n headers,\n body: requestBody,\n signal: AbortSignal.timeout(CONNECTION_REFRESH_TIMEOUT_MS),\n },\n settings,\n {\n fetchImpl: transportOptions.fetchImpl ?? undiciFetch,\n ...(transportOptions.dnsLookup ? { dnsLookup: transportOptions.dnsLookup } : {}),\n label: \"OAuth token endpoint\",\n requireHttpsOutsideLocalTest: true,\n },\n );\n if (response.status >= 300 && response.status < 400) {\n await cancelResponseBody(response);\n throw new ConnectionRefreshHttpError(response.status);\n }\n if (!response.ok) {\n throw new ConnectionRefreshHttpError(\n response.status,\n await readOAuthRefreshErrorCode(response),\n );\n }\n const payload = await readResponseJsonBounded<Record<string, unknown>>(\n response,\n OAUTH_MAX_RESPONSE_BYTES,\n \"OAuth refresh token response\",\n );\n const accessToken = stringValue(payload.access_token);\n if (!accessToken) {\n throw new Error(\"connection refresh response did not include access_token\");\n }\n const expiresAt = expiresAtFromTokenResponse(payload, cred.expiresAt);\n const scopeText = stringValue(payload.scope);\n const returnedScopes = scopeText?.split(/[\\s,]+/).filter(Boolean) ?? [];\n // A successful Microsoft refresh proves offline access, although Microsoft\n // reports only access-token permissions in the response's scope field.\n if (\n scopeText &&\n ref.providerDomain.toLowerCase() === \"graph.microsoft.com\" &&\n !returnedScopes.some((scope) => scope.toLowerCase() === \"offline_access\")\n ) {\n returnedScopes.push(\"offline_access\");\n }\n const refreshTokenExpiresIn =\n typeof payload.refresh_token_expires_in === \"number\"\n ? payload.refresh_token_expires_in\n : undefined;\n const refreshTokenExpiresAt =\n personalGitHub && refreshTokenExpiresIn && refreshTokenExpiresIn > 0\n ? new Date(Date.now() + refreshTokenExpiresIn * 1000).toISOString()\n : null;\n if (\n personalGitHub &&\n scopeText &&\n (returnedScopes.length !== PERSONAL_GITHUB_REQUESTED_SCOPES.length ||\n returnedScopes.some((scope) => !PERSONAL_GITHUB_REQUESTED_SCOPES.includes(scope as \"repo\")))\n ) {\n throw new ConnectionRefreshHttpError(401, \"scope_changed\");\n }\n const nextCredential = {\n ...cred.credential,\n access_token: accessToken,\n refresh_token: stringValue(payload.refresh_token) ?? refreshToken,\n token_type:\n stringValue(payload.token_type) ??\n stringValue((cred.credential as { token_type?: unknown }).token_type) ??\n \"Bearer\",\n ...(expiresAt ? { expires_at: expiresAt.toISOString() } : {}),\n ...(resource ? { resource } : {}),\n ...(scopeText\n ? {\n scope:\n ref.providerDomain.toLowerCase() === \"graph.microsoft.com\"\n ? returnedScopes.join(\" \")\n : scopeText,\n }\n : {}),\n ...(refreshTokenExpiresAt ? { refresh_token_expires_at: refreshTokenExpiresAt } : {}),\n ...(clientSecret && !personalGitHub\n ? { client_secret: clientSecret, token_endpoint_auth_method: authMethod }\n : {}),\n };\n return {\n credential: nextCredential,\n expiresAt,\n ...(personalGitHub\n ? { grantedScopes: [...PERSONAL_GITHUB_REQUESTED_SCOPES] }\n : scopeText\n ? { grantedScopes: returnedScopes }\n : {}),\n ...(refreshTokenExpiresAt\n ? {\n metadata: PersonalGitHubConnectionMetadata.parse({\n ...personalGitHubMetadata.data,\n refreshTokenExpiresAt,\n }),\n }\n : {}),\n };\n}\n\nasync function readOAuthRefreshErrorCode(response: Response): Promise<string | null> {\n try {\n const payload = await readResponseJsonBounded<Record<string, unknown>>(\n response,\n OAUTH_MAX_RESPONSE_BYTES,\n \"OAuth refresh error response\",\n );\n const code = stringValue(payload.error);\n return code && /^[a-z0-9_.-]{1,64}$/i.test(code) ? code : null;\n } catch {\n await cancelResponseBody(response);\n return null;\n }\n}\n\nfunction expiresAtFromTokenResponse(\n payload: Record<string, unknown>,\n fallback: Date | null,\n): Date | null {\n const expiresAt = stringValue(payload.expires_at);\n if (expiresAt) {\n const parsed = new Date(expiresAt);\n return Number.isNaN(parsed.getTime()) ? fallback : parsed;\n }\n const expiresIn = typeof payload.expires_in === \"number\" ? payload.expires_in : undefined;\n if (expiresIn && Number.isFinite(expiresIn) && expiresIn > 0) {\n return new Date(Date.now() + expiresIn * 1000);\n }\n return fallback;\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n const out: Record<string, string> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (typeof raw !== \"string\") {\n return null;\n }\n out[key] = raw;\n }\n return out;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nasync function cancelResponseBody(response: Response): Promise<void> {\n await response.body?.cancel().catch(() => undefined);\n}\n","import { sql } from \"drizzle-orm\";\nimport { setSubjectRlsContext, withRlsContext, type Database } from \"./database\";\nimport type { ConnectionCredentialForBroker } from \"./connection-token-resolver\";\n\n/** Serialize rotating-token exchange across workers, not only within one process. */\nexport async function withConnectionRefreshLock<T>(\n db: Database,\n credential: ConnectionCredentialForBroker,\n work: (lockedDb: Database) => Promise<T>,\n): Promise<T> {\n return withRlsContext(\n db,\n { accountId: credential.accountId, workspaceId: credential.workspaceId },\n async (tx) => {\n if (credential.subjectId) await setSubjectRlsContext(tx, credential.subjectId);\n await tx.execute(\n sql`select pg_advisory_xact_lock(hashtextextended(${`connection-refresh:${credential.id}`}, 0))`,\n );\n return work(tx);\n },\n );\n}\n","/**\n * Canonical comparison key for provider-reported OAuth scopes.\n *\n * Google may return the canonical userinfo scope URLs after the application\n * requested the standard `email` / `profile` aliases. Microsoft scope names\n * are case-insensitive. All other providers retain exact comparison.\n */\nexport function connectionScopeKey(providerDomain: string, value: string): string {\n const scope = value.trim();\n const domain = providerDomain.toLowerCase();\n if (domain === \"googleapis.com\" || domain.endsWith(\".googleapis.com\")) {\n if (scope === \"email\" || scope === \"https://www.googleapis.com/auth/userinfo.email\") {\n return \"google:email\";\n }\n if (scope === \"profile\" || scope === \"https://www.googleapis.com/auth/userinfo.profile\") {\n return \"google:profile\";\n }\n }\n return domain === \"graph.microsoft.com\" ? scope.toLowerCase() : scope;\n}\n"],"mappings":";;;;;;AAeA;AAAA,EACE;AAAA,EACA;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A,SAAS,aAAa,OAA+C;AACnE,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;AAC/D,WAAO;AAAA,EACT;AACA,QAAM,MAA8B,CAAC;AACrC,aAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC9C,QAAI,OAAO,QAAQ,UAAU;AAC3B,aAAO;AAAA,IACT;AACA,QAAI,GAAG,IAAI;AAAA,EACb;AACA,SAAO;AACT;AAEA,SAAS,YAAY,OAAoC;AACvD,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAEA,eAAe,mBAAmB,UAAmC;AACnE,QAAM,SAAS,MAAM,OAAO,EAAE,MAAM,MAAM,MAAS;AACrD;","names":["key"]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
withWorkspaceRls,
|
|
6
6
|
withWorkspaceSubjectRls,
|
|
7
7
|
withWorkspaceSubjectSessionActivityRls
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-JEKW3C74.js";
|
|
9
9
|
|
|
10
10
|
// src/session-tenancy.ts
|
|
11
11
|
import { createHash } from "crypto";
|
|
@@ -502,4 +502,4 @@ export {
|
|
|
502
502
|
forkSessionContent,
|
|
503
503
|
replayAppliedSessionFork
|
|
504
504
|
};
|
|
505
|
-
//# sourceMappingURL=chunk-
|
|
505
|
+
//# sourceMappingURL=chunk-PIVVJPQ3.js.map
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
rawRows,
|
|
3
3
|
withWorkspaceRls
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-JEKW3C74.js";
|
|
5
5
|
import {
|
|
6
6
|
sessionEvents,
|
|
7
7
|
sessionTurns
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-6PRATKUO.js";
|
|
9
9
|
import {
|
|
10
10
|
LOSSLESS_JSON_STRING_PREFIX,
|
|
11
11
|
fromPostgresLosslessJson
|
|
@@ -244,4 +244,4 @@ export {
|
|
|
244
244
|
readSessionMessageSliceInScope,
|
|
245
245
|
listSessionEventSlices
|
|
246
246
|
};
|
|
247
|
-
//# sourceMappingURL=chunk-
|
|
247
|
+
//# sourceMappingURL=chunk-RUEJOEIC.js.map
|
|
@@ -623,6 +623,10 @@ var XAI_AUTHORITY_TABLES = [
|
|
|
623
623
|
var UNIFIED_KNOWLEDGE_ROUTINES = [
|
|
624
624
|
"knowledge_index_claim(text, integer, integer)",
|
|
625
625
|
"knowledge_index_work(uuid, uuid, uuid, jsonb)",
|
|
626
|
+
"knowledge_index_billing_policy(uuid, uuid, uuid, text, timestamp with time zone, bigint)",
|
|
627
|
+
"knowledge_index_wait_for_funding(uuid, uuid, uuid)",
|
|
628
|
+
"knowledge_index_paid_publication_guard(uuid, uuid, uuid)",
|
|
629
|
+
"knowledge_visible_index_status(uuid, uuid, jsonb, jsonb, text)",
|
|
626
630
|
"knowledge_entry_apply(uuid, uuid, jsonb, jsonb)",
|
|
627
631
|
"knowledge_entry_confirm_legacy(uuid, uuid, jsonb, jsonb)",
|
|
628
632
|
"agent_instruction_apply(uuid, uuid, jsonb, jsonb)",
|
|
@@ -4074,6 +4078,18 @@ BEGIN
|
|
|
4074
4078
|
IF to_regprocedure(format('%I.knowledge_entry_apply(uuid,uuid,jsonb,jsonb)', ${literal(schema)})) IS NOT NULL THEN
|
|
4075
4079
|
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.knowledge_index_claim(text,integer,integer) TO %I', ${literal(schema)}, ${literal(role)});
|
|
4076
4080
|
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.knowledge_index_work(uuid,uuid,uuid,jsonb) TO %I', ${literal(schema)}, ${literal(role)});
|
|
4081
|
+
IF to_regprocedure(format('%I.knowledge_index_billing_policy(uuid,uuid,uuid,text,timestamptz,bigint)', ${literal(schema)})) IS NOT NULL THEN
|
|
4082
|
+
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.knowledge_index_billing_policy(uuid,uuid,uuid,text,timestamptz,bigint) TO %I', ${literal(schema)}, ${literal(role)});
|
|
4083
|
+
END IF;
|
|
4084
|
+
IF to_regprocedure(format('%I.knowledge_index_wait_for_funding(uuid,uuid,uuid)', ${literal(schema)})) IS NOT NULL THEN
|
|
4085
|
+
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.knowledge_index_wait_for_funding(uuid,uuid,uuid) TO %I', ${literal(schema)}, ${literal(role)});
|
|
4086
|
+
END IF;
|
|
4087
|
+
IF to_regprocedure(format('%I.knowledge_index_paid_publication_guard(uuid,uuid,uuid)', ${literal(schema)})) IS NOT NULL THEN
|
|
4088
|
+
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.knowledge_index_paid_publication_guard(uuid,uuid,uuid) TO %I', ${literal(schema)}, ${literal(role)});
|
|
4089
|
+
END IF;
|
|
4090
|
+
IF to_regprocedure(format('%I.knowledge_visible_index_status(uuid,uuid,jsonb,jsonb,text)', ${literal(schema)})) IS NOT NULL THEN
|
|
4091
|
+
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.knowledge_visible_index_status(uuid,uuid,jsonb,jsonb,text) TO %I', ${literal(schema)}, ${literal(role)});
|
|
4092
|
+
END IF;
|
|
4077
4093
|
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.agent_instruction_apply(uuid,uuid,jsonb,jsonb) TO %I', ${literal(schema)}, ${literal(role)});
|
|
4078
4094
|
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.knowledge_entry_apply(uuid,uuid,jsonb,jsonb) TO %I', ${literal(schema)}, ${literal(role)});
|
|
4079
4095
|
EXECUTE format('GRANT EXECUTE ON FUNCTION %I.knowledge_entry_confirm_legacy(uuid,uuid,jsonb,jsonb) TO %I', ${literal(schema)}, ${literal(role)});
|
|
@@ -5582,4 +5598,4 @@ export {
|
|
|
5582
5598
|
runtimeDatabaseReadyCheck,
|
|
5583
5599
|
provisionRoles
|
|
5584
5600
|
};
|
|
5585
|
-
//# sourceMappingURL=chunk-
|
|
5601
|
+
//# sourceMappingURL=chunk-SRAMNVHT.js.map
|