@aglyn/plugins-workflows 1.0.0-beta.287 → 1.0.0-beta.288

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-workflows",
3
- "version": "1.0.0-beta.287",
3
+ "version": "1.0.0-beta.288",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,17 +25,17 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.287",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.287",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.287",
31
- "@aglyn/shared-ui-next": "1.0.0-beta.287",
32
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.287",
33
- "@aglyn/shared-util-email": "1.0.0-beta.287",
34
- "@aglyn/shared-util-http": "1.0.0-beta.287",
35
- "@aglyn/shared-util-timestamp": "1.0.0-beta.287",
36
- "@aglyn/tenant-data-admin": "1.0.0-beta.287",
37
- "@aglyn/tenant-feature-instance": "1.0.0-beta.287",
38
- "@aglyn/tenant-runtime": "1.0.0-beta.287",
28
+ "@aglyn/aglyn": "1.0.0-beta.288",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.288",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.288",
31
+ "@aglyn/shared-ui-next": "1.0.0-beta.288",
32
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.288",
33
+ "@aglyn/shared-util-email": "1.0.0-beta.288",
34
+ "@aglyn/shared-util-http": "1.0.0-beta.288",
35
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.288",
36
+ "@aglyn/tenant-data-admin": "1.0.0-beta.288",
37
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.288",
38
+ "@aglyn/tenant-runtime": "1.0.0-beta.288",
39
39
  "@swc/helpers": "0.5.23"
40
40
  },
41
41
  "peerDependencies": {
@@ -17,9 +17,11 @@
17
17
  // this at boot, and the barrel reaches the client contexts.
18
18
  import { registerInteractionStepChecks } from "@aglyn/aglyn/plugin-manager/interaction-step-checks";
19
19
  import { registerPluginActivityActions } from "@aglyn/aglyn/plugin-manager/plugin-activity-actions";
20
+ import { registerPluginEntitlements } from "@aglyn/aglyn/plugin-manager/plugin-entitlements";
20
21
  import { BUNDLE_ID } from "./constants/bundle-common.js";
21
22
  import { hostActionStepProblem, SERVER_ACTION_STEP_TYPES } from "./model/host-actions.js";
22
23
  import { describeAutomationRunAction } from "./model/run-activity-words.js";
24
+ import { WORKFLOWS_PERMISSIONS } from "./model/workflows-permissions.js";
23
25
  /**
24
26
  * The automation editor's DECLARATIONS: what another surface reads of this
25
27
  * plugin before any of its own surfaces load, in both apps and in the
@@ -31,6 +33,12 @@ import { describeAutomationRunAction } from "./model/run-activity-words.js";
31
33
  * this editor would (`validateStoredInteraction`). Light by construction: the
32
34
  * checks are pure, and nothing here reaches Firestore or React.
33
35
  */ export function registerWorkflowsDeclarations() {
36
+ // The org automations' keys (AGL-4047): the one permission catalog lists
37
+ // them beside the core keys.
38
+ registerPluginEntitlements({
39
+ pluginId: BUNDLE_ID,
40
+ orgPermissions: WORKFLOWS_PERMISSIONS
41
+ });
34
42
  registerInteractionStepChecks(SERVER_ACTION_STEP_TYPES, hostActionStepProblem, {
35
43
  pluginId: BUNDLE_ID
36
44
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/declarations.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The seam from its own module, not the plugin-manager barrel: both apps load\n// this at boot, and the barrel reaches the client contexts.\nimport { registerInteractionStepChecks } from '@aglyn/aglyn/plugin-manager/interaction-step-checks'\nimport { registerPluginActivityActions } from '@aglyn/aglyn/plugin-manager/plugin-activity-actions'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { hostActionStepProblem, SERVER_ACTION_STEP_TYPES } from './model/host-actions'\nimport { describeAutomationRunAction } from './model/run-activity-words'\n\n/**\n * The automation editor's DECLARATIONS: what another surface reads of this\n * plugin before any of its own surfaces load, in both apps and in the\n * console's browser.\n *\n * The checks of the server steps an automation holds (AGL-3080), so a plugin\n * that writes an automation it does not edit — a recipe installed into a\n * site, a drafted automation graded before it is handed over — refuses what\n * this editor would (`validateStoredInteraction`). Light by construction: the\n * checks are pure, and nothing here reaches Firestore or React.\n */\nexport function registerWorkflowsDeclarations(): void {\n registerInteractionStepChecks(SERVER_ACTION_STEP_TYPES, hostActionStepProblem, { pluginId: BUNDLE_ID })\n // The run lines the engine files in a site's activity read in words in every feed and the apps' activity rows (AGL-3892).\n registerPluginActivityActions({\n pluginId: BUNDLE_ID,\n group: { id: 'automation', label: 'Automation' },\n actions: [],\n describeAction: describeAutomationRunAction,\n })\n}\n"],"names":["registerInteractionStepChecks","registerPluginActivityActions","BUNDLE_ID","hostActionStepProblem","SERVER_ACTION_STEP_TYPES","describeAutomationRunAction","registerWorkflowsDeclarations","pluginId","group","id","label","actions","describeAction"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,4DAA4D;AAC5D,SAASA,6BAA6B,QAAQ,sDAAqD;AACnG,SAASC,6BAA6B,QAAQ,sDAAqD;AACnG,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,qBAAqB,EAAEC,wBAAwB,QAAQ,0BAAsB;AACtF,SAASC,2BAA2B,QAAQ,gCAA4B;AAExE;;;;;;;;;;CAUC,GACD,OAAO,SAASC;IACdN,8BAA8BI,0BAA0BD,uBAAuB;QAAEI,UAAUL;IAAU;IACrG,0HAA0H;IAC1HD,8BAA8B;QAC5BM,UAAUL;QACVM,OAAO;YAAEC,IAAI;YAAcC,OAAO;QAAa;QAC/CC,SAAS,EAAE;QACXC,gBAAgBP;IAClB;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/declarations.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The seam from its own module, not the plugin-manager barrel: both apps load\n// this at boot, and the barrel reaches the client contexts.\nimport { registerInteractionStepChecks } from '@aglyn/aglyn/plugin-manager/interaction-step-checks'\nimport { registerPluginActivityActions } from '@aglyn/aglyn/plugin-manager/plugin-activity-actions'\nimport { registerPluginEntitlements } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { hostActionStepProblem, SERVER_ACTION_STEP_TYPES } from './model/host-actions'\nimport { describeAutomationRunAction } from './model/run-activity-words'\nimport { WORKFLOWS_PERMISSIONS } from './model/workflows-permissions'\n\n/**\n * The automation editor's DECLARATIONS: what another surface reads of this\n * plugin before any of its own surfaces load, in both apps and in the\n * console's browser.\n *\n * The checks of the server steps an automation holds (AGL-3080), so a plugin\n * that writes an automation it does not edit — a recipe installed into a\n * site, a drafted automation graded before it is handed over — refuses what\n * this editor would (`validateStoredInteraction`). Light by construction: the\n * checks are pure, and nothing here reaches Firestore or React.\n */\nexport function registerWorkflowsDeclarations(): void {\n // The org automations' keys (AGL-4047): the one permission catalog lists\n // them beside the core keys.\n registerPluginEntitlements({ pluginId: BUNDLE_ID, orgPermissions: WORKFLOWS_PERMISSIONS })\n registerInteractionStepChecks(SERVER_ACTION_STEP_TYPES, hostActionStepProblem, { pluginId: BUNDLE_ID })\n // The run lines the engine files in a site's activity read in words in every feed and the apps' activity rows (AGL-3892).\n registerPluginActivityActions({\n pluginId: BUNDLE_ID,\n group: { id: 'automation', label: 'Automation' },\n actions: [],\n describeAction: describeAutomationRunAction,\n })\n}\n"],"names":["registerInteractionStepChecks","registerPluginActivityActions","registerPluginEntitlements","BUNDLE_ID","hostActionStepProblem","SERVER_ACTION_STEP_TYPES","describeAutomationRunAction","WORKFLOWS_PERMISSIONS","registerWorkflowsDeclarations","pluginId","orgPermissions","group","id","label","actions","describeAction"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,4DAA4D;AAC5D,SAASA,6BAA6B,QAAQ,sDAAqD;AACnG,SAASC,6BAA6B,QAAQ,sDAAqD;AACnG,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,qBAAqB,EAAEC,wBAAwB,QAAQ,0BAAsB;AACtF,SAASC,2BAA2B,QAAQ,gCAA4B;AACxE,SAASC,qBAAqB,QAAQ,mCAA+B;AAErE;;;;;;;;;;CAUC,GACD,OAAO,SAASC;IACd,yEAAyE;IACzE,6BAA6B;IAC7BN,2BAA2B;QAAEO,UAAUN;QAAWO,gBAAgBH;IAAsB;IACxFP,8BAA8BK,0BAA0BD,uBAAuB;QAAEK,UAAUN;IAAU;IACrG,0HAA0H;IAC1HF,8BAA8B;QAC5BQ,UAAUN;QACVQ,OAAO;YAAEC,IAAI;YAAcC,OAAO;QAAa;QAC/CC,SAAS,EAAE;QACXC,gBAAgBT;IAClB;AACF"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types';
18
+ import type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements';
19
+ /** Workflows' keys. */
20
+ export type WorkflowsPermission = 'workflows.orgAutomations' | 'workflows.sitePause';
21
+ /** Who paused an org automation on a site before it was a key: the site's Admin and Editor. */
22
+ export declare const WORKFLOWS_SITE_PAUSE_PRESET: Readonly<Record<HostAccessRole, boolean>>;
23
+ /** The keys as the plugin declares them into the org permission catalog. */
24
+ export declare const WORKFLOWS_PERMISSIONS: readonly PluginOrgPermissionDeclaration[];
25
+ /** The refusal a door answers without one: names the permission, never a role. */
26
+ export declare function workflowsPermissionRefusal(key: WorkflowsPermission): string;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ /** Who paused an org automation on a site before it was a key: the site's Admin and Editor. */ export const WORKFLOWS_SITE_PAUSE_PRESET = {
18
+ admin: true,
19
+ editor: true,
20
+ author: false,
21
+ viewer: false
22
+ };
23
+ /** The keys as the plugin declares them into the org permission catalog. */ export const WORKFLOWS_PERMISSIONS = [
24
+ {
25
+ key: 'workflows.orgAutomations',
26
+ label: 'Manage org automations',
27
+ description: 'Create, change, switch on and off, remove and import the organization’s automations. Members of the whole workspace only.',
28
+ roleDefaults: {
29
+ owner: true,
30
+ admin: true,
31
+ editor: true,
32
+ viewer: false
33
+ },
34
+ group: 'workflows',
35
+ groupLabel: 'Workflows'
36
+ },
37
+ {
38
+ key: 'workflows.sitePause',
39
+ label: 'Pause org automations on a site',
40
+ description: 'Pause or resume one of the organization’s automations on a site. Follows the site role unless a role or member sets it; "Manage org automations" also allows it.',
41
+ roleDefaults: {
42
+ owner: true,
43
+ admin: true,
44
+ editor: true,
45
+ viewer: false
46
+ },
47
+ hostRoleDefaults: _extends({}, WORKFLOWS_SITE_PAUSE_PRESET),
48
+ group: 'workflows',
49
+ groupLabel: 'Workflows',
50
+ presetFromSiteRole: true
51
+ }
52
+ ];
53
+ /** The refusal a door answers without one: names the permission, never a role. */ export function workflowsPermissionRefusal(key) {
54
+ var _ref;
55
+ var _WORKFLOWS_PERMISSIONS_find;
56
+ const label = (_ref = (_WORKFLOWS_PERMISSIONS_find = WORKFLOWS_PERMISSIONS.find((entry)=>entry.key === key)) == null ? void 0 : _WORKFLOWS_PERMISSIONS_find.label) != null ? _ref : key;
57
+ return `Your role does not include "${label}" — ask an organization admin`;
58
+ }
59
+
60
+ //# sourceMappingURL=workflows-permissions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/model/workflows-permissions.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\n\n/*\n * WORKFLOWS' KEYS (AGL-4047).\n *\n * The organization's automations were written by an owner, admin or editor\n * of the whole workspace, and paused on one site by that site's Admin or\n * Editor (or by one of the workspace's managers). Those are now keys:\n * \"Manage org automations\", whose default is the workspace role, and \"Pause\n * org automations on a site\", whose preset is the site role\n * (`presetFromSiteRole`). Every member keeps exactly the access they had,\n * and a custom role, a member's own permissions or a site's toggle can grant\n * or refuse either one.\n */\n\n/** Workflows' keys. */\nexport type WorkflowsPermission = 'workflows.orgAutomations' | 'workflows.sitePause'\n\n/** Who paused an org automation on a site before it was a key: the site's Admin and Editor. */\nexport const WORKFLOWS_SITE_PAUSE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: false,\n viewer: false,\n}\n\n/** The keys as the plugin declares them into the org permission catalog. */\nexport const WORKFLOWS_PERMISSIONS: readonly PluginOrgPermissionDeclaration[] = [\n {\n key: 'workflows.orgAutomations',\n label: 'Manage org automations',\n description:\n 'Create, change, switch on and off, remove and import the organization’s automations. Members of the whole workspace only.',\n roleDefaults: { owner: true, admin: true, editor: true, viewer: false },\n group: 'workflows',\n groupLabel: 'Workflows',\n },\n {\n key: 'workflows.sitePause',\n label: 'Pause org automations on a site',\n description:\n 'Pause or resume one of the organization’s automations on a site. Follows the site role unless a role or member sets it; \"Manage org automations\" also allows it.',\n roleDefaults: { owner: true, admin: true, editor: true, viewer: false },\n hostRoleDefaults: { ...WORKFLOWS_SITE_PAUSE_PRESET },\n group: 'workflows',\n groupLabel: 'Workflows',\n presetFromSiteRole: true,\n },\n]\n\n/** The refusal a door answers without one: names the permission, never a role. */\nexport function workflowsPermissionRefusal(key: WorkflowsPermission): string {\n const label = WORKFLOWS_PERMISSIONS.find((entry) => entry.key === key)?.label ?? key\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n"],"names":["WORKFLOWS_SITE_PAUSE_PRESET","admin","editor","author","viewer","WORKFLOWS_PERMISSIONS","key","label","description","roleDefaults","owner","group","groupLabel","hostRoleDefaults","presetFromSiteRole","workflowsPermissionRefusal","find","entry"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAqBD,6FAA6F,GAC7F,OAAO,MAAMA,8BAAyE;IACpFC,OAAO;IACPC,QAAQ;IACRC,QAAQ;IACRC,QAAQ;AACV,EAAC;AAED,0EAA0E,GAC1E,OAAO,MAAMC,wBAAmE;IAC9E;QACEC,KAAK;QACLC,OAAO;QACPC,aACE;QACFC,cAAc;YAAEC,OAAO;YAAMT,OAAO;YAAMC,QAAQ;YAAME,QAAQ;QAAM;QACtEO,OAAO;QACPC,YAAY;IACd;IACA;QACEN,KAAK;QACLC,OAAO;QACPC,aACE;QACFC,cAAc;YAAEC,OAAO;YAAMT,OAAO;YAAMC,QAAQ;YAAME,QAAQ;QAAM;QACtES,kBAAkB,aAAKb;QACvBW,OAAO;QACPC,YAAY;QACZE,oBAAoB;IACtB;CACD,CAAA;AAED,gFAAgF,GAChF,OAAO,SAASC,2BAA2BT,GAAwB;;QACnDD;IAAd,MAAME,iBAAQF,8BAAAA,sBAAsBW,IAAI,CAAC,CAACC,QAAUA,MAAMX,GAAG,KAAKA,yBAApDD,4BAA0DE,KAAK,mBAAID;IACjF,OAAO,CAAC,4BAA4B,EAAEC,MAAM,6BAA6B,CAAC;AAC5E"}
@@ -15,6 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  import { type AglynOrgMember, type PluginApiHandler, type PluginApiRequestSubject } from '@aglyn/aglyn/server';
18
+ import { type WorkflowsPermission } from '../model/workflows-permissions';
18
19
  import { ORG_AUTOMATION_ACTIVITY_TARGET, ORG_AUTOMATION_API_ROUTES, type OrgAutomationFields } from '../model/org-automations';
19
20
  export { ORG_AUTOMATION_API_ROUTES };
20
21
  /** What `automations/manage` may be asked to do. */
@@ -32,6 +33,8 @@ export interface OrgAutomationRouteDeps {
32
33
  } | null>;
33
34
  getOrgDoc(orgId: string): Promise<Record<string, unknown> | null>;
34
35
  resolveOrgIdForHost(hostId: string): Promise<string | null>;
36
+ /** Whether a member holds a workspace key with no site named (AGL-4047): `memberHasOrgPermission`. */
37
+ holdsOrgKey(orgId: string, member: Partial<AglynOrgMember>, key: WorkflowsPermission): Promise<boolean>;
35
38
  logOrgActivity(orgId: string, actor: {
36
39
  uid: string;
37
40
  email?: string | null;
@@ -37,6 +37,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
37
37
  * THIS site. The site's own admins and editors may use it, and so may an
38
38
  * org-wide editor; nobody may pause a site through it but the one named.
39
39
  */ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
40
+ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
40
41
  import { hostIdsFromScope, visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
41
42
  import { isPluginEnabled } from "@aglyn/aglyn/plugin-manager/enabled-plugins";
42
43
  import { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from "@aglyn/aglyn/server";
@@ -46,9 +47,10 @@ import { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from "@ag
46
47
  * the id predicate and the org reads.
47
48
  */ import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
48
49
  import firebaseAdmin from "@aglyn/tenant-data-admin/server/firebase-admin";
49
- import { getOrgDoc, logHostActivity, logOrgActivity, resolveOrgIdForHost, resolveOrgMembership } from "@aglyn/tenant-data-admin/server/organizations";
50
+ import { getOrgDoc, logHostActivity, logOrgActivity, memberHasOrgPermission, resolveOrgIdForHost, resolveOrgMembership } from "@aglyn/tenant-data-admin/server/organizations";
50
51
  import { FieldValue } from "firebase-admin/firestore";
51
52
  import { BUNDLE_ID } from "../constants/bundle-common.js";
53
+ import { WORKFLOWS_SITE_PAUSE_PRESET, workflowsPermissionRefusal } from "../model/workflows-permissions.js";
52
54
  import { ORG_AUTOMATION_ACTIVITY_TARGET, ORG_AUTOMATION_API_ROUTES, ORG_AUTOMATIONS_COLLECTION, ORG_AUTOMATIONS_MAX, orgAutomationPausedHostIds, prunePausedHostIds, readOrgAutomation } from "../model/org-automations.js";
53
55
  export { ORG_AUTOMATION_API_ROUTES };
54
56
  /** What `automations/manage` may be asked to do. */ export const ORG_AUTOMATION_MANAGE_ACTIONS = [
@@ -57,15 +59,6 @@ export { ORG_AUTOMATION_API_ROUTES };
57
59
  'setEnabled',
58
60
  'delete'
59
61
  ];
60
- /** The org roles that may write the organization's automations. */ const ORG_MANAGE_ROLES = [
61
- 'owner',
62
- 'admin',
63
- 'editor'
64
- ];
65
- /** The site roles that may pause an org automation on their own site. */ const SITE_PAUSE_ROLES = [
66
- 'admin',
67
- 'editor'
68
- ];
69
62
  function defaultDeps() {
70
63
  return {
71
64
  firestore: ()=>firebaseAdmin.app().firestore(),
@@ -83,6 +76,7 @@ function defaultDeps() {
83
76
  return (_ref = await getOrgDoc(orgId)) != null ? _ref : null;
84
77
  },
85
78
  resolveOrgIdForHost,
79
+ holdsOrgKey: (orgId, member, key)=>memberHasOrgPermission(orgId, member, key),
86
80
  logOrgActivity: (orgId, actor, action, target)=>logOrgActivity(orgId, actor, action, target),
87
81
  logHostActivity: (hostId, actor, action, target)=>logHostActivity(hostId, actor, action, target),
88
82
  newId: createResourceUid
@@ -264,7 +258,7 @@ function automationsOf(firestore, orgId) {
264
258
  error: 'Unauthenticated'
265
259
  });
266
260
  try {
267
- var _member_role, _caller_email;
261
+ var _caller_email;
268
262
  var _req_body3;
269
263
  const caller = await deps.verifyIdToken(token).catch(()=>null);
270
264
  if (!caller) return res.status(401).json({
@@ -272,9 +266,12 @@ function automationsOf(firestore, orgId) {
272
266
  });
273
267
  const membership = await deps.resolveOrgMembership(caller.uid, orgId);
274
268
  const member = membership == null ? void 0 : membership.member;
275
- if (!member || !isOrgWideMember(member) || !ORG_MANAGE_ROLES.includes(String((_member_role = member.role) != null ? _member_role : ''))) {
269
+ // "Manage org automations" (AGL-4047), for members of the whole
270
+ // workspace: its default is the owner, admins and editors this asked
271
+ // for before, then their custom role and their own permissions.
272
+ if (!member || !isOrgWideMember(member) || !await deps.holdsOrgKey(orgId, member, 'workflows.orgAutomations')) {
276
273
  return res.status(403).json({
277
- error: 'Not an organization owner, admin or editor'
274
+ error: workflowsPermissionRefusal('workflows.orgAutomations')
278
275
  });
279
276
  }
280
277
  /*
@@ -437,7 +434,7 @@ function automationsOf(firestore, orgId) {
437
434
  error: 'Unauthenticated'
438
435
  });
439
436
  try {
440
- var _ref2, _caller_uid, _host_get, _caller_email;
437
+ var _ref2, _caller_email;
441
438
  var _req_body3;
442
439
  const caller = await deps.verifyIdToken(token).catch(()=>null);
443
440
  if (!caller) return res.status(401).json({
@@ -465,17 +462,18 @@ function automationsOf(firestore, orgId) {
465
462
  * projection — the same answer every site door asks — or an org-wide
466
463
  * editor, asked of the membership itself so a projection that has not
467
464
  * caught up cannot refuse the organization's own managers.
468
- */ const siteRole = String((_caller_uid = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[caller.uid]) != null ? _caller_uid : '');
469
- let allowed = SITE_PAUSE_ROLES.includes(siteRole);
465
+ */ // "Pause org automations on a site" (AGL-4047): the site's stamp, else
466
+ // the preset of the member's site role, the Admin and Editor this asked
467
+ // for; or "Manage org automations" for a member of the whole workspace.
468
+ let allowed = holdsStampedSiteKey(host, caller.uid, 'workflows.sitePause', WORKFLOWS_SITE_PAUSE_PRESET);
470
469
  if (!allowed) {
471
- var _ref3;
472
470
  const membership = await deps.resolveOrgMembership(caller.uid, orgId);
473
471
  const member = membership == null ? void 0 : membership.member;
474
- allowed = Boolean(member) && isOrgWideMember(member) && ORG_MANAGE_ROLES.includes(String((_ref3 = member == null ? void 0 : member.role) != null ? _ref3 : ''));
472
+ allowed = Boolean(member) && isOrgWideMember(member) && await deps.holdsOrgKey(orgId, member, 'workflows.orgAutomations');
475
473
  }
476
474
  if (!allowed) {
477
475
  return res.status(403).json({
478
- error: 'Not an admin or editor of this site'
476
+ error: workflowsPermissionRefusal('workflows.sitePause')
479
477
  });
480
478
  }
481
479
  const name = await firestore.runTransaction(async (transaction)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/server/org-automations-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WRITING AN ORG AUTOMATION, and pausing one on a site (AGL-3302).\n *\n * `orgs/{orgId}/automations` is closed to every client write, the way the\n * outreach collections are: an org automation runs on every site it is\n * placed on, as that site, so its trigger, its steps and its placement are\n * decisions the server checks — the vocabulary, the organization's sites, the\n * plan — and nothing a browser may write around.\n *\n * ## Two doors\n *\n * `automations/manage` is the organization's: it creates, edits, switches on\n * and off, and deletes. It names the org and NO site, so it declares a\n * subject resolver for the dispatchers' release gate and asks the org's\n * plugin switch itself; the caller must be an org-wide owner, admin or\n * editor.\n *\n * `automations/pause` is the SITE's — the host level control. It names the\n * site, so the dispatcher applies that site's plugin switch as for any site\n * request, and it changes one thing: whether this automation is paused on\n * THIS site. The site's own admins and editors may use it, and so may an\n * org-wide editor; nobody may pause a site through it but the one named.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { hostIdsFromScope, visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport {\n type AglynOrgMember,\n checkEntitlement,\n isOrgWideMember,\n type PluginApiHandler,\n type PluginApiRequestSubject,\n planLabelGrantingFeature,\n} from '@aglyn/aglyn/server'\n/*\n * The MODULES, not the barrel: `@aglyn/tenant-data-admin`'s index reaches the\n * Next render cache, and everything these doors need is the Admin SDK handle,\n * the id predicate and the org reads.\n */\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport {\n getOrgDoc,\n logHostActivity,\n logOrgActivity,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n ORG_AUTOMATION_ACTIVITY_TARGET,\n ORG_AUTOMATION_API_ROUTES,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n orgAutomationPausedHostIds,\n prunePausedHostIds,\n readOrgAutomation,\n type OrgAutomationFields,\n} from '../model/org-automations'\n\nexport { ORG_AUTOMATION_API_ROUTES }\n\n/** What `automations/manage` may be asked to do. */\nexport const ORG_AUTOMATION_MANAGE_ACTIONS = [\n 'create',\n 'update',\n 'setEnabled',\n 'delete',\n] as const\n\ntype ManageAction = (typeof ORG_AUTOMATION_MANAGE_ACTIONS)[number]\n\n/** The org roles that may write the organization's automations. */\nconst ORG_MANAGE_ROLES = ['owner', 'admin', 'editor'] as const\n\n/** The site roles that may pause an org automation on their own site. */\nconst SITE_PAUSE_ROLES = ['admin', 'editor'] as const\n\n/** What the doors reach outside this module; specs hand in their own. */\nexport interface OrgAutomationRouteDeps {\n firestore(): FirebaseFirestore.Firestore\n verifyIdToken(token: string): Promise<{ uid: string; email?: string | null }>\n resolveOrgMembership(\n uid: string,\n orgId: string,\n ): Promise<{ orgId: string; member: Partial<AglynOrgMember> } | null>\n getOrgDoc(orgId: string): Promise<Record<string, unknown> | null>\n resolveOrgIdForHost(hostId: string): Promise<string | null>\n logOrgActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: typeof ORG_AUTOMATION_ACTIVITY_TARGET; id: string; name?: string },\n ): Promise<void>\n logHostActivity(\n hostId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: 'workflow'; id: string; name?: string },\n ): Promise<void>\n newId(): string\n}\n\nfunction defaultDeps(): OrgAutomationRouteDeps {\n return {\n firestore: () =>\n firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore,\n verifyIdToken: async (token) => {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(token)\n return { uid: decoded.uid, email: decoded.email ?? null }\n },\n resolveOrgMembership: async (uid, orgId) =>\n (await resolveOrgMembership(uid, orgId)) as never,\n getOrgDoc: async (orgId) =>\n ((await getOrgDoc(orgId)) as Record<string, unknown> | null) ?? null,\n resolveOrgIdForHost,\n logOrgActivity: (orgId, actor, action, target) =>\n logOrgActivity(orgId, actor, action, target),\n logHostActivity: (hostId, actor, action, target) =>\n logHostActivity(hostId, actor, action, target),\n newId: createResourceUid,\n }\n}\n\n/** The bearer token a request carries, or null. */\nfunction bearerToken(headers: Partial<Record<string, string | string[]>>): string | null {\n const authorization = String(headers['authorization'] ?? '')\n return authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length) || null\n : null\n}\n\nfunction automationsOf(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): FirebaseFirestore.CollectionReference {\n return firestore\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_AUTOMATIONS_COLLECTION)\n}\n\n/**\n * Whether every site a placement names belongs to this organization — asked\n * of `hostIndex`, the mirror `resolveOrgIdForHost` reads, in one round trip.\n * `['org']` names no site and always answers yes.\n */\nasync function placementIsTheOrgs(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n visibleTo: readonly string[],\n): Promise<boolean> {\n const hostIds = hostIdsFromScope(visibleTo)\n if (!hostIds.length) return true\n if (!hostIds.every(isDocumentId)) return false\n const entries = await firestore.getAll(\n ...hostIds.map((hostId) => firestore.collection('hostIndex').doc(hostId)),\n )\n return entries.every((entry) => entry.exists && entry.get('orgId') === orgId)\n}\n\n/**\n * The organization a `automations/manage` request is for, read off its JSON\n * body, so the dispatchers' release gate asks about the right organization.\n * Consulted only for a request that names no site. Unverified, exactly as a\n * `hostId` is: the handler refuses anyone who is not an org-wide member.\n */\nexport async function orgAutomationsManageSubject(\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n if (request.method !== 'POST') return null\n const body = (await request.json().catch(() => null)) as {\n orgId?: unknown\n } | null\n const orgId = typeof body?.orgId === 'string' ? body.orgId : ''\n return isDocumentId(orgId) ? { orgId } : null\n}\n\n/** What writing an org automation came to: its id, or the refusal the route answers with. */\nexport type OrgAutomationWrite = { ok: true; id: string } | { ok: false; status: number; error: string }\n\n/**\n * Creates an org automation as `automations/manage` does: its sites must be\n * the organization's, and the organization holds at most\n * {@link ORG_AUTOMATIONS_MAX} live ones. The route and the package import\n * (AGL-3535) both create through here.\n */\nexport async function createOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; fields: OrgAutomationFields; actorUid: string },\n): Promise<OrgAutomationWrite> {\n if (!(await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo))) {\n return { ok: false, status: 400, error: 'A site you chose is not in this organization' }\n }\n const collection = automationsOf(firestore, input.orgId)\n /*\n * Counted before the write rather than inside a transaction. The\n * cap bounds storage, not money, so the overshoot two simultaneous\n * saves can buy is one document — the trade the site actions cap\n * makes for the same reason.\n */\n const live = (await collection.where('deletedAt', '==', null).count().get()).data().count\n if (live >= ORG_AUTOMATIONS_MAX) {\n return {\n ok: false,\n status: 409,\n error: `An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first`,\n }\n }\n await collection.doc(input.id).create({\n ...input.fields,\n pausedHostIds: [],\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n createdBy: input.actorUid,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return { ok: true, id: input.id }\n}\n\n/** Rewrites a live org automation as `automations/manage` does; a site it no longer runs on leaves its pause list. */\nexport async function updateOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; fields: OrgAutomationFields; actorUid: string },\n): Promise<OrgAutomationWrite> {\n if (!(await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo))) {\n return { ok: false, status: 400, error: 'A site you chose is not in this organization' }\n }\n const collection = automationsOf(firestore, input.orgId)\n const outcome = await firestore.runTransaction(async (transaction) => {\n const ref = collection.doc(input.id)\n const current = await transaction.get(ref)\n if (!current.exists || current.get('deletedAt')) return 'missing'\n transaction.update(ref, {\n ...input.fields,\n // A site the automation no longer runs on has nothing left to\n // pause: its entry goes, so a later placement starts unpaused.\n pausedHostIds: prunePausedHostIds(orgAutomationPausedHostIds(current.data()), input.fields.visibleTo),\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return 'updated'\n })\n return outcome === 'missing' ? { ok: false, status: 404, error: 'Unknown org automation' } : { ok: true, id: input.id }\n}\n\n/**\n * Deletes an org automation as `automations/manage` does — softly, switched\n * off (see the handler). `null` for one that does not exist; `again` for\n * one already deleted.\n */\nexport async function deleteOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; actorUid: string },\n): Promise<{ name: string; again: boolean } | null> {\n return firestore.runTransaction(async (transaction) => {\n const ref = automationsOf(firestore, input.orgId).doc(input.id)\n const current = await transaction.get(ref)\n if (!current.exists) return null\n // Deleting twice is the same request answered again.\n if (current.get('deletedAt')) return { name: '', again: true }\n transaction.update(ref, {\n deletedAt: FieldValue.serverTimestamp(),\n deletedBy: input.actorUid,\n // Off as well, so the engine's query — which asks for switched-on\n // automations only — never spends one of its places on it.\n enabled: false,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return { name: String(current.get('name') ?? ''), again: false }\n })\n}\n\n/**\n * `automations/manage`: create, edit, switch on or off, and delete one of the\n * organization's automations.\n *\n * A DELETE is soft — `deletedAt` stamped and the automation switched off —\n * because the id is what every run history row and every waiting person\n * names: the rows keep a name to show, and the people waiting inside it are\n * stopped by the resume's kill switch on their next beat. Deleting and\n * switching off are never refused for want of a plan, so an organization\n * that downgraded can always stop what it built.\n */\nexport function createOrgAutomationsManageHandler(\n overrides: Partial<OrgAutomationRouteDeps> = {},\n): PluginApiHandler {\n return async (req, res) => {\n const deps = { ...defaultDeps(), ...overrides }\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const orgId = String(req.body?.orgId ?? '')\n const action = String(req.body?.action ?? '') as ManageAction\n if (!isDocumentId(orgId)) {\n return res.status(400).json({ error: 'Invalid orgId' })\n }\n if (!(ORG_AUTOMATION_MANAGE_ACTIONS as readonly string[]).includes(action)) {\n return res.status(400).json({ error: 'Unknown action' })\n }\n const automationId = String(req.body?.automationId ?? '')\n if (action !== 'create' && !isDocumentId(automationId)) {\n return res.status(400).json({ error: 'Invalid automationId' })\n }\n const token = bearerToken(req.headers)\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const caller = await deps.verifyIdToken(token).catch(() => null)\n if (!caller) return res.status(401).json({ error: 'Unauthenticated' })\n const membership = await deps.resolveOrgMembership(caller.uid, orgId)\n const member = membership?.member\n if (\n !member ||\n !isOrgWideMember(member) ||\n !(ORG_MANAGE_ROLES as readonly string[]).includes(String(member.role ?? ''))\n ) {\n return res\n .status(403)\n .json({ error: 'Not an organization owner, admin or editor' })\n }\n /*\n * A request naming no site reaches here past only the release gate —\n * the dispatcher's per-site switch needs a site — so the organization's\n * own switch is asked here.\n */\n const org = await deps.getOrgDoc(orgId)\n if (!org || !isPluginEnabled(org as never, BUNDLE_ID)) {\n return res.status(404).json({ error: 'Not found' })\n }\n const enabling =\n action === 'create' ||\n action === 'update' ||\n (action === 'setEnabled' && req.body?.enabled === true)\n if (enabling && !checkEntitlement(org as never, 'actions')) {\n return res.status(403).json({\n error: `Org automations need the ${planLabelGrantingFeature('actions') ?? 'Pro'} plan`,\n })\n }\n\n const firestore = deps.firestore()\n const collection = automationsOf(firestore, orgId)\n const actor = { uid: caller.uid, email: caller.email ?? null }\n const logged = (verb: string, id: string, name: string) =>\n deps.logOrgActivity(orgId, actor, verb, {\n type: ORG_AUTOMATION_ACTIVITY_TARGET,\n id,\n name,\n })\n\n if (action === 'create' || action === 'update') {\n const read = readOrgAutomation(req.body?.automation)\n if (read.ok === false) {\n return res.status(400).json({ error: read.problem })\n }\n const written =\n action === 'create'\n ? await createOrgAutomationRecord(firestore, { orgId, id: deps.newId(), fields: read.value, actorUid: caller.uid })\n : await updateOrgAutomationRecord(firestore, { orgId, id: automationId, fields: read.value, actorUid: caller.uid })\n if (written.ok === false) {\n return res.status(written.status).json({ error: written.error })\n }\n await logged(action === 'create' ? 'Created an org automation' : 'Edited an org automation', written.id, read.value.name)\n return res.status(200).json({ automationId: written.id })\n }\n\n if (action === 'setEnabled') {\n if (typeof req.body?.enabled !== 'boolean') {\n return res.status(400).json({ error: 'Say whether it is enabled' })\n }\n const enabled = req.body.enabled as boolean\n const name = await firestore.runTransaction(async (transaction) => {\n const ref = collection.doc(automationId)\n const current = await transaction.get(ref)\n if (!current.exists || current.get('deletedAt')) return null\n transaction.update(ref, {\n enabled,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: caller.uid,\n })\n return String(current.get('name') ?? '')\n })\n if (name === null) {\n return res.status(404).json({ error: 'Unknown org automation' })\n }\n await logged(\n enabled ? 'Switched on an org automation' : 'Switched off an org automation',\n automationId,\n name,\n )\n return res.status(200).json({ automationId, enabled })\n }\n\n // delete\n const deleted = await deleteOrgAutomationRecord(firestore, { orgId, id: automationId, actorUid: caller.uid })\n if (!deleted) {\n return res.status(404).json({ error: 'Unknown org automation' })\n }\n if (!deleted.again) {\n await logged('Deleted an org automation', automationId, deleted.name)\n }\n return res.status(200).json({ automationId, deleted: true })\n } catch (error) {\n console.error('[org automations] manage failed', orgId, action, error)\n return res\n .status(500)\n .json({ error: 'The request could not be completed' })\n }\n }\n}\n\n/**\n * `automations/pause`: pause or resume one org automation on ONE site.\n *\n * `pausedHostIds` is changed with `arrayUnion`/`arrayRemove` of the named\n * site alone, inside a transaction that first confirms the automation runs\n * there — so a site's editor can take their own site out of an org\n * automation and put it back, and can never touch another site's entry or\n * the automation itself. Pausing stops the people already waiting inside it\n * on this site as well, on their next beat: the resume reads a pause as the\n * kill switch.\n *\n * Never refused for want of a plan: a pause is how a site stops something,\n * and stopping is always allowed.\n */\nexport function createOrgAutomationPauseHandler(\n overrides: Partial<OrgAutomationRouteDeps> = {},\n): PluginApiHandler {\n return async (req, res) => {\n const deps = { ...defaultDeps(), ...overrides }\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const automationId = String(req.body?.automationId ?? '')\n const paused = req.body?.paused\n if (!isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Invalid hostId' })\n }\n if (!isDocumentId(automationId)) {\n return res.status(400).json({ error: 'Invalid automationId' })\n }\n if (typeof paused !== 'boolean') {\n return res.status(400).json({ error: 'Say whether it is paused' })\n }\n const token = bearerToken(req.headers)\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const caller = await deps.verifyIdToken(token).catch(() => null)\n if (!caller) return res.status(401).json({ error: 'Unauthenticated' })\n const firestore = deps.firestore()\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n const orgId = await deps.resolveOrgIdForHost(hostId)\n if (!orgId) {\n return res.status(409).json({\n error: 'This site is not part of an organization, so it runs no org automations.',\n })\n }\n const requestedOrgId = String(req.body?.orgId ?? '')\n if (requestedOrgId && requestedOrgId !== orgId) {\n return res.status(400).json({ error: 'That site is not in this organization' })\n }\n /*\n * The site's own admins and editors, read off the host's `memberRoles`\n * projection — the same answer every site door asks — or an org-wide\n * editor, asked of the membership itself so a projection that has not\n * caught up cannot refuse the organization's own managers.\n */\n const siteRole = String((host.get('memberRoles') ?? {})[caller.uid] ?? '')\n let allowed = (SITE_PAUSE_ROLES as readonly string[]).includes(siteRole)\n if (!allowed) {\n const membership = await deps.resolveOrgMembership(caller.uid, orgId)\n const member = membership?.member\n allowed =\n Boolean(member) &&\n isOrgWideMember(member) &&\n (ORG_MANAGE_ROLES as readonly string[]).includes(String(member?.role ?? ''))\n }\n if (!allowed) {\n return res\n .status(403)\n .json({ error: 'Not an admin or editor of this site' })\n }\n\n const name = await firestore.runTransaction(async (transaction) => {\n const ref = automationsOf(firestore, orgId).doc(automationId)\n const current = await transaction.get(ref)\n if (\n !current.exists ||\n current.get('deletedAt') ||\n !visibleToHost(current.get('visibleTo') as string[] | undefined, hostId)\n ) {\n return null\n }\n transaction.update(ref, {\n pausedHostIds: paused\n ? FieldValue.arrayUnion(hostId)\n : FieldValue.arrayRemove(hostId),\n })\n return String(current.get('name') ?? '')\n })\n if (name === null) {\n return res\n .status(404)\n .json({ error: 'No org automation by that id runs on this site' })\n }\n await deps.logHostActivity(\n hostId,\n { uid: caller.uid, email: caller.email ?? null },\n paused\n ? 'Paused an org automation on this site'\n : 'Resumed an org automation on this site',\n { type: 'workflow', id: automationId, name },\n )\n return res.status(200).json({ automationId, hostId, paused })\n } catch (error) {\n console.error('[org automations] pause failed', hostId, automationId, error)\n return res\n .status(500)\n .json({ error: 'The request could not be completed' })\n }\n }\n}\n\nexport const orgAutomationsManageHandler = createOrgAutomationsManageHandler()\nexport const orgAutomationPauseHandler = createOrgAutomationPauseHandler()\n"],"names":["createResourceUid","hostIdsFromScope","visibleToHost","isPluginEnabled","checkEntitlement","isOrgWideMember","planLabelGrantingFeature","isDocumentId","firebaseAdmin","getOrgDoc","logHostActivity","logOrgActivity","resolveOrgIdForHost","resolveOrgMembership","FieldValue","BUNDLE_ID","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATION_API_ROUTES","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","orgAutomationPausedHostIds","prunePausedHostIds","readOrgAutomation","ORG_AUTOMATION_MANAGE_ACTIONS","ORG_MANAGE_ROLES","SITE_PAUSE_ROLES","defaultDeps","firestore","app","verifyIdToken","token","decoded","auth","uid","email","orgId","actor","action","target","hostId","newId","bearerToken","headers","authorization","String","startsWith","slice","length","automationsOf","collection","doc","placementIsTheOrgs","visibleTo","hostIds","every","entries","getAll","map","entry","exists","get","orgAutomationsManageSubject","request","method","body","json","catch","createOrgAutomationRecord","input","fields","ok","status","error","live","where","count","data","id","create","pausedHostIds","deletedAt","createdAt","serverTimestamp","createdBy","actorUid","updatedAt","updatedBy","updateOrgAutomationRecord","outcome","runTransaction","transaction","ref","current","update","deleteOrgAutomationRecord","name","again","deletedBy","enabled","createOrgAutomationsManageHandler","overrides","req","res","deps","includes","automationId","member","caller","membership","role","org","enabling","logged","verb","type","read","automation","problem","written","value","deleted","console","createOrgAutomationPauseHandler","paused","host","requestedOrgId","siteRole","allowed","Boolean","arrayUnion","arrayRemove","orgAutomationsManageHandler","orgAutomationPauseHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,sCAAqC;AACrF,SAASC,eAAe,QAAQ,8CAA6C;AAC7E,SAEEC,gBAAgB,EAChBC,eAAe,EAGfC,wBAAwB,QACnB,sBAAqB;AAC5B;;;;CAIC,GACD,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,OAAOC,mBAAmB,iDAAgD;AAC1E,SACEC,SAAS,EACTC,eAAe,EACfC,cAAc,EACdC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,UAAU,QAAQ,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gBAC7B;gBACA,OAAOK,QAAOgD,eAAAA,QAAQhC,GAAG,CAAC,mBAAZgC,eAAuB;YACvC;YACA,IAAIG,SAAS,MAAM;gBACjB,OAAOO,IACJ/B,MAAM,CAAC,KACPN,IAAI,CAAC;oBAAEO,OAAO;gBAAiD;YACpE;YACA,MAAM+B,KAAK7F,eAAe,CACxB6B,QACA;gBAAEN,KAAK0E,OAAO1E,GAAG;gBAAEC,KAAK,GAAEyE,gBAAAA,OAAOzE,KAAK,YAAZyE,gBAAgB;YAAK,GAC/CgB,SACI,0CACA,0CACJ;gBAAET,MAAM;gBAAYrC,IAAI4B;gBAAcV;YAAK;YAE7C,OAAOO,IAAI/B,MAAM,CAAC,KAAKN,IAAI,CAAC;gBAAEwC;gBAAclE;gBAAQoF;YAAO;QAC7D,EAAE,OAAOnD,OAAO;YACdiD,QAAQjD,KAAK,CAAC,kCAAkCjC,QAAQkE,cAAcjC;YACtE,OAAO8B,IACJ/B,MAAM,CAAC,KACPN,IAAI,CAAC;gBAAEO,OAAO;YAAqC;QACxD;IACF;AACF;AAEA,OAAO,MAAM2D,8BAA8BhC,oCAAmC;AAC9E,OAAO,MAAMiC,4BAA4BV,kCAAiC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/server/org-automations-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WRITING AN ORG AUTOMATION, and pausing one on a site (AGL-3302).\n *\n * `orgs/{orgId}/automations` is closed to every client write, the way the\n * outreach collections are: an org automation runs on every site it is\n * placed on, as that site, so its trigger, its steps and its placement are\n * decisions the server checks — the vocabulary, the organization's sites, the\n * plan — and nothing a browser may write around.\n *\n * ## Two doors\n *\n * `automations/manage` is the organization's: it creates, edits, switches on\n * and off, and deletes. It names the org and NO site, so it declares a\n * subject resolver for the dispatchers' release gate and asks the org's\n * plugin switch itself; the caller must be an org-wide owner, admin or\n * editor.\n *\n * `automations/pause` is the SITE's — the host level control. It names the\n * site, so the dispatcher applies that site's plugin switch as for any site\n * request, and it changes one thing: whether this automation is paused on\n * THIS site. The site's own admins and editors may use it, and so may an\n * org-wide editor; nobody may pause a site through it but the one named.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { hostIdsFromScope, visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport {\n type AglynOrgMember,\n checkEntitlement,\n isOrgWideMember,\n type PluginApiHandler,\n type PluginApiRequestSubject,\n planLabelGrantingFeature,\n} from '@aglyn/aglyn/server'\n/*\n * The MODULES, not the barrel: `@aglyn/tenant-data-admin`'s index reaches the\n * Next render cache, and everything these doors need is the Admin SDK handle,\n * the id predicate and the org reads.\n */\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport {\n getOrgDoc,\n logHostActivity,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n WORKFLOWS_SITE_PAUSE_PRESET,\n workflowsPermissionRefusal,\n type WorkflowsPermission,\n} from '../model/workflows-permissions'\nimport {\n ORG_AUTOMATION_ACTIVITY_TARGET,\n ORG_AUTOMATION_API_ROUTES,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n orgAutomationPausedHostIds,\n prunePausedHostIds,\n readOrgAutomation,\n type OrgAutomationFields,\n} from '../model/org-automations'\n\nexport { ORG_AUTOMATION_API_ROUTES }\n\n/** What `automations/manage` may be asked to do. */\nexport const ORG_AUTOMATION_MANAGE_ACTIONS = [\n 'create',\n 'update',\n 'setEnabled',\n 'delete',\n] as const\n\ntype ManageAction = (typeof ORG_AUTOMATION_MANAGE_ACTIONS)[number]\n\n\n/** What the doors reach outside this module; specs hand in their own. */\nexport interface OrgAutomationRouteDeps {\n firestore(): FirebaseFirestore.Firestore\n verifyIdToken(token: string): Promise<{ uid: string; email?: string | null }>\n resolveOrgMembership(\n uid: string,\n orgId: string,\n ): Promise<{ orgId: string; member: Partial<AglynOrgMember> } | null>\n getOrgDoc(orgId: string): Promise<Record<string, unknown> | null>\n resolveOrgIdForHost(hostId: string): Promise<string | null>\n /** Whether a member holds a workspace key with no site named (AGL-4047): `memberHasOrgPermission`. */\n holdsOrgKey(orgId: string, member: Partial<AglynOrgMember>, key: WorkflowsPermission): Promise<boolean>\n logOrgActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: typeof ORG_AUTOMATION_ACTIVITY_TARGET; id: string; name?: string },\n ): Promise<void>\n logHostActivity(\n hostId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: 'workflow'; id: string; name?: string },\n ): Promise<void>\n newId(): string\n}\n\nfunction defaultDeps(): OrgAutomationRouteDeps {\n return {\n firestore: () =>\n firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore,\n verifyIdToken: async (token) => {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(token)\n return { uid: decoded.uid, email: decoded.email ?? null }\n },\n resolveOrgMembership: async (uid, orgId) =>\n (await resolveOrgMembership(uid, orgId)) as never,\n getOrgDoc: async (orgId) =>\n ((await getOrgDoc(orgId)) as Record<string, unknown> | null) ?? null,\n resolveOrgIdForHost,\n holdsOrgKey: (orgId, member, key) => memberHasOrgPermission(orgId, member, key as never),\n logOrgActivity: (orgId, actor, action, target) =>\n logOrgActivity(orgId, actor, action, target),\n logHostActivity: (hostId, actor, action, target) =>\n logHostActivity(hostId, actor, action, target),\n newId: createResourceUid,\n }\n}\n\n/** The bearer token a request carries, or null. */\nfunction bearerToken(headers: Partial<Record<string, string | string[]>>): string | null {\n const authorization = String(headers['authorization'] ?? '')\n return authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length) || null\n : null\n}\n\nfunction automationsOf(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): FirebaseFirestore.CollectionReference {\n return firestore\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_AUTOMATIONS_COLLECTION)\n}\n\n/**\n * Whether every site a placement names belongs to this organization — asked\n * of `hostIndex`, the mirror `resolveOrgIdForHost` reads, in one round trip.\n * `['org']` names no site and always answers yes.\n */\nasync function placementIsTheOrgs(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n visibleTo: readonly string[],\n): Promise<boolean> {\n const hostIds = hostIdsFromScope(visibleTo)\n if (!hostIds.length) return true\n if (!hostIds.every(isDocumentId)) return false\n const entries = await firestore.getAll(\n ...hostIds.map((hostId) => firestore.collection('hostIndex').doc(hostId)),\n )\n return entries.every((entry) => entry.exists && entry.get('orgId') === orgId)\n}\n\n/**\n * The organization a `automations/manage` request is for, read off its JSON\n * body, so the dispatchers' release gate asks about the right organization.\n * Consulted only for a request that names no site. Unverified, exactly as a\n * `hostId` is: the handler refuses anyone who is not an org-wide member.\n */\nexport async function orgAutomationsManageSubject(\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n if (request.method !== 'POST') return null\n const body = (await request.json().catch(() => null)) as {\n orgId?: unknown\n } | null\n const orgId = typeof body?.orgId === 'string' ? body.orgId : ''\n return isDocumentId(orgId) ? { orgId } : null\n}\n\n/** What writing an org automation came to: its id, or the refusal the route answers with. */\nexport type OrgAutomationWrite = { ok: true; id: string } | { ok: false; status: number; error: string }\n\n/**\n * Creates an org automation as `automations/manage` does: its sites must be\n * the organization's, and the organization holds at most\n * {@link ORG_AUTOMATIONS_MAX} live ones. The route and the package import\n * (AGL-3535) both create through here.\n */\nexport async function createOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; fields: OrgAutomationFields; actorUid: string },\n): Promise<OrgAutomationWrite> {\n if (!(await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo))) {\n return { ok: false, status: 400, error: 'A site you chose is not in this organization' }\n }\n const collection = automationsOf(firestore, input.orgId)\n /*\n * Counted before the write rather than inside a transaction. The\n * cap bounds storage, not money, so the overshoot two simultaneous\n * saves can buy is one document — the trade the site actions cap\n * makes for the same reason.\n */\n const live = (await collection.where('deletedAt', '==', null).count().get()).data().count\n if (live >= ORG_AUTOMATIONS_MAX) {\n return {\n ok: false,\n status: 409,\n error: `An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first`,\n }\n }\n await collection.doc(input.id).create({\n ...input.fields,\n pausedHostIds: [],\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n createdBy: input.actorUid,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return { ok: true, id: input.id }\n}\n\n/** Rewrites a live org automation as `automations/manage` does; a site it no longer runs on leaves its pause list. */\nexport async function updateOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; fields: OrgAutomationFields; actorUid: string },\n): Promise<OrgAutomationWrite> {\n if (!(await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo))) {\n return { ok: false, status: 400, error: 'A site you chose is not in this organization' }\n }\n const collection = automationsOf(firestore, input.orgId)\n const outcome = await firestore.runTransaction(async (transaction) => {\n const ref = collection.doc(input.id)\n const current = await transaction.get(ref)\n if (!current.exists || current.get('deletedAt')) return 'missing'\n transaction.update(ref, {\n ...input.fields,\n // A site the automation no longer runs on has nothing left to\n // pause: its entry goes, so a later placement starts unpaused.\n pausedHostIds: prunePausedHostIds(orgAutomationPausedHostIds(current.data()), input.fields.visibleTo),\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return 'updated'\n })\n return outcome === 'missing' ? { ok: false, status: 404, error: 'Unknown org automation' } : { ok: true, id: input.id }\n}\n\n/**\n * Deletes an org automation as `automations/manage` does — softly, switched\n * off (see the handler). `null` for one that does not exist; `again` for\n * one already deleted.\n */\nexport async function deleteOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; actorUid: string },\n): Promise<{ name: string; again: boolean } | null> {\n return firestore.runTransaction(async (transaction) => {\n const ref = automationsOf(firestore, input.orgId).doc(input.id)\n const current = await transaction.get(ref)\n if (!current.exists) return null\n // Deleting twice is the same request answered again.\n if (current.get('deletedAt')) return { name: '', again: true }\n transaction.update(ref, {\n deletedAt: FieldValue.serverTimestamp(),\n deletedBy: input.actorUid,\n // Off as well, so the engine's query — which asks for switched-on\n // automations only — never spends one of its places on it.\n enabled: false,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return { name: String(current.get('name') ?? ''), again: false }\n })\n}\n\n/**\n * `automations/manage`: create, edit, switch on or off, and delete one of the\n * organization's automations.\n *\n * A DELETE is soft — `deletedAt` stamped and the automation switched off —\n * because the id is what every run history row and every waiting person\n * names: the rows keep a name to show, and the people waiting inside it are\n * stopped by the resume's kill switch on their next beat. Deleting and\n * switching off are never refused for want of a plan, so an organization\n * that downgraded can always stop what it built.\n */\nexport function createOrgAutomationsManageHandler(\n overrides: Partial<OrgAutomationRouteDeps> = {},\n): PluginApiHandler {\n return async (req, res) => {\n const deps = { ...defaultDeps(), ...overrides }\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const orgId = String(req.body?.orgId ?? '')\n const action = String(req.body?.action ?? '') as ManageAction\n if (!isDocumentId(orgId)) {\n return res.status(400).json({ error: 'Invalid orgId' })\n }\n if (!(ORG_AUTOMATION_MANAGE_ACTIONS as readonly string[]).includes(action)) {\n return res.status(400).json({ error: 'Unknown action' })\n }\n const automationId = String(req.body?.automationId ?? '')\n if (action !== 'create' && !isDocumentId(automationId)) {\n return res.status(400).json({ error: 'Invalid automationId' })\n }\n const token = bearerToken(req.headers)\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const caller = await deps.verifyIdToken(token).catch(() => null)\n if (!caller) return res.status(401).json({ error: 'Unauthenticated' })\n const membership = await deps.resolveOrgMembership(caller.uid, orgId)\n const member = membership?.member\n // \"Manage org automations\" (AGL-4047), for members of the whole\n // workspace: its default is the owner, admins and editors this asked\n // for before, then their custom role and their own permissions.\n if (\n !member ||\n !isOrgWideMember(member) ||\n !(await deps.holdsOrgKey(orgId, member, 'workflows.orgAutomations'))\n ) {\n return res.status(403).json({ error: workflowsPermissionRefusal('workflows.orgAutomations') })\n }\n /*\n * A request naming no site reaches here past only the release gate —\n * the dispatcher's per-site switch needs a site — so the organization's\n * own switch is asked here.\n */\n const org = await deps.getOrgDoc(orgId)\n if (!org || !isPluginEnabled(org as never, BUNDLE_ID)) {\n return res.status(404).json({ error: 'Not found' })\n }\n const enabling =\n action === 'create' ||\n action === 'update' ||\n (action === 'setEnabled' && req.body?.enabled === true)\n if (enabling && !checkEntitlement(org as never, 'actions')) {\n return res.status(403).json({\n error: `Org automations need the ${planLabelGrantingFeature('actions') ?? 'Pro'} plan`,\n })\n }\n\n const firestore = deps.firestore()\n const collection = automationsOf(firestore, orgId)\n const actor = { uid: caller.uid, email: caller.email ?? null }\n const logged = (verb: string, id: string, name: string) =>\n deps.logOrgActivity(orgId, actor, verb, {\n type: ORG_AUTOMATION_ACTIVITY_TARGET,\n id,\n name,\n })\n\n if (action === 'create' || action === 'update') {\n const read = readOrgAutomation(req.body?.automation)\n if (read.ok === false) {\n return res.status(400).json({ error: read.problem })\n }\n const written =\n action === 'create'\n ? await createOrgAutomationRecord(firestore, { orgId, id: deps.newId(), fields: read.value, actorUid: caller.uid })\n : await updateOrgAutomationRecord(firestore, { orgId, id: automationId, fields: read.value, actorUid: caller.uid })\n if (written.ok === false) {\n return res.status(written.status).json({ error: written.error })\n }\n await logged(action === 'create' ? 'Created an org automation' : 'Edited an org automation', written.id, read.value.name)\n return res.status(200).json({ automationId: written.id })\n }\n\n if (action === 'setEnabled') {\n if (typeof req.body?.enabled !== 'boolean') {\n return res.status(400).json({ error: 'Say whether it is enabled' })\n }\n const enabled = req.body.enabled as boolean\n const name = await firestore.runTransaction(async (transaction) => {\n const ref = collection.doc(automationId)\n const current = await transaction.get(ref)\n if (!current.exists || current.get('deletedAt')) return null\n transaction.update(ref, {\n enabled,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: caller.uid,\n })\n return String(current.get('name') ?? '')\n })\n if (name === null) {\n return res.status(404).json({ error: 'Unknown org automation' })\n }\n await logged(\n enabled ? 'Switched on an org automation' : 'Switched off an org automation',\n automationId,\n name,\n )\n return res.status(200).json({ automationId, enabled })\n }\n\n // delete\n const deleted = await deleteOrgAutomationRecord(firestore, { orgId, id: automationId, actorUid: caller.uid })\n if (!deleted) {\n return res.status(404).json({ error: 'Unknown org automation' })\n }\n if (!deleted.again) {\n await logged('Deleted an org automation', automationId, deleted.name)\n }\n return res.status(200).json({ automationId, deleted: true })\n } catch (error) {\n console.error('[org automations] manage failed', orgId, action, error)\n return res\n .status(500)\n .json({ error: 'The request could not be completed' })\n }\n }\n}\n\n/**\n * `automations/pause`: pause or resume one org automation on ONE site.\n *\n * `pausedHostIds` is changed with `arrayUnion`/`arrayRemove` of the named\n * site alone, inside a transaction that first confirms the automation runs\n * there — so a site's editor can take their own site out of an org\n * automation and put it back, and can never touch another site's entry or\n * the automation itself. Pausing stops the people already waiting inside it\n * on this site as well, on their next beat: the resume reads a pause as the\n * kill switch.\n *\n * Never refused for want of a plan: a pause is how a site stops something,\n * and stopping is always allowed.\n */\nexport function createOrgAutomationPauseHandler(\n overrides: Partial<OrgAutomationRouteDeps> = {},\n): PluginApiHandler {\n return async (req, res) => {\n const deps = { ...defaultDeps(), ...overrides }\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const automationId = String(req.body?.automationId ?? '')\n const paused = req.body?.paused\n if (!isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Invalid hostId' })\n }\n if (!isDocumentId(automationId)) {\n return res.status(400).json({ error: 'Invalid automationId' })\n }\n if (typeof paused !== 'boolean') {\n return res.status(400).json({ error: 'Say whether it is paused' })\n }\n const token = bearerToken(req.headers)\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const caller = await deps.verifyIdToken(token).catch(() => null)\n if (!caller) return res.status(401).json({ error: 'Unauthenticated' })\n const firestore = deps.firestore()\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n const orgId = await deps.resolveOrgIdForHost(hostId)\n if (!orgId) {\n return res.status(409).json({\n error: 'This site is not part of an organization, so it runs no org automations.',\n })\n }\n const requestedOrgId = String(req.body?.orgId ?? '')\n if (requestedOrgId && requestedOrgId !== orgId) {\n return res.status(400).json({ error: 'That site is not in this organization' })\n }\n /*\n * The site's own admins and editors, read off the host's `memberRoles`\n * projection — the same answer every site door asks — or an org-wide\n * editor, asked of the membership itself so a projection that has not\n * caught up cannot refuse the organization's own managers.\n */\n // \"Pause org automations on a site\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked\n // for; or \"Manage org automations\" for a member of the whole workspace.\n let allowed = holdsStampedSiteKey(host, caller.uid, 'workflows.sitePause', WORKFLOWS_SITE_PAUSE_PRESET)\n if (!allowed) {\n const membership = await deps.resolveOrgMembership(caller.uid, orgId)\n const member = membership?.member\n allowed =\n Boolean(member) &&\n isOrgWideMember(member) &&\n (await deps.holdsOrgKey(orgId, member as Partial<AglynOrgMember>, 'workflows.orgAutomations'))\n }\n if (!allowed) {\n return res.status(403).json({ error: workflowsPermissionRefusal('workflows.sitePause') })\n }\n\n const name = await firestore.runTransaction(async (transaction) => {\n const ref = automationsOf(firestore, orgId).doc(automationId)\n const current = await transaction.get(ref)\n if (\n !current.exists ||\n current.get('deletedAt') ||\n !visibleToHost(current.get('visibleTo') as string[] | undefined, hostId)\n ) {\n return null\n }\n transaction.update(ref, {\n pausedHostIds: paused\n ? FieldValue.arrayUnion(hostId)\n : FieldValue.arrayRemove(hostId),\n })\n return String(current.get('name') ?? '')\n })\n if (name === null) {\n return res\n .status(404)\n .json({ error: 'No org automation by that id runs on this site' })\n }\n await deps.logHostActivity(\n hostId,\n { uid: caller.uid, email: caller.email ?? null },\n paused\n ? 'Paused an org automation on this site'\n : 'Resumed an org automation on this site',\n { type: 'workflow', id: automationId, name },\n )\n return res.status(200).json({ automationId, hostId, paused })\n } catch (error) {\n console.error('[org automations] pause failed', hostId, automationId, error)\n return res\n .status(500)\n .json({ error: 'The request could not be completed' })\n }\n }\n}\n\nexport const orgAutomationsManageHandler = createOrgAutomationsManageHandler()\nexport const orgAutomationPauseHandler = createOrgAutomationPauseHandler()\n"],"names":["createResourceUid","holdsStampedSiteKey","hostIdsFromScope","visibleToHost","isPluginEnabled","checkEntitlement","isOrgWideMember","planLabelGrantingFeature","isDocumentId","firebaseAdmin","getOrgDoc","logHostActivity","logOrgActivity","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","FieldValue","BUNDLE_ID","WORKFLOWS_SITE_PAUSE_PRESET","workflowsPermissionRefusal","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATION_API_ROUTES","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","orgAutomationPausedHostIds","prunePausedHostIds","readOrgAutomation","ORG_AUTOMATION_MANAGE_ACTIONS","defaultDeps","firestore","app","verifyIdToken","token","decoded","auth","uid","email","orgId","holdsOrgKey","member","key","actor","action","target","hostId","newId","bearerToken","headers","authorization","String","startsWith","slice","length","automationsOf","collection","doc","placementIsTheOrgs","visibleTo","hostIds","every","entries","getAll","map","entry","exists","get","orgAutomationsManageSubject","request","method","body","json","catch","createOrgAutomationRecord","input","fields","ok","status","error","live","where","count","data","id","create","pausedHostIds","deletedAt","createdAt","serverTimestamp","createdBy","actorUid","updatedAt","updatedBy","updateOrgAutomationRecord","outcome","runTransaction","transaction","ref","current","update","deleteOrgAutomationRecord","name","again","deletedBy","enabled","createOrgAutomationsManageHandler","overrides","req","res","deps","includes","automationId","caller","membership","org","enabling","logged","verb","type","read","automation","problem","written","value","deleted","console","createOrgAutomationPauseHandler","paused","host","requestedOrgId","allowed","Boolean","arrayUnion","arrayRemove","orgAutomationsManageHandler","orgAutomationPauseHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,sCAAqC;AACrF,SAASC,eAAe,QAAQ,8CAA6C;AAC7E,SAEEC,gBAAgB,EAChBC,eAAe,EAGfC,wBAAwB,QACnB,sBAAqB;AAC5B;;;;CAIC,GACD,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,OAAOC,mBAAmB,iDAAgD;AAC1E,SACEC,SAAS,EACTC,eAAe,EACfC,cAAc,EACdC,sBAAsB,EACtBC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,2BAA2B,EAC3BC,0BAA0B,QAErB,oCAAgC;AACvC,SACEC,8BAA8B,EAC9BC,yBAAyB,EACzBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,0BAA0B,EAC1BC,kBAAkB,EAClBC,iBAAiB,QAEZ,8BAA0B;AAEjC,SAASL,yBAAyB,GAAE;AAEpC,kDAAkD,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ACJ;gBAAET,MAAM;gBAAYnC,IAAI4B;gBAAcV;YAAK;YAE7C,OAAOO,IAAI/B,MAAM,CAAC,KAAKN,IAAI,CAAC;gBAAEwC;gBAAclE;gBAAQkF;YAAO;QAC7D,EAAE,OAAOjD,OAAO;YACd+C,QAAQ/C,KAAK,CAAC,kCAAkCjC,QAAQkE,cAAcjC;YACtE,OAAO8B,IACJ/B,MAAM,CAAC,KACPN,IAAI,CAAC;gBAAEO,OAAO;YAAqC;QACxD;IACF;AACF;AAEA,OAAO,MAAMwD,8BAA8B7B,oCAAmC;AAC9E,OAAO,MAAM8B,4BAA4BT,kCAAiC"}
@@ -22,6 +22,8 @@ export interface OrgAutomationsPackageDeps {
22
22
  firestore(): Firestore;
23
23
  readOrg(orgId: string): Promise<Record<string, unknown> | null>;
24
24
  memberOf(uid: string, orgId: string): Promise<Record<string, unknown> | null>;
25
+ /** Whether a member holds "Manage org automations" (AGL-4047): `memberHasOrgPermission`. */
26
+ holdsOrgAutomations(orgId: string, member: Record<string, unknown>): Promise<boolean>;
25
27
  logOrgActivity(orgId: string, uid: string, action: string, target: {
26
28
  id: string;
27
29
  name: string;
@@ -30,7 +30,8 @@ import { existingPackageItemsOf } from "@aglyn/aglyn/data-transfer";
30
30
  import { isPluginEnabled } from "@aglyn/aglyn/plugin-manager/enabled-plugins";
31
31
  import { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from "@aglyn/aglyn/server";
32
32
  import firebaseAdmin from "@aglyn/tenant-data-admin/server/firebase-admin";
33
- import { getOrgDoc, logOrgActivity, resolveOrgMembership } from "@aglyn/tenant-data-admin/server/organizations";
33
+ import { getOrgDoc, logOrgActivity, memberHasOrgPermission, resolveOrgMembership } from "@aglyn/tenant-data-admin/server/organizations";
34
+ import { workflowsPermissionRefusal } from "../model/workflows-permissions.js";
34
35
  import { BUNDLE_ID } from "../constants/bundle-common.js";
35
36
  import { ORG_AUTOMATION_ACTIVITY_TARGET, ORG_AUTOMATIONS_COLLECTION, ORG_AUTOMATIONS_MAX, readOrgAutomation } from "../model/org-automations.js";
36
37
  import { createOrgAutomationRecord, deleteOrgAutomationRecord, updateOrgAutomationRecord } from "../server/org-automations-routes.js";
@@ -47,6 +48,7 @@ function defaultDeps() {
47
48
  var _this;
48
49
  return (_ref = (_this = await resolveOrgMembership(uid, orgId)) == null ? void 0 : _this.member) != null ? _ref : null;
49
50
  },
51
+ holdsOrgAutomations: (orgId, member)=>memberHasOrgPermission(orgId, member, 'workflows.orgAutomations'),
50
52
  logOrgActivity: (orgId, uid, action, target)=>logOrgActivity(orgId, {
51
53
  uid,
52
54
  email: null
@@ -57,15 +59,12 @@ function defaultDeps() {
57
59
  }
58
60
  const automationsOf = (firestore, orgId)=>firestore.collection('orgs').doc(orgId).collection(ORG_AUTOMATIONS_COLLECTION);
59
61
  /** Why `automations/manage` would refuse this importer, or `null` when it would not. */ async function importerRefusal(deps, ctx) {
60
- var _member_role;
61
62
  if (!ctx.actorUid) return 'Org automations are imported by a member of the organization.';
62
63
  const member = await deps.memberOf(ctx.actorUid, ctx.orgId);
63
- if (!member || !isOrgWideMember(member) || ![
64
- 'owner',
65
- 'admin',
66
- 'editor'
67
- ].includes(String((_member_role = member['role']) != null ? _member_role : ''))) {
68
- return 'Org automations are written by an organization owner, admin or editor.';
64
+ // "Manage org automations" (AGL-4047), for members of the whole workspace,
65
+ // as `automations/manage` asks it.
66
+ if (!member || !isOrgWideMember(member) || !await deps.holdsOrgAutomations(ctx.orgId, member)) {
67
+ return workflowsPermissionRefusal('workflows.orgAutomations');
69
68
  }
70
69
  const org = await deps.readOrg(ctx.orgId);
71
70
  if (!org || !isPluginEnabled(org, BUNDLE_ID)) return 'Workflows is not on for this workspace.';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/transfer/org-automations-package.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * ORG AUTOMATIONS IN A WORKSPACE PACKAGE — the server half (AGL-3535).\n *\n * Written through `automations/manage`'s own writes\n * (`createOrgAutomationRecord`, `updateOrgAutomationRecord`,\n * `deleteOrgAutomationRecord`): its reader, its placement check, its cap,\n * its soft delete and its activity lines. The importer is held to that\n * door's rules too — an org-wide owner, admin or editor, in a workspace\n * running Workflows on a plan with org automations — so an import can do\n * nothing that door would refuse. A new automation lands switched off; a\n * replaced one keeps whether it was on.\n *=========================================*/\n\nimport { DECLARED_SUBSCRIPTION_TOPICS } from '@aglyn/aglyn/app-utils/subscription-topics'\nimport { existingPackageItemsOf, type ExistingPackageItem, type TransferReferenceKind, type TransferRowResult } from '@aglyn/aglyn/data-transfer'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport type {\n TransferApplyResult,\n TransferApplyWriter,\n TransferPackageItemContent,\n TransferPackageItemWrite,\n TransferPackageRevertResult,\n TransferPackageRevertStep,\n TransferResourceContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from '@aglyn/aglyn/server'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { getOrgDoc, logOrgActivity, resolveOrgMembership } from '@aglyn/tenant-data-admin/server/organizations'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n ORG_AUTOMATION_ACTIVITY_TARGET,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n readOrgAutomation,\n} from '../model/org-automations'\nimport {\n createOrgAutomationRecord,\n deleteOrgAutomationRecord,\n updateOrgAutomationRecord,\n} from '../server/org-automations-routes'\nimport {\n ORG_AUTOMATION_REFERENCE_KINDS,\n ORG_AUTOMATIONS_TRANSFER_KEY,\n orgAutomationPackageContent,\n rawOrgAutomationContent,\n type OrgAutomationPackageContent,\n} from './org-automations-package'\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OrgAutomationsPackageDeps {\n firestore(): Firestore\n readOrg(orgId: string): Promise<Record<string, unknown> | null>\n memberOf(uid: string, orgId: string): Promise<Record<string, unknown> | null>\n logOrgActivity(orgId: string, uid: string, action: string, target: { id: string; name: string }): Promise<void>\n}\n\nfunction defaultDeps(): OrgAutomationsPackageDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore() as unknown as Firestore,\n readOrg: async (orgId) => ((await getOrgDoc(orgId)) as Record<string, unknown> | null) ?? null,\n memberOf: async (uid, orgId) => ((await resolveOrgMembership(uid, orgId))?.member as Record<string, unknown> | undefined) ?? null,\n logOrgActivity: (orgId, uid, action, target) =>\n logOrgActivity(orgId, { uid, email: null }, action, { type: ORG_AUTOMATION_ACTIVITY_TARGET, ...target }),\n }\n}\n\nconst automationsOf = (firestore: Firestore, orgId: string) =>\n firestore.collection('orgs').doc(orgId).collection(ORG_AUTOMATIONS_COLLECTION)\n\n/** Why `automations/manage` would refuse this importer, or `null` when it would not. */\nasync function importerRefusal(deps: OrgAutomationsPackageDeps, ctx: TransferResourceContext): Promise<string | null> {\n if (!ctx.actorUid) return 'Org automations are imported by a member of the organization.'\n const member = await deps.memberOf(ctx.actorUid, ctx.orgId)\n if (!member || !isOrgWideMember(member as never) || !['owner', 'admin', 'editor'].includes(String(member['role'] ?? ''))) {\n return 'Org automations are written by an organization owner, admin or editor.'\n }\n const org = await deps.readOrg(ctx.orgId)\n if (!org || !isPluginEnabled(org as never, BUNDLE_ID)) return 'Workflows is not on for this workspace.'\n if (!checkEntitlement(org as never, 'actions')) {\n return `Org automations need the ${planLabelGrantingFeature('actions') ?? 'Pro'} plan.`\n }\n return null\n}\n\nasync function readAll(\n deps: OrgAutomationsPackageDeps,\n orgId: string,\n ids?: readonly string[],\n): Promise<Array<TransferPackageItemContent<OrgAutomationPackageContent>>> {\n const collection = automationsOf(deps.firestore(), orgId)\n const docs = ids\n ? (await Promise.all(ids.map((id) => collection.doc(id).get()))).filter((doc) => doc.exists)\n : (await collection.where('deletedAt', '==', null).get()).docs\n return docs.flatMap((doc) => {\n if (doc.get('deletedAt')) return []\n const content = orgAutomationPackageContent(doc.data())\n return content ? [{ kind: ORG_AUTOMATIONS_TRANSFER_KEY, id: doc.id, name: content.name, content }] : []\n })\n}\n\n/** The fields one write stores: the content, read by the route's reader, switched on only if it already was. */\nfunction fieldsOf(content: OrgAutomationPackageContent, name: string, enabled: boolean) {\n return readOrgAutomation({ ...content, name, enabled })\n}\n\nexport function createOrgAutomationsPackage(deps: OrgAutomationsPackageDeps = defaultDeps()) {\n /** Whether the automation is on now; a new one is off. */\n const enabledNow = async (orgId: string, id: string) =>\n (await automationsOf(deps.firestore(), orgId).doc(id).get()).get('enabled') === true\n\n return {\n async items(ctx: TransferResourceContext): Promise<ExistingPackageItem[]> {\n return existingPackageItemsOf(ORG_AUTOMATIONS_TRANSFER_KEY, await readAll(deps, ctx.orgId))\n },\n\n async readItems(ctx: TransferResourceContext, ids: readonly string[]) {\n return readAll(deps, ctx.orgId, ids)\n },\n\n async problems(ctx: TransferResourceContext, write: TransferPackageItemWrite<OrgAutomationPackageContent>) {\n const refusal = await importerRefusal(deps, ctx)\n if (refusal) return [refusal]\n const content = rawOrgAutomationContent(write.content)\n const read = fieldsOf(content, write.rename?.name ?? content.name, false)\n if (read.ok === false) return [read.problem]\n const problems: string[] = []\n if (write.decision !== 'replace') {\n const collection = automationsOf(deps.firestore(), ctx.orgId)\n if ((await collection.doc(write.targetId).get()).exists) {\n problems.push('An automation with this id was deleted from this workspace, so it cannot come back under it.')\n }\n const live = (await collection.where('deletedAt', '==', null).count().get()).data().count\n if (live >= ORG_AUTOMATIONS_MAX) {\n problems.push(`An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first.`)\n }\n }\n return problems\n },\n\n async referenceTargets(ctx: TransferResourceContext, kinds: readonly string[]): Promise<TransferReferenceKind[]> {\n const org = deps.firestore().collection('orgs').doc(ctx.orgId)\n const named = async (collection: string, field: string) =>\n (await org.collection(collection).get()).docs\n .filter((doc) => !doc.get('deletedAt'))\n .map((doc) => {\n const name = String(doc.get(field) ?? doc.get('label') ?? '').trim()\n return { id: doc.id, ...(name ? { name } : {}) }\n })\n const answers: TransferReferenceKind[] = []\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.list)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.list, label: 'Email list', targets: await named('lists', 'name') })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.topic)) {\n // Asked only when the email plugin, which owns the topic catalog and answers `email.topics`\n // (AGL-3550), is not running here — and without it the catalog is the built-ins the plugins declare.\n const targets = DECLARED_SUBSCRIPTION_TOPICS.map((topic) => ({ id: topic.id, name: topic.name }))\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.topic, label: 'Subscription topic', targets })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.member)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.member, label: 'Member', targets: await named('members', 'email') })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.dataset)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.dataset, label: 'Dataset', targets: await named('datasets', 'name') })\n }\n return answers\n },\n\n async writeItems(\n ctx: TransferResourceContext,\n items: ReadonlyArray<TransferPackageItemWrite<OrgAutomationPackageContent>>,\n writer: TransferApplyWriter,\n ): Promise<TransferApplyResult> {\n const refusal = await importerRefusal(deps, ctx)\n const firestore = deps.firestore()\n const results: TransferRowResult[] = []\n for (const write of items) {\n const before = await writer.alreadyApplied(write.row)\n if (before) {\n results.push(before)\n continue\n }\n const content = rawOrgAutomationContent(write.content)\n const name = write.rename?.name ?? content.name\n const replacing = write.decision === 'replace'\n const read = fieldsOf(content, name, replacing ? await enabledNow(ctx.orgId, write.targetId) : false)\n let result: TransferRowResult\n if (refusal) result = { row: write.row, outcome: 'failed', message: refusal }\n else if (read.ok === false) result = { row: write.row, outcome: 'failed', message: read.problem }\n else {\n const input = { orgId: ctx.orgId, id: write.targetId, fields: read.value, actorUid: ctx.actorUid ?? '' }\n const written = replacing ? await updateOrgAutomationRecord(firestore, input) : await createOrgAutomationRecord(firestore, input)\n if (written.ok === false) result = { row: write.row, outcome: 'failed', recordId: write.targetId, message: written.error }\n else {\n await deps.logOrgActivity(ctx.orgId, ctx.actorUid ?? '', replacing ? 'Edited an org automation' : 'Created an org automation', {\n id: written.id,\n name: read.value.name,\n })\n result = { row: write.row, outcome: replacing ? 'updated' : 'created', recordId: written.id }\n }\n }\n await writer.markApplied(result)\n results.push(result)\n }\n return { results, undo: [] }\n },\n\n async revertItems(\n ctx: TransferResourceContext,\n steps: ReadonlyArray<TransferPackageRevertStep<OrgAutomationPackageContent>>,\n ): Promise<TransferPackageRevertResult> {\n const firestore = deps.firestore()\n const outcome: TransferPackageRevertResult = { done: [], refused: [] }\n for (const step of steps) {\n if (step.action === 'delete') {\n const deleted = await deleteOrgAutomationRecord(firestore, { orgId: ctx.orgId, id: step.id, actorUid: ctx.actorUid ?? '' })\n if (deleted && !deleted.again) {\n await deps.logOrgActivity(ctx.orgId, ctx.actorUid ?? '', 'Deleted an org automation', { id: step.id, name: deleted.name })\n }\n outcome.done.push(step.id)\n continue\n }\n const content = rawOrgAutomationContent(step.content)\n const read = fieldsOf(content, content.name, await enabledNow(ctx.orgId, step.id))\n if (read.ok === false) {\n outcome.refused.push({ id: step.id, reason: read.problem })\n continue\n }\n const written = await updateOrgAutomationRecord(firestore, { orgId: ctx.orgId, id: step.id, fields: read.value, actorUid: ctx.actorUid ?? '' })\n if (written.ok === false) outcome.refused.push({ id: step.id, reason: written.error })\n else outcome.done.push(step.id)\n }\n return outcome\n },\n }\n}\n"],"names":["DECLARED_SUBSCRIPTION_TOPICS","existingPackageItemsOf","isPluginEnabled","checkEntitlement","isOrgWideMember","planLabelGrantingFeature","firebaseAdmin","getOrgDoc","logOrgActivity","resolveOrgMembership","BUNDLE_ID","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","readOrgAutomation","createOrgAutomationRecord","deleteOrgAutomationRecord","updateOrgAutomationRecord","ORG_AUTOMATION_REFERENCE_KINDS","ORG_AUTOMATIONS_TRANSFER_KEY","orgAutomationPackageContent","rawOrgAutomationContent","defaultDeps","firestore","app","readOrg","orgId","memberOf","uid","member","action","target","email","type","automationsOf","collection","doc","importerRefusal","deps","ctx","actorUid","includes","String","org","readAll","ids","docs","Promise","all","map","id","get","filter","exists","where","flatMap","content","data","kind","name","fieldsOf","enabled","createOrgAutomationsPackage","enabledNow","items","readItems","problems","write","refusal","read","rename","ok","problem","decision","targetId","push","live","count","referenceTargets","kinds","named","field","trim","answers","list","label","targets","topic","dataset","writeItems","writer","results","before","alreadyApplied","row","replacing","result","outcome","message","input","fields","value","written","recordId","error","markApplied","undo","revertItems","steps","done","refused","step","deleted","again","reason"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;2CAW2C,GAE3C,SAASA,4BAA4B,QAAQ,6CAA4C;AACzF,SAASC,sBAAsB,QAAsF,6BAA4B;AACjJ,SAASC,eAAe,QAAQ,8CAA6C;AAU7E,SAASC,gBAAgB,EAAEC,eAAe,EAAEC,wBAAwB,QAAQ,sBAAqB;AACjG,OAAOC,mBAAmB,iDAAgD;AAC1E,SAASC,SAAS,EAAEC,cAAc,EAAEC,oBAAoB,QAAQ,gDAA+C;AAC/G,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,mBAAmB,EACnBC,iBAAiB,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AAE;4BAAES,MAAMqD,QAAQrD,IAAI;wBAAC;oBAC1H;oBACAsC,QAAQY,IAAI,CAAClC,IAAI,CAACoC,KAAK7D,EAAE;oBACzB;gBACF;gBACA,MAAMM,UAAUnC,wBAAwB0F,KAAKvD,OAAO;gBACpD,MAAMa,OAAOT,SAASJ,SAASA,QAAQG,IAAI,EAAE,MAAMI,WAAWxB,IAAIb,KAAK,EAAEqF,KAAK7D,EAAE;gBAChF,IAAImB,KAAKE,EAAE,KAAK,OAAO;oBACrB0B,QAAQa,OAAO,CAACnC,IAAI,CAAC;wBAAEzB,IAAI6D,KAAK7D,EAAE;wBAAEgE,QAAQ7C,KAAKG,OAAO;oBAAC;oBACzD;gBACF;gBACA,MAAM8B,UAAU,MAAMrF,0BAA0BM,WAAW;oBAAEG,OAAOa,IAAIb,KAAK;oBAAEwB,IAAI6D,KAAK7D,EAAE;oBAAEkD,QAAQ/B,KAAKgC,KAAK;oBAAE7D,QAAQ,GAAED,gBAAAA,IAAIC,QAAQ,YAAZD,gBAAgB;gBAAG;gBAC7I,IAAI+D,QAAQ/B,EAAE,KAAK,OAAO0B,QAAQa,OAAO,CAACnC,IAAI,CAAC;oBAAEzB,IAAI6D,KAAK7D,EAAE;oBAAEgE,QAAQZ,QAAQE,KAAK;gBAAC;qBAC/EP,QAAQY,IAAI,CAAClC,IAAI,CAACoC,KAAK7D,EAAE;YAChC;YACA,OAAO+C;QACT;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/transfer/org-automations-package.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * ORG AUTOMATIONS IN A WORKSPACE PACKAGE — the server half (AGL-3535).\n *\n * Written through `automations/manage`'s own writes\n * (`createOrgAutomationRecord`, `updateOrgAutomationRecord`,\n * `deleteOrgAutomationRecord`): its reader, its placement check, its cap,\n * its soft delete and its activity lines. The importer is held to that\n * door's rules too — an org-wide owner, admin or editor, in a workspace\n * running Workflows on a plan with org automations — so an import can do\n * nothing that door would refuse. A new automation lands switched off; a\n * replaced one keeps whether it was on.\n *=========================================*/\n\nimport { DECLARED_SUBSCRIPTION_TOPICS } from '@aglyn/aglyn/app-utils/subscription-topics'\nimport { existingPackageItemsOf, type ExistingPackageItem, type TransferReferenceKind, type TransferRowResult } from '@aglyn/aglyn/data-transfer'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport type {\n TransferApplyResult,\n TransferApplyWriter,\n TransferPackageItemContent,\n TransferPackageItemWrite,\n TransferPackageRevertResult,\n TransferPackageRevertStep,\n TransferResourceContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from '@aglyn/aglyn/server'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport {\n getOrgDoc,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { workflowsPermissionRefusal } from '../model/workflows-permissions'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n ORG_AUTOMATION_ACTIVITY_TARGET,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n readOrgAutomation,\n} from '../model/org-automations'\nimport {\n createOrgAutomationRecord,\n deleteOrgAutomationRecord,\n updateOrgAutomationRecord,\n} from '../server/org-automations-routes'\nimport {\n ORG_AUTOMATION_REFERENCE_KINDS,\n ORG_AUTOMATIONS_TRANSFER_KEY,\n orgAutomationPackageContent,\n rawOrgAutomationContent,\n type OrgAutomationPackageContent,\n} from './org-automations-package'\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OrgAutomationsPackageDeps {\n firestore(): Firestore\n readOrg(orgId: string): Promise<Record<string, unknown> | null>\n memberOf(uid: string, orgId: string): Promise<Record<string, unknown> | null>\n /** Whether a member holds \"Manage org automations\" (AGL-4047): `memberHasOrgPermission`. */\n holdsOrgAutomations(orgId: string, member: Record<string, unknown>): Promise<boolean>\n logOrgActivity(orgId: string, uid: string, action: string, target: { id: string; name: string }): Promise<void>\n}\n\nfunction defaultDeps(): OrgAutomationsPackageDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore() as unknown as Firestore,\n readOrg: async (orgId) => ((await getOrgDoc(orgId)) as Record<string, unknown> | null) ?? null,\n memberOf: async (uid, orgId) => ((await resolveOrgMembership(uid, orgId))?.member as Record<string, unknown> | undefined) ?? null,\n holdsOrgAutomations: (orgId, member) => memberHasOrgPermission(orgId, member as never, 'workflows.orgAutomations' as never),\n logOrgActivity: (orgId, uid, action, target) =>\n logOrgActivity(orgId, { uid, email: null }, action, { type: ORG_AUTOMATION_ACTIVITY_TARGET, ...target }),\n }\n}\n\nconst automationsOf = (firestore: Firestore, orgId: string) =>\n firestore.collection('orgs').doc(orgId).collection(ORG_AUTOMATIONS_COLLECTION)\n\n/** Why `automations/manage` would refuse this importer, or `null` when it would not. */\nasync function importerRefusal(deps: OrgAutomationsPackageDeps, ctx: TransferResourceContext): Promise<string | null> {\n if (!ctx.actorUid) return 'Org automations are imported by a member of the organization.'\n const member = await deps.memberOf(ctx.actorUid, ctx.orgId)\n // \"Manage org automations\" (AGL-4047), for members of the whole workspace,\n // as `automations/manage` asks it.\n if (!member || !isOrgWideMember(member as never) || !(await deps.holdsOrgAutomations(ctx.orgId, member))) {\n return workflowsPermissionRefusal('workflows.orgAutomations')\n }\n const org = await deps.readOrg(ctx.orgId)\n if (!org || !isPluginEnabled(org as never, BUNDLE_ID)) return 'Workflows is not on for this workspace.'\n if (!checkEntitlement(org as never, 'actions')) {\n return `Org automations need the ${planLabelGrantingFeature('actions') ?? 'Pro'} plan.`\n }\n return null\n}\n\nasync function readAll(\n deps: OrgAutomationsPackageDeps,\n orgId: string,\n ids?: readonly string[],\n): Promise<Array<TransferPackageItemContent<OrgAutomationPackageContent>>> {\n const collection = automationsOf(deps.firestore(), orgId)\n const docs = ids\n ? (await Promise.all(ids.map((id) => collection.doc(id).get()))).filter((doc) => doc.exists)\n : (await collection.where('deletedAt', '==', null).get()).docs\n return docs.flatMap((doc) => {\n if (doc.get('deletedAt')) return []\n const content = orgAutomationPackageContent(doc.data())\n return content ? [{ kind: ORG_AUTOMATIONS_TRANSFER_KEY, id: doc.id, name: content.name, content }] : []\n })\n}\n\n/** The fields one write stores: the content, read by the route's reader, switched on only if it already was. */\nfunction fieldsOf(content: OrgAutomationPackageContent, name: string, enabled: boolean) {\n return readOrgAutomation({ ...content, name, enabled })\n}\n\nexport function createOrgAutomationsPackage(deps: OrgAutomationsPackageDeps = defaultDeps()) {\n /** Whether the automation is on now; a new one is off. */\n const enabledNow = async (orgId: string, id: string) =>\n (await automationsOf(deps.firestore(), orgId).doc(id).get()).get('enabled') === true\n\n return {\n async items(ctx: TransferResourceContext): Promise<ExistingPackageItem[]> {\n return existingPackageItemsOf(ORG_AUTOMATIONS_TRANSFER_KEY, await readAll(deps, ctx.orgId))\n },\n\n async readItems(ctx: TransferResourceContext, ids: readonly string[]) {\n return readAll(deps, ctx.orgId, ids)\n },\n\n async problems(ctx: TransferResourceContext, write: TransferPackageItemWrite<OrgAutomationPackageContent>) {\n const refusal = await importerRefusal(deps, ctx)\n if (refusal) return [refusal]\n const content = rawOrgAutomationContent(write.content)\n const read = fieldsOf(content, write.rename?.name ?? content.name, false)\n if (read.ok === false) return [read.problem]\n const problems: string[] = []\n if (write.decision !== 'replace') {\n const collection = automationsOf(deps.firestore(), ctx.orgId)\n if ((await collection.doc(write.targetId).get()).exists) {\n problems.push('An automation with this id was deleted from this workspace, so it cannot come back under it.')\n }\n const live = (await collection.where('deletedAt', '==', null).count().get()).data().count\n if (live >= ORG_AUTOMATIONS_MAX) {\n problems.push(`An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first.`)\n }\n }\n return problems\n },\n\n async referenceTargets(ctx: TransferResourceContext, kinds: readonly string[]): Promise<TransferReferenceKind[]> {\n const org = deps.firestore().collection('orgs').doc(ctx.orgId)\n const named = async (collection: string, field: string) =>\n (await org.collection(collection).get()).docs\n .filter((doc) => !doc.get('deletedAt'))\n .map((doc) => {\n const name = String(doc.get(field) ?? doc.get('label') ?? '').trim()\n return { id: doc.id, ...(name ? { name } : {}) }\n })\n const answers: TransferReferenceKind[] = []\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.list)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.list, label: 'Email list', targets: await named('lists', 'name') })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.topic)) {\n // Asked only when the email plugin, which owns the topic catalog and answers `email.topics`\n // (AGL-3550), is not running here — and without it the catalog is the built-ins the plugins declare.\n const targets = DECLARED_SUBSCRIPTION_TOPICS.map((topic) => ({ id: topic.id, name: topic.name }))\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.topic, label: 'Subscription topic', targets })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.member)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.member, label: 'Member', targets: await named('members', 'email') })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.dataset)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.dataset, label: 'Dataset', targets: await named('datasets', 'name') })\n }\n return answers\n },\n\n async writeItems(\n ctx: TransferResourceContext,\n items: ReadonlyArray<TransferPackageItemWrite<OrgAutomationPackageContent>>,\n writer: TransferApplyWriter,\n ): Promise<TransferApplyResult> {\n const refusal = await importerRefusal(deps, ctx)\n const firestore = deps.firestore()\n const results: TransferRowResult[] = []\n for (const write of items) {\n const before = await writer.alreadyApplied(write.row)\n if (before) {\n results.push(before)\n continue\n }\n const content = rawOrgAutomationContent(write.content)\n const name = write.rename?.name ?? content.name\n const replacing = write.decision === 'replace'\n const read = fieldsOf(content, name, replacing ? await enabledNow(ctx.orgId, write.targetId) : false)\n let result: TransferRowResult\n if (refusal) result = { row: write.row, outcome: 'failed', message: refusal }\n else if (read.ok === false) result = { row: write.row, outcome: 'failed', message: read.problem }\n else {\n const input = { orgId: ctx.orgId, id: write.targetId, fields: read.value, actorUid: ctx.actorUid ?? '' }\n const written = replacing ? await updateOrgAutomationRecord(firestore, input) : await createOrgAutomationRecord(firestore, input)\n if (written.ok === false) result = { row: write.row, outcome: 'failed', recordId: write.targetId, message: written.error }\n else {\n await deps.logOrgActivity(ctx.orgId, ctx.actorUid ?? '', replacing ? 'Edited an org automation' : 'Created an org automation', {\n id: written.id,\n name: read.value.name,\n })\n result = { row: write.row, outcome: replacing ? 'updated' : 'created', recordId: written.id }\n }\n }\n await writer.markApplied(result)\n results.push(result)\n }\n return { results, undo: [] }\n },\n\n async revertItems(\n ctx: TransferResourceContext,\n steps: ReadonlyArray<TransferPackageRevertStep<OrgAutomationPackageContent>>,\n ): Promise<TransferPackageRevertResult> {\n const firestore = deps.firestore()\n const outcome: TransferPackageRevertResult = { done: [], refused: [] }\n for (const step of steps) {\n if (step.action === 'delete') {\n const deleted = await deleteOrgAutomationRecord(firestore, { orgId: ctx.orgId, id: step.id, actorUid: ctx.actorUid ?? '' })\n if (deleted && !deleted.again) {\n await deps.logOrgActivity(ctx.orgId, ctx.actorUid ?? '', 'Deleted an org automation', { id: step.id, name: deleted.name })\n }\n outcome.done.push(step.id)\n continue\n }\n const content = rawOrgAutomationContent(step.content)\n const read = fieldsOf(content, content.name, await enabledNow(ctx.orgId, step.id))\n if (read.ok === false) {\n outcome.refused.push({ id: step.id, reason: read.problem })\n continue\n }\n const written = await updateOrgAutomationRecord(firestore, { orgId: ctx.orgId, id: step.id, fields: read.value, actorUid: ctx.actorUid ?? '' })\n if (written.ok === false) outcome.refused.push({ id: step.id, reason: written.error })\n else outcome.done.push(step.id)\n }\n return outcome\n },\n }\n}\n"],"names":["DECLARED_SUBSCRIPTION_TOPICS","existingPackageItemsOf","isPluginEnabled","checkEntitlement","isOrgWideMember","planLabelGrantingFeature","firebaseAdmin","getOrgDoc","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","workflowsPermissionRefusal","BUNDLE_ID","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","readOrgAutomation","createOrgAutomationRecord","deleteOrgAutomationRecord","updateOrgAutomationRecord","ORG_AUTOMATION_REFERENCE_KINDS","ORG_AUTOMATIONS_TRANSFER_KEY","orgAutomationPackageContent","rawOrgAutomationContent","defaultDeps","firestore","app","readOrg","orgId","memberOf","uid","member","holdsOrgAutomations","action","target","email","type","automationsOf","collection","doc","importerRefusal","deps","ctx","actorUid","org","readAll","ids","docs","Promise","all","map","id","get","filter","exists","where","flatMap","content","data","kind","name","fieldsOf","enabled","createOrgAutomationsPackage","enabledNow","items","readItems","problems","write","refusal","read","rename","ok","problem","decision","targetId","push","live","count","referenceTargets","kinds","named","field","String","trim","answers","includes","list","label","targets","topic","dataset","writeItems","writer","results","before","alreadyApplied","row","replacing","result","outcome","message","input","fields","value","written","recordId","error","markApplied","undo","revertItems","steps","done","refused","step","deleted","again","reason"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;2CAW2C,GAE3C,SAASA,4BAA4B,QAAQ,6CAA4C;AACzF,SAASC,sBAAsB,QAAsF,6BAA4B;AACjJ,SAASC,eAAe,QAAQ,8CAA6C;AAU7E,SAASC,gBAAgB,EAAEC,eAAe,EAAEC,wBAAwB,QAAQ,sBAAqB;AACjG,OAAOC,mBAAmB,iDAAgD;AAC1E,SACEC,SAAS,E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