@aglyn/tenant-data-admin 1.0.0-beta.270 → 1.0.0-beta.272
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/server/append-only-history-write.d.ts +38 -0
- package/src/lib/server/append-only-history-write.js +60 -0
- package/src/lib/server/append-only-history-write.js.map +1 -0
- package/src/lib/server/billing-addons.d.ts +58 -32
- package/src/lib/server/billing-addons.js +100 -86
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +166 -0
- package/src/lib/server/bundle-links.js +286 -0
- package/src/lib/server/bundle-links.js.map +1 -0
- package/src/lib/server/client-build.d.ts +74 -0
- package/src/lib/server/client-build.js +264 -0
- package/src/lib/server/client-build.js.map +1 -0
- package/src/lib/server/domain-ownership.d.ts +205 -0
- package/src/lib/server/domain-ownership.js +575 -0
- package/src/lib/server/domain-ownership.js.map +1 -0
- package/src/lib/server/erase.d.ts +17 -0
- package/src/lib/server/erase.js +21 -0
- package/src/lib/server/erase.js.map +1 -1
- package/src/lib/server/host-memberships.d.ts +35 -2
- package/src/lib/server/host-memberships.js +63 -2
- package/src/lib/server/host-memberships.js.map +1 -1
- package/src/lib/server/org-billing.d.ts +4 -2
- package/src/lib/server/org-billing.js +5 -0
- package/src/lib/server/org-billing.js.map +1 -1
- package/src/lib/server/site-care-emails.d.ts +53 -0
- package/src/lib/server/site-care-emails.js +97 -0
- package/src/lib/server/site-care-emails.js.map +1 -0
- package/src/lib/server/site-care-inbound.d.ts +123 -0
- package/src/lib/server/site-care-inbound.js +197 -0
- package/src/lib/server/site-care-inbound.js.map +1 -0
- package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
- package/src/lib/server/site-care-project-reconcile.js +211 -0
- package/src/lib/server/site-care-project-reconcile.js.map +1 -0
- package/src/lib/server/site-care-project-stripe.d.ts +114 -0
- package/src/lib/server/site-care-project-stripe.js +305 -0
- package/src/lib/server/site-care-project-stripe.js.map +1 -0
- package/src/lib/server/site-care-projects.d.ts +169 -0
- package/src/lib/server/site-care-projects.js +882 -0
- package/src/lib/server/site-care-projects.js.map +1 -0
- package/src/lib/server/site-care-reconcile.d.ts +81 -0
- package/src/lib/server/site-care-reconcile.js +349 -0
- package/src/lib/server/site-care-reconcile.js.map +1 -0
- package/src/lib/server/site-care-requests.d.ts +243 -0
- package/src/lib/server/site-care-requests.js +1414 -0
- package/src/lib/server/site-care-requests.js.map +1 -0
- package/src/lib/server/site-care-stripe.d.ts +175 -0
- package/src/lib/server/site-care-stripe.js +375 -0
- package/src/lib/server/site-care-stripe.js.map +1 -0
- package/src/lib/server/sso-provisioning.d.ts +6 -0
- package/src/lib/server/sso-provisioning.js +7 -0
- package/src/lib/server/sso-provisioning.js.map +1 -1
- package/src/lib/server/upgrade-proposal.d.ts +40 -1
- package/src/lib/server/upgrade-proposal.js +92 -50
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/tenancy.d.ts +1 -0
- package/src/tenancy.js +2 -0
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/domain-ownership.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 * DOMAIN OWNERSHIP CLAIMS (AGL-3974, parent AGL-3973).\n *\n * \"This workspace proved it controls example.com.\" A site import pulls a\n * person's existing website into Aglyn, and an import is a one-click clone\n * of whatever address is typed, so the content and images are pulled only\n * after the workspace has proved the domain is its own. Payment alone is not\n * a control: the first paying customer was a phisher on a stolen card.\n *\n * ## Why this is not the SSO claim\n *\n * `orgs/{orgId}/ssoDomains/{domain}` (sso-provisioning.ts) is one org per\n * domain, because a verified SSO domain ROUTES every sign-in on it. Owning a\n * site is not exclusive in that way: an agency and its client may both hold\n * a proof for the client's domain, and neither proof routes anything. So the\n * claim here is keyed by (org, domain) and carries no global index:\n * `orgs/{orgId}/domainOwnershipClaims/{domain}`. Rules: an owner or admin of\n * the org reads it (it holds the token they publish); only this module, over\n * the Admin SDK, writes it.\n *\n * ## Three ways to prove it, any one of which is enough\n *\n * - **DNS**: a TXT record `aglyn-domain-verification=<token>` at\n * `_aglyn-challenge.<domain>`, the same host and prefix SSO uses, matched as\n * a whole record (`recordsProveOwnership`).\n * - **Meta tag**: `<meta name=\"aglyn-site-verification\" content=\"<token>\">` on\n * the home page, read by the caller through the site-import crawler's safe\n * fetch and handed in as `readVerificationMeta`; this module never opens a\n * socket to a site.\n * - **Email**: a one-time code sent to an address AT the domain (the person\n * types owner@theirdomain.com). Reading mail there is control of the\n * domain's mail. The code is stored only as an HMAC under the server's\n * signing secret, expires in {@link DOMAIN_OWNERSHIP_CODE_TTL_MS}, and is\n * burned after {@link DOMAIN_OWNERSHIP_CODE_MAX_ATTEMPTS} wrong tries. The\n * HMAC matters because an owner or admin can read the claim document: a\n * plain hash of a six-digit code is reversed by trying a million values.\n *\n * ## Three answers, never two\n *\n * Every check answers `proven`, `not-yet` or `unreachable`. `unreachable`\n * (nobody answered the DNS question, the home page could not be read) is\n * evidence of nothing, the same third state `dns-probe.ts` exists for, and it\n * never demotes a proof already recorded.\n *=========================================*/\n\nimport { createHmac, randomBytes, randomInt } from 'crypto'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { lookupTxt as defaultLookupTxt, type DnsLookupResult } from './dns-probe'\nimport firebaseAdmin from './firebase-admin'\nimport { tokenSigningSecret } from './media-signing'\nimport { safeEqual } from './safe-equal'\nimport {\n challengeValue,\n isPublicEmailDomain,\n recordsProveOwnership,\n SSO_CHALLENGE_PREFIX,\n} from './sso-provisioning'\n\n/** The subcollection under `orgs/{orgId}`; the document id is the domain. */\nexport const DOMAIN_OWNERSHIP_CLAIMS_COLLECTION = 'domainOwnershipClaims'\n\n/** The `name` of the home page meta tag that carries the token. */\nexport const DOMAIN_OWNERSHIP_META_NAME = 'aglyn-site-verification'\n\n/** The system email that carries the one-time code. */\nexport const DOMAIN_OWNERSHIP_CODE_EMAIL_KEY = 'domain-ownership-code'\n\n/** How long an emailed code works. */\nexport const DOMAIN_OWNERSHIP_CODE_TTL_MS = 15 * 60 * 1000\n\n/** Wrong codes allowed before the code is burned and a new one must be sent. */\nexport const DOMAIN_OWNERSHIP_CODE_MAX_ATTEMPTS = 5\n\n/** The least time between two codes for one claim. */\nexport const DOMAIN_OWNERSHIP_CODE_RESEND_MS = 60 * 1000\n\n/** Codes one workspace may send in an hour, across every claim. */\nexport const DOMAIN_OWNERSHIP_CODES_PER_ORG_PER_HOUR = 10\n\n/** Codes one address may receive in an hour, from every workspace. */\nexport const DOMAIN_OWNERSHIP_CODES_PER_ADDRESS_PER_HOUR = 5\n\n/**\n * How long a proof stands before an import asks for it again. A domain can\n * lapse and be bought by someone else; a month is short enough that the new\n * owner's content is not imported on the old owner's proof.\n */\nexport const DOMAIN_OWNERSHIP_PROOF_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\nconst DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/\nconst EMAIL_LOCAL_PATTERN = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}$/i\n\nexport type DomainOwnershipMethod = 'dns' | 'meta' | 'email'\n\n/** What one check found. `unreachable` is evidence in neither direction. */\nexport type DomainOwnershipCheckStatus = 'proven' | 'not-yet' | 'unreachable'\n\n/** The stored document. Times are epoch milliseconds. */\nexport interface DomainOwnershipClaimDoc {\n domain: string\n token: string\n status: 'pending' | 'proven'\n createdAt: number\n createdBy: string\n provenMethod?: DomainOwnershipMethod\n provenAt?: number\n /** The record host, the page, or the address the proof came from. */\n provenDetail?: string\n lastCheckedAt?: number\n lastChecks?: Partial<Record<DomainOwnershipMethod, DomainOwnershipCheckStatus>>\n emailCode?: {\n address: string\n /** HMAC-SHA256 of the code, keyed by the signing secret. Never the code. */\n hash: string\n sentAt: number\n expiresAt: number\n attempts: number\n } | null\n}\n\n/** What the console is shown: the instructions, never the code's hash. */\nexport interface DomainOwnershipClaimView {\n domain: string\n status: 'pending' | 'proven'\n /** False once a proof is older than {@link DOMAIN_OWNERSHIP_PROOF_MAX_AGE_MS}. */\n current: boolean\n provenMethod: DomainOwnershipMethod | null\n provenAt: number | null\n provenDetail: string | null\n lastChecks: Partial<Record<DomainOwnershipMethod, DomainOwnershipCheckStatus>>\n dns: { host: string; type: 'TXT'; value: string }\n meta: { name: string; content: string; tag: string }\n email: {\n /** Addresses must end in `@<domain>`. */\n domain: string\n pendingAddress: string | null\n expiresAt: number | null\n attemptsLeft: number | null\n }\n}\n\nexport interface DomainOwnershipCheckResult {\n method: DomainOwnershipMethod\n status: DomainOwnershipCheckStatus\n /** A sentence for the person: what was looked at, and what to do next. */\n message: string\n claim: DomainOwnershipClaimView\n}\n\n/** `{ value, error }`, both keys always present, as `validateSsoDomain` does. */\nexport interface OwnershipDomainCheck {\n domain: string | null\n error: string | null\n}\n\n/** A home page's `aglyn-site-verification` values, read by the caller. */\nexport type ReadVerificationMeta = (\n domain: string,\n) => Promise<{ answered: boolean; values: string[]; url?: string }>\n\n/** Sends the code; the default is {@link deliverDomainOwnershipCode}. */\nexport type DeliverDomainOwnershipCode = (input: {\n orgId: string\n org: Record<string, unknown> | null\n domain: string\n address: string\n code: string\n expiresInMinutes: number\n}) => Promise<{ sent: boolean; status?: number; error?: string }>\n\nexport interface DomainOwnershipDeps {\n firestore?: FirebaseFirestore.Firestore\n lookupTxt?: (host: string) => Promise<DnsLookupResult<string>>\n readVerificationMeta?: ReadVerificationMeta\n deliverCode?: DeliverDomainOwnershipCode\n now?: () => number\n /** The HMAC key for codes; the default is `TOKEN_SIGNING_SECRET`. */\n secret?: () => string\n mintToken?: () => string\n mintCode?: () => string\n}\n\n/*------------------------------------------\n * Pure helpers\n *-----------------------------------------*/\n\n/**\n * The domain a claim is about: lowercased, any scheme, path, port or address\n * prefix a person pasted removed, and a leading `www.` folded into the bare\n * name, because the site's two names are one site to its owner and the\n * crawler treats them as one origin.\n */\nexport function normalizeOwnershipDomain(input: string): OwnershipDomainCheck {\n let raw = String(input ?? '').trim().toLowerCase()\n const at = raw.lastIndexOf('@')\n if (at >= 0 && !raw.includes('/')) raw = raw.slice(at + 1)\n raw = raw.replace(/^[a-z][a-z0-9+.-]*:\\/\\//, '')\n raw = raw.split(/[/?#]/)[0] ?? ''\n raw = raw.replace(/:\\d+$/, '').replace(/\\.+$/, '').replace(/^www\\./, '')\n if (!raw || !DOMAIN_PATTERN.test(raw)) {\n return { domain: null, error: 'Enter your website’s address, for example example.com' }\n }\n if (isPublicEmailDomain(raw)) {\n return {\n domain: null,\n error: 'That is an email provider’s domain, not a website you own.',\n }\n }\n if (lookalikeBrandForHost(raw)) {\n return { domain: null, error: 'That address looks like another company’s website.' }\n }\n return { domain: raw, error: null }\n}\n\n/** The TXT record host for a domain. */\nexport function domainOwnershipRecordHost(domain: string): string {\n return `${SSO_CHALLENGE_PREFIX}.${domain}`\n}\n\n/** The meta tag a person pastes into their home page's `<head>`. */\nexport function domainOwnershipMetaTag(token: string): string {\n return `<meta name=\"${DOMAIN_OWNERSHIP_META_NAME}\" content=\"${token}\">`\n}\n\n/** Exact, whole-value match, for the reason `recordsProveOwnership` gives. */\nexport function metaValuesProveOwnership(values: readonly string[], token: string): boolean {\n if (!token) return false\n return values.some((value) => safeEqual(String(value ?? '').trim(), token))\n}\n\n/**\n * The address a code may go to: a plausible mailbox whose domain IS the\n * claim's domain (the `www.` twin included), and nothing else. A parent or a\n * sibling domain proves nothing about this one.\n */\nexport function ownershipEmailAddress(input: string, domain: string): string | null {\n const address = String(input ?? '').trim().toLowerCase()\n const at = address.lastIndexOf('@')\n if (at <= 0) return null\n const local = address.slice(0, at)\n const host = address.slice(at + 1)\n if (!EMAIL_LOCAL_PATTERN.test(local) || local.startsWith('.') || local.endsWith('.')) {\n return null\n }\n if (host !== domain && host !== `www.${domain}`) return null\n return address\n}\n\n/** HMAC of a code, bound to the claim and the address it was sent to. */\nexport function hashOwnershipCode(\n secret: string,\n input: { orgId: string; domain: string; address: string; code: string },\n): string {\n return createHmac('sha256', secret)\n .update(`domain-ownership-code\\n${input.orgId}\\n${input.domain}\\n${input.address}\\n${input.code}`)\n .digest('hex')\n}\n\n/** Whether a stored proof is still one an import may rely on. */\nexport function isOwnershipProofCurrent(\n claim: Pick<DomainOwnershipClaimDoc, 'status' | 'provenAt'> | null | undefined,\n now: number,\n): boolean {\n if (!claim || claim.status !== 'proven' || typeof claim.provenAt !== 'number') return false\n return now - claim.provenAt <= DOMAIN_OWNERSHIP_PROOF_MAX_AGE_MS\n}\n\nexport function domainOwnershipClaimView(\n claim: DomainOwnershipClaimDoc,\n now: number,\n): DomainOwnershipClaimView {\n const code = claim.emailCode ?? null\n const codeLive = Boolean(code && code.expiresAt > now && code.attempts < DOMAIN_OWNERSHIP_CODE_MAX_ATTEMPTS)\n return {\n domain: claim.domain,\n status: claim.status,\n current: isOwnershipProofCurrent(claim, now),\n provenMethod: claim.provenMethod ?? null,\n provenAt: claim.provenAt ?? null,\n provenDetail: claim.provenDetail ?? null,\n lastChecks: claim.lastChecks ?? {},\n dns: {\n host: domainOwnershipRecordHost(claim.domain),\n type: 'TXT',\n value: challengeValue(claim.token),\n },\n meta: {\n name: DOMAIN_OWNERSHIP_META_NAME,\n content: claim.token,\n tag: domainOwnershipMetaTag(claim.token),\n },\n email: {\n domain: claim.domain,\n pendingAddress: codeLive ? code?.address ?? null : null,\n expiresAt: codeLive ? code?.expiresAt ?? null : null,\n attemptsLeft: codeLive && code ? DOMAIN_OWNERSHIP_CODE_MAX_ATTEMPTS - code.attempts : null,\n },\n }\n}\n\n/*------------------------------------------\n * Firestore\n *-----------------------------------------*/\n\nfunction resolved(deps: DomainOwnershipDeps) {\n return {\n firestore: deps.firestore ?? firebaseAdmin.app().firestore(),\n lookupTxt: deps.lookupTxt ?? defaultLookupTxt,\n now: deps.now ?? Date.now,\n secret: deps.secret ?? tokenSigningSecret,\n mintToken: deps.mintToken ?? (() => randomBytes(24).toString('base64url')),\n mintCode: deps.mintCode ?? (() => String(randomInt(0, 1_000_000)).padStart(6, '0')),\n }\n}\n\nfunction claimRef(firestore: FirebaseFirestore.Firestore, orgId: string, domain: string) {\n return firestore\n .collection('orgs')\n .doc(orgId)\n .collection(DOMAIN_OWNERSHIP_CLAIMS_COLLECTION)\n .doc(domain)\n}\n\nasync function readClaim(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n domain: string,\n): Promise<DomainOwnershipClaimDoc | null> {\n const snapshot = await claimRef(firestore, orgId, domain).get()\n return snapshot.exists ? (snapshot.data() as DomainOwnershipClaimDoc) : null\n}\n\n/**\n * Start (or re-read) a claim. Idempotent: an existing claim keeps its token,\n * because a new one would break a record or tag the person already published.\n */\nexport async function issueDomainOwnershipClaim(\n orgId: string,\n rawDomain: string,\n uid: string,\n deps: DomainOwnershipDeps = {},\n): Promise<{ claim: DomainOwnershipClaimView | null; error: string | null }> {\n const { domain, error } = normalizeOwnershipDomain(rawDomain)\n if (!domain) return { claim: null, error }\n const io = resolved(deps)\n const ref = claimRef(io.firestore, orgId, domain)\n const existing = await readClaim(io.firestore, orgId, domain)\n if (existing?.token) return { claim: domainOwnershipClaimView(existing, io.now()), error: null }\n const claim: DomainOwnershipClaimDoc = {\n domain,\n token: io.mintToken(),\n status: 'pending',\n createdAt: io.now(),\n createdBy: uid,\n lastChecks: {},\n emailCode: null,\n }\n await ref.set(claim)\n return { claim: domainOwnershipClaimView(claim, io.now()), error: null }\n}\n\n/** Every claim the org holds, newest first. */\nexport async function listDomainOwnershipClaims(\n orgId: string,\n deps: DomainOwnershipDeps = {},\n): Promise<DomainOwnershipClaimView[]> {\n const io = resolved(deps)\n const snapshot = await io.firestore\n .collection('orgs')\n .doc(orgId)\n .collection(DOMAIN_OWNERSHIP_CLAIMS_COLLECTION)\n .get()\n return snapshot.docs\n .map((doc) => doc.data() as DomainOwnershipClaimDoc)\n .sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0))\n .map((claim) => domainOwnershipClaimView(claim, io.now()))\n}\n\n/**\n * Whether the org holds a CURRENT proof for the domain: the one question an\n * import asks before it pulls a page or an image.\n */\nexport async function isDomainOwnershipProven(\n orgId: string,\n rawDomain: string,\n deps: DomainOwnershipDeps = {},\n): Promise<boolean> {\n const { domain } = normalizeOwnershipDomain(rawDomain)\n if (!domain) return false\n const io = resolved(deps)\n return isOwnershipProofCurrent(await readClaim(io.firestore, orgId, domain), io.now())\n}\n\n/** Writes one check's outcome; a proof is only ever added, never removed. */\nasync function recordCheck(\n io: ReturnType<typeof resolved>,\n orgId: string,\n claim: DomainOwnershipClaimDoc,\n method: DomainOwnershipMethod,\n status: DomainOwnershipCheckStatus,\n detail: string,\n extra: Partial<DomainOwnershipClaimDoc> = {},\n): Promise<DomainOwnershipClaimDoc> {\n const now = io.now()\n const next: DomainOwnershipClaimDoc = {\n ...claim,\n ...extra,\n lastCheckedAt: now,\n lastChecks: { ...(claim.lastChecks ?? {}), [method]: status },\n ...(status === 'proven'\n ? { status: 'proven', provenMethod: method, provenAt: now, provenDetail: detail }\n : {}),\n }\n await claimRef(io.firestore, orgId, claim.domain).set(next)\n return next\n}\n\nconst CHECK_MESSAGES: Record<'dns' | 'meta', Record<DomainOwnershipCheckStatus, string>> = {\n dns: {\n proven: 'Found the DNS record. Your site is verified.',\n 'not-yet':\n 'The DNS record is not there yet. Changes can take a few minutes to an hour to appear; try again soon.',\n unreachable: 'DNS did not answer just now. Nothing has changed; try again in a minute.',\n },\n meta: {\n proven: 'Found the tag on your home page. Your site is verified.',\n 'not-yet':\n 'The tag is not on your home page yet. Publish the page with the tag in its head section, then try again.',\n unreachable: 'Your home page could not be read just now. Nothing has changed; try again in a minute.',\n },\n}\n\n/** Look for the DNS record or the meta tag now. */\nexport async function checkDomainOwnership(\n orgId: string,\n rawDomain: string,\n method: 'dns' | 'meta',\n deps: DomainOwnershipDeps = {},\n): Promise<{ result: DomainOwnershipCheckResult | null; error: string | null }> {\n const { domain, error } = normalizeOwnershipDomain(rawDomain)\n if (!domain) return { result: null, error }\n const io = resolved(deps)\n const claim = await readClaim(io.firestore, orgId, domain)\n if (!claim?.token) return { result: null, error: 'Add the site first.' }\n\n let status: DomainOwnershipCheckStatus\n let detail: string\n if (method === 'dns') {\n detail = domainOwnershipRecordHost(domain)\n const lookup = await io.lookupTxt(detail).catch(() => ({ answered: false, records: [] }))\n status = !lookup.answered\n ? 'unreachable'\n : recordsProveOwnership(lookup.records, claim.token)\n ? 'proven'\n : 'not-yet'\n } else {\n detail = `https://${domain}/`\n const read = deps.readVerificationMeta\n const found = read\n ? await read(domain).catch(() => ({ answered: false, values: [] as string[], url: undefined }))\n : { answered: false, values: [] as string[], url: undefined }\n if (found.url) detail = found.url\n status = !found.answered\n ? 'unreachable'\n : metaValuesProveOwnership(found.values, claim.token)\n ? 'proven'\n : 'not-yet'\n }\n const next = await recordCheck(io, orgId, claim, method, status, detail)\n return {\n error: null,\n result: {\n method,\n status,\n message: CHECK_MESSAGES[method][status],\n claim: domainOwnershipClaimView(next, io.now()),\n },\n }\n}\n\n/** Email a one-time code to an address at the domain. */\nexport async function sendDomainOwnershipCode(\n orgId: string,\n rawDomain: string,\n rawAddress: string,\n context: { org: Record<string, unknown> | null },\n deps: DomainOwnershipDeps = {},\n): Promise<{ claim: DomainOwnershipClaimView | null; error: string | null; status: number }> {\n const { domain, error } = normalizeOwnershipDomain(rawDomain)\n if (!domain) return { claim: null, error, status: 400 }\n const io = resolved(deps)\n const claim = await readClaim(io.firestore, orgId, domain)\n if (!claim?.token) return { claim: null, error: 'Add the site first.', status: 404 }\n const address = ownershipEmailAddress(rawAddress, domain)\n if (!address) {\n return {\n claim: null,\n error: `Enter an email address that ends in @${domain}.`,\n status: 400,\n }\n }\n const now = io.now()\n if (claim.emailCode && now - claim.emailCode.sentAt < DOMAIN_OWNERSHIP_CODE_RESEND_MS) {\n return { claim: null, error: 'A code was just sent. Wait a minute before asking for another.', status: 429 }\n }\n const code = io.mintCode()\n const deliver = deps.deliverCode ?? deliverDomainOwnershipCode\n const sent = await deliver({\n orgId,\n org: context.org,\n domain,\n address,\n code,\n expiresInMinutes: Math.round(DOMAIN_OWNERSHIP_CODE_TTL_MS / 60_000),\n })\n if (!sent.sent) {\n return { claim: null, error: sent.error ?? 'The code could not be sent.', status: sent.status ?? 502 }\n }\n const next: DomainOwnershipClaimDoc = {\n ...claim,\n emailCode: {\n address,\n hash: hashOwnershipCode(io.secret(), { orgId, domain, address, code }),\n sentAt: now,\n expiresAt: now + DOMAIN_OWNERSHIP_CODE_TTL_MS,\n attempts: 0,\n },\n }\n await claimRef(io.firestore, orgId, domain).set(next)\n return { claim: domainOwnershipClaimView(next, now), error: null, status: 200 }\n}\n\n/**\n * Check a code the person typed. Counted in a transaction, so parallel\n * guesses cannot get past the attempt limit between a read and a write.\n */\nexport async function confirmDomainOwnershipCode(\n orgId: string,\n rawDomain: string,\n rawCode: string,\n deps: DomainOwnershipDeps = {},\n): Promise<{ result: DomainOwnershipCheckResult | null; error: string | null }> {\n const { domain, error } = normalizeOwnershipDomain(rawDomain)\n if (!domain) return { result: null, error }\n const io = resolved(deps)\n const ref = claimRef(io.firestore, orgId, domain)\n const typed = String(rawCode ?? '').replace(/\\s+/g, '')\n const outcome = await io.firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const claim = snapshot.exists ? (snapshot.data() as DomainOwnershipClaimDoc) : null\n if (!claim?.token) return { claim: null, status: null, message: 'Add the site first.' }\n const now = io.now()\n const code = claim.emailCode\n if (!code) {\n return { claim, status: 'not-yet' as const, message: 'Send a code first.' }\n }\n if (code.expiresAt <= now || code.attempts >= DOMAIN_OWNERSHIP_CODE_MAX_ATTEMPTS) {\n return {\n claim,\n status: 'not-yet' as const,\n message: 'That code has expired. Send a new one.',\n }\n }\n const expected = code.hash\n const presented = /^\\d{6}$/.test(typed)\n ? hashOwnershipCode(io.secret(), { orgId, domain, address: code.address, code: typed })\n : ''\n if (presented && safeEqual(presented, expected)) {\n const next: DomainOwnershipClaimDoc = {\n ...claim,\n status: 'proven',\n provenMethod: 'email',\n provenAt: now,\n provenDetail: code.address,\n lastCheckedAt: now,\n lastChecks: { ...(claim.lastChecks ?? {}), email: 'proven' },\n emailCode: null,\n }\n tx.set(ref, next)\n return { claim: next, status: 'proven' as const, message: 'Code accepted. Your site is verified.' }\n }\n const attempts = code.attempts + 1\n const left = DOMAIN_OWNERSHIP_CODE_MAX_ATTEMPTS - attempts\n const next: DomainOwnershipClaimDoc = {\n ...claim,\n lastCheckedAt: now,\n lastChecks: { ...(claim.lastChecks ?? {}), email: 'not-yet' },\n emailCode: { ...code, attempts },\n }\n tx.set(ref, next)\n return {\n claim: next,\n status: 'not-yet' as const,\n message:\n left > 0\n ? `That code is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.`\n : 'That code is not right, and it can no longer be used. Send a new one.',\n }\n })\n if (!outcome.claim || !outcome.status) return { result: null, error: outcome.message }\n return {\n error: null,\n result: {\n method: 'email',\n status: outcome.status,\n message: outcome.message,\n claim: domainOwnershipClaimView(outcome.claim, io.now()),\n },\n }\n}\n\n/*------------------------------------------\n * The email\n *-----------------------------------------*/\n\n/**\n * Sends the `domain-ownership-code` system email in the workspace's brand,\n * after two ceilings: per workspace, so one cannot mail a domain's whole\n * staff, and per address, so no address is flooded from many workspaces.\n */\nexport const deliverDomainOwnershipCode: DeliverDomainOwnershipCode = async (input) => {\n if (!isEmailConfigured()) {\n return { sent: false, status: 501, error: 'Email is not configured on this deployment.' }\n }\n const { consumeRateLimit } = await import('./rate-limit-store')\n const perOrg = await consumeRateLimit(`domain-ownership-code:${input.orgId}`, {\n limit: DOMAIN_OWNERSHIP_CODES_PER_ORG_PER_HOUR,\n windowMs: 60 * 60 * 1000,\n })\n if (!perOrg.allowed) {\n return { sent: false, status: 429, error: 'Too many codes sent. Try again in an hour.' }\n }\n const perAddress = await consumeRateLimit(`domain-ownership-code-target:${input.address}`, {\n limit: DOMAIN_OWNERSHIP_CODES_PER_ADDRESS_PER_HOUR,\n windowMs: 60 * 60 * 1000,\n })\n if (!perAddress.allowed) {\n return { sent: false, status: 429, error: 'Too many codes for that address. Try again later.' }\n }\n const { renderSystemEmailContent, systemEmailBrand } = await import('./render-system-email')\n const branding = resolveBrandingProfile((input.org ?? null) as never)\n const workspace = String(input.org?.['name'] ?? '').trim() || 'A workspace'\n const text = [\n `${workspace} asked to confirm that ${input.domain} belongs to them, so they can bring the ` +\n `site into ${branding.productName}.`,\n '',\n `Your code: ${input.code}`,\n '',\n `It works for ${input.expiresInMinutes} minutes. Type it where you asked for it.`,\n '',\n 'If you did not ask for this, ignore this email. Nothing is copied from your site without the code.',\n ].join('\\n')\n const content = await renderSystemEmailContent(\n DOMAIN_OWNERSHIP_CODE_EMAIL_KEY,\n {\n 'org.name': workspace,\n domain: input.domain,\n code: input.code,\n expiresInMinutes: String(input.expiresInMinutes),\n },\n systemEmailBrand(input.org ?? null),\n { subject: `Your code to verify ${input.domain}`, text },\n )\n const result = await sendEmail({\n to: input.address,\n ...content,\n fromName: branding.fromName,\n context: DOMAIN_OWNERSHIP_CODE_EMAIL_KEY,\n })\n if (!result.sent) {\n return { sent: false, status: 502, error: 'The code could not be sent. Try again.' }\n }\n const { meterOrgEmail } = await import('./email-metering')\n await meterOrgEmail(input.orgId).catch(() => undefined)\n return { sent: true }\n}\n"],"names":["createHmac","randomBytes","randomInt","resolveBrandingProfile","isEmailConfigured","sendEmail","lookalikeBrandForHost","lookupTxt","defaultLookupTxt","firebaseAdmin","tokenSigningSecret","safeEqual","challengeValue","isPublicEmailDomain","recordsProveOwnership","SSO_CHALLENGE_PREFIX","DOMAIN_OWNERSHIP_CLAIMS_COLLECTION","DOMAIN_OWNERSHIP_META_NAME","DOMAIN_OWNERSHIP_CODE_EMAIL_KEY","DOMAIN_OWNERSHIP_CODE_TTL_MS","DOMAIN_OWNERSHIP_CODE_MAX_ATTEMPTS","DOMAIN_OWNERSHIP_CODE_RESEND_MS","DOMAIN_OWNERSHIP_CODES_PER_ORG_PER_HOUR","DOMAIN_OWNERSHIP_CODES_PER_ADDRESS_PER_HOUR","DOMAIN_OWNERSHIP_PROOF_MAX_AGE_MS","DOMAIN_PATTERN","EMAIL_LOCAL_PATTERN","normalizeOwnershipDomain","input","raw","String","trim","toLowerCase","at","lastIndexOf","includes","slice","replace","split","test","domain","error","domainOwnershipRecordHost","domainOwnershipMetaTag","token","metaValuesProveOwnership","values","some","value","ownershipEmailAddress","address","local","host","startsWith","endsWith","hashOwnershipCode","secret","update","orgId","code","digest","isOwnershipProofCurrent","claim","now","status","provenAt","domainOwnershipClaimView","emailCode","codeLive","Boolean","expiresAt","attempts","current","provenMethod","provenDetail","lastChecks","dns","type","meta","name","content","tag","email","pendingAddress","attemptsLeft","resolved","deps","firestore","app","Date","mintToken","toString","mintCode","padStart","claimRef","collection","doc","readClaim","snapshot","get","exists","data","issueDomainOwnershipClaim","rawDomain","uid","io","ref","existing","createdAt","createdBy","set","listDomainOwnershipClaims","docs","map","sort","a","b","isDomainOwnershipProven","recordCheck","method","detail","extra","next","lastCheckedAt","CHECK_MESSAGES","proven","unreachable","checkDomainOwnership","result","lookup","catch","answered","records","read","readVerificationMeta","found","url","undefined","message","sendDomainOwnershipCode","rawAddress","context","sentAt","deliver","deliverCode","deliverDomainOwnershipCode","sent","org","expiresInMinutes","Math","round","hash","confirmDomainOwnershipCode","rawCode","typed","outcome","runTransaction","tx","expected","presented","left","consumeRateLimit","perOrg","limit","windowMs","allowed","perAddress","renderSystemEmailContent","systemEmailBrand","branding","workspace","text","productName","join","subject","to","fromName","meterOrgEmail"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2C2C,GAE3C,SAASA,UAAU,EAAEC,WAAW,EAAEC,SAAS,QAAQ,SAAQ;AAC3D,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,aAAaC,gBAAgB,QAA8B,iBAAa;AACjF,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SAASC,SAAS,QAAQ,kBAAc;AACxC,SACEC,cAAc,EACdC,mBAAmB,EACnBC,qBAAqB,EACrBC,oBAAoB,QACf,wBAAoB;AAE3B,2EAA2E,GAC3E,OAAO,MAAMC,qCAAqC,wBAAuB;AAEzE,iEAAiE,GACjE,OAAO,MAAMC,6BAA6B,0BAAyB;AAEnE,qDAAqD,GACrD,OAAO,MAAMC,kCAAkC,wBAAuB;AAEtE,oCAAoC,GACpC,OAAO,MAAMC,+BAA+B,KAAK,KAAK,KAAI;AAE1D,8EAA8E,GAC9E,OAAO,MAAMC,qCAAqC,EAAC;AAEnD,oDAAoD,GACpD,OAAO,MAAMC,kCAAkC,KAAK,KAAI;AAExD,iEAAiE,GACjE,OAAO,MAAMC,0CAA0C,GAAE;AAEzD,oEAAoE,GACpE,OAAO,MAAMC,8CAA8C,EAAC;AAE5D;;;;CAIC,GACD,OAAO,MAAMC,oCAAoC,KAAK,KAAK,KAAK,KAAK,KAAI;AAEzE,MAAMC,iBAAiB;AACvB,MAAMC,sBAAsB;AA4F5B;;2CAE2C,GAE3C;;;;;CAKC,GACD,OAAO,SAASC,yBAAyBC,KAAa;Q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IAAI,CAAC8G,OAAOkB,IAAI,EAAE;QAChB,OAAO;YAAEA,MAAM;YAAOlF,QAAQ;YAAKvB,OAAO;QAAyC;IACrF;IACA,MAAM,EAAEwI,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC;IACvC,MAAMA,cAAcrJ,MAAM8B,KAAK,EAAEwE,KAAK,CAAC,IAAMO;IAC7C,OAAO;QAAES,MAAM;IAAK;AACtB,EAAC"}
|
|
@@ -18,9 +18,26 @@ import { type AccountAddressSet, type AccountAddressSource } from './account-add
|
|
|
18
18
|
import { type PluginUserErasureReport } from '@aglyn/aglyn/plugin-manager/plugin-user-erasure';
|
|
19
19
|
import { type PluginOrgErasureReport } from '@aglyn/aglyn/plugin-manager/plugin-org-erasure';
|
|
20
20
|
import { type ConsentGroupSiteHold } from '@aglyn/aglyn/app-utils/consent-groups';
|
|
21
|
+
import { type PluginSiteResourcePreviewRow } from '@aglyn/aglyn/plugin-manager/plugin-site-resources';
|
|
21
22
|
import { type SendingDomainDisposition, type TeardownSendingDomainDriver } from './sending-domain-debt';
|
|
22
23
|
/** The reversible hold before a requested erasure is executed (AGL-485). */
|
|
23
24
|
export declare const ERASURE_HOLD_MS: number;
|
|
25
|
+
/** What deleting a site takes with it, plugin by plugin (AGL-4003). */
|
|
26
|
+
export interface HostErasePreview {
|
|
27
|
+
/**
|
|
28
|
+
* Each plugin's resources shared with the site: the ones that go, with how
|
|
29
|
+
* many items each holds, and how many stay. `preview: null` is a plugin
|
|
30
|
+
* that could not answer, so the list is incomplete.
|
|
31
|
+
*/
|
|
32
|
+
resources: PluginSiteResourcePreviewRow[];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* What the Delete site card shows before it asks (AGL-4003): the resources
|
|
36
|
+
* plugins share with the site alone, which go with it — a dataset and its
|
|
37
|
+
* records — and how many shared ones stay. Asked of the same erasers
|
|
38
|
+
* {@link eraseHost} runs, so the list is what the delete does. Reads only.
|
|
39
|
+
*/
|
|
40
|
+
export declare function previewHostErase(orgId: string, hostId: string): Promise<HostErasePreview>;
|
|
24
41
|
/**
|
|
25
42
|
* Permanently erase a single site and everything it owns (AGL-488).
|
|
26
43
|
* Unlike deleting the host doc alone (which orphans data), this cleans up
|
package/src/lib/server/erase.js
CHANGED
|
@@ -32,6 +32,7 @@ import { isBillingSubscription } from "@aglyn/aglyn/server";
|
|
|
32
32
|
// barrel, and which sites a consent group still needs is the rule itself.
|
|
33
33
|
import { consentGroupSiteHold } from "@aglyn/aglyn/app-utils/consent-groups";
|
|
34
34
|
import { listPluginOrgCollections } from "@aglyn/aglyn/plugin-manager/plugin-host-collections";
|
|
35
|
+
import { erasePluginSiteResources, previewPluginSiteResources } from "@aglyn/aglyn/plugin-manager/plugin-site-resources";
|
|
35
36
|
import { runPluginEventHandlers } from "@aglyn/aglyn/plugin-manager/plugin-events";
|
|
36
37
|
import { releasedHostNames } from "./host-released-names.js";
|
|
37
38
|
import { readOrgBilling } from "./org-billing.js";
|
|
@@ -178,6 +179,19 @@ import { addAdminAudit } from "./admin-audit-write.js";
|
|
|
178
179
|
}
|
|
179
180
|
return erased;
|
|
180
181
|
}
|
|
182
|
+
/**
|
|
183
|
+
* What the Delete site card shows before it asks (AGL-4003): the resources
|
|
184
|
+
* plugins share with the site alone, which go with it — a dataset and its
|
|
185
|
+
* records — and how many shared ones stay. Asked of the same erasers
|
|
186
|
+
* {@link eraseHost} runs, so the list is what the delete does. Reads only.
|
|
187
|
+
*/ export async function previewHostErase(orgId, hostId) {
|
|
188
|
+
return {
|
|
189
|
+
resources: await previewPluginSiteResources({
|
|
190
|
+
orgId,
|
|
191
|
+
hostId
|
|
192
|
+
})
|
|
193
|
+
};
|
|
194
|
+
}
|
|
181
195
|
/**
|
|
182
196
|
* {@link eraseHost} refused a site its consent group still needs (AGL-3320).
|
|
183
197
|
* Nothing was erased; the site leaves its group, and is deleted after.
|
|
@@ -283,6 +297,13 @@ export async function eraseHost(hostId, options = {}) {
|
|
|
283
297
|
console.error(`eraseHost: projection cleanup failed for ${hostId}`, error);
|
|
284
298
|
});
|
|
285
299
|
await eraseHostOwnedOrgDocuments(orgId, hostId);
|
|
300
|
+
// What plugins share with this site alone — a dataset and its records —
|
|
301
|
+
// and this site's place in the sharing of what it shares with others
|
|
302
|
+
// (AGL-4003). Each plugin's share is isolated and never throws here.
|
|
303
|
+
await erasePluginSiteResources({
|
|
304
|
+
orgId,
|
|
305
|
+
hostId
|
|
306
|
+
});
|
|
286
307
|
}
|
|
287
308
|
// The host document tree (screens/layouts/versions/counters/products/…).
|
|
288
309
|
await firestore.recursiveDelete(hostRef);
|