@open-mercato/core 0.6.1-develop.3276.1.1fcd145078 → 0.6.1-develop.3278.1.a4d26475e4
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/.turbo/turbo-build.log +2 -2
- package/dist/generated/entities/domain_mapping/index.js +31 -0
- package/dist/generated/entities/domain_mapping/index.js.map +7 -0
- package/dist/generated/entities.ids.generated.js +2 -1
- package/dist/generated/entities.ids.generated.js.map +2 -2
- package/dist/generated/entity-fields-registry.js +16 -0
- package/dist/generated/entity-fields-registry.js.map +2 -2
- package/dist/helpers/integration/salesUi.js +18 -17
- package/dist/helpers/integration/salesUi.js.map +2 -2
- package/dist/modules/customer_accounts/acl.js +2 -1
- package/dist/modules/customer_accounts/acl.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/domain-mappings/[id]/health-check.js +110 -0
- package/dist/modules/customer_accounts/api/admin/domain-mappings/[id]/health-check.js.map +7 -0
- package/dist/modules/customer_accounts/api/admin/domain-mappings/[id]/verify.js +114 -0
- package/dist/modules/customer_accounts/api/admin/domain-mappings/[id]/verify.js.map +7 -0
- package/dist/modules/customer_accounts/api/admin/domain-mappings.js +271 -0
- package/dist/modules/customer_accounts/api/admin/domain-mappings.js.map +7 -0
- package/dist/modules/customer_accounts/api/domain-check.js +70 -0
- package/dist/modules/customer_accounts/api/domain-check.js.map +7 -0
- package/dist/modules/customer_accounts/api/domain-resolve/all.js +128 -0
- package/dist/modules/customer_accounts/api/domain-resolve/all.js.map +7 -0
- package/dist/modules/customer_accounts/api/domain-resolve.js +84 -0
- package/dist/modules/customer_accounts/api/domain-resolve.js.map +7 -0
- package/dist/modules/customer_accounts/api/login.js +14 -3
- package/dist/modules/customer_accounts/api/login.js.map +2 -2
- package/dist/modules/customer_accounts/api/magic-link/request.js +14 -3
- package/dist/modules/customer_accounts/api/magic-link/request.js.map +2 -2
- package/dist/modules/customer_accounts/api/password/reset-request.js +14 -3
- package/dist/modules/customer_accounts/api/password/reset-request.js.map +2 -2
- package/dist/modules/customer_accounts/api/signup.js +32 -5
- package/dist/modules/customer_accounts/api/signup.js.map +2 -2
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Actions.js +48 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Actions.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Diagnostics.js +43 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Diagnostics.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/DnsConfig.js +53 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/DnsConfig.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/DomainPanel.js +69 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/DomainPanel.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/OrgSwitcher.js +31 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/OrgSwitcher.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/RegisterDialog.js +147 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/RegisterDialog.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/StatusBadgeSection.js +39 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/StatusBadgeSection.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Stepper.js +60 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Stepper.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/domainStatusMap.js +11 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/domainStatusMap.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/types.js +1 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/types.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/page.js +361 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/page.js.map +7 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/page.meta.js +28 -0
- package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/page.meta.js.map +7 -0
- package/dist/modules/customer_accounts/data/enrichers.js +78 -12
- package/dist/modules/customer_accounts/data/enrichers.js.map +2 -2
- package/dist/modules/customer_accounts/data/entities.js +85 -2
- package/dist/modules/customer_accounts/data/entities.js.map +2 -2
- package/dist/modules/customer_accounts/data/guards.js +130 -0
- package/dist/modules/customer_accounts/data/guards.js.map +7 -0
- package/dist/modules/customer_accounts/data/validators.js +19 -0
- package/dist/modules/customer_accounts/data/validators.js.map +2 -2
- package/dist/modules/customer_accounts/di.js +23 -1
- package/dist/modules/customer_accounts/di.js.map +2 -2
- package/dist/modules/customer_accounts/events.js +9 -2
- package/dist/modules/customer_accounts/events.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerAuthServer.js +27 -7
- package/dist/modules/customer_accounts/lib/customerAuthServer.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerUrl.js +48 -0
- package/dist/modules/customer_accounts/lib/customerUrl.js.map +7 -0
- package/dist/modules/customer_accounts/lib/hostname.js +55 -0
- package/dist/modules/customer_accounts/lib/hostname.js.map +7 -0
- package/dist/modules/customer_accounts/lib/platformDomains.js +7 -0
- package/dist/modules/customer_accounts/lib/platformDomains.js.map +7 -0
- package/dist/modules/customer_accounts/lib/proxyRanges.js +71 -0
- package/dist/modules/customer_accounts/lib/proxyRanges.js.map +7 -0
- package/dist/modules/customer_accounts/lib/rateLimiter.js +7 -0
- package/dist/modules/customer_accounts/lib/rateLimiter.js.map +2 -2
- package/dist/modules/customer_accounts/lib/resolveTenantContext.js +63 -0
- package/dist/modules/customer_accounts/lib/resolveTenantContext.js.map +7 -0
- package/dist/modules/customer_accounts/lib/secretCompare.js +13 -0
- package/dist/modules/customer_accounts/lib/secretCompare.js.map +7 -0
- package/dist/modules/customer_accounts/migrations/Migration20260430120000_customer_accounts.js +37 -0
- package/dist/modules/customer_accounts/migrations/Migration20260430120000_customer_accounts.js.map +7 -0
- package/dist/modules/customer_accounts/notifications.client.js +76 -0
- package/dist/modules/customer_accounts/notifications.client.js.map +2 -2
- package/dist/modules/customer_accounts/notifications.js +76 -0
- package/dist/modules/customer_accounts/notifications.js.map +2 -2
- package/dist/modules/customer_accounts/services/domainMappingService.js +497 -0
- package/dist/modules/customer_accounts/services/domainMappingService.js.map +7 -0
- package/dist/modules/customer_accounts/setup.js +48 -1
- package/dist/modules/customer_accounts/setup.js.map +2 -2
- package/dist/modules/customer_accounts/subscribers/invalidateDomainCache.js +29 -0
- package/dist/modules/customer_accounts/subscribers/invalidateDomainCache.js.map +7 -0
- package/dist/modules/customer_accounts/subscribers/notifyDomainActivated.js +29 -0
- package/dist/modules/customer_accounts/subscribers/notifyDomainActivated.js.map +7 -0
- package/dist/modules/customer_accounts/subscribers/notifyDomainDnsFailed.js +30 -0
- package/dist/modules/customer_accounts/subscribers/notifyDomainDnsFailed.js.map +7 -0
- package/dist/modules/customer_accounts/subscribers/notifyDomainTlsFailed.js +31 -0
- package/dist/modules/customer_accounts/subscribers/notifyDomainTlsFailed.js.map +7 -0
- package/dist/modules/customer_accounts/subscribers/notifyDomainVerified.js +29 -0
- package/dist/modules/customer_accounts/subscribers/notifyDomainVerified.js.map +7 -0
- package/dist/modules/customer_accounts/workers/domainTlsRetryWorker.js +67 -0
- package/dist/modules/customer_accounts/workers/domainTlsRetryWorker.js.map +7 -0
- package/dist/modules/customer_accounts/workers/domainVerificationWorker.js +34 -0
- package/dist/modules/customer_accounts/workers/domainVerificationWorker.js.map +7 -0
- package/dist/modules/customers/api/companies/route.js +4 -9
- package/dist/modules/customers/api/companies/route.js.map +2 -2
- package/dist/modules/customers/api/deals/route.js +4 -9
- package/dist/modules/customers/api/deals/route.js.map +2 -2
- package/dist/modules/customers/api/people/route.js +4 -9
- package/dist/modules/customers/api/people/route.js.map +2 -2
- package/dist/modules/customers/api/utils.js +0 -12
- package/dist/modules/customers/api/utils.js.map +2 -2
- package/dist/modules/customers/backend/customers/companies/page.js +361 -284
- package/dist/modules/customers/backend/customers/companies/page.js.map +2 -2
- package/dist/modules/customers/backend/customers/deals/page.js +378 -473
- package/dist/modules/customers/backend/customers/deals/page.js.map +2 -2
- package/dist/modules/customers/backend/customers/people/page.js +368 -286
- package/dist/modules/customers/backend/customers/people/page.js.map +2 -2
- package/dist/modules/customers/components/detail/assignableStaff.js +15 -1
- package/dist/modules/customers/components/detail/assignableStaff.js.map +2 -2
- package/dist/modules/customers/widgets/injection/ai-assistant-trigger/widget.client.js +188 -36
- package/dist/modules/customers/widgets/injection/ai-assistant-trigger/widget.client.js.map +2 -2
- package/dist/modules/customers/widgets/injection/ai-assistant-trigger/widget.js +2 -2
- package/dist/modules/customers/widgets/injection/ai-assistant-trigger/widget.js.map +2 -2
- package/dist/modules/customers/widgets/injection-table.js +6 -0
- package/dist/modules/customers/widgets/injection-table.js.map +2 -2
- package/dist/modules/perspectives/services/perspectiveService.js +16 -2
- package/dist/modules/perspectives/services/perspectiveService.js.map +2 -2
- package/dist/modules/portal/frontend/[orgSlug]/portal/login/page.js +1 -0
- package/dist/modules/portal/frontend/[orgSlug]/portal/login/page.js.map +2 -2
- package/dist/modules/query_index/lib/engine.js +31 -8
- package/dist/modules/query_index/lib/engine.js.map +2 -2
- package/generated/entities/domain_mapping/index.ts +14 -0
- package/generated/entities.ids.generated.ts +2 -1
- package/generated/entity-fields-registry.ts +16 -0
- package/package.json +5 -5
- package/src/helpers/integration/salesUi.ts +27 -23
- package/src/modules/customer_accounts/acl.ts +1 -0
- package/src/modules/customer_accounts/api/admin/domain-mappings/[id]/health-check.ts +119 -0
- package/src/modules/customer_accounts/api/admin/domain-mappings/[id]/verify.ts +123 -0
- package/src/modules/customer_accounts/api/admin/domain-mappings.ts +303 -0
- package/src/modules/customer_accounts/api/domain-check.ts +83 -0
- package/src/modules/customer_accounts/api/domain-resolve/all.ts +139 -0
- package/src/modules/customer_accounts/api/domain-resolve.ts +91 -0
- package/src/modules/customer_accounts/api/login.ts +14 -3
- package/src/modules/customer_accounts/api/magic-link/request.ts +14 -3
- package/src/modules/customer_accounts/api/password/reset-request.ts +15 -3
- package/src/modules/customer_accounts/api/signup.ts +36 -5
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Actions.tsx +70 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Diagnostics.tsx +66 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/DnsConfig.tsx +78 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/DomainPanel.tsx +90 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/OrgSwitcher.tsx +43 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/RegisterDialog.tsx +178 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/StatusBadgeSection.tsx +56 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Stepper.tsx +69 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/domainStatusMap.ts +10 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/types.ts +31 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/page.meta.ts +26 -0
- package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/page.tsx +411 -0
- package/src/modules/customer_accounts/data/enrichers.ts +95 -12
- package/src/modules/customer_accounts/data/entities.ts +80 -1
- package/src/modules/customer_accounts/data/guards.ts +155 -0
- package/src/modules/customer_accounts/data/validators.ts +26 -0
- package/src/modules/customer_accounts/di.ts +35 -1
- package/src/modules/customer_accounts/events.ts +8 -1
- package/src/modules/customer_accounts/i18n/de.json +78 -0
- package/src/modules/customer_accounts/i18n/en.json +78 -0
- package/src/modules/customer_accounts/i18n/es.json +78 -0
- package/src/modules/customer_accounts/i18n/pl.json +78 -0
- package/src/modules/customer_accounts/lib/customerAuthServer.ts +44 -8
- package/src/modules/customer_accounts/lib/customerUrl.ts +72 -0
- package/src/modules/customer_accounts/lib/hostname.ts +76 -0
- package/src/modules/customer_accounts/lib/platformDomains.ts +14 -0
- package/src/modules/customer_accounts/lib/proxyRanges.ts +85 -0
- package/src/modules/customer_accounts/lib/rateLimiter.ts +10 -0
- package/src/modules/customer_accounts/lib/resolveTenantContext.ts +96 -0
- package/src/modules/customer_accounts/lib/secretCompare.ts +20 -0
- package/src/modules/customer_accounts/migrations/.snapshot-open-mercato.json +341 -0
- package/src/modules/customer_accounts/migrations/Migration20260430120000_customer_accounts.ts +38 -0
- package/src/modules/customer_accounts/notifications.client.ts +76 -0
- package/src/modules/customer_accounts/notifications.ts +76 -0
- package/src/modules/customer_accounts/services/domainMappingService.ts +632 -0
- package/src/modules/customer_accounts/setup.ts +81 -1
- package/src/modules/customer_accounts/subscribers/invalidateDomainCache.ts +35 -0
- package/src/modules/customer_accounts/subscribers/notifyDomainActivated.ts +32 -0
- package/src/modules/customer_accounts/subscribers/notifyDomainDnsFailed.ts +33 -0
- package/src/modules/customer_accounts/subscribers/notifyDomainTlsFailed.ts +34 -0
- package/src/modules/customer_accounts/subscribers/notifyDomainVerified.ts +32 -0
- package/src/modules/customer_accounts/workers/domainTlsRetryWorker.ts +84 -0
- package/src/modules/customer_accounts/workers/domainVerificationWorker.ts +45 -0
- package/src/modules/customers/api/companies/route.ts +4 -9
- package/src/modules/customers/api/deals/route.ts +4 -9
- package/src/modules/customers/api/people/route.ts +4 -9
- package/src/modules/customers/api/utils.ts +0 -14
- package/src/modules/customers/backend/customers/companies/page.tsx +321 -237
- package/src/modules/customers/backend/customers/deals/page.tsx +321 -455
- package/src/modules/customers/backend/customers/people/page.tsx +331 -240
- package/src/modules/customers/components/detail/assignableStaff.ts +21 -0
- package/src/modules/customers/i18n/de.json +31 -0
- package/src/modules/customers/i18n/en.json +31 -0
- package/src/modules/customers/i18n/es.json +31 -0
- package/src/modules/customers/i18n/pl.json +31 -0
- package/src/modules/customers/widgets/injection/ai-assistant-trigger/widget.client.tsx +197 -40
- package/src/modules/customers/widgets/injection/ai-assistant-trigger/widget.ts +13 -7
- package/src/modules/customers/widgets/injection-table.ts +6 -0
- package/src/modules/perspectives/services/perspectiveService.ts +30 -2
- package/src/modules/portal/frontend/[orgSlug]/portal/login/page.tsx +1 -0
- package/src/modules/query_index/lib/engine.ts +46 -8
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
import { Resolver, promises as dnsPromises } from "node:dns";
|
|
2
|
+
import { request as httpsRequest } from "node:https";
|
|
3
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
+
import {
|
|
5
|
+
DomainMapping
|
|
6
|
+
} from "@open-mercato/core/modules/customer_accounts/data/entities";
|
|
7
|
+
import { Organization } from "@open-mercato/core/modules/directory/data/entities";
|
|
8
|
+
import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
|
|
9
|
+
import { normalizeHostname, tryNormalizeHostname } from "@open-mercato/core/modules/customer_accounts/lib/hostname";
|
|
10
|
+
import { platformDomains } from "@open-mercato/core/modules/customer_accounts/lib/platformDomains";
|
|
11
|
+
import { detectProxy, isInKnownProxyRange } from "@open-mercato/core/modules/customer_accounts/lib/proxyRanges";
|
|
12
|
+
const DOMAIN_ROUTING_TAG = "domain_routing";
|
|
13
|
+
const RESOLVE_KEY_PREFIX = "domain_routing:resolve";
|
|
14
|
+
const ACTIVE_BY_ORG_KEY_PREFIX = "domain_routing:active-by-org";
|
|
15
|
+
const RESOLVE_TTL_MS = 5 * 6e4;
|
|
16
|
+
const TLS_HEALTH_CHECK_TIMEOUT_MS = 1e4;
|
|
17
|
+
const TLS_HEALTH_CHECK_RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
|
|
18
|
+
const DEFAULT_DNS_RECHECK_THRESHOLD_MS = 5 * 6e4;
|
|
19
|
+
const DEFAULT_TLS_MAX_RETRIES = 6;
|
|
20
|
+
const defaultDnsResolver = {
|
|
21
|
+
async resolveCname(hostname) {
|
|
22
|
+
try {
|
|
23
|
+
return await dnsPromises.resolveCname(hostname);
|
|
24
|
+
} catch (err) {
|
|
25
|
+
const code = err.code;
|
|
26
|
+
if (code === "ENODATA" || code === "ENOTFOUND") return [];
|
|
27
|
+
throw err;
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
async resolve4(hostname) {
|
|
31
|
+
try {
|
|
32
|
+
return await dnsPromises.resolve4(hostname);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
const code = err.code;
|
|
35
|
+
if (code === "ENODATA" || code === "ENOTFOUND") return [];
|
|
36
|
+
throw err;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const defaultHealthCheck = (hostname, timeoutMs) => new Promise((resolve) => {
|
|
41
|
+
const headerName = (process.env.CUSTOMER_DOMAIN_ORIGIN_HEADER ?? "X-Open-Mercato-Origin").toLowerCase();
|
|
42
|
+
const req = httpsRequest(
|
|
43
|
+
{
|
|
44
|
+
host: hostname,
|
|
45
|
+
port: 443,
|
|
46
|
+
path: "/api/customer_accounts/domain-check",
|
|
47
|
+
method: "GET",
|
|
48
|
+
headers: { "X-Domain-Check-Secret": process.env.DOMAIN_CHECK_SECRET ?? "" },
|
|
49
|
+
timeout: timeoutMs
|
|
50
|
+
},
|
|
51
|
+
(res) => {
|
|
52
|
+
const headerValue = res.headers[headerName];
|
|
53
|
+
const originHeader = Array.isArray(headerValue) ? headerValue[0] : headerValue;
|
|
54
|
+
const originHeaderPresent = typeof originHeader === "string" && originHeader === "1";
|
|
55
|
+
const status = res.statusCode ?? 0;
|
|
56
|
+
res.resume();
|
|
57
|
+
resolve({
|
|
58
|
+
ok: status >= 200 && status < 400,
|
|
59
|
+
originHeaderPresent,
|
|
60
|
+
reason: status >= 200 && status < 400 ? void 0 : `HTTP ${status}`
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
);
|
|
64
|
+
req.on("timeout", () => {
|
|
65
|
+
req.destroy(new Error("TLS health check timed out"));
|
|
66
|
+
});
|
|
67
|
+
req.on("error", (err) => {
|
|
68
|
+
resolve({ ok: false, originHeaderPresent: false, reason: err.message });
|
|
69
|
+
});
|
|
70
|
+
req.end();
|
|
71
|
+
});
|
|
72
|
+
class DomainMappingService {
|
|
73
|
+
constructor(em, deps) {
|
|
74
|
+
this.em = em;
|
|
75
|
+
this.cache = deps?.cacheService ?? null;
|
|
76
|
+
this.dns = deps?.dnsResolver ?? defaultDnsResolver;
|
|
77
|
+
this.healthCheckImpl = deps?.healthCheck ?? defaultHealthCheck;
|
|
78
|
+
}
|
|
79
|
+
// -------------------------------------------------------------------------
|
|
80
|
+
// Read paths
|
|
81
|
+
// -------------------------------------------------------------------------
|
|
82
|
+
async findById(id, scope) {
|
|
83
|
+
const where = { id };
|
|
84
|
+
if (scope?.tenantId) where.tenantId = scope.tenantId;
|
|
85
|
+
return this.em.findOne(DomainMapping, where);
|
|
86
|
+
}
|
|
87
|
+
async findByOrganization(organizationId, scope) {
|
|
88
|
+
const where = { organizationId };
|
|
89
|
+
if (scope?.tenantId) where.tenantId = scope.tenantId;
|
|
90
|
+
return this.em.find(DomainMapping, where, { orderBy: { createdAt: "asc" } });
|
|
91
|
+
}
|
|
92
|
+
async resolveByHostname(input) {
|
|
93
|
+
const hostname = tryNormalizeHostname(input);
|
|
94
|
+
if (!hostname) return null;
|
|
95
|
+
if (platformDomains().includes(hostname)) return null;
|
|
96
|
+
const cacheKey = `${RESOLVE_KEY_PREFIX}:${hostname}`;
|
|
97
|
+
if (this.cache) {
|
|
98
|
+
const cached = await this.cache.get(cacheKey);
|
|
99
|
+
if (cached !== void 0 && cached !== null) return cached;
|
|
100
|
+
}
|
|
101
|
+
const result = await this.lookupResolveResult(hostname);
|
|
102
|
+
if (this.cache) {
|
|
103
|
+
await this.cache.set(cacheKey, result, {
|
|
104
|
+
ttl: RESOLVE_TTL_MS,
|
|
105
|
+
tags: [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:${hostname}`]
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
async isAllowedForTls(input) {
|
|
111
|
+
const hostname = tryNormalizeHostname(input);
|
|
112
|
+
if (!hostname) return null;
|
|
113
|
+
if (platformDomains().includes(hostname)) return null;
|
|
114
|
+
const row = await this.em.findOne(DomainMapping, {
|
|
115
|
+
hostname,
|
|
116
|
+
status: { $in: ["active", "verified"] }
|
|
117
|
+
});
|
|
118
|
+
if (!row) return null;
|
|
119
|
+
return { organizationId: row.organizationId, status: row.status };
|
|
120
|
+
}
|
|
121
|
+
async resolveActiveByOrg(organizationId) {
|
|
122
|
+
const cacheKey = `${ACTIVE_BY_ORG_KEY_PREFIX}:${organizationId}`;
|
|
123
|
+
if (this.cache) {
|
|
124
|
+
const cached = await this.cache.get(cacheKey);
|
|
125
|
+
if (cached !== void 0 && cached !== null) return cached;
|
|
126
|
+
}
|
|
127
|
+
const row = await this.em.findOne(DomainMapping, {
|
|
128
|
+
organizationId,
|
|
129
|
+
status: "active"
|
|
130
|
+
});
|
|
131
|
+
const result = row ? { hostname: row.hostname, status: row.status } : null;
|
|
132
|
+
if (this.cache) {
|
|
133
|
+
await this.cache.set(cacheKey, result, {
|
|
134
|
+
ttl: RESOLVE_TTL_MS,
|
|
135
|
+
tags: [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:org:${organizationId}`]
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
return result;
|
|
139
|
+
}
|
|
140
|
+
async resolveAll() {
|
|
141
|
+
const rows = await this.em.find(DomainMapping, { status: "active" });
|
|
142
|
+
if (rows.length === 0) return [];
|
|
143
|
+
const orgIds = Array.from(new Set(rows.map((r) => r.organizationId)));
|
|
144
|
+
const orgs = await this.em.find(Organization, { id: { $in: orgIds } });
|
|
145
|
+
const slugByOrg = new Map(orgs.map((o) => [o.id, o.slug ?? null]));
|
|
146
|
+
return rows.map((row) => ({
|
|
147
|
+
domainMappingId: row.id,
|
|
148
|
+
hostname: row.hostname,
|
|
149
|
+
tenantId: row.tenantId,
|
|
150
|
+
organizationId: row.organizationId,
|
|
151
|
+
orgSlug: slugByOrg.get(row.organizationId) ?? null,
|
|
152
|
+
status: row.status
|
|
153
|
+
}));
|
|
154
|
+
}
|
|
155
|
+
// -------------------------------------------------------------------------
|
|
156
|
+
// Worker queries
|
|
157
|
+
// -------------------------------------------------------------------------
|
|
158
|
+
async findPendingVerification(threshold) {
|
|
159
|
+
const olderThan = threshold?.olderThanMs ?? DEFAULT_DNS_RECHECK_THRESHOLD_MS;
|
|
160
|
+
const cutoff = new Date(Date.now() - olderThan);
|
|
161
|
+
return this.em.find(
|
|
162
|
+
DomainMapping,
|
|
163
|
+
{
|
|
164
|
+
status: { $in: ["pending", "dns_failed"] },
|
|
165
|
+
$or: [{ lastDnsCheckAt: null }, { lastDnsCheckAt: { $lt: cutoff } }]
|
|
166
|
+
},
|
|
167
|
+
{ orderBy: { lastDnsCheckAt: "asc" } }
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
async findPendingTls(options) {
|
|
171
|
+
const maxRetries = options?.maxRetries ?? DEFAULT_TLS_MAX_RETRIES;
|
|
172
|
+
const limit = options?.batchSize ?? 50;
|
|
173
|
+
return this.em.find(
|
|
174
|
+
DomainMapping,
|
|
175
|
+
{
|
|
176
|
+
$or: [
|
|
177
|
+
{ status: "verified" },
|
|
178
|
+
{ status: "tls_failed", tlsRetryCount: { $lt: maxRetries } }
|
|
179
|
+
]
|
|
180
|
+
},
|
|
181
|
+
{ orderBy: { updatedAt: "asc" }, limit }
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
// -------------------------------------------------------------------------
|
|
185
|
+
// Write paths
|
|
186
|
+
// -------------------------------------------------------------------------
|
|
187
|
+
async register(input) {
|
|
188
|
+
const hostname = normalizeHostname(input.hostname);
|
|
189
|
+
let replacesDomain = null;
|
|
190
|
+
if (input.replacesDomainId) {
|
|
191
|
+
replacesDomain = await this.em.findOne(DomainMapping, {
|
|
192
|
+
id: input.replacesDomainId,
|
|
193
|
+
tenantId: input.tenantId
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
const entity = this.em.create(DomainMapping, {
|
|
197
|
+
hostname,
|
|
198
|
+
tenantId: input.tenantId,
|
|
199
|
+
organizationId: input.organizationId,
|
|
200
|
+
replacesDomain: replacesDomain ?? null,
|
|
201
|
+
provider: "traefik",
|
|
202
|
+
status: "pending",
|
|
203
|
+
tlsRetryCount: 0,
|
|
204
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
205
|
+
});
|
|
206
|
+
await this.em.persist(entity).flush();
|
|
207
|
+
await emitCustomerAccountsEvent("customer_accounts.domain_mapping.created", {
|
|
208
|
+
id: entity.id,
|
|
209
|
+
hostname: entity.hostname,
|
|
210
|
+
organizationId: entity.organizationId,
|
|
211
|
+
tenantId: entity.tenantId,
|
|
212
|
+
status: entity.status
|
|
213
|
+
});
|
|
214
|
+
await this.invalidateCacheFor(entity.hostname, entity.organizationId);
|
|
215
|
+
return entity;
|
|
216
|
+
}
|
|
217
|
+
async verify(id) {
|
|
218
|
+
const entity = await this.em.findOne(DomainMapping, { id });
|
|
219
|
+
if (!entity) throw new Error(`DomainMapping ${id} not found`);
|
|
220
|
+
const expectedCname = process.env.CUSTOM_DOMAIN_CNAME_TARGET ?? "";
|
|
221
|
+
const expectedARecord = process.env.CUSTOM_DOMAIN_A_RECORD_TARGET ?? null;
|
|
222
|
+
const now = /* @__PURE__ */ new Date();
|
|
223
|
+
entity.lastDnsCheckAt = now;
|
|
224
|
+
const verification = await this.runDnsVerification(entity.hostname, {
|
|
225
|
+
expectedCname,
|
|
226
|
+
expectedARecord
|
|
227
|
+
});
|
|
228
|
+
if (verification.ok) {
|
|
229
|
+
entity.status = "verified";
|
|
230
|
+
entity.verifiedAt = now;
|
|
231
|
+
entity.dnsFailureReason = null;
|
|
232
|
+
entity.tlsRetryCount = 0;
|
|
233
|
+
entity.tlsFailureReason = null;
|
|
234
|
+
await this.em.persist(entity).flush();
|
|
235
|
+
await emitCustomerAccountsEvent("customer_accounts.domain_mapping.verified", {
|
|
236
|
+
id: entity.id,
|
|
237
|
+
hostname: entity.hostname,
|
|
238
|
+
organizationId: entity.organizationId,
|
|
239
|
+
tenantId: entity.tenantId
|
|
240
|
+
});
|
|
241
|
+
await this.invalidateCacheFor(entity.hostname, entity.organizationId);
|
|
242
|
+
return { domainMapping: entity };
|
|
243
|
+
}
|
|
244
|
+
entity.status = "dns_failed";
|
|
245
|
+
entity.dnsFailureReason = verification.reason;
|
|
246
|
+
await this.em.persist(entity).flush();
|
|
247
|
+
await emitCustomerAccountsEvent("customer_accounts.domain_mapping.dns_failed", {
|
|
248
|
+
id: entity.id,
|
|
249
|
+
hostname: entity.hostname,
|
|
250
|
+
organizationId: entity.organizationId,
|
|
251
|
+
tenantId: entity.tenantId,
|
|
252
|
+
reason: verification.reason,
|
|
253
|
+
detectedRecords: verification.diagnostics.detectedRecords
|
|
254
|
+
});
|
|
255
|
+
await this.invalidateCacheFor(entity.hostname, entity.organizationId);
|
|
256
|
+
return { domainMapping: entity, diagnostics: verification.diagnostics };
|
|
257
|
+
}
|
|
258
|
+
async activate(id) {
|
|
259
|
+
const entity = await this.em.findOne(DomainMapping, { id });
|
|
260
|
+
if (!entity) throw new Error(`DomainMapping ${id} not found`);
|
|
261
|
+
if (entity.status === "active") return entity;
|
|
262
|
+
if (entity.status !== "verified" && entity.status !== "tls_failed") {
|
|
263
|
+
throw new Error(`DomainMapping ${id} cannot transition to active from ${entity.status}`);
|
|
264
|
+
}
|
|
265
|
+
entity.status = "active";
|
|
266
|
+
entity.tlsRetryCount = 0;
|
|
267
|
+
entity.tlsFailureReason = null;
|
|
268
|
+
await this.em.persist(entity).flush();
|
|
269
|
+
await emitCustomerAccountsEvent("customer_accounts.domain_mapping.activated", {
|
|
270
|
+
id: entity.id,
|
|
271
|
+
hostname: entity.hostname,
|
|
272
|
+
organizationId: entity.organizationId,
|
|
273
|
+
tenantId: entity.tenantId
|
|
274
|
+
});
|
|
275
|
+
if (entity.replacesDomain) {
|
|
276
|
+
const replaced = await this.em.findOne(DomainMapping, {
|
|
277
|
+
id: entity.replacesDomain.id
|
|
278
|
+
});
|
|
279
|
+
if (replaced) {
|
|
280
|
+
const replacedHostname = replaced.hostname;
|
|
281
|
+
const replacedOrg = replaced.organizationId;
|
|
282
|
+
this.em.remove(replaced);
|
|
283
|
+
await this.em.flush();
|
|
284
|
+
await emitCustomerAccountsEvent("customer_accounts.domain_mapping.replaced", {
|
|
285
|
+
id: entity.id,
|
|
286
|
+
hostname: entity.hostname,
|
|
287
|
+
organizationId: entity.organizationId,
|
|
288
|
+
tenantId: entity.tenantId,
|
|
289
|
+
replacedDomainId: replaced.id,
|
|
290
|
+
replacedHostname
|
|
291
|
+
});
|
|
292
|
+
await emitCustomerAccountsEvent("customer_accounts.domain_mapping.deleted", {
|
|
293
|
+
id: replaced.id,
|
|
294
|
+
hostname: replacedHostname,
|
|
295
|
+
organizationId: replacedOrg,
|
|
296
|
+
tenantId: replaced.tenantId
|
|
297
|
+
});
|
|
298
|
+
await this.invalidateCacheFor(replacedHostname, replacedOrg);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
await this.invalidateCacheFor(entity.hostname, entity.organizationId);
|
|
302
|
+
return entity;
|
|
303
|
+
}
|
|
304
|
+
async remove(id, scope) {
|
|
305
|
+
const where = { id };
|
|
306
|
+
if (scope?.tenantId) where.tenantId = scope.tenantId;
|
|
307
|
+
const entity = await this.em.findOne(DomainMapping, where);
|
|
308
|
+
if (!entity) return;
|
|
309
|
+
const hostname = entity.hostname;
|
|
310
|
+
const organizationId = entity.organizationId;
|
|
311
|
+
const tenantId = entity.tenantId;
|
|
312
|
+
this.em.remove(entity);
|
|
313
|
+
await this.em.flush();
|
|
314
|
+
await emitCustomerAccountsEvent("customer_accounts.domain_mapping.deleted", {
|
|
315
|
+
id,
|
|
316
|
+
hostname,
|
|
317
|
+
organizationId,
|
|
318
|
+
tenantId
|
|
319
|
+
});
|
|
320
|
+
await this.invalidateCacheFor(hostname, organizationId);
|
|
321
|
+
}
|
|
322
|
+
async healthCheck(id) {
|
|
323
|
+
const entity = await this.em.findOne(DomainMapping, { id });
|
|
324
|
+
if (!entity) throw new Error(`DomainMapping ${id} not found`);
|
|
325
|
+
if (entity.status === "active") return entity;
|
|
326
|
+
if (entity.status !== "verified" && entity.status !== "tls_failed") {
|
|
327
|
+
throw new Error(`DomainMapping ${id} cannot run health check from status ${entity.status}`);
|
|
328
|
+
}
|
|
329
|
+
let lastReason = null;
|
|
330
|
+
for (let attempt = 0; attempt < TLS_HEALTH_CHECK_RETRY_DELAYS_MS.length; attempt++) {
|
|
331
|
+
const result = await this.healthCheckImpl(entity.hostname, TLS_HEALTH_CHECK_TIMEOUT_MS);
|
|
332
|
+
if (result.ok) {
|
|
333
|
+
return this.activate(entity.id);
|
|
334
|
+
}
|
|
335
|
+
lastReason = result.reason ?? "TLS health check failed";
|
|
336
|
+
if (attempt + 1 < TLS_HEALTH_CHECK_RETRY_DELAYS_MS.length) {
|
|
337
|
+
await delay(TLS_HEALTH_CHECK_RETRY_DELAYS_MS[attempt]);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
entity.status = "tls_failed";
|
|
341
|
+
entity.tlsFailureReason = lastReason ?? "TLS health check failed";
|
|
342
|
+
entity.tlsRetryCount = (entity.tlsRetryCount ?? 0) + 1;
|
|
343
|
+
await this.em.persist(entity).flush();
|
|
344
|
+
await emitCustomerAccountsEvent("customer_accounts.domain_mapping.tls_failed", {
|
|
345
|
+
id: entity.id,
|
|
346
|
+
hostname: entity.hostname,
|
|
347
|
+
organizationId: entity.organizationId,
|
|
348
|
+
tenantId: entity.tenantId,
|
|
349
|
+
reason: entity.tlsFailureReason,
|
|
350
|
+
retryCount: entity.tlsRetryCount
|
|
351
|
+
});
|
|
352
|
+
await this.invalidateCacheFor(entity.hostname, entity.organizationId);
|
|
353
|
+
return entity;
|
|
354
|
+
}
|
|
355
|
+
// -------------------------------------------------------------------------
|
|
356
|
+
// Internals
|
|
357
|
+
// -------------------------------------------------------------------------
|
|
358
|
+
async lookupResolveResult(hostname) {
|
|
359
|
+
const row = await this.em.findOne(DomainMapping, { hostname, status: "active" });
|
|
360
|
+
if (!row) return null;
|
|
361
|
+
const org = await this.em.findOne(Organization, { id: row.organizationId });
|
|
362
|
+
return {
|
|
363
|
+
domainMappingId: row.id,
|
|
364
|
+
hostname: row.hostname,
|
|
365
|
+
tenantId: row.tenantId,
|
|
366
|
+
organizationId: row.organizationId,
|
|
367
|
+
orgSlug: org?.slug ?? null,
|
|
368
|
+
status: row.status
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
async invalidateCacheFor(hostname, organizationId) {
|
|
372
|
+
if (!this.cache) return;
|
|
373
|
+
const tags = [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:${hostname}`];
|
|
374
|
+
if (organizationId) tags.push(`${DOMAIN_ROUTING_TAG}:org:${organizationId}`);
|
|
375
|
+
try {
|
|
376
|
+
await this.cache.deleteByTags(tags);
|
|
377
|
+
} catch {
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
async runDnsVerification(hostname, expected) {
|
|
381
|
+
const detectedRecords = [];
|
|
382
|
+
const baseDiag = (overrides) => ({
|
|
383
|
+
expectedCnameTarget: expected.expectedCname,
|
|
384
|
+
expectedARecordTarget: expected.expectedARecord,
|
|
385
|
+
detectedRecords,
|
|
386
|
+
suggestion: overrides?.suggestion ?? "",
|
|
387
|
+
reverseResolve: overrides?.reverseResolve
|
|
388
|
+
});
|
|
389
|
+
let cnameRecords = [];
|
|
390
|
+
try {
|
|
391
|
+
cnameRecords = await this.dns.resolveCname(hostname);
|
|
392
|
+
} catch (err) {
|
|
393
|
+
return {
|
|
394
|
+
ok: false,
|
|
395
|
+
reason: `DNS lookup error (CNAME): ${err.message}`,
|
|
396
|
+
diagnostics: baseDiag({
|
|
397
|
+
suggestion: "DNS lookup failed unexpectedly. Try again in a few minutes."
|
|
398
|
+
})
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
for (const cname of cnameRecords) detectedRecords.push({ type: "CNAME", value: cname });
|
|
402
|
+
if (expected.expectedCname && cnameRecords.length > 0) {
|
|
403
|
+
const expectedCname = tryNormalizeHostname(expected.expectedCname) ?? expected.expectedCname.toLowerCase();
|
|
404
|
+
const match = cnameRecords.some((c) => (tryNormalizeHostname(c) ?? c.toLowerCase()) === expectedCname);
|
|
405
|
+
if (match) {
|
|
406
|
+
return {
|
|
407
|
+
ok: true,
|
|
408
|
+
method: "cname",
|
|
409
|
+
diagnostics: baseDiag({
|
|
410
|
+
suggestion: "CNAME record matches the expected target."
|
|
411
|
+
})
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
return {
|
|
415
|
+
ok: false,
|
|
416
|
+
reason: `CNAME points to ${cnameRecords.join(", ")} instead of ${expected.expectedCname}`,
|
|
417
|
+
diagnostics: baseDiag({
|
|
418
|
+
suggestion: `Update your CNAME record to point to ${expected.expectedCname}.`
|
|
419
|
+
})
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
let aRecords = [];
|
|
423
|
+
try {
|
|
424
|
+
aRecords = await this.dns.resolve4(hostname);
|
|
425
|
+
} catch (err) {
|
|
426
|
+
return {
|
|
427
|
+
ok: false,
|
|
428
|
+
reason: `DNS lookup error (A): ${err.message}`,
|
|
429
|
+
diagnostics: baseDiag({ suggestion: "DNS lookup failed unexpectedly. Try again in a few minutes." })
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
for (const a of aRecords) {
|
|
433
|
+
const proxy = detectProxy(a);
|
|
434
|
+
detectedRecords.push({ type: "A", value: a, ...proxy ? { proxy } : {} });
|
|
435
|
+
}
|
|
436
|
+
if (aRecords.length === 0) {
|
|
437
|
+
return {
|
|
438
|
+
ok: false,
|
|
439
|
+
reason: `No CNAME or A record found for ${hostname}`,
|
|
440
|
+
diagnostics: baseDiag({
|
|
441
|
+
suggestion: expected.expectedARecord ? `For a subdomain, add a CNAME record pointing to ${expected.expectedCname}. For an apex domain, add an A record pointing to ${expected.expectedARecord}. DNS propagation can take up to 48 hours.` : `Add a CNAME record pointing to ${expected.expectedCname}. DNS propagation can take up to 48 hours.`
|
|
442
|
+
})
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
if (expected.expectedARecord && aRecords.includes(expected.expectedARecord)) {
|
|
446
|
+
return {
|
|
447
|
+
ok: true,
|
|
448
|
+
method: "a-record",
|
|
449
|
+
diagnostics: baseDiag({ suggestion: "A record matches the expected target." })
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
const proxiedRecords = aRecords.filter((ip) => isInKnownProxyRange(ip));
|
|
453
|
+
if (proxiedRecords.length > 0) {
|
|
454
|
+
const probe = await this.healthCheckImpl(hostname, TLS_HEALTH_CHECK_TIMEOUT_MS);
|
|
455
|
+
if (probe.ok && probe.originHeaderPresent) {
|
|
456
|
+
return {
|
|
457
|
+
ok: true,
|
|
458
|
+
method: "reverse-resolve",
|
|
459
|
+
diagnostics: baseDiag({
|
|
460
|
+
reverseResolve: { attempted: true, originHeaderPresent: true },
|
|
461
|
+
suggestion: "Domain is proxied \u2014 reverse-resolve confirmed traffic reaches our origin."
|
|
462
|
+
})
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
return {
|
|
466
|
+
ok: false,
|
|
467
|
+
reason: "A record points to a known proxy IP, but reverse-resolve over HTTPS did not reach our server",
|
|
468
|
+
diagnostics: baseDiag({
|
|
469
|
+
reverseResolve: { attempted: true, originHeaderPresent: false },
|
|
470
|
+
suggestion: expected.expectedCname ? `Your DNS uses a proxy. Either disable the proxy and add a CNAME \u2192 ${expected.expectedCname}, or configure your proxy to forward traffic to ${expected.expectedCname}.` : "Disable the DNS proxy or configure it to forward traffic to our platform."
|
|
471
|
+
})
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
return {
|
|
475
|
+
ok: false,
|
|
476
|
+
reason: expected.expectedARecord ? `A record points to ${aRecords.join(", ")} instead of ${expected.expectedARecord}` : `A record points to ${aRecords.join(", ")} but apex-domain registration is not enabled on this deployment`,
|
|
477
|
+
diagnostics: baseDiag({
|
|
478
|
+
suggestion: expected.expectedARecord ? `Update your A record to point to ${expected.expectedARecord}.` : `Apex-domain registration is not enabled on this deployment. Use a subdomain (e.g., shop.${hostname}) and add a CNAME pointing to ${expected.expectedCname}.`
|
|
479
|
+
})
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
const __testing__ = {
|
|
484
|
+
DEFAULT_DNS_RECHECK_THRESHOLD_MS,
|
|
485
|
+
DEFAULT_TLS_MAX_RETRIES,
|
|
486
|
+
TLS_HEALTH_CHECK_RETRY_DELAYS_MS,
|
|
487
|
+
RESOLVE_TTL_MS,
|
|
488
|
+
DOMAIN_ROUTING_TAG,
|
|
489
|
+
defaultHealthCheck,
|
|
490
|
+
defaultDnsResolver,
|
|
491
|
+
Resolver
|
|
492
|
+
};
|
|
493
|
+
export {
|
|
494
|
+
DomainMappingService,
|
|
495
|
+
__testing__
|
|
496
|
+
};
|
|
497
|
+
//# sourceMappingURL=domainMappingService.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/customer_accounts/services/domainMappingService.ts"],
|
|
4
|
+
"sourcesContent": ["import { Resolver, promises as dnsPromises } from 'node:dns'\nimport { request as httpsRequest } from 'node:https'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport {\n DomainMapping,\n type DomainStatus,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { normalizeHostname, tryNormalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\nimport { platformDomains } from '@open-mercato/core/modules/customer_accounts/lib/platformDomains'\nimport { detectProxy, isInKnownProxyRange } from '@open-mercato/core/modules/customer_accounts/lib/proxyRanges'\n\nconst DOMAIN_ROUTING_TAG = 'domain_routing'\nconst RESOLVE_KEY_PREFIX = 'domain_routing:resolve'\nconst ACTIVE_BY_ORG_KEY_PREFIX = 'domain_routing:active-by-org'\nconst RESOLVE_TTL_MS = 5 * 60_000\nconst TLS_HEALTH_CHECK_TIMEOUT_MS = 10_000\nconst TLS_HEALTH_CHECK_RETRY_DELAYS_MS = [1_000, 4_000, 16_000]\nconst DEFAULT_DNS_RECHECK_THRESHOLD_MS = 5 * 60_000\nconst DEFAULT_TLS_MAX_RETRIES = 6\n\nexport type ResolveResult = {\n domainMappingId: string\n hostname: string\n tenantId: string\n organizationId: string\n orgSlug: string | null\n status: DomainStatus\n}\n\nexport type DnsDiagnostics = {\n expectedCnameTarget: string\n expectedARecordTarget: string | null\n detectedRecords: Array<{ type: 'CNAME' | 'A'; value: string; proxy?: string }>\n reverseResolve?: { attempted: boolean; originHeaderPresent: boolean }\n suggestion: string\n}\n\nexport type VerifyResult = {\n domainMapping: DomainMapping\n diagnostics?: DnsDiagnostics\n}\n\nexport type RegisterInput = {\n hostname: string\n organizationId: string\n tenantId: string\n replacesDomainId?: string\n}\n\ntype CacheService = {\n get(key: string, options?: unknown): Promise<unknown>\n set(key: string, value: unknown, options?: { ttl?: number; tags?: string[] }): Promise<void>\n deleteByTags(tags: string[]): Promise<number>\n}\n\ntype DnsResolverContract = {\n resolveCname(hostname: string): Promise<string[]>\n resolve4(hostname: string): Promise<string[]>\n}\n\ntype HealthCheckContract = (hostname: string, timeoutMs: number) => Promise<{\n ok: boolean\n originHeaderPresent: boolean\n reason?: string\n}>\n\nconst defaultDnsResolver: DnsResolverContract = {\n async resolveCname(hostname) {\n try {\n return await dnsPromises.resolveCname(hostname)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENODATA' || code === 'ENOTFOUND') return []\n throw err\n }\n },\n async resolve4(hostname) {\n try {\n return await dnsPromises.resolve4(hostname)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENODATA' || code === 'ENOTFOUND') return []\n throw err\n }\n },\n}\n\nconst defaultHealthCheck: HealthCheckContract = (hostname, timeoutMs) =>\n new Promise((resolve) => {\n const headerName = (process.env.CUSTOMER_DOMAIN_ORIGIN_HEADER ?? 'X-Open-Mercato-Origin').toLowerCase()\n const req = httpsRequest(\n {\n host: hostname,\n port: 443,\n path: '/api/customer_accounts/domain-check',\n method: 'GET',\n headers: { 'X-Domain-Check-Secret': process.env.DOMAIN_CHECK_SECRET ?? '' },\n timeout: timeoutMs,\n },\n (res) => {\n const headerValue = res.headers[headerName]\n const originHeader = Array.isArray(headerValue) ? headerValue[0] : headerValue\n const originHeaderPresent = typeof originHeader === 'string' && originHeader === '1'\n const status = res.statusCode ?? 0\n res.resume() // discard body\n resolve({\n ok: status >= 200 && status < 400,\n originHeaderPresent,\n reason: status >= 200 && status < 400 ? undefined : `HTTP ${status}`,\n })\n },\n )\n req.on('timeout', () => {\n req.destroy(new Error('TLS health check timed out'))\n })\n req.on('error', (err) => {\n resolve({ ok: false, originHeaderPresent: false, reason: (err as Error).message })\n })\n req.end()\n })\n\nexport class DomainMappingService {\n private cache: CacheService | null\n private dns: DnsResolverContract\n private healthCheckImpl: HealthCheckContract\n\n constructor(\n private em: EntityManager,\n deps?: {\n cacheService?: CacheService\n dnsResolver?: DnsResolverContract\n healthCheck?: HealthCheckContract\n },\n ) {\n this.cache = deps?.cacheService ?? null\n this.dns = deps?.dnsResolver ?? defaultDnsResolver\n this.healthCheckImpl = deps?.healthCheck ?? defaultHealthCheck\n }\n\n // -------------------------------------------------------------------------\n // Read paths\n // -------------------------------------------------------------------------\n\n async findById(id: string, scope?: { tenantId?: string }): Promise<DomainMapping | null> {\n const where: Record<string, unknown> = { id }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n return this.em.findOne(DomainMapping, where as never)\n }\n\n async findByOrganization(\n organizationId: string,\n scope?: { tenantId?: string },\n ): Promise<DomainMapping[]> {\n const where: Record<string, unknown> = { organizationId }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n return this.em.find(DomainMapping, where as never, { orderBy: { createdAt: 'asc' } })\n }\n\n async resolveByHostname(input: string): Promise<ResolveResult | null> {\n const hostname = tryNormalizeHostname(input)\n if (!hostname) return null\n if (platformDomains().includes(hostname)) return null\n\n const cacheKey = `${RESOLVE_KEY_PREFIX}:${hostname}`\n if (this.cache) {\n const cached = (await this.cache.get(cacheKey)) as ResolveResult | null | undefined\n if (cached !== undefined && cached !== null) return cached\n }\n\n const result = await this.lookupResolveResult(hostname)\n if (this.cache) {\n await this.cache.set(cacheKey, result, {\n ttl: RESOLVE_TTL_MS,\n tags: [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:${hostname}`],\n })\n }\n return result\n }\n\n async isAllowedForTls(input: string): Promise<{ organizationId: string; status: DomainStatus } | null> {\n const hostname = tryNormalizeHostname(input)\n if (!hostname) return null\n if (platformDomains().includes(hostname)) return null\n const row = await this.em.findOne(DomainMapping, {\n hostname,\n status: { $in: ['active', 'verified'] },\n } as never)\n if (!row) return null\n return { organizationId: row.organizationId, status: row.status }\n }\n\n async resolveActiveByOrg(organizationId: string): Promise<{ hostname: string; status: DomainStatus } | null> {\n const cacheKey = `${ACTIVE_BY_ORG_KEY_PREFIX}:${organizationId}`\n if (this.cache) {\n const cached = (await this.cache.get(cacheKey)) as { hostname: string; status: DomainStatus } | null | undefined\n if (cached !== undefined && cached !== null) return cached\n }\n\n const row = await this.em.findOne(DomainMapping, {\n organizationId,\n status: 'active',\n } as never)\n const result = row ? { hostname: row.hostname, status: row.status } : null\n\n if (this.cache) {\n await this.cache.set(cacheKey, result, {\n ttl: RESOLVE_TTL_MS,\n tags: [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:org:${organizationId}`],\n })\n }\n return result\n }\n\n async resolveAll(): Promise<ResolveResult[]> {\n const rows = await this.em.find(DomainMapping, { status: 'active' } as never)\n if (rows.length === 0) return []\n const orgIds = Array.from(new Set(rows.map((r) => r.organizationId)))\n const orgs = await this.em.find(Organization, { id: { $in: orgIds } } as never)\n const slugByOrg = new Map<string, string | null>(orgs.map((o) => [o.id, o.slug ?? null]))\n\n return rows.map<ResolveResult>((row) => ({\n domainMappingId: row.id,\n hostname: row.hostname,\n tenantId: row.tenantId,\n organizationId: row.organizationId,\n orgSlug: slugByOrg.get(row.organizationId) ?? null,\n status: row.status,\n }))\n }\n\n // -------------------------------------------------------------------------\n // Worker queries\n // -------------------------------------------------------------------------\n\n async findPendingVerification(threshold?: { olderThanMs?: number }): Promise<DomainMapping[]> {\n const olderThan = threshold?.olderThanMs ?? DEFAULT_DNS_RECHECK_THRESHOLD_MS\n const cutoff = new Date(Date.now() - olderThan)\n return this.em.find(\n DomainMapping,\n {\n status: { $in: ['pending', 'dns_failed'] },\n $or: [{ lastDnsCheckAt: null }, { lastDnsCheckAt: { $lt: cutoff } }],\n } as never,\n { orderBy: { lastDnsCheckAt: 'asc' } },\n )\n }\n\n async findPendingTls(options?: { maxRetries?: number; batchSize?: number }): Promise<DomainMapping[]> {\n const maxRetries = options?.maxRetries ?? DEFAULT_TLS_MAX_RETRIES\n const limit = options?.batchSize ?? 50\n return this.em.find(\n DomainMapping,\n {\n $or: [\n { status: 'verified' },\n { status: 'tls_failed', tlsRetryCount: { $lt: maxRetries } },\n ],\n } as never,\n { orderBy: { updatedAt: 'asc' }, limit },\n )\n }\n\n // -------------------------------------------------------------------------\n // Write paths\n // -------------------------------------------------------------------------\n\n async register(input: RegisterInput): Promise<DomainMapping> {\n const hostname = normalizeHostname(input.hostname)\n\n let replacesDomain: DomainMapping | null = null\n if (input.replacesDomainId) {\n replacesDomain = await this.em.findOne(DomainMapping, {\n id: input.replacesDomainId,\n tenantId: input.tenantId,\n } as never)\n }\n\n const entity = this.em.create(DomainMapping, {\n hostname,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n replacesDomain: replacesDomain ?? null,\n provider: 'traefik',\n status: 'pending',\n tlsRetryCount: 0,\n createdAt: new Date(),\n } as never)\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.created', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n status: entity.status,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n\n return entity\n }\n\n async verify(id: string): Promise<VerifyResult> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n\n const expectedCname = process.env.CUSTOM_DOMAIN_CNAME_TARGET ?? ''\n const expectedARecord = process.env.CUSTOM_DOMAIN_A_RECORD_TARGET ?? null\n const now = new Date()\n entity.lastDnsCheckAt = now\n\n const verification = await this.runDnsVerification(entity.hostname, {\n expectedCname,\n expectedARecord,\n })\n\n if (verification.ok) {\n entity.status = 'verified'\n entity.verifiedAt = now\n entity.dnsFailureReason = null\n entity.tlsRetryCount = 0\n entity.tlsFailureReason = null\n await this.em.persist(entity).flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.verified', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return { domainMapping: entity }\n }\n\n entity.status = 'dns_failed'\n entity.dnsFailureReason = verification.reason\n await this.em.persist(entity).flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.dns_failed', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n reason: verification.reason,\n detectedRecords: verification.diagnostics.detectedRecords,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return { domainMapping: entity, diagnostics: verification.diagnostics }\n }\n\n async activate(id: string): Promise<DomainMapping> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n if (entity.status === 'active') return entity\n if (entity.status !== 'verified' && entity.status !== 'tls_failed') {\n throw new Error(`DomainMapping ${id} cannot transition to active from ${entity.status}`)\n }\n\n entity.status = 'active'\n entity.tlsRetryCount = 0\n entity.tlsFailureReason = null\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.activated', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n } as never)\n\n if (entity.replacesDomain) {\n const replaced = await this.em.findOne(DomainMapping, {\n id: (entity.replacesDomain as unknown as { id: string }).id,\n } as never)\n if (replaced) {\n const replacedHostname = replaced.hostname\n const replacedOrg = replaced.organizationId\n this.em.remove(replaced)\n await this.em.flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.replaced', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n replacedDomainId: replaced.id,\n replacedHostname,\n } as never)\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.deleted', {\n id: replaced.id,\n hostname: replacedHostname,\n organizationId: replacedOrg,\n tenantId: replaced.tenantId,\n } as never)\n await this.invalidateCacheFor(replacedHostname, replacedOrg)\n }\n }\n\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return entity\n }\n\n async remove(id: string, scope?: { tenantId?: string }): Promise<void> {\n const where: Record<string, unknown> = { id }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n const entity = await this.em.findOne(DomainMapping, where as never)\n if (!entity) return\n\n const hostname = entity.hostname\n const organizationId = entity.organizationId\n const tenantId = entity.tenantId\n\n this.em.remove(entity)\n await this.em.flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.deleted', {\n id,\n hostname,\n organizationId,\n tenantId,\n } as never)\n await this.invalidateCacheFor(hostname, organizationId)\n }\n\n async healthCheck(id: string): Promise<DomainMapping> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n if (entity.status === 'active') return entity\n if (entity.status !== 'verified' && entity.status !== 'tls_failed') {\n throw new Error(`DomainMapping ${id} cannot run health check from status ${entity.status}`)\n }\n\n let lastReason: string | null = null\n for (let attempt = 0; attempt < TLS_HEALTH_CHECK_RETRY_DELAYS_MS.length; attempt++) {\n const result = await this.healthCheckImpl(entity.hostname, TLS_HEALTH_CHECK_TIMEOUT_MS)\n if (result.ok) {\n return this.activate(entity.id)\n }\n lastReason = result.reason ?? 'TLS health check failed'\n if (attempt + 1 < TLS_HEALTH_CHECK_RETRY_DELAYS_MS.length) {\n await delay(TLS_HEALTH_CHECK_RETRY_DELAYS_MS[attempt])\n }\n }\n\n entity.status = 'tls_failed'\n entity.tlsFailureReason = lastReason ?? 'TLS health check failed'\n entity.tlsRetryCount = (entity.tlsRetryCount ?? 0) + 1\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.tls_failed', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n reason: entity.tlsFailureReason,\n retryCount: entity.tlsRetryCount,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return entity\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async lookupResolveResult(hostname: string): Promise<ResolveResult | null> {\n const row = await this.em.findOne(DomainMapping, { hostname, status: 'active' } as never)\n if (!row) return null\n const org = await this.em.findOne(Organization, { id: row.organizationId } as never)\n return {\n domainMappingId: row.id,\n hostname: row.hostname,\n tenantId: row.tenantId,\n organizationId: row.organizationId,\n orgSlug: org?.slug ?? null,\n status: row.status,\n }\n }\n\n private async invalidateCacheFor(hostname: string, organizationId: string | null): Promise<void> {\n if (!this.cache) return\n const tags = [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:${hostname}`]\n if (organizationId) tags.push(`${DOMAIN_ROUTING_TAG}:org:${organizationId}`)\n try {\n await this.cache.deleteByTags(tags)\n } catch {\n // Cache invalidation is best-effort \u2014 TTL backstop ensures eventual consistency.\n }\n }\n\n private async runDnsVerification(\n hostname: string,\n expected: { expectedCname: string; expectedARecord: string | null },\n ): Promise<\n | {\n ok: true\n method: 'cname' | 'a-record' | 'reverse-resolve'\n diagnostics: DnsDiagnostics\n }\n | { ok: false; reason: string; diagnostics: DnsDiagnostics }\n > {\n const detectedRecords: DnsDiagnostics['detectedRecords'] = []\n const baseDiag = (overrides?: Partial<DnsDiagnostics>): DnsDiagnostics => ({\n expectedCnameTarget: expected.expectedCname,\n expectedARecordTarget: expected.expectedARecord,\n detectedRecords,\n suggestion: overrides?.suggestion ?? '',\n reverseResolve: overrides?.reverseResolve,\n })\n\n // Phase 1: CNAME\n let cnameRecords: string[] = []\n try {\n cnameRecords = await this.dns.resolveCname(hostname)\n } catch (err) {\n return {\n ok: false,\n reason: `DNS lookup error (CNAME): ${(err as Error).message}`,\n diagnostics: baseDiag({\n suggestion: 'DNS lookup failed unexpectedly. Try again in a few minutes.',\n }),\n }\n }\n for (const cname of cnameRecords) detectedRecords.push({ type: 'CNAME', value: cname })\n\n if (expected.expectedCname && cnameRecords.length > 0) {\n const expectedCname = tryNormalizeHostname(expected.expectedCname) ?? expected.expectedCname.toLowerCase()\n const match = cnameRecords.some((c) => (tryNormalizeHostname(c) ?? c.toLowerCase()) === expectedCname)\n if (match) {\n return {\n ok: true,\n method: 'cname',\n diagnostics: baseDiag({\n suggestion: 'CNAME record matches the expected target.',\n }),\n }\n }\n return {\n ok: false,\n reason: `CNAME points to ${cnameRecords.join(', ')} instead of ${expected.expectedCname}`,\n diagnostics: baseDiag({\n suggestion: `Update your CNAME record to point to ${expected.expectedCname}.`,\n }),\n }\n }\n\n // Phase 2: A record\n let aRecords: string[] = []\n try {\n aRecords = await this.dns.resolve4(hostname)\n } catch (err) {\n return {\n ok: false,\n reason: `DNS lookup error (A): ${(err as Error).message}`,\n diagnostics: baseDiag({ suggestion: 'DNS lookup failed unexpectedly. Try again in a few minutes.' }),\n }\n }\n for (const a of aRecords) {\n const proxy = detectProxy(a)\n detectedRecords.push({ type: 'A', value: a, ...(proxy ? { proxy } : {}) })\n }\n\n if (aRecords.length === 0) {\n return {\n ok: false,\n reason: `No CNAME or A record found for ${hostname}`,\n diagnostics: baseDiag({\n suggestion: expected.expectedARecord\n ? `For a subdomain, add a CNAME record pointing to ${expected.expectedCname}. For an apex domain, add an A record pointing to ${expected.expectedARecord}. DNS propagation can take up to 48 hours.`\n : `Add a CNAME record pointing to ${expected.expectedCname}. DNS propagation can take up to 48 hours.`,\n }),\n }\n }\n\n if (expected.expectedARecord && aRecords.includes(expected.expectedARecord)) {\n return {\n ok: true,\n method: 'a-record',\n diagnostics: baseDiag({ suggestion: 'A record matches the expected target.' }),\n }\n }\n\n // Phase 3: reverse-resolve through proxy\n const proxiedRecords = aRecords.filter((ip) => isInKnownProxyRange(ip))\n if (proxiedRecords.length > 0) {\n const probe = await this.healthCheckImpl(hostname, TLS_HEALTH_CHECK_TIMEOUT_MS)\n if (probe.ok && probe.originHeaderPresent) {\n return {\n ok: true,\n method: 'reverse-resolve',\n diagnostics: baseDiag({\n reverseResolve: { attempted: true, originHeaderPresent: true },\n suggestion: 'Domain is proxied \u2014 reverse-resolve confirmed traffic reaches our origin.',\n }),\n }\n }\n return {\n ok: false,\n reason: 'A record points to a known proxy IP, but reverse-resolve over HTTPS did not reach our server',\n diagnostics: baseDiag({\n reverseResolve: { attempted: true, originHeaderPresent: false },\n suggestion: expected.expectedCname\n ? `Your DNS uses a proxy. Either disable the proxy and add a CNAME \u2192 ${expected.expectedCname}, or configure your proxy to forward traffic to ${expected.expectedCname}.`\n : 'Disable the DNS proxy or configure it to forward traffic to our platform.',\n }),\n }\n }\n\n return {\n ok: false,\n reason: expected.expectedARecord\n ? `A record points to ${aRecords.join(', ')} instead of ${expected.expectedARecord}`\n : `A record points to ${aRecords.join(', ')} but apex-domain registration is not enabled on this deployment`,\n diagnostics: baseDiag({\n suggestion: expected.expectedARecord\n ? `Update your A record to point to ${expected.expectedARecord}.`\n : `Apex-domain registration is not enabled on this deployment. Use a subdomain (e.g., shop.${hostname}) and add a CNAME pointing to ${expected.expectedCname}.`,\n }),\n }\n }\n}\n\n// Re-exported for tests; allow injection of fakes.\nexport const __testing__ = {\n DEFAULT_DNS_RECHECK_THRESHOLD_MS,\n DEFAULT_TLS_MAX_RETRIES,\n TLS_HEALTH_CHECK_RETRY_DELAYS_MS,\n RESOLVE_TTL_MS,\n DOMAIN_ROUTING_TAG,\n defaultHealthCheck,\n defaultDnsResolver,\n Resolver,\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,UAAU,YAAY,mBAAmB;AAClD,SAAS,WAAW,oBAAoB;AACxC,SAAS,cAAc,aAAa;AAEpC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAC1C,SAAS,mBAAmB,4BAA4B;AACxD,SAAS,uBAAuB;AAChC,SAAS,aAAa,2BAA2B;AAEjD,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AACjC,MAAM,iBAAiB,IAAI;AAC3B,MAAM,8BAA8B;AACpC,MAAM,mCAAmC,CAAC,KAAO,KAAO,IAAM;AAC9D,MAAM,mCAAmC,IAAI;AAC7C,MAAM,0BAA0B;AAgDhC,MAAM,qBAA0C;AAAA,EAC9C,MAAM,aAAa,UAAU;AAC3B,QAAI;AACF,aAAO,MAAM,YAAY,aAAa,QAAQ;AAAA,IAChD,SAAS,KAAK;AACZ,YAAM,OAAQ,IAA8B;AAC5C,UAAI,SAAS,aAAa,SAAS,YAAa,QAAO,CAAC;AACxD,YAAM;AAAA,IACR;AAA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AgB,UAAU,2BAA2B;AAC9E,UAAI,MAAM,MAAM,MAAM,qBAAqB;AACzC,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,QAAQ;AAAA,UACR,aAAa,SAAS;AAAA,YACpB,gBAAgB,EAAE,WAAW,MAAM,qBAAqB,KAAK;AAAA,YAC7D,YAAY;AAAA,UACd,CAAC;AAAA,QACH;AAAA,MACF;AACA,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,QAAQ;AAAA,QACR,aAAa,SAAS;AAAA,UACpB,gBAAgB,EAAE,WAAW,MAAM,qBAAqB,MAAM;AAAA,UAC9D,YAAY,SAAS,gBACjB,0EAAqE,SAAS,aAAa,mDAAmD,SAAS,aAAa,MACpK;AAAA,QACN,CAAC;AAAA,MACH;AAAA,IACF;AAEA,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,SAAS,kBACb,sBAAsB,SAAS,KAAK,IAAI,CAAC,eAAe,SAAS,eAAe,KAChF,sBAAsB,SAAS,KAAK,IAAI,CAAC;AAAA,MAC7C,aAAa,SAAS;AAAA,QACpB,YAAY,SAAS,kBACjB,oCAAoC,SAAS,eAAe,MAC5D,2FAA2F,QAAQ,iCAAiC,SAAS,aAAa;AAAA,MAChK,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAGO,MAAM,cAAc;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -6,6 +6,47 @@ import {
|
|
|
6
6
|
CustomerUser,
|
|
7
7
|
CustomerUserRole
|
|
8
8
|
} from "@open-mercato/core/modules/customer_accounts/data/entities";
|
|
9
|
+
const DOMAIN_VERIFICATION_SCHEDULE_ID = "5e9ef5fc-1f4d-5b3d-8b58-8e1a5a4d1001";
|
|
10
|
+
const DOMAIN_TLS_RETRY_SCHEDULE_ID = "5e9ef5fc-1f4d-5b3d-8b58-8e1a5a4d1002";
|
|
11
|
+
function intervalSecondsFromEnv(envName, fallbackSeconds) {
|
|
12
|
+
const parsed = Number.parseInt(process.env[envName] ?? "", 10);
|
|
13
|
+
const seconds = Number.isFinite(parsed) && parsed > 0 ? parsed : fallbackSeconds;
|
|
14
|
+
return `${seconds}s`;
|
|
15
|
+
}
|
|
16
|
+
async function registerDomainSchedules(container) {
|
|
17
|
+
if (typeof container.hasRegistration !== "function" || !container.hasRegistration("schedulerService")) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const schedulerService = container.resolve("schedulerService");
|
|
21
|
+
await schedulerService.register({
|
|
22
|
+
id: DOMAIN_VERIFICATION_SCHEDULE_ID,
|
|
23
|
+
name: "Custom domain \u2014 DNS auto-verification",
|
|
24
|
+
description: "Re-runs DNS verification for custom-domain mappings stuck in pending or dns_failed, and triggers TLS health checks on success.",
|
|
25
|
+
scopeType: "system",
|
|
26
|
+
scheduleType: "interval",
|
|
27
|
+
scheduleValue: intervalSecondsFromEnv("DOMAIN_AUTO_VERIFY_INTERVAL_SECONDS", 300),
|
|
28
|
+
timezone: "UTC",
|
|
29
|
+
targetType: "queue",
|
|
30
|
+
targetQueue: "domain-verification",
|
|
31
|
+
sourceType: "module",
|
|
32
|
+
sourceModule: "customer_accounts",
|
|
33
|
+
isEnabled: true
|
|
34
|
+
});
|
|
35
|
+
await schedulerService.register({
|
|
36
|
+
id: DOMAIN_TLS_RETRY_SCHEDULE_ID,
|
|
37
|
+
name: "Custom domain \u2014 TLS retry",
|
|
38
|
+
description: "Retries TLS certificate provisioning for verified or tls_failed custom-domain mappings, with batch cap and adaptive backoff on Let's Encrypt rate limits.",
|
|
39
|
+
scopeType: "system",
|
|
40
|
+
scheduleType: "interval",
|
|
41
|
+
scheduleValue: intervalSecondsFromEnv("DOMAIN_TLS_RETRY_INTERVAL_SECONDS", 1800),
|
|
42
|
+
timezone: "UTC",
|
|
43
|
+
targetType: "queue",
|
|
44
|
+
targetQueue: "domain-tls-retry",
|
|
45
|
+
sourceType: "module",
|
|
46
|
+
sourceModule: "customer_accounts",
|
|
47
|
+
isEnabled: true
|
|
48
|
+
});
|
|
49
|
+
}
|
|
9
50
|
const DEFAULT_ROLES = [
|
|
10
51
|
{
|
|
11
52
|
name: "Portal Admin",
|
|
@@ -124,7 +165,7 @@ const setup = {
|
|
|
124
165
|
async onTenantCreated({ em, tenantId, organizationId }) {
|
|
125
166
|
await seedDefaultRoles(em, { tenantId, organizationId });
|
|
126
167
|
},
|
|
127
|
-
async seedDefaults({ em, tenantId, organizationId }) {
|
|
168
|
+
async seedDefaults({ em, tenantId, organizationId, container }) {
|
|
128
169
|
await seedDefaultRoles(em, { tenantId, organizationId });
|
|
129
170
|
try {
|
|
130
171
|
const { getModules } = await import("@open-mercato/shared/lib/modules/registry");
|
|
@@ -132,6 +173,12 @@ const setup = {
|
|
|
132
173
|
await ensureDefaultCustomerRoleAcls(em, tenantId, allModules);
|
|
133
174
|
} catch {
|
|
134
175
|
}
|
|
176
|
+
try {
|
|
177
|
+
await registerDomainSchedules(
|
|
178
|
+
container
|
|
179
|
+
);
|
|
180
|
+
} catch {
|
|
181
|
+
}
|
|
135
182
|
},
|
|
136
183
|
async seedExamples({ em, tenantId, organizationId }) {
|
|
137
184
|
const BCRYPT_COST = 10;
|