@aglyn/tenant-data-admin 1.0.0-beta.285 → 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.
@@ -0,0 +1,165 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ /**
18
+ * Per-member permission overrides (AGL-4047): the writes behind the member
19
+ * Permissions section and the per-site collaborator toggles.
20
+ *
21
+ * Two places a member's own decisions live, and each write may set a key
22
+ * (`true` / `false`) or CLEAR it (`null`, back to inherit):
23
+ *
24
+ * - `permissions[key]` on `orgs/{orgId}/members/{uid}` for an org catalog
25
+ * key, layered over the org role and the custom role by
26
+ * `resolveOrgPermissions`;
27
+ * - `hostPermissions[hostId][key]` for a key a site collaborator holds per
28
+ * site, layered over their host role by `resolveCollaboratorHostPermissions`,
29
+ * and for a key that follows the site role, for a workspace-wide member
30
+ * that site narrows (AGL-4047, `narrowPermissionsToSite`);
31
+ * - `siteNarrowing[key]` on the member for a key a site can narrow: whether
32
+ * it follows a narrower site role for them (`true`) or they keep it
33
+ * (`false`), over their custom role's choice and the built-in default.
34
+ *
35
+ * Catalog keys are dotted (`billing.view`), so every write addresses the
36
+ * field through a `FieldPath` — a dotted string would be read as nesting.
37
+ * Both writes re-project before they answer: `resolvedPermissions` on the
38
+ * member and `memberPermissions` on the hosts are what the rules read, and
39
+ * a narrowing that answers 200 before it is stamped is a window in which
40
+ * the rules still grant.
41
+ */ import { hostPermissionKeys, narrowedPermissionKeysOf, narrowPermissionsToSite, ORG_PERMISSION_KEYS, resolveCollaboratorHostPermissions, siteNarrowedPermissionKeys, siteNarrowingChoices } from "@aglyn/aglyn/server";
42
+ import { FieldPath, FieldValue } from "firebase-admin/firestore";
43
+ import firebaseAdmin from "./firebase-admin.js";
44
+ import { resolveMemberCustomRole, resolveMemberOrgPermissions, resolveMemberSiteNarrowing, syncOrgAuthProjections } from "./organizations.js";
45
+ const firestore = ()=>firebaseAdmin.app().firestore();
46
+ function memberRef(orgId, uid) {
47
+ return firestore().collection('orgs').doc(orgId).collection('members').doc(uid);
48
+ }
49
+ /**
50
+ * Writes a map of keys under `parents` on one document: each set, or
51
+ * deleted on null, in one update, addressed by `FieldPath` so a dotted key
52
+ * stays one field.
53
+ */ async function updateFields(ref, parents, changes, alsoUnder) {
54
+ const fields = (under, map)=>Object.entries(map).map(([key, value])=>[
55
+ new FieldPath(...under, key),
56
+ value === null ? FieldValue.delete() : value
57
+ ]);
58
+ const [head, ...tail] = [
59
+ ...fields(parents, changes),
60
+ ...alsoUnder ? fields(alsoUnder.parents, alsoUnder.changes) : []
61
+ ];
62
+ if (!head) return;
63
+ await ref.update(head[0], head[1], ...tail.flat());
64
+ }
65
+ /**
66
+ * Sets or clears a member's org-level overrides, and their narrowing
67
+ * choices (`siteNarrowing`, AGL-4047), in one write. Keys outside the
68
+ * catalog, and narrowing for a key no site can narrow, are refused before
69
+ * anything is written (the route validates first; this is the floor). The
70
+ * member must exist. Every host is re-projected, because a narrowing choice
71
+ * moves the member's verdict on each site that narrows them.
72
+ */ export async function setMemberPermissionOverrides(options) {
73
+ const { orgId, uid, changes, narrowing = {} } = options;
74
+ const catalog = new Set(ORG_PERMISSION_KEYS);
75
+ for (const key of Object.keys(changes)){
76
+ if (!catalog.has(key)) throw new Error(`"${key}" is not a catalog permission`);
77
+ }
78
+ const narrowable = new Set(siteNarrowedPermissionKeys());
79
+ for (const key of Object.keys(narrowing)){
80
+ if (!narrowable.has(key)) throw new Error(`"${key}" is not a permission a site can narrow`);
81
+ }
82
+ const ref = memberRef(orgId, uid);
83
+ const snapshot = await ref.get();
84
+ if (!snapshot.exists) throw new Error('member not found');
85
+ const stored = _extends({
86
+ $id: uid
87
+ }, snapshot.data());
88
+ const before = await resolveMemberOrgPermissions(orgId, stored);
89
+ await updateFields(ref, [
90
+ 'permissions'
91
+ ], changes, {
92
+ parents: [
93
+ 'siteNarrowing'
94
+ ],
95
+ changes: narrowing
96
+ });
97
+ await syncOrgAuthProjections(orgId);
98
+ const member = _extends({
99
+ $id: uid
100
+ }, (await ref.get()).data());
101
+ return {
102
+ before,
103
+ after: await resolveMemberOrgPermissions(orgId, member),
104
+ member,
105
+ siteNarrowing: siteNarrowingChoices(member, await resolveMemberCustomRole(orgId, member))
106
+ };
107
+ }
108
+ /**
109
+ * Sets or clears a member's per-site toggles on one site. For a site
110
+ * collaborator, only the keys a plugin declared per-site
111
+ * (`hostPermissionKeys`) are stored. For a member who works across the
112
+ * workspace, only on a site that narrows them and only the keys that follow
113
+ * the site role for them (`narrowedPermissionKeysOf`, AGL-4047): the site's
114
+ * way to give back, or keep refused, what their narrower access there took.
115
+ * The member must reach the site.
116
+ */ export async function setHostPermissionOverrides(options) {
117
+ var _resolveCollaboratorHostPermissions;
118
+ const { orgId, uid, hostId, changes } = options;
119
+ const ref = memberRef(orgId, uid);
120
+ const snapshot = await ref.get();
121
+ if (!snapshot.exists) throw new Error('member not found');
122
+ const stored = _extends({
123
+ $id: uid
124
+ }, snapshot.data());
125
+ const narrowing = await resolveMemberSiteNarrowing(orgId, stored, hostId);
126
+ const narrowed = narrowing !== null;
127
+ const siteKeys = new Set(narrowed ? narrowedPermissionKeysOf(narrowing) : hostPermissionKeys());
128
+ for (const key of Object.keys(changes)){
129
+ if (!siteKeys.has(key)) throw new Error(`"${key}" is not a per-site permission`);
130
+ }
131
+ // A narrowed member's verdict on this site, every per-site key and every
132
+ // key a site can narrow, from the same resolver the rules projection uses.
133
+ const narrowedVerdicts = async (member)=>{
134
+ const granted = narrowPermissionsToSite(await resolveMemberOrgPermissions(orgId, member), await resolveMemberSiteNarrowing(orgId, member, hostId));
135
+ return Object.fromEntries([
136
+ ...hostPermissionKeys(),
137
+ ...siteNarrowedPermissionKeys()
138
+ ].map((key)=>[
139
+ key,
140
+ granted[key] === true
141
+ ]));
142
+ };
143
+ const before = narrowed ? await narrowedVerdicts(stored) : resolveCollaboratorHostPermissions(stored, hostId);
144
+ if (!before) throw new Error('member has no access to this site');
145
+ await updateFields(ref, [
146
+ 'hostPermissions',
147
+ hostId
148
+ ], changes);
149
+ await syncOrgAuthProjections(orgId, hostId);
150
+ const member = _extends({
151
+ $id: uid
152
+ }, (await ref.get()).data());
153
+ return {
154
+ before,
155
+ after: narrowed ? await narrowedVerdicts(member) : (_resolveCollaboratorHostPermissions = resolveCollaboratorHostPermissions(member, hostId)) != null ? _resolveCollaboratorHostPermissions : Object.fromEntries([
156
+ ...siteKeys
157
+ ].map((key)=>[
158
+ key,
159
+ false
160
+ ])),
161
+ member
162
+ };
163
+ }
164
+
165
+ //# sourceMappingURL=member-permission-overrides.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/member-permission-overrides.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 * Per-member permission overrides (AGL-4047): the writes behind the member\n * Permissions section and the per-site collaborator toggles.\n *\n * Two places a member's own decisions live, and each write may set a key\n * (`true` / `false`) or CLEAR it (`null`, back to inherit):\n *\n * - `permissions[key]` on `orgs/{orgId}/members/{uid}` for an org catalog\n * key, layered over the org role and the custom role by\n * `resolveOrgPermissions`;\n * - `hostPermissions[hostId][key]` for a key a site collaborator holds per\n * site, layered over their host role by `resolveCollaboratorHostPermissions`,\n * and for a key that follows the site role, for a workspace-wide member\n * that site narrows (AGL-4047, `narrowPermissionsToSite`);\n * - `siteNarrowing[key]` on the member for a key a site can narrow: whether\n * it follows a narrower site role for them (`true`) or they keep it\n * (`false`), over their custom role's choice and the built-in default.\n *\n * Catalog keys are dotted (`billing.view`), so every write addresses the\n * field through a `FieldPath` — a dotted string would be read as nesting.\n * Both writes re-project before they answer: `resolvedPermissions` on the\n * member and `memberPermissions` on the hosts are what the rules read, and\n * a narrowing that answers 200 before it is stamped is a window in which\n * the rules still grant.\n */\n\nimport {\n hostPermissionKeys,\n narrowedPermissionKeysOf,\n narrowPermissionsToSite,\n ORG_PERMISSION_KEYS,\n resolveCollaboratorHostPermissions,\n siteNarrowedPermissionKeys,\n siteNarrowingChoices,\n type AglynOrgMember,\n} from '@aglyn/aglyn/server'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport {\n resolveMemberCustomRole,\n resolveMemberOrgPermissions,\n resolveMemberSiteNarrowing,\n syncOrgAuthProjections,\n} from './organizations'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** A key to `true` / `false`, or to `null` to clear it. */\nexport type PermissionOverrideWrite = Record<string, boolean | null>\n\n/** A member's verdicts on either side of an override write. */\nexport interface PermissionOverridesResult {\n before: Record<string, boolean>\n after: Record<string, boolean>\n /** The member document as it stands after the write. */\n member: AglynOrgMember\n}\n\nfunction memberRef(orgId: string, uid: string) {\n return firestore().collection('orgs').doc(orgId).collection('members').doc(uid)\n}\n\n/**\n * Writes a map of keys under `parents` on one document: each set, or\n * deleted on null, in one update, addressed by `FieldPath` so a dotted key\n * stays one field.\n */\nasync function updateFields(\n ref: FirebaseFirestore.DocumentReference,\n parents: readonly string[],\n changes: PermissionOverrideWrite,\n alsoUnder?: { parents: readonly string[]; changes: PermissionOverrideWrite },\n): Promise<void> {\n const fields = (under: readonly string[], map: PermissionOverrideWrite) =>\n Object.entries(map).map(\n ([key, value]) => [new FieldPath(...under, key), value === null ? FieldValue.delete() : value] as const,\n )\n const [head, ...tail] = [\n ...fields(parents, changes),\n ...(alsoUnder ? fields(alsoUnder.parents, alsoUnder.changes) : []),\n ]\n if (!head) return\n await ref.update(head[0], head[1], ...tail.flat())\n}\n\n/**\n * Sets or clears a member's org-level overrides, and their narrowing\n * choices (`siteNarrowing`, AGL-4047), in one write. Keys outside the\n * catalog, and narrowing for a key no site can narrow, are refused before\n * anything is written (the route validates first; this is the floor). The\n * member must exist. Every host is re-projected, because a narrowing choice\n * moves the member's verdict on each site that narrows them.\n */\nexport async function setMemberPermissionOverrides(options: {\n orgId: string\n uid: string\n changes: PermissionOverrideWrite\n narrowing?: PermissionOverrideWrite\n}): Promise<PermissionOverridesResult & { siteNarrowing: Record<string, boolean> }> {\n const { orgId, uid, changes, narrowing = {} } = options\n const catalog = new Set<string>(ORG_PERMISSION_KEYS)\n for (const key of Object.keys(changes)) {\n if (!catalog.has(key)) throw new Error(`\"${key}\" is not a catalog permission`)\n }\n const narrowable = new Set(siteNarrowedPermissionKeys())\n for (const key of Object.keys(narrowing)) {\n if (!narrowable.has(key)) throw new Error(`\"${key}\" is not a permission a site can narrow`)\n }\n const ref = memberRef(orgId, uid)\n const snapshot = await ref.get()\n if (!snapshot.exists) throw new Error('member not found')\n const stored = { $id: uid, ...snapshot.data() } as AglynOrgMember\n const before = await resolveMemberOrgPermissions(orgId, stored)\n await updateFields(ref, ['permissions'], changes, { parents: ['siteNarrowing'], changes: narrowing })\n await syncOrgAuthProjections(orgId)\n const member = { $id: uid, ...(await ref.get()).data() } as AglynOrgMember\n return {\n before,\n after: await resolveMemberOrgPermissions(orgId, member),\n member,\n siteNarrowing: siteNarrowingChoices(member, await resolveMemberCustomRole(orgId, member)),\n }\n}\n\n/**\n * Sets or clears a member's per-site toggles on one site. For a site\n * collaborator, only the keys a plugin declared per-site\n * (`hostPermissionKeys`) are stored. For a member who works across the\n * workspace, only on a site that narrows them and only the keys that follow\n * the site role for them (`narrowedPermissionKeysOf`, AGL-4047): the site's\n * way to give back, or keep refused, what their narrower access there took.\n * The member must reach the site.\n */\nexport async function setHostPermissionOverrides(options: {\n orgId: string\n uid: string\n hostId: string\n changes: PermissionOverrideWrite\n}): Promise<PermissionOverridesResult> {\n const { orgId, uid, hostId, changes } = options\n const ref = memberRef(orgId, uid)\n const snapshot = await ref.get()\n if (!snapshot.exists) throw new Error('member not found')\n const stored = { $id: uid, ...snapshot.data() } as AglynOrgMember\n const narrowing = await resolveMemberSiteNarrowing(orgId, stored, hostId)\n const narrowed = narrowing !== null\n const siteKeys = new Set(narrowed ? narrowedPermissionKeysOf(narrowing) : hostPermissionKeys())\n for (const key of Object.keys(changes)) {\n if (!siteKeys.has(key)) throw new Error(`\"${key}\" is not a per-site permission`)\n }\n // A narrowed member's verdict on this site, every per-site key and every\n // key a site can narrow, from the same resolver the rules projection uses.\n const narrowedVerdicts = async (member: AglynOrgMember): Promise<Record<string, boolean>> => {\n const granted = narrowPermissionsToSite(\n await resolveMemberOrgPermissions(orgId, member),\n await resolveMemberSiteNarrowing(orgId, member, hostId),\n )\n return Object.fromEntries(\n [...hostPermissionKeys(), ...siteNarrowedPermissionKeys()].map((key) => [key, granted[key] === true]),\n )\n }\n const before = narrowed ? await narrowedVerdicts(stored) : resolveCollaboratorHostPermissions(stored, hostId)\n if (!before) throw new Error('member has no access to this site')\n await updateFields(ref, ['hostPermissions', hostId], changes)\n await syncOrgAuthProjections(orgId, hostId)\n const member = { $id: uid, ...(await ref.get()).data() } as AglynOrgMember\n return {\n before,\n after: narrowed\n ? await narrowedVerdicts(member)\n : (resolveCollaboratorHostPermissions(member, hostId) ??\n Object.fromEntries([...siteKeys].map((key) => [key, false]))),\n member,\n }\n}\n"],"names":["hostPermissionKeys","narrowedPermissionKeysOf","narrowPermissionsToSite","ORG_PERMISSION_KEYS","resolveCollaboratorHostPermissions","siteNarrowedPermissionKeys","siteNarrowingChoices","FieldPath","FieldValue","firebaseAdmin","resolveMemberCustomRole","resolveMemberOrgPermissions","resolveMemberSiteNarrowing","syncOrgAuthProjections","firestore","app","memberRef","orgId","uid","collection","doc","updateFields","ref","parents","changes","alsoUnder","fields","under","map","Object","entries","key","value","delete","head","tail","update","flat","setMemberPermissionOverrides","options","narrowing","catalog","Set","keys","has","Error","narrowable","snapshot","get","exists","stored","$id","data","before","member","after","siteNarrowing","setHostPermissionOverrides","hostId","narrowed","siteKeys","narrowedVerdicts","granted","fromEntries"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GAED,SACEA,kBAAkB,EAClBC,wBAAwB,EACxBC,uBAAuB,EACvBC,mBAAmB,EACnBC,kCAAkC,EAClCC,0BAA0B,EAC1BC,oBAAoB,QAEf,sBAAqB;AAC5B,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,OAAOC,mBAAmB,sBAAkB;AAC5C,SACEC,uBAAuB,EACvBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,sBAAsB,QACjB,qBAAiB;AAExB,MAAMC,YAAY,IAAML,cAAcM,GAAG,GAAGD,SAAS;AAarD,SAASE,UAAUC,KAAa,EAAEC,GAAW;IAC3C,OAAOJ,YAAYK,UAAU,CAAC,QAAQC,GAAG,CAACH,OAAOE,UAAU,CAAC,WAAWC,GAAG,CAACF;AAC7E;AAEA;;;;CAIC,GACD,eAAeG,aACbC,GAAwC,EACxCC,OAA0B,EAC1BC,OAAgC,EAChCC,SAA4E;IAE5E,MAAMC,SAAS,CAACC,OAA0BC,MACxCC,OAAOC,OAAO,CAACF,KAAKA,GAAG,CACrB,CAAC,CAACG,KAAKC,MAAM,GAAK;gBAAC,IAAIzB,aAAaoB,OAAOI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,QAAQQ;IACtG,IAAI,CAACL,QAAQ,MAAM,IAAIR,MAAM;IAC7B,MAAMxB,aAAaC,KAAK;QAAC;QAAmBoC;KAAO,EAAElC;IACrD,MAAMX,uBAAuBI,OAAOyC;IACpC,MAAMJ,SAAS;QAAEH,KAAKjC;OAAQ,AAAC,CAAA,MAAMI,IAAI0B,GAAG,EAAC,EAAGI,IAAI;IACpD,OAAO;QACLC;QACAE,OAAOI,WACH,MAAME,iBAAiBP,WACtBlD,sCAAAA,mCAAmCkD,QAAQI,mBAA3CtD,sCACDyB,OAAOkC,WAAW,CAAC;eAAIH;SAAS,CAAChC,GAAG,CAAC,CAACG,MAAQ;gBAACA;gBAAK;aAAM;QAC9DuB;IACF;AACF"}
@@ -20,7 +20,7 @@
20
20
  * and the projections the security rules authorize against are never
21
21
  * client-writable (docs/MULTI_TENANT_FIRESTORE.md §8).
22
22
  */
23
- import { type ConsentGroup, type AglynOrganization, type AglynOrgBilling, type AglynOrgMember, type HostAccessRole, type OrgPermission, type OrgPlan, type OrgRole, type OwnerHandoffPreviousOwner } from '@aglyn/aglyn/server';
23
+ import { type ConsentGroup, type SiteNarrowing, type AglynOrganization, type AglynOrgBilling, type AglynOrgCustomRole, type AglynOrgMember, type HostAccessRole, type OrgPermission, type OrgPlan, type OrgRole, type OwnerHandoffPreviousOwner } from '@aglyn/aglyn/server';
24
24
  import type { OrgOverrideReasonCode } from '@aglyn/aglyn/app-utils/org-override-reason';
25
25
  import type { PluginActivityTargetType } from '@aglyn/aglyn/plugin-manager/plugin-activity-actions';
26
26
  import type { HostActivityActor } from '@aglyn/aglyn/app-utils/activity-presenter';
@@ -311,6 +311,19 @@ export declare function orgDataQueryForHost(hostId: string, name: OrgDataCollect
311
311
  * base role allows.
312
312
  */
313
313
  export declare function resolveMemberOrgPermissions(orgId: string, member: Partial<AglynOrgMember> | null | undefined): Promise<Record<OrgPermission, boolean>>;
314
+ /**
315
+ * The custom role a member carries, or null: one read, and none without a
316
+ * `roleId`. A dangling id resolves to null, so the member falls back to
317
+ * their role's defaults (see `resolveMemberOrgPermissions`).
318
+ */
319
+ export declare function resolveMemberCustomRole(orgId: string, member: Partial<AglynOrgMember> | null | undefined): Promise<AglynOrgCustomRole | null>;
320
+ /**
321
+ * How this site narrows this member (AGL-4047), with their custom role's
322
+ * narrowing choices applied, or null where it does not. Reads the custom
323
+ * role only for a member whose access to the site is narrower than their
324
+ * workspace role, so every other caller pays nothing.
325
+ */
326
+ export declare function resolveMemberSiteNarrowing(orgId: string, member: Partial<AglynOrgMember> | null | undefined, hostId: string | null | undefined): Promise<SiteNarrowing | null>;
314
327
  export declare function memberHasOrgPermission(orgId: string, member: Partial<AglynOrgMember> | null | undefined, permission: OrgPermission): Promise<boolean>;
315
328
  /**
316
329
  * May this member hold a catalog permission on this site (AGL-2927,
@@ -19,7 +19,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
19
19
  * Admin-SDK-only by design: org creation, slug reservation, membership
20
20
  * and the projections the security rules authorize against are never
21
21
  * client-writable (docs/MULTI_TENANT_FIRESTORE.md §8).
22
- */ import { consentGroupForHost, checkHostCollaboratorQuota, checkSeatQuota, countCollaboratorSeats, countManagerSeatsExcluding, createResourceUid, generateOrgSlug, projectMemberResolvedPermissions, resolveOrgPermissions, isOrgWideMember, isValidOrgSlug, hostPermissionKeys, parseOwnerHandoff, usesCustomerSeat, orgPermissionLabel, pluginOrgPermissionKeys, projectHostMemberPermissions, projectHostMemberRoles, projectMemberScopeTokens, resolveCollaboratorHostPermissions, scopeTokensForHost } from "@aglyn/aglyn/server";
22
+ */ import { consentGroupForHost, checkHostCollaboratorQuota, checkSeatQuota, countCollaboratorSeats, countManagerSeatsExcluding, createResourceUid, generateOrgSlug, projectMemberResolvedPermissions, resolveOrgPermissions, isOrgWideMember, isValidOrgSlug, hostPermissionKeys, parseOwnerHandoff, usesCustomerSeat, orgPermissionLabel, pluginOrgPermissionKeys, projectHostMemberPermissions, projectHostMemberRoles, projectMemberScopeTokens, resolveCollaboratorHostPermissions, narrowPermissionsToSite, siteMayNarrow, applySiteRolePresets, siteNarrowingFor, scopeTokensForHost } from "@aglyn/aglyn/server";
23
23
  import { ACCOUNT_ACQUISITION_FIELD, organizationAcquisition } from "@aglyn/aglyn/app-utils/account-acquisition";
24
24
  import { activitySearchTokens } from "@aglyn/aglyn/app-utils/activity-search";
25
25
  import { nameSearchKey, nameSearchReversed, nameSearchTokens } from "@aglyn/aglyn/app-utils/name-search";
@@ -692,12 +692,26 @@ export async function orgDataCollectionForHost(hostId, name) {
692
692
  * dangling id — a deleted role must not lock a member out of surfaces their
693
693
  * base role allows.
694
694
  */ export async function resolveMemberOrgPermissions(orgId, member) {
695
- let customRole = null;
696
- if (member == null ? void 0 : member.roleId) {
697
- const snapshot = await firestore().collection('orgs').doc(orgId).collection('roles').doc(member.roleId).get();
698
- customRole = snapshot.exists ? snapshot.data() : null;
699
- }
700
- return resolveOrgPermissions(member, customRole);
695
+ return resolveOrgPermissions(member, await resolveMemberCustomRole(orgId, member));
696
+ }
697
+ /**
698
+ * The custom role a member carries, or null: one read, and none without a
699
+ * `roleId`. A dangling id resolves to null, so the member falls back to
700
+ * their role's defaults (see `resolveMemberOrgPermissions`).
701
+ */ export async function resolveMemberCustomRole(orgId, member) {
702
+ if (!(member == null ? void 0 : member.roleId)) return null;
703
+ const snapshot = await firestore().collection('orgs').doc(orgId).collection('roles').doc(member.roleId).get();
704
+ return snapshot.exists ? snapshot.data() : null;
705
+ }
706
+ /**
707
+ * How this site narrows this member (AGL-4047), with their custom role's
708
+ * narrowing choices applied, or null where it does not. Reads the custom
709
+ * role only for a member whose access to the site is narrower than their
710
+ * workspace role, so every other caller pays nothing.
711
+ */ export async function resolveMemberSiteNarrowing(orgId, member, hostId) {
712
+ const site = typeof hostId === 'string' ? hostId.trim() : '';
713
+ if (!siteMayNarrow(member, site)) return null;
714
+ return siteNarrowingFor(member, site, await resolveMemberCustomRole(orgId, member));
701
715
  }
702
716
  export async function memberHasOrgPermission(orgId, member, permission) {
703
717
  if (!member) return false;
@@ -747,14 +761,21 @@ export async function memberHasOrgPermission(orgId, member, permission) {
747
761
  * `hostId` is whatever the body carried, trimmed by the caller or not — an
748
762
  * empty string and `undefined` both mean "no site named".
749
763
  */ export async function memberHasPermissionOnHost(orgId, hostId, member, permission) {
750
- var _ref;
751
- var _resolveCollaboratorHostPermissions;
764
+ var _applySiteRolePresets_permission, _resolveCollaboratorHostPermissions;
752
765
  if (!member) return false;
766
+ const site = typeof hostId === 'string' ? hostId.trim() : '';
753
767
  if (isOrgWideMember(member)) {
754
- return verdictFor(permission, await resolveMemberOrgPermissions(orgId, member), ()=>resolveMemberOrgPermissions(orgId, member));
768
+ // On a site that narrows them (AGL-4047), the keys that follow the site
769
+ // role for them (their own choice, their custom role's, or the built-in
770
+ // default) are decided for it; everywhere else this is the workspace's
771
+ // verdict. A key whose preset is the site role is decided for the site
772
+ // named, from the access they hold there (`applySiteRolePresets`).
773
+ const customRole = await resolveMemberCustomRole(orgId, member);
774
+ const narrowing = siteMayNarrow(member, site) ? siteNarrowingFor(member, site, customRole) : null;
775
+ const onSite = ()=>applySiteRolePresets(narrowPermissionsToSite(resolveOrgPermissions(member, customRole), narrowing), member, site, customRole);
776
+ return verdictFor(permission, onSite(), async ()=>onSite());
755
777
  }
756
- const site = typeof hostId === 'string' ? hostId.trim() : '';
757
- return (_ref = (_resolveCollaboratorHostPermissions = resolveCollaboratorHostPermissions(member, site)) == null ? void 0 : _resolveCollaboratorHostPermissions[permission]) != null ? _ref : false;
778
+ return (_applySiteRolePresets_permission = applySiteRolePresets((_resolveCollaboratorHostPermissions = resolveCollaboratorHostPermissions(member, site)) != null ? _resolveCollaboratorHostPermissions : {}, member, site)[permission]) != null ? _applySiteRolePresets_permission : false;
758
779
  }
759
780
  /**
760
781
  * The 403 a door sends when `memberHasPermissionOnHost` says no: the same