Skip to content

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

feat(google-workspace): add Google Workspace piece (#16295)

Fabio452170b37f5c
diff --git a/bun.lock b/bun.lock
index 8a6872701c1..d600caedfd7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -855,7 +855,7 @@
},
"packages/pieces/community/assembled": {
"name": "@activepieces/piece-assembled",
- "version": "0.1.9",
+ "version": "0.1.10",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -964,7 +964,7 @@
},
"packages/pieces/community/azure-ad": {
"name": "@activepieces/piece-azure-ad",
- "version": "0.3.3",
+ "version": "0.3.4",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -1050,7 +1050,7 @@
},
"packages/pieces/community/bamboohr": {
"name": "@activepieces/piece-bamboohr",
- "version": "0.3.1",
+ "version": "0.3.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -1263,7 +1263,7 @@
},
"packages/pieces/community/bitly": {
"name": "@activepieces/piece-bitly",
- "version": "0.2.0",
+ "version": "0.2.1",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -1302,7 +1302,7 @@
},
"packages/pieces/community/bluesky": {
"name": "@activepieces/piece-bluesky",
- "version": "0.2.0",
+ "version": "0.2.1",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -1555,7 +1555,7 @@
},
"packages/pieces/community/campaign-monitor": {
"name": "@activepieces/piece-campaign-monitor",
- "version": "0.1.8",
+ "version": "0.1.9",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -2334,7 +2334,7 @@
},
"packages/pieces/community/coralogix": {
"name": "@activepieces/piece-coralogix",
- "version": "0.2.3",
+ "version": "0.2.4",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -2404,7 +2404,7 @@
},
"packages/pieces/community/cursor": {
"name": "@activepieces/piece-cursor",
- "version": "0.1.8",
+ "version": "0.1.9",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -2831,7 +2831,7 @@
},
"packages/pieces/community/dropbox": {
"name": "@activepieces/piece-dropbox",
- "version": "0.10.0",
+ "version": "0.10.1",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -3259,7 +3259,7 @@
},
"packages/pieces/community/fireberry": {
"name": "@activepieces/piece-fireberry",
- "version": "0.1.7",
+ "version": "0.1.8",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -3380,7 +3380,7 @@
},
"packages/pieces/community/flowlu": {
"name": "@activepieces/piece-flowlu",
- "version": "0.2.1",
+ "version": "0.2.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -3817,7 +3817,7 @@
},
"packages/pieces/community/gmail": {
"name": "@activepieces/piece-gmail",
- "version": "0.18.2",
+ "version": "0.18.3",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -3854,7 +3854,7 @@
},
"packages/pieces/community/google-ads": {
"name": "@activepieces/piece-google-ads",
- "version": "0.0.2",
+ "version": "0.0.3",
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
@@ -3880,7 +3880,7 @@
},
"packages/pieces/community/google-calendar": {
"name": "@activepieces/piece-google-calendar",
- "version": "0.13.2",
+ "version": "0.13.3",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -4058,7 +4058,7 @@
},
"packages/pieces/community/google-sheets": {
"name": "@activepieces/piece-google-sheets",
- "version": "0.19.2",
+ "version": "0.19.3",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -4136,6 +4136,18 @@
"@types/mime-types": "2.1.1",
},
},
+ "packages/pieces/community/google-workspace": {
+ "name": "@activepieces/piece-google-workspace",
+ "version": "0.0.1",
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*",
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6",
+ },
+ },
"packages/pieces/community/googlechat": {
"name": "@activepieces/piece-googlechat",
"version": "0.1.8",
@@ -4645,7 +4657,7 @@
},
"packages/pieces/community/insightly": {
"name": "@activepieces/piece-insightly",
- "version": "0.1.7",
+ "version": "0.1.8",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -4658,7 +4670,7 @@
},
"packages/pieces/community/insighto-ai": {
"name": "@activepieces/piece-insighto-ai",
- "version": "0.1.7",
+ "version": "0.1.8",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -4797,7 +4809,7 @@
},
"packages/pieces/community/jira-cloud": {
"name": "@activepieces/piece-jira-cloud",
- "version": "0.6.1",
+ "version": "0.6.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -5616,7 +5628,7 @@
},
"packages/pieces/community/mailgun": {
"name": "@activepieces/piece-mailgun",
- "version": "0.1.1",
+ "version": "0.1.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -6555,7 +6567,7 @@
},
"packages/pieces/community/ntfy": {
"name": "@activepieces/piece-ntfy",
- "version": "0.4.1",
+ "version": "0.4.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -6569,7 +6581,7 @@
},
"packages/pieces/community/nuelink": {
"name": "@activepieces/piece-nuelink",
- "version": "0.2.1",
+ "version": "0.2.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -6597,7 +6609,7 @@
},
"packages/pieces/community/odoo": {
"name": "@activepieces/piece-odoo",
- "version": "0.3.2",
+ "version": "0.3.3",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -6955,7 +6967,7 @@
},
"packages/pieces/community/pastefy": {
"name": "@activepieces/piece-pastefy",
- "version": "0.3.1",
+ "version": "0.3.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -7163,7 +7175,7 @@
},
"packages/pieces/community/pinterest": {
"name": "@activepieces/piece-pinterest",
- "version": "0.2.3",
+ "version": "0.2.4",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -7178,7 +7190,7 @@
},
"packages/pieces/community/pipedrive": {
"name": "@activepieces/piece-pipedrive",
- "version": "0.10.2",
+ "version": "0.10.3",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -7209,7 +7221,7 @@
},
"packages/pieces/community/plausible": {
"name": "@activepieces/piece-plausible",
- "version": "0.2.0",
+ "version": "0.2.1",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -8010,7 +8022,7 @@
},
"packages/pieces/community/rss": {
"name": "@activepieces/piece-rss",
- "version": "0.7.1",
+ "version": "0.7.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -8305,7 +8317,7 @@
},
"packages/pieces/community/sendpulse": {
"name": "@activepieces/piece-sendpulse",
- "version": "0.2.1",
+ "version": "0.2.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -8455,7 +8467,7 @@
},
"packages/pieces/community/short-io": {
"name": "@activepieces/piece-short-io",
- "version": "0.3.1",
+ "version": "0.3.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -8830,7 +8842,7 @@
},
"packages/pieces/community/spotify": {
"name": "@activepieces/piece-spotify",
- "version": "0.6.1",
+ "version": "0.6.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -9263,7 +9275,7 @@
},
"packages/pieces/community/ticktick": {
"name": "@activepieces/piece-ticktick",
- "version": "0.3.0",
+ "version": "0.3.1",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -9386,7 +9398,7 @@
},
"packages/pieces/community/totalcms": {
"name": "@activepieces/piece-totalcms",
- "version": "1.0.1",
+ "version": "1.0.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -9458,7 +9470,7 @@
},
"packages/pieces/community/twilio": {
"name": "@activepieces/piece-twilio",
- "version": "0.7.1",
+ "version": "0.7.2",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -10203,7 +10215,7 @@
},
"packages/pieces/community/wufoo": {
"name": "@activepieces/piece-wufoo",
- "version": "0.2.0",
+ "version": "0.2.1",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -10283,7 +10295,7 @@
},
"packages/pieces/community/youtube": {
"name": "@activepieces/piece-youtube",
- "version": "0.9.2",
+ "version": "0.9.3",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -10330,7 +10342,7 @@
},
"packages/pieces/community/zendesk-sell": {
"name": "@activepieces/piece-zendesk-sell",
- "version": "0.2.2",
+ "version": "0.2.3",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -12020,6 +12032,8 @@
"@activepieces/piece-google-vertexai": ["@activepieces/piece-google-vertexai@workspace:packages/pieces/community/google-vertexai"],
+ "@activepieces/piece-google-workspace": ["@activepieces/piece-google-workspace@workspace:packages/pieces/community/google-workspace"],
+
"@activepieces/piece-googlechat": ["@activepieces/piece-googlechat@workspace:packages/pieces/community/googlechat"],
"@activepieces/piece-gorgias": ["@activepieces/piece-gorgias@workspace:packages/pieces/community/gorgias"],
diff --git a/packages/pieces/community/google-workspace/.eslintrc.json b/packages/pieces/community/google-workspace/.eslintrc.json
new file mode 100644
index 00000000000..9ee1a0770e8
--- /dev/null
+++ b/packages/pieces/community/google-workspace/.eslintrc.json
@@ -0,0 +1,26 @@
+{
+ "extends": ["../../../../.eslintrc.json"],
+ "ignorePatterns": ["!**/*"],
+ "overrides": [
+ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": {} },
+ {
+ "files": ["*.ts", "*.tsx"],
+ "rules": {
+ "no-restricted-imports": [
+ "error",
+ {
+ "patterns": [
+ "lodash",
+ "lodash/*",
+ "@activepieces/core-*",
+ "@activepieces/server*",
+ "@activepieces/engine",
+ "@activepieces/shared"
+ ]
+ }
+ ]
+ }
+ },
+ { "files": ["*.js", "*.jsx"], "rules": {} }
+ ]
+}
diff --git a/packages/pieces/community/google-workspace/README.md b/packages/pieces/community/google-workspace/README.md
new file mode 100644
index 00000000000..251e9d7771a
--- /dev/null
+++ b/packages/pieces/community/google-workspace/README.md
@@ -0,0 +1,26 @@
+# Google Workspace
+
+Manage Google Workspace users, groups, organizational units and devices, and react to Admin audit events, through the [Admin SDK](https://developers.google.com/workspace/admin) (Directory, Reports and Data Transfer APIs).
+
+## Connection
+
+Both methods use your own Google Cloud project, which must have the **Admin SDK API** enabled.
+
+- **Google Account (OAuth2)**: sign in as a Workspace administrator with an OAuth client from your Google Cloud project. The administrator's role decides what the connection can do.
+- **Service Account (Domain-Wide Delegation)**: provide the service account's `client_email` and `private_key`, plus the e-mail of the administrator it acts as. Authorize the service account's client ID in the Admin console (Security, API controls, Domain-wide delegation) with the scopes listed in the connection dialog. Flows then run without an administrator signing in.
+
+## Actions
+
+- **Add Record**, **Get Record**, **Update Record**, **Delete Record**, **Search Records**: work on users, groups, group members, organizational units, mobile devices, Chrome OS devices and role assignments (each type supports the operations the Directory API allows).
+- **Suspend User**: suspend a user (blocks sign-in, keeps data) or lift the suspension.
+- **Mobile Device Action**: approve, block or wipe a managed mobile device. Wipes are irreversible.
+- **Transfer Data**: move a user's application data (Drive, Calendar, ...) to another user, for example when offboarding.
+- **Custom API Call**: call any Admin SDK endpoint with the connection's credentials.
+
+## Triggers
+
+- **New Admin Activity Event**: an administrator action in the Admin console audit log.
+- **New Application Activity Event**: an audit event of a chosen application (Login, Drive, Calendar, Groups, Mobile, ...).
+- **New User Event**: a user is created, deleted, undeleted, suspended, unsuspended, has their admin status changed, or is otherwise updated.
+
+Triggers use Reports API push notifications, so they fire in real time. Some audit logs (for example Login and Drive) reach Google with a delay of a few minutes.
diff --git a/packages/pieces/community/google-workspace/package.json b/packages/pieces/community/google-workspace/package.json
new file mode 100644
index 00000000000..498c0c6a0d7
--- /dev/null
+++ b/packages/pieces/community/google-workspace/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@activepieces/piece-google-workspace",
+ "version": "0.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'",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*"
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
+ }
+}
diff --git a/packages/pieces/community/google-workspace/src/i18n/translation.json b/packages/pieces/community/google-workspace/src/i18n/translation.json
new file mode 100644
index 00000000000..f560c121d50
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/i18n/translation.json
@@ -0,0 +1,162 @@
+{
+ "Manage Google Workspace users, groups, organizational units and devices, and react to Admin audit events.": "Manage Google Workspace users, groups, organizational units and devices, and react to Admin audit events.",
+ "Add Record": "Add Record",
+ "Update Record": "Update Record",
+ "Delete Record": "Delete Record",
+ "Get Record": "Get Record",
+ "Search Records": "Search Records",
+ "Suspend User": "Suspend User",
+ "Mobile Device Action": "Mobile Device Action",
+ "Transfer Data": "Transfer Data",
+ "Custom API Call": "Custom API Call",
+ "Create a user, group, group member, organizational unit or role assignment": "Create a user, group, group member, organizational unit or role assignment",
+ "Change fields of a user, group, group member, organizational unit or Chrome OS device (PATCH: untouched fields stay as they are)": "Change fields of a user, group, group member, organizational unit or Chrome OS device (PATCH: untouched fields stay as they are)",
+ "Remove a user, group, group member, organizational unit, mobile device or role assignment. Deleted users can be restored for 20 days from the Admin console; everything else is permanent.": "Remove a user, group, group member, organizational unit, mobile device or role assignment. Deleted users can be restored for 20 days from the Admin console; everything else is permanent.",
+ "Return the full record of a user, group, group member, org unit, device or role assignment": "Return the full record of a user, group, group member, org unit, device or role assignment",
+ "List records of one type with the Directory search syntax and pagination": "List records of one type with the Directory search syntax and pagination",
+ "Suspend a directory user (blocks sign-in, keeps data), or lift the suspension": "Suspend a directory user (blocks sign-in, keeps data), or lift the suspension",
+ "Approve, block or wipe a managed mobile device": "Approve, block or wipe a managed mobile device",
+ "Transfer a user's application data (Drive files, Calendar events, ...) to another user, e.g. when offboarding": "Transfer a user's application data (Drive files, Calendar events, ...) to another user, e.g. when offboarding",
+ "Call any Admin SDK endpoint. Paths are relative to https://admin.googleapis.com, e.g. /admin/directory/v1/users?customer=my_customer, /admin/reports/v1/activity/users/all/applications/login, /admin/datatransfer/v1/applications.": "Call any Admin SDK endpoint. Paths are relative to https://admin.googleapis.com, e.g. /admin/directory/v1/users?customer=my_customer, /admin/reports/v1/activity/users/all/applications/login, /admin/datatransfer/v1/applications.",
+ "Resource Type": "Resource Type",
+ "Parent Record": "Parent Record",
+ "Fields": "Fields",
+ "Extra Fields (JSON)": "Extra Fields (JSON)",
+ "Record Identifier": "Record Identifier",
+ "Extra Query Parameters": "Extra Query Parameters",
+ "Query": "Query",
+ "Domain": "Domain",
+ "Fetch All Pages": "Fetch All Pages",
+ "Max Rows": "Max Rows",
+ "Page Token": "Page Token",
+ "User": "User",
+ "Suspended": "Suspended",
+ "Device Resource ID": "Device Resource ID",
+ "Action": "Action",
+ "From User": "From User",
+ "To User": "To User",
+ "Application": "Application",
+ "Transfer Parameters": "Transfer Parameters",
+ "Wait for Completion": "Wait for Completion",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
+ "Which kind of record. Only the types this action supports are listed.": "Which kind of record. Only the types this action supports are listed.",
+ "Only for **Group member**: the group e-mail or id.": "Only for **Group member**: the group e-mail or id.",
+ "The fields of the new record. They change with the Resource Type.": "The fields of the new record. They change with the Resource Type.",
+ "Optional. Any other field in the Directory API shape of the resource type (camelCase); the Fields above win on conflicts. Examples: **User**: `{\"primaryEmail\":\"[email protected]\",\"name\":{\"givenName\":\"Jane\",\"familyName\":\"Doe\"},\"password\":\"a-temporary-password\",\"changePasswordAtNextLogin\":true,\"orgUnitPath\":\"/\"}` · **Group**: `{\"email\":\"[email protected]\",\"name\":\"Sales\",\"description\":\"Sales team\"}` · **Group member**: `{\"email\":\"[email protected]\",\"role\":\"MEMBER\"}` · **Organizational unit**: `{\"name\":\"W": "Optional. Any other field in the Directory API shape of the resource type (camelCase); the Fields above win on conflicts. Examples: **User**: `{\"primaryEmail\":\"[email protected]\",\"name\":{\"givenName\":\"Jane\",\"familyName\":\"Doe\"},\"password\":\"a-temporary-password\",\"changePasswordAtNextLogin\":true,\"orgUnitPath\":\"/\"}` · **Group**: `{\"email\":\"[email protected]\",\"name\":\"Sales\",\"description\":\"Sales team\"}` · **Group member**: `{\"email\":\"[email protected]\",\"role\":\"MEMBER\"}` · **Organizational unit**: `{\"name\":\"West\",\"parentOrgUnitPath\":\"/Sales\",\"description\":\"West coast sales\"}` · **Role assignment**: `{\"roleId\":\"12345678901234567\",\"assignedTo\":\"1122334455667788990\",\"scopeType\":\"CUSTOMER\"}`",
+ "**User**: primary e-mail, alias or user id · **Group**: group e-mail, alias or group id · **Group member**: member e-mail or id · **Organizational unit**: org unit path (e.g. /Sales/West) or `id:<orgUnitId>` · **Mobile device**: device resource id · **Chrome OS device**: device id · **Role assignment**: role assignment id": "**User**: primary e-mail, alias or user id · **Group**: group e-mail, alias or group id · **Group member**: member e-mail or id · **Organizational unit**: org unit path (e.g. /Sales/West) or `id:<orgUnitId>` · **Mobile device**: device resource id · **Chrome OS device**: device id · **Role assignment**: role assignment id",
+ "Only the fields you fill in are changed; empty fields keep their current value.": "Only the fields you fill in are changed; empty fields keep their current value.",
+ "Optional Directory API parameters for this collection, e.g. `projection: full` and `customFieldMask: Schema1` for users, `viewType: domain_public`.": "Optional Directory API parameters for this collection, e.g. `projection: full` and `customFieldMask: Schema1` for users, `viewType: domain_public`.",
+ "Directory search syntax (only for User, Group, Mobile device, Chrome OS device). Examples: `email:sales*` · `orgUnitPath=/Sales isSuspended=false` · `name:'Jane Doe'` · `manager='[email protected]'`. Leave empty to list everything.": "Directory search syntax (only for User, Group, Mobile device, Chrome OS device). Examples: `email:sales*` · `orgUnitPath=/Sales isSuspended=false` · `name:'Jane Doe'` · `manager='[email protected]'`. Leave empty to list everything.",
+ "Only users and groups: restrict to one domain of the account (default: every domain of the customer).": "Only users and groups: restrict to one domain of the account (default: every domain of the customer).",
+ "**User**: orderBy, sortOrder, projection, customFieldMask, showDeleted, viewType · **Group**: orderBy, sortOrder, userKey · **Group member**: roles, includeDerivedMembership · **Organizational unit**: orgUnitPath, type · **Mobile device**: orderBy, sortOrder, projection · **Chrome OS device**: orgUnitPath, orderBy, sortOrder, projection, includeChildOrgunits · **Role assignment**: roleId, userKey, includeIndirectRoleAssignments": "**User**: orderBy, sortOrder, projection, customFieldMask, showDeleted, viewType · **Group**: orderBy, sortOrder, userKey · **Group member**: roles, includeDerivedMembership · **Organizational unit**: orgUnitPath, type · **Mobile device**: orderBy, sortOrder, projection · **Chrome OS device**: orgUnitPath, orderBy, sortOrder, projection, includeChildOrgunits · **Role assignment**: roleId, userKey, includeIndirectRoleAssignments",
+ "Follow the pagination until the list is exhausted (up to Max Rows). Off: return one page and its next page token.": "Follow the pagination until the list is exhausted (up to Max Rows). Off: return one page and its next page token.",
+ "With \"Fetch All Pages\": stop after this many records (default 500, at most 10000). Without it: the page size (Google caps it per collection); organizational units have no paging, so extra rows are dropped and Truncated is set.": "With \"Fetch All Pages\": stop after this many records (default 500, at most 10000). Without it: the page size (Google caps it per collection); organizational units have no paging, so extra rows are dropped and Truncated is set.",
+ "Only without \"Fetch All Pages\": the `nextPageToken` of a previous run to continue from.": "Only without \"Fetch All Pages\": the `nextPageToken` of a previous run to continue from.",
+ "Primary e-mail, alias or id of the user.": "Primary e-mail, alias or id of the user.",
+ "On: suspend the user. Off: reactivate a suspended user.": "On: suspend the user. Off: reactivate a suspended user.",
+ "The `resourceId` of the mobile device (from Search Records with type Mobile device).": "The `resourceId` of the mobile device (from Search Records with type Mobile device).",
+ "Wipes cannot be undone once the device receives them.": "Wipes cannot be undone once the device receives them.",
+ "E-mail or id of the user whose data moves. The user must still exist (suspended is fine).": "E-mail or id of the user whose data moves. The user must still exist (suspended is fine).",
+ "E-mail or id of the user receiving the data.": "E-mail or id of the user receiving the data.",
+ "Which application's data to transfer. The label lists the parameters the application accepts.": "Which application's data to transfer. The label lists the parameters the application accepts.",
+ "Parameter key to value(s), comma-separated for several. Drive: `PRIVACY_LEVEL` = `SHARED,PRIVATE` (which files); Calendar: `RELEASE_RESOURCES` = `TRUE` (free the old owner's rooms/resources). Leave empty for the application's default.": "Parameter key to value(s), comma-separated for several. Drive: `PRIVACY_LEVEL` = `SHARED,PRIVATE` (which files); Calendar: `RELEASE_RESOURCES` = `TRUE` (free the old owner's rooms/resources). Leave empty for the application's default.",
+ "Poll the transfer for up to 120 seconds and return its final status; the step fails if it is still running by then or did not complete. Off: return right after Google accepts it.": "Poll the transfer for up to 120 seconds and return its final status; the step fails if it is still running by then or did not complete. Off: return right after Google accepts it.",
+ "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.",
+ "Group": "Group",
+ "Group member": "Group member",
+ "Organizational unit": "Organizational unit",
+ "Role assignment": "Role assignment",
+ "Chrome OS device": "Chrome OS device",
+ "Mobile device": "Mobile device",
+ "Approve": "Approve",
+ "Block": "Block",
+ "Wipe account (remove the Workspace account from the device)": "Wipe account (remove the Workspace account from the device)",
+ "Wipe device (factory reset, irreversible)": "Wipe device (factory reset, irreversible)",
+ "Cancel remote wipe, then activate": "Cancel remote wipe, then activate",
+ "Cancel remote wipe, then block": "Cancel remote wipe, then block",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
+ "Request": "Request",
+ "Data to send": "Data to send",
+ "New Admin Activity Event": "New Admin Activity Event",
+ "New Application Activity Event": "New Application Activity Event",
+ "New User Event": "New User Event",
+ "Fires when an administrator performs an action in the Admin console (audit log \"admin\"), in real time through a push notification": "Fires when an administrator performs an action in the Admin console (audit log \"admin\"), in real time through a push notification",
+ "Fires on an audit event of a Google Workspace application (Drive, Login, Calendar, Groups, Mobile, ...), in real time through a push notification": "Fires on an audit event of a Google Workspace application (Drive, Login, Calendar, Groups, Mobile, ...), in real time through a push notification",
+ "Fires when a user is created, deleted, suspended, undeleted, promoted/demoted as admin or otherwise changed, in real time through a push notification": "Fires when a user is created, deleted, suspended, undeleted, promoted/demoted as admin or otherwise changed, in real time through a push notification",
+ "Event Name": "Event Name",
+ "Filters": "Filters",
+ "User Events": "User Events",
+ "Only this admin audit event, e.g. `CREATE_USER`, `DELETE_USER`, `CHANGE_PASSWORD`, `ADD_GROUP_MEMBER`, `CREATE_ORG_UNIT`, `CHANGE_APPLICATION_SETTING`. Leave empty for every admin event. Names: https://developers.google.com/workspace/admin/reports/v1/appendix/activity/admin": "Only this admin audit event, e.g. `CREATE_USER`, `DELETE_USER`, `CHANGE_PASSWORD`, `ADD_GROUP_MEMBER`, `CREATE_ORG_UNIT`, `CHANGE_APPLICATION_SETTING`. Leave empty for every admin event. Names: https://developers.google.com/workspace/admin/reports/v1/appendix/activity/admin",
+ "Optional event-parameter conditions, comma-separated, in the Reports API `filters` syntax, e.g. `[email protected]` or `ORG_UNIT_NAME==Sales`.": "Optional event-parameter conditions, comma-separated, in the Reports API `filters` syntax, e.g. `[email protected]` or `ORG_UNIT_NAME==Sales`.",
+ "Which audit log to watch.": "Which audit log to watch.",
+ "Only this event of the application, e.g. `login_success` (Login), `download` / `create` / `edit` (Drive), `change_calendar_acls` (Calendar), `DEVICE_REGISTER_UNREGISTER_EVENT` (Mobile). Leave empty for every event. Names per application: https://developers.google.com/workspace/admin/reports/v1/appendix": "Only this event of the application, e.g. `login_success` (Login), `download` / `create` / `edit` (Drive), `change_calendar_acls` (Calendar), `DEVICE_REGISTER_UNREGISTER_EVENT` (Mobile). Leave empty for every event. Names per application: https://developers.google.com/workspace/admin/reports/v1/appendix",
+ "Optional event-parameter conditions, comma-separated, in the Reports API `filters` syntax, e.g. `doc_type==spreadsheet` or `login_type==google_password`.": "Optional event-parameter conditions, comma-separated, in the Reports API `filters` syntax, e.g. `doc_type==spreadsheet` or `login_type==google_password`.",
+ "Which lifecycle events to fire on.": "Which lifecycle events to fire on.",
+ "Only users of this domain (e.g. `example.com`). Leave empty for every domain of the account.": "Only users of this domain (e.g. `example.com`). Leave empty for every domain of the account.",
+ "Admin console": "Admin console",
+ "Login": "Login",
+ "User accounts": "User accounts",
+ "Drive": "Drive",
+ "Gmail": "Gmail",
+ "Calendar": "Calendar",
+ "Groups": "Groups",
+ "Groups Enterprise": "Groups Enterprise",
+ "Chat": "Chat",
+ "Meet": "Meet",
+ "Meet hardware": "Meet hardware",
+ "Mobile devices": "Mobile devices",
+ "Chrome": "Chrome",
+ "Chrome sync": "Chrome sync",
+ "OAuth tokens": "OAuth tokens",
+ "SAML": "SAML",
+ "Rules": "Rules",
+ "Context-aware access": "Context-aware access",
+ "Access transparency": "Access transparency",
+ "Access evaluation": "Access evaluation",
+ "Admin data actions": "Admin data actions",
+ "Google Cloud": "Google Cloud",
+ "Looker Studio": "Looker Studio",
+ "Keep": "Keep",
+ "Vault": "Vault",
+ "Classroom": "Classroom",
+ "Assignments": "Assignments",
+ "Cloud Search": "Cloud Search",
+ "Tasks": "Tasks",
+ "Contacts": "Contacts",
+ "Takeout": "Takeout",
+ "Voice": "Voice",
+ "Data migration": "Data migration",
+ "Directory Sync": "Directory Sync",
+ "LDAP": "LDAP",
+ "Profile": "Profile",
+ "Graduation": "Graduation",
+ "Gemini in Workspace apps": "Gemini in Workspace apps",
+ "Workspace Studio": "Workspace Studio",
+ "Jamboard": "Jamboard",
+ "Google+": "Google+",
+ "User created": "User created",
+ "User deleted": "User deleted",
+ "User undeleted": "User undeleted",
+ "User suspended": "User suspended",
+ "User unsuspended": "User unsuspended",
+ "Admin status changed": "Admin status changed",
+ "User updated (any other change)": "User updated (any other change)"
+}
\ No newline at end of file
diff --git a/packages/pieces/community/google-workspace/src/index.ts b/packages/pieces/community/google-workspace/src/index.ts
new file mode 100644
index 00000000000..6b15b9e1f93
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/index.ts
@@ -0,0 +1,54 @@
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+
+import { addRecord } from './lib/actions/add-record';
+import { deleteRecord } from './lib/actions/delete-record';
+import { getRecord } from './lib/actions/get-record';
+import { mobileDeviceAction } from './lib/actions/mobile-device-action';
+import { searchRecords } from './lib/actions/search-records';
+import { suspendUser } from './lib/actions/suspend-user';
+import { transferData } from './lib/actions/transfer-data';
+import { updateRecord } from './lib/actions/update-record';
+import { googleWorkspaceAuth } from './lib/auth';
+import { googleWorkspaceClient } from './lib/common/client';
+import { googleWorkspaceUtils } from './lib/common/utils';
+import { newAdminActivityEvent } from './lib/triggers/new-admin-activity-event';
+import { newApplicationActivityEvent } from './lib/triggers/new-application-activity-event';
+import { newUserEvent } from './lib/triggers/new-user-event';
+
+export const googleWorkspace = createPiece({
+ displayName: 'Google Workspace',
+ description:
+ 'Manage Google Workspace users, groups, organizational units and devices, and react to Admin audit events.',
+ auth: googleWorkspaceAuth,
+ minimumSupportedRelease: '0.88.0',
+ logoUrl: 'https://cdn.activepieces.com/pieces/google-workspace.png',
+ categories: [PieceCategory.PRODUCTIVITY],
+ authors: ['fabio-kozlowski'],
+ actions: [
+ addRecord,
+ updateRecord,
+ deleteRecord,
+ getRecord,
+ searchRecords,
+ suspendUser,
+ mobileDeviceAction,
+ transferData,
+ createCustomApiCallAction({
+ auth: googleWorkspaceAuth,
+ baseUrl: () => googleWorkspaceClient.baseUrl(),
+ description: `Call any Admin SDK endpoint. Paths are relative to ${googleWorkspaceUtils.adminApiRoot}, e.g. /${googleWorkspaceUtils.directoryPath}/users?customer=my_customer, /${googleWorkspaceUtils.reportsPath}/activity/users/all/applications/login, /${googleWorkspaceUtils.dataTransferPath}/applications.`,
+ authMapping: async (auth, propsValue) => {
+ const urlProp: unknown = propsValue['url'];
+ googleWorkspaceUtils.assertCustomApiCallUrl(
+ typeof urlProp === 'object' && urlProp !== null
+ ? Object.fromEntries(Object.entries(urlProp))['url']
+ : undefined,
+ );
+ const { access_token } = await googleWorkspaceClient.resolveAuth(auth);
+ return { Authorization: `Bearer ${access_token}` };
+ },
+ }),
+ ],
+ triggers: [newAdminActivityEvent, newApplicationActivityEvent, newUserEvent],
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/actions/add-record.ts b/packages/pieces/community/google-workspace/src/lib/actions/add-record.ts
new file mode 100644
index 00000000000..d8fa01d3221
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/actions/add-record.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceClient } from '../common/client';
+import { googleWorkspaceProps } from '../common/props';
+import { googleWorkspaceUtils } from '../common/utils';
+import { recordOutputSchema } from '../output-schemas';
+
+export const addRecord = createAction({
+ name: 'addRecord',
+ classification: 'WRITE',
+ displayName: 'Add Record',
+ description: 'Create a user, group, group member, organizational unit or role assignment',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates one Google Workspace directory record (user, group, group member, organizational unit or role assignment) from the Fields of the chosen type and/or Extra Fields, a JSON body in the Admin SDK Directory API shape. Use to provision a new entry; to change an existing one use Update Record. Each call creates a new record, so a retry fails with a conflict or creates a duplicate.',
+ idempotent: false,
+ },
+ auth: googleWorkspaceAuth,
+ props: {
+ resourceType: googleWorkspaceProps.resourceType({ verb: 'create' }),
+ parent: googleWorkspaceProps.parent({ required: false }),
+ recordFields: googleWorkspaceProps.recordFields({ required: false, mode: 'create' }),
+ record: googleWorkspaceProps.record({ required: false }),
+ },
+ outputSchema: recordOutputSchema,
+ async run(context) {
+ const { resourceType, parent, recordFields, record } = context.propsValue;
+ const def = googleWorkspaceUtils.resourceDefinition(resourceType);
+ googleWorkspaceUtils.assertVerb({ def, verb: 'create' });
+ const body = googleWorkspaceUtils.recordBody({ def, fields: recordFields, extra: record });
+ if (Object.keys(body).length === 0) {
+ throw new Error('Fill in the Fields (or Extra Fields) of the new record.');
+ }
+ const auth = await googleWorkspaceClient.resolveAuth(context.auth);
+
+ const created = await googleWorkspaceClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.POST,
+ path: def.collectionPath(parent),
+ body,
+ });
+
+ return {
+ resourceType: def.type,
+ id: googleWorkspaceUtils.idOf({ def, item: created }),
+ record: created,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/actions/delete-record.ts b/packages/pieces/community/google-workspace/src/lib/actions/delete-record.ts
new file mode 100644
index 00000000000..42639cfe75c
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/actions/delete-record.ts
@@ -0,0 +1,47 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceApi } from '../common/api';
+import { googleWorkspaceClient } from '../common/client';
+import { googleWorkspaceProps } from '../common/props';
+import { googleWorkspaceUtils } from '../common/utils';
+import { deleteRecordOutputSchema } from '../output-schemas';
+
+export const deleteRecord = createAction({
+ name: 'deleteRecord',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Record',
+ description:
+ 'Remove a user, group, group member, organizational unit, mobile device or role assignment. Deleted users can be restored for 20 days from the Admin console; everything else is permanent.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Deletes one Google Workspace directory record (user, group, group member, organizational unit, mobile device or role assignment). Prefer Suspend User to block a user without losing data. Only deleted users can be restored (for 20 days, from the Admin console); a retry after success fails with not found.',
+ idempotent: false,
+ },
+ auth: googleWorkspaceAuth,
+ props: {
+ resourceType: googleWorkspaceProps.resourceType({ verb: 'delete' }),
+ identifier: googleWorkspaceProps.identifier({ required: true }),
+ parent: googleWorkspaceProps.parent({ required: false }),
+ },
+ outputSchema: deleteRecordOutputSchema,
+ async run(context) {
+ const { resourceType, identifier, parent } = context.propsValue;
+ const def = googleWorkspaceUtils.resourceDefinition(resourceType);
+ googleWorkspaceUtils.assertVerb({ def, verb: 'delete' });
+ const auth = await googleWorkspaceClient.resolveAuth(context.auth);
+
+ await googleWorkspaceClient.request<unknown>({
+ auth,
+ method: HttpMethod.DELETE,
+ path: def.itemPath({
+ id: await googleWorkspaceApi.resolveIdentifier({ def, auth, id: identifier }),
+ parent,
+ }),
+ });
+
+ return { resourceType: def.type, id: String(identifier).trim(), removed: true };
+ },
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/actions/get-record.ts b/packages/pieces/community/google-workspace/src/lib/actions/get-record.ts
new file mode 100644
index 00000000000..10810c56205
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/actions/get-record.ts
@@ -0,0 +1,54 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceApi } from '../common/api';
+import { googleWorkspaceClient } from '../common/client';
+import { googleWorkspaceProps } from '../common/props';
+import { googleWorkspaceUtils } from '../common/utils';
+import { recordOutputSchema } from '../output-schemas';
+
+export const getRecord = createAction({
+ name: 'getRecord',
+ classification: 'READ',
+ displayName: 'Get Record',
+ description:
+ 'Return the full record of a user, group, group member, org unit, device or role assignment',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reads one Google Workspace directory record (user, group, group member, organizational unit, mobile or Chrome OS device, role assignment) by its identifier. Use when the key is known; to find records by criteria use Search Records. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ auth: googleWorkspaceAuth,
+ props: {
+ resourceType: googleWorkspaceProps.resourceType({ verb: 'get' }),
+ identifier: googleWorkspaceProps.identifier({ required: true }),
+ parent: googleWorkspaceProps.parent({ required: false }),
+ params: Property.Object({
+ displayName: 'Extra Query Parameters',
+ description:
+ 'Optional Directory API parameters for this collection, e.g. `projection: full` and `customFieldMask: Schema1` for users, `viewType: domain_public`.',
+ required: false,
+ }),
+ },
+ outputSchema: recordOutputSchema,
+ async run(context) {
+ const { resourceType, identifier, parent, params } = context.propsValue;
+ const def = googleWorkspaceUtils.resourceDefinition(resourceType);
+ googleWorkspaceUtils.assertVerb({ def, verb: 'get' });
+ const auth = await googleWorkspaceClient.resolveAuth(context.auth);
+
+ const record = await googleWorkspaceClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.GET,
+ path: def.itemPath({
+ id: await googleWorkspaceApi.resolveIdentifier({ def, auth, id: identifier }),
+ parent,
+ }),
+ query: googleWorkspaceUtils.stringValues(params),
+ });
+
+ return { resourceType: def.type, id: googleWorkspaceUtils.idOf({ def, item: record }), record };
+ },
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/actions/mobile-device-action.ts b/packages/pieces/community/google-workspace/src/lib/actions/mobile-device-action.ts
new file mode 100644
index 00000000000..061536412ad
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/actions/mobile-device-action.ts
@@ -0,0 +1,61 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceClient } from '../common/client';
+import { googleWorkspaceUtils } from '../common/utils';
+import { mobileDeviceActionOutputSchema } from '../output-schemas';
+
+export const MOBILE_DEVICE_ACTIONS: { label: string; value: string }[] = [
+ { label: 'Approve', value: 'approve' },
+ { label: 'Block', value: 'block' },
+ {
+ label: 'Wipe account (remove the Workspace account from the device)',
+ value: 'admin_account_wipe',
+ },
+ { label: 'Wipe device (factory reset, irreversible)', value: 'admin_remote_wipe' },
+ { label: 'Cancel remote wipe, then activate', value: 'cancel_remote_wipe_then_activate' },
+ { label: 'Cancel remote wipe, then block', value: 'cancel_remote_wipe_then_block' },
+];
+
+export const mobileDeviceAction = createAction({
+ name: 'mobileDeviceAction',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Mobile Device Action',
+ description: 'Approve, block or wipe a managed mobile device',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends an administrative command to one managed mobile device: approve, block, wipe the Workspace account, factory-reset wipe, or cancel a pending wipe. Needs the device resourceId (from Search Records with type Mobile device). Wipes are irreversible once the device receives them, so do not retry blindly.',
+ idempotent: false,
+ },
+ auth: googleWorkspaceAuth,
+ props: {
+ resourceId: Property.ShortText({
+ displayName: 'Device Resource ID',
+ description:
+ 'The `resourceId` of the mobile device (from Search Records with type Mobile device).',
+ required: true,
+ }),
+ action: Property.StaticDropdown<string, true>({
+ displayName: 'Action',
+ description: 'Wipes cannot be undone once the device receives them.',
+ required: true,
+ options: { options: MOBILE_DEVICE_ACTIONS },
+ }),
+ },
+ outputSchema: mobileDeviceActionOutputSchema,
+ async run(context) {
+ const { resourceId, action } = context.propsValue;
+ const auth = await googleWorkspaceClient.resolveAuth(context.auth);
+
+ await googleWorkspaceClient.request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: `${googleWorkspaceUtils.resources.mobile_device.itemPath({ id: resourceId })}/action`,
+ body: { action },
+ });
+
+ return { resourceId: String(resourceId).trim(), action, success: true };
+ },
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/actions/search-records.ts b/packages/pieces/community/google-workspace/src/lib/actions/search-records.ts
new file mode 100644
index 00000000000..22bcc7bcd90
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/actions/search-records.ts
@@ -0,0 +1,139 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceClient } from '../common/client';
+import { googleWorkspaceProps } from '../common/props';
+import { googleWorkspaceUtils } from '../common/utils';
+import { searchRecordsOutputSchema } from '../output-schemas';
+
+import type { GoogleWorkspaceQuery } from '../common/types';
+
+function queryableLabels(): string {
+ return Object.values(googleWorkspaceUtils.resources)
+ .filter((def) => def.supportsQuery)
+ .map((def) => def.label)
+ .join(', ');
+}
+
+const DEFAULT_MAX_ROWS = 500;
+const HARD_MAX_ROWS = 10_000;
+
+export const searchRecords = createAction({
+ name: 'searchRecords',
+ classification: 'SEARCH',
+ displayName: 'Search Records',
+ description: 'List records of one type with the Directory search syntax and pagination',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists Google Workspace directory records of one type (users, groups, group members, organizational units, mobile or Chrome OS devices, role assignments), optionally filtered with the Directory search syntax (users, groups and devices only) or a domain (users and groups only). Returns one page with a next page token, or every page up to Max Rows. Read-only and safe to retry; use Get Record when the identifier is known.',
+ idempotent: true,
+ },
+ auth: googleWorkspaceAuth,
+ props: {
+ resourceType: googleWorkspaceProps.resourceType({ verb: 'list' }),
+ parent: googleWorkspaceProps.parent({ required: false }),
+ query: Property.ShortText({
+ displayName: 'Query',
+ description: `Directory search syntax (only for ${queryableLabels()}). Examples: \`email:sales*\` · \`orgUnitPath=/Sales isSuspended=false\` · \`name:'Jane Doe'\` · \`manager='[email protected]'\`. Leave empty to list everything.`,
+ required: false,
+ }),
+ domain: Property.ShortText({
+ displayName: 'Domain',
+ description:
+ 'Only users and groups: restrict to one domain of the account (default: every domain of the customer).',
+ required: false,
+ }),
+ params: Property.Object({
+ displayName: 'Extra Query Parameters',
+ description: Object.values(googleWorkspaceUtils.resources)
+ .filter((def) => def.extraListParams?.length)
+ .map((def) => `**${def.label}**: ${def.extraListParams?.join(', ')}`)
+ .join(' · '),
+ required: false,
+ }),
+ fetchAllPages: Property.Checkbox({
+ displayName: 'Fetch All Pages',
+ description:
+ 'Follow the pagination until the list is exhausted (up to Max Rows). Off: return one page and its next page token.',
+ required: false,
+ defaultValue: false,
+ }),
+ maxRows: Property.Number({
+ displayName: 'Max Rows',
+ description: `With "Fetch All Pages": stop after this many records (default ${DEFAULT_MAX_ROWS}, at most ${HARD_MAX_ROWS}). Without it: the page size (Google caps it per collection); organizational units have no paging, so extra rows are dropped and Truncated is set.`,
+ required: false,
+ defaultValue: DEFAULT_MAX_ROWS,
+ }),
+ pageToken: Property.ShortText({
+ displayName: 'Page Token',
+ description:
+ 'Only without "Fetch All Pages": the `nextPageToken` of a previous run to continue from.',
+ required: false,
+ }),
+ },
+ outputSchema: searchRecordsOutputSchema,
+ async run(context) {
+ const { resourceType, parent, query, domain, params, fetchAllPages, maxRows, pageToken } =
+ context.propsValue;
+ const def = googleWorkspaceUtils.resourceDefinition(resourceType);
+ googleWorkspaceUtils.assertVerb({ def, verb: 'list' });
+
+ if (query && !def.supportsQuery) {
+ throw new Error(
+ `${def.label} records cannot be filtered with a query; use the extra parameters (${
+ def.extraListParams?.join(', ') ?? 'none'
+ }) instead.`,
+ );
+ }
+ if (domain && !def.supportsDomain) {
+ throw new Error('The domain filter only applies to users and groups.');
+ }
+
+ const auth = await googleWorkspaceClient.resolveAuth(context.auth);
+ const path = def.collectionPath(parent);
+ const cap = Math.floor(
+ Math.min(Math.max(Number(maxRows) || DEFAULT_MAX_ROWS, 1), HARD_MAX_ROWS),
+ );
+ const extraParams = googleWorkspaceUtils.stringValues(params);
+ const baseQuery: GoogleWorkspaceQuery = {
+ ...(def.supportsDomain && !domain && !extraParams['userKey']
+ ? { customer: googleWorkspaceUtils.myCustomer }
+ : {}),
+ ...(domain ? { domain } : {}),
+ ...(query ? { query } : {}),
+ ...extraParams,
+ };
+ const pageSize = def.maxPageSize ? { maxResults: Math.min(cap, def.maxPageSize) } : {};
+
+ if (fetchAllPages) {
+ const { items, truncated } = await googleWorkspaceClient.listAll<Record<string, unknown>>({
+ auth,
+ path,
+ itemsKey: def.itemsKey,
+ query: { ...baseQuery, ...pageSize },
+ maxRows: cap,
+ });
+ return { resourceType: def.type, items, count: items.length, truncated };
+ }
+
+ const page = await googleWorkspaceClient.listPage<Record<string, unknown>>({
+ auth,
+ path,
+ itemsKey: def.itemsKey,
+ query: {
+ ...baseQuery,
+ ...pageSize,
+ pageToken: pageToken || undefined,
+ },
+ });
+ const items = page.items.slice(0, cap);
+ return {
+ resourceType: def.type,
+ items,
+ count: items.length,
+ nextPageToken: page.nextPageToken ?? null,
+ truncated: items.length < page.items.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/actions/suspend-user.ts b/packages/pieces/community/google-workspace/src/lib/actions/suspend-user.ts
new file mode 100644
index 00000000000..bbf757d2e14
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/actions/suspend-user.ts
@@ -0,0 +1,55 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceClient } from '../common/client';
+import { googleWorkspaceUtils } from '../common/utils';
+import { suspendUserOutputSchema } from '../output-schemas';
+
+export const suspendUser = createAction({
+ name: 'suspendUser',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Suspend User',
+ description: 'Suspend a directory user (blocks sign-in, keeps data), or lift the suspension',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Suspends a Google Workspace user (blocks sign-in and access while keeping the account and its data) or, with Suspended off, reactivates a suspended user. Prefer this over Delete Record when offboarding. Sets the user to the requested state, so retries are safe.',
+ idempotent: true,
+ },
+ auth: googleWorkspaceAuth,
+ props: {
+ userKey: Property.ShortText({
+ displayName: 'User',
+ description: 'Primary e-mail, alias or id of the user.',
+ required: true,
+ }),
+ suspended: Property.Checkbox({
+ displayName: 'Suspended',
+ description: 'On: suspend the user. Off: reactivate a suspended user.',
+ required: false,
+ defaultValue: true,
+ }),
+ },
+ outputSchema: suspendUserOutputSchema,
+ async run(context) {
+ const { userKey, suspended } = context.propsValue;
+ const auth = await googleWorkspaceClient.resolveAuth(context.auth);
+ const value = suspended !== false;
+
+ const user = await googleWorkspaceClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.PATCH,
+ path: googleWorkspaceUtils.resources.user.itemPath({ id: userKey }),
+ body: { suspended: value },
+ });
+
+ return {
+ id: user['id'] ?? null,
+ primaryEmail: user['primaryEmail'] ?? null,
+ suspended: typeof user['suspended'] === 'boolean' ? user['suspended'] : value,
+ suspensionReason: user['suspensionReason'] ?? null,
+ record: user,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/actions/transfer-data.ts b/packages/pieces/community/google-workspace/src/lib/actions/transfer-data.ts
new file mode 100644
index 00000000000..fe20d5ed6f0
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/actions/transfer-data.ts
@@ -0,0 +1,272 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceClient } from '../common/client';
+import { googleWorkspaceProps } from '../common/props';
+import { googleWorkspaceUtils } from '../common/utils';
+import { transferDataOutputSchema } from '../output-schemas';
+
+import type {
+ GoogleWorkspaceApplicationDataTransfer,
+ GoogleWorkspaceDataTransfer,
+ GoogleWorkspaceResolvedAuth,
+ GoogleWorkspaceTransferParam,
+} from '../common/types';
+
+function toTransferParams(value: unknown): GoogleWorkspaceTransferParam[] {
+ const entries = typeof value === 'object' && value !== null ? Object.entries(value) : [];
+ return entries
+ .map(([key, raw]) => ({
+ key: key.trim(),
+ value: (Array.isArray(raw) ? raw : String(raw ?? '').split(','))
+ .map((v) => String(v).trim())
+ .filter(Boolean),
+ }))
+ .filter((p) => p.key && p.value.length > 0);
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function pollUntilDone({
+ auth,
+ transfer,
+ transferId,
+ deadline,
+}: {
+ auth: GoogleWorkspaceResolvedAuth;
+ transfer: GoogleWorkspaceDataTransfer;
+ transferId: string;
+ deadline: number;
+}): Promise<GoogleWorkspaceDataTransfer> {
+ let latest = transfer;
+ while (isRunning(latest) && Date.now() < deadline) {
+ await sleep(Math.min(POLL_INTERVAL_MS, deadline - Date.now()));
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) {
+ return latest;
+ }
+ try {
+ latest = await getTransfer({ auth, transferId, timeoutMs: remaining });
+ } catch (error) {
+ if (Date.now() < deadline) {
+ throw new Error(
+ `Transfer ${transferId} was started in Google and was not cancelled, but checking its status failed: ${
+ error instanceof Error ? error.message : String(error)
+ }. Check it with Custom API Call (GET /${
+ googleWorkspaceUtils.dataTransferPath
+ }/transfers/${transferId}) before running this step again.`,
+ { cause: error },
+ );
+ }
+ return latest;
+ }
+ }
+ return latest;
+}
+
+function isRunning(transfer: GoogleWorkspaceDataTransfer): boolean {
+ return RUNNING_STATUSES.includes(transfer.overallTransferStatusCode ?? '');
+}
+
+function assertNotFailed({
+ transfer,
+ requireCompleted,
+}: {
+ transfer: GoogleWorkspaceDataTransfer;
+ requireCompleted: boolean;
+}): void {
+ const status = transfer.overallTransferStatusCode ?? 'unknown';
+ const failed = (transfer.applicationDataTransfers ?? []).filter(
+ (a) => a.applicationTransferStatus === FAILED_STATUS,
+ );
+ const overallFailed = requireCompleted ? status !== COMPLETED_STATUS : status === FAILED_STATUS;
+ if (!overallFailed && failed.length === 0) {
+ return;
+ }
+ const applications = failed
+ .map((a) => `application ${a.applicationId}: ${FAILED_STATUS}`)
+ .join(', ');
+ const transferId = transfer.id ?? 'without id';
+ throw new Error(
+ `Transfer ${transferId} did not complete in Google (status: ${status}${
+ applications ? `; ${applications}` : ''
+ }). The data of From User may not have moved, so do not delete that user yet. Check the details with Custom API Call (GET /${
+ googleWorkspaceUtils.dataTransferPath
+ }/transfers/${transferId}) and start a new transfer once the cause is fixed.`,
+ );
+}
+
+function shape(transfer: GoogleWorkspaceDataTransfer) {
+ return {
+ transferId: transfer.id ?? null,
+ status: transfer.overallTransferStatusCode ?? null,
+ oldOwnerUserId: transfer.oldOwnerUserId,
+ newOwnerUserId: transfer.newOwnerUserId,
+ requestTime: transfer.requestTime ?? null,
+ applications: (transfer.applicationDataTransfers ?? []).map((a) => ({
+ applicationId: a.applicationId,
+ status: a.applicationTransferStatus ?? null,
+ params: a.applicationTransferParams ?? [],
+ })),
+ };
+}
+
+async function userProfileId({
+ auth,
+ userKey,
+}: {
+ auth: GoogleWorkspaceResolvedAuth;
+ userKey: string;
+}): Promise<string> {
+ const key = String(userKey ?? '').trim();
+ if (!key) {
+ throw new Error('A user e-mail or id is required.');
+ }
+ if (/^\d+$/.test(key)) {
+ return key;
+ }
+ const user = await googleWorkspaceClient.request<{ id?: string }>({
+ auth,
+ method: HttpMethod.GET,
+ path: `${googleWorkspaceUtils.directoryPath}/users/${encodeURIComponent(key)}`,
+ query: { projection: 'basic' },
+ });
+ if (!user.id) {
+ throw new Error(`Google returned no id for user "${key}".`);
+ }
+ return user.id;
+}
+
+async function createTransfer({
+ auth,
+ transfer,
+}: {
+ auth: GoogleWorkspaceResolvedAuth;
+ transfer: GoogleWorkspaceDataTransfer;
+}): Promise<GoogleWorkspaceDataTransfer> {
+ return await googleWorkspaceClient.request<GoogleWorkspaceDataTransfer>({
+ auth,
+ method: HttpMethod.POST,
+ path: `${googleWorkspaceUtils.dataTransferPath}/transfers`,
+ body: transfer,
+ });
+}
+
+async function getTransfer({
+ auth,
+ transferId,
+ timeoutMs,
+}: {
+ auth: GoogleWorkspaceResolvedAuth;
+ transferId: string;
+ timeoutMs?: number;
+}): Promise<GoogleWorkspaceDataTransfer> {
+ return await googleWorkspaceClient.request<GoogleWorkspaceDataTransfer>({
+ auth,
+ method: HttpMethod.GET,
+ path: `${googleWorkspaceUtils.dataTransferPath}/transfers/${encodeURIComponent(transferId)}`,
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
+ });
+}
+
+const COMPLETED_STATUS = 'completed';
+const FAILED_STATUS = 'failed';
+const RUNNING_STATUSES = ['inProgress', 'pending'];
+const POLL_INTERVAL_MS = 10_000;
+const POLL_WAIT_MS = 120_000;
+const POLL_WAIT_SECONDS = POLL_WAIT_MS / 1000;
+
+export const transferData = createAction({
+ name: 'transferData',
+ classification: 'WRITE',
+ displayName: 'Transfer Data',
+ description:
+ "Transfer a user's application data (Drive files, Calendar events, ...) to another user, e.g. when offboarding",
+ audience: 'both',
+ aiMetadata: {
+ description:
+ "Starts a Google Workspace data transfer that moves one application's data (Drive files, Calendar events, Looker Studio assets, ...) from one user to another, typically when offboarding. Both users must exist; the source may be suspended. Each call starts a new transfer, so do not retry a successful call.",
+ idempotent: false,
+ },
+ errorHandlingOptions: {
+ continueOnFailure: { defaultValue: false },
+ retryOnFailure: { defaultValue: false, hide: true },
+ },
+ auth: googleWorkspaceAuth,
+ props: {
+ oldOwner: Property.ShortText({
+ displayName: 'From User',
+ description:
+ 'E-mail or id of the user whose data moves. The user must still exist (suspended is fine).',
+ required: true,
+ }),
+ newOwner: Property.ShortText({
+ displayName: 'To User',
+ description: 'E-mail or id of the user receiving the data.',
+ required: true,
+ }),
+ applicationId: googleWorkspaceProps.applicationId({ required: true }),
+ transferParams: Property.Object({
+ displayName: 'Transfer Parameters',
+ description:
+ "Parameter key to value(s), comma-separated for several. Drive: `PRIVACY_LEVEL` = `SHARED,PRIVATE` (which files); Calendar: `RELEASE_RESOURCES` = `TRUE` (free the old owner's rooms/resources). Leave empty for the application's default.",
+ required: false,
+ }),
+ waitForCompletion: Property.Checkbox({
+ displayName: 'Wait for Completion',
+ description: `Poll the transfer for up to ${POLL_WAIT_SECONDS} seconds and return its final status; the step fails if it is still running by then or did not complete. Off: return right after Google accepts it.`,
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: transferDataOutputSchema,
+ async run(context) {
+ const { oldOwner, newOwner, applicationId, transferParams, waitForCompletion } =
+ context.propsValue;
+ const auth = await googleWorkspaceClient.resolveAuth(context.auth);
+
+ const [oldOwnerUserId, newOwnerUserId] = await Promise.all([
+ userProfileId({ auth, userKey: oldOwner }),
+ userProfileId({ auth, userKey: newOwner }),
+ ]);
+ if (oldOwnerUserId === newOwnerUserId) {
+ throw new Error('From User and To User are the same account.');
+ }
+
+ const params = toTransferParams(transferParams);
+ const application: GoogleWorkspaceApplicationDataTransfer = {
+ applicationId: String(applicationId),
+ ...(params.length > 0 ? { applicationTransferParams: params } : {}),
+ };
+
+ let transfer = await createTransfer({
+ auth,
+ transfer: {
+ oldOwnerUserId,
+ newOwnerUserId,
+ applicationDataTransfers: [application],
+ },
+ });
+
+ const transferId = transfer.id;
+ if (waitForCompletion && transferId) {
+ transfer = await pollUntilDone({
+ auth,
+ transfer,
+ transferId,
+ deadline: Date.now() + POLL_WAIT_MS,
+ });
+ if (isRunning(transfer)) {
+ throw new Error(
+ `Transfer ${transferId} is still running in Google after waiting ${POLL_WAIT_SECONDS} seconds. It was not cancelled and will finish on its own. Check its status with Custom API Call (GET /${googleWorkspaceUtils.dataTransferPath}/transfers/${transferId}), or turn Wait for Completion off to continue as soon as Google accepts the transfer.`,
+ );
+ }
+ }
+ assertNotFailed({ transfer, requireCompleted: Boolean(waitForCompletion && transferId) });
+
+ return shape(transfer);
+ },
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/actions/update-record.ts b/packages/pieces/community/google-workspace/src/lib/actions/update-record.ts
new file mode 100644
index 00000000000..513af6e72a1
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/actions/update-record.ts
@@ -0,0 +1,58 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceApi } from '../common/api';
+import { googleWorkspaceClient } from '../common/client';
+import { googleWorkspaceProps } from '../common/props';
+import { googleWorkspaceUtils } from '../common/utils';
+import { recordOutputSchema } from '../output-schemas';
+
+export const updateRecord = createAction({
+ name: 'updateRecord',
+ classification: 'WRITE',
+ displayName: 'Update Record',
+ description:
+ 'Change fields of a user, group, group member, organizational unit or Chrome OS device (PATCH: untouched fields stay as they are)',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Partially updates one existing Google Workspace directory record (user, group, group member, organizational unit or Chrome OS device) with the given fields; omitted fields stay unchanged. Use Suspend User for suspensions and Add Record to create. Safe to retry: the record ends in the same state.',
+ idempotent: true,
+ },
+ auth: googleWorkspaceAuth,
+ props: {
+ resourceType: googleWorkspaceProps.resourceType({ verb: 'update' }),
+ identifier: googleWorkspaceProps.identifier({ required: true }),
+ parent: googleWorkspaceProps.parent({ required: false }),
+ recordFields: googleWorkspaceProps.recordFields({ required: false, mode: 'update' }),
+ record: googleWorkspaceProps.record({ required: false }),
+ },
+ outputSchema: recordOutputSchema,
+ async run(context) {
+ const { resourceType, identifier, parent, recordFields, record } = context.propsValue;
+ const def = googleWorkspaceUtils.resourceDefinition(resourceType);
+ googleWorkspaceUtils.assertVerb({ def, verb: 'update' });
+ const body = googleWorkspaceUtils.recordBody({ def, fields: recordFields, extra: record });
+ if (Object.keys(body).length === 0) {
+ throw new Error('The record has no fields to update.');
+ }
+ const auth = await googleWorkspaceClient.resolveAuth(context.auth);
+
+ const updated = await googleWorkspaceClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.PATCH,
+ path: def.itemPath({
+ id: await googleWorkspaceApi.resolveIdentifier({ def, auth, id: identifier }),
+ parent,
+ }),
+ body,
+ });
+
+ return {
+ resourceType: def.type,
+ id: googleWorkspaceUtils.idOf({ def, item: updated }),
+ record: updated,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/auth.ts b/packages/pieces/community/google-workspace/src/lib/auth.ts
new file mode 100644
index 00000000000..73e6ed11e27
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/auth.ts
@@ -0,0 +1,97 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { PieceAuth, Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceClient } from './common/client';
+
+import type { GoogleWorkspaceServiceAccount } from './common/types';
+
+async function validateServiceAccount(
+ creds: GoogleWorkspaceServiceAccount,
+): Promise<{ valid: true } | { valid: false; error: string }> {
+ try {
+ const token = await googleWorkspaceClient.mintServiceAccountToken({
+ creds,
+ scopes: googleWorkspaceClient.scopes,
+ });
+ const user = await googleWorkspaceClient.request<{
+ isAdmin?: boolean;
+ isDelegatedAdmin?: boolean;
+ primaryEmail?: string;
+ }>({
+ auth: { access_token: token },
+ method: HttpMethod.GET,
+ path: `admin/directory/v1/users/${encodeURIComponent(creds.adminEmail.trim())}`,
+ });
+ if (!user.isAdmin && !user.isDelegatedAdmin) {
+ return {
+ valid: false,
+ error: `${
+ user.primaryEmail ?? creds.adminEmail
+ } is not a Workspace administrator; pick a user with an admin role.`,
+ };
+ }
+ return { valid: true };
+ } catch (error) {
+ return { valid: false, error: error instanceof Error ? error.message : String(error) };
+ }
+}
+
+const delegationScopeList = googleWorkspaceClient.scopes
+ .map((scope) => ` - \`${scope}\``)
+ .join('\n');
+
+const oauthInstructions = `
+Sign in as a **Google Workspace administrator** with an OAuth client from **your own** Google Cloud project:
+
+1. In [Google Cloud Console](https://console.cloud.google.com/), select or create a project. **APIs & Services → Library**: enable **Admin SDK API**.
+2. **APIs & Services → OAuth consent screen**: add the Admin SDK scopes this connection requests (users, groups, org units, devices, roles, data transfer, audit reports). While the app is in *Testing*, add the administrators that will connect as test users.
+3. **APIs & Services → Credentials → Create credentials → OAuth client ID**, type *Web application*. Add the **Redirect URL shown below** to *Authorized redirect URIs*.
+4. Paste the **Client ID** and **Client Secret** here and sign in with an administrator account. The account's admin role decides what the connection can do.
+`.trim();
+
+const serviceAccountInstructions = `
+Connect with a **service account** that has **domain-wide delegation**, so flows run without an administrator signing in:
+
+1. In [Google Cloud Console](https://console.cloud.google.com/), enable **Admin SDK API**, then **IAM & Admin → Service Accounts → Create**. Open the account, **Keys → Add key → JSON** and download the key file.
+2. In the [Admin console](https://admin.google.com/) go to **Security → Access and data control → API controls → Manage domain-wide delegation → Add new**. Paste the service account's numeric **Client ID** (from the key file, \`client_id\`) and, as scopes (comma-separated), exactly these:
+${delegationScopeList}
+3. Fill in below the key file's \`client_email\` and \`private_key\` (the whole value, with or without its line breaks), plus the e-mail of the **administrator the service account acts as**. Delegation can take a few minutes to propagate.
+`.trim();
+
+export const googleWorkspaceOAuth2 = PieceAuth.OAuth2({
+ displayName: 'Google Account (OAuth2)',
+ description: oauthInstructions,
+ authUrl: 'https://accounts.google.com/o/oauth2/auth',
+ tokenUrl: 'https://oauth2.googleapis.com/token',
+ required: true,
+ scope: [...googleWorkspaceClient.scopes, 'email'],
+});
+
+export const googleWorkspaceServiceAccount = PieceAuth.CustomAuth({
+ displayName: 'Service Account (Domain-Wide Delegation)',
+ description: serviceAccountInstructions,
+ required: true,
+ props: {
+ clientEmail: Property.ShortText({
+ displayName: 'Service Account E-mail',
+ description:
+ 'The `client_email` of the key file, e.g. `[email protected]`.',
+ required: true,
+ }),
+ privateKey: PieceAuth.SecretText({
+ displayName: 'Private Key',
+ description:
+ 'The `private_key` of the key file: the whole PEM block from `-----BEGIN PRIVATE KEY-----` to `-----END PRIVATE KEY-----`. Line breaks do not matter: the literal `\\n` of the JSON file, real newlines or a single line all work.',
+ required: true,
+ }),
+ adminEmail: Property.ShortText({
+ displayName: 'Administrator to Impersonate',
+ description:
+ "E-mail of a Workspace administrator in your domain. The service account acts with this user's admin role.",
+ required: true,
+ }),
+ },
+ validate: async ({ auth }) => validateServiceAccount(auth),
+});
+
+export const googleWorkspaceAuth = [googleWorkspaceOAuth2, googleWorkspaceServiceAccount];
diff --git a/packages/pieces/community/google-workspace/src/lib/common/activity-trigger.ts b/packages/pieces/community/google-workspace/src/lib/common/activity-trigger.ts
new file mode 100644
index 00000000000..426c94b2b0b
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/common/activity-trigger.ts
@@ -0,0 +1,598 @@
+import { randomUUID } from 'node:crypto';
+
+import { HttpMethod } from '@activepieces/pieces-common';
+import {
+ createTrigger,
+ DEDUPE_KEY_PROPERTY,
+ TriggerStrategy,
+ WebhookRenewStrategy,
+} from '@activepieces/pieces-framework';
+import type {
+ ActionClassification,
+ AiMetadata,
+ InputPropertyMap,
+ StaticPropsValue,
+ Store,
+} from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { activityEventOutputSchema } from '../output-schemas';
+import { googleWorkspaceClient } from './client';
+import { googleWorkspaceUtils } from './utils';
+
+import type {
+ GoogleWorkspaceActivity,
+ GoogleWorkspaceActivityEvent,
+ GoogleWorkspaceActivityParameter,
+ GoogleWorkspaceActivityQuery,
+ GoogleWorkspaceAuthValue,
+ GoogleWorkspaceChannel,
+ GoogleWorkspaceChannelRequest,
+ GoogleWorkspaceResolvedAuth,
+} from './types';
+
+function createActivityTrigger<Props extends InputPropertyMap>(spec: ActivityTriggerSpec<Props>) {
+ const accepts = ({
+ event,
+ props,
+ }: {
+ event: GoogleWorkspaceActivityEvent;
+ props: StaticPropsValue<Props>;
+ }) => (spec.accept ? spec.accept({ event, props }) : true);
+
+ return createTrigger({
+ name: spec.name,
+ classification: spec.classification,
+ displayName: spec.displayName,
+ description: spec.description,
+ aiMetadata: spec.aiMetadata,
+ auth: googleWorkspaceAuth,
+ props: spec.props,
+ type: TriggerStrategy.WEBHOOK,
+ renewConfiguration: { strategy: WebhookRenewStrategy.CRON, cronExpression: CHANNEL_RENEW_CRON },
+ sampleData: SAMPLE_EVENT,
+ outputSchema: activityEventOutputSchema,
+
+ async onEnable(context) {
+ const keys = channelKeys(context.flows.current.version.id);
+ await context.store.delete(keys.disabled);
+ const stale = await context.store.get<StoredChannel>(keys.channel);
+ const failures = await stopChannels({
+ auth: context.auth,
+ store: context.store,
+ keys,
+ channels: [stale],
+ });
+ await clearStore({ store: context.store, keys });
+ warnOnUnstopped(failures);
+ await openChannel({
+ auth: context.auth,
+ query: spec.query(context.propsValue),
+ webhookUrl: context.webhookUrl,
+ store: context.store,
+ keys,
+ });
+ },
+
+ async onRenew(context) {
+ const keys = channelKeys(context.flows.current.version.id);
+ const current = await context.store.get<StoredChannel>(keys.channel);
+ const saved = await openChannel({
+ auth: context.auth,
+ query: current?.query ?? spec.query(context.propsValue),
+ webhookUrl: context.webhookUrl,
+ store: context.store,
+ keys,
+ replacing: current,
+ });
+ if (saved) {
+ failOnUnstopped(
+ await stopChannels({
+ auth: context.auth,
+ store: context.store,
+ keys,
+ channels: [current],
+ }),
+ );
+ }
+ },
+
+ async onDisable(context) {
+ const keys = channelKeys(context.flows.current.version.id);
+ await context.store.put(keys.disabled, true);
+ const current = await context.store.get<StoredChannel>(keys.channel);
+ failOnUnstopped(
+ await stopChannels({ auth: context.auth, store: context.store, keys, channels: [current] }),
+ );
+ await clearStore({ store: context.store, keys });
+ },
+
+ async run(context) {
+ const { headers, body } = context.payload;
+ const token = headerOf({ headers, name: 'x-goog-channel-token' });
+ if (
+ !token ||
+ headerOf({ headers, name: 'x-goog-resource-state' }) === 'sync' ||
+ !isActivity(body)
+ ) {
+ return [];
+ }
+ const keys = channelKeys(context.flows.current.version.id);
+ if (!(await isKnownToken({ store: context.store, keys, token, now: Date.now() }))) {
+ return [];
+ }
+ return flattenActivity(body)
+ .filter((event) => accepts({ event, props: context.propsValue }))
+ .map((event) => ({ ...event, [DEDUPE_KEY_PROPERTY]: event.id }));
+ },
+
+ async test(context) {
+ const query = spec.query(context.propsValue);
+ const activities = await reports.listActivities({
+ auth: await googleWorkspaceClient.resolveAuth(context.auth),
+ query: { ...query, maxResults: 50 },
+ });
+ const events = activities
+ .flatMap(flattenActivity)
+ .filter((event) => accepts({ event, props: context.propsValue }));
+ return events.slice(0, TEST_SAMPLE_SIZE);
+ },
+ });
+}
+
+function channelKeys(flowVersionId: string): ChannelKeys {
+ return {
+ channel: `${KEY_PREFIX}:channel:${flowVersionId}`,
+ pendingToken: `${KEY_PREFIX}:pending-token:${flowVersionId}`,
+ previousChannel: `${KEY_PREFIX}:previous-channel:${flowVersionId}`,
+ unstoppedChannels: `${KEY_PREFIX}:unstopped-channels:${flowVersionId}`,
+ disabled: `${KEY_PREFIX}:disabled:${flowVersionId}`,
+ };
+}
+
+async function isKnownToken({
+ store,
+ keys,
+ token,
+ now,
+}: {
+ store: Store;
+ keys: ChannelKeys;
+ token: string;
+ now: number;
+}): Promise<boolean> {
+ const current = await store.get<StoredChannel>(keys.channel);
+ if (current?.token === token) {
+ return true;
+ }
+ const pending = await store.get<string>(keys.pendingToken);
+ if (pending === token) {
+ return true;
+ }
+ const previous = await store.get<PreviousChannel>(keys.previousChannel);
+ return (
+ previous?.previousToken === token && now - previous.previousStoppedAt < IN_FLIGHT_WINDOW_MS
+ );
+}
+
+function headerOf({
+ headers,
+ name,
+}: {
+ headers: Record<string, string> | undefined;
+ name: string;
+}): string | undefined {
+ if (!headers) return undefined;
+ const wanted = name.toLowerCase();
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === wanted);
+ return entry?.[1];
+}
+
+async function openChannel({
+ auth,
+ query,
+ webhookUrl,
+ store,
+ keys,
+ replacing = null,
+}: {
+ auth: GoogleWorkspaceAuthValue | undefined;
+ query: GoogleWorkspaceActivityQuery;
+ webhookUrl: string;
+ store: Store;
+ keys: ChannelKeys;
+ replacing?: StoredChannel | null;
+}): Promise<boolean> {
+ const resolved = await googleWorkspaceClient.resolveAuth(auth);
+ const request = newChannelRequest({ address: webhookUrl });
+ await store.put(keys.pendingToken, request.token);
+ const channel = await watchOrRollback({
+ store,
+ keys,
+ token: request.token,
+ watch: () => reports.watch({ auth: resolved, query, channel: request }),
+ });
+ const opened: StoredChannel = {
+ ...channel,
+ id: channel.id ?? request.id,
+ token: request.token,
+ query,
+ };
+ const latest = await store.get<StoredChannel>(keys.channel);
+ if (!isSameChannel({ a: latest, b: replacing })) {
+ await deletePendingToken({ store, keys, token: request.token });
+ failOnUnstopped(await stopChannels({ auth, store, keys, channels: [opened] }));
+ return false;
+ }
+ if (replacing) {
+ const previous: PreviousChannel = {
+ previousToken: replacing.token,
+ previousStoppedAt: Date.now(),
+ };
+ await store.put(keys.previousChannel, previous);
+ }
+ await store.put(keys.channel, opened);
+ await deletePendingToken({ store, keys, token: request.token });
+ if (await store.get<boolean>(keys.disabled)) {
+ await store.delete(keys.channel);
+ await store.delete(keys.previousChannel);
+ failOnUnstopped(await stopChannels({ auth, store, keys, channels: [opened, replacing] }));
+ return false;
+ }
+ return true;
+}
+
+function isSameChannel({ a, b }: { a: StoredChannel | null; b: StoredChannel | null }): boolean {
+ return a?.id === b?.id && a?.token === b?.token;
+}
+
+async function deletePendingToken({
+ store,
+ keys,
+ token,
+}: {
+ store: Store;
+ keys: ChannelKeys;
+ token: string;
+}): Promise<void> {
+ if ((await store.get<string>(keys.pendingToken)) === token) {
+ await store.delete(keys.pendingToken);
+ }
+}
+
+async function watchOrRollback({
+ store,
+ keys,
+ token,
+ watch,
+}: {
+ store: Store;
+ keys: ChannelKeys;
+ token: string;
+ watch: () => Promise<GoogleWorkspaceChannel>;
+}): Promise<GoogleWorkspaceChannel> {
+ try {
+ return await watch();
+ } catch (error) {
+ await deletePendingToken({ store, keys, token });
+ throw error;
+ }
+}
+
+async function stopChannels({
+ auth,
+ store,
+ keys,
+ channels,
+}: {
+ auth: GoogleWorkspaceAuthValue | undefined;
+ store: Store;
+ keys: ChannelKeys;
+ channels: (StoredChannel | null)[];
+}): Promise<StopFailure[]> {
+ const leftover = (await store.get<ChannelRef[]>(keys.unstoppedChannels)) ?? [];
+ const targets = uniqueRefs([...channels.flatMap(toRef), ...leftover]);
+ const failures = await stopEach({ auth, targets });
+ if (failures.length === 0) {
+ if (leftover.length > 0) {
+ await store.delete(keys.unstoppedChannels);
+ }
+ return [];
+ }
+ await store.put(
+ keys.unstoppedChannels,
+ failures.map(({ channel }) => channel),
+ );
+ return failures;
+}
+
+function failOnUnstopped(failures: StopFailure[]): void {
+ if (failures.length > 0) {
+ throw new Error(unstoppedMessage(failures));
+ }
+}
+
+function warnOnUnstopped(failures: StopFailure[]): void {
+ if (failures.length > 0) {
+ console.warn(`${unstoppedMessage(failures)} The new channel was opened anyway.`);
+ }
+}
+
+function unstoppedMessage(failures: StopFailure[]): string {
+ const ids = failures.map(({ channel }) => channel.id).join(', ');
+ return `Could not stop the Google Workspace notification channel(s) ${ids}: ${
+ failures[0]?.reason ?? 'unknown error'
+ }. They are kept for another stop attempt the next time this trigger is enabled, renewed or disabled; either way Google expires them within 6 hours.`;
+}
+
+async function stopEach({
+ auth,
+ targets,
+}: {
+ auth: GoogleWorkspaceAuthValue | undefined;
+ targets: ChannelRef[];
+}): Promise<StopFailure[]> {
+ if (targets.length === 0) return [];
+ let resolved: GoogleWorkspaceResolvedAuth;
+ try {
+ resolved = await googleWorkspaceClient.resolveAuth(auth);
+ } catch (error) {
+ return targets.map((channel) => ({ channel, reason: describe(error) }));
+ }
+ const failures: StopFailure[] = [];
+ for (const channel of targets) {
+ try {
+ await reports.stop({ auth: resolved, channel });
+ } catch (error) {
+ if (!isGone(error)) {
+ failures.push({ channel, reason: describe(error) });
+ }
+ }
+ }
+ return failures;
+}
+
+function toRef(channel: StoredChannel | null): ChannelRef[] {
+ return channel?.resourceId ? [{ id: channel.id, resourceId: channel.resourceId }] : [];
+}
+
+function uniqueRefs(refs: ChannelRef[]): ChannelRef[] {
+ return refs.filter(
+ (ref, index) =>
+ refs.findIndex((other) => other.id === ref.id && other.resourceId === ref.resourceId) ===
+ index,
+ );
+}
+
+function isGone(error: unknown): boolean {
+ return error instanceof googleWorkspaceClient.ApiError && GONE_STATUSES.includes(error.status);
+}
+
+function describe(error: unknown): string {
+ return (error instanceof Error ? error.message : String(error)).slice(0, MAX_REASON_LENGTH);
+}
+
+async function clearStore({ store, keys }: { store: Store; keys: ChannelKeys }): Promise<void> {
+ await store.delete(keys.channel);
+ await store.delete(keys.pendingToken);
+ await store.delete(keys.previousChannel);
+}
+
+function newChannelRequest({
+ address,
+ now = Date.now(),
+}: {
+ address: string;
+ now?: number;
+}): GoogleWorkspaceChannelRequest {
+ return {
+ id: randomUUID(),
+ address,
+ token: randomUUID(),
+ expiration: now + CHANNEL_MAX_LIFETIME_MS,
+ };
+}
+
+function flattenActivity(activity: GoogleWorkspaceActivity): GoogleWorkspaceActivityEvent[] {
+ const events = activity.events ?? [];
+ const base = `${activity.id?.time ?? ''}:${activity.id?.uniqueQualifier ?? ''}`;
+ return events.map((event, index) => ({
+ id: events.length > 1 ? `${base}:${index}` : base,
+ time: activity.id?.time ?? null,
+ application: activity.id?.applicationName ?? null,
+ eventType: event.type ?? null,
+ eventName: event.name ?? null,
+ actor: {
+ email: activity.actor?.email ?? null,
+ profileId: activity.actor?.profileId ?? null,
+ callerType: activity.actor?.callerType ?? null,
+ },
+ ipAddress: activity.ipAddress ?? null,
+ ownerDomain: activity.ownerDomain ?? null,
+ parameters: Object.fromEntries(
+ (event.parameters ?? []).flatMap((p): [string, unknown][] =>
+ p.name ? [[p.name, parameterValue(p)]] : [],
+ ),
+ ),
+ activity,
+ }));
+}
+
+function isActivity(body: unknown): body is GoogleWorkspaceActivity {
+ return (
+ typeof body === 'object' && body !== null && 'events' in body && Array.isArray(body.events)
+ );
+}
+
+function activityPath({
+ query,
+ suffix = '',
+}: {
+ query: GoogleWorkspaceActivityQuery;
+ suffix?: string;
+}): string {
+ const userKey = encodeURIComponent((query.userKey ?? 'all').trim() || 'all');
+ return `${
+ googleWorkspaceUtils.reportsPath
+ }/activity/users/${userKey}/applications/${encodeURIComponent(query.application)}${suffix}`;
+}
+
+function queryParams(
+ query: GoogleWorkspaceActivityQuery,
+): Record<string, string | number | undefined> {
+ return {
+ eventName: query.eventName?.trim() || undefined,
+ filters: query.filters?.trim() || undefined,
+ startTime: query.startTime,
+ maxResults: query.maxResults,
+ };
+}
+
+function parameterValue(p: GoogleWorkspaceActivityParameter): unknown {
+ if (p.value !== undefined) return p.value;
+ if (p.intValue !== undefined) return p.intValue;
+ if (p.boolValue !== undefined) return p.boolValue;
+ if (p.multiValue !== undefined) return p.multiValue;
+ if (p.multiIntValue !== undefined) return p.multiIntValue;
+ if (p.messageValue !== undefined) return p.messageValue;
+ if (p.multiMessageValue !== undefined) return p.multiMessageValue;
+ return null;
+}
+
+async function listActivities({
+ auth,
+ query,
+}: {
+ auth: GoogleWorkspaceResolvedAuth;
+ query: GoogleWorkspaceActivityQuery;
+}): Promise<GoogleWorkspaceActivity[]> {
+ const { items } = await googleWorkspaceClient.listPage<GoogleWorkspaceActivity>({
+ auth,
+ path: activityPath({ query }),
+ itemsKey: 'items',
+ query: queryParams(query),
+ });
+ return items;
+}
+
+async function watch({
+ auth,
+ query,
+ channel,
+}: {
+ auth: GoogleWorkspaceResolvedAuth;
+ query: GoogleWorkspaceActivityQuery;
+ channel: GoogleWorkspaceChannelRequest;
+}): Promise<GoogleWorkspaceChannel> {
+ return await googleWorkspaceClient.request<GoogleWorkspaceChannel>({
+ auth,
+ method: HttpMethod.POST,
+ path: activityPath({ query, suffix: '/watch' }),
+ query: queryParams(query),
+ body: {
+ id: channel.id,
+ type: 'web_hook',
+ address: channel.address,
+ token: channel.token,
+ expiration: String(channel.expiration),
+ payload: true,
+ },
+ });
+}
+
+async function stop({
+ auth,
+ channel,
+}: {
+ auth: GoogleWorkspaceResolvedAuth;
+ channel: Pick<GoogleWorkspaceChannel, 'id' | 'resourceId'>;
+}): Promise<void> {
+ await googleWorkspaceClient.request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: 'admin/reports_v1/channels/stop',
+ body: { id: channel.id, resourceId: channel.resourceId },
+ });
+}
+
+const reports = { listActivities, watch, stop };
+
+const CHANNEL_MAX_LIFETIME_MS = (6 * 60 - 5) * 60 * 1000;
+const CHANNEL_RENEW_CRON = '0 */4 * * *';
+
+const SAMPLE_EVENT: GoogleWorkspaceActivityEvent = {
+ id: '2026-10-05T12:34:56.789Z:8721456339812',
+ time: '2026-10-05T12:34:56.789Z',
+ application: 'admin',
+ eventType: 'USER_SETTINGS',
+ eventName: 'CREATE_USER',
+ actor: { email: '[email protected]', profileId: '104938271650192837465', callerType: 'USER' },
+ ipAddress: '203.0.113.10',
+ ownerDomain: 'example.com',
+ parameters: { USER_EMAIL: '[email protected]' },
+ activity: {
+ kind: 'admin#reports#activity',
+ id: {
+ time: '2026-10-05T12:34:56.789Z',
+ uniqueQualifier: '8721456339812',
+ applicationName: 'admin',
+ customerId: 'C01abcd2e',
+ },
+ actor: { email: '[email protected]', profileId: '104938271650192837465', callerType: 'USER' },
+ ownerDomain: 'example.com',
+ ipAddress: '203.0.113.10',
+ events: [
+ {
+ type: 'USER_SETTINGS',
+ name: 'CREATE_USER',
+ parameters: [{ name: 'USER_EMAIL', value: '[email protected]' }],
+ },
+ ],
+ },
+};
+
+const KEY_PREFIX = 'google-workspace';
+const GONE_STATUSES = [404, 410];
+const MAX_REASON_LENGTH = 300;
+const TEST_SAMPLE_SIZE = 10;
+const IN_FLIGHT_WINDOW_MS = 2 * 60 * 1000;
+
+export const googleWorkspaceActivityTrigger = {
+ create: createActivityTrigger,
+ reports,
+ newChannelRequest,
+ flattenActivity,
+ isActivity,
+ sampleEvent: SAMPLE_EVENT,
+ channelMaxLifetimeMs: CHANNEL_MAX_LIFETIME_MS,
+ renewCron: CHANNEL_RENEW_CRON,
+};
+
+type StoredChannel = GoogleWorkspaceChannel & {
+ token: string;
+ query: GoogleWorkspaceActivityQuery;
+};
+type PreviousChannel = { previousToken: string; previousStoppedAt: number };
+type ChannelKeys = {
+ channel: string;
+ pendingToken: string;
+ previousChannel: string;
+ unstoppedChannels: string;
+ disabled: string;
+};
+type ChannelRef = Pick<GoogleWorkspaceChannel, 'id' | 'resourceId'>;
+type StopFailure = { channel: ChannelRef; reason: string };
+
+type ActivityTriggerSpec<Props extends InputPropertyMap> = {
+ name: string;
+ classification: ActionClassification;
+ displayName: string;
+ description: string;
+ aiMetadata: AiMetadata;
+ props: Props;
+ query: (props: StaticPropsValue<Props>) => GoogleWorkspaceActivityQuery;
+ accept?: (params: {
+ event: GoogleWorkspaceActivityEvent;
+ props: StaticPropsValue<Props>;
+ }) => boolean;
+};
diff --git a/packages/pieces/community/google-workspace/src/lib/common/api.ts b/packages/pieces/community/google-workspace/src/lib/common/api.ts
new file mode 100644
index 00000000000..8b56a8060e5
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/common/api.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+
+import { googleWorkspaceClient } from './client';
+import { googleWorkspaceUtils } from './utils';
+
+import type { GoogleWorkspaceResolvedAuth, GoogleWorkspaceResourceDefinition } from './types';
+
+async function resolveIdentifier({
+ def,
+ auth,
+ id,
+}: {
+ def: GoogleWorkspaceResourceDefinition;
+ auth: GoogleWorkspaceResolvedAuth;
+ id: string;
+}): Promise<string> {
+ if (def.type === 'org_unit' && googleWorkspaceUtils.isRootOrgUnitPath(id)) {
+ return await rootOrgUnitId(auth);
+ }
+ return id;
+}
+
+async function rootOrgUnitId(auth: GoogleWorkspaceResolvedAuth): Promise<string> {
+ const response = await googleWorkspaceClient.request<{
+ organizationUnits?: { orgUnitId?: unknown; orgUnitPath?: unknown }[];
+ }>({
+ auth,
+ method: HttpMethod.GET,
+ path: googleWorkspaceUtils.resources.org_unit.collectionPath(),
+ query: { type: 'allIncludingParent' },
+ });
+ const units = response.organizationUnits;
+ const rootId = (Array.isArray(units) ? units : []).find(
+ (unit) => typeof unit === 'object' && unit !== null && unit.orgUnitPath === '/',
+ )?.orgUnitId;
+ if (typeof rootId !== 'string' || rootId === '') {
+ throw new Error(
+ 'Could not read the ID of the root organizational unit (/) from Google. Use its ID (id:...) instead of /.',
+ );
+ }
+ return rootId;
+}
+
+export const googleWorkspaceApi = { resolveIdentifier };
diff --git a/packages/pieces/community/google-workspace/src/lib/common/client.ts b/packages/pieces/community/google-workspace/src/lib/common/client.ts
new file mode 100644
index 00000000000..1b8fc9f1d5c
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/common/client.ts
@@ -0,0 +1,582 @@
+import { createHash, createSign } from 'node:crypto';
+
+import { HttpMethod } from '@activepieces/pieces-common';
+import { AppConnectionType } from '@activepieces/pieces-framework';
+
+import type {
+ GoogleWorkspaceAuthValue,
+ GoogleWorkspaceErrorDetail,
+ GoogleWorkspaceListPage,
+ GoogleWorkspaceQuery,
+ GoogleWorkspaceResolvedAuth,
+ GoogleWorkspaceServiceAccount,
+} from './types';
+
+class GoogleWorkspaceApiError extends Error {
+ readonly status: number;
+ readonly googleStatus: string | undefined;
+ readonly errors: GoogleWorkspaceErrorDetail[];
+
+ constructor({ status, googleStatus, errors, summary }: GoogleWorkspaceApiErrorParams) {
+ super(summary);
+ this.name = 'GoogleWorkspaceApiError';
+ this.status = status;
+ this.googleStatus = googleStatus;
+ this.errors = errors;
+ }
+
+ static fromResponse({ status, text }: { status: number; text: string }): GoogleWorkspaceApiError {
+ const parsed = parseErrorBody(text);
+
+ const errors: GoogleWorkspaceErrorDetail[] = (parsed.error?.errors ?? []).map((e) => ({
+ reason: e.reason ?? 'unknown',
+ message: e.message ?? '',
+ ...(e.domain ? { domain: e.domain } : {}),
+ ...(e.location ? { location: e.location } : {}),
+ }));
+
+ const googleStatus = parsed.error?.status;
+ const head = `Google Workspace API returned ${status}${
+ googleStatus ? ` (${googleStatus})` : ''
+ }`;
+ const detail =
+ errors.length > 0
+ ? errors
+ .map((e) => `${e.reason}: ${e.message}${e.location ? ` [${e.location}]` : ''}`)
+ .join('; ')
+ : parsed.error?.message ?? rawBodySummary(safeJson(text));
+
+ return new GoogleWorkspaceApiError({
+ status,
+ googleStatus,
+ errors,
+ summary: `${head}: ${detail}${hintFor({ status, errors })}`,
+ });
+ }
+
+ hasReason(reason: string): boolean {
+ return this.errors.some((e) => e.reason === reason);
+ }
+}
+
+function baseUrl(): string {
+ return GOOGLE_ADMIN_API_ROOT;
+}
+
+async function request<T>({
+ auth,
+ method,
+ path,
+ query,
+ body,
+ timeoutMs,
+}: RequestParams & { auth: GoogleWorkspaceResolvedAuth }): Promise<T> {
+ const response = await send({
+ url: requestUrl({ path, query }),
+ method,
+ token: auth.access_token,
+ body,
+ timeoutMs,
+ });
+ if (!response.ok) {
+ throw GoogleWorkspaceApiError.fromResponse({ status: response.status, text: response.text });
+ }
+ return parseSuccessBody<T>({ status: response.status, text: response.text });
+}
+
+async function listPage<T>({
+ auth,
+ path,
+ itemsKey,
+ query = {},
+}: ListPageParams & { auth: GoogleWorkspaceResolvedAuth }): Promise<GoogleWorkspaceListPage<T>> {
+ const body = await request<ListResponse<T>>({ auth, method: HttpMethod.GET, path, query });
+ const rawItems = body[itemsKey];
+ const items = Array.isArray(rawItems) ? rawItems : [];
+ const rawToken = body['nextPageToken'];
+ const nextPageToken = typeof rawToken === 'string' ? rawToken : undefined;
+ return { items, ...(nextPageToken ? { nextPageToken } : {}) };
+}
+
+async function listAll<T>({
+ auth,
+ path,
+ itemsKey,
+ query = {},
+ maxRows = 2000,
+}: ListPageParams & { auth: GoogleWorkspaceResolvedAuth; maxRows?: number }): Promise<{
+ items: T[];
+ truncated: boolean;
+}> {
+ const items: T[] = [];
+ let pageToken: string | undefined;
+ do {
+ const page = await listPage<T>({ auth, path, itemsKey, query: { ...query, pageToken } });
+ for (const item of page.items) {
+ if (items.length >= maxRows) {
+ return { items, truncated: true };
+ }
+ items.push(item);
+ }
+ pageToken = page.nextPageToken;
+ if (items.length >= maxRows) {
+ return { items, truncated: Boolean(pageToken) };
+ }
+ } while (pageToken);
+ return { items, truncated: false };
+}
+
+async function resolveAuth(
+ auth: GoogleWorkspaceAuthValue | undefined,
+): Promise<GoogleWorkspaceResolvedAuth> {
+ if (!auth) {
+ throw new Error('A Google Workspace connection is required.');
+ }
+ if (auth.type === AppConnectionType.CUSTOM_AUTH) {
+ return { access_token: await mintServiceAccountToken({ creds: auth.props, scopes: SCOPES }) };
+ }
+ if (!auth.access_token) {
+ throw new Error('The Google Workspace connection has no access token; reconnect it.');
+ }
+ return { access_token: auth.access_token };
+}
+
+function normalizePrivateKey(value: string): string {
+ const text = String(value ?? '')
+ .trim()
+ .replace(/^"|"$/g, '')
+ .replace(/\\n/g, '\n');
+ const match = PEM_SHAPE.exec(text);
+ if (!match) {
+ throw new Error(PEM_ERROR);
+ }
+ const [, label, rawBody] = match;
+ const body = (rawBody ?? '').replace(/\s+/g, '');
+ if (body.length === 0 || !/^[A-Za-z0-9+/=]+$/.test(body)) {
+ throw new Error(PEM_ERROR);
+ }
+ const lines = body.match(/.{1,64}/g) ?? [];
+ return `-----BEGIN ${label}-----\n${lines.join('\n')}\n-----END ${label}-----\n`;
+}
+
+function buildAssertion({
+ creds,
+ scopes,
+ now = Math.floor(Date.now() / 1000),
+}: {
+ creds: GoogleWorkspaceServiceAccount;
+ scopes: string[];
+ now?: number;
+}): string {
+ const header = base64Url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
+ const claims = base64Url(
+ JSON.stringify({
+ iss: creds.clientEmail.trim(),
+ sub: creds.adminEmail.trim(),
+ scope: scopes.join(' '),
+ aud: GOOGLE_TOKEN_URL,
+ iat: now,
+ exp: now + JWT_LIFETIME_SECONDS,
+ }),
+ );
+ const input = `${header}.${claims}`;
+ let signature: string;
+ try {
+ signature = createSign('RSA-SHA256')
+ .update(input)
+ .end()
+ .sign(normalizePrivateKey(creds.privateKey), 'base64url');
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith('The private key must be')) throw error;
+ throw new Error(
+ `The private key could not be read (${
+ error instanceof Error ? error.message : String(error)
+ }). Paste the whole private_key value of the service account key file.`,
+ );
+ }
+ return `${input}.${signature}`;
+}
+
+async function mintServiceAccountToken({
+ creds,
+ scopes,
+}: {
+ creds: GoogleWorkspaceServiceAccount;
+ scopes: string[];
+}): Promise<string> {
+ const cacheKey = tokenCacheKey({ creds, scopes });
+ const now = Math.floor(Date.now() / 1000);
+ const cached = readCachedToken({ key: cacheKey, now });
+ if (cached) {
+ return cached;
+ }
+
+ const { status, body } = await requestToken(
+ new URLSearchParams({
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
+ assertion: buildAssertion({ creds, scopes, now }),
+ }).toString(),
+ );
+
+ if (status < 200 || status >= 300) {
+ throw new Error(describeTokenError({ status, body }));
+ }
+ if (!body.access_token) {
+ throw new Error(
+ `Google token endpoint returned no access token${
+ body.error ? ` (${body.error}: ${body.error_description ?? ''})` : ''
+ }.`,
+ );
+ }
+ writeCachedToken({
+ key: cacheKey,
+ token: {
+ accessToken: body.access_token,
+ expiresAt: now + (body.expires_in ?? JWT_LIFETIME_SECONDS),
+ },
+ now,
+ });
+ return body.access_token;
+}
+
+function clearTokenCache(): void {
+ tokenCache.clear();
+}
+
+function cachedTokenCount(): number {
+ return tokenCache.size;
+}
+
+function hintFor({
+ status,
+ errors,
+}: {
+ status: number;
+ errors: GoogleWorkspaceErrorDetail[];
+}): string {
+ const reasons = new Set(errors.map((e) => e.reason));
+ if (status === 403 && reasons.has('accessNotConfigured')) {
+ return ' Enable the Admin SDK API in the Google Cloud project that owns the OAuth client or service account.';
+ }
+ if (status === 403 && (reasons.has('forbidden') || reasons.has('insufficientPermissions'))) {
+ return ' The connected account lacks the admin privilege or the OAuth scope for this call; reconnect granting every scope, or use an account with the right admin role.';
+ }
+ if (status === 404) {
+ return ' Check the identifier: user and group keys are e-mails or ids, org units are paths, devices use their resource id.';
+ }
+ if (status === 409) {
+ return ' A record with that key already exists.';
+ }
+ return '';
+}
+
+function rawBodySummary(body: unknown): string {
+ if (typeof body !== 'string') return JSON.stringify(body ?? null);
+ if (/^\s*<(!doctype|html)/i.test(body)) {
+ const title = /<title>([^<]*)<\/title>/i.exec(body)?.[1]?.trim();
+ const url = /<code>([^<]*)<\/code>/i.exec(body)?.[1]?.trim();
+ return `${title ?? 'HTML error page'}${
+ url ? ` for ${url}` : ''
+ } (the request URL is malformed, usually an empty identifier).`;
+ }
+ return body.length > 500 ? `${body.slice(0, 500)}...` : body;
+}
+
+function safeJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+function parseErrorBody(text: string): GoogleErrorBody {
+ const body = safeJson(text);
+ if (
+ typeof body !== 'object' ||
+ body === null ||
+ !('error' in body) ||
+ typeof body.error !== 'object' ||
+ body.error === null
+ ) {
+ return {};
+ }
+ const error: GoogleErrorPayload = body.error;
+ return {
+ error: {
+ message: optionalString(error.message),
+ status: optionalString(error.status),
+ errors: Array.isArray(error.errors) ? error.errors.map(toGoogleErrorEntry) : undefined,
+ },
+ };
+}
+
+function toGoogleErrorEntry(entry: unknown): GoogleErrorEntry {
+ if (typeof entry !== 'object' || entry === null) {
+ return {};
+ }
+ const fields: GoogleErrorPayload = entry;
+ return {
+ domain: optionalString(fields.domain),
+ reason: optionalString(fields.reason),
+ message: optionalString(fields.message),
+ location: optionalString(fields.location),
+ };
+}
+
+function optionalString(value: unknown): string | undefined {
+ return typeof value === 'string' ? value : undefined;
+}
+
+function requestUrl({
+ path,
+ query,
+}: {
+ path: string;
+ query: GoogleWorkspaceQuery | undefined;
+}): string {
+ const url = new URL(`${GOOGLE_ADMIN_API_ROOT}/${path.replace(/^\//, '')}`);
+ for (const [key, value] of Object.entries(query ?? {})) {
+ if (value !== undefined && value !== '') {
+ url.searchParams.set(key, String(value));
+ }
+ }
+ return url.toString();
+}
+
+async function send({ url, method, token, body, timeoutMs }: SendParams): Promise<RawResponse> {
+ const payload = body === undefined ? undefined : JSON.stringify(body);
+ try {
+ const response = await fetch(url, {
+ method,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ ...(payload === undefined ? {} : { 'Content-Type': 'application/json' }),
+ },
+ ...(payload === undefined ? {} : { body: payload }),
+ signal: AbortSignal.timeout(requestTimeout(timeoutMs)),
+ });
+ return { status: response.status, ok: response.ok, text: await response.text() };
+ } catch (error) {
+ const reason = error instanceof Error ? error.name : 'unknown error';
+ throw new Error(`Could not reach the Google Workspace API (${reason}). Try again in a moment.`);
+ }
+}
+
+function requestTimeout(timeoutMs: number | undefined): number {
+ if (timeoutMs === undefined) return REQUEST_TIMEOUT_MS;
+ return Math.min(REQUEST_TIMEOUT_MS, Math.max(1, Math.ceil(timeoutMs)));
+}
+
+function parseSuccessBody<T>({ status, text }: { status: number; text: string }): T {
+ const source = text.trim() === '' ? EMPTY_JSON_BODY : text;
+ try {
+ return JSON.parse(source);
+ } catch {
+ throw new GoogleWorkspaceApiError({
+ status,
+ googleStatus: undefined,
+ errors: [],
+ summary: `Google Workspace API returned ${status} with a response that is not JSON.`,
+ });
+ }
+}
+
+function tokenCacheKey({
+ creds,
+ scopes,
+}: {
+ creds: GoogleWorkspaceServiceAccount;
+ scopes: string[];
+}): string {
+ const keyHash = createHash('sha256').update(normalizePrivateKey(creds.privateKey)).digest('hex');
+ return [creds.clientEmail.trim(), creds.adminEmail.trim(), keyHash, scopes.join(' ')].join('|');
+}
+
+function base64Url(input: string | Buffer): string {
+ return Buffer.from(input).toString('base64url');
+}
+
+async function requestToken(form: string): Promise<{ status: number; body: TokenResponse }> {
+ let response: Response;
+ try {
+ response = await fetch(GOOGLE_TOKEN_URL, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
+ body: form,
+ signal: AbortSignal.timeout(TOKEN_REQUEST_TIMEOUT_MS),
+ });
+ } catch (error) {
+ const reason = error instanceof Error ? error.name : 'unknown error';
+ throw new Error(
+ `Could not reach the Google token endpoint (${reason}). Try again in a moment.`,
+ );
+ }
+ let parsed: unknown;
+ try {
+ parsed = await response.json();
+ } catch {
+ parsed = undefined;
+ }
+ return { status: response.status, body: toTokenResponse(parsed) };
+}
+
+function toTokenResponse(value: unknown): TokenResponse {
+ if (typeof value !== 'object' || value === null) return {};
+ const record: Record<string, unknown> = { ...value };
+ return {
+ access_token: stringField(record['access_token']),
+ expires_in: typeof record['expires_in'] === 'number' ? record['expires_in'] : undefined,
+ error: stringField(record['error']),
+ error_description: stringField(record['error_description']),
+ };
+}
+
+function stringField(value: unknown): string | undefined {
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+}
+
+function describeTokenError({ status, body }: { status: number; body: TokenResponse }): string {
+ if (!body.error) {
+ return `Google token endpoint returned ${status}.`;
+ }
+ const hint =
+ body.error === 'unauthorized_client'
+ ? " Check that domain-wide delegation is authorized in the Admin console for this service account's client ID with exactly the scopes the connection lists."
+ : body.error === 'invalid_grant'
+ ? ' Check the administrator e-mail (it must exist in your domain) and the server clock.'
+ : '';
+ return `Google rejected the service account (${body.error}): ${
+ body.error_description ?? ''
+ }${hint}`.trim();
+}
+
+function readCachedToken({ key, now }: { key: string; now: number }): string | undefined {
+ sweepExpiredTokens(now);
+ return tokenCache.get(key)?.accessToken;
+}
+
+function writeCachedToken({
+ key,
+ token,
+ now,
+}: {
+ key: string;
+ token: CachedToken;
+ now: number;
+}): void {
+ sweepExpiredTokens(now);
+ tokenCache.delete(key);
+ tokenCache.set(key, token);
+ for (const oldest of tokenCache.keys()) {
+ if (tokenCache.size <= MAX_CACHED_TOKENS) break;
+ tokenCache.delete(oldest);
+ }
+}
+
+function sweepExpiredTokens(now: number): void {
+ for (const [key, token] of tokenCache) {
+ if (token.expiresAt - REFRESH_MARGIN_SECONDS <= now) {
+ tokenCache.delete(key);
+ }
+ }
+}
+
+const SCOPES = [
+ 'https://www.googleapis.com/auth/admin.directory.user',
+ 'https://www.googleapis.com/auth/admin.directory.group',
+ 'https://www.googleapis.com/auth/admin.directory.group.member',
+ 'https://www.googleapis.com/auth/admin.directory.orgunit',
+ 'https://www.googleapis.com/auth/admin.directory.device.mobile',
+ 'https://www.googleapis.com/auth/admin.directory.device.chromeos',
+ 'https://www.googleapis.com/auth/admin.directory.rolemanagement',
+ 'https://www.googleapis.com/auth/admin.directory.userschema.readonly',
+ 'https://www.googleapis.com/auth/admin.datatransfer',
+ 'https://www.googleapis.com/auth/admin.reports.audit.readonly',
+];
+const GOOGLE_ADMIN_API_ROOT = 'https://admin.googleapis.com';
+const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';
+const REQUEST_TIMEOUT_MS = 60_000;
+const EMPTY_JSON_BODY = '{}';
+const JWT_LIFETIME_SECONDS = 3600;
+const REFRESH_MARGIN_SECONDS = 300;
+const TOKEN_REQUEST_TIMEOUT_MS = 30_000;
+const MAX_CACHED_TOKENS = 100;
+const PEM_SHAPE = /-----BEGIN ([A-Z ]*PRIVATE KEY)-----([\s\S]*?)-----END \1-----/;
+const PEM_ERROR =
+ 'The private key must be the PEM block from the service account key file (-----BEGIN PRIVATE KEY----- to -----END PRIVATE KEY-----).';
+const tokenCache = new Map<string, CachedToken>();
+
+export const googleWorkspaceClient = {
+ baseUrl,
+ request,
+ listPage,
+ listAll,
+ resolveAuth,
+ mintServiceAccountToken,
+ normalizePrivateKey,
+ buildAssertion,
+ clearTokenCache,
+ cachedTokenCount,
+ ApiError: GoogleWorkspaceApiError,
+ scopes: SCOPES,
+ tokenUrl: GOOGLE_TOKEN_URL,
+};
+
+type RequestParams = {
+ method: HttpMethod;
+ path: string;
+ query?: GoogleWorkspaceQuery;
+ body?: unknown;
+ timeoutMs?: number;
+};
+
+type ListPageParams = { path: string; itemsKey: string; query?: GoogleWorkspaceQuery };
+
+type SendParams = {
+ url: string;
+ method: HttpMethod;
+ token: string;
+ body: unknown;
+ timeoutMs: number | undefined;
+};
+
+type RawResponse = { status: number; ok: boolean; text: string };
+
+type GoogleErrorEntry = { domain?: string; reason?: string; message?: string; location?: string };
+
+type GoogleErrorPayload = {
+ message?: unknown;
+ status?: unknown;
+ errors?: unknown;
+ domain?: unknown;
+ reason?: unknown;
+ location?: unknown;
+};
+
+type GoogleErrorBody = {
+ error?: {
+ message?: string;
+ status?: string;
+ errors?: GoogleErrorEntry[];
+ };
+};
+
+type ListResponse<T> = Record<string, T[] | string | undefined>;
+
+type GoogleWorkspaceApiErrorParams = {
+ status: number;
+ googleStatus: string | undefined;
+ errors: GoogleWorkspaceErrorDetail[];
+ summary: string;
+};
+
+type TokenResponse = {
+ access_token?: string;
+ expires_in?: number;
+ error?: string;
+ error_description?: string;
+};
+
+type CachedToken = { accessToken: string; expiresAt: number };
diff --git a/packages/pieces/community/google-workspace/src/lib/common/props.ts b/packages/pieces/community/google-workspace/src/lib/common/props.ts
new file mode 100644
index 00000000000..9557772f761
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/common/props.ts
@@ -0,0 +1,239 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, tryCatch } from '@activepieces/pieces-framework';
+import type { DropdownState, DynamicPropsValue } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceAuth } from '../auth';
+import { googleWorkspaceClient } from './client';
+import { googleWorkspaceUtils } from './utils';
+
+import type {
+ GoogleWorkspaceAuthValue,
+ GoogleWorkspaceCustomSchema,
+ GoogleWorkspaceRecordField,
+ GoogleWorkspaceRecordMode,
+ GoogleWorkspaceTransferApplication,
+ GoogleWorkspaceVerb,
+} from './types';
+
+function resourceType({ verb }: { verb: GoogleWorkspaceVerb }) {
+ return Property.StaticDropdown<string, true>({
+ displayName: 'Resource Type',
+ description: 'Which kind of record. Only the types this action supports are listed.',
+ required: true,
+ options: {
+ options: googleWorkspaceUtils.resourceTypeOptions.filter((option) =>
+ googleWorkspaceUtils.resources[option.value].verbs.includes(verb),
+ ),
+ },
+ });
+}
+
+function identifier<R extends boolean>({
+ required,
+ displayName = 'Record Identifier',
+ description = Object.values(googleWorkspaceUtils.resources)
+ .map((def) => `**${def.label}**: ${def.idHint}`)
+ .join(' · '),
+}: PropParams<R>) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+function parent<R extends boolean>({
+ required,
+ displayName = 'Parent Record',
+ description = Object.values(googleWorkspaceUtils.resources)
+ .filter((def) => def.parentLabel)
+ .map((def) => `Only for **${def.label}**: the ${def.parentLabel}.`)
+ .join(' '),
+}: PropParams<R>) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+function record<R extends boolean>({
+ required,
+ displayName = 'Extra Fields (JSON)',
+ description = `Optional. Any other field in the Directory API shape of the resource type (camelCase); the Fields above win on conflicts. Examples: ${createExamples()}`,
+}: PropParams<R>) {
+ return Property.Json({ displayName, description, required });
+}
+
+function recordFields<R extends boolean>({
+ required,
+ mode,
+ displayName = 'Fields',
+ description = mode === 'create'
+ ? 'The fields of the new record. They change with the Resource Type.'
+ : 'Only the fields you fill in are changed; empty fields keep their current value.',
+}: PropParams<R> & { mode: GoogleWorkspaceRecordMode }) {
+ return Property.DynamicProperties({
+ auth: googleWorkspaceAuth,
+ displayName,
+ description,
+ required,
+ refreshers: ['resourceType'],
+ props: async ({ auth, resourceType }): Promise<DynamicPropsValue> => {
+ if (typeof resourceType !== 'string' || !googleWorkspaceUtils.isResourceType(resourceType)) {
+ return {};
+ }
+ const def = googleWorkspaceUtils.resources[resourceType];
+ const standard = (def.fields ?? []).map((field) => [field.key, fieldInput({ field, mode })]);
+ const custom = resourceType === 'user' && auth ? await customUserFieldInputs(auth) : [];
+ return Object.fromEntries([...standard, ...custom]);
+ },
+ });
+}
+
+function fieldInput({
+ field,
+ mode,
+}: {
+ field: GoogleWorkspaceRecordField;
+ mode: GoogleWorkspaceRecordMode;
+}) {
+ const base = {
+ displayName: field.displayName,
+ description: field.description,
+ required: mode === 'create' && field.requiredOnCreate === true,
+ };
+ if (field.kind === 'checkbox') {
+ return Property.Checkbox(base);
+ }
+ if (field.kind === 'dropdown') {
+ return Property.StaticDropdown({
+ ...base,
+ options: {
+ options: (field.options ?? []).map((option) => ({ label: option, value: option })),
+ },
+ });
+ }
+ return Property.ShortText(base);
+}
+
+async function customUserFieldInputs(
+ auth: GoogleWorkspaceAuthValue,
+): Promise<[string, DynamicPropsValue[string]][]> {
+ const { data: response } = await tryCatch(async () =>
+ googleWorkspaceClient.request<{ schemas?: GoogleWorkspaceCustomSchema[] }>({
+ auth: await googleWorkspaceClient.resolveAuth(auth),
+ method: HttpMethod.GET,
+ path: `${googleWorkspaceUtils.directoryPath}/customer/${googleWorkspaceUtils.myCustomer}/schemas`,
+ }),
+ );
+ return (response?.schemas ?? []).flatMap((schema) =>
+ (schema.fields ?? []).map((field): [string, DynamicPropsValue[string]] => [
+ googleWorkspaceUtils.customFieldKey({
+ schemaName: schema.schemaName,
+ fieldName: field.fieldName,
+ }),
+ customFieldInput({ schema, field }),
+ ]),
+ );
+}
+
+function customFieldInput({
+ schema,
+ field,
+}: {
+ schema: GoogleWorkspaceCustomSchema;
+ field: NonNullable<GoogleWorkspaceCustomSchema['fields']>[number];
+}) {
+ const displayName = `${schema.displayName ?? schema.schemaName}: ${
+ field.displayName ?? field.fieldName
+ }`;
+ const description = `Custom field (${field.fieldType ?? 'STRING'}).${
+ field.multiValued ? ' Several values: add one item each.' : ''
+ }`;
+ if (field.multiValued) {
+ return Property.Array({ displayName, description, required: false });
+ }
+ if (field.fieldType === 'BOOL') {
+ return Property.Checkbox({ displayName, description, required: false });
+ }
+ if (field.fieldType === 'INT64' || field.fieldType === 'DOUBLE') {
+ return Property.Number({ displayName, description, required: false });
+ }
+ return Property.ShortText({ displayName, description, required: false });
+}
+
+function applicationId<R extends boolean>({
+ required,
+ displayName = 'Application',
+ description = "Which application's data to transfer. The label lists the parameters the application accepts.",
+}: PropParams<R>) {
+ return Property.Dropdown<string, R, typeof googleWorkspaceAuth>({
+ displayName,
+ description,
+ required,
+ auth: googleWorkspaceAuth,
+ refreshers: [],
+ options: async ({ auth }) => await applicationOptions(auth),
+ });
+}
+
+async function applicationOptions(
+ auth: GoogleWorkspaceAuthValue | undefined,
+): Promise<DropdownState<string>> {
+ if (!auth) {
+ return disabledOptions({
+ placeholder: 'Please select an existing or create a new connection.',
+ });
+ }
+ try {
+ const { items: applications } =
+ await googleWorkspaceClient.listAll<GoogleWorkspaceTransferApplication>({
+ auth: await googleWorkspaceClient.resolveAuth(auth),
+ path: `${googleWorkspaceUtils.dataTransferPath}/applications`,
+ itemsKey: 'applications',
+ query: { customerId: googleWorkspaceUtils.myCustomer, maxResults: 100 },
+ maxRows: 500,
+ });
+ if (applications.length === 0) {
+ return disabledOptions({
+ placeholder: 'No application supports data transfer in this account.',
+ });
+ }
+ return {
+ disabled: false,
+ options: applications.map((app) => ({ label: labelFor(app), value: String(app.id) })),
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return disabledOptions({
+ placeholder: `An error occurred while listing the transferable applications: ${detail.slice(
+ 0,
+ 300,
+ )}`,
+ });
+ }
+}
+
+function labelFor(app: GoogleWorkspaceTransferApplication): string {
+ const params = (app.transferParams ?? []).map((p) => `${p.key}: ${p.value.join('|')}`).join(', ');
+ return params ? `${app.name} (${params})` : app.name;
+}
+
+function createExamples(): string {
+ return Object.values(googleWorkspaceUtils.resources)
+ .filter((def) => def.createExample)
+ .map((def) => `**${def.label}**: \`${JSON.stringify(def.createExample)}\``)
+ .join(' · ');
+}
+
+function disabledOptions({ placeholder }: { placeholder: string }): DropdownState<never> {
+ return { disabled: true, options: [], placeholder };
+}
+
+export const googleWorkspaceProps = {
+ resourceType,
+ identifier,
+ parent,
+ record,
+ recordFields,
+ applicationId,
+};
+
+export type PropParams<R extends boolean> = {
+ required: R;
+ displayName?: string;
+ description?: string;
+};
diff --git a/packages/pieces/community/google-workspace/src/lib/common/types.ts b/packages/pieces/community/google-workspace/src/lib/common/types.ts
new file mode 100644
index 00000000000..d81c9c5f5e5
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/common/types.ts
@@ -0,0 +1,161 @@
+import type { AppConnectionType } from '@activepieces/pieces-framework';
+
+export type GoogleWorkspaceServiceAccount = {
+ clientEmail: string;
+ privateKey: string;
+ adminEmail: string;
+};
+
+export type GoogleWorkspaceAuthValue =
+ | { type: AppConnectionType.OAUTH2; access_token: string }
+ | { type: AppConnectionType.CUSTOM_AUTH; props: GoogleWorkspaceServiceAccount };
+
+export type GoogleWorkspaceResolvedAuth = { access_token: string };
+
+export type GoogleWorkspaceQuery = Record<string, string | number | boolean | undefined>;
+
+export type GoogleWorkspaceListPage<T> = {
+ items: T[];
+ nextPageToken?: string;
+};
+
+export type GoogleWorkspaceErrorDetail = {
+ reason: string;
+ message: string;
+ domain?: string;
+ location?: string;
+};
+
+export type GoogleWorkspaceResourceType =
+ | 'user'
+ | 'group'
+ | 'group_member'
+ | 'org_unit'
+ | 'mobile_device'
+ | 'chromeos_device'
+ | 'role_assignment';
+
+export type GoogleWorkspaceVerb = 'get' | 'list' | 'create' | 'update' | 'delete';
+
+export type GoogleWorkspaceResourceDefinition = {
+ type: GoogleWorkspaceResourceType;
+ label: string;
+ collectionPath: (parent?: string) => string;
+ itemPath: (params: { id: string; parent?: string }) => string;
+ itemsKey: string;
+ idField: string;
+ idHint: string;
+ parentLabel?: string;
+ verbs: GoogleWorkspaceVerb[];
+ supportsQuery: boolean;
+ supportsDomain: boolean;
+ maxPageSize?: number;
+ createExample?: Record<string, unknown>;
+ extraListParams?: string[];
+ fields?: GoogleWorkspaceRecordField[];
+};
+
+export type GoogleWorkspaceRecordField = {
+ key: string;
+ path: string[];
+ displayName: string;
+ description?: string;
+ kind: 'text' | 'checkbox' | 'dropdown';
+ options?: string[];
+ requiredOnCreate?: boolean;
+};
+
+export type GoogleWorkspaceRecordMode = 'create' | 'update';
+
+export type GoogleWorkspaceCustomSchemaField = {
+ fieldName: string;
+ displayName?: string;
+ fieldType?: string;
+ multiValued?: boolean;
+};
+
+export type GoogleWorkspaceCustomSchema = {
+ schemaName: string;
+ displayName?: string;
+ fields?: GoogleWorkspaceCustomSchemaField[];
+};
+
+export type GoogleWorkspaceActivityQuery = {
+ application: string;
+ userKey?: string;
+ eventName?: string;
+ filters?: string;
+ startTime?: string;
+ maxResults?: number;
+};
+
+export type GoogleWorkspaceChannelRequest = {
+ id: string;
+ address: string;
+ token: string;
+ expiration: number;
+};
+
+export type GoogleWorkspaceChannel = {
+ id: string;
+ resourceId: string;
+ resourceUri?: string;
+ token?: string;
+ expiration?: string;
+};
+
+export type GoogleWorkspaceActivityParameter = {
+ name?: string;
+ value?: string;
+ intValue?: string;
+ boolValue?: boolean;
+ multiValue?: string[];
+ multiIntValue?: string[];
+ messageValue?: unknown;
+ multiMessageValue?: unknown[];
+};
+
+export type GoogleWorkspaceActivity = {
+ kind?: string;
+ id?: { time?: string; uniqueQualifier?: string; applicationName?: string; customerId?: string };
+ actor?: { email?: string; profileId?: string; callerType?: string; key?: string };
+ ownerDomain?: string;
+ ipAddress?: string;
+ events?: { type?: string; name?: string; parameters?: GoogleWorkspaceActivityParameter[] }[];
+};
+
+export type GoogleWorkspaceActivityEvent = {
+ id: string;
+ time: string | null;
+ application: string | null;
+ eventType: string | null;
+ eventName: string | null;
+ actor: { email: string | null; profileId: string | null; callerType: string | null };
+ ipAddress: string | null;
+ ownerDomain: string | null;
+ parameters: Record<string, unknown>;
+ activity: GoogleWorkspaceActivity;
+};
+
+export type GoogleWorkspaceTransferParam = { key: string; value: string[] };
+
+export type GoogleWorkspaceTransferApplication = {
+ id: string;
+ name: string;
+ transferParams?: GoogleWorkspaceTransferParam[];
+};
+
+export type GoogleWorkspaceApplicationDataTransfer = {
+ applicationId: string;
+ applicationTransferParams?: GoogleWorkspaceTransferParam[];
+ applicationTransferStatus?: string;
+};
+
+export type GoogleWorkspaceDataTransfer = {
+ id?: string;
+ oldOwnerUserId: string;
+ newOwnerUserId: string;
+ overallTransferStatusCode?: string;
+ requestTime?: string;
+ applicationDataTransfers?: GoogleWorkspaceApplicationDataTransfer[];
+};
diff --git a/packages/pieces/community/google-workspace/src/lib/common/utils.ts b/packages/pieces/community/google-workspace/src/lib/common/utils.ts
new file mode 100644
index 00000000000..b6678017f27
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/common/utils.ts
@@ -0,0 +1,535 @@
+import type {
+ GoogleWorkspaceRecordField,
+ GoogleWorkspaceResourceDefinition,
+ GoogleWorkspaceResourceType,
+ GoogleWorkspaceVerb,
+} from './types';
+
+function resourceDefinition(type: string): GoogleWorkspaceResourceDefinition {
+ if (!isResourceType(type)) {
+ throw new Error(
+ `Unknown resource type "${type}". Expected one of: ${Object.keys(RESOURCES).join(', ')}.`,
+ );
+ }
+ return RESOURCES[type];
+}
+
+function assertVerb({
+ def,
+ verb,
+}: {
+ def: GoogleWorkspaceResourceDefinition;
+ verb: GoogleWorkspaceVerb;
+}): void {
+ if (!def.verbs.includes(verb)) {
+ throw new Error(
+ `${
+ def.label
+ } records do not support "${verb}" through the Directory API (allowed: ${def.verbs.join(
+ ', ',
+ )}).`,
+ );
+ }
+}
+
+function idOf({
+ def,
+ item,
+}: {
+ def: GoogleWorkspaceResourceDefinition;
+ item: Record<string, unknown>;
+}): string | null {
+ const value = item[def.idField];
+ return value === undefined || value === null ? null : String(value);
+}
+
+function isRootOrgUnitPath(id: string): boolean {
+ return String(id ?? '').trim() === '/';
+}
+
+function parseRecord(value: unknown): Record<string, unknown> {
+ const parsed: unknown = typeof value === 'string' ? JSON.parse(value) : value;
+ if (!isPlainObject(parsed)) {
+ throw new Error('The record must be a JSON object.');
+ }
+ return parsed;
+}
+
+function stringValues(value: Record<string, unknown> | undefined): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries(value ?? {})
+ .filter(([, v]) => v !== undefined && v !== null && v !== '')
+ .map(([k, v]) => [k, String(v)]),
+ );
+}
+
+function assertCustomApiCallUrl(url: unknown): void {
+ if (typeof url !== 'string' || !(url.startsWith('http://') || url.startsWith('https://'))) {
+ return;
+ }
+ const allowed = new URL(GOOGLE_ADMIN_API_ROOT).origin;
+ let origin: string;
+ try {
+ origin = new URL(url).origin;
+ } catch {
+ throw new Error(
+ `The URL "${url}" is not valid. Use a path relative to ${GOOGLE_ADMIN_API_ROOT}, e.g. /${DIRECTORY_PATH}/users.`,
+ );
+ }
+ if (origin !== allowed) {
+ throw new Error(
+ `Custom API Call only sends the Google Workspace credentials to ${allowed}, not to ${origin}. Use a path relative to ${GOOGLE_ADMIN_API_ROOT} (e.g. /${DIRECTORY_PATH}/users) or a full URL on that host.`,
+ );
+ }
+}
+
+function buildRecordBody({
+ def,
+ values,
+}: {
+ def: GoogleWorkspaceResourceDefinition;
+ values: Record<string, unknown> | undefined;
+}): Record<string, unknown> {
+ const entries = Object.entries(values ?? {}).filter(
+ ([, value]) => value !== undefined && value !== null && value !== '',
+ );
+ return entries.reduce<Record<string, unknown>>((body, [key, value]) => {
+ const field = (def.fields ?? []).find((f) => f.key === key);
+ if (field) {
+ return setPath({ target: body, path: field.path, value });
+ }
+ const custom = parseCustomFieldKey(key);
+ if (custom) {
+ const customValue = Array.isArray(value) ? value.map((v) => ({ value: v })) : value;
+ return setPath({
+ target: body,
+ path: ['customSchemas', custom.schemaName, custom.fieldName],
+ value: customValue,
+ });
+ }
+ return body;
+ }, {});
+}
+
+function recordBody({
+ def,
+ fields,
+ extra,
+}: {
+ def: GoogleWorkspaceResourceDefinition;
+ fields: Record<string, unknown> | undefined;
+ extra: unknown;
+}): Record<string, unknown> {
+ const extraFields =
+ extra === undefined || extra === null || extra === '' ? {} : parseRecord(extra);
+ return { ...extraFields, ...buildRecordBody({ def, values: fields }) };
+}
+
+function customFieldKey({
+ schemaName,
+ fieldName,
+}: {
+ schemaName: string;
+ fieldName: string;
+}): string {
+ return `${CUSTOM_FIELD_PREFIX}${schemaName.length}_${schemaName}_${fieldName}`;
+}
+
+function parseCustomFieldKey(key: string): { schemaName: string; fieldName: string } | null {
+ const match = /^custom_(\d+)_(.*)$/.exec(key);
+ if (!match?.[1] || match[2] === undefined) {
+ return null;
+ }
+ const length = Number(match[1]);
+ const rest = match[2];
+ if (rest.length < length + 2 || rest[length] !== '_') {
+ return null;
+ }
+ return { schemaName: rest.slice(0, length), fieldName: rest.slice(length + 1) };
+}
+
+function setPath({
+ target,
+ path,
+ value,
+}: {
+ target: Record<string, unknown>;
+ path: string[];
+ value: unknown;
+}): Record<string, unknown> {
+ const [head, ...rest] = path;
+ if (head === undefined) {
+ return target;
+ }
+ if (rest.length === 0) {
+ return { ...target, [head]: value };
+ }
+ const child = target[head];
+ return {
+ ...target,
+ [head]: setPath({ target: isPlainObject(child) ? child : {}, path: rest, value }),
+ };
+}
+
+function isResourceType(value: string): value is GoogleWorkspaceResourceType {
+ return Object.prototype.hasOwnProperty.call(RESOURCES, value);
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function customer(segment: string): string {
+ return `${DIRECTORY_PATH}/customer/${MY_CUSTOMER}/${segment}`;
+}
+
+function enc(value: string): string {
+ const trimmed = String(value ?? '').trim();
+ if (trimmed === '') {
+ throw new Error(
+ 'The record identifier is empty. Fill it in (or check the step it comes from produced a value).',
+ );
+ }
+ return encodeURIComponent(trimmed);
+}
+
+function encOrgUnit(path: string): string {
+ return enc(
+ String(path ?? '')
+ .trim()
+ .replace(/^\//, ''),
+ );
+}
+
+function requireParent({
+ parent,
+ type,
+}: {
+ parent: string | undefined;
+ type: GoogleWorkspaceResourceType;
+}): string {
+ const value = String(parent ?? '').trim();
+ if (!value) {
+ throw new Error(
+ `"${RESOURCES[type].label}" needs the parent record: fill in the ${RESOURCES[type].parentLabel}.`,
+ );
+ }
+ return value;
+}
+
+const GOOGLE_ADMIN_API_ROOT = 'https://admin.googleapis.com';
+const DIRECTORY_PATH = 'admin/directory/v1';
+const REPORTS_PATH = 'admin/reports/v1';
+const DATA_TRANSFER_PATH = 'admin/datatransfer/v1';
+const MY_CUSTOMER = 'my_customer';
+
+const CUSTOM_FIELD_PREFIX = 'custom_';
+
+const USER_FIELDS: GoogleWorkspaceRecordField[] = [
+ {
+ key: 'primaryEmail',
+ path: ['primaryEmail'],
+ displayName: 'Primary Email',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ {
+ key: 'givenName',
+ path: ['name', 'givenName'],
+ displayName: 'First Name',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ {
+ key: 'familyName',
+ path: ['name', 'familyName'],
+ displayName: 'Last Name',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ {
+ key: 'password',
+ path: ['password'],
+ displayName: 'Password',
+ description: 'At least 8 characters. Never returned by Google.',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ {
+ key: 'changePasswordAtNextLogin',
+ path: ['changePasswordAtNextLogin'],
+ displayName: 'Change Password at Next Login',
+ kind: 'checkbox',
+ },
+ {
+ key: 'orgUnitPath',
+ path: ['orgUnitPath'],
+ displayName: 'Organizational Unit Path',
+ description: 'e.g. `/` or `/Sales/West`.',
+ kind: 'text',
+ },
+ { key: 'recoveryEmail', path: ['recoveryEmail'], displayName: 'Recovery Email', kind: 'text' },
+ {
+ key: 'recoveryPhone',
+ path: ['recoveryPhone'],
+ displayName: 'Recovery Phone',
+ description: 'E.164 format, e.g. `+15551234567`.',
+ kind: 'text',
+ },
+];
+
+const GROUP_FIELDS: GoogleWorkspaceRecordField[] = [
+ {
+ key: 'email',
+ path: ['email'],
+ displayName: 'Group Email',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ { key: 'name', path: ['name'], displayName: 'Name', kind: 'text' },
+ { key: 'description', path: ['description'], displayName: 'Description', kind: 'text' },
+];
+
+const GROUP_MEMBER_FIELDS: GoogleWorkspaceRecordField[] = [
+ {
+ key: 'email',
+ path: ['email'],
+ displayName: 'Member Email',
+ description: 'E-mail of the user or group to add.',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ {
+ key: 'role',
+ path: ['role'],
+ displayName: 'Role',
+ kind: 'dropdown',
+ options: ['MEMBER', 'MANAGER', 'OWNER'],
+ },
+];
+
+const ORG_UNIT_FIELDS: GoogleWorkspaceRecordField[] = [
+ { key: 'name', path: ['name'], displayName: 'Name', kind: 'text', requiredOnCreate: true },
+ {
+ key: 'parentOrgUnitPath',
+ path: ['parentOrgUnitPath'],
+ displayName: 'Parent Path',
+ description: 'e.g. `/` for the top level or `/Sales`.',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ { key: 'description', path: ['description'], displayName: 'Description', kind: 'text' },
+];
+
+const CHROMEOS_DEVICE_FIELDS: GoogleWorkspaceRecordField[] = [
+ { key: 'annotatedUser', path: ['annotatedUser'], displayName: 'Annotated User', kind: 'text' },
+ {
+ key: 'annotatedLocation',
+ path: ['annotatedLocation'],
+ displayName: 'Annotated Location',
+ kind: 'text',
+ },
+ { key: 'annotatedAssetId', path: ['annotatedAssetId'], displayName: 'Asset ID', kind: 'text' },
+ { key: 'notes', path: ['notes'], displayName: 'Notes', kind: 'text' },
+ {
+ key: 'orgUnitPath',
+ path: ['orgUnitPath'],
+ displayName: 'Organizational Unit Path',
+ kind: 'text',
+ },
+];
+
+const ROLE_ASSIGNMENT_FIELDS: GoogleWorkspaceRecordField[] = [
+ {
+ key: 'roleId',
+ path: ['roleId'],
+ displayName: 'Role ID',
+ description:
+ 'Find it with Custom API Call: GET /admin/directory/v1/customer/my_customer/roles.',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ {
+ key: 'assignedTo',
+ path: ['assignedTo'],
+ displayName: 'Assigned To (User ID)',
+ description: 'The numeric id of the user, from Get Record.',
+ kind: 'text',
+ requiredOnCreate: true,
+ },
+ {
+ key: 'scopeType',
+ path: ['scopeType'],
+ displayName: 'Scope',
+ kind: 'dropdown',
+ options: ['CUSTOMER', 'ORG_UNIT'],
+ requiredOnCreate: true,
+ },
+ {
+ key: 'orgUnitId',
+ path: ['orgUnitId'],
+ displayName: 'Org Unit ID',
+ description: 'Only with scope ORG_UNIT.',
+ kind: 'text',
+ },
+];
+
+const RESOURCES: Record<GoogleWorkspaceResourceType, GoogleWorkspaceResourceDefinition> = {
+ user: {
+ type: 'user',
+ label: 'User',
+ collectionPath: () => `${DIRECTORY_PATH}/users`,
+ itemPath: ({ id }) => `${DIRECTORY_PATH}/users/${enc(id)}`,
+ itemsKey: 'users',
+ idField: 'id',
+ idHint: 'primary e-mail, alias or user id',
+ verbs: ['get', 'list', 'create', 'update', 'delete'],
+ supportsQuery: true,
+ supportsDomain: true,
+ maxPageSize: 500,
+ createExample: {
+ primaryEmail: '[email protected]',
+ name: { givenName: 'Jane', familyName: 'Doe' },
+ password: 'a-temporary-password',
+ changePasswordAtNextLogin: true,
+ orgUnitPath: '/',
+ },
+ extraListParams: [
+ 'orderBy',
+ 'sortOrder',
+ 'projection',
+ 'customFieldMask',
+ 'showDeleted',
+ 'viewType',
+ ],
+ fields: USER_FIELDS,
+ },
+ group: {
+ type: 'group',
+ label: 'Group',
+ collectionPath: () => `${DIRECTORY_PATH}/groups`,
+ itemPath: ({ id }) => `${DIRECTORY_PATH}/groups/${enc(id)}`,
+ itemsKey: 'groups',
+ idField: 'id',
+ idHint: 'group e-mail, alias or group id',
+ verbs: ['get', 'list', 'create', 'update', 'delete'],
+ supportsQuery: true,
+ supportsDomain: true,
+ maxPageSize: 200,
+ createExample: { email: '[email protected]', name: 'Sales', description: 'Sales team' },
+ extraListParams: ['orderBy', 'sortOrder', 'userKey'],
+ fields: GROUP_FIELDS,
+ },
+ group_member: {
+ type: 'group_member',
+ label: 'Group member',
+ collectionPath: (parent) =>
+ `${DIRECTORY_PATH}/groups/${enc(requireParent({ parent, type: 'group_member' }))}/members`,
+ itemPath: ({ id, parent }) =>
+ `${DIRECTORY_PATH}/groups/${enc(
+ requireParent({ parent, type: 'group_member' }),
+ )}/members/${enc(id)}`,
+ itemsKey: 'members',
+ idField: 'id',
+ idHint: 'member e-mail or id',
+ parentLabel: 'group e-mail or id',
+ verbs: ['get', 'list', 'create', 'update', 'delete'],
+ supportsQuery: false,
+ supportsDomain: false,
+ maxPageSize: 200,
+ createExample: { email: '[email protected]', role: 'MEMBER' },
+ extraListParams: ['roles', 'includeDerivedMembership'],
+ fields: GROUP_MEMBER_FIELDS,
+ },
+ org_unit: {
+ type: 'org_unit',
+ label: 'Organizational unit',
+ collectionPath: () => customer('orgunits'),
+ itemPath: ({ id }) => customer(`orgunits/${encOrgUnit(id)}`),
+ itemsKey: 'organizationUnits',
+ idField: 'orgUnitId',
+ idHint: 'org unit path (e.g. /Sales/West) or `id:<orgUnitId>`',
+ verbs: ['get', 'list', 'create', 'update', 'delete'],
+ supportsQuery: false,
+ supportsDomain: false,
+ createExample: { name: 'West', parentOrgUnitPath: '/Sales', description: 'West coast sales' },
+ extraListParams: ['orgUnitPath', 'type'],
+ fields: ORG_UNIT_FIELDS,
+ },
+ mobile_device: {
+ type: 'mobile_device',
+ label: 'Mobile device',
+ collectionPath: () => customer('devices/mobile'),
+ itemPath: ({ id }) => customer(`devices/mobile/${enc(id)}`),
+ itemsKey: 'mobiledevices',
+ idField: 'resourceId',
+ idHint: 'device resource id',
+ verbs: ['get', 'list', 'delete'],
+ supportsQuery: true,
+ supportsDomain: false,
+ maxPageSize: 100,
+ extraListParams: ['orderBy', 'sortOrder', 'projection'],
+ },
+ chromeos_device: {
+ type: 'chromeos_device',
+ label: 'Chrome OS device',
+ collectionPath: () => customer('devices/chromeos'),
+ itemPath: ({ id }) => customer(`devices/chromeos/${enc(id)}`),
+ itemsKey: 'chromeosdevices',
+ idField: 'deviceId',
+ idHint: 'device id',
+ verbs: ['get', 'list', 'update'],
+ supportsQuery: true,
+ supportsDomain: false,
+ maxPageSize: 200,
+ extraListParams: ['orgUnitPath', 'orderBy', 'sortOrder', 'projection', 'includeChildOrgunits'],
+ fields: CHROMEOS_DEVICE_FIELDS,
+ },
+ role_assignment: {
+ type: 'role_assignment',
+ label: 'Role assignment',
+ collectionPath: () => customer('roleassignments'),
+ itemPath: ({ id }) => customer(`roleassignments/${enc(id)}`),
+ itemsKey: 'items',
+ idField: 'roleAssignmentId',
+ idHint: 'role assignment id',
+ verbs: ['get', 'list', 'create', 'delete'],
+ supportsQuery: false,
+ supportsDomain: false,
+ maxPageSize: 200,
+ createExample: {
+ roleId: '12345678901234567',
+ assignedTo: '1122334455667788990',
+ scopeType: 'CUSTOMER',
+ },
+ extraListParams: ['roleId', 'userKey', 'includeIndirectRoleAssignments'],
+ fields: ROLE_ASSIGNMENT_FIELDS,
+ },
+};
+
+const RESOURCE_TYPE_OPTIONS: { label: string; value: GoogleWorkspaceResourceType }[] =
+ Object.values(RESOURCES).map((def) => ({
+ label: def.label,
+ value: def.type,
+ }));
+
+export const googleWorkspaceUtils = {
+ resources: RESOURCES,
+ resourceTypeOptions: RESOURCE_TYPE_OPTIONS,
+ resourceDefinition,
+ assertVerb,
+ idOf,
+ isRootOrgUnitPath,
+ isResourceType,
+ parseRecord,
+ stringValues,
+ assertCustomApiCallUrl,
+ buildRecordBody,
+ recordBody,
+ customFieldKey,
+ adminApiRoot: GOOGLE_ADMIN_API_ROOT,
+ directoryPath: DIRECTORY_PATH,
+ reportsPath: REPORTS_PATH,
+ dataTransferPath: DATA_TRANSFER_PATH,
+ myCustomer: MY_CUSTOMER,
+};
diff --git a/packages/pieces/community/google-workspace/src/lib/output-schemas.ts b/packages/pieces/community/google-workspace/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..85b067e7999
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/output-schemas.ts
@@ -0,0 +1,96 @@
+import type { OutputSchema } from '@activepieces/pieces-framework';
+
+export const recordOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'resourceType', label: 'Resource Type' },
+ { key: 'id', label: 'Record ID' },
+ { key: 'record', label: 'Record' },
+ ],
+};
+
+export const deleteRecordOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'resourceType', label: 'Resource Type' },
+ { key: 'id', label: 'Record Identifier' },
+ { key: 'removed', label: 'Removed', format: 'boolean' },
+ ],
+};
+
+export const searchRecordsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'resourceType', label: 'Resource Type' },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'items', label: 'Records' },
+ { key: 'nextPageToken', label: 'Next Page Token' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean' },
+ ],
+};
+
+export const suspendUserOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'User ID' },
+ { key: 'primaryEmail', label: 'Primary Email', format: 'email' },
+ { key: 'suspended', label: 'Suspended', format: 'boolean' },
+ { key: 'suspensionReason', label: 'Suspension Reason' },
+ { key: 'record', label: 'User Record' },
+ ],
+};
+
+export const mobileDeviceActionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'resourceId', label: 'Device Resource ID' },
+ { key: 'action', label: 'Action' },
+ { key: 'success', label: 'Success', format: 'boolean' },
+ ],
+};
+
+export const transferDataOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'transferId', label: 'Transfer ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'oldOwnerUserId', label: 'From User ID' },
+ { key: 'newOwnerUserId', label: 'To User ID' },
+ { key: 'requestTime', label: 'Request Time', format: 'datetime' },
+ {
+ key: 'applications',
+ label: 'Applications',
+ labelKey: 'applicationId',
+ listItems: [
+ { key: 'applicationId', label: 'Application ID' },
+ { key: 'status', label: 'Status' },
+ {
+ key: 'params',
+ label: 'Parameters',
+ labelKey: 'key',
+ listItems: [
+ { key: 'key', label: 'Key' },
+ { key: 'value', label: 'Values' },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+export const activityEventOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Event ID' },
+ { key: 'time', label: 'Time', format: 'datetime' },
+ { key: 'application', label: 'Application' },
+ { key: 'eventType', label: 'Event Type' },
+ { key: 'eventName', label: 'Event Name' },
+ {
+ key: 'actor',
+ label: 'Actor',
+ children: [
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'profileId', label: 'Profile ID' },
+ { key: 'callerType', label: 'Caller Type' },
+ ],
+ },
+ { key: 'ipAddress', label: 'IP Address' },
+ { key: 'ownerDomain', label: 'Owner Domain' },
+ { key: 'parameters', label: 'Parameters', dynamicKey: true },
+ { key: 'activity', label: 'Raw Activity' },
+ ],
+};
diff --git a/packages/pieces/community/google-workspace/src/lib/triggers/new-admin-activity-event.ts b/packages/pieces/community/google-workspace/src/lib/triggers/new-admin-activity-event.ts
new file mode 100644
index 00000000000..f6b0f5e831f
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/triggers/new-admin-activity-event.ts
@@ -0,0 +1,34 @@
+import { Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceActivityTrigger } from '../common/activity-trigger';
+
+export const newAdminActivityEvent = googleWorkspaceActivityTrigger.create({
+ name: 'newAdminActivityEvent',
+ classification: 'READ',
+ displayName: 'New Admin Activity Event',
+ description:
+ 'Fires when an administrator performs an action in the Admin console (audit log "admin"), in real time through a push notification',
+ aiMetadata: {
+ description:
+ 'Fires when an administrator action is recorded in the Google Workspace Admin console audit log, optionally limited to one event name and parameter filters. Emits one item per audit event; Google may group several events of one activity in a single notification.',
+ },
+ props: {
+ eventName: Property.ShortText({
+ displayName: 'Event Name',
+ description:
+ 'Only this admin audit event, e.g. `CREATE_USER`, `DELETE_USER`, `CHANGE_PASSWORD`, `ADD_GROUP_MEMBER`, `CREATE_ORG_UNIT`, `CHANGE_APPLICATION_SETTING`. Leave empty for every admin event. Names: https://developers.google.com/workspace/admin/reports/v1/appendix/activity/admin',
+ required: false,
+ }),
+ filters: Property.ShortText({
+ displayName: 'Filters',
+ description:
+ 'Optional event-parameter conditions, comma-separated, in the Reports API `filters` syntax, e.g. `[email protected]` or `ORG_UNIT_NAME==Sales`.',
+ required: false,
+ }),
+ },
+ query: (props) => ({
+ application: 'admin',
+ eventName: props.eventName ?? undefined,
+ filters: props.filters ?? undefined,
+ }),
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/triggers/new-application-activity-event.ts b/packages/pieces/community/google-workspace/src/lib/triggers/new-application-activity-event.ts
new file mode 100644
index 00000000000..24a3e22c046
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/triggers/new-application-activity-event.ts
@@ -0,0 +1,84 @@
+import { Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceActivityTrigger } from '../common/activity-trigger';
+
+export const ACTIVITY_APPLICATIONS: { label: string; value: string }[] = [
+ { label: 'Admin console', value: 'admin' },
+ { label: 'Login', value: 'login' },
+ { label: 'User accounts', value: 'user_accounts' },
+ { label: 'Drive', value: 'drive' },
+ { label: 'Gmail', value: 'gmail' },
+ { label: 'Calendar', value: 'calendar' },
+ { label: 'Groups', value: 'groups' },
+ { label: 'Groups Enterprise', value: 'groups_enterprise' },
+ { label: 'Chat', value: 'chat' },
+ { label: 'Meet', value: 'meet' },
+ { label: 'Meet hardware', value: 'meet_hardware' },
+ { label: 'Mobile devices', value: 'mobile' },
+ { label: 'Chrome', value: 'chrome' },
+ { label: 'Chrome sync', value: 'chrome_sync' },
+ { label: 'OAuth tokens', value: 'token' },
+ { label: 'SAML', value: 'saml' },
+ { label: 'Rules', value: 'rules' },
+ { label: 'Context-aware access', value: 'context_aware_access' },
+ { label: 'Access transparency', value: 'access_transparency' },
+ { label: 'Access evaluation', value: 'access_evaluation' },
+ { label: 'Admin data actions', value: 'admin_data_action' },
+ { label: 'Google Cloud', value: 'gcp' },
+ { label: 'Looker Studio', value: 'data_studio' },
+ { label: 'Keep', value: 'keep' },
+ { label: 'Vault', value: 'vault' },
+ { label: 'Classroom', value: 'classroom' },
+ { label: 'Assignments', value: 'assignments' },
+ { label: 'Cloud Search', value: 'cloud_search' },
+ { label: 'Tasks', value: 'tasks' },
+ { label: 'Contacts', value: 'contacts' },
+ { label: 'Takeout', value: 'takeout' },
+ { label: 'Voice', value: 'voice' },
+ { label: 'Data migration', value: 'data_migration' },
+ { label: 'Directory Sync', value: 'directory_sync' },
+ { label: 'LDAP', value: 'ldap' },
+ { label: 'Profile', value: 'profile' },
+ { label: 'Graduation', value: 'graduation' },
+ { label: 'Gemini in Workspace apps', value: 'gemini_in_workspace_apps' },
+ { label: 'Workspace Studio', value: 'workspace_studio' },
+ { label: 'Jamboard', value: 'jamboard' },
+ { label: 'Google+', value: 'gplus' },
+];
+
+export const newApplicationActivityEvent = googleWorkspaceActivityTrigger.create({
+ name: 'newApplicationActivityEvent',
+ classification: 'READ',
+ displayName: 'New Application Activity Event',
+ description:
+ 'Fires on an audit event of a Google Workspace application (Drive, Login, Calendar, Groups, Mobile, ...), in real time through a push notification',
+ aiMetadata: {
+ description:
+ 'Fires when the selected Google Workspace application (Drive, Login, Calendar, Groups, Mobile and others) records an audit event, optionally limited to one event name and parameter filters. Emits one item per audit event.',
+ },
+ props: {
+ application: Property.StaticDropdown<string, true>({
+ displayName: 'Application',
+ description: 'Which audit log to watch.',
+ required: true,
+ options: { options: ACTIVITY_APPLICATIONS },
+ }),
+ eventName: Property.ShortText({
+ displayName: 'Event Name',
+ description:
+ 'Only this event of the application, e.g. `login_success` (Login), `download` / `create` / `edit` (Drive), `change_calendar_acls` (Calendar), `DEVICE_REGISTER_UNREGISTER_EVENT` (Mobile). Leave empty for every event. Names per application: https://developers.google.com/workspace/admin/reports/v1/appendix',
+ required: false,
+ }),
+ filters: Property.ShortText({
+ displayName: 'Filters',
+ description:
+ 'Optional event-parameter conditions, comma-separated, in the Reports API `filters` syntax, e.g. `doc_type==spreadsheet` or `login_type==google_password`.',
+ required: false,
+ }),
+ },
+ query: (props) => ({
+ application: props.application,
+ eventName: props.eventName ?? undefined,
+ filters: props.filters ?? undefined,
+ }),
+});
diff --git a/packages/pieces/community/google-workspace/src/lib/triggers/new-user-event.ts b/packages/pieces/community/google-workspace/src/lib/triggers/new-user-event.ts
new file mode 100644
index 00000000000..baa26548d8d
--- /dev/null
+++ b/packages/pieces/community/google-workspace/src/lib/triggers/new-user-event.ts
@@ -0,0 +1,81 @@
+import { Property } from '@activepieces/pieces-framework';
+
+import { googleWorkspaceActivityTrigger } from '../common/activity-trigger';
+
+import type { GoogleWorkspaceActivityEvent } from '../common/types';
+
+export function acceptUserEvent({
+ event,
+ props,
+}: {
+ event: GoogleWorkspaceActivityEvent;
+ props: UserEventFilter;
+}): boolean {
+ const eventName = event.eventName;
+ if (event.eventType !== 'USER_SETTINGS' || !eventName) return false;
+
+ const wanted = new Set(props.kinds ?? []);
+ const kind = USER_EVENT_KINDS.find((k) => k.events.includes(eventName));
+ const matchesKind = kind
+ ? wanted.has(kind.value)
+ : wanted.has('updated') && !LIFECYCLE_EVENTS.has(eventName);
+ if (!matchesKind) return false;
+
+ const domain = props.domain?.trim().toLowerCase();
+ if (!domain) return true;
+ const userEmail = String(event.parameters['USER_EMAIL'] ?? '').toLowerCase();
+ return userEmail.endsWith(`@${domain}`);
+}
+
+export const USER_EVENT_KINDS: { label: string; value: string; events: string[] }[] = [
+ { label: 'User created', value: 'created', events: ['CREATE_USER'] },
+ { label: 'User deleted', value: 'deleted', events: ['DELETE_USER'] },
+ { label: 'User undeleted', value: 'undeleted', events: ['UNDELETE_USER'] },
+ { label: 'User suspended', value: 'suspended', events: ['SUSPEND_USER'] },
+ { label: 'User unsuspended', value: 'unsuspended', events: ['UNSUSPEND_USER'] },
+ {
+ label: 'Admin status changed',
+ value: 'admin_changed',
+ events: [
+ 'GRANT_ADMIN_PRIVILEGE',
+ 'REVOKE_ADMIN_PRIVILEGE',
+ 'GRANT_DELEGATED_ADMIN_PRIVILEGES',
+ 'REVOKE_DELEGATED_ADMIN_PRIVILEGES',
+ ],
+ },
+ { label: 'User updated (any other change)', value: 'updated', events: [] },
+];
+
+const LIFECYCLE_EVENTS = new Set(USER_EVENT_KINDS.flatMap((k) => k.events));
+
+export const newUserEvent = googleWorkspaceActivityTrigger.create({
+ name: 'newUserEvent',
+ classification: 'READ',
+ displayName: 'New User Event',
+ description:
+ 'Fires when a user is created, deleted, suspended, undeleted, promoted/demoted as admin or otherwise changed, in real time through a push notification',
+ aiMetadata: {
+ description:
+ 'Fires on Google Workspace user lifecycle events from the Admin console audit log: created, deleted, undeleted, suspended, unsuspended, admin status changed, or any other user change, optionally limited to one domain. Emits one item per matching event.',
+ },
+ props: {
+ kinds: Property.StaticMultiSelectDropdown<string, true>({
+ displayName: 'User Events',
+ description: 'Which lifecycle events to fire on.',
+ required: true,
+ defaultValue: ['created'],
+ options: { options: USER_EVENT_KINDS.map(({ label, value }) => ({ label, value })) },
+ }),
+ domain: Property.ShortText({
+ displayName: 'Domain',
+ description:
+ 'Only users of this domain (e.g. `example.com`). Leave empty for every domain of the account.',
+ required: false,
+ }),
+ },
+ query: () => ({ application: 'admin' }),
+ accept: ({ event, props }) =>
+ acceptUserEvent({ event, props: { kinds: props.kinds, domain: props.domain } }),
+});
+
+type UserEventFilter = { kinds: string[]; domain?: string | undefined };
diff --git a/packages/pieces/community/google-workspace/test/lib/actions/read-actions.test.ts b/packages/pieces/community/google-workspace/test/lib/actions/read-actions.test.ts
new file mode 100644
index 00000000000..2c20d260986
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/actions/read-actions.test.ts
@@ -0,0 +1,215 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({
+ request: vi.fn<() => Promise<unknown>>(),
+ listPage: vi.fn<() => Promise<unknown>>(),
+ listAll: vi.fn<() => Promise<unknown>>(),
+}));
+const resolveAuth = vi.hoisted(() => vi.fn<() => Promise<{ access_token: string }>>());
+
+vi.mock('../../../src/lib/common/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../src/lib/common/client')>();
+ return { ...actual, googleWorkspaceClient: { ...actual.googleWorkspaceClient, ...api, resolveAuth } };
+});
+
+const { getRecord } = await import('../../../src/lib/actions/get-record');
+const { searchRecords } = await import('../../../src/lib/actions/search-records');
+
+const AUTH = { type: 'OAUTH2', access_token: 'tok' };
+const RESOLVED = { access_token: 'resolved' };
+const ctx = (propsValue: Record<string, unknown>) => ({ auth: AUTH, propsValue }) as never;
+
+beforeEach(() => {
+ for (const fn of Object.values(api)) fn.mockReset();
+ resolveAuth.mockReset().mockResolvedValue(RESOLVED);
+});
+
+describe('getRecord', () => {
+ it('should GET the item path of the type and return the record with its id', async () => {
+ api.request.mockResolvedValue({ id: '1122', primaryEmail: '[email protected]' });
+
+ const result = await getRecord.run(ctx({ resourceType: 'user', identifier: '[email protected]', params: { projection: 'full' } }));
+
+ expect(resolveAuth).toHaveBeenCalledWith(AUTH);
+ expect(api.request).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ method: 'GET',
+ path: 'admin/directory/v1/users/jane%40example.com',
+ query: { projection: 'full' },
+ });
+ expect(result).toEqual({ resourceType: 'user', id: '1122', record: { id: '1122', primaryEmail: '[email protected]' } });
+ });
+
+ it('should scope a group member under the parent group', async () => {
+ api.request.mockResolvedValue({ id: '9', email: '[email protected]', role: 'MEMBER' });
+
+ await getRecord.run(ctx({ resourceType: 'group_member', identifier: '[email protected]', parent: '[email protected]' }));
+
+ expect(api.request).toHaveBeenCalledWith(
+ expect.objectContaining({ auth: RESOLVED, path: 'admin/directory/v1/groups/sales%40example.com/members/jane%40example.com' })
+ );
+ });
+
+ it('should resolve the root org unit path to its id from the list that includes the parent', async () => {
+ api.request
+ .mockResolvedValueOnce({
+ organizationUnits: [
+ { orgUnitId: 'id:sales1', orgUnitPath: '/Sales', parentOrgUnitId: 'id:root1', parentOrgUnitPath: '/' },
+ { orgUnitId: 'id:root1', orgUnitPath: '/', name: 'Example' },
+ ],
+ })
+ .mockResolvedValueOnce({ orgUnitId: 'id:root1', orgUnitPath: '/' });
+
+ const result = await getRecord.run(ctx({ resourceType: 'org_unit', identifier: '/' }));
+
+ expect(api.request).toHaveBeenNthCalledWith(1, {
+ auth: RESOLVED,
+ method: 'GET',
+ path: 'admin/directory/v1/customer/my_customer/orgunits',
+ query: { type: 'allIncludingParent' },
+ });
+ expect(api.request).toHaveBeenNthCalledWith(2, expect.objectContaining({ path: 'admin/directory/v1/customer/my_customer/orgunits/id%3Aroot1' }));
+ expect(result).toEqual({ resourceType: 'org_unit', id: 'id:root1', record: { orgUnitId: 'id:root1', orgUnitPath: '/' } });
+ });
+
+ it('should resolve the root org unit when the account has no child units', async () => {
+ api.request
+ .mockResolvedValueOnce({ organizationUnits: [{ orgUnitId: 'id:root2', orgUnitPath: '/', name: 'Example' }] })
+ .mockResolvedValueOnce({ orgUnitId: 'id:root2', orgUnitPath: '/' });
+
+ const result = await getRecord.run(ctx({ resourceType: 'org_unit', identifier: '/' }));
+
+ expect(api.request).toHaveBeenNthCalledWith(1, expect.objectContaining({ query: { type: 'allIncludingParent' } }));
+ expect(api.request).toHaveBeenNthCalledWith(2, expect.objectContaining({ path: 'admin/directory/v1/customer/my_customer/orgunits/id%3Aroot2' }));
+ expect(result).toEqual({ resourceType: 'org_unit', id: 'id:root2', record: { orgUnitId: 'id:root2', orgUnitPath: '/' } });
+ });
+
+ it('should ask for the root org unit id when Google does not return it', async () => {
+ api.request.mockResolvedValueOnce({ organizationUnits: [{ orgUnitId: 'id:sales1', orgUnitPath: '/Sales' }] });
+
+ await expect(getRecord.run(ctx({ resourceType: 'org_unit', identifier: ' / ' }))).rejects.toThrow('Use its ID (id:...) instead of /');
+ expect(api.request).toHaveBeenCalledTimes(1);
+ });
+
+ it('should fail before calling Google when the parent is missing', async () => {
+ await expect(getRecord.run(ctx({ resourceType: 'group_member', identifier: '[email protected]' }))).rejects.toThrow('needs the parent record');
+ expect(api.request).not.toHaveBeenCalled();
+ });
+});
+
+describe('searchRecords', () => {
+ it('should list one page of users under my_customer with the query and the page size capped by Google', async () => {
+ api.listPage.mockResolvedValue({ items: [{ id: '1' }], nextPageToken: 'p2' });
+
+ const result = await searchRecords.run(ctx({ resourceType: 'user', query: 'email:sales*', maxRows: 5000, params: { orderBy: 'email' } }));
+
+ expect(api.listPage).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ path: 'admin/directory/v1/users',
+ itemsKey: 'users',
+ query: {
+ customer: 'my_customer',
+ query: 'email:sales*',
+ orderBy: 'email',
+ maxResults: 500,
+ pageToken: undefined,
+ },
+ });
+ expect(result).toEqual({ resourceType: 'user', items: [{ id: '1' }], count: 1, nextPageToken: 'p2', truncated: false });
+ });
+
+ it('should filter by domain instead of customer when a domain is given', async () => {
+ api.listPage.mockResolvedValue({ items: [] });
+
+ const result = await searchRecords.run(ctx({ resourceType: 'group', domain: 'example.com', pageToken: 'tok', maxRows: 50 }));
+
+ expect(api.listPage).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ path: 'admin/directory/v1/groups',
+ itemsKey: 'groups',
+ query: {
+ domain: 'example.com',
+ maxResults: 50,
+ pageToken: 'tok',
+ },
+ });
+ expect(result).toEqual({ resourceType: 'group', items: [], count: 0, nextPageToken: null, truncated: false });
+ });
+
+ it('should list the groups of a user without customer, which Google rejects alongside userKey', async () => {
+ api.listPage.mockResolvedValue({ items: [] });
+
+ await searchRecords.run(ctx({ resourceType: 'group', maxRows: 50, params: { userKey: '[email protected]' } }));
+
+ expect(api.listPage).toHaveBeenCalledWith(
+ expect.objectContaining({ query: { userKey: '[email protected]', maxResults: 50, pageToken: undefined } })
+ );
+ });
+
+ it('should fetch every page up to Max Rows when asked', async () => {
+ api.listAll.mockResolvedValue({ items: [{ id: '1' }, { id: '2' }], truncated: true });
+
+ const result = await searchRecords.run(ctx({ resourceType: 'group_member', parent: '[email protected]', fetchAllPages: true, maxRows: 2 }));
+
+ expect(api.listAll).toHaveBeenCalledWith({ auth: RESOLVED, path: 'admin/directory/v1/groups/sales%40example.com/members', itemsKey: 'members', query: { maxResults: 2 }, maxRows: 2 });
+ expect(result).toEqual({ resourceType: 'group_member', items: [{ id: '1' }, { id: '2' }], count: 2, truncated: true });
+ });
+
+ it('should round a fractional Max Rows down to whole rows for a single page', async () => {
+ api.listPage.mockResolvedValue({ items: [{ id: '1' }, { id: '2' }, { id: '3' }] });
+
+ const result = await searchRecords.run(ctx({ resourceType: 'user', maxRows: 2.5 }));
+
+ expect(api.listPage).toHaveBeenCalledWith(expect.objectContaining({ query: expect.objectContaining({ maxResults: 2 }) }));
+ expect(result).toEqual(expect.objectContaining({ items: [{ id: '1' }, { id: '2' }], count: 2, truncated: true }));
+ });
+
+ it('should round a fractional Max Rows down to whole rows when fetching every page', async () => {
+ api.listAll.mockResolvedValue({ items: [{ id: '1' }, { id: '2' }], truncated: true });
+
+ await searchRecords.run(ctx({ resourceType: 'group_member', parent: '[email protected]', fetchAllPages: true, maxRows: 2.5 }));
+
+ expect(api.listAll).toHaveBeenCalledWith(expect.objectContaining({ query: { maxResults: 2 }, maxRows: 2 }));
+ });
+
+ it('should list org units without pagination parameters', async () => {
+ api.listPage.mockResolvedValue({ items: [{ orgUnitPath: '/Sales' }] });
+
+ const result = await searchRecords.run(ctx({ resourceType: 'org_unit', params: { type: 'all' } }));
+
+ expect(api.listPage).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ path: 'admin/directory/v1/customer/my_customer/orgunits',
+ itemsKey: 'organizationUnits',
+ query: {
+ type: 'all',
+ pageToken: undefined,
+ },
+ });
+ expect(result).toEqual({ resourceType: 'org_unit', items: [{ orgUnitPath: '/Sales' }], count: 1, nextPageToken: null, truncated: false });
+ });
+
+ it('should apply Max Rows locally to org units and flag the dropped rows', async () => {
+ api.listPage.mockResolvedValue({ items: [{ orgUnitPath: '/A' }, { orgUnitPath: '/B' }, { orgUnitPath: '/C' }] });
+
+ const result = await searchRecords.run(ctx({ resourceType: 'org_unit', maxRows: 2 }));
+
+ expect(api.listPage).toHaveBeenCalledWith(expect.objectContaining({ query: { pageToken: undefined } }));
+ expect(result).toEqual({
+ resourceType: 'org_unit',
+ items: [{ orgUnitPath: '/A' }, { orgUnitPath: '/B' }],
+ count: 2,
+ nextPageToken: null,
+ truncated: true,
+ });
+ });
+
+ it('should refuse a query on a collection without search and a domain outside users/groups', async () => {
+ await expect(searchRecords.run(ctx({ resourceType: 'org_unit', query: 'name:Sales' }))).rejects.toThrow(
+ 'Organizational unit records cannot be filtered with a query; use the extra parameters (orgUnitPath, type) instead.'
+ );
+ await expect(searchRecords.run(ctx({ resourceType: 'mobile_device', domain: 'example.com' }))).rejects.toThrow('only applies to users and groups');
+ expect(api.listPage).not.toHaveBeenCalled();
+ expect(api.listAll).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/actions/record-mutations.test.ts b/packages/pieces/community/google-workspace/test/lib/actions/record-mutations.test.ts
new file mode 100644
index 00000000000..33a61f73948
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/actions/record-mutations.test.ts
@@ -0,0 +1,93 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const request = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
+const resolveAuth = vi.hoisted(() => vi.fn<() => Promise<{ access_token: string }>>());
+
+vi.mock('../../../src/lib/common/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../src/lib/common/client')>();
+ return { ...actual, googleWorkspaceClient: { ...actual.googleWorkspaceClient, request, resolveAuth } };
+});
+
+const { addRecord } = await import('../../../src/lib/actions/add-record');
+const { updateRecord } = await import('../../../src/lib/actions/update-record');
+const { deleteRecord } = await import('../../../src/lib/actions/delete-record');
+
+const AUTH = { type: 'OAUTH2', access_token: 'tok' };
+const RESOLVED = { access_token: 'resolved' };
+
+type Runnable = { run: (ctx: unknown) => Promise<unknown> };
+const run = (action: Runnable, propsValue: Record<string, unknown>) => action.run({ auth: AUTH, propsValue });
+
+beforeEach(() => {
+ request.mockReset();
+ resolveAuth.mockReset().mockResolvedValue(RESOLVED);
+});
+
+describe('addRecord', () => {
+ it('should POST the JSON body to the collection and return the created record with its id', async () => {
+ request.mockResolvedValue({ id: '1122', primaryEmail: '[email protected]' });
+ const record = { primaryEmail: '[email protected]', name: { givenName: 'Jane', familyName: 'Doe' }, password: 'x' };
+
+ const result = await run(addRecord, { resourceType: 'user', record });
+
+ expect(request).toHaveBeenCalledWith({ auth: RESOLVED, method: 'POST', path: 'admin/directory/v1/users', body: record });
+ expect(result).toEqual({ resourceType: 'user', id: '1122', record: { id: '1122', primaryEmail: '[email protected]' } });
+ });
+
+ it('should accept the record as a JSON string and scope members under the parent group', async () => {
+ request.mockResolvedValue({ id: '9', email: '[email protected]', role: 'MEMBER' });
+
+ await run(addRecord, { resourceType: 'group_member', parent: '[email protected]', record: '{"email":"[email protected]","role":"MEMBER"}' });
+
+ expect(request).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ method: 'POST',
+ path: 'admin/directory/v1/groups/sales%40example.com/members',
+ body: { email: '[email protected]', role: 'MEMBER' },
+ });
+ });
+
+ it('should refuse types the Directory API cannot create, before calling Google', async () => {
+ await expect(run(addRecord, { resourceType: 'mobile_device', record: {} })).rejects.toThrow('Mobile device records do not support "create"');
+ await expect(run(addRecord, { resourceType: 'user', record: '[1,2]' })).rejects.toThrow('must be a JSON object');
+ expect(request).not.toHaveBeenCalled();
+ });
+});
+
+describe('updateRecord', () => {
+ it('should PATCH the item path with only the given fields', async () => {
+ request.mockResolvedValue({ orgUnitId: 'id:abc', name: 'West', description: 'West coast' });
+
+ const result = await run(updateRecord, { resourceType: 'org_unit', identifier: '/Sales/West', record: { description: 'West coast' } });
+
+ expect(request).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ method: 'PATCH',
+ path: 'admin/directory/v1/customer/my_customer/orgunits/Sales%2FWest',
+ body: { description: 'West coast' },
+ });
+ expect(result).toEqual({ resourceType: 'org_unit', id: 'id:abc', record: { orgUnitId: 'id:abc', name: 'West', description: 'West coast' } });
+ });
+
+ it('should refuse an empty record and types without update', async () => {
+ await expect(run(updateRecord, { resourceType: 'user', identifier: '[email protected]', record: {} })).rejects.toThrow('no fields to update');
+ await expect(run(updateRecord, { resourceType: 'mobile_device', identifier: 'x', record: { a: 1 } })).rejects.toThrow('do not support "update"');
+ expect(request).not.toHaveBeenCalled();
+ });
+});
+
+describe('deleteRecord', () => {
+ it('should DELETE the item path and report the removal', async () => {
+ request.mockResolvedValue(undefined);
+
+ const result = await run(deleteRecord, { resourceType: 'group', identifier: ' [email protected] ' });
+
+ expect(request).toHaveBeenCalledWith({ auth: RESOLVED, method: 'DELETE', path: 'admin/directory/v1/groups/sales%40example.com' });
+ expect(result).toEqual({ resourceType: 'group', id: '[email protected]', removed: true });
+ });
+
+ it('should refuse types without delete (Chrome OS devices)', async () => {
+ await expect(run(deleteRecord, { resourceType: 'chromeos_device', identifier: 'dev-1' })).rejects.toThrow('do not support "delete"');
+ expect(request).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/actions/record-privacy.test.ts b/packages/pieces/community/google-workspace/test/lib/actions/record-privacy.test.ts
new file mode 100644
index 00000000000..7d511ced615
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/actions/record-privacy.test.ts
@@ -0,0 +1,111 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const network = vi.hoisted(() => ({ unexpectedCalls: 0 }));
+const fetchMock = vi.hoisted(() =>
+ vi.fn<(input: string | URL | Request, init?: RequestInit) => Promise<Response>>(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ })
+);
+vi.stubGlobal('fetch', fetchMock);
+
+const { addRecord } = await import('../../../src/lib/actions/add-record');
+const { updateRecord } = await import('../../../src/lib/actions/update-record');
+
+const AUTH = { type: 'OAUTH2', access_token: 'ya29.oauth-token' };
+const PASSWORD = 'Sup3r-Secret-Passw0rd!';
+const RECOVERY_PHONE = '+15550001111';
+const USER = {
+ primaryEmail: '[email protected]',
+ name: { givenName: 'Jane', familyName: 'Doe' },
+ password: PASSWORD,
+ recoveryPhone: RECOVERY_PHONE,
+ customSchemas: { HR: { salary: 'confidential-123' } },
+};
+const SECRETS = [PASSWORD, RECOVERY_PHONE, 'confidential-123'];
+
+type Runnable = { run: (ctx: unknown) => Promise<unknown> };
+
+function errorText(error: unknown): string {
+ const parts: string[] = [];
+ let current: unknown = error;
+ while (current !== undefined && current !== null) {
+ parts.push(current instanceof Error ? `${current.message} ${current.stack ?? ''}` : String(current));
+ parts.push(typeof current === 'object' ? JSON.stringify(current, Object.getOwnPropertyNames(current)) : String(current));
+ current = current instanceof Error ? current.cause : undefined;
+ }
+ return parts.join('\n');
+}
+
+const consoleSpies: ReturnType<typeof vi.spyOn>[] = [];
+
+beforeEach(() => {
+ network.unexpectedCalls = 0;
+ fetchMock.mockReset().mockImplementation(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ consoleSpies.length = 0;
+ for (const level of ['error', 'warn', 'log', 'info', 'debug'] as const) {
+ consoleSpies.push(vi.spyOn(console, level).mockImplementation(() => undefined));
+ }
+});
+
+afterEach(() => {
+ expect(network.unexpectedCalls).toBe(0);
+ vi.restoreAllMocks();
+});
+
+describe('user writes carrying a password', () => {
+ it.each([
+ {
+ status: 400,
+ body: { error: { code: 400, message: 'Invalid Password', errors: [{ domain: 'global', reason: 'invalid', message: 'Invalid Password' }] } },
+ message: 'Google Workspace API returned 400: invalid: Invalid Password',
+ },
+ {
+ status: 409,
+ body: { error: { code: 409, message: 'Entity already exists.', errors: [{ domain: 'global', reason: 'duplicate', message: 'Entity already exists.' }] } },
+ message: 'Google Workspace API returned 409: duplicate: Entity already exists. A record with that key already exists.',
+ },
+ ])('should fail Add Record with $status without exposing the password or logging anything', async ({ status, body, message }) => {
+ fetchMock.mockImplementationOnce(async () => Response.json(body, { status }));
+
+ const failure = await (addRecord as Runnable).run({ auth: AUTH, propsValue: { resourceType: 'user', record: USER } }).catch((e: unknown) => e);
+
+ expect(failure).toBeInstanceOf(Error);
+ expect((failure as Error).message).toBe(message);
+ expect((failure as Error).cause).toBeUndefined();
+ const text = errorText(failure);
+ SECRETS.forEach((secret) => expect(text).not.toContain(secret));
+ consoleSpies.forEach((spy) => expect(spy).not.toHaveBeenCalled());
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual(USER);
+ });
+
+ it('should fail Update Record with a password change without exposing it or logging anything', async () => {
+ fetchMock.mockImplementationOnce(async () =>
+ Response.json({ error: { code: 403, status: 'PERMISSION_DENIED', message: 'Not Authorized to access this resource/api', errors: [{ reason: 'forbidden', message: 'Not Authorized to access this resource/api' }] } }, { status: 403 })
+ );
+
+ const failure = await (updateRecord as Runnable)
+ .run({ auth: AUTH, propsValue: { resourceType: 'user', identifier: '[email protected]', record: { password: PASSWORD } } })
+ .catch((e: unknown) => e);
+
+ expect(failure).toBeInstanceOf(Error);
+ expect((failure as Error).message).toContain('Google Workspace API returned 403 (PERMISSION_DENIED): forbidden');
+ expect(errorText(failure)).not.toContain(PASSWORD);
+ consoleSpies.forEach((spy) => expect(spy).not.toHaveBeenCalled());
+ });
+
+ it('should still return the created user on success', async () => {
+ fetchMock.mockImplementationOnce(async () => Response.json({ id: '1122', primaryEmail: '[email protected]' }));
+
+ await expect((addRecord as Runnable).run({ auth: AUTH, propsValue: { resourceType: 'user', record: USER } })).resolves.toEqual({
+ resourceType: 'user',
+ id: '1122',
+ record: { id: '1122', primaryEmail: '[email protected]' },
+ });
+ consoleSpies.forEach((spy) => expect(spy).not.toHaveBeenCalled());
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/actions/suspend-and-device.test.ts b/packages/pieces/community/google-workspace/test/lib/actions/suspend-and-device.test.ts
new file mode 100644
index 00000000000..ef4599c9589
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/actions/suspend-and-device.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const request = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
+const resolveAuth = vi.hoisted(() => vi.fn<() => Promise<{ access_token: string }>>());
+
+vi.mock('../../../src/lib/common/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../src/lib/common/client')>();
+ return { ...actual, googleWorkspaceClient: { ...actual.googleWorkspaceClient, request, resolveAuth } };
+});
+
+const { suspendUser } = await import('../../../src/lib/actions/suspend-user');
+const { MOBILE_DEVICE_ACTIONS, mobileDeviceAction } = await import('../../../src/lib/actions/mobile-device-action');
+
+const AUTH = { type: 'OAUTH2', access_token: 'tok' };
+const RESOLVED = { access_token: 'resolved' };
+
+type Runnable = { run: (ctx: unknown) => Promise<unknown> };
+const run = (action: Runnable, propsValue: Record<string, unknown>) => action.run({ auth: AUTH, propsValue });
+
+beforeEach(() => {
+ request.mockReset();
+ resolveAuth.mockReset().mockResolvedValue(RESOLVED);
+});
+
+describe('suspendUser', () => {
+ it('should PATCH suspended=true by default and summarize the user', async () => {
+ request.mockResolvedValue({ id: '1', primaryEmail: '[email protected]', suspended: true, suspensionReason: 'ADMIN' });
+
+ const result = await run(suspendUser, { userKey: '[email protected]' });
+
+ expect(request).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ method: 'PATCH',
+ path: 'admin/directory/v1/users/jane%40example.com',
+ body: { suspended: true },
+ });
+ expect(result).toEqual({
+ id: '1',
+ primaryEmail: '[email protected]',
+ suspended: true,
+ suspensionReason: 'ADMIN',
+ record: { id: '1', primaryEmail: '[email protected]', suspended: true, suspensionReason: 'ADMIN' },
+ });
+ });
+
+ it('should lift the suspension when the checkbox is off', async () => {
+ request.mockResolvedValue({ id: '1', primaryEmail: '[email protected]', suspended: false });
+
+ const result = await run(suspendUser, { userKey: '1', suspended: false });
+
+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ auth: RESOLVED, path: 'admin/directory/v1/users/1', body: { suspended: false } }));
+ expect(result).toMatchObject({ suspended: false, suspensionReason: null });
+ });
+});
+
+describe('mobileDeviceAction', () => {
+ it('should offer the six Directory actions', () => {
+ expect(MOBILE_DEVICE_ACTIONS.map((a) => a.value)).toEqual([
+ 'approve',
+ 'block',
+ 'admin_account_wipe',
+ 'admin_remote_wipe',
+ 'cancel_remote_wipe_then_activate',
+ 'cancel_remote_wipe_then_block',
+ ]);
+ });
+
+ it('should POST the action to the device and report success (Google answers 204)', async () => {
+ request.mockResolvedValue(undefined);
+
+ const result = await run(mobileDeviceAction, { resourceId: 'AFiQxQ-abc', action: 'block' });
+
+ expect(request).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ method: 'POST',
+ path: 'admin/directory/v1/customer/my_customer/devices/mobile/AFiQxQ-abc/action',
+ body: { action: 'block' },
+ });
+ expect(result).toEqual({ resourceId: 'AFiQxQ-abc', action: 'block', success: true });
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/actions/transfer-data.test.ts b/packages/pieces/community/google-workspace/test/lib/actions/transfer-data.test.ts
new file mode 100644
index 00000000000..72ae34fcf05
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/actions/transfer-data.test.ts
@@ -0,0 +1,315 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({
+ listApplications: vi.fn<(auth: unknown) => Promise<unknown>>(),
+ createTransfer: vi.fn<(params: { auth: unknown; transfer: unknown }) => Promise<unknown>>(),
+ getTransfer: vi.fn<(params: { auth: unknown; transferId: string; timeoutMs?: number }) => Promise<unknown>>(),
+}));
+const userProfileId = vi.hoisted(() => vi.fn<(params: { auth: unknown; userKey: string }) => Promise<string>>());
+const resolveAuth = vi.hoisted(() => vi.fn<() => Promise<{ access_token: string }>>());
+const client = vi.hoisted(() => ({
+ request: async ({ auth, method, path, body, timeoutMs }: { auth: unknown; method: string; path: string; body?: unknown; timeoutMs?: number }) => {
+ const user = /^admin\/directory\/v1\/users\/(.+)$/.exec(path);
+ if (user?.[1]) {
+ return { id: await userProfileId({ auth, userKey: decodeURIComponent(user[1]) }) };
+ }
+ if (method === 'POST' && path === 'admin/datatransfer/v1/transfers') {
+ return api.createTransfer({ auth, transfer: body });
+ }
+ const transfer = /^admin\/datatransfer\/v1\/transfers\/(.+)$/.exec(path);
+ if (transfer?.[1]) {
+ return api.getTransfer({ auth, transferId: decodeURIComponent(transfer[1]), ...(timeoutMs === undefined ? {} : { timeoutMs }) });
+ }
+ throw new Error(`Unexpected request ${method} ${path}`);
+ },
+ listAll: async ({ auth }: { auth: unknown }) => ({ items: await api.listApplications(auth), truncated: false }),
+}));
+
+vi.mock('../../../src/lib/common/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../src/lib/common/client')>();
+ return { ...actual, googleWorkspaceClient: { ...actual.googleWorkspaceClient, ...client, resolveAuth } };
+});
+
+const { transferData } = await import('../../../src/lib/actions/transfer-data');
+const { googleWorkspaceProps } = await import('../../../src/lib/common/props');
+
+const applicationOptions = (auth: unknown) => googleWorkspaceProps.applicationId({ required: true }).options({ auth } as never, {} as never);
+
+const AUTH = { type: 'OAUTH2', access_token: 'tok' };
+const RESOLVED = { access_token: 'resolved' };
+
+const run = (propsValue: Record<string, unknown>) => transferData.run({ auth: AUTH, propsValue } as never);
+
+beforeEach(() => {
+ for (const fn of Object.values(api)) fn.mockReset();
+ userProfileId.mockReset().mockImplementation(async ({ userKey }) => (userKey === '[email protected]' ? '111' : '222'));
+ resolveAuth.mockReset().mockResolvedValue(RESOLVED);
+ vi.useRealTimers();
+});
+
+describe('transfer parameters', () => {
+ it('should turn comma-separated strings and arrays into the API key/value shape and drop empty ones', async () => {
+ api.createTransfer.mockResolvedValue({ id: 't0', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' });
+
+ await run({
+ oldOwner: '[email protected]',
+ newOwner: '[email protected]',
+ applicationId: '55656082996',
+ transferParams: { PRIVACY_LEVEL: 'SHARED, PRIVATE', RELEASE_RESOURCES: ['TRUE'], EMPTY: '' },
+ });
+
+ expect(api.createTransfer).toHaveBeenCalledWith(
+ expect.objectContaining({
+ transfer: expect.objectContaining({
+ applicationDataTransfers: [
+ {
+ applicationId: '55656082996',
+ applicationTransferParams: [
+ { key: 'PRIVACY_LEVEL', value: ['SHARED', 'PRIVATE'] },
+ { key: 'RELEASE_RESOURCES', value: ['TRUE'] },
+ ],
+ },
+ ],
+ }),
+ })
+ );
+ });
+});
+
+describe('applicationOptions()', () => {
+ it('should label applications with their parameters', async () => {
+ api.listApplications.mockResolvedValue([
+ { id: '55656082996', name: 'Drive and Docs', transferParams: [{ key: 'PRIVACY_LEVEL', value: ['SHARED', 'PRIVATE'] }] },
+ { id: '435070579839', name: 'Calendar', transferParams: [{ key: 'RELEASE_RESOURCES', value: ['TRUE', 'FALSE'] }] },
+ { id: '1', name: 'Looker Studio' },
+ ]);
+
+ await expect(applicationOptions(AUTH as never)).resolves.toEqual({
+ disabled: false,
+ options: [
+ { label: 'Drive and Docs (PRIVACY_LEVEL: SHARED|PRIVATE)', value: '55656082996' },
+ { label: 'Calendar (RELEASE_RESOURCES: TRUE|FALSE)', value: '435070579839' },
+ { label: 'Looker Studio', value: '1' },
+ ],
+ });
+ expect(api.listApplications).toHaveBeenCalledWith(RESOLVED);
+ });
+
+ it('should degrade without a connection, and surface the error when Google fails', async () => {
+ await expect(applicationOptions(undefined)).resolves.toMatchObject({ disabled: true, options: [] });
+ api.listApplications.mockRejectedValue(new Error('Google Workspace API returned 403 (PERMISSION_DENIED): forbidden: Not Authorized'));
+ await expect(applicationOptions(AUTH as never)).resolves.toMatchObject({
+ disabled: true,
+ placeholder: 'An error occurred while listing the transferable applications: Google Workspace API returned 403 (PERMISSION_DENIED): forbidden: Not Authorized',
+ });
+ });
+});
+
+describe('transferData', () => {
+ it('should hide Retry On Failure and default it to off so a timeout rethrow never starts a second transfer', () => {
+ expect(transferData.errorHandlingOptions).toEqual({
+ continueOnFailure: { defaultValue: false },
+ retryOnFailure: { defaultValue: false, hide: true },
+ });
+ });
+
+ it('should resolve both users to profile ids and create the transfer with the parameters', async () => {
+ api.createTransfer.mockResolvedValue({
+ id: 'AKrEtIbj',
+ oldOwnerUserId: '111',
+ newOwnerUserId: '222',
+ overallTransferStatusCode: 'inProgress',
+ requestTime: '2026-10-05T10:00:00.000Z',
+ applicationDataTransfers: [
+ { applicationId: '55656082996', applicationTransferStatus: 'pending', applicationTransferParams: [{ key: 'PRIVACY_LEVEL', value: ['SHARED'] }] },
+ ],
+ });
+
+ const result = await run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '55656082996', transferParams: { PRIVACY_LEVEL: 'SHARED' } });
+
+ expect(api.createTransfer).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ transfer: {
+ oldOwnerUserId: '111',
+ newOwnerUserId: '222',
+ applicationDataTransfers: [{ applicationId: '55656082996', applicationTransferParams: [{ key: 'PRIVACY_LEVEL', value: ['SHARED'] }] }],
+ },
+ });
+ expect(api.getTransfer).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ transferId: 'AKrEtIbj',
+ status: 'inProgress',
+ oldOwnerUserId: '111',
+ newOwnerUserId: '222',
+ requestTime: '2026-10-05T10:00:00.000Z',
+ applications: [{ applicationId: '55656082996', status: 'pending', params: [{ key: 'PRIVACY_LEVEL', value: ['SHARED'] }] }],
+ });
+ });
+
+ it('should poll until the transfer completes when asked to wait', async () => {
+ vi.useFakeTimers();
+ api.createTransfer.mockResolvedValue({ id: 't1', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' });
+ api.getTransfer
+ .mockResolvedValueOnce({ id: 't1', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' })
+ .mockResolvedValueOnce({ id: 't1', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'completed' });
+
+ const pending = run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: true });
+ await vi.advanceTimersByTimeAsync(25_000);
+ const result = await pending;
+
+ expect(api.getTransfer).toHaveBeenCalledTimes(2);
+ expect(api.getTransfer).toHaveBeenNthCalledWith(1, { auth: RESOLVED, transferId: 't1', timeoutMs: 110_000 });
+ expect(api.getTransfer).toHaveBeenNthCalledWith(2, { auth: RESOLVED, transferId: 't1', timeoutMs: 100_000 });
+ expect(result).toMatchObject({ transferId: 't1', status: 'completed', applications: [] });
+ });
+
+ it('should fail with the transfer id when the transfer is still running after the last poll', async () => {
+ vi.useFakeTimers();
+ const running = { id: 't2', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' };
+ api.createTransfer.mockResolvedValue(running);
+ api.getTransfer.mockResolvedValue(running);
+
+ const pending = run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: true });
+ const outcome = expect(pending).rejects.toThrow(
+ 'Transfer t2 is still running in Google after waiting 120 seconds. It was not cancelled and will finish on its own. Check its status with Custom API Call (GET /admin/datatransfer/v1/transfers/t2), or turn Wait for Completion off'
+ );
+ await vi.advanceTimersByTimeAsync(130_000);
+ await outcome;
+
+ expect(api.getTransfer).toHaveBeenCalledTimes(11);
+ });
+
+ it('should stop at the 120 second deadline even when each status call is slow', async () => {
+ vi.useFakeTimers();
+ const running = { id: 't4', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' };
+ api.createTransfer.mockResolvedValue(running);
+ api.getTransfer.mockImplementation(
+ ({ timeoutMs = 60_000 }) =>
+ new Promise((resolve, reject) => {
+ if (timeoutMs < 70_000) {
+ setTimeout(() => reject(new Error('Could not reach the Google Workspace API (TimeoutError). Try again in a moment.')), timeoutMs);
+ return;
+ }
+ setTimeout(() => resolve(running), 70_000);
+ })
+ );
+ const startedAt = Date.now();
+ let settledAt = 0;
+
+ const pending = run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: true }).finally(() => {
+ settledAt = Date.now();
+ });
+ const outcome = expect(pending).rejects.toThrow('Transfer t4 is still running in Google after waiting 120 seconds.');
+ await vi.advanceTimersByTimeAsync(1_000_000);
+ await outcome;
+
+ expect(settledAt - startedAt).toBe(120_000);
+ expect(api.getTransfer.mock.calls.map(([params]) => params.timeoutMs)).toEqual([110_000, 30_000]);
+ });
+
+ it('should return normally when a slow status call reports completion before the deadline', async () => {
+ vi.useFakeTimers();
+ api.createTransfer.mockResolvedValue({ id: 't5', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' });
+ api.getTransfer.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ setTimeout(() => resolve({ id: 't5', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'completed' }), 100_000);
+ })
+ );
+
+ const pending = run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: true });
+ await vi.advanceTimersByTimeAsync(115_000);
+ const result = await pending;
+
+ expect(api.getTransfer).toHaveBeenCalledTimes(1);
+ expect(api.getTransfer).toHaveBeenCalledWith({ auth: RESOLVED, transferId: 't5', timeoutMs: 110_000 });
+ expect(result).toMatchObject({ transferId: 't5', status: 'completed' });
+ });
+
+ it('should surface a status call failure that happens before the deadline with the transfer id', async () => {
+ vi.useFakeTimers();
+ api.createTransfer.mockResolvedValue({ id: 't6', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' });
+ api.getTransfer.mockRejectedValue(new Error('Google Workspace API returned 403'));
+
+ const pending = run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: true });
+ const outcome = expect(pending).rejects.toThrow(
+ 'Transfer t6 was started in Google and was not cancelled, but checking its status failed: Google Workspace API returned 403. Check it with Custom API Call (GET /admin/datatransfer/v1/transfers/t6) before running this step again.'
+ );
+ await vi.advanceTimersByTimeAsync(10_000);
+ await outcome;
+ });
+
+ it('should fail with the transfer id when the transfer ends as failed', async () => {
+ vi.useFakeTimers();
+ api.createTransfer.mockResolvedValue({ id: 't7', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' });
+ api.getTransfer.mockResolvedValue({
+ id: 't7',
+ oldOwnerUserId: '111',
+ newOwnerUserId: '222',
+ overallTransferStatusCode: 'failed',
+ applicationDataTransfers: [{ applicationId: '55656082996', applicationTransferStatus: 'failed' }],
+ });
+
+ const pending = run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '55656082996', waitForCompletion: true });
+ const outcome = expect(pending).rejects.toThrow(
+ 'Transfer t7 did not complete in Google (status: failed; application 55656082996: failed). The data of From User may not have moved, so do not delete that user yet. Check the details with Custom API Call (GET /admin/datatransfer/v1/transfers/t7)'
+ );
+ await vi.advanceTimersByTimeAsync(10_000);
+ await outcome;
+
+ expect(api.getTransfer).toHaveBeenCalledTimes(1);
+ });
+
+ it('should fail when the transfer completes but an application failed', async () => {
+ vi.useFakeTimers();
+ api.createTransfer.mockResolvedValue({ id: 't8', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' });
+ api.getTransfer.mockResolvedValue({
+ id: 't8',
+ oldOwnerUserId: '111',
+ newOwnerUserId: '222',
+ overallTransferStatusCode: 'completed',
+ applicationDataTransfers: [{ applicationId: '1', applicationTransferStatus: 'failed' }],
+ });
+
+ const pending = run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: true });
+ const outcome = expect(pending).rejects.toThrow('Transfer t8 did not complete in Google (status: completed; application 1: failed).');
+ await vi.advanceTimersByTimeAsync(10_000);
+ await outcome;
+ });
+
+ it('should fail on any final status other than completed when asked to wait', async () => {
+ vi.useFakeTimers();
+ api.createTransfer.mockResolvedValue({ id: 't9', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' });
+ api.getTransfer.mockResolvedValue({ id: 't9', oldOwnerUserId: '111', newOwnerUserId: '222' });
+
+ const pending = run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: true });
+ const outcome = expect(pending).rejects.toThrow('Transfer t9 did not complete in Google (status: unknown).');
+ await vi.advanceTimersByTimeAsync(10_000);
+ await outcome;
+ });
+
+ it('should fail with the transfer id when Google reports a failed transfer right away, even without waiting', async () => {
+ api.createTransfer.mockResolvedValue({ id: 't10', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'failed' });
+
+ await expect(run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: false })).rejects.toThrow(
+ 'Transfer t10 did not complete in Google (status: failed).'
+ );
+ expect(api.getTransfer).not.toHaveBeenCalled();
+ });
+
+ it('should not poll or fail on a running transfer when not asked to wait', async () => {
+ api.createTransfer.mockResolvedValue({ id: 't3', oldOwnerUserId: '111', newOwnerUserId: '222', overallTransferStatusCode: 'inProgress' });
+
+ const result = await run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1', waitForCompletion: false });
+
+ expect(api.getTransfer).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ transferId: 't3', status: 'inProgress' });
+ });
+
+ it('should refuse a transfer to the same user before calling Google', async () => {
+ userProfileId.mockResolvedValue('111');
+
+ await expect(run({ oldOwner: '[email protected]', newOwner: '[email protected]', applicationId: '1' })).rejects.toThrow('same account');
+ expect(api.createTransfer).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/common/activities.test.ts b/packages/pieces/community/google-workspace/test/lib/common/activities.test.ts
new file mode 100644
index 00000000000..dcbc264b70f
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/common/activities.test.ts
@@ -0,0 +1,195 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const network = vi.hoisted(() => ({ unexpectedCalls: 0 }));
+const fetchMock = vi.hoisted(() =>
+ vi.fn<(input: string | URL | Request, init?: RequestInit) => Promise<Response>>(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ })
+);
+vi.stubGlobal('fetch', fetchMock);
+
+const { googleWorkspaceActivityTrigger } = await import('../../../src/lib/common/activity-trigger');
+const { ACTIVITY_APPLICATIONS } = await import('../../../src/lib/triggers/new-application-activity-event');
+
+const { flattenActivity, isActivity, newChannelRequest } = googleWorkspaceActivityTrigger;
+const ReportsApi = googleWorkspaceActivityTrigger.reports;
+const SAMPLE_EVENT = googleWorkspaceActivityTrigger.sampleEvent;
+const CHANNEL_MAX_LIFETIME_MS = googleWorkspaceActivityTrigger.channelMaxLifetimeMs;
+
+const AUTH = { access_token: 'tok' };
+const ROOT = 'https://admin.googleapis.com';
+
+function answerWith(response: () => Response): void {
+ fetchMock.mockImplementation(async () => response());
+}
+
+function sent(call = 0): { url: URL; method: string | undefined; body: unknown } {
+ const [input, init] = fetchMock.mock.calls[call] ?? [];
+ return { url: new URL(String(input)), method: init?.method, body: init?.body === undefined ? undefined : JSON.parse(String(init.body)) };
+}
+
+beforeEach(() => {
+ network.unexpectedCalls = 0;
+ fetchMock.mockReset().mockImplementation(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ expect(network.unexpectedCalls).toBe(0);
+});
+
+describe('ReportsApi', () => {
+ it('should list activities of an application for all users with the optional filters', async () => {
+ answerWith(() => Response.json({ items: [{ id: { time: 't' }, events: [] }] }));
+
+ const items = await ReportsApi.listActivities({ auth: AUTH, query: { application: 'admin', eventName: 'CREATE_USER', filters: ' ', maxResults: 50 } });
+
+ expect(items).toEqual([{ id: { time: 't' }, events: [] }]);
+ const request = sent();
+ expect(request.method).toBe('GET');
+ expect(`${request.url.origin}${request.url.pathname}`).toBe(`${ROOT}/admin/reports/v1/activity/users/all/applications/admin`);
+ expect(Object.fromEntries(request.url.searchParams)).toEqual({ eventName: 'CREATE_USER', maxResults: '50' });
+ });
+
+ it('should open a web_hook channel with the token and the 6-hour expiration', async () => {
+ answerWith(() => Response.json({ id: 'chan-1', resourceId: 'res-1', expiration: '1700021600000' }));
+
+ const channel = await ReportsApi.watch({
+ auth: AUTH,
+ query: { application: 'drive', userKey: '[email protected]', eventName: 'download' },
+ channel: { id: 'chan-1', address: 'https://ipaas.example/webhooks/abc', token: 'secret', expiration: 1_700_021_600_000 },
+ });
+
+ expect(channel).toEqual({ id: 'chan-1', resourceId: 'res-1', expiration: '1700021600000' });
+ const request = sent();
+ expect(request.method).toBe('POST');
+ expect(`${request.url.origin}${request.url.pathname}`).toBe(`${ROOT}/admin/reports/v1/activity/users/jane%40example.com/applications/drive/watch`);
+ expect(Object.fromEntries(request.url.searchParams)).toEqual({ eventName: 'download' });
+ expect(request.body).toEqual({
+ id: 'chan-1',
+ type: 'web_hook',
+ address: 'https://ipaas.example/webhooks/abc',
+ token: 'secret',
+ expiration: '1700021600000',
+ payload: true,
+ });
+ });
+
+ it('should keep the channel token out of the error when watch fails', async () => {
+ answerWith(() => Response.json({ error: { code: 400, message: 'Invalid address', errors: [{ reason: 'invalid', message: 'Invalid address' }] } }, { status: 400 }));
+ const spies = (['error', 'log', 'warn'] as const).map((level) => vi.spyOn(console, level).mockImplementation(() => undefined));
+
+ const failure = await ReportsApi.watch({
+ auth: AUTH,
+ query: { application: 'admin' },
+ channel: { id: 'chan-1', address: 'https://ipaas.example/webhooks/abc', token: 'channel-secret-token', expiration: 1 },
+ }).catch((e: unknown) => e);
+
+ expect(failure).toBeInstanceOf(Error);
+ expect(failure).toMatchObject({ message: 'Google Workspace API returned 400: invalid: Invalid address' });
+ expect(JSON.stringify(failure, Object.getOwnPropertyNames(failure))).not.toContain('channel-secret-token');
+ spies.forEach((spy) => expect(spy).not.toHaveBeenCalled());
+ });
+
+ it('should stop a channel through the reports_v1 channels endpoint and accept the empty 204 reply', async () => {
+ answerWith(() => new Response(null, { status: 204 }));
+
+ await expect(ReportsApi.stop({ auth: AUTH, channel: { id: 'chan-1', resourceId: 'res-1' } })).resolves.toBeUndefined();
+
+ const request = sent();
+ expect(request.method).toBe('POST');
+ expect(request.url.toString()).toBe(`${ROOT}/admin/reports_v1/channels/stop`);
+ expect(request.body).toEqual({ id: 'chan-1', resourceId: 'res-1' });
+ });
+});
+
+describe('newChannelRequest()', () => {
+ it('should mint distinct uuids for the id and the token, expiring just under the six-hour maximum Google accepts', () => {
+ const request = newChannelRequest({ address: 'https://hook', now: 1_000 });
+
+ expect(request.address).toBe('https://hook');
+ expect(request.id).toMatch(/^[0-9a-f-]{36}$/);
+ expect(request.token).toMatch(/^[0-9a-f-]{36}$/);
+ expect(request.id).not.toBe(request.token);
+ expect(request.expiration).toBe(1_000 + CHANNEL_MAX_LIFETIME_MS);
+ expect(CHANNEL_MAX_LIFETIME_MS).toBeLessThan(6 * 60 * 60 * 1000);
+ });
+});
+
+describe('flattenActivity()', () => {
+ it('should emit one item per event with parameters as an object', () => {
+ const activity = {
+ id: { time: '2026-10-05T10:00:00.000Z', uniqueQualifier: '42', applicationName: 'admin' },
+ actor: { email: '[email protected]', profileId: '1', callerType: 'USER' },
+ ipAddress: '1.2.3.4',
+ ownerDomain: 'example.com',
+ events: [
+ { type: 'USER_SETTINGS', name: 'CREATE_USER', parameters: [{ name: 'USER_EMAIL', value: '[email protected]' }] },
+ {
+ type: 'USER_SETTINGS',
+ name: 'CHANGE_FIRST_NAME',
+ parameters: [
+ { name: 'USER_EMAIL', value: '[email protected]' },
+ { name: 'NEW_VALUE', value: 'Jane' },
+ { name: 'COUNT', intValue: '3' },
+ { name: 'FLAG', boolValue: true },
+ { name: 'LIST', multiValue: ['a', 'b'] },
+ { value: 'nameless' },
+ ],
+ },
+ ],
+ };
+
+ const events = flattenActivity(activity);
+
+ expect(events).toHaveLength(2);
+ expect(events[0]).toMatchObject({
+ id: '2026-10-05T10:00:00.000Z:42:0',
+ time: '2026-10-05T10:00:00.000Z',
+ application: 'admin',
+ eventType: 'USER_SETTINGS',
+ eventName: 'CREATE_USER',
+ actor: { email: '[email protected]', profileId: '1', callerType: 'USER' },
+ ipAddress: '1.2.3.4',
+ ownerDomain: 'example.com',
+ parameters: { USER_EMAIL: '[email protected]' },
+ });
+ expect(events[1]?.id).toBe('2026-10-05T10:00:00.000Z:42:1');
+ expect(events[1]?.parameters).toEqual({ USER_EMAIL: '[email protected]', NEW_VALUE: 'Jane', COUNT: '3', FLAG: true, LIST: ['a', 'b'] });
+ expect(events[0]?.activity).toBe(activity);
+ });
+
+ it('should keep the plain activity id when there is a single event and tolerate missing fields', () => {
+ expect(flattenActivity({ id: { time: 't', uniqueQualifier: 'q' }, events: [{ name: 'login_success' }] })).toEqual([
+ expect.objectContaining({
+ id: 't:q',
+ eventName: 'login_success',
+ eventType: null,
+ actor: { email: null, profileId: null, callerType: null },
+ parameters: {},
+ }),
+ ]);
+ expect(flattenActivity({})).toEqual([]);
+ });
+});
+
+describe('isActivity()', () => {
+ it('should recognise a notification body with events and reject sync/empty bodies', () => {
+ expect(isActivity(SAMPLE_EVENT.activity)).toBe(true);
+ expect(isActivity({})).toBe(false);
+ expect(isActivity('')).toBe(false);
+ expect(isActivity(null)).toBe(false);
+ });
+});
+
+describe('ACTIVITY_APPLICATIONS', () => {
+ it('should be unique values with labels, including the common audit logs', () => {
+ const values = ACTIVITY_APPLICATIONS.map((a) => a.value);
+ expect(new Set(values).size).toBe(values.length);
+ expect(values).toEqual(expect.arrayContaining(['admin', 'login', 'drive', 'calendar', 'groups', 'mobile', 'user_accounts', 'token', 'saml']));
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/common/activity-trigger.test.ts b/packages/pieces/community/google-workspace/test/lib/common/activity-trigger.test.ts
new file mode 100644
index 00000000000..36db26b5fe0
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/common/activity-trigger.test.ts
@@ -0,0 +1,808 @@
+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({
+ watch: vi.fn<(params: { auth: unknown; query: unknown; channel: { id: string; token: string; expiration: number } }) => Promise<unknown>>(),
+ stop: vi.fn<(params: { auth: unknown; channel: { id: string; resourceId: string } }) => Promise<void>>(),
+ listActivities: vi.fn<() => Promise<unknown>>(),
+}));
+const resolveAuth = vi.hoisted(() => vi.fn<() => Promise<{ access_token: string }>>());
+
+vi.mock('../../../src/lib/common/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../src/lib/common/client')>();
+ return { ...actual, googleWorkspaceClient: { ...actual.googleWorkspaceClient, resolveAuth } };
+});
+
+const { googleWorkspaceActivityTrigger } = await import('../../../src/lib/common/activity-trigger');
+const { googleWorkspaceClient } = await import('../../../src/lib/common/client');
+
+const createActivityTrigger = googleWorkspaceActivityTrigger.create;
+const SAMPLE_EVENT = googleWorkspaceActivityTrigger.sampleEvent;
+const GoogleWorkspaceApiError = googleWorkspaceClient.ApiError;
+
+const AUTH = { type: 'OAUTH2', access_token: 'tok' };
+const RESOLVED = { access_token: 'resolved' };
+const WEBHOOK_URL = 'https://ipaas.example/api/v1/webhooks/flow-1';
+const FLOW_ID = 'flow-1';
+const VERSION = 'version-1';
+const NEXT_VERSION = 'version-2';
+const keysOf = (version: string) => ({
+ channel: `google-workspace:channel:${version}`,
+ pending: `google-workspace:pending-token:${version}`,
+ previous: `google-workspace:previous-channel:${version}`,
+ unstopped: `google-workspace:unstopped-channels:${version}`,
+ disabled: `google-workspace:disabled:${version}`,
+});
+const STORE_KEY = keysOf(VERSION).channel;
+const PENDING_KEY = keysOf(VERSION).pending;
+const PREVIOUS_KEY = keysOf(VERSION).previous;
+const UNSTOPPED_KEY = keysOf(VERSION).unstopped;
+const DISABLED_KEY = keysOf(VERSION).disabled;
+const MINUTE = 60 * 1000;
+const HOUR = 60 * MINUTE;
+const IN_FLIGHT_MS = 2 * MINUTE;
+const NOW = Date.parse('2026-10-08T12:00:00.000Z');
+
+function memoryStore() {
+ const data = new Map<string, unknown>();
+ return {
+ data,
+ put: vi.fn<(key: string, value: unknown) => Promise<unknown>>(async (key, value) => {
+ data.set(key, value);
+ return value;
+ }),
+ get: vi.fn<(key: string) => Promise<unknown>>(async (key) => data.get(key) ?? null),
+ delete: vi.fn<(key: string) => Promise<void>>(async (key) => {
+ data.delete(key);
+ }),
+ };
+}
+
+type MemoryStore = ReturnType<typeof memoryStore>;
+type StoredState = { id: string; resourceId: string; token: string; expiration?: string; query: unknown };
+
+const trigger = createActivityTrigger({
+ name: 'testTrigger',
+ classification: 'READ',
+ displayName: 'Test',
+ description: 'Test',
+ aiMetadata: { description: 'Test' },
+ props: {},
+ query: () => ({ application: 'admin', eventName: 'CREATE_USER' }),
+ accept: ({ event }) => event.eventName !== 'IGNORED',
+});
+
+type Hook = (ctx: unknown) => Promise<unknown>;
+const hooks = trigger as unknown as { onEnable: Hook; onRenew: Hook; onDisable: Hook; run: Hook; test: Hook };
+
+function ctx({
+ store,
+ payload,
+ version = VERSION,
+}: {
+ store: MemoryStore;
+ payload?: { headers?: Record<string, string>; body?: unknown };
+ version?: string;
+}) {
+ return {
+ auth: AUTH,
+ propsValue: {},
+ store,
+ webhookUrl: WEBHOOK_URL,
+ flows: { current: { id: FLOW_ID, version: { id: version } } },
+ payload: { headers: {}, body: undefined, queryParams: {}, ...payload },
+ };
+}
+
+function deliver({
+ store,
+ token,
+ body = SAMPLE_EVENT.activity,
+ version = VERSION,
+}: {
+ store: MemoryStore;
+ token: string;
+ body?: unknown;
+ version?: string;
+}) {
+ return hooks.run(ctx({ store, version, payload: { headers: { 'x-goog-channel-token': token }, body } })) as Promise<Record<string, unknown>[]>;
+}
+
+function at(time: number) {
+ vi.spyOn(Date, 'now').mockReturnValue(time);
+}
+
+function activityAt({ time, qualifier = 'q' }: { time: number | null; qualifier?: string }) {
+ const id = { ...SAMPLE_EVENT.activity.id, uniqueQualifier: qualifier, time: time === null ? undefined : new Date(time).toISOString() };
+ return { body: { ...SAMPLE_EVENT.activity, id }, eventId: `${id.time ?? ''}:${qualifier}` };
+}
+
+function stored(store: MemoryStore, version = VERSION): StoredState {
+ return store.data.get(keysOf(version).channel) as StoredState;
+}
+
+function googleError(status: number) {
+ return new GoogleWorkspaceApiError({ status, googleStatus: undefined, errors: [], summary: `Google Workspace API returned ${status}` });
+}
+
+let resourceCounter = 0;
+
+async function enabled() {
+ const store = memoryStore();
+ await hooks.onEnable(ctx({ store }));
+ return { store, token: stored(store).token };
+}
+
+async function renewed() {
+ at(NOW - 4 * HOUR);
+ const { store, token: oldToken } = await enabled();
+ at(NOW);
+ await hooks.onRenew(ctx({ store }));
+ return { store, oldToken, newToken: stored(store).token };
+}
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+ vi.spyOn(googleWorkspaceActivityTrigger.reports, 'watch').mockImplementation((params) => api.watch(params));
+ vi.spyOn(googleWorkspaceActivityTrigger.reports, 'stop').mockImplementation((params) => api.stop(params));
+ vi.spyOn(googleWorkspaceActivityTrigger.reports, 'listActivities').mockImplementation((params) => api.listActivities(params));
+ resourceCounter = 0;
+ api.watch.mockReset().mockImplementation(async ({ channel }) => {
+ resourceCounter += 1;
+ return { id: channel.id, resourceId: `res-${resourceCounter}`, expiration: String(channel.expiration) };
+ });
+ api.stop.mockReset().mockResolvedValue(undefined);
+ api.listActivities.mockReset();
+ resolveAuth.mockReset().mockResolvedValue(RESOLVED);
+});
+
+describe('createActivityTrigger()', () => {
+ it('should be a webhook trigger renewed by cron with sample data', () => {
+ expect(trigger.type).toBe('WEBHOOK');
+ expect(trigger.renewConfiguration).toEqual({ strategy: 'CRON', cronExpression: '0 */4 * * *' });
+ expect(trigger.sampleData).toBe(SAMPLE_EVENT);
+ });
+
+ describe('onEnable()', () => {
+ it('should open a channel to the webhook url and remember it with its token', async () => {
+ at(NOW);
+ const { store } = await enabled();
+
+ expect(api.watch).toHaveBeenCalledWith({
+ auth: RESOLVED,
+ query: { application: 'admin', eventName: 'CREATE_USER' },
+ channel: expect.objectContaining({ address: WEBHOOK_URL, id: expect.any(String), token: expect.any(String), expiration: expect.any(Number) }),
+ });
+ const state = stored(store);
+ expect(state.resourceId).toBe('res-1');
+ expect(state.token).toMatch(/^[0-9a-f-]{36}$/);
+ expect(state.expiration).toEqual(expect.any(String));
+ expect(state.query).toEqual({ application: 'admin', eventName: 'CREATE_USER' });
+ expect([...store.data.keys()]).toEqual([STORE_KEY]);
+ expect(api.stop).not.toHaveBeenCalled();
+ });
+
+ it('should stop a stale channel and start clean with only the channel key', async () => {
+ const { store, oldToken, newToken } = await renewed();
+ store.data.set(PENDING_KEY, 'stale');
+ store.delete.mockClear();
+ api.stop.mockClear();
+
+ await hooks.onEnable(ctx({ store }));
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel.resourceId)).toEqual(['res-2']);
+ expect(store.delete.mock.calls.map(([key]) => key)).toEqual([DISABLED_KEY, STORE_KEY, PENDING_KEY, PREVIOUS_KEY, PENDING_KEY]);
+ expect([...store.data.keys()]).toEqual([STORE_KEY]);
+ await expect(deliver({ store, token: stored(store).token })).resolves.toHaveLength(1);
+ await expect(deliver({ store, token: oldToken })).resolves.toEqual([]);
+ await expect(deliver({ store, token: newToken })).resolves.toEqual([]);
+ });
+
+ it('should accept the pending token while the first channel is being opened', async () => {
+ const store = memoryStore();
+ const delivered: unknown[][] = [];
+ api.watch.mockImplementationOnce(async ({ channel }) => {
+ delivered.push(await deliver({ store, token: channel.token }));
+ delivered.push(await deliver({ store, token: channel.token, body: activityAt({ time: null }).body }));
+ return { id: channel.id, resourceId: 'res-1', expiration: String(channel.expiration) };
+ });
+
+ await hooks.onEnable(ctx({ store }));
+
+ expect(delivered).toEqual([[expect.objectContaining({ id: SAMPLE_EVENT.id })], [expect.anything()]]);
+ expect(store.data.has(PENDING_KEY)).toBe(false);
+ });
+ });
+
+ describe('onRenew()', () => {
+ it('should save the pending token, watch, save the new channel, drop the pending token, then stop the old channel', async () => {
+ at(NOW - 4 * HOUR);
+ const { store, token: oldToken } = await enabled();
+ const first = stored(store);
+ store.put.mockClear();
+ store.delete.mockClear();
+ at(NOW);
+
+ await hooks.onRenew(ctx({ store }));
+
+ const second = stored(store);
+ expect(second).toEqual(expect.objectContaining({ resourceId: 'res-2', expiration: expect.any(String) }));
+ expect(second.id).not.toBe(first.id);
+ expect(second.token).not.toBe(oldToken);
+ expect(api.stop).toHaveBeenCalledTimes(1);
+ expect(api.stop).toHaveBeenCalledWith({ auth: RESOLVED, channel: { id: first.id, resourceId: 'res-1' } });
+ expect(store.data.get(PREVIOUS_KEY)).toEqual({ previousToken: oldToken, previousStoppedAt: NOW });
+ expect(store.data.has(PENDING_KEY)).toBe(false);
+
+ const putOrder = (key: string) => store.put.mock.invocationCallOrder[store.put.mock.calls.findIndex(([k]) => k === key)] as number;
+ const deleteOrder = (key: string) => store.delete.mock.invocationCallOrder[store.delete.mock.calls.findIndex(([k]) => k === key)] as number;
+ const sequence = [
+ putOrder(PENDING_KEY),
+ api.watch.mock.invocationCallOrder[1] as number,
+ putOrder(STORE_KEY),
+ deleteOrder(PENDING_KEY),
+ api.stop.mock.invocationCallOrder[0] as number,
+ ];
+ expect(sequence).toEqual([...sequence].sort((a, b) => a - b));
+ expect(putOrder(PREVIOUS_KEY)).toBeLessThan(putOrder(STORE_KEY));
+ });
+
+ it('should accept the pending token and the old token while watch is in flight', async () => {
+ at(NOW - 4 * HOUR);
+ const { store, token: oldToken } = await enabled();
+ at(NOW);
+ const fromPending: unknown[][] = [];
+ const fromOld: unknown[][] = [];
+ api.watch.mockImplementationOnce(async ({ channel }) => {
+ fromPending.push(await deliver({ store, token: channel.token, body: activityAt({ time: NOW }).body }));
+ fromOld.push(await deliver({ store, token: oldToken, body: activityAt({ time: NOW - 5 * MINUTE }).body }));
+ return { id: channel.id, resourceId: 'res-2', expiration: String(channel.expiration) };
+ });
+
+ await hooks.onRenew(ctx({ store }));
+
+ expect(fromPending.map((items) => items.length)).toEqual([1]);
+ expect(fromOld.map((items) => items.length)).toEqual([1]);
+ });
+
+ it('should accept the old token while the old channel is being stopped', async () => {
+ at(NOW - 4 * HOUR);
+ const { store, token: oldToken } = await enabled();
+ at(NOW);
+ const duringStop: unknown[][] = [];
+ api.stop.mockImplementationOnce(async () => {
+ duringStop.push(await deliver({ store, token: oldToken }));
+ });
+
+ await hooks.onRenew(ctx({ store }));
+
+ expect(duringStop.map((items) => items.length)).toEqual([1]);
+ });
+
+ it('should roll back the pending token, keep the old channel state and not stop it when watch fails', async () => {
+ const { store, token } = await enabled();
+ const before = structuredClone([...store.data.entries()]);
+ let pendingToken = '';
+ api.watch.mockImplementationOnce(async ({ channel }) => {
+ pendingToken = channel.token;
+ throw new Error('403 forbidden');
+ });
+
+ await expect(hooks.onRenew(ctx({ store }))).rejects.toThrow('403 forbidden');
+
+ expect([...store.data.entries()]).toEqual(before);
+ expect(api.stop).not.toHaveBeenCalled();
+ await expect(deliver({ store, token: pendingToken })).resolves.toEqual([]);
+ await expect(deliver({ store, token })).resolves.toHaveLength(1);
+ });
+
+ it('should tolerate an old channel that is already expired or gone', async () => {
+ at(NOW - 4 * HOUR);
+ const { store } = await enabled();
+ at(NOW);
+ api.stop.mockRejectedValueOnce(googleError(404));
+
+ await expect(hooks.onRenew(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(stored(store).resourceId).toBe('res-2');
+ expect(store.data.has(PENDING_KEY)).toBe(false);
+ expect(store.data.has(UNSTOPPED_KEY)).toBe(false);
+ });
+
+ it('should keep the new channel, remember the old one and fail when the old channel cannot be stopped', async () => {
+ at(NOW - 4 * HOUR);
+ const { store, token: oldToken } = await enabled();
+ const first = stored(store);
+ at(NOW);
+ api.stop.mockRejectedValueOnce(googleError(500));
+
+ await expect(hooks.onRenew(ctx({ store }))).rejects.toThrow(
+ `Could not stop the Google Workspace notification channel(s) ${first.id}: Google Workspace API returned 500. They are kept for another stop attempt the next time this trigger is enabled, renewed or disabled; either way Google expires them within 6 hours.`
+ );
+
+ const second = stored(store);
+ expect(second.resourceId).toBe('res-2');
+ expect(store.data.get(UNSTOPPED_KEY)).toEqual([{ id: first.id, resourceId: 'res-1' }]);
+ expect(store.data.get(PREVIOUS_KEY)).toEqual({ previousToken: oldToken, previousStoppedAt: NOW });
+ expect(store.data.has(PENDING_KEY)).toBe(false);
+ await expect(deliver({ store, token: second.token })).resolves.toHaveLength(1);
+ });
+
+ it('should stop a channel left over by a failed renewal on the next renewal', async () => {
+ at(NOW - 4 * HOUR);
+ const { store } = await enabled();
+ const first = stored(store);
+ at(NOW);
+ api.stop.mockRejectedValueOnce(googleError(500));
+ await expect(hooks.onRenew(ctx({ store }))).rejects.toThrow('Could not stop');
+ api.stop.mockClear();
+
+ at(NOW + 4 * HOUR);
+ await expect(hooks.onRenew(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel)).toEqual([
+ { id: expect.any(String), resourceId: 'res-2' },
+ { id: first.id, resourceId: 'res-1' },
+ ]);
+ expect(store.data.has(UNSTOPPED_KEY)).toBe(false);
+ expect(stored(store).resourceId).toBe('res-3');
+ });
+
+ it('should drop the pending token and remember the renewal channel when a superseded renewal cannot stop it', async () => {
+ at(NOW - 4 * HOUR);
+ const { store } = await enabled();
+ at(NOW);
+ let channelB: StoredState | undefined;
+ let renewalChannelId = '';
+ api.watch.mockImplementationOnce(async ({ channel }) => {
+ renewalChannelId = channel.id;
+ await hooks.onEnable(ctx({ store }));
+ channelB = stored(store);
+ return { id: channel.id, resourceId: 'res-C', expiration: String(channel.expiration) };
+ });
+ api.stop.mockClear();
+ api.stop.mockResolvedValueOnce(undefined).mockRejectedValueOnce(googleError(503));
+
+ await expect(hooks.onRenew(ctx({ store }))).rejects.toThrow(`Could not stop the Google Workspace notification channel(s) ${renewalChannelId}`);
+
+ expect(stored(store)).toEqual(channelB);
+ expect(store.data.has(PENDING_KEY)).toBe(false);
+ expect(store.data.get(UNSTOPPED_KEY)).toEqual([{ id: renewalChannelId, resourceId: 'res-C' }]);
+ });
+
+ it('should keep a channel republished during the renewal watch and stop the renewal channel instead', async () => {
+ at(NOW - 4 * HOUR);
+ const { store, token: tokenA } = await enabled();
+ const channelA = stored(store);
+ at(NOW);
+ let tokenC = '';
+ let channelB: StoredState | undefined;
+ api.watch.mockImplementationOnce(async ({ channel }) => {
+ tokenC = channel.token;
+ await hooks.onEnable(ctx({ store }));
+ channelB = stored(store);
+ return { id: channel.id, resourceId: 'res-C', expiration: String(channel.expiration) };
+ });
+ api.stop.mockClear();
+
+ await expect(hooks.onRenew(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(channelB?.resourceId).toBe('res-2');
+ expect(stored(store)).toEqual(channelB);
+ expect(api.stop.mock.calls.map(([params]) => params.channel.resourceId)).toEqual([channelA.resourceId, 'res-C']);
+ expect(store.data.has(PENDING_KEY)).toBe(false);
+ expect(store.data.has(PREVIOUS_KEY)).toBe(false);
+ await expect(deliver({ store, token: channelB?.token ?? '' })).resolves.toHaveLength(1);
+ await expect(deliver({ store, token: tokenC })).resolves.toEqual([]);
+ await expect(deliver({ store, token: tokenA })).resolves.toEqual([]);
+ });
+
+ it('should keep the pending token of a republish still watching when a superseded renewal gives up', async () => {
+ at(NOW - 4 * HOUR);
+ const { store } = await enabled();
+ at(NOW);
+ api.watch.mockImplementationOnce(async ({ channel }) => {
+ store.data.delete(STORE_KEY);
+ store.data.set(PENDING_KEY, 'republish-token');
+ return { id: channel.id, resourceId: 'res-C', expiration: String(channel.expiration) };
+ });
+ api.stop.mockClear();
+
+ await hooks.onRenew(ctx({ store }));
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel.resourceId)).toEqual(['res-C']);
+ expect(store.data.has(STORE_KEY)).toBe(false);
+ expect(store.data.get(PENDING_KEY)).toBe('republish-token');
+ await expect(deliver({ store, token: 'republish-token' })).resolves.toHaveLength(1);
+ });
+
+ it('should leave the pending token of another flow when its own watch fails', async () => {
+ const { store, token } = await enabled();
+ api.watch.mockImplementationOnce(async () => {
+ store.data.set(PENDING_KEY, 'republish-token');
+ throw new Error('403 forbidden');
+ });
+
+ await expect(hooks.onRenew(ctx({ store }))).rejects.toThrow('403 forbidden');
+
+ expect(store.data.get(PENDING_KEY)).toBe('republish-token');
+ await expect(deliver({ store, token: 'republish-token' })).resolves.toHaveLength(1);
+ await expect(deliver({ store, token })).resolves.toHaveLength(1);
+ });
+
+ it('should stop only the channel being replaced on consecutive renewals', async () => {
+ const { store, newToken } = await renewed();
+ api.stop.mockClear();
+
+ at(NOW + 4 * HOUR);
+ await hooks.onRenew(ctx({ store }));
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel.resourceId)).toEqual(['res-2']);
+ expect(store.data.get(PREVIOUS_KEY)).toEqual({ previousToken: newToken, previousStoppedAt: NOW + 4 * HOUR });
+ });
+ });
+
+ describe('run()', () => {
+ it('should key every emitted event by its id for the platform dedupe', async () => {
+ const { store, token } = await enabled();
+ const body = {
+ ...SAMPLE_EVENT.activity,
+ events: [
+ { type: 'USER_SETTINGS', name: 'CREATE_USER', parameters: [] },
+ { type: 'USER_SETTINGS', name: 'DELETE_USER', parameters: [] },
+ ],
+ };
+
+ const items = await deliver({ store, token, body });
+
+ expect(items).toHaveLength(2);
+ expect(items.map((i) => i[DEDUPE_KEY_PROPERTY])).toEqual(items.map((i) => i['id']));
+ expect(items.map((i) => i[DEDUPE_KEY_PROPERTY])).toEqual([`${SAMPLE_EVENT.id}:0`, `${SAMPLE_EVENT.id}:1`]);
+ });
+
+ it('should key events from the current and the previous channel the same way so the overlap collapses', async () => {
+ const { store, oldToken, newToken } = await renewed();
+ const { body, eventId } = activityAt({ time: NOW });
+
+ const fromNew = await deliver({ store, token: newToken, body });
+ const fromOld = await deliver({ store, token: oldToken, body });
+
+ expect(fromNew).toEqual([expect.objectContaining({ id: eventId, [DEDUPE_KEY_PROPERTY]: eventId })]);
+ expect(fromOld).toEqual(fromNew);
+ });
+
+ it('should never write to the store, whatever is delivered', async () => {
+ const { store, oldToken, newToken } = await renewed();
+ store.put.mockClear();
+ store.delete.mockClear();
+ const before = structuredClone([...store.data.entries()]);
+
+ await deliver({ store, token: newToken, body: activityAt({ time: NOW + MINUTE }).body });
+ await deliver({ store, token: oldToken, body: activityAt({ time: NOW - 5 * MINUTE }).body });
+ at(NOW + IN_FLIGHT_MS);
+ await deliver({ store, token: oldToken });
+ await deliver({ store, token: 'forged' });
+ await deliver({ store, token: newToken, body: { ...SAMPLE_EVENT.activity, events: [{ type: 'USER_SETTINGS', name: 'IGNORED', parameters: [] }] } });
+ await hooks.run(ctx({ store, payload: { headers: { 'x-goog-channel-token': newToken, 'x-goog-resource-state': 'sync' } } }));
+
+ expect(store.put).not.toHaveBeenCalled();
+ expect(store.delete).not.toHaveBeenCalled();
+ expect([...store.data.entries()]).toEqual(before);
+ });
+
+ it('should emit a retried delivery again so a failed submission loses nothing', async () => {
+ const { store, token } = await enabled();
+
+ const first = await deliver({ store, token });
+ const retried = await deliver({ store, token });
+
+ expect(first).toEqual([expect.objectContaining({ id: SAMPLE_EVENT.id, [DEDUPE_KEY_PROPERTY]: SAMPLE_EVENT.id })]);
+ expect(retried).toEqual(first);
+ });
+
+ it('should turn a notification with the right token into events, applying the accept filter', async () => {
+ const { store, token } = await enabled();
+ const body = {
+ ...SAMPLE_EVENT.activity,
+ events: [
+ { type: 'USER_SETTINGS', name: 'CREATE_USER', parameters: [{ name: 'USER_EMAIL', value: '[email protected]' }] },
+ { type: 'USER_SETTINGS', name: 'IGNORED', parameters: [] },
+ ],
+ };
+
+ const items = (await hooks.run(ctx({ store, payload: { headers: { 'X-Goog-Channel-Token': token, 'x-goog-resource-state': 'exists' }, body } }))) as {
+ eventName: string;
+ }[];
+
+ expect(items.map((i) => i.eventName)).toEqual(['CREATE_USER']);
+ });
+
+ it('should ignore the sync message and anything without a known channel token', async () => {
+ const { store, token } = await enabled();
+
+ await expect(hooks.run(ctx({ store, payload: { headers: { 'x-goog-channel-token': token, 'x-goog-resource-state': 'sync' } } }))).resolves.toEqual([]);
+ await expect(deliver({ store, token: 'forged' })).resolves.toEqual([]);
+ await expect(hooks.run(ctx({ store, payload: { headers: {}, body: SAMPLE_EVENT.activity } }))).resolves.toEqual([]);
+ await expect(deliver({ store: memoryStore(), token })).resolves.toEqual([]);
+ });
+
+ it('should accept every activity from the current channel whatever its time, late logs included', async () => {
+ const { store, newToken } = await renewed();
+
+ for (const deliveredAt of [NOW, NOW + 30 * MINUTE, NOW + 3 * HOUR]) {
+ at(deliveredAt);
+ for (const time of [NOW - 5 * HOUR, NOW - 30 * MINUTE, NOW - 1, NOW, NOW + 10 * MINUTE, null]) {
+ await expect(deliver({ store, token: newToken, body: activityAt({ time }).body })).resolves.toHaveLength(1);
+ }
+ }
+ });
+
+ it('should accept the previous channel token only within the in-flight window after it was stopped', async () => {
+ const { store, oldToken } = await renewed();
+ const late = activityAt({ time: NOW - 30 * MINUTE }).body;
+
+ at(NOW + IN_FLIGHT_MS - 1);
+ await expect(deliver({ store, token: oldToken, body: late })).resolves.toHaveLength(1);
+ at(NOW + IN_FLIGHT_MS);
+ await expect(deliver({ store, token: oldToken, body: late })).resolves.toEqual([]);
+ });
+
+ it('should reject the token of a channel replaced two renewals ago', async () => {
+ const { store, oldToken } = await renewed();
+ at(NOW + 4 * HOUR);
+ await hooks.onRenew(ctx({ store }));
+
+ await expect(deliver({ store, token: oldToken })).resolves.toEqual([]);
+ });
+ });
+
+ describe('onDisable()', () => {
+ it('should stop the current channel and delete the channel, pending and previous keys', async () => {
+ const { store } = await renewed();
+ store.data.set(PENDING_KEY, 'stale');
+ store.delete.mockClear();
+ api.stop.mockClear();
+
+ await expect(hooks.onDisable(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel.resourceId)).toEqual(['res-2']);
+ expect(store.delete.mock.calls.map(([key]) => key)).toEqual([STORE_KEY, PENDING_KEY, PREVIOUS_KEY]);
+ expect([...store.data.keys()]).toEqual([DISABLED_KEY]);
+ });
+
+ it('should tolerate a channel that is already expired', async () => {
+ const { store } = await enabled();
+ api.stop.mockRejectedValueOnce(googleError(404));
+
+ await expect(hooks.onDisable(ctx({ store }))).resolves.toBeUndefined();
+
+ expect([...store.data.keys()]).toEqual([DISABLED_KEY]);
+ });
+
+ it('should fail without forgetting the channel when Google refuses to stop it, and stop it on retry', async () => {
+ const { store } = await enabled();
+ const channel = stored(store);
+ api.stop.mockRejectedValueOnce(googleError(403));
+
+ await expect(hooks.onDisable(ctx({ store }))).rejects.toThrow(
+ `Could not stop the Google Workspace notification channel(s) ${channel.id}: Google Workspace API returned 403.`
+ );
+
+ expect(stored(store)).toEqual(channel);
+ expect(store.data.get(UNSTOPPED_KEY)).toEqual([{ id: channel.id, resourceId: 'res-1' }]);
+ api.stop.mockClear();
+
+ await expect(hooks.onDisable(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel)).toEqual([{ id: channel.id, resourceId: 'res-1' }]);
+ expect([...store.data.keys()]).toEqual([DISABLED_KEY]);
+ });
+
+ it('should stop the renewal channel when disable runs after the renewal check and before it saves the channel', async () => {
+ at(NOW - 4 * HOUR);
+ const { store } = await enabled();
+ const old = stored(store);
+ at(NOW);
+ const save = store.put.getMockImplementation();
+ let paused = false;
+ store.put.mockImplementation(async (key, value) => {
+ if (key === STORE_KEY && !paused) {
+ paused = true;
+ await hooks.onDisable(ctx({ store }));
+ }
+ return save ? save(key, value) : value;
+ });
+ api.stop.mockClear();
+
+ await expect(hooks.onRenew(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(paused).toBe(true);
+ expect(new Set(api.stop.mock.calls.map(([params]) => params.channel.resourceId))).toEqual(new Set([old.resourceId, 'res-2']));
+ expect([...store.data.keys()]).toEqual([DISABLED_KEY]);
+ });
+
+ it('should stop the renewal channel when disable runs after the renewal saved the channel and before it reads the disable marker', async () => {
+ at(NOW - 4 * HOUR);
+ const { store } = await enabled();
+ const old = stored(store);
+ at(NOW);
+ const read = store.get.getMockImplementation();
+ let paused = false;
+ store.get.mockImplementation(async (key) => {
+ if (key === DISABLED_KEY && !paused) {
+ paused = true;
+ await hooks.onDisable(ctx({ store }));
+ }
+ return read ? read(key) : null;
+ });
+ api.stop.mockClear();
+
+ await expect(hooks.onRenew(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(paused).toBe(true);
+ expect(new Set(api.stop.mock.calls.map(([params]) => params.channel.resourceId))).toEqual(new Set([old.resourceId, 'res-2']));
+ expect([...store.data.keys()]).toEqual([DISABLED_KEY]);
+ });
+
+ it('should fail and keep every key when the channel cannot be stopped because the connection fails', async () => {
+ const { store } = await enabled();
+ const before = structuredClone([...store.data.entries()]);
+ resolveAuth.mockRejectedValueOnce(new Error('A Google Workspace connection is required.'));
+
+ await expect(hooks.onDisable(ctx({ store }))).rejects.toThrow('A Google Workspace connection is required.');
+
+ expect(api.stop).not.toHaveBeenCalled();
+ expect([...store.data.entries()].filter(([key]) => key !== UNSTOPPED_KEY && key !== DISABLED_KEY)).toEqual(before);
+ expect(store.data.get(UNSTOPPED_KEY)).toEqual([{ id: stored(store).id, resourceId: 'res-1' }]);
+ });
+ });
+
+ describe('onEnable() with a channel that cannot be stopped', () => {
+ it('should warn, keep the stale channel for a retry and still open the new channel', async () => {
+ const { store } = await enabled();
+ const stale = stored(store);
+ api.watch.mockClear();
+ api.stop.mockRejectedValueOnce(googleError(500));
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+
+ await expect(hooks.onEnable(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(`Could not stop the Google Workspace notification channel(s) ${stale.id}`));
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('The new channel was opened anyway.'));
+ expect(api.watch).toHaveBeenCalledTimes(1);
+ expect(stored(store).id).not.toBe(stale.id);
+ expect(store.data.get(UNSTOPPED_KEY)).toEqual([{ id: stale.id, resourceId: stale.resourceId }]);
+ warn.mockRestore();
+ });
+
+ it('should stop the channel left over by a failed enable on the next enable', async () => {
+ const { store } = await enabled();
+ const stale = stored(store);
+ api.stop.mockRejectedValueOnce(googleError(500));
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ await hooks.onEnable(ctx({ store }));
+ const current = stored(store);
+ api.stop.mockClear();
+
+ await hooks.onEnable(ctx({ store }));
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel.id).sort()).toEqual([current.id, stale.id].sort());
+ expect(store.data.has(UNSTOPPED_KEY)).toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockRestore();
+ });
+ });
+
+ describe('flow versions', () => {
+ it('should read the flow version id from the context in every hook', async () => {
+ const store = memoryStore();
+ const reads: string[] = [];
+ const tracked = ({ hook, payload }: { hook: string; payload?: { headers: Record<string, string>; body: unknown } }) => {
+ const context = ctx({ store, payload });
+ Object.defineProperty(context.flows.current, 'version', {
+ get: () => {
+ reads.push(hook);
+ return { id: VERSION };
+ },
+ });
+ return context;
+ };
+
+ await hooks.onEnable(tracked({ hook: 'onEnable' }));
+ await hooks.onRenew(tracked({ hook: 'onRenew' }));
+ const items = await hooks.run(
+ tracked({ hook: 'run', payload: { headers: { 'x-goog-channel-token': stored(store).token }, body: SAMPLE_EVENT.activity } })
+ );
+ await hooks.onDisable(tracked({ hook: 'onDisable' }));
+
+ expect(items).toHaveLength(1);
+ expect([...new Set(reads)]).toEqual(['onEnable', 'onRenew', 'run', 'onDisable']);
+ expect([...store.data.keys()]).toEqual([DISABLED_KEY]);
+ });
+
+ it('should keep every key of a version under its flow version id', async () => {
+ const { store } = await renewed();
+ store.data.set(PENDING_KEY, 'pending');
+
+ await hooks.onEnable(ctx({ store, version: NEXT_VERSION }));
+
+ expect([...store.data.keys()].sort()).toEqual([STORE_KEY, PENDING_KEY, PREVIOUS_KEY, keysOf(NEXT_VERSION).channel].sort());
+ });
+
+ it('should leave the new version channel untouched when an old version renewal finishes after its onEnable', async () => {
+ at(NOW - 4 * HOUR);
+ const { store, token: tokenA } = await enabled();
+ const channelA = stored(store);
+ at(NOW);
+ let tokenC = '';
+ let channelB: StoredState | undefined;
+ api.watch.mockImplementationOnce(async ({ channel }) => {
+ tokenC = channel.token;
+ await hooks.onEnable(ctx({ store, version: NEXT_VERSION }));
+ channelB = stored(store, NEXT_VERSION);
+ return { id: channel.id, resourceId: 'res-C', expiration: String(channel.expiration) };
+ });
+ api.stop.mockClear();
+
+ await expect(hooks.onRenew(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(channelB?.resourceId).toBe('res-2');
+ expect(stored(store, NEXT_VERSION)).toEqual(channelB);
+ expect(store.data.has(keysOf(NEXT_VERSION).previous)).toBe(false);
+ expect(stored(store).resourceId).toBe('res-C');
+ expect(api.stop.mock.calls.map(([params]) => params.channel.resourceId)).toEqual([channelA.resourceId]);
+ await expect(deliver({ store, token: channelB?.token ?? '', version: NEXT_VERSION })).resolves.toHaveLength(1);
+ await expect(deliver({ store, token: tokenC, version: NEXT_VERSION })).resolves.toEqual([]);
+ await expect(deliver({ store, token: tokenA, version: NEXT_VERSION })).resolves.toEqual([]);
+ });
+
+ it('should stop the channel an old version renewal opened after that version was disabled', async () => {
+ at(NOW - 4 * HOUR);
+ const { store } = await enabled();
+ const channelA = stored(store);
+ at(NOW);
+ let channelB: StoredState | undefined;
+ api.watch.mockImplementationOnce(async ({ channel }) => {
+ await hooks.onEnable(ctx({ store, version: NEXT_VERSION }));
+ channelB = stored(store, NEXT_VERSION);
+ await hooks.onDisable(ctx({ store }));
+ return { id: channel.id, resourceId: 'res-C', expiration: String(channel.expiration) };
+ });
+ api.stop.mockClear();
+
+ await expect(hooks.onRenew(ctx({ store }))).resolves.toBeUndefined();
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel.resourceId)).toEqual([channelA.resourceId, 'res-C']);
+ expect([...store.data.keys()].sort()).toEqual([DISABLED_KEY, keysOf(NEXT_VERSION).channel].sort());
+ expect(stored(store, NEXT_VERSION)).toEqual(channelB);
+ await expect(deliver({ store, token: channelB?.token ?? '', version: NEXT_VERSION })).resolves.toHaveLength(1);
+ });
+
+ it('should stop only its own channel and delete only its own keys on disable', async () => {
+ const { store } = await enabled();
+ await hooks.onEnable(ctx({ store, version: NEXT_VERSION }));
+ const channelB = stored(store, NEXT_VERSION);
+ api.stop.mockClear();
+
+ await hooks.onDisable(ctx({ store }));
+
+ expect(api.stop.mock.calls.map(([params]) => params.channel.resourceId)).toEqual(['res-1']);
+ expect([...store.data.keys()].sort()).toEqual([DISABLED_KEY, keysOf(NEXT_VERSION).channel].sort());
+ await expect(deliver({ store, token: channelB.token, version: NEXT_VERSION })).resolves.toHaveLength(1);
+ });
+ });
+
+ it('should read the latest activities through the list endpoint on test, flattened and filtered', async () => {
+ api.listActivities.mockResolvedValue([
+ { id: { time: 't1', uniqueQualifier: '1' }, events: [{ type: 'USER_SETTINGS', name: 'CREATE_USER' }, { name: 'IGNORED' }] },
+ { id: { time: 't2', uniqueQualifier: '2' }, events: [{ type: 'USER_SETTINGS', name: 'CREATE_USER' }] },
+ ]);
+
+ const items = (await hooks.test(ctx({ store: memoryStore() }))) as { id: string }[];
+
+ expect(api.listActivities).toHaveBeenCalledWith({ auth: RESOLVED, query: { application: 'admin', eventName: 'CREATE_USER', maxResults: 50 } });
+ expect(items.map((i) => i.id)).toEqual(['t1:1:0', 't2:2']);
+ expect(items.every((i) => !Object.prototype.hasOwnProperty.call(i, DEDUPE_KEY_PROPERTY))).toBe(true);
+ expect(api.watch).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/common/client.test.ts b/packages/pieces/community/google-workspace/test/lib/common/client.test.ts
new file mode 100644
index 00000000000..78f3cf8bd13
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/common/client.test.ts
@@ -0,0 +1,300 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const network = vi.hoisted(() => ({ unexpectedCalls: 0 }));
+const fetchMock = vi.hoisted(() =>
+ vi.fn<(input: string | URL | Request, init?: RequestInit) => Promise<Response>>(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ })
+);
+vi.stubGlobal('fetch', fetchMock);
+
+const { HttpMethod } = await import('@activepieces/pieces-common');
+const { googleWorkspaceClient } = await import('../../../src/lib/common/client');
+const { googleWorkspaceUtils } = await import('../../../src/lib/common/utils');
+
+const GOOGLE_ADMIN_API_ROOT = googleWorkspaceClient.baseUrl();
+const GoogleWorkspaceApi = googleWorkspaceClient;
+const GoogleWorkspaceApiError = googleWorkspaceClient.ApiError;
+const assertCustomApiCallUrl = (propsValue: { url?: { url?: string } }) => googleWorkspaceUtils.assertCustomApiCallUrl(propsValue.url?.url);
+
+const TOKEN = 'ya29.test-token';
+const AUTH = { access_token: TOKEN };
+
+function jsonResponse(status: number, body: unknown): Response {
+ return new Response(typeof body === 'string' ? body : JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+}
+
+function answerWith(status: number, body: unknown): void {
+ fetchMock.mockImplementation(async () => jsonResponse(status, body));
+}
+
+function sentUrl(call = 0): URL {
+ return new URL(String(fetchMock.mock.calls[call]?.[0]));
+}
+
+function sentInit(call = 0): RequestInit {
+ return fetchMock.mock.calls[call]?.[1] ?? {};
+}
+
+beforeEach(() => {
+ network.unexpectedCalls = 0;
+ fetchMock.mockReset().mockImplementation(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ expect(network.unexpectedCalls).toBe(0);
+ expect(globalThis.fetch).toBe(fetchMock);
+});
+
+describe('GoogleWorkspaceApi', () => {
+ describe('request()', () => {
+ it('should call the Admin SDK root with the bearer token, a deadline and no empty query params', async () => {
+ answerWith(200, { primaryEmail: '[email protected]' });
+
+ const body = await GoogleWorkspaceApi.request({
+ auth: AUTH,
+ method: HttpMethod.GET,
+ path: '/admin/directory/v1/users/jane%40example.com',
+ query: { projection: 'full', customFieldMask: undefined, viewType: '' },
+ });
+
+ expect(body).toEqual({ primaryEmail: '[email protected]' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe(`${GOOGLE_ADMIN_API_ROOT}/admin/directory/v1/users/jane%40example.com?projection=full`);
+ const init = sentInit();
+ expect(init.method).toBe('GET');
+ expect(init.headers).toEqual({ Authorization: `Bearer ${TOKEN}`, Accept: 'application/json' });
+ expect(init.body).toBeUndefined();
+ expect(init.signal).toBeInstanceOf(AbortSignal);
+ });
+
+ it('should use the 60 second deadline by default and a shorter per-call timeout capped by it', async () => {
+ answerWith(200, {});
+ const timeout = vi.spyOn(AbortSignal, 'timeout');
+
+ await GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'a' });
+ await GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'a', timeoutMs: 30_000 });
+ await GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'a', timeoutMs: 110_000 });
+ await GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'a', timeoutMs: 0.4 });
+
+ expect(timeout.mock.calls.map(([ms]) => ms)).toEqual([60_000, 30_000, 60_000, 1]);
+ timeout.mockRestore();
+ });
+
+ it('should send the body as JSON on writes and add no query string when there is none', async () => {
+ answerWith(200, { id: '1' });
+
+ await GoogleWorkspaceApi.request({
+ auth: AUTH,
+ method: HttpMethod.POST,
+ path: 'admin/directory/v1/groups',
+ body: { email: '[email protected]' },
+ });
+
+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe(`${GOOGLE_ADMIN_API_ROOT}/admin/directory/v1/groups`);
+ const init = sentInit();
+ expect(init.method).toBe('POST');
+ expect(init.headers).toEqual({ Authorization: `Bearer ${TOKEN}`, Accept: 'application/json', 'Content-Type': 'application/json' });
+ expect(JSON.parse(String(init.body))).toEqual({ email: '[email protected]' });
+ });
+
+ it('should encode numeric and boolean query values as strings', async () => {
+ answerWith(200, { users: [] });
+
+ await GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'admin/directory/v1/users', query: { maxResults: 50, showDeleted: false } });
+
+ expect(Object.fromEntries(sentUrl().searchParams)).toEqual({ maxResults: '50', showDeleted: 'false' });
+ });
+
+ it('should resolve an empty object for a 204 or an empty success body', async () => {
+ fetchMock.mockImplementationOnce(async () => new Response(null, { status: 204 }));
+ await expect(GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.DELETE, path: 'admin/directory/v1/users/1' })).resolves.toEqual({});
+
+ fetchMock.mockImplementationOnce(async () => new Response('', { status: 200 }));
+ await expect(
+ GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.POST, path: 'admin/reports_v1/channels/stop', body: { id: 'c' } })
+ ).resolves.toEqual({});
+ });
+
+ it('should reject a success body that is not JSON without echoing it', async () => {
+ fetchMock.mockImplementationOnce(async () => new Response('not json at all', { status: 200 }));
+
+ const failure = await GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'admin/directory/v1/users' }).catch((e: unknown) => e);
+
+ expect(failure).toBeInstanceOf(GoogleWorkspaceApiError);
+ expect((failure as Error).message).toBe('Google Workspace API returned 200 with a response that is not JSON.');
+ });
+
+ it('should turn a Google error body into a GoogleWorkspaceApiError with reason, message and hint', async () => {
+ answerWith(404, {
+ error: {
+ code: 404,
+ message: 'Resource Not Found: userKey',
+ errors: [{ domain: 'global', reason: 'notFound', message: 'Resource Not Found: userKey' }],
+ },
+ });
+
+ const failure = await GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'admin/directory/v1/users/x' }).catch(
+ (e: unknown) => e
+ );
+
+ expect(failure).toBeInstanceOf(GoogleWorkspaceApiError);
+ const error = failure as InstanceType<typeof GoogleWorkspaceApiError>;
+ expect(error.status).toBe(404);
+ expect(error.hasReason('notFound')).toBe(true);
+ expect(error.errors).toEqual([{ reason: 'notFound', message: 'Resource Not Found: userKey', domain: 'global' }]);
+ expect(error.message).toBe(
+ 'Google Workspace API returned 404: notFound: Resource Not Found: userKey Check the identifier: user and group keys are e-mails or ids, org units are paths, devices use their resource id.'
+ );
+ expect(error.cause).toBeUndefined();
+ });
+
+ it('should tell the user to enable the Admin SDK API on accessNotConfigured', async () => {
+ answerWith(403, {
+ error: {
+ code: 403,
+ status: 'PERMISSION_DENIED',
+ message: 'Admin SDK API has not been used in project 123 before or it is disabled.',
+ errors: [{ reason: 'accessNotConfigured', message: 'Access Not Configured.' }],
+ },
+ });
+
+ await expect(GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'admin/directory/v1/users' })).rejects.toThrow(
+ 'Google Workspace API returned 403 (PERMISSION_DENIED): accessNotConfigured: Access Not Configured. Enable the Admin SDK API'
+ );
+ });
+
+ it('should fall back to the raw body when Google sends no structured error', async () => {
+ answerWith(502, 'Bad Gateway');
+
+ await expect(GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'admin/directory/v1/users' })).rejects.toThrow(
+ 'Google Workspace API returned 502: Bad Gateway'
+ );
+ });
+
+ it('should summarize an HTML error page instead of dumping it', async () => {
+ answerWith(
+ 404,
+ '<!DOCTYPE html>\n<html lang=en><title>Error 404 (Not Found)!!1</title><p>The requested URL <code>/admin/directory/v1/users/</code> was not found on this server.</p></html>'
+ );
+
+ await expect(GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'admin/directory/v1/users/' })).rejects.toThrow(
+ 'Google Workspace API returned 404: Error 404 (Not Found)!!1 for /admin/directory/v1/users/ (the request URL is malformed, usually an empty identifier). Check the identifier'
+ );
+ });
+
+ it('should report a network failure or timeout by its name only, without the request or a cause', async () => {
+ fetchMock.mockImplementationOnce(async (_input, init) => {
+ throw new TypeError('fetch failed', { cause: new Error(String(init?.body)) });
+ });
+
+ const failure = await GoogleWorkspaceApi.request({
+ auth: AUTH,
+ method: HttpMethod.POST,
+ path: 'admin/directory/v1/users',
+ body: { password: 'S3cret-network!' },
+ }).catch((e: unknown) => e);
+
+ expect(failure).toBeInstanceOf(Error);
+ const error = failure as Error;
+ expect(error.message).toBe('Could not reach the Google Workspace API (TypeError). Try again in a moment.');
+ expect(error.cause).toBeUndefined();
+ expect(`${error.message} ${error.stack ?? ''}`).not.toContain('S3cret-network!');
+
+ fetchMock.mockImplementationOnce(async () => {
+ throw new DOMException('The operation was aborted due to timeout', 'TimeoutError');
+ });
+ await expect(GoogleWorkspaceApi.request({ auth: AUTH, method: HttpMethod.GET, path: 'admin/directory/v1/users' })).rejects.toThrow(
+ 'Could not reach the Google Workspace API (TimeoutError). Try again in a moment.'
+ );
+ });
+ });
+
+ describe('listPage()', () => {
+ it('should read the collection array by its key and the next page token', async () => {
+ answerWith(200, { kind: 'admin#directory#users', users: [{ id: '1' }], nextPageToken: 'p2' });
+
+ const page = await GoogleWorkspaceApi.listPage({ auth: AUTH, path: 'admin/directory/v1/users', itemsKey: 'users', query: { customer: 'my_customer' } });
+
+ expect(page).toEqual({ items: [{ id: '1' }], nextPageToken: 'p2' });
+ expect(Object.fromEntries(sentUrl().searchParams)).toEqual({ customer: 'my_customer' });
+ });
+
+ it('should return an empty list when the collection key is absent', async () => {
+ answerWith(200, { kind: 'admin#directory#groups' });
+
+ await expect(GoogleWorkspaceApi.listPage({ auth: AUTH, path: 'admin/directory/v1/groups', itemsKey: 'groups' })).resolves.toEqual({ items: [] });
+ });
+ });
+
+ describe('listAll()', () => {
+ it('should follow nextPageToken until exhausted', async () => {
+ fetchMock
+ .mockImplementationOnce(async () => jsonResponse(200, { users: [{ id: '1' }, { id: '2' }], nextPageToken: 'p2' }))
+ .mockImplementationOnce(async () => jsonResponse(200, { users: [{ id: '3' }] }));
+
+ const { items, truncated } = await GoogleWorkspaceApi.listAll({ auth: AUTH, path: 'admin/directory/v1/users', itemsKey: 'users', query: { customer: 'my_customer' } });
+
+ expect(items).toEqual([{ id: '1' }, { id: '2' }, { id: '3' }]);
+ expect(truncated).toBe(false);
+ expect(Object.fromEntries(sentUrl(1).searchParams)).toEqual({ customer: 'my_customer', pageToken: 'p2' });
+ });
+
+ it('should stop at maxRows and flag the result as truncated', async () => {
+ answerWith(200, { users: [{ id: '1' }, { id: '2' }, { id: '3' }], nextPageToken: 'more' });
+
+ const { items, truncated } = await GoogleWorkspaceApi.listAll({ auth: AUTH, path: 'admin/directory/v1/users', itemsKey: 'users', query: {}, maxRows: 2 });
+
+ expect(items).toEqual([{ id: '1' }, { id: '2' }]);
+ expect(truncated).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not fetch another page once a full page reaches maxRows', async () => {
+ fetchMock.mockImplementationOnce(async () => jsonResponse(200, { users: [{ id: '1' }, { id: '2' }], nextPageToken: 'more' }));
+
+ const { items, truncated } = await GoogleWorkspaceApi.listAll({ auth: AUTH, path: 'admin/directory/v1/users', itemsKey: 'users', query: {}, maxRows: 2 });
+
+ expect(items).toEqual([{ id: '1' }, { id: '2' }]);
+ expect(truncated).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('should report a complete result when the last page lands exactly on maxRows', async () => {
+ fetchMock.mockImplementationOnce(async () => jsonResponse(200, { users: [{ id: '1' }, { id: '2' }] }));
+
+ const { items, truncated } = await GoogleWorkspaceApi.listAll({ auth: AUTH, path: 'admin/directory/v1/users', itemsKey: 'users', query: {}, maxRows: 2 });
+
+ expect(items).toHaveLength(2);
+ expect(truncated).toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+ });
+});
+
+describe('assertCustomApiCallUrl()', () => {
+ it('should allow relative paths and full URLs on the Admin SDK host', () => {
+ expect(() => assertCustomApiCallUrl({ url: { url: '/admin/directory/v1/users' } })).not.toThrow();
+ expect(() => assertCustomApiCallUrl({ url: { url: 'admin/reports/v1/activity/users/all/applications/login' } })).not.toThrow();
+ expect(() => assertCustomApiCallUrl({ url: { url: 'https://admin.googleapis.com/admin/directory/v1/users' } })).not.toThrow();
+ expect(() => assertCustomApiCallUrl({})).not.toThrow();
+ });
+
+ it('should refuse a full URL on another host before the token is attached', () => {
+ expect(() => assertCustomApiCallUrl({ url: { url: 'https://attacker.example.com/collect' } })).toThrow(
+ 'Custom API Call only sends the Google Workspace credentials to https://admin.googleapis.com, not to https://attacker.example.com.'
+ );
+ expect(() => assertCustomApiCallUrl({ url: { url: 'https://admin.googleapis.com.attacker.example.com/x' } })).toThrow('not to');
+ expect(() => assertCustomApiCallUrl({ url: { url: 'https://www.googleapis.com/drive/v3/files' } })).toThrow('not to');
+ expect(() => assertCustomApiCallUrl({ url: { url: 'http://admin.googleapis.com/admin/directory/v1/users' } })).toThrow('not to');
+ });
+
+ it('should refuse a full URL that cannot be parsed', () => {
+ expect(() => assertCustomApiCallUrl({ url: { url: 'https://' } })).toThrow('is not valid');
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/common/data-transfer.test.ts b/packages/pieces/community/google-workspace/test/lib/common/data-transfer.test.ts
new file mode 100644
index 00000000000..03cfabcf73e
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/common/data-transfer.test.ts
@@ -0,0 +1,92 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const network = vi.hoisted(() => ({ unexpectedCalls: 0 }));
+const fetchMock = vi.hoisted(() =>
+ vi.fn<(input: string | URL | Request, init?: RequestInit) => Promise<Response>>(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ })
+);
+vi.stubGlobal('fetch', fetchMock);
+
+const { googleWorkspaceClient } = await import('../../../src/lib/common/client');
+const { googleWorkspaceProps } = await import('../../../src/lib/common/props');
+const { transferData } = await import('../../../src/lib/actions/transfer-data');
+
+const GOOGLE_ADMIN_API_ROOT = googleWorkspaceClient.baseUrl();
+const AUTH = { type: 'OAUTH2', access_token: 'ya29.test-token' };
+const listApplications = () => googleWorkspaceProps.applicationId({ required: true }).options({ auth: AUTH } as never, {} as never);
+const transfer = (propsValue: Record<string, unknown>) => transferData.run({ auth: AUTH, propsValue } as never);
+
+function replyOnce(body: unknown): void {
+ fetchMock.mockImplementationOnce(async () => Response.json(body));
+}
+
+function sent(call: number): { url: URL; method: string | undefined; body: unknown } {
+ const [input, init] = fetchMock.mock.calls[call] ?? [];
+ return { url: new URL(String(input)), method: init?.method, body: init?.body === undefined ? undefined : JSON.parse(String(init.body)) };
+}
+
+function pathOf(url: URL): string {
+ return `${url.origin}${url.pathname}`;
+}
+
+beforeEach(() => {
+ network.unexpectedCalls = 0;
+ fetchMock.mockReset().mockImplementation(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ expect(network.unexpectedCalls).toBe(0);
+});
+
+describe('transferable applications', () => {
+ it('should list them under my_customer, following pages', async () => {
+ replyOnce({ applications: [{ id: '1', name: 'Drive and Docs' }], nextPageToken: 'p2' });
+ replyOnce({ applications: [{ id: '2', name: 'Calendar' }] });
+
+ const state = await listApplications();
+
+ expect(state.options.map((o) => o.label)).toEqual(['Drive and Docs', 'Calendar']);
+ const first = sent(0);
+ expect(pathOf(first.url)).toBe(`${GOOGLE_ADMIN_API_ROOT}/admin/datatransfer/v1/applications`);
+ expect(Object.fromEntries(first.url.searchParams)).toEqual({ customerId: 'my_customer', maxResults: '100' });
+ });
+});
+
+describe('transfer requests', () => {
+ it('should POST the transfer, passing numeric user ids through without a lookup', async () => {
+ replyOnce({ id: 't1', oldOwnerUserId: '1', newOwnerUserId: '2', overallTransferStatusCode: 'inProgress' });
+
+ await transfer({ oldOwner: ' 1 ', newOwner: '2', applicationId: '55' });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(sent(0)).toEqual({
+ url: new URL(`${GOOGLE_ADMIN_API_ROOT}/admin/datatransfer/v1/transfers`),
+ method: 'POST',
+ body: { oldOwnerUserId: '1', newOwnerUserId: '2', applicationDataTransfers: [{ applicationId: '55' }] },
+ });
+ });
+
+ it('should look up an e-mail in the Directory and use its id', async () => {
+ replyOnce({ id: '998877', primaryEmail: '[email protected]' });
+ replyOnce({ id: 't1', oldOwnerUserId: '998877', newOwnerUserId: '2', overallTransferStatusCode: 'inProgress' });
+
+ await transfer({ oldOwner: '[email protected]', newOwner: '2', applicationId: '55' });
+
+ const lookup = sent(0);
+ expect(pathOf(lookup.url)).toBe(`${GOOGLE_ADMIN_API_ROOT}/admin/directory/v1/users/jane%40example.com`);
+ expect(Object.fromEntries(lookup.url.searchParams)).toEqual({ projection: 'basic' });
+ expect(sent(1).body).toMatchObject({ oldOwnerUserId: '998877' });
+ });
+
+ it('should refuse an empty key and a user without id', async () => {
+ await expect(transfer({ oldOwner: '', newOwner: '2', applicationId: '55' })).rejects.toThrow('A user e-mail or id is required.');
+ replyOnce({ primaryEmail: '[email protected]' });
+ await expect(transfer({ oldOwner: '[email protected]', newOwner: '2', applicationId: '55' })).rejects.toThrow('Google returned no id for user "[email protected]".');
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/common/record-body.test.ts b/packages/pieces/community/google-workspace/test/lib/common/record-body.test.ts
new file mode 100644
index 00000000000..9fddd7c8aa6
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/common/record-body.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import { googleWorkspaceUtils } from '../../../src/lib/common/utils';
+
+const { recordBody, customFieldKey, resources } = googleWorkspaceUtils;
+
+describe('recordBody()', () => {
+ it('should nest form fields into the Directory API shape and drop empty ones', () => {
+ expect(
+ recordBody({
+ def: resources.user,
+ fields: { primaryEmail: '[email protected]', givenName: 'Jane', familyName: 'Doe', recoveryEmail: '', orgUnitPath: undefined },
+ extra: undefined,
+ })
+ ).toEqual({ primaryEmail: '[email protected]', name: { givenName: 'Jane', familyName: 'Doe' } });
+ });
+
+ it('should keep a checkbox set to false, which an update must be able to send', () => {
+ expect(recordBody({ def: resources.user, fields: { changePasswordAtNextLogin: false }, extra: undefined })).toEqual({
+ changePasswordAtNextLogin: false,
+ });
+ });
+
+ it('should merge Extra Fields with the form, the form winning on conflicts', () => {
+ expect(
+ recordBody({
+ def: resources.group,
+ fields: { name: 'Sales' },
+ extra: '{"name": "ignored", "description": "from json"}',
+ })
+ ).toEqual({ name: 'Sales', description: 'from json' });
+ });
+
+ it('should put custom fields under customSchemas, multi-valued ones as value objects', () => {
+ const single = customFieldKey({ schemaName: 'HR_Data', fieldName: 'employee_id' });
+ const multi = customFieldKey({ schemaName: 'HR_Data', fieldName: 'skills' });
+
+ expect(recordBody({ def: resources.user, fields: { [single]: 'E-42', [multi]: ['go', 'ts'] }, extra: undefined })).toEqual({
+ customSchemas: { HR_Data: { employee_id: 'E-42', skills: [{ value: 'go' }, { value: 'ts' }] } },
+ });
+ });
+
+ it('should ignore unknown keys and reject Extra Fields that are not an object', () => {
+ expect(recordBody({ def: resources.group, fields: { custom_bad: 'x', other: 'y' }, extra: '' })).toEqual({});
+ expect(() => recordBody({ def: resources.group, fields: {}, extra: '[1]' })).toThrow('The record must be a JSON object.');
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/common/service-account.test.ts b/packages/pieces/community/google-workspace/test/lib/common/service-account.test.ts
new file mode 100644
index 00000000000..29ca10cbd7d
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/common/service-account.test.ts
@@ -0,0 +1,322 @@
+import { createVerify, generateKeyPairSync } from 'node:crypto';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const network = vi.hoisted(() => ({ unexpectedCalls: 0 }));
+const fetchMock = vi.hoisted(() =>
+ vi.fn<(input: string | URL | Request, init?: RequestInit) => Promise<Response>>(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ })
+);
+vi.stubGlobal('fetch', fetchMock);
+
+const { googleWorkspaceClient } = await import('../../../src/lib/common/client');
+const { googleWorkspaceServiceAccount } = await import('../../../src/lib/auth');
+
+const { cachedTokenCount, buildAssertion, clearTokenCache, mintServiceAccountToken, normalizePrivateKey } = googleWorkspaceClient;
+const GOOGLE_TOKEN_URL = googleWorkspaceClient.tokenUrl;
+const validateServiceAccount = (creds: { clientEmail: string; privateKey: string; adminEmail: string }) =>
+ googleWorkspaceServiceAccount.validate?.({ auth: creds } as never);
+
+const { privateKey, publicKey } = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+});
+
+const CREDS = {
+ clientEmail: '[email protected]',
+ privateKey,
+ adminEmail: '[email protected]',
+};
+const SCOPES = ['https://www.googleapis.com/auth/admin.directory.user'];
+
+function decodeSegment(segment: string): Record<string, unknown> {
+ return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
+}
+
+function tokenResponse(status: number, body: unknown): Response {
+ return new Response(typeof body === 'string' ? body : JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+}
+
+function answerWith(status: number, body: unknown): void {
+ fetchMock.mockImplementation(async () => tokenResponse(status, body));
+}
+
+function sentAssertion(call = 0): string {
+ const init = fetchMock.mock.calls[call]?.[1];
+ return new URLSearchParams(String(init?.body ?? '')).get('assertion') ?? '';
+}
+
+function errorChainText(error: unknown): string {
+ const parts: string[] = [];
+ let current: unknown = error;
+ while (current !== undefined && current !== null) {
+ parts.push(current instanceof Error ? `${current.message} ${current.stack ?? ''}` : String(current));
+ parts.push(typeof current === 'object' ? JSON.stringify(current, Object.getOwnPropertyNames(current)) : String(current));
+ current = current instanceof Error ? current.cause : undefined;
+ }
+ return parts.join('\n');
+}
+
+async function captureRejection(promise: Promise<unknown>): Promise<unknown> {
+ try {
+ await promise;
+ } catch (error) {
+ return error;
+ }
+ throw new Error('expected the promise to reject');
+}
+
+beforeEach(() => {
+ network.unexpectedCalls = 0;
+ fetchMock.mockReset().mockImplementation(async () => {
+ network.unexpectedCalls++;
+ throw new Error('Unexpected real network call');
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ clearTokenCache();
+});
+
+afterEach(() => {
+ expect(network.unexpectedCalls).toBe(0);
+ expect(globalThis.fetch).toBe(fetchMock);
+ vi.restoreAllMocks();
+});
+
+describe('normalizePrivateKey()', () => {
+ it('should turn the literal newline sequences of a JSON key file into newlines and strip quotes', () => {
+ const pasted = `"${privateKey.replace(/\n/g, '\\n')}"`;
+
+ expect(normalizePrivateKey(pasted)).toBe(privateKey);
+ });
+
+ it('should rebuild a PEM whose newlines were lost in a one-line field or replaced by spaces', () => {
+ const oneLine = privateKey.replace(/\n/g, '');
+ const spaced = privateKey.replace(/\n/g, ' ');
+
+ expect(normalizePrivateKey(oneLine)).toBe(privateKey);
+ expect(normalizePrivateKey(spaced)).toBe(privateKey);
+ expect(() => buildAssertion({ creds: { ...CREDS, privateKey: oneLine }, scopes: SCOPES, now: 1_700_000_000 })).not.toThrow();
+ });
+
+ it('should refuse anything that is not a PEM private key', () => {
+ expect(() => normalizePrivateKey('AIzaSy-not-a-key')).toThrow('must be the PEM block');
+ expect(() => normalizePrivateKey('-----BEGIN PRIVATE KEY-----\n***\n-----END PRIVATE KEY-----')).toThrow('must be the PEM block');
+ });
+
+ it('should explain a key Node cannot decode instead of leaking the OpenSSL code', () => {
+ const corrupted = privateKey.replace(/\n/g, '').replace('MIIE', 'AAAA');
+ expect(() => buildAssertion({ creds: { ...CREDS, privateKey: corrupted }, scopes: SCOPES, now: 1_700_000_000 })).toThrow('The private key could not be read');
+ });
+});
+
+describe('buildAssertion()', () => {
+ it('should build an RS256 JWT with the delegation claims, verifiable with the public key', () => {
+ const jwt = buildAssertion({ creds: CREDS, scopes: SCOPES, now: 1_700_000_000 });
+ const [header, claims, signature] = jwt.split('.') as [string, string, string];
+
+ expect(decodeSegment(header)).toEqual({ alg: 'RS256', typ: 'JWT' });
+ expect(decodeSegment(claims)).toEqual({
+ iss: CREDS.clientEmail,
+ sub: CREDS.adminEmail,
+ scope: SCOPES[0],
+ aud: GOOGLE_TOKEN_URL,
+ iat: 1_700_000_000,
+ exp: 1_700_003_600,
+ });
+ expect(createVerify('RSA-SHA256').update(`${header}.${claims}`).end().verify(publicKey, signature, 'base64url')).toBe(true);
+ });
+});
+
+describe('mintServiceAccountToken()', () => {
+ it('should POST the jwt-bearer grant with fetch and return the access token', async () => {
+ answerWith(200, { access_token: 'ya29.minted', expires_in: 3600 });
+
+ await expect(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES })).resolves.toBe('ya29.minted');
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0] ?? [];
+ expect(url).toBe(GOOGLE_TOKEN_URL);
+ expect(init?.method).toBe('POST');
+ expect(init?.headers).toMatchObject({ 'Content-Type': 'application/x-www-form-urlencoded' });
+ const form = new URLSearchParams(String(init?.body));
+ expect(form.get('grant_type')).toBe('urn:ietf:params:oauth:grant-type:jwt-bearer');
+ expect(form.get('assertion')).toMatch(/^[\w-]+\.[\w-]+\.[\w-]+$/);
+ });
+
+ it('should reuse the token for the same credentials and scopes until it nears expiry', async () => {
+ answerWith(200, { access_token: 'ya29.cached', expires_in: 3600 });
+
+ await mintServiceAccountToken({ creds: CREDS, scopes: SCOPES });
+ await mintServiceAccountToken({ creds: CREDS, scopes: SCOPES });
+ await mintServiceAccountToken({ creds: { ...CREDS, adminEmail: '[email protected]' }, scopes: SCOPES });
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('should not share a cached token between connections with the same e-mail but different private keys', async () => {
+ const { privateKey: otherKey } = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ });
+ fetchMock
+ .mockImplementationOnce(async () => tokenResponse(200, { access_token: 'ya29.first', expires_in: 3600 }))
+ .mockImplementationOnce(async () => tokenResponse(200, { access_token: 'ya29.second', expires_in: 3600 }));
+
+ await expect(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES })).resolves.toBe('ya29.first');
+ await expect(mintServiceAccountToken({ creds: { ...CREDS, privateKey: otherKey }, scopes: SCOPES })).resolves.toBe('ya29.second');
+ await expect(
+ mintServiceAccountToken({ creds: { ...CREDS, privateKey: privateKey.replace(/\n/g, '\\n') }, scopes: SCOPES })
+ ).resolves.toBe('ya29.first');
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('should drop expired tokens from the cache when a new one is stored', async () => {
+ const start = 1_700_000_000_000;
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(start);
+ answerWith(200, { access_token: 'ya29.old', expires_in: 3600 });
+ await mintServiceAccountToken({ creds: CREDS, scopes: SCOPES });
+ expect(cachedTokenCount()).toBe(1);
+
+ clock.mockReturnValue(start + 2 * 3600 * 1000);
+ answerWith(200, { access_token: 'ya29.new', expires_in: 3600 });
+ await mintServiceAccountToken({ creds: { ...CREDS, adminEmail: '[email protected]' }, scopes: SCOPES });
+
+ expect(cachedTokenCount()).toBe(1);
+ await expect(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES })).resolves.toBe('ya29.new');
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('should drop expired tokens from the cache on a lookup', async () => {
+ const start = 1_700_000_000_000;
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(start);
+ answerWith(200, { access_token: 'ya29.old', expires_in: 3600 });
+ await mintServiceAccountToken({ creds: CREDS, scopes: SCOPES });
+
+ clock.mockReturnValue(start + 2 * 3600 * 1000);
+ answerWith(500, 'unavailable');
+ await expect(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES })).rejects.toThrow('Google token endpoint returned 500.');
+
+ expect(cachedTokenCount()).toBe(0);
+ });
+
+ it('should keep at most 100 tokens, evicting the oldest first', async () => {
+ let issued = 0;
+ fetchMock.mockImplementation(async () => tokenResponse(200, { access_token: `ya29.${issued++}`, expires_in: 3600 }));
+ const credsFor = (index: number) => ({ ...CREDS, adminEmail: `admin${index}@example.com` });
+
+ for (let index = 0; index <= 100; index++) {
+ await mintServiceAccountToken({ creds: credsFor(index), scopes: SCOPES });
+ }
+
+ expect(cachedTokenCount()).toBe(100);
+ expect(fetchMock).toHaveBeenCalledTimes(101);
+ await expect(mintServiceAccountToken({ creds: credsFor(1), scopes: SCOPES })).resolves.toBe('ya29.1');
+ expect(fetchMock).toHaveBeenCalledTimes(101);
+ await expect(mintServiceAccountToken({ creds: credsFor(0), scopes: SCOPES })).resolves.toBe('ya29.101');
+ expect(fetchMock).toHaveBeenCalledTimes(102);
+ expect(cachedTokenCount()).toBe(100);
+ });
+
+ it('should explain an unauthorized_client answer as a missing domain-wide delegation', async () => {
+ answerWith(401, { error: 'unauthorized_client', error_description: 'Client is unauthorized to retrieve access tokens using this method.' });
+
+ await expect(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES })).rejects.toThrow(
+ 'Google rejected the service account (unauthorized_client): Client is unauthorized to retrieve access tokens using this method. Check that domain-wide delegation is authorized'
+ );
+ });
+
+ it('should never put the signed assertion in the error or the logs when Google rejects it', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ const consoleLog = vi.spyOn(console, 'log').mockImplementation(() => undefined);
+ answerWith(400, { error: 'invalid_grant', error_description: 'Invalid email or User ID' });
+
+ const error = await captureRejection(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES }));
+
+ const assertion = sentAssertion();
+ expect(assertion.length).toBeGreaterThan(100);
+ expect(error).toBeInstanceOf(Error);
+ expect(error instanceof Error ? error.message : '').toBe(
+ 'Google rejected the service account (invalid_grant): Invalid email or User ID Check the administrator e-mail (it must exist in your domain) and the server clock.'
+ );
+ expect(error instanceof Error ? error.cause : 'not an error').toBeUndefined();
+ expect(errorChainText(error)).not.toContain(assertion);
+ expect(errorChainText(error)).not.toContain(assertion.split('.')[2]);
+ for (const call of [...consoleError.mock.calls, ...consoleLog.mock.calls]) {
+ expect(errorChainText(call)).not.toContain(assertion);
+ }
+ });
+
+ it('should report a non-JSON error answer by its status only', async () => {
+ answerWith(502, '<html>Bad Gateway</html>');
+
+ await expect(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES })).rejects.toThrow(/^Google token endpoint returned 502\.$/);
+ });
+
+ it('should hide the request when the token endpoint cannot be reached', async () => {
+ fetchMock.mockImplementation(async (_input, init) => {
+ throw new TypeError('fetch failed', { cause: new Error(String(init?.body)) });
+ });
+
+ const error = await captureRejection(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES }));
+
+ expect(error instanceof Error ? error.message : '').toBe('Could not reach the Google token endpoint (TypeError). Try again in a moment.');
+ expect(error instanceof Error ? error.cause : 'not an error').toBeUndefined();
+ expect(errorChainText(error)).not.toContain(sentAssertion());
+ });
+
+ it('should fail when Google answers 200 without a token', async () => {
+ answerWith(200, { error: 'invalid_scope', error_description: 'Invalid scope' });
+
+ await expect(mintServiceAccountToken({ creds: CREDS, scopes: SCOPES })).rejects.toThrow('no access token (invalid_scope: Invalid scope)');
+ });
+});
+
+describe('validateServiceAccount()', () => {
+ function answerTokenThenUser(user: unknown): void {
+ fetchMock.mockImplementation(async (input) =>
+ String(input) === GOOGLE_TOKEN_URL ? tokenResponse(200, { access_token: 'ya29.v', expires_in: 3600 }) : tokenResponse(200, user)
+ );
+ }
+
+ it('should mint a token and accept an administrator', async () => {
+ answerTokenThenUser({ primaryEmail: '[email protected]', isAdmin: true });
+
+ await expect(validateServiceAccount(CREDS)).resolves.toEqual({ valid: true });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const [url, init] = fetchMock.mock.calls[1] ?? [];
+ expect(String(url)).toBe('https://admin.googleapis.com/admin/directory/v1/users/admin%40example.com');
+ expect(init?.method).toBe('GET');
+ expect(init?.headers).toMatchObject({ Authorization: 'Bearer ya29.v' });
+ });
+
+ it('should reject a user that is not an administrator', async () => {
+ answerTokenThenUser({ primaryEmail: '[email protected]', isAdmin: false, isDelegatedAdmin: false });
+
+ await expect(validateServiceAccount(CREDS)).resolves.toEqual({
+ valid: false,
+ error: '[email protected] is not a Workspace administrator; pick a user with an admin role.',
+ });
+ });
+
+ it('should surface the token error as the validation error', async () => {
+ answerWith(400, { error: 'invalid_grant', error_description: 'Invalid email or User ID' });
+
+ const result = await validateServiceAccount(CREDS);
+
+ expect(result.valid).toBe(false);
+ expect(result).toMatchObject({ error: expect.stringContaining('invalid_grant') });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('should reject a malformed key without calling Google', async () => {
+ const result = await validateServiceAccount({ ...CREDS, privateKey: 'nope' });
+
+ expect(result).toEqual({ valid: false, error: expect.stringContaining('PEM block') });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/lib/triggers/triggers.test.ts b/packages/pieces/community/google-workspace/test/lib/triggers/triggers.test.ts
new file mode 100644
index 00000000000..af334300e66
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/lib/triggers/triggers.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ActivityEvent } from '../../../src/lib/common/activities';
+import { acceptUserEvent } from '../../../src/lib/triggers/new-user-event';
+
+function event(name: string, type = 'USER_SETTINGS', email = '[email protected]'): ActivityEvent {
+ return {
+ id: `t:${name}`,
+ time: 't',
+ application: 'admin',
+ eventType: type,
+ eventName: name,
+ actor: { email: '[email protected]', profileId: null, callerType: null },
+ ipAddress: null,
+ ownerDomain: null,
+ parameters: { USER_EMAIL: email },
+ activity: {},
+ };
+}
+
+describe('acceptUserEvent()', () => {
+ it('should match lifecycle events to the selected kinds', () => {
+ expect(acceptUserEvent({ event: event('CREATE_USER'), props: { kinds: ['created'] } })).toBe(true);
+ expect(acceptUserEvent({ event: event('DELETE_USER'), props: { kinds: ['created'] } })).toBe(false);
+ expect(acceptUserEvent({ event: event('SUSPEND_USER'), props: { kinds: ['suspended', 'unsuspended'] } })).toBe(true);
+ expect(acceptUserEvent({ event: event('REVOKE_ADMIN_PRIVILEGE'), props: { kinds: ['admin_changed'] } })).toBe(true);
+ });
+
+ it('should treat any other USER_SETTINGS event as "updated"', () => {
+ expect(acceptUserEvent({ event: event('CHANGE_FIRST_NAME'), props: { kinds: ['updated'] } })).toBe(true);
+ expect(acceptUserEvent({ event: event('MOVE_USER_TO_ORG_UNIT'), props: { kinds: ['updated'] } })).toBe(true);
+ expect(acceptUserEvent({ event: event('CREATE_USER'), props: { kinds: ['updated'] } })).toBe(false);
+ expect(acceptUserEvent({ event: event('CHANGE_FIRST_NAME'), props: { kinds: ['created'] } })).toBe(false);
+ });
+
+ it('should ignore events of other types and filter by domain, case-insensitively', () => {
+ expect(acceptUserEvent({ event: event('CREATE_GROUP', 'GROUP_SETTINGS'), props: { kinds: ['created', 'updated'] } })).toBe(false);
+ expect(acceptUserEvent({ event: event('CREATE_USER'), props: { kinds: ['created'], domain: 'Example.com' } })).toBe(true);
+ expect(acceptUserEvent({ event: event('CREATE_USER', 'USER_SETTINGS', '[email protected]'), props: { kinds: ['created'], domain: 'example.com' } })).toBe(false);
+ expect(acceptUserEvent({ event: { ...event('CREATE_USER'), parameters: {} }, props: { kinds: ['created'], domain: 'example.com' } })).toBe(false);
+ });
+});
+
diff --git a/packages/pieces/community/google-workspace/test/piece.test.ts b/packages/pieces/community/google-workspace/test/piece.test.ts
new file mode 100644
index 00000000000..1a79a2d1717
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/piece.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+
+import { googleWorkspace } from '../src/index';
+
+describe('googleWorkspace piece', () => {
+ it('should refuse to send the Google token to a Custom API Call URL on another host', async () => {
+ const customCall = googleWorkspace.actions()['custom_api_call'];
+ const context = {
+ auth: { type: 'OAUTH2', access_token: 'ya29.secret' },
+ propsValue: { method: 'GET', url: { url: 'https://attacker.example.com/collect' }, headers: {}, queryParams: {} },
+ } as unknown as Parameters<typeof customCall.run>[0];
+
+ await expect(customCall.run(context)).rejects.toThrow('not to https://attacker.example.com');
+ });
+});
diff --git a/packages/pieces/community/google-workspace/test/setup.ts b/packages/pieces/community/google-workspace/test/setup.ts
new file mode 100644
index 00000000000..0e24d4494e9
--- /dev/null
+++ b/packages/pieces/community/google-workspace/test/setup.ts
@@ -0,0 +1,9 @@
+import { beforeEach, vi } from 'vitest';
+
+const blockNetwork = vi.fn(async (input: unknown): Promise<Response> => {
+ throw new Error(`Unexpected network call in tests: ${String(input)}`);
+});
+
+beforeEach(() => {
+ vi.stubGlobal('fetch', blockNetwork);
+});
diff --git a/packages/pieces/community/google-workspace/tsconfig.json b/packages/pieces/community/google-workspace/tsconfig.json
new file mode 100644
index 00000000000..71bc5814f5d
--- /dev/null
+++ b/packages/pieces/community/google-workspace/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "extends": "../../../../tsconfig.base.json",
+ "compilerOptions": {
+ "module": "commonjs",
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "noImplicitOverride": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "files": [],
+ "include": [],
+ "references": [{ "path": "./tsconfig.lib.json" }]
+}
diff --git a/packages/pieces/community/google-workspace/tsconfig.lib.json b/packages/pieces/community/google-workspace/tsconfig.lib.json
new file mode 100644
index 00000000000..a648eb45d7f
--- /dev/null
+++ b/packages/pieces/community/google-workspace/tsconfig.lib.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": ".",
+ "baseUrl": ".",
+ "paths": {},
+ "outDir": "./dist",
+ "declaration": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
+}
diff --git a/packages/pieces/community/google-workspace/vitest.config.ts b/packages/pieces/community/google-workspace/vitest.config.ts
new file mode 100644
index 00000000000..48da723763b
--- /dev/null
+++ b/packages/pieces/community/google-workspace/vitest.config.ts
@@ -0,0 +1,20 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ setupFiles: ['test/setup.ts'],
+ },
+ resolve: {
+ alias: {
+ '@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/tsconfig.base.json b/tsconfig.base.json
index 0804cdfd5b0..bcf68bf14bb 100644
--- a/tsconfig.base.json
+++ b/tsconfig.base.json
@@ -238,6 +238,9 @@
"@activepieces/piece-google-document-ai": [
"packages/pieces/community/google-document-ai/src/index.ts"
],
+ "@activepieces/piece-google-workspace": [
+ "packages/pieces/community/google-workspace/src/index.ts"
+ ],
"@activepieces/piece-rounded-studio": [
"packages/pieces/community/rounded-studio/src/index.ts"
],