π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
fix(integrations): keep the new refresh token when reconnecting a channel
Gilad Resisi49aa92ac2730
diff --git a/apps/backend/src/api/routes/no.auth.integrations.controller.ts b/apps/backend/src/api/routes/no.auth.integrations.controller.tsindex 3ac67cb54..e88615860 100644--- a/apps/backend/src/api/routes/no.auth.integrations.controller.ts+++ b/apps/backend/src/api/routes/no.auth.integrations.controller.ts@@ -136,7 +136,14 @@ export class NoAuthIntegrationsController {refresh,auth.accessToken);- return res({ ...newAuth, refreshToken: body.refresh });+ // keep the fresh refresh token and expiration from the new+ // authentication, otherwise the stored refresh token is wiped and+ // the channel breaks again as soon as the access token expires+ return res({+ ...newAuth,+ refreshToken: auth.refreshToken,+ expiresIn: auth.expiresIn,+ });} catch (err: any) {return res({error: err.message,diff --git a/apps/orchestrator/src/activities/post.activity.ts b/apps/orchestrator/src/activities/post.activity.tsindex cd7eefd82..6011d6518 100644--- a/apps/orchestrator/src/activities/post.activity.ts+++ b/apps/orchestrator/src/activities/post.activity.ts@@ -460,7 +460,10 @@ export class PostActivity {return refresh;} catch (err) {- await this._refreshIntegrationService.setBetweenSteps(integration);+ await this._refreshIntegrationService.setBetweenSteps(+ integration,+ (err as Error)?.message || ''+ );return false;}}@@ -489,7 +492,10 @@ export class PostActivity {return refresh;} catch (err) {- await this._refreshIntegrationService.setBetweenSteps(integration, cause);+ await this._refreshIntegrationService.setBetweenSteps(+ integration,+ cause || (err as Error)?.message || ''+ );return false;}}diff --git a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.tsindex 15434d6c8..73406e22d 100644--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts@@ -284,7 +284,8 @@ export class IntegrationRepository {profile: username,providerIdentifier: provider,token,- refreshToken,+ // never wipe a stored refresh token with an empty one+ ...(refreshToken ? { refreshToken } : {}),...(expiresIn? { tokenExpiration: new Date(Date.now() + expiresIn * 1000) }: {}),diff --git a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.tsindex a129641bf..4f38d921b 100644--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts@@ -183,9 +183,9 @@ export class IntegrationService {}}- async disconnectChannel(orgId: string, integration: Integration) {+ async disconnectChannel(orgId: string, integration: Integration, err = '') {await this._integrationRepository.disconnectChannel(orgId, integration.id);- await this.informAboutRefreshError(orgId, integration);+ await this.informAboutRefreshError(orgId, integration, err);}async informAboutRefreshError(@@ -195,7 +195,7 @@ export class IntegrationService {) {await this._notificationService.inAppNotification(orgId,- `Could not refresh your ${integration.providerIdentifier} channel ${err}`,+ `Could not refresh your ${integration.providerIdentifier} channel`,`Could not refresh your ${integration.providerIdentifier} channel ${err}. Please go back to the system and connect it again ${process.env.FRONTEND_URL}/launches`,true,false,diff --git a/libraries/nestjs-libraries/src/integrations/refresh.integration.service.ts b/libraries/nestjs-libraries/src/integrations/refresh.integration.service.tsindex 0689bdc60..8fabd0b5c 100644--- a/libraries/nestjs-libraries/src/integrations/refresh.integration.service.ts+++ b/libraries/nestjs-libraries/src/integrations/refresh.integration.service.ts@@ -73,25 +73,31 @@ export class RefreshIntegrationService {socialProvider: SocialProvider,cause = ''): Promise<AuthTokenDetails | false> {+ let refreshError: any = undefined;const refresh: false | AuthTokenDetails = await socialProvider.refreshToken(integration.refreshToken)- .catch((err) => false);+ .catch((err) => {+ refreshError = err;+ return false as const;+ });if (!refresh || !refresh.accessToken) {+ if (refreshError) {+ console.error(+ `Could not refresh ${integration.providerIdentifier} integration ${integration.id}`,+ refreshError?.response?.data || refreshError?.message || refreshError+ );+ }+await this._integrationService.refreshNeeded(integration.organizationId,integration.id);- await this._integrationService.informAboutRefreshError(- integration.organizationId,- integration,- cause- );-await this._integrationService.disconnectChannel(integration.organizationId,- integration+ integration,+ socialProvider.refreshErrorMessage?.(refreshError) || cause);return false;@@ -104,11 +110,20 @@ export class RefreshIntegrationService {return refresh;}- const reConnect = await socialProvider.reConnect(- integration.rootInternalId,- integration.internalId,- refresh.accessToken- );+ let reConnect;+ try {+ reConnect = await socialProvider.reConnect(+ integration.rootInternalId,+ integration.internalId,+ refresh.accessToken+ );+ } catch (err: any) {+ console.error(+ `Could not reconnect ${integration.providerIdentifier} integration ${integration.id} after a successful token refresh`,+ err?.response?.data || err?.message || err+ );+ throw err;+ }return {...refresh,diff --git a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.tsindex fb9db3cf7..15178fe3d 100644--- a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts+++ b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts@@ -167,6 +167,7 @@ export interface SocialProviderconvertToJPEG?: boolean;stripLinks?: () => boolean;refreshCron?: boolean;+ refreshErrorMessage?(err: any): string | undefined;dto?: any;maxLength: (additionalSettings?: any, settings?: any) => number;checkValidity(diff --git a/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts b/libraries/nestjs-libraries/src/integrations/social/youtube.provider.tsindex 1e6f3852a..d9f3f8fa1 100644--- a/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts@@ -259,6 +259,19 @@ export class YoutubeProvider extends SocialAbstract implements SocialProvider {return undefined;}+ refreshErrorMessage(err: any): string | undefined {+ const data = err?.response?.data || {};+ const text = `${data.error_subtype || ''} ${data.error_description || ''} ${+ err?.message || ''+ }`;++ if (text.includes('invalid_rapt')) {+ return `because your organization's Google Workspace session policy invalidated its access. Ask your Google Workspace admin to mark Postiz as a trusted app and turn on "Exempt trusted apps" (https://support.google.com/a/answer/9368756) to prevent this from happening again`;+ }++ return undefined;+ }+async refreshToken(refresh_token: string): Promise<AuthTokenDetails> {const { client, oauth2 } = clientAndYoutube();client.setCredentials({ refresh_token });@@ -394,10 +407,17 @@ export class YoutubeProvider extends SocialAbstract implements SocialProvider {requiredId: string,accessToken: string): Promise<Omit<AuthTokenDetails, 'refreshToken' | 'expiresIn'>> {- const pages = await this.pages(accessToken);- const findPage = pages.find((p) => p.id === requiredId);+ const { client, youtube } = clientAndYoutube();+ client.setCredentials({ access_token: accessToken });++ // don't go through pages() here, it swallows the real Google error and an+ // empty list would be reported as a missing channel+ const { data } = await youtube(client).channels.list({+ part: ['id'],+ mine: true,+ });- if (!findPage) {+ if (!(data.items || []).some((p) => p.id === requiredId)) {throw new Error('Channel not found');}