@aglyn/tenant-data-admin 1.0.0-beta.269 → 1.0.0-beta.270
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 +10 -3
- package/src/lib/render-cache.js +10 -3
- package/src/lib/render-cache.js.map +1 -1
- package/src/lib/server/billing-addons.d.ts +8 -6
- package/src/lib/server/billing-addons.js +19 -8
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/configured-url-fetch.d.ts +26 -0
- package/src/lib/server/configured-url-fetch.js +68 -0
- package/src/lib/server/configured-url-fetch.js.map +1 -1
- package/src/lib/server/custom-domain-redirects.d.ts +50 -0
- package/src/lib/server/custom-domain-redirects.js +61 -0
- package/src/lib/server/custom-domain-redirects.js.map +1 -0
- package/src/lib/server/host-custom-domain.d.ts +125 -0
- package/src/lib/server/host-custom-domain.js +395 -0
- package/src/lib/server/host-custom-domain.js.map +1 -0
- package/src/lib/server/host-released-names.d.ts +1 -2
- package/src/lib/server/host-released-names.js +4 -2
- package/src/lib/server/host-released-names.js.map +1 -1
- package/src/lib/server/media-photo-links.d.ts +196 -0
- package/src/lib/server/media-photo-links.js +290 -0
- package/src/lib/server/media-photo-links.js.map +1 -0
- package/src/lib/server/organizations.d.ts +25 -1
- package/src/lib/server/organizations.js +62 -2
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/personal-data-export.js +21 -1
- package/src/lib/server/personal-data-export.js.map +1 -1
- package/src/lib/server/push-delivery.js +32 -14
- package/src/lib/server/push-delivery.js.map +1 -1
- package/src/lib/server/tenant-dns-check.d.ts +58 -0
- package/src/lib/server/tenant-dns-check.js +197 -0
- package/src/lib/server/tenant-dns-check.js.map +1 -0
- package/src/tenancy.d.ts +4 -0
- package/src/tenancy.js +8 -0
- package/src/tenancy.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-data-admin",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.270",
|
|
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.0.0-beta.
|
|
29
|
-
"@aglyn/shared-util-email": "1.0.0-beta.
|
|
30
|
-
"@aglyn/shared-util-fbserver": "1.0.0-beta.
|
|
31
|
-
"@aglyn/shared-util-first-touch": "1.0.0-beta.
|
|
32
|
-
"@aglyn/shared-util-http": "1.0.0-beta.
|
|
33
|
-
"@aglyn/shared-util-tools": "1.0.0-beta.
|
|
28
|
+
"@aglyn/aglyn": "1.0.0-beta.270",
|
|
29
|
+
"@aglyn/shared-util-email": "1.0.0-beta.270",
|
|
30
|
+
"@aglyn/shared-util-fbserver": "1.0.0-beta.270",
|
|
31
|
+
"@aglyn/shared-util-first-touch": "1.0.0-beta.270",
|
|
32
|
+
"@aglyn/shared-util-http": "1.0.0-beta.270",
|
|
33
|
+
"@aglyn/shared-util-tools": "1.0.0-beta.270",
|
|
34
34
|
"@msgpack/msgpack": "^3.1.3",
|
|
35
35
|
"@swc/helpers": "0.5.23",
|
|
36
36
|
"sharp": "^0.35.5",
|
|
@@ -94,9 +94,16 @@ export declare const tenantDataTag: (hostId: string) => string;
|
|
|
94
94
|
* ⛔ NOT for reads that change OUTSIDE a publish. Two deliberately keep their
|
|
95
95
|
* own short TTLs and must not be moved onto this one:
|
|
96
96
|
*
|
|
97
|
-
* - `ORG_BILLING_TTL_SECONDS` —
|
|
98
|
-
*
|
|
99
|
-
*
|
|
97
|
+
* - `ORG_BILLING_TTL_SECONDS` — the request-time org read (the lockdown
|
|
98
|
+
* verdict and the other dynamic routes), where a bandwidth cap or a
|
|
99
|
+
* suspension stamped straight onto the doc arrives by TTL alone. The
|
|
100
|
+
* render's own org read is on this backstop instead (`scope: 'render'`):
|
|
101
|
+
* plan transitions, staff overrides and org settings all announce
|
|
102
|
+
* themselves through `revalidateOrgHosts`.
|
|
103
|
+
*
|
|
104
|
+
* ⚠️ Any TTL read inside the ISR render also caps the PAGE: `unstable_cache`
|
|
105
|
+
* lowers the regeneration's `revalidate` to the shortest TTL it saw, so one
|
|
106
|
+
* 60s entry holds the catch-all's 3600 at 60.
|
|
100
107
|
* - `HOST_ALIAS_TTL_SECONDS` / `HOST_DOC_TTL_SECONDS` — a custom domain
|
|
101
108
|
* attaching is the customer sitting there waiting for their site
|
|
102
109
|
* (AGL-2010), and the `cname--` alias entry expires only by TTL.
|
package/src/lib/render-cache.js
CHANGED
|
@@ -92,9 +92,16 @@
|
|
|
92
92
|
* ⛔ NOT for reads that change OUTSIDE a publish. Two deliberately keep their
|
|
93
93
|
* own short TTLs and must not be moved onto this one:
|
|
94
94
|
*
|
|
95
|
-
* - `ORG_BILLING_TTL_SECONDS` —
|
|
96
|
-
*
|
|
97
|
-
*
|
|
95
|
+
* - `ORG_BILLING_TTL_SECONDS` — the request-time org read (the lockdown
|
|
96
|
+
* verdict and the other dynamic routes), where a bandwidth cap or a
|
|
97
|
+
* suspension stamped straight onto the doc arrives by TTL alone. The
|
|
98
|
+
* render's own org read is on this backstop instead (`scope: 'render'`):
|
|
99
|
+
* plan transitions, staff overrides and org settings all announce
|
|
100
|
+
* themselves through `revalidateOrgHosts`.
|
|
101
|
+
*
|
|
102
|
+
* ⚠️ Any TTL read inside the ISR render also caps the PAGE: `unstable_cache`
|
|
103
|
+
* lowers the regeneration's `revalidate` to the shortest TTL it saw, so one
|
|
104
|
+
* 60s entry holds the catch-all's 3600 at 60.
|
|
98
105
|
* - `HOST_ALIAS_TTL_SECONDS` / `HOST_DOC_TTL_SECONDS` — a custom domain
|
|
99
106
|
* attaching is the customer sitting there waiting for their site
|
|
100
107
|
* (AGL-2010), and the `cname--` alias entry expires only by TTL.
|
|
@@ -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` — a plan change happens in the console and\n * nothing busts the tenant tag for it, so this TTL is the ONLY thing\n * propagating an upgrade or a downgrade to the live site.\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCC,GACD,OAAO,MAAMC,kCAAkC,KAAI;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwCC,GACD,OAAO,MAAMC,8BAA8B,IAAG;AAE9C;;;;CAIC,GACD,OAAO,MAAMC,qBAAqB,CAACC,QACjC,CAAC,YAAY,EAAEA,OAAO,CAAA;AAExB;;;;CAIC,GACD,IAAA,AAAMC,cAAN,MAAMA,oBAAoBC;IACxB,YAAY,AAASC,KAAc,CAAE;QACnC,KAAK,CAAC,6BADaA,QAAAA;QAEnB,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA,MAAMC,4BAA4B,CAACC,QACjCA,iBAAiBJ,SAASI,MAAMC,OAAO,CAACC,QAAQ,CAAC;AAEnD;;;;CAIC,GACD,OAAO,SAASC,YAAeN,KAAQ;IACrC,IAAIA,UAAUO,aAAaP,UAAU,MAAM,OAAOA;IAClD,OAAOQ,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACV;AACnC;AAwBA,OAAO,eAAeW,gBACpBC,OAA8B;IAE9B,MAAM,EAAEC,GAAG,EAAEC,UAAU,EAAEC,IAAI,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAC/C,MAAMM,SAAS3B,eACb;QACE,MAAMS,QAAQM,YAAY,MAAMU;QAChC,IAAIhB,UAAUO,aAAcU,SAAS,CAACA,MAAMjB,QAAS;YACnD,MAAM,IAAIF,YAAYE;QACxB;QACA,OAAOA;IACT,GACA;WAAIa;KAAI,EACR;QAAEC;QAAYC,MAAM;eAAIA;SAAK;IAAC;IAEhC,IAAI;QACF,OAAO,MAAMG;IACf,EAAE,OAAOf,OAAO;QACd,IAAIA,iBAAiBL,aAAa,OAAOK,MAAMH,KAAK;QACpD,uEAAuE;QACvE,sEAAsE;QACtE,IAAIE,0BAA0BC,QAAQ,OAAOG,YAAY,MAAMU;QAC/D,MAAMb;IACR;AACF"}
|
|
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GACD,OAAO,MAAMC,kCAAkC,KAAI;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwCC,GACD,OAAO,MAAMC,8BAA8B,IAAG;AAE9C;;;;CAIC,GACD,OAAO,MAAMC,qBAAqB,CAACC,QACjC,CAAC,YAAY,EAAEA,OAAO,CAAA;AAExB;;;;CAIC,GACD,IAAA,AAAMC,cAAN,MAAMA,oBAAoBC;IACxB,YAAY,AAASC,KAAc,CAAE;QACnC,KAAK,CAAC,6BADaA,QAAAA;QAEnB,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA,MAAMC,4BAA4B,CAACC,QACjCA,iBAAiBJ,SAASI,MAAMC,OAAO,CAACC,QAAQ,CAAC;AAEnD;;;;CAIC,GACD,OAAO,SAASC,YAAeN,KAAQ;IACrC,IAAIA,UAAUO,aAAaP,UAAU,MAAM,OAAOA;IAClD,OAAOQ,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACV;AACnC;AAwBA,OAAO,eAAeW,gBACpBC,OAA8B;IAE9B,MAAM,EAAEC,GAAG,EAAEC,UAAU,EAAEC,IAAI,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAC/C,MAAMM,SAAS3B,eACb;QACE,MAAMS,QAAQM,YAAY,MAAMU;QAChC,IAAIhB,UAAUO,aAAcU,SAAS,CAACA,MAAMjB,QAAS;YACnD,MAAM,IAAIF,YAAYE;QACxB;QACA,OAAOA;IACT,GACA;WAAIa;KAAI,EACR;QAAEC;QAAYC,MAAM;eAAIA;SAAK;IAAC;IAEhC,IAAI;QACF,OAAO,MAAMG;IACf,EAAE,OAAOf,OAAO;QACd,IAAIA,iBAAiBL,aAAa,OAAOK,MAAMH,KAAK;QACpD,uEAAuE;QACvE,sEAAsE;QACtE,IAAIE,0BAA0BC,QAAQ,OAAOG,YAAY,MAAMU;QAC/D,MAAMb;IACR;AACF"}
|
|
@@ -22,8 +22,8 @@ import { resolveOrgEntitlements, type OrgPlan, type OrgSeatAddons } from '@aglyn
|
|
|
22
22
|
* one subscription, so every kind has a monthly and a yearly price
|
|
23
23
|
* (Stripe allows a single interval per subscription; annual orgs attach
|
|
24
24
|
* the `_YEARLY` variants). Seat/member/dataset/host prices and the Aglyn AI
|
|
25
|
-
* add-on (AGL-2896) are per-plan; POS registers
|
|
26
|
-
* flat. Prices are minted by `tools/scripts/setup-stripe.mjs` — keep the
|
|
25
|
+
* add-on (AGL-2896) are per-plan; POS registers, the Event Calendar and
|
|
26
|
+
* Site Care (AGL-3954) are flat. Prices are minted by `tools/scripts/setup-stripe.mjs` — keep the
|
|
27
27
|
* three in sync.
|
|
28
28
|
*/
|
|
29
29
|
export type AddonKind = keyof Required<OrgSeatAddons>;
|
|
@@ -139,7 +139,7 @@ export declare function findPlanItem<T extends {
|
|
|
139
139
|
/**
|
|
140
140
|
* Monthly USD per unit for an add-on on a plan (yearly prices are ×12 of
|
|
141
141
|
* this); null when the plan doesn't sell the kind. Single pricing source
|
|
142
|
-
* of truth: `PLAN_PRICING` + the
|
|
142
|
+
* of truth: `PLAN_PRICING` + the three flat add-on constants.
|
|
143
143
|
*/
|
|
144
144
|
export declare function addonUnitUsd(kind: AddonKind, plan: OrgPlan): number | null;
|
|
145
145
|
/**
|
|
@@ -157,8 +157,10 @@ export declare function addonQuantitiesFromItems(items: Array<{
|
|
|
157
157
|
* Max purchasable quantity per kind, from a purchases-free entitlement
|
|
158
158
|
* resolution (plan defaults + staff overrides only) so the ceiling does not
|
|
159
159
|
* drift as the org buys: seat/dataset kinds stop at the plan's hard max,
|
|
160
|
-
* hosts/registers use flat ceilings, the Event Calendar
|
|
161
|
-
* toggles. POS registers additionally require the `pos`
|
|
160
|
+
* hosts/registers use flat ceilings, the Event Calendar, Aglyn AI and Site
|
|
161
|
+
* Care are 0/1 toggles. POS registers additionally require the `pos`
|
|
162
|
+
* feature, and Site Care a plan that sells it (`planSellsSiteCare`), which is
|
|
163
|
+
* why the plan travels with the baseline.
|
|
162
164
|
*
|
|
163
165
|
* Lives here rather than inside `/api/billing/addons` because a PLAN CHANGE
|
|
164
166
|
* needs the same ceiling for a different plan. The addons route asks "how many
|
|
@@ -166,6 +168,6 @@ export declare function addonQuantitiesFromItems(items: Array<{
|
|
|
166
168
|
* what it already bought can the plan it is moving to actually deliver". Two
|
|
167
169
|
* readers, one definition — a second copy is how they answer differently.
|
|
168
170
|
*/
|
|
169
|
-
export declare function addonMaxForBaseline(kind: AddonKind, baseline: ReturnType<typeof resolveOrgEntitlements
|
|
171
|
+
export declare function addonMaxForBaseline(kind: AddonKind, baseline: ReturnType<typeof resolveOrgEntitlements>, plan: OrgPlan): number;
|
|
170
172
|
/** The ceiling a PLAN would impose on an add-on kind, purchases excluded. */
|
|
171
173
|
export declare function addonMaxForPlan(kind: AddonKind, plan: OrgPlan): number;
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/ import { EVENT_CALENDAR_ADDON_MONTHLY_USD, EXTRA_HOSTS_ADDON_MAX, PLAN_PRICING, POS_REGISTER_ADDON_MONTHLY_USD, POS_REGISTERS_ADDON_MAX, resolveOrgEntitlements, SELF_SERVE_PLANS, UNLIMITED } from "@aglyn/aglyn/server";
|
|
16
|
+
*/ import { EVENT_CALENDAR_ADDON_MONTHLY_USD, EXTRA_HOSTS_ADDON_MAX, PLAN_PRICING, planSellsSiteCare, POS_REGISTER_ADDON_MONTHLY_USD, POS_REGISTERS_ADDON_MAX, resolveOrgEntitlements, SELF_SERVE_PLANS, SITE_CARE_ADDON_MONTHLY_USD, UNLIMITED } from "@aglyn/aglyn/server";
|
|
17
17
|
export const ADDON_KINDS = [
|
|
18
18
|
'managers',
|
|
19
19
|
'members',
|
|
@@ -21,7 +21,8 @@ export const ADDON_KINDS = [
|
|
|
21
21
|
'hosts',
|
|
22
22
|
'posRegisters',
|
|
23
23
|
'eventCalendar',
|
|
24
|
-
'aiAddon'
|
|
24
|
+
'aiAddon',
|
|
25
|
+
'siteCare'
|
|
25
26
|
];
|
|
26
27
|
/** Kinds priced per plan (env `STRIPE_PRICE_{PLAN}_{SUFFIX}[_YEARLY]`). */ const PER_PLAN_ENV_SUFFIX = {
|
|
27
28
|
managers: 'EXTRA_SEAT',
|
|
@@ -32,7 +33,8 @@ export const ADDON_KINDS = [
|
|
|
32
33
|
};
|
|
33
34
|
/** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */ const FLAT_ENV_NAME = {
|
|
34
35
|
posRegisters: 'POS_REGISTER',
|
|
35
|
-
eventCalendar: 'EVENT_CALENDAR'
|
|
36
|
+
eventCalendar: 'EVENT_CALENDAR',
|
|
37
|
+
siteCare: 'SITE_CARE'
|
|
36
38
|
};
|
|
37
39
|
/**
|
|
38
40
|
* Every plan that is sold with a Stripe price — DERIVED, never hand-listed
|
|
@@ -196,7 +198,7 @@ function env(name) {
|
|
|
196
198
|
/**
|
|
197
199
|
* Monthly USD per unit for an add-on on a plan (yearly prices are ×12 of
|
|
198
200
|
* this); null when the plan doesn't sell the kind. Single pricing source
|
|
199
|
-
* of truth: `PLAN_PRICING` + the
|
|
201
|
+
* of truth: `PLAN_PRICING` + the three flat add-on constants.
|
|
200
202
|
*/ export function addonUnitUsd(kind, plan) {
|
|
201
203
|
const pricing = PLAN_PRICING[plan];
|
|
202
204
|
switch(kind){
|
|
@@ -214,6 +216,8 @@ function env(name) {
|
|
|
214
216
|
return EVENT_CALENDAR_ADDON_MONTHLY_USD;
|
|
215
217
|
case 'aiAddon':
|
|
216
218
|
return pricing.aiAddonMonthlyUsd;
|
|
219
|
+
case 'siteCare':
|
|
220
|
+
return SITE_CARE_ADDON_MONTHLY_USD;
|
|
217
221
|
}
|
|
218
222
|
}
|
|
219
223
|
/**
|
|
@@ -239,15 +243,17 @@ function env(name) {
|
|
|
239
243
|
* Max purchasable quantity per kind, from a purchases-free entitlement
|
|
240
244
|
* resolution (plan defaults + staff overrides only) so the ceiling does not
|
|
241
245
|
* drift as the org buys: seat/dataset kinds stop at the plan's hard max,
|
|
242
|
-
* hosts/registers use flat ceilings, the Event Calendar
|
|
243
|
-
* toggles. POS registers additionally require the `pos`
|
|
246
|
+
* hosts/registers use flat ceilings, the Event Calendar, Aglyn AI and Site
|
|
247
|
+
* Care are 0/1 toggles. POS registers additionally require the `pos`
|
|
248
|
+
* feature, and Site Care a plan that sells it (`planSellsSiteCare`), which is
|
|
249
|
+
* why the plan travels with the baseline.
|
|
244
250
|
*
|
|
245
251
|
* Lives here rather than inside `/api/billing/addons` because a PLAN CHANGE
|
|
246
252
|
* needs the same ceiling for a different plan. The addons route asks "how many
|
|
247
253
|
* may this org buy on the plan it is on"; `buildTargetItems` asks "how many of
|
|
248
254
|
* what it already bought can the plan it is moving to actually deliver". Two
|
|
249
255
|
* readers, one definition — a second copy is how they answer differently.
|
|
250
|
-
*/ export function addonMaxForBaseline(kind, baseline) {
|
|
256
|
+
*/ export function addonMaxForBaseline(kind, baseline, plan) {
|
|
251
257
|
const bounded = (included, max)=>Number.isFinite(max) ? Math.max(0, max - included) : EXTRA_HOSTS_ADDON_MAX;
|
|
252
258
|
switch(kind){
|
|
253
259
|
case 'managers':
|
|
@@ -266,12 +272,17 @@ function env(name) {
|
|
|
266
272
|
// Org-wide like the Event Calendar: one purchase, and the price map
|
|
267
273
|
// (null on Free and Enterprise) says whether the plan sells it at all.
|
|
268
274
|
return 1;
|
|
275
|
+
case 'siteCare':
|
|
276
|
+
// Flat-priced, so the price map cannot say "not sold here" the way it
|
|
277
|
+
// does for Aglyn AI. This ceiling is the rule that keeps Free (no
|
|
278
|
+
// subscription) and Enterprise (quoted per deal) from buying it.
|
|
279
|
+
return planSellsSiteCare(plan) ? 1 : 0;
|
|
269
280
|
}
|
|
270
281
|
}
|
|
271
282
|
/** The ceiling a PLAN would impose on an add-on kind, purchases excluded. */ export function addonMaxForPlan(kind, plan) {
|
|
272
283
|
return addonMaxForBaseline(kind, resolveOrgEntitlements({
|
|
273
284
|
plan
|
|
274
|
-
}));
|
|
285
|
+
}), plan);
|
|
275
286
|
}
|
|
276
287
|
|
|
277
288
|
//# sourceMappingURL=billing-addons.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/billing-addons.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 EVENT_CALENDAR_ADDON_MONTHLY_USD,\n EXTRA_HOSTS_ADDON_MAX,\n PLAN_PRICING,\n POS_REGISTER_ADDON_MONTHLY_USD,\n POS_REGISTERS_ADDON_MAX,\n resolveOrgEntitlements,\n SELF_SERVE_PLANS,\n UNLIMITED,\n type OrgPlan,\n type OrgSeatAddons,\n} from '@aglyn/aglyn/server'\n\n/**\n * Self-serve add-on price map (AGL-525): the bridge between\n * `STRIPE_PRICE_*` env price ids, `org.seatAddons` keys, and\n * `PLAN_PRICING` USD amounts. Add-ons bill as extra items on the org's\n * one subscription, so every kind has a monthly and a yearly price\n * (Stripe allows a single interval per subscription; annual orgs attach\n * the `_YEARLY` variants). Seat/member/dataset/host prices and the Aglyn AI\n * add-on (AGL-2896) are per-plan; POS registers and the Event Calendar are\n * flat. Prices are minted by `tools/scripts/setup-stripe.mjs` — keep the\n * three in sync.\n */\nexport type AddonKind = keyof Required<OrgSeatAddons>\n\nexport const ADDON_KINDS: readonly AddonKind[] = [\n 'managers',\n 'members',\n 'datasets',\n 'hosts',\n 'posRegisters',\n 'eventCalendar',\n 'aiAddon',\n]\n\nexport type BillingInterval = 'month' | 'year'\n\n/** Kinds priced per plan (env `STRIPE_PRICE_{PLAN}_{SUFFIX}[_YEARLY]`). */\nconst PER_PLAN_ENV_SUFFIX: Partial<Record<AddonKind, string>> = {\n managers: 'EXTRA_SEAT',\n members: 'EXTRA_MEMBER',\n datasets: 'EXTRA_DATASET',\n hosts: 'EXTRA_HOST',\n aiAddon: 'AI_ADDON',\n}\n\n/** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */\nconst FLAT_ENV_NAME: Partial<Record<AddonKind, string>> = {\n posRegisters: 'POS_REGISTER',\n eventCalendar: 'EVENT_CALENDAR',\n}\n\n/**\n * Every plan that is sold with a Stripe price — DERIVED, never hand-listed\n * (AGL-1340).\n *\n * The literal that used to sit here listed starter, pro, business and\n * advanced only — it predated the Scale and Agency tiers, so\n * `addonKindFromPriceId()` could not recognise a single Scale/Agency add-on\n * price coming back from Stripe. `addonPriceId()` still SOLD them (it only\n * uppercases the plan), so the money moved and the read-back returned\n * nothing: the webhook wrote `seatAddons: {all zeros}` for the\n * highest-paying orgs on the next subscription event, and `seatAddons` is an\n * ENTITLEMENT INPUT (`plan-entitlements.ts` — it raises `hostLimit` and\n * `posRegisters`, and flips the `eventCalendar` feature).\n *\n * Deriving from `SELF_SERVE_PLANS` is what stops the next tier from\n * reintroducing it: `free` has nothing to sell and `enterprise` is quoted\n * per deal (no `STRIPE_PRICE_ENTERPRISE_*` exists), so everything else is\n * by definition a paid, priced plan.\n */\nexport const PAID_PLANS: readonly OrgPlan[] = SELF_SERVE_PLANS.filter(\n (plan) => plan !== 'free',\n)\n\nfunction env(name: string): string | null {\n const value = process.env[name]\n return value ? value : null\n}\n\n/**\n * The Stripe price id for an add-on kind on a plan at a billing interval;\n * null when the plan doesn't sell it (free) or the env isn't configured.\n */\nexport function addonPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n const yearly = interval === 'year' ? '_YEARLY' : ''\n const flat = FLAT_ENV_NAME[kind]\n if (flat) return env(`STRIPE_PRICE_${flat}${yearly}`)\n const suffix = PER_PLAN_ENV_SUFFIX[kind]\n if (!suffix || plan === 'free') return null\n return env(`STRIPE_PRICE_${plan.toUpperCase()}_${suffix}${yearly}`)\n}\n\n/**\n * Reverse map: which add-on kind a subscription item's price id sells.\n * Null for non-add-on prices (the base plan item, unknown prices).\n */\nexport function addonKindFromPriceId(\n priceId: string | null | undefined,\n): AddonKind | null {\n if (!priceId) return null\n for (const kind of ADDON_KINDS) {\n for (const interval of ['month', 'year'] as const) {\n if (FLAT_ENV_NAME[kind]) {\n if (addonPriceId(kind, 'starter', interval) === priceId) return kind\n continue\n }\n for (const plan of PAID_PLANS) {\n if (addonPriceId(kind, plan, interval) === priceId) return kind\n }\n }\n }\n return null\n}\n\n/**\n * The BASE plan's Stripe price id at an interval\n * (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced\n * `enterprise`, and for an env that isn't configured. Read at call time, so\n * it never freezes a stale value at module load the way the routes'\n * `PRICE_ENV` maps do.\n */\nexport function planPriceId(\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n if (!PAID_PLANS.includes(plan)) return null\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_${plan.toUpperCase()}${yearly}`)\n}\n\n/**\n * Which plan a subscription item's price sells AND on which interval; null for\n * an add-on price, the metered price, an ad-hoc enterprise price, and anything\n * unknown.\n *\n * The interval half exists because a schedule phase read back from Stripe\n * carries price IDS and nothing else (AGL-2150): rebuilding that phase's item\n * list needs to know which interval it is priced on, and guessing it from the\n * live subscription is wrong exactly when the pending change is also an\n * interval change.\n */\nexport function planAndIntervalFromPriceId(\n priceId: string | null | undefined,\n): { plan: OrgPlan; interval: BillingInterval } | null {\n if (!priceId) return null\n for (const plan of PAID_PLANS) {\n for (const interval of ['month', 'year'] as const) {\n if (planPriceId(plan, interval) === priceId) return { plan, interval }\n }\n }\n return null\n}\n\n/**\n * Which plan a subscription item's price sells; null for an add-on price,\n * the metered price, an ad-hoc enterprise price, and anything unknown.\n */\nexport function planFromPriceId(\n priceId: string | null | undefined,\n): OrgPlan | null {\n return planAndIntervalFromPriceId(priceId)?.plan ?? null\n}\n\n/**\n * The shared metered-usage price (AGL-635) that makes reported usage\n * billable, for a given billing interval.\n *\n * Stripe rejects a subscription whose items mix `recurring.interval`, so the\n * metered item has to recur the same way the plan does. There are two prices\n * — `aglyn_metered_usage` (monthly) and `aglyn_metered_usage_yearly` — and\n * both bill $0.01 per aggregated unit against the SAME meter, because the\n * rollup posts an already-computed value in CENTS. The interval is therefore\n * the only thing that differs, and it is the only thing a caller must get\n * right.\n *\n * `interval` is REQUIRED on purpose (AGL-1280). It used to be monthly-only\n * with no argument, so the failure mode of forgetting it was attaching a\n * monthly price to a yearly subscription — the exact mixed-interval crash\n * this signature now makes unrepresentable. A default would hand that\n * footgun straight back.\n */\nexport function meteredPriceId(interval: 'month' | 'year'): string | null {\n return env(\n interval === 'year' ? 'STRIPE_PRICE_METERED_YEARLY' : 'STRIPE_PRICE_METERED',\n )\n}\n\n/**\n * Whether a price id is EITHER shared metered-usage price.\n *\n * Interval-agnostic by design: callers ask this to exclude the metered item\n * from plan/add-on reasoning, and an annual subscription's metered item must\n * be excluded just as thoroughly as a monthly one.\n */\nexport function isMeteredPriceId(priceId: string | null | undefined): boolean {\n if (!priceId) return false\n return (\n priceId === meteredPriceId('month') || priceId === meteredPriceId('year')\n )\n}\n\n/**\n * The subscription's BASE PLAN item, identified POSITIVELY (AGL-1340).\n *\n * This used to be \"whatever no add-on price claims\" — identification by\n * elimination, which quietly returns the wrong item the moment a\n * subscription carries anything the add-on map doesn't recognise: the\n * metered item, a grandfathered v1 price, a coupon-era SKU, an item added\n * by hand in the Stripe dashboard. Picking an add-on item as the plan item\n * means a plan switch re-prices the ADD-ON, and reads the billing interval\n * off it.\n *\n * So: match a known `STRIPE_PRICE_{PLAN}[_YEARLY]` first. Only when nothing\n * matches — an enterprise deal bills on an ad-hoc price, and grandfathered\n * subscriptions predate the current SKUs — fall back to the old rule,\n * minus the metered item, and finally to `items[0]` so behaviour for those\n * subscriptions is unchanged.\n */\nexport function findPlanItem<T extends { price?: { id?: string } | null }>(\n items: readonly T[] | null | undefined,\n): T | null {\n const list = items ?? []\n const byPlanPrice = list.find((item) => planFromPriceId(item?.price?.id))\n if (byPlanPrice) return byPlanPrice\n const notAnAddon = list.find(\n (item) =>\n !addonKindFromPriceId(item?.price?.id) &&\n !isMeteredPriceId(item?.price?.id),\n )\n return notAnAddon ?? list[0] ?? null\n}\n\n/**\n * Monthly USD per unit for an add-on on a plan (yearly prices are ×12 of\n * this); null when the plan doesn't sell the kind. Single pricing source\n * of truth: `PLAN_PRICING` + the two flat add-on constants.\n */\nexport function addonUnitUsd(kind: AddonKind, plan: OrgPlan): number | null {\n const pricing = PLAN_PRICING[plan]\n switch (kind) {\n case 'managers':\n return pricing.extraSeatMonthlyUsd\n case 'members':\n return pricing.extraCollaboratorMonthlyUsd\n case 'datasets':\n return pricing.extraDatasetMonthlyUsd\n case 'hosts':\n return pricing.extraHostMonthlyUsd\n case 'posRegisters':\n return POS_REGISTER_ADDON_MONTHLY_USD\n case 'eventCalendar':\n return EVENT_CALENDAR_ADDON_MONTHLY_USD\n case 'aiAddon':\n return pricing.aiAddonMonthlyUsd\n }\n}\n\n/**\n * Full add-on quantity map (explicit zeros for absent kinds) from a\n * subscription's items — the shape written to `org.seatAddons` so\n * removals and dashboard edits converge on sync (AGL-527).\n */\nexport function addonQuantitiesFromItems(\n items:\n | Array<{ price?: { id?: string } | null; quantity?: number | null }>\n | null\n | undefined,\n): Record<AddonKind, number> {\n const quantities = Object.fromEntries(\n ADDON_KINDS.map((kind) => [kind, 0]),\n ) as Record<AddonKind, number>\n for (const item of items ?? []) {\n const kind = addonKindFromPriceId(item?.price?.id)\n if (kind) {\n quantities[kind] += Math.max(0, Math.floor(Number(item?.quantity ?? 0)))\n }\n }\n return quantities\n}\n\n/**\n * Max purchasable quantity per kind, from a purchases-free entitlement\n * resolution (plan defaults + staff overrides only) so the ceiling does not\n * drift as the org buys: seat/dataset kinds stop at the plan's hard max,\n * hosts/registers use flat ceilings, the Event Calendar and Aglyn AI are 0/1\n * toggles. POS registers additionally require the `pos` feature.\n *\n * Lives here rather than inside `/api/billing/addons` because a PLAN CHANGE\n * needs the same ceiling for a different plan. The addons route asks \"how many\n * may this org buy on the plan it is on\"; `buildTargetItems` asks \"how many of\n * what it already bought can the plan it is moving to actually deliver\". Two\n * readers, one definition — a second copy is how they answer differently.\n */\nexport function addonMaxForBaseline(\n kind: AddonKind,\n baseline: ReturnType<typeof resolveOrgEntitlements>,\n): number {\n const bounded = (included: number, max: number) =>\n Number.isFinite(max) ? Math.max(0, max - included) : EXTRA_HOSTS_ADDON_MAX\n switch (kind) {\n case 'managers':\n return bounded(baseline.managersPerOrg, baseline.maxManagersPerOrg)\n case 'members':\n return bounded(baseline.membersPerHost, baseline.maxMembersPerHost)\n case 'datasets':\n return bounded(baseline.datasetsPerOrg, baseline.maxDatasetsPerOrg)\n case 'hosts':\n return baseline.hostLimit === UNLIMITED ? 0 : EXTRA_HOSTS_ADDON_MAX\n case 'posRegisters':\n return baseline.features.pos ? POS_REGISTERS_ADDON_MAX : 0\n case 'eventCalendar':\n return 1\n case 'aiAddon':\n // Org-wide like the Event Calendar: one purchase, and the price map\n // (null on Free and Enterprise) says whether the plan sells it at all.\n return 1\n }\n}\n\n/** The ceiling a PLAN would impose on an add-on kind, purchases excluded. */\nexport function addonMaxForPlan(kind: AddonKind, plan: OrgPlan): number {\n return addonMaxForBaseline(kind, resolveOrgEntitlements({ plan } as never))\n}\n"],"names":["EVENT_CALENDAR_ADDON_MONTHLY_USD","EXTRA_HOSTS_ADDON_MAX","PLAN_PRICING","POS_REGISTER_ADDON_MONTHLY_USD","POS_REGISTERS_ADDON_MAX","resolveOrgEntitlements","SELF_SERVE_PLANS","UNLIMITED","ADDON_KINDS","PER_PLAN_ENV_SUFFIX","managers","members","datasets","hosts","aiAddon","FLAT_ENV_NAME","posRegisters","eventCalendar","PAID_PLANS","filter","plan","env","name","value","process","addonPriceId","kind","interval","yearly","flat","suffix","toUpperCase","addonKindFromPriceId","priceId","planPriceId","includes","planAndIntervalFromPriceId","planFromPriceId","meteredPriceId","isMeteredPriceId","findPlanItem","items","notAnAddon","list","byPlanPrice","find","item","price","id","addonUnitUsd","pricing","extraSeatMonthlyUsd","extraCollaboratorMonthlyUsd","extraDatasetMonthlyUsd","extraHostMonthlyUsd","aiAddonMonthlyUsd","addonQuantitiesFromItems","quantities","Object","fromEntries","map","Math","max","floor","Number","quantity","addonMaxForBaseline","baseline","bounded","included","isFinite","managersPerOrg","maxManagersPerOrg","membersPerHost","maxMembersPerHost","datasetsPerOrg","maxDatasetsPerOrg","hostLimit","features","pos","addonMaxForPlan"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gCAAgC,EAChCC,qBAAqB,EACrBC,YAAY,EACZC,8BAA8B,EAC9BC,uBAAuB,EACvBC,sBAAsB,EACtBC,gBAAgB,EAChBC,SAAS,QAGJ,sBAAqB;AAe5B,OAAO,MAAMC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AiB;QACpE,KAAK;YACH,OAAOJ,QAAQD,SAASM,cAAc,EAAEN,SAASO,iBAAiB;QACpE,KAAK;YACH,OAAON,QAAQD,SAASQ,cAAc,EAAER,SAASS,iBAAiB;QACpE,KAAK;YACH,OAAOT,SAASU,SAAS,KAAKtE,YAAY,IAAIN;QAChD,KAAK;YACH,OAAOkE,SAASW,QAAQ,CAACC,GAAG,GAAG3E,0BAA0B;QAC3D,KAAK;YACH,OAAO;QACT,KAAK;YACH,oEAAoE;YACpE,uEAAuE;YACvE,OAAO;IACX;AACF;AAEA,2EAA2E,GAC3E,OAAO,SAAS4E,gBAAgBtD,IAAe,EAAEN,IAAa;IAC5D,OAAO8C,oBAAoBxC,MAAMrB,uBAAuB;QAAEe;IAAK;AACjE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/billing-addons.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 EVENT_CALENDAR_ADDON_MONTHLY_USD,\n EXTRA_HOSTS_ADDON_MAX,\n PLAN_PRICING,\n planSellsSiteCare,\n POS_REGISTER_ADDON_MONTHLY_USD,\n POS_REGISTERS_ADDON_MAX,\n resolveOrgEntitlements,\n SELF_SERVE_PLANS,\n SITE_CARE_ADDON_MONTHLY_USD,\n UNLIMITED,\n type OrgPlan,\n type OrgSeatAddons,\n} from '@aglyn/aglyn/server'\n\n/**\n * Self-serve add-on price map (AGL-525): the bridge between\n * `STRIPE_PRICE_*` env price ids, `org.seatAddons` keys, and\n * `PLAN_PRICING` USD amounts. Add-ons bill as extra items on the org's\n * one subscription, so every kind has a monthly and a yearly price\n * (Stripe allows a single interval per subscription; annual orgs attach\n * the `_YEARLY` variants). Seat/member/dataset/host prices and the Aglyn AI\n * add-on (AGL-2896) are per-plan; POS registers, the Event Calendar and\n * Site Care (AGL-3954) are flat. Prices are minted by `tools/scripts/setup-stripe.mjs` — keep the\n * three in sync.\n */\nexport type AddonKind = keyof Required<OrgSeatAddons>\n\nexport const ADDON_KINDS: readonly AddonKind[] = [\n 'managers',\n 'members',\n 'datasets',\n 'hosts',\n 'posRegisters',\n 'eventCalendar',\n 'aiAddon',\n 'siteCare',\n]\n\nexport type BillingInterval = 'month' | 'year'\n\n/** Kinds priced per plan (env `STRIPE_PRICE_{PLAN}_{SUFFIX}[_YEARLY]`). */\nconst PER_PLAN_ENV_SUFFIX: Partial<Record<AddonKind, string>> = {\n managers: 'EXTRA_SEAT',\n members: 'EXTRA_MEMBER',\n datasets: 'EXTRA_DATASET',\n hosts: 'EXTRA_HOST',\n aiAddon: 'AI_ADDON',\n}\n\n/** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */\nconst FLAT_ENV_NAME: Partial<Record<AddonKind, string>> = {\n posRegisters: 'POS_REGISTER',\n eventCalendar: 'EVENT_CALENDAR',\n siteCare: 'SITE_CARE',\n}\n\n/**\n * Every plan that is sold with a Stripe price — DERIVED, never hand-listed\n * (AGL-1340).\n *\n * The literal that used to sit here listed starter, pro, business and\n * advanced only — it predated the Scale and Agency tiers, so\n * `addonKindFromPriceId()` could not recognise a single Scale/Agency add-on\n * price coming back from Stripe. `addonPriceId()` still SOLD them (it only\n * uppercases the plan), so the money moved and the read-back returned\n * nothing: the webhook wrote `seatAddons: {all zeros}` for the\n * highest-paying orgs on the next subscription event, and `seatAddons` is an\n * ENTITLEMENT INPUT (`plan-entitlements.ts` — it raises `hostLimit` and\n * `posRegisters`, and flips the `eventCalendar` feature).\n *\n * Deriving from `SELF_SERVE_PLANS` is what stops the next tier from\n * reintroducing it: `free` has nothing to sell and `enterprise` is quoted\n * per deal (no `STRIPE_PRICE_ENTERPRISE_*` exists), so everything else is\n * by definition a paid, priced plan.\n */\nexport const PAID_PLANS: readonly OrgPlan[] = SELF_SERVE_PLANS.filter(\n (plan) => plan !== 'free',\n)\n\nfunction env(name: string): string | null {\n const value = process.env[name]\n return value ? value : null\n}\n\n/**\n * The Stripe price id for an add-on kind on a plan at a billing interval;\n * null when the plan doesn't sell it (free) or the env isn't configured.\n */\nexport function addonPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n const yearly = interval === 'year' ? '_YEARLY' : ''\n const flat = FLAT_ENV_NAME[kind]\n if (flat) return env(`STRIPE_PRICE_${flat}${yearly}`)\n const suffix = PER_PLAN_ENV_SUFFIX[kind]\n if (!suffix || plan === 'free') return null\n return env(`STRIPE_PRICE_${plan.toUpperCase()}_${suffix}${yearly}`)\n}\n\n/**\n * Reverse map: which add-on kind a subscription item's price id sells.\n * Null for non-add-on prices (the base plan item, unknown prices).\n */\nexport function addonKindFromPriceId(\n priceId: string | null | undefined,\n): AddonKind | null {\n if (!priceId) return null\n for (const kind of ADDON_KINDS) {\n for (const interval of ['month', 'year'] as const) {\n if (FLAT_ENV_NAME[kind]) {\n if (addonPriceId(kind, 'starter', interval) === priceId) return kind\n continue\n }\n for (const plan of PAID_PLANS) {\n if (addonPriceId(kind, plan, interval) === priceId) return kind\n }\n }\n }\n return null\n}\n\n/**\n * The BASE plan's Stripe price id at an interval\n * (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced\n * `enterprise`, and for an env that isn't configured. Read at call time, so\n * it never freezes a stale value at module load the way the routes'\n * `PRICE_ENV` maps do.\n */\nexport function planPriceId(\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n if (!PAID_PLANS.includes(plan)) return null\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_${plan.toUpperCase()}${yearly}`)\n}\n\n/**\n * Which plan a subscription item's price sells AND on which interval; null for\n * an add-on price, the metered price, an ad-hoc enterprise price, and anything\n * unknown.\n *\n * The interval half exists because a schedule phase read back from Stripe\n * carries price IDS and nothing else (AGL-2150): rebuilding that phase's item\n * list needs to know which interval it is priced on, and guessing it from the\n * live subscription is wrong exactly when the pending change is also an\n * interval change.\n */\nexport function planAndIntervalFromPriceId(\n priceId: string | null | undefined,\n): { plan: OrgPlan; interval: BillingInterval } | null {\n if (!priceId) return null\n for (const plan of PAID_PLANS) {\n for (const interval of ['month', 'year'] as const) {\n if (planPriceId(plan, interval) === priceId) return { plan, interval }\n }\n }\n return null\n}\n\n/**\n * Which plan a subscription item's price sells; null for an add-on price,\n * the metered price, an ad-hoc enterprise price, and anything unknown.\n */\nexport function planFromPriceId(\n priceId: string | null | undefined,\n): OrgPlan | null {\n return planAndIntervalFromPriceId(priceId)?.plan ?? null\n}\n\n/**\n * The shared metered-usage price (AGL-635) that makes reported usage\n * billable, for a given billing interval.\n *\n * Stripe rejects a subscription whose items mix `recurring.interval`, so the\n * metered item has to recur the same way the plan does. There are two prices\n * — `aglyn_metered_usage` (monthly) and `aglyn_metered_usage_yearly` — and\n * both bill $0.01 per aggregated unit against the SAME meter, because the\n * rollup posts an already-computed value in CENTS. The interval is therefore\n * the only thing that differs, and it is the only thing a caller must get\n * right.\n *\n * `interval` is REQUIRED on purpose (AGL-1280). It used to be monthly-only\n * with no argument, so the failure mode of forgetting it was attaching a\n * monthly price to a yearly subscription — the exact mixed-interval crash\n * this signature now makes unrepresentable. A default would hand that\n * footgun straight back.\n */\nexport function meteredPriceId(interval: 'month' | 'year'): string | null {\n return env(\n interval === 'year' ? 'STRIPE_PRICE_METERED_YEARLY' : 'STRIPE_PRICE_METERED',\n )\n}\n\n/**\n * Whether a price id is EITHER shared metered-usage price.\n *\n * Interval-agnostic by design: callers ask this to exclude the metered item\n * from plan/add-on reasoning, and an annual subscription's metered item must\n * be excluded just as thoroughly as a monthly one.\n */\nexport function isMeteredPriceId(priceId: string | null | undefined): boolean {\n if (!priceId) return false\n return (\n priceId === meteredPriceId('month') || priceId === meteredPriceId('year')\n )\n}\n\n/**\n * The subscription's BASE PLAN item, identified POSITIVELY (AGL-1340).\n *\n * This used to be \"whatever no add-on price claims\" — identification by\n * elimination, which quietly returns the wrong item the moment a\n * subscription carries anything the add-on map doesn't recognise: the\n * metered item, a grandfathered v1 price, a coupon-era SKU, an item added\n * by hand in the Stripe dashboard. Picking an add-on item as the plan item\n * means a plan switch re-prices the ADD-ON, and reads the billing interval\n * off it.\n *\n * So: match a known `STRIPE_PRICE_{PLAN}[_YEARLY]` first. Only when nothing\n * matches — an enterprise deal bills on an ad-hoc price, and grandfathered\n * subscriptions predate the current SKUs — fall back to the old rule,\n * minus the metered item, and finally to `items[0]` so behaviour for those\n * subscriptions is unchanged.\n */\nexport function findPlanItem<T extends { price?: { id?: string } | null }>(\n items: readonly T[] | null | undefined,\n): T | null {\n const list = items ?? []\n const byPlanPrice = list.find((item) => planFromPriceId(item?.price?.id))\n if (byPlanPrice) return byPlanPrice\n const notAnAddon = list.find(\n (item) =>\n !addonKindFromPriceId(item?.price?.id) &&\n !isMeteredPriceId(item?.price?.id),\n )\n return notAnAddon ?? list[0] ?? null\n}\n\n/**\n * Monthly USD per unit for an add-on on a plan (yearly prices are ×12 of\n * this); null when the plan doesn't sell the kind. Single pricing source\n * of truth: `PLAN_PRICING` + the three flat add-on constants.\n */\nexport function addonUnitUsd(kind: AddonKind, plan: OrgPlan): number | null {\n const pricing = PLAN_PRICING[plan]\n switch (kind) {\n case 'managers':\n return pricing.extraSeatMonthlyUsd\n case 'members':\n return pricing.extraCollaboratorMonthlyUsd\n case 'datasets':\n return pricing.extraDatasetMonthlyUsd\n case 'hosts':\n return pricing.extraHostMonthlyUsd\n case 'posRegisters':\n return POS_REGISTER_ADDON_MONTHLY_USD\n case 'eventCalendar':\n return EVENT_CALENDAR_ADDON_MONTHLY_USD\n case 'aiAddon':\n return pricing.aiAddonMonthlyUsd\n case 'siteCare':\n return SITE_CARE_ADDON_MONTHLY_USD\n }\n}\n\n/**\n * Full add-on quantity map (explicit zeros for absent kinds) from a\n * subscription's items — the shape written to `org.seatAddons` so\n * removals and dashboard edits converge on sync (AGL-527).\n */\nexport function addonQuantitiesFromItems(\n items:\n | Array<{ price?: { id?: string } | null; quantity?: number | null }>\n | null\n | undefined,\n): Record<AddonKind, number> {\n const quantities = Object.fromEntries(\n ADDON_KINDS.map((kind) => [kind, 0]),\n ) as Record<AddonKind, number>\n for (const item of items ?? []) {\n const kind = addonKindFromPriceId(item?.price?.id)\n if (kind) {\n quantities[kind] += Math.max(0, Math.floor(Number(item?.quantity ?? 0)))\n }\n }\n return quantities\n}\n\n/**\n * Max purchasable quantity per kind, from a purchases-free entitlement\n * resolution (plan defaults + staff overrides only) so the ceiling does not\n * drift as the org buys: seat/dataset kinds stop at the plan's hard max,\n * hosts/registers use flat ceilings, the Event Calendar, Aglyn AI and Site\n * Care are 0/1 toggles. POS registers additionally require the `pos`\n * feature, and Site Care a plan that sells it (`planSellsSiteCare`), which is\n * why the plan travels with the baseline.\n *\n * Lives here rather than inside `/api/billing/addons` because a PLAN CHANGE\n * needs the same ceiling for a different plan. The addons route asks \"how many\n * may this org buy on the plan it is on\"; `buildTargetItems` asks \"how many of\n * what it already bought can the plan it is moving to actually deliver\". Two\n * readers, one definition — a second copy is how they answer differently.\n */\nexport function addonMaxForBaseline(\n kind: AddonKind,\n baseline: ReturnType<typeof resolveOrgEntitlements>,\n plan: OrgPlan,\n): number {\n const bounded = (included: number, max: number) =>\n Number.isFinite(max) ? Math.max(0, max - included) : EXTRA_HOSTS_ADDON_MAX\n switch (kind) {\n case 'managers':\n return bounded(baseline.managersPerOrg, baseline.maxManagersPerOrg)\n case 'members':\n return bounded(baseline.membersPerHost, baseline.maxMembersPerHost)\n case 'datasets':\n return bounded(baseline.datasetsPerOrg, baseline.maxDatasetsPerOrg)\n case 'hosts':\n return baseline.hostLimit === UNLIMITED ? 0 : EXTRA_HOSTS_ADDON_MAX\n case 'posRegisters':\n return baseline.features.pos ? POS_REGISTERS_ADDON_MAX : 0\n case 'eventCalendar':\n return 1\n case 'aiAddon':\n // Org-wide like the Event Calendar: one purchase, and the price map\n // (null on Free and Enterprise) says whether the plan sells it at all.\n return 1\n case 'siteCare':\n // Flat-priced, so the price map cannot say \"not sold here\" the way it\n // does for Aglyn AI. This ceiling is the rule that keeps Free (no\n // subscription) and Enterprise (quoted per deal) from buying it.\n return planSellsSiteCare(plan) ? 1 : 0\n }\n}\n\n/** The ceiling a PLAN would impose on an add-on kind, purchases excluded. */\nexport function addonMaxForPlan(kind: AddonKind, plan: OrgPlan): number {\n return addonMaxForBaseline(\n kind,\n resolveOrgEntitlements({ plan } as never),\n plan,\n )\n}\n"],"names":["EVENT_CALENDAR_ADDON_MONTHLY_USD","EXTRA_HOSTS_ADDON_MAX","PLAN_PRICING","planSellsSiteCare","POS_REGISTER_ADDON_MONTHLY_USD","POS_REGISTERS_ADDON_MAX","resolveOrgEntitlements","SELF_SERVE_PLANS","SITE_CARE_ADDON_MONTHLY_USD","UNLIMITED","ADDON_KINDS","PER_PLAN_ENV_SUFFIX","managers","members","datasets","hosts","aiAddon","FLAT_ENV_NAME","posRegisters","eventCalendar","siteCare","PAID_PLANS","filter","plan","env","name","value","process","addonPriceId","kind","interval","yearly","flat","suffix","toUpperCase","addonKindFromPriceId","priceId","planPriceId","includes","planAndIntervalFromPriceId","planFromPriceId","meteredPriceId","isMeteredPriceId","findPlanItem","items","notAnAddon","list","byPlanPrice","find","item","price","id","addonUnitUsd","pricing","extraSeatMonthlyUsd","extraCollaboratorMonthlyUsd","extraDatasetMonthlyUsd","extraHostMonthlyUsd","aiAddonMonthlyUsd","addonQuantitiesFromItems","quantities","Object","fromEntries","map","Math","max","floor","Number","quantity","addonMaxForBaseline","baseline","bounded","included","isFinite","managersPerOrg","maxManagersPerOrg","membersPerHost","maxMembersPerHost","datasetsPerOrg","maxDat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MmB,QAAQ,mBAAI;QACtE;IACF;IACA,OAAOR;AACT;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASS,oBACdxC,IAAe,EACfyC,QAAmD,EACnD/C,IAAa;IAEb,MAAMgD,UAAU,CAACC,UAAkBP,MACjCE,OAAOM,QAAQ,CAACR,OAAOD,KAAKC,GAAG,CAAC,GAAGA,MAAMO,YAAYvE;IACvD,OAAQ4B;QACN,KAAK;YACH,OAAO0C,QAAQD,SAASI,cAAc,EAAEJ,SAASK,iBAAiB;QACpE,KAAK;YACH,OAAOJ,QAAQD,SAASM,cAAc,EAAEN,SAASO,iBAAiB;QACpE,KAAK;YACH,OAAON,QAAQD,SAASQ,cAAc,EAAER,SAASS,iBAAiB;QACpE,KAAK;YACH,OAAOT,SAASU,SAAS,KAAKvE,YAAY,IAAIR;QAChD,KAAK;YACH,OAAOqE,SAASW,QAAQ,CAACC,GAAG,GAAG7E,0BAA0B;QAC3D,KAAK;YACH,OAAO;QACT,KAAK;YACH,oEAAoE;YACpE,uEAAuE;YACvE,OAAO;QACT,KAAK;YACH,sEAAsE;YACtE,kEAAkE;YAClE,iEAAiE;YACjE,OAAOF,kBAAkBoB,QAAQ,IAAI;IACzC;AACF;AAEA,2EAA2E,GAC3E,OAAO,SAAS4D,gBAAgBtD,IAAe,EAAEN,IAAa;IAC5D,OAAO8C,oBACLxC,MACAvB,uBAAuB;QAAEiB;IAAK,IAC9BA;AAEJ"}
|
|
@@ -40,3 +40,29 @@ export type ConfiguredUrlFetchResult =
|
|
|
40
40
|
export declare function fetchConfiguredPublicUrl(url: string, init: Omit<RequestInit, 'redirect'>, deps?: {
|
|
41
41
|
resolve?: typeof resolvePublicIp;
|
|
42
42
|
}): Promise<ConfiguredUrlFetchResult>;
|
|
43
|
+
export type ConfiguredUrlReadResult =
|
|
44
|
+
/**
|
|
45
|
+
* Called: the status, and the body as text. `body` is null when the reply
|
|
46
|
+
* ran past `maxBytes`, which a caller reads as no answer.
|
|
47
|
+
*/
|
|
48
|
+
{
|
|
49
|
+
ok: true;
|
|
50
|
+
status: number;
|
|
51
|
+
body: string | null;
|
|
52
|
+
} | {
|
|
53
|
+
ok: false;
|
|
54
|
+
refusal: ConfiguredUrlRefusal;
|
|
55
|
+
host: string;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* {@link fetchConfiguredPublicUrl} for a caller that reads the answer: the
|
|
59
|
+
* same refusals, the same pinned address, no redirect followed, and the body
|
|
60
|
+
* read up to `maxBytes`. A server reading a document at an address it
|
|
61
|
+
* discovered in somebody's DNS (AGL-3963) holds the reply to a size it chose,
|
|
62
|
+
* so a host that streams forever costs one bounded read. Throws only what
|
|
63
|
+
* `fetch` throws.
|
|
64
|
+
*/
|
|
65
|
+
export declare function readConfiguredPublicUrl(url: string, init: Omit<RequestInit, 'redirect'>, options: {
|
|
66
|
+
maxBytes: number;
|
|
67
|
+
resolve?: typeof resolvePublicIp;
|
|
68
|
+
}): Promise<ConfiguredUrlReadResult>;
|
|
@@ -114,5 +114,73 @@ import { createPinnedDispatcher, resolvePublicIp } from "./serve-plugin-fetch.js
|
|
|
114
114
|
await dispatcher.close().catch(()=>undefined);
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* {@link fetchConfiguredPublicUrl} for a caller that reads the answer: the
|
|
119
|
+
* same refusals, the same pinned address, no redirect followed, and the body
|
|
120
|
+
* read up to `maxBytes`. A server reading a document at an address it
|
|
121
|
+
* discovered in somebody's DNS (AGL-3963) holds the reply to a size it chose,
|
|
122
|
+
* so a host that streams forever costs one bounded read. Throws only what
|
|
123
|
+
* `fetch` throws.
|
|
124
|
+
*/ export async function readConfiguredPublicUrl(url, init, options) {
|
|
125
|
+
var _options_resolve;
|
|
126
|
+
const refusal = configuredUrlRefusal(url);
|
|
127
|
+
let host;
|
|
128
|
+
try {
|
|
129
|
+
host = new URL(url).hostname;
|
|
130
|
+
} catch (unused) {
|
|
131
|
+
host = '';
|
|
132
|
+
}
|
|
133
|
+
if (refusal) return {
|
|
134
|
+
ok: false,
|
|
135
|
+
refusal,
|
|
136
|
+
host
|
|
137
|
+
};
|
|
138
|
+
const pinned = await ((_options_resolve = options.resolve) != null ? _options_resolve : resolvePublicIp)(host);
|
|
139
|
+
if (!pinned) return {
|
|
140
|
+
ok: false,
|
|
141
|
+
refusal: 'private-address',
|
|
142
|
+
host
|
|
143
|
+
};
|
|
144
|
+
const dispatcher = createPinnedDispatcher(pinned);
|
|
145
|
+
try {
|
|
146
|
+
var _response_status;
|
|
147
|
+
var _response_body;
|
|
148
|
+
const pinnedInit = _extends({}, init, {
|
|
149
|
+
redirect: 'manual',
|
|
150
|
+
dispatcher
|
|
151
|
+
});
|
|
152
|
+
const response = await fetch(url, pinnedInit);
|
|
153
|
+
const status = Number((_response_status = response.status) != null ? _response_status : 0);
|
|
154
|
+
const reader = (_response_body = response.body) == null ? void 0 : _response_body.getReader();
|
|
155
|
+
if (!reader) return {
|
|
156
|
+
ok: true,
|
|
157
|
+
status,
|
|
158
|
+
body: ''
|
|
159
|
+
};
|
|
160
|
+
const chunks = [];
|
|
161
|
+
let size = 0;
|
|
162
|
+
for(;;){
|
|
163
|
+
const { done, value } = await reader.read();
|
|
164
|
+
if (done) break;
|
|
165
|
+
size += value.byteLength;
|
|
166
|
+
if (size > options.maxBytes) {
|
|
167
|
+
await reader.cancel().catch(()=>undefined);
|
|
168
|
+
return {
|
|
169
|
+
ok: true,
|
|
170
|
+
status,
|
|
171
|
+
body: null
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
chunks.push(value);
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
ok: true,
|
|
178
|
+
status,
|
|
179
|
+
body: Buffer.concat(chunks).toString('utf8')
|
|
180
|
+
};
|
|
181
|
+
} finally{
|
|
182
|
+
await dispatcher.close().catch(()=>undefined);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
117
185
|
|
|
118
186
|
//# sourceMappingURL=configured-url-fetch.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/configured-url-fetch.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * A SERVER CALL TO A URL A TENANT TYPED (AGL-3363).\n *\n * Some features call an address the merchant configured, from the\n * platform's own servers: a dropship supplier's order webhook is the first.\n * That address is author data, so it gets the checks the plugin fetch proxy\n * (`serve-plugin-fetch.ts`, AGL-515/1881) gives a plugin's declared origin,\n * through the same two primitives, rather than a bare `fetch`:\n *\n * - https only, on the default port, with no credentials in the authority;\n * - a host that wears a brand it is not (`lookalikeBrandForHost`) is refused\n * for every workspace, the phishing screen's strong tier;\n * - the name must resolve to PUBLIC addresses only, and the connection is\n * pinned to the address that was checked (`resolvePublicIp` +\n * `createPinnedDispatcher`), so a name cannot be rebound to the cloud\n * metadata endpoint or a private range between the check and the connect;\n * - a redirect is not followed (`redirect: 'manual'`): a 3xx is the answer,\n * which a caller that wants a 2xx treats as a failure.\n *\n * This sits beside the plugin fetch proxy and is not it: that one proxies a\n * browser's request to an allowlisted origin and streams the reply; this is\n * a server's own call with no allowlist but the rules above.\n *=========================================*/\n\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { createPinnedDispatcher, resolvePublicIp } from './serve-plugin-fetch'\n\n/** Why a configured URL was not called. */\nexport type ConfiguredUrlRefusal =\n | 'malformed'\n | 'not-https'\n | 'credentials'\n | 'port'\n | 'lookalike'\n | 'private-address'\n\n/** The checks that need no network: shape, scheme, port, credentials, brand. */\nexport function configuredUrlRefusal(url: unknown): ConfiguredUrlRefusal | null {\n let parsed: URL\n try {\n parsed = new URL(String(url ?? ''))\n } catch {\n return 'malformed'\n }\n if (parsed.protocol !== 'https:') return 'not-https'\n if (parsed.username || parsed.password) return 'credentials'\n if (parsed.port && parsed.port !== '443') return 'port'\n if (lookalikeBrandForHost(parsed.hostname)) return 'lookalike'\n return null\n}\n\n/** What the merchant is told a refusal means, in their words. */\nexport function describeConfiguredUrlRefusal(refusal: ConfiguredUrlRefusal): string {\n switch (refusal) {\n case 'malformed':\n return 'the address is not a valid web address'\n case 'not-https':\n return 'the address must start with https://'\n case 'credentials':\n return 'the address must not contain a user name or password'\n case 'port':\n return 'the address must use the standard https port'\n case 'lookalike':\n return 'the address looks like another company’s website'\n case 'private-address':\n return 'the address does not lead to a public server'\n }\n}\n\nexport type ConfiguredUrlFetchResult =\n /** Called: the status it answered. The body is discarded. */\n | { ok: true; status: number }\n | { ok: false; refusal: ConfiguredUrlRefusal; host: string }\n\n/**\n * Call `url` under the rules above and answer its status; the body is\n * discarded, because a notification's receiver answers with a status and\n * nothing a caller should read. Never follows a redirect. Throws only what\n * `fetch` throws (a timeout, a reset), for the caller to retry.\n */\nexport async function fetchConfiguredPublicUrl(\n url: string,\n init: Omit<RequestInit, 'redirect'>,\n deps: { resolve?: typeof resolvePublicIp } = {},\n): Promise<ConfiguredUrlFetchResult> {\n const refusal = configuredUrlRefusal(url)\n let host: string\n try {\n host = new URL(url).hostname\n } catch {\n host = ''\n }\n if (refusal) return { ok: false, refusal, host }\n const pinned = await (deps.resolve ?? resolvePublicIp)(host)\n if (!pinned) return { ok: false, refusal: 'private-address', host }\n const dispatcher = createPinnedDispatcher(pinned)\n try {\n // `dispatcher` is undici's, which the global fetch honors; spread from a\n // variable so the DOM `RequestInit` type does not reject the field.\n const pinnedInit = { ...init, redirect: 'manual' as const, dispatcher }\n const response = await fetch(url, pinnedInit as RequestInit)\n // Released before the dispatcher closes: `close` waits for requests in\n // flight, and an unread body is one.\n await response.body?.cancel().catch(() => undefined)\n return { ok: true, status: Number(response.status ?? 0) }\n } finally {\n await dispatcher.close().catch(() => undefined)\n }\n}\n"],"names":["lookalikeBrandForHost","createPinnedDispatcher","resolvePublicIp","configuredUrlRefusal","url","parsed","URL","String","protocol","username","password","port","hostname","describeConfiguredUrlRefusal","refusal","fetchConfiguredPublicUrl","init","deps","host","ok","pinned","resolve","dispatcher","response","pinnedInit","redirect","fetch","body","cancel","catch","undefined","status","Number","close"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,SAASA,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,sBAAsB,EAAEC,eAAe,QAAQ,0BAAsB;AAW9E,8EAA8E,GAC9E,OAAO,SAASC,qBAAqBC,GAAY;IAC/C,IAAIC;IACJ,IAAI;QACFA,SAAS,IAAIC,IAAIC,OAAOH,cAAAA,MAAO;IACjC,EAAE,eAAM;QACN,OAAO;IACT;IACA,IAAIC,OAAOG,QAAQ,KAAK,UAAU,OAAO;IACzC,IAAIH,OAAOI,QAAQ,IAAIJ,OAAOK,QAAQ,EAAE,OAAO;IAC/C,IAAIL,OAAOM,IAAI,IAAIN,OAAOM,IAAI,KAAK,OAAO,OAAO;IACjD,IAAIX,sBAAsBK,OAAOO,QAAQ,GAAG,OAAO;IACnD,OAAO;AACT;AAEA,+DAA+D,GAC/D,OAAO,SAASC,6BAA6BC,OAA6B;IACxE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;IACX;AACF;AAOA;;;;;CAKC,GACD,OAAO,eAAeC,yBACpBX,GAAW,EACXY,IAAmC,EACnCC,OAA6C,CAAC,CAAC;QAUzBA;IARtB,MAAMH,UAAUX,qBAAqBC;IACrC,IAAIc;IACJ,IAAI;QACFA,OAAO,IAAIZ,IAAIF,KAAKQ,QAAQ;IAC9B,EAAE,eAAM;QACNM,OAAO;IACT;IACA,IAAIJ,SAAS,OAAO;QAAEK,IAAI;QAAOL;QAASI;IAAK;IAC/C,MAAME,SAAS,MAAM,EAACH,gBAAAA,KAAKI,OAAO,YAAZJ,gBAAgBf,iBAAiBgB;IACvD,IAAI,CAACE,QAAQ,OAAO;QAAED,IAAI;QAAOL,SAAS;QAAmBI;IAAK;IAClE,MAAMI,aAAarB,uBAAuBmB;IAC1C,IAAI;YAQgCG;YAD5BA;QANN,yEAAyE;QACzE,oEAAoE;QACpE,MAAMC,aAAa,aAAKR;YAAMS,UAAU;YAAmBH;;QAC3D,MAAMC,WAAW,MAAMG,MAAMtB,KAAKoB;QAClC,uEAAuE;QACvE,qCAAqC;QACrC,QAAMD,iBAAAA,SAASI,IAAI,qBAAbJ,eAAeK,MAAM,GAAGC,KAAK,CAAC,IAAMC;QAC1C,OAAO;YAAEX,IAAI;YAAMY,QAAQC,QAAOT,mBAAAA,SAASQ,MAAM,YAAfR,mBAAmB;QAAG;IAC1D,SAAU;QACR,MAAMD,WAAWW,KAAK,GAAGJ,KAAK,CAAC,IAAMC;IACvC;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/configured-url-fetch.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * A SERVER CALL TO A URL A TENANT TYPED (AGL-3363).\n *\n * Some features call an address the merchant configured, from the\n * platform's own servers: a dropship supplier's order webhook is the first.\n * That address is author data, so it gets the checks the plugin fetch proxy\n * (`serve-plugin-fetch.ts`, AGL-515/1881) gives a plugin's declared origin,\n * through the same two primitives, rather than a bare `fetch`:\n *\n * - https only, on the default port, with no credentials in the authority;\n * - a host that wears a brand it is not (`lookalikeBrandForHost`) is refused\n * for every workspace, the phishing screen's strong tier;\n * - the name must resolve to PUBLIC addresses only, and the connection is\n * pinned to the address that was checked (`resolvePublicIp` +\n * `createPinnedDispatcher`), so a name cannot be rebound to the cloud\n * metadata endpoint or a private range between the check and the connect;\n * - a redirect is not followed (`redirect: 'manual'`): a 3xx is the answer,\n * which a caller that wants a 2xx treats as a failure.\n *\n * This sits beside the plugin fetch proxy and is not it: that one proxies a\n * browser's request to an allowlisted origin and streams the reply; this is\n * a server's own call with no allowlist but the rules above.\n *=========================================*/\n\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { createPinnedDispatcher, resolvePublicIp } from './serve-plugin-fetch'\n\n/** Why a configured URL was not called. */\nexport type ConfiguredUrlRefusal =\n | 'malformed'\n | 'not-https'\n | 'credentials'\n | 'port'\n | 'lookalike'\n | 'private-address'\n\n/** The checks that need no network: shape, scheme, port, credentials, brand. */\nexport function configuredUrlRefusal(url: unknown): ConfiguredUrlRefusal | null {\n let parsed: URL\n try {\n parsed = new URL(String(url ?? ''))\n } catch {\n return 'malformed'\n }\n if (parsed.protocol !== 'https:') return 'not-https'\n if (parsed.username || parsed.password) return 'credentials'\n if (parsed.port && parsed.port !== '443') return 'port'\n if (lookalikeBrandForHost(parsed.hostname)) return 'lookalike'\n return null\n}\n\n/** What the merchant is told a refusal means, in their words. */\nexport function describeConfiguredUrlRefusal(refusal: ConfiguredUrlRefusal): string {\n switch (refusal) {\n case 'malformed':\n return 'the address is not a valid web address'\n case 'not-https':\n return 'the address must start with https://'\n case 'credentials':\n return 'the address must not contain a user name or password'\n case 'port':\n return 'the address must use the standard https port'\n case 'lookalike':\n return 'the address looks like another company’s website'\n case 'private-address':\n return 'the address does not lead to a public server'\n }\n}\n\nexport type ConfiguredUrlFetchResult =\n /** Called: the status it answered. The body is discarded. */\n | { ok: true; status: number }\n | { ok: false; refusal: ConfiguredUrlRefusal; host: string }\n\n/**\n * Call `url` under the rules above and answer its status; the body is\n * discarded, because a notification's receiver answers with a status and\n * nothing a caller should read. Never follows a redirect. Throws only what\n * `fetch` throws (a timeout, a reset), for the caller to retry.\n */\nexport async function fetchConfiguredPublicUrl(\n url: string,\n init: Omit<RequestInit, 'redirect'>,\n deps: { resolve?: typeof resolvePublicIp } = {},\n): Promise<ConfiguredUrlFetchResult> {\n const refusal = configuredUrlRefusal(url)\n let host: string\n try {\n host = new URL(url).hostname\n } catch {\n host = ''\n }\n if (refusal) return { ok: false, refusal, host }\n const pinned = await (deps.resolve ?? resolvePublicIp)(host)\n if (!pinned) return { ok: false, refusal: 'private-address', host }\n const dispatcher = createPinnedDispatcher(pinned)\n try {\n // `dispatcher` is undici's, which the global fetch honors; spread from a\n // variable so the DOM `RequestInit` type does not reject the field.\n const pinnedInit = { ...init, redirect: 'manual' as const, dispatcher }\n const response = await fetch(url, pinnedInit as RequestInit)\n // Released before the dispatcher closes: `close` waits for requests in\n // flight, and an unread body is one.\n await response.body?.cancel().catch(() => undefined)\n return { ok: true, status: Number(response.status ?? 0) }\n } finally {\n await dispatcher.close().catch(() => undefined)\n }\n}\n\nexport type ConfiguredUrlReadResult =\n /**\n * Called: the status, and the body as text. `body` is null when the reply\n * ran past `maxBytes`, which a caller reads as no answer.\n */\n | { ok: true; status: number; body: string | null }\n | { ok: false; refusal: ConfiguredUrlRefusal; host: string }\n\n/**\n * {@link fetchConfiguredPublicUrl} for a caller that reads the answer: the\n * same refusals, the same pinned address, no redirect followed, and the body\n * read up to `maxBytes`. A server reading a document at an address it\n * discovered in somebody's DNS (AGL-3963) holds the reply to a size it chose,\n * so a host that streams forever costs one bounded read. Throws only what\n * `fetch` throws.\n */\nexport async function readConfiguredPublicUrl(\n url: string,\n init: Omit<RequestInit, 'redirect'>,\n options: { maxBytes: number; resolve?: typeof resolvePublicIp },\n): Promise<ConfiguredUrlReadResult> {\n const refusal = configuredUrlRefusal(url)\n let host: string\n try {\n host = new URL(url).hostname\n } catch {\n host = ''\n }\n if (refusal) return { ok: false, refusal, host }\n const pinned = await (options.resolve ?? resolvePublicIp)(host)\n if (!pinned) return { ok: false, refusal: 'private-address', host }\n const dispatcher = createPinnedDispatcher(pinned)\n try {\n const pinnedInit = { ...init, redirect: 'manual' as const, dispatcher }\n const response = await fetch(url, pinnedInit as RequestInit)\n const status = Number(response.status ?? 0)\n const reader = response.body?.getReader()\n if (!reader) return { ok: true, status, body: '' }\n const chunks: Uint8Array[] = []\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (size > options.maxBytes) {\n await reader.cancel().catch(() => undefined)\n return { ok: true, status, body: null }\n }\n chunks.push(value)\n }\n return { ok: true, status, body: Buffer.concat(chunks).toString('utf8') }\n } finally {\n await dispatcher.close().catch(() => undefined)\n }\n}\n"],"names":["lookalikeBrandForHost","createPinnedDispatcher","resolvePublicIp","configuredUrlRefusal","url","parsed","URL","String","protocol","username","password","port","hostname","describeConfiguredUrlRefusal","refusal","fetchConfiguredPublicUrl","init","deps","host","ok","pinned","resolve","dispatcher","response","pinnedInit","redirect","fetch","body","cancel","catch","undefined","status","Number","close","readConfiguredPublicUrl","options","reader","getReader","chunks","size","done","value","read","byteLength","maxBytes","push","Buffer","concat","toString"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,SAASA,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,sBAAsB,EAAEC,eAAe,QAAQ,0BAAsB;AAW9E,8EAA8E,GAC9E,OAAO,SAASC,qBAAqBC,GAAY;IAC/C,IAAIC;IACJ,IAAI;QACFA,SAAS,IAAIC,IAAIC,OAAOH,cAAAA,MAAO;IAC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I;oBAAMY;oBAAQJ,MAAM;gBAAK;YACxC;YACAW,OAAOO,IAAI,CAACJ;QACd;QACA,OAAO;YAAEtB,IAAI;YAAMY;YAAQJ,MAAMmB,OAAOC,MAAM,CAACT,QAAQU,QAAQ,CAAC;QAAQ;IAC1E,SAAU;QACR,MAAM1B,WAAWW,KAAK,GAAGJ,KAAK,CAAC,IAAMC;IACvC;AACF"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Registers `{subdomain}.aglyn.app` on the tenant deployment as a per-domain
|
|
19
|
+
* REDIRECT to the custom domain (AGL-1273). The app-level canonical redirect
|
|
20
|
+
* in `loadPageData` is baked into an ISR entry keyed on pathname, so it
|
|
21
|
+
* structurally cannot carry the query string — a campaign that pointed at the
|
|
22
|
+
* platform subdomain lost its `utm_*` on the hop. The edge redirect preserves
|
|
23
|
+
* path AND query at zero runtime cost, and the app-level redirect stays as the
|
|
24
|
+
* fallback wherever the provider cannot express a redirect at all.
|
|
25
|
+
*
|
|
26
|
+
* A redirect is a REGISTRATION, not a special case: create the name carrying
|
|
27
|
+
* the redirect, or point an existing entry at the new target. Both halves live
|
|
28
|
+
* in the provider, so a name already on the deployment gets its redirect
|
|
29
|
+
* applied rather than being read as "already done" — an entry left serving
|
|
30
|
+
* instead of forwarding is a second live copy of the site on a name that was
|
|
31
|
+
* supposed to hand visitors to the custom domain.
|
|
32
|
+
*
|
|
33
|
+
* Best-effort BY DESIGN: the custom domain is already attached by the time
|
|
34
|
+
* this runs, and a redirect-registration failure must not unwind that. A
|
|
35
|
+
* failure sets `subdomainRedirectPending` so the gap is visible and the
|
|
36
|
+
* completer cron (`/api/admin/finish-domain-attachments`) can close it.
|
|
37
|
+
*/
|
|
38
|
+
export declare function upsertSubdomainRedirect(options: {
|
|
39
|
+
subdomain: string;
|
|
40
|
+
target: string;
|
|
41
|
+
}): Promise<boolean>;
|
|
42
|
+
/**
|
|
43
|
+
* Registers the twin as a redirect to the primary. Best-effort for the same
|
|
44
|
+
* reason the subdomain redirect is: the primary serves either way, and a twin
|
|
45
|
+
* that did not land is recorded as `cnameTwinPending` for the completer.
|
|
46
|
+
*/
|
|
47
|
+
export declare function upsertCustomDomainTwin(options: {
|
|
48
|
+
twin: string;
|
|
49
|
+
target: string;
|
|
50
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,61 @@
|
|
|
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 { TENANT_APEX } from "@aglyn/aglyn/app-utils/tenant-apex";
|
|
17
|
+
import { attachProjectDomain } from "./workspace-domains.js";
|
|
18
|
+
/*
|
|
19
|
+
* The two redirects a connected custom domain registers on the tenant
|
|
20
|
+
* deployment (AGL-3961). Kept apart from `host-custom-domain.ts`, which owns
|
|
21
|
+
* the claim, so the completer cron and its spec reach them without the claim's
|
|
22
|
+
* Firestore and activity imports.
|
|
23
|
+
*/ /**
|
|
24
|
+
* Registers `{subdomain}.aglyn.app` on the tenant deployment as a per-domain
|
|
25
|
+
* REDIRECT to the custom domain (AGL-1273). The app-level canonical redirect
|
|
26
|
+
* in `loadPageData` is baked into an ISR entry keyed on pathname, so it
|
|
27
|
+
* structurally cannot carry the query string — a campaign that pointed at the
|
|
28
|
+
* platform subdomain lost its `utm_*` on the hop. The edge redirect preserves
|
|
29
|
+
* path AND query at zero runtime cost, and the app-level redirect stays as the
|
|
30
|
+
* fallback wherever the provider cannot express a redirect at all.
|
|
31
|
+
*
|
|
32
|
+
* A redirect is a REGISTRATION, not a special case: create the name carrying
|
|
33
|
+
* the redirect, or point an existing entry at the new target. Both halves live
|
|
34
|
+
* in the provider, so a name already on the deployment gets its redirect
|
|
35
|
+
* applied rather than being read as "already done" — an entry left serving
|
|
36
|
+
* instead of forwarding is a second live copy of the site on a name that was
|
|
37
|
+
* supposed to hand visitors to the custom domain.
|
|
38
|
+
*
|
|
39
|
+
* Best-effort BY DESIGN: the custom domain is already attached by the time
|
|
40
|
+
* this runs, and a redirect-registration failure must not unwind that. A
|
|
41
|
+
* failure sets `subdomainRedirectPending` so the gap is visible and the
|
|
42
|
+
* completer cron (`/api/admin/finish-domain-attachments`) can close it.
|
|
43
|
+
*/ export async function upsertSubdomainRedirect(options) {
|
|
44
|
+
const { subdomain, target } = options;
|
|
45
|
+
const result = await attachProjectDomain(`${subdomain}.${TENANT_APEX}`, {
|
|
46
|
+
redirectTo: target
|
|
47
|
+
}, 'tenant');
|
|
48
|
+
return result.outcome === 'attached' || result.outcome === 'already-exists';
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Registers the twin as a redirect to the primary. Best-effort for the same
|
|
52
|
+
* reason the subdomain redirect is: the primary serves either way, and a twin
|
|
53
|
+
* that did not land is recorded as `cnameTwinPending` for the completer.
|
|
54
|
+
*/ export async function upsertCustomDomainTwin(options) {
|
|
55
|
+
const result = await attachProjectDomain(options.twin, {
|
|
56
|
+
redirectTo: options.target
|
|
57
|
+
}, 'tenant');
|
|
58
|
+
return result.outcome === 'attached' || result.outcome === 'already-exists';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=custom-domain-redirects.js.map
|