@aglyn/aglyn 1.0.0-beta.177 → 1.0.0-beta.178

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.
@@ -24,6 +24,21 @@
24
24
  export declare const SUBDOMAIN_PATTERN: RegExp;
25
25
  /** Platform/system names a tenant must not squat. */
26
26
  export declare const RESERVED_SUBDOMAINS: Set<string>;
27
+ /**
28
+ * The one label a console URL occupies directly under a workspace domain
29
+ * (AGL-3295): `studio` for `https://studio.example.com` under `example.com`.
30
+ *
31
+ * `null` when either setting is missing or unparseable, and when the console
32
+ * is the apex itself, sits deeper, or lies outside the domain — none of those
33
+ * can collide with a workspace address, so none needs reserving.
34
+ *
35
+ * Pure, and in this dependency-free module, so the console's host gate and the
36
+ * organization-slug blocklist derive the same label from the same two
37
+ * settings. An install whose console is not at `app.` or `console.` is the
38
+ * case it exists for: without it, that label is read as a workspace nobody
39
+ * owns.
40
+ */
41
+ export declare function consoleLabelUnder(consoleUrl: string | null | undefined, workspaceDomain: string | null | undefined): string | null;
27
42
  /** True when the subdomain is reserved or contains a blocked fragment. */
28
43
  export declare function isBlockedSubdomain(subdomain: string): boolean;
29
44
  /**
@@ -63,6 +63,33 @@
63
63
  'porn',
64
64
  'nazi'
65
65
  ];
66
+ /**
67
+ * The one label a console URL occupies directly under a workspace domain
68
+ * (AGL-3295): `studio` for `https://studio.example.com` under `example.com`.
69
+ *
70
+ * `null` when either setting is missing or unparseable, and when the console
71
+ * is the apex itself, sits deeper, or lies outside the domain — none of those
72
+ * can collide with a workspace address, so none needs reserving.
73
+ *
74
+ * Pure, and in this dependency-free module, so the console's host gate and the
75
+ * organization-slug blocklist derive the same label from the same two
76
+ * settings. An install whose console is not at `app.` or `console.` is the
77
+ * case it exists for: without it, that label is read as a workspace nobody
78
+ * owns.
79
+ */ export function consoleLabelUnder(consoleUrl, workspaceDomain) {
80
+ const domain = String(workspaceDomain != null ? workspaceDomain : '').trim().toLowerCase();
81
+ const raw = String(consoleUrl != null ? consoleUrl : '').trim();
82
+ if (!domain || !raw) return null;
83
+ let hostname;
84
+ try {
85
+ hostname = new URL(raw).hostname.toLowerCase();
86
+ } catch (unused) {
87
+ return null;
88
+ }
89
+ if (!hostname.endsWith(`.${domain}`)) return null;
90
+ const label = hostname.slice(0, -(domain.length + 1));
91
+ return label && !label.includes('.') ? label : null;
92
+ }
66
93
  /** True when the subdomain is reserved or contains a blocked fragment. */ export function isBlockedSubdomain(subdomain) {
67
94
  const normalized = subdomain.toLowerCase();
68
95
  if (RESERVED_SUBDOMAINS.has(normalized)) return true;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/host-naming.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 * Host naming guards (AGL-147): one shared subdomain policy for the create\n * API, the rename/validate API, and the console dialogs — pattern, reserved\n * + profanity blocklists, a display-name → subdomain generator, and\n * taken-name suggestions.\n */\n\n/** 3–30 chars, lowercase alphanumeric + dashes, no leading dash. */\nexport const SUBDOMAIN_PATTERN = /^[a-z0-9][a-z0-9-]{2,29}$/\n\n/** Platform/system names a tenant must not squat. */\nexport const RESERVED_SUBDOMAINS = new Set([\n 'www',\n 'app',\n 'api',\n 'admin',\n 'console',\n 'mail',\n 'demo',\n 'staging',\n 'dev',\n 'test',\n 'docs',\n 'blog',\n 'help',\n 'support',\n 'status',\n 'cdn',\n 'assets',\n 'static',\n 'ftp',\n 'smtp',\n 'ns1',\n 'ns2',\n 'aglyn',\n 'billing',\n 'account',\n 'login',\n 'signup',\n 'auth',\n])\n\n/**\n * Profanity fragments blocked as substrings in generated or typed\n * subdomains. Deliberately short: obvious slurs and vulgarity only —\n * substring matching is aggressive, so entries must be unambiguous.\n */\nconst BLOCKED_FRAGMENTS = [\n 'fuck',\n 'shit',\n 'cunt',\n 'nigger',\n 'faggot',\n 'bitch',\n 'porn',\n 'nazi',\n]\n\n/** True when the subdomain is reserved or contains a blocked fragment. */\nexport function isBlockedSubdomain(subdomain: string): boolean {\n const normalized = subdomain.toLowerCase()\n if (RESERVED_SUBDOMAINS.has(normalized)) return true\n const collapsed = normalized.replace(/[^a-z0-9]/g, '')\n return BLOCKED_FRAGMENTS.some((fragment) => collapsed.includes(fragment))\n}\n\n/**\n * Best-effort subdomain from a display name: lowercase, spaces/symbols to\n * dashes, collapsed, trimmed to the pattern's 30-char cap. Returns '' when\n * nothing usable remains (caller falls back to manual entry).\n */\nexport function generateSubdomain(displayName: string): string {\n const slug = displayName\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 30)\n .replace(/-+$/, '')\n if (!SUBDOMAIN_PATTERN.test(slug) || isBlockedSubdomain(slug)) return ''\n return slug\n}\n\n/**\n * Alternatives for a taken subdomain: `name-2`, `name-<year>`, `name-site`.\n * Candidates are truncated to fit the pattern; blocked names are dropped.\n * Availability is the caller's job (needs a Firestore query).\n */\nexport function suggestSubdomains(base: string, year = new Date().getFullYear()): string[] {\n const stem = base.toLowerCase().replace(/-+$/, '')\n const withSuffix = (suffix: string) =>\n `${stem.slice(0, 30 - suffix.length - 1)}-${suffix}`.replace(/-{2,}/g, '-')\n const candidates = [withSuffix('2'), withSuffix(String(year)), withSuffix('site')]\n return [\n ...new Set(\n candidates.filter(\n (candidate) =>\n SUBDOMAIN_PATTERN.test(candidate) && !isBlockedSubdomain(candidate),\n ),\n ),\n ]\n}\n\n/**\n * The apex tenant sites are served from. Console lives on `app.aglyn.com`.\n *\n * CONFIGURABLE, not a literal (AGL-2121). AGL-2022 moved the console's\n * *display* links onto `NEXT_PUBLIC_TENANT_DOMAIN` and shipped a green spec\n * for it; this constant — which every OTHER consumer reads — stayed a bare\n * `'aglyn.app'`. So a self-hoster who set the variable got correct \"View live\"\n * links in their own console while the software went on emitting our apex\n * everywhere that actually reaches the public: `<link rel=\"canonical\">`,\n * `/api/sitemap`, `/api/robots`, `/api/collections-rss` item links,\n * `/api/manifest`, `og:image`, and the origin inbox-bound `<img src>` resolves\n * against. Their customers' sites told Google, every feed reader and every\n * inbox that they lived at a name the operator does not control and we do not\n * serve for them.\n *\n * Same variable and same default as `tenant-links.ts` — one value, one name\n * (AGL-733). Dot notation is load-bearing: this module reaches client bundles,\n * and Next inlines `NEXT_PUBLIC_*` by substituting `process.env.NAME`\n * textually; the bracket form is never substituted and would read `undefined`\n * in the browser. Trimmed so a half-finished `.env` line reads as absent\n * rather than as a whitespace apex.\n *\n * The asymmetry with `operator-identity.ts` — which refuses to default at all\n * — is deliberate. A wrong apex is visible to the operator on the first click\n * in their own console, so a default they can see and correct is a default. A\n * wrong contact address fails silently and off-site, which is why that one\n * refuses to guess.\n */\nexport const TENANT_APEX =\n (process.env.NEXT_PUBLIC_TENANT_DOMAIN || '').trim() || 'aglyn.app'\n\n/**\n * The absolute origin a published site is reachable at (AGL-1224).\n *\n * A custom domain wins over the platform subdomain, matching what the tenant\n * renderer already emits as `<link rel=\"canonical\">` — a site on a custom\n * domain that advertised its `.aglyn.app` origin would be describing itself\n * by a name its visitors never see.\n *\n * Returns undefined rather than a half-built URL when a host has neither, so\n * a caller that needs an absolute URL can tell it does not have one. Emails\n * are the sharp case: an image `src` that is site-relative resolves against\n * nothing in an inbox, so \"no origin\" has to be answerable.\n */\nexport function hostPublicOrigin(\n host:\n | { cname?: string | null; subdomain?: string | null }\n | null\n | undefined,\n): string | undefined {\n if (host?.cname) return `https://${host.cname}`\n if (host?.subdomain) return `https://${host.subdomain}.${TENANT_APEX}`\n return undefined\n}\n\n/**\n * The custom-domain lifecycle as it is actually persisted on the host doc.\n *\n * There is no `verifiedAt`, no `status`, no `sslReady` — the console's\n * `/api/domains/*` routes write exactly these three fields, so this is the\n * whole vocabulary anything downstream has to reason from.\n */\nexport interface HostCustomDomainState {\n cname?: string | null\n /** Vercel attach failed or was unconfigured — the domain does NOT serve. */\n cnameAttachmentPending?: boolean | null\n /** Vercel detach failed — the customer is mid-disconnect. */\n cnameDetachmentPending?: boolean | null\n subdomain?: string | null\n}\n\n/** A bare hostname: labels of a-z0-9/dash, at least two of them. */\nconst CUSTOM_DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.(?!-)[a-z0-9-]{1,63})+$/\n\n/**\n * The custom domain a host is actually **serving on**, or undefined (AGL-1272).\n *\n * Deliberately stricter than `hostPublicOrigin`, which answers \"what name does\n * this site call itself\" and is right to prefer `cname` the moment it exists.\n * This answers a load-bearing question instead — \"is it safe to send visitors\n * away from the platform subdomain and onto this name\" — and the cost of\n * getting it wrong is the whole site, not a wrong URL in an email.\n *\n * So every reason to doubt the domain is a refusal:\n *\n * - `cnameAttachmentPending` means the Vercel attach never landed (missing\n * env, or a 5xx). The domain is claimed in Firestore and serves nothing:\n * no certificate, no routing. This is precisely the \"attached but not\n * live\" state, and redirecting to it strands the site on a dead host.\n * - `cnameDetachmentPending` means the customer asked to disconnect and the\n * platform release failed. The name may still resolve, but the customer's\n * stated intent is to leave it, so we stop advertising it.\n * - A name inside `aglyn.app` is refused outright. `{sub}.aglyn.app` is the\n * very origin we redirect FROM, and the tenant middleware resolves that\n * space by `subdomain` before it ever considers `cname` — so a host whose\n * cname pointed back into it would redirect to itself forever.\n * - A name that is not hostname-shaped is refused. `/api/domains/attach`\n * lowercases and trims what the wizard sends but never pattern-checks it\n * (only `/api/domains/verify` does), so a junk value can reach Firestore.\n * A junk value reaching a `Location:` header is a different class of\n * problem again.\n *\n * Note what this CANNOT tell you: DNS was verified once, at connect time, and\n * nothing re-checks it. A domain whose DNS is later repointed or whose\n * registration lapses still reads as live here. That residual risk is why the\n * redirect built on this is temporary and revocable rather than permanent.\n */\nexport function liveCustomDomain(\n host: HostCustomDomainState | null | undefined,\n): string | undefined {\n if (!host) return undefined\n if (host.cnameAttachmentPending === true) return undefined\n if (host.cnameDetachmentPending === true) return undefined\n const domain = String(host.cname ?? '')\n .trim()\n .toLowerCase()\n if (!CUSTOM_DOMAIN_PATTERN.test(domain)) return undefined\n if (domain === TENANT_APEX || domain.endsWith(`.${TENANT_APEX}`)) {\n return undefined\n }\n return domain\n}\n"],"names":["SUBDOMAIN_PATTERN","RESERVED_SUBDOMAINS","Set","BLOCKED_FRAGMENTS","isBlockedSubdomain","subdomain","normalized","toLowerCase","has","collapsed","replace","some","fragment","includes","generateSubdomain","displayName","slug","normalize","slice","test","suggestSubdomains","base","year","Date","getFullYear","stem","withSuffix","suffix","length","candidates","String","filter","candidate","TENANT_APEX","process","env","NEXT_PUBLIC_TENANT_DOMAIN","trim","hostPublicOrigin","host","cname","undefined","CUSTOM_DOMAIN_PATTERN","liveCustomDomain","cnameAttachmentPending","cnameDetachmentPending","domain","endsWith"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAED,kEAAkE,GAClE,OAAO,MAAMA,oBAAoB,4BAA2B;AAE5D,mDAAmD,GACnD,OAAO,MAAMC,sBAAsB,IAAIC,IAAI;IACzC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAC;AAEF;;;;CAIC,GACD,MAAMC,oBAAoB;IACxB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,wEAAwE,GACxE,OAAO,SAASC,mBAAmBC,SAAiB;IAClD,MAAMC,aAAaD,UAAUE,WAAW;IACxC,IAAIN,oBAAoB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AQ,EAAED,KAAKC,KAAK,EAAE;IAC/C,IAAID,wBAAAA,KAAMlC,SAAS,EAAE,OAAO,CAAC,QAAQ,EAAEkC,KAAKlC,SAAS,CAAC,CAAC,EAAE4B,aAAa;IACtE,OAAOQ;AACT;AAkBA,kEAAkE,GAClE,MAAMC,wBAAwB;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GACD,OAAO,SAASC,iBACdJ,IAA8C;QAKxBA;IAHtB,IAAI,CAACA,MAAM,OAAOE;IAClB,IAAIF,KAAKK,sBAAsB,KAAK,MAAM,OAAOH;IACjD,IAAIF,KAAKM,sBAAsB,KAAK,MAAM,OAAOJ;IACjD,MAAMK,SAAShB,QAAOS,cAAAA,KAAKC,KAAK,YAAVD,cAAc,IACjCF,IAAI,GACJ9B,WAAW;IACd,IAAI,CAACmC,sBAAsBvB,IAAI,CAAC2B,SAAS,OAAOL;IAChD,IAAIK,WAAWb,eAAea,OAAOC,QAAQ,CAAC,CAAC,CAAC,EAAEd,aAAa,GAAG;QAChE,OAAOQ;IACT;IACA,OAAOK;AACT"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/host-naming.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 * Host naming guards (AGL-147): one shared subdomain policy for the create\n * API, the rename/validate API, and the console dialogs — pattern, reserved\n * + profanity blocklists, a display-name → subdomain generator, and\n * taken-name suggestions.\n */\n\n/** 3–30 chars, lowercase alphanumeric + dashes, no leading dash. */\nexport const SUBDOMAIN_PATTERN = /^[a-z0-9][a-z0-9-]{2,29}$/\n\n/** Platform/system names a tenant must not squat. */\nexport const RESERVED_SUBDOMAINS = new Set([\n 'www',\n 'app',\n 'api',\n 'admin',\n 'console',\n 'mail',\n 'demo',\n 'staging',\n 'dev',\n 'test',\n 'docs',\n 'blog',\n 'help',\n 'support',\n 'status',\n 'cdn',\n 'assets',\n 'static',\n 'ftp',\n 'smtp',\n 'ns1',\n 'ns2',\n 'aglyn',\n 'billing',\n 'account',\n 'login',\n 'signup',\n 'auth',\n])\n\n/**\n * Profanity fragments blocked as substrings in generated or typed\n * subdomains. Deliberately short: obvious slurs and vulgarity only —\n * substring matching is aggressive, so entries must be unambiguous.\n */\nconst BLOCKED_FRAGMENTS = [\n 'fuck',\n 'shit',\n 'cunt',\n 'nigger',\n 'faggot',\n 'bitch',\n 'porn',\n 'nazi',\n]\n\n/**\n * The one label a console URL occupies directly under a workspace domain\n * (AGL-3295): `studio` for `https://studio.example.com` under `example.com`.\n *\n * `null` when either setting is missing or unparseable, and when the console\n * is the apex itself, sits deeper, or lies outside the domain — none of those\n * can collide with a workspace address, so none needs reserving.\n *\n * Pure, and in this dependency-free module, so the console's host gate and the\n * organization-slug blocklist derive the same label from the same two\n * settings. An install whose console is not at `app.` or `console.` is the\n * case it exists for: without it, that label is read as a workspace nobody\n * owns.\n */\nexport function consoleLabelUnder(\n consoleUrl: string | null | undefined,\n workspaceDomain: string | null | undefined,\n): string | null {\n const domain = String(workspaceDomain ?? '')\n .trim()\n .toLowerCase()\n const raw = String(consoleUrl ?? '').trim()\n if (!domain || !raw) return null\n let hostname: string\n try {\n hostname = new URL(raw).hostname.toLowerCase()\n } catch {\n return null\n }\n if (!hostname.endsWith(`.${domain}`)) return null\n const label = hostname.slice(0, -(domain.length + 1))\n return label && !label.includes('.') ? label : null\n}\n\n/** True when the subdomain is reserved or contains a blocked fragment. */\nexport function isBlockedSubdomain(subdomain: string): boolean {\n const normalized = subdomain.toLowerCase()\n if (RESERVED_SUBDOMAINS.has(normalized)) return true\n const collapsed = normalized.replace(/[^a-z0-9]/g, '')\n return BLOCKED_FRAGMENTS.some((fragment) => collapsed.includes(fragment))\n}\n\n/**\n * Best-effort subdomain from a display name: lowercase, spaces/symbols to\n * dashes, collapsed, trimmed to the pattern's 30-char cap. Returns '' when\n * nothing usable remains (caller falls back to manual entry).\n */\nexport function generateSubdomain(displayName: string): string {\n const slug = displayName\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 30)\n .replace(/-+$/, '')\n if (!SUBDOMAIN_PATTERN.test(slug) || isBlockedSubdomain(slug)) return ''\n return slug\n}\n\n/**\n * Alternatives for a taken subdomain: `name-2`, `name-<year>`, `name-site`.\n * Candidates are truncated to fit the pattern; blocked names are dropped.\n * Availability is the caller's job (needs a Firestore query).\n */\nexport function suggestSubdomains(base: string, year = new Date().getFullYear()): string[] {\n const stem = base.toLowerCase().replace(/-+$/, '')\n const withSuffix = (suffix: string) =>\n `${stem.slice(0, 30 - suffix.length - 1)}-${suffix}`.replace(/-{2,}/g, '-')\n const candidates = [withSuffix('2'), withSuffix(String(year)), withSuffix('site')]\n return [\n ...new Set(\n candidates.filter(\n (candidate) =>\n SUBDOMAIN_PATTERN.test(candidate) && !isBlockedSubdomain(candidate),\n ),\n ),\n ]\n}\n\n/**\n * The apex tenant sites are served from. Console lives on `app.aglyn.com`.\n *\n * CONFIGURABLE, not a literal (AGL-2121). AGL-2022 moved the console's\n * *display* links onto `NEXT_PUBLIC_TENANT_DOMAIN` and shipped a green spec\n * for it; this constant — which every OTHER consumer reads — stayed a bare\n * `'aglyn.app'`. So a self-hoster who set the variable got correct \"View live\"\n * links in their own console while the software went on emitting our apex\n * everywhere that actually reaches the public: `<link rel=\"canonical\">`,\n * `/api/sitemap`, `/api/robots`, `/api/collections-rss` item links,\n * `/api/manifest`, `og:image`, and the origin inbox-bound `<img src>` resolves\n * against. Their customers' sites told Google, every feed reader and every\n * inbox that they lived at a name the operator does not control and we do not\n * serve for them.\n *\n * Same variable and same default as `tenant-links.ts` — one value, one name\n * (AGL-733). Dot notation is load-bearing: this module reaches client bundles,\n * and Next inlines `NEXT_PUBLIC_*` by substituting `process.env.NAME`\n * textually; the bracket form is never substituted and would read `undefined`\n * in the browser. Trimmed so a half-finished `.env` line reads as absent\n * rather than as a whitespace apex.\n *\n * The asymmetry with `operator-identity.ts` — which refuses to default at all\n * — is deliberate. A wrong apex is visible to the operator on the first click\n * in their own console, so a default they can see and correct is a default. A\n * wrong contact address fails silently and off-site, which is why that one\n * refuses to guess.\n */\nexport const TENANT_APEX =\n (process.env.NEXT_PUBLIC_TENANT_DOMAIN || '').trim() || 'aglyn.app'\n\n/**\n * The absolute origin a published site is reachable at (AGL-1224).\n *\n * A custom domain wins over the platform subdomain, matching what the tenant\n * renderer already emits as `<link rel=\"canonical\">` — a site on a custom\n * domain that advertised its `.aglyn.app` origin would be describing itself\n * by a name its visitors never see.\n *\n * Returns undefined rather than a half-built URL when a host has neither, so\n * a caller that needs an absolute URL can tell it does not have one. Emails\n * are the sharp case: an image `src` that is site-relative resolves against\n * nothing in an inbox, so \"no origin\" has to be answerable.\n */\nexport function hostPublicOrigin(\n host:\n | { cname?: string | null; subdomain?: string | null }\n | null\n | undefined,\n): string | undefined {\n if (host?.cname) return `https://${host.cname}`\n if (host?.subdomain) return `https://${host.subdomain}.${TENANT_APEX}`\n return undefined\n}\n\n/**\n * The custom-domain lifecycle as it is actually persisted on the host doc.\n *\n * There is no `verifiedAt`, no `status`, no `sslReady` — the console's\n * `/api/domains/*` routes write exactly these three fields, so this is the\n * whole vocabulary anything downstream has to reason from.\n */\nexport interface HostCustomDomainState {\n cname?: string | null\n /** Vercel attach failed or was unconfigured — the domain does NOT serve. */\n cnameAttachmentPending?: boolean | null\n /** Vercel detach failed — the customer is mid-disconnect. */\n cnameDetachmentPending?: boolean | null\n subdomain?: string | null\n}\n\n/** A bare hostname: labels of a-z0-9/dash, at least two of them. */\nconst CUSTOM_DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.(?!-)[a-z0-9-]{1,63})+$/\n\n/**\n * The custom domain a host is actually **serving on**, or undefined (AGL-1272).\n *\n * Deliberately stricter than `hostPublicOrigin`, which answers \"what name does\n * this site call itself\" and is right to prefer `cname` the moment it exists.\n * This answers a load-bearing question instead — \"is it safe to send visitors\n * away from the platform subdomain and onto this name\" — and the cost of\n * getting it wrong is the whole site, not a wrong URL in an email.\n *\n * So every reason to doubt the domain is a refusal:\n *\n * - `cnameAttachmentPending` means the Vercel attach never landed (missing\n * env, or a 5xx). The domain is claimed in Firestore and serves nothing:\n * no certificate, no routing. This is precisely the \"attached but not\n * live\" state, and redirecting to it strands the site on a dead host.\n * - `cnameDetachmentPending` means the customer asked to disconnect and the\n * platform release failed. The name may still resolve, but the customer's\n * stated intent is to leave it, so we stop advertising it.\n * - A name inside `aglyn.app` is refused outright. `{sub}.aglyn.app` is the\n * very origin we redirect FROM, and the tenant middleware resolves that\n * space by `subdomain` before it ever considers `cname` — so a host whose\n * cname pointed back into it would redirect to itself forever.\n * - A name that is not hostname-shaped is refused. `/api/domains/attach`\n * lowercases and trims what the wizard sends but never pattern-checks it\n * (only `/api/domains/verify` does), so a junk value can reach Firestore.\n * A junk value reaching a `Location:` header is a different class of\n * problem again.\n *\n * Note what this CANNOT tell you: DNS was verified once, at connect time, and\n * nothing re-checks it. A domain whose DNS is later repointed or whose\n * registration lapses still reads as live here. That residual risk is why the\n * redirect built on this is temporary and revocable rather than permanent.\n */\nexport function liveCustomDomain(\n host: HostCustomDomainState | null | undefined,\n): string | undefined {\n if (!host) return undefined\n if (host.cnameAttachmentPending === true) return undefined\n if (host.cnameDetachmentPending === true) return undefined\n const domain = String(host.cname ?? '')\n .trim()\n .toLowerCase()\n if (!CUSTOM_DOMAIN_PATTERN.test(domain)) return undefined\n if (domain === TENANT_APEX || domain.endsWith(`.${TENANT_APEX}`)) {\n return undefined\n }\n return domain\n}\n"],"names":["SUBDOMAIN_PATTERN","RESERVED_SUBDOMAINS","Set","BLOCKED_FRAGMENTS","consoleLabelUnder","consoleUrl","workspaceDomain","domain","String","trim","toLowerCase","raw","hostname","URL","endsWith","label","slice","length","includes","isBlockedSubdomain","subdomain","normalized","has","collapsed","replace","some","fragment","generateSubdomain","displayName","slug","normalize","test","suggestSubdomains","base","year","Date","getFullYear","stem","withSuffix","suffix","candidates","filter","candidate","TENANT_APEX","process","env","NEXT_PUBLIC_TENANT_DOMAIN","hostPublicOrigin","host","cname","undefined","CUSTOM_DOMAIN_PATTERN","liveCustomDomain","cnameAttachmentPending","cnameDetachmentPending"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAED,kEAAkE,GAClE,OAAO,MAAMA,oBAAoB,4BAA2B;AAE5D,mDAAmD,GACnD,OAAO,MAAMC,sBAAsB,IAAIC,IAAI;IACzC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAC;AAEF;;;;CAIC,GACD,MAAMC,oBAAoB;IACxB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,kBACdC,UAAqC,EACrCC,eAA0C;IAE1C,MAAMC,SAASC,OAAOF,0BAAAA,kBAAmB,IACtCG,IAAI,GACJC,WAAW;IACd,MAAMC,MAAMH,OAAOH,qBAAAA,aAAc,IAAII,IAAI;IACzC,IAAI,CAACF,UAAU,CAACI,KAAK,OAAO;IAC5B,IAAIC;IACJ,IAAI;QACFA,WAAW,IAAIC,IAAIF,KAAKC,QAAQ,CAACF,WAAW;IAC9C,EAAE,eAAM;QACN,OAAO;IACT;IACA,IAAI,CAACE,SAASE,QAAQ,CAAC,CAAC,CAAC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W,cAAc,CAACvB,mBAAmBuB;KAGhE;AACH;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,MAAMC,cACX,AAACC,CAAAA,QAAQC,GAAG,CAACC,yBAAyB,IAAI,EAAC,EAAGrC,IAAI,MAAM,YAAW;AAErE;;;;;;;;;;;;CAYC,GACD,OAAO,SAASsC,iBACdC,IAGa;IAEb,IAAIA,wBAAAA,KAAMC,KAAK,EAAE,OAAO,CAAC,QAAQ,EAAED,KAAKC,KAAK,EAAE;IAC/C,IAAID,wBAAAA,KAAM5B,SAAS,EAAE,OAAO,CAAC,QAAQ,EAAE4B,KAAK5B,SAAS,CAAC,CAAC,EAAEuB,aAAa;IACtE,OAAOO;AACT;AAkBA,kEAAkE,GAClE,MAAMC,wBAAwB;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GACD,OAAO,SAASC,iBACdJ,IAA8C;QAKxBA;IAHtB,IAAI,CAACA,MAAM,OAAOE;IAClB,IAAIF,KAAKK,sBAAsB,KAAK,MAAM,OAAOH;IACjD,IAAIF,KAAKM,sBAAsB,KAAK,MAAM,OAAOJ;IACjD,MAAM3C,SAASC,QAAOwC,cAAAA,KAAKC,KAAK,YAAVD,cAAc,IACjCvC,IAAI,GACJC,WAAW;IACd,IAAI,CAACyC,sBAAsBpB,IAAI,CAACxB,SAAS,OAAO2C;IAChD,IAAI3C,WAAWoC,eAAepC,OAAOO,QAAQ,CAAC,CAAC,CAAC,EAAE6B,aAAa,GAAG;QAChE,OAAOO;IACT;IACA,OAAO3C;AACT"}
@@ -18,7 +18,7 @@
18
18
  * (`{slug}.aglyn.com`) and role math shared by the org APIs, the console
19
19
  * UI, and the Firestore rules' mental model. See
20
20
  * docs/MULTI_TENANT_FIRESTORE.md.
21
- */ import { generateSubdomain, isBlockedSubdomain, SUBDOMAIN_PATTERN } from "./host-naming.js";
21
+ */ import { consoleLabelUnder, generateSubdomain, isBlockedSubdomain, SUBDOMAIN_PATTERN } from "./host-naming.js";
22
22
  import { hostScopeToken, ORG_SCOPE_TOKEN, visibleToTokens } from "./scope-tokens.js";
23
23
  /** Same lexical policy as host subdomains: 3–30 lowercase/digits/dashes. */ export const ORG_SLUG_PATTERN = SUBDOMAIN_PATTERN;
24
24
  /**
@@ -30,8 +30,19 @@ import { hostScopeToken, ORG_SCOPE_TOKEN, visibleToTokens } from "./scope-tokens
30
30
  'orgs',
31
31
  'workspace'
32
32
  ]);
33
+ /**
34
+ * The label this deployment serves its own console on, when it has one
35
+ * (AGL-3295).
36
+ *
37
+ * `app` and `console` are reserved above for every install. One whose console
38
+ * lives at, say, `studio.example.com` needs `studio` refused as well, or an
39
+ * organization could claim a workspace address the console itself answers.
40
+ * Read from the same two settings the console's host gate reads; with either
41
+ * unset nothing extra is reserved, because nothing extra is shadowed.
42
+ */ const CONSOLE_LABEL = consoleLabelUnder(process.env.NEXT_PUBLIC_CONSOLE_URL, process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN);
33
43
  export function isBlockedOrgSlug(slug) {
34
- return RESERVED_ORG_ONLY.has(slug.toLowerCase()) || isBlockedSubdomain(slug);
44
+ const normalized = slug.toLowerCase();
45
+ return RESERVED_ORG_ONLY.has(normalized) || normalized === CONSOLE_LABEL || isBlockedSubdomain(slug);
35
46
  }
36
47
  export function isValidOrgSlug(slug) {
37
48
  return ORG_SLUG_PATTERN.test(slug) && !isBlockedOrgSlug(slug);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/organizations.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 * Organization helpers (AGL-233): slug policy for workspace subdomains\n * (`{slug}.aglyn.com`) and role math shared by the org APIs, the console\n * UI, and the Firestore rules' mental model. See\n * docs/MULTI_TENANT_FIRESTORE.md.\n */\n\nimport type {\n AglynOrgMember,\n HostAccessRole,\n HostUid,\n OrgRole,\n ScopeToken,\n UserOrgMembership,\n} from '../foundation'\nimport {\n generateSubdomain,\n isBlockedSubdomain,\n SUBDOMAIN_PATTERN,\n} from './host-naming'\nimport {\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n visibleToTokens,\n} from './scope-tokens'\n\n/** Same lexical policy as host subdomains: 3–30 lowercase/digits/dashes. */\nexport const ORG_SLUG_PATTERN = SUBDOMAIN_PATTERN\n\n/**\n * Org workspace slugs ride the host reserved/profanity blocklist plus\n * console-specific labels the workspace router must own.\n */\nconst RESERVED_ORG_ONLY = new Set(['staff', 'org', 'orgs', 'workspace'])\n\nexport function isBlockedOrgSlug(slug: string): boolean {\n return RESERVED_ORG_ONLY.has(slug.toLowerCase()) || isBlockedSubdomain(slug)\n}\n\nexport function isValidOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug) && !isBlockedOrgSlug(slug)\n}\n\n/** Best-effort slug from an org name; '' when nothing usable remains. */\nexport function generateOrgSlug(name: string): string {\n const slug = generateSubdomain(name)\n return slug && !isBlockedOrgSlug(slug) ? slug : ''\n}\n\nexport const ORG_ROLES: readonly OrgRole[] = [\n 'owner',\n 'admin',\n 'editor',\n 'viewer',\n]\n\nconst ORG_ROLE_WEIGHT: Record<OrgRole, number> = {\n owner: 3,\n admin: 2,\n editor: 1,\n viewer: 0,\n}\n\nexport function isOrgRole(value: unknown): value is OrgRole {\n return typeof value === 'string' && value in ORG_ROLE_WEIGHT\n}\n\nexport function orgRoleAtLeast(\n role: OrgRole | null | undefined,\n minimum: OrgRole,\n): boolean {\n if (!role || !(role in ORG_ROLE_WEIGHT)) return false\n return ORG_ROLE_WEIGHT[role] >= ORG_ROLE_WEIGHT[minimum]\n}\n\n/** Org settings, members, invites, host creation: admin and owner. */\nexport function canManageOrg(role: OrgRole | null | undefined): boolean {\n return orgRoleAtLeast(role, 'admin')\n}\n\n/**\n * The member's effective role on one host, or null for no access.\n * Owner/admin span every host; editor/viewer resolve through `allHosts`\n * (mapped to their org role) or the per-host access map.\n */\nexport function hostRoleFor(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): HostAccessRole | null {\n const role = member?.role\n if (!isOrgRole(role)) return null\n if (role === 'owner' || role === 'admin') return 'admin'\n const explicit = member?.hostAccess?.[hostId]\n if (explicit) return explicit\n return member?.allHosts ? role : null\n}\n\n/**\n * Host roles that may MUTATE content — the axis `canWriteHostContent()` in\n * the security rules asks (AGL-2334).\n *\n * `author` is here and absent from `HOST_PUBLISH_ROLES` below: that single\n * difference IS the \"edit content but not publish\" role. Kept as two named\n * sets rather than two inline comparisons because they are read in three\n * places that must not drift — this module, the ~20 server gates, and the\n * rules — and because a new host role added to the union has to be a\n * deliberate decision on BOTH lists rather than an omission from one.\n */\nexport const HOST_CONTENT_WRITE_ROLES: readonly HostAccessRole[] = [\n 'admin',\n 'editor',\n 'author',\n]\n\n/**\n * Host roles that may make content LIVE. Everything that registers a route,\n * moves a live-version pointer, schedules either of those for later, or\n * flips a collection entry to `published` asks this and not the set above.\n *\n * The list is short and it is the whole product decision: `author` is not on\n * it. If a role is ever added here, the rules' `canPublishHostContent()` and\n * the publish-surface field freezes below it must be updated in the same\n * change — they are the enforcement, this is the server-side echo of it.\n */\nexport const HOST_PUBLISH_ROLES: readonly HostAccessRole[] = ['admin', 'editor']\n\n/**\n * Whether the member may mutate a host's content — admin, editor **or\n * author** on it.\n *\n * An author is a content editor in every respect this predicate covers; what\n * it deliberately does NOT cover is publication. Any caller that is really\n * asking \"may this person make something live\" must call `canPublishHost`\n * instead — this one answering `true` for an author is the point of the role,\n * not a gap in it.\n */\nexport function canWriteHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_CONTENT_WRITE_ROLES.includes(role)\n}\n\n/**\n * Whether the member may PUBLISH on a host — register a route, move a live\n * version pointer, schedule either for later, or publish a collection entry.\n *\n * Strictly narrower than `canWriteHost`: `author` edits and does not publish.\n * This is the server-side echo of the rules, not the enforcement — publishing\n * is a set of client-direct Firestore writes across five document shapes, so\n * `cloud/firebase-firestore.rules` is where it is actually refused. Server\n * routes that schedule or trigger a publish ask this so the console can say\n * no with a message instead of surfacing a bare permission-denied.\n */\nexport function canPublishHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_PUBLISH_ROLES.includes(role)\n}\n\n/**\n * The same question asked of a bare `memberRoles` value rather than a member\n * document — the shape every Admin-SDK route already has in hand after its\n * `hosts/{hostId}` read, so it does not have to re-load the org membership.\n *\n * `String(role)` at the call sites keeps `undefined` out; an unknown value\n * is simply not in the set, which fails CLOSED.\n */\nexport function hostRoleCanWrite(role: unknown): boolean {\n return HOST_CONTENT_WRITE_ROLES.includes(role as HostAccessRole)\n}\n\n/** Publish-axis twin of `hostRoleCanWrite`; `author` is excluded. */\nexport function hostRoleCanPublish(role: unknown): boolean {\n return HOST_PUBLISH_ROLES.includes(role as HostAccessRole)\n}\n\n/**\n * Whether a member's reach is the whole org rather than a list of sites.\n *\n * Owner and admin always are; editor/viewer are only when `allHosts` says\n * so — **or** when the membership predates the flag entirely. A pre-\n * `allHosts` doc carries neither the flag nor a `hostAccess` map, and\n * reading that as \"scoped, with access to nothing\" would lock real members\n * out of their own workspace. A site collaborator ALWAYS has a non-empty\n * `hostAccess` (that is what `grantHostAccess` writes), so the absence of\n * both is the legacy shape, not a scoped one.\n *\n * Single source of truth for `resolveOrgPermissions` (the server gate),\n * `projectMemberScopeTokens` (the rules projection), and the rules'\n * own `isOrgWideMember()` — three copies of this predicate that disagree\n * is a privilege bug, not a style problem (AGL-1026, AGL-1038).\n */\nexport function isOrgWideMember(\n member: Partial<AglynOrgMember> | null | undefined,\n): boolean {\n if (!member) return false\n const role = member.role\n if (role === 'owner' || role === 'admin') return true\n if (member.allHosts === true) return true\n const scoping = member.hostAccess\n return (\n member.allHosts === undefined && !Object.keys(scoping ?? {}).length\n )\n}\n\n/**\n * How many of these roster entries consume a **manager** seat (AGL-1113).\n *\n * `orgs/{orgId}/members` holds BOTH org managers and site-scoped\n * collaborators — adding a collaborator to one site writes an org member doc\n * with `allHosts:false` + `hostAccess`, so a raw `.count()` of the collection\n * billed every collaborator as a manager. Collaborators are metered\n * separately, per host, against `membersPerHost` at\n * `hosts/{hostId}/members` — counting them here charged them twice and\n * tripped the manager gate for orgs nowhere near their manager limit.\n *\n * Reuses `isOrgWideMember` rather than filtering on `allHosts` directly:\n * owner/admin are managers whatever the flag says, and a pre-`allHosts` doc\n * is a manager too. A Firestore `where('allHosts','==',true)` count gets both\n * of those wrong, which is why callers pass entries in and count here.\n *\n * Accepts pending INVITES as well as members — an invite carries the same\n * `role`/`allHosts`/`hostAccess` shape and reserves the seat it will become.\n */\nexport function countManagerSeats(\n entries: ReadonlyArray<Partial<AglynOrgMember> | null | undefined>,\n): number {\n let count = 0\n for (const entry of entries) if (isOrgWideMember(entry)) count += 1\n return count\n}\n\n/**\n * One roster row or pending invite, as the collaborator counter needs to see\n * it (AGL-2068). Deliberately structural rather than `Partial<AglynOrgMember>`\n * — an INVITE is not a member document, it is keyed by email and has no uid,\n * and the whole point of this counter is that the two populations must be\n * counted together or the cap is enforced against a fraction of itself.\n */\nexport interface CollaboratorSeatEntry {\n /** Member documents are keyed by uid; invites have none. */\n uid?: string | null\n email?: string | null\n role?: unknown\n allHosts?: boolean\n hostAccess?: Record<string, unknown> | null\n}\n\n/**\n * The identity key one entry occupies, or `''` when it identifies nobody.\n *\n * EMAIL FIRST, uid second, and that order is the join (AGL-2068). A person\n * admitted to a site is one seat whether they arrive as an accepted member or\n * as a still-pending invite, and those two rows live in different collections\n * keyed different ways — `orgs/{id}/members/{uid}` and\n * `orgs/{id}/invites/{inviteId}` — with the address as the only field both\n * carry. Counting by uid would count the invite and the membership it becomes\n * as two seats; counting only invites would miss every member.\n *\n * Legacy roster rows written before `email` was mirrored fall back to the uid,\n * which cannot collide with an address (the `uid:` prefix is not a legal\n * local-part/domain pair) and so is safe to mix into the same set.\n */\nfunction collaboratorSeatKey(entry: CollaboratorSeatEntry): string {\n const email =\n typeof entry.email === 'string' ? entry.email.trim().toLowerCase() : ''\n if (email) return email\n const uid = typeof entry.uid === 'string' ? entry.uid.trim() : ''\n return uid ? `uid:${uid}` : ''\n}\n\n/**\n * Every principal consuming a COLLABORATOR seat on one host (AGL-2068).\n *\n * ## Why this exists at all\n *\n * `membersPerHost` was enforced on one of the four doors that admit a site\n * collaborator, and that one door counted `hosts/{hostId}/members` — a\n * DISPLAY roster only `/api/hosts/members` writes. The other three\n * (`/api/orgs/invites` create, `/api/orgs/invites` accept, and the\n * `hostAccess` branch of `/api/orgs/members`) land in `orgs/{id}/members` and\n * the `hosts/{id}.memberRoles` projection, and were invisible to it. So the\n * cap was both skipped on three paths and under-counted on the fourth, and a\n * free org — `membersPerHost: 1` — could take on unlimited collaborators,\n * each with full site access, on a plan that is never invoiced.\n *\n * verbatim: **\"We need to make sure the free/hobby tier\n * does hard cap so it always actually stays free.\"**\n *\n * ## What counts\n *\n * A SCOPED grant on `hostId`, and nothing else. An org-wide member\n * (owner/admin, or `allHosts`) reaches every host but consumes a MANAGER\n * seat — `countManagerSeats` is that side, and charging them here would bill\n * one person twice and trip a cap they are not on. This is the same split\n * AGL-1113 drew; it is now drawn from one place instead of three.\n *\n * Pending invites count, for the reason the manager gate counts them: an\n * invite reserves the seat it will become, and a cap that only bites on\n * acceptance can be walked past by mailing out N invites first.\n */\nexport function collaboratorSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n): Set<string> {\n const keys = new Set<string>()\n if (!hostId) return keys\n for (const entry of entries) {\n if (!entry) continue\n // Managers are the other counter's population, whatever host map they\n // happen to carry — a promoted collaborator keeps their old `hostAccess`.\n if (isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n if (!entry.hostAccess?.[hostId]) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many collaborator seats on `hostId` are spoken for by someone OTHER\n * than `exclude` (AGL-2068).\n *\n * `exclude` is the principal the caller is about to admit, and dropping them\n * is what makes this composable with `checkSeatQuota(…, used)`, whose\n * contract is \"usage BEFORE the resource being created\". Without it the\n * accept path refuses its own invite: at the moment acceptance is decided the\n * invitee holds a pending invite AND is about to hold a membership, so they\n * would be counted once or twice against a cap they are the subject of.\n *\n * Both identities are dropped, not whichever one is present. A person can be\n * on the roster under a uid with no mirrored email and hold an invite under\n * that address, and the seat is still one seat.\n *\n * ## `emails`, not `email` — an account holds several (AGL-2486)\n *\n * Since an invitation may be accepted at any CONFIRMED address on the account,\n * the pending invite the accepter is about to consume can be keyed by an\n * address that is not their primary. `exclude.email` alone is the primary, so\n * that invite survived the exclusion and the person was counted against a cap\n * they are the subject of — the exact double-count the paragraph above says\n * this function exists to prevent, re-opened by widening the accept match.\n *\n * It fails CLOSED (a spurious \"out of seats\" refusal, never a free seat), and\n * only for an org sitting exactly on its cap, which is why it survived review.\n *\n * `emails` takes every address PROVEN to belong to the principal being\n * admitted. Passing an address that is not theirs would hand out a free seat,\n * so callers must pass confirmed addresses for that uid and nothing else.\n */\nexport function countCollaboratorSeats(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = collaboratorSeatKeys(entries, hostId)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * Every principal consuming a MANAGER seat, as identities rather than rows.\n *\n * The org-wide half of `collaboratorSeatKeys`, drawn from the same entries and\n * split on the same predicate, so the two counters partition one roster\n * instead of overlapping on it.\n *\n * Deduplicating by identity is the difference from {@link countManagerSeats},\n * and it is what makes this composable with an `exclude`: a person holding a\n * pending invite AND the membership it became is one seat, and the row-wise\n * counter reports two because it is handed the two collections separately and\n * sums them.\n */\nexport function managerSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n): Set<string> {\n const keys = new Set<string>()\n for (const entry of entries) {\n if (!entry) continue\n if (!isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many manager seats are spoken for by someone OTHER than `exclude`.\n *\n * The manager twin of {@link countCollaboratorSeats}, and it exists for the\n * same reason that one takes an `exclude`: `checkSeatQuota`'s contract is\n * \"usage BEFORE the resource being created\", and on the invite-accept path the\n * accepter holds a pending invite and is about to hold a membership at the\n * same instant. Counted plainly they are charged once or twice for a seat they\n * are the subject of, and an org on its last seat refuses its own invitation.\n *\n * Both identities are dropped, and `emails` carries the further addresses\n * proven to belong to that account — an invitation may be accepted at any\n * confirmed address, so the invite being consumed need not be keyed by the\n * primary one. Passing an address that is not theirs would hand out a free\n * seat, so callers must pass confirmed addresses for that uid and nothing\n * else.\n *\n * Kept SEPARATE from {@link countManagerSeats} rather than replacing it: that\n * one is row-wise and is what the billing and console surfaces count with, and\n * quietly making it identity-wise would change every one of those totals.\n */\nexport function countManagerSeatsExcluding(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = managerSeatKeys(entries)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * What KIND of user a console row represents (AGL-1114) — the distinction\n * that decides which seat they consume, and the one the Team table could not\n * express because a manager and a collaborator differ only by fields the\n * table never showed.\n *\n * Deliberately NOT the same axis as `role`. A `role: 'editor'` is a manager\n * when their reach is the whole org and a collaborator when it is two sites;\n * reading the role alone is the mistake that let a collaborator look like\n * team staff (see the org-leak and role-gate work).\n *\n * `siteMember` is the third kind and never appears in `orgs/{id}/members` at\n * all: it is an end-user account on a PUBLISHED site (`siteMembers`), not a\n * console user. It has no Firebase Auth record of any kind — a site member is\n * a Firestore document under `hosts/{hostId}/siteMembers` with its own scrypt\n * hash and its own session cookie — so no surface that lists AUTH accounts,\n * the staff user directory included, can contain one. The label is here so the\n * vocabulary is complete, for a surface that lists site accounts and needs a\n * word for them. Free and uncounted on every plan (AGL-889).\n */\nexport type ConsoleUserType = 'manager' | 'collaborator' | 'siteMember'\n\nexport const CONSOLE_USER_TYPE_LABELS: Record<ConsoleUserType, string> = {\n manager: 'Team manager',\n collaborator: 'Site collaborator',\n siteMember: 'Site member',\n}\n\n/** One line on what each kind is and what it costs — tooltip/legend copy. */\nexport const CONSOLE_USER_TYPE_HINTS: Record<ConsoleUserType, string> = {\n manager:\n 'Reaches the whole organization. Uses one of your team (manager) seats.',\n collaborator:\n 'Scoped to specific sites. Uses a collaborator seat on each site they ' +\n 'can reach, not a team seat.',\n siteMember:\n 'An end-user account on a published site, not a console user. Free and ' +\n 'unlimited on every plan.',\n}\n\n/**\n * Classify an `orgs/{orgId}/members` entry (or a pending invite, same shape).\n * Never returns `siteMember` — nothing in that collection is one; the value\n * exists for surfaces that list published-site accounts and must label them —\n * never for one that lists both, since the two populations do not share an\n * identity system.\n */\nexport function consoleUserType(\n member: Partial<AglynOrgMember> | null | undefined,\n): Exclude<ConsoleUserType, 'siteMember'> {\n return isOrgWideMember(member) ? 'manager' : 'collaborator'\n}\n\n/**\n * Whether an account is governed by enterprise SSO (AGL-1128) — it lives in\n * an org's GCIP tenant pool rather than the project pool, so its identity is\n * owned by the customer's IdP.\n *\n * `tenantId` is the whole signal: Firebase sets it on the user whenever the\n * account belongs to a tenant, and only SSO accounts do.\n */\nexport function isSsoGovernedAccount(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return Boolean(user?.tenantId)\n}\n\n/**\n * Whether the account may connect an additional consumer sign-in provider.\n *\n * **No, for any SSO-governed account.** The customer's IdP is the single gate\n * they bought: they revoke there, enforce MFA there, offboard there. A linked\n * personal Google account is a way in their IdP can never see or revoke —\n * exactly what SSO is purchased to prevent.\n *\n * Deliberately NOT gated on `sso.enforced`. That flag exists so we never\n * LOCK OUT an existing sign-in method; it is not a licence to hand out new\n * bypasses meanwhile. Nothing here removes a provider an account already has,\n * so this can never lock anyone out.\n *\n * This is the intent, not the boundary — the boundary is upstream, since a\n * GCIP tenant only accepts providers enabled on that tenant. Both matter: the\n * boundary is remote config that could drift, and a UI that offers a\n * security-regressing action is wrong even when the action would fail.\n */\nexport function canLinkSocialProvider(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return !isSsoGovernedAccount(user)\n}\n\n/**\n * The same question as `isOrgWideMember`, asked of the `users/{uid}/orgs`\n * reverse-index row instead of the member doc (AGL-1032).\n *\n * The console navigates from the index — it is what `useOrgScope` loads —\n * and the index carries a MIRROR of the predicate, not the inputs to it, so\n * this cannot recompute: `role: 'viewer'` on the index means \"viewer\",\n * whether the member reaches every site or one.\n *\n * Reads a missing flag as org-wide, for the same reason `isOrgWideMember`\n * reads a missing `allHosts` that way: rows written before the mirror\n * existed have no flag, and hiding the workspace from a real member is a\n * worse failure than showing org chrome to a collaborator whose reads the\n * rules refuse anyway. Owner/admin are org-wide by role regardless of the\n * mirror, so a stale row can never lock an admin out.\n *\n * Navigation only — never an access decision. AGL-1026 (rules) and the\n * Admin-SDK scope checks are the boundary.\n */\nexport function isOrgWideMembership(\n membership:\n | Pick<UserOrgMembership, 'role' | 'orgWide'>\n | null\n | undefined,\n): boolean {\n if (!membership) return true\n if (membership.role === 'owner' || membership.role === 'admin') return true\n return membership.orgWide !== false\n}\n\n/**\n * The `scopeTokens` projection stamped onto member docs (AGL-1038) so the\n * rules can intersect a caller's reach with a resource's `visibleTo` —\n * rules have no `.map()`, so `hostAccess`'s keys cannot be turned into\n * tokens at evaluation time and have to be denormalized here.\n *\n * Org-wide members get `['org']`; they own the org and read everything in\n * it, scoped or not (the rules short-circuit on them anyway). A scoped\n * collaborator gets `'org'` plus one token per granted host — `'org'`\n * because an org-WIDE resource stays readable by any member, which is\n * today's behavior and not something this project narrows.\n *\n * Not capped at `MAX_SCOPE_HOSTS`: the rules' `hasAny` has no 30-value\n * limit, only the client `array-contains-any` query does, so a member of\n * more than 30 sites is a listing problem for AGL-1044 to chunk, not a\n * reason to under-grant here.\n */\nexport function projectMemberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n if (isOrgWideMember(member)) return [ORG_SCOPE_TOKEN]\n const hostIds = Object.keys(member?.hostAccess ?? {})\n return [ORG_SCOPE_TOKEN, ...hostIds.map(hostScopeToken)]\n}\n\n/**\n * A member's effective read set: the stored `scopeTokens` projection when it\n * is there, recomputed from the membership when it is not.\n *\n * The fallback is the security-relevant half and it was written out by hand\n * in four places (`use-scope-tokens`, `erase-scope`, the media sign route,\n * and by omission in `resolveMediaScope`, which only ever recomputed). Four\n * copies of \"what may this member see\" is the shape that eventually\n * disagrees, and a copy that reads `member.scopeTokens` WITHOUT the\n * `.length` guard silently grants nothing to a member the AGL-1040 backfill\n * has not reached — or, written the other way round, grants everything.\n *\n * Recomputing is the safe fallback rather than a convenience: it produces\n * exactly what `grantHostAccess` would have stamped, so an unstamped member\n * doc behaves as its `hostAccess` says, never as \"no access\" and never as\n * org-wide.\n */\nexport function memberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n const stored = member?.scopeTokens\n return stored?.length ? stored : projectMemberScopeTokens(member)\n}\n\n/**\n * May this member see a resource carrying `visibleTo`? (AGL-1037/1038)\n *\n * The whole client-side/server-side authorization question in one place:\n * org-wide members read everything they own; everyone else needs their read\n * set to intersect the resource's scope. Absent/empty `visibleTo` is\n * org-wide by the same rule the Firestore rules use, so an unbackfilled\n * resource does not vanish.\n *\n * Every Admin-SDK path must call this (or `scopeAllows`, which wraps an\n * already-resolved scope) — the Admin SDK bypasses rules entirely, so this\n * IS the enforcement there, not a second opinion about it.\n *\n * NOT a membership check, and never a substitute for one: a `null` member\n * \"can see\" an org-wide resource here, because the question this answers is\n * \"is this resource in scope for that reach\", not \"is this person in the\n * org\". Resolve membership first and refuse the caller if there is none —\n * conflating the two is exactly how AGL-1026 exposed a whole org.\n */\nexport function memberCanSee(\n member: Partial<AglynOrgMember> | null | undefined,\n visibleTo: readonly string[] | null | undefined,\n): boolean {\n if (isOrgWideMember(member)) return true\n return visibleToTokens(visibleTo ?? undefined, memberScopeTokens(member))\n}\n\n/**\n * The `memberRoles` projection stamped onto host docs so Firestore rules\n * authorize host content with the single host-doc read they already do\n * (docs/MULTI_TENANT_FIRESTORE.md §5). Recomputed by the membership API\n * whenever a member changes; owner/admin appear on every host.\n */\nexport function projectHostMemberRoles(\n members: ReadonlyArray<Partial<AglynOrgMember> & { $id: string }>,\n hostId: HostUid,\n): Record<string, HostAccessRole> {\n const projection: Record<string, HostAccessRole> = {}\n for (const member of members) {\n const role = hostRoleFor(member, hostId)\n if (role) projection[member.$id] = role\n }\n return projection\n}\n"],"names":["generateSubdomain","isBlockedSubdomain","SUBDOMAIN_PATTERN","hostScopeToken","ORG_SCOPE_TOKEN","visibleToTokens","ORG_SLUG_PATTERN","RESERVED_ORG_ONLY","Set","isBlockedOrgSlug","slug","has","toLowerCase","isValidOrgSlug","test","generateOrgSlug","name","ORG_ROLES","ORG_ROLE_WEIGHT","owner","admin","editor","viewer","isOrgRole","value","orgRoleAtLeast","role","minimum","canManageOrg","hostRoleFor","member","hostId","explicit","hostAccess","allHosts","HOST_CONTENT_WRITE_ROLES","HOST_PUBLISH_ROLES","canWriteHost","includes","canPublishHost","hostRoleCanWrite","hostRoleCanPublish","isOrgWideMember","scoping","undefined","Object","keys","length","countManagerSeats","entries","count","entry","collaboratorSeatKey","email","trim","uid","collaboratorSeatKeys","key","add","countCollaboratorSeats","exclude","candidate","emails","delete","size","managerSeatKeys","countManagerSeatsExcluding","CONSOLE_USER_TYPE_LABELS","manager","collaborator","siteMember","CONSOLE_USER_TYPE_HINTS","consoleUserType","isSsoGovernedAccount","user","Boolean","tenantId","canLinkSocialProvider","isOrgWideMembership","membership","orgWide","projectMemberScopeTokens","hostIds","map","memberScopeTokens","stored","scopeTokens","memberCanSee","visibleTo","projectHostMemberRoles","members","projection","$id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAUD,SACEA,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,QACZ,mBAAe;AACtB,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,QACV,oBAAgB;AAEvB,0EAA0E,GAC1E,OAAO,MAAMC,mBAAmBJ,kBAAiB;AAEjD;;;CAGC,GACD,MAAMK,oBAAoB,IAAIC,IAAI;IAAC;IAAS;IAAO;IAAQ;CAAY;AAEvE,OAAO,SAASC,iBAAiBC,IAAY;IAC3C,OAAOH,kBAAkBI,GAAG,CAACD,KAAKE,WAAW,OAAOX,mBAAmBS;AACzE;AAEA,OAAO,SAASG,eAAeH,IAAY;IACzC,OAAOJ,iBAAiBQ,IAAI,CAACJ,SAAS,CAACD,iBAAiBC;AAC1D;AAEA,uEAAuE,GACvE,OAAO,SAASK,gBAAgBC,IAAY;IAC1C,MAAMN,OAAOV,kBAAkBgB;IAC/B,OAAON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C,yBACdnD,MAAkD;;IAElD,IAAIY,gBAAgBZ,SAAS,OAAO;QAAC1B;KAAgB;IACrD,MAAM8E,UAAUrC,OAAOC,IAAI,SAAChB,0BAAAA,OAAQG,UAAU,mBAAI,CAAC;IACnD,OAAO;QAAC7B;WAAoB8E,QAAQC,GAAG,CAAChF;KAAgB;AAC1D;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASiF,kBACdtD,MAAkD;IAElD,MAAMuD,SAASvD,0BAAAA,OAAQwD,WAAW;IAClC,OAAOD,CAAAA,0BAAAA,OAAQtC,MAAM,IAAGsC,SAASJ,yBAAyBnD;AAC5D;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASyD,aACdzD,MAAkD,EAClD0D,SAA+C;IAE/C,IAAI9C,gBAAgBZ,SAAS,OAAO;IACpC,OAAOzB,gBAAgBmF,oBAAAA,YAAa5C,WAAWwC,kBAAkBtD;AACnE;AAEA;;;;;CAKC,GACD,OAAO,SAAS2D,uBACdC,OAAiE,EACjE3D,MAAe;IAEf,MAAM4D,aAA6C,CAAC;IACpD,KAAK,MAAM7D,UAAU4D,QAAS;QAC5B,MAAMhE,OAAOG,YAAYC,QAAQC;QACjC,IAAIL,MAAMiE,UAAU,CAAC7D,OAAO8D,GAAG,CAAC,GAAGlE;IACrC;IACA,OAAOiE;AACT"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/organizations.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 * Organization helpers (AGL-233): slug policy for workspace subdomains\n * (`{slug}.aglyn.com`) and role math shared by the org APIs, the console\n * UI, and the Firestore rules' mental model. See\n * docs/MULTI_TENANT_FIRESTORE.md.\n */\n\nimport type {\n AglynOrgMember,\n HostAccessRole,\n HostUid,\n OrgRole,\n ScopeToken,\n UserOrgMembership,\n} from '../foundation'\nimport {\n consoleLabelUnder,\n generateSubdomain,\n isBlockedSubdomain,\n SUBDOMAIN_PATTERN,\n} from './host-naming'\nimport {\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n visibleToTokens,\n} from './scope-tokens'\n\n/** Same lexical policy as host subdomains: 3–30 lowercase/digits/dashes. */\nexport const ORG_SLUG_PATTERN = SUBDOMAIN_PATTERN\n\n/**\n * Org workspace slugs ride the host reserved/profanity blocklist plus\n * console-specific labels the workspace router must own.\n */\nconst RESERVED_ORG_ONLY = new Set(['staff', 'org', 'orgs', 'workspace'])\n\n/**\n * The label this deployment serves its own console on, when it has one\n * (AGL-3295).\n *\n * `app` and `console` are reserved above for every install. One whose console\n * lives at, say, `studio.example.com` needs `studio` refused as well, or an\n * organization could claim a workspace address the console itself answers.\n * Read from the same two settings the console's host gate reads; with either\n * unset nothing extra is reserved, because nothing extra is shadowed.\n */\nconst CONSOLE_LABEL = consoleLabelUnder(\n process.env.NEXT_PUBLIC_CONSOLE_URL,\n process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN,\n)\n\nexport function isBlockedOrgSlug(slug: string): boolean {\n const normalized = slug.toLowerCase()\n return (\n RESERVED_ORG_ONLY.has(normalized) ||\n normalized === CONSOLE_LABEL ||\n isBlockedSubdomain(slug)\n )\n}\n\nexport function isValidOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug) && !isBlockedOrgSlug(slug)\n}\n\n/** Best-effort slug from an org name; '' when nothing usable remains. */\nexport function generateOrgSlug(name: string): string {\n const slug = generateSubdomain(name)\n return slug && !isBlockedOrgSlug(slug) ? slug : ''\n}\n\nexport const ORG_ROLES: readonly OrgRole[] = [\n 'owner',\n 'admin',\n 'editor',\n 'viewer',\n]\n\nconst ORG_ROLE_WEIGHT: Record<OrgRole, number> = {\n owner: 3,\n admin: 2,\n editor: 1,\n viewer: 0,\n}\n\nexport function isOrgRole(value: unknown): value is OrgRole {\n return typeof value === 'string' && value in ORG_ROLE_WEIGHT\n}\n\nexport function orgRoleAtLeast(\n role: OrgRole | null | undefined,\n minimum: OrgRole,\n): boolean {\n if (!role || !(role in ORG_ROLE_WEIGHT)) return false\n return ORG_ROLE_WEIGHT[role] >= ORG_ROLE_WEIGHT[minimum]\n}\n\n/** Org settings, members, invites, host creation: admin and owner. */\nexport function canManageOrg(role: OrgRole | null | undefined): boolean {\n return orgRoleAtLeast(role, 'admin')\n}\n\n/**\n * The member's effective role on one host, or null for no access.\n * Owner/admin span every host; editor/viewer resolve through `allHosts`\n * (mapped to their org role) or the per-host access map.\n */\nexport function hostRoleFor(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): HostAccessRole | null {\n const role = member?.role\n if (!isOrgRole(role)) return null\n if (role === 'owner' || role === 'admin') return 'admin'\n const explicit = member?.hostAccess?.[hostId]\n if (explicit) return explicit\n return member?.allHosts ? role : null\n}\n\n/**\n * Host roles that may MUTATE content — the axis `canWriteHostContent()` in\n * the security rules asks (AGL-2334).\n *\n * `author` is here and absent from `HOST_PUBLISH_ROLES` below: that single\n * difference IS the \"edit content but not publish\" role. Kept as two named\n * sets rather than two inline comparisons because they are read in three\n * places that must not drift — this module, the ~20 server gates, and the\n * rules — and because a new host role added to the union has to be a\n * deliberate decision on BOTH lists rather than an omission from one.\n */\nexport const HOST_CONTENT_WRITE_ROLES: readonly HostAccessRole[] = [\n 'admin',\n 'editor',\n 'author',\n]\n\n/**\n * Host roles that may make content LIVE. Everything that registers a route,\n * moves a live-version pointer, schedules either of those for later, or\n * flips a collection entry to `published` asks this and not the set above.\n *\n * The list is short and it is the whole product decision: `author` is not on\n * it. If a role is ever added here, the rules' `canPublishHostContent()` and\n * the publish-surface field freezes below it must be updated in the same\n * change — they are the enforcement, this is the server-side echo of it.\n */\nexport const HOST_PUBLISH_ROLES: readonly HostAccessRole[] = ['admin', 'editor']\n\n/**\n * Whether the member may mutate a host's content — admin, editor **or\n * author** on it.\n *\n * An author is a content editor in every respect this predicate covers; what\n * it deliberately does NOT cover is publication. Any caller that is really\n * asking \"may this person make something live\" must call `canPublishHost`\n * instead — this one answering `true` for an author is the point of the role,\n * not a gap in it.\n */\nexport function canWriteHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_CONTENT_WRITE_ROLES.includes(role)\n}\n\n/**\n * Whether the member may PUBLISH on a host — register a route, move a live\n * version pointer, schedule either for later, or publish a collection entry.\n *\n * Strictly narrower than `canWriteHost`: `author` edits and does not publish.\n * This is the server-side echo of the rules, not the enforcement — publishing\n * is a set of client-direct Firestore writes across five document shapes, so\n * `cloud/firebase-firestore.rules` is where it is actually refused. Server\n * routes that schedule or trigger a publish ask this so the console can say\n * no with a message instead of surfacing a bare permission-denied.\n */\nexport function canPublishHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_PUBLISH_ROLES.includes(role)\n}\n\n/**\n * The same question asked of a bare `memberRoles` value rather than a member\n * document — the shape every Admin-SDK route already has in hand after its\n * `hosts/{hostId}` read, so it does not have to re-load the org membership.\n *\n * `String(role)` at the call sites keeps `undefined` out; an unknown value\n * is simply not in the set, which fails CLOSED.\n */\nexport function hostRoleCanWrite(role: unknown): boolean {\n return HOST_CONTENT_WRITE_ROLES.includes(role as HostAccessRole)\n}\n\n/** Publish-axis twin of `hostRoleCanWrite`; `author` is excluded. */\nexport function hostRoleCanPublish(role: unknown): boolean {\n return HOST_PUBLISH_ROLES.includes(role as HostAccessRole)\n}\n\n/**\n * Whether a member's reach is the whole org rather than a list of sites.\n *\n * Owner and admin always are; editor/viewer are only when `allHosts` says\n * so — **or** when the membership predates the flag entirely. A pre-\n * `allHosts` doc carries neither the flag nor a `hostAccess` map, and\n * reading that as \"scoped, with access to nothing\" would lock real members\n * out of their own workspace. A site collaborator ALWAYS has a non-empty\n * `hostAccess` (that is what `grantHostAccess` writes), so the absence of\n * both is the legacy shape, not a scoped one.\n *\n * Single source of truth for `resolveOrgPermissions` (the server gate),\n * `projectMemberScopeTokens` (the rules projection), and the rules'\n * own `isOrgWideMember()` — three copies of this predicate that disagree\n * is a privilege bug, not a style problem (AGL-1026, AGL-1038).\n */\nexport function isOrgWideMember(\n member: Partial<AglynOrgMember> | null | undefined,\n): boolean {\n if (!member) return false\n const role = member.role\n if (role === 'owner' || role === 'admin') return true\n if (member.allHosts === true) return true\n const scoping = member.hostAccess\n return (\n member.allHosts === undefined && !Object.keys(scoping ?? {}).length\n )\n}\n\n/**\n * How many of these roster entries consume a **manager** seat (AGL-1113).\n *\n * `orgs/{orgId}/members` holds BOTH org managers and site-scoped\n * collaborators — adding a collaborator to one site writes an org member doc\n * with `allHosts:false` + `hostAccess`, so a raw `.count()` of the collection\n * billed every collaborator as a manager. Collaborators are metered\n * separately, per host, against `membersPerHost` at\n * `hosts/{hostId}/members` — counting them here charged them twice and\n * tripped the manager gate for orgs nowhere near their manager limit.\n *\n * Reuses `isOrgWideMember` rather than filtering on `allHosts` directly:\n * owner/admin are managers whatever the flag says, and a pre-`allHosts` doc\n * is a manager too. A Firestore `where('allHosts','==',true)` count gets both\n * of those wrong, which is why callers pass entries in and count here.\n *\n * Accepts pending INVITES as well as members — an invite carries the same\n * `role`/`allHosts`/`hostAccess` shape and reserves the seat it will become.\n */\nexport function countManagerSeats(\n entries: ReadonlyArray<Partial<AglynOrgMember> | null | undefined>,\n): number {\n let count = 0\n for (const entry of entries) if (isOrgWideMember(entry)) count += 1\n return count\n}\n\n/**\n * One roster row or pending invite, as the collaborator counter needs to see\n * it (AGL-2068). Deliberately structural rather than `Partial<AglynOrgMember>`\n * — an INVITE is not a member document, it is keyed by email and has no uid,\n * and the whole point of this counter is that the two populations must be\n * counted together or the cap is enforced against a fraction of itself.\n */\nexport interface CollaboratorSeatEntry {\n /** Member documents are keyed by uid; invites have none. */\n uid?: string | null\n email?: string | null\n role?: unknown\n allHosts?: boolean\n hostAccess?: Record<string, unknown> | null\n}\n\n/**\n * The identity key one entry occupies, or `''` when it identifies nobody.\n *\n * EMAIL FIRST, uid second, and that order is the join (AGL-2068). A person\n * admitted to a site is one seat whether they arrive as an accepted member or\n * as a still-pending invite, and those two rows live in different collections\n * keyed different ways — `orgs/{id}/members/{uid}` and\n * `orgs/{id}/invites/{inviteId}` — with the address as the only field both\n * carry. Counting by uid would count the invite and the membership it becomes\n * as two seats; counting only invites would miss every member.\n *\n * Legacy roster rows written before `email` was mirrored fall back to the uid,\n * which cannot collide with an address (the `uid:` prefix is not a legal\n * local-part/domain pair) and so is safe to mix into the same set.\n */\nfunction collaboratorSeatKey(entry: CollaboratorSeatEntry): string {\n const email =\n typeof entry.email === 'string' ? entry.email.trim().toLowerCase() : ''\n if (email) return email\n const uid = typeof entry.uid === 'string' ? entry.uid.trim() : ''\n return uid ? `uid:${uid}` : ''\n}\n\n/**\n * Every principal consuming a COLLABORATOR seat on one host (AGL-2068).\n *\n * ## Why this exists at all\n *\n * `membersPerHost` was enforced on one of the four doors that admit a site\n * collaborator, and that one door counted `hosts/{hostId}/members` — a\n * DISPLAY roster only `/api/hosts/members` writes. The other three\n * (`/api/orgs/invites` create, `/api/orgs/invites` accept, and the\n * `hostAccess` branch of `/api/orgs/members`) land in `orgs/{id}/members` and\n * the `hosts/{id}.memberRoles` projection, and were invisible to it. So the\n * cap was both skipped on three paths and under-counted on the fourth, and a\n * free org — `membersPerHost: 1` — could take on unlimited collaborators,\n * each with full site access, on a plan that is never invoiced.\n *\n * verbatim: **\"We need to make sure the free/hobby tier\n * does hard cap so it always actually stays free.\"**\n *\n * ## What counts\n *\n * A SCOPED grant on `hostId`, and nothing else. An org-wide member\n * (owner/admin, or `allHosts`) reaches every host but consumes a MANAGER\n * seat — `countManagerSeats` is that side, and charging them here would bill\n * one person twice and trip a cap they are not on. This is the same split\n * AGL-1113 drew; it is now drawn from one place instead of three.\n *\n * Pending invites count, for the reason the manager gate counts them: an\n * invite reserves the seat it will become, and a cap that only bites on\n * acceptance can be walked past by mailing out N invites first.\n */\nexport function collaboratorSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n): Set<string> {\n const keys = new Set<string>()\n if (!hostId) return keys\n for (const entry of entries) {\n if (!entry) continue\n // Managers are the other counter's population, whatever host map they\n // happen to carry — a promoted collaborator keeps their old `hostAccess`.\n if (isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n if (!entry.hostAccess?.[hostId]) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many collaborator seats on `hostId` are spoken for by someone OTHER\n * than `exclude` (AGL-2068).\n *\n * `exclude` is the principal the caller is about to admit, and dropping them\n * is what makes this composable with `checkSeatQuota(…, used)`, whose\n * contract is \"usage BEFORE the resource being created\". Without it the\n * accept path refuses its own invite: at the moment acceptance is decided the\n * invitee holds a pending invite AND is about to hold a membership, so they\n * would be counted once or twice against a cap they are the subject of.\n *\n * Both identities are dropped, not whichever one is present. A person can be\n * on the roster under a uid with no mirrored email and hold an invite under\n * that address, and the seat is still one seat.\n *\n * ## `emails`, not `email` — an account holds several (AGL-2486)\n *\n * Since an invitation may be accepted at any CONFIRMED address on the account,\n * the pending invite the accepter is about to consume can be keyed by an\n * address that is not their primary. `exclude.email` alone is the primary, so\n * that invite survived the exclusion and the person was counted against a cap\n * they are the subject of — the exact double-count the paragraph above says\n * this function exists to prevent, re-opened by widening the accept match.\n *\n * It fails CLOSED (a spurious \"out of seats\" refusal, never a free seat), and\n * only for an org sitting exactly on its cap, which is why it survived review.\n *\n * `emails` takes every address PROVEN to belong to the principal being\n * admitted. Passing an address that is not theirs would hand out a free seat,\n * so callers must pass confirmed addresses for that uid and nothing else.\n */\nexport function countCollaboratorSeats(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = collaboratorSeatKeys(entries, hostId)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * Every principal consuming a MANAGER seat, as identities rather than rows.\n *\n * The org-wide half of `collaboratorSeatKeys`, drawn from the same entries and\n * split on the same predicate, so the two counters partition one roster\n * instead of overlapping on it.\n *\n * Deduplicating by identity is the difference from {@link countManagerSeats},\n * and it is what makes this composable with an `exclude`: a person holding a\n * pending invite AND the membership it became is one seat, and the row-wise\n * counter reports two because it is handed the two collections separately and\n * sums them.\n */\nexport function managerSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n): Set<string> {\n const keys = new Set<string>()\n for (const entry of entries) {\n if (!entry) continue\n if (!isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many manager seats are spoken for by someone OTHER than `exclude`.\n *\n * The manager twin of {@link countCollaboratorSeats}, and it exists for the\n * same reason that one takes an `exclude`: `checkSeatQuota`'s contract is\n * \"usage BEFORE the resource being created\", and on the invite-accept path the\n * accepter holds a pending invite and is about to hold a membership at the\n * same instant. Counted plainly they are charged once or twice for a seat they\n * are the subject of, and an org on its last seat refuses its own invitation.\n *\n * Both identities are dropped, and `emails` carries the further addresses\n * proven to belong to that account — an invitation may be accepted at any\n * confirmed address, so the invite being consumed need not be keyed by the\n * primary one. Passing an address that is not theirs would hand out a free\n * seat, so callers must pass confirmed addresses for that uid and nothing\n * else.\n *\n * Kept SEPARATE from {@link countManagerSeats} rather than replacing it: that\n * one is row-wise and is what the billing and console surfaces count with, and\n * quietly making it identity-wise would change every one of those totals.\n */\nexport function countManagerSeatsExcluding(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = managerSeatKeys(entries)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * What KIND of user a console row represents (AGL-1114) — the distinction\n * that decides which seat they consume, and the one the Team table could not\n * express because a manager and a collaborator differ only by fields the\n * table never showed.\n *\n * Deliberately NOT the same axis as `role`. A `role: 'editor'` is a manager\n * when their reach is the whole org and a collaborator when it is two sites;\n * reading the role alone is the mistake that let a collaborator look like\n * team staff (see the org-leak and role-gate work).\n *\n * `siteMember` is the third kind and never appears in `orgs/{id}/members` at\n * all: it is an end-user account on a PUBLISHED site (`siteMembers`), not a\n * console user. It has no Firebase Auth record of any kind — a site member is\n * a Firestore document under `hosts/{hostId}/siteMembers` with its own scrypt\n * hash and its own session cookie — so no surface that lists AUTH accounts,\n * the staff user directory included, can contain one. The label is here so the\n * vocabulary is complete, for a surface that lists site accounts and needs a\n * word for them. Free and uncounted on every plan (AGL-889).\n */\nexport type ConsoleUserType = 'manager' | 'collaborator' | 'siteMember'\n\nexport const CONSOLE_USER_TYPE_LABELS: Record<ConsoleUserType, string> = {\n manager: 'Team manager',\n collaborator: 'Site collaborator',\n siteMember: 'Site member',\n}\n\n/** One line on what each kind is and what it costs — tooltip/legend copy. */\nexport const CONSOLE_USER_TYPE_HINTS: Record<ConsoleUserType, string> = {\n manager:\n 'Reaches the whole organization. Uses one of your team (manager) seats.',\n collaborator:\n 'Scoped to specific sites. Uses a collaborator seat on each site they ' +\n 'can reach, not a team seat.',\n siteMember:\n 'An end-user account on a published site, not a console user. Free and ' +\n 'unlimited on every plan.',\n}\n\n/**\n * Classify an `orgs/{orgId}/members` entry (or a pending invite, same shape).\n * Never returns `siteMember` — nothing in that collection is one; the value\n * exists for surfaces that list published-site accounts and must label them —\n * never for one that lists both, since the two populations do not share an\n * identity system.\n */\nexport function consoleUserType(\n member: Partial<AglynOrgMember> | null | undefined,\n): Exclude<ConsoleUserType, 'siteMember'> {\n return isOrgWideMember(member) ? 'manager' : 'collaborator'\n}\n\n/**\n * Whether an account is governed by enterprise SSO (AGL-1128) — it lives in\n * an org's GCIP tenant pool rather than the project pool, so its identity is\n * owned by the customer's IdP.\n *\n * `tenantId` is the whole signal: Firebase sets it on the user whenever the\n * account belongs to a tenant, and only SSO accounts do.\n */\nexport function isSsoGovernedAccount(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return Boolean(user?.tenantId)\n}\n\n/**\n * Whether the account may connect an additional consumer sign-in provider.\n *\n * **No, for any SSO-governed account.** The customer's IdP is the single gate\n * they bought: they revoke there, enforce MFA there, offboard there. A linked\n * personal Google account is a way in their IdP can never see or revoke —\n * exactly what SSO is purchased to prevent.\n *\n * Deliberately NOT gated on `sso.enforced`. That flag exists so we never\n * LOCK OUT an existing sign-in method; it is not a licence to hand out new\n * bypasses meanwhile. Nothing here removes a provider an account already has,\n * so this can never lock anyone out.\n *\n * This is the intent, not the boundary — the boundary is upstream, since a\n * GCIP tenant only accepts providers enabled on that tenant. Both matter: the\n * boundary is remote config that could drift, and a UI that offers a\n * security-regressing action is wrong even when the action would fail.\n */\nexport function canLinkSocialProvider(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return !isSsoGovernedAccount(user)\n}\n\n/**\n * The same question as `isOrgWideMember`, asked of the `users/{uid}/orgs`\n * reverse-index row instead of the member doc (AGL-1032).\n *\n * The console navigates from the index — it is what `useOrgScope` loads —\n * and the index carries a MIRROR of the predicate, not the inputs to it, so\n * this cannot recompute: `role: 'viewer'` on the index means \"viewer\",\n * whether the member reaches every site or one.\n *\n * Reads a missing flag as org-wide, for the same reason `isOrgWideMember`\n * reads a missing `allHosts` that way: rows written before the mirror\n * existed have no flag, and hiding the workspace from a real member is a\n * worse failure than showing org chrome to a collaborator whose reads the\n * rules refuse anyway. Owner/admin are org-wide by role regardless of the\n * mirror, so a stale row can never lock an admin out.\n *\n * Navigation only — never an access decision. AGL-1026 (rules) and the\n * Admin-SDK scope checks are the boundary.\n */\nexport function isOrgWideMembership(\n membership:\n | Pick<UserOrgMembership, 'role' | 'orgWide'>\n | null\n | undefined,\n): boolean {\n if (!membership) return true\n if (membership.role === 'owner' || membership.role === 'admin') return true\n return membership.orgWide !== false\n}\n\n/**\n * The `scopeTokens` projection stamped onto member docs (AGL-1038) so the\n * rules can intersect a caller's reach with a resource's `visibleTo` —\n * rules have no `.map()`, so `hostAccess`'s keys cannot be turned into\n * tokens at evaluation time and have to be denormalized here.\n *\n * Org-wide members get `['org']`; they own the org and read everything in\n * it, scoped or not (the rules short-circuit on them anyway). A scoped\n * collaborator gets `'org'` plus one token per granted host — `'org'`\n * because an org-WIDE resource stays readable by any member, which is\n * today's behavior and not something this project narrows.\n *\n * Not capped at `MAX_SCOPE_HOSTS`: the rules' `hasAny` has no 30-value\n * limit, only the client `array-contains-any` query does, so a member of\n * more than 30 sites is a listing problem for AGL-1044 to chunk, not a\n * reason to under-grant here.\n */\nexport function projectMemberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n if (isOrgWideMember(member)) return [ORG_SCOPE_TOKEN]\n const hostIds = Object.keys(member?.hostAccess ?? {})\n return [ORG_SCOPE_TOKEN, ...hostIds.map(hostScopeToken)]\n}\n\n/**\n * A member's effective read set: the stored `scopeTokens` projection when it\n * is there, recomputed from the membership when it is not.\n *\n * The fallback is the security-relevant half and it was written out by hand\n * in four places (`use-scope-tokens`, `erase-scope`, the media sign route,\n * and by omission in `resolveMediaScope`, which only ever recomputed). Four\n * copies of \"what may this member see\" is the shape that eventually\n * disagrees, and a copy that reads `member.scopeTokens` WITHOUT the\n * `.length` guard silently grants nothing to a member the AGL-1040 backfill\n * has not reached — or, written the other way round, grants everything.\n *\n * Recomputing is the safe fallback rather than a convenience: it produces\n * exactly what `grantHostAccess` would have stamped, so an unstamped member\n * doc behaves as its `hostAccess` says, never as \"no access\" and never as\n * org-wide.\n */\nexport function memberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n const stored = member?.scopeTokens\n return stored?.length ? stored : projectMemberScopeTokens(member)\n}\n\n/**\n * May this member see a resource carrying `visibleTo`? (AGL-1037/1038)\n *\n * The whole client-side/server-side authorization question in one place:\n * org-wide members read everything they own; everyone else needs their read\n * set to intersect the resource's scope. Absent/empty `visibleTo` is\n * org-wide by the same rule the Firestore rules use, so an unbackfilled\n * resource does not vanish.\n *\n * Every Admin-SDK path must call this (or `scopeAllows`, which wraps an\n * already-resolved scope) — the Admin SDK bypasses rules entirely, so this\n * IS the enforcement there, not a second opinion about it.\n *\n * NOT a membership check, and never a substitute for one: a `null` member\n * \"can see\" an org-wide resource here, because the question this answers is\n * \"is this resource in scope for that reach\", not \"is this person in the\n * org\". Resolve membership first and refuse the caller if there is none —\n * conflating the two is exactly how AGL-1026 exposed a whole org.\n */\nexport function memberCanSee(\n member: Partial<AglynOrgMember> | null | undefined,\n visibleTo: readonly string[] | null | undefined,\n): boolean {\n if (isOrgWideMember(member)) return true\n return visibleToTokens(visibleTo ?? undefined, memberScopeTokens(member))\n}\n\n/**\n * The `memberRoles` projection stamped onto host docs so Firestore rules\n * authorize host content with the single host-doc read they already do\n * (docs/MULTI_TENANT_FIRESTORE.md §5). Recomputed by the membership API\n * whenever a member changes; owner/admin appear on every host.\n */\nexport function projectHostMemberRoles(\n members: ReadonlyArray<Partial<AglynOrgMember> & { $id: string }>,\n hostId: HostUid,\n): Record<string, HostAccessRole> {\n const projection: Record<string, HostAccessRole> = {}\n for (const member of members) {\n const role = hostRoleFor(member, hostId)\n if (role) projection[member.$id] = role\n }\n return projection\n}\n"],"names":["consoleLabelUnder","generateSubdomain","isBlockedSubdomain","SUBDOMAIN_PATTERN","hostScopeToken","ORG_SCOPE_TOKEN","visibleToTokens","ORG_SLUG_PATTERN","RESERVED_ORG_ONLY","Set","CONSOLE_LABEL","process","env","NEXT_PUBLIC_CONSOLE_URL","NEXT_PUBLIC_WORKSPACE_DOMAIN","isBlockedOrgSlug","slug","normalized","toLowerCase","has","isValidOrgSlug","test","generateOrgSlug","name","ORG_ROLES","ORG_ROLE_WEIGHT","owner","admin","editor","viewer","isOrgRole","value","orgRoleAtLeast","role","minimum","canManageOrg","hostRoleFor","member","hostId","explicit","hostAccess","allHosts","HOST_CONTENT_WRITE_ROLES","HOST_PUBLISH_ROLES","canWriteHost","includes","canPublishHost","hostRoleCanWrite","hostRoleCanPublish","isOrgWideMember","scoping","undefined","Object","keys","length","countManagerSeats","entries","count","entry","collaboratorSeatKey","email","trim","uid","collaboratorSeatKeys","key","add","countCollaboratorSeats","exclude","candidate","emails","delete","size","managerSeatKeys","countManagerSeatsExcluding","CONSOLE_USER_TYPE_LABELS","manager","collaborator","siteMember","CONSOLE_USER_TYPE_HINTS","consoleUserType","isSsoGovernedAccount","user","Boolean","tenantId","canLinkSocialProvider","isOrgWideMembership","membership","orgWide","projectMemberScopeTokens","hostIds","map","memberScopeTokens","stored","scopeTokens","memberCanSee","visibleTo","projectHostMemberRoles","members","projection","$id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAUD,SACEA,iBAAiB,EACjBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,QACZ,mBAAe;AACtB,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,QACV,oBAAgB;AAEvB,0EAA0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