AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(pieces): see which account each connection belongs to on 20 more pieces (#16025)
Ibrahim Abuznaidf9b149bfea1f
diff --git a/bun.lock b/bun.lockindex dd9923d1c26..66e9d34135c 100644--- a/bun.lock+++ b/bun.lock@@ -1937,7 +1937,7 @@},"packages/pieces/community/clicdata": {"name": "@activepieces/piece-clicdata",- "version": "0.0.9",+ "version": "0.0.10","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -1946,6 +1946,7 @@},"devDependencies": {"tslib": "^2.3.0",+ "vitest": "3.2.6",},},"packages/pieces/community/clickfunnels": {@@ -2613,7 +2614,7 @@},"packages/pieces/community/digital-ocean": {"name": "@activepieces/piece-digital-ocean",- "version": "0.1.0",+ "version": "0.1.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -2622,6 +2623,7 @@},"devDependencies": {"tslib": "^2.3.0",+ "vitest": "3.2.6",},},"packages/pieces/community/digital-pilot": {@@ -3483,7 +3485,7 @@},"packages/pieces/community/free-agent": {"name": "@activepieces/piece-free-agent",- "version": "0.1.7",+ "version": "0.1.8","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -3492,6 +3494,7 @@},"devDependencies": {"tslib": "^2.3.0",+ "vitest": "3.2.6",},},"packages/pieces/community/freshdesk": {@@ -3698,7 +3701,7 @@},"packages/pieces/community/github": {"name": "@activepieces/piece-github",- "version": "0.9.0",+ "version": "0.9.2","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -3755,7 +3758,7 @@},"packages/pieces/community/gmail": {"name": "@activepieces/piece-gmail",- "version": "0.17.1",+ "version": "0.17.3","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -4598,7 +4601,7 @@},"packages/pieces/community/instagram-business": {"name": "@activepieces/piece-instagram-business",- "version": "1.0.0",+ "version": "1.0.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -4607,6 +4610,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/instantly-ai": {@@ -4638,7 +4642,7 @@},"packages/pieces/community/intercom": {"name": "@activepieces/piece-intercom",- "version": "0.8.1",+ "version": "0.8.2","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -4650,6 +4654,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/intruder": {@@ -4891,7 +4896,7 @@},"packages/pieces/community/klaviyo": {"name": "@activepieces/piece-klaviyo",- "version": "0.2.0",+ "version": "0.2.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -4901,6 +4906,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/klenty": {@@ -5439,7 +5445,7 @@},"packages/pieces/community/mailchimp": {"name": "@activepieces/piece-mailchimp",- "version": "0.5.8",+ "version": "0.5.9","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -5450,6 +5456,7 @@"devDependencies": {"@types/mailchimp__mailchimp_marketing": "3.0.22","tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/mailer-lite": {@@ -6410,7 +6417,7 @@},"packages/pieces/community/notion": {"name": "@activepieces/piece-notion",- "version": "0.7.3",+ "version": "0.7.4","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -7030,7 +7037,7 @@},"packages/pieces/community/pinterest": {"name": "@activepieces/piece-pinterest",- "version": "0.2.0",+ "version": "0.2.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -7040,11 +7047,12 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/pipedrive": {"name": "@activepieces/piece-pipedrive",- "version": "0.10.0",+ "version": "0.10.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -7056,6 +7064,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/placid": {@@ -7113,7 +7122,7 @@},"packages/pieces/community/podio": {"name": "@activepieces/piece-podio",- "version": "0.2.1",+ "version": "0.2.2","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -7122,6 +7131,7 @@},"devDependencies": {"tslib": "^2.3.0",+ "vitest": "3.2.6",},},"packages/pieces/community/pollybot-ai": {@@ -7815,7 +7825,7 @@},"packages/pieces/community/ringcentral": {"name": "@activepieces/piece-ringcentral",- "version": "0.1.0",+ "version": "0.1.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8006,7 +8016,7 @@},"packages/pieces/community/savvycal": {"name": "@activepieces/piece-savvycal",- "version": "0.2.0",+ "version": "0.2.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8015,6 +8025,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/scenario": {@@ -8323,7 +8334,7 @@},"packages/pieces/community/sign-now": {"name": "@activepieces/piece-sign-now",- "version": "0.0.6",+ "version": "0.0.7","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8333,6 +8344,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/signrequest": {@@ -8389,7 +8401,7 @@},"packages/pieces/community/simplyprint": {"name": "@activepieces/piece-simplyprint",- "version": "0.6.6",+ "version": "0.6.7","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8674,7 +8686,7 @@},"packages/pieces/community/spotify": {"name": "@activepieces/piece-spotify",- "version": "0.6.0",+ "version": "0.6.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8683,6 +8695,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/square": {@@ -9193,7 +9206,7 @@},"packages/pieces/community/todoist": {"name": "@activepieces/piece-todoist",- "version": "0.5.0",+ "version": "0.5.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -9203,6 +9216,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/toggl-track": {@@ -10311,7 +10325,7 @@},"packages/pieces/community/zoom": {"name": "@activepieces/piece-zoom",- "version": "0.8.0",+ "version": "0.8.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -10320,6 +10334,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/zuora": {diff --git a/packages/pieces/community/clicdata/package.json b/packages/pieces/community/clicdata/package.jsonindex 77e59934548..2394bde7706 100644--- a/packages/pieces/community/clicdata/package.json+++ b/packages/pieces/community/clicdata/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-clicdata",- "version": "0.0.9",+ "version": "0.0.10","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -11,11 +11,13 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "^2.3.0"+ "tslib": "^2.3.0",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/clicdata/src/lib/common/auth.ts b/packages/pieces/community/clicdata/src/lib/common/auth.tsindex a1207bdcede..d9fbd7f5dcd 100644--- a/packages/pieces/community/clicdata/src/lib/common/auth.ts+++ b/packages/pieces/community/clicdata/src/lib/common/auth.ts@@ -3,7 +3,7 @@ import {PieceAuth,Property,} from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';import { clicdataApiCall } from './client';import { AppConnectionType } from '@activepieces/pieces-framework';@@ -41,6 +41,8 @@ export const clicdataAuth = [};}},+ getConnectionIdentifier: async ({ auth }) =>+ fetchAccountLabel({ Authorization: `Bearer ${auth.access_token}` }),}),PieceAuth.SecretText({displayName: 'API Key',@@ -64,6 +66,8 @@ export const clicdataAuth = [};}},+ getConnectionIdentifier: async ({ auth }) =>+ fetchAccountLabel({ 'CLICDATA-API-KEY': auth }),}),PieceAuth.CustomAuth({displayName: 'Basic Auth',@@ -105,9 +109,31 @@ export const clicdataAuth = [};}},+ getConnectionIdentifier: async ({ auth }) =>+ auth.userEmail?.trim() || undefined,}),];export type ClicdataAuthValue = AppConnectionValueForAuthProperty<typeof clicdataAuth>;++async function fetchAccountLabel(+ headers: Record<string, string>+): Promise<string | undefined> {+ try {+ const response = await httpClient.sendRequest<{+ result?: { name?: string; domain?: string };+ }>({+ method: HttpMethod.GET,+ url: 'https://api.clicdata.com/account',+ queryParams: { api_version: '2022.01' },+ headers,+ timeout: 5000,+ });+ const account = response.body.result;+ return account?.name || account?.domain || undefined;+ } catch {+ return undefined;+ }+}diff --git a/packages/pieces/community/clicdata/test/connection-identifier.test.ts b/packages/pieces/community/clicdata/test/connection-identifier.test.tsnew file mode 100644index 00000000000..80cc33098c3--- /dev/null+++ b/packages/pieces/community/clicdata/test/connection-identifier.test.ts@@ -0,0 +1,265 @@+import { PropertyType } from '@activepieces/pieces-framework';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { clicdataAuth } from '../src/lib/common/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++const ACCOUNT_URL = 'https://api.clicdata.com/account?api_version=2022.01';++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function stubNetworkError(): void {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+}++function oauth(extra: Partial<ClicdataOAuthValue> = {}): ClicdataOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++function withoutKey<T extends object>({+ value,+ key,+}: {+ value: T;+ key: keyof T;+}): T {+ const copy = { ...value };+ Reflect.deleteProperty(copy, key);+ return copy;+}++async function identifyWithOAuth(auth: ClicdataOAuthValue = oauth()) {+ const variant = clicdataAuth[0];+ if (variant.type !== PropertyType.OAUTH2) {+ throw new Error('clicdataAuth[0] is not the OAuth2 auth');+ }+ const hook = variant.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('clicdataAuth[0] has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++async function identifyWithApiKey(key: string) {+ const variant = clicdataAuth[1];+ if (variant.type !== PropertyType.SECRET_TEXT) {+ throw new Error('clicdataAuth[1] is not the API key auth');+ }+ const hook = variant.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('clicdataAuth[1] has no getConnectionIdentifier hook');+ }+ return hook({ auth: key, server });+}++async function identifyWithBasic(auth: ClicdataBasicValue) {+ const variant = clicdataAuth[2];+ if (variant.type !== PropertyType.CUSTOM_AUTH) {+ throw new Error('clicdataAuth[2] is not the Basic auth');+ }+ const hook = variant.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('clicdataAuth[2] has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('clicdata OAuth2 getConnectionIdentifier', () => {+ test('happy path: result.name from GET /account with the bearer token', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ success: true,+ result: { id: 1, name: 'My Account', domain: 'myaccount' },+ },+ }));+ expect(await identifyWithOAuth()).toBe('My Account');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe(ACCOUNT_URL);+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('token data carries no identity on ClicData: the call is still made', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { success: true, result: { name: 'My Account' } },+ }));+ expect(+ await identifyWithOAuth(+ oauth({ data: { grant_type: 'client_credentials' } })+ )+ ).toBe('My Account');+ expect(seen).toHaveLength(1);+ });++ test('empty result.name falls back to result.domain', async () => {+ stubFetch(() => ({+ status: 200,+ body: { success: true, result: { id: 1, name: '', domain: 'myaccount' } },+ }));+ expect(await identifyWithOAuth()).toBe('myaccount');+ });++ test('empty name and domain returns undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { success: true, result: { id: 1, name: '', domain: '' } },+ }));+ expect(await identifyWithOAuth()).toBeUndefined();+ });++ test('success:false body with HTTP 200 returns undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ success: false,+ error: { code: 'unauthorized', description: 'Missing scope' },+ },+ }));+ expect(await identifyWithOAuth()).toBeUndefined();+ });++ test('HTTP 401 returns undefined without throwing', async () => {+ stubFetch(() => ({+ status: 401,+ body: {+ success: false,+ error: { code: '401', description: 'Unauthorized' },+ },+ }));+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ });++ test('HTTP 500 returns undefined without throwing', async () => {+ stubFetch(() => ({ status: 500, body: {} }));+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ });++ test('network error returns undefined without throwing', async () => {+ stubNetworkError();+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ });+});++describe('clicdata API key getConnectionIdentifier', () => {+ test('GET /account with the CLICDATA-API-KEY header and no Authorization header', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { success: true, result: { name: 'My Account' } },+ }));+ expect(await identifyWithApiKey('KEY123')).toBe('My Account');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe(ACCOUNT_URL);+ expect(seen[0].method).toBe('GET');+ expect(seen[0].headers.get('clicdata-api-key')).toBe('KEY123');+ expect(seen[0].auth).toBeNull();+ });++ test('HTTP 401 returns undefined without throwing', async () => {+ stubFetch(() => ({ status: 401, body: {} }));+ await expect(identifyWithApiKey('KEY123')).resolves.toBeUndefined();+ });+});++describe('clicdata Basic auth getConnectionIdentifier', () => {+ test('returns the typed userEmail, trimmed, with zero network calls', async () => {+ const seen = stubFetch(() => ({ status: 500, body: {} }));+ expect(+ await identifyWithBasic({+ clientId: 'c1',+ userEmail: ' [email protected] ',+ userPassword: 'pw',+ })+ ).toBe('[email protected]');+ expect(seen).toHaveLength(0);+ });++ test('blank userEmail returns undefined', async () => {+ expect(+ await identifyWithBasic({+ clientId: 'c1',+ userEmail: ' ',+ userPassword: 'pw',+ })+ ).toBeUndefined();+ });++ test('missing userEmail returns undefined without throwing', async () => {+ const auth = withoutKey({+ value: { clientId: 'c1', userEmail: 'unused', userPassword: 'pw' },+ key: 'userEmail',+ });+ await expect(identifyWithBasic(auth)).resolves.toBeUndefined();+ });+});++type ClicdataOAuthValue = Parameters<+ NonNullable<+ Extract<+ (typeof clicdataAuth)[number],+ { type: PropertyType.OAUTH2 }+ >['getConnectionIdentifier']+ >+>[0]['auth'];++type ClicdataBasicValue = Parameters<+ NonNullable<+ Extract<+ (typeof clicdataAuth)[number],+ { type: PropertyType.CUSTOM_AUTH }+ >['getConnectionIdentifier']+ >+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/clicdata/vitest.config.ts b/packages/pieces/community/clicdata/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/clicdata/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/digital-ocean/package.json b/packages/pieces/community/digital-ocean/package.jsonindex e56104f0a97..18d5295e74f 100644--- a/packages/pieces/community/digital-ocean/package.json+++ b/packages/pieces/community/digital-ocean/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-digital-ocean",- "version": "0.1.0",+ "version": "0.1.1","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -11,11 +11,13 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "^2.3.0"+ "tslib": "^2.3.0",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/digital-ocean/src/lib/common/auth.ts b/packages/pieces/community/digital-ocean/src/lib/common/auth.tsindex c1afc0711d8..4e457efcfa7 100644--- a/packages/pieces/community/digital-ocean/src/lib/common/auth.ts+++ b/packages/pieces/community/digital-ocean/src/lib/common/auth.ts@@ -2,7 +2,7 @@ import {AppConnectionValueForAuthProperty,PieceAuth,} from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';import { digitalOceanApiCall } from './client';import { AppConnectionType } from '@activepieces/pieces-framework';@@ -31,6 +31,14 @@ export const digitalOceanAuth = [};}},+ getConnectionIdentifier: async ({ auth }) => {+ const info: DigitalOceanTokenInfo | undefined = auth.data['info'];+ const fromToken = info?.email || info?.name || info?.team_name;+ if (fromToken) {+ return fromToken;+ }+ return fetchAccountLabel(auth.access_token);+ },}),PieceAuth.SecretText({displayName: 'Personal Access Token',@@ -55,9 +63,41 @@ export const digitalOceanAuth = [};}},+ getConnectionIdentifier: async ({ auth }) => fetchAccountLabel(auth),}),];export type DigitalOceanAuthValue = AppConnectionValueForAuthProperty<typeof digitalOceanAuth>;++async function fetchAccountLabel(+ token: string+): Promise<string | undefined> {+ try {+ const response = await httpClient.sendRequest<{+ account?: DigitalOceanAccount;+ }>({+ method: HttpMethod.GET,+ url: 'https://api.digitalocean.com/v2/account',+ headers: { Authorization: `Bearer ${token}` },+ timeout: 5000,+ });+ const account = response.body.account;+ return account?.email || account?.name || account?.team?.name || undefined;+ } catch {+ return undefined;+ }+}++type DigitalOceanTokenInfo = {+ email?: string;+ name?: string;+ team_name?: string;+};++type DigitalOceanAccount = {+ email?: string;+ name?: string;+ team?: { name?: string };+};diff --git a/packages/pieces/community/digital-ocean/test/connection-identifier.test.ts b/packages/pieces/community/digital-ocean/test/connection-identifier.test.tsnew file mode 100644index 00000000000..458366eab49--- /dev/null+++ b/packages/pieces/community/digital-ocean/test/connection-identifier.test.ts@@ -0,0 +1,272 @@+import { PropertyType } from '@activepieces/pieces-framework';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { digitalOceanAuth } from '../src/lib/common/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++const ACCOUNT_URL = 'https://api.digitalocean.com/v2/account';++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function stubNetworkError(): void {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+}++function oauth(+ extra: Partial<DigitalOceanOAuthValue> = {}+): DigitalOceanOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identifyWithOAuth(auth: DigitalOceanOAuthValue = oauth()) {+ const variant = digitalOceanAuth[0];+ if (variant.type !== PropertyType.OAUTH2) {+ throw new Error('digitalOceanAuth[0] is not the OAuth2 auth');+ }+ const hook = variant.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('digitalOceanAuth[0] has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++async function identifyWithPat(token: string) {+ const variant = digitalOceanAuth[1];+ if (variant.type !== PropertyType.SECRET_TEXT) {+ throw new Error(+ 'digitalOceanAuth[1] is not the Personal Access Token auth'+ );+ }+ const hook = variant.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('digitalOceanAuth[1] has no getConnectionIdentifier hook');+ }+ return hook({ auth: token, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('digital-ocean OAuth2 getConnectionIdentifier', () => {+ test('token data: info.email from the token response, zero network calls', async () => {+ const seen = stubFetch(() => ({ status: 500, body: {} }));+ const id = await identifyWithOAuth(+ oauth({+ data: {+ info: {+ name: 'Sammy',+ email: '[email protected]',+ uuid: 'u1',+ team_uuid: 't1',+ team_name: 'My Team',+ },+ },+ })+ );+ expect(id).toBe('[email protected]');+ expect(seen).toHaveLength(0);+ });++ test('token data: info.name when info.email is empty, zero network calls', async () => {+ const seen = stubFetch(() => ({ status: 500, body: {} }));+ expect(+ await identifyWithOAuth(+ oauth({+ data: { info: { email: '', name: 'Sammy', team_name: 'My Team' } },+ })+ )+ ).toBe('Sammy');+ expect(seen).toHaveLength(0);+ });++ test('token data: info.team_name when email and name are empty, zero network calls', async () => {+ const seen = stubFetch(() => ({ status: 500, body: {} }));+ expect(+ await identifyWithOAuth(+ oauth({ data: { info: { email: '', name: '', team_name: 'My Team' } } })+ )+ ).toBe('My Team');+ expect(seen).toHaveLength(0);+ });++ test('no info in token data: GET /v2/account with the bearer token returns account.email', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ account: {+ email: '[email protected]',+ name: 'Sammy',+ team: { name: 'My Team' },+ },+ },+ }));+ expect(await identifyWithOAuth()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe(ACCOUNT_URL);+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('info with all-empty fields falls through to the network call', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { account: { email: '[email protected]' } },+ }));+ expect(+ await identifyWithOAuth(+ oauth({ data: { info: { email: '', name: '', team_name: '' } } })+ )+ ).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ });++ test('network: empty account.email falls back to account.name', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ account: { email: '', name: 'Sammy', team: { name: 'My Team' } },+ },+ }));+ expect(await identifyWithOAuth()).toBe('Sammy');+ });++ test('network: empty email and name fall back to account.team.name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { account: { email: '', name: '', team: { name: 'My Team' } } },+ }));+ expect(await identifyWithOAuth()).toBe('My Team');+ });++ test('network: all fields empty returns undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { account: { email: '', name: '', team: { name: '' } } },+ }));+ expect(await identifyWithOAuth()).toBeUndefined();+ });++ test('network: body without account returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: {} }));+ expect(await identifyWithOAuth()).toBeUndefined();+ });++ test('HTTP 401 returns undefined without throwing', async () => {+ stubFetch(() => ({+ status: 401,+ body: { id: 'unauthorized', message: 'Unable to authenticate you.' },+ }));+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ });++ test('HTTP 403 for a token missing account:read returns undefined without throwing', async () => {+ stubFetch(() => ({+ status: 403,+ body: {+ id: 'forbidden',+ message: 'You are not authorized to perform this operation',+ },+ }));+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ });++ test('HTTP 500 returns undefined without throwing', async () => {+ stubFetch(() => ({ status: 500, body: { id: 'server_error' } }));+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ });++ test('network error returns undefined without throwing', async () => {+ stubNetworkError();+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ });+});++describe('digital-ocean Personal Access Token getConnectionIdentifier', () => {+ test('GET /v2/account sends the PAT in the bearer header and returns account.email', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { account: { email: '[email protected]', name: 'Sammy' } },+ }));+ expect(await identifyWithPat('dop_v1_PAT')).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe(ACCOUNT_URL);+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer dop_v1_PAT');+ });++ test('empty email and name fall back to team.name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { account: { email: '', name: '', team: { name: 'My Team' } } },+ }));+ expect(await identifyWithPat('dop_v1_PAT')).toBe('My Team');+ });++ test('HTTP 403 from a scoped PAT without account:read returns undefined without throwing', async () => {+ stubFetch(() => ({ status: 403, body: { id: 'forbidden' } }));+ await expect(identifyWithPat('dop_v1_PAT')).resolves.toBeUndefined();+ });++ test('network error returns undefined without throwing', async () => {+ stubNetworkError();+ await expect(identifyWithPat('dop_v1_PAT')).resolves.toBeUndefined();+ });+});++type DigitalOceanOAuthValue = Parameters<+ NonNullable<+ Extract<+ (typeof digitalOceanAuth)[number],+ { type: PropertyType.OAUTH2 }+ >['getConnectionIdentifier']+ >+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/digital-ocean/vitest.config.ts b/packages/pieces/community/digital-ocean/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/digital-ocean/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/free-agent/package.json b/packages/pieces/community/free-agent/package.jsonindex 880f39fa1cf..136ce1b3b62 100644--- a/packages/pieces/community/free-agent/package.json+++ b/packages/pieces/community/free-agent/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-free-agent",- "version": "0.1.7",+ "version": "0.1.8","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -11,11 +11,13 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "^2.3.0"+ "tslib": "^2.3.0",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/free-agent/src/lib/auth.ts b/packages/pieces/community/free-agent/src/lib/auth.tsindex 989107445b6..6abcbdee732 100644--- a/packages/pieces/community/free-agent/src/lib/auth.ts+++ b/packages/pieces/community/free-agent/src/lib/auth.ts@@ -27,4 +27,28 @@ export const freeAgentAuth = PieceAuth.OAuth2({};}},+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<{ user?: FreeAgentUser }>({+ method: HttpMethod.GET,+ url: 'https://api.freeagent.com/v2/users/me',+ headers: {+ Authorization: `Bearer ${auth.access_token}`,+ Accept: 'application/json',+ },+ timeout: 5000,+ });+ const user = response.body.user;+ const fullName = [user?.first_name, user?.last_name].filter(Boolean).join(' ');+ return user?.email || fullName || undefined;+ } catch {+ return undefined;+ }+ },});++type FreeAgentUser = {+ email?: string;+ first_name?: string;+ last_name?: string;+};diff --git a/packages/pieces/community/free-agent/test/connection-identifier.test.ts b/packages/pieces/community/free-agent/test/connection-identifier.test.tsnew file mode 100644index 00000000000..bef619b483c--- /dev/null+++ b/packages/pieces/community/free-agent/test/connection-identifier.test.ts@@ -0,0 +1,159 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { freeAgentAuth } from '../src/lib/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<FreeAgentOAuthValue> = {}): FreeAgentOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identify(auth: FreeAgentOAuthValue = oauth()) {+ const hook = freeAgentAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('freeAgentAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('free-agent getConnectionIdentifier', () => {+ test('happy path: user.email from GET /v2/users/me with the bearer token', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ user: {+ url: 'https://api.freeagent.com/v2/users/1',+ first_name: 'My',+ last_name: 'User',+ email: '[email protected]',+ },+ },+ }));+ expect(await identify()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.freeagent.com/v2/users/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ expect(seen[0].headers.get('accept')).toBe('application/json');+ });++ test('token data carries no identity on FreeAgent: the call is still made', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { user: { email: '[email protected]' } },+ }));+ expect(+ await identify(oauth({ data: { refresh_token_expires_in: 631151957 } }))+ ).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ });++ test('empty email falls back to "first last"', async () => {+ stubFetch(() => ({+ status: 200,+ body: { user: { email: '', first_name: 'My', last_name: 'User' } },+ }));+ expect(await identify()).toBe('My User');+ });++ test('missing email with only first_name returns first_name alone', async () => {+ stubFetch(() => ({+ status: 200,+ body: { user: { first_name: 'My', last_name: '' } },+ }));+ expect(await identify()).toBe('My');+ });++ test('missing email with only last_name returns last_name alone', async () => {+ stubFetch(() => ({ status: 200, body: { user: { last_name: 'User' } } }));+ expect(await identify()).toBe('User');+ });++ test('all fields empty returns undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { user: { email: '', first_name: '', last_name: '' } },+ }));+ expect(await identify()).toBeUndefined();+ });++ test('body without user returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: {} }));+ expect(await identify()).toBeUndefined();+ });++ test('HTTP 401 returns undefined without throwing', async () => {+ stubFetch(() => ({+ status: 401,+ body: { errors: { error: { message: 'Access token not recognised' } } },+ }));+ await expect(identify()).resolves.toBeUndefined();+ });++ test('HTTP 500 returns undefined without throwing', async () => {+ stubFetch(() => ({ status: 500, body: {} }));+ await expect(identify()).resolves.toBeUndefined();+ });++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });+});++type FreeAgentOAuthValue = Parameters<+ NonNullable<(typeof freeAgentAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/free-agent/vitest.config.ts b/packages/pieces/community/free-agent/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/free-agent/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/github/package.json b/packages/pieces/community/github/package.jsonindex cd069a48475..427ebda5426 100644--- a/packages/pieces/community/github/package.json+++ b/packages/pieces/community/github/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-github",- "version": "0.9.1",+ "version": "0.9.2","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/github/src/lib/auth.ts b/packages/pieces/community/github/src/lib/auth.tsindex aff09e0aad3..5633ff19afc 100644--- a/packages/pieces/community/github/src/lib/auth.ts+++ b/packages/pieces/community/github/src/lib/auth.ts@@ -12,6 +12,23 @@ export const githubOAuth2Auth = PieceAuth.OAuth2({authUrl: 'https://github.com/login/oauth/authorize',tokenUrl: 'https://github.com/login/oauth/access_token',scope: ['admin:repo_hook', 'admin:org', 'repo', 'gist'],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<GithubUser>({+ method: HttpMethod.GET,+ url: 'https://api.github.com/user',+ headers: {+ Authorization: `Bearer ${auth.access_token}`,+ Accept: 'application/vnd.github+json',+ 'X-GitHub-Api-Version': '2022-11-28',+ },+ timeout: 5000,+ });+ return response.body?.email || response.body?.login || undefined;+ } catch {+ return undefined;+ }+ },});export const githubAppAuth = PieceAuth.CustomAuth({@@ -122,3 +139,5 @@ async function tryExchangeJwt({};}}++type GithubUser = { email?: string | null; login?: string };diff --git a/packages/pieces/community/github/test/connection-identifier.test.ts b/packages/pieces/community/github/test/connection-identifier.test.tsnew file mode 100644index 00000000000..37cca31cb7f--- /dev/null+++ b/packages/pieces/community/github/test/connection-identifier.test.ts@@ -0,0 +1,155 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ githubAppAuth,+ githubOAuth2Auth,+ githubPatAuth,+} from '../src/lib/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<GithubOAuthValue> = {}): GithubOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identify(auth: GithubOAuthValue = oauth()) {+ const hook = githubOAuth2Auth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('githubOAuth2Auth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('github getConnectionIdentifier', () => {+ test('happy path: GET /user returns the public email', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { login: 'octocat', email: '[email protected]', name: 'The Octocat' },+ }));+ expect(await identify()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.github.com/user');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ expect(seen[0].headers.get('accept')).toBe('application/vnd.github+json');+ expect(seen[0].headers.get('x-github-api-version')).toBe('2022-11-28');+ });++ test('null public email falls back to login', async () => {+ stubFetch(() => ({+ status: 200,+ body: { login: 'octocat', email: null, name: 'The Octocat' },+ }));+ expect(await identify()).toBe('octocat');+ });++ test('empty public email falls back to login', async () => {+ stubFetch(() => ({ status: 200, body: { login: 'octocat', email: '' } }));+ expect(await identify()).toBe('octocat');+ });++ test('missing email field falls back to login', async () => {+ stubFetch(() => ({ status: 200, body: { login: 'octocat' } }));+ expect(await identify()).toBe('octocat');+ });++ test('no email and empty login returns undefined, never empty string', async () => {+ stubFetch(() => ({ status: 200, body: { login: '', email: null } }));+ expect(await identify()).toBeUndefined();+ });++ test('empty body returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: {} }));+ expect(await identify()).toBeUndefined();+ });++ test('null body returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: null }));+ expect(await identify()).toBeUndefined();+ });++ test('does not call /user/emails (piece lacks user:email scope)', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { login: 'octocat', email: null },+ }));+ await identify();+ expect(seen.map((s) => s.url)).toEqual(['https://api.github.com/user']);+ });++ test.each([401, 403, 500])(+ 'HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { message: 'nope' } }));+ await expect(identify()).resolves.toBeUndefined();+ }+ );++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });++ test('only the OAuth2 auth carries the hook', () => {+ expect(typeof githubOAuth2Auth.getConnectionIdentifier).toBe('function');+ expect(githubPatAuth.getConnectionIdentifier).toBeUndefined();+ expect(githubAppAuth.getConnectionIdentifier).toBeUndefined();+ });+});++type GithubOAuthValue = Parameters<+ NonNullable<(typeof githubOAuth2Auth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/gmail/package.json b/packages/pieces/community/gmail/package.jsonindex 8e4ee206c59..a200c59e2e7 100644--- a/packages/pieces/community/gmail/package.json+++ b/packages/pieces/community/gmail/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-gmail",- "version": "0.17.2",+ "version": "0.17.3","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/gmail/src/lib/auth.ts b/packages/pieces/community/gmail/src/lib/auth.tsindex 465ad54e8c1..911ba1c6b83 100644--- a/packages/pieces/community/gmail/src/lib/auth.ts+++ b/packages/pieces/community/gmail/src/lib/auth.ts@@ -4,6 +4,7 @@ import {Property,} from '@activepieces/pieces-framework';import { AppConnectionType } from '@activepieces/pieces-framework';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';import { oauth2 as googleOauth2 } from '@googleapis/oauth2';import { JWT, OAuth2Client } from 'google-auth-library';@@ -23,6 +24,19 @@ export const gmailAuth = [tokenUrl: 'https://oauth2.googleapis.com/token',required: true,scope: gmailScopes,+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<GmailProfile>({+ method: HttpMethod.GET,+ url: 'https://gmail.googleapis.com/gmail/v1/users/me/profile',+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ return response.body?.emailAddress || undefined;+ } catch {+ return undefined;+ }+ },}),PieceAuth.CustomAuth({displayName: 'Service Account (Advanced)',@@ -115,3 +129,5 @@ export async function getUserEmail(.data.email ?? undefined);}++type GmailProfile = { emailAddress?: string };diff --git a/packages/pieces/community/gmail/test/connection-identifier.test.ts b/packages/pieces/community/gmail/test/connection-identifier.test.tsnew file mode 100644index 00000000000..c83427010fe--- /dev/null+++ b/packages/pieces/community/gmail/test/connection-identifier.test.ts@@ -0,0 +1,158 @@+import { PropertyType } from '@activepieces/pieces-framework';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { gmailAuth } from '../src/lib/auth';++vi.mock('@googleapis/oauth2', () => ({+ oauth2: () => {+ throw new Error('googleapis must not be used by the hook');+ },+}));+vi.mock('google-auth-library', () => ({+ JWT: class {},+ OAuth2Client: class {},+}));++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++const oauthAuth = gmailAuth[0];++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<GmailOAuthValue> = {}): GmailOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identify(auth: GmailOAuthValue = oauth()) {+ if (oauthAuth.type !== PropertyType.OAUTH2) {+ throw new Error('gmailAuth[0] is not the OAuth2 auth');+ }+ const hook = oauthAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('gmailAuth[0] has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('gmail getConnectionIdentifier', () => {+ test('happy path: Gmail users.getProfile returns emailAddress', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ emailAddress: '[email protected]',+ messagesTotal: 10,+ threadsTotal: 5,+ historyId: '1',+ },+ }));+ expect(await identify()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe(+ 'https://gmail.googleapis.com/gmail/v1/users/me/profile'+ );+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('does not hit the userinfo endpoint (needs the email scope old connections may lack)', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { emailAddress: '[email protected]' },+ }));+ await identify();+ expect(seen.some((s) => s.url.includes('userinfo'))).toBe(false);+ });++ test('empty emailAddress returns undefined, never empty string', async () => {+ stubFetch(() => ({ status: 200, body: { emailAddress: '' } }));+ expect(await identify()).toBeUndefined();+ });++ test('missing emailAddress returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: { messagesTotal: 1 } }));+ expect(await identify()).toBeUndefined();+ });++ test('null body returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: null }));+ expect(await identify()).toBeUndefined();+ });++ test.each([401, 403, 500])(+ 'HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { error: { code: status } } }));+ await expect(identify()).resolves.toBeUndefined();+ }+ );++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });++ test('only the OAuth2 auth carries the hook; the service-account auth does not', () => {+ expect(typeof oauthAuth.getConnectionIdentifier).toBe('function');+ expect(gmailAuth[1].getConnectionIdentifier).toBeUndefined();+ });+});++type GmailOAuthValue = Parameters<+ NonNullable<+ Extract<+ (typeof gmailAuth)[number],+ { type: PropertyType.OAUTH2 }+ >['getConnectionIdentifier']+ >+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/instagram-business/package.json b/packages/pieces/community/instagram-business/package.jsonindex a8e7abf33d2..bcb28573e8e 100644--- a/packages/pieces/community/instagram-business/package.json+++ b/packages/pieces/community/instagram-business/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-instagram-business",- "version": "1.0.0",+ "version": "1.0.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/instagram-business/src/lib/common/index.ts b/packages/pieces/community/instagram-business/src/lib/common/index.tsindex b49fce87b05..22204c181cd 100644--- a/packages/pieces/community/instagram-business/src/lib/common/index.ts+++ b/packages/pieces/community/instagram-business/src/lib/common/index.ts@@ -41,6 +41,20 @@ const instagramBusinessAuth = PieceAuth.OAuth2({'pages_manage_metadata','pages_messaging',],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<{ name?: string }>({+ method: HttpMethod.GET,+ url: `${INSTAGRAM_API_BASE}/me`,+ queryParams: { fields: 'name' },+ headers: { authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ return response.body.name || undefined;+ } catch {+ return undefined;+ }+ },});async function graphRequest<T>({diff --git a/packages/pieces/community/instagram-business/test/connection-identifier.test.ts b/packages/pieces/community/instagram-business/test/connection-identifier.test.tsnew file mode 100644index 00000000000..6ad7bff5a7e--- /dev/null+++ b/packages/pieces/community/instagram-business/test/connection-identifier.test.ts@@ -0,0 +1,142 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { instagramCommon } from '../src/lib/common';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<InstagramOAuthValue> = {}): InstagramOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identify(auth: InstagramOAuthValue = oauth()) {+ const hook = instagramCommon.authentication.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error(+ 'instagramCommon.authentication has no getConnectionIdentifier hook'+ );+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('instagram-business getConnectionIdentifier', () => {+ test('happy path: name from GET graph.facebook.com/v23.0/me?fields=name with the bearer token', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { name: 'Pat Lee', id: '1234567890' },+ }));+ expect(await identify()).toBe('Pat Lee');+ expect(seen).toHaveLength(1);+ const url = new URL(seen[0].url);+ expect(`${url.origin}${url.pathname}`).toBe(+ 'https://graph.facebook.com/v23.0/me'+ );+ expect(url.searchParams.get('fields')).toBe('name');+ expect([...url.searchParams.keys()]).toEqual(['fields']);+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('access token is not leaked into the query string', async () => {+ const seen = stubFetch(() => ({ status: 200, body: { name: 'Pat Lee' } }));+ await identify();+ expect(seen[0].url).not.toContain('TKN');+ });++ test('missing name returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: { id: '1234567890' } }));+ expect(await identify()).toBeUndefined();+ });++ test('empty name returns undefined, never empty string', async () => {+ stubFetch(() => ({ status: 200, body: { id: '1234567890', name: '' } }));+ expect(await identify()).toBeUndefined();+ });++ test('Graph OAuthException 400 returns undefined without throwing', async () => {+ stubFetch(() => ({+ status: 400,+ body: {+ error: {+ message: 'Error validating access token',+ type: 'OAuthException',+ code: 190,+ },+ },+ }));+ await expect(identify()).resolves.toBeUndefined();+ });++ test('HTTP 401 returns undefined without throwing', async () => {+ stubFetch(() => ({ status: 401, body: { error: { code: 190 } } }));+ await expect(identify()).resolves.toBeUndefined();+ });++ test('HTTP 500 returns undefined without throwing', async () => {+ stubFetch(() => ({ status: 500, body: { error: { code: 2 } } }));+ await expect(identify()).resolves.toBeUndefined();+ });++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });+});++type InstagramOAuthValue = Parameters<+ NonNullable<+ (typeof instagramCommon)['authentication']['getConnectionIdentifier']+ >+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/instagram-business/vitest.config.ts b/packages/pieces/community/instagram-business/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/instagram-business/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/intercom/package.json b/packages/pieces/community/intercom/package.jsonindex cf942c8b75b..0c607dcbfc0 100644--- a/packages/pieces/community/intercom/package.json+++ b/packages/pieces/community/intercom/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-intercom",- "version": "0.8.1",+ "version": "0.8.2","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {@@ -13,11 +13,13 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/intercom/src/lib/auth.ts b/packages/pieces/community/intercom/src/lib/auth.tsindex f6550c4e9b9..d868b1dd6da 100644--- a/packages/pieces/community/intercom/src/lib/auth.ts+++ b/packages/pieces/community/intercom/src/lib/auth.ts@@ -35,6 +35,8 @@ export const intercomOAuth2Auth = PieceAuth.OAuth2({props: {region:regionProp},+ getConnectionIdentifier: async ({ auth }) =>+ fetchAdminLabel({ token: auth.access_token, region: auth.props?.['region'] }),});@@ -64,6 +66,32 @@ const intercomCustomAuth = PieceAuth.CustomAuth({return { valid: false, error: (e as Error).message };}},+ getConnectionIdentifier: async ({ auth }) =>+ fetchAdminLabel({ token: auth.accessToken, region: auth.region }),});export const intercomAuth = [intercomOAuth2Auth, intercomCustomAuth];++async function fetchAdminLabel({+ token,+ region,+}: {+ token: string;+ region: unknown;+}): Promise<string | undefined> {+ const host = typeof region === 'string' && region.length > 0 ? region : 'intercom';+ try {+ const response = await httpClient.sendRequest<IntercomAdmin>({+ method: HttpMethod.GET,+ url: `https://api.${host}.io/me`,+ headers: { Authorization: `Bearer ${token}` },+ timeout: 5000,+ });+ const admin = response.body;+ return admin.email || admin.name || admin.app?.name || undefined;+ } catch {+ return undefined;+ }+}++type IntercomAdmin = { email?: string; name?: string; app?: { name?: string } };diff --git a/packages/pieces/community/intercom/test/connection-identifier.test.ts b/packages/pieces/community/intercom/test/connection-identifier.test.tsnew file mode 100644index 00000000000..878161312fe--- /dev/null+++ b/packages/pieces/community/intercom/test/connection-identifier.test.ts@@ -0,0 +1,205 @@+import { PropertyType } from '@activepieces/pieces-framework';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { intercomAuth, intercomOAuth2Auth } from '../src/lib/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++const admin = {+ type: 'admin',+ id: '1',+ email: '[email protected]',+ name: 'Pat Lee',+ email_verified: true,+ app: { type: 'app', id_code: 'abc', name: 'Acme Support' },+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<IntercomOAuthValue> = {}): IntercomOAuthValue {+ return {+ access_token: 'TKN',+ data: {},+ props: { region: 'intercom' },+ ...extra,+ };+}++function withoutKey<T extends object>({+ value,+ key,+}: {+ value: T;+ key: keyof T;+}): T {+ const copy = { ...value };+ Reflect.deleteProperty(copy, key);+ return copy;+}++async function identifyWithOAuth(auth: IntercomOAuthValue = oauth()) {+ const hook = intercomOAuth2Auth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('intercomOAuth2Auth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++async function identifyWithCustom(region: string) {+ const variant = intercomAuth[1];+ if (variant.type !== PropertyType.CUSTOM_AUTH) {+ throw new Error('intercomAuth[1] is not the access token auth');+ }+ const hook = variant.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('intercomAuth[1] has no getConnectionIdentifier hook');+ }+ return hook({ auth: { accessToken: 'ACC', region }, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('intercom getConnectionIdentifier', () => {+ test('variant order is [OAUTH2, CUSTOM_AUTH] and both declare the hook', () => {+ expect(intercomAuth[0]).toBe(intercomOAuth2Auth);+ expect(typeof intercomOAuth2Auth.getConnectionIdentifier).toBe('function');+ expect(intercomAuth[1].type).toBe(PropertyType.CUSTOM_AUTH);+ expect(typeof intercomAuth[1].getConnectionIdentifier).toBe('function');+ });++ test('oauth US: admin email from api.intercom.io/me with the bearer token', async () => {+ const seen = stubFetch(() => ({ status: 200, body: admin }));+ expect(await identifyWithOAuth()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.intercom.io/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('oauth EU: region prop builds api.eu.intercom.io', async () => {+ const seen = stubFetch(() => ({ status: 200, body: admin }));+ expect(+ await identifyWithOAuth(oauth({ props: { region: 'eu.intercom' } }))+ ).toBe('[email protected]');+ expect(seen[0].url).toBe('https://api.eu.intercom.io/me');+ });++ test.each([+ [+ 'props without region',+ oauth({+ props: withoutKey({ value: { region: 'unused' }, key: 'region' }),+ }),+ ],+ ['no props at all', oauth({ props: undefined })],+ ])('oauth %s defaults to the US host', async (_name, auth) => {+ const seen = stubFetch(() => ({ status: 200, body: admin }));+ expect(await identifyWithOAuth(auth)).toBe('[email protected]');+ expect(seen[0].url).toBe('https://api.intercom.io/me');+ });++ test('custom auth AU: region builds api.au.intercom.io with the access token', async () => {+ const seen = stubFetch(() => ({ status: 200, body: admin }));+ expect(await identifyWithCustom('au.intercom')).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.au.intercom.io/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer ACC');+ });++ test('empty email falls back to admin name', async () => {+ stubFetch(() => ({ status: 200, body: { ...admin, email: '' } }));+ expect(await identifyWithOAuth()).toBe('Pat Lee');+ });++ test('empty email and name fall back to app name', async () => {+ stubFetch(() => ({ status: 200, body: { ...admin, email: '', name: '' } }));+ expect(await identifyWithCustom('intercom')).toBe('Acme Support');+ });++ test('no usable fields returns undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { type: 'admin', id: '1', email: '', app: {} },+ }));+ expect(await identifyWithOAuth()).toBeUndefined();+ });++ test.each([401, 403, 500])(+ 'oauth: HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({+ status,+ body: { type: 'error.list', errors: [{ code: 'unauthorized' }] },+ }));+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ }+ );++ test.each([401, 500])(+ 'custom auth: HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { type: 'error.list' } }));+ await expect(identifyWithCustom('eu.intercom')).resolves.toBeUndefined();+ }+ );++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identifyWithOAuth()).resolves.toBeUndefined();+ await expect(identifyWithCustom('intercom')).resolves.toBeUndefined();+ });+});++type IntercomOAuthValue = Parameters<+ NonNullable<(typeof intercomOAuth2Auth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/intercom/vitest.config.ts b/packages/pieces/community/intercom/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/intercom/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/klaviyo/package.json b/packages/pieces/community/klaviyo/package.jsonindex 8331fa69155..08bab5b26dc 100644--- a/packages/pieces/community/klaviyo/package.json+++ b/packages/pieces/community/klaviyo/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-klaviyo",- "version": "0.2.0",+ "version": "0.2.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -16,6 +17,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/klaviyo/src/lib/common/auth.ts b/packages/pieces/community/klaviyo/src/lib/common/auth.tsindex db641f62323..5a184d23e3a 100644--- a/packages/pieces/community/klaviyo/src/lib/common/auth.ts+++ b/packages/pieces/community/klaviyo/src/lib/common/auth.ts@@ -31,6 +31,8 @@ export const klaviyoAuth = [};}},+ getConnectionIdentifier: async ({ auth }) =>+ fetchAccountLabel(`Klaviyo-API-Key ${auth}`),}),PieceAuth.OAuth2({description: `@@ -65,6 +67,8 @@ To connect via OAuth2, follow the [Klaviyo OAuth setup guide](https://developerspkce: true,pkceMethod: 'S256',authorizationMethod: OAuth2AuthorizationMethod.HEADER,+ getConnectionIdentifier: async ({ auth }) =>+ fetchAccountLabel(`Bearer ${auth.access_token}`),}),];@@ -78,3 +82,37 @@ export function getAuthorizationHeader(auth: KlaviyoAuthValue): string {}return `Bearer ${auth.access_token}`;}++async function fetchAccountLabel(+ authorization: string+): Promise<string | undefined> {+ try {+ const response = await httpClient.sendRequest<KlaviyoAccounts>({+ method: HttpMethod.GET,+ url: 'https://a.klaviyo.com/api/accounts',+ headers: {+ Authorization: authorization,+ revision: '2025-04-15',+ accept: 'application/vnd.api+json',+ },+ timeout: 5000,+ });+ const contact = response.body.data?.[0]?.attributes?.contact_information;+ return (+ contact?.organization_name || contact?.default_sender_email || undefined+ );+ } catch {+ return undefined;+ }+}++type KlaviyoAccounts = {+ data?: {+ attributes?: {+ contact_information?: {+ organization_name?: string;+ default_sender_email?: string;+ };+ };+ }[];+};diff --git a/packages/pieces/community/klaviyo/test/connection-identifier.test.ts b/packages/pieces/community/klaviyo/test/connection-identifier.test.tsnew file mode 100644index 00000000000..98af64c0b17--- /dev/null+++ b/packages/pieces/community/klaviyo/test/connection-identifier.test.ts@@ -0,0 +1,227 @@+import { PropertyType } from '@activepieces/pieces-framework';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { klaviyoAuth } from '../src/lib/common/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<KlaviyoOAuthValue> = {}): KlaviyoOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++function accounts(contact: KlaviyoContact | undefined) {+ return {+ data: [+ {+ type: 'account',+ id: 'ABC',+ attributes: { test_account: false, contact_information: contact },+ },+ ],+ };+}++async function identifyWithApiKey() {+ const variant = klaviyoAuth[0];+ if (variant.type !== PropertyType.SECRET_TEXT) {+ throw new Error('klaviyoAuth[0] is not the API key auth');+ }+ const hook = variant.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('klaviyoAuth[0] has no getConnectionIdentifier hook');+ }+ return hook({ auth: 'pk_123', server });+}++async function identifyWithOAuth() {+ const variant = klaviyoAuth[1];+ if (variant.type !== PropertyType.OAUTH2) {+ throw new Error('klaviyoAuth[1] is not the OAuth2 auth');+ }+ const hook = variant.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('klaviyoAuth[1] has no getConnectionIdentifier hook');+ }+ return hook({ auth: oauth(), server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('klaviyo getConnectionIdentifier', () => {+ test('variant order is [SECRET_TEXT, OAUTH2] and both declare the hook', () => {+ expect(klaviyoAuth[0].type).toBe(PropertyType.SECRET_TEXT);+ expect(klaviyoAuth[1].type).toBe(PropertyType.OAUTH2);+ expect(typeof klaviyoAuth[0].getConnectionIdentifier).toBe('function');+ expect(typeof klaviyoAuth[1].getConnectionIdentifier).toBe('function');+ });++ test('api key: organization_name from /api/accounts with the Klaviyo-API-Key header and revision', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: accounts({+ organization_name: 'Acme Org',+ default_sender_email: '[email protected]',+ }),+ }));+ expect(await identifyWithApiKey()).toBe('Acme Org');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://a.klaviyo.com/api/accounts');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Klaviyo-API-Key pk_123');+ expect(seen[0].headers.get('revision')).toBe('2025-04-15');+ });++ test('oauth: organization_name from /api/accounts with the bearer token and revision', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: accounts({+ organization_name: 'Acme Org',+ default_sender_email: '[email protected]',+ }),+ }));+ expect(await identifyWithOAuth()).toBe('Acme Org');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://a.klaviyo.com/api/accounts');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ expect(seen[0].headers.get('revision')).toBe('2025-04-15');+ });++ test.each([+ ['api key', identifyWithApiKey],+ ['oauth', identifyWithOAuth],+ ])(+ '%s: empty organization_name falls back to default_sender_email',+ async (_name, identify) => {+ stubFetch(() => ({+ status: 200,+ body: accounts({+ organization_name: '',+ default_sender_email: '[email protected]',+ }),+ }));+ expect(await identify()).toBe('[email protected]');+ }+ );++ test.each([+ ['api key', identifyWithApiKey],+ ['oauth', identifyWithOAuth],+ ])('%s: empty contact fields return undefined', async (_name, identify) => {+ stubFetch(() => ({+ status: 200,+ body: accounts({ organization_name: '', default_sender_email: '' }),+ }));+ expect(await identify()).toBeUndefined();+ });++ test.each([+ ['api key', identifyWithApiKey],+ ['oauth', identifyWithOAuth],+ ])(+ '%s: missing contact_information returns undefined',+ async (_name, identify) => {+ stubFetch(() => ({ status: 200, body: accounts(undefined) }));+ expect(await identify()).toBeUndefined();+ }+ );++ test.each([+ ['api key', identifyWithApiKey],+ ['oauth', identifyWithOAuth],+ ])('%s: empty data array returns undefined', async (_name, identify) => {+ stubFetch(() => ({ status: 200, body: { data: [] } }));+ expect(await identify()).toBeUndefined();+ });++ test.each([+ ['api key', 401, identifyWithApiKey],+ ['api key', 403, identifyWithApiKey],+ ['api key', 500, identifyWithApiKey],+ ['oauth', 401, identifyWithOAuth],+ ['oauth', 403, identifyWithOAuth],+ ['oauth', 500, identifyWithOAuth],+ ])(+ '%s: HTTP %i returns undefined without throwing',+ async (_name, status, identify) => {+ stubFetch(() => ({ status, body: { errors: [{ status }] } }));+ await expect(identify()).resolves.toBeUndefined();+ }+ );++ test.each([+ ['api key', identifyWithApiKey],+ ['oauth', identifyWithOAuth],+ ])(+ '%s: network error returns undefined without throwing',+ async (_name, identify) => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ }+ );+});++type KlaviyoOAuthValue = Parameters<+ NonNullable<+ Extract<+ (typeof klaviyoAuth)[number],+ { type: PropertyType.OAUTH2 }+ >['getConnectionIdentifier']+ >+>[0]['auth'];++type KlaviyoContact = {+ organization_name?: string;+ default_sender_email?: string;+};++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/klaviyo/vitest.config.ts b/packages/pieces/community/klaviyo/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/klaviyo/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/mailchimp/package.json b/packages/pieces/community/mailchimp/package.jsonindex 31535b32078..a53601713d3 100644--- a/packages/pieces/community/mailchimp/package.json+++ b/packages/pieces/community/mailchimp/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-mailchimp",- "version": "0.5.8",+ "version": "0.5.9","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {@@ -13,10 +13,12 @@"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"devDependencies": {"@types/mailchimp__mailchimp_marketing": "3.0.22",- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/mailchimp/src/index.ts b/packages/pieces/community/mailchimp/src/index.tsindex ab3c2312408..3053ff69249 100644--- a/packages/pieces/community/mailchimp/src/index.ts+++ b/packages/pieces/community/mailchimp/src/index.ts@@ -1,4 +1,5 @@import { PieceAuth, createPiece } from '@activepieces/pieces-framework';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';import { addMemberToList } from './lib/actions/add-member-to-list';import { addNoteToSubscriber } from './lib/actions/add-note-to-subscriber';import { removeSubscriberFromTag } from './lib/actions/remove-subscriber-from-tag';@@ -34,6 +35,25 @@ export const mailchimpAuth = PieceAuth.OAuth2({tokenUrl: 'https://login.mailchimp.com/oauth2/token',required: true,scope: [],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<MailchimpMetadata>({+ method: HttpMethod.GET,+ url: 'https://login.mailchimp.com/oauth2/metadata',+ headers: { Authorization: `OAuth ${auth.access_token}` },+ timeout: 5000,+ });+ const metadata = response.body;+ return (+ metadata.login?.email ||+ metadata.login?.login_email ||+ metadata.accountname ||+ undefined+ );+ } catch {+ return undefined;+ }+ },});export const mailchimp = createPiece({@@ -75,3 +95,8 @@ export const mailchimp = createPiece({mailChimpNewSegmentTagSubscriberTrigger,],});++type MailchimpMetadata = {+ accountname?: string;+ login?: { email?: string; login_email?: string };+};diff --git a/packages/pieces/community/mailchimp/test/connection-identifier.test.ts b/packages/pieces/community/mailchimp/test/connection-identifier.test.tsnew file mode 100644index 00000000000..e9c106d6be5--- /dev/null+++ b/packages/pieces/community/mailchimp/test/connection-identifier.test.ts@@ -0,0 +1,140 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { mailchimpAuth } from '../src';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<MailchimpOAuthValue> = {}): MailchimpOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identify(auth: MailchimpOAuthValue = oauth()) {+ const hook = mailchimpAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('mailchimpAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('mailchimp getConnectionIdentifier', () => {+ test('happy path: login.email from oauth2/metadata with the OAuth header', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ dc: 'us6',+ accountname: 'Acme',+ login: { email: '[email protected]', login_email: '[email protected]' },+ },+ }));+ expect(await identify()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://login.mailchimp.com/oauth2/metadata');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('OAuth TKN');+ });++ test('empty login.email falls back to login.login_email', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ accountname: 'Acme',+ login: { email: '', login_email: '[email protected]' },+ },+ }));+ expect(await identify()).toBe('[email protected]');+ });++ test('no login emails falls back to accountname', async () => {+ stubFetch(() => ({+ status: 200,+ body: { accountname: 'Acme Inc', login: { email: '', login_email: '' } },+ }));+ expect(await identify()).toBe('Acme Inc');+ });++ test('missing login object falls back to accountname', async () => {+ stubFetch(() => ({+ status: 200,+ body: { dc: 'us6', accountname: 'Acme Inc' },+ }));+ expect(await identify()).toBe('Acme Inc');+ });++ test('all fields empty or missing returns undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { dc: 'us6', accountname: '', login: {} },+ }));+ expect(await identify()).toBeUndefined();+ });++ test.each([401, 403, 500])(+ 'HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { error: 'nope' } }));+ await expect(identify()).resolves.toBeUndefined();+ }+ );++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });+});++type MailchimpOAuthValue = Parameters<+ NonNullable<(typeof mailchimpAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/mailchimp/vitest.config.ts b/packages/pieces/community/mailchimp/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/mailchimp/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/notion/package.json b/packages/pieces/community/notion/package.jsonindex 8b540f455c4..3b791d60575 100644--- a/packages/pieces/community/notion/package.json+++ b/packages/pieces/community/notion/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-notion",- "version": "0.7.3",+ "version": "0.7.4","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/notion/src/lib/auth.test.ts b/packages/pieces/community/notion/src/lib/auth.test.tsnew file mode 100644index 00000000000..3c9461f1e66--- /dev/null+++ b/packages/pieces/community/notion/src/lib/auth.test.ts@@ -0,0 +1,243 @@+import { PropertyType } from '@activepieces/pieces-framework';+import { afterEach, expect, test, vi } from 'vitest';+import { notionAuth, notionOAuth2Auth } from './auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++const customAuth = notionAuth[1];++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<NotionOAuthValue> = {}): NotionOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function runOAuth(data: Record<string, unknown>) {+ const hook = notionOAuth2Auth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('notionOAuth2Auth has no getConnectionIdentifier hook');+ }+ return hook({ auth: oauth({ data }), server });+}++async function runCustom() {+ if (customAuth.type !== PropertyType.CUSTOM_AUTH) {+ throw new Error('notionAuth[1] is not the custom auth');+ }+ const hook = customAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('notionAuth[1] has no getConnectionIdentifier hook');+ }+ return hook({ auth: { accessToken: 'secret_xyz' }, server });+}++function personOwner({+ person,+ name = 'Pat Lee',+}: {+ person: Record<string, unknown>;+ name?: string | null;+}) {+ return {+ type: 'user',+ user: {+ object: 'user',+ id: 'u1',+ type: 'person',+ name,+ avatar_url: null,+ person,+ },+ };+}++afterEach(() => {+ vi.unstubAllGlobals();+});++test('notion: variant order is [OAUTH2, CUSTOM_AUTH] and both declare the hook', () => {+ expect(notionAuth[0]).toBe(notionOAuth2Auth);+ expect(customAuth.type).toBe('CUSTOM_AUTH');+ expect(typeof customAuth.getConnectionIdentifier).toBe('function');+});++test('notion oauth: owner email from token data, zero network calls', async () => {+ const seen = stubFetch(() => ({ status: 500, body: {} }));+ expect(+ await runOAuth({+ bot_id: 'b1',+ workspace_name: 'Acme HQ',+ owner: personOwner({ person: { email: '[email protected]' } }),+ })+ ).toBe('[email protected]');+ expect(seen).toHaveLength(0);+});++test('notion oauth: no email in token data falls back to workspace_name, zero network calls', async () => {+ const seen = stubFetch(() => ({ status: 500, body: {} }));+ expect(+ await runOAuth({+ workspace_name: 'Acme HQ',+ owner: personOwner({ person: {} }),+ })+ ).toBe('Acme HQ');+ expect(seen).toHaveLength(0);+});++test('notion oauth: empty email and null workspace_name fall back to owner name, zero network calls', async () => {+ const seen = stubFetch(() => ({ status: 500, body: {} }));+ expect(+ await runOAuth({+ workspace_name: null,+ owner: personOwner({ person: { email: '' } }),+ })+ ).toBe('Pat Lee');+ expect(seen).toHaveLength(0);+});++test('notion oauth: token data without identity calls /v1/users/me with Notion-Version and reads the bot owner email', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ object: 'user',+ type: 'bot',+ bot: {+ owner: personOwner({ person: { email: '[email protected]' } }),+ workspace_name: 'Acme HQ',+ },+ },+ }));+ expect(+ await runOAuth({+ workspace_name: '',+ owner: { type: 'workspace', workspace: true },+ })+ ).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.notion.com/v1/users/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ expect(seen[0].headers.get('notion-version')).toBe('2022-02-22');+});++test('notion oauth: empty token data falls back to bot workspace_name', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ type: 'bot',+ bot: {+ owner: { type: 'workspace', workspace: true },+ workspace_name: 'Acme HQ',+ },+ },+ }));+ expect(await runOAuth({})).toBe('Acme HQ');+});++test('notion oauth: empty token data and empty bot returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: { type: 'bot', bot: {} } }));+ expect(await runOAuth({})).toBeUndefined();+});++test.each([401, 403, 500])(+ 'notion oauth: empty token data and HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { object: 'error' } }));+ await expect(runOAuth({})).resolves.toBeUndefined();+ }+);++test('notion oauth: empty token data and network error returns undefined without throwing', async () => {+ stubFetch(() => {+ throw new TypeError('fetch failed');+ });+ await expect(runOAuth({})).resolves.toBeUndefined();+});++test('notion custom auth: internal integration bot returns workspace_name', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ object: 'user',+ type: 'bot',+ name: 'My integration',+ bot: {+ owner: { type: 'workspace', workspace: true },+ workspace_name: 'Acme HQ',+ },+ },+ }));+ expect(await runCustom()).toBe('Acme HQ');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.notion.com/v1/users/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer secret_xyz');+ expect(seen[0].headers.get('notion-version')).toBe('2022-02-22');+});++test('notion custom auth: missing bot returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: { object: 'user', type: 'bot' } }));+ expect(await runCustom()).toBeUndefined();+});++test.each([401, 500])(+ 'notion custom auth: HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { object: 'error' } }));+ await expect(runCustom()).resolves.toBeUndefined();+ }+);++test('notion custom auth: network error returns undefined without throwing', async () => {+ stubFetch(() => {+ throw new TypeError('fetch failed');+ });+ await expect(runCustom()).resolves.toBeUndefined();+});++type NotionOAuthValue = Parameters<+ NonNullable<(typeof notionOAuth2Auth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/notion/src/lib/auth.ts b/packages/pieces/community/notion/src/lib/auth.tsindex 965ba0d3abe..2d1a312279a 100644--- a/packages/pieces/community/notion/src/lib/auth.ts+++ b/packages/pieces/community/notion/src/lib/auth.ts@@ -17,6 +17,8 @@ export const notionOAuth2Auth = PieceAuth.OAuth2({},authorizationMethod: OAuth2AuthorizationMethod.HEADER,required: true,+ getConnectionIdentifier: async ({ auth }) =>+ labelOf(auth.data) || fetchBotLabel(auth.access_token),});const notionCustomAuth = PieceAuth.CustomAuth({@@ -49,6 +51,38 @@ const notionCustomAuth = PieceAuth.CustomAuth({return { valid: false, error: (e as Error).message };}},+ getConnectionIdentifier: async ({ auth }) => fetchBotLabel(auth.accessToken),});export const notionAuth = [notionOAuth2Auth, notionCustomAuth];++function labelOf(grant: NotionGrant | undefined): string | undefined {+ return (+ grant?.owner?.user?.person?.email ||+ grant?.workspace_name ||+ grant?.owner?.user?.name ||+ undefined+ );+}++async function fetchBotLabel(token: string): Promise<string | undefined> {+ try {+ const response = await httpClient.sendRequest<{ bot?: NotionGrant }>({+ method: HttpMethod.GET,+ url: 'https://api.notion.com/v1/users/me',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Notion-Version': '2022-02-22',+ },+ timeout: 5000,+ });+ return labelOf(response.body.bot);+ } catch {+ return undefined;+ }+}++type NotionGrant = {+ workspace_name?: string | null;+ owner?: { user?: { name?: string | null; person?: { email?: string } } };+};diff --git a/packages/pieces/community/pinterest/package.json b/packages/pieces/community/pinterest/package.jsonindex ab04db64da0..7d6fc848e6a 100644--- a/packages/pieces/community/pinterest/package.json+++ b/packages/pieces/community/pinterest/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-pinterest",- "version": "0.2.0",+ "version": "0.2.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -16,6 +17,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/pinterest/src/lib/common/auth.ts b/packages/pieces/community/pinterest/src/lib/common/auth.tsindex ceea24dd8d8..d16a38ebf40 100644--- a/packages/pieces/community/pinterest/src/lib/common/auth.ts+++ b/packages/pieces/community/pinterest/src/lib/common/auth.ts@@ -2,6 +2,7 @@ import {PieceAuth,OAuth2AuthorizationMethod,} from '@activepieces/pieces-framework';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';const authGuide = `Connect a Pinterest **business** account.@@ -27,4 +28,20 @@ export const pinterestAuth = PieceAuth.OAuth2({'user_accounts:read',],authorizationMethod: OAuth2AuthorizationMethod.HEADER,+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<PinterestAccount>({+ method: HttpMethod.GET,+ url: 'https://api.pinterest.com/v5/user_account',+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ const account = response.body;+ return account.username || account.business_name || undefined;+ } catch {+ return undefined;+ }+ },});++type PinterestAccount = { username?: string; business_name?: string | null };diff --git a/packages/pieces/community/pinterest/test/connection-identifier.test.ts b/packages/pieces/community/pinterest/test/connection-identifier.test.tsnew file mode 100644index 00000000000..7191e225f1c--- /dev/null+++ b/packages/pieces/community/pinterest/test/connection-identifier.test.ts@@ -0,0 +1,140 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { pinterestAuth } from '../src/lib/common/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<PinterestOAuthValue> = {}): PinterestOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identify(auth: PinterestOAuthValue = oauth()) {+ const hook = pinterestAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('pinterestAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('pinterest getConnectionIdentifier', () => {+ test('happy path: username from v5/user_account with the bearer token', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ username: 'acme_shop',+ business_name: 'Acme Shop',+ account_type: 'BUSINESS',+ },+ }));+ expect(await identify()).toBe('acme_shop');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.pinterest.com/v5/user_account');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('token data carries no identity, so the call is always made', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { username: 'acme_shop' },+ }));+ expect(+ await identify(+ oauth({+ data: {+ access_token: 'TKN',+ scope: 'user_accounts:read',+ token_type: 'bearer',+ },+ })+ )+ ).toBe('acme_shop');+ expect(seen).toHaveLength(1);+ });++ test('empty username falls back to business_name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { username: '', business_name: 'Acme Shop' },+ }));+ expect(await identify()).toBe('Acme Shop');+ });++ test('missing username and null business_name returns undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { business_name: null, account_type: 'PINNER' },+ }));+ expect(await identify()).toBeUndefined();+ });++ test.each([401, 403, 500])(+ 'HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { code: 2, message: 'nope' } }));+ await expect(identify()).resolves.toBeUndefined();+ }+ );++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });+});++type PinterestOAuthValue = Parameters<+ NonNullable<(typeof pinterestAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/pinterest/vitest.config.ts b/packages/pieces/community/pinterest/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/pinterest/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/pipedrive/package.json b/packages/pieces/community/pipedrive/package.jsonindex deb995e0262..6e887c5c275 100644--- a/packages/pieces/community/pipedrive/package.json+++ b/packages/pieces/community/pipedrive/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-pipedrive",- "version": "0.10.0",+ "version": "0.10.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -18,6 +19,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/pipedrive/src/lib/auth.ts b/packages/pieces/community/pipedrive/src/lib/auth.tsindex 4267c7966dc..f33a01a8498 100644--- a/packages/pieces/community/pipedrive/src/lib/auth.ts+++ b/packages/pieces/community/pipedrive/src/lib/auth.ts@@ -1,4 +1,5 @@import { PieceAuth } from '@activepieces/pieces-framework';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';export const pipedriveAuth = PieceAuth.OAuth2({description: '',@@ -16,4 +17,26 @@ export const pipedriveAuth = PieceAuth.OAuth2({'products:full','webhooks:full'],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<{ data?: PipedriveUser }>({+ method: HttpMethod.GET,+ url: `${apiDomainOf(auth.data['api_domain'])}/api/v1/users/me`,+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ const user = response.body?.data;+ return user?.email || user?.name || undefined;+ } catch {+ return undefined;+ }+ },});++function apiDomainOf(apiDomain: unknown): string {+ return typeof apiDomain === 'string' && apiDomain.length > 0+ ? apiDomain+ : 'https://api.pipedrive.com';+}++type PipedriveUser = { email?: string; name?: string };diff --git a/packages/pieces/community/pipedrive/test/connection-identifier.test.ts b/packages/pieces/community/pipedrive/test/connection-identifier.test.tsnew file mode 100644index 00000000000..40bc07e15be--- /dev/null+++ b/packages/pieces/community/pipedrive/test/connection-identifier.test.ts@@ -0,0 +1,165 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { pipedriveAuth } from '../src/lib/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<PipedriveOAuthValue> = {}): PipedriveOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++function withDomain(+ data: Record<string, unknown> = { api_domain: 'https://acme.pipedrive.com' }+): PipedriveOAuthValue {+ return oauth({ data });+}++async function identify(auth: PipedriveOAuthValue = withDomain()) {+ const hook = pipedriveAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('pipedriveAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('pipedrive getConnectionIdentifier', () => {+ test('happy path: GET {api_domain}/api/v1/users/me returns data.email', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ success: true,+ data: {+ id: 1,+ name: 'Pat Doe',+ email: '[email protected]',+ company_name: 'Acme',+ },+ },+ }));+ expect(await identify()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://acme.pipedrive.com/api/v1/users/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('empty email falls back to name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { success: true, data: { name: 'Pat Doe', email: '' } },+ }));+ expect(await identify()).toBe('Pat Doe');+ });++ test('missing email falls back to name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { success: true, data: { name: 'Pat Doe' } },+ }));+ expect(await identify()).toBe('Pat Doe');+ });++ test('empty email and name returns undefined, never empty string', async () => {+ stubFetch(() => ({+ status: 200,+ body: { success: true, data: { name: '', email: '' } },+ }));+ expect(await identify()).toBeUndefined();+ });++ test('missing data envelope returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: { success: true } }));+ expect(await identify()).toBeUndefined();+ });++ test('null body returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: null }));+ expect(await identify()).toBeUndefined();+ });++ test.each([+ { label: 'missing', data: {} },+ { label: 'empty', data: { api_domain: '' } },+ { label: 'non-string', data: { api_domain: 42 } },+ ])(+ '$label api_domain falls back to https://api.pipedrive.com like the custom API call action',+ async ({ data }) => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { success: true, data: { email: '[email protected]' } },+ }));+ expect(await identify(withDomain(data))).toBe('[email protected]');+ expect(seen[0].url).toBe('https://api.pipedrive.com/api/v1/users/me');+ }+ );++ test.each([401, 403, 500])(+ 'HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { success: false, error: 'nope' } }));+ await expect(identify()).resolves.toBeUndefined();+ }+ );++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });+});++type PipedriveOAuthValue = Parameters<+ NonNullable<(typeof pipedriveAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/pipedrive/vitest.config.ts b/packages/pieces/community/pipedrive/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/pipedrive/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/podio/package.json b/packages/pieces/community/podio/package.jsonindex 24d464004d9..30a1ece2abd 100644--- a/packages/pieces/community/podio/package.json+++ b/packages/pieces/community/podio/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-podio",- "version": "0.2.1",+ "version": "0.2.2","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -11,11 +11,13 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "^2.3.0"+ "tslib": "^2.3.0",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/podio/src/lib/auth.ts b/packages/pieces/community/podio/src/lib/auth.tsindex 66d56f20c37..4c7a86ce13e 100644--- a/packages/pieces/community/podio/src/lib/auth.ts+++ b/packages/pieces/community/podio/src/lib/auth.ts@@ -1,6 +1,6 @@import { PieceAuth } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { podioApiCall } from './common/client';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { PODIO_API_URL, podioApiCall } from './common/client';import { validateAuthData } from './common/auth';export const podioAuth = PieceAuth.OAuth2({@@ -9,6 +9,19 @@ export const podioAuth = PieceAuth.OAuth2({tokenUrl: 'https://podio.com/oauth/token',required: true,scope: ['global:read', 'global:write'],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<PodioUserStatus>({+ method: HttpMethod.GET,+ url: `${PODIO_API_URL}/user/status`,+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ return response.body?.user?.mail || response.body?.profile?.name || undefined;+ } catch {+ return undefined;+ }+ },validate: async ({ auth }) => {try {const validation = validateAuthData(auth);@@ -43,3 +56,5 @@ export const podioAuth = PieceAuth.OAuth2({}},});++type PodioUserStatus = { user?: { mail?: string }; profile?: { name?: string } };diff --git a/packages/pieces/community/podio/test/connection-identifier.test.ts b/packages/pieces/community/podio/test/connection-identifier.test.tsnew file mode 100644index 00000000000..bb6ddc3e20c--- /dev/null+++ b/packages/pieces/community/podio/test/connection-identifier.test.ts@@ -0,0 +1,137 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { podioAuth } from '../src/lib/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<PodioOAuthValue> = {}): PodioOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identify(+ auth: PodioOAuthValue = oauth({ data: { ref: { type: 'user', id: 99 } } })+) {+ const hook = podioAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('podioAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('podio getConnectionIdentifier', () => {+ test('happy path: GET /user/status returns user.mail', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ user: { user_id: 99, mail: '[email protected]' },+ profile: { profile_id: 7, name: 'Pat Doe', mail: ['[email protected]'] },+ },+ }));+ expect(await identify()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.podio.com/user/status');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('empty user.mail falls back to profile.name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { user: { user_id: 99, mail: '' }, profile: { name: 'Pat Doe' } },+ }));+ expect(await identify()).toBe('Pat Doe');+ });++ test('missing user object falls back to profile.name', async () => {+ stubFetch(() => ({ status: 200, body: { profile: { name: 'Pat Doe' } } }));+ expect(await identify()).toBe('Pat Doe');+ });++ test('empty mail and empty name returns undefined, never empty string', async () => {+ stubFetch(() => ({+ status: 200,+ body: { user: { mail: '' }, profile: { name: '' } },+ }));+ expect(await identify()).toBeUndefined();+ });++ test('missing user and profile returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: { inbox_new: 0 } }));+ expect(await identify()).toBeUndefined();+ });++ test('null body returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: null }));+ expect(await identify()).toBeUndefined();+ });++ test.each([401, 403, 420, 500])(+ 'HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { error: 'nope' } }));+ await expect(identify()).resolves.toBeUndefined();+ }+ );++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });+});++type PodioOAuthValue = Parameters<+ NonNullable<(typeof podioAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/podio/vitest.config.ts b/packages/pieces/community/podio/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/podio/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/ringcentral/package.json b/packages/pieces/community/ringcentral/package.jsonindex eeb233118f9..cbb1e69e1a9 100644--- a/packages/pieces/community/ringcentral/package.json+++ b/packages/pieces/community/ringcentral/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-ringcentral",- "version": "0.1.0",+ "version": "0.1.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/ringcentral/src/lib/common/auth.test.ts b/packages/pieces/community/ringcentral/src/lib/common/auth.test.tsnew file mode 100644index 00000000000..88edfa04835--- /dev/null+++ b/packages/pieces/community/ringcentral/src/lib/common/auth.test.ts@@ -0,0 +1,189 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { ringcentralAuth } from './auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++const EXT_PATH = '/restapi/v1.0/account/~/extension/~';++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(+ extra: Partial<RingcentralOAuthValue> = {}+): RingcentralOAuthValue {+ return { access_token: 'TKN', data: {}, ...extra };+}++async function run(extra: Partial<RingcentralOAuthValue> = {}) {+ const hook = ringcentralAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('ringcentralAuth has no getConnectionIdentifier hook');+ }+ return hook({+ auth: oauth({+ props: { environment: 'platform.ringcentral.com' },+ ...extra,+ }),+ server,+ });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('ringcentral getConnectionIdentifier', () => {+ test('happy path (production): contact.email from GET extension/~ with the bearer token', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ id: 101,+ name: 'Pat Lee',+ extensionNumber: '101',+ contact: { firstName: 'Pat', lastName: 'Lee', email: '[email protected]' },+ },+ }));+ expect(await run()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe(`https://platform.ringcentral.com${EXT_PATH}`);+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('sandbox environment prop -> devtest host', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { contact: { email: '[email protected]' } },+ }));+ expect(+ await run({ props: { environment: 'platform.devtest.ringcentral.com' } })+ ).toBe('[email protected]');+ expect(seen[0].url).toBe(+ `https://platform.devtest.ringcentral.com${EXT_PATH}`+ );+ });++ test('no environment prop -> production host (same default as the piece client)', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { contact: { email: '[email protected]' } },+ }));+ expect(await run({ props: undefined })).toBe('[email protected]');+ expect(seen[0].url).toBe(`https://platform.ringcentral.com${EXT_PATH}`);+ });++ test('token data carries no identity on RingCentral: the call is still made', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { contact: { email: '[email protected]' } },+ }));+ expect(+ await run({+ data: {+ owner_id: '101',+ endpoint_id: 'e1',+ refresh_token_expires_in: 604800,+ },+ })+ ).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ });++ test('contact.email empty -> extension name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { name: 'Pat Lee', contact: { email: '' } },+ }));+ expect(await run()).toBe('Pat Lee');+ });++ test('no contact object -> extension name', async () => {+ stubFetch(() => ({ status: 200, body: { name: 'Pat Lee' } }));+ expect(await run()).toBe('Pat Lee');+ });++ test('email and name both empty -> undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { name: '', contact: { email: '' } },+ }));+ expect(await run()).toBeUndefined();+ });++ test('401 -> undefined, no throw', async () => {+ stubFetch(() => ({+ status: 401,+ body: { errorCode: 'TokenInvalid', message: 'Token not found' },+ }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('403 app lacks ReadAccounts -> undefined, no throw', async () => {+ stubFetch(() => ({+ status: 403,+ body: {+ errorCode: 'CMN-401',+ message: '[ReadAccounts] permission required',+ },+ }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('500 -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 500, body: {} }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('network error -> undefined, no throw', async () => {+ stubFetch(() => {+ throw new TypeError('fetch failed');+ });+ await expect(run()).resolves.toBeUndefined();+ });+});++type RingcentralOAuthValue = Parameters<+ NonNullable<(typeof ringcentralAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/ringcentral/src/lib/common/auth.ts b/packages/pieces/community/ringcentral/src/lib/common/auth.tsindex 192dcd5ef32..12a8ccfb999 100644--- a/packages/pieces/community/ringcentral/src/lib/common/auth.ts+++ b/packages/pieces/community/ringcentral/src/lib/common/auth.ts@@ -3,6 +3,8 @@ import {PieceAuth,Property,} from '@activepieces/pieces-framework';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { ringcentralCommon } from './client';export const ringcentralAuth = PieceAuth.OAuth2({description:@@ -32,4 +34,22 @@ export const ringcentralAuth = PieceAuth.OAuth2({scope: [],// The platform's default prompt=consent sends RingCentral's login to SSO-only (API_ERROR_208).prompt: 'omit',+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<RingCentralExtension>({+ method: HttpMethod.GET,+ url: `${ringcentralCommon.getServerUrl(auth)}/restapi/v1.0/account/~/extension/~`,+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ return response.body.contact?.email || response.body.name || undefined;+ } catch {+ return undefined;+ }+ },});++type RingCentralExtension = {+ name?: string;+ contact?: { email?: string };+};diff --git a/packages/pieces/community/savvycal/package.json b/packages/pieces/community/savvycal/package.jsonindex 2b4465f46b1..b91513a586a 100644--- a/packages/pieces/community/savvycal/package.json+++ b/packages/pieces/community/savvycal/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-savvycal",- "version": "0.2.0",+ "version": "0.2.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/savvycal/src/lib/auth.ts b/packages/pieces/community/savvycal/src/lib/auth.tsindex ea8a2629075..ff21c43462b 100644--- a/packages/pieces/community/savvycal/src/lib/auth.ts+++ b/packages/pieces/community/savvycal/src/lib/auth.ts@@ -10,6 +10,7 @@ export const savvyCalAuth = [tokenUrl: 'https://savvycal.com/oauth/token',required: true,scope: [],+ getConnectionIdentifier: async ({ auth }) => fetchUserLabel(auth.access_token),}),PieceAuth.CustomAuth({displayName: 'Personal Access Token',@@ -44,6 +45,7 @@ export const savvyCalAuth = [return { valid: false, error: 'Invalid token. Please check your Personal Access Token and try again.' };}},+ getConnectionIdentifier: async ({ auth }) => fetchUserLabel(auth.token),}),];@@ -55,3 +57,26 @@ export function getToken(auth: SavvyCalAuthValue): string {}return auth.access_token;}++async function fetchUserLabel(token: string): Promise<string | undefined> {+ try {+ const response = await httpClient.sendRequest<SavvyCalUser>({+ method: HttpMethod.GET,+ url: `${SAVVYCAL_BASE_URL}/me`,+ headers: { Authorization: `Bearer ${token}` },+ timeout: 5000,+ });+ const user = response.body;+ const fullName = [user.first_name, user.last_name].filter(Boolean).join(' ');+ return user.email || user.display_name || fullName || undefined;+ } catch {+ return undefined;+ }+}++type SavvyCalUser = {+ email?: string;+ display_name?: string;+ first_name?: string;+ last_name?: string;+};diff --git a/packages/pieces/community/savvycal/test/connection-identifier.test.ts b/packages/pieces/community/savvycal/test/connection-identifier.test.tsnew file mode 100644index 00000000000..3d1e14c67dd--- /dev/null+++ b/packages/pieces/community/savvycal/test/connection-identifier.test.ts@@ -0,0 +1,188 @@+import { PropertyType } from '@activepieces/pieces-framework';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { savvyCalAuth } from '../src/lib/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++const oauth2Auth = savvyCalAuth[0];+const patAuth = savvyCalAuth[1];++const user = {+ id: 'user_01',+ email: '[email protected]',+ display_name: 'Pat Lee',+ first_name: 'Pat',+ last_name: 'Lee',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<SavvyCalOAuthValue> = {}): SavvyCalOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function runOAuth() {+ if (oauth2Auth.type !== PropertyType.OAUTH2) {+ throw new Error('savvyCalAuth[0] is not the OAuth2 auth');+ }+ const hook = oauth2Auth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('savvyCalAuth[0] has no getConnectionIdentifier hook');+ }+ return hook({ auth: oauth(), server });+}++async function runPat() {+ if (patAuth.type !== PropertyType.CUSTOM_AUTH) {+ throw new Error('savvyCalAuth[1] is not the personal access token auth');+ }+ const hook = patAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('savvyCalAuth[1] has no getConnectionIdentifier hook');+ }+ return hook({ auth: { token: 'pt_secret_ABC' }, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('savvycal getConnectionIdentifier', () => {+ test('both auths declare the hook', () => {+ expect(typeof oauth2Auth.getConnectionIdentifier).toBe('function');+ expect(typeof patAuth.getConnectionIdentifier).toBe('function');+ });++ test('OAuth2 happy path: email from GET /v1/me with the access token', async () => {+ const seen = stubFetch(() => ({ status: 200, body: user }));+ expect(await runOAuth()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.savvycal.com/v1/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('Personal Access Token happy path: same endpoint with the PAT as bearer', async () => {+ const seen = stubFetch(() => ({ status: 200, body: user }));+ expect(await runPat()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.savvycal.com/v1/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer pt_secret_ABC');+ });++ test('empty email -> display_name', async () => {+ stubFetch(() => ({ status: 200, body: { ...user, email: '' } }));+ expect(await runOAuth()).toBe('Pat Lee');+ });++ test('no email, no display_name -> "first last"', async () => {+ stubFetch(() => ({+ status: 200,+ body: { id: 'user_01', first_name: 'Pat', last_name: 'Lee' },+ }));+ expect(await runPat()).toBe('Pat Lee');+ });++ test('only first_name -> first_name without a trailing space', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ id: 'user_01',+ email: '',+ display_name: '',+ first_name: 'Pat',+ last_name: '',+ },+ }));+ expect(await runOAuth()).toBe('Pat');+ });++ test('nothing usable -> undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ id: 'user_01',+ email: '',+ display_name: '',+ first_name: '',+ last_name: '',+ },+ }));+ expect(await runOAuth()).toBeUndefined();+ });++ test('401 -> undefined, no throw (both auths)', async () => {+ stubFetch(() => ({ status: 401, body: { error: 'unauthorized' } }));+ await expect(runOAuth()).resolves.toBeUndefined();+ await expect(runPat()).resolves.toBeUndefined();+ });++ test('500 -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 500, body: { error: 'boom' } }));+ await expect(runOAuth()).resolves.toBeUndefined();+ });++ test('network error -> undefined, no throw (both auths)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(runOAuth()).resolves.toBeUndefined();+ await expect(runPat()).resolves.toBeUndefined();+ });+});++type SavvyCalOAuthValue = Parameters<+ NonNullable<+ Extract<+ (typeof savvyCalAuth)[number],+ { type: PropertyType.OAUTH2 }+ >['getConnectionIdentifier']+ >+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/savvycal/vitest.config.ts b/packages/pieces/community/savvycal/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/savvycal/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/sign-now/package.json b/packages/pieces/community/sign-now/package.jsonindex d4f72c46899..4d3c39ca350 100644--- a/packages/pieces/community/sign-now/package.json+++ b/packages/pieces/community/sign-now/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-sign-now",- "version": "0.0.6",+ "version": "0.0.7","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -12,11 +12,13 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/sign-now/src/lib/common/auth.ts b/packages/pieces/community/sign-now/src/lib/common/auth.tsindex f3f69151827..65d57462a35 100644--- a/packages/pieces/community/sign-now/src/lib/common/auth.ts+++ b/packages/pieces/community/sign-now/src/lib/common/auth.ts@@ -13,6 +13,7 @@ export const signNowOAuth2Auth = PieceAuth.OAuth2({// SignNow does not accept access_type or prompt params — suppress both with empty stringsextra: { access_type: '' },prompt: 'omit',+ getConnectionIdentifier: async ({ auth }) => fetchSignNowUserLabel(auth.access_token),});export const signNowApiKeyAuth = PieceAuth.CustomAuth({@@ -48,6 +49,7 @@ export const signNowApiKeyAuth = PieceAuth.CustomAuth({return { valid: false, error: (e as Error).message };}},+ getConnectionIdentifier: async ({ auth }) => fetchSignNowUserLabel(auth.apiKey),});export const signNowAuth = [signNowOAuth2Auth, signNowApiKeyAuth];@@ -63,3 +65,29 @@ export function getSignNowBearerToken(auth: SignNowAuthValue): string {}return (auth as Extract<SignNowAuthValue, { type: AppConnectionType.CUSTOM_AUTH }>).props.apiKey.trim();}++async function fetchSignNowUserLabel(token: string): Promise<string | undefined> {+ try {+ const response = await httpClient.sendRequest<SignNowUser>({+ method: HttpMethod.GET,+ url: 'https://api.signnow.com/user',+ headers: {+ Authorization: `Bearer ${token.trim()}`,+ Accept: 'application/json',+ },+ timeout: 5000,+ });+ const user = response.body;+ const fullName = [user.first_name, user.last_name].filter(Boolean).join(' ');+ return user.primary_email || user.emails?.find(Boolean) || fullName || undefined;+ } catch {+ return undefined;+ }+}++type SignNowUser = {+ primary_email?: string;+ emails?: string[];+ first_name?: string;+ last_name?: string;+};diff --git a/packages/pieces/community/sign-now/test/connection-identifier.test.ts b/packages/pieces/community/sign-now/test/connection-identifier.test.tsnew file mode 100644index 00000000000..ce3c951c90c--- /dev/null+++ b/packages/pieces/community/sign-now/test/connection-identifier.test.ts@@ -0,0 +1,217 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ signNowApiKeyAuth,+ signNowAuth,+ signNowOAuth2Auth,+} from '../src/lib/common/auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++const USER_URL = 'https://api.signnow.com/user';++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<SignNowOAuthValue> = {}): SignNowOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++function apiKeyValueWithoutKey(): SignNowApiKeyValue {+ const auth: SignNowApiKeyValue = { apiKey: '' };+ Reflect.deleteProperty(auth, 'apiKey');+ return auth;+}++async function runOAuth(extra: Partial<SignNowOAuthValue> = {}) {+ const hook = signNowOAuth2Auth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('signNowOAuth2Auth has no getConnectionIdentifier hook');+ }+ return hook({ auth: oauth(extra), server });+}++async function runApiKey(auth: SignNowApiKeyValue) {+ const hook = signNowApiKeyAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('signNowApiKeyAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('sign-now OAuth2 getConnectionIdentifier', () => {+ test('both auths in the exported array carry the hook', () => {+ expect(+ signNowAuth.every(+ (auth) => typeof auth.getConnectionIdentifier === 'function'+ )+ ).toBe(true);+ });++ test('happy path: primary_email from GET /user with the bearer token', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ id: 'u1',+ first_name: 'Pat',+ last_name: 'Lee',+ emails: ['[email protected]'],+ primary_email: '[email protected]',+ },+ }));+ expect(await runOAuth()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe(USER_URL);+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ expect(seen[0].headers.get('accept')).toBe('application/json');+ });++ test('token data carries no identity on SignNow: the call is still made', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { primary_email: '[email protected]' },+ }));+ expect(await runOAuth({ data: { last_login: 0, id: 'u1' } })).toBe(+ );+ expect(seen).toHaveLength(1);+ });++ test('primary_email empty -> first non-empty entry of emails[]', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ primary_email: '',+ emails: ['', '[email protected]'],+ first_name: 'Pat',+ },+ }));+ expect(await runOAuth()).toBe('[email protected]');+ });++ test('no emails -> "first last"', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ primary_email: '',+ emails: [],+ first_name: 'Pat',+ last_name: 'Lee',+ },+ }));+ expect(await runOAuth()).toBe('Pat Lee');+ });++ test('only first_name -> first_name', async () => {+ stubFetch(() => ({ status: 200, body: { first_name: 'Pat' } }));+ expect(await runOAuth()).toBe('Pat');+ });++ test('everything empty -> undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { primary_email: '', emails: [''], first_name: '', last_name: '' },+ }));+ expect(await runOAuth()).toBeUndefined();+ });++ test('401 -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 401, body: { error: 'invalid_token' } }));+ await expect(runOAuth()).resolves.toBeUndefined();+ });++ test('500 -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 500, body: {} }));+ await expect(runOAuth()).resolves.toBeUndefined();+ });++ test('network error -> undefined, no throw', async () => {+ stubFetch(() => {+ throw new TypeError('fetch failed');+ });+ await expect(runOAuth()).resolves.toBeUndefined();+ });+});++describe('sign-now API key getConnectionIdentifier', () => {+ test('GET /user with the trimmed API key as bearer -> primary_email', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { primary_email: '[email protected]' },+ }));+ expect(await runApiKey({ apiKey: ' KEY123 ' })).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe(USER_URL);+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer KEY123');+ });++ test('401 -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 401, body: {} }));+ await expect(runApiKey({ apiKey: 'KEY123' })).resolves.toBeUndefined();+ });++ test('missing apiKey -> undefined, no throw', async () => {+ stubFetch(() => ({+ status: 200,+ body: { primary_email: '[email protected]' },+ }));+ const auth = apiKeyValueWithoutKey();+ expect(auth).toEqual({});+ await expect(runApiKey(auth)).resolves.toBeUndefined();+ });+});++type SignNowOAuthValue = Parameters<+ NonNullable<(typeof signNowOAuth2Auth)['getConnectionIdentifier']>+>[0]['auth'];++type SignNowApiKeyValue = Parameters<+ NonNullable<(typeof signNowApiKeyAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/sign-now/vitest.config.ts b/packages/pieces/community/sign-now/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/sign-now/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/simplyprint/package.json b/packages/pieces/community/simplyprint/package.jsonindex eed90c28f62..7b5cddba67d 100644--- a/packages/pieces/community/simplyprint/package.json+++ b/packages/pieces/community/simplyprint/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-simplyprint",- "version": "0.6.6",+ "version": "0.6.7","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/simplyprint/src/lib/auth.test.ts b/packages/pieces/community/simplyprint/src/lib/auth.test.tsnew file mode 100644index 00000000000..511a46e702c--- /dev/null+++ b/packages/pieces/community/simplyprint/src/lib/auth.test.ts@@ -0,0 +1,159 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { simplyprintAuth } from './auth';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(+ extra: Partial<SimplyprintOAuthValue> = {}+): SimplyprintOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function run(extra: Partial<SimplyprintOAuthValue> = {}) {+ const hook = simplyprintAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('simplyprintAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth: oauth(extra), server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('simplyprint getConnectionIdentifier', () => {+ test('happy path: user.email from GET /api/0/account/GetUser with the bearer token', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ status: true,+ message: null,+ user: { id: 112, name: 'John Doe', email: '[email protected]' },+ company: { id: 123, name: 'My Company' },+ },+ }));+ expect(await run()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://simplyprint.io/api/0/account/GetUser');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('token data carries no identity on SimplyPrint: the call is still made', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { status: true, user: { email: '[email protected]' } },+ }));+ expect(await run({ data: {} })).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ });++ test('user.email empty -> user.name', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ status: true,+ user: { id: 112, name: 'John Doe', email: '' },+ company: { id: 123, name: 'My Company' },+ },+ }));+ expect(await run()).toBe('John Doe');+ });++ test('no user object -> company.name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { status: true, company: { id: 123, name: 'My Company' } },+ }));+ expect(await run()).toBe('My Company');+ });++ test('all empty -> undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: {+ status: true,+ user: { id: 112, name: '', email: '' },+ company: { id: 123, name: '' },+ },+ }));+ expect(await run()).toBeUndefined();+ });++ test('status:false body (HTTP 200) -> undefined', async () => {+ stubFetch(() => ({+ status: 200,+ body: { status: false, message: 'Invalid token' },+ }));+ expect(await run()).toBeUndefined();+ });++ test('401 -> undefined, no throw', async () => {+ stubFetch(() => ({+ status: 401,+ body: { status: false, message: 'Unauthorized' },+ }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('500 -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 500, body: {} }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('network error -> undefined, no throw', async () => {+ stubFetch(() => {+ throw new TypeError('fetch failed');+ });+ await expect(run()).resolves.toBeUndefined();+ });+});++type SimplyprintOAuthValue = Parameters<+ NonNullable<(typeof simplyprintAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/simplyprint/src/lib/auth.ts b/packages/pieces/community/simplyprint/src/lib/auth.tsindex 8b6758c9204..70ae0969219 100644--- a/packages/pieces/community/simplyprint/src/lib/auth.ts+++ b/packages/pieces/community/simplyprint/src/lib/auth.ts@@ -37,6 +37,23 @@ export const simplyprintAuth = PieceAuth.OAuth2({'webhooks.read','webhooks.write',],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<{+ user?: { name?: string; email?: string };+ company?: { name?: string };+ }>({+ method: HttpMethod.GET,+ url: `${BASE_URL.api}/0/account/GetUser`,+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ const { user, company } = response.body;+ return user?.email || user?.name || company?.name || undefined;+ } catch {+ return undefined;+ }+ },});// Bounded LRU. Without the cap, every OAuth-token rotation leaves an orphandiff --git a/packages/pieces/community/spotify/package.json b/packages/pieces/community/spotify/package.jsonindex 7fb07d43446..0bdc304b595 100644--- a/packages/pieces/community/spotify/package.json+++ b/packages/pieces/community/spotify/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-spotify",- "version": "0.6.0",+ "version": "0.6.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/spotify/src/lib/common/index.ts b/packages/pieces/community/spotify/src/lib/common/index.tsindex 2fcc0ffe2ed..ed230c0c364 100644--- a/packages/pieces/community/spotify/src/lib/common/index.ts+++ b/packages/pieces/community/spotify/src/lib/common/index.ts@@ -1,10 +1,15 @@-import { getAccessTokenOrThrow } from '@activepieces/pieces-common';+import {+ getAccessTokenOrThrow,+ httpClient,+ HttpMethod,+} from '@activepieces/pieces-common';import {OAuth2PropertyValue,PieceAuth,Property,} from '@activepieces/pieces-framework';import { SpotifyWebApi } from './client';+import { User } from './models/user';const markdownDescription = `To obtain a client ID and client secret for Spotify, follow these simple steps:@@ -38,6 +43,20 @@ export const spotifyCommon = {'user-follow-read','user-follow-modify',],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<User>({+ method: HttpMethod.GET,+ url: 'https://api.spotify.com/v1/me',+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ const user = response.body;+ return user.email || user.display_name || user.id || undefined;+ } catch {+ return undefined;+ }+ },}),device_id: (required = true) =>Property.Dropdown({diff --git a/packages/pieces/community/spotify/test/connection-identifier.test.ts b/packages/pieces/community/spotify/test/connection-identifier.test.tsnew file mode 100644index 00000000000..1bd3509ca80--- /dev/null+++ b/packages/pieces/community/spotify/test/connection-identifier.test.ts@@ -0,0 +1,160 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { spotifyCommon } from '../src/lib/common';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<SpotifyOAuthValue> = {}): SpotifyOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function run(auth: SpotifyOAuthValue = oauth()) {+ const hook = spotifyCommon.authentication.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error(+ 'spotifyCommon.authentication has no getConnectionIdentifier hook'+ );+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('spotify getConnectionIdentifier', () => {+ test('happy path: email from GET /v1/me with the bearer token (only when user-read-email was granted)', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { id: 'wizzler', email: '[email protected]', display_name: 'Pat Lee' },+ }));+ expect(await run()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.spotify.com/v1/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('current scopes: no email field -> display_name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { id: 'wizzler', display_name: 'Pat Lee', type: 'user' },+ }));+ expect(await run()).toBe('Pat Lee');+ });++ test('empty email -> display_name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { id: 'wizzler', email: '', display_name: 'Pat Lee' },+ }));+ expect(await run()).toBe('Pat Lee');+ });++ test('null display_name -> id', async () => {+ stubFetch(() => ({+ status: 200,+ body: { id: 'wizzler', display_name: null },+ }));+ expect(await run()).toBe('wizzler');+ });++ test('empty display_name -> id', async () => {+ stubFetch(() => ({+ status: 200,+ body: { id: 'wizzler', display_name: '' },+ }));+ expect(await run()).toBe('wizzler');+ });++ test('nothing usable -> undefined', async () => {+ stubFetch(() => ({ status: 200, body: { id: '', display_name: null } }));+ expect(await run()).toBeUndefined();+ });++ test('401 -> undefined, no throw', async () => {+ stubFetch(() => ({+ status: 401,+ body: { error: { status: 401, message: 'Invalid access token' } },+ }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('403 (app in development mode, user not allowlisted) -> undefined, no throw', async () => {+ stubFetch(() => ({+ status: 403,+ body: {+ error: {+ status: 403,+ message: 'User not registered in the Developer Dashboard',+ },+ },+ }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('500 -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 500, body: { error: { status: 500 } } }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('network error -> undefined, no throw', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(run()).resolves.toBeUndefined();+ });+});++type SpotifyOAuthValue = Parameters<+ NonNullable<+ (typeof spotifyCommon)['authentication']['getConnectionIdentifier']+ >+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/spotify/vitest.config.ts b/packages/pieces/community/spotify/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/spotify/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/todoist/package.json b/packages/pieces/community/todoist/package.jsonindex b22c1bd928f..e3c939b93e4 100644--- a/packages/pieces/community/todoist/package.json+++ b/packages/pieces/community/todoist/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-todoist",- "version": "0.5.0",+ "version": "0.5.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -16,6 +17,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/todoist/src/index.ts b/packages/pieces/community/todoist/src/index.tsindex 71907d268e6..d0b9b51d593 100644--- a/packages/pieces/community/todoist/src/index.ts+++ b/packages/pieces/community/todoist/src/index.ts@@ -1,4 +1,4 @@-import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createCustomApiCallAction, httpClient, HttpMethod } from '@activepieces/pieces-common';import { OAuth2PropertyValue, PieceAuth, createPiece } from '@activepieces/pieces-framework';import { PieceCategory } from '@activepieces/pieces-framework';import { todoistCreateTaskAction } from './lib/actions/create-task-action';@@ -54,6 +54,19 @@ export const todoistAuth = PieceAuth.OAuth2({authUrl: 'https://todoist.com/oauth/authorize',tokenUrl: 'https://todoist.com/oauth/access_token',scope: ['data:read_write'],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<TodoistUser>({+ method: HttpMethod.GET,+ url: 'https://api.todoist.com/api/v1/user',+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ return response.body?.email || response.body?.full_name || undefined;+ } catch {+ return undefined;+ }+ },});export const todoist = createPiece({@@ -121,3 +134,5 @@ export const todoist = createPiece({],triggers: [todoistTaskCompletedTrigger],});++type TodoistUser = { email?: string; full_name?: string };diff --git a/packages/pieces/community/todoist/test/connection-identifier.test.ts b/packages/pieces/community/todoist/test/connection-identifier.test.tsnew file mode 100644index 00000000000..996c06a878c--- /dev/null+++ b/packages/pieces/community/todoist/test/connection-identifier.test.ts@@ -0,0 +1,128 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { todoistAuth } from '../src';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<TodoistOAuthValue> = {}): TodoistOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function identify(auth: TodoistOAuthValue = oauth()) {+ const hook = todoistAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('todoistAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth, server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('todoist getConnectionIdentifier', () => {+ test('happy path: GET /api/v1/user returns email', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: {+ id: '1234567',+ email: '[email protected]',+ full_name: 'Maria Garcia',+ },+ }));+ expect(await identify()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.todoist.com/api/v1/user');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('empty email falls back to full_name', async () => {+ stubFetch(() => ({+ status: 200,+ body: { email: '', full_name: 'Maria Garcia' },+ }));+ expect(await identify()).toBe('Maria Garcia');+ });++ test('missing email falls back to full_name', async () => {+ stubFetch(() => ({ status: 200, body: { full_name: 'Maria Garcia' } }));+ expect(await identify()).toBe('Maria Garcia');+ });++ test('empty email and empty full_name returns undefined, never empty string', async () => {+ stubFetch(() => ({ status: 200, body: { email: '', full_name: '' } }));+ expect(await identify()).toBeUndefined();+ });++ test('null body returns undefined', async () => {+ stubFetch(() => ({ status: 200, body: null }));+ expect(await identify()).toBeUndefined();+ });++ test.each([401, 403, 500])(+ 'HTTP %i returns undefined without throwing',+ async (status) => {+ stubFetch(() => ({ status, body: { error: 'nope' } }));+ await expect(identify()).resolves.toBeUndefined();+ }+ );++ test('network error returns undefined without throwing', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(identify()).resolves.toBeUndefined();+ });+});++type TodoistOAuthValue = Parameters<+ NonNullable<(typeof todoistAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/todoist/vitest.config.ts b/packages/pieces/community/todoist/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/todoist/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})diff --git a/packages/pieces/community/zoom/package.json b/packages/pieces/community/zoom/package.jsonindex 4a96226610b..f1905b39a84 100644--- a/packages/pieces/community/zoom/package.json+++ b/packages/pieces/community/zoom/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-zoom",- "version": "0.8.0",+ "version": "0.8.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/zoom/src/i18n/translation.json b/packages/pieces/community/zoom/src/i18n/translation.jsonindex 822c453f694..8bc01c5b58b 100644--- a/packages/pieces/community/zoom/src/i18n/translation.json+++ b/packages/pieces/community/zoom/src/i18n/translation.json@@ -1,6 +1,6 @@{"Video conferencing, web conferencing, webinars, screen sharing": "Video conferencing, web conferencing, webinars, screen sharing",- "\n 1. Go to [marketplace.zoom.us](https://marketplace.zoom.us/) and log in to your account.\n 2. In the upper-right corner, click **Develop** then **Build App**.\n 3. Select **General App**.\n 4. Copy the Client ID and Client Secret.Add Redirect URL and press continue.\n 5. Go to **Scopes** from left side bar and add **meeting:write:meeting**, **meeting:read:meeting**, **meeting:read:list_meetings**, **meeting:update:meeting**, and **meeting:write:registrant** as scopes.": "\n 1. Go to [marketplace.zoom.us](https://marketplace.zoom.us/) and log in to your account.\n 2. In the upper-right corner, click **Develop** then **Build App**.\n 3. Select **General App**.\n 4. Copy the Client ID and Client Secret.Add Redirect URL and press continue.\n 5. Go to **Scopes** from left side bar and add **meeting:write:meeting**, **meeting:read:meeting**, **meeting:read:list_meetings**, **meeting:update:meeting**, and **meeting:write:registrant** as scopes.",+ "\n 1. Go to [marketplace.zoom.us](https://marketplace.zoom.us/) and log in to your account.\n 2. In the upper-right corner, click **Develop** then **Build App**.\n 3. Select **General App**.\n 4. Copy the Client ID and Client Secret.Add Redirect URL and press continue.\n 5. Go to **Scopes** from left side bar and add **meeting:write:meeting**, **meeting:read:meeting**, **meeting:read:list_meetings**, **meeting:update:meeting**, **meeting:write:registrant**, and **user:read:user** as scopes.": "\n 1. Go to [marketplace.zoom.us](https://marketplace.zoom.us/) and log in to your account.\n 2. In the upper-right corner, click **Develop** then **Build App**.\n 3. Select **General App**.\n 4. Copy the Client ID and Client Secret.Add Redirect URL and press continue.\n 5. Go to **Scopes** from left side bar and add **meeting:write:meeting**, **meeting:read:meeting**, **meeting:read:list_meetings**, **meeting:update:meeting**, **meeting:write:registrant**, and **user:read:user** as scopes.","Create Zoom Meeting": "Create Zoom Meeting","Create Zoom Meeting Registrant": "Create Zoom Meeting Registrant","Find Zoom Meeting": "Find Zoom Meeting",@@ -53,9 +53,9 @@"Query Parameters": "Query Parameters","Body Type": "Body Type","Body": "Body",- "Response is Binary ?": "Response is Binary ?",- "No Error on Failure": "No Error on Failure",- "Timeout (in seconds)": "Timeout (in seconds)",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout","Follow redirects": "Follow redirects","The meeting's topic": "The meeting's topic","Meeting start date-time": "Meeting start date-time",@@ -93,7 +93,11 @@"Whether to mute participants upon entry.": "Whether to mute participants upon entry.","Whether to enable waiting room.": "Whether to enable waiting room.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.","Local": "Local","Cloud": "Cloud","None": "None",@@ -123,8 +127,5 @@"PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE",- "HEAD": "HEAD",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw"+ "HEAD": "HEAD"}\ No newline at end of filediff --git a/packages/pieces/community/zoom/src/index.ts b/packages/pieces/community/zoom/src/index.tsindex 13235b81198..68a42d25606 100644--- a/packages/pieces/community/zoom/src/index.ts+++ b/packages/pieces/community/zoom/src/index.ts@@ -1,4 +1,4 @@-import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createCustomApiCallAction, httpClient, HttpMethod } from '@activepieces/pieces-common';import {OAuth2PropertyValue,PieceAuth,@@ -16,12 +16,25 @@ export const zoomAuth = PieceAuth.OAuth2({2. In the upper-right corner, click **Develop** then **Build App**.3. Select **General App**.4. Copy the Client ID and Client Secret.Add Redirect URL and press continue.- 5. Go to **Scopes** from left side bar and add **meeting:write:meeting**, **meeting:read:meeting**, **meeting:read:list_meetings**, **meeting:update:meeting**, and **meeting:write:registrant** as scopes.`,+ 5. Go to **Scopes** from left side bar and add **meeting:write:meeting**, **meeting:read:meeting**, **meeting:read:list_meetings**, **meeting:update:meeting**, **meeting:write:registrant**, and **user:read:user** as scopes.`,authUrl: 'https://zoom.us/oauth/authorize',tokenUrl: 'https://zoom.us/oauth/token',required: true,// scope: ['meeting:write:admin', 'meeting:write'],scope: [],+ getConnectionIdentifier: async ({ auth }) => {+ try {+ const response = await httpClient.sendRequest<{ email?: string; display_name?: string }>({+ method: HttpMethod.GET,+ url: 'https://api.zoom.us/v2/users/me',+ headers: { Authorization: `Bearer ${auth.access_token}` },+ timeout: 5000,+ });+ return response.body.email || response.body.display_name || undefined;+ } catch {+ return undefined;+ }+ },});export const zoom = createPiece({diff --git a/packages/pieces/community/zoom/test/connection-identifier.test.ts b/packages/pieces/community/zoom/test/connection-identifier.test.tsnew file mode 100644index 00000000000..d5acef5b4eb--- /dev/null+++ b/packages/pieces/community/zoom/test/connection-identifier.test.ts@@ -0,0 +1,160 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { zoomAuth } from '../src';++const server = {+ apiUrl: 'http://localhost:3000/api/',+ publicUrl: 'http://localhost:4200/',+};++function stubFetch(respond: (request: FetchRequest) => FakeResponse): Seen[] {+ const seen: Seen[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : 'GET')+ ).toUpperCase();+ const headers = new Headers(+ init?.headers ?? (input instanceof Request ? input.headers : undefined)+ );+ const body = typeof init?.body === 'string' ? init.body : null;+ seen.push({+ url,+ method,+ auth: headers.get('authorization'),+ headers,+ body,+ });+ const r = respond({ url, method });+ return new Response(JSON.stringify(r.body), {+ status: r.status,+ headers: { 'content-type': 'application/json' },+ });+ })+ );+ return seen;+}++function oauth(extra: Partial<ZoomOAuthValue> = {}): ZoomOAuthValue {+ return { access_token: 'TKN', data: {}, props: {}, ...extra };+}++async function run(extra: Partial<ZoomOAuthValue> = {}) {+ const hook = zoomAuth.getConnectionIdentifier;+ if (hook === undefined) {+ throw new Error('zoomAuth has no getConnectionIdentifier hook');+ }+ return hook({ auth: oauth(extra), server });+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('zoom getConnectionIdentifier', () => {+ test('happy path: email from GET /v2/users/me with the bearer token', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { id: 'u1', email: '[email protected]', display_name: 'Pat Lee' },+ }));+ expect(await run()).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ expect(seen[0].url).toBe('https://api.zoom.us/v2/users/me');+ expect(seen[0].method).toBe('GET');+ expect(seen[0].auth).toBe('Bearer TKN');+ });++ test('falls back to display_name when email is missing', async () => {+ stubFetch(() => ({+ status: 200,+ body: { id: 'u1', display_name: 'Pat Lee' },+ }));+ expect(await run()).toBe('Pat Lee');+ });++ test('falls back to display_name when email is an empty string', async () => {+ stubFetch(() => ({+ status: 200,+ body: { id: 'u1', email: '', display_name: 'Pat Lee' },+ }));+ expect(await run()).toBe('Pat Lee');+ });++ test('returns undefined when email and display_name are both empty', async () => {+ stubFetch(() => ({+ status: 200,+ body: { id: 'u1', email: '', display_name: '' },+ }));+ expect(await run()).toBeUndefined();+ });++ test('token data is ignored: the call is still made (Zoom puts no identity in the token response)', async () => {+ const seen = stubFetch(() => ({+ status: 200,+ body: { email: '[email protected]' },+ }));+ expect(+ await run({+ data: { scope: 'meeting:read:meeting', api_url: 'https://api.zoom.us' },+ })+ ).toBe('[email protected]');+ expect(seen).toHaveLength(1);+ });++ test('400 missing-scope response -> undefined, no throw', async () => {+ stubFetch(() => ({+ status: 400,+ body: {+ code: 4711,+ message:+ 'Invalid access token, does not contain scopes:[user:read:user]',+ },+ }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('401 -> undefined, no throw', async () => {+ stubFetch(() => ({+ status: 401,+ body: { code: 124, message: 'Invalid access token.' },+ }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('500 -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 500, body: { message: 'boom' } }));+ await expect(run()).resolves.toBeUndefined();+ });++ test('network error -> undefined, no throw', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new TypeError('fetch failed');+ })+ );+ await expect(run()).resolves.toBeUndefined();+ });++ test('null body -> undefined, no throw', async () => {+ stubFetch(() => ({ status: 200, body: null }));+ await expect(run()).resolves.toBeUndefined();+ });+});++type ZoomOAuthValue = Parameters<+ NonNullable<(typeof zoomAuth)['getConnectionIdentifier']>+>[0]['auth'];++type FetchRequest = { url: string; method: string };++type FakeResponse = { status: number; body: unknown };++type Seen = {+ url: string;+ method: string;+ auth: string | null;+ headers: Headers;+ body: string | null;+};diff --git a/packages/pieces/community/zoom/vitest.config.ts b/packages/pieces/community/zoom/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/zoom/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})