@aglyn/plugins-crm 1.11.0 → 1.13.0

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.
Files changed (96) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/contact-list-columns.js +4 -3
  3. package/src/lib/components/contact-list-columns.js.map +1 -1
  4. package/src/lib/components/contact-properties-card.js +6 -2
  5. package/src/lib/components/contact-properties-card.js.map +1 -1
  6. package/src/lib/components/contacts-bulk-bar.js +16 -5
  7. package/src/lib/components/contacts-bulk-bar.js.map +1 -1
  8. package/src/lib/components/contacts-section.js +6 -13
  9. package/src/lib/components/contacts-section.js.map +1 -1
  10. package/src/lib/components/crm-record-insights-zone.js +7 -0
  11. package/src/lib/components/crm-record-insights-zone.js.map +1 -1
  12. package/src/lib/components/crm-send-email-dialog.js +1 -1
  13. package/src/lib/components/crm-send-email-dialog.js.map +1 -1
  14. package/src/lib/components/deal-board.d.ts +2 -0
  15. package/src/lib/components/deal-board.js +20 -11
  16. package/src/lib/components/deal-board.js.map +1 -1
  17. package/src/lib/components/deal-stage-card.js +41 -28
  18. package/src/lib/components/deal-stage-card.js.map +1 -1
  19. package/src/lib/components/deals-bulk-bar.js +20 -10
  20. package/src/lib/components/deals-bulk-bar.js.map +1 -1
  21. package/src/lib/components/deals-section.js +1 -0
  22. package/src/lib/components/deals-section.js.map +1 -1
  23. package/src/lib/components/email-capture-card.d.ts +1 -1
  24. package/src/lib/components/email-capture-card.js +2 -1
  25. package/src/lib/components/email-capture-card.js.map +1 -1
  26. package/src/lib/components/record-sharing-card.d.ts +6 -5
  27. package/src/lib/components/record-sharing-card.js +45 -30
  28. package/src/lib/components/record-sharing-card.js.map +1 -1
  29. package/src/lib/components/settings-section.d.ts +18 -11
  30. package/src/lib/components/settings-section.js +36 -19
  31. package/src/lib/components/settings-section.js.map +1 -1
  32. package/src/lib/components/sharing-rules-card.js +2 -1
  33. package/src/lib/components/sharing-rules-card.js.map +1 -1
  34. package/src/lib/components/use-org-members.d.ts +17 -10
  35. package/src/lib/components/use-org-members.js +31 -66
  36. package/src/lib/components/use-org-members.js.map +1 -1
  37. package/src/lib/declarations.d.ts +6 -2
  38. package/src/lib/declarations.js +14 -2
  39. package/src/lib/declarations.js.map +1 -1
  40. package/src/lib/declarations.server.js +16 -0
  41. package/src/lib/declarations.server.js.map +1 -1
  42. package/src/lib/hooks/use-crm-activity-logger.d.ts +2 -2
  43. package/src/lib/hooks/use-crm-activity-logger.js +2 -2
  44. package/src/lib/hooks/use-crm-activity-logger.js.map +1 -1
  45. package/src/lib/hooks/use-crm-record-names.js +59 -6
  46. package/src/lib/hooks/use-crm-record-names.js.map +1 -1
  47. package/src/lib/hooks/use-deal-stage-api.d.ts +2 -0
  48. package/src/lib/hooks/use-deal-stage-api.js +7 -2
  49. package/src/lib/hooks/use-deal-stage-api.js.map +1 -1
  50. package/src/lib/hooks/use-org-member-directory.js +49 -12
  51. package/src/lib/hooks/use-org-member-directory.js.map +1 -1
  52. package/src/lib/hooks/use-stage-move-blocked.d.ts +32 -0
  53. package/src/lib/hooks/use-stage-move-blocked.js +71 -0
  54. package/src/lib/hooks/use-stage-move-blocked.js.map +1 -0
  55. package/src/lib/model/crm-api.d.ts +1 -1
  56. package/src/lib/model/crm-api.js +1 -1
  57. package/src/lib/model/crm-api.js.map +1 -1
  58. package/src/lib/model/crm-permissions.d.ts +35 -0
  59. package/src/lib/model/crm-permissions.js +87 -0
  60. package/src/lib/model/crm-permissions.js.map +1 -0
  61. package/src/lib/model/crm-sharing.d.ts +1 -1
  62. package/src/lib/model/crm-sharing.js +1 -1
  63. package/src/lib/model/crm-sharing.js.map +1 -1
  64. package/src/lib/plugin.js +4 -5
  65. package/src/lib/plugin.js.map +1 -1
  66. package/src/lib/server/capture-contact.d.ts +3 -3
  67. package/src/lib/server/capture-contact.js +3 -3
  68. package/src/lib/server/capture-contact.js.map +1 -1
  69. package/src/lib/server/crm-setup-writers.server.d.ts +2 -3
  70. package/src/lib/server/crm-setup-writers.server.js +4 -16
  71. package/src/lib/server/crm-setup-writers.server.js.map +1 -1
  72. package/src/lib/server/crm-sharing.d.ts +5 -4
  73. package/src/lib/server/crm-sharing.js +8 -6
  74. package/src/lib/server/crm-sharing.js.map +1 -1
  75. package/src/lib/server/email-template-duplicate.js +7 -7
  76. package/src/lib/server/email-template-duplicate.js.map +1 -1
  77. package/src/lib/server/inbound-address.d.ts +9 -7
  78. package/src/lib/server/inbound-address.js +18 -15
  79. package/src/lib/server/inbound-address.js.map +1 -1
  80. package/src/lib/server/org-caller.d.ts +19 -5
  81. package/src/lib/server/org-caller.js +25 -5
  82. package/src/lib/server/org-caller.js.map +1 -1
  83. package/src/lib/server/recipe-routes.d.ts +0 -34
  84. package/src/lib/server/recipe-routes.js +11 -10
  85. package/src/lib/server/recipe-routes.js.map +1 -1
  86. package/src/lib/server/scope-sharing-patch.d.ts +22 -0
  87. package/src/lib/server/scope-sharing-patch.js +25 -0
  88. package/src/lib/server/scope-sharing-patch.js.map +1 -0
  89. package/src/lib/server/task-routes.d.ts +6 -5
  90. package/src/lib/server/task-routes.js +11 -13
  91. package/src/lib/server/task-routes.js.map +1 -1
  92. package/src/lib/server-deal-stage.d.ts +11 -6
  93. package/src/lib/server-deal-stage.js +18 -16
  94. package/src/lib/server-deal-stage.js.map +1 -1
  95. package/src/lib/server.js +16 -18
  96. package/src/lib/server.js.map +1 -1
@@ -37,7 +37,7 @@
37
37
  * host variants get for free from the site role, spelled out for the variant
38
38
  * that has no site.
39
39
  */
40
- import { type AglynOrganization, type PluginApiRequest } from '@aglyn/aglyn/server';
40
+ import type { AglynOrganization, PluginApiRequest } from '@aglyn/aglyn/server';
41
41
  /**
42
42
  * Which level a CRM route runs at, read off its body once.
43
43
  *
@@ -85,8 +85,13 @@ export interface OrgCallerRefusal {
85
85
  export type OrgCallerRequirement =
86
86
  /** `data.manage`, org-wide — the key the CRM is gated on. Staff pass. */
87
87
  'data.manage'
88
- /** A workspace owner or admin, org-wide. Staff acting alone do NOT pass. */
89
- | 'manage-org'
88
+ /**
89
+ * "Change CRM settings" (`crm.settings`, AGL-4047), org-wide — who may
90
+ * share records across sites, change the sharing rules and rotate the
91
+ * capture address. On for owners and admins by default, the role list this
92
+ * asked before it was a key. Staff acting alone do NOT pass.
93
+ */
94
+ | 'crm.settings'
90
95
  /**
91
96
  * "Privacy requests" (`org.privacy`, AGL-4047), org-wide — who may file a
92
97
  * person's erasure. On for owners and admins by default. Staff acting
@@ -98,14 +103,14 @@ export type OrgCallerRequirement =
98
103
  * their role, a custom role and per-member overrides — asked of
99
104
  * `memberHasOrgPermission`. A lookup that fails answers `false`.
100
105
  */
101
- export declare function holdsOrgPermission(orgId: string | null | undefined, uid: string, permission: 'org.privacy'): Promise<boolean>;
106
+ export declare function holdsOrgPermission(orgId: string | null | undefined, uid: string, permission: 'org.privacy' | 'crm.settings' | 'crm.moveStages'): Promise<boolean>;
102
107
  /**
103
108
  * A verified session, org-wide reach in `orgId`, and the requirement — in
104
109
  * that order, the cheapest refusal first — then the org document, which
105
110
  * every org variant needs for the plan and the consent groups.
106
111
  *
107
112
  * Staff are admitted to the `data.manage` requirement as every CRM route
108
- * admits them, and refused the `manage-org` and `org.privacy` ones as the
113
+ * admits them, and refused the `crm.settings` and `org.privacy` ones as the
109
114
  * erasure route refuses them: the workspace is the controller of its
110
115
  * people's data and the instruction to erase has to come from it.
111
116
  */
@@ -113,6 +118,15 @@ export declare function authorizeOrgCaller(req: PluginApiRequest, orgId: string,
113
118
  needs: OrgCallerRequirement;
114
119
  refusal: string;
115
120
  }): Promise<OrgCaller | OrgCallerRefusal>;
121
+ /**
122
+ * Who may move a contact or a deal between stages at the organization level
123
+ * (AGL-4047): what these doors asked before, an org-wide member holding "Manage
124
+ * data" with staff passing it, and then "Move contacts and deals between
125
+ * stages", which follows that key until someone decides it, so with nothing
126
+ * decided it answers the same. Staff are not asked it, as they are not asked
127
+ * "Manage data".
128
+ */
129
+ export declare function authorizeOrgStageMover(req: PluginApiRequest, orgId: string, refusal: string): Promise<OrgCaller | OrgCallerRefusal>;
116
130
  /**
117
131
  * The organization a create names when it comes with no site, in the shape
118
132
  * `getOrgForHost` answers for one that does, or `null` when there is none.
@@ -35,10 +35,10 @@
35
35
  * separately, and no permission grant restores it; this is the boundary the
36
36
  * host variants get for free from the site role, spelled out for the variant
37
37
  * that has no site.
38
- */ import { canManageOrg } from "@aglyn/aglyn/server";
39
- import { firebaseAdmin, getOrgDoc, memberHasOrgPermission, resolveOrgMembership } from "@aglyn/tenant-data-admin";
38
+ */ import { firebaseAdmin, getOrgDoc, memberHasOrgPermission, resolveOrgMembership } from "@aglyn/tenant-data-admin";
40
39
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
41
40
  import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
41
+ import { CRM_MOVE_STAGES_REFUSAL } from "../model/crm-permissions.js";
42
42
  export function readCrmRouteScope(body) {
43
43
  var _ref, _ref1;
44
44
  const hostId = String((_ref = body == null ? void 0 : body['hostId']) != null ? _ref : '').trim().slice(0, 128);
@@ -99,11 +99,11 @@ export function readCrmRouteScope(body) {
99
99
  * every org variant needs for the plan and the consent groups.
100
100
  *
101
101
  * Staff are admitted to the `data.manage` requirement as every CRM route
102
- * admits them, and refused the `manage-org` and `org.privacy` ones as the
102
+ * admits them, and refused the `crm.settings` and `org.privacy` ones as the
103
103
  * erasure route refuses them: the workspace is the controller of its
104
104
  * people's data and the instruction to erase has to come from it.
105
105
  */ export async function authorizeOrgCaller(req, orgId, options) {
106
- var _req_headers_authorization, _ref, _decoded_email, _decoded_name;
106
+ var _req_headers_authorization, _decoded_email, _decoded_name;
107
107
  const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
108
108
  const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined;
109
109
  if (!idToken) return {
@@ -135,7 +135,7 @@ export function readCrmRouteScope(body) {
135
135
  orgId
136
136
  }).catch(()=>null);
137
137
  const orgWide = Boolean(membership == null ? void 0 : membership.orgWide) && (membership == null ? void 0 : membership.orgId) === orgId;
138
- const admitted = options.needs === 'data.manage' ? staff || orgWide && await holdsDataManage(orgId, decoded.uid) : options.needs === 'org.privacy' ? orgWide && await holdsOrgPermission(orgId, decoded.uid, 'org.privacy') : orgWide && canManageOrg((_ref = membership == null ? void 0 : membership.role) != null ? _ref : null);
138
+ const admitted = options.needs === 'data.manage' ? staff || orgWide && await holdsDataManage(orgId, decoded.uid) : orgWide && await holdsOrgPermission(orgId, decoded.uid, options.needs);
139
139
  if (!admitted) return {
140
140
  ok: false,
141
141
  status: 403,
@@ -157,6 +157,26 @@ export function readCrmRouteScope(body) {
157
157
  org
158
158
  };
159
159
  }
160
+ /**
161
+ * Who may move a contact or a deal between stages at the organization level
162
+ * (AGL-4047): what these doors asked before, an org-wide member holding "Manage
163
+ * data" with staff passing it, and then "Move contacts and deals between
164
+ * stages", which follows that key until someone decides it, so with nothing
165
+ * decided it answers the same. Staff are not asked it, as they are not asked
166
+ * "Manage data".
167
+ */ export async function authorizeOrgStageMover(req, orgId, refusal) {
168
+ const caller = await authorizeOrgCaller(req, orgId, {
169
+ needs: 'data.manage',
170
+ refusal
171
+ });
172
+ if (caller.ok === false || caller.staff) return caller;
173
+ if (await holdsOrgPermission(orgId, caller.uid, 'crm.moveStages')) return caller;
174
+ return {
175
+ ok: false,
176
+ status: 403,
177
+ error: CRM_MOVE_STAGES_REFUSAL
178
+ };
179
+ }
160
180
  /**
161
181
  * The organization a create names when it comes with no site, in the shape
162
182
  * `getOrgForHost` answers for one that does, or `null` when there is none.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/org-caller.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 * WHO IS CALLING AT THE ORGANIZATION LEVEL (AGL-2634).\n *\n * The CRM's host-routed actions — a stage move, a merge, an erasure, an\n * email — were written for the site hub: each resolves the org FROM the\n * site, checks the caller's role ON that site, and logs into that site's\n * feed. The organization-level hub (AGL-2630) mounts the same surfaces with\n * no site, and for a while every one of those actions ran \"as the record's\n * own capturing site\", which left a record nobody's site had captured with\n * nothing to run as. The org variant of each route authorizes HERE instead:\n * by the org the body names, for an org-wide member, with the permission\n * the whole CRM is gated on — the same three facts the org hub's own page\n * gate checks (`resolveOrgCrmAccess`), so what the console offers and what\n * the server admits cannot drift.\n *\n * A ROLE IS NOT A REACH. A site collaborator is a real member document\n * carrying `role: 'editor'`, and that role holds `data.manage` — so a gate\n * that read the permission alone would admit a contractor on one microsite\n * to act over every site in the agency. `orgWide` is checked first and\n * separately, and no permission grant restores it; this is the boundary the\n * host variants get for free from the site role, spelled out for the variant\n * that has no site.\n */\n\nimport { type AglynOrganization, canManageOrg, type PluginApiRequest } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgDoc,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\n\n/**\n * Which level a CRM route runs at, read off its body once.\n *\n * `orgId` present is the ORGANIZATION variant, whatever else the body\n * carries: the org-level console always names its org, and a `hostId`\n * beside it is the record's own site or the site an email leaves from —\n * never what the caller is authorized against. `hostId` alone is the site\n * variant every route has always had.\n */\nexport interface CrmRouteScope {\n level: 'site' | 'org'\n hostId: string\n orgId: string\n}\n\nexport function readCrmRouteScope(\n body: Record<string, unknown> | null | undefined,\n): CrmRouteScope | null {\n const hostId = String(body?.['hostId'] ?? '')\n .trim()\n .slice(0, 128)\n const orgId = String(body?.['orgId'] ?? '')\n .trim()\n .slice(0, 128)\n if (orgId) return { level: 'org', hostId, orgId }\n if (hostId) return { level: 'site', hostId, orgId: '' }\n return null\n}\n\n/**\n * Whether `uid` holds `data.manage` in `orgId`, as the permission catalog\n * resolves it: the member's role, a custom role and per-member overrides\n * (AGL-2843).\n *\n * Asked of `memberHasOrgPermission`, never of the `permissions` map\n * `resolveOrgPermissions` returns. That map is the legacy six keys plus the\n * keys plugins register (`ResolvedOrgPermissionSet`), and `data.manage` is a\n * catalog key, so it is never in it: a gate that read it there would refuse\n * everyone but staff. A lookup that fails answers `false`.\n */\nexport async function holdsDataManage(\n orgId: string | null | undefined,\n uid: string,\n): Promise<boolean> {\n if (!orgId) return false\n try {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member ?? null\n if (!member) return false\n return (await memberHasOrgPermission(orgId, member, 'data.manage')) === true\n } catch {\n return false\n }\n}\n\nexport interface OrgCaller {\n ok: true\n uid: string\n /** The token's address, or null for an account with none. */\n email: string | null\n /** The token's display name, `''` when it carries none. */\n name: string\n staff: boolean\n orgId: string\n org: Partial<AglynOrganization>\n}\n\nexport interface OrgCallerRefusal {\n ok: false\n status: number\n error: string\n}\n\n/** What the caller must hold over the whole organization. */\nexport type OrgCallerRequirement =\n /** `data.manage`, org-wide — the key the CRM is gated on. Staff pass. */\n | 'data.manage'\n /** A workspace owner or admin, org-wide. Staff acting alone do NOT pass. */\n | 'manage-org'\n /**\n * \"Privacy requests\" (`org.privacy`, AGL-4047), org-wide — who may file a\n * person's erasure. On for owners and admins by default. Staff acting\n * alone do NOT pass.\n */\n | 'org.privacy'\n\n/**\n * Whether `uid` holds a catalog key in `orgId` as the catalog resolves it —\n * their role, a custom role and per-member overrides — asked of\n * `memberHasOrgPermission`. A lookup that fails answers `false`.\n */\nexport async function holdsOrgPermission(\n orgId: string | null | undefined,\n uid: string,\n permission: 'org.privacy',\n): Promise<boolean> {\n if (!orgId) return false\n try {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member ?? null\n if (!member) return false\n return (await memberHasOrgPermission(orgId, member, permission)) === true\n } catch {\n return false\n }\n}\n\n/**\n * A verified session, org-wide reach in `orgId`, and the requirement — in\n * that order, the cheapest refusal first — then the org document, which\n * every org variant needs for the plan and the consent groups.\n *\n * Staff are admitted to the `data.manage` requirement as every CRM route\n * admits them, and refused the `manage-org` and `org.privacy` ones as the\n * erasure route refuses them: the workspace is the controller of its\n * people's data and the instruction to erase has to come from it.\n */\nexport async function authorizeOrgCaller(\n req: PluginApiRequest,\n orgId: string,\n options: { needs: OrgCallerRequirement; refusal: string },\n): Promise<OrgCaller | OrgCallerRefusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let decoded: { uid: string; email?: string; name?: string; staff?: unknown }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // A refused credential is the caller's 401. A failure to check one is\n // ours and keeps a 5xx, so an outage pages instead of reading as a bad\n // token (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the organization caller could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const staff = decoded.staff === true\n const membership = await resolveOrgPermissions(decoded.uid, { orgId }).catch(\n () => null,\n )\n const orgWide = Boolean(membership?.orgWide) && membership?.orgId === orgId\n const admitted =\n options.needs === 'data.manage'\n ? staff || (orgWide && (await holdsDataManage(orgId, decoded.uid)))\n : options.needs === 'org.privacy'\n ? orgWide && (await holdsOrgPermission(orgId, decoded.uid, 'org.privacy'))\n : orgWide && canManageOrg(membership?.role ?? null)\n if (!admitted) return { ok: false, status: 403, error: options.refusal }\n const org = await getOrgDoc(orgId).catch(() => null)\n if (!org) return { ok: false, status: 404, error: 'Unknown organization' }\n return {\n ok: true,\n uid: decoded.uid,\n email: decoded.email ?? null,\n name: String(decoded.name ?? '')\n .trim()\n .slice(0, 120),\n staff,\n orgId,\n org,\n }\n}\n\n/**\n * The organization a create names when it comes with no site, in the shape\n * `getOrgForHost` answers for one that does, or `null` when there is none.\n */\nexport async function readOrgForCreate(\n orgId: string,\n): Promise<{ orgId: string; org: Partial<AglynOrganization> } | null> {\n const org = await getOrgDoc(orgId).catch(() => null)\n return org ? { orgId, org } : null\n}\n\n/**\n * Every site of the organization, by document id — the host set an\n * org-level act sweeps when it needs one (AGL-2634). One equality on\n * `hosts.orgId`, the query the erasure route already ran, which needs no\n * composite index.\n */\nexport async function orgHostIds(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> {\n const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).get()\n return hosts.docs.map((doc: { id: string }) => String(doc.id))\n}\n"],"names":["canManageOrg","firebaseAdmin","getOrgDoc","memberHasOrgPermission","resolveOrgMembership","isRefusedIdToken","resolveOrgPermissions","readCrmRouteScope","body","hostId","String","trim","slice","orgId","level","holdsDataManage","uid","membership","member","holdsOrgPermission","permission","authorizeOrgCaller","req","options","decoded","authorization","headers","idToken","startsWith","length","undefined","ok","status","error","app","auth","verifyIdToken","console","staff","catch","orgWide","Boolean","admitted","needs","role","refusal","org","email","name","readOrgForCreate","orgHostIds","firestore","hosts","collection","where","get","docs","map","doc","id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,SAAiCA,YAAY,QAA+B,sBAAqB;AACjG,SACEC,aAAa,EACbC,SAAS,EACTC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,qBAAqB,QAAQ,wCAAuC;AAiB7E,OAAO,SAASC,kBACdC,IAAgD;;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,KAAKQ,QAAQR,GAAG;QAChB+B,KAAK,GAAEvB,iBAAAA,QAAQuB,KAAK,YAAbvB,iBAAiB;QACxBwB,MAAMtC,QAAOc,gBAAAA,QAAQwB,IAAI,YAAZxB,gBAAgB,IAC1Bb,IAAI,GACJC,KAAK,CAAC,GAAG;QACZ0B;QACAzB;QACAiC;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,eAAeG,iBACpBpC,KAAa;IAEb,MAAMiC,MAAM,MAAM5C,UAAUW,OAAO0B,KAAK,CAAC,IAAM;IAC/C,OAAOO,MAAM;QAAEjC;QAAOiC;IAAI,IAAI;AAChC;AAEA;;;;;CAKC,GACD,OAAO,eAAeI,WACpBC,SAAsC,EACtCtC,KAAa;IAEb,MAAMuC,QAAQ,MAAMD,UAAUE,UAAU,CAAC,SAASC,KAAK,CAAC,SAAS,MAAMzC,OAAO0C,GAAG;IACjF,OAAOH,MAAMI,IAAI,CAACC,GAAG,CAAC,CAACC,MAAwBhD,OAAOgD,IAAIC,EAAE;AAC9D"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/org-caller.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 * WHO IS CALLING AT THE ORGANIZATION LEVEL (AGL-2634).\n *\n * The CRM's host-routed actions — a stage move, a merge, an erasure, an\n * email — were written for the site hub: each resolves the org FROM the\n * site, checks the caller's role ON that site, and logs into that site's\n * feed. The organization-level hub (AGL-2630) mounts the same surfaces with\n * no site, and for a while every one of those actions ran \"as the record's\n * own capturing site\", which left a record nobody's site had captured with\n * nothing to run as. The org variant of each route authorizes HERE instead:\n * by the org the body names, for an org-wide member, with the permission\n * the whole CRM is gated on — the same three facts the org hub's own page\n * gate checks (`resolveOrgCrmAccess`), so what the console offers and what\n * the server admits cannot drift.\n *\n * A ROLE IS NOT A REACH. A site collaborator is a real member document\n * carrying `role: 'editor'`, and that role holds `data.manage` — so a gate\n * that read the permission alone would admit a contractor on one microsite\n * to act over every site in the agency. `orgWide` is checked first and\n * separately, and no permission grant restores it; this is the boundary the\n * host variants get for free from the site role, spelled out for the variant\n * that has no site.\n */\n\nimport type { AglynOrganization, PluginApiRequest } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgDoc,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { CRM_MOVE_STAGES_REFUSAL } from '../model/crm-permissions'\n\n/**\n * Which level a CRM route runs at, read off its body once.\n *\n * `orgId` present is the ORGANIZATION variant, whatever else the body\n * carries: the org-level console always names its org, and a `hostId`\n * beside it is the record's own site or the site an email leaves from —\n * never what the caller is authorized against. `hostId` alone is the site\n * variant every route has always had.\n */\nexport interface CrmRouteScope {\n level: 'site' | 'org'\n hostId: string\n orgId: string\n}\n\nexport function readCrmRouteScope(\n body: Record<string, unknown> | null | undefined,\n): CrmRouteScope | null {\n const hostId = String(body?.['hostId'] ?? '')\n .trim()\n .slice(0, 128)\n const orgId = String(body?.['orgId'] ?? '')\n .trim()\n .slice(0, 128)\n if (orgId) return { level: 'org', hostId, orgId }\n if (hostId) return { level: 'site', hostId, orgId: '' }\n return null\n}\n\n/**\n * Whether `uid` holds `data.manage` in `orgId`, as the permission catalog\n * resolves it: the member's role, a custom role and per-member overrides\n * (AGL-2843).\n *\n * Asked of `memberHasOrgPermission`, never of the `permissions` map\n * `resolveOrgPermissions` returns. That map is the legacy six keys plus the\n * keys plugins register (`ResolvedOrgPermissionSet`), and `data.manage` is a\n * catalog key, so it is never in it: a gate that read it there would refuse\n * everyone but staff. A lookup that fails answers `false`.\n */\nexport async function holdsDataManage(\n orgId: string | null | undefined,\n uid: string,\n): Promise<boolean> {\n if (!orgId) return false\n try {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member ?? null\n if (!member) return false\n return (await memberHasOrgPermission(orgId, member, 'data.manage')) === true\n } catch {\n return false\n }\n}\n\nexport interface OrgCaller {\n ok: true\n uid: string\n /** The token's address, or null for an account with none. */\n email: string | null\n /** The token's display name, `''` when it carries none. */\n name: string\n staff: boolean\n orgId: string\n org: Partial<AglynOrganization>\n}\n\nexport interface OrgCallerRefusal {\n ok: false\n status: number\n error: string\n}\n\n/** What the caller must hold over the whole organization. */\nexport type OrgCallerRequirement =\n /** `data.manage`, org-wide — the key the CRM is gated on. Staff pass. */\n | 'data.manage'\n /**\n * \"Change CRM settings\" (`crm.settings`, AGL-4047), org-wide — who may\n * share records across sites, change the sharing rules and rotate the\n * capture address. On for owners and admins by default, the role list this\n * asked before it was a key. Staff acting alone do NOT pass.\n */\n | 'crm.settings'\n /**\n * \"Privacy requests\" (`org.privacy`, AGL-4047), org-wide — who may file a\n * person's erasure. On for owners and admins by default. Staff acting\n * alone do NOT pass.\n */\n | 'org.privacy'\n\n/**\n * Whether `uid` holds a catalog key in `orgId` as the catalog resolves it —\n * their role, a custom role and per-member overrides — asked of\n * `memberHasOrgPermission`. A lookup that fails answers `false`.\n */\nexport async function holdsOrgPermission(\n orgId: string | null | undefined,\n uid: string,\n permission: 'org.privacy' | 'crm.settings' | 'crm.moveStages',\n): Promise<boolean> {\n if (!orgId) return false\n try {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member ?? null\n if (!member) return false\n return (await memberHasOrgPermission(orgId, member, permission)) === true\n } catch {\n return false\n }\n}\n\n/**\n * A verified session, org-wide reach in `orgId`, and the requirement — in\n * that order, the cheapest refusal first — then the org document, which\n * every org variant needs for the plan and the consent groups.\n *\n * Staff are admitted to the `data.manage` requirement as every CRM route\n * admits them, and refused the `crm.settings` and `org.privacy` ones as the\n * erasure route refuses them: the workspace is the controller of its\n * people's data and the instruction to erase has to come from it.\n */\nexport async function authorizeOrgCaller(\n req: PluginApiRequest,\n orgId: string,\n options: { needs: OrgCallerRequirement; refusal: string },\n): Promise<OrgCaller | OrgCallerRefusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let decoded: { uid: string; email?: string; name?: string; staff?: unknown }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // A refused credential is the caller's 401. A failure to check one is\n // ours and keeps a 5xx, so an outage pages instead of reading as a bad\n // token (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the organization caller could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const staff = decoded.staff === true\n const membership = await resolveOrgPermissions(decoded.uid, { orgId }).catch(\n () => null,\n )\n const orgWide = Boolean(membership?.orgWide) && membership?.orgId === orgId\n const admitted =\n options.needs === 'data.manage'\n ? staff || (orgWide && (await holdsDataManage(orgId, decoded.uid)))\n : orgWide && (await holdsOrgPermission(orgId, decoded.uid, options.needs))\n if (!admitted) return { ok: false, status: 403, error: options.refusal }\n const org = await getOrgDoc(orgId).catch(() => null)\n if (!org) return { ok: false, status: 404, error: 'Unknown organization' }\n return {\n ok: true,\n uid: decoded.uid,\n email: decoded.email ?? null,\n name: String(decoded.name ?? '')\n .trim()\n .slice(0, 120),\n staff,\n orgId,\n org,\n }\n}\n\n/**\n * Who may move a contact or a deal between stages at the organization level\n * (AGL-4047): what these doors asked before, an org-wide member holding \"Manage\n * data\" with staff passing it, and then \"Move contacts and deals between\n * stages\", which follows that key until someone decides it, so with nothing\n * decided it answers the same. Staff are not asked it, as they are not asked\n * \"Manage data\".\n */\nexport async function authorizeOrgStageMover(\n req: PluginApiRequest,\n orgId: string,\n refusal: string,\n): Promise<OrgCaller | OrgCallerRefusal> {\n const caller = await authorizeOrgCaller(req, orgId, { needs: 'data.manage', refusal })\n if (caller.ok === false || caller.staff) return caller\n if (await holdsOrgPermission(orgId, caller.uid, 'crm.moveStages')) return caller\n return { ok: false, status: 403, error: CRM_MOVE_STAGES_REFUSAL }\n}\n\n/**\n * The organization a create names when it comes with no site, in the shape\n * `getOrgForHost` answers for one that does, or `null` when there is none.\n */\nexport async function readOrgForCreate(\n orgId: string,\n): Promise<{ orgId: string; org: Partial<AglynOrganization> } | null> {\n const org = await getOrgDoc(orgId).catch(() => null)\n return org ? { orgId, org } : null\n}\n\n/**\n * Every site of the organization, by document id — the host set an\n * org-level act sweeps when it needs one (AGL-2634). One equality on\n * `hosts.orgId`, the query the erasure route already ran, which needs no\n * composite index.\n */\nexport async function orgHostIds(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> {\n const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).get()\n return hosts.docs.map((doc: { id: string }) => String(doc.id))\n}\n"],"names":["firebaseAdmin","getOrgDoc","memberHasOrgPermission","resolveOrgMembership","isRefusedIdToken","resolveOrgPermissions","CRM_MOVE_STAGES_REFUSAL","readCrmRouteScope","body","hostId","String","trim","slice","orgId","level","holdsDataManage","uid","membership","member","holdsOrgPermission","permission","authorizeOrgCaller","req","options","decoded","authorization","headers","idToken","startsWith","length","undefined","ok","status","error","app","auth","verifyIdToken","console","staff","catch","orgWide","Boolean","admitted","needs","refusal","org","email","name","authorizeOrgStageMover","caller","readOrgForCreate","orgHostIds","firestore","hosts","collection","where","get","docs","map","doc","id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAGD,SACEA,aAAa,EACbC,SAAS,EACT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CAAC,IAAM;IAC/C,IAAI,CAACM,KAAK,OAAO;QAAEd,IAAI;QAAOC,QAAQ;QAAKC,OAAO;IAAuB;IACzE,OAAO;QACLF,IAAI;QACJf,KAAKQ,QAAQR,GAAG;QAChB8B,KAAK,GAAEtB,iBAAAA,QAAQsB,KAAK,YAAbtB,iBAAiB;QACxBuB,MAAMrC,QAAOc,gBAAAA,QAAQuB,IAAI,YAAZvB,gBAAgB,IAC1Bb,IAAI,GACJC,KAAK,CAAC,GAAG;QACZ0B;QACAzB;QACAgC;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeG,uBACpB1B,GAAqB,EACrBT,KAAa,EACb+B,OAAe;IAEf,MAAMK,SAAS,MAAM5B,mBAAmBC,KAAKT,OAAO;QAAE8B,OAAO;QAAeC;IAAQ;IACpF,IAAIK,OAAOlB,EAAE,KAAK,SAASkB,OAAOX,KAAK,EAAE,OAAOW;IAChD,IAAI,MAAM9B,mBAAmBN,OAAOoC,OAAOjC,GAAG,EAAE,mBAAmB,OAAOiC;IAC1E,OAAO;QAAElB,IAAI;QAAOC,QAAQ;QAAKC,OAAO3B;IAAwB;AAClE;AAEA;;;CAGC,GACD,OAAO,eAAe4C,iBACpBrC,KAAa;IAEb,MAAMgC,MAAM,MAAM5C,UAAUY,OAAO0B,KAAK,CAAC,IAAM;IAC/C,OAAOM,MAAM;QAAEhC;QAAOgC;IAAI,IAAI;AAChC;AAEA;;;;;CAKC,GACD,OAAO,eAAeM,WACpBC,SAAsC,EACtCvC,KAAa;IAEb,MAAMwC,QAAQ,MAAMD,UAAUE,UAAU,CAAC,SAASC,KAAK,CAAC,SAAS,MAAM1C,OAAO2C,GAAG;IACjF,OAAOH,MAAMI,IAAI,CAACC,GAAG,CAAC,CAACC,MAAwBjD,OAAOiD,IAAIC,EAAE;AAC9D"}
@@ -14,40 +14,6 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- /**
18
- * THE RECIPES, INSTALLED FROM THE ORGANIZATION (AGL-2639).
19
- *
20
- * On a site, a recipe opens the Actions editor prefilled and writes nothing
21
- * until the person saves — the editor is the writer, and the site's own
22
- * role is the authority. The organization-level CRM hub has no editor: it
23
- * mounts over every site with no site of its own, and an org running five
24
- * sites installed "Welcome a new lead" five times by hand. These two routes
25
- * are the org hub's door to a site's automations.
26
- *
27
- * `crm/recipe-install` writes the action a recipe builds into ONE site's
28
- * `hosts/{hostId}/actions`, as the site editor would have saved it — the
29
- * same builder, the same validator, the same stored shape — and refuses a
30
- * second install of the same recipe on the same site by the stamp the
31
- * builder puts on it. A server route rather than a client write for three
32
- * reasons the browser cannot supply: the document is created by a server
33
- * on every plan (the rules close `actions` to client creates, and the
34
- * per-site cap is counted here); the stamp is the server's word, not the
35
- * caller's; and the site is checked to be one the caller may manage —
36
- * at the org level, a site OF THE ORG the caller holds org-wide reach in,
37
- * so a host id typed into the body cannot reach a site under another
38
- * workspace.
39
- *
40
- * `crm/recipe-status` reads the stamps back for every site of the org, so
41
- * the card can say which sites carry which recipe. An action with no stamp
42
- * at all — saved before the stamp existed — is counted, not ignored: it
43
- * may well be a recipe, and the reader is told the site "may already have
44
- * it" rather than shown a clean slate.
45
- *
46
- * Both routes serve the site variant too (`hostId` alone, authorized by the
47
- * host role that creates actions today), so a site-level caller gets the
48
- * same answers; the org variant (`orgId` in the body) is the one the org
49
- * hub uses.
50
- */
51
17
  import { type PluginApiHandler } from '@aglyn/aglyn/server';
52
18
  export declare const CRM_RECIPE_INSTALL_ROUTE: "crm/recipe-install";
53
19
  export declare const CRM_RECIPE_STATUS_ROUTE: "crm/recipe-status";
@@ -44,10 +44,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
44
44
  * it" rather than shown a clean slate.
45
45
  *
46
46
  * Both routes serve the site variant too (`hostId` alone, authorized by the
47
- * host role that creates actions today), so a site-level caller gets the
47
+ * site key that creates actions today), so a site-level caller gets the
48
48
  * same answers; the org variant (`orgId` in the body) is the one the org
49
49
  * hub uses.
50
- */ import { ACTIONS_MAX_PER_HOST, checkEntitlement, createResourceUid, hostRoleCanWrite, planLabelGrantingFeature, siteInteractionDocument } from "@aglyn/aglyn/server";
50
+ */ import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
51
+ import { ACTIONS_MAX_PER_HOST, checkEntitlement, createResourceUid, planLabelGrantingFeature, siteInteractionDocument } from "@aglyn/aglyn/server";
51
52
  import { interactionRecipeStamp } from "@aglyn/aglyn/plugin-manager/interaction-recipes";
52
53
  import { validateStoredInteraction } from "@aglyn/aglyn/plugin-manager/interaction-step-checks";
53
54
  import { firebaseAdmin, getOrgForHost, logHostActivity, logOrgActivity } from "@aglyn/tenant-data-admin";
@@ -65,12 +66,13 @@ function typed(value, max) {
65
66
  return String(value != null ? value : '').trim().slice(0, max);
66
67
  }
67
68
  /**
68
- * The site variant's authority: the role on the host document that creates
69
- * an action through `/api/hosts/resources` today. Staff pass, as they pass
70
- * that route. Answers the host snapshot it read, so the caller reads it
71
- * once.
69
+ * The site variant's authority: "Edit site content" (`site.edit`, AGL-4047) on
70
+ * the host document, whose preset is the Admin, Editor and Author this asked
71
+ * for and which creates an action through `/api/hosts/resources` today. Staff
72
+ * pass, as they pass that route. Answers the host snapshot it read, so the
73
+ * caller reads it once.
72
74
  */ async function authorizeSiteWriter(req, hostId) {
73
- var _req_headers_authorization, _host_get, _decoded_email;
75
+ var _req_headers_authorization, _decoded_email;
74
76
  const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
75
77
  const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined;
76
78
  if (!idToken) return {
@@ -103,12 +105,11 @@ function typed(value, max) {
103
105
  status: 404,
104
106
  error: 'Unknown site'
105
107
  };
106
- const role = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[decoded.uid];
107
- if (!staff && !hostRoleCanWrite(role)) {
108
+ if (!staff && !holdsSiteKey(host, decoded.uid, 'site.edit')) {
108
109
  return {
109
110
  ok: false,
110
111
  status: 403,
111
- error: 'Editing requires the editor role'
112
+ error: siteKeyRefusal('site.edit')
112
113
  };
113
114
  }
114
115
  const resolved = await getOrgForHost(hostId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/recipe-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 * THE RECIPES, INSTALLED FROM THE ORGANIZATION (AGL-2639).\n *\n * On a site, a recipe opens the Actions editor prefilled and writes nothing\n * until the person saves — the editor is the writer, and the site's own\n * role is the authority. The organization-level CRM hub has no editor: it\n * mounts over every site with no site of its own, and an org running five\n * sites installed \"Welcome a new lead\" five times by hand. These two routes\n * are the org hub's door to a site's automations.\n *\n * `crm/recipe-install` writes the action a recipe builds into ONE site's\n * `hosts/{hostId}/actions`, as the site editor would have saved it — the\n * same builder, the same validator, the same stored shape — and refuses a\n * second install of the same recipe on the same site by the stamp the\n * builder puts on it. A server route rather than a client write for three\n * reasons the browser cannot supply: the document is created by a server\n * on every plan (the rules close `actions` to client creates, and the\n * per-site cap is counted here); the stamp is the server's word, not the\n * caller's; and the site is checked to be one the caller may manage —\n * at the org level, a site OF THE ORG the caller holds org-wide reach in,\n * so a host id typed into the body cannot reach a site under another\n * workspace.\n *\n * `crm/recipe-status` reads the stamps back for every site of the org, so\n * the card can say which sites carry which recipe. An action with no stamp\n * at all — saved before the stamp existed — is counted, not ignored: it\n * may well be a recipe, and the reader is told the site \"may already have\n * it\" rather than shown a clean slate.\n *\n * Both routes serve the site variant too (`hostId` alone, authorized by the\n * host role that creates actions today), so a site-level caller gets the\n * same answers; the org variant (`orgId` in the body) is the one the org\n * hub uses.\n */\n\nimport {\n ACTIONS_MAX_PER_HOST,\n type AglynOrganization,\n checkEntitlement,\n createResourceUid,\n hostRoleCanWrite,\n planLabelGrantingFeature,\n type PluginApiHandler,\n type PluginApiRequest,\n siteInteractionDocument,\n} from '@aglyn/aglyn/server'\nimport { interactionRecipeStamp } from '@aglyn/aglyn/plugin-manager/interaction-recipes'\nimport { validateStoredInteraction } from '@aglyn/aglyn/plugin-manager/interaction-step-checks'\nimport {\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n logOrgActivity,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n CRM_API_ROUTES,\n type CrmRecipeInstallRequest,\n type CrmRecipeInstallResult,\n type CrmRecipeSiteStatus,\n} from '../constants/api-routes'\nimport { crmActionRecipe, type CrmActionRecipeId } from '../model/crm-recipes'\nimport { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\n\nexport const CRM_RECIPE_INSTALL_ROUTE = CRM_API_ROUTES.recipeInstall\nexport const CRM_RECIPE_STATUS_ROUTE = CRM_API_ROUTES.recipeStatus\n\ntype Refusal = { ok: false; status: number; error: string }\n\n/** A verified caller who may write a site's actions, and the site's org. */\ninterface SiteWriter {\n ok: true\n uid: string\n email: string | null\n staff: boolean\n orgId: string\n org: Partial<AglynOrganization>\n host: FirebaseFirestore.DocumentSnapshot\n}\n\nconst INSTALL_REFUSAL =\n 'Installing a recipe requires the data permission across the whole workspace'\nconst STATUS_REFUSAL =\n 'Reading which sites carry a recipe requires the data permission across the whole workspace'\n\nfunction typed(value: unknown, max: number): string {\n return String(value ?? '')\n .trim()\n .slice(0, max)\n}\n\n/**\n * The site variant's authority: the role on the host document that creates\n * an action through `/api/hosts/resources` today. Staff pass, as they pass\n * that route. Answers the host snapshot it read, so the caller reads it\n * once.\n */\nasync function authorizeSiteWriter(\n req: PluginApiRequest,\n hostId: string,\n): Promise<SiteWriter | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let decoded: { uid: string; email?: string; staff?: unknown }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the recipe site writer could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const staff = decoded.staff === true\n const host = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n const role = (host.get('memberRoles') ?? {})[decoded.uid]\n if (!staff && !hostRoleCanWrite(role)) {\n return { ok: false, status: 403, error: 'Editing requires the editor role' }\n }\n const resolved = await getOrgForHost(hostId)\n if (!resolved) return { ok: false, status: 404, error: 'Unknown site' }\n return {\n ok: true,\n uid: decoded.uid,\n email: decoded.email ?? null,\n staff,\n orgId: resolved.orgId,\n org: resolved.org,\n host,\n }\n}\n\n/**\n * The org variant's site check: the host document, when it belongs to the\n * organization the caller was admitted to. A site under another workspace\n * — or none — reads as unknown, so a probe learns nothing from the answer.\n */\nasync function siteOfOrg(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n orgId: string,\n): Promise<FirebaseFirestore.DocumentSnapshot | null> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n return host.exists && host.get('orgId') === orgId ? host : null\n}\n\n/** How a site reads in a feed line: its display name, its subdomain, its id. */\nfunction siteLabel(host: FirebaseFirestore.DocumentSnapshot): string {\n return (\n String(host.get('displayName') ?? '').trim() ||\n String(host.get('subdomain') ?? '').trim() ||\n host.id\n )\n}\n\n/**\n * The stamps a site's LIVE actions carry, read with a field mask: the\n * install's duplicate check and the status sweep ask the same question,\n * and neither needs a trigger or a step list to answer it. A soft-deleted\n * action (`deletedAt`) is a freed slot and counts for nothing.\n */\nfunction readSiteStamps(rows: FirebaseFirestore.QuerySnapshot): {\n installed: Map<CrmActionRecipeId, string>\n unstamped: number\n live: number\n} {\n const installed = new Map<CrmActionRecipeId, string>()\n let unstamped = 0\n let live = 0\n for (const row of rows.docs) {\n if (row.get('deletedAt') != null) continue\n live += 1\n const stamp = interactionRecipeStamp(row.data())\n if (stamp === undefined) unstamped += 1\n else if (stamp && !installed.has(stamp as CrmActionRecipeId)) {\n installed.set(stamp as CrmActionRecipeId, row.id)\n }\n }\n return { installed, unstamped, live }\n}\n\nconst stampsQuery = (host: FirebaseFirestore.DocumentReference) =>\n host.collection('actions').select('recipe', 'deletedAt')\n\n/**\n * `POST /api/crm/recipe-install`\n *\n * The body is a CrmRecipeInstallRequest: the site, the recipe, the form a\n * recipe that needs one is keyed on, and the org at the organization level.\n * Answers 201 with a CrmRecipeInstallResult once the action is written, and\n * 409 when a live action on the site already carries the stamp — naming it,\n * so the caller can say \"already installed\" rather than install it twice.\n *\n * The write is one transaction: the stamps are read, the duplicate and the\n * per-site cap are judged, and the document is created — all inside it, so\n * two installs racing for the same site cannot both land.\n */\nexport const crmRecipeInstallHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const body: Partial<CrmRecipeInstallRequest> =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const scope = readCrmRouteScope(body as Record<string, unknown>)\n const hostId = scope?.hostId ?? ''\n if (!scope || !hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const recipe = crmActionRecipe(typed(body.recipeId, 64))\n if (!recipe) {\n res.status(400).json({ error: 'Pick a recipe' })\n return\n }\n const formId = typed(body.formId, 200)\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n let writer: SiteWriter\n if (scope.level === 'org') {\n const caller = await authorizeOrgCaller(req, scope.orgId, {\n needs: 'data.manage',\n refusal: INSTALL_REFUSAL,\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n const host = await siteOfOrg(firestore, hostId, caller.orgId)\n if (!host) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n writer = {\n ok: true,\n uid: caller.uid,\n email: caller.email,\n staff: caller.staff,\n orgId: caller.orgId,\n org: caller.org,\n host,\n }\n } else {\n const caller = await authorizeSiteWriter(req, hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n writer = caller\n }\n\n // A recipe is a CRM automation first (AGL-2787): the suite is asked\n // before the actions builder, so a plan without either is told about\n // the one the recipe belongs to.\n const suite = crmSuiteRefusal(writer.org, 'A CRM recipe')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n // The gate the site's own Recipes menu applies, judged here from the\n // org document rather than trusted from the console: a recipe is an\n // action, and the plan that carries one carries the other.\n if (!checkEntitlement(writer.org, 'actions')) {\n res.status(403).json({\n error:\n `The actions builder requires the ${planLabelGrantingFeature('actions') ?? 'Pro'} ` +\n 'plan — see Billing to upgrade',\n })\n return\n }\n\n const hostRef = writer.host.ref\n let form: { id: string; name: string; facts: { routesLeads: boolean } } | undefined\n if (recipe.picks?.kind === 'form') {\n if (!formId) {\n res.status(400).json({ error: 'Pick one of the site’s forms' })\n return\n }\n const snapshot = await hostRef.collection('forms').doc(formId).get()\n if (!snapshot.exists) {\n res.status(404).json({ error: 'Unknown form' })\n return\n }\n // An archived form collects nothing, so a recipe keyed on it would\n // never fire; the name falls back to the id the way every form list's does.\n if (snapshot.get('archivedAt') != null) {\n res.status(400).json({ error: 'That form is archived and collects nothing' })\n return\n }\n form = {\n id: snapshot.id,\n name: String(snapshot.get('displayName') ?? '').trim() || snapshot.id,\n // The fact the Forms plugin's list source shares (AGL-3458): a\n // lead-routed form makes leads, so its recipe listens for one.\n facts: { routesLeads: snapshot.get('routing')?.lead === true },\n }\n }\n\n const action = recipe.build(form ? { picked: form } : undefined)\n // The automation editor's own checks of every step, registered from its\n // declarations: a recipe installs only what that editor would save.\n const problem = validateStoredInteraction(action)\n if (problem) {\n res.status(400).json({ error: problem })\n return\n }\n\n const actionId = createResourceUid()\n const outcome = await firestore.runTransaction(async (tx) => {\n const stamps = readSiteStamps(await tx.get(stampsQuery(hostRef)))\n const existing = stamps.installed.get(recipe.id)\n if (existing) {\n return {\n status: 409,\n error: 'Already installed on this site',\n actionId: existing,\n }\n }\n if (stamps.live >= ACTIONS_MAX_PER_HOST) {\n return {\n status: 403,\n error: `interactions and actions are capped at ${ACTIONS_MAX_PER_HOST} per site`,\n }\n }\n tx.create(hostRef.collection('actions').doc(actionId), {\n ...siteInteractionDocument(action),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: writer.uid,\n })\n return null\n })\n if (outcome) {\n res.status(outcome.status).json({\n error: outcome.error,\n ...(outcome.actionId ? { actionId: outcome.actionId } : {}),\n })\n return\n }\n\n const actor = { uid: writer.uid, email: writer.email }\n await logHostActivity(hostId, actor, 'Installed recipe', {\n type: 'content',\n id: actionId,\n name: action.name,\n })\n // The org hub's own feed line, for the act it performed (AGL-2634).\n if (scope.level === 'org') {\n await logOrgActivity(\n writer.orgId,\n actor,\n `Installed the “${recipe.title}” recipe on ${siteLabel(writer.host)}`,\n { type: 'host', id: hostId, name: siteLabel(writer.host) },\n )\n }\n const answer: CrmRecipeInstallResult = {\n ok: true,\n actionId,\n name: action.name,\n recipeId: recipe.id,\n }\n res.status(201).json(answer)\n } catch (error) {\n console.error('[crm] recipe install failed', hostId, error)\n res.status(500).json({ error: 'The recipe could not be installed' })\n }\n}\n\n/**\n * `POST /api/crm/recipe-status`\n *\n * The body names the organization (`orgId`) for every one of its sites, or\n * one site (`hostId`) for that site alone. Answers `ok: true` and `sites`,\n * one CrmRecipeSiteStatus per site swept.\n */\nexport const crmRecipeStatusHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const body: Record<string, unknown> =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const scope = readCrmRouteScope(body)\n if (!scope) {\n res.status(400).json({ error: 'Missing orgId or hostId' })\n return\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n let orgId: string | null = null\n let org: unknown\n if (scope.level === 'org') {\n const caller = await authorizeOrgCaller(req, scope.orgId, {\n needs: 'data.manage',\n refusal: STATUS_REFUSAL,\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n orgId = caller.orgId\n org = caller.org\n } else {\n const caller = await authorizeSiteWriter(req, scope.hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n org = caller.org\n }\n // The plan after the caller, before any site is read (AGL-2851).\n const suite = crmSuiteRefusal(org, 'Reading which sites carry a CRM recipe')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const hostIds = orgId ? await orgHostIds(firestore, orgId) : [scope.hostId]\n const sites = await Promise.all(\n hostIds.map(async (hostId): Promise<CrmRecipeSiteStatus> => {\n const stamps = readSiteStamps(\n await stampsQuery(firestore.collection('hosts').doc(hostId)).get(),\n )\n return {\n hostId,\n installed: [...stamps.installed.keys()],\n unstamped: stamps.unstamped,\n }\n }),\n )\n res.status(200).json({ ok: true, sites })\n } catch (error) {\n console.error('[crm] recipe status failed', error)\n res.status(500).json({ error: 'The recipe status could not be read' })\n }\n}\n"],"names":["ACTIONS_MAX_PER_HOST","checkEntitlement","createResourceUid","hostRoleCanWrite","planLabelGrantingFeature","siteInteractionDocument","interactionRecipeStamp","validateStoredInteraction","firebaseAdmin","getOrgForHost","logHostActivity","logOrgActivity","isRefusedIdToken","FieldValue","CRM_API_ROUTES","crmActionRecipe","authorizeOrgCaller","orgHostIds","readCrmRouteScope","crmSuiteRefusal","CRM_RECIPE_INSTALL_ROUTE","recipeInstall","CRM_RECIPE_STATUS_ROUTE","recipeStatus","INSTALL_REFUSAL","STATUS_REFUSAL","typed","value","max","String","trim","slice","authorizeSiteWriter","req","hostId","host","decoded","authorization","headers","idToken","startsWith","length","undefined","ok","status","error","app","auth","verifyIdToken","console","staff","firestore","collection","doc","get","exists","role","uid","resolved","email","orgId","org","siteOfOrg","siteLabel","id","readSiteStamps","rows","installed","Map","unstamped","live","row","docs","stamp","data","has","set","stampsQuery","select","crmRecipeInstallHandler","res","method","setHeader","json","body","JSON","parse","scope","recipe","recipeId","formId","writer","level","caller","needs","refusal","suite","hostRef","ref","form","picks","kind","snapshot","name","facts","routesLeads","lead","action","build","picked","problem","actionId","outcome","runTransaction","tx","stamps","existing","create","createdAt","serverTimestamp","updatedAt","createdBy","actor","type","title","answer","crmRecipeStatusHandler","hostIds","sites","Promise","all","map","keys"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GAED,SACEA,oBAAoB,EAEpBC,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,EAChBC,wBAAwB,EAGxBC,uBAAuB,QAClB,sBAAqB;AAC5B,SAASC,sBAAsB,QAAQ,kDAAiD;AACxF,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SACEC,aAAa,EACbC,aAAa,EACbC,eAAe,EACfC,cAAc,QACT,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,cAAc,QAIT,6BAAyB;AAChC,SAASC,eAAe,QAAgC,0BAAsB;AAC9E,SAASC,kBAAkB,EAAEC,UAAU,EAAEC,iBAAiB,QAAQ,kBAAc;A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crm/src/lib/server/recipe-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 * THE RECIPES, INSTALLED FROM THE ORGANIZATION (AGL-2639).\n *\n * On a site, a recipe opens the Actions editor prefilled and writes nothing\n * until the person saves — the editor is the writer, and the site's own\n * role is the authority. The organization-level CRM hub has no editor: it\n * mounts over every site with no site of its own, and an org running five\n * sites installed \"Welcome a new lead\" five times by hand. These two routes\n * are the org hub's door to a site's automations.\n *\n * `crm/recipe-install` writes the action a recipe builds into ONE site's\n * `hosts/{hostId}/actions`, as the site editor would have saved it — the\n * same builder, the same validator, the same stored shape — and refuses a\n * second install of the same recipe on the same site by the stamp the\n * builder puts on it. A server route rather than a client write for three\n * reasons the browser cannot supply: the document is created by a server\n * on every plan (the rules close `actions` to client creates, and the\n * per-site cap is counted here); the stamp is the server's word, not the\n * caller's; and the site is checked to be one the caller may manage —\n * at the org level, a site OF THE ORG the caller holds org-wide reach in,\n * so a host id typed into the body cannot reach a site under another\n * workspace.\n *\n * `crm/recipe-status` reads the stamps back for every site of the org, so\n * the card can say which sites carry which recipe. An action with no stamp\n * at all — saved before the stamp existed — is counted, not ignored: it\n * may well be a recipe, and the reader is told the site \"may already have\n * it\" rather than shown a clean slate.\n *\n * Both routes serve the site variant too (`hostId` alone, authorized by the\n * site key that creates actions today), so a site-level caller gets the\n * same answers; the org variant (`orgId` in the body) is the one the org\n * hub uses.\n */\n\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n ACTIONS_MAX_PER_HOST,\n type AglynOrganization,\n checkEntitlement,\n createResourceUid,\n planLabelGrantingFeature,\n type PluginApiHandler,\n type PluginApiRequest,\n siteInteractionDocument,\n} from '@aglyn/aglyn/server'\nimport { interactionRecipeStamp } from '@aglyn/aglyn/plugin-manager/interaction-recipes'\nimport { validateStoredInteraction } from '@aglyn/aglyn/plugin-manager/interaction-step-checks'\nimport {\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n logOrgActivity,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n CRM_API_ROUTES,\n type CrmRecipeInstallRequest,\n type CrmRecipeInstallResult,\n type CrmRecipeSiteStatus,\n} from '../constants/api-routes'\nimport { crmActionRecipe, type CrmActionRecipeId } from '../model/crm-recipes'\nimport { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\n\nexport const CRM_RECIPE_INSTALL_ROUTE = CRM_API_ROUTES.recipeInstall\nexport const CRM_RECIPE_STATUS_ROUTE = CRM_API_ROUTES.recipeStatus\n\ntype Refusal = { ok: false; status: number; error: string }\n\n/** A verified caller who may write a site's actions, and the site's org. */\ninterface SiteWriter {\n ok: true\n uid: string\n email: string | null\n staff: boolean\n orgId: string\n org: Partial<AglynOrganization>\n host: FirebaseFirestore.DocumentSnapshot\n}\n\nconst INSTALL_REFUSAL =\n 'Installing a recipe requires the data permission across the whole workspace'\nconst STATUS_REFUSAL =\n 'Reading which sites carry a recipe requires the data permission across the whole workspace'\n\nfunction typed(value: unknown, max: number): string {\n return String(value ?? '')\n .trim()\n .slice(0, max)\n}\n\n/**\n * The site variant's authority: \"Edit site content\" (`site.edit`, AGL-4047) on\n * the host document, whose preset is the Admin, Editor and Author this asked\n * for and which creates an action through `/api/hosts/resources` today. Staff\n * pass, as they pass that route. Answers the host snapshot it read, so the\n * caller reads it once.\n */\nasync function authorizeSiteWriter(\n req: PluginApiRequest,\n hostId: string,\n): Promise<SiteWriter | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let decoded: { uid: string; email?: string; staff?: unknown }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the recipe site writer could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const staff = decoded.staff === true\n const host = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (!staff && !holdsSiteKey(host, decoded.uid, 'site.edit')) {\n return { ok: false, status: 403, error: siteKeyRefusal('site.edit') }\n }\n const resolved = await getOrgForHost(hostId)\n if (!resolved) return { ok: false, status: 404, error: 'Unknown site' }\n return {\n ok: true,\n uid: decoded.uid,\n email: decoded.email ?? null,\n staff,\n orgId: resolved.orgId,\n org: resolved.org,\n host,\n }\n}\n\n/**\n * The org variant's site check: the host document, when it belongs to the\n * organization the caller was admitted to. A site under another workspace\n * — or none — reads as unknown, so a probe learns nothing from the answer.\n */\nasync function siteOfOrg(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n orgId: string,\n): Promise<FirebaseFirestore.DocumentSnapshot | null> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n return host.exists && host.get('orgId') === orgId ? host : null\n}\n\n/** How a site reads in a feed line: its display name, its subdomain, its id. */\nfunction siteLabel(host: FirebaseFirestore.DocumentSnapshot): string {\n return (\n String(host.get('displayName') ?? '').trim() ||\n String(host.get('subdomain') ?? '').trim() ||\n host.id\n )\n}\n\n/**\n * The stamps a site's LIVE actions carry, read with a field mask: the\n * install's duplicate check and the status sweep ask the same question,\n * and neither needs a trigger or a step list to answer it. A soft-deleted\n * action (`deletedAt`) is a freed slot and counts for nothing.\n */\nfunction readSiteStamps(rows: FirebaseFirestore.QuerySnapshot): {\n installed: Map<CrmActionRecipeId, string>\n unstamped: number\n live: number\n} {\n const installed = new Map<CrmActionRecipeId, string>()\n let unstamped = 0\n let live = 0\n for (const row of rows.docs) {\n if (row.get('deletedAt') != null) continue\n live += 1\n const stamp = interactionRecipeStamp(row.data())\n if (stamp === undefined) unstamped += 1\n else if (stamp && !installed.has(stamp as CrmActionRecipeId)) {\n installed.set(stamp as CrmActionRecipeId, row.id)\n }\n }\n return { installed, unstamped, live }\n}\n\nconst stampsQuery = (host: FirebaseFirestore.DocumentReference) =>\n host.collection('actions').select('recipe', 'deletedAt')\n\n/**\n * `POST /api/crm/recipe-install`\n *\n * The body is a CrmRecipeInstallRequest: the site, the recipe, the form a\n * recipe that needs one is keyed on, and the org at the organization level.\n * Answers 201 with a CrmRecipeInstallResult once the action is written, and\n * 409 when a live action on the site already carries the stamp — naming it,\n * so the caller can say \"already installed\" rather than install it twice.\n *\n * The write is one transaction: the stamps are read, the duplicate and the\n * per-site cap are judged, and the document is created — all inside it, so\n * two installs racing for the same site cannot both land.\n */\nexport const crmRecipeInstallHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const body: Partial<CrmRecipeInstallRequest> =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const scope = readCrmRouteScope(body as Record<string, unknown>)\n const hostId = scope?.hostId ?? ''\n if (!scope || !hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const recipe = crmActionRecipe(typed(body.recipeId, 64))\n if (!recipe) {\n res.status(400).json({ error: 'Pick a recipe' })\n return\n }\n const formId = typed(body.formId, 200)\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n let writer: SiteWriter\n if (scope.level === 'org') {\n const caller = await authorizeOrgCaller(req, scope.orgId, {\n needs: 'data.manage',\n refusal: INSTALL_REFUSAL,\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n const host = await siteOfOrg(firestore, hostId, caller.orgId)\n if (!host) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n writer = {\n ok: true,\n uid: caller.uid,\n email: caller.email,\n staff: caller.staff,\n orgId: caller.orgId,\n org: caller.org,\n host,\n }\n } else {\n const caller = await authorizeSiteWriter(req, hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n writer = caller\n }\n\n // A recipe is a CRM automation first (AGL-2787): the suite is asked\n // before the actions builder, so a plan without either is told about\n // the one the recipe belongs to.\n const suite = crmSuiteRefusal(writer.org, 'A CRM recipe')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n // The gate the site's own Recipes menu applies, judged here from the\n // org document rather than trusted from the console: a recipe is an\n // action, and the plan that carries one carries the other.\n if (!checkEntitlement(writer.org, 'actions')) {\n res.status(403).json({\n error:\n `The actions builder requires the ${planLabelGrantingFeature('actions') ?? 'Pro'} ` +\n 'plan — see Billing to upgrade',\n })\n return\n }\n\n const hostRef = writer.host.ref\n let form: { id: string; name: string; facts: { routesLeads: boolean } } | undefined\n if (recipe.picks?.kind === 'form') {\n if (!formId) {\n res.status(400).json({ error: 'Pick one of the site’s forms' })\n return\n }\n const snapshot = await hostRef.collection('forms').doc(formId).get()\n if (!snapshot.exists) {\n res.status(404).json({ error: 'Unknown form' })\n return\n }\n // An archived form collects nothing, so a recipe keyed on it would\n // never fire; the name falls back to the id the way every form list's does.\n if (snapshot.get('archivedAt') != null) {\n res.status(400).json({ error: 'That form is archived and collects nothing' })\n return\n }\n form = {\n id: snapshot.id,\n name: String(snapshot.get('displayName') ?? '').trim() || snapshot.id,\n // The fact the Forms plugin's list source shares (AGL-3458): a\n // lead-routed form makes leads, so its recipe listens for one.\n facts: { routesLeads: snapshot.get('routing')?.lead === true },\n }\n }\n\n const action = recipe.build(form ? { picked: form } : undefined)\n // The automation editor's own checks of every step, registered from its\n // declarations: a recipe installs only what that editor would save.\n const problem = validateStoredInteraction(action)\n if (problem) {\n res.status(400).json({ error: problem })\n return\n }\n\n const actionId = createResourceUid()\n const outcome = await firestore.runTransaction(async (tx) => {\n const stamps = readSiteStamps(await tx.get(stampsQuery(hostRef)))\n const existing = stamps.installed.get(recipe.id)\n if (existing) {\n return {\n status: 409,\n error: 'Already installed on this site',\n actionId: existing,\n }\n }\n if (stamps.live >= ACTIONS_MAX_PER_HOST) {\n return {\n status: 403,\n error: `interactions and actions are capped at ${ACTIONS_MAX_PER_HOST} per site`,\n }\n }\n tx.create(hostRef.collection('actions').doc(actionId), {\n ...siteInteractionDocument(action),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: writer.uid,\n })\n return null\n })\n if (outcome) {\n res.status(outcome.status).json({\n error: outcome.error,\n ...(outcome.actionId ? { actionId: outcome.actionId } : {}),\n })\n return\n }\n\n const actor = { uid: writer.uid, email: writer.email }\n await logHostActivity(hostId, actor, 'Installed recipe', {\n type: 'content',\n id: actionId,\n name: action.name,\n })\n // The org hub's own feed line, for the act it performed (AGL-2634).\n if (scope.level === 'org') {\n await logOrgActivity(\n writer.orgId,\n actor,\n `Installed the “${recipe.title}” recipe on ${siteLabel(writer.host)}`,\n { type: 'host', id: hostId, name: siteLabel(writer.host) },\n )\n }\n const answer: CrmRecipeInstallResult = {\n ok: true,\n actionId,\n name: action.name,\n recipeId: recipe.id,\n }\n res.status(201).json(answer)\n } catch (error) {\n console.error('[crm] recipe install failed', hostId, error)\n res.status(500).json({ error: 'The recipe could not be installed' })\n }\n}\n\n/**\n * `POST /api/crm/recipe-status`\n *\n * The body names the organization (`orgId`) for every one of its sites, or\n * one site (`hostId`) for that site alone. Answers `ok: true` and `sites`,\n * one CrmRecipeSiteStatus per site swept.\n */\nexport const crmRecipeStatusHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const body: Record<string, unknown> =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const scope = readCrmRouteScope(body)\n if (!scope) {\n res.status(400).json({ error: 'Missing orgId or hostId' })\n return\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n let orgId: string | null = null\n let org: unknown\n if (scope.level === 'org') {\n const caller = await authorizeOrgCaller(req, scope.orgId, {\n needs: 'data.manage',\n refusal: STATUS_REFUSAL,\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n orgId = caller.orgId\n org = caller.org\n } else {\n const caller = await authorizeSiteWriter(req, scope.hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n org = caller.org\n }\n // The plan after the caller, before any site is read (AGL-2851).\n const suite = crmSuiteRefusal(org, 'Reading which sites carry a CRM recipe')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const hostIds = orgId ? await orgHostIds(firestore, orgId) : [scope.hostId]\n const sites = await Promise.all(\n hostIds.map(async (hostId): Promise<CrmRecipeSiteStatus> => {\n const stamps = readSiteStamps(\n await stampsQuery(firestore.collection('hosts').doc(hostId)).get(),\n )\n return {\n hostId,\n installed: [...stamps.installed.keys()],\n unstamped: stamps.unstamped,\n }\n }),\n )\n res.status(200).json({ ok: true, sites })\n } catch (error) {\n console.error('[crm] recipe status failed', error)\n res.status(500).json({ error: 'The recipe status could not be read' })\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","ACTIONS_MAX_PER_HOST","checkEntitlement","createResourceUid","planLabelGrantingFeature","siteInteractionDocument","interactionRecipeStamp","validateStoredInteraction","firebaseAdmin","getOrgForHost","logHostActivity","logOrgActivity","isRefusedIdToken","FieldValue","CRM_API_ROUTES","crmActionRecipe","authorizeOrgCaller","orgHostIds","readCrmRouteScope","crmSuiteRefusal","CRM_RECIPE_INSTALL_ROUTE","recipeInstall","CRM_RECIPE_STATUS_ROUTE","recipeStatus","INSTALL_REFUSAL","STATUS_REFUSAL","typed","value","max","String","trim","slice","authorizeSiteWriter","req","hostId","decoded","authorization","headers","idToken","startsWith","length","undefined","ok","status","error","app","auth","verifyIdToken","console","staff","host","firestore","collection","doc","get","exists","uid","resolved","email","orgId","org","siteOfOrg","siteLabel","id","readSiteStamps","rows","installed","Map","unstamped","live","row","docs","stamp","data","has","set","stampsQuery","select","crmRecipeInstallHandler","res","method","setHeader","json","body","JSON","parse","scope","recipe","recipeId","formId","writer","level","caller","needs","refusal","suite","hostRef","ref","form","picks","kind","snapshot","name","facts","routesLeads","lead","action","build","picked","problem","actionId","outcome","runTransaction","tx","stamps","existing","create","createdAt","serverTimestamp","updatedAt","createdBy","actor","type","title","answer","crmRecipeStatusHandler","hostIds","sites","Promise","all","map","keys"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GAED,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SACEC,oBAAoB,EAEpBC,gBAAgB,EAChBC,iBAAiB,EACjBC,wBAAwB,EAGxBC,uBAAuB,QAClB,sBAAqB;AAC5B,SAASC,sBAAsB,QAAQ,kDAAiD;AACxF,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SACEC,aAAa,EACbC,aAAa,EACbC,eAAe,EACfC,cAAc,QACT,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,cAAc,QAIT,6BAAyB;AAChC,SAASC,eAAe,QAAgC,0BAAsB;AAC9E,SAASC,kBAAkB,EAAEC,UAAU,EAAEC,iBAAiB,QAAQ,kBAAc;AAChF,SAASC,eAAe,QAAQ,kBAAc;AAE9C,OAAO,MAAMC,2BAA2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hC,GAAG;QAClB,OAAO;YACL,MAAMgC,SAAS,MAAM5D,oBAAoBC,KAAKqD,MAAMpD,MAAM;YAC1D,IAAI0D,OAAOlD,EAAE,KAAK,OAAO;gBACvBqC,IAAIpC,MAAM,CAACiD,OAAOjD,MAAM,EAAEuC,IAAI,CAAC;oBAAEtC,OAAOgD,OAAOhD,KAAK;gBAAC;gBACrD;YACF;YACAgB,MAAMgC,OAAOhC,GAAG;QAClB;QACA,iEAAiE;QACjE,MAAMmC,QAAQ5E,gBAAgByC,KAAK;QACnC,IAAImC,OAAO;YACThB,IAAIpC,MAAM,CAACoD,MAAMpD,MAAM,EAAEuC,IAAI,CAACa,MAAMZ,IAAI;YACxC;QACF;QACA,MAAM2C,UAAUnE,QAAQ,MAAM1C,WAAWkC,WAAWQ,SAAS;YAAC2B,MAAMpD,MAAM;SAAC;QAC3E,MAAM6F,QAAQ,MAAMC,QAAQC,GAAG,CAC7BH,QAAQI,GAAG,CAAC,OAAOhG;YACjB,MAAMgF,SAASlD,eACb,MAAMY,YAAYzB,UAAUC,UAAU,CAAC,SAASC,GAAG,CAACnB,SAASoB,GAAG;YAElE,OAAO;gBACLpB;gBACAgC,WAAW;uBAAIgD,OAAOhD,SAAS,CAACiE,IAAI;iBAAG;gBACvC/D,WAAW8C,OAAO9C,SAAS;YAC7B;QACF;QAEFW,IAAIpC,MAAM,CAAC,KAAKuC,IAAI,CAAC;YAAExC,IAAI;YAAMqF;QAAM;IACzC,EAAE,OAAOnF,OAAO;QACdI,QAAQJ,KAAK,CAAC,8BAA8BA;QAC5CmC,IAAIpC,MAAM,CAAC,KAAKuC,IAAI,CAAC;YAAEtC,OAAO;QAAsC;IACtE;AACF,EAAC"}
@@ -0,0 +1,22 @@
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
+ /**
18
+ * The CRM's scoped list fields are derived from `visibleTo` (AGL-3321), so a
19
+ * sweep that changes the sites on a record restamps them in the same write,
20
+ * and a site's search finds the record the moment it can see it.
21
+ */
22
+ export declare function crmScopeSharingPatch(collection: string, next: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,25 @@
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 { crmListFieldsPatch } from "@aglyn/aglyn/app-utils/crm";
17
+ /**
18
+ * The CRM's scoped list fields are derived from `visibleTo` (AGL-3321), so a
19
+ * sweep that changes the sites on a record restamps them in the same write,
20
+ * and a site's search finds the record the moment it can see it.
21
+ */ export function crmScopeSharingPatch(collection, next) {
22
+ return crmListFieldsPatch(collection, next);
23
+ }
24
+
25
+ //# sourceMappingURL=scope-sharing-patch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/scope-sharing-patch.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 { crmListFieldsPatch, type CrmListCollection } from '@aglyn/aglyn/app-utils/crm'\n\n/**\n * The CRM's scoped list fields are derived from `visibleTo` (AGL-3321), so a\n * sweep that changes the sites on a record restamps them in the same write,\n * and a site's search finds the record the moment it can see it.\n */\nexport function crmScopeSharingPatch(\n collection: string,\n next: Record<string, unknown>,\n): Record<string, unknown> {\n return crmListFieldsPatch(collection as CrmListCollection, next)\n}\n"],"names":["crmListFieldsPatch","crmScopeSharingPatch","collection","next"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAgC,6BAA4B;AAEvF;;;;CAIC,GACD,OAAO,SAASC,qBACdC,UAAkB,EAClBC,IAA6B;IAE7B,OAAOH,mBAAmBE,YAAiCC;AAC7D"}
@@ -37,9 +37,10 @@ import { type CrmRouteScope } from './org-caller';
37
37
  *
38
38
  * Both authenticate the way the other console plugin routes do — the ID
39
39
  * token in the `Authorization` header — and then ask the same two questions
40
- * the rules ask of a `crmTasks` write: is this member allowed to write org
41
- * data (`owner`/`admin`/`editor`, and `data.manage` resolved through their
42
- * custom role), and can they reach THIS document's scope.
40
+ * the rules ask of a `crmTasks` write: does this member hold "Manage data"
41
+ * (`data.manage`, resolved through their custom role and own permissions; the
42
+ * owner, admins and editors by default), and can they reach THIS document's
43
+ * scope.
43
44
  *
44
45
  * ## The organization variant (AGL-2637)
45
46
  *
@@ -95,8 +96,8 @@ export interface CrmWriterOptions {
95
96
  /**
96
97
  * Who is asking, and whether they may write this CRM at all.
97
98
  *
98
- * Under a site: the org resolved from the site and the rules' own role and
99
- * permission questions. At the organization level: the org the body names,
99
+ * Under a site: the org resolved from the site and the rules' own question,
100
+ * "Manage data". At the organization level: the org the body names,
100
101
  * for an org-wide member with the permission. The scope question — may they
101
102
  * reach THIS task — is asked by the caller against the document, because on
102
103
  * a create the document does not exist yet and its scope is what the route
@@ -27,6 +27,7 @@ import { authorizeOrgCaller, readCrmRouteScope } from "./org-caller.js";
27
27
  import { crmSuiteRefusal } from "./suite-gate.js";
28
28
  import { crmTaskReminderAfterEdit, crmTaskReminderPending, crmTaskReminderWhen } from "../model/crm-task-reminders.js";
29
29
  import { crmNextActivityLinksOf, recomputeCrmNextTaskAt } from "./crm-next-activity.js";
30
+ /** What a site's CRM writer is refused with: names the permission, never a role. */ const MANAGE_DATA_REFUSAL = 'Your role does not include "Manage data" — ask an organization admin';
30
31
  /** What the suite gate names when a task route refuses a plan without it. */ const TASKS_ACT = "Working a record's tasks";
31
32
  export const refuse = (status, error)=>({
32
33
  ok: false,
@@ -39,8 +40,8 @@ const ORG_REFUSAL = 'Editing tasks at the organization level requires the "Manag
39
40
  /**
40
41
  * Who is asking, and whether they may write this CRM at all.
41
42
  *
42
- * Under a site: the org resolved from the site and the rules' own role and
43
- * permission questions. At the organization level: the org the body names,
43
+ * Under a site: the org resolved from the site and the rules' own question,
44
+ * "Manage data". At the organization level: the org the body names,
44
45
  * for an org-wide member with the permission. The scope question — may they
45
46
  * reach THIS task — is asked by the caller against the document, because on
46
47
  * a create the document does not exist yet and its scope is what the route
@@ -87,20 +88,17 @@ const ORG_REFUSAL = 'Editing tasks at the organization level requires the "Manag
87
88
  const membership = await resolveOrgMembership(decoded.uid, orgId).catch(()=>null);
88
89
  const member = (_ref = membership == null ? void 0 : membership.member) != null ? _ref : null;
89
90
  if (!staff) {
90
- var _ref1;
91
- const role = String((_ref1 = member == null ? void 0 : member.role) != null ? _ref1 : '');
92
91
  /*
93
- * The rules' `canWriteOrgData()` restated: the role list is what an
94
- * unstamped permission map falls through to, and the permission is the
95
- * only half a custom role's revocation can reach. A route that checked
96
- * one and not the other would open a door the rules keep shut.
97
- */ const writerRole = role === 'owner' || role === 'admin' || role === 'editor';
98
- const suspended = (member == null ? void 0 : member.orgSuspended) === true;
99
- if (!member || !writerRole || suspended) {
100
- return refuse(403, 'Your organization role does not allow editing the CRM.');
92
+ * The rules' `canWriteOrgData()` restated (AGL-4047): a member who is not
93
+ * suspended and holds the key, whose default is the owner, admins and
94
+ * editors. A route that asked anything else would open a door the rules
95
+ * keep shut, or shut one they open.
96
+ */ const suspended = (member == null ? void 0 : member.orgSuspended) === true;
97
+ if (!member || suspended) {
98
+ return refuse(403, MANAGE_DATA_REFUSAL);
101
99
  }
102
100
  if (!await memberHasOrgPermission(orgId, member, 'data.manage')) {
103
- return refuse(403, 'Your organization role does not allow editing the CRM.');
101
+ return refuse(403, MANAGE_DATA_REFUSAL);
104
102
  }
105
103
  }
106
104
  const suite = suiteAct ? crmSuiteRefusal(org, suiteAct) : null;