Files
PaperClipAI/server/src/services/tool-access/oauth/grant-refresh.ts
T
DottaandPaperclip c67909cb0f fix: keep tool approvals valid through OAuth refresh and delayed review (#20340)
## Thinking Path

> - Paperclip lets people manage agent work and approve app actions.
> - An approval must bind the action that the person reviewed.
> - OAuth access tokens can expire while that person is away.
> - The old target snapshot treated each token refresh as a new
authorization. It also imposed a one-hour review deadline.
> - This pull request separates token renewal from authorization
identity and keeps the human decision durable.
> - Current access, the reviewed arguments, meaningful target changes,
task closure, and execution receipts still control dispatch.
> - People can approve later without repeating a decision after routine
connection maintenance.

## Linked Issues or Issue Description

**What happened?**

A pending app action returned `approved_tool_target_changed` after its
OAuth tokens refreshed. The tool and connection settings were unchanged.
The same card also expired after one hour. A sign-in problem could
discard an accepted decision before provider dispatch.

**Expected behavior**

The original card remains reviewable after routine OAuth refresh and a
server restart. A later approval runs the exact reviewed action once. A
connection repair preserves the decision while Paperclip verifies the
same authorization. Meaningful changes require a new review.

**Steps to reproduce**

1. Connect an OAuth MCP app and configure an action to require approval.
2. Request the action, then refresh its access and refresh tokens before
approving.
3. Approve the original card. Before this change, it returns HTTP 409
even when the authorization is unchanged.
4. Wait more than one hour. Before this change, the card expires without
a task-specific deadline.

**Paperclip version or commit**

Reproduced from master at `76254ead2229`. The final branch is rebased
onto current master.

## What Changed

- Add versioned approval target comparison. New snapshots bind
credential identity epochs, consent, permissions, ownership, connection
configuration, tool contracts, and credential references. Authenticated
OAuth refresh preserves identity. Manual credential replacement does
not.
- Remove the implicit one-hour deadline from ordinary app action
reviews. Keep explicit deadlines and terminal-task expiry. Synchronize
the nullable interaction deadline in shared contracts and UI.
- Keep accepted, undispatched actions when sign-in is required. Show a
saved-approval repair state. Resume on committed connection changes
after target and access revalidation, without an idle retry loop.
- Preserve the existing execution claim, result receipt, and
uncertain-outcome no-replay rules.
- Explain meaningful target changes without inviting the person to retry
the stale card.
- Add a production task-thread Storybook example and document
compatibility and recovery behavior.

## Verification

- Red: production-refresher invalid-grant handling and formal-approval
withdrawal during a sign-in wait also reproduced as failing regressions
before their fixes.
- Red: before implementation, the local OAuth HTTP fixture failed for
both public and confidential clients with `approved_tool_target_changed`
after token refresh.
- Green: the extended fixture passes for public and confidential clients
with personal and shared grants. It covers actual local HTTP token
exchanges, multiple refreshes, a rebuilt gateway, an ended originating
run, approval after 25 hours, duplicate approval, preserved sharing
arguments, sign-in waiting, and event-driven repair. The gateways use
the production OAuth refresher; an invalid refresh preserves the
accepted decision before provider dispatch. Omitted-scope responses
cover equivalent scope-reporting changes. The provider is an isolated
local fixture, not a deployed Notebook service.
- Negative controls refuse changed consent, scopes, tool definition,
destination, and manual credential replacement before provider
execution.
- Existing gateway service, connected-tool acceptance, secret owner,
secret service, unsigned-review queue, and connection-health suites
passed. Explicit-deadline fixtures still prove expiry behavior,
including deadlines on accepted sign-in waits. A withdrawn formal
approval cancels a waiting action before connection recovery.
- Approval card, task-chat, error-copy and target-comparison tests
passed. Server and UI typechecks passed. Token gates and Storybook
catalog checks passed.
- Inspected the new saved-approval repair card in local Storybook using
the production task thread. It shows a reconnect link and no second
approval button or false running state.
- `pnpm verify --explain` returned exit 2 and requested broad CI
coverage. [Full
CI](https://github.com/paperclipai/paperclip/actions/runs/42677855507)
passed on `eb4f1c7caa9ee6e802c314ffc5eadec475a5de0c`, including build,
typecheck/release registry, general and serialized tests, and all eight
browser shards.
- Greptile reviewed the same final head at 5/5. Both findings from the
first review are fixed and their threads resolved; no open follow-ups
remain.

## Risks

- No database migration is needed. The new comparison reuses the vault
identity epoch. Only authenticated OAuth refresh code can preserve that
epoch; HTTP credential-write schemas cannot select that behavior.
- Earlier signed requests keep their original exact-version checks and
saved deadlines. Already-expired cards are not revived. A historical
card whose credentials already changed needs a fresh review.
- A new consent, account, permission set, destination, or manually
replaced credential must not inherit the old authorization. Reconnection
continues automatically only when revalidation proves the same saved
authorization.
- The interaction enrichment now permits a null deadline. Existing
string deadlines remain valid. The web client and shared validator
change together.
- This PR does not deploy to staging or perform a live Notebook
publication.

## Model Used

OpenAI Codex, GPT-6 family, with repository tools, code execution, and
browser inspection. The runtime does not expose the exact model ID,
context-window limit, or reasoning-mode label; those values are not
asserted.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-09 13:46:28 -06:00

641 lines
27 KiB
TypeScript

import { notifyGitHubCredentialChange } from "../../github-connection-notifications.js";
import { writeToolConnectionHealthChange } from "../../tool-connection-health-notifications.js";
import type { ActorInfo } from "../types.js";
import { createOAuthClientProtocol, storedOAuthTokenEndpointAuthMethod } from "./client.js";
import { oauthConfig, normalizeOauthScopes, resolveGrantedOauthScopes } from "./metadata.js";
import { googleWorkspaceEffectiveScopes, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared";
import { emitConnectionUpdated } from "../../connector-telemetry.js";
import { and, eq, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { connectionGrants, companySecrets, toolConnections } from "@paperclipai/db";
import type { ToolCredentialSecretRef } from "@paperclipai/shared";
import { conflict, HttpError, unprocessable } from "../../../errors.js";
import { secretService } from "../../secrets.js";
import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { actorForSecret, type OAuthCredentialStore } from "./credential-store.js";
import { withoutOAuthRefreshLease, type OAuthRefreshLeases } from "./refresh-leases.js";
import { managedConnectorProfile, oauthGrantConfig, oauthGrantExpiresAtMs } from "./client-settings.js";
import { connectionSetupUrl, connectionReconnectUrl } from "../identifiers.js";
import { singleFlight } from "../single-flight.js";
function asRecord(value: unknown): Record<string, unknown> {
if (value && typeof value === "object" && !Array.isArray(value))
return value as Record<string, unknown>;
return {};
}
type GrantRefreshDependencies = {
now: () => Date;
store: Pick<OAuthCredentialStore, "getOAuthGrantRow" | "resolveOAuthGrantSecret" | "createOrRotateOAuthSecret" | "oauthClientForConnection" | "syncCredentialBindings">;
leases: Pick<OAuthRefreshLeases, "acquireOAuthGrantRefreshLease" | "clearOAuthGrantRefreshLease">;
currentCloudConnector: () => PaperclipCloudConnector | null;
getConnectionRow(idOrUid: string, companyId?: string): Promise<typeof toolConnections.$inferSelect>;
exchangeOAuthToken: ReturnType<typeof createOAuthClientProtocol>["exchangeOAuthToken"];
};
export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentCloudConnector, getConnectionRow, exchangeOAuthToken }: GrantRefreshDependencies) {
const oauthGrantRefreshFlights = new Map<string, Promise<unknown>>();
const { getOAuthGrantRow, resolveOAuthGrantSecret, createOrRotateOAuthSecret, oauthClientForConnection, syncCredentialBindings } = store;
const { acquireOAuthGrantRefreshLease, clearOAuthGrantRefreshLease } = leases;
async function refreshOAuthGrantCredentials(input: {
companyId: string;
connectionId: string;
grantId: string;
forceRefresh?: boolean;
actor?: ActorInfo;
issueId?: string | null;
heartbeatRunId?: string | null;
}): Promise<typeof connectionGrants.$inferSelect> {
const connection = await getConnectionRow(
input.connectionId,
input.companyId,
);
const initialGrant = await getOAuthGrantRow(input);
const oauth = oauthConfig(connection);
const oauthProvider =
typeof oauth.provider === "string" ? oauth.provider : null;
const oauthTokenUrl =
typeof oauth.tokenUrl === "string" ? oauth.tokenUrl : null;
if (
connection.authKind === "oauth" &&
connection.credentialSource === "paperclip_vault" &&
isPaperclipCloudConnectorStrategy(oauth.strategy)
) {
const grantOauth = oauthGrantConfig(initialGrant);
const expiresAt =
typeof grantOauth.accessTokenExpiresAt === "string"
? Date.parse(grantOauth.accessTokenExpiresAt)
: Number.NaN;
const refreshedAt =
typeof grantOauth.refreshedAt === "string"
? Date.parse(grantOauth.refreshedAt)
: Number.NaN;
const rotationDue =
Number.isFinite(expiresAt) &&
(!Number.isFinite(refreshedAt) ||
refreshedAt <= Date.now() - 30 * 24 * 60 * 60_000);
const refreshDue =
Number.isFinite(expiresAt) && expiresAt <= Date.now() + 60 * 60_000;
// A GitHub App can deliberately issue a non-expiring ghu_ token. Its
// continuity is checked against /user below; only an expiring token pair
// enters this rotation path.
if (!input.forceRefresh && !refreshDue && !rotationDue)
return initialGrant;
if (!Number.isFinite(expiresAt)) return initialGrant;
return singleFlight(
oauthGrantRefreshFlights,
initialGrant.id,
async () => {
const lease = await acquireOAuthGrantRefreshLease(
connection,
initialGrant,
true,
);
if (!lease.leaseId) return lease.grant;
try {
const grant = lease.grant;
const profile = managedConnectorProfile(
typeof oauth.connectorProfile === "string"
? oauth.connectorProfile
: undefined,
);
const cloudConnector = currentCloudConnector();
const connectorSubject =
grant.kind === "agent" && grant.subjectAgentId
? `agent:${grant.subjectAgentId}`
: grant.kind === "user" && grant.subjectUserId
? grant.subjectUserId
: typeof oauth.connectorSubjectUserId === "string"
? oauth.connectorSubjectUserId
: null;
const accessRef = grant.credentialSecretRefs.find(
(ref) => ref.configPath === "oauth.access_token",
);
const refreshRef = grant.credentialSecretRefs.find(
(ref) => ref.configPath === "oauth.refresh_token",
);
if (
!profile ||
!cloudConnector ||
!connectorSubject ||
!accessRef ||
!refreshRef
) {
throw unprocessable("Managed authorization must be reconnected", {
code: "oauth_reauthorization_required",
setupUrl: connectionSetupUrl(connection),
reconnectUrl: connectionReconnectUrl(connection),
});
}
const refreshSecret = await resolveOAuthGrantSecret(
connection,
grant,
refreshRef,
input.actor,
input,
);
let credentials;
try {
credentials = await cloudConnector.refresh({
subject: connectorSubject,
companyId: connection.companyId,
profile: profile.id,
refreshToken: refreshSecret.value,
});
if (profile.id === "workspace.all") {
const requested = normalizeOauthScopes(oauthGrantConfig(grant).requestedScopes ?? oauthGrantConfig(grant).scopes);
credentials.scopes = googleWorkspaceEffectiveScopes(requested, credentials.scopes);
}
if (profile.id === "workspace.all" && !isGoogleWorkspaceScopeGrant(credentials.scopes)) {
throw new PaperclipCloudConnectorError("Google did not return verifiable permissions", "REAUTHORIZATION_REQUIRED");
}
} catch (error) {
if (
error instanceof PaperclipCloudConnectorError &&
error.code === "REAUTHORIZATION_REQUIRED"
) {
await db
.update(connectionGrants)
.set({ status: "needs_reauthorization", updatedAt: now() })
.where(
and(
eq(connectionGrants.id, grant.id),
eq(connectionGrants.companyId, grant.companyId),
),
);
throw unprocessable(
"Managed authorization must be reconnected",
{
code: "oauth_reauthorization_required",
setupUrl: connectionSetupUrl(connection),
reconnectUrl: connectionReconnectUrl(connection),
},
);
}
throw error;
}
const credentialActor: ActorInfo | undefined =
grant.kind === "user" && grant.subjectUserId
? { actorType: "user", actorId: grant.subjectUserId }
: input.actor;
const oauthUpdates = {
strategy: "paperclip_cloud_connector",
accessTokenExpiresAt: credentials.accessTokenExpiresAt,
scopes: credentials.scopes,
tokenType: credentials.tokenType,
refreshedAt: now().toISOString(),
...(credentials.refreshTokenExpiresAt
? { refreshTokenExpiresAt: credentials.refreshTokenExpiresAt }
: {}),
};
const updated = await db.transaction(async (tx) => {
await notifyGitHubCredentialChange(tx, connection);
const [current] = await tx.select({ id: connectionGrants.id }).from(connectionGrants)
.where(and(eq(connectionGrants.id, grant.id), eq(connectionGrants.companyId, grant.companyId),
eq(connectionGrants.status, "active"),
sql`${connectionGrants.providerTenant} -> 'oauth' -> 'refreshLease' ->> 'id' = ${lease.leaseId}`))
.for("update");
if (!current) throw conflict("OAuth credentials changed while refresh was in progress", {
code: "oauth_refresh_superseded", retryable: true,
});
const txSecrets = secretService(tx);
await txSecrets.rotate(
accessRef.secretId,
{ value: credentials.accessToken, preserveAiSessionEpoch: true },
actorForSecret(credentialActor),
);
if (credentials.refreshToken) {
await txSecrets.rotate(
refreshRef.secretId,
{ value: credentials.refreshToken, preserveAiSessionEpoch: true },
actorForSecret(credentialActor),
);
}
const [committed] = await tx
.update(connectionGrants)
.set({
providerTenant: sql`jsonb_set(coalesce(${connectionGrants.providerTenant}, '{}'::jsonb), '{oauth}', (coalesce(${connectionGrants.providerTenant}->'oauth', '{}'::jsonb) || ${JSON.stringify(oauthUpdates)}::jsonb) - 'refreshLease')`,
status: "active",
updatedAt: now(),
})
.where(
and(
eq(connectionGrants.id, grant.id),
eq(connectionGrants.companyId, grant.companyId),
eq(connectionGrants.status, "active"),
sql`${connectionGrants.providerTenant} -> 'oauth' -> 'refreshLease' ->> 'id' = ${lease.leaseId}`,
),
)
.returning();
return committed;
});
if (!updated)
throw conflict(
"OAuth credentials changed while refresh was in progress",
{
code: "oauth_refresh_superseded",
retryable: true,
},
);
return updated;
} finally {
await clearOAuthGrantRefreshLease(lease.grant, lease.leaseId).catch(
() => undefined,
);
}
},
);
}
if (
connection.authKind !== "oauth" ||
connection.credentialSource !== "paperclip_vault" ||
!oauthTokenUrl ||
!oauthProvider
) {
return initialGrant;
}
const expiresAtMs = oauthGrantExpiresAtMs(initialGrant, connection);
if (
!input.forceRefresh &&
(expiresAtMs === null || expiresAtMs > Date.now() + 60_000)
) {
return initialGrant;
}
return singleFlight(oauthGrantRefreshFlights, initialGrant.id, async () => {
const lease = await acquireOAuthGrantRefreshLease(
connection,
initialGrant,
input.forceRefresh === true,
);
if (!lease.leaseId) return lease.grant;
try {
const grant = lease.grant;
const refreshRef = grant.credentialSecretRefs.find(
(ref) => ref.configPath === "oauth.refresh_token",
);
if (!refreshRef) {
throw unprocessable(
"OAuth credentials have expired and no refresh token is available",
{
code: "oauth_refresh_missing",
setupUrl: connectionSetupUrl(connection),
reconnectUrl: connectionReconnectUrl(connection),
},
);
}
const refreshSecret = await resolveOAuthGrantSecret(
connection,
grant,
refreshRef,
input.actor,
input,
);
const credentialActor: ActorInfo | undefined =
grant.kind === "user" && grant.subjectUserId
? { actorType: "user", actorId: grant.subjectUserId }
: input.actor;
const client = await oauthClientForConnection(
connection,
oauthProvider,
credentialActor,
);
if (!client.clientId)
throw unprocessable(
`OAuth client id is not configured for ${oauthProvider}`,
);
const grantOauth = oauthGrantConfig(grant);
let token: Awaited<ReturnType<typeof exchangeOAuthToken>>;
try {
token = await exchangeOAuthToken({
tokenUrl: oauthTokenUrl,
clientId: client.clientId,
clientSecret: client.clientSecret,
tokenEndpointAuthMethod: storedOAuthTokenEndpointAuthMethod(
oauth,
client.clientSecret,
),
grantType: "refresh_token",
scopes:
normalizeOauthScopes(grantOauth.scopes).length > 0
? normalizeOauthScopes(grantOauth.scopes)
: normalizeOauthScopes(oauth.scopes).length > 0
? normalizeOauthScopes(oauth.scopes)
: normalizeOauthScopes(oauth.scope),
refreshToken: refreshSecret.value,
resource:
typeof oauth.resource === "string" && oauth.resource
? oauth.resource
: null,
});
} catch (error) {
if (
error instanceof HttpError &&
asRecord(error.details).code === "oauth_reauthorization_required"
) {
const retainedCredentialSecretRefs =
grant.credentialSecretRefs.filter(
(ref) =>
ref.configPath !== "oauth.access_token" &&
ref.configPath !== "oauth.refresh_token",
);
const [marked] = await db
.update(connectionGrants)
.set({
status: "needs_reauthorization",
providerTenant: sql`${connectionGrants.providerTenant} #- '{oauth,refreshLease}' #- '{oauth,accessTokenExpiresAt}'`,
credentialSecretRefs: retainedCredentialSecretRefs,
updatedAt: now(),
})
.where(
and(
eq(connectionGrants.id, grant.id),
eq(connectionGrants.companyId, grant.companyId),
eq(connectionGrants.status, "active"),
sql`${connectionGrants.providerTenant} -> 'oauth' -> 'refreshLease' ->> 'id' = ${lease.leaseId}`,
sql`exists (
select 1 from ${companySecrets}
where ${companySecrets.id} = ${refreshRef.secretId}
and ${companySecrets.companyId} = ${connection.companyId}
and ${companySecrets.latestVersion} = ${refreshSecret.latestVersion}
)`,
),
)
.returning();
if (!marked) {
const latest = await getOAuthGrantRow(input);
const latestExpiresAt = oauthGrantExpiresAtMs(latest, connection);
if (
latest.status === "active" &&
latestExpiresAt &&
latestExpiresAt > Date.now() + 60_000
)
return latest;
throw conflict(
"OAuth credentials changed while refresh was in progress. Retry the request.",
{
code: "oauth_refresh_superseded",
retryable: true,
},
);
}
if (marked.kind === "organization") {
const latestConnection = await getConnectionRow(
connection.id,
connection.companyId,
);
const [reauthorizationRequired] = await writeToolConnectionHealthChange(db, latestConnection, tx => tx
.update(toolConnections)
.set({
status: "draft",
enabled: false,
credentialSecretRefs:
latestConnection.credentialSecretRefs.filter(
(ref) =>
ref.configPath !== "oauth.access_token" &&
ref.configPath !== "oauth.refresh_token",
),
credentialRefs: latestConnection.credentialRefs.filter(
(ref) =>
ref.name !== "oauth.access_token" &&
ref.name !== "oauth.refresh_token",
),
updatedAt: now(),
})
.where(
and(
eq(toolConnections.id, latestConnection.id),
eq(toolConnections.companyId, latestConnection.companyId),
),
)
.returning());
await syncCredentialBindings(reauthorizationRequired);
emitConnectionUpdated(
reauthorizationRequired,
latestConnection,
"credential_refresh",
);
} else {
const activeGrantRefs = await db
.select({
refs: connectionGrants.credentialSecretRefs,
})
.from(connectionGrants)
.where(
and(
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
eq(connectionGrants.status, "active"),
),
);
await syncCredentialBindings(
connection,
activeGrantRefs.flatMap((row) => row.refs),
);
}
throw new HttpError(error.status, error.message, {
...asRecord(error.details),
setupUrl: connectionSetupUrl(connection),
reconnectUrl: connectionReconnectUrl(connection),
});
}
throw error;
}
if (connection.config.sourceTemplateKey === "google-workspace"
&& !isGoogleWorkspaceScopeGrant(normalizeOauthScopes(token.scope))) {
await db.update(connectionGrants).set({ status: "needs_reauthorization", updatedAt: now() })
.where(and(eq(connectionGrants.id, grant.id), eq(connectionGrants.companyId, connection.companyId)));
throw unprocessable("Google did not return verifiable permissions. Reconnect Google Workspace.", { code: "oauth_reauthorization_required" });
}
let nextRefreshRef: ToolCredentialSecretRef | null = null;
if (token.refreshToken) {
nextRefreshRef = await createOrRotateOAuthSecret({
companyId: connection.companyId,
connection,
configPath: "oauth.refresh_token",
label: "OAuth refresh token",
value: token.refreshToken,
preserveOAuthIdentity: true,
actor: credentialActor,
existingRefs: grant.credentialSecretRefs,
ownerUserId:
grant.kind === "user"
? (grant.subjectUserId ?? undefined)
: undefined,
});
}
const accessRef = await createOrRotateOAuthSecret({
companyId: connection.companyId,
connection,
configPath: "oauth.access_token",
label: "OAuth access token",
value: token.accessToken,
preserveOAuthIdentity: true,
actor: credentialActor,
existingRefs: grant.credentialSecretRefs,
ownerUserId:
grant.kind === "user"
? (grant.subjectUserId ?? undefined)
: undefined,
});
const nextCredentialSecretRefs = [
...grant.credentialSecretRefs.filter(
(ref) =>
ref.configPath !== "oauth.access_token" &&
(!nextRefreshRef || ref.configPath !== "oauth.refresh_token"),
),
accessRef,
...(nextRefreshRef ? [nextRefreshRef] : []),
];
const expiresAt = token.expiresIn
? new Date(Date.now() + token.expiresIn * 1000).toISOString()
: null;
// A refresh carries no fresh authorization request, so the baseline stays what
// Paperclip asked for when *this* grant was authorized. Judging the response against
// the grant's own scopes instead would let an over-grant that the provider re-asserts
// on every refresh read back as clean, because the widened grant would have become
// its own baseline. The connection-level list is only a fallback for grants created
// before the per-grant baseline existed — it is whichever callback ran last, so on a
// connection two users authorized with different scopes it is the wrong baseline for
// at least one of them.
const refreshed = resolveGrantedOauthScopes({
tokenScope: token.scope,
requestedScopes:
grantOauth.requestedScopes ??
oauth.scopes ??
oauth.scope ??
grantOauth.scopes,
previous: {
scopes: grantOauth.scopes,
scopeSource: grantOauth.scopeSource,
unrequestedScopes: grantOauth.unrequestedScopes,
},
});
if (connection.config.sourceTemplateKey === "google-workspace") {
refreshed.scopes = googleWorkspaceEffectiveScopes(normalizeOauthScopes(grantOauth.requestedScopes ?? grantOauth.scopes), refreshed.scopes);
}
const oauthUpdates = {
strategy:
typeof grantOauth.strategy === "string"
? grantOauth.strategy
: "direct_oauth",
accessTokenExpiresAt: expiresAt ?? null,
scopes: refreshed.scopes,
scopeSource: refreshed.scopeSource,
unrequestedScopes: refreshed.unrequestedScopes,
tokenType: token.tokenType,
refreshedAt: now().toISOString(),
};
const [updated] = await writeToolConnectionHealthChange(db, connection, tx => tx
.update(connectionGrants)
.set({
providerTenant: sql`jsonb_set(coalesce(${connectionGrants.providerTenant}, '{}'::jsonb), '{oauth}', (coalesce(${connectionGrants.providerTenant}->'oauth', '{}'::jsonb) || ${JSON.stringify(oauthUpdates)}::jsonb) - 'refreshLease')`,
credentialSecretRefs: nextCredentialSecretRefs,
status: "active",
updatedAt: now(),
})
.where(
and(
eq(connectionGrants.id, grant.id),
eq(connectionGrants.companyId, grant.companyId),
eq(connectionGrants.status, "active"),
sql`${connectionGrants.providerTenant} -> 'oauth' -> 'refreshLease' ->> 'id' = ${lease.leaseId}`,
),
)
.returning());
if (!updated) {
throw conflict(
"OAuth credentials changed while refresh was in progress. Retry the request.",
{
code: "oauth_refresh_superseded",
retryable: true,
},
);
}
if (grant.kind === "organization") {
const latestConnection = await getConnectionRow(
connection.id,
connection.companyId,
);
const latestOauth = oauthConfig(latestConnection);
const nextConfig = {
...latestConnection.config,
oauth: {
...withoutOAuthRefreshLease(latestOauth),
expiresAt,
scope: token.scope ?? latestOauth.scope ?? null,
tokenType: token.tokenType,
refreshedAt: now().toISOString(),
},
providerMetadata: {
...asRecord(latestConnection.config.providerMetadata),
oauth: {
expiresAt,
scope: token.scope ?? latestOauth.scope ?? null,
// Carry the same provenance the grant just recorded. Without it a connection
// read reverts to a bare scope with no source and no over-grant warning after
// the first ordinary refresh, while the grant read still has both.
scopeSource: refreshed.scopeSource,
unrequestedScopes: refreshed.unrequestedScopes,
tokenType: token.tokenType,
},
},
};
await db
.update(toolConnections)
.set({
config: nextConfig,
transportConfig: nextConfig,
updatedAt: now(),
})
.where(
and(
eq(toolConnections.id, latestConnection.id),
eq(toolConnections.companyId, latestConnection.companyId),
),
);
}
const previousKeys = new Set(
grant.credentialSecretRefs.map(
(ref) => `${ref.secretId}:${ref.configPath}`,
),
);
const nextKeys = new Set(
nextCredentialSecretRefs.map(
(ref) => `${ref.secretId}:${ref.configPath}`,
),
);
if (
previousKeys.size !== nextKeys.size ||
[...previousKeys].some((key) => !nextKeys.has(key))
) {
const activeGrantRefs = await db
.select({
refs: connectionGrants.credentialSecretRefs,
})
.from(connectionGrants)
.where(
and(
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
eq(connectionGrants.status, "active"),
),
);
await syncCredentialBindings(
connection,
activeGrantRefs.flatMap((row) => row.refs),
);
}
return updated;
} finally {
await clearOAuthGrantRefreshLease(lease.grant, lease.leaseId).catch(
() => undefined,
);
}
});
}
return refreshOAuthGrantCredentials;
}