@aglyn/tenant-data-admin 1.19.0 → 1.20.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.
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type PluginRunsOn, type PluginSiteStranding } from '@aglyn/aglyn/plugin-manager/plugin-site-exclusions';
18
+ /** A "Runs on" choice off the wire, or null for anything else. */
19
+ export declare function pluginRunsOnChoiceFrom(value: unknown): PluginRunsOn | null;
20
+ export type PluginRunsOnWrite = {
21
+ ok: false;
22
+ status: 400 | 403 | 404;
23
+ problem: string;
24
+ stranded?: PluginSiteStranding[];
25
+ } | {
26
+ ok: true;
27
+ /** Sites whose deny-list now names the plugin. */
28
+ leftOutHostIds: string[];
29
+ /** Sites whose deny-list no longer names it. */
30
+ broughtBackHostIds: string[];
31
+ };
32
+ /**
33
+ * Writes a "Runs on" choice into each site's deny-list, in one transaction.
34
+ *
35
+ * Nothing is written when the choice can't be (`planPluginRunsOn`), when a
36
+ * site whose entry changes refuses the member, or when the workspace is gone.
37
+ */
38
+ export declare function writePluginRunsOn(options: {
39
+ firestore: FirebaseFirestore.Firestore;
40
+ orgId: string;
41
+ pluginId: string;
42
+ choice: PluginRunsOn;
43
+ /** Whether the member may change this site's plugins: "Manage site settings" there. */
44
+ mayChangeSite: (hostId: string) => Promise<boolean>;
45
+ /** The refusal for a site that says no. */
46
+ refusedOnSite: (siteName: string) => string;
47
+ /** Server time for `updatedAt`. */
48
+ now: () => unknown;
49
+ /** The plugin's name in a refusal, for one the catalog can't name. */
50
+ label?: string;
51
+ /**
52
+ * The plugin is being installed for the workspace in the same request: a
53
+ * marketplace plugin with "All sites except…", written BEFORE its pin, so a
54
+ * site left out never runs it, not even for one page (AGL-4047).
55
+ *
56
+ * Two things follow. The workspace reads it as on, since the install
57
+ * switches it on. And the choice only ever LEAVES sites out: a site that
58
+ * switched this plugin off for itself before (it had been installed and
59
+ * removed) keeps its own switch, as a plain All sites install keeps it.
60
+ */
61
+ installing?: boolean;
62
+ }): Promise<PluginRunsOnWrite>;
@@ -0,0 +1,142 @@
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
+ */ import { planPluginRunsOn } from "@aglyn/aglyn/plugin-manager/plugin-site-exclusions";
18
+ import { orgHostIdsFromDoc } from "./scope-sharing-sweep.js";
19
+ /**
20
+ * WHERE A PLUGIN RUNS ACROSS A WORKSPACE, WRITTEN BY THE SERVER (AGL-4047).
21
+ *
22
+ * A workspace's "Runs on" choice for a plugin is stored nowhere of its own: a
23
+ * site left out is a site whose `disabledPlugins` deny-list names the plugin,
24
+ * the same entry that site's own Admin › Plugins switch writes
25
+ * (`plugin-site-exclusions.ts`). So this writes those entries, every site in
26
+ * one transaction that first reads the workspace document, which names the
27
+ * sites: a site being created either lands first and is read here, or lands
28
+ * after with no entry, which runs the plugin, as "all sites except…" says.
29
+ *
30
+ * Each site whose entry changes needs "Manage site settings" there, the key the
31
+ * rules ask of a client write to that site's plugin lists. The caller asks the
32
+ * workspace key first. Nobody can change a site's plugins through here who
33
+ * couldn't on that site's own page.
34
+ *
35
+ * Two callers: the console's "Runs on" field for a built-in plugin
36
+ * (`/api/orgs/plugin-sites`), and a marketplace plugin installed for the
37
+ * workspace with "All sites except…" (the marketplace's install route), which
38
+ * a site's switch stops since the realm join reads it.
39
+ */ /** The most site ids one choice may name: far past any workspace. */ const RUNS_ON_MAX_IDS = 1000;
40
+ /** A "Runs on" choice off the wire, or null for anything else. */ export function pluginRunsOnChoiceFrom(value) {
41
+ const choice = value != null ? value : {};
42
+ if (choice.mode === 'all') return {
43
+ mode: 'all'
44
+ };
45
+ if (choice.mode !== 'allExcept') return null;
46
+ const ids = choice.exceptHostIds;
47
+ return Array.isArray(ids) && ids.length <= RUNS_ON_MAX_IDS && ids.every((id)=>typeof id === 'string' && /^[^:/]+$/.test(id)) ? {
48
+ mode: 'allExcept',
49
+ exceptHostIds: ids
50
+ } : null;
51
+ }
52
+ /**
53
+ * Writes a "Runs on" choice into each site's deny-list, in one transaction.
54
+ *
55
+ * Nothing is written when the choice can't be (`planPluginRunsOn`), when a
56
+ * site whose entry changes refuses the member, or when the workspace is gone.
57
+ */ export async function writePluginRunsOn(options) {
58
+ const { firestore, orgId, pluginId, choice } = options;
59
+ const orgRef = firestore.collection('orgs').doc(orgId);
60
+ return firestore.runTransaction(async (tx)=>{
61
+ var _org_data;
62
+ const org = await tx.get(orgRef);
63
+ if (!org.exists) return {
64
+ ok: false,
65
+ status: 404,
66
+ problem: 'No such workspace'
67
+ };
68
+ const orgData = (_org_data = org.data()) != null ? _org_data : {};
69
+ const hostIds = orgHostIdsFromDoc(orgData);
70
+ const hostRefs = hostIds.map((hostId)=>firestore.collection('hosts').doc(hostId));
71
+ const snapshots = hostRefs.length ? await tx.getAll(...hostRefs) : [];
72
+ // A site the workspace document still names but that is gone, or that
73
+ // another workspace now holds, is not this workspace's to write.
74
+ const held = snapshots.filter((snapshot)=>snapshot.exists && snapshot.get('orgId') === orgId);
75
+ const names = new Map(held.map((snapshot)=>[
76
+ snapshot.id,
77
+ String(snapshot.get('displayName') || snapshot.get('subdomain') || 'a site')
78
+ ]));
79
+ const enabled = orgData['enabledPlugins'];
80
+ const plan = planPluginRunsOn(_extends({
81
+ pluginId,
82
+ choice,
83
+ // The install switches it on for the workspace (`syncEnabledPlugins`),
84
+ // so the choice is planned as for a plugin that is on.
85
+ org: options.installing && Array.isArray(enabled) ? _extends({}, orgData, {
86
+ enabledPlugins: [
87
+ ...enabled.map(String),
88
+ pluginId
89
+ ]
90
+ }) : orgData,
91
+ installedListings: options.installing ? [
92
+ pluginId
93
+ ] : undefined,
94
+ sites: held.map((snapshot)=>{
95
+ var _snapshot_get, _snapshot_get1;
96
+ return {
97
+ id: snapshot.id,
98
+ disabledPlugins: (_snapshot_get = snapshot.get('disabledPlugins')) != null ? _snapshot_get : null,
99
+ enabledPlugins: (_snapshot_get1 = snapshot.get('enabledPlugins')) != null ? _snapshot_get1 : null
100
+ };
101
+ }),
102
+ siteName: (hostId)=>{
103
+ var _names_get;
104
+ return (_names_get = names.get(hostId)) != null ? _names_get : 'a site';
105
+ }
106
+ }, options.label ? {
107
+ label: options.label
108
+ } : {}));
109
+ if (plan.problem !== null) {
110
+ return {
111
+ ok: false,
112
+ status: 400,
113
+ problem: plan.problem,
114
+ stranded: plan.stranded
115
+ };
116
+ }
117
+ const writes = options.installing ? plan.writes.filter((write)=>write.leftOut) : plan.writes;
118
+ for (const write of writes){
119
+ if (!await options.mayChangeSite(write.hostId)) {
120
+ var _names_get;
121
+ return {
122
+ ok: false,
123
+ status: 403,
124
+ problem: options.refusedOnSite((_names_get = names.get(write.hostId)) != null ? _names_get : 'a site')
125
+ };
126
+ }
127
+ }
128
+ for (const write of writes){
129
+ tx.update(firestore.collection('hosts').doc(write.hostId), {
130
+ disabledPlugins: write.disabledPlugins,
131
+ updatedAt: options.now()
132
+ });
133
+ }
134
+ return {
135
+ ok: true,
136
+ leftOutHostIds: writes.filter((write)=>write.leftOut).map((write)=>write.hostId),
137
+ broughtBackHostIds: writes.filter((write)=>!write.leftOut).map((write)=>write.hostId)
138
+ };
139
+ });
140
+ }
141
+
142
+ //# sourceMappingURL=plugin-runs-on.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/plugin-runs-on.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 {\n planPluginRunsOn,\n type PluginRunsOn,\n type PluginSiteStranding,\n} from '@aglyn/aglyn/plugin-manager/plugin-site-exclusions'\nimport { orgHostIdsFromDoc } from './scope-sharing-sweep'\n\n/**\n * WHERE A PLUGIN RUNS ACROSS A WORKSPACE, WRITTEN BY THE SERVER (AGL-4047).\n *\n * A workspace's \"Runs on\" choice for a plugin is stored nowhere of its own: a\n * site left out is a site whose `disabledPlugins` deny-list names the plugin,\n * the same entry that site's own Admin › Plugins switch writes\n * (`plugin-site-exclusions.ts`). So this writes those entries, every site in\n * one transaction that first reads the workspace document, which names the\n * sites: a site being created either lands first and is read here, or lands\n * after with no entry, which runs the plugin, as \"all sites except…\" says.\n *\n * Each site whose entry changes needs \"Manage site settings\" there, the key the\n * rules ask of a client write to that site's plugin lists. The caller asks the\n * workspace key first. Nobody can change a site's plugins through here who\n * couldn't on that site's own page.\n *\n * Two callers: the console's \"Runs on\" field for a built-in plugin\n * (`/api/orgs/plugin-sites`), and a marketplace plugin installed for the\n * workspace with \"All sites except…\" (the marketplace's install route), which\n * a site's switch stops since the realm join reads it.\n */\n\n/** The most site ids one choice may name: far past any workspace. */\nconst RUNS_ON_MAX_IDS = 1000\n\n/** A \"Runs on\" choice off the wire, or null for anything else. */\nexport function pluginRunsOnChoiceFrom(value: unknown): PluginRunsOn | null {\n const choice = (value ?? {}) as { mode?: unknown; exceptHostIds?: unknown }\n if (choice.mode === 'all') return { mode: 'all' }\n if (choice.mode !== 'allExcept') return null\n const ids = choice.exceptHostIds\n return Array.isArray(ids) &&\n ids.length <= RUNS_ON_MAX_IDS &&\n ids.every((id) => typeof id === 'string' && /^[^:/]+$/.test(id))\n ? { mode: 'allExcept', exceptHostIds: ids as string[] }\n : null\n}\n\nexport type PluginRunsOnWrite =\n | {\n ok: false\n status: 400 | 403 | 404\n problem: string\n stranded?: PluginSiteStranding[]\n }\n | {\n ok: true\n /** Sites whose deny-list now names the plugin. */\n leftOutHostIds: string[]\n /** Sites whose deny-list no longer names it. */\n broughtBackHostIds: string[]\n }\n\n/**\n * Writes a \"Runs on\" choice into each site's deny-list, in one transaction.\n *\n * Nothing is written when the choice can't be (`planPluginRunsOn`), when a\n * site whose entry changes refuses the member, or when the workspace is gone.\n */\nexport async function writePluginRunsOn(options: {\n firestore: FirebaseFirestore.Firestore\n orgId: string\n pluginId: string\n choice: PluginRunsOn\n /** Whether the member may change this site's plugins: \"Manage site settings\" there. */\n mayChangeSite: (hostId: string) => Promise<boolean>\n /** The refusal for a site that says no. */\n refusedOnSite: (siteName: string) => string\n /** Server time for `updatedAt`. */\n now: () => unknown\n /** The plugin's name in a refusal, for one the catalog can't name. */\n label?: string\n /**\n * The plugin is being installed for the workspace in the same request: a\n * marketplace plugin with \"All sites except…\", written BEFORE its pin, so a\n * site left out never runs it, not even for one page (AGL-4047).\n *\n * Two things follow. The workspace reads it as on, since the install\n * switches it on. And the choice only ever LEAVES sites out: a site that\n * switched this plugin off for itself before (it had been installed and\n * removed) keeps its own switch, as a plain All sites install keeps it.\n */\n installing?: boolean\n}): Promise<PluginRunsOnWrite> {\n const { firestore, orgId, pluginId, choice } = options\n const orgRef = firestore.collection('orgs').doc(orgId)\n return firestore.runTransaction(async (tx): Promise<PluginRunsOnWrite> => {\n const org = await tx.get(orgRef)\n if (!org.exists) return { ok: false, status: 404, problem: 'No such workspace' }\n const orgData = (org.data() ?? {}) as Record<string, unknown>\n const hostIds = orgHostIdsFromDoc(orgData)\n const hostRefs = hostIds.map((hostId) => firestore.collection('hosts').doc(hostId))\n const snapshots = hostRefs.length ? await tx.getAll(...hostRefs) : []\n // A site the workspace document still names but that is gone, or that\n // another workspace now holds, is not this workspace's to write.\n const held = snapshots.filter((snapshot) => snapshot.exists && snapshot.get('orgId') === orgId)\n const names = new Map(\n held.map((snapshot) => [\n snapshot.id,\n String(snapshot.get('displayName') || snapshot.get('subdomain') || 'a site'),\n ]),\n )\n const enabled = orgData['enabledPlugins']\n const plan = planPluginRunsOn({\n pluginId,\n choice,\n // The install switches it on for the workspace (`syncEnabledPlugins`),\n // so the choice is planned as for a plugin that is on.\n org: (options.installing && Array.isArray(enabled)\n ? { ...orgData, enabledPlugins: [...enabled.map(String), pluginId] }\n : orgData) as { enabledPlugins?: string[] },\n installedListings: options.installing ? [pluginId] : undefined,\n sites: held.map((snapshot) => ({\n id: snapshot.id,\n disabledPlugins: snapshot.get('disabledPlugins') ?? null,\n enabledPlugins: snapshot.get('enabledPlugins') ?? null,\n })),\n siteName: (hostId) => names.get(hostId) ?? 'a site',\n ...(options.label ? { label: options.label } : {}),\n })\n if (plan.problem !== null) {\n return { ok: false, status: 400, problem: plan.problem, stranded: plan.stranded }\n }\n const writes = options.installing ? plan.writes.filter((write) => write.leftOut) : plan.writes\n for (const write of writes) {\n if (!(await options.mayChangeSite(write.hostId))) {\n return {\n ok: false,\n status: 403,\n problem: options.refusedOnSite(names.get(write.hostId) ?? 'a site'),\n }\n }\n }\n for (const write of writes) {\n tx.update(firestore.collection('hosts').doc(write.hostId), {\n disabledPlugins: write.disabledPlugins,\n updatedAt: options.now(),\n })\n }\n return {\n ok: true,\n leftOutHostIds: writes.filter((write) => write.leftOut).map((write) => write.hostId),\n broughtBackHostIds: writes.filter((write) => !write.leftOut).map((write) => write.hostId),\n }\n })\n}\n"],"names":["planPluginRunsOn","orgHostIdsFromDoc","RUNS_ON_MAX_IDS","pluginRunsOnChoiceFrom","value","choice","mode","ids","exceptHostIds","Array","isArray","length","every","id","test","writePluginRunsOn","options","firestore","orgId","pluginId","orgRef","collection","doc","runTransaction","tx","org","get","exists","ok","status","problem","orgData","data","hostIds","hostRefs","map","hostId","snapshots","getAll","held","filter","snapshot","names","Map","String","enabled","plan","installing","enabledPlugins","installedListings","undefined","sites","disabledPlugins","siteName","label","stranded","writes","write","leftOut","mayChangeSite","refusedOnSite","update","updatedAt","now","leftOutHostIds","broughtBackHostIds"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QAGX,qDAAoD;AAC3D,SAASC,iBAAiB,QAAQ,2BAAuB;AAEzD;;;;;;;;;;;;;;;;;;;;CAoBC,GAED,mEAAmE,GACnE,MAAMC,kBAAkB;AAExB,gEAAgE,GAChE,OAAO,SAASC,uBAAuBC,KAAc;IACnD,MAAMC,SAAUD,gBAAAA,QAAS,CAAC;IAC1B,IAAIC,OAAOC,IAAI,KAAK,OAAO,OAAO;QAAEA,MAAM;IAAM;IAChD,IAAID,OAAOC,IAAI,KAAK,aAAa,OAAO;IACxC,MAAMC,MAAMF,OAAOG,aAAa;IAChC,OAAOC,MAAMC,OAAO,CAACH,QACnBA,IAAII,MAAM,IAAIT,mBACdK,IAAIK,KAAK,CAAC,CAACC,KAAO,OAAOA,OAAO,YAAY,WAAWC,IAAI,CAACD,OAC1D;QAAEP,MAAM;QAAaE,eAAeD;IAAgB,IACpD;AACN;AAiBA;;;;;CAKC,GACD,OAAO,eAAeQ,kBAAkBC,OAwBvC;IACC,MAAM,EAAEC,SAAS,EAAEC,KAAK,EAAEC,QAAQ,EAAEd,MAAM,EAAE,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CAACA,MAAMC,OAAO,EAAEvB,GAAG,CAAC,CAACsB,QAAUA,MAAMrB,MAAM;QAC1F;IACF;AACF"}
@@ -76,7 +76,11 @@ export declare function resolveMarketplacePluginVersion(listingId: string, versi
76
76
  * switchboard toggle, a plan move) expires `tenant-plugins:{hostId}` for each
77
77
  * site it reaches;
78
78
  * - a platform event (a takedown, a revoked version, realm trust withdrawn or
79
- * rejected away) expires `tenant-plugins` on every site at once.
79
+ * rejected away) expires `tenant-plugins` on every site at once;
80
+ * - a site's own Admin › Plugins switch (AGL-4047) writes `disabledPlugins` on
81
+ * the host document, a rendered field, so the console drops the whole site
82
+ * and with it `tenant-data:{hostId}`, which this entry carries too
83
+ * (`tenantPluginGateTags`).
80
84
  *
81
85
  * Each of those is staged in the publish outbox BEFORE it is sent, so a
82
86
  * refused call is retried by the console's drain, and an alert is raised when
@@ -176,7 +176,11 @@ import { TENANT_CACHE_BACKSTOP_SECONDS, tenantPluginGateTags, withRenderCache }
176
176
  * switchboard toggle, a plan move) expires `tenant-plugins:{hostId}` for each
177
177
  * site it reaches;
178
178
  * - a platform event (a takedown, a revoked version, realm trust withdrawn or
179
- * rejected away) expires `tenant-plugins` on every site at once.
179
+ * rejected away) expires `tenant-plugins` on every site at once;
180
+ * - a site's own Admin › Plugins switch (AGL-4047) writes `disabledPlugins` on
181
+ * the host document, a rendered field, so the console drops the whole site
182
+ * and with it `tenant-data:{hostId}`, which this entry carries too
183
+ * (`tenantPluginGateTags`).
180
184
  *
181
185
  * Each of those is staged in the publish outbox BEFORE it is sent, so a
182
186
  * refused call is retried by the console's drain, and an alert is raised when
@@ -204,9 +208,37 @@ export async function getRealmPluginInstalls(options) {
204
208
  return resolveRealmPluginInstalls(options);
205
209
  }
206
210
  }
211
+ /**
212
+ * The listings ONE site switched off on its Admin › Plugins page (AGL-4047).
213
+ *
214
+ * The site switch writes a marketplace plugin's listing id into the host's
215
+ * `disabledPlugins`, beside the built-in ids it holds. The built-in half was
216
+ * always honored (`resolveHostEnabledPlugins`); this join read only the
217
+ * workspace's list, so a marketplace plugin a site switched off kept loading on
218
+ * its published pages and kept binding its functions there.
219
+ *
220
+ * Masked to that one field, as the org read below is: the host document is the
221
+ * largest one a site has. Issued alongside the org resolution, so it adds a
222
+ * read to a cache miss and no round trip to it. A read that fails rejects the
223
+ * join, which every caller already answers as "no marketplace plugins", so a
224
+ * failure can never run a plugin the site turned off.
225
+ */ async function readSiteDisabledListings(firestore, hostId) {
226
+ const [host] = await firestore.getAll(firestore.collection('hosts').doc(hostId), {
227
+ fieldMask: [
228
+ 'disabledPlugins'
229
+ ]
230
+ });
231
+ const disabled = host == null ? void 0 : host.get('disabledPlugins');
232
+ return new Set(Array.isArray(disabled) ? disabled.map(String) : []);
233
+ }
207
234
  async function resolveRealmPluginInstalls(options) {
208
235
  var _options_orgId;
209
236
  const firestore = firebaseAdmin.app().firestore();
237
+ // Started first and awaited last: it depends on nothing the org hop reads.
238
+ const siteDisabled = options.hostId ? readSiteDisabledListings(firestore, options.hostId) : null;
239
+ // Marked handled now, consumed below: a rejection must not sit unobserved
240
+ // while the org hop is awaited.
241
+ siteDisabled == null ? void 0 : siteDisabled.catch(()=>undefined);
210
242
  const orgId = (_options_orgId = options.orgId) != null ? _options_orgId : options.hostId ? await resolveOrgIdForHost(options.hostId) : null;
211
243
  // Switchboard gate (AGL-424): a workspace with an EXPLICIT
212
244
  // `enabledPlugins` list only realm-loads listings on it (install sync
@@ -255,6 +287,18 @@ async function resolveRealmPluginInstalls(options) {
255
287
  if (!enabledFilter.includes(listingId)) pins.delete(listingId);
256
288
  }
257
289
  }
290
+ // The site's own switch, after the workspace's (AGL-4047). A site can only
291
+ // narrow: it switches off what the workspace runs, never on what it does
292
+ // not. It covers the site's own pins too; the switch is the site's answer
293
+ // for that listing, wherever the pin lives.
294
+ if (siteDisabled) {
295
+ const disabled = await siteDisabled;
296
+ for (const listingId of [
297
+ ...pins.keys()
298
+ ]){
299
+ if (disabled.has(listingId)) pins.delete(listingId);
300
+ }
301
+ }
258
302
  if (!pins.size) return [];
259
303
  const installs = await Promise.all([
260
304
  ...pins.values()
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/realm-plugins.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 {\n getPluginConfigSchema,\n isPluginRevoked,\n mergePluginConfig,\n readPluginContributions,\n resolvePluginConfig,\n type PluginContributions,\n type PluginRevocation,\n type RealmPluginInstall,\n} from '@aglyn/aglyn/server'\nimport { PLUGIN_DISTRIBUTION } from '@aglyn/aglyn/plugin-manager/plugin-distribution'\nimport { firebaseAdmin } from './firebase-admin'\nimport { resolveOrgIdForHost } from './organizations'\nimport {\n TENANT_CACHE_BACKSTOP_SECONDS,\n tenantPluginGateTags,\n withRenderCache,\n} from '../render-cache'\n\n/**\n * One `pluginSettings` document, or `undefined` if it cannot be read.\n *\n * A failed read degrades to \"no answer at this level\" rather than throwing,\n * so a transient Firestore error costs a handler its overrides and not its\n * request. The caller layers what comes back, so a missing site document and\n * a missing site override are the same thing to it.\n */\nasync function readPluginSettings(\n scope: 'orgs' | 'hosts',\n scopeId: string,\n pluginId: string,\n): Promise<Record<string, unknown> | undefined> {\n try {\n return (\n await firebaseAdmin\n .app()\n .firestore()\n .collection(scope)\n .doc(scopeId)\n .collection('pluginSettings')\n .doc(pluginId)\n .get()\n ).data()\n } catch {\n return undefined\n }\n}\n\n/**\n * Server-side plugin config read (AGL-428): the stored overrides merged over\n * the plugin's declared defaults (type-coerced — the docs are\n * manager-writable). Without a registered schema the raw doc (or {}) comes\n * back, so handlers degrade to their own fallbacks.\n *\n * `hostId` resolves the SITE's answer on top of the workspace's (AGL-428,\n * AGL-1014), and a handler that has one must pass it. A per-site setting the console can\n * store and the server never reads is not a setting: the operator lowers the\n * flagship branch's booking horizon, the console shows the number they typed,\n * and `/api/bookings/slots` keeps offering the workspace's — a disagreement\n * with no error and no surface that shows both sides.\n *\n * The site read is CONDITIONAL on being handed a host, so a request with no\n * site in scope pays nothing for a document that could not apply to it. It\n * runs alongside the org read rather than after it: the two documents are\n * independent, and sequencing them would put a second serial round trip on\n * every request that resolves config.\n */\nexport async function getPluginConfig(\n orgId: string | null | undefined,\n pluginId: string,\n options: { hostId?: string | null } = {},\n): Promise<Record<string, unknown>> {\n const schema = getPluginConfigSchema(pluginId)\n const hostId = options.hostId\n if (!orgId && !hostId) return schema ? mergePluginConfig(schema, null) : {}\n const [org, host] = await Promise.all([\n orgId ? readPluginSettings('orgs', orgId, pluginId) : undefined,\n hostId ? readPluginSettings('hosts', hostId, pluginId) : undefined,\n ])\n // Coercion happens once, at the end, inside `resolvePluginConfig` — a\n // malformed site value falls back to the WORKSPACE value it was trying to\n // replace rather than skipping past it to the schema default.\n if (schema) return resolvePluginConfig(schema, { org, host })\n // No schema: there is no field list to layer by, so the site document\n // simply narrows the workspace's, key for key.\n return { ...(org ?? {}), ...(host ?? {}) }\n}\n\n/**\n * Server-side resolution of a workspace's TRUSTED-REALM plugin installs\n * (AGL-420). Install docs pin `{version, sha256}`, but the trust grant\n * (`trust: 'realm'` + the platform Ed25519 `signature`) lives on the\n * server-only version doc — staff sign AFTER review, possibly long after\n * the install — so this join is the single source the loaders consume:\n *\n * 1. Read the org's installs (and the host's, when a host is in scope).\n * 2. Join each pin with its version document, in the store the\n * distributing plugin declares (`PLUGIN_DISTRIBUTION`, AGL-3080 — the\n * marketplace's listings today); only versions carrying `trust: 'realm'`\n * survive.\n * 3. Drop revoked versions (the kill switch keyed by the listing id) — a\n * revocation beats a still-present trust grant.\n * 4. Drop hidden listings (AGL-948) — `resolveMarketplacePluginVersion`\n * returns null for a listing under staff takedown. `deletedAt` is not\n * a blocker; see that function for why the two differ.\n *\n * The returned sha256/signature come from the VERSION doc, not the install\n * copy, so a tampered install doc cannot smuggle different bytes past the\n * loader's content check.\n */\n\ninterface InstallPin {\n listingId: string\n version: string\n}\n\n/**\n * One version-doc read, shaped for the remote loaders' `resolveVersion`.\n *\n * Also the staff-takedown gate (AGL-948): a listing carrying `hiddenAt`\n * resolves to null, so an already-installed plugin stops loading the\n * moment staff hide it. Takedown used to only de-list — a plugin pulled\n * for abuse kept executing in every workspace that had installed it until\n * someone separately wrote a revocation. It lives HERE rather than in the\n * join because every remote path funnels through this function: the\n * console and site realm joins, and both apps' remote-server-bundle\n * loaders.\n *\n * `deletedAt` is deliberately NOT a blocker. A publisher retiring a\n * listing must not break the sites already paying for it; unpublish\n * blocks new installs (`install-plugin`) and that is all it means.\n */\nexport async function resolveMarketplacePluginVersion(\n listingId: string,\n version: string,\n): Promise<{\n sha256: string\n signature?: string\n trust?: string\n hostAbi?: number\n pluginId?: string\n identity?: string\n contributes?: PluginContributions\n} | null> {\n // No distributing plugin declared a store: nothing can be vouched for, so\n // nothing resolves (see `plugin-distribution.ts` — absent is closed).\n const distribution = PLUGIN_DISTRIBUTION\n if (!distribution) return null\n const firestore = firebaseAdmin.app().firestore()\n const listingRef = firestore.collection(distribution.listings).doc(listingId)\n // THE REVOCATION READ IS IN THIS `Promise.all`, NOT AFTER IT (2026-08-26).\n //\n // It is keyed on `listingId` alone, so it never depended on the two reads\n // above — awaiting it below them cost a SECOND sequential Firestore round\n // trip on every resolution, and `resolveRealmPluginInstalls` calls this\n // once per pinned install. That is the shape that grows with the number of\n // plugins an org has installed: `/api/orgs/realm-plugins` is deliberately\n // uncached (see the TTL note below), and at a P75 of 907ms it was already\n // the slowest org-scoped console route before anyone uploaded in volume.\n //\n // The trade is one extra read on the paths that exit early (a hidden\n // listing, a missing version doc) in exchange for halving the round trips\n // on the path that actually happens. The kill switch is UNCHANGED: the\n // check below still runs before any value is returned, and it still reads\n // live — this moves when the read is issued, never whether it is honored.\n const [listing, snapshot, revocationSnapshot] = await Promise.all([\n listingRef.get(),\n listingRef.collection(distribution.versions).doc(version).get(),\n firestore.collection(distribution.revocations).doc(listingId).get(),\n ])\n // A missing listing doc is NOT a blocker: Firestore does not cascade to\n // subcollections, so a hard-deleted listing leaves working installs\n // resolving off an orphaned version doc. Only an explicit takedown stops\n // them.\n if (listing.get('hiddenAt')) return null\n const data = snapshot.data()\n if (!data?.sha256) return null\n // THE KILL SWITCH BELONGS AT THE CHOKEPOINT (AGL-2307).\n //\n // It used to live one level up, in `resolveRealmPluginInstalls` — which is\n // the path the tenant render and the console gate take, and NOT the path\n // remote SERVER bundles take. `loadRemoteServerBundles` resolves through\n // this function and nothing else, so a per-version revocation left a realm\n // server handler running: `hiddenAt` caught a full takedown, but a targeted\n // revocation deliberately does not hide the listing, which is the whole\n // difference between the two controls.\n //\n // Placed here rather than added as a second copy at the server loader, for\n // the reason this file's own comment gives about `hiddenAt`: this is the\n // one function every realm consumer funnels through, and a control that has\n // to be remembered per consumer is one that will be missed by the next one.\n const revocation = revocationSnapshot.data() as PluginRevocation | undefined\n if (isPluginRevoked(revocation, version)) return null\n const hostAbi = Number(data.manifest?.hostAbi)\n // Where the loaders may run this version (AGL-3116), from the manifest it\n // was published and reviewed with. A block that does not read is treated\n // as absent, so the documented default applies rather than \"nowhere\".\n const contributes = readPluginContributions(data.manifest?.contributes)\n const pluginId =\n typeof data.manifest?.id === 'string' && data.manifest.id\n ? String(data.manifest.id)\n : undefined\n // The namespace these bytes were published under (AGL-3390), which the\n // loaders hold every registration to. Absent on a version published before\n // identities existed, and such a version never server-renders.\n const identity =\n typeof data.identity === 'string' && data.identity\n ? String(data.identity)\n : undefined\n return {\n sha256: String(data.sha256),\n ...(data.signature ? { signature: String(data.signature) } : {}),\n ...(data.trust ? { trust: String(data.trust) } : {}),\n ...(Number.isInteger(hostAbi) && hostAbi > 0 ? { hostAbi } : {}),\n ...(pluginId ? { pluginId } : {}),\n ...(identity ? { identity } : {}),\n ...(contributes ? { contributes } : {}),\n }\n}\n\n/**\n * SECURITY-RELEVANT CACHE (AGL-1302, AGL-4121): the join drops revoked,\n * taken-down, untrusted and switched-off versions, so this entry decides which\n * plugins a published site loads.\n *\n * It is no longer bounded by its TTL. Every write that changes the answer\n * expires it, and every page that read it, the moment it lands, through the\n * plugin tags (`tenantPluginGateTags`), which the tenant expires with\n * `{ expire: 0 }` rather than stale-while-revalidate:\n *\n * - a site's set (an install, an uninstall, a version re-pin, a workspace\n * switchboard toggle, a plan move) expires `tenant-plugins:{hostId}` for each\n * site it reaches;\n * - a platform event (a takedown, a revoked version, realm trust withdrawn or\n * rejected away) expires `tenant-plugins` on every site at once.\n *\n * Each of those is staged in the publish outbox BEFORE it is sent, so a\n * refused call is retried by the console's drain, and an alert is raised when\n * neither the call nor the outbox entry landed. That is what lets the TTL be\n * the platform backstop rather than five minutes: at 300s this one read held\n * every full page on a five-minute window (#2459). Only the HOST-scoped call\n * (the tenant render path) is cached; the console's org-scoped call stays\n * fresh so an install shows up in the workspace the moment it lands.\n */\nexport const REALM_PLUGIN_INSTALLS_TTL_SECONDS = TENANT_CACHE_BACKSTOP_SECONDS\n\nexport async function getRealmPluginInstalls(options: {\n orgId?: string\n hostId?: string\n}): Promise<RealmPluginInstall[]> {\n const hostId = options.hostId\n if (!hostId || options.orgId) return resolveRealmPluginInstalls(options)\n try {\n return await withRenderCache({\n key: ['tenant-realm-plugins', hostId],\n revalidate: REALM_PLUGIN_INSTALLS_TTL_SECONDS,\n tags: tenantPluginGateTags(hostId),\n read: () => resolveRealmPluginInstalls(options),\n })\n } catch (error) {\n console.error(error)\n return resolveRealmPluginInstalls(options)\n }\n}\n\nasync function resolveRealmPluginInstalls(options: {\n orgId?: string\n hostId?: string\n}): Promise<RealmPluginInstall[]> {\n const firestore = firebaseAdmin.app().firestore()\n const orgId =\n options.orgId ??\n (options.hostId ? await resolveOrgIdForHost(options.hostId) : null)\n\n // Switchboard gate (AGL-424): a workspace with an EXPLICIT\n // `enabledPlugins` list only realm-loads listings on it (install sync\n // keeps the list in step; toggling one off disables it without\n // uninstalling). Absent field = default-open, so pre-switchboard\n // installs keep loading.\n //\n // Masked to that one field (AGL-4121): the org document is among the largest\n // the tenant reads, and this is the only field the join uses from it.\n let enabledFilter: readonly string[] | null = null\n if (orgId) {\n const [org] = await firestore.getAll(firestore.collection('orgs').doc(orgId), {\n fieldMask: ['enabledPlugins'],\n })\n const configured = org?.get('enabledPlugins')\n if (Array.isArray(configured)) enabledFilter = configured.map(String)\n }\n\n const pins = new Map<string, InstallPin>()\n const collect = async (\n ref: FirebaseFirestore.CollectionReference,\n ): Promise<void> => {\n // Only the pin's `version` is used; an install doc carries its manifest\n // copy too, so the rest is projected away (AGL-4121).\n const snapshot = await ref.select('version').get()\n for (const doc of snapshot.docs) {\n const version = doc.get('version')\n if (typeof version === 'string' && version) {\n pins.set(doc.id, { listingId: doc.id, version })\n }\n }\n }\n if (orgId) {\n await collect(firestore.collection('orgs').doc(orgId).collection('installs'))\n }\n if (options.hostId) {\n // Host pins win over org pins for the same listing (more specific).\n await collect(\n firestore.collection('hosts').doc(options.hostId).collection('installs'),\n )\n }\n if (enabledFilter) {\n for (const listingId of [...pins.keys()]) {\n if (!enabledFilter.includes(listingId)) pins.delete(listingId)\n }\n }\n if (!pins.size) return []\n\n const installs = await Promise.all(\n [...pins.values()].map(async (pin): Promise<RealmPluginInstall | null> => {\n const pinned = await resolveMarketplacePluginVersion(\n pin.listingId,\n pin.version,\n )\n // The revocation check moved INTO `resolveMarketplacePluginVersion`\n // (AGL-2307) so the remote-server loader — which resolves through that\n // function and never reaches this join — gets it too. A `null` here\n // therefore already means \"taken down, unknown, or killed\".\n if (!pinned || pinned.trust !== 'realm' || !pinned.signature) return null\n return {\n listingId: pin.listingId,\n version: pin.version,\n sha256: pinned.sha256,\n trust: 'realm',\n signature: pinned.signature,\n ...(pinned.hostAbi !== undefined ? { hostAbi: pinned.hostAbi } : {}),\n ...(pinned.pluginId ? { pluginId: pinned.pluginId } : {}),\n ...(pinned.identity ? { identity: pinned.identity } : {}),\n ...(pinned.contributes ? { contributes: pinned.contributes } : {}),\n }\n }),\n )\n return installs.filter((install): install is RealmPluginInstall =>\n Boolean(install),\n )\n}\n"],"names":["getPluginConfigSchema","isPluginRevoked","mergePluginConfig","readPluginContributions","resolvePluginConfig","PLUGIN_DISTRIBUTION","firebaseAdmin","resolveOrgIdForHost","TENANT_CACHE_BACKSTOP_SECONDS","tenantPluginGateTags","withRenderCache","readPluginSettings","scope","scopeId","pluginId","app","firestore","collection","doc","get","data","undefined","getPluginConfig","orgId","options","schema","hostId","org","host","Promise","all","resolveMarketplacePluginVersion","listingId","version","distribution","listingRef","listings","listing","snapshot","revocationSnapshot","versions","revocations","sha256","revocation","hostAbi","Number","manifest","contributes","id","String","identity","signature","trust","isInteger","REALM_PLUGIN_INSTALLS_TTL_SECONDS","getRealmPluginInstalls","resolveRealmPluginInstalls","key","revalidate","tags","read","error","console","enabledFilter","getAll","fieldMask","configured","Array","isArray","map","pins","Map","collect","ref","select","docs","set","keys","includes","delete","size","installs","values","pin","pinned","filter","install","Boolean"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,eAAe,EACfC,iBAAiB,EACjBC,uBAAuB,EACvBC,mBAAmB,QAId,sBAAqB;AAC5B,SAASC,mBAAmB,QAAQ,kDAAiD;AACrF,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,mBAAmB,QAAQ,qBAAiB;AACrD,SACEC,6BAA6B,EAC7BC,oBAAoB,EACpBC,eAAe,QACV,qBAAiB;AAExB;;;;;;;CAOC,GACD,eAAeC,mBACbC,KAAuB,EACvBC,OAAe,EACfC,QAAgB;IAEhB,IAAI;QACF,OAAO,AACL,CAAA,MAAMR,cACHS,GAAG,GACHC,SAAS,GACTC,U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WAAW,MAAMpD,QAAQC,GAAG,CAChC;WAAIwC,KAAKY,MAAM;KAAG,CAACb,GAAG,CAAC,OAAOc;QAC5B,MAAMC,SAAS,MAAMrD,gCACnBoD,IAAInD,SAAS,EACbmD,IAAIlD,OAAO;QAEb,oEAAoE;QACpE,uEAAuE;QACvE,oEAAoE;QACpE,4DAA4D;QAC5D,IAAI,CAACmD,UAAUA,OAAOhC,KAAK,KAAK,WAAW,CAACgC,OAAOjC,SAAS,EAAE,OAAO;QACrE,OAAO;YACLnB,WAAWmD,IAAInD,SAAS;YACxBC,SAASkD,IAAIlD,OAAO;YACpBS,QAAQ0C,OAAO1C,MAAM;YACrBU,OAAO;YACPD,WAAWiC,OAAOjC,SAAS;WACvBiC,OAAOxC,OAAO,KAAKvB,YAAY;YAAEuB,SAASwC,OAAOxC,OAAO;QAAC,IAAI,CAAC,GAC9DwC,OAAOtE,QAAQ,GAAG;YAAEA,UAAUsE,OAAOtE,QAAQ;QAAC,IAAI,CAAC,GACnDsE,OAAOlC,QAAQ,GAAG;YAAEA,UAAUkC,OAAOlC,QAAQ;QAAC,IAAI,CAAC,GACnDkC,OAAOrC,WAAW,GAAG;YAAEA,aAAaqC,OAAOrC,WAAW;QAAC,IAAI,CAAC;IAEpE;IAEF,OAAOkC,SAASI,MAAM,CAAC,CAACC,UACtBC,QAAQD;AAEZ"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/realm-plugins.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 {\n getPluginConfigSchema,\n isPluginRevoked,\n mergePluginConfig,\n readPluginContributions,\n resolvePluginConfig,\n type PluginContributions,\n type PluginRevocation,\n type RealmPluginInstall,\n} from '@aglyn/aglyn/server'\nimport { PLUGIN_DISTRIBUTION } from '@aglyn/aglyn/plugin-manager/plugin-distribution'\nimport { firebaseAdmin } from './firebase-admin'\nimport { resolveOrgIdForHost } from './organizations'\nimport {\n TENANT_CACHE_BACKSTOP_SECONDS,\n tenantPluginGateTags,\n withRenderCache,\n} from '../render-cache'\n\n/**\n * One `pluginSettings` document, or `undefined` if it cannot be read.\n *\n * A failed read degrades to \"no answer at this level\" rather than throwing,\n * so a transient Firestore error costs a handler its overrides and not its\n * request. The caller layers what comes back, so a missing site document and\n * a missing site override are the same thing to it.\n */\nasync function readPluginSettings(\n scope: 'orgs' | 'hosts',\n scopeId: string,\n pluginId: string,\n): Promise<Record<string, unknown> | undefined> {\n try {\n return (\n await firebaseAdmin\n .app()\n .firestore()\n .collection(scope)\n .doc(scopeId)\n .collection('pluginSettings')\n .doc(pluginId)\n .get()\n ).data()\n } catch {\n return undefined\n }\n}\n\n/**\n * Server-side plugin config read (AGL-428): the stored overrides merged over\n * the plugin's declared defaults (type-coerced — the docs are\n * manager-writable). Without a registered schema the raw doc (or {}) comes\n * back, so handlers degrade to their own fallbacks.\n *\n * `hostId` resolves the SITE's answer on top of the workspace's (AGL-428,\n * AGL-1014), and a handler that has one must pass it. A per-site setting the console can\n * store and the server never reads is not a setting: the operator lowers the\n * flagship branch's booking horizon, the console shows the number they typed,\n * and `/api/bookings/slots` keeps offering the workspace's — a disagreement\n * with no error and no surface that shows both sides.\n *\n * The site read is CONDITIONAL on being handed a host, so a request with no\n * site in scope pays nothing for a document that could not apply to it. It\n * runs alongside the org read rather than after it: the two documents are\n * independent, and sequencing them would put a second serial round trip on\n * every request that resolves config.\n */\nexport async function getPluginConfig(\n orgId: string | null | undefined,\n pluginId: string,\n options: { hostId?: string | null } = {},\n): Promise<Record<string, unknown>> {\n const schema = getPluginConfigSchema(pluginId)\n const hostId = options.hostId\n if (!orgId && !hostId) return schema ? mergePluginConfig(schema, null) : {}\n const [org, host] = await Promise.all([\n orgId ? readPluginSettings('orgs', orgId, pluginId) : undefined,\n hostId ? readPluginSettings('hosts', hostId, pluginId) : undefined,\n ])\n // Coercion happens once, at the end, inside `resolvePluginConfig` — a\n // malformed site value falls back to the WORKSPACE value it was trying to\n // replace rather than skipping past it to the schema default.\n if (schema) return resolvePluginConfig(schema, { org, host })\n // No schema: there is no field list to layer by, so the site document\n // simply narrows the workspace's, key for key.\n return { ...(org ?? {}), ...(host ?? {}) }\n}\n\n/**\n * Server-side resolution of a workspace's TRUSTED-REALM plugin installs\n * (AGL-420). Install docs pin `{version, sha256}`, but the trust grant\n * (`trust: 'realm'` + the platform Ed25519 `signature`) lives on the\n * server-only version doc — staff sign AFTER review, possibly long after\n * the install — so this join is the single source the loaders consume:\n *\n * 1. Read the org's installs (and the host's, when a host is in scope).\n * When a host is in scope, drop every listing that site's own Admin ›\n * Plugins switch turned off (its `disabledPlugins`, AGL-4047), the same\n * deny-list `resolveHostEnabledPlugins` subtracts for a built-in plugin.\n * 2. Join each pin with its version document, in the store the\n * distributing plugin declares (`PLUGIN_DISTRIBUTION`, AGL-3080 — the\n * marketplace's listings today); only versions carrying `trust: 'realm'`\n * survive.\n * 3. Drop revoked versions (the kill switch keyed by the listing id) — a\n * revocation beats a still-present trust grant.\n * 4. Drop hidden listings (AGL-948) — `resolveMarketplacePluginVersion`\n * returns null for a listing under staff takedown. `deletedAt` is not\n * a blocker; see that function for why the two differ.\n *\n * The returned sha256/signature come from the VERSION doc, not the install\n * copy, so a tampered install doc cannot smuggle different bytes past the\n * loader's content check.\n */\n\ninterface InstallPin {\n listingId: string\n version: string\n}\n\n/**\n * One version-doc read, shaped for the remote loaders' `resolveVersion`.\n *\n * Also the staff-takedown gate (AGL-948): a listing carrying `hiddenAt`\n * resolves to null, so an already-installed plugin stops loading the\n * moment staff hide it. Takedown used to only de-list — a plugin pulled\n * for abuse kept executing in every workspace that had installed it until\n * someone separately wrote a revocation. It lives HERE rather than in the\n * join because every remote path funnels through this function: the\n * console and site realm joins, and both apps' remote-server-bundle\n * loaders.\n *\n * `deletedAt` is deliberately NOT a blocker. A publisher retiring a\n * listing must not break the sites already paying for it; unpublish\n * blocks new installs (`install-plugin`) and that is all it means.\n */\nexport async function resolveMarketplacePluginVersion(\n listingId: string,\n version: string,\n): Promise<{\n sha256: string\n signature?: string\n trust?: string\n hostAbi?: number\n pluginId?: string\n identity?: string\n contributes?: PluginContributions\n} | null> {\n // No distributing plugin declared a store: nothing can be vouched for, so\n // nothing resolves (see `plugin-distribution.ts` — absent is closed).\n const distribution = PLUGIN_DISTRIBUTION\n if (!distribution) return null\n const firestore = firebaseAdmin.app().firestore()\n const listingRef = firestore.collection(distribution.listings).doc(listingId)\n // THE REVOCATION READ IS IN THIS `Promise.all`, NOT AFTER IT (2026-08-26).\n //\n // It is keyed on `listingId` alone, so it never depended on the two reads\n // above — awaiting it below them cost a SECOND sequential Firestore round\n // trip on every resolution, and `resolveRealmPluginInstalls` calls this\n // once per pinned install. That is the shape that grows with the number of\n // plugins an org has installed: `/api/orgs/realm-plugins` is deliberately\n // uncached (see the TTL note below), and at a P75 of 907ms it was already\n // the slowest org-scoped console route before anyone uploaded in volume.\n //\n // The trade is one extra read on the paths that exit early (a hidden\n // listing, a missing version doc) in exchange for halving the round trips\n // on the path that actually happens. The kill switch is UNCHANGED: the\n // check below still runs before any value is returned, and it still reads\n // live — this moves when the read is issued, never whether it is honored.\n const [listing, snapshot, revocationSnapshot] = await Promise.all([\n listingRef.get(),\n listingRef.collection(distribution.versions).doc(version).get(),\n firestore.collection(distribution.revocations).doc(listingId).get(),\n ])\n // A missing listing doc is NOT a blocker: Firestore does not cascade to\n // subcollections, so a hard-deleted listing leaves working installs\n // resolving off an orphaned version doc. Only an explicit takedown stops\n // them.\n if (listing.get('hiddenAt')) return null\n const data = snapshot.data()\n if (!data?.sha256) return null\n // THE KILL SWITCH BELONGS AT THE CHOKEPOINT (AGL-2307).\n //\n // It used to live one level up, in `resolveRealmPluginInstalls` — which is\n // the path the tenant render and the console gate take, and NOT the path\n // remote SERVER bundles take. `loadRemoteServerBundles` resolves through\n // this function and nothing else, so a per-version revocation left a realm\n // server handler running: `hiddenAt` caught a full takedown, but a targeted\n // revocation deliberately does not hide the listing, which is the whole\n // difference between the two controls.\n //\n // Placed here rather than added as a second copy at the server loader, for\n // the reason this file's own comment gives about `hiddenAt`: this is the\n // one function every realm consumer funnels through, and a control that has\n // to be remembered per consumer is one that will be missed by the next one.\n const revocation = revocationSnapshot.data() as PluginRevocation | undefined\n if (isPluginRevoked(revocation, version)) return null\n const hostAbi = Number(data.manifest?.hostAbi)\n // Where the loaders may run this version (AGL-3116), from the manifest it\n // was published and reviewed with. A block that does not read is treated\n // as absent, so the documented default applies rather than \"nowhere\".\n const contributes = readPluginContributions(data.manifest?.contributes)\n const pluginId =\n typeof data.manifest?.id === 'string' && data.manifest.id\n ? String(data.manifest.id)\n : undefined\n // The namespace these bytes were published under (AGL-3390), which the\n // loaders hold every registration to. Absent on a version published before\n // identities existed, and such a version never server-renders.\n const identity =\n typeof data.identity === 'string' && data.identity\n ? String(data.identity)\n : undefined\n return {\n sha256: String(data.sha256),\n ...(data.signature ? { signature: String(data.signature) } : {}),\n ...(data.trust ? { trust: String(data.trust) } : {}),\n ...(Number.isInteger(hostAbi) && hostAbi > 0 ? { hostAbi } : {}),\n ...(pluginId ? { pluginId } : {}),\n ...(identity ? { identity } : {}),\n ...(contributes ? { contributes } : {}),\n }\n}\n\n/**\n * SECURITY-RELEVANT CACHE (AGL-1302, AGL-4121): the join drops revoked,\n * taken-down, untrusted and switched-off versions, so this entry decides which\n * plugins a published site loads.\n *\n * It is no longer bounded by its TTL. Every write that changes the answer\n * expires it, and every page that read it, the moment it lands, through the\n * plugin tags (`tenantPluginGateTags`), which the tenant expires with\n * `{ expire: 0 }` rather than stale-while-revalidate:\n *\n * - a site's set (an install, an uninstall, a version re-pin, a workspace\n * switchboard toggle, a plan move) expires `tenant-plugins:{hostId}` for each\n * site it reaches;\n * - a platform event (a takedown, a revoked version, realm trust withdrawn or\n * rejected away) expires `tenant-plugins` on every site at once;\n * - a site's own Admin › Plugins switch (AGL-4047) writes `disabledPlugins` on\n * the host document, a rendered field, so the console drops the whole site\n * and with it `tenant-data:{hostId}`, which this entry carries too\n * (`tenantPluginGateTags`).\n *\n * Each of those is staged in the publish outbox BEFORE it is sent, so a\n * refused call is retried by the console's drain, and an alert is raised when\n * neither the call nor the outbox entry landed. That is what lets the TTL be\n * the platform backstop rather than five minutes: at 300s this one read held\n * every full page on a five-minute window (#2459). Only the HOST-scoped call\n * (the tenant render path) is cached; the console's org-scoped call stays\n * fresh so an install shows up in the workspace the moment it lands.\n */\nexport const REALM_PLUGIN_INSTALLS_TTL_SECONDS = TENANT_CACHE_BACKSTOP_SECONDS\n\nexport async function getRealmPluginInstalls(options: {\n orgId?: string\n hostId?: string\n}): Promise<RealmPluginInstall[]> {\n const hostId = options.hostId\n if (!hostId || options.orgId) return resolveRealmPluginInstalls(options)\n try {\n return await withRenderCache({\n key: ['tenant-realm-plugins', hostId],\n revalidate: REALM_PLUGIN_INSTALLS_TTL_SECONDS,\n tags: tenantPluginGateTags(hostId),\n read: () => resolveRealmPluginInstalls(options),\n })\n } catch (error) {\n console.error(error)\n return resolveRealmPluginInstalls(options)\n }\n}\n\n/**\n * The listings ONE site switched off on its Admin › Plugins page (AGL-4047).\n *\n * The site switch writes a marketplace plugin's listing id into the host's\n * `disabledPlugins`, beside the built-in ids it holds. The built-in half was\n * always honored (`resolveHostEnabledPlugins`); this join read only the\n * workspace's list, so a marketplace plugin a site switched off kept loading on\n * its published pages and kept binding its functions there.\n *\n * Masked to that one field, as the org read below is: the host document is the\n * largest one a site has. Issued alongside the org resolution, so it adds a\n * read to a cache miss and no round trip to it. A read that fails rejects the\n * join, which every caller already answers as \"no marketplace plugins\", so a\n * failure can never run a plugin the site turned off.\n */\nasync function readSiteDisabledListings(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<ReadonlySet<string>> {\n const [host] = await firestore.getAll(firestore.collection('hosts').doc(hostId), {\n fieldMask: ['disabledPlugins'],\n })\n const disabled = host?.get('disabledPlugins')\n return new Set(Array.isArray(disabled) ? disabled.map(String) : [])\n}\n\nasync function resolveRealmPluginInstalls(options: {\n orgId?: string\n hostId?: string\n}): Promise<RealmPluginInstall[]> {\n const firestore = firebaseAdmin.app().firestore()\n // Started first and awaited last: it depends on nothing the org hop reads.\n const siteDisabled = options.hostId\n ? readSiteDisabledListings(firestore, options.hostId)\n : null\n // Marked handled now, consumed below: a rejection must not sit unobserved\n // while the org hop is awaited.\n siteDisabled?.catch(() => undefined)\n const orgId =\n options.orgId ??\n (options.hostId ? await resolveOrgIdForHost(options.hostId) : null)\n\n // Switchboard gate (AGL-424): a workspace with an EXPLICIT\n // `enabledPlugins` list only realm-loads listings on it (install sync\n // keeps the list in step; toggling one off disables it without\n // uninstalling). Absent field = default-open, so pre-switchboard\n // installs keep loading.\n //\n // Masked to that one field (AGL-4121): the org document is among the largest\n // the tenant reads, and this is the only field the join uses from it.\n let enabledFilter: readonly string[] | null = null\n if (orgId) {\n const [org] = await firestore.getAll(firestore.collection('orgs').doc(orgId), {\n fieldMask: ['enabledPlugins'],\n })\n const configured = org?.get('enabledPlugins')\n if (Array.isArray(configured)) enabledFilter = configured.map(String)\n }\n\n const pins = new Map<string, InstallPin>()\n const collect = async (\n ref: FirebaseFirestore.CollectionReference,\n ): Promise<void> => {\n // Only the pin's `version` is used; an install doc carries its manifest\n // copy too, so the rest is projected away (AGL-4121).\n const snapshot = await ref.select('version').get()\n for (const doc of snapshot.docs) {\n const version = doc.get('version')\n if (typeof version === 'string' && version) {\n pins.set(doc.id, { listingId: doc.id, version })\n }\n }\n }\n if (orgId) {\n await collect(firestore.collection('orgs').doc(orgId).collection('installs'))\n }\n if (options.hostId) {\n // Host pins win over org pins for the same listing (more specific).\n await collect(\n firestore.collection('hosts').doc(options.hostId).collection('installs'),\n )\n }\n if (enabledFilter) {\n for (const listingId of [...pins.keys()]) {\n if (!enabledFilter.includes(listingId)) pins.delete(listingId)\n }\n }\n // The site's own switch, after the workspace's (AGL-4047). A site can only\n // narrow: it switches off what the workspace runs, never on what it does\n // not. It covers the site's own pins too; the switch is the site's answer\n // for that listing, wherever the pin lives.\n if (siteDisabled) {\n const disabled = await siteDisabled\n for (const listingId of [...pins.keys()]) {\n if (disabled.has(listingId)) pins.delete(listingId)\n }\n }\n if (!pins.size) return []\n\n const installs = await Promise.all(\n [...pins.values()].map(async (pin): Promise<RealmPluginInstall | null> => {\n const pinned = await resolveMarketplacePluginVersion(\n pin.listingId,\n pin.version,\n )\n // The revocation check moved INTO `resolveMarketplacePluginVersion`\n // (AGL-2307) so the remote-server loader — which resolves through that\n // function and never reaches this join — gets it too. A `null` here\n // therefore already means \"taken down, unknown, or killed\".\n if (!pinned || pinned.trust !== 'realm' || !pinned.signature) return null\n return {\n listingId: pin.listingId,\n version: pin.version,\n sha256: pinned.sha256,\n trust: 'realm',\n signature: pinned.signature,\n ...(pinned.hostAbi !== undefined ? { hostAbi: pinned.hostAbi } : {}),\n ...(pinned.pluginId ? { pluginId: pinned.pluginId } : {}),\n ...(pinned.identity ? { identity: pinned.identity } : {}),\n ...(pinned.contributes ? { contributes: pinned.contributes } : {}),\n }\n }),\n )\n return installs.filter((install): install is RealmPluginInstall =>\n Boolean(install),\n )\n}\n"],"names":["getPluginConfigSchema","isPluginRevoked","mergePluginConfig","readPluginContributions","resolvePluginConfig","PLUGIN_DISTRIBUTION","firebaseAdmin","resolveOrgIdForHost","TENANT_CACHE_BACKSTOP_SECONDS","tenantPluginGateTags","withRenderCache","readPluginSettings","scope","scopeId","pluginId","app","firestore","collection","doc","get","data","undefined","getPluginConfig","orgId","options","schema","hostId","org","host","Promise","all","resolveMarketplacePluginVersion","listingId","version","distribution","listingRef","listings","listing","snapshot","revocationSnapshot","versions","revocations","sha256","revocation","hostAbi","Number","manifest","contributes","id","String","identity","signature","trust","isInteger","REALM_PLUGIN_INSTALLS_TTL_SECONDS","getRealmPluginInstalls","resolveRealmPluginInstalls","key","revalidate","tags","read","error","console","readSiteDisabledListings","getAll","fieldMask","disabled","Set","Array","isArray","map","siteDisabled","catch","enabledFilter","configured","pins","Map","collect","ref","select","docs","set","keys","includes","delete","has","size","installs","values","pin","pinned","filter","install","Boolean"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,eAAe,EACfC,iBAAiB,EACjBC,uBAAuB,EACvBC,mBAAmB,QAId,sBAAqB;AAC5B,SAASC,mBAAmB,QAAQ,kDAAiD;AACrF,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,mBAAmB,QAAQ,qBAAiB;AACrD,SACEC,6BAA6B,EAC7BC,oBAAoB,EACpBC,eAAe,QACV,qBAAiB;AAExB;;;;;;;CAOC,GACD,eAAeC,mBACbC,KAAuB,EACvBC,OAAe,EACfC,QAAgB;IAEhB,IAAI;QACF,OAAO,AACL,CAAA,MAAMR,cACHS,GAAG,GACHC,SAAS,GACTC,UAAU,CAACL,OACXM,GAAG,CAACL,SACJI,UAAU,CAAC,kBACXC,GAAG,CAACJ,UACJK,GAAG,EAAC,EACPC,IAAI;IACR,EAAE,eAAM;QACN,OAAOC;IACT;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,eAAeC,gBACpBC,KAAgC,EAChCT,QAAgB,EAChBU,UAAsC,CAAC,CAAC;IAExC,MAAMC,SAASzB,sBAAsBc;IACrC,MAAMY,SAASF,QAAQE,MAAM;IAC7B,IAAI,CAACH,SAAS,CAACG,QAAQ,OAAOD,SAASvB,kBAAkBuB,QAAQ,QAAQ,CAAC;IAC1E,MAAM,CAACE,KAAKC,KAAK,GAAG,MAAMC,QAAQC,GAAG,CAAC;QACpCP,QAAQZ,mBAAmB,QAAQY,OAAOT,YAAYO;QAC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0EAA0E;IAC1E,4CAA4C;IAC5C,IAAIuC,cAAc;QAChB,MAAML,WAAW,MAAMK;QACvB,KAAK,MAAMvC,aAAa;eAAI2C,KAAKO,IAAI;SAAG,CAAE;YACxC,IAAIhB,SAASmB,GAAG,CAACrD,YAAY2C,KAAKS,MAAM,CAACpD;QAC3C;IACF;IACA,IAAI,CAAC2C,KAAKW,IAAI,EAAE,OAAO,EAAE;IAEzB,MAAMC,WAAW,MAAM1D,QAAQC,GAAG,CAChC;WAAI6C,KAAKa,MAAM;KAAG,CAAClB,GAAG,CAAC,OAAOmB;QAC5B,MAAMC,SAAS,MAAM3D,gCACnB0D,IAAIzD,SAAS,EACbyD,IAAIxD,OAAO;QAEb,oEAAoE;QACpE,uEAAuE;QACvE,oEAAoE;QACpE,4DAA4D;QAC5D,IAAI,CAACyD,UAAUA,OAAOtC,KAAK,KAAK,WAAW,CAACsC,OAAOvC,SAAS,EAAE,OAAO;QACrE,OAAO;YACLnB,WAAWyD,IAAIzD,SAAS;YACxBC,SAASwD,IAAIxD,OAAO;YACpBS,QAAQgD,OAAOhD,MAAM;YACrBU,OAAO;YACPD,WAAWuC,OAAOvC,SAAS;WACvBuC,OAAO9C,OAAO,KAAKvB,YAAY;YAAEuB,SAAS8C,OAAO9C,OAAO;QAAC,IAAI,CAAC,GAC9D8C,OAAO5E,QAAQ,GAAG;YAAEA,UAAU4E,OAAO5E,QAAQ;QAAC,IAAI,CAAC,GACnD4E,OAAOxC,QAAQ,GAAG;YAAEA,UAAUwC,OAAOxC,QAAQ;QAAC,IAAI,CAAC,GACnDwC,OAAO3C,WAAW,GAAG;YAAEA,aAAa2C,OAAO3C,WAAW;QAAC,IAAI,CAAC;IAEpE;IAEF,OAAOwC,SAASI,MAAM,CAAC,CAACC,UACtBC,QAAQD;AAEZ"}
@@ -49,7 +49,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
49
49
  */ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
50
50
  import { reconcileAllExcept, SCOPE_MODE_ALL_EXCEPT } from "@aglyn/aglyn/app-utils/scope-tokens";
51
51
  import { runPluginDeclarationsRepair } from "@aglyn/aglyn/plugin-manager/plugin-declarations-repair";
52
- import { listScopeSharingCollections, scopeSharingPatchFor } from "@aglyn/aglyn/plugin-manager/plugin-scope-sharing";
52
+ import { listScopeSharingCollections, listScopeSharingSiteChangeHooks, scopeSharingPatchFor } from "@aglyn/aglyn/plugin-manager/plugin-scope-sharing";
53
53
  import { FieldPath, FieldValue } from "firebase-admin/firestore";
54
54
  import firebaseAdmin from "./firebase-admin.js";
55
55
  /** Where a sweep with work left records its cursor. */ export const SCOPE_SWEEPS_COLLECTION = 'scopeSweeps';
@@ -273,6 +273,28 @@ function requiredPatch(collection) {
273
273
  console.error(`[scope-sweep] could not leave ${orgId}'s sweep for the job`, writeError);
274
274
  });
275
275
  }
276
+ await runSiteChangeHooks(_extends({
277
+ orgId,
278
+ reason
279
+ }, hostId ? {
280
+ hostId
281
+ } : {}));
282
+ }
283
+ /**
284
+ * The plugins' own share of a site change (`registerPluginScopeSharingSiteChange`):
285
+ * sharing kept somewhere the sweep does not walk, such as the CRM's grants.
286
+ * Each gets {@link INLINE_BUDGET_MS} and finishes the rest itself. Never throws.
287
+ * A hook registers with its plugin's server declarations, at boot.
288
+ */ async function runSiteChangeHooks(input) {
289
+ for (const { pluginId, hook } of listScopeSharingSiteChangeHooks()){
290
+ try {
291
+ await hook(_extends({}, input, {
292
+ budgetMs: INLINE_BUDGET_MS
293
+ }));
294
+ } catch (error) {
295
+ console.error(`[scope-sweep] ${pluginId}'s site-change hook failed for ${input.orgId}`, error);
296
+ }
297
+ }
276
298
  }
277
299
  /**
278
300
  * Carries on every unfinished sweep: the job's handler. A sweep document exists