@aglyn/tenant-data-admin 1.0.0-beta.269 → 1.0.0-beta.271

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.
Files changed (77) hide show
  1. package/package.json +7 -7
  2. package/src/lib/render-cache.d.ts +10 -3
  3. package/src/lib/render-cache.js +10 -3
  4. package/src/lib/render-cache.js.map +1 -1
  5. package/src/lib/server/append-only-history-write.d.ts +38 -0
  6. package/src/lib/server/append-only-history-write.js +60 -0
  7. package/src/lib/server/append-only-history-write.js.map +1 -0
  8. package/src/lib/server/billing-addons.d.ts +58 -30
  9. package/src/lib/server/billing-addons.js +102 -77
  10. package/src/lib/server/billing-addons.js.map +1 -1
  11. package/src/lib/server/bundle-links.d.ts +166 -0
  12. package/src/lib/server/bundle-links.js +286 -0
  13. package/src/lib/server/bundle-links.js.map +1 -0
  14. package/src/lib/server/client-build.d.ts +74 -0
  15. package/src/lib/server/client-build.js +264 -0
  16. package/src/lib/server/client-build.js.map +1 -0
  17. package/src/lib/server/configured-url-fetch.d.ts +26 -0
  18. package/src/lib/server/configured-url-fetch.js +68 -0
  19. package/src/lib/server/configured-url-fetch.js.map +1 -1
  20. package/src/lib/server/custom-domain-redirects.d.ts +50 -0
  21. package/src/lib/server/custom-domain-redirects.js +61 -0
  22. package/src/lib/server/custom-domain-redirects.js.map +1 -0
  23. package/src/lib/server/host-custom-domain.d.ts +125 -0
  24. package/src/lib/server/host-custom-domain.js +395 -0
  25. package/src/lib/server/host-custom-domain.js.map +1 -0
  26. package/src/lib/server/host-memberships.d.ts +35 -2
  27. package/src/lib/server/host-memberships.js +63 -2
  28. package/src/lib/server/host-memberships.js.map +1 -1
  29. package/src/lib/server/host-released-names.d.ts +1 -2
  30. package/src/lib/server/host-released-names.js +4 -2
  31. package/src/lib/server/host-released-names.js.map +1 -1
  32. package/src/lib/server/media-photo-links.d.ts +196 -0
  33. package/src/lib/server/media-photo-links.js +290 -0
  34. package/src/lib/server/media-photo-links.js.map +1 -0
  35. package/src/lib/server/org-billing.d.ts +4 -2
  36. package/src/lib/server/org-billing.js +5 -0
  37. package/src/lib/server/org-billing.js.map +1 -1
  38. package/src/lib/server/organizations.d.ts +25 -1
  39. package/src/lib/server/organizations.js +62 -2
  40. package/src/lib/server/organizations.js.map +1 -1
  41. package/src/lib/server/personal-data-export.js +21 -1
  42. package/src/lib/server/personal-data-export.js.map +1 -1
  43. package/src/lib/server/push-delivery.js +32 -14
  44. package/src/lib/server/push-delivery.js.map +1 -1
  45. package/src/lib/server/site-care-emails.d.ts +52 -0
  46. package/src/lib/server/site-care-emails.js +97 -0
  47. package/src/lib/server/site-care-emails.js.map +1 -0
  48. package/src/lib/server/site-care-inbound.d.ts +80 -0
  49. package/src/lib/server/site-care-inbound.js +171 -0
  50. package/src/lib/server/site-care-inbound.js.map +1 -0
  51. package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
  52. package/src/lib/server/site-care-project-reconcile.js +211 -0
  53. package/src/lib/server/site-care-project-reconcile.js.map +1 -0
  54. package/src/lib/server/site-care-project-stripe.d.ts +114 -0
  55. package/src/lib/server/site-care-project-stripe.js +305 -0
  56. package/src/lib/server/site-care-project-stripe.js.map +1 -0
  57. package/src/lib/server/site-care-projects.d.ts +169 -0
  58. package/src/lib/server/site-care-projects.js +882 -0
  59. package/src/lib/server/site-care-projects.js.map +1 -0
  60. package/src/lib/server/site-care-reconcile.d.ts +81 -0
  61. package/src/lib/server/site-care-reconcile.js +349 -0
  62. package/src/lib/server/site-care-reconcile.js.map +1 -0
  63. package/src/lib/server/site-care-requests.d.ts +243 -0
  64. package/src/lib/server/site-care-requests.js +1414 -0
  65. package/src/lib/server/site-care-requests.js.map +1 -0
  66. package/src/lib/server/site-care-stripe.d.ts +175 -0
  67. package/src/lib/server/site-care-stripe.js +375 -0
  68. package/src/lib/server/site-care-stripe.js.map +1 -0
  69. package/src/lib/server/tenant-dns-check.d.ts +58 -0
  70. package/src/lib/server/tenant-dns-check.js +197 -0
  71. package/src/lib/server/tenant-dns-check.js.map +1 -0
  72. package/src/lib/server/upgrade-proposal.d.ts +40 -1
  73. package/src/lib/server/upgrade-proposal.js +92 -50
  74. package/src/lib/server/upgrade-proposal.js.map +1 -1
  75. package/src/tenancy.d.ts +5 -0
  76. package/src/tenancy.js +10 -0
  77. package/src/tenancy.js.map +1 -1
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type ClientBuildIntent, type ClientBuildRecord } from '@aglyn/aglyn/app-utils/client-build';
18
+ import { type PluginSmsSendOutcome } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging';
19
+ /** A refusal the route answers with its status. */
20
+ export declare class ClientBuildError extends Error {
21
+ readonly status: number;
22
+ constructor(message: string, status: number);
23
+ }
24
+ /** A stored record, read back defensively; `null` when the workspace has none. */
25
+ export declare function readClientBuildRecord(raw: unknown): ClientBuildRecord | null;
26
+ /** The workspace's build, or `null` before one was started. */
27
+ export declare function loadClientBuild(orgId: string): Promise<ClientBuildRecord | null>;
28
+ /**
29
+ * The intent the hand-off proposes (AGL-3955, AGL-3956): what the build left
30
+ * for the owner's checkout, or `null` when the workspace was not built here.
31
+ */
32
+ export declare function loadClientBuildIntent(orgId: string): Promise<ClientBuildIntent | null>;
33
+ /** What a save may change; each part left out keeps what is stored. */
34
+ export interface ClientBuildPatch {
35
+ intake?: unknown;
36
+ domain?: unknown;
37
+ hostId?: unknown;
38
+ host?: unknown;
39
+ jobId?: unknown;
40
+ /** `true` once the starter site was given instead of a guided start. */
41
+ starter?: unknown;
42
+ }
43
+ /**
44
+ * Writes the build, merged over what is stored. The intake and the domain
45
+ * are validated as the screen validated them; the intent is derived, never
46
+ * taken from the body: the plan the workspace was comped on, Site Care, and
47
+ * the domain the Domain step recorded. A site is accepted only when it
48
+ * belongs to this workspace.
49
+ */
50
+ export declare function saveClientBuild(options: {
51
+ orgId: string;
52
+ actorUid: string;
53
+ patch: ClientBuildPatch;
54
+ now?: number;
55
+ }): Promise<ClientBuildRecord>;
56
+ /** What sending the preview came to, per channel. */
57
+ export interface ClientBuildPreviewOutcome {
58
+ emailed: boolean;
59
+ /** The text's outcome; `none` when the intake has no phone to text. */
60
+ text: PluginSmsSendOutcome['status'] | 'none' | 'unavailable';
61
+ previewUrl: string;
62
+ siteAddress: string | null;
63
+ }
64
+ /**
65
+ * Sends the owner the preview: a text and an email with the link to the site
66
+ * as it is now and the address it will live at. Only once the site has a
67
+ * published page, since the link would otherwise open an empty site. Each
68
+ * channel is attempted on its own and reported; the send is an Audit Log row.
69
+ */
70
+ export declare function sendClientBuildPreview(options: {
71
+ orgId: string;
72
+ actorUid: string;
73
+ now?: number;
74
+ }): Promise<ClientBuildPreviewOutcome>;
@@ -0,0 +1,264 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { CLIENT_BUILD_COLLECTION, CLIENT_BUILD_DOC_ID, clientBuildIntent, clientBuildPhone, clientBuildPreviewText, clientBuildSiteAddress, EMPTY_CLIENT_BUILD_INTAKE, parseClientBuildDomain, parseClientBuildIntake, readClientBuildIntent } from "@aglyn/aglyn/app-utils/client-build";
18
+ import { hostPublicOrigin } from "@aglyn/aglyn/app-utils/host-naming";
19
+ import { readOrgPlanComp } from "@aglyn/aglyn/app-utils/plan-entitlements";
20
+ import { PLATFORM_BRAND_NAME } from "@aglyn/aglyn/app-utils/platform-brand";
21
+ import { pluginSmsMessaging } from "@aglyn/aglyn/plugin-manager/plugin-sms-messaging";
22
+ import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
23
+ import { addAdminAudit } from "./admin-audit-write.js";
24
+ import { meterOrgEmail } from "./email-metering.js";
25
+ import firebaseAdmin from "./firebase-admin.js";
26
+ import { renderSystemEmailContent, systemEmailBrand } from "./render-system-email.js";
27
+ /**
28
+ * THE ONE-SCREEN BUILD FOR A CLIENT, ON THE SERVER (AGL-3958).
29
+ *
30
+ * One record per workspace, at `orgs/{orgId}/clientBuild/current`, which the
31
+ * rules open to no client: the owner's phone and email are staff's to hold
32
+ * until the owner joins, and the org document is read by every member. Only
33
+ * `/api/admin/client-build` (staff) calls this module.
34
+ */ const firestore = ()=>firebaseAdmin.app().firestore();
35
+ /** A refusal the route answers with its status. */ export class ClientBuildError extends Error {
36
+ constructor(message, status){
37
+ super(message), this.status = status;
38
+ this.name = 'ClientBuildError';
39
+ }
40
+ }
41
+ function recordRef(orgId) {
42
+ return firestore().collection('orgs').doc(orgId).collection(CLIENT_BUILD_COLLECTION).doc(CLIENT_BUILD_DOC_ID);
43
+ }
44
+ /** A stored record, read back defensively; `null` when the workspace has none. */ export function readClientBuildRecord(raw) {
45
+ var _time, _text;
46
+ if (!raw || typeof raw !== 'object') return null;
47
+ const source = raw;
48
+ const intake = parseClientBuildIntake(source['intake']);
49
+ const domain = source['domain'] ? parseClientBuildDomain(source['domain']) : null;
50
+ const intent = readClientBuildIntent(source['intent']);
51
+ const text = (value)=>typeof value === 'string' && value ? value : null;
52
+ const time = (value)=>typeof value === 'number' && Number.isFinite(value) ? value : null;
53
+ return {
54
+ // A stored intake that no longer validates is still the one staff typed.
55
+ intake: typeof intake === 'string' ? _extends({}, EMPTY_CLIENT_BUILD_INTAKE, source['intake']) : intake,
56
+ domain: typeof domain === 'string' ? null : domain,
57
+ intent: intent != null ? intent : clientBuildIntent({
58
+ plan: null,
59
+ domain: typeof domain === 'string' ? null : domain
60
+ }),
61
+ hostId: text(source['hostId']),
62
+ host: text(source['host']),
63
+ jobId: text(source['jobId']),
64
+ starter: source['starter'] === true,
65
+ previewSentAt: time(source['previewSentAt']),
66
+ updatedAt: (_time = time(source['updatedAt'])) != null ? _time : 0,
67
+ updatedBy: (_text = text(source['updatedBy'])) != null ? _text : ''
68
+ };
69
+ }
70
+ /** The workspace's build, or `null` before one was started. */ export async function loadClientBuild(orgId) {
71
+ const snapshot = await recordRef(orgId).get();
72
+ return snapshot.exists ? readClientBuildRecord(snapshot.data()) : null;
73
+ }
74
+ /**
75
+ * The intent the hand-off proposes (AGL-3955, AGL-3956): what the build left
76
+ * for the owner's checkout, or `null` when the workspace was not built here.
77
+ */ export async function loadClientBuildIntent(orgId) {
78
+ var _ref;
79
+ var _this;
80
+ return (_ref = (_this = await loadClientBuild(orgId)) == null ? void 0 : _this.intent) != null ? _ref : null;
81
+ }
82
+ const ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
83
+ /**
84
+ * Writes the build, merged over what is stored. The intake and the domain
85
+ * are validated as the screen validated them; the intent is derived, never
86
+ * taken from the body: the plan the workspace was comped on, Site Care, and
87
+ * the domain the Domain step recorded. A site is accepted only when it
88
+ * belongs to this workspace.
89
+ */ export async function saveClientBuild(options) {
90
+ var _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _options_now;
91
+ var _readOrgPlanComp;
92
+ const { orgId, actorUid, patch } = options;
93
+ const org = await firestore().collection('orgs').doc(orgId).get();
94
+ if (!org.exists) throw new ClientBuildError('Unknown workspace', 404);
95
+ const stored = await loadClientBuild(orgId);
96
+ let intake = (_ref = stored == null ? void 0 : stored.intake) != null ? _ref : null;
97
+ if (patch.intake !== undefined) {
98
+ const parsed = parseClientBuildIntake(patch.intake);
99
+ if (typeof parsed === 'string') throw new ClientBuildError(parsed, 400);
100
+ intake = parsed;
101
+ }
102
+ if (!intake) throw new ClientBuildError('Missing the business details', 400);
103
+ let domain = (_ref1 = stored == null ? void 0 : stored.domain) != null ? _ref1 : null;
104
+ if (patch.domain !== undefined) {
105
+ if (patch.domain === null) domain = null;
106
+ else {
107
+ const parsed = parseClientBuildDomain(patch.domain);
108
+ if (typeof parsed === 'string') throw new ClientBuildError(parsed, 400);
109
+ domain = parsed;
110
+ }
111
+ }
112
+ let hostId = (_ref2 = stored == null ? void 0 : stored.hostId) != null ? _ref2 : null;
113
+ let host = (_ref3 = stored == null ? void 0 : stored.host) != null ? _ref3 : null;
114
+ if (patch.hostId !== undefined) {
115
+ var _patch_hostId;
116
+ const id = String((_patch_hostId = patch.hostId) != null ? _patch_hostId : '');
117
+ if (!ID_PATTERN.test(id)) throw new ClientBuildError('Unknown site', 400);
118
+ const site = await firestore().collection('hosts').doc(id).get();
119
+ if (!site.exists || site.get('orgId') !== orgId) {
120
+ throw new ClientBuildError('That site is not in this workspace', 400);
121
+ }
122
+ hostId = id;
123
+ host = typeof site.get('subdomain') === 'string' ? site.get('subdomain') : patch.host ? String(patch.host) : null;
124
+ }
125
+ let jobId = (_ref4 = stored == null ? void 0 : stored.jobId) != null ? _ref4 : null;
126
+ if (patch.jobId !== undefined) {
127
+ var _patch_jobId;
128
+ const id = String((_patch_jobId = patch.jobId) != null ? _patch_jobId : '');
129
+ if (!ID_PATTERN.test(id)) throw new ClientBuildError('Unknown job', 400);
130
+ jobId = id;
131
+ }
132
+ let starter = (_ref5 = stored == null ? void 0 : stored.starter) != null ? _ref5 : false;
133
+ if (patch.starter !== undefined) {
134
+ if (typeof patch.starter !== 'boolean') throw new ClientBuildError('Unknown starter choice', 400);
135
+ starter = patch.starter;
136
+ }
137
+ const record = {
138
+ intake,
139
+ domain,
140
+ // Derived on every write, never taken from the body: the plan the
141
+ // workspace was comped on, Site Care, monthly, and the domain above.
142
+ intent: clientBuildIntent({
143
+ plan: (_ref6 = (_readOrgPlanComp = readOrgPlanComp(org.data())) == null ? void 0 : _readOrgPlanComp.plan) != null ? _ref6 : null,
144
+ domain
145
+ }),
146
+ hostId,
147
+ host,
148
+ jobId,
149
+ starter,
150
+ previewSentAt: (_ref7 = stored == null ? void 0 : stored.previewSentAt) != null ? _ref7 : null,
151
+ updatedAt: (_options_now = options.now) != null ? _options_now : Date.now(),
152
+ updatedBy: actorUid
153
+ };
154
+ await recordRef(orgId).set(record);
155
+ return record;
156
+ }
157
+ /**
158
+ * Sends the owner the preview: a text and an email with the link to the site
159
+ * as it is now and the address it will live at. Only once the site has a
160
+ * published page, since the link would otherwise open an empty site. Each
161
+ * channel is attempted on its own and reported; the send is an Audit Log row.
162
+ */ export async function sendClientBuildPreview(options) {
163
+ var _site_screens, _site_subdomain, _options_now;
164
+ const { orgId, actorUid } = options;
165
+ const record = await loadClientBuild(orgId);
166
+ if (!(record == null ? void 0 : record.hostId)) throw new ClientBuildError('Build the site first', 409);
167
+ const [orgSnapshot, siteSnapshot] = await Promise.all([
168
+ firestore().collection('orgs').doc(orgId).get(),
169
+ firestore().collection('hosts').doc(record.hostId).get()
170
+ ]);
171
+ if (!siteSnapshot.exists || siteSnapshot.get('orgId') !== orgId) {
172
+ throw new ClientBuildError('That site is not in this workspace', 409);
173
+ }
174
+ const site = siteSnapshot.data();
175
+ if (!Object.keys((_site_screens = site.screens) != null ? _site_screens : {}).length) {
176
+ throw new ClientBuildError('The site has no published page yet', 409);
177
+ }
178
+ const previewUrl = hostPublicOrigin({
179
+ subdomain: (_site_subdomain = site.subdomain) != null ? _site_subdomain : null
180
+ });
181
+ if (!previewUrl) throw new ClientBuildError('The site has no address yet', 409);
182
+ const siteAddress = clientBuildSiteAddress(record.domain, previewUrl);
183
+ const { intake } = record;
184
+ const businessName = intake.businessName || 'your business';
185
+ const brand = systemEmailBrand(orgSnapshot.data());
186
+ const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME;
187
+ let emailed = false;
188
+ if (intake.email && isEmailConfigured()) {
189
+ try {
190
+ const content = await renderSystemEmailContent('client-build-preview', {
191
+ 'business.name': businessName,
192
+ 'preview.url': previewUrl,
193
+ 'site.address': siteAddress != null ? siteAddress : previewUrl
194
+ }, brand, {
195
+ subject: `Your new website for ${businessName} is ready to look at`,
196
+ text: `We built the website for ${businessName} with you today. Open it on your phone and look ` + `around: every page, picture and word can still be changed.\n\n${previewUrl}` + (siteAddress ? `\n\nIt will live at ${siteAddress}.` : '')
197
+ });
198
+ const result = await sendEmail(_extends({
199
+ to: intake.email,
200
+ subject: content.subject,
201
+ text: content.text
202
+ }, content.html ? {
203
+ html: content.html
204
+ } : {}, brand.fromName ? {
205
+ fromName: brand.fromName
206
+ } : {}, {
207
+ context: 'client-build-preview'
208
+ }));
209
+ emailed = result.sent;
210
+ if (result.sent) await meterOrgEmail(orgId);
211
+ } catch (error) {
212
+ console.error('[client-build] the preview email failed', error);
213
+ }
214
+ }
215
+ let text = 'none';
216
+ const phone = clientBuildPhone(intake);
217
+ if (phone) {
218
+ const sms = pluginSmsMessaging();
219
+ if (!(sms == null ? void 0 : sms.isConfigured())) text = 'unavailable';
220
+ else {
221
+ const outcome = await sms.send({
222
+ to: phone,
223
+ body: clientBuildPreviewText({
224
+ businessName,
225
+ previewUrl,
226
+ siteAddress,
227
+ productName
228
+ }),
229
+ hostId: record.hostId,
230
+ // Owed to the owner's own request, at the booth or the door, and
231
+ // waited on right now: never held for quiet hours.
232
+ purpose: 'transactional',
233
+ context: 'client-build-preview'
234
+ });
235
+ text = outcome.status;
236
+ }
237
+ }
238
+ const sentAt = (_options_now = options.now) != null ? _options_now : Date.now();
239
+ if (emailed || text === 'sent') await recordRef(orgId).set({
240
+ previewSentAt: sentAt
241
+ }, {
242
+ merge: true
243
+ });
244
+ await addAdminAudit(firestore(), {
245
+ actorUid,
246
+ action: 'client-build.preview-sent',
247
+ target: `orgs/${orgId}`,
248
+ // Which channels went, never the owner's address or number.
249
+ after: {
250
+ hostId: record.hostId,
251
+ emailed,
252
+ text
253
+ },
254
+ at: firebaseAdmin.firestore.FieldValue.serverTimestamp()
255
+ });
256
+ return {
257
+ emailed,
258
+ text,
259
+ previewUrl,
260
+ siteAddress
261
+ };
262
+ }
263
+
264
+ //# sourceMappingURL=client-build.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/client-build.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CLIENT_BUILD_COLLECTION,\n CLIENT_BUILD_DOC_ID,\n clientBuildIntent,\n clientBuildPhone,\n clientBuildPreviewText,\n clientBuildSiteAddress,\n EMPTY_CLIENT_BUILD_INTAKE,\n parseClientBuildDomain,\n parseClientBuildIntake,\n readClientBuildIntent,\n type ClientBuildDomain,\n type ClientBuildIntent,\n type ClientBuildRecord,\n} from '@aglyn/aglyn/app-utils/client-build'\nimport { hostPublicOrigin } from '@aglyn/aglyn/app-utils/host-naming'\nimport { readOrgPlanComp } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n pluginSmsMessaging,\n type PluginSmsSendOutcome,\n} from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/server'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { addAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { renderSystemEmailContent, systemEmailBrand } from './render-system-email'\n\n/**\n * THE ONE-SCREEN BUILD FOR A CLIENT, ON THE SERVER (AGL-3958).\n *\n * One record per workspace, at `orgs/{orgId}/clientBuild/current`, which the\n * rules open to no client: the owner's phone and email are staff's to hold\n * until the owner joins, and the org document is read by every member. Only\n * `/api/admin/client-build` (staff) calls this module.\n */\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** A refusal the route answers with its status. */\nexport class ClientBuildError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n this.name = 'ClientBuildError'\n }\n}\n\nfunction recordRef(orgId: string) {\n return firestore().collection('orgs').doc(orgId).collection(CLIENT_BUILD_COLLECTION).doc(CLIENT_BUILD_DOC_ID)\n}\n\n/** A stored record, read back defensively; `null` when the workspace has none. */\nexport function readClientBuildRecord(raw: unknown): ClientBuildRecord | null {\n if (!raw || typeof raw !== 'object') return null\n const source = raw as Record<string, unknown>\n const intake = parseClientBuildIntake(source['intake'])\n const domain = source['domain'] ? parseClientBuildDomain(source['domain']) : null\n const intent = readClientBuildIntent(source['intent'])\n const text = (value: unknown) => (typeof value === 'string' && value ? value : null)\n const time = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) ? value : null)\n return {\n // A stored intake that no longer validates is still the one staff typed.\n intake: typeof intake === 'string' ? { ...EMPTY_CLIENT_BUILD_INTAKE, ...(source['intake'] as object) } : intake,\n domain: typeof domain === 'string' ? null : domain,\n intent: intent ?? clientBuildIntent({ plan: null, domain: typeof domain === 'string' ? null : domain }),\n hostId: text(source['hostId']),\n host: text(source['host']),\n jobId: text(source['jobId']),\n starter: source['starter'] === true,\n previewSentAt: time(source['previewSentAt']),\n updatedAt: time(source['updatedAt']) ?? 0,\n updatedBy: text(source['updatedBy']) ?? '',\n }\n}\n\n/** The workspace's build, or `null` before one was started. */\nexport async function loadClientBuild(orgId: string): Promise<ClientBuildRecord | null> {\n const snapshot = await recordRef(orgId).get()\n return snapshot.exists ? readClientBuildRecord(snapshot.data()) : null\n}\n\n/**\n * The intent the hand-off proposes (AGL-3955, AGL-3956): what the build left\n * for the owner's checkout, or `null` when the workspace was not built here.\n */\nexport async function loadClientBuildIntent(orgId: string): Promise<ClientBuildIntent | null> {\n return (await loadClientBuild(orgId))?.intent ?? null\n}\n\n/** What a save may change; each part left out keeps what is stored. */\nexport interface ClientBuildPatch {\n intake?: unknown\n domain?: unknown\n hostId?: unknown\n host?: unknown\n jobId?: unknown\n /** `true` once the starter site was given instead of a guided start. */\n starter?: unknown\n}\n\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * Writes the build, merged over what is stored. The intake and the domain\n * are validated as the screen validated them; the intent is derived, never\n * taken from the body: the plan the workspace was comped on, Site Care, and\n * the domain the Domain step recorded. A site is accepted only when it\n * belongs to this workspace.\n */\nexport async function saveClientBuild(options: {\n orgId: string\n actorUid: string\n patch: ClientBuildPatch\n now?: number\n}): Promise<ClientBuildRecord> {\n const { orgId, actorUid, patch } = options\n const org = await firestore().collection('orgs').doc(orgId).get()\n if (!org.exists) throw new ClientBuildError('Unknown workspace', 404)\n const stored = await loadClientBuild(orgId)\n\n let intake = stored?.intake ?? null\n if (patch.intake !== undefined) {\n const parsed = parseClientBuildIntake(patch.intake)\n if (typeof parsed === 'string') throw new ClientBuildError(parsed, 400)\n intake = parsed\n }\n if (!intake) throw new ClientBuildError('Missing the business details', 400)\n\n let domain: ClientBuildDomain | null = stored?.domain ?? null\n if (patch.domain !== undefined) {\n if (patch.domain === null) domain = null\n else {\n const parsed = parseClientBuildDomain(patch.domain)\n if (typeof parsed === 'string') throw new ClientBuildError(parsed, 400)\n domain = parsed\n }\n }\n\n let hostId = stored?.hostId ?? null\n let host = stored?.host ?? null\n if (patch.hostId !== undefined) {\n const id = String(patch.hostId ?? '')\n if (!ID_PATTERN.test(id)) throw new ClientBuildError('Unknown site', 400)\n const site = await firestore().collection('hosts').doc(id).get()\n if (!site.exists || site.get('orgId') !== orgId) {\n throw new ClientBuildError('That site is not in this workspace', 400)\n }\n hostId = id\n host = typeof site.get('subdomain') === 'string' ? site.get('subdomain') : (patch.host ? String(patch.host) : null)\n }\n\n let jobId = stored?.jobId ?? null\n if (patch.jobId !== undefined) {\n const id = String(patch.jobId ?? '')\n if (!ID_PATTERN.test(id)) throw new ClientBuildError('Unknown job', 400)\n jobId = id\n }\n\n let starter = stored?.starter ?? false\n if (patch.starter !== undefined) {\n if (typeof patch.starter !== 'boolean') throw new ClientBuildError('Unknown starter choice', 400)\n starter = patch.starter\n }\n\n const record: ClientBuildRecord = {\n intake,\n domain,\n // Derived on every write, never taken from the body: the plan the\n // workspace was comped on, Site Care, monthly, and the domain above.\n intent: clientBuildIntent({\n plan: readOrgPlanComp(org.data() as Partial<AglynOrgBilling>)?.plan ?? null,\n domain,\n }),\n hostId,\n host,\n jobId,\n starter,\n previewSentAt: stored?.previewSentAt ?? null,\n updatedAt: options.now ?? Date.now(),\n updatedBy: actorUid,\n }\n await recordRef(orgId).set(record)\n return record\n}\n\n/** What sending the preview came to, per channel. */\nexport interface ClientBuildPreviewOutcome {\n emailed: boolean\n /** The text's outcome; `none` when the intake has no phone to text. */\n text: PluginSmsSendOutcome['status'] | 'none' | 'unavailable'\n previewUrl: string\n siteAddress: string | null\n}\n\n/**\n * Sends the owner the preview: a text and an email with the link to the site\n * as it is now and the address it will live at. Only once the site has a\n * published page, since the link would otherwise open an empty site. Each\n * channel is attempted on its own and reported; the send is an Audit Log row.\n */\nexport async function sendClientBuildPreview(options: {\n orgId: string\n actorUid: string\n now?: number\n}): Promise<ClientBuildPreviewOutcome> {\n const { orgId, actorUid } = options\n const record = await loadClientBuild(orgId)\n if (!record?.hostId) throw new ClientBuildError('Build the site first', 409)\n const [orgSnapshot, siteSnapshot] = await Promise.all([\n firestore().collection('orgs').doc(orgId).get(),\n firestore().collection('hosts').doc(record.hostId).get(),\n ])\n if (!siteSnapshot.exists || siteSnapshot.get('orgId') !== orgId) {\n throw new ClientBuildError('That site is not in this workspace', 409)\n }\n const site = siteSnapshot.data() as { screens?: Record<string, unknown>; subdomain?: string; cname?: string }\n if (!Object.keys(site.screens ?? {}).length) {\n throw new ClientBuildError('The site has no published page yet', 409)\n }\n const previewUrl = hostPublicOrigin({ subdomain: site.subdomain ?? null })\n if (!previewUrl) throw new ClientBuildError('The site has no address yet', 409)\n const siteAddress = clientBuildSiteAddress(record.domain, previewUrl)\n const { intake } = record\n const businessName = intake.businessName || 'your business'\n\n const brand = systemEmailBrand(orgSnapshot.data() as Record<string, unknown>)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n\n let emailed = false\n if (intake.email && isEmailConfigured()) {\n try {\n const content = await renderSystemEmailContent(\n 'client-build-preview',\n {\n 'business.name': businessName,\n 'preview.url': previewUrl,\n 'site.address': siteAddress ?? previewUrl,\n },\n brand,\n {\n subject: `Your new website for ${businessName} is ready to look at`,\n text:\n `We built the website for ${businessName} with you today. Open it on your phone and look ` +\n `around: every page, picture and word can still be changed.\\n\\n${previewUrl}` +\n (siteAddress ? `\\n\\nIt will live at ${siteAddress}.` : ''),\n },\n )\n const result = await sendEmail({\n to: intake.email,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'client-build-preview',\n })\n emailed = result.sent\n if (result.sent) await meterOrgEmail(orgId)\n } catch (error) {\n console.error('[client-build] the preview email failed', error)\n }\n }\n\n let text: ClientBuildPreviewOutcome['text'] = 'none'\n const phone = clientBuildPhone(intake)\n if (phone) {\n const sms = pluginSmsMessaging()\n if (!sms?.isConfigured()) text = 'unavailable'\n else {\n const outcome = await sms.send({\n to: phone,\n body: clientBuildPreviewText({ businessName, previewUrl, siteAddress, productName }),\n hostId: record.hostId,\n // Owed to the owner's own request, at the booth or the door, and\n // waited on right now: never held for quiet hours.\n purpose: 'transactional',\n context: 'client-build-preview',\n })\n text = outcome.status\n }\n }\n\n const sentAt = options.now ?? Date.now()\n if (emailed || text === 'sent') await recordRef(orgId).set({ previewSentAt: sentAt }, { merge: true })\n await addAdminAudit(firestore(), {\n actorUid,\n action: 'client-build.preview-sent',\n target: `orgs/${orgId}`,\n // Which channels went, never the owner's address or number.\n after: { hostId: record.hostId, emailed, text },\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n return { emailed, text, previewUrl, siteAddress }\n}\n"],"names":["CLIENT_BUILD_COLLECTION","CLIENT_BUILD_DOC_ID","clientBuildIntent","clientBuildPhone","clientBuildPreviewText","clientBuildSiteAddress","EMPTY_CLIENT_BUILD_INTAKE","parseClientBuildDomain","parseClientBuildIntake","readClientBuildIntent","hostPublicOrigin","readOrgPlanComp","PLATFORM_BRAND_NAME","pluginSmsMessaging","isEmailConfigured","sendEmail","addAdminAudit","meterOrgEmail","firebaseAdmin","renderSystemEmailContent","systemEmailBrand","firestore","app","ClientBuildError","Error","message","status","name","recordRef","orgId","collection","doc","readClientBuildRecord","raw","time","text","source","intake","domain","intent","value","Number","isFinite","plan","hostId","host","jobId","starter","previewSentAt","updatedAt","updatedBy","loadClientBuild","snapshot","get","exists","data","loadClientBuildIntent","ID_PATTERN","saveClientBuild","options","actorUid","patch","org","stored","undefined","parsed","id","String","test","site","record","now","Date","set","sendClientBuildPreview","orgSnapshot","siteSnapshot","Promise","all","Object","keys","screens","length","previewUrl","subdomain","siteAddress","businessName","brand","productName","merge","emailed","email","content","subject","result","to","html","fromName","context","sent","error","console","phone","sms","isConfigured","outcome","send","body","purpose","sentAt","action","target","after","at","FieldValue","serverTimestamp"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,uBAAuB,EACvBC,mBAAmB,EACnBC,iBAAiB,EACjBC,gBAAgB,EAChBC,sBAAs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,OAAO;QACvB,4DAA4D;QAC5DmF,OAAO;YAAEpE,QAAQ0B,OAAO1B,MAAM;YAAE8C;YAASvD;QAAK;QAC9C8E,IAAI/F,cAAcG,SAAS,CAAC6F,UAAU,CAACC,eAAe;IACxD;IACA,OAAO;QAAEzB;QAASvD;QAAMgD;QAAYE;IAAY;AAClD"}
@@ -40,3 +40,29 @@ export type ConfiguredUrlFetchResult =
40
40
  export declare function fetchConfiguredPublicUrl(url: string, init: Omit<RequestInit, 'redirect'>, deps?: {
41
41
  resolve?: typeof resolvePublicIp;
42
42
  }): Promise<ConfiguredUrlFetchResult>;
43
+ export type ConfiguredUrlReadResult =
44
+ /**
45
+ * Called: the status, and the body as text. `body` is null when the reply
46
+ * ran past `maxBytes`, which a caller reads as no answer.
47
+ */
48
+ {
49
+ ok: true;
50
+ status: number;
51
+ body: string | null;
52
+ } | {
53
+ ok: false;
54
+ refusal: ConfiguredUrlRefusal;
55
+ host: string;
56
+ };
57
+ /**
58
+ * {@link fetchConfiguredPublicUrl} for a caller that reads the answer: the
59
+ * same refusals, the same pinned address, no redirect followed, and the body
60
+ * read up to `maxBytes`. A server reading a document at an address it
61
+ * discovered in somebody's DNS (AGL-3963) holds the reply to a size it chose,
62
+ * so a host that streams forever costs one bounded read. Throws only what
63
+ * `fetch` throws.
64
+ */
65
+ export declare function readConfiguredPublicUrl(url: string, init: Omit<RequestInit, 'redirect'>, options: {
66
+ maxBytes: number;
67
+ resolve?: typeof resolvePublicIp;
68
+ }): Promise<ConfiguredUrlReadResult>;
@@ -114,5 +114,73 @@ import { createPinnedDispatcher, resolvePublicIp } from "./serve-plugin-fetch.js
114
114
  await dispatcher.close().catch(()=>undefined);
115
115
  }
116
116
  }
117
+ /**
118
+ * {@link fetchConfiguredPublicUrl} for a caller that reads the answer: the
119
+ * same refusals, the same pinned address, no redirect followed, and the body
120
+ * read up to `maxBytes`. A server reading a document at an address it
121
+ * discovered in somebody's DNS (AGL-3963) holds the reply to a size it chose,
122
+ * so a host that streams forever costs one bounded read. Throws only what
123
+ * `fetch` throws.
124
+ */ export async function readConfiguredPublicUrl(url, init, options) {
125
+ var _options_resolve;
126
+ const refusal = configuredUrlRefusal(url);
127
+ let host;
128
+ try {
129
+ host = new URL(url).hostname;
130
+ } catch (unused) {
131
+ host = '';
132
+ }
133
+ if (refusal) return {
134
+ ok: false,
135
+ refusal,
136
+ host
137
+ };
138
+ const pinned = await ((_options_resolve = options.resolve) != null ? _options_resolve : resolvePublicIp)(host);
139
+ if (!pinned) return {
140
+ ok: false,
141
+ refusal: 'private-address',
142
+ host
143
+ };
144
+ const dispatcher = createPinnedDispatcher(pinned);
145
+ try {
146
+ var _response_status;
147
+ var _response_body;
148
+ const pinnedInit = _extends({}, init, {
149
+ redirect: 'manual',
150
+ dispatcher
151
+ });
152
+ const response = await fetch(url, pinnedInit);
153
+ const status = Number((_response_status = response.status) != null ? _response_status : 0);
154
+ const reader = (_response_body = response.body) == null ? void 0 : _response_body.getReader();
155
+ if (!reader) return {
156
+ ok: true,
157
+ status,
158
+ body: ''
159
+ };
160
+ const chunks = [];
161
+ let size = 0;
162
+ for(;;){
163
+ const { done, value } = await reader.read();
164
+ if (done) break;
165
+ size += value.byteLength;
166
+ if (size > options.maxBytes) {
167
+ await reader.cancel().catch(()=>undefined);
168
+ return {
169
+ ok: true,
170
+ status,
171
+ body: null
172
+ };
173
+ }
174
+ chunks.push(value);
175
+ }
176
+ return {
177
+ ok: true,
178
+ status,
179
+ body: Buffer.concat(chunks).toString('utf8')
180
+ };
181
+ } finally{
182
+ await dispatcher.close().catch(()=>undefined);
183
+ }
184
+ }
117
185
 
118
186
  //# sourceMappingURL=configured-url-fetch.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/configured-url-fetch.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * A SERVER CALL TO A URL A TENANT TYPED (AGL-3363).\n *\n * Some features call an address the merchant configured, from the\n * platform's own servers: a dropship supplier's order webhook is the first.\n * That address is author data, so it gets the checks the plugin fetch proxy\n * (`serve-plugin-fetch.ts`, AGL-515/1881) gives a plugin's declared origin,\n * through the same two primitives, rather than a bare `fetch`:\n *\n * - https only, on the default port, with no credentials in the authority;\n * - a host that wears a brand it is not (`lookalikeBrandForHost`) is refused\n * for every workspace, the phishing screen's strong tier;\n * - the name must resolve to PUBLIC addresses only, and the connection is\n * pinned to the address that was checked (`resolvePublicIp` +\n * `createPinnedDispatcher`), so a name cannot be rebound to the cloud\n * metadata endpoint or a private range between the check and the connect;\n * - a redirect is not followed (`redirect: 'manual'`): a 3xx is the answer,\n * which a caller that wants a 2xx treats as a failure.\n *\n * This sits beside the plugin fetch proxy and is not it: that one proxies a\n * browser's request to an allowlisted origin and streams the reply; this is\n * a server's own call with no allowlist but the rules above.\n *=========================================*/\n\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { createPinnedDispatcher, resolvePublicIp } from './serve-plugin-fetch'\n\n/** Why a configured URL was not called. */\nexport type ConfiguredUrlRefusal =\n | 'malformed'\n | 'not-https'\n | 'credentials'\n | 'port'\n | 'lookalike'\n | 'private-address'\n\n/** The checks that need no network: shape, scheme, port, credentials, brand. */\nexport function configuredUrlRefusal(url: unknown): ConfiguredUrlRefusal | null {\n let parsed: URL\n try {\n parsed = new URL(String(url ?? ''))\n } catch {\n return 'malformed'\n }\n if (parsed.protocol !== 'https:') return 'not-https'\n if (parsed.username || parsed.password) return 'credentials'\n if (parsed.port && parsed.port !== '443') return 'port'\n if (lookalikeBrandForHost(parsed.hostname)) return 'lookalike'\n return null\n}\n\n/** What the merchant is told a refusal means, in their words. */\nexport function describeConfiguredUrlRefusal(refusal: ConfiguredUrlRefusal): string {\n switch (refusal) {\n case 'malformed':\n return 'the address is not a valid web address'\n case 'not-https':\n return 'the address must start with https://'\n case 'credentials':\n return 'the address must not contain a user name or password'\n case 'port':\n return 'the address must use the standard https port'\n case 'lookalike':\n return 'the address looks like another company’s website'\n case 'private-address':\n return 'the address does not lead to a public server'\n }\n}\n\nexport type ConfiguredUrlFetchResult =\n /** Called: the status it answered. The body is discarded. */\n | { ok: true; status: number }\n | { ok: false; refusal: ConfiguredUrlRefusal; host: string }\n\n/**\n * Call `url` under the rules above and answer its status; the body is\n * discarded, because a notification's receiver answers with a status and\n * nothing a caller should read. Never follows a redirect. Throws only what\n * `fetch` throws (a timeout, a reset), for the caller to retry.\n */\nexport async function fetchConfiguredPublicUrl(\n url: string,\n init: Omit<RequestInit, 'redirect'>,\n deps: { resolve?: typeof resolvePublicIp } = {},\n): Promise<ConfiguredUrlFetchResult> {\n const refusal = configuredUrlRefusal(url)\n let host: string\n try {\n host = new URL(url).hostname\n } catch {\n host = ''\n }\n if (refusal) return { ok: false, refusal, host }\n const pinned = await (deps.resolve ?? resolvePublicIp)(host)\n if (!pinned) return { ok: false, refusal: 'private-address', host }\n const dispatcher = createPinnedDispatcher(pinned)\n try {\n // `dispatcher` is undici's, which the global fetch honors; spread from a\n // variable so the DOM `RequestInit` type does not reject the field.\n const pinnedInit = { ...init, redirect: 'manual' as const, dispatcher }\n const response = await fetch(url, pinnedInit as RequestInit)\n // Released before the dispatcher closes: `close` waits for requests in\n // flight, and an unread body is one.\n await response.body?.cancel().catch(() => undefined)\n return { ok: true, status: Number(response.status ?? 0) }\n } finally {\n await dispatcher.close().catch(() => undefined)\n }\n}\n"],"names":["lookalikeBrandForHost","createPinnedDispatcher","resolvePublicIp","configuredUrlRefusal","url","parsed","URL","String","protocol","username","password","port","hostname","describeConfiguredUrlRefusal","refusal","fetchConfiguredPublicUrl","init","deps","host","ok","pinned","resolve","dispatcher","response","pinnedInit","redirect","fetch","body","cancel","catch","undefined","status","Number","close"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,SAASA,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,sBAAsB,EAAEC,eAAe,QAAQ,0BAAsB;AAW9E,8EAA8E,GAC9E,OAAO,SAASC,qBAAqBC,GAAY;IAC/C,IAAIC;IACJ,IAAI;QACFA,SAAS,IAAIC,IAAIC,OAAOH,cAAAA,MAAO;IACjC,EAAE,eAAM;QACN,OAAO;IACT;IACA,IAAIC,OAAOG,QAAQ,KAAK,UAAU,OAAO;IACzC,IAAIH,OAAOI,QAAQ,IAAIJ,OAAOK,QAAQ,EAAE,OAAO;IAC/C,IAAIL,OAAOM,IAAI,IAAIN,OAAOM,IAAI,KAAK,OAAO,OAAO;IACjD,IAAIX,sBAAsBK,OAAOO,QAAQ,GAAG,OAAO;IACnD,OAAO;AACT;AAEA,+DAA+D,GAC/D,OAAO,SAASC,6BAA6BC,OAA6B;IACxE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;IACX;AACF;AAOA;;;;;CAKC,GACD,OAAO,eAAeC,yBACpBX,GAAW,EACXY,IAAmC,EACnCC,OAA6C,CAAC,CAAC;QAUzBA;IARtB,MAAMH,UAAUX,qBAAqBC;IACrC,IAAIc;IACJ,IAAI;QACFA,OAAO,IAAIZ,IAAIF,KAAKQ,QAAQ;IAC9B,EAAE,eAAM;QACNM,OAAO;IACT;IACA,IAAIJ,SAAS,OAAO;QAAEK,IAAI;QAAOL;QAASI;IAAK;IAC/C,MAAME,SAAS,MAAM,EAACH,gBAAAA,KAAKI,OAAO,YAAZJ,gBAAgBf,iBAAiBgB;IACvD,IAAI,CAACE,QAAQ,OAAO;QAAED,IAAI;QAAOL,SAAS;QAAmBI;IAAK;IAClE,MAAMI,aAAarB,uBAAuBmB;IAC1C,IAAI;YAQgCG;YAD5BA;QANN,yEAAyE;QACzE,oEAAoE;QACpE,MAAMC,aAAa,aAAKR;YAAMS,UAAU;YAAmBH;;QAC3D,MAAMC,WAAW,MAAMG,MAAMtB,KAAKoB;QAClC,uEAAuE;QACvE,qCAAqC;QACrC,QAAMD,iBAAAA,SAASI,IAAI,qBAAbJ,eAAeK,MAAM,GAAGC,KAAK,CAAC,IAAMC;QAC1C,OAAO;YAAEX,IAAI;YAAMY,QAAQC,QAAOT,mBAAAA,SAASQ,MAAM,YAAfR,mBAAmB;QAAG;IAC1D,SAAU;QACR,MAAMD,WAAWW,KAAK,GAAGJ,KAAK,CAAC,IAAMC;IACvC;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/configured-url-fetch.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * A SERVER CALL TO A URL A TENANT TYPED (AGL-3363).\n *\n * Some features call an address the merchant configured, from the\n * platform's own servers: a dropship supplier's order webhook is the first.\n * That address is author data, so it gets the checks the plugin fetch proxy\n * (`serve-plugin-fetch.ts`, AGL-515/1881) gives a plugin's declared origin,\n * through the same two primitives, rather than a bare `fetch`:\n *\n * - https only, on the default port, with no credentials in the authority;\n * - a host that wears a brand it is not (`lookalikeBrandForHost`) is refused\n * for every workspace, the phishing screen's strong tier;\n * - the name must resolve to PUBLIC addresses only, and the connection is\n * pinned to the address that was checked (`resolvePublicIp` +\n * `createPinnedDispatcher`), so a name cannot be rebound to the cloud\n * metadata endpoint or a private range between the check and the connect;\n * - a redirect is not followed (`redirect: 'manual'`): a 3xx is the answer,\n * which a caller that wants a 2xx treats as a failure.\n *\n * This sits beside the plugin fetch proxy and is not it: that one proxies a\n * browser's request to an allowlisted origin and streams the reply; this is\n * a server's own call with no allowlist but the rules above.\n *=========================================*/\n\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { createPinnedDispatcher, resolvePublicIp } from './serve-plugin-fetch'\n\n/** Why a configured URL was not called. */\nexport type ConfiguredUrlRefusal =\n | 'malformed'\n | 'not-https'\n | 'credentials'\n | 'port'\n | 'lookalike'\n | 'private-address'\n\n/** The checks that need no network: shape, scheme, port, credentials, brand. */\nexport function configuredUrlRefusal(url: unknown): ConfiguredUrlRefusal | null {\n let parsed: URL\n try {\n parsed = new URL(String(url ?? ''))\n } catch {\n return 'malformed'\n }\n if (parsed.protocol !== 'https:') return 'not-https'\n if (parsed.username || parsed.password) return 'credentials'\n if (parsed.port && parsed.port !== '443') return 'port'\n if (lookalikeBrandForHost(parsed.hostname)) return 'lookalike'\n return null\n}\n\n/** What the merchant is told a refusal means, in their words. */\nexport function describeConfiguredUrlRefusal(refusal: ConfiguredUrlRefusal): string {\n switch (refusal) {\n case 'malformed':\n return 'the address is not a valid web address'\n case 'not-https':\n return 'the address must start with https://'\n case 'credentials':\n return 'the address must not contain a user name or password'\n case 'port':\n return 'the address must use the standard https port'\n case 'lookalike':\n return 'the address looks like another company’s website'\n case 'private-address':\n return 'the address does not lead to a public server'\n }\n}\n\nexport type ConfiguredUrlFetchResult =\n /** Called: the status it answered. The body is discarded. */\n | { ok: true; status: number }\n | { ok: false; refusal: ConfiguredUrlRefusal; host: string }\n\n/**\n * Call `url` under the rules above and answer its status; the body is\n * discarded, because a notification's receiver answers with a status and\n * nothing a caller should read. Never follows a redirect. Throws only what\n * `fetch` throws (a timeout, a reset), for the caller to retry.\n */\nexport async function fetchConfiguredPublicUrl(\n url: string,\n init: Omit<RequestInit, 'redirect'>,\n deps: { resolve?: typeof resolvePublicIp } = {},\n): Promise<ConfiguredUrlFetchResult> {\n const refusal = configuredUrlRefusal(url)\n let host: string\n try {\n host = new URL(url).hostname\n } catch {\n host = ''\n }\n if (refusal) return { ok: false, refusal, host }\n const pinned = await (deps.resolve ?? resolvePublicIp)(host)\n if (!pinned) return { ok: false, refusal: 'private-address', host }\n const dispatcher = createPinnedDispatcher(pinned)\n try {\n // `dispatcher` is undici's, which the global fetch honors; spread from a\n // variable so the DOM `RequestInit` type does not reject the field.\n const pinnedInit = { ...init, redirect: 'manual' as const, dispatcher }\n const response = await fetch(url, pinnedInit as RequestInit)\n // Released before the dispatcher closes: `close` waits for requests in\n // flight, and an unread body is one.\n await response.body?.cancel().catch(() => undefined)\n return { ok: true, status: Number(response.status ?? 0) }\n } finally {\n await dispatcher.close().catch(() => undefined)\n }\n}\n\nexport type ConfiguredUrlReadResult =\n /**\n * Called: the status, and the body as text. `body` is null when the reply\n * ran past `maxBytes`, which a caller reads as no answer.\n */\n | { ok: true; status: number; body: string | null }\n | { ok: false; refusal: ConfiguredUrlRefusal; host: string }\n\n/**\n * {@link fetchConfiguredPublicUrl} for a caller that reads the answer: the\n * same refusals, the same pinned address, no redirect followed, and the body\n * read up to `maxBytes`. A server reading a document at an address it\n * discovered in somebody's DNS (AGL-3963) holds the reply to a size it chose,\n * so a host that streams forever costs one bounded read. Throws only what\n * `fetch` throws.\n */\nexport async function readConfiguredPublicUrl(\n url: string,\n init: Omit<RequestInit, 'redirect'>,\n options: { maxBytes: number; resolve?: typeof resolvePublicIp },\n): Promise<ConfiguredUrlReadResult> {\n const refusal = configuredUrlRefusal(url)\n let host: string\n try {\n host = new URL(url).hostname\n } catch {\n host = ''\n }\n if (refusal) return { ok: false, refusal, host }\n const pinned = await (options.resolve ?? resolvePublicIp)(host)\n if (!pinned) return { ok: false, refusal: 'private-address', host }\n const dispatcher = createPinnedDispatcher(pinned)\n try {\n const pinnedInit = { ...init, redirect: 'manual' as const, dispatcher }\n const response = await fetch(url, pinnedInit as RequestInit)\n const status = Number(response.status ?? 0)\n const reader = response.body?.getReader()\n if (!reader) return { ok: true, status, body: '' }\n const chunks: Uint8Array[] = []\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (size > options.maxBytes) {\n await reader.cancel().catch(() => undefined)\n return { ok: true, status, body: null }\n }\n chunks.push(value)\n }\n return { ok: true, status, body: Buffer.concat(chunks).toString('utf8') }\n } finally {\n await dispatcher.close().catch(() => undefined)\n }\n}\n"],"names":["lookalikeBrandForHost","createPinnedDispatcher","resolvePublicIp","configuredUrlRefusal","url","parsed","URL","String","protocol","username","password","port","hostname","describeConfiguredUrlRefusal","refusal","fetchConfiguredPublicUrl","init","deps","host","ok","pinned","resolve","dispatcher","response","pinnedInit","redirect","fetch","body","cancel","catch","undefined","status","Number","close","readConfiguredPublicUrl","options","reader","getReader","chunks","size","done","value","read","byteLength","maxBytes","push","Buffer","concat","toString"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,SAASA,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,sBAAsB,EAAEC,eAAe,QAAQ,0BAAsB;AAW9E,8EAA8E,GAC9E,OAAO,SAASC,qBAAqBC,GAAY;IAC/C,IAAIC;IACJ,IAAI;QACFA,SAAS,IAAIC,IAAIC,OAAOH,cAAAA,MAAO;IACjC,EAAE,eAAM;QACN,OAAO;IACT;IACA,IAAIC,OAAOG,QAAQ,KAAK,UAAU,OAAO;IACzC,IAAIH,OAAOI,QAAQ,IAAIJ,OAAOK,QAAQ,EAAE,OAAO;IAC/C,IAAIL,OAAOM,IAAI,IAAIN,OAAOM,IAAI,KAAK,OAAO,OAAO;IACjD,IAAIX,sB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,CAAC,IAAMC;IACvC;AACF"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Registers `{subdomain}.aglyn.app` on the tenant deployment as a per-domain
19
+ * REDIRECT to the custom domain (AGL-1273). The app-level canonical redirect
20
+ * in `loadPageData` is baked into an ISR entry keyed on pathname, so it
21
+ * structurally cannot carry the query string — a campaign that pointed at the
22
+ * platform subdomain lost its `utm_*` on the hop. The edge redirect preserves
23
+ * path AND query at zero runtime cost, and the app-level redirect stays as the
24
+ * fallback wherever the provider cannot express a redirect at all.
25
+ *
26
+ * A redirect is a REGISTRATION, not a special case: create the name carrying
27
+ * the redirect, or point an existing entry at the new target. Both halves live
28
+ * in the provider, so a name already on the deployment gets its redirect
29
+ * applied rather than being read as "already done" — an entry left serving
30
+ * instead of forwarding is a second live copy of the site on a name that was
31
+ * supposed to hand visitors to the custom domain.
32
+ *
33
+ * Best-effort BY DESIGN: the custom domain is already attached by the time
34
+ * this runs, and a redirect-registration failure must not unwind that. A
35
+ * failure sets `subdomainRedirectPending` so the gap is visible and the
36
+ * completer cron (`/api/admin/finish-domain-attachments`) can close it.
37
+ */
38
+ export declare function upsertSubdomainRedirect(options: {
39
+ subdomain: string;
40
+ target: string;
41
+ }): Promise<boolean>;
42
+ /**
43
+ * Registers the twin as a redirect to the primary. Best-effort for the same
44
+ * reason the subdomain redirect is: the primary serves either way, and a twin
45
+ * that did not land is recorded as `cnameTwinPending` for the completer.
46
+ */
47
+ export declare function upsertCustomDomainTwin(options: {
48
+ twin: string;
49
+ target: string;
50
+ }): Promise<boolean>;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { TENANT_APEX } from "@aglyn/aglyn/app-utils/tenant-apex";
17
+ import { attachProjectDomain } from "./workspace-domains.js";
18
+ /*
19
+ * The two redirects a connected custom domain registers on the tenant
20
+ * deployment (AGL-3961). Kept apart from `host-custom-domain.ts`, which owns
21
+ * the claim, so the completer cron and its spec reach them without the claim's
22
+ * Firestore and activity imports.
23
+ */ /**
24
+ * Registers `{subdomain}.aglyn.app` on the tenant deployment as a per-domain
25
+ * REDIRECT to the custom domain (AGL-1273). The app-level canonical redirect
26
+ * in `loadPageData` is baked into an ISR entry keyed on pathname, so it
27
+ * structurally cannot carry the query string — a campaign that pointed at the
28
+ * platform subdomain lost its `utm_*` on the hop. The edge redirect preserves
29
+ * path AND query at zero runtime cost, and the app-level redirect stays as the
30
+ * fallback wherever the provider cannot express a redirect at all.
31
+ *
32
+ * A redirect is a REGISTRATION, not a special case: create the name carrying
33
+ * the redirect, or point an existing entry at the new target. Both halves live
34
+ * in the provider, so a name already on the deployment gets its redirect
35
+ * applied rather than being read as "already done" — an entry left serving
36
+ * instead of forwarding is a second live copy of the site on a name that was
37
+ * supposed to hand visitors to the custom domain.
38
+ *
39
+ * Best-effort BY DESIGN: the custom domain is already attached by the time
40
+ * this runs, and a redirect-registration failure must not unwind that. A
41
+ * failure sets `subdomainRedirectPending` so the gap is visible and the
42
+ * completer cron (`/api/admin/finish-domain-attachments`) can close it.
43
+ */ export async function upsertSubdomainRedirect(options) {
44
+ const { subdomain, target } = options;
45
+ const result = await attachProjectDomain(`${subdomain}.${TENANT_APEX}`, {
46
+ redirectTo: target
47
+ }, 'tenant');
48
+ return result.outcome === 'attached' || result.outcome === 'already-exists';
49
+ }
50
+ /**
51
+ * Registers the twin as a redirect to the primary. Best-effort for the same
52
+ * reason the subdomain redirect is: the primary serves either way, and a twin
53
+ * that did not land is recorded as `cnameTwinPending` for the completer.
54
+ */ export async function upsertCustomDomainTwin(options) {
55
+ const result = await attachProjectDomain(options.twin, {
56
+ redirectTo: options.target
57
+ }, 'tenant');
58
+ return result.outcome === 'attached' || result.outcome === 'already-exists';
59
+ }
60
+
61
+ //# sourceMappingURL=custom-domain-redirects.js.map