Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions apps/builder/__tests__/disconnect-instagram.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { unsubscribePageFromInstagramWebhook as unsubscribeInstagramLogin } from "@chatbotx.io/integration-instagram/apis/page"
import { unsubscribePageFromInstagramWebhook as unsubscribeFacebookLogin } from "@chatbotx.io/integration-instagram-facebook/apis/page"
import { HttpResponse, http, server } from "@chatbotx.io/vitest-config/msw"
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
test,
vi,
} from "vitest"

const mocks = vi.hoisted(() => ({
disconnect: vi.fn(),
findIntegration: vi.fn(),
transaction: vi.fn(async () => undefined),
}))

vi.mock("@chatbotx.io/business", () => ({
coexistService: {},
contactScanService: {},
contactSyncService: {},
instagramIntegrationService: {
findByIdForWorkspace: mocks.findIntegration,
},
messengerIntegrationService: { existsForPage: vi.fn(async () => false) },
workspaceService: { findById: vi.fn(async () => ({ ownerId: "owner-1" })) },
}))
vi.mock("@chatbotx.io/business/audit", () => ({
auditService: { record: vi.fn() },
}))
vi.mock("@chatbotx.io/business/connection", () => ({
connectionStateService: {},
}))
vi.mock("@chatbotx.io/business/errors", () => ({
notFoundException: (message: string) => new Error(message),
}))
vi.mock("@chatbotx.io/database/client", () => ({
db: { transaction: mocks.transaction },
}))
vi.mock("@chatbotx.io/database/repositories", () => ({
metaCapiEventRepository: {},
}))
vi.mock("@/integration", () => ({
integrations: {
instagram: { disconnect: mocks.disconnect },
instagramFacebook: { disconnect: mocks.disconnect },
},
}))
vi.mock("@/lib/log", () => ({ logger: { warn: vi.fn() } }))

const { disconnectInstagram } = await import(
"@/features/integration-instagram/actions/disconnect-instagram"
)

const run = () =>
disconnectInstagram({
workspaceId: "workspace-1",
integrationInstagramId: "integration-1",
})

type MetaError = { code: number; message: string }

const LOGINS = [
{
type: "facebook",
url: "https://graph.facebook.com/:version/page-1/subscribed_apps",
unsubscribe: () =>
unsubscribeFacebookLogin({
pageId: "page-1",
appAccessToken: "client-1|secret",
}),
},
{
type: "instagram",
url: "https://graph.instagram.com/:version/page-1/subscribed_apps",
unsubscribe: () =>
unsubscribeInstagramLogin({ igId: "page-1", accessToken: "token" }),
},
]

describe.each(
LOGINS,
)("disconnectInstagram ($type login) when the unsubscribe fails", (login) => {
// Builder tests have no shared MSW setup: listen here, and never reach Meta.
beforeAll(() => server.listen({ onUnhandledRequest: "error" }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

beforeEach(() => {
vi.clearAllMocks()
mocks.findIntegration.mockResolvedValue({
id: "integration-1",
inboxId: "inbox-1",
type: login.type,
auth: { clientId: "client-1", metadata: { pageId: "page-1" } },
})
})

const metaRejects = (error: MetaError) => {
server.use(
http.delete(login.url, () =>
HttpResponse.json({ error }, { status: 400 }),
),
)
mocks.disconnect.mockImplementation(login.unsubscribe)
}

test("removes the channel when the app is no longer installed", async () => {
metaRejects({
code: 100,
message: "(#100) App is not installed: 123",
})

await run()

expect(mocks.transaction).toHaveBeenCalledTimes(1)
})

test("keeps the channel and surfaces a rate limit", async () => {
metaRejects({ code: 4, message: "(#4) Application request limit reached" })

await expect(run()).rejects.toThrow("request limit")
expect(mocks.transaction).not.toHaveBeenCalled()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import { db } from "@chatbotx.io/database/client"
import { metaCapiEventRepository } from "@chatbotx.io/database/repositories"
import {
type InstagramAuthValue,
isRevokedTokenError,
isDisconnectSafeError,
} from "@chatbotx.io/integration-instagram"
import { isRevokedTokenError as isRevokedTokenErrorFacebook } from "@chatbotx.io/integration-instagram-facebook"
import { isDisconnectSafeError as isDisconnectSafeErrorFacebook } from "@chatbotx.io/integration-instagram-facebook"
import { integrations } from "@/integration"
import { logger } from "@/lib/log"

Expand Down Expand Up @@ -60,11 +60,11 @@ export const disconnectInstagram = async (ctx: {
"Instagram disconnect API call failed — proceeding with local cleanup",
)

const isRevoked = isFacebook
? isRevokedTokenErrorFacebook(error)
: isRevokedTokenError(error)
const isSafeToIgnore = isFacebook
? isDisconnectSafeErrorFacebook(error)
: isDisconnectSafeError(error)

if (!isRevoked) {
if (!isSafeToIgnore) {
throw error
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { HttpResponse, http, server } from "@chatbotx.io/vitest-config/msw"
import { describe, expect, test } from "vitest"
import { unsubscribePageFromInstagramWebhook } from "../src/apis/page"
import { DEFAULT_API_VERSION } from "../src/constants"
import { isDisconnectSafeError } from "../src/lib/error-mapper"

const URL = `https://graph.facebook.com/${DEFAULT_API_VERSION}/page-1/subscribed_apps`

const unsubscribeError = async (
status: number,
error: Record<string, unknown>,
): Promise<unknown> => {
server.use(http.delete(URL, () => HttpResponse.json({ error }, { status })))
return await unsubscribePageFromInstagramWebhook({
pageId: "page-1",
appAccessToken: "client-id|client-secret",
version: DEFAULT_API_VERSION,
}).catch((err: unknown) => err)
}

describe("isDisconnectSafeError for a Facebook-backed Instagram unsubscribe", () => {
test.each([
[
"the app is no longer installed",
{ code: 100, message: "(#100) App is not installed: 123" },
],
[
"the token was revoked",
{
code: 190,
error_subcode: 458,
type: "OAuthException",
message: "Error validating access token",
},
],
])("is true when %s", async (_name, error) => {
expect(isDisconnectSafeError(await unsubscribeError(400, error))).toBe(true)
})

test.each([
[
"a rate limit",
400,
{ code: 4, message: "(#4) Application request limit reached" },
],
[
"a server error",
500,
{ code: 2, message: "Service temporarily unavailable" },
],
[
"another invalid parameter",
400,
{ code: 100, message: "(#100) Invalid parameter" },
],
[
"a missing object",
400,
{ code: 100, error_subcode: 33, message: "Unsupported delete request." },
],
[
"a permissions error",
400,
{ code: 200, message: "(#200) Permissions error" },
],
[
"a 190 without a revocation subcode",
400,
{
code: 190,
type: "OAuthException",
message: "Error validating client secret.",
},
],
])("is false for %s", async (_name, status, error) => {
expect(isDisconnectSafeError(await unsubscribeError(status, error))).toBe(
false,
)
})
})
6 changes: 5 additions & 1 deletion integrations/instagram-facebook/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@ export {
listInstagramStories,
} from "./apis/post"
export * from "./integration"
export { isRevokedTokenError, mapToChannelError } from "./lib/error-mapper"
export {
isDisconnectSafeError,
isRevokedTokenError,
mapToChannelError,
} from "./lib/error-mapper"
export * from "./schema"
13 changes: 13 additions & 0 deletions integrations/instagram-facebook/src/lib/error-mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
ChannelErrorReason,
UNKNOWN_ERROR,
} from "@chatbotx.io/sdk"
import { isGraphAppNotInstalled } from "@chatbotx.io/utils/graph-error"
import {
type ChannelErrorSource,
InstagramException,
Expand Down Expand Up @@ -232,6 +233,18 @@ export function isRevokedTokenError(error: unknown): boolean {
)
}

// === Disconnect-safe error detection ===
/** True when retrying the unsubscribe is pointless: the local disconnect proceeds. */
export function isDisconnectSafeError(error: unknown): boolean {
if (!(error instanceof InstagramException)) {
return false
}
return (
isRevokedTokenError(error) ||
isGraphAppNotInstalled(mapToChannelError(error))
)
}

// === Handover Protocol: "not the thread owner" detection ===
// Meta refuses a Send API call with code 200 + error_subcode 2534037 when the
// conversation is owned by another app (the Instagram inbox takes the thread
Expand Down
80 changes: 80 additions & 0 deletions integrations/instagram/__tests__/disconnect-safe-error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { HttpResponse, http, server } from "@chatbotx.io/vitest-config/msw"
import { describe, expect, test } from "vitest"
import { unsubscribePageFromInstagramWebhook } from "../src/apis/page"
import { DEFAULT_API_VERSION } from "../src/constants"
import { isDisconnectSafeError } from "../src/lib/error-mapper"

const URL = `https://graph.instagram.com/${DEFAULT_API_VERSION}/ig-1/subscribed_apps`

const unsubscribeError = async (
status: number,
error: Record<string, unknown>,
): Promise<unknown> => {
server.use(http.delete(URL, () => HttpResponse.json({ error }, { status })))
return await unsubscribePageFromInstagramWebhook({
igId: "ig-1",
accessToken: "token",
version: DEFAULT_API_VERSION,
}).catch((err: unknown) => err)
}

describe("isDisconnectSafeError for an Instagram Login unsubscribe", () => {
test.each([
[
"the app is no longer installed",
{ code: 100, message: "(#100) App is not installed: 123" },
],
[
"the token was revoked",
{
code: 190,
error_subcode: 458,
type: "OAuthException",
message: "Error validating access token",
},
],
])("is true when %s", async (_name, error) => {
expect(isDisconnectSafeError(await unsubscribeError(400, error))).toBe(true)
})

test.each([
[
"a rate limit",
400,
{ code: 4, message: "(#4) Application request limit reached" },
],
[
"a server error",
500,
{ code: 2, message: "Service temporarily unavailable" },
],
[
"another invalid parameter",
400,
{ code: 100, message: "(#100) Invalid parameter" },
],
[
"a missing object",
400,
{ code: 100, error_subcode: 33, message: "Unsupported delete request." },
],
[
"a permissions error",
400,
{ code: 200, message: "(#200) Permissions error" },
],
[
"a 190 without a revocation subcode",
400,
{
code: 190,
type: "OAuthException",
message: "Error validating client secret.",
},
],
])("is false for %s", async (_name, status, error) => {
expect(isDisconnectSafeError(await unsubscribeError(status, error))).toBe(
false,
)
})
})
6 changes: 5 additions & 1 deletion integrations/instagram/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,9 @@ export {
} from "./apis/post"
export * from "./apis/sync"
export * from "./integration"
export { isRevokedTokenError, mapToChannelError } from "./lib/error-mapper"
export {
isDisconnectSafeError,
isRevokedTokenError,
mapToChannelError,
} from "./lib/error-mapper"
export * from "./schema"
13 changes: 13 additions & 0 deletions integrations/instagram/src/lib/error-mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
ChannelErrorReason,
UNKNOWN_ERROR,
} from "@chatbotx.io/sdk"
import { isGraphAppNotInstalled } from "@chatbotx.io/utils/graph-error"
import {
type ChannelErrorSource,
InstagramException,
Expand Down Expand Up @@ -235,3 +236,15 @@ export function isRevokedTokenError(error: unknown): boolean {
REVOKED_TOKEN_SUBCODES.has(subCode)
)
}

// === Disconnect-safe error detection ===
/** True when retrying the unsubscribe is pointless: the local disconnect proceeds. */
export function isDisconnectSafeError(error: unknown): boolean {
if (!(error instanceof InstagramException)) {
return false
}
return (
isRevokedTokenError(error) ||
isGraphAppNotInstalled(mapToChannelError(error))
)
}
Loading
Loading