@aglyn/tenant-data-admin 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,11 +7,11 @@ of `@aglyn/tenant-runtime`, of Aglyn's server apps, and of the server half of
7
7
  the `@aglyn/plugins-*` packages. Install it directly only if you are writing
8
8
  server code against an Aglyn deployment's Firestore.
9
9
 
10
- > Beta. Published from the Aglyn monorepo under the `beta` dist-tag; APIs can change between beta releases.
10
+ > Published to npm from the Aglyn monorepo. Versions follow [semantic versioning](https://semver.org).
11
11
 
12
12
  ## Install
13
13
 
14
- npm install @aglyn/tenant-data-admin@beta
14
+ npm install @aglyn/tenant-data-admin
15
15
 
16
16
  Peer dependencies:
17
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.5.0",
29
- "@aglyn/shared-util-email": "1.5.0",
30
- "@aglyn/shared-util-fbserver": "1.5.0",
31
- "@aglyn/shared-util-first-touch": "1.5.0",
32
- "@aglyn/shared-util-http": "1.5.0",
33
- "@aglyn/shared-util-tools": "1.5.0",
28
+ "@aglyn/aglyn": "1.7.0",
29
+ "@aglyn/shared-util-email": "1.7.0",
30
+ "@aglyn/shared-util-fbserver": "1.7.0",
31
+ "@aglyn/shared-util-first-touch": "1.7.0",
32
+ "@aglyn/shared-util-http": "1.7.0",
33
+ "@aglyn/shared-util-tools": "1.7.0",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -43,6 +43,11 @@ export declare function upsertSubdomainRedirect(options: {
43
43
  * Registers the twin as a redirect to the primary. Best-effort for the same
44
44
  * reason the subdomain redirect is: the primary serves either way, and a twin
45
45
  * that did not land is recorded as `cnameTwinPending` for the completer.
46
+ *
47
+ * Permanent, unlike the subdomain's (AGL-4134). That one has to stay revocable
48
+ * because disconnecting a domain hands the subdomain back. A twin is the same
49
+ * domain at a second spelling, and a temporary redirect tells search engines
50
+ * to keep both.
46
51
  */
47
52
  export declare function upsertCustomDomainTwin(options: {
48
53
  twin: string;
@@ -51,9 +51,15 @@ import { attachProjectDomain } from "./workspace-domains.js";
51
51
  * Registers the twin as a redirect to the primary. Best-effort for the same
52
52
  * reason the subdomain redirect is: the primary serves either way, and a twin
53
53
  * that did not land is recorded as `cnameTwinPending` for the completer.
54
+ *
55
+ * Permanent, unlike the subdomain's (AGL-4134). That one has to stay revocable
56
+ * because disconnecting a domain hands the subdomain back. A twin is the same
57
+ * domain at a second spelling, and a temporary redirect tells search engines
58
+ * to keep both.
54
59
  */ export async function upsertCustomDomainTwin(options) {
55
60
  const result = await attachProjectDomain(options.twin, {
56
- redirectTo: options.target
61
+ redirectTo: options.target,
62
+ permanent: true
57
63
  }, 'tenant');
58
64
  return result.outcome === 'attached' || result.outcome === 'already-exists';
59
65
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/custom-domain-redirects.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 { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport { attachProjectDomain } from './workspace-domains'\n\n/*\n * The two redirects a connected custom domain registers on the tenant\n * deployment (AGL-3961). Kept apart from `host-custom-domain.ts`, which owns\n * the claim, so the completer cron and its spec reach them without the claim's\n * Firestore and activity imports.\n */\n\n/**\n * Registers `{subdomain}.aglyn.app` on the tenant deployment as a per-domain\n * REDIRECT to the custom domain (AGL-1273). The app-level canonical redirect\n * in `loadPageData` is baked into an ISR entry keyed on pathname, so it\n * structurally cannot carry the query string — a campaign that pointed at the\n * platform subdomain lost its `utm_*` on the hop. The edge redirect preserves\n * path AND query at zero runtime cost, and the app-level redirect stays as the\n * fallback wherever the provider cannot express a redirect at all.\n *\n * A redirect is a REGISTRATION, not a special case: create the name carrying\n * the redirect, or point an existing entry at the new target. Both halves live\n * in the provider, so a name already on the deployment gets its redirect\n * applied rather than being read as \"already done\" — an entry left serving\n * instead of forwarding is a second live copy of the site on a name that was\n * supposed to hand visitors to the custom domain.\n *\n * Best-effort BY DESIGN: the custom domain is already attached by the time\n * this runs, and a redirect-registration failure must not unwind that. A\n * failure sets `subdomainRedirectPending` so the gap is visible and the\n * completer cron (`/api/admin/finish-domain-attachments`) can close it.\n */\nexport async function upsertSubdomainRedirect(options: {\n subdomain: string\n target: string\n}): Promise<boolean> {\n const { subdomain, target } = options\n const result = await attachProjectDomain(\n `${subdomain}.${TENANT_APEX}`,\n { redirectTo: target },\n 'tenant',\n )\n return result.outcome === 'attached' || result.outcome === 'already-exists'\n}\n\n/**\n * Registers the twin as a redirect to the primary. Best-effort for the same\n * reason the subdomain redirect is: the primary serves either way, and a twin\n * that did not land is recorded as `cnameTwinPending` for the completer.\n */\nexport async function upsertCustomDomainTwin(options: {\n twin: string\n target: string\n}): Promise<boolean> {\n const result = await attachProjectDomain(\n options.twin,\n { redirectTo: options.target },\n 'tenant',\n )\n return result.outcome === 'attached' || result.outcome === 'already-exists'\n}\n\n"],"names":["TENANT_APEX","attachProjectDomain","upsertSubdomainRedirect","options","subdomain","target","result","redirectTo","outcome","upsertCustomDomainTwin","twin"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,WAAW,QAAQ,qCAAoC;AAChE,SAASC,mBAAmB,QAAQ,yBAAqB;AAEzD;;;;;CAKC,GAED;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,eAAeC,wBAAwBC,OAG7C;IACC,MAAM,EAAEC,SAAS,EAAEC,MAAM,EAAE,GAAGF;IAC9B,MAAMG,SAAS,MAAML,oBACnB,GAAGG,UAAU,CAAC,EAAEJ,aAAa,EAC7B;QAAEO,YAAYF;IAAO,GACrB;IAEF,OAAOC,OAAOE,OAAO,KAAK,cAAcF,OAAOE,OAAO,KAAK;AAC7D;AAEA;;;;CAIC,GACD,OAAO,eAAeC,uBAAuBN,OAG5C;IACC,MAAMG,SAAS,MAAML,oBACnBE,QAAQO,IAAI,EACZ;QAAEH,YAAYJ,QAAQE,MAAM;IAAC,GAC7B;IAEF,OAAOC,OAAOE,OAAO,KAAK,cAAcF,OAAOE,OAAO,KAAK;AAC7D"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/custom-domain-redirects.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 { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport { attachProjectDomain } from './workspace-domains'\n\n/*\n * The two redirects a connected custom domain registers on the tenant\n * deployment (AGL-3961). Kept apart from `host-custom-domain.ts`, which owns\n * the claim, so the completer cron and its spec reach them without the claim's\n * Firestore and activity imports.\n */\n\n/**\n * Registers `{subdomain}.aglyn.app` on the tenant deployment as a per-domain\n * REDIRECT to the custom domain (AGL-1273). The app-level canonical redirect\n * in `loadPageData` is baked into an ISR entry keyed on pathname, so it\n * structurally cannot carry the query string — a campaign that pointed at the\n * platform subdomain lost its `utm_*` on the hop. The edge redirect preserves\n * path AND query at zero runtime cost, and the app-level redirect stays as the\n * fallback wherever the provider cannot express a redirect at all.\n *\n * A redirect is a REGISTRATION, not a special case: create the name carrying\n * the redirect, or point an existing entry at the new target. Both halves live\n * in the provider, so a name already on the deployment gets its redirect\n * applied rather than being read as \"already done\" — an entry left serving\n * instead of forwarding is a second live copy of the site on a name that was\n * supposed to hand visitors to the custom domain.\n *\n * Best-effort BY DESIGN: the custom domain is already attached by the time\n * this runs, and a redirect-registration failure must not unwind that. A\n * failure sets `subdomainRedirectPending` so the gap is visible and the\n * completer cron (`/api/admin/finish-domain-attachments`) can close it.\n */\nexport async function upsertSubdomainRedirect(options: {\n subdomain: string\n target: string\n}): Promise<boolean> {\n const { subdomain, target } = options\n const result = await attachProjectDomain(\n `${subdomain}.${TENANT_APEX}`,\n { redirectTo: target },\n 'tenant',\n )\n return result.outcome === 'attached' || result.outcome === 'already-exists'\n}\n\n/**\n * Registers the twin as a redirect to the primary. Best-effort for the same\n * reason the subdomain redirect is: the primary serves either way, and a twin\n * that did not land is recorded as `cnameTwinPending` for the completer.\n *\n * Permanent, unlike the subdomain's (AGL-4134). That one has to stay revocable\n * because disconnecting a domain hands the subdomain back. A twin is the same\n * domain at a second spelling, and a temporary redirect tells search engines\n * to keep both.\n */\nexport async function upsertCustomDomainTwin(options: {\n twin: string\n target: string\n}): Promise<boolean> {\n const result = await attachProjectDomain(\n options.twin,\n { redirectTo: options.target, permanent: true },\n 'tenant',\n )\n return result.outcome === 'attached' || result.outcome === 'already-exists'\n}\n\n"],"names":["TENANT_APEX","attachProjectDomain","upsertSubdomainRedirect","options","subdomain","target","result","redirectTo","outcome","upsertCustomDomainTwin","twin","permanent"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,WAAW,QAAQ,qCAAoC;AAChE,SAASC,mBAAmB,QAAQ,yBAAqB;AAEzD;;;;;CAKC,GAED;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,eAAeC,wBAAwBC,OAG7C;IACC,MAAM,EAAEC,SAAS,EAAEC,MAAM,EAAE,GAAGF;IAC9B,MAAMG,SAAS,MAAML,oBACnB,GAAGG,UAAU,CAAC,EAAEJ,aAAa,EAC7B;QAAEO,YAAYF;IAAO,GACrB;IAEF,OAAOC,OAAOE,OAAO,KAAK,cAAcF,OAAOE,OAAO,KAAK;AAC7D;AAEA;;;;;;;;;CASC,GACD,OAAO,eAAeC,uBAAuBN,OAG5C;IACC,MAAMG,SAAS,MAAML,oBACnBE,QAAQO,IAAI,EACZ;QAAEH,YAAYJ,QAAQE,MAAM;QAAEM,WAAW;IAAK,GAC9C;IAEF,OAAOL,OAAOE,OAAO,KAAK,cAAcF,OAAOE,OAAO,KAAK;AAC7D"}
@@ -30,6 +30,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
30
30
  * the same token is the drift this file exists to prevent.
31
31
  */ import { abortedDetail, domainDeadline, domainStatus, normalizeHost, redirectHostname } from "./domain-provider.js";
32
32
  /** Mirrors the app-level canonical redirect: revocable, method-preserving. */ const REDIRECT_STATUS_CODE = 307;
33
+ /** For a `permanent` redirect: search engines keep both names on a 307. */ const PERMANENT_REDIRECT_STATUS_CODE = 308;
33
34
  function settingsFor(scope) {
34
35
  const token = process.env.VERCEL_TOKEN;
35
36
  const projectId = scope === 'tenant' ? process.env.VERCEL_TENANT_PROJECT_ID : process.env.VERCEL_CONSOLE_PROJECT_ID;
@@ -77,10 +78,11 @@ function authHeaders(settings) {
77
78
  detail: 'invalid-redirect'
78
79
  };
79
80
  }
81
+ const redirectStatusCode = options.permanent ? PERMANENT_REDIRECT_STATUS_CODE : REDIRECT_STATUS_CODE;
80
82
  const body = redirect ? {
81
83
  name: domain,
82
84
  redirect,
83
- redirectStatusCode: REDIRECT_STATUS_CODE
85
+ redirectStatusCode
84
86
  } : {
85
87
  name: domain
86
88
  };
@@ -104,7 +106,9 @@ function authHeaders(settings) {
104
106
  if (code === 'domain_already_in_use' || response.status === 409) {
105
107
  // An entry that already exists still has to CARRY the redirect, or the
106
108
  // twin quietly serves the console instead of forwarding to the primary.
107
- if (redirect) return patchRedirect(settings, domain, redirect);
109
+ if (redirect) {
110
+ return patchRedirect(settings, domain, redirect, redirectStatusCode);
111
+ }
108
112
  return {
109
113
  outcome: 'already-exists',
110
114
  domain
@@ -125,7 +129,7 @@ function authHeaders(settings) {
125
129
  };
126
130
  }
127
131
  }
128
- /** Point an already-attached name at `redirect`. Same never-throws contract. */ async function patchRedirect(settings, domain, redirect) {
132
+ /** Point an already-attached name at `redirect`. Same never-throws contract. */ async function patchRedirect(settings, domain, redirect, redirectStatusCode) {
129
133
  try {
130
134
  const response = await fetch(`https://api.vercel.com/v9/projects/${settings.projectId}/domains/${encodeURIComponent(domain)}${query(settings.teamId)}`, {
131
135
  method: 'PATCH',
@@ -134,7 +138,7 @@ function authHeaders(settings) {
134
138
  }),
135
139
  body: JSON.stringify({
136
140
  redirect,
137
- redirectStatusCode: REDIRECT_STATUS_CODE
141
+ redirectStatusCode
138
142
  }),
139
143
  signal: domainDeadline()
140
144
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/domain-provider-vercel.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 * The Vercel driver — how Aglyn's own hosting registers a name.\n *\n * One implementation of the call, one deadline, one never-throws contract. It\n * was five copies before this file existed: `workspace-domains.ts`, three\n * console routes and `subdomain-redirect.ts` each held their own `fetch` to\n * `api.vercel.com`, which is how two copies of a constant drift apart — the\n * bug AGL-1135 was, one layer down.\n *\n * ## The two projects\n *\n * The console and the tenant runtime are separate Vercel projects, so the\n * scope picks the id. One token and one team serve both: a second variable for\n * the same token is the drift this file exists to prevent.\n */\n\nimport {\n abortedDetail,\n domainDeadline,\n domainStatus,\n normalizeHost,\n redirectHostname,\n type DomainAttachOptions,\n type DomainProvider,\n type DomainResult,\n type DomainScope,\n type ProjectDomainStatus,\n} from './domain-provider'\n\n/** Mirrors the app-level canonical redirect: revocable, method-preserving. */\nconst REDIRECT_STATUS_CODE = 307\n\ninterface VercelSettings {\n token: string\n projectId: string\n teamId?: string\n}\n\nfunction settingsFor(scope: DomainScope): VercelSettings | null {\n const token = process.env.VERCEL_TOKEN\n const projectId =\n scope === 'tenant'\n ? process.env.VERCEL_TENANT_PROJECT_ID\n : process.env.VERCEL_CONSOLE_PROJECT_ID\n if (!token || !projectId) return null\n return { token, projectId, teamId: process.env.VERCEL_TEAM_ID }\n}\n\nfunction query(teamId?: string): string {\n return teamId ? `?teamId=${encodeURIComponent(teamId)}` : ''\n}\n\nfunction authHeaders(settings: VercelSettings): Record<string, string> {\n return { Authorization: `Bearer ${settings.token}` }\n}\n\n/**\n * Attach one fully-qualified name to the scope's project.\n *\n * Idempotent: Vercel answers `domain_already_in_use` when the name is already\n * on the project, which is success for our purposes — the reconcile script and\n * the create path can both run without coordinating.\n *\n * ⚠️ Tolerating `domain_already_in_use` is only safe while **every** name this\n * is asked to attach is also claimed in Firestore. Without that, a second org\n * attaches a name someone else already holds, reads `already-exists` as\n * success, and gets a console that looks healthy while its visitors are served\n * — or redirected — somewhere else. That is the AGL-743 shape, and\n * `console-domains.ts` is where the claim is kept in step.\n */\nasync function attach(\n scope: DomainScope,\n name: string,\n options: DomainAttachOptions = {},\n): Promise<DomainResult> {\n const domain = normalizeHost(name)\n const settings = settingsFor(scope)\n if (!settings || !domain) return { outcome: 'skipped', domain }\n\n const redirect = options.redirectTo\n ? redirectHostname(options.redirectTo)\n : null\n if (options.redirectTo && !redirect) {\n console.error('[domain-provider:vercel] refusing a non-hostname redirect', options.redirectTo)\n return { outcome: 'failed', domain, detail: 'invalid-redirect' }\n }\n const body = redirect\n ? { name: domain, redirect, redirectStatusCode: REDIRECT_STATUS_CODE }\n : { name: domain }\n\n try {\n const response = await fetch(\n `https://api.vercel.com/v10/projects/${settings.projectId}/domains${query(settings.teamId)}`,\n {\n method: 'POST',\n headers: { ...authHeaders(settings), 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: domainDeadline(),\n },\n )\n if (response.ok) return { outcome: 'attached', domain }\n const payload = await response.json().catch(() => null)\n const code = String(payload?.error?.code ?? '')\n if (code === 'domain_already_in_use' || response.status === 409) {\n // An entry that already exists still has to CARRY the redirect, or the\n // twin quietly serves the console instead of forwarding to the primary.\n if (redirect) return patchRedirect(settings, domain, redirect)\n return { outcome: 'already-exists', domain }\n }\n console.error('[domain-provider:vercel] attach failed', domain, code)\n return { outcome: 'failed', domain, detail: code || String(response.status) }\n } catch (error) {\n console.error('[domain-provider:vercel] attach threw', domain, error)\n return { outcome: 'failed', domain, detail: abortedDetail(error) }\n }\n}\n\n/** Point an already-attached name at `redirect`. Same never-throws contract. */\nasync function patchRedirect(\n settings: VercelSettings,\n domain: string,\n redirect: string,\n): Promise<DomainResult> {\n try {\n const response = await fetch(\n `https://api.vercel.com/v9/projects/${settings.projectId}/domains/${encodeURIComponent(domain)}${query(settings.teamId)}`,\n {\n method: 'PATCH',\n headers: { ...authHeaders(settings), 'Content-Type': 'application/json' },\n body: JSON.stringify({\n redirect,\n redirectStatusCode: REDIRECT_STATUS_CODE,\n }),\n signal: domainDeadline(),\n },\n )\n if (response.ok) return { outcome: 'already-exists', domain }\n console.error('[domain-provider:vercel] redirect patch failed', domain, response.status)\n return { outcome: 'failed', domain, detail: String(response.status) }\n } catch (error) {\n console.error('[domain-provider:vercel] redirect patch threw', domain, error)\n return { outcome: 'failed', domain, detail: abortedDetail(error) }\n }\n}\n\nasync function detach(\n scope: DomainScope,\n name: string,\n): Promise<DomainResult> {\n const domain = normalizeHost(name)\n const settings = settingsFor(scope)\n if (!settings || !domain) return { outcome: 'skipped', domain }\n try {\n const response = await fetch(\n `https://api.vercel.com/v9/projects/${settings.projectId}/domains/${encodeURIComponent(domain)}${query(settings.teamId)}`,\n {\n method: 'DELETE',\n headers: authHeaders(settings),\n signal: domainDeadline(),\n },\n )\n if (response.ok) return { outcome: 'detached', domain }\n if (response.status === 404) return { outcome: 'not-found', domain }\n console.error('[domain-provider:vercel] detach failed', domain, response.status)\n return { outcome: 'failed', domain, detail: String(response.status) }\n } catch (error) {\n console.error('[domain-provider:vercel] detach threw', domain, error)\n return { outcome: 'failed', domain, detail: abortedDetail(error) }\n }\n}\n\n/** Whether any issued certificate's names cover `domain`, wildcards included. */\nfunction certificateCovers(cns: unknown, domain: string): boolean {\n if (!Array.isArray(cns)) return false\n const parent = domain.split('.').slice(1).join('.')\n return cns.some((name) => {\n const cn = normalizeHost(String(name ?? ''))\n return cn === domain || (cn.startsWith('*.') && cn.slice(2) === parent)\n })\n}\n\n/**\n * What a name is ACTUALLY doing on the project, right now.\n *\n * `attach` answers \"did the POST succeed\", which is a different question and a\n * much weaker one. A domain can be on the project and still serve nothing:\n * Vercel accepts the name, then withholds routing and the certificate until\n * ownership is proven (when the apex is registered to another Vercel account)\n * or until DNS actually points here. Both states return a successful POST.\n *\n * That is the gap this closes (AGL-1913): the site custom-domain wizard\n * reported `attached: true` off the POST alone, so \"certificate is still\n * issuing\" and \"this will never work\" rendered as the same green chip.\n *\n * Three reads, cheapest first, each of which can end the walk:\n *\n * 1. `GET /v9/projects/{project}/domains/{name}` — 404 means the name is not\n * on this project at all, and `verified: false` means Vercel is holding it\n * pending the `verification` challenge it returns alongside.\n * 2. `GET /v6/domains/{name}/config` — the platform's own DNS check.\n * `misconfigured` is authoritative in a way our resolver check is not, and\n * `conflicts` names the records answering for the domain that are NOT ours\n * — the stale-A-record-shadowing-an-ALIAS case, reported rather than\n * inferred.\n * 3. `GET /v5/certs?domain={name}` — whether a certificate covers the name\n * yet. Only consulted once the first two are clean, and a FAILED cert read\n * reports `serving` rather than inventing a problem: an unreachable certs\n * API must never turn a healthy domain amber.\n */\nasync function status(\n scope: DomainScope,\n name: string,\n): Promise<ProjectDomainStatus> {\n const domain = normalizeHost(name)\n const settings = settingsFor(scope)\n if (!settings || !domain) return domainStatus(domain, 'skipped')\n const headers = authHeaders(settings)\n const team = query(settings.teamId)\n\n try {\n const attached = await fetch(\n `https://api.vercel.com/v9/projects/${settings.projectId}/domains/${encodeURIComponent(domain)}${team}`,\n { headers, signal: domainDeadline() },\n )\n if (attached.status === 404) return domainStatus(domain, 'not-attached')\n if (!attached.ok) {\n return domainStatus(domain, 'unknown', { detail: String(attached.status) })\n }\n const payload = await attached.json().catch(() => null)\n if (payload?.verified === false) {\n return domainStatus(domain, 'ownership-pending', {\n verification: Array.isArray(payload?.verification)\n ? payload.verification\n : [],\n })\n }\n\n const configured = await fetch(\n `https://api.vercel.com/v6/domains/${encodeURIComponent(domain)}/config${team}`,\n { headers, signal: domainDeadline() },\n )\n if (!configured.ok) {\n return domainStatus(domain, 'unknown', { detail: String(configured.status) })\n }\n const dns = await configured.json().catch(() => null)\n const conflicts = Array.isArray(dns?.conflicts) ? dns.conflicts : []\n if (dns?.misconfigured === true) {\n return domainStatus(domain, 'dns-misconfigured', { conflicts })\n }\n\n const certs = await fetch(\n `https://api.vercel.com/v5/certs?domain=${encodeURIComponent(domain)}${\n settings.teamId ? `&teamId=${encodeURIComponent(settings.teamId)}` : ''\n }`,\n { headers, signal: domainDeadline() },\n )\n // A certs read that did not answer must not turn a healthy domain amber.\n if (!certs.ok) return domainStatus(domain, 'serving', { conflicts })\n const issued = await certs.json().catch(() => null)\n const covered =\n Array.isArray(issued?.certs) &&\n issued.certs.some((cert: { cns?: unknown }) =>\n certificateCovers(cert?.cns, domain),\n )\n return domainStatus(domain, covered ? 'serving' : 'certificate-pending', {\n conflicts,\n })\n } catch (error) {\n console.error('[domain-provider:vercel] status threw', domain, error)\n return domainStatus(domain, 'unknown', { detail: abortedDetail(error) })\n }\n}\n\nexport const VERCEL_DOMAIN_PROVIDER: DomainProvider = {\n id: 'vercel',\n configured: (scope) => settingsFor(scope) !== null,\n attach,\n detach,\n status,\n}\n"],"names":["abortedDetail","domainDeadline","domainStatus","normalizeHost","redirectHostname","REDIRECT_STATUS_CODE","settingsFor","scope","token","process","env","VERCEL_TOKEN","projectId","VERCEL_TENANT_PROJECT_ID","VERCEL_CONSOLE_PROJECT_ID","teamId","VERCEL_TEAM_ID","query","encodeURIComponent","authHeaders","settings","Authorization","attach","name","options","domain","outcome","redirect","redirectTo","console","error","detail","body","redirectStatusCode","payload","response","fetch","method","headers","JSON","stringify","signal","ok","json","catch","code","String","status","patchRedirect","detach","certificateCovers","cns","Array","isArray","parent","split","slice","join","some","cn","startsWith","team","attached","verified","verification","configured","dns","conflicts","misconfigured","certs","issued","covered","cert","VERCEL_DOMAIN_PROVIDER","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED,SACEA,aAAa,EACbC,cAAc,EACdC,YAAY,EACZC,aAAa,EACbC,gBAAgB,QAMX,uBAAmB;AAE1B,4EAA4E,GAC5E,MAAMC,uBAAuB;AAQ7B,SAASC,YAAYC,KAAkB;IACrC,MAAMC,QAAQC,QAAQC,GAAG,CAACC,YAAY;IACtC,MAAMC,YACJL,UAAU,WACNE,QAAQC,GAAG,CAACG,wBAAwB,GACpCJ,QAAQC,GAAG,CAACI,yBAAyB;IAC3C,IAAI,CAACN,SAAS,CAACI,WAAW,OAAO;IACjC,OAAO;QAAEJ;QAAOI;QAAWG,QAAQN,QAAQC,GAAG,CAACM,cAAc;IAAC;AAChE;AAEA,SAASC,MAAMF,MAAe;I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AAU;QAC/D;QAEA,MAAME,QAAQ,MAAMjC,MAClB,CAAC,uCAAuC,EAAElB,mBAAmBO,UAC3DL,SAASL,MAAM,GAAG,CAAC,QAAQ,EAAEG,mBAAmBE,SAASL,MAAM,GAAG,GAAG,IACrE,EACF;YAAEuB;YAASG,QAAQxC;QAAiB;QAEtC,yEAAyE;QACzE,IAAI,CAACoE,MAAM3B,EAAE,EAAE,OAAOxC,aAAauB,QAAQ,WAAW;YAAE0C;QAAU;QAClE,MAAMG,SAAS,MAAMD,MAAM1B,IAAI,GAAGC,KAAK,CAAC,IAAM;QAC9C,MAAM2B,UACJnB,MAAMC,OAAO,CAACiB,0BAAAA,OAAQD,KAAK,KAC3BC,OAAOD,KAAK,CAACX,IAAI,CAAC,CAACc,OACjBtB,kBAAkBsB,wBAAAA,KAAMrB,GAAG,EAAE1B;QAEjC,OAAOvB,aAAauB,QAAQ8C,UAAU,YAAY,uBAAuB;YACvEJ;QACF;IACF,EAAE,OAAOrC,OAAO;QACdD,QAAQC,KAAK,CAAC,yCAAyCL,QAAQK;QAC/D,OAAO5B,aAAauB,QAAQ,WAAW;YAAEM,QAAQ/B,cAAc8B;QAAO;IACxE;AACF;AAEA,OAAO,MAAM2C,yBAAyC;IACpDC,IAAI;IACJT,YAAY,CAAC1D,QAAUD,YAAYC,WAAW;IAC9Ce;IACA2B;IACAF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/domain-provider-vercel.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 * The Vercel driver — how Aglyn's own hosting registers a name.\n *\n * One implementation of the call, one deadline, one never-throws contract. It\n * was five copies before this file existed: `workspace-domains.ts`, three\n * console routes and `subdomain-redirect.ts` each held their own `fetch` to\n * `api.vercel.com`, which is how two copies of a constant drift apart — the\n * bug AGL-1135 was, one layer down.\n *\n * ## The two projects\n *\n * The console and the tenant runtime are separate Vercel projects, so the\n * scope picks the id. One token and one team serve both: a second variable for\n * the same token is the drift this file exists to prevent.\n */\n\nimport {\n abortedDetail,\n domainDeadline,\n domainStatus,\n normalizeHost,\n redirectHostname,\n type DomainAttachOptions,\n type DomainProvider,\n type DomainResult,\n type DomainScope,\n type ProjectDomainStatus,\n} from './domain-provider'\n\n/** Mirrors the app-level canonical redirect: revocable, method-preserving. */\nconst REDIRECT_STATUS_CODE = 307\n\n/** For a `permanent` redirect: search engines keep both names on a 307. */\nconst PERMANENT_REDIRECT_STATUS_CODE = 308\n\ninterface VercelSettings {\n token: string\n projectId: string\n teamId?: string\n}\n\nfunction settingsFor(scope: DomainScope): VercelSettings | null {\n const token = process.env.VERCEL_TOKEN\n const projectId =\n scope === 'tenant'\n ? process.env.VERCEL_TENANT_PROJECT_ID\n : process.env.VERCEL_CONSOLE_PROJECT_ID\n if (!token || !projectId) return null\n return { token, projectId, teamId: process.env.VERCEL_TEAM_ID }\n}\n\nfunction query(teamId?: string): string {\n return teamId ? `?teamId=${encodeURIComponent(teamId)}` : ''\n}\n\nfunction authHeaders(settings: VercelSettings): Record<string, string> {\n return { Authorization: `Bearer ${settings.token}` }\n}\n\n/**\n * Attach one fully-qualified name to the scope's project.\n *\n * Idempotent: Vercel answers `domain_already_in_use` when the name is already\n * on the project, which is success for our purposes — the reconcile script and\n * the create path can both run without coordinating.\n *\n * ⚠️ Tolerating `domain_already_in_use` is only safe while **every** name this\n * is asked to attach is also claimed in Firestore. Without that, a second org\n * attaches a name someone else already holds, reads `already-exists` as\n * success, and gets a console that looks healthy while its visitors are served\n * — or redirected — somewhere else. That is the AGL-743 shape, and\n * `console-domains.ts` is where the claim is kept in step.\n */\nasync function attach(\n scope: DomainScope,\n name: string,\n options: DomainAttachOptions = {},\n): Promise<DomainResult> {\n const domain = normalizeHost(name)\n const settings = settingsFor(scope)\n if (!settings || !domain) return { outcome: 'skipped', domain }\n\n const redirect = options.redirectTo\n ? redirectHostname(options.redirectTo)\n : null\n if (options.redirectTo && !redirect) {\n console.error('[domain-provider:vercel] refusing a non-hostname redirect', options.redirectTo)\n return { outcome: 'failed', domain, detail: 'invalid-redirect' }\n }\n const redirectStatusCode = options.permanent\n ? PERMANENT_REDIRECT_STATUS_CODE\n : REDIRECT_STATUS_CODE\n const body = redirect\n ? { name: domain, redirect, redirectStatusCode }\n : { name: domain }\n\n try {\n const response = await fetch(\n `https://api.vercel.com/v10/projects/${settings.projectId}/domains${query(settings.teamId)}`,\n {\n method: 'POST',\n headers: { ...authHeaders(settings), 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: domainDeadline(),\n },\n )\n if (response.ok) return { outcome: 'attached', domain }\n const payload = await response.json().catch(() => null)\n const code = String(payload?.error?.code ?? '')\n if (code === 'domain_already_in_use' || response.status === 409) {\n // An entry that already exists still has to CARRY the redirect, or the\n // twin quietly serves the console instead of forwarding to the primary.\n if (redirect) {\n return patchRedirect(settings, domain, redirect, redirectStatusCode)\n }\n return { outcome: 'already-exists', domain }\n }\n console.error('[domain-provider:vercel] attach failed', domain, code)\n return { outcome: 'failed', domain, detail: code || String(response.status) }\n } catch (error) {\n console.error('[domain-provider:vercel] attach threw', domain, error)\n return { outcome: 'failed', domain, detail: abortedDetail(error) }\n }\n}\n\n/** Point an already-attached name at `redirect`. Same never-throws contract. */\nasync function patchRedirect(\n settings: VercelSettings,\n domain: string,\n redirect: string,\n redirectStatusCode: number,\n): Promise<DomainResult> {\n try {\n const response = await fetch(\n `https://api.vercel.com/v9/projects/${settings.projectId}/domains/${encodeURIComponent(domain)}${query(settings.teamId)}`,\n {\n method: 'PATCH',\n headers: { ...authHeaders(settings), 'Content-Type': 'application/json' },\n body: JSON.stringify({ redirect, redirectStatusCode }),\n signal: domainDeadline(),\n },\n )\n if (response.ok) return { outcome: 'already-exists', domain }\n console.error('[domain-provider:vercel] redirect patch failed', domain, response.status)\n return { outcome: 'failed', domain, detail: String(response.status) }\n } catch (error) {\n console.error('[domain-provider:vercel] redirect patch threw', domain, error)\n return { outcome: 'failed', domain, detail: abortedDetail(error) }\n }\n}\n\nasync function detach(\n scope: DomainScope,\n name: string,\n): Promise<DomainResult> {\n const domain = normalizeHost(name)\n const settings = settingsFor(scope)\n if (!settings || !domain) return { outcome: 'skipped', domain }\n try {\n const response = await fetch(\n `https://api.vercel.com/v9/projects/${settings.projectId}/domains/${encodeURIComponent(domain)}${query(settings.teamId)}`,\n {\n method: 'DELETE',\n headers: authHeaders(settings),\n signal: domainDeadline(),\n },\n )\n if (response.ok) return { outcome: 'detached', domain }\n if (response.status === 404) return { outcome: 'not-found', domain }\n console.error('[domain-provider:vercel] detach failed', domain, response.status)\n return { outcome: 'failed', domain, detail: String(response.status) }\n } catch (error) {\n console.error('[domain-provider:vercel] detach threw', domain, error)\n return { outcome: 'failed', domain, detail: abortedDetail(error) }\n }\n}\n\n/** Whether any issued certificate's names cover `domain`, wildcards included. */\nfunction certificateCovers(cns: unknown, domain: string): boolean {\n if (!Array.isArray(cns)) return false\n const parent = domain.split('.').slice(1).join('.')\n return cns.some((name) => {\n const cn = normalizeHost(String(name ?? ''))\n return cn === domain || (cn.startsWith('*.') && cn.slice(2) === parent)\n })\n}\n\n/**\n * What a name is ACTUALLY doing on the project, right now.\n *\n * `attach` answers \"did the POST succeed\", which is a different question and a\n * much weaker one. A domain can be on the project and still serve nothing:\n * Vercel accepts the name, then withholds routing and the certificate until\n * ownership is proven (when the apex is registered to another Vercel account)\n * or until DNS actually points here. Both states return a successful POST.\n *\n * That is the gap this closes (AGL-1913): the site custom-domain wizard\n * reported `attached: true` off the POST alone, so \"certificate is still\n * issuing\" and \"this will never work\" rendered as the same green chip.\n *\n * Three reads, cheapest first, each of which can end the walk:\n *\n * 1. `GET /v9/projects/{project}/domains/{name}` — 404 means the name is not\n * on this project at all, and `verified: false` means Vercel is holding it\n * pending the `verification` challenge it returns alongside.\n * 2. `GET /v6/domains/{name}/config` — the platform's own DNS check.\n * `misconfigured` is authoritative in a way our resolver check is not, and\n * `conflicts` names the records answering for the domain that are NOT ours\n * — the stale-A-record-shadowing-an-ALIAS case, reported rather than\n * inferred.\n * 3. `GET /v5/certs?domain={name}` — whether a certificate covers the name\n * yet. Only consulted once the first two are clean, and a FAILED cert read\n * reports `serving` rather than inventing a problem: an unreachable certs\n * API must never turn a healthy domain amber.\n */\nasync function status(\n scope: DomainScope,\n name: string,\n): Promise<ProjectDomainStatus> {\n const domain = normalizeHost(name)\n const settings = settingsFor(scope)\n if (!settings || !domain) return domainStatus(domain, 'skipped')\n const headers = authHeaders(settings)\n const team = query(settings.teamId)\n\n try {\n const attached = await fetch(\n `https://api.vercel.com/v9/projects/${settings.projectId}/domains/${encodeURIComponent(domain)}${team}`,\n { headers, signal: domainDeadline() },\n )\n if (attached.status === 404) return domainStatus(domain, 'not-attached')\n if (!attached.ok) {\n return domainStatus(domain, 'unknown', { detail: String(attached.status) })\n }\n const payload = await attached.json().catch(() => null)\n if (payload?.verified === false) {\n return domainStatus(domain, 'ownership-pending', {\n verification: Array.isArray(payload?.verification)\n ? payload.verification\n : [],\n })\n }\n\n const configured = await fetch(\n `https://api.vercel.com/v6/domains/${encodeURIComponent(domain)}/config${team}`,\n { headers, signal: domainDeadline() },\n )\n if (!configured.ok) {\n return domainStatus(domain, 'unknown', { detail: String(configured.status) })\n }\n const dns = await configured.json().catch(() => null)\n const conflicts = Array.isArray(dns?.conflicts) ? dns.conflicts : []\n if (dns?.misconfigured === true) {\n return domainStatus(domain, 'dns-misconfigured', { conflicts })\n }\n\n const certs = await fetch(\n `https://api.vercel.com/v5/certs?domain=${encodeURIComponent(domain)}${\n settings.teamId ? `&teamId=${encodeURIComponent(settings.teamId)}` : ''\n }`,\n { headers, signal: domainDeadline() },\n )\n // A certs read that did not answer must not turn a healthy domain amber.\n if (!certs.ok) return domainStatus(domain, 'serving', { conflicts })\n const issued = await certs.json().catch(() => null)\n const covered =\n Array.isArray(issued?.certs) &&\n issued.certs.some((cert: { cns?: unknown }) =>\n certificateCovers(cert?.cns, domain),\n )\n return domainStatus(domain, covered ? 'serving' : 'certificate-pending', {\n conflicts,\n })\n } catch (error) {\n console.error('[domain-provider:vercel] status threw', domain, error)\n return domainStatus(domain, 'unknown', { detail: abortedDetail(error) })\n }\n}\n\nexport const VERCEL_DOMAIN_PROVIDER: DomainProvider = {\n id: 'vercel',\n configured: (scope) => settingsFor(scope) !== null,\n attach,\n detach,\n status,\n}\n"],"names":["abortedDetail","domainDeadline","domainStatus","normalizeHost","redirectHostname","REDIRECT_STATUS_CODE","PERMANENT_REDIRECT_STATUS_CODE","settingsFor","scope","token","process","env","VERCEL_TOKEN","projectId","VERCEL_TENANT_PROJECT_ID","VERCEL_CONSOLE_PROJECT_ID","teamId","VERCEL_TEAM_ID","query","encodeURIComponent","authHeaders","settings","Authorization","attach","name","options","domain","outcome","redirect","redirectTo","console","error","detail","redirectStatusCode","permanent","body","payload","response","fetch","method","headers","JSON","stringify","signal","ok","json","catch","code","String","status","patchRedirect","detach","certificateCovers","cns","Array","isArray","parent","split","slice","join","some","cn","startsWith","team","attached","verified","verification","configured","dns","conflicts","misconfigured","certs","issued","covered","cert","VERCEL_DOMAIN_PROVIDER","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED,SACEA,aAAa,EACbC,cAAc,EACdC,YAAY,EACZC,aAAa,EACbC,gBAAgB,QAMX,uBAAmB;AAE1B,4EAA4E,GAC5E,MAAMC,uBAAuB;AAE7B,yEAAyE,GACzE,MAAMC,iCAAiC;AAQvC,SAASC,YAAYC,KAAkB;IACrC,MAAMC,QAAQC,QAAQC,GAAG,CAACC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supposed to forward.
89
89
  */
90
90
  redirectTo?: string;
91
+ /**
92
+ * The redirect is for good, not revocable: the same site at a second
93
+ * spelling, which search engines must fold into one (AGL-4134).
94
+ */
95
+ permanent?: boolean;
91
96
  }
92
97
  export type ProjectDomainState = 'serving' | 'certificate-pending' | 'ownership-pending' | 'dns-misconfigured' | 'not-attached' | 'skipped' | 'unknown';
93
98
  /** One challenge record a provider wants before it will serve the name. */
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/domain-provider.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 * How a hostname gets served — the one seam the hosting vendor lives behind.\n *\n * ## The lock-in this removes\n *\n * Attaching a name was `POST https://api.vercel.com/...`, written out five\n * times across the console routes and this library. Every workspace subdomain\n * and every customer's custom domain therefore required a Vercel project and a\n * Vercel token, and a self-hosted install had no way to register a name at all\n * — it got `skipped` and a console that advertised a URL nothing resolved.\n * \"Bring your own Firebase, run it on Docker\" cannot be true while the way a\n * site becomes reachable is one vendor's API.\n *\n * So the vendor is a driver now. The three operations a name needs are the\n * whole contract, and an operator picks — or writes — the implementation:\n *\n * | provider | for |\n * |------------|-----------------------------------------------------------|\n * | `vercel` | Aglyn's own hosting, and anyone else on Vercel |\n * | `wildcard` | a container behind a proxy with `*.example.com` DNS |\n * | `webhook` | anything else — Caddy, Traefik, cert-manager, a registrar |\n * | `none` | names are somebody else's job entirely |\n *\n * ## Why a webhook is the extension point and not a module path\n *\n * The obvious \"supply your own layer\" is a file path the app imports at boot.\n * It does not survive the product: both apps are bundled by Next, so a path\n * resolved at runtime is not in the bundle, and an operator running the\n * published image has no build step to add one to. A webhook needs no rebuild,\n * works from the shipped image, and is the same shape whether the operator's\n * DNS lives in Caddy's admin API, a Traefik provider, or a shell script behind\n * `nc`. The cost is one HTTP hop on an operation that already makes one.\n *\n * ## The contract every driver owes\n *\n * 1. **Never throw.** A caller creates orgs and renders cards with these\n * results; an exception takes down an org creation over a DNS API. Return\n * `failed` — or `skipped`, which is not a failure.\n * 2. **Idempotent.** `attach` on a name already attached is `already-exists`,\n * which is success. Reconcile passes and create paths both run.\n * 3. **`skipped` means \"not my job\", not \"it went wrong\".** It is what an\n * unconfigured driver returns, and callers treat it as neither success nor\n * failure.\n * 4. **`unknown` status is not evidence of a problem.** {@link domainStateServes}\n * returns true for it deliberately: a probe that could not answer must not\n * strand every domain on a deployment whose provider has no status API.\n */\n\n/**\n * Which deployment a name should reach.\n *\n * Two, because Aglyn runs two apps: the console at `app.<domain>` with its\n * per-workspace subdomains, and the tenant runtime that serves published\n * sites and every customer's own domain. On Vercel they are separate projects;\n * behind a proxy they are separate upstreams; for a webhook they are a field.\n */\nexport type DomainScope = 'console' | 'tenant'\n\nexport type DomainOutcome =\n | 'attached'\n | 'detached'\n | 'already-exists'\n | 'not-found'\n | 'skipped'\n | 'failed'\n\nexport interface DomainResult {\n outcome: DomainOutcome\n domain: string\n /** Why, when the outcome alone does not say it. Never user-facing prose. */\n detail?: string\n}\n\nexport interface DomainAttachOptions {\n /**\n * Register the name as a REDIRECT to this bare hostname rather than serving\n * the app on it — how a renamed workspace keeps its old slug working.\n *\n * A driver that cannot express a redirect returns `skipped` rather than\n * attaching a serving name, because the two are not interchangeable: a\n * serving twin is a second live copy of the console on a name that was\n * supposed to forward.\n */\n redirectTo?: string\n}\n\nexport type ProjectDomainState =\n | 'serving'\n | 'certificate-pending'\n | 'ownership-pending'\n | 'dns-misconfigured'\n | 'not-attached'\n | 'skipped'\n | 'unknown'\n\n/** One challenge record a provider wants before it will serve the name. */\nexport interface ProjectDomainVerification {\n type: string\n domain: string\n value: string\n reason?: string\n}\n\nexport interface ProjectDomainStatus {\n state: ProjectDomainState\n domain: string\n /** Present when `state` is `ownership-pending`; what to add at the registrar. */\n verification: ProjectDomainVerification[]\n /**\n * Records answering for this name that are not ours, as the provider sees\n * them. A non-empty list on an otherwise-serving domain is the shadowing\n * case: it resolves correctly some of the time.\n */\n conflicts: { type?: string; name?: string; value?: string }[]\n /** Why, when the state alone does not say it. */\n detail?: string\n}\n\nexport interface DomainProvider {\n /** Stable id, used in this module's log lines. Never a display name. */\n readonly id: string\n /** Whether this deployment can actually register names for `scope`. */\n configured(scope: DomainScope): boolean\n attach(\n scope: DomainScope,\n domain: string,\n options?: DomainAttachOptions,\n ): Promise<DomainResult>\n detach(scope: DomainScope, domain: string): Promise<DomainResult>\n status(scope: DomainScope, domain: string): Promise<ProjectDomainStatus>\n}\n\n/**\n * Whether a probed state means visitors may be sent to the domain (AGL-2011).\n *\n * The ONE definition of \"serving\", because it has to be. The predicate lived\n * inline in `/api/domains/attach` and again in\n * `/api/admin/finish-domain-attachments`, and the sweeper's own comment says\n * why that is dangerous: a sweeper using a looser definition than the door it\n * completes for re-introduces the bug that door was fixed to avoid.\n *\n * `certificate-pending` is NOT serving (AGL-1996): the name is accepted and\n * routed but no certificate exists yet, so the destination answers with a TLS\n * error. `unknown` and `skipped` ARE, deliberately — a status probe that could\n * not answer is not evidence of a problem, and treating it as one would strand\n * every domain on a deployment whose provider has no status API to ask.\n */\nexport function domainStateServes(state: ProjectDomainState): boolean {\n return (\n state !== 'not-attached' &&\n state !== 'ownership-pending' &&\n state !== 'dns-misconfigured' &&\n state !== 'certificate-pending'\n )\n}\n\nexport function domainStatus(\n domain: string,\n state: ProjectDomainState,\n extra: Partial<ProjectDomainStatus> = {},\n): ProjectDomainStatus {\n return { state, domain, verification: [], conflicts: [], ...extra }\n}\n\nconst HOSTNAME_PATTERN =\n /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/\n\nexport function normalizeHost(input: string): string {\n return String(input ?? '')\n .trim()\n .toLowerCase()\n .replace(/\\.$/, '')\n}\n\n/**\n * A redirect target reduced to a BARE HOSTNAME, or `null` if it is not one.\n *\n * Vercel rejects `https://aglyn.com` here with `bad_request`, whose message\n * reads \"Unable to redirect to https://…, because that domain is not added to\n * the project\" — it blames the target for being absent when the format was\n * wrong. That misreading is why AGL-1273's redirect shipped looking correct\n * and never once succeeded, and survived weeks before AGL-1365 caught it.\n *\n * Enforced at the seam rather than trusted per driver, so a webhook operator\n * receives the same shape Vercel demands and no driver has to re-derive it.\n */\nexport function redirectHostname(target: string): string | null {\n const raw = normalizeHost(target)\n if (!raw) return null\n const host = raw\n .replace(/^[a-z][a-z0-9+.-]*:\\/\\//, '')\n .split(/[/?#]/)[0]\n .replace(/\\.$/, '')\n return HOSTNAME_PATTERN.test(host) ? host : null\n}\n\n/**\n * Ceiling on any provider call (AGL-1136).\n *\n * These are awaited — org creation and rename wait for them — so an\n * unresponsive DNS API would otherwise hang the operation until the platform\n * killed the function, turning \"the subdomain is not attached yet\" into \"the\n * workspace could not be created\". The whole point of the call being\n * best-effort is that it can lose without taking anything with it, and a\n * promise with no timeout cannot lose.\n */\nexport const DOMAIN_PROVIDER_TIMEOUT_MS = 5000\n\n/** `AbortSignal.timeout`, without assuming the runtime has it. */\nexport function domainDeadline(): AbortSignal | undefined {\n try {\n return AbortSignal.timeout(DOMAIN_PROVIDER_TIMEOUT_MS)\n } catch {\n return undefined\n }\n}\n\n/** Whether a rejection was our own deadline rather than the network's. */\nexport function abortedDetail(error: unknown): 'timeout' | 'network' {\n const name = (error as { name?: string })?.name\n return name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network'\n}\n\n/**\n * The driver that registers nothing.\n *\n * Not an error state. A deployment can legitimately have names handled\n * entirely outside the product — a platform team's own DNS pipeline, or an\n * install that only ever uses path routing — and the correct behaviour there\n * is silence, not a failure logged on every signup forever.\n */\nexport const NO_DOMAIN_PROVIDER: DomainProvider = {\n id: 'none',\n configured: () => false,\n attach: async (_scope, domain) => ({ outcome: 'skipped', domain }),\n detach: async (_scope, domain) => ({ outcome: 'skipped', domain }),\n status: async (_scope, domain) => domainStatus(domain, 'skipped'),\n}\n\nexport type DomainProviderId = 'vercel' | 'wildcard' | 'webhook' | 'none'\n\n/**\n * The configured provider id, or `null` to let {@link domainProvider} infer it.\n *\n * An explicit value always wins, including `none` — an operator switching a\n * driver off while its credentials are still in the environment means it.\n */\nfunction requestedProviderId(): DomainProviderId | null {\n const raw = String(process.env.AGLYN_DOMAIN_PROVIDER ?? '')\n .trim()\n .toLowerCase()\n if (!raw) return null\n if (\n raw === 'vercel' ||\n raw === 'wildcard' ||\n raw === 'webhook' ||\n raw === 'none'\n ) {\n return raw\n }\n console.error(\n `[domain-provider] unknown AGLYN_DOMAIN_PROVIDER \"${raw}\" — falling back ` +\n 'to detection. Valid values: vercel, wildcard, webhook, none.',\n )\n return null\n}\n\nlet cached: { key: string; provider: DomainProvider } | null = null\n\n/**\n * The provider this deployment uses.\n *\n * ⚠️ Detection, when `AGLYN_DOMAIN_PROVIDER` is unset, deliberately only ever\n * selects `vercel` — never `wildcard`. Wildcard reports a name as SERVING\n * without checking anything, and inferring it from an apex an operator merely\n * configured would have the console advertise addresses that resolve nowhere\n * while showing a green chip. Claiming to serve a name is the operator's\n * assertion to make, so it takes their explicit setting.\n *\n * Memoized on the environment values it reads rather than once per process, so\n * a spec can change them between cases without a reset hook that production\n * would carry for nobody.\n */\nexport function domainProvider(): DomainProvider {\n const requested = requestedProviderId()\n const key = [\n requested ?? '',\n process.env.VERCEL_TOKEN ? '1' : '',\n process.env.AGLYN_DOMAIN_WEBHOOK_URL ?? '',\n process.env.AGLYN_DOMAIN_WILDCARD_SUFFIXES ?? '',\n process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN ?? '',\n process.env.NEXT_PUBLIC_TENANT_DOMAIN ?? '',\n ].join('\\x00')\n if (cached?.key === key) return cached.provider\n\n const provider = selectProvider(requested)\n cached = { key, provider }\n return provider\n}\n\nfunction selectProvider(requested: DomainProviderId | null): DomainProvider {\n // Required lazily so a deployment pays for only the driver it uses, and so\n // this module stays importable from an edge runtime that has no `fetch`\n // credentials of its own.\n switch (requested ?? (process.env.VERCEL_TOKEN ? 'vercel' : 'none')) {\n case 'vercel':\n return require('./domain-provider-vercel').VERCEL_DOMAIN_PROVIDER\n case 'wildcard':\n return require('./domain-provider-wildcard').wildcardDomainProvider()\n case 'webhook':\n return require('./domain-provider-webhook').webhookDomainProvider()\n default:\n return NO_DOMAIN_PROVIDER\n }\n}\n"],"names":["domainStateServes","state","domainStatus","domain","extra","verification","conflicts","HOSTNAME_PATTERN","normalizeHost","input","String","trim","toLowerCase","replace","redirectHostname","target","raw","host","split","test","DOMAIN_PROVIDER_TIMEOUT_MS","domainDeadline","AbortSignal","timeout","undefined","abortedDetail","error","name","NO_DOMAIN_PROVIDER","id","configured","attach","_scope","outcome","detach","status","requestedProviderId","process","env","AGLYN_DOMAIN_PROVIDER","console","cached","domainProvider","requested","key","VERCEL_TOKEN","AGLYN_DOMAIN_WEBHOOK_URL","AGLYN_DOMAIN_WILDCARD_SUFFIXES","NEXT_PUBLIC_WORKSPACE_DOMAIN","NEXT_PUBLIC_TENANT_DOMAIN","join","provider","selectProvider","require","VERCEL_DOMAIN_PROVIDER","wildcardDomainProvider","webhookDomainProvider"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GAED;;;;;;;CAOC;AA6ED;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASA,kBAAkBC,KAAyB;IACzD,OACEA,UAAU,kBACVA,UAAU,uBACVA,UAAU,uBACVA,UAAU;AAEd;AAEA,OAAO,SAASC,aACdC,MAAc,EACdF,KAAyB,EACzBG,QAAsC,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in/src/lib/server/domain-provider.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 * How a hostname gets served — the one seam the hosting vendor lives behind.\n *\n * ## The lock-in this removes\n *\n * Attaching a name was `POST https://api.vercel.com/...`, written out five\n * times across the console routes and this library. Every workspace subdomain\n * and every customer's custom domain therefore required a Vercel project and a\n * Vercel token, and a self-hosted install had no way to register a name at all\n * — it got `skipped` and a console that advertised a URL nothing resolved.\n * \"Bring your own Firebase, run it on Docker\" cannot be true while the way a\n * site becomes reachable is one vendor's API.\n *\n * So the vendor is a driver now. The three operations a name needs are the\n * whole contract, and an operator picks — or writes — the implementation:\n *\n * | provider | for |\n * |------------|-----------------------------------------------------------|\n * | `vercel` | Aglyn's own hosting, and anyone else on Vercel |\n * | `wildcard` | a container behind a proxy with `*.example.com` DNS |\n * | `webhook` | anything else — Caddy, Traefik, cert-manager, a registrar |\n * | `none` | names are somebody else's job entirely |\n *\n * ## Why a webhook is the extension point and not a module path\n *\n * The obvious \"supply your own layer\" is a file path the app imports at boot.\n * It does not survive the product: both apps are bundled by Next, so a path\n * resolved at runtime is not in the bundle, and an operator running the\n * published image has no build step to add one to. A webhook needs no rebuild,\n * works from the shipped image, and is the same shape whether the operator's\n * DNS lives in Caddy's admin API, a Traefik provider, or a shell script behind\n * `nc`. The cost is one HTTP hop on an operation that already makes one.\n *\n * ## The contract every driver owes\n *\n * 1. **Never throw.** A caller creates orgs and renders cards with these\n * results; an exception takes down an org creation over a DNS API. Return\n * `failed` — or `skipped`, which is not a failure.\n * 2. **Idempotent.** `attach` on a name already attached is `already-exists`,\n * which is success. Reconcile passes and create paths both run.\n * 3. **`skipped` means \"not my job\", not \"it went wrong\".** It is what an\n * unconfigured driver returns, and callers treat it as neither success nor\n * failure.\n * 4. **`unknown` status is not evidence of a problem.** {@link domainStateServes}\n * returns true for it deliberately: a probe that could not answer must not\n * strand every domain on a deployment whose provider has no status API.\n */\n\n/**\n * Which deployment a name should reach.\n *\n * Two, because Aglyn runs two apps: the console at `app.<domain>` with its\n * per-workspace subdomains, and the tenant runtime that serves published\n * sites and every customer's own domain. On Vercel they are separate projects;\n * behind a proxy they are separate upstreams; for a webhook they are a field.\n */\nexport type DomainScope = 'console' | 'tenant'\n\nexport type DomainOutcome =\n | 'attached'\n | 'detached'\n | 'already-exists'\n | 'not-found'\n | 'skipped'\n | 'failed'\n\nexport interface DomainResult {\n outcome: DomainOutcome\n domain: string\n /** Why, when the outcome alone does not say it. Never user-facing prose. */\n detail?: string\n}\n\nexport interface DomainAttachOptions {\n /**\n * Register the name as a REDIRECT to this bare hostname rather than serving\n * the app on it — how a renamed workspace keeps its old slug working.\n *\n * A driver that cannot express a redirect returns `skipped` rather than\n * attaching a serving name, because the two are not interchangeable: a\n * serving twin is a second live copy of the console on a name that was\n * supposed to forward.\n */\n redirectTo?: string\n /**\n * The redirect is for good, not revocable: the same site at a second\n * spelling, which search engines must fold into one (AGL-4134).\n */\n permanent?: boolean\n}\n\nexport type ProjectDomainState =\n | 'serving'\n | 'certificate-pending'\n | 'ownership-pending'\n | 'dns-misconfigured'\n | 'not-attached'\n | 'skipped'\n | 'unknown'\n\n/** One challenge record a provider wants before it will serve the name. */\nexport interface ProjectDomainVerification {\n type: string\n domain: string\n value: string\n reason?: string\n}\n\nexport interface ProjectDomainStatus {\n state: ProjectDomainState\n domain: string\n /** Present when `state` is `ownership-pending`; what to add at the registrar. */\n verification: ProjectDomainVerification[]\n /**\n * Records answering for this name that are not ours, as the provider sees\n * them. A non-empty list on an otherwise-serving domain is the shadowing\n * case: it resolves correctly some of the time.\n */\n conflicts: { type?: string; name?: string; value?: string }[]\n /** Why, when the state alone does not say it. */\n detail?: string\n}\n\nexport interface DomainProvider {\n /** Stable id, used in this module's log lines. Never a display name. */\n readonly id: string\n /** Whether this deployment can actually register names for `scope`. */\n configured(scope: DomainScope): boolean\n attach(\n scope: DomainScope,\n domain: string,\n options?: DomainAttachOptions,\n ): Promise<DomainResult>\n detach(scope: DomainScope, domain: string): Promise<DomainResult>\n status(scope: DomainScope, domain: string): Promise<ProjectDomainStatus>\n}\n\n/**\n * Whether a probed state means visitors may be sent to the domain (AGL-2011).\n *\n * The ONE definition of \"serving\", because it has to be. The predicate lived\n * inline in `/api/domains/attach` and again in\n * `/api/admin/finish-domain-attachments`, and the sweeper's own comment says\n * why that is dangerous: a sweeper using a looser definition than the door it\n * completes for re-introduces the bug that door was fixed to avoid.\n *\n * `certificate-pending` is NOT serving (AGL-1996): the name is accepted and\n * routed but no certificate exists yet, so the destination answers with a TLS\n * error. `unknown` and `skipped` ARE, deliberately — a status probe that could\n * not answer is not evidence of a problem, and treating it as one would strand\n * every domain on a deployment whose provider has no status API to ask.\n */\nexport function domainStateServes(state: ProjectDomainState): boolean {\n return (\n state !== 'not-attached' &&\n state !== 'ownership-pending' &&\n state !== 'dns-misconfigured' &&\n state !== 'certificate-pending'\n )\n}\n\nexport function domainStatus(\n domain: string,\n state: ProjectDomainState,\n extra: Partial<ProjectDomainStatus> = {},\n): ProjectDomainStatus {\n return { state, domain, verification: [], conflicts: [], ...extra }\n}\n\nconst HOSTNAME_PATTERN =\n /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/\n\nexport function normalizeHost(input: string): string {\n return String(input ?? '')\n .trim()\n .toLowerCase()\n .replace(/\\.$/, '')\n}\n\n/**\n * A redirect target reduced to a BARE HOSTNAME, or `null` if it is not one.\n *\n * Vercel rejects `https://aglyn.com` here with `bad_request`, whose message\n * reads \"Unable to redirect to https://…, because that domain is not added to\n * the project\" — it blames the target for being absent when the format was\n * wrong. That misreading is why AGL-1273's redirect shipped looking correct\n * and never once succeeded, and survived weeks before AGL-1365 caught it.\n *\n * Enforced at the seam rather than trusted per driver, so a webhook operator\n * receives the same shape Vercel demands and no driver has to re-derive it.\n */\nexport function redirectHostname(target: string): string | null {\n const raw = normalizeHost(target)\n if (!raw) return null\n const host = raw\n .replace(/^[a-z][a-z0-9+.-]*:\\/\\//, '')\n .split(/[/?#]/)[0]\n .replace(/\\.$/, '')\n return HOSTNAME_PATTERN.test(host) ? host : null\n}\n\n/**\n * Ceiling on any provider call (AGL-1136).\n *\n * These are awaited — org creation and rename wait for them — so an\n * unresponsive DNS API would otherwise hang the operation until the platform\n * killed the function, turning \"the subdomain is not attached yet\" into \"the\n * workspace could not be created\". The whole point of the call being\n * best-effort is that it can lose without taking anything with it, and a\n * promise with no timeout cannot lose.\n */\nexport const DOMAIN_PROVIDER_TIMEOUT_MS = 5000\n\n/** `AbortSignal.timeout`, without assuming the runtime has it. */\nexport function domainDeadline(): AbortSignal | undefined {\n try {\n return AbortSignal.timeout(DOMAIN_PROVIDER_TIMEOUT_MS)\n } catch {\n return undefined\n }\n}\n\n/** Whether a rejection was our own deadline rather than the network's. */\nexport function abortedDetail(error: unknown): 'timeout' | 'network' {\n const name = (error as { name?: string })?.name\n return name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network'\n}\n\n/**\n * The driver that registers nothing.\n *\n * Not an error state. A deployment can legitimately have names handled\n * entirely outside the product — a platform team's own DNS pipeline, or an\n * install that only ever uses path routing — and the correct behaviour there\n * is silence, not a failure logged on every signup forever.\n */\nexport const NO_DOMAIN_PROVIDER: DomainProvider = {\n id: 'none',\n configured: () => false,\n attach: async (_scope, domain) => ({ outcome: 'skipped', domain }),\n detach: async (_scope, domain) => ({ outcome: 'skipped', domain }),\n status: async (_scope, domain) => domainStatus(domain, 'skipped'),\n}\n\nexport type DomainProviderId = 'vercel' | 'wildcard' | 'webhook' | 'none'\n\n/**\n * The configured provider id, or `null` to let {@link domainProvider} infer it.\n *\n * An explicit value always wins, including `none` — an operator switching a\n * driver off while its credentials are still in the environment means it.\n */\nfunction requestedProviderId(): DomainProviderId | null {\n const raw = String(process.env.AGLYN_DOMAIN_PROVIDER ?? '')\n .trim()\n .toLowerCase()\n if (!raw) return null\n if (\n raw === 'vercel' ||\n raw === 'wildcard' ||\n raw === 'webhook' ||\n raw === 'none'\n ) {\n return raw\n }\n console.error(\n `[domain-provider] unknown AGLYN_DOMAIN_PROVIDER \"${raw}\" — falling back ` +\n 'to detection. Valid values: vercel, wildcard, webhook, none.',\n )\n return null\n}\n\nlet cached: { key: string; provider: DomainProvider } | null = null\n\n/**\n * The provider this deployment uses.\n *\n * ⚠️ Detection, when `AGLYN_DOMAIN_PROVIDER` is unset, deliberately only ever\n * selects `vercel` — never `wildcard`. Wildcard reports a name as SERVING\n * without checking anything, and inferring it from an apex an operator merely\n * configured would have the console advertise addresses that resolve nowhere\n * while showing a green chip. Claiming to serve a name is the operator's\n * assertion to make, so it takes their explicit setting.\n *\n * Memoized on the environment values it reads rather than once per process, so\n * a spec can change them between cases without a reset hook that production\n * would carry for nobody.\n */\nexport function domainProvider(): DomainProvider {\n const requested = requestedProviderId()\n const key = [\n requested ?? '',\n process.env.VERCEL_TOKEN ? '1' : '',\n process.env.AGLYN_DOMAIN_WEBHOOK_URL ?? '',\n process.env.AGLYN_DOMAIN_WILDCARD_SUFFIXES ?? '',\n process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN ?? '',\n process.env.NEXT_PUBLIC_TENANT_DOMAIN ?? '',\n ].join('\\x00')\n if (cached?.key === key) return cached.provider\n\n const provider = selectProvider(requested)\n cached = { key, provider }\n return provider\n}\n\nfunction selectProvider(requested: DomainProviderId | null): DomainProvider {\n // Required lazily so a deployment pays for only the driver it uses, and so\n // this module stays importable from an edge runtime that has no `fetch`\n // credentials of its own.\n switch (requested ?? (process.env.VERCEL_TOKEN ? 'vercel' : 'none')) {\n case 'vercel':\n return require('./domain-provider-vercel').VERCEL_DOMAIN_PROVIDER\n case 'wildcard':\n return require('./domain-provider-wildcard').wildcardDomainProvider()\n case 'webhook':\n return require('./domain-provider-webhook').webhookDomainProvider()\n default:\n return NO_DOMAIN_PROVIDER\n }\n}\n"],"names":["domainStateServes","state","domainStatus","domain","extra","verification","conflicts","HOSTNAME_PATTERN","normalizeHost","input","String","trim","toLowerCase","replace","redirectHostname","target","raw","host","split","test","DOMAIN_PROVIDER_TIMEOUT_MS","domainDeadline","AbortSignal","timeout","undefined","abortedDetail","error","name","NO_DOMAIN_PROVIDER","id","configured","attach","_scope","outcome","detach","status","requestedProviderId","process","env","AGLYN_DOMAIN_PROVIDER","console","cached","domainProvider","requested","key","VERCEL_TOKEN","AGLYN_DOMAIN_WEBHOOK_URL","AGLYN_DOMAIN_WILDCARD_SUFFIXES","NEXT_PUBLIC_WORKSPACE_DOMAIN","NEXT_PUBLIC_TENANT_DOMAIN","join","provider","selectProvider","require","VERCEL_DOMAIN_PROVIDER","wildcardDomainProvider","webhookDomainProvider"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GAED;;;;;;;CAOC;AAkFD;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASA,kBAAkBC,KAAyB;IACzD,OACEA,UAAU,kBACVA,UAAU,uBACVA,UAAU,uBACVA,UAAU;AAEd;AAEA,OAAO,SAASC,aACdC,MAAc,EACdF,KAAyB,EACzBG,QAAsC,CAAC,CAAC;IAExC,OAAO;QAAEH;QAAOE;QAAQE,cAAc,EAAE;QAAEC,WAAW,EAAE;OAAKF;AAC9D;AAEA,MAAMG,mBACJ;AAEF,OAAO,SAASC,cAAcC,KAAa;IACzC,OAAOC,OAAOD,gBAAAA,QAAS,IACpBE,IAAI,GACJC,WAAW,GACXC,OAAO,CAAC,OAAO;AACpB;AAEA;;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O;AACT;AAEA,IAAIyB,SAA2D;AAE/D;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC;QAKZL,uCACAA,6CACAA,2CACAA;IAPF,MAAMM,YAAYP;IAClB,MAAMQ,MAAM;QACVD,oBAAAA,YAAa;QACbN,QAAQC,GAAG,CAACO,YAAY,GAAG,MAAM;SACjCR,wCAAAA,QAAQC,GAAG,CAACQ,wBAAwB,YAApCT,wCAAwC;SACxCA,8CAAAA,QAAQC,GAAG,CAACS,8BAA8B,YAA1CV,8CAA8C;SAC9CA,4CAAAA,QAAQC,GAAG,CAACU,4BAA4B,YAAxCX,4CAA4C;SAC5CA,yCAAAA,QAAQC,GAAG,CAACW,yBAAyB,YAArCZ,yCAAyC;KAC1C,CAACa,IAAI,CAAC;IACP,IAAIT,CAAAA,0BAAAA,OAAQG,GAAG,MAAKA,KAAK,OAAOH,OAAOU,QAAQ;IAE/C,MAAMA,WAAWC,eAAeT;IAChCF,SAAS;QAAEG;QAAKO;IAAS;IACzB,OAAOA;AACT;AAEA,SAASC,eAAeT,SAAkC;IACxD,2EAA2E;IAC3E,wEAAwE;IACxE,0BAA0B;IAC1B,OAAQA,oBAAAA,YAAcN,QAAQC,GAAG,CAACO,YAAY,GAAG,WAAW;QAC1D,KAAK;YACH,OAAOQ,QAAQ,4BAA4BC,sBAAsB;QACnE,KAAK;YACH,OAAOD,QAAQ,8BAA8BE,sBAAsB;QACrE,KAAK;YACH,OAAOF,QAAQ,6BAA6BG,qBAAqB;QACnE;YACE,OAAO5B;IACX;AACF"}
@@ -35,9 +35,11 @@ import { type ProjectDomainState, type ProjectDomainStatus } from './domain-prov
35
35
  * ## The twin
36
36
  *
37
37
  * `twin` is the `www.`/apex partner of the domain, served as a REDIRECT to it
38
- * (AGL-1311 memo §5.2). It is opt-in, because only a caller that writes the
39
- * twin's DNS can promise it resolves: a bought domain, or a provider applying
40
- * a Domain Connect template. The manual card connects one name, as before.
38
+ * (AGL-1311 memo §5.2). It is opt-in, and every connect path now opts in: a
39
+ * bought domain, a provider applying a Domain Connect template, and the manual
40
+ * card (AGL-4134). The card cannot promise the twin's DNS resolves, but a twin
41
+ * nobody points at simply never receives a visitor, while a twin left off a
42
+ * domain with both records makes one of its two addresses a dead end.
41
43
  *
42
44
  * The twin is claimed in the SAME transaction as the primary and is checked
43
45
  * against every other site's primary AND twin, both ways round. Without that,
@@ -41,9 +41,11 @@ import { attachProjectDomain, detachProjectDomain, projectDomainStatus } from ".
41
41
  * ## The twin
42
42
  *
43
43
  * `twin` is the `www.`/apex partner of the domain, served as a REDIRECT to it
44
- * (AGL-1311 memo §5.2). It is opt-in, because only a caller that writes the
45
- * twin's DNS can promise it resolves: a bought domain, or a provider applying
46
- * a Domain Connect template. The manual card connects one name, as before.
44
+ * (AGL-1311 memo §5.2). It is opt-in, and every connect path now opts in: a
45
+ * bought domain, a provider applying a Domain Connect template, and the manual
46
+ * card (AGL-4134). The card cannot promise the twin's DNS resolves, but a twin
47
+ * nobody points at simply never receives a visitor, while a twin left off a
48
+ * domain with both records makes one of its two addresses a dead end.
47
49
  *
48
50
  * The twin is claimed in the SAME transaction as the primary and is checked
49
51
  * against every other site's primary AND twin, both ways round. Without that,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-custom-domain.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 type { HostActivityActor } from '@aglyn/aglyn/app-utils/activity-presenter'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport { runPluginEventHandlers } from '@aglyn/aglyn/plugin-manager/plugin-events'\nimport {\n domainProvider,\n domainStateServes,\n type ProjectDomainState,\n type ProjectDomainStatus,\n} from './domain-provider'\nimport firebaseAdmin from './firebase-admin'\nimport { flagLookalikeCustomDomain } from './hosted-page-review'\nimport { syncHostProjectionForMembers } from './host-memberships'\nimport {\n upsertCustomDomainTwin,\n upsertSubdomainRedirect,\n} from './custom-domain-redirects'\nimport { logHostActivity } from './organizations'\nimport {\n attachProjectDomain,\n detachProjectDomain,\n projectDomainStatus,\n} from './workspace-domains'\n\n/**\n * CONNECTING A NAME TO A SITE, as one server function (AGL-3961).\n *\n * This is the sequence `/api/domains/attach` ran inline: claim the name in a\n * transaction, attach it to the tenant deployment, probe what the platform\n * actually did, record the shortfall, point the platform subdomain at it, log\n * it, and tell plugins. It lives here so a caller with no ID token — a plugin\n * that bought the name, a sweeper finishing an order — connects a domain\n * through exactly the same claim the customer's own button uses. A second copy\n * of the claim is how two sites end up holding one name (AGL-743).\n *\n * Authorization is the CALLER's: the route checks the admin role, lockdown and\n * the plan before it gets here, and a plugin checks its own. This function\n * assumes the caller may connect `domain` to `hostId` and that `domain` has\n * already been through `validatePlatformDomain`.\n *\n * ## The twin\n *\n * `twin` is the `www.`/apex partner of the domain, served as a REDIRECT to it\n * (AGL-1311 memo §5.2). It is opt-in, because only a caller that writes the\n * twin's DNS can promise it resolves: a bought domain, or a provider applying\n * a Domain Connect template. The manual card connects one name, as before.\n *\n * The twin is claimed in the SAME transaction as the primary and is checked\n * against every other site's primary AND twin, both ways round. Without that,\n * org B could connect org A's `www.` sibling, the attach would answer\n * `already-exists`, and B would be shown a healthy domain that redirects to\n * A's site.\n */\n\n/** Firestore field holding the redirect twin of `cname`. */\nexport const HOST_CNAME_TWIN_FIELD = 'cnameTwin'\n\nexport interface ConnectHostDomainInput {\n hostId: string\n /** Lowercased and validated by `validatePlatformDomain`. */\n domain: string\n actor: HostActivityActor\n /**\n * The `www.`/apex partner to serve as a redirect to `domain`. Must be\n * `www.<domain>` or the name `domain` is `www.` of.\n */\n twin?: string | null\n}\n\nexport type ConnectHostDomainResult =\n | {\n ok: 'connected'\n state: ProjectDomainState\n verification: ProjectDomainStatus['verification']\n conflicts: ProjectDomainStatus['conflicts']\n /** The twin this connect claimed, or null. */\n twin: string | null\n }\n | {\n ok: 'refused'\n /** The HTTP status a route should answer with. */\n status: 404 | 409 | 501 | 502\n /** Customer-facing copy, unchanged from the route that owned it. */\n error: string\n code:\n | 'unknown-site'\n | 'taken'\n | 'not-configured'\n | 'attach-failed'\n | 'held-elsewhere'\n state?: ProjectDomainState\n }\n\nconst NOT_CONFIGURED =\n 'Domain attachment is not configured on this deployment ' +\n '(no domain provider — set AGLYN_DOMAIN_PROVIDER).'\n\n/**\n * The redirect twin a domain may carry: `www.x` ↔ `x`. Null for anything else,\n * because a twin is a name reserved on the site's behalf and a guess in either\n * direction locks another site out of a name it never chose.\n */\nexport function customDomainTwinOf(domain: string, twin: string): boolean {\n const primary = domain.trim().toLowerCase()\n const other = twin.trim().toLowerCase()\n if (!primary || !other || primary === other) return false\n return other === `www.${primary}` || primary === `www.${other}`\n}\n\n/** Every other site that holds `name` as its primary or its twin. */\nasync function holdersOf(\n tx: FirebaseFirestore.Transaction,\n firestore: FirebaseFirestore.Firestore,\n name: string,\n): Promise<string[]> {\n const [asPrimary, asTwin] = await Promise.all([\n tx.get(firestore.collection('hosts').where('cname', '==', name).limit(2)),\n tx.get(\n firestore\n .collection('hosts')\n .where(HOST_CNAME_TWIN_FIELD, '==', name)\n .limit(2),\n ),\n ])\n return [...asPrimary.docs, ...asTwin.docs].map((snapshot) => snapshot.id)\n}\n\n/** Claims, attaches and finishes `domain` for `hostId`. Never throws. */\nexport async function connectHostCustomDomain(\n input: ConnectHostDomainInput,\n): Promise<ConnectHostDomainResult> {\n const { hostId, domain, actor } = input\n const twin =\n input.twin && customDomainTwinOf(domain, input.twin)\n ? input.twin.trim().toLowerCase()\n : null\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return {\n ok: 'refused',\n status: 404,\n code: 'unknown-site',\n error: 'Unknown site',\n }\n }\n const orgId = String(hostSnapshot.get('orgId') ?? '')\n\n // Claiming the domain and persisting `host.cname` happen in ONE\n // transaction (AGL-743). The write used to be a client-side `updateDoc`\n // that ran BEFORE this check, so losing the 409 still left the losing host\n // holding the domain — and `get-host.ts` then resolved the duplicate by\n // Firestore document order, i.e. one org could be served on another org's\n // domain. A cross-document invariant cannot be enforced from the client, so\n // this is the only writer of `cname`.\n const claimed = await firestore.runTransaction(async (tx) => {\n const names = twin ? [domain, twin] : [domain]\n for (const name of names) {\n const holders = await holdersOf(tx, firestore, name)\n if (holders.some((id) => id !== hostId)) return false\n }\n tx.set(\n hostRef,\n {\n cname: domain,\n [HOST_CNAME_TWIN_FIELD]: twin ?? firebaseAdmin.firestore.FieldValue.delete(),\n },\n { merge: true },\n )\n return true\n })\n if (!claimed) {\n return {\n ok: 'refused',\n status: 409,\n code: 'taken',\n error: 'That domain is already connected to another site',\n }\n }\n // Every member's row of this site carries the domain for the Sites list's\n // search and its Custom domain filter (AGL-3321, `membershipRow`), so the\n // rows follow the write. Best-effort, as the rename's re-sync is: a row\n // left behind is re-derived by the next re-sync of this site.\n if (orgId) {\n await syncHostProjectionForMembers(orgId, hostId).catch(() => undefined)\n }\n // A domain that wears a brand (`paypal-secure.com`) goes to staff in the\n // abuse queue — flagged, not refused (AGL-3356). Never throws.\n await flagLookalikeCustomDomain({ hostId, orgId: orgId || null, domain })\n\n const markPending = () =>\n hostRef\n .set({ cnameAttachmentPending: true }, { merge: true })\n .catch(() => undefined)\n\n // Ask the provider whether this deployment can register a name at all,\n // rather than testing one vendor's credentials. A self-host behind its own\n // proxy answers yes; a deployment that leaves names to somebody else\n // answers no, and the wizard says so instead of reporting an outage.\n if (!domainProvider().configured('tenant')) {\n // Backfill path (AGL-166): remember the attachment never happened so the\n // wizard can show it honestly and offer a retry.\n await markPending()\n return { ok: 'refused', status: 501, code: 'not-configured', error: NOT_CONFIGURED }\n }\n\n // The `already-exists` tolerance lives in the provider, not here: a name\n // already registered is success for a create path and a retry alike.\n const attach = await attachProjectDomain(domain, {}, 'tenant')\n if (attach.outcome === 'skipped') {\n // Configured, and still nothing registered — a provider that does not\n // manage this particular name. Same honest answer as no provider at all.\n await markPending()\n return { ok: 'refused', status: 501, code: 'not-configured', error: NOT_CONFIGURED }\n }\n if (attach.outcome === 'failed') {\n await markPending()\n return {\n ok: 'refused',\n status: 502,\n code: 'attach-failed',\n error: attach.detail ?? 'Attach failed at the platform',\n }\n }\n\n // What the registration said is not what the customer gets (AGL-1913).\n //\n // - `already-exists` was tolerated above as idempotency, but it is also the\n // answer when the name is registered to a DIFFERENT deployment.\n // `projectDomainStatus` asks whether the name is on OUR deployment rather\n // than inferring it from the tolerated outcome.\n // - A provider accepts a name whose apex belongs to another account and\n // then withholds routing and the certificate until a TXT challenge is\n // answered.\n //\n // `certificate-pending` is NOT serving (AGL-1996): treating it as live\n // registered the edge redirect before a certificate existed, so the site\n // lost BOTH addresses. `admin/finish-domain-attachments` re-probes and\n // completes it without a human (AGL-2010).\n const status = await projectDomainStatus(domain, { scope: 'tenant' })\n const serves = domainStateServes(status.state)\n if (status.state === 'not-attached') {\n await markPending()\n return {\n ok: 'refused',\n status: 409,\n code: 'held-elsewhere',\n error:\n 'That domain is already registered to another account on our ' +\n 'hosting platform, so it could not be attached. Contact support ' +\n 'with the domain name.',\n state: status.state,\n }\n }\n await hostRef\n .set(\n {\n cnameAttachmentPending: serves\n ? firebaseAdmin.firestore.FieldValue.delete()\n : // Not a lie about the attach: it landed. But the field is what\n // `liveCustomDomain` reads to decide whether it is safe to send\n // visitors here, and a domain awaiting an ownership challenge or\n // pointed elsewhere is exactly what that guard exists for.\n true,\n },\n { merge: true },\n )\n .catch(() => undefined)\n\n // Query-preserving edge redirect from the platform subdomain (AGL-1273),\n // only once the domain actually serves — the edge-level twin of\n // `liveCustomDomain`'s refusal on `cnameAttachmentPending`.\n const subdomain = String(hostSnapshot.get('subdomain') ?? '')\n .trim()\n .toLowerCase()\n if (subdomain && serves) {\n const redirected = await upsertSubdomainRedirect({\n subdomain,\n target: domain,\n }).catch(() => false)\n await hostRef\n .set(\n redirected\n ? { subdomainRedirectPending: firebaseAdmin.firestore.FieldValue.delete() }\n : { subdomainRedirectPending: true },\n { merge: true },\n )\n .catch(() => undefined)\n }\n\n // The twin forwards to the primary, so it is registered whether or not the\n // primary serves yet: a redirect to a name still issuing its certificate is\n // the same wait the visitor would have on the primary itself.\n if (twin) {\n const twinned = await upsertCustomDomainTwin({ twin, target: domain }).catch(\n () => false,\n )\n await hostRef\n .set(\n twinned\n ? { cnameTwinPending: firebaseAdmin.firestore.FieldValue.delete() }\n : { cnameTwinPending: true },\n { merge: true },\n )\n .catch(() => undefined)\n }\n\n // The site's public address changed hands (AGL-118). One entry, at the\n // single terminal success.\n await logHostActivity(hostId, actor, 'Attached a custom domain', {\n type: 'host',\n id: hostId,\n name: domain,\n })\n // Plugins that register the domain somewhere of their own — commerce's\n // Stripe payment method domains, so Apple Pay shows on it (AGL-3629).\n // After the claim and the attach, so the name is this site's; isolated, so\n // a plugin that fails cannot fail the connect.\n await runPluginEventHandlers('host.domain.attached', {\n orgId: orgId || null,\n hostId,\n domain,\n })\n return {\n ok: 'connected',\n state: status.state,\n verification: status.verification,\n conflicts: status.conflicts,\n twin,\n }\n}\n\n/**\n * Releases a site's twin from the tenant deployment. The primary has its own\n * release in `/api/domains/detach`; the twin rides along so it can never\n * outlive the name it forwards to.\n */\nexport async function releaseCustomDomainTwin(\n twin: string | null | undefined,\n): Promise<boolean> {\n const name = String(twin ?? '').trim().toLowerCase()\n if (!name) return true\n const released = await detachProjectDomain(name, 'tenant')\n return released.outcome !== 'failed'\n}\n\nexport type DisconnectHostDomainResult =\n | {\n ok: 'released'\n /** The name released, for the caller's cache work. */\n domain: string\n /** The site's platform subdomain, which serves again. */\n subdomain: string\n }\n /** Nothing to release: the caller's desired end state already holds. */\n | { ok: 'already-clear' }\n | {\n ok: 'refused'\n status: 404 | 502\n code: 'unknown-site' | 'detach-failed'\n error: string\n }\n\n/**\n * Releases a site's custom domain (AGL-742): removes it from the tenant\n * deployment, puts the platform subdomain back to serving, releases the twin,\n * clears the claim, logs it and tells plugins — the sequence\n * `/api/domains/detach` ran inline, here so a plugin can release a name it\n * bought once that name stops being the site's (it expired, or moved away).\n *\n * Deliberately does NOT touch DNS: a connected domain's records live in the\n * customer's own zone.\n *\n * Cache work is the caller's, after this returns: the console's\n * `revalidateHostAliases` drops the tenant's `cname--` alias entry, and a\n * caller without it degrades to the cache's TTL.\n */\nexport async function disconnectHostCustomDomain(input: {\n hostId: string\n actor: HostActivityActor\n reason?: 'detached' | 'site-deleted'\n}): Promise<DisconnectHostDomainResult> {\n const { hostId, actor } = input\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return { ok: 'refused', status: 404, code: 'unknown-site', error: 'Unknown site' }\n }\n const domain = String(hostSnapshot.get('cname') ?? '')\n .trim()\n .toLowerCase()\n if (!domain) return { ok: 'already-clear' }\n\n // `not-found` is success — the desired end state already holds — mirroring\n // how attach tolerates a name already registered.\n const released = await detachProjectDomain(domain, 'tenant')\n if (released.outcome === 'failed') {\n // Recorded so a retry (and a staff view) can see a release that never\n // landed; `cname` is KEPT, because the name is still attached.\n await hostRef\n .set({ cnameDetachmentPending: true }, { merge: true })\n .catch(() => undefined)\n return {\n ok: 'refused',\n status: 502,\n code: 'detach-failed',\n error: released.detail ?? 'Detach failed at the platform',\n }\n }\n\n // The platform subdomain was registered as a REDIRECT to the domain\n // (AGL-1273), and the redirect is a property of its registration, so it is\n // dropped with the registration and put back plain — which is what makes\n // it serve again. A `not-found` means a wildcard serves it and it carried\n // no redirect of its own; registering one there would create an entry\n // this never removed.\n const subdomain = String(hostSnapshot.get('subdomain') ?? '')\n .trim()\n .toLowerCase()\n if (subdomain) {\n const platformName = `${subdomain}.${TENANT_APEX}`\n const removed = await detachProjectDomain(platformName, 'tenant')\n if (removed.outcome === 'detached') {\n await attachProjectDomain(platformName, {}, 'tenant')\n }\n }\n\n // The twin forwards to the name just released, so it goes with it.\n // Best-effort: a twin left on the deployment redirects to a name that no\n // longer serves, which is a dead end but not another site — and the claim\n // below is cleared either way, so no site can be shown the name as its own.\n await releaseCustomDomainTwin(hostSnapshot.get(HOST_CNAME_TWIN_FIELD)).catch(\n () => false,\n )\n await hostRef.set(\n {\n cname: firebaseAdmin.firestore.FieldValue.delete(),\n [HOST_CNAME_TWIN_FIELD]: firebaseAdmin.firestore.FieldValue.delete(),\n cnameTwinPending: firebaseAdmin.firestore.FieldValue.delete(),\n cnameAttachmentPending: firebaseAdmin.firestore.FieldValue.delete(),\n cnameDetachmentPending: firebaseAdmin.firestore.FieldValue.delete(),\n subdomainRedirectPending: firebaseAdmin.firestore.FieldValue.delete(),\n },\n { merge: true },\n )\n // The Sites list's rows of this site drop the domain from their search and\n // read \"no custom domain\" again (AGL-3321). Best-effort.\n const orgId = String(hostSnapshot.get('orgId') ?? '')\n if (orgId) {\n await syncHostProjectionForMembers(orgId, hostId).catch(() => undefined)\n }\n // THE EVENT IS `cname` LEAVING THE DOCUMENT (AGL-118), which is the write\n // directly above — the mirror image of where connect logs. The refusals\n // above write no entry: a failed release still holds the name, and a row\n // there would say the customer released a domain we are still holding.\n await logHostActivity(hostId, actor, 'Released the custom domain', {\n type: 'host',\n id: hostId,\n name: domain,\n })\n // The name no longer serves this site: plugins undo what they registered\n // for it (AGL-3629), each checking no other site still serves it.\n await runPluginEventHandlers('host.domain.released', {\n orgId: orgId || null,\n hostId,\n domain,\n reason: input.reason ?? 'detached',\n })\n return { ok: 'released', domain, subdomain }\n}\n"],"names":["TENANT_APEX","runPluginEventHandlers","domainProvider","domainStateServes","firebaseAdmin","flagLookalikeCustomDomain","syncHostProjectionForMembers","upsertCustomDomainTwin","upsertSubdomainRedirect","logHostActivity","attachProjectDomain","detachProjectDomain","projectDomainStatus","HOST_CNAME_TWIN_FIELD","NOT_CONFIGURED","customDomainTwinOf","domain","twin","primary","trim","toLowerCase","other","holdersOf","tx","firestore","name","asPrimary","asTwin","Promise","all","get","collection","where","limit","docs","map","snapshot","id","connectHostCustomDomain","input","hostSnapshot","hostId","actor","app","hostRef","doc","exists","ok","status","code","error","orgId","String","claimed","runTransaction","names","holders","some","set","cname","FieldValue","delete","merge","catch","undefined","markPending","cnameAttachmentPending","configured","attach","outcome","detail","scope","serves","state","subdomain","redirected","target","subdomainRedirectPending","twinned","cnameTwinPending","type","verification","conflicts","releaseCustomDomainTwin","released","disconnectHostCustomDomain","cnameDetachmentPending","platformName","removed","reason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,WAAW,QAAQ,qCAAoC;AAChE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SACEC,cAAc,EACdC,iBAAiB,QAGZ,uBAAmB;AAC1B,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,yBAAyB,QAAQ,0BAAsB;AAChE,SAASC,4BAA4B,QAAQ,wBAAoB;AACjE,SACEC,sBAAsB,EACtBC,uBAAuB,QAClB,+BAA2B;AAClC,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,mBAAmB,QACd,yBAAqB;AAE5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GAED,0DAA0D,GAC1D,OAAO,MAAMC,wBAAwB,YAAW;AAsChD,MAAMC,iBACJ,4DACA;AAEF;;;;CAIC,GACD,OAAO,SAASC,mBAAmBC,MAAc,EAAEC,IAAY;IAC7D,MAAMC,UAAUF,OAAOG,IAAI,GAAGC,WAAW;IACzC,MAAMC,QAAQJ,KAAKE,IAAI,GAAGC,WAAW;IACrC,IAAI,CAACF,WAAW,CAACG,SAASH,YAA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AAI;QAAY/B;QAAQ0D;IAAU;AAC7C"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-custom-domain.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 type { HostActivityActor } from '@aglyn/aglyn/app-utils/activity-presenter'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport { runPluginEventHandlers } from '@aglyn/aglyn/plugin-manager/plugin-events'\nimport {\n domainProvider,\n domainStateServes,\n type ProjectDomainState,\n type ProjectDomainStatus,\n} from './domain-provider'\nimport firebaseAdmin from './firebase-admin'\nimport { flagLookalikeCustomDomain } from './hosted-page-review'\nimport { syncHostProjectionForMembers } from './host-memberships'\nimport {\n upsertCustomDomainTwin,\n upsertSubdomainRedirect,\n} from './custom-domain-redirects'\nimport { logHostActivity } from './organizations'\nimport {\n attachProjectDomain,\n detachProjectDomain,\n projectDomainStatus,\n} from './workspace-domains'\n\n/**\n * CONNECTING A NAME TO A SITE, as one server function (AGL-3961).\n *\n * This is the sequence `/api/domains/attach` ran inline: claim the name in a\n * transaction, attach it to the tenant deployment, probe what the platform\n * actually did, record the shortfall, point the platform subdomain at it, log\n * it, and tell plugins. It lives here so a caller with no ID token — a plugin\n * that bought the name, a sweeper finishing an order — connects a domain\n * through exactly the same claim the customer's own button uses. A second copy\n * of the claim is how two sites end up holding one name (AGL-743).\n *\n * Authorization is the CALLER's: the route checks the admin role, lockdown and\n * the plan before it gets here, and a plugin checks its own. This function\n * assumes the caller may connect `domain` to `hostId` and that `domain` has\n * already been through `validatePlatformDomain`.\n *\n * ## The twin\n *\n * `twin` is the `www.`/apex partner of the domain, served as a REDIRECT to it\n * (AGL-1311 memo §5.2). It is opt-in, and every connect path now opts in: a\n * bought domain, a provider applying a Domain Connect template, and the manual\n * card (AGL-4134). The card cannot promise the twin's DNS resolves, but a twin\n * nobody points at simply never receives a visitor, while a twin left off a\n * domain with both records makes one of its two addresses a dead end.\n *\n * The twin is claimed in the SAME transaction as the primary and is checked\n * against every other site's primary AND twin, both ways round. Without that,\n * org B could connect org A's `www.` sibling, the attach would answer\n * `already-exists`, and B would be shown a healthy domain that redirects to\n * A's site.\n */\n\n/** Firestore field holding the redirect twin of `cname`. */\nexport const HOST_CNAME_TWIN_FIELD = 'cnameTwin'\n\nexport interface ConnectHostDomainInput {\n hostId: string\n /** Lowercased and validated by `validatePlatformDomain`. */\n domain: string\n actor: HostActivityActor\n /**\n * The `www.`/apex partner to serve as a redirect to `domain`. Must be\n * `www.<domain>` or the name `domain` is `www.` of.\n */\n twin?: string | null\n}\n\nexport type ConnectHostDomainResult =\n | {\n ok: 'connected'\n state: ProjectDomainState\n verification: ProjectDomainStatus['verification']\n conflicts: ProjectDomainStatus['conflicts']\n /** The twin this connect claimed, or null. */\n twin: string | null\n }\n | {\n ok: 'refused'\n /** The HTTP status a route should answer with. */\n status: 404 | 409 | 501 | 502\n /** Customer-facing copy, unchanged from the route that owned it. */\n error: string\n code:\n | 'unknown-site'\n | 'taken'\n | 'not-configured'\n | 'attach-failed'\n | 'held-elsewhere'\n state?: ProjectDomainState\n }\n\nconst NOT_CONFIGURED =\n 'Domain attachment is not configured on this deployment ' +\n '(no domain provider — set AGLYN_DOMAIN_PROVIDER).'\n\n/**\n * The redirect twin a domain may carry: `www.x` ↔ `x`. Null for anything else,\n * because a twin is a name reserved on the site's behalf and a guess in either\n * direction locks another site out of a name it never chose.\n */\nexport function customDomainTwinOf(domain: string, twin: string): boolean {\n const primary = domain.trim().toLowerCase()\n const other = twin.trim().toLowerCase()\n if (!primary || !other || primary === other) return false\n return other === `www.${primary}` || primary === `www.${other}`\n}\n\n/** Every other site that holds `name` as its primary or its twin. */\nasync function holdersOf(\n tx: FirebaseFirestore.Transaction,\n firestore: FirebaseFirestore.Firestore,\n name: string,\n): Promise<string[]> {\n const [asPrimary, asTwin] = await Promise.all([\n tx.get(firestore.collection('hosts').where('cname', '==', name).limit(2)),\n tx.get(\n firestore\n .collection('hosts')\n .where(HOST_CNAME_TWIN_FIELD, '==', name)\n .limit(2),\n ),\n ])\n return [...asPrimary.docs, ...asTwin.docs].map((snapshot) => snapshot.id)\n}\n\n/** Claims, attaches and finishes `domain` for `hostId`. Never throws. */\nexport async function connectHostCustomDomain(\n input: ConnectHostDomainInput,\n): Promise<ConnectHostDomainResult> {\n const { hostId, domain, actor } = input\n const twin =\n input.twin && customDomainTwinOf(domain, input.twin)\n ? input.twin.trim().toLowerCase()\n : null\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return {\n ok: 'refused',\n status: 404,\n code: 'unknown-site',\n error: 'Unknown site',\n }\n }\n const orgId = String(hostSnapshot.get('orgId') ?? '')\n\n // Claiming the domain and persisting `host.cname` happen in ONE\n // transaction (AGL-743). The write used to be a client-side `updateDoc`\n // that ran BEFORE this check, so losing the 409 still left the losing host\n // holding the domain — and `get-host.ts` then resolved the duplicate by\n // Firestore document order, i.e. one org could be served on another org's\n // domain. A cross-document invariant cannot be enforced from the client, so\n // this is the only writer of `cname`.\n const claimed = await firestore.runTransaction(async (tx) => {\n const names = twin ? [domain, twin] : [domain]\n for (const name of names) {\n const holders = await holdersOf(tx, firestore, name)\n if (holders.some((id) => id !== hostId)) return false\n }\n tx.set(\n hostRef,\n {\n cname: domain,\n [HOST_CNAME_TWIN_FIELD]: twin ?? firebaseAdmin.firestore.FieldValue.delete(),\n },\n { merge: true },\n )\n return true\n })\n if (!claimed) {\n return {\n ok: 'refused',\n status: 409,\n code: 'taken',\n error: 'That domain is already connected to another site',\n }\n }\n // Every member's row of this site carries the domain for the Sites list's\n // search and its Custom domain filter (AGL-3321, `membershipRow`), so the\n // rows follow the write. Best-effort, as the rename's re-sync is: a row\n // left behind is re-derived by the next re-sync of this site.\n if (orgId) {\n await syncHostProjectionForMembers(orgId, hostId).catch(() => undefined)\n }\n // A domain that wears a brand (`paypal-secure.com`) goes to staff in the\n // abuse queue — flagged, not refused (AGL-3356). Never throws.\n await flagLookalikeCustomDomain({ hostId, orgId: orgId || null, domain })\n\n const markPending = () =>\n hostRef\n .set({ cnameAttachmentPending: true }, { merge: true })\n .catch(() => undefined)\n\n // Ask the provider whether this deployment can register a name at all,\n // rather than testing one vendor's credentials. A self-host behind its own\n // proxy answers yes; a deployment that leaves names to somebody else\n // answers no, and the wizard says so instead of reporting an outage.\n if (!domainProvider().configured('tenant')) {\n // Backfill path (AGL-166): remember the attachment never happened so the\n // wizard can show it honestly and offer a retry.\n await markPending()\n return { ok: 'refused', status: 501, code: 'not-configured', error: NOT_CONFIGURED }\n }\n\n // The `already-exists` tolerance lives in the provider, not here: a name\n // already registered is success for a create path and a retry alike.\n const attach = await attachProjectDomain(domain, {}, 'tenant')\n if (attach.outcome === 'skipped') {\n // Configured, and still nothing registered — a provider that does not\n // manage this particular name. Same honest answer as no provider at all.\n await markPending()\n return { ok: 'refused', status: 501, code: 'not-configured', error: NOT_CONFIGURED }\n }\n if (attach.outcome === 'failed') {\n await markPending()\n return {\n ok: 'refused',\n status: 502,\n code: 'attach-failed',\n error: attach.detail ?? 'Attach failed at the platform',\n }\n }\n\n // What the registration said is not what the customer gets (AGL-1913).\n //\n // - `already-exists` was tolerated above as idempotency, but it is also the\n // answer when the name is registered to a DIFFERENT deployment.\n // `projectDomainStatus` asks whether the name is on OUR deployment rather\n // than inferring it from the tolerated outcome.\n // - A provider accepts a name whose apex belongs to another account and\n // then withholds routing and the certificate until a TXT challenge is\n // answered.\n //\n // `certificate-pending` is NOT serving (AGL-1996): treating it as live\n // registered the edge redirect before a certificate existed, so the site\n // lost BOTH addresses. `admin/finish-domain-attachments` re-probes and\n // completes it without a human (AGL-2010).\n const status = await projectDomainStatus(domain, { scope: 'tenant' })\n const serves = domainStateServes(status.state)\n if (status.state === 'not-attached') {\n await markPending()\n return {\n ok: 'refused',\n status: 409,\n code: 'held-elsewhere',\n error:\n 'That domain is already registered to another account on our ' +\n 'hosting platform, so it could not be attached. Contact support ' +\n 'with the domain name.',\n state: status.state,\n }\n }\n await hostRef\n .set(\n {\n cnameAttachmentPending: serves\n ? firebaseAdmin.firestore.FieldValue.delete()\n : // Not a lie about the attach: it landed. But the field is what\n // `liveCustomDomain` reads to decide whether it is safe to send\n // visitors here, and a domain awaiting an ownership challenge or\n // pointed elsewhere is exactly what that guard exists for.\n true,\n },\n { merge: true },\n )\n .catch(() => undefined)\n\n // Query-preserving edge redirect from the platform subdomain (AGL-1273),\n // only once the domain actually serves — the edge-level twin of\n // `liveCustomDomain`'s refusal on `cnameAttachmentPending`.\n const subdomain = String(hostSnapshot.get('subdomain') ?? '')\n .trim()\n .toLowerCase()\n if (subdomain && serves) {\n const redirected = await upsertSubdomainRedirect({\n subdomain,\n target: domain,\n }).catch(() => false)\n await hostRef\n .set(\n redirected\n ? { subdomainRedirectPending: firebaseAdmin.firestore.FieldValue.delete() }\n : { subdomainRedirectPending: true },\n { merge: true },\n )\n .catch(() => undefined)\n }\n\n // The twin forwards to the primary, so it is registered whether or not the\n // primary serves yet: a redirect to a name still issuing its certificate is\n // the same wait the visitor would have on the primary itself.\n if (twin) {\n const twinned = await upsertCustomDomainTwin({ twin, target: domain }).catch(\n () => false,\n )\n await hostRef\n .set(\n twinned\n ? { cnameTwinPending: firebaseAdmin.firestore.FieldValue.delete() }\n : { cnameTwinPending: true },\n { merge: true },\n )\n .catch(() => undefined)\n }\n\n // The site's public address changed hands (AGL-118). One entry, at the\n // single terminal success.\n await logHostActivity(hostId, actor, 'Attached a custom domain', {\n type: 'host',\n id: hostId,\n name: domain,\n })\n // Plugins that register the domain somewhere of their own — commerce's\n // Stripe payment method domains, so Apple Pay shows on it (AGL-3629).\n // After the claim and the attach, so the name is this site's; isolated, so\n // a plugin that fails cannot fail the connect.\n await runPluginEventHandlers('host.domain.attached', {\n orgId: orgId || null,\n hostId,\n domain,\n })\n return {\n ok: 'connected',\n state: status.state,\n verification: status.verification,\n conflicts: status.conflicts,\n twin,\n }\n}\n\n/**\n * Releases a site's twin from the tenant deployment. The primary has its own\n * release in `/api/domains/detach`; the twin rides along so it can never\n * outlive the name it forwards to.\n */\nexport async function releaseCustomDomainTwin(\n twin: string | null | undefined,\n): Promise<boolean> {\n const name = String(twin ?? '').trim().toLowerCase()\n if (!name) return true\n const released = await detachProjectDomain(name, 'tenant')\n return released.outcome !== 'failed'\n}\n\nexport type DisconnectHostDomainResult =\n | {\n ok: 'released'\n /** The name released, for the caller's cache work. */\n domain: string\n /** The site's platform subdomain, which serves again. */\n subdomain: string\n }\n /** Nothing to release: the caller's desired end state already holds. */\n | { ok: 'already-clear' }\n | {\n ok: 'refused'\n status: 404 | 502\n code: 'unknown-site' | 'detach-failed'\n error: string\n }\n\n/**\n * Releases a site's custom domain (AGL-742): removes it from the tenant\n * deployment, puts the platform subdomain back to serving, releases the twin,\n * clears the claim, logs it and tells plugins — the sequence\n * `/api/domains/detach` ran inline, here so a plugin can release a name it\n * bought once that name stops being the site's (it expired, or moved away).\n *\n * Deliberately does NOT touch DNS: a connected domain's records live in the\n * customer's own zone.\n *\n * Cache work is the caller's, after this returns: the console's\n * `revalidateHostAliases` drops the tenant's `cname--` alias entry, and a\n * caller without it degrades to the cache's TTL.\n */\nexport async function disconnectHostCustomDomain(input: {\n hostId: string\n actor: HostActivityActor\n reason?: 'detached' | 'site-deleted'\n}): Promise<DisconnectHostDomainResult> {\n const { hostId, actor } = input\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return { ok: 'refused', status: 404, code: 'unknown-site', error: 'Unknown site' }\n }\n const domain = String(hostSnapshot.get('cname') ?? '')\n .trim()\n .toLowerCase()\n if (!domain) return { ok: 'already-clear' }\n\n // `not-found` is success — the desired end state already holds — mirroring\n // how attach tolerates a name already registered.\n const released = await detachProjectDomain(domain, 'tenant')\n if (released.outcome === 'failed') {\n // Recorded so a retry (and a staff view) can see a release that never\n // landed; `cname` is KEPT, because the name is still attached.\n await hostRef\n .set({ cnameDetachmentPending: true }, { merge: true })\n .catch(() => undefined)\n return {\n ok: 'refused',\n status: 502,\n code: 'detach-failed',\n error: released.detail ?? 'Detach failed at the platform',\n }\n }\n\n // The platform subdomain was registered as a REDIRECT to the domain\n // (AGL-1273), and the redirect is a property of its registration, so it is\n // dropped with the registration and put back plain — which is what makes\n // it serve again. A `not-found` means a wildcard serves it and it carried\n // no redirect of its own; registering one there would create an entry\n // this never removed.\n const subdomain = String(hostSnapshot.get('subdomain') ?? '')\n .trim()\n .toLowerCase()\n if (subdomain) {\n const platformName = `${subdomain}.${TENANT_APEX}`\n const removed = await detachProjectDomain(platformName, 'tenant')\n if (removed.outcome === 'detached') {\n await attachProjectDomain(platformName, {}, 'tenant')\n }\n }\n\n // The twin forwards to the name just released, so it goes with it.\n // Best-effort: a twin left on the deployment redirects to a name that no\n // longer serves, which is a dead end but not another site — and the claim\n // below is cleared either way, so no site can be shown the name as its own.\n await releaseCustomDomainTwin(hostSnapshot.get(HOST_CNAME_TWIN_FIELD)).catch(\n () => false,\n )\n await hostRef.set(\n {\n cname: firebaseAdmin.firestore.FieldValue.delete(),\n [HOST_CNAME_TWIN_FIELD]: firebaseAdmin.firestore.FieldValue.delete(),\n cnameTwinPending: firebaseAdmin.firestore.FieldValue.delete(),\n cnameAttachmentPending: firebaseAdmin.firestore.FieldValue.delete(),\n cnameDetachmentPending: firebaseAdmin.firestore.FieldValue.delete(),\n subdomainRedirectPending: firebaseAdmin.firestore.FieldValue.delete(),\n },\n { merge: true },\n )\n // The Sites list's rows of this site drop the domain from their search and\n // read \"no custom domain\" again (AGL-3321). Best-effort.\n const orgId = String(hostSnapshot.get('orgId') ?? '')\n if (orgId) {\n await syncHostProjectionForMembers(orgId, hostId).catch(() => undefined)\n }\n // THE EVENT IS `cname` LEAVING THE DOCUMENT (AGL-118), which is the write\n // directly above — the mirror image of where connect logs. The refusals\n // above write no entry: a failed release still holds the name, and a row\n // there would say the customer released a domain we are still holding.\n await logHostActivity(hostId, actor, 'Released the custom domain', {\n type: 'host',\n id: hostId,\n name: domain,\n })\n // The name no longer serves this site: plugins undo what they registered\n // for it (AGL-3629), each checking no other site still serves it.\n await runPluginEventHandlers('host.domain.released', {\n orgId: orgId || null,\n hostId,\n domain,\n reason: input.reason ?? 'detached',\n })\n return { ok: 'released', domain, subdomain }\n}\n"],"names":["TENANT_APEX","runPluginEventHandlers","domainProvider","domainStateServes","firebaseAdmin","flagLookalikeCustomDomain","syncHostProjectionForMembers","upsertCustomDomainTwin","upsertSubdomainRedirect","logHostActivity","attachProjectDomain","detachProjectDomain","projectDomainStatus","HOST_CNAME_TWIN_FIELD","NOT_CONFIGURED","customDomainTwinOf","domain","twin","primary","trim","toLowerCase","other","holdersOf","tx","firestore","name","asPrimary","asTwin","Promise","all","get","collection","where","limit","docs","map","snapshot","id","connectHostCustomDomain","input","hostSnapshot","hostId","actor","app","hostRef","doc","exists","ok","status","code","error","orgId","String","claimed","runTransaction","names","holders","some","set","cname","FieldValue","delete","merge","catch","undefined","markPending","cnameAttachmentPending","configured","attach","outcome","detail","scope","serves","state","subdomain","redirected","target","subdomainRedirectPending","twinned","cnameTwinPending","type","verification","conflicts","releaseCustomDomainTwin","released","disconnectHostCustomDomain","cnameDetachmentPending","platformName","removed","reason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,WAAW,QAAQ,qCAAoC;AAChE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SACEC,cAAc,EACdC,iBAAiB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