@aglyn/tenant-data-admin 1.15.1 → 1.16.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.
- package/package.json +7 -7
- package/src/lib/render-cache.d.ts +69 -2
- package/src/lib/render-cache.js +82 -2
- package/src/lib/render-cache.js.map +1 -1
- package/src/lib/server/realm-plugins.d.ts +25 -0
- package/src/lib/server/realm-plugins.js +37 -19
- package/src/lib/server/realm-plugins.js.map +1 -1
- package/src/lib/server/release-flags.d.ts +28 -0
- package/src/lib/server/release-flags.js +76 -18
- package/src/lib/server/release-flags.js.map +1 -1
- package/src/lib/server/seller-payment-account.d.ts +53 -0
- package/src/lib/server/seller-payment-account.js +43 -0
- package/src/lib/server/seller-payment-account.js.map +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-data-admin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-util-email": "1.
|
|
30
|
-
"@aglyn/shared-util-fbserver": "1.
|
|
31
|
-
"@aglyn/shared-util-first-touch": "1.
|
|
32
|
-
"@aglyn/shared-util-http": "1.
|
|
33
|
-
"@aglyn/shared-util-tools": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.16.0",
|
|
29
|
+
"@aglyn/shared-util-email": "1.16.0",
|
|
30
|
+
"@aglyn/shared-util-fbserver": "1.16.0",
|
|
31
|
+
"@aglyn/shared-util-first-touch": "1.16.0",
|
|
32
|
+
"@aglyn/shared-util-http": "1.16.0",
|
|
33
|
+
"@aglyn/shared-util-tools": "1.16.0",
|
|
34
34
|
"@msgpack/msgpack": "^3.1.3",
|
|
35
35
|
"@swc/helpers": "0.5.23",
|
|
36
36
|
"sharp": "^0.35.5",
|
|
@@ -66,10 +66,54 @@
|
|
|
66
66
|
* themselves.
|
|
67
67
|
*/
|
|
68
68
|
export declare const tenantDataTag: (hostId: string) => string;
|
|
69
|
+
/**
|
|
70
|
+
* THE BACKSTOP every tenant render-path read and the page itself share
|
|
71
|
+
* (AGL-4121): seven days.
|
|
72
|
+
*
|
|
73
|
+
* Freshness is change-driven. Every write that changes what a page shows
|
|
74
|
+
* drops it on demand, and the security-relevant drops (a plugin removed,
|
|
75
|
+
* disabled, taken down, revoked or untrusted) are staged in the publish
|
|
76
|
+
* outbox first, so a failed call is retried by the drain rather than left to
|
|
77
|
+
* this timer. The timer only bounds an unannounced direct Firestore edit.
|
|
78
|
+
*
|
|
79
|
+
* One number on purpose. Next lowers a page's window to the SHORTEST cached
|
|
80
|
+
* read its render makes (`unstable_cache` and `fetch` both shrink the work
|
|
81
|
+
* store's `revalidate`), so a single read left on a shorter TTL quietly
|
|
82
|
+
* becomes the page's window — exactly what kept #2459's one-day page on five
|
|
83
|
+
* minutes. `tenant-page-window.spec.ts` sweeps the render path for that.
|
|
84
|
+
*/
|
|
85
|
+
export declare const TENANT_CACHE_BACKSTOP_SECONDS = 604800;
|
|
86
|
+
/**
|
|
87
|
+
* Every cached read that decides WHICH PLUGINS a site may load — the signed
|
|
88
|
+
* realm installs, the pinned installs with their kill-switch state, and the
|
|
89
|
+
* image hosts those plugins declare — carries these tags beside
|
|
90
|
+
* `tenantDataTag` (AGL-4121), and so does every page whose render read one.
|
|
91
|
+
*
|
|
92
|
+
* - `tenantPluginsTag(hostId)`: one site's plugin set changed (an uninstall,
|
|
93
|
+
* a switchboard toggle, a plan move).
|
|
94
|
+
* - `TENANT_PLUGINS_TAG`: a platform event changed it for every site at once
|
|
95
|
+
* (a takedown, a revoked version, realm trust withdrawn). One tag bust
|
|
96
|
+
* reaches every affected site with no host walk and no fan-out cap.
|
|
97
|
+
*
|
|
98
|
+
* The tenant's `/api/revalidate` expires both with `{ expire: 0 }`, not the
|
|
99
|
+
* stale-while-revalidate `'max'` the data tag takes: a removed plugin must
|
|
100
|
+
* not run for even one more visitor.
|
|
101
|
+
*/
|
|
102
|
+
export declare const TENANT_PLUGINS_TAG = "tenant-plugins";
|
|
103
|
+
export declare const tenantPluginsTag: (hostId: string) => string;
|
|
104
|
+
/** The full tag set for a read that decides which plugins load on a site. */
|
|
105
|
+
export declare const tenantPluginGateTags: (hostId: string) => string[];
|
|
69
106
|
/**
|
|
70
107
|
* The backstop TTL for published site data — every read that
|
|
71
108
|
* `revalidateTag(tenantDataTag(hostId))` busts on publish.
|
|
72
109
|
*
|
|
110
|
+
* ## Seven days (AGL-4121)
|
|
111
|
+
*
|
|
112
|
+
* The hour below became the backstop once every product write announced
|
|
113
|
+
* itself; AGL-4121 audited the remaining unannounced writers (shopper stock
|
|
114
|
+
* and reviews, the plugin switchboard, realm trust) and wired them, so the
|
|
115
|
+
* hour is now {@link TENANT_CACHE_BACKSTOP_SECONDS}.
|
|
116
|
+
*
|
|
73
117
|
* WHY AN HOUR AND NOT A MINUTE (2026-08-26, from the Vercel cost review).
|
|
74
118
|
*
|
|
75
119
|
* Every cache in this layer shipped at 60s, and the page above them was
|
|
@@ -112,7 +156,7 @@ export declare const tenantDataTag: (hostId: string) => string;
|
|
|
112
156
|
* cache here and carries its own memo, which is what
|
|
113
157
|
* `lockdown-middleware-propagation.spec.ts` measures.
|
|
114
158
|
*/
|
|
115
|
-
export declare const PUBLISHED_SITE_DATA_TTL_SECONDS =
|
|
159
|
+
export declare const PUBLISHED_SITE_DATA_TTL_SECONDS = 604800;
|
|
116
160
|
/**
|
|
117
161
|
* The backstop for the one read a screen publish changes under an UNCHANGED
|
|
118
162
|
* cache key — the version pointer (AGL-2573).
|
|
@@ -153,8 +197,18 @@ export declare const PUBLISHED_SITE_DATA_TTL_SECONDS = 3600;
|
|
|
153
197
|
* one per hour — regenerations are already bounded by the ISR window, so the
|
|
154
198
|
* ceiling is the render rate and not the request rate. That is the price of
|
|
155
199
|
* the bound, and it is the cheapest read on the path.
|
|
200
|
+
*
|
|
201
|
+
* ## Equal to the page window again (AGL-4121)
|
|
202
|
+
*
|
|
203
|
+
* The reasoning above held while the pointer sat BELOW the page window. It
|
|
204
|
+
* stopped holding once AGL-4121 measured that a TTL read in the render lowers
|
|
205
|
+
* the page's own window to match: at 600s the pointer was what regenerated
|
|
206
|
+
* every page every ten minutes. The failure it bounded is now closed at the
|
|
207
|
+
* source instead — every pointer move rides the publish outbox (AGL-2575),
|
|
208
|
+
* whose drain retries a refused announce — so the pointer takes the backstop
|
|
209
|
+
* and stays exactly `<=` the page window, which the spec still enforces.
|
|
156
210
|
*/
|
|
157
|
-
export declare const PUBLISH_POINTER_TTL_SECONDS =
|
|
211
|
+
export declare const PUBLISH_POINTER_TTL_SECONDS = 604800;
|
|
158
212
|
/**
|
|
159
213
|
* The alias→hostId resolution is tagged separately because it is the one
|
|
160
214
|
* cache keyed BEFORE the hostId is known. It only changes on subdomain
|
|
@@ -189,3 +243,16 @@ export interface RenderCacheOptions<T> {
|
|
|
189
243
|
store?: (value: T) => boolean;
|
|
190
244
|
}
|
|
191
245
|
export declare function withRenderCache<T>(options: RenderCacheOptions<T>): Promise<T>;
|
|
246
|
+
/**
|
|
247
|
+
* Lowers the window of the page being rendered to `seconds`, and nothing
|
|
248
|
+
* else (AGL-4121).
|
|
249
|
+
*
|
|
250
|
+
* For the narrow cases where a page shows something that changes on a clock
|
|
251
|
+
* rather than on a write — a publish schedule that is still pending. Next
|
|
252
|
+
* takes the shortest `revalidate` any cached read made during a regeneration,
|
|
253
|
+
* so a tiny cached constant read with this TTL holds THAT page (and only
|
|
254
|
+
* that page) on the short window, while every other page keeps the backstop.
|
|
255
|
+
*
|
|
256
|
+
* Outside a Next render (jest, scripts) it is a no-op.
|
|
257
|
+
*/
|
|
258
|
+
export declare function capRenderWindow(seconds: number): Promise<void>;
|
package/src/lib/render-cache.js
CHANGED
|
@@ -64,10 +64,55 @@
|
|
|
64
64
|
* made it; the TTL is only the backstop for writes that never announce
|
|
65
65
|
* themselves.
|
|
66
66
|
*/ export const tenantDataTag = (hostId)=>`tenant-data:${hostId}`;
|
|
67
|
+
/**
|
|
68
|
+
* THE BACKSTOP every tenant render-path read and the page itself share
|
|
69
|
+
* (AGL-4121): seven days.
|
|
70
|
+
*
|
|
71
|
+
* Freshness is change-driven. Every write that changes what a page shows
|
|
72
|
+
* drops it on demand, and the security-relevant drops (a plugin removed,
|
|
73
|
+
* disabled, taken down, revoked or untrusted) are staged in the publish
|
|
74
|
+
* outbox first, so a failed call is retried by the drain rather than left to
|
|
75
|
+
* this timer. The timer only bounds an unannounced direct Firestore edit.
|
|
76
|
+
*
|
|
77
|
+
* One number on purpose. Next lowers a page's window to the SHORTEST cached
|
|
78
|
+
* read its render makes (`unstable_cache` and `fetch` both shrink the work
|
|
79
|
+
* store's `revalidate`), so a single read left on a shorter TTL quietly
|
|
80
|
+
* becomes the page's window — exactly what kept #2459's one-day page on five
|
|
81
|
+
* minutes. `tenant-page-window.spec.ts` sweeps the render path for that.
|
|
82
|
+
*/ export const TENANT_CACHE_BACKSTOP_SECONDS = 604800;
|
|
83
|
+
/**
|
|
84
|
+
* Every cached read that decides WHICH PLUGINS a site may load — the signed
|
|
85
|
+
* realm installs, the pinned installs with their kill-switch state, and the
|
|
86
|
+
* image hosts those plugins declare — carries these tags beside
|
|
87
|
+
* `tenantDataTag` (AGL-4121), and so does every page whose render read one.
|
|
88
|
+
*
|
|
89
|
+
* - `tenantPluginsTag(hostId)`: one site's plugin set changed (an uninstall,
|
|
90
|
+
* a switchboard toggle, a plan move).
|
|
91
|
+
* - `TENANT_PLUGINS_TAG`: a platform event changed it for every site at once
|
|
92
|
+
* (a takedown, a revoked version, realm trust withdrawn). One tag bust
|
|
93
|
+
* reaches every affected site with no host walk and no fan-out cap.
|
|
94
|
+
*
|
|
95
|
+
* The tenant's `/api/revalidate` expires both with `{ expire: 0 }`, not the
|
|
96
|
+
* stale-while-revalidate `'max'` the data tag takes: a removed plugin must
|
|
97
|
+
* not run for even one more visitor.
|
|
98
|
+
*/ export const TENANT_PLUGINS_TAG = 'tenant-plugins';
|
|
99
|
+
export const tenantPluginsTag = (hostId)=>`tenant-plugins:${hostId}`;
|
|
100
|
+
/** The full tag set for a read that decides which plugins load on a site. */ export const tenantPluginGateTags = (hostId)=>[
|
|
101
|
+
tenantDataTag(hostId),
|
|
102
|
+
tenantPluginsTag(hostId),
|
|
103
|
+
TENANT_PLUGINS_TAG
|
|
104
|
+
];
|
|
67
105
|
/**
|
|
68
106
|
* The backstop TTL for published site data — every read that
|
|
69
107
|
* `revalidateTag(tenantDataTag(hostId))` busts on publish.
|
|
70
108
|
*
|
|
109
|
+
* ## Seven days (AGL-4121)
|
|
110
|
+
*
|
|
111
|
+
* The hour below became the backstop once every product write announced
|
|
112
|
+
* itself; AGL-4121 audited the remaining unannounced writers (shopper stock
|
|
113
|
+
* and reviews, the plugin switchboard, realm trust) and wired them, so the
|
|
114
|
+
* hour is now {@link TENANT_CACHE_BACKSTOP_SECONDS}.
|
|
115
|
+
*
|
|
71
116
|
* WHY AN HOUR AND NOT A MINUTE (2026-08-26, from the Vercel cost review).
|
|
72
117
|
*
|
|
73
118
|
* Every cache in this layer shipped at 60s, and the page above them was
|
|
@@ -109,7 +154,7 @@
|
|
|
109
154
|
* Takedowns are unaffected either way: the middleware runs ahead of every
|
|
110
155
|
* cache here and carries its own memo, which is what
|
|
111
156
|
* `lockdown-middleware-propagation.spec.ts` measures.
|
|
112
|
-
*/ export const PUBLISHED_SITE_DATA_TTL_SECONDS =
|
|
157
|
+
*/ export const PUBLISHED_SITE_DATA_TTL_SECONDS = TENANT_CACHE_BACKSTOP_SECONDS;
|
|
113
158
|
/**
|
|
114
159
|
* The backstop for the one read a screen publish changes under an UNCHANGED
|
|
115
160
|
* cache key — the version pointer (AGL-2573).
|
|
@@ -150,7 +195,17 @@
|
|
|
150
195
|
* one per hour — regenerations are already bounded by the ISR window, so the
|
|
151
196
|
* ceiling is the render rate and not the request rate. That is the price of
|
|
152
197
|
* the bound, and it is the cheapest read on the path.
|
|
153
|
-
|
|
198
|
+
*
|
|
199
|
+
* ## Equal to the page window again (AGL-4121)
|
|
200
|
+
*
|
|
201
|
+
* The reasoning above held while the pointer sat BELOW the page window. It
|
|
202
|
+
* stopped holding once AGL-4121 measured that a TTL read in the render lowers
|
|
203
|
+
* the page's own window to match: at 600s the pointer was what regenerated
|
|
204
|
+
* every page every ten minutes. The failure it bounded is now closed at the
|
|
205
|
+
* source instead — every pointer move rides the publish outbox (AGL-2575),
|
|
206
|
+
* whose drain retries a refused announce — so the pointer takes the backstop
|
|
207
|
+
* and stays exactly `<=` the page window, which the spec still enforces.
|
|
208
|
+
*/ export const PUBLISH_POINTER_TTL_SECONDS = TENANT_CACHE_BACKSTOP_SECONDS;
|
|
154
209
|
/**
|
|
155
210
|
* The alias→hostId resolution is tagged separately because it is the one
|
|
156
211
|
* cache keyed BEFORE the hostId is known. It only changes on subdomain
|
|
@@ -201,5 +256,30 @@ export async function withRenderCache(options) {
|
|
|
201
256
|
throw error;
|
|
202
257
|
}
|
|
203
258
|
}
|
|
259
|
+
/**
|
|
260
|
+
* Lowers the window of the page being rendered to `seconds`, and nothing
|
|
261
|
+
* else (AGL-4121).
|
|
262
|
+
*
|
|
263
|
+
* For the narrow cases where a page shows something that changes on a clock
|
|
264
|
+
* rather than on a write — a publish schedule that is still pending. Next
|
|
265
|
+
* takes the shortest `revalidate` any cached read made during a regeneration,
|
|
266
|
+
* so a tiny cached constant read with this TTL holds THAT page (and only
|
|
267
|
+
* that page) on the short window, while every other page keeps the backstop.
|
|
268
|
+
*
|
|
269
|
+
* Outside a Next render (jest, scripts) it is a no-op.
|
|
270
|
+
*/ export async function capRenderWindow(seconds) {
|
|
271
|
+
const window = Math.max(1, Math.floor(seconds));
|
|
272
|
+
try {
|
|
273
|
+
await unstable_cache(async ()=>window, [
|
|
274
|
+
'tenant-render-window-cap',
|
|
275
|
+
String(window)
|
|
276
|
+
], {
|
|
277
|
+
revalidate: window
|
|
278
|
+
})();
|
|
279
|
+
} catch (error) {
|
|
280
|
+
if (isMissingIncrementalCache(error)) return;
|
|
281
|
+
console.error('[render-cache] could not cap the page window', error);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
204
284
|
|
|
205
285
|
//# sourceMappingURL=render-cache.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/tenant/data/admin/src/lib/render-cache.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 { unstable_cache } from 'next/cache'\n\n/**\n * Cross-request caching for the tenant render path's Firestore reads\n * (AGL-1302, the caching half of AGL-1151).\n *\n * Every tenant SSR render fanned out to ~15–40 uncached Admin-SDK reads —\n * host resolution, org billing, screen + version, the layout chain, and the\n * whole compose bundle (components, variables, functions, datasets,\n * workflows, plugin installs). None of that data is per-visitor, and almost\n * all of it is identical across every path on a site, so a 50-route sweep\n * paid the same host-scoped reads 50 times over. Routine verification\n * traffic alone burned ~44K reads/day (87% of the free tier).\n *\n * This module is deliberately a THIN wrapper around `unstable_cache` rather\n * than a cache of its own, so invalidation stays Next's: entries are tagged\n * and the existing publish/revalidate path (`/api/revalidate`, AGL-1150)\n * busts them with `revalidateTag` the same moment it drops the page HTML.\n *\n * Ground rules encoded here, because `unstable_cache` enforces none of them:\n *\n * - VALUES ARE JSON. `unstable_cache` stores `JSON.stringify(result)`, so a\n * cache HIT returns plain data while a MISS would return live objects —\n * Firestore `Timestamp`s, most importantly, whose `.seconds` getter decays\n * to `_seconds` across the round trip. Serving two shapes for the same\n * read is how a schedule check works in testing and misfires in\n * production, so `withRenderCache` normalizes the MISS through the same\n * JSON round trip. Callers whose logic needs live `Timestamp` semantics\n * must not cache that read (see the pending-`publishSchedule` guards at\n * the call sites).\n *\n * - NEGATIVES ARE NOT CACHED unless a caller opts in via `store`. A\n * transient miss (host not found, doc missing) cached for the TTL is a\n * self-inflicted outage; the Firestore negative-cache class of bug is\n * exactly this shape.\n *\n * - OUTSIDE NEXT (jest, scripts) there is no incremental cache and\n * `unstable_cache` throws its `incrementalCache missing` invariant before\n * running the callback. The wrapper catches precisely that and falls back\n * to the uncached read, so shared-lib specs exercise the same code path\n * they always did.\n *\n * - NEVER cache per-user reads through this. Everything cached here must be\n * a pure function of published site data.\n */\n\n/**\n * One tag per host covers every host-scoped cached doc — the host doc, the\n * compose bundle, plugin installs, the sitemap payload. The tenant\n * `/api/revalidate` route busts it on publish (alongside its existing\n * `revalidatePath` calls), so a publish is exactly as instant as AGL-1150\n * made it; the TTL is only the backstop for writes that never announce\n * themselves.\n */\nexport const tenantDataTag = (hostId: string): string => `tenant-data:${hostId}`\n\n/**\n * The backstop TTL for published site data — every read that\n * `revalidateTag(tenantDataTag(hostId))` busts on publish.\n *\n * WHY AN HOUR AND NOT A MINUTE (2026-08-26, from the Vercel cost review).\n *\n * Every cache in this layer shipped at 60s, and the page above them was\n * `revalidate = 60` too. Setting the backstop to the same order as the\n * request rate makes it the PRIMARY propagation mechanism rather than a\n * backstop: the whole chain expired together, so a render a minute paid the\n * full sequential Firestore walk — host, org billing, redirect rules, page\n * resolution, screen, compose bundle, enrichers — and none of it was ever\n * stale in a way anyone could observe, because the publish path had already\n * busted the tag the moment the content changed.\n *\n * Measured on `/[host]/[scheme]/[[...slug]]`: 0.78 GB-hr across 635 invocations, a P75\n * of 3.65s, and ~4.4 GB-s per render — the most expensive route per hit in\n * the account, on a site with no real traffic yet.\n *\n * So the TTL goes back to being what `withRenderCache`'s own docstring says\n * it is: \"the backstop for writes that never announce themselves.\" An hour\n * bounds an unannounced direct-to-Firestore edit. Everything that goes\n * through the product announces itself and is busted in the same instant it\n * always was, so publish latency is unchanged.\n *\n * ⛔ NOT for reads that change OUTSIDE a publish. Two deliberately keep their\n * own short TTLs and must not be moved onto this one:\n *\n * - `ORG_BILLING_TTL_SECONDS` — the request-time org read (the lockdown\n * verdict and the other dynamic routes), where a bandwidth cap or a\n * suspension stamped straight onto the doc arrives by TTL alone. The\n * render's own org read is on this backstop instead (`scope: 'render'`):\n * plan transitions, staff overrides and org settings all announce\n * themselves through `revalidateOrgHosts`.\n *\n * ⚠️ Any TTL read inside the ISR render also caps the PAGE: `unstable_cache`\n * lowers the regeneration's `revalidate` to the shortest TTL it saw, so one\n * 60s entry holds the catch-all's 3600 at 60.\n * - `HOST_ALIAS_TTL_SECONDS` / `HOST_DOC_TTL_SECONDS` — a custom domain\n * attaching is the customer sitting there waiting for their site\n * (AGL-2010), and the `cname--` alias entry expires only by TTL.\n *\n * Takedowns are unaffected either way: the middleware runs ahead of every\n * cache here and carries its own memo, which is what\n * `lockdown-middleware-propagation.spec.ts` measures.\n */\nexport const PUBLISHED_SITE_DATA_TTL_SECONDS = 3600\n\n/**\n * The backstop for the one read a screen publish changes under an UNCHANGED\n * cache key — the version pointer (AGL-2573).\n *\n * The hour above is argued on the premise that \"everything that goes through\n * the product announces itself\". That premise held for eleven days in August\n * and then did not: the tenant refused the announce and every publish on the\n * platform fell back to this TTL. The announce is still the mechanism — no TTL\n * can make a publish instant, because the page above these caches is ISR-held\n * and does not re-run a loader to notice a fresher document — but a backstop\n * only bounds a failure, and an hour is not a bound anyone would choose for\n * \"your published page is not the page you published\".\n *\n * Applied to the POINTER alone, deliberately, because the pointer alone is\n * what makes the hour expensive. `get-screen-version` is keyed by `versionId`,\n * so the body of a newly published version misses on its own; the only thing\n * standing between a visitor and it is the screen document that names which\n * version is live. That document is one small read, and shortening it leaves\n * the expensive reads — the compose bundle, the node trees — at the hour the\n * cost review set.\n *\n * The principle rather than a tuned figure: **the pointer must never be staler\n * than the HTML that reads it** — `<=` the tenant catch-all's ISR window\n * (`apps/tenant/app/[host]/[scheme]/[[...slug]]/page.tsx`), which\n * `publish-pointer-tracks-page-window.spec.ts` enforces. Above the window, the\n * page regenerates and faithfully rebuilds itself from a stale pointer, which\n * is the failure being closed.\n *\n * It matched that window exactly while the window was also 600s. It no longer\n * does, and staying at 600 under an hour-long window is the deliberate choice\n * (AGL-2690): the loader runs only when the page regenerates, so a shorter TTL\n * here costs the same single read per regeneration — a miss instead of a hit —\n * and buys a rebuild from data at most ten minutes old rather than up to an\n * hour old. That difference only shows when the publish announce is down, and\n * the announce has been down for eleven days once already.\n *\n * The read cost this adds is one document per page REGENERATION rather than\n * one per hour — regenerations are already bounded by the ISR window, so the\n * ceiling is the render rate and not the request rate. That is the price of\n * the bound, and it is the cheapest read on the path.\n */\nexport const PUBLISH_POINTER_TTL_SECONDS = 600\n\n/**\n * The alias→hostId resolution is tagged separately because it is the one\n * cache keyed BEFORE the hostId is known. It only changes on subdomain\n * rename or custom-domain (dis)connect, never on publish.\n */\nexport const tenantHostAliasTag = (alias: string): string =>\n `tenant-host:${alias}`\n\n/**\n * A value that must be RETURNED but not STORED (a negative result, or a doc\n * carrying a pending publish schedule). Thrown out of the cached callback so\n * `unstable_cache` never writes it, caught by the wrapper and unwrapped.\n */\nclass BypassStore extends Error {\n constructor(readonly value: unknown) {\n super('render-cache bypass')\n this.name = 'RenderCacheBypass'\n }\n}\n\nconst isMissingIncrementalCache = (error: unknown): boolean =>\n error instanceof Error && error.message.includes('incrementalCache missing')\n\n/**\n * The same normalization the page props already go through (`JSON.parse(\n * JSON.stringify(...))` at every loader exit), applied at the cache boundary\n * so hits and misses hand back byte-identical shapes.\n */\nexport function toPlainJson<T>(value: T): T {\n if (value === undefined || value === null) return value\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nexport interface RenderCacheOptions<T> {\n /**\n * Cache key parts. The FIRST part must be unique per read helper — every\n * call funnels through the same callback source, and `unstable_cache` keys\n * on callback text + key parts, so the name prefix is what keeps\n * `getScreen` and `getComponents` from colliding.\n */\n key: readonly string[]\n /** TTL in seconds — the staleness backstop when no tag bust arrives. */\n revalidate: number\n /** Tags `revalidateTag` can bust — see `tenantDataTag`. */\n tags: readonly string[]\n /** The uncached read. Must resolve to JSON-serializable data. */\n read: () => Promise<T>\n /**\n * Return `false` to serve the value WITHOUT storing it. Negative results\n * and docs whose live `Timestamp` semantics matter (pending publish\n * schedules) belong here. `undefined` is never stored regardless.\n */\n store?: (value: T) => boolean\n}\n\nexport async function withRenderCache<T>(\n options: RenderCacheOptions<T>,\n): Promise<T> {\n const { key, revalidate, tags, read, store } = options\n const cached = unstable_cache(\n async () => {\n const value = toPlainJson(await read())\n if (value === undefined || (store && !store(value))) {\n throw new BypassStore(value)\n }\n return value\n },\n [...key],\n { revalidate, tags: [...tags] },\n )\n try {\n return await cached()\n } catch (error) {\n if (error instanceof BypassStore) return error.value as T\n // No Next server context (jest, one-off scripts): the invariant throws\n // before the callback runs, so reading directly is not a double read.\n if (isMissingIncrementalCache(error)) return toPlainJson(await read())\n throw error\n }\n}\n"],"names":["unstable_cache","tenantDataTag","hostId","PUBLISHED_SITE_DATA_TTL_SECONDS","PUBLISH_POINTER_TTL_SECONDS","tenantHostAliasTag","alias","BypassStore","Error","value","name","isMissingIncrementalCache","error","message","includes","toPlainJson","undefined","JSON","parse","stringify","withRenderCache","options","key","revalidate","tags","read","store","cached"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,QAAQ,aAAY;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED;;;;;;;CAOC,GACD,OAAO,MAAMC,gBAAgB,CAACC,SAA2B,CAAC,YAAY,EAAEA,QAAQ,CAAA;AAEhF;;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"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/tenant/data/admin/src/lib/render-cache.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 { unstable_cache } from 'next/cache'\n\n/**\n * Cross-request caching for the tenant render path's Firestore reads\n * (AGL-1302, the caching half of AGL-1151).\n *\n * Every tenant SSR render fanned out to ~15–40 uncached Admin-SDK reads —\n * host resolution, org billing, screen + version, the layout chain, and the\n * whole compose bundle (components, variables, functions, datasets,\n * workflows, plugin installs). None of that data is per-visitor, and almost\n * all of it is identical across every path on a site, so a 50-route sweep\n * paid the same host-scoped reads 50 times over. Routine verification\n * traffic alone burned ~44K reads/day (87% of the free tier).\n *\n * This module is deliberately a THIN wrapper around `unstable_cache` rather\n * than a cache of its own, so invalidation stays Next's: entries are tagged\n * and the existing publish/revalidate path (`/api/revalidate`, AGL-1150)\n * busts them with `revalidateTag` the same moment it drops the page HTML.\n *\n * Ground rules encoded here, because `unstable_cache` enforces none of them:\n *\n * - VALUES ARE JSON. `unstable_cache` stores `JSON.stringify(result)`, so a\n * cache HIT returns plain data while a MISS would return live objects —\n * Firestore `Timestamp`s, most importantly, whose `.seconds` getter decays\n * to `_seconds` across the round trip. Serving two shapes for the same\n * read is how a schedule check works in testing and misfires in\n * production, so `withRenderCache` normalizes the MISS through the same\n * JSON round trip. Callers whose logic needs live `Timestamp` semantics\n * must not cache that read (see the pending-`publishSchedule` guards at\n * the call sites).\n *\n * - NEGATIVES ARE NOT CACHED unless a caller opts in via `store`. A\n * transient miss (host not found, doc missing) cached for the TTL is a\n * self-inflicted outage; the Firestore negative-cache class of bug is\n * exactly this shape.\n *\n * - OUTSIDE NEXT (jest, scripts) there is no incremental cache and\n * `unstable_cache` throws its `incrementalCache missing` invariant before\n * running the callback. The wrapper catches precisely that and falls back\n * to the uncached read, so shared-lib specs exercise the same code path\n * they always did.\n *\n * - NEVER cache per-user reads through this. Everything cached here must be\n * a pure function of published site data.\n */\n\n/**\n * One tag per host covers every host-scoped cached doc — the host doc, the\n * compose bundle, plugin installs, the sitemap payload. The tenant\n * `/api/revalidate` route busts it on publish (alongside its existing\n * `revalidatePath` calls), so a publish is exactly as instant as AGL-1150\n * made it; the TTL is only the backstop for writes that never announce\n * themselves.\n */\nexport const tenantDataTag = (hostId: string): string => `tenant-data:${hostId}`\n\n/**\n * THE BACKSTOP every tenant render-path read and the page itself share\n * (AGL-4121): seven days.\n *\n * Freshness is change-driven. Every write that changes what a page shows\n * drops it on demand, and the security-relevant drops (a plugin removed,\n * disabled, taken down, revoked or untrusted) are staged in the publish\n * outbox first, so a failed call is retried by the drain rather than left to\n * this timer. The timer only bounds an unannounced direct Firestore edit.\n *\n * One number on purpose. Next lowers a page's window to the SHORTEST cached\n * read its render makes (`unstable_cache` and `fetch` both shrink the work\n * store's `revalidate`), so a single read left on a shorter TTL quietly\n * becomes the page's window — exactly what kept #2459's one-day page on five\n * minutes. `tenant-page-window.spec.ts` sweeps the render path for that.\n */\nexport const TENANT_CACHE_BACKSTOP_SECONDS = 604800\n\n/**\n * Every cached read that decides WHICH PLUGINS a site may load — the signed\n * realm installs, the pinned installs with their kill-switch state, and the\n * image hosts those plugins declare — carries these tags beside\n * `tenantDataTag` (AGL-4121), and so does every page whose render read one.\n *\n * - `tenantPluginsTag(hostId)`: one site's plugin set changed (an uninstall,\n * a switchboard toggle, a plan move).\n * - `TENANT_PLUGINS_TAG`: a platform event changed it for every site at once\n * (a takedown, a revoked version, realm trust withdrawn). One tag bust\n * reaches every affected site with no host walk and no fan-out cap.\n *\n * The tenant's `/api/revalidate` expires both with `{ expire: 0 }`, not the\n * stale-while-revalidate `'max'` the data tag takes: a removed plugin must\n * not run for even one more visitor.\n */\nexport const TENANT_PLUGINS_TAG = 'tenant-plugins'\nexport const tenantPluginsTag = (hostId: string): string =>\n `tenant-plugins:${hostId}`\n\n/** The full tag set for a read that decides which plugins load on a site. */\nexport const tenantPluginGateTags = (hostId: string): string[] => [\n tenantDataTag(hostId),\n tenantPluginsTag(hostId),\n TENANT_PLUGINS_TAG,\n]\n\n/**\n * The backstop TTL for published site data — every read that\n * `revalidateTag(tenantDataTag(hostId))` busts on publish.\n *\n * ## Seven days (AGL-4121)\n *\n * The hour below became the backstop once every product write announced\n * itself; AGL-4121 audited the remaining unannounced writers (shopper stock\n * and reviews, the plugin switchboard, realm trust) and wired them, so the\n * hour is now {@link TENANT_CACHE_BACKSTOP_SECONDS}.\n *\n * WHY AN HOUR AND NOT A MINUTE (2026-08-26, from the Vercel cost review).\n *\n * Every cache in this layer shipped at 60s, and the page above them was\n * `revalidate = 60` too. Setting the backstop to the same order as the\n * request rate makes it the PRIMARY propagation mechanism rather than a\n * backstop: the whole chain expired together, so a render a minute paid the\n * full sequential Firestore walk — host, org billing, redirect rules, page\n * resolution, screen, compose bundle, enrichers — and none of it was ever\n * stale in a way anyone could observe, because the publish path had already\n * busted the tag the moment the content changed.\n *\n * Measured on `/[host]/[scheme]/[[...slug]]`: 0.78 GB-hr across 635 invocations, a P75\n * of 3.65s, and ~4.4 GB-s per render — the most expensive route per hit in\n * the account, on a site with no real traffic yet.\n *\n * So the TTL goes back to being what `withRenderCache`'s own docstring says\n * it is: \"the backstop for writes that never announce themselves.\" An hour\n * bounds an unannounced direct-to-Firestore edit. Everything that goes\n * through the product announces itself and is busted in the same instant it\n * always was, so publish latency is unchanged.\n *\n * ⛔ NOT for reads that change OUTSIDE a publish. Two deliberately keep their\n * own short TTLs and must not be moved onto this one:\n *\n * - `ORG_BILLING_TTL_SECONDS` — the request-time org read (the lockdown\n * verdict and the other dynamic routes), where a bandwidth cap or a\n * suspension stamped straight onto the doc arrives by TTL alone. The\n * render's own org read is on this backstop instead (`scope: 'render'`):\n * plan transitions, staff overrides and org settings all announce\n * themselves through `revalidateOrgHosts`.\n *\n * ⚠️ Any TTL read inside the ISR render also caps the PAGE: `unstable_cache`\n * lowers the regeneration's `revalidate` to the shortest TTL it saw, so one\n * 60s entry holds the catch-all's 3600 at 60.\n * - `HOST_ALIAS_TTL_SECONDS` / `HOST_DOC_TTL_SECONDS` — a custom domain\n * attaching is the customer sitting there waiting for their site\n * (AGL-2010), and the `cname--` alias entry expires only by TTL.\n *\n * Takedowns are unaffected either way: the middleware runs ahead of every\n * cache here and carries its own memo, which is what\n * `lockdown-middleware-propagation.spec.ts` measures.\n */\nexport const PUBLISHED_SITE_DATA_TTL_SECONDS = TENANT_CACHE_BACKSTOP_SECONDS\n\n/**\n * The backstop for the one read a screen publish changes under an UNCHANGED\n * cache key — the version pointer (AGL-2573).\n *\n * The hour above is argued on the premise that \"everything that goes through\n * the product announces itself\". That premise held for eleven days in August\n * and then did not: the tenant refused the announce and every publish on the\n * platform fell back to this TTL. The announce is still the mechanism — no TTL\n * can make a publish instant, because the page above these caches is ISR-held\n * and does not re-run a loader to notice a fresher document — but a backstop\n * only bounds a failure, and an hour is not a bound anyone would choose for\n * \"your published page is not the page you published\".\n *\n * Applied to the POINTER alone, deliberately, because the pointer alone is\n * what makes the hour expensive. `get-screen-version` is keyed by `versionId`,\n * so the body of a newly published version misses on its own; the only thing\n * standing between a visitor and it is the screen document that names which\n * version is live. That document is one small read, and shortening it leaves\n * the expensive reads — the compose bundle, the node trees — at the hour the\n * cost review set.\n *\n * The principle rather than a tuned figure: **the pointer must never be staler\n * than the HTML that reads it** — `<=` the tenant catch-all's ISR window\n * (`apps/tenant/app/[host]/[scheme]/[[...slug]]/page.tsx`), which\n * `publish-pointer-tracks-page-window.spec.ts` enforces. Above the window, the\n * page regenerates and faithfully rebuilds itself from a stale pointer, which\n * is the failure being closed.\n *\n * It matched that window exactly while the window was also 600s. It no longer\n * does, and staying at 600 under an hour-long window is the deliberate choice\n * (AGL-2690): the loader runs only when the page regenerates, so a shorter TTL\n * here costs the same single read per regeneration — a miss instead of a hit —\n * and buys a rebuild from data at most ten minutes old rather than up to an\n * hour old. That difference only shows when the publish announce is down, and\n * the announce has been down for eleven days once already.\n *\n * The read cost this adds is one document per page REGENERATION rather than\n * one per hour — regenerations are already bounded by the ISR window, so the\n * ceiling is the render rate and not the request rate. That is the price of\n * the bound, and it is the cheapest read on the path.\n *\n * ## Equal to the page window again (AGL-4121)\n *\n * The reasoning above held while the pointer sat BELOW the page window. It\n * stopped holding once AGL-4121 measured that a TTL read in the render lowers\n * the page's own window to match: at 600s the pointer was what regenerated\n * every page every ten minutes. The failure it bounded is now closed at the\n * source instead — every pointer move rides the publish outbox (AGL-2575),\n * whose drain retries a refused announce — so the pointer takes the backstop\n * and stays exactly `<=` the page window, which the spec still enforces.\n */\nexport const PUBLISH_POINTER_TTL_SECONDS = TENANT_CACHE_BACKSTOP_SECONDS\n\n/**\n * The alias→hostId resolution is tagged separately because it is the one\n * cache keyed BEFORE the hostId is known. It only changes on subdomain\n * rename or custom-domain (dis)connect, never on publish.\n */\nexport const tenantHostAliasTag = (alias: string): string =>\n `tenant-host:${alias}`\n\n/**\n * A value that must be RETURNED but not STORED (a negative result, or a doc\n * carrying a pending publish schedule). Thrown out of the cached callback so\n * `unstable_cache` never writes it, caught by the wrapper and unwrapped.\n */\nclass BypassStore extends Error {\n constructor(readonly value: unknown) {\n super('render-cache bypass')\n this.name = 'RenderCacheBypass'\n }\n}\n\nconst isMissingIncrementalCache = (error: unknown): boolean =>\n error instanceof Error && error.message.includes('incrementalCache missing')\n\n/**\n * The same normalization the page props already go through (`JSON.parse(\n * JSON.stringify(...))` at every loader exit), applied at the cache boundary\n * so hits and misses hand back byte-identical shapes.\n */\nexport function toPlainJson<T>(value: T): T {\n if (value === undefined || value === null) return value\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nexport interface RenderCacheOptions<T> {\n /**\n * Cache key parts. The FIRST part must be unique per read helper — every\n * call funnels through the same callback source, and `unstable_cache` keys\n * on callback text + key parts, so the name prefix is what keeps\n * `getScreen` and `getComponents` from colliding.\n */\n key: readonly string[]\n /** TTL in seconds — the staleness backstop when no tag bust arrives. */\n revalidate: number\n /** Tags `revalidateTag` can bust — see `tenantDataTag`. */\n tags: readonly string[]\n /** The uncached read. Must resolve to JSON-serializable data. */\n read: () => Promise<T>\n /**\n * Return `false` to serve the value WITHOUT storing it. Negative results\n * and docs whose live `Timestamp` semantics matter (pending publish\n * schedules) belong here. `undefined` is never stored regardless.\n */\n store?: (value: T) => boolean\n}\n\nexport async function withRenderCache<T>(\n options: RenderCacheOptions<T>,\n): Promise<T> {\n const { key, revalidate, tags, read, store } = options\n const cached = unstable_cache(\n async () => {\n const value = toPlainJson(await read())\n if (value === undefined || (store && !store(value))) {\n throw new BypassStore(value)\n }\n return value\n },\n [...key],\n { revalidate, tags: [...tags] },\n )\n try {\n return await cached()\n } catch (error) {\n if (error instanceof BypassStore) return error.value as T\n // No Next server context (jest, one-off scripts): the invariant throws\n // before the callback runs, so reading directly is not a double read.\n if (isMissingIncrementalCache(error)) return toPlainJson(await read())\n throw error\n }\n}\n\n/**\n * Lowers the window of the page being rendered to `seconds`, and nothing\n * else (AGL-4121).\n *\n * For the narrow cases where a page shows something that changes on a clock\n * rather than on a write — a publish schedule that is still pending. Next\n * takes the shortest `revalidate` any cached read made during a regeneration,\n * so a tiny cached constant read with this TTL holds THAT page (and only\n * that page) on the short window, while every other page keeps the backstop.\n *\n * Outside a Next render (jest, scripts) it is a no-op.\n */\nexport async function capRenderWindow(seconds: number): Promise<void> {\n const window = Math.max(1, Math.floor(seconds))\n try {\n await unstable_cache(async () => window, ['tenant-render-window-cap', String(window)], {\n revalidate: window,\n })()\n } catch (error) {\n if (isMissingIncrementalCache(error)) return\n console.error('[render-cache] could not cap the page window', error)\n }\n}\n"],"names":["unstable_cache","tenantDataTag","hostId","TENANT_CACHE_BACKSTOP_SECONDS","TENANT_PLUGINS_TAG","tenantPluginsTag","tenantPluginGateTags","PUBLISHED_SITE_DATA_TTL_SECONDS","PUBLISH_POINTER_TTL_SECONDS","tenantHostAliasTag","alias","BypassStore","Error","value","name","isMissingIncrementalCache","error","message","includes","toPlainJson","undefined","JSON","parse","stringify","withRenderCache","options","key","revalidate","tags","read","store","cached","capRenderWindow","seconds","window","Math","max","floor","String","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,QAAQ,aAAY;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED;;;;;;;CAOC,GACD,OAAO,MAAMC,gBAAgB,CAACC,SAA2B,CAAC,YAAY,EAAEA,QAAQ,CAAA;AAEhF;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,gCAAgC,OAAM;AAEnD;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,qBAAqB,iBAAgB;AAClD,OAAO,MAAMC,mBAAmB,CAACH,SAC/B,CAAC,eAAe,EAAEA,QAAQ,CAAA;AAE5B,2EAA2E,GAC3E,OAAO,MAAMI,uBAAuB,CAACJ,SAA6B;QAChED,cAAcC;QACdG,iBAAiBH;QACjBE;KACD,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoDC,GACD,OAAO,MAAMG,kCAAkCJ,8BAA6B;AAE5E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkDC,GACD,OAAO,MAAMK,8BAA8BL,8BAA6B;AAExE;;;;CAIC,GACD,OAAO,MAAMM,qBAAqB,CAACC,QACjC,CAAC,YAAY,EAAEA,OAAO,CAAA;AAExB;;;;CAIC,GACD,IAAA,AAAMC,cAAN,MAAMA,oBAAoBC;IACxB,YAAY,AAASC,KAAc,CAAE;QACnC,KAAK,CAAC,6B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listingId: string, versi
|
|
|
62
62
|
identity?: string;
|
|
63
63
|
contributes?: PluginContributions;
|
|
64
64
|
} | null>;
|
|
65
|
+
/**
|
|
66
|
+
* SECURITY-RELEVANT CACHE (AGL-1302, AGL-4121): the join drops revoked,
|
|
67
|
+
* taken-down, untrusted and switched-off versions, so this entry decides which
|
|
68
|
+
* plugins a published site loads.
|
|
69
|
+
*
|
|
70
|
+
* It is no longer bounded by its TTL. Every write that changes the answer
|
|
71
|
+
* expires it, and every page that read it, the moment it lands, through the
|
|
72
|
+
* plugin tags (`tenantPluginGateTags`), which the tenant expires with
|
|
73
|
+
* `{ expire: 0 }` rather than stale-while-revalidate:
|
|
74
|
+
*
|
|
75
|
+
* - a site's set (an install, an uninstall, a version re-pin, a workspace
|
|
76
|
+
* switchboard toggle, a plan move) expires `tenant-plugins:{hostId}` for each
|
|
77
|
+
* site it reaches;
|
|
78
|
+
* - a platform event (a takedown, a revoked version, realm trust withdrawn or
|
|
79
|
+
* rejected away) expires `tenant-plugins` on every site at once.
|
|
80
|
+
*
|
|
81
|
+
* Each of those is staged in the publish outbox BEFORE it is sent, so a
|
|
82
|
+
* refused call is retried by the console's drain, and an alert is raised when
|
|
83
|
+
* neither the call nor the outbox entry landed. That is what lets the TTL be
|
|
84
|
+
* the platform backstop rather than five minutes: at 300s this one read held
|
|
85
|
+
* every full page on a five-minute window (#2459). Only the HOST-scoped call
|
|
86
|
+
* (the tenant render path) is cached; the console's org-scoped call stays
|
|
87
|
+
* fresh so an install shows up in the workspace the moment it lands.
|
|
88
|
+
*/
|
|
89
|
+
export declare const REALM_PLUGIN_INSTALLS_TTL_SECONDS = 604800;
|
|
65
90
|
export declare function getRealmPluginInstalls(options: {
|
|
66
91
|
orgId?: string;
|
|
67
92
|
hostId?: string;
|
|
@@ -18,7 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
18
18
|
import { PLUGIN_DISTRIBUTION } from "@aglyn/aglyn/plugin-manager/plugin-distribution";
|
|
19
19
|
import { firebaseAdmin } from "./firebase-admin.js";
|
|
20
20
|
import { resolveOrgIdForHost } from "./organizations.js";
|
|
21
|
-
import {
|
|
21
|
+
import { TENANT_CACHE_BACKSTOP_SECONDS, tenantPluginGateTags, withRenderCache } from "../render-cache.js";
|
|
22
22
|
/**
|
|
23
23
|
* One `pluginSettings` document, or `undefined` if it cannot be read.
|
|
24
24
|
*
|
|
@@ -163,19 +163,29 @@ import { tenantDataTag, withRenderCache } from "../render-cache.js";
|
|
|
163
163
|
} : {});
|
|
164
164
|
}
|
|
165
165
|
/**
|
|
166
|
-
* SECURITY-RELEVANT
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
|
|
166
|
+
* SECURITY-RELEVANT CACHE (AGL-1302, AGL-4121): the join drops revoked,
|
|
167
|
+
* taken-down, untrusted and switched-off versions, so this entry decides which
|
|
168
|
+
* plugins a published site loads.
|
|
169
|
+
*
|
|
170
|
+
* It is no longer bounded by its TTL. Every write that changes the answer
|
|
171
|
+
* expires it, and every page that read it, the moment it lands, through the
|
|
172
|
+
* plugin tags (`tenantPluginGateTags`), which the tenant expires with
|
|
173
|
+
* `{ expire: 0 }` rather than stale-while-revalidate:
|
|
174
|
+
*
|
|
175
|
+
* - a site's set (an install, an uninstall, a version re-pin, a workspace
|
|
176
|
+
* switchboard toggle, a plan move) expires `tenant-plugins:{hostId}` for each
|
|
177
|
+
* site it reaches;
|
|
178
|
+
* - a platform event (a takedown, a revoked version, realm trust withdrawn or
|
|
179
|
+
* rejected away) expires `tenant-plugins` on every site at once.
|
|
180
|
+
*
|
|
181
|
+
* Each of those is staged in the publish outbox BEFORE it is sent, so a
|
|
182
|
+
* refused call is retried by the console's drain, and an alert is raised when
|
|
183
|
+
* neither the call nor the outbox entry landed. That is what lets the TTL be
|
|
184
|
+
* the platform backstop rather than five minutes: at 300s this one read held
|
|
185
|
+
* every full page on a five-minute window (#2459). Only the HOST-scoped call
|
|
186
|
+
* (the tenant render path) is cached; the console's org-scoped call stays
|
|
187
|
+
* fresh so an install shows up in the workspace the moment it lands.
|
|
188
|
+
*/ export const REALM_PLUGIN_INSTALLS_TTL_SECONDS = TENANT_CACHE_BACKSTOP_SECONDS;
|
|
179
189
|
export async function getRealmPluginInstalls(options) {
|
|
180
190
|
const hostId = options.hostId;
|
|
181
191
|
if (!hostId || options.orgId) return resolveRealmPluginInstalls(options);
|
|
@@ -186,9 +196,7 @@ export async function getRealmPluginInstalls(options) {
|
|
|
186
196
|
hostId
|
|
187
197
|
],
|
|
188
198
|
revalidate: REALM_PLUGIN_INSTALLS_TTL_SECONDS,
|
|
189
|
-
tags:
|
|
190
|
-
tenantDataTag(hostId)
|
|
191
|
-
],
|
|
199
|
+
tags: tenantPluginGateTags(hostId),
|
|
192
200
|
read: ()=>resolveRealmPluginInstalls(options)
|
|
193
201
|
});
|
|
194
202
|
} catch (error) {
|
|
@@ -205,14 +213,24 @@ async function resolveRealmPluginInstalls(options) {
|
|
|
205
213
|
// keeps the list in step; toggling one off disables it without
|
|
206
214
|
// uninstalling). Absent field = default-open, so pre-switchboard
|
|
207
215
|
// installs keep loading.
|
|
216
|
+
//
|
|
217
|
+
// Masked to that one field (AGL-4121): the org document is among the largest
|
|
218
|
+
// the tenant reads, and this is the only field the join uses from it.
|
|
208
219
|
let enabledFilter = null;
|
|
209
220
|
if (orgId) {
|
|
210
|
-
const
|
|
221
|
+
const [org] = await firestore.getAll(firestore.collection('orgs').doc(orgId), {
|
|
222
|
+
fieldMask: [
|
|
223
|
+
'enabledPlugins'
|
|
224
|
+
]
|
|
225
|
+
});
|
|
226
|
+
const configured = org == null ? void 0 : org.get('enabledPlugins');
|
|
211
227
|
if (Array.isArray(configured)) enabledFilter = configured.map(String);
|
|
212
228
|
}
|
|
213
229
|
const pins = new Map();
|
|
214
230
|
const collect = async (ref)=>{
|
|
215
|
-
|
|
231
|
+
// Only the pin's `version` is used; an install doc carries its manifest
|
|
232
|
+
// copy too, so the rest is projected away (AGL-4121).
|
|
233
|
+
const snapshot = await ref.select('version').get();
|
|
216
234
|
for (const doc of snapshot.docs){
|
|
217
235
|
const version = doc.get('version');
|
|
218
236
|
if (typeof version === 'string' && version) {
|
|
@@ -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 { tenantDataTag, withRenderCache } 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 TTL (AGL-1302): the join drops revoked and taken-down\n * versions, so this cache bounds how long a killed plugin keeps loading on\n * published sites when nothing announces the kill. Every write that changes\n * the answer announces itself through `tenant-data:{hostId}`: a takedown or\n * a revoked version through `dropCachesForListing`, an install or uninstall\n * through the marketplace's `announcePinChange` (AGL-3741). So this is the\n * backstop for a fan-out that failed or was capped, not the propagation —\n * five minutes, where it was one, because at one minute it re-read every\n * site's pins, listings, versions and revocations sixty times an hour. Only\n * the HOST-scoped call (the tenant render path) is cached; the console's\n * org-scoped call stays fresh so an install shows up in the workspace the\n * moment it lands.\n */\nconst REALM_PLUGIN_INSTALLS_TTL_SECONDS = 300\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: [tenantDataTag(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 let enabledFilter: readonly string[] | null = null\n if (orgId) {\n const configured = (\n await firestore.collection('orgs').doc(orgId).get()\n ).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 const snapshot = await ref.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","tenantDataTag","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","configured","Array","isArray","map","pins","Map","collect","ref","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,SAASC,aAAa,EAAEC,eAAe,QAAQ,qBAAiB;AAEhE;;;;;;;CAOC,GACD,eAAeC,mBACbC,KAAuB,EACvBC,OAAe,EACfC,QAAgB;IAEhB,IAAI;QACF,OAAO,AACL,CAAA,MAAMP,cACHQ,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,SAASxB,sBAAsBa;IACrC,MAAMY,SAASF,QAAQE,MAAM;IAC7B,IAAI,CAACH,SAAS,CAACG,QAAQ,OAAOD,S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,CAAC,GAC9DqC,OAAOnE,QAAQ,GAAG;YAAEA,UAAUmE,OAAOnE,QAAQ;QAAC,IAAI,CAAC,GACnDmE,OAAO/B,QAAQ,GAAG;YAAEA,UAAU+B,OAAO/B,QAAQ;QAAC,IAAI,CAAC,GACnD+B,OAAOlC,WAAW,GAAG;YAAEA,aAAakC,OAAOlC,WAAW;QAAC,IAAI,CAAC;IAEpE;IAEF,OAAO+B,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 * 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,SAAS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The org fields the targeting answer is made of, and the only ones read
|
|
51
|
+
* (AGL-4121). `releaseFlags` is the overrides; the rest is everything
|
|
52
|
+
* `resolveEffectivePlan` consults: the stored `plan`, the subscription status
|
|
53
|
+
* (`billingStatus` mirror first, then `subscription.status`), and a staff comp
|
|
54
|
+
* (`entitlements.planComp`).
|
|
55
|
+
*
|
|
56
|
+
* This read runs once a minute per org on every warm instance that renders a
|
|
57
|
+
* page or dispatches an API call, and the org document is one of the largest
|
|
58
|
+
* the tenant reads, so fetching all of it to use five fields was paying
|
|
59
|
+
* Firestore egress for nothing. A field that `resolveEffectivePlan` starts
|
|
60
|
+
* reading must be added here: `release-flags-org-field-mask.spec.ts` resolves
|
|
61
|
+
* the plan from the masked projection and from the whole document and fails
|
|
62
|
+
* when they disagree.
|
|
63
|
+
*/
|
|
64
|
+
export declare const ORG_RELEASE_FLAG_FIELDS: readonly ["releaseFlags", "plan", "billingStatus", "subscription.status", "entitlements.planComp"];
|
|
49
65
|
/**
|
|
50
66
|
* Both halves of the per-org answer from ONE cached document read.
|
|
51
67
|
*
|
|
@@ -67,6 +83,18 @@ export declare function getOrgReleaseFlagOverrides(orgId: string | null | undefi
|
|
|
67
83
|
* which is the failure this issue exists to fix.
|
|
68
84
|
*/
|
|
69
85
|
export declare function isServerReleaseFlagOnForOrg(flagKey: ReleaseFlagKey, orgId: string | null | undefined): Promise<boolean>;
|
|
86
|
+
/**
|
|
87
|
+
* {@link isServerReleaseFlagOnForOrg} for a caller that already holds the org
|
|
88
|
+
* document (AGL-4121): the same verdict, with the targeting taken from `org`
|
|
89
|
+
* instead of a second read of the same document.
|
|
90
|
+
*
|
|
91
|
+
* For request-time callers whose copy is no older than this module's own
|
|
92
|
+
* minute — the lockdown verdict holds the org through `getOrgBilling`'s
|
|
93
|
+
* 60-second request entry — so a grant still lands within the minute it
|
|
94
|
+
* always took. `org` null means the caller looked and found none, and answers
|
|
95
|
+
* as an unreadable org does: no overrides, unknown tier.
|
|
96
|
+
*/
|
|
97
|
+
export declare function isServerReleaseFlagOnForLoadedOrg(flagKey: ReleaseFlagKey, orgId: string | null | undefined, org: Record<string, unknown> | null): Promise<boolean>;
|
|
70
98
|
/** Test seam: drops both caches so a spec can change a verdict. */
|
|
71
99
|
export declare function __resetReleaseFlagCaches(): void;
|
|
72
100
|
/**
|
|
@@ -64,6 +64,36 @@ export async function getServerReleaseFlagValues() {
|
|
|
64
64
|
return pending;
|
|
65
65
|
}
|
|
66
66
|
const orgCache = new Map();
|
|
67
|
+
/** One read in flight per org: concurrent misses on one instance share it. */ const orgPending = new Map();
|
|
68
|
+
/**
|
|
69
|
+
* The org fields the targeting answer is made of, and the only ones read
|
|
70
|
+
* (AGL-4121). `releaseFlags` is the overrides; the rest is everything
|
|
71
|
+
* `resolveEffectivePlan` consults: the stored `plan`, the subscription status
|
|
72
|
+
* (`billingStatus` mirror first, then `subscription.status`), and a staff comp
|
|
73
|
+
* (`entitlements.planComp`).
|
|
74
|
+
*
|
|
75
|
+
* This read runs once a minute per org on every warm instance that renders a
|
|
76
|
+
* page or dispatches an API call, and the org document is one of the largest
|
|
77
|
+
* the tenant reads, so fetching all of it to use five fields was paying
|
|
78
|
+
* Firestore egress for nothing. A field that `resolveEffectivePlan` starts
|
|
79
|
+
* reading must be added here: `release-flags-org-field-mask.spec.ts` resolves
|
|
80
|
+
* the plan from the masked projection and from the whole document and fails
|
|
81
|
+
* when they disagree.
|
|
82
|
+
*/ export const ORG_RELEASE_FLAG_FIELDS = [
|
|
83
|
+
'releaseFlags',
|
|
84
|
+
'plan',
|
|
85
|
+
'billingStatus',
|
|
86
|
+
'subscription.status',
|
|
87
|
+
'entitlements.planComp'
|
|
88
|
+
];
|
|
89
|
+
/** The targeting answer from an org document already in hand, or `null` for none. */ function targetingFromOrgData(data) {
|
|
90
|
+
return {
|
|
91
|
+
overrides: parseOrgReleaseFlagOverrides(data == null ? void 0 : data['releaseFlags']),
|
|
92
|
+
// Only when a document actually came back. `resolveEffectivePlan` would
|
|
93
|
+
// read a missing doc as Free.
|
|
94
|
+
plan: data ? resolveEffectivePlan(data) : null
|
|
95
|
+
};
|
|
96
|
+
}
|
|
67
97
|
/**
|
|
68
98
|
* Both halves of the per-org answer from ONE cached document read.
|
|
69
99
|
*
|
|
@@ -78,25 +108,34 @@ const orgCache = new Map();
|
|
|
78
108
|
};
|
|
79
109
|
const hit = orgCache.get(orgId);
|
|
80
110
|
if (hit && Date.now() - hit.at < TTL_MS) return hit.targeting;
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
111
|
+
const inFlight = orgPending.get(orgId);
|
|
112
|
+
if (inFlight) return inFlight;
|
|
113
|
+
const pending = (async ()=>{
|
|
114
|
+
let targeting = {
|
|
115
|
+
overrides: {},
|
|
116
|
+
plan: null
|
|
117
|
+
};
|
|
118
|
+
try {
|
|
119
|
+
const firestore = firebaseAdmin.app().firestore();
|
|
120
|
+
const [snapshot] = await firestore.getAll(firestore.collection('orgs').doc(orgId), {
|
|
121
|
+
fieldMask: [
|
|
122
|
+
...ORG_RELEASE_FLAG_FIELDS
|
|
123
|
+
]
|
|
124
|
+
});
|
|
125
|
+
targeting = targetingFromOrgData(snapshot == null ? void 0 : snapshot.data());
|
|
126
|
+
} catch (unused) {
|
|
127
|
+
// No Firestore here, or the doc is unreadable — inherit, never fail.
|
|
128
|
+
}
|
|
129
|
+
orgCache.set(orgId, {
|
|
130
|
+
at: Date.now(),
|
|
131
|
+
targeting
|
|
132
|
+
});
|
|
133
|
+
return targeting;
|
|
134
|
+
})().finally(()=>{
|
|
135
|
+
orgPending.delete(orgId);
|
|
98
136
|
});
|
|
99
|
-
|
|
137
|
+
orgPending.set(orgId, pending);
|
|
138
|
+
return pending;
|
|
100
139
|
}
|
|
101
140
|
export async function getOrgReleaseFlagOverrides(orgId) {
|
|
102
141
|
return (await getOrgReleaseFlagTargeting(orgId)).overrides;
|
|
@@ -117,9 +156,28 @@ export async function getOrgReleaseFlagOverrides(orgId) {
|
|
|
117
156
|
]);
|
|
118
157
|
return isReleaseFlagOnForOrg(flagKey, values[flagKey], orgId != null ? orgId : null, targeting.overrides, targeting.plan);
|
|
119
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* {@link isServerReleaseFlagOnForOrg} for a caller that already holds the org
|
|
161
|
+
* document (AGL-4121): the same verdict, with the targeting taken from `org`
|
|
162
|
+
* instead of a second read of the same document.
|
|
163
|
+
*
|
|
164
|
+
* For request-time callers whose copy is no older than this module's own
|
|
165
|
+
* minute — the lockdown verdict holds the org through `getOrgBilling`'s
|
|
166
|
+
* 60-second request entry — so a grant still lands within the minute it
|
|
167
|
+
* always took. `org` null means the caller looked and found none, and answers
|
|
168
|
+
* as an unreadable org does: no overrides, unknown tier.
|
|
169
|
+
*/ export async function isServerReleaseFlagOnForLoadedOrg(flagKey, orgId, org) {
|
|
170
|
+
const values = await getServerReleaseFlagValues();
|
|
171
|
+
const targeting = orgId ? targetingFromOrgData(org) : {
|
|
172
|
+
overrides: {},
|
|
173
|
+
plan: null
|
|
174
|
+
};
|
|
175
|
+
return isReleaseFlagOnForOrg(flagKey, values[flagKey], orgId != null ? orgId : null, targeting.overrides, targeting.plan);
|
|
176
|
+
}
|
|
120
177
|
/** Test seam: drops both caches so a spec can change a verdict. */ export function __resetReleaseFlagCaches() {
|
|
121
178
|
cache = undefined;
|
|
122
179
|
orgCache.clear();
|
|
180
|
+
orgPending.clear();
|
|
123
181
|
}
|
|
124
182
|
/**
|
|
125
183
|
* The server half of the plugin release gate (AGL-422): subtracts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/release-flags.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 filterPluginsByReleaseFlags,\n isReleaseFlagKey,\n isReleaseFlagOnForOrg,\n parseOrgReleaseFlagOverrides,\n parseReleaseFlagValue,\n RELEASE_FLAGS,\n resolveEffectivePlan,\n type OrgPlan,\n type OrgReleaseFlagOverrides,\n type ReleaseFlagKey,\n type ReleaseFlagValue,\n} from '@aglyn/aglyn/server'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * Server-side release-flag verdicts (AGL-422): the tenant loader and the\n * API dispatchers subtract flagged-off plugins, so the server needs the\n * same Remote Config values the console client activates. The admin SDK\n * template read is cached with a short TTL — flag flips propagate within\n * a minute without a per-request round trip.\n *\n * Fail-open to the REGISTRY DEFAULTS (not \"all on\"): environments without\n * Remote Config (emulator e2e, local dev) behave exactly like an\n * unpublished template does on the client, so verdicts agree across\n * surfaces.\n */\n\nconst TTL_MS = 60_000\n\nlet cache:\n | { at: number; values: Record<ReleaseFlagKey, ReleaseFlagValue> }\n | undefined\nlet pending:\n | Promise<Record<ReleaseFlagKey, ReleaseFlagValue>>\n | undefined\n\nconst registryDefaults = (): Record<ReleaseFlagKey, ReleaseFlagValue> =>\n Object.fromEntries(\n RELEASE_FLAGS.map((definition) => [\n definition.key,\n { enabled: definition.defaultEnabled },\n ]),\n ) as Record<ReleaseFlagKey, ReleaseFlagValue>\n\nexport async function getServerReleaseFlagValues(): Promise<\n Record<ReleaseFlagKey, ReleaseFlagValue>\n> {\n if (cache && Date.now() - cache.at < TTL_MS) return cache.values\n if (!pending) {\n pending = (async () => {\n const values = registryDefaults()\n try {\n const template = await firebaseAdmin.app().remoteConfig().getTemplate()\n for (const definition of RELEASE_FLAGS) {\n const parameter = template.parameters[definition.key]\n const defaultValue = parameter?.defaultValue\n const raw =\n defaultValue && 'value' in defaultValue\n ? defaultValue.value\n : undefined\n values[definition.key] = parseReleaseFlagValue(\n raw,\n definition.defaultEnabled,\n )\n }\n } catch {\n // No Remote Config here (emulator/local) — registry defaults gate.\n }\n cache = { at: Date.now(), values }\n return values\n })().finally(() => {\n pending = undefined\n })\n }\n return pending\n}\n\n/**\n * Per-org release-flag overrides (AGL-1635), read off `orgs/{orgId}`.\n *\n * Cached on the same TTL as the template read above, and for the same\n * reason: these are consulted on every published page render and every API\n * dispatch, so an uncached read would add a Firestore round trip to the hot\n * path. A grant therefore takes up to a minute to land, matching how long a\n * flag flip already takes — one propagation story, not two.\n *\n * Keyed by orgId because a subject may be a uid or a hostId, and only an\n * org can carry overrides. Failure is silent and yields `{}`: a missing org\n * doc or a denied read must gate exactly as \"no override set\", never as an\n * error that takes a published page down.\n */\n/**\n * What one org read answers about release flags: the staff overrides, and\n * the org's EFFECTIVE plan for tier targeting (AGL-2486).\n *\n * `plan` is null when the read did not produce an org document — missing,\n * denied, or no Firestore at all. Deliberately not `'free'`: an org whose\n * doc could not be read has an UNKNOWN tier, and\n * `resolveEffectivePlan(undefined)` answers `'free'`, which would hand a\n * Free-targeted flag to every org the read failed for. The two cases have to\n * stay distinguishable at the boundary, because the evaluator treats an\n * unknown plan as a refusal and a known `'free'` as a match.\n */\ninterface OrgReleaseFlagTargeting {\n overrides: OrgReleaseFlagOverrides\n plan: OrgPlan | null\n}\n\nconst orgCache = new Map<string, { at: number; targeting: OrgReleaseFlagTargeting }>()\n\n/**\n * Both halves of the per-org answer from ONE cached document read.\n *\n * Sharing the read is the point: `plan` and `releaseFlags` live on the same\n * org document, this runs on every published page render and every API\n * dispatch, and fetching the tier separately would have doubled the hot-path\n * Firestore traffic to learn something already in hand.\n */\nexport async function getOrgReleaseFlagTargeting(\n orgId: string | null | undefined,\n): Promise<OrgReleaseFlagTargeting> {\n if (!orgId) return { overrides: {}, plan: null }\n const hit = orgCache.get(orgId)\n if (hit && Date.now() - hit.at < TTL_MS) return hit.targeting\n const targeting: OrgReleaseFlagTargeting = { overrides: {}, plan: null }\n try {\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .get()\n const data = snapshot.data()\n targeting.overrides = parseOrgReleaseFlagOverrides(data?.['releaseFlags'])\n // Only when a document actually came back. `snapshot.data()` is undefined\n // for a missing doc, and `resolveEffectivePlan` would read that as Free.\n if (data) targeting.plan = resolveEffectivePlan(data as any)\n } catch {\n // No Firestore here, or the doc is unreadable — inherit, never fail.\n }\n orgCache.set(orgId, { at: Date.now(), targeting })\n return targeting\n}\n\nexport async function getOrgReleaseFlagOverrides(\n orgId: string | null | undefined,\n): Promise<OrgReleaseFlagOverrides> {\n return (await getOrgReleaseFlagTargeting(orgId)).overrides\n}\n\n/**\n * The verdict for ONE flag and ONE org, overrides applied (AGL-1635).\n *\n * The surfaces that gate a single flag server-side — the tenant admin bar\n * slot, edit-context redemption, edit-access minting — resolve through here\n * rather than reading `getServerReleaseFlagValues()` and calling\n * `isReleaseFlagOn` themselves, so a per-org grant reaches all of them at\n * once. A gate that kept the old two-step would silently ignore overrides,\n * which is the failure this issue exists to fix.\n */\nexport async function isServerReleaseFlagOnForOrg(\n flagKey: ReleaseFlagKey,\n orgId: string | null | undefined,\n): Promise<boolean> {\n const [values, targeting] = await Promise.all([\n getServerReleaseFlagValues(),\n getOrgReleaseFlagTargeting(orgId),\n ])\n return isReleaseFlagOnForOrg(\n flagKey,\n values[flagKey],\n orgId ?? null,\n targeting.overrides,\n targeting.plan,\n )\n}\n\n/** Test seam: drops both caches so a spec can change a verdict. */\nexport function __resetReleaseFlagCaches(): void {\n cache = undefined\n orgCache.clear()\n}\n\n/**\n * The server half of the plugin release gate (AGL-422): subtracts\n * flagged-off first-party plugins from an effective set. The staff bypass is\n * only paid for when something was actually subtracted AND the request\n * carries a bearer token — the common all-flags-on path never verifies.\n *\n * `orgId` is the ONLY subject: it selects the per-org overrides (AGL-1635)\n * and it is the rollout bucket. AGL-1635 took a separate `subjectId` here\n * because callers fell back to a hostId when the org lookup missed, and a\n * hostId must never be read as an org id. AGL-1656 removed that fallback\n * instead of accommodating it — a hostId and an orgId hash to different\n * buckets, so a mid-rollout flag could land the published site and the\n * console on opposite sides of the same percentage for the same workspace.\n * With one subject the two cannot disagree by construction, and there is no\n * longer a parameter through which a non-org subject could be reintroduced.\n */\nexport async function filterEnabledPluginsByReleaseFlags(\n pluginIds: readonly string[],\n options: {\n /**\n * The org this request belongs to: rollout bucket AND override key.\n * Null when no org could be resolved — a subject-less request gets the\n * fully-enabled flags only, never a partial rollout.\n */\n orgId?: string | null\n /** Raw Authorization header, when the caller has one (API dispatch). */\n authorization?: string | null\n /**\n * The account a TOKENLESS request acts for, as its route proved it\n * (AGL-2978) — see `PluginApiRequestSubject.uid`. Consulted for the staff\n * preview only, and only when the request carries no bearer token: a\n * request with a token is the token's, whatever else it names.\n */\n subjectUid?: string | null\n },\n): Promise<string[]> {\n const [values, targeting] = await Promise.all([\n getServerReleaseFlagValues(),\n getOrgReleaseFlagTargeting(options.orgId),\n ])\n const isFlagOn = (flagKey: string): boolean =>\n isReleaseFlagKey(flagKey)\n ? isReleaseFlagOnForOrg(\n flagKey,\n values[flagKey],\n options.orgId ?? null,\n targeting.overrides,\n targeting.plan,\n )\n : true\n const filtered = filterPluginsByReleaseFlags(pluginIds, isFlagOn)\n if (filtered.length === pluginIds.length) return filtered\n\n const authorization = options.authorization ?? ''\n if (authorization.startsWith('Bearer ')) {\n try {\n const decoded = await firebaseAdmin\n .app()\n .auth()\n .verifyIdToken(authorization.slice('Bearer '.length))\n if (decoded['staff'] === true) return [...pluginIds]\n } catch {\n // Invalid token — gate as anonymous.\n }\n return filtered\n }\n if (options.subjectUid) {\n // The same claim the token path reads, looked up by account: a staff\n // member's own provider redirect carries no token, and previewing a dark\n // plugin has to survive the round trip their session started. Paid only\n // when a flag actually subtracted something and a route vouched for the\n // account. Across every auth pool (AGL-1122): a staff member who signs in\n // through SSO is a tenant user the project pool does not hold.\n try {\n const account = await findUserByUidAcrossPools(options.subjectUid)\n if (account?.record.customClaims?.['staff'] === true) return [...pluginIds]\n } catch {\n // Auth did not answer — gate as anonymous.\n }\n }\n return filtered\n}\n"],"names":["filterPluginsByReleaseFlags","isReleaseFlagKey","isReleaseFlagOnForOrg","parseOrgReleaseFlagOverrides","parseReleaseFlagValue","RELEASE_FLAGS","resolveEffectivePlan","findUserByUidAcrossPools","firebaseAdmin","TTL_MS","cache","pending","registryDefaults","Object","fromEntries","map","definition","key","enabled","defaultEnabled","getServerReleaseFlagValues","Date","now","at","values","template","app","remoteConfig","getTemplate","parameter","parameters","defaultValue","raw","value","undefined","finally","orgCache","Map","getOrgReleaseFlagTargeting","orgId","overrides","plan","hit","get","targeting","snapshot","firestore","collection","doc","data","set","getOrgReleaseFlagOverrides","isServerReleaseFlagOnForOrg","flagKey","Promise","all","__resetReleaseFlagCaches","clear","filterEnabledPluginsByReleaseFlags","pluginIds","options","isFlagOn","filtered","length","authorization","startsWith","decoded","auth","verifyIdToken","slice","subjectUid","account","record","customClaims"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,2BAA2B,EAC3BC,gBAAgB,EAChBC,qBAAqB,EACrBC,4BAA4B,EAC5BC,qBAAqB,EACrBC,aAAa,EACbC,oBAAoB,QAKf,sBAAqB;AAC5B,SAASC,wBAAwB,QAAQ,kBAAc;AACvD,SAASC,aAAa,QAAQ,sBAAkB;AAEhD;;;;;;;;;;;CAWC,GAED,MAAMC,SAAS;AAEf,IAAIC;AAGJ,IAAIC;AAIJ,MAAMC,mBAAmB,IACvBC,OAAOC,WAAW,CAChBT,cAAcU,GAAG,CAAC,CAACC,aAAe;YAChCA,WAAWC,GAAG;YACd;gBAAEC,SAASF,W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MAAM,EAAE,OAAOD;IAEjD,MAAME,iBAAgBJ,yBAAAA,QAAQI,aAAa,YAArBJ,yBAAyB;IAC/C,IAAII,cAAcC,UAAU,CAAC,YAAY;QACvC,IAAI;YACF,MAAMC,UAAU,MAAM1D,cACnBkB,GAAG,GACHyC,IAAI,GACJC,aAAa,CAACJ,cAAcK,KAAK,CAAC,UAAUN,MAAM;YACrD,IAAIG,OAAO,CAAC,QAAQ,KAAK,MAAM,OAAO;mBAAIP;aAAU;QACtD,EAAE,eAAM;QACN,qCAAqC;QACvC;QACA,OAAOG;IACT;IACA,IAAIF,QAAQU,UAAU,EAAE;QACtB,qEAAqE;QACrE,yEAAyE;QACzE,wEAAwE;QACxE,wEAAwE;QACxE,0EAA0E;QAC1E,+DAA+D;QAC/D,IAAI;gBAEEC;YADJ,MAAMA,UAAU,MAAMhE,yBAAyBqD,QAAQU,UAAU;YACjE,IAAIC,CAAAA,4BAAAA,+BAAAA,QAASC,MAAM,CAACC,YAAY,qBAA5BF,4BAA8B,CAAC,QAAQ,MAAK,MAAM,OAAO;mBAAIZ;aAAU;QAC7E,EAAE,eAAM;QACN,2CAA2C;QAC7C;IACF;IACA,OAAOG;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/release-flags.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 filterPluginsByReleaseFlags,\n isReleaseFlagKey,\n isReleaseFlagOnForOrg,\n parseOrgReleaseFlagOverrides,\n parseReleaseFlagValue,\n RELEASE_FLAGS,\n resolveEffectivePlan,\n type OrgPlan,\n type OrgReleaseFlagOverrides,\n type ReleaseFlagKey,\n type ReleaseFlagValue,\n} from '@aglyn/aglyn/server'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * Server-side release-flag verdicts (AGL-422): the tenant loader and the\n * API dispatchers subtract flagged-off plugins, so the server needs the\n * same Remote Config values the console client activates. The admin SDK\n * template read is cached with a short TTL — flag flips propagate within\n * a minute without a per-request round trip.\n *\n * Fail-open to the REGISTRY DEFAULTS (not \"all on\"): environments without\n * Remote Config (emulator e2e, local dev) behave exactly like an\n * unpublished template does on the client, so verdicts agree across\n * surfaces.\n */\n\nconst TTL_MS = 60_000\n\nlet cache:\n | { at: number; values: Record<ReleaseFlagKey, ReleaseFlagValue> }\n | undefined\nlet pending:\n | Promise<Record<ReleaseFlagKey, ReleaseFlagValue>>\n | undefined\n\nconst registryDefaults = (): Record<ReleaseFlagKey, ReleaseFlagValue> =>\n Object.fromEntries(\n RELEASE_FLAGS.map((definition) => [\n definition.key,\n { enabled: definition.defaultEnabled },\n ]),\n ) as Record<ReleaseFlagKey, ReleaseFlagValue>\n\nexport async function getServerReleaseFlagValues(): Promise<\n Record<ReleaseFlagKey, ReleaseFlagValue>\n> {\n if (cache && Date.now() - cache.at < TTL_MS) return cache.values\n if (!pending) {\n pending = (async () => {\n const values = registryDefaults()\n try {\n const template = await firebaseAdmin.app().remoteConfig().getTemplate()\n for (const definition of RELEASE_FLAGS) {\n const parameter = template.parameters[definition.key]\n const defaultValue = parameter?.defaultValue\n const raw =\n defaultValue && 'value' in defaultValue\n ? defaultValue.value\n : undefined\n values[definition.key] = parseReleaseFlagValue(\n raw,\n definition.defaultEnabled,\n )\n }\n } catch {\n // No Remote Config here (emulator/local) — registry defaults gate.\n }\n cache = { at: Date.now(), values }\n return values\n })().finally(() => {\n pending = undefined\n })\n }\n return pending\n}\n\n/**\n * Per-org release-flag overrides (AGL-1635), read off `orgs/{orgId}`.\n *\n * Cached on the same TTL as the template read above, and for the same\n * reason: these are consulted on every published page render and every API\n * dispatch, so an uncached read would add a Firestore round trip to the hot\n * path. A grant therefore takes up to a minute to land, matching how long a\n * flag flip already takes — one propagation story, not two.\n *\n * Keyed by orgId because a subject may be a uid or a hostId, and only an\n * org can carry overrides. Failure is silent and yields `{}`: a missing org\n * doc or a denied read must gate exactly as \"no override set\", never as an\n * error that takes a published page down.\n */\n/**\n * What one org read answers about release flags: the staff overrides, and\n * the org's EFFECTIVE plan for tier targeting (AGL-2486).\n *\n * `plan` is null when the read did not produce an org document — missing,\n * denied, or no Firestore at all. Deliberately not `'free'`: an org whose\n * doc could not be read has an UNKNOWN tier, and\n * `resolveEffectivePlan(undefined)` answers `'free'`, which would hand a\n * Free-targeted flag to every org the read failed for. The two cases have to\n * stay distinguishable at the boundary, because the evaluator treats an\n * unknown plan as a refusal and a known `'free'` as a match.\n */\ninterface OrgReleaseFlagTargeting {\n overrides: OrgReleaseFlagOverrides\n plan: OrgPlan | null\n}\n\nconst orgCache = new Map<string, { at: number; targeting: OrgReleaseFlagTargeting }>()\n/** One read in flight per org: concurrent misses on one instance share it. */\nconst orgPending = new Map<string, Promise<OrgReleaseFlagTargeting>>()\n\n/**\n * The org fields the targeting answer is made of, and the only ones read\n * (AGL-4121). `releaseFlags` is the overrides; the rest is everything\n * `resolveEffectivePlan` consults: the stored `plan`, the subscription status\n * (`billingStatus` mirror first, then `subscription.status`), and a staff comp\n * (`entitlements.planComp`).\n *\n * This read runs once a minute per org on every warm instance that renders a\n * page or dispatches an API call, and the org document is one of the largest\n * the tenant reads, so fetching all of it to use five fields was paying\n * Firestore egress for nothing. A field that `resolveEffectivePlan` starts\n * reading must be added here: `release-flags-org-field-mask.spec.ts` resolves\n * the plan from the masked projection and from the whole document and fails\n * when they disagree.\n */\nexport const ORG_RELEASE_FLAG_FIELDS = [\n 'releaseFlags',\n 'plan',\n 'billingStatus',\n 'subscription.status',\n 'entitlements.planComp',\n] as const\n\n/** The targeting answer from an org document already in hand, or `null` for none. */\nfunction targetingFromOrgData(\n data: Record<string, unknown> | null | undefined,\n): OrgReleaseFlagTargeting {\n return {\n overrides: parseOrgReleaseFlagOverrides(data?.['releaseFlags']),\n // Only when a document actually came back. `resolveEffectivePlan` would\n // read a missing doc as Free.\n plan: data ? resolveEffectivePlan(data as any) : null,\n }\n}\n\n/**\n * Both halves of the per-org answer from ONE cached document read.\n *\n * Sharing the read is the point: `plan` and `releaseFlags` live on the same\n * org document, this runs on every published page render and every API\n * dispatch, and fetching the tier separately would have doubled the hot-path\n * Firestore traffic to learn something already in hand.\n */\nexport async function getOrgReleaseFlagTargeting(\n orgId: string | null | undefined,\n): Promise<OrgReleaseFlagTargeting> {\n if (!orgId) return { overrides: {}, plan: null }\n const hit = orgCache.get(orgId)\n if (hit && Date.now() - hit.at < TTL_MS) return hit.targeting\n const inFlight = orgPending.get(orgId)\n if (inFlight) return inFlight\n const pending = (async () => {\n let targeting: OrgReleaseFlagTargeting = { overrides: {}, plan: null }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const [snapshot] = await firestore.getAll(\n firestore.collection('orgs').doc(orgId),\n { fieldMask: [...ORG_RELEASE_FLAG_FIELDS] },\n )\n targeting = targetingFromOrgData(\n snapshot?.data() as Record<string, unknown> | undefined,\n )\n } catch {\n // No Firestore here, or the doc is unreadable — inherit, never fail.\n }\n orgCache.set(orgId, { at: Date.now(), targeting })\n return targeting\n })().finally(() => {\n orgPending.delete(orgId)\n })\n orgPending.set(orgId, pending)\n return pending\n}\n\nexport async function getOrgReleaseFlagOverrides(\n orgId: string | null | undefined,\n): Promise<OrgReleaseFlagOverrides> {\n return (await getOrgReleaseFlagTargeting(orgId)).overrides\n}\n\n/**\n * The verdict for ONE flag and ONE org, overrides applied (AGL-1635).\n *\n * The surfaces that gate a single flag server-side — the tenant admin bar\n * slot, edit-context redemption, edit-access minting — resolve through here\n * rather than reading `getServerReleaseFlagValues()` and calling\n * `isReleaseFlagOn` themselves, so a per-org grant reaches all of them at\n * once. A gate that kept the old two-step would silently ignore overrides,\n * which is the failure this issue exists to fix.\n */\nexport async function isServerReleaseFlagOnForOrg(\n flagKey: ReleaseFlagKey,\n orgId: string | null | undefined,\n): Promise<boolean> {\n const [values, targeting] = await Promise.all([\n getServerReleaseFlagValues(),\n getOrgReleaseFlagTargeting(orgId),\n ])\n return isReleaseFlagOnForOrg(\n flagKey,\n values[flagKey],\n orgId ?? null,\n targeting.overrides,\n targeting.plan,\n )\n}\n\n/**\n * {@link isServerReleaseFlagOnForOrg} for a caller that already holds the org\n * document (AGL-4121): the same verdict, with the targeting taken from `org`\n * instead of a second read of the same document.\n *\n * For request-time callers whose copy is no older than this module's own\n * minute — the lockdown verdict holds the org through `getOrgBilling`'s\n * 60-second request entry — so a grant still lands within the minute it\n * always took. `org` null means the caller looked and found none, and answers\n * as an unreadable org does: no overrides, unknown tier.\n */\nexport async function isServerReleaseFlagOnForLoadedOrg(\n flagKey: ReleaseFlagKey,\n orgId: string | null | undefined,\n org: Record<string, unknown> | null,\n): Promise<boolean> {\n const values = await getServerReleaseFlagValues()\n const targeting = orgId ? targetingFromOrgData(org) : { overrides: {}, plan: null }\n return isReleaseFlagOnForOrg(\n flagKey,\n values[flagKey],\n orgId ?? null,\n targeting.overrides,\n targeting.plan,\n )\n}\n\n/** Test seam: drops both caches so a spec can change a verdict. */\nexport function __resetReleaseFlagCaches(): void {\n cache = undefined\n orgCache.clear()\n orgPending.clear()\n}\n\n/**\n * The server half of the plugin release gate (AGL-422): subtracts\n * flagged-off first-party plugins from an effective set. The staff bypass is\n * only paid for when something was actually subtracted AND the request\n * carries a bearer token — the common all-flags-on path never verifies.\n *\n * `orgId` is the ONLY subject: it selects the per-org overrides (AGL-1635)\n * and it is the rollout bucket. AGL-1635 took a separate `subjectId` here\n * because callers fell back to a hostId when the org lookup missed, and a\n * hostId must never be read as an org id. AGL-1656 removed that fallback\n * instead of accommodating it — a hostId and an orgId hash to different\n * buckets, so a mid-rollout flag could land the published site and the\n * console on opposite sides of the same percentage for the same workspace.\n * With one subject the two cannot disagree by construction, and there is no\n * longer a parameter through which a non-org subject could be reintroduced.\n */\nexport async function filterEnabledPluginsByReleaseFlags(\n pluginIds: readonly string[],\n options: {\n /**\n * The org this request belongs to: rollout bucket AND override key.\n * Null when no org could be resolved — a subject-less request gets the\n * fully-enabled flags only, never a partial rollout.\n */\n orgId?: string | null\n /** Raw Authorization header, when the caller has one (API dispatch). */\n authorization?: string | null\n /**\n * The account a TOKENLESS request acts for, as its route proved it\n * (AGL-2978) — see `PluginApiRequestSubject.uid`. Consulted for the staff\n * preview only, and only when the request carries no bearer token: a\n * request with a token is the token's, whatever else it names.\n */\n subjectUid?: string | null\n },\n): Promise<string[]> {\n const [values, targeting] = await Promise.all([\n getServerReleaseFlagValues(),\n getOrgReleaseFlagTargeting(options.orgId),\n ])\n const isFlagOn = (flagKey: string): boolean =>\n isReleaseFlagKey(flagKey)\n ? isReleaseFlagOnForOrg(\n flagKey,\n values[flagKey],\n options.orgId ?? null,\n targeting.overrides,\n targeting.plan,\n )\n : true\n const filtered = filterPluginsByReleaseFlags(pluginIds, isFlagOn)\n if (filtered.length === pluginIds.length) return filtered\n\n const authorization = options.authorization ?? ''\n if (authorization.startsWith('Bearer ')) {\n try {\n const decoded = await firebaseAdmin\n .app()\n .auth()\n .verifyIdToken(authorization.slice('Bearer '.length))\n if (decoded['staff'] === true) return [...pluginIds]\n } catch {\n // Invalid token — gate as anonymous.\n }\n return filtered\n }\n if (options.subjectUid) {\n // The same claim the token path reads, looked up by account: a staff\n // member's own provider redirect carries no token, and previewing a dark\n // plugin has to survive the round trip their session started. Paid only\n // when a flag actually subtracted something and a route vouched for the\n // account. Across every auth pool (AGL-1122): a staff member who signs in\n // through SSO is a tenant user the project pool does not hold.\n try {\n const account = await findUserByUidAcrossPools(options.subjectUid)\n if (account?.record.customClaims?.['staff'] === true) return [...pluginIds]\n } catch {\n // Auth did not answer — gate as anonymous.\n }\n }\n return filtered\n}\n"],"names":["filterPluginsByReleaseFlags","isReleaseFlagKey","isReleaseFlagOnForOrg","parseOrgReleaseFlagOverrides","parseReleaseFlagValue","RELEASE_FLAGS","resolveEffectivePlan","findUserByUidAcrossPools","firebaseAdmin","TTL_MS","cache","pending","registryDefaults","Object","fromEntries","map","definition","key","enabled","defaultEnabled","getServerReleaseFlagValues","Date","now","at","values","template","app","remoteConfig","getTemplate","parameter","parameters","defaultValue","raw","value","undefined","finally","orgCache","Map","orgPending","ORG_RELEASE_FLAG_FIELDS","targetingFromOrgData","data","overrides","plan","getOrgReleaseFlagTargeting","orgId","hit","get","targeting","inFlight","firestore","snapshot","getAll","collection","doc","fieldMask","set","delete","getOrgReleaseFlagOverrides","isServerReleaseFlagOnForOrg","flagKey","Promise","all","isServerReleaseFlagOnForLoadedOrg","org","__resetReleaseFlagCaches","clear","filterEnabledPluginsByReleaseFlags","pluginIds","options","isFlagOn","filtered","length","authorization","startsWith","decoded","auth","verifyIdToken","slice","subjectUid","account","record","customClaims"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,2BAA2B,EAC3BC,gBAAgB,EAChBC,qBAAqB,EACrBC,4BAA4B,EAC5BC,qBAAqB,EACrBC,aAAa,EACbC,oBAAoB,QAKf,sBAAqB;AAC5B,SAASC,wBAAwB,QAAQ,kBAAc;AACvD,SAASC,aAAa,QAAQ,sBAAkB;AAEhD;;;;;;;;;;;CAWC,GAED,MAAMC,SAAS;AAEf,IAAIC;AAGJ,IAAIC;AAIJ,MAAMC,mBAAmB,IACvBC,OAAOC,WAAW,CAChBT,cAAcU,GAAG,CAAC,CAACC,aAAe;YAChCA,WAAWC,GAAG;YACd;gBAAEC,SAASF,WAAWG,cAAc;YAAC;SACtC;AAGL,OAAO,eAAeC;IAGpB,IAAIV,SAASW,KAAKC,GAAG,KAAKZ,MAAMa,EAAE,GAAGd,QAAQ,OAAOC,MAAMc,MAAM;IAChE,IAAI,CAACb,SAAS;QACZA,UAAU,AA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ASC,MAAM,CAACC,YAAY,qBAA5BF,4BAA8B,CAAC,QAAQ,MAAK,MAAM,OAAO;mBAAIZ;aAAU;QAC7E,EAAE,eAAM;QACN,2CAA2C;QAC7C;IACF;IACA,OAAOG;AACT"}
|
|
@@ -0,0 +1,53 @@
|
|
|
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 SaleChargeModel } from './payment-provider';
|
|
18
|
+
/**
|
|
19
|
+
* The Stripe account a site sells into, and how it sells (direct or
|
|
20
|
+
* destination), as recorded for it.
|
|
21
|
+
*
|
|
22
|
+
* ONE place reads where that record lives. Today it is the site owner's
|
|
23
|
+
* profile (`profiles/{ownerUid}`: `stripeAccountId`, `stripeChargeModel`,
|
|
24
|
+
* `stripeChargesEnabled`, `stripeAccountLivemode`), so one account serves
|
|
25
|
+
* every workspace that person owns. When the account moves to the workspace
|
|
26
|
+
* (one account per store, as the hosted store builders do), this function is
|
|
27
|
+
* the one that changes: the in-person money routes (the register's card
|
|
28
|
+
* readers, Tap to Pay, booking payments at the counter) ask it and nothing
|
|
29
|
+
* else.
|
|
30
|
+
*
|
|
31
|
+
* Readiness is NOT decided here: the fields are returned as recorded, for
|
|
32
|
+
* `merchantAccountIsReady` to judge at the door that charges. A Terminal
|
|
33
|
+
* Location or reader belongs on the account whatever its readiness.
|
|
34
|
+
*/
|
|
35
|
+
export interface SellerPaymentAccount {
|
|
36
|
+
/** The connected account id, trimmed. */
|
|
37
|
+
accountId: string;
|
|
38
|
+
/** `direct` only when recorded so; anything else is a destination seller. */
|
|
39
|
+
chargeModel: SaleChargeModel;
|
|
40
|
+
/** As recorded (`stripeChargesEnabled`), for the readiness rule. */
|
|
41
|
+
chargesEnabled: unknown;
|
|
42
|
+
/** As recorded (`stripeAccountLivemode`), for the readiness rule. */
|
|
43
|
+
accountLivemode: unknown;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The site's selling account, or null when none is recorded.
|
|
47
|
+
*
|
|
48
|
+
* `org` is the owning workspace when the caller already holds it (`null`
|
|
49
|
+
* means the site has none, and so no account); omitted, it is looked up.
|
|
50
|
+
* A failed read throws: a caller that guessed "the platform" on an error
|
|
51
|
+
* would put a direct seller's money or readers on the wrong account.
|
|
52
|
+
*/
|
|
53
|
+
export declare function sellerPaymentAccount(hostId: string, org?: Record<string, any> | null): Promise<SellerPaymentAccount | null>;
|
|
@@ -0,0 +1,43 @@
|
|
|
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 firebaseAdmin from "./firebase-admin.js";
|
|
17
|
+
import { getOrgForHost } from "./organizations.js";
|
|
18
|
+
import { saleChargeModel } from "./payment-provider.js";
|
|
19
|
+
/**
|
|
20
|
+
* The site's selling account, or null when none is recorded.
|
|
21
|
+
*
|
|
22
|
+
* `org` is the owning workspace when the caller already holds it (`null`
|
|
23
|
+
* means the site has none, and so no account); omitted, it is looked up.
|
|
24
|
+
* A failed read throws: a caller that guessed "the platform" on an error
|
|
25
|
+
* would put a direct seller's money or readers on the wrong account.
|
|
26
|
+
*/ export async function sellerPaymentAccount(hostId, org) {
|
|
27
|
+
var _ref, _ref1, _profile_get;
|
|
28
|
+
var _this;
|
|
29
|
+
const owner = org !== undefined ? org : (_ref = (_this = await getOrgForHost(hostId)) == null ? void 0 : _this.org) != null ? _ref : null;
|
|
30
|
+
const ownerUid = String((_ref1 = owner == null ? void 0 : owner['ownerUid']) != null ? _ref1 : '');
|
|
31
|
+
if (!ownerUid) return null;
|
|
32
|
+
const profile = await firebaseAdmin.app().firestore().collection('profiles').doc(ownerUid).get();
|
|
33
|
+
const accountId = String((_profile_get = profile.get('stripeAccountId')) != null ? _profile_get : '').trim();
|
|
34
|
+
if (!accountId) return null;
|
|
35
|
+
return {
|
|
36
|
+
accountId,
|
|
37
|
+
chargeModel: saleChargeModel(profile.get('stripeChargeModel')),
|
|
38
|
+
chargesEnabled: profile.get('stripeChargesEnabled'),
|
|
39
|
+
accountLivemode: profile.get('stripeAccountLivemode')
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=seller-payment-account.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/seller-payment-account.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 firebaseAdmin from './firebase-admin'\nimport { getOrgForHost } from './organizations'\nimport { saleChargeModel, type SaleChargeModel } from './payment-provider'\n\n/**\n * The Stripe account a site sells into, and how it sells (direct or\n * destination), as recorded for it.\n *\n * ONE place reads where that record lives. Today it is the site owner's\n * profile (`profiles/{ownerUid}`: `stripeAccountId`, `stripeChargeModel`,\n * `stripeChargesEnabled`, `stripeAccountLivemode`), so one account serves\n * every workspace that person owns. When the account moves to the workspace\n * (one account per store, as the hosted store builders do), this function is\n * the one that changes: the in-person money routes (the register's card\n * readers, Tap to Pay, booking payments at the counter) ask it and nothing\n * else.\n *\n * Readiness is NOT decided here: the fields are returned as recorded, for\n * `merchantAccountIsReady` to judge at the door that charges. A Terminal\n * Location or reader belongs on the account whatever its readiness.\n */\nexport interface SellerPaymentAccount {\n /** The connected account id, trimmed. */\n accountId: string\n /** `direct` only when recorded so; anything else is a destination seller. */\n chargeModel: SaleChargeModel\n /** As recorded (`stripeChargesEnabled`), for the readiness rule. */\n chargesEnabled: unknown\n /** As recorded (`stripeAccountLivemode`), for the readiness rule. */\n accountLivemode: unknown\n}\n\n/**\n * The site's selling account, or null when none is recorded.\n *\n * `org` is the owning workspace when the caller already holds it (`null`\n * means the site has none, and so no account); omitted, it is looked up.\n * A failed read throws: a caller that guessed \"the platform\" on an error\n * would put a direct seller's money or readers on the wrong account.\n */\nexport async function sellerPaymentAccount(\n hostId: string,\n org?: Record<string, any> | null,\n): Promise<SellerPaymentAccount | null> {\n const owner =\n org !== undefined\n ? org\n : (((await getOrgForHost(hostId))?.org as Record<string, any> | undefined) ?? null)\n const ownerUid = String(owner?.['ownerUid'] ?? '')\n if (!ownerUid) return null\n const profile = await firebaseAdmin\n .app()\n .firestore()\n .collection('profiles')\n .doc(ownerUid)\n .get()\n const accountId = String(profile.get('stripeAccountId') ?? '').trim()\n if (!accountId) return null\n return {\n accountId,\n chargeModel: saleChargeModel(profile.get('stripeChargeModel')),\n chargesEnabled: profile.get('stripeChargesEnabled'),\n accountLivemode: profile.get('stripeAccountLivemode'),\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","saleChargeModel","sellerPaymentAccount","hostId","org","profile","owner","undefined","ownerUid","String","app","firestore","collection","doc","get","accountId","trim","chargeModel","chargesEnabled","accountLivemode"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,OAAOA,mBAAmB,sBAAkB;AAC5C,SAASC,aAAa,QAAQ,qBAAiB;AAC/C,SAASC,eAAe,QAA8B,wBAAoB;AA8B1E;;;;;;;CAOC,GACD,OAAO,eAAeC,qBACpBC,MAAc,EACdC,GAAgC;qBAcPC;QAThB;IAHT,MAAMC,QACJF,QAAQG,YACJH,eACG,QAAA,MAAMJ,cAAcG,4BAArB,AAAC,MAA8BC,GAAG,mBAAwC;IAClF,MAAMI,WAAWC,gBAAOH,yBAAAA,KAAO,CAAC,WAAW,oBAAI;IAC/C,IAAI,CAACE,UAAU,OAAO;IACtB,MAAMH,UAAU,MAAMN,cACnBW,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,YACXC,GAAG,CAACL,UACJM,GAAG;IACN,MAAMC,YAAYN,QAAOJ,eAAAA,QAAQS,GAAG,CAAC,8BAAZT,eAAkC,IAAIW,IAAI;IACnE,IAAI,CAACD,WAAW,OAAO;IACvB,OAAO;QACLA;QACAE,aAAahB,gBAAgBI,QAAQS,GAAG,CAAC;QACzCI,gBAAgBb,QAAQS,GAAG,CAAC;QAC5BK,iBAAiBd,QAAQS,GAAG,CAAC;IAC/B;AACF"}
|