Compare commits

...

4 Commits

Author SHA1 Message Date
Gilad Resisi
88eb6defbf fix(refresh): log a summary of the refresh error instead of the raw object
The raw error can carry the token request body (client secret, refresh
token) on providers whose refresh fails through the base fetch or a client
library. Log the message, HTTP status and the token endpoint's response
body instead, which is what makes the failure diagnosable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 11:35:10 +07:00
Gilad Resisi
2dee7f0be0 fix(refresh): only the scheduled refresh tolerates unrecognized errors
Tolerating unrecognized refresh errors everywhere meant a dead token on a
provider without a handleErrors override was never flagged: the refresh
that follows a rejected post went through the same code and stayed silent.

The refresh service now takes a tolerateUnknownErrors flag, off by default.
The refreshToken activity turns it on only when the calling workflow is
refreshTokenWorkflow, read from the activity context, so post workflows of
every version (including the still-running v1.0.1 runs that share this
activity) keep disconnecting after a rejected post.

Also add 'disconnect' to the optional handleErrors interface type, which the
base class returns since this branch was opened.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 10:13:36 +07:00
Gilad Resisi
aefcccc43b Merge origin/main into fix/refresh-transient-errors 2026-09-23 09:30:37 +07:00
Gilad Resisi
060b14db59 fix(refresh): only disconnect channels on recognized auth errors, log refresh failures
A transient error during token refresh (network blip, provider 5xx, rate
limit) was swallowed by .catch(() => false) and treated the same as a dead
refresh token: the channel was flagged refreshNeeded, disconnected, and the
user emailed to reconnect — with no log of what actually failed. A production
customer's GMB channel hit this repeatedly (~50min after each reconnect, on
access-token expiry) with no post in between.

Now the refresh error is logged and classified with the provider's own
handleErrors (same pattern runInConcurrent already uses): only errors the
provider recognizes as an invalid refresh token keep the old disconnect flow;
anything else logs and returns false so the next refresh retries cleanly.
Providers without a handleErrors override are no longer disconnected from the
refresh path — a genuinely dead token still gets flagged at the next real API
call when fetch throws RefreshToken on 401.

Verified e2e against the local DB by driving RefreshIntegrationService.refresh
directly: transient ECONNREFUSED disconnected youtube on the old code and
leaves it connected (logged) on the new; a real invalid_grant from Google
still flags refreshNeeded + sends the reconnect notification; a bad_body error
on a provider without handleErrors (reddit) logs without disconnecting.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-02 17:19:36 +07:00
4 changed files with 67 additions and 6 deletions

View File

@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { Context } from '@temporalio/activity';
import {
Activity,
ActivityMethod,
@ -558,9 +559,17 @@ export class PostActivity {
integration.providerIdentifier
);
// the scheduled refresh has no rejected request behind it, so an
// unrecognized refresh error must not disconnect the channel there; post
// workflows calling this same activity keep disconnecting
const scheduled =
Context.current().info.workflowType === 'refreshTokenWorkflow';
try {
const refresh = await this._refreshIntegrationService.refresh(
integration
integration,
'',
scheduled
);
if (!refresh) {
return false;

View File

@ -7,6 +7,7 @@ import {
SocialProvider,
} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
import { TemporalService } from 'nestjs-temporal-core';
import { safeStringify } from '@gitroom/nestjs-libraries/integrations/social.abstract';
@Injectable()
export class RefreshIntegrationService {
@ -16,12 +17,21 @@ export class RefreshIntegrationService {
private _integrationService: IntegrationService,
private _temporalService: TemporalService
) {}
async refresh(integration: Integration, cause = ''): Promise<false | AuthTokenDetails> {
async refresh(
integration: Integration,
cause = '',
tolerateUnknownErrors = false
): Promise<false | AuthTokenDetails> {
const socialProvider = this._integrationManager.getSocialIntegration(
integration.providerIdentifier
);
const refresh = await this.refreshProcess(integration, socialProvider, cause);
const refresh = await this.refreshProcess(
integration,
socialProvider,
cause,
tolerateUnknownErrors
);
if (!refresh) {
return false as const;
@ -71,13 +81,49 @@ export class RefreshIntegrationService {
private async refreshProcess(
integration: Integration,
socialProvider: SocialProvider,
cause = ''
cause = '',
tolerateUnknownErrors = false
): Promise<AuthTokenDetails | false> {
let refreshError: any = null;
const refresh: false | AuthTokenDetails = await socialProvider
.refreshToken(integration.refreshToken)
.catch((err) => false);
.catch((err) => {
refreshError = err;
return false as const;
});
if (!refresh || !refresh.accessToken) {
// log a summary, not the raw error: a failed token request can carry the
// request body (client secret, refresh token) on the error object
console.error(
`Refresh failed for ${integration.providerIdentifier} (${integration.id}):`,
refreshError
? `message=${refreshError?.message || ''} status=${
refreshError?.status || refreshError?.response?.status || 0
} response=${safeStringify(
refreshError?.details?.[0]?.json ??
refreshError?.response?.data ??
''
)}`
: 'no access token returned'
);
// the scheduled refresh has no proof the token is dead, so transient /
// unrecognized errors should not disconnect the channel there, only
// errors the provider recognizes as an invalid refresh token. Every
// other caller refreshes because the platform already rejected the
// token, so they keep disconnecting.
if (refreshError && tolerateUnknownErrors) {
const handle = socialProvider.handleErrors?.(
`${refreshError?.message || ''} ${safeStringify(refreshError)}`,
refreshError?.status || refreshError?.response?.status || 0
);
if (handle?.type !== 'refresh-token') {
return false;
}
}
await this._integrationService.refreshNeeded(
integration.organizationId,
integration.id

View File

@ -106,7 +106,7 @@ export class NotEnoughScopes {
) {}
}
function safeStringify(obj: any) {
export function safeStringify(obj: any) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {

View File

@ -164,6 +164,12 @@ export interface SocialProvider
ISocialMediaIntegration {
identifier: string;
refreshWait?: boolean;
handleErrors?(
body: string,
status: number
):
| { type: 'refresh-token' | 'bad-body' | 'retry' | 'disconnect'; value: string }
| undefined;
convertToJPEG?: boolean;
stripLinks?: () => boolean;
refreshCron?: boolean;