@aglyn/tenant-data-admin 1.0.0-beta.275 → 1.0.0-beta.282
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/server/account-emails.js +18 -4
- package/src/lib/server/account-emails.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +5 -0
- package/src/lib/server/bundle-links.js +4 -2
- package/src/lib/server/bundle-links.js.map +1 -1
- package/src/lib/server/erase.js +9 -0
- package/src/lib/server/erase.js.map +1 -1
- package/src/lib/server/media-strong-digest.js +33 -5
- package/src/lib/server/media-strong-digest.js.map +1 -1
- package/src/lib/server/organizations.js +20 -0
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/owner-handoff-emails.d.ts +43 -0
- package/src/lib/server/owner-handoff-emails.js +134 -0
- package/src/lib/server/owner-handoff-emails.js.map +1 -0
- package/src/lib/server/personal-data-export.js +18 -4
- package/src/lib/server/personal-data-export.js.map +1 -1
- package/src/lib/server/render-monitor.d.ts +8 -4
- package/src/lib/server/render-monitor.js +12 -8
- package/src/lib/server/render-monitor.js.map +1 -1
- package/src/lib/server/site-care-inbound.d.ts +75 -4
- package/src/lib/server/site-care-inbound.js +236 -26
- package/src/lib/server/site-care-inbound.js.map +1 -1
- package/src/lib/server/site-care-reconcile.d.ts +36 -2
- package/src/lib/server/site-care-reconcile.js +219 -54
- package/src/lib/server/site-care-reconcile.js.map +1 -1
- package/src/lib/server/site-care-requests.d.ts +43 -1
- package/src/lib/server/site-care-requests.js +117 -6
- package/src/lib/server/site-care-requests.js.map +1 -1
- package/src/lib/server/upgrade-proposal.d.ts +6 -1
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/lib/server/upload-cors-reconcile.d.ts +2 -2
- package/src/lib/server/upload-cors-reconcile.js +2 -2
- package/src/lib/server/upload-cors-reconcile.js.map +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -15,9 +16,11 @@
|
|
|
15
16
|
* limitations under the License.
|
|
16
17
|
*/ import { inboundMailDomain } from "@aglyn/aglyn/app-utils/inbound-mail-domain";
|
|
17
18
|
import { emailAddressOf, htmlToPlainText, stripQuotedHistory, threadSubject } from "@aglyn/aglyn/app-utils/email-text";
|
|
19
|
+
import { MEMBER_EMAIL_ALIASES_COLLECTION, memberAddressRoster } from "@aglyn/aglyn/app-utils/member-email-aliases";
|
|
18
20
|
import { SITE_CARE_INBOUND_LOCAL_PART, siteCareSupportAddress } from "@aglyn/aglyn/app-utils/site-care";
|
|
19
21
|
import { getEmailConfig } from "@aglyn/shared-util-email";
|
|
20
22
|
import { appendSiteCareReply, openSiteCareRequest, orgHasSiteCare, readSiteCareOrg } from "./site-care-requests.js";
|
|
23
|
+
import { findAccountByVerifiedAlias } from "./account-emails.js";
|
|
21
24
|
import { findUserByEmailAcrossPools } from "./auth-pools.js";
|
|
22
25
|
/** This deployment's {@link SiteCareInboundAddresses}, read per call. */ export function siteCareInboundAddresses() {
|
|
23
26
|
return {
|
|
@@ -87,36 +90,224 @@ import { findUserByEmailAcrossPools } from "./auth-pools.js";
|
|
|
87
90
|
/**
|
|
88
91
|
* Every pool, not only the project's: an owner who signs in through SSO is a
|
|
89
92
|
* GCIP tenant user the project pool never returns (AGL-1122), and their mail
|
|
90
|
-
* would be read as a stranger's.
|
|
93
|
+
* would be read as a stranger's. Then the account addresses people add to
|
|
94
|
+
* their account and CONFIRM (AGL-2486): a confirmed address is one of that
|
|
95
|
+
* account's sign-in identifiers, held by no other account, so mail from it is
|
|
96
|
+
* that person's (AGL-4031). An address only typed, never confirmed, is not in
|
|
97
|
+
* that index and is never read as anyone's.
|
|
91
98
|
*/ export const findSiteCareAccount = async (email)=>{
|
|
92
99
|
const found = await findUserByEmailAcrossPools(email).catch(()=>null);
|
|
93
|
-
|
|
100
|
+
if (found) return {
|
|
94
101
|
uid: found.record.uid
|
|
102
|
+
};
|
|
103
|
+
const alias = await findAccountByVerifiedAlias(email).catch(()=>null);
|
|
104
|
+
return alias ? {
|
|
105
|
+
uid: alias.uid
|
|
95
106
|
} : null;
|
|
96
107
|
};
|
|
108
|
+
// ── Which addresses are the same mailbox ────────────────────────────────────
|
|
109
|
+
/** The two spellings of Google's consumer mail domain: one mailbox under either. */ const GMAIL_DOMAINS = [
|
|
110
|
+
'gmail.com',
|
|
111
|
+
'googlemail.com'
|
|
112
|
+
];
|
|
113
|
+
function splitAddress(address) {
|
|
114
|
+
const at = address.lastIndexOf('@');
|
|
115
|
+
return {
|
|
116
|
+
local: address.slice(0, at),
|
|
117
|
+
domain: address.slice(at + 1)
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** The local part before any `+tag`; the whole of it when that would leave nothing. */ function untagged(local) {
|
|
121
|
+
const plus = local.indexOf('+');
|
|
122
|
+
return plus > 0 ? local.slice(0, plus) : local;
|
|
123
|
+
}
|
|
124
|
+
/** A Gmail mailbox as Gmail delivers it: no tag, no dots, one domain. */ function gmailMailbox(local) {
|
|
125
|
+
return `${untagged(local).replace(/\./g, '')}@gmail.com`;
|
|
126
|
+
}
|
|
97
127
|
/**
|
|
98
|
-
* The
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
128
|
+
* The addresses a sender may be signed in under, in the order they are tried
|
|
129
|
+
* (AGL-4031). Each tier is tried only when every earlier one named nobody, so
|
|
130
|
+
* an address that is itself somebody's sign-in is never read as somebody
|
|
131
|
+
* else's that merely looks like it:
|
|
132
|
+
*
|
|
133
|
+
* 1. the address as written (compared lower-cased, as every member address is);
|
|
134
|
+
* 2. without its `+tag`: `avery+site@example.com` is `avery@example.com`'s
|
|
135
|
+
* mailbox wherever plus-addressing is offered, and the tag is how people
|
|
136
|
+
* sort mail, not a second identity;
|
|
137
|
+
* 3. for Gmail only, the same mailbox's other spellings: Gmail ignores the
|
|
138
|
+
* dots in a local part and delivers `gmail.com` and `googlemail.com` to one
|
|
139
|
+
* inbox. No other domain's dots are folded, and no tier ever leaves the
|
|
140
|
+
* sender's own domain except between those two.
|
|
141
|
+
*/ export function siteCareSenderCandidates(sender) {
|
|
142
|
+
const address = emailAddressOf(sender);
|
|
143
|
+
if (!address) return [];
|
|
144
|
+
const { local, domain } = splitAddress(address);
|
|
145
|
+
const seen = new Set([
|
|
146
|
+
address
|
|
147
|
+
]);
|
|
148
|
+
const tiers = [
|
|
149
|
+
[
|
|
150
|
+
address
|
|
151
|
+
]
|
|
152
|
+
];
|
|
153
|
+
const tier = (values)=>{
|
|
154
|
+
const fresh = values.filter((value)=>!seen.has(value));
|
|
155
|
+
fresh.forEach((value)=>seen.add(value));
|
|
156
|
+
if (fresh.length) tiers.push(fresh);
|
|
157
|
+
};
|
|
158
|
+
tier([
|
|
159
|
+
`${untagged(local)}@${domain}`
|
|
160
|
+
]);
|
|
161
|
+
if (GMAIL_DOMAINS.includes(domain)) {
|
|
162
|
+
const dotless = untagged(local).replace(/\./g, '');
|
|
163
|
+
const written = untagged(local);
|
|
164
|
+
tier(GMAIL_DOMAINS.flatMap((gmail)=>[
|
|
165
|
+
`${written}@${gmail}`,
|
|
166
|
+
`${dotless}@${gmail}`
|
|
167
|
+
]));
|
|
168
|
+
}
|
|
169
|
+
return tiers;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Whether mail from `sender` came from the mailbox `memberAddress` names, by
|
|
173
|
+
* the same rules as {@link siteCareSenderCandidates}: the address itself,
|
|
174
|
+
* the sender's `+tag` dropped onto the member's untagged address, and, for
|
|
175
|
+
* Gmail alone, dots and the domain's two spellings ignored. A member's own
|
|
176
|
+
* tagged address is matched only as written: `avery+site@` signing in does
|
|
177
|
+
* not make every `avery+…@` theirs.
|
|
178
|
+
*/ export function siteCareAddressMatches(sender, memberAddress) {
|
|
179
|
+
const from = emailAddressOf(sender);
|
|
180
|
+
const member = emailAddressOf(memberAddress);
|
|
181
|
+
if (!from || !member) return false;
|
|
182
|
+
if (from === member) return true;
|
|
183
|
+
const a = splitAddress(from);
|
|
184
|
+
const b = splitAddress(member);
|
|
185
|
+
if (GMAIL_DOMAINS.includes(a.domain) && GMAIL_DOMAINS.includes(b.domain)) {
|
|
186
|
+
return gmailMailbox(a.local) === gmailMailbox(b.local);
|
|
187
|
+
}
|
|
188
|
+
return a.domain === b.domain && untagged(a.local) === b.local;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The one member of a roster a sender is, or null: a member who signs in
|
|
192
|
+
* with the sender's mailbox first, then the one member who confirmed it as
|
|
193
|
+
* an alias in that workspace (AGL-2975). Two members who both match are a
|
|
194
|
+
* guess, and a guess files nothing — the message stays ordinary support mail.
|
|
195
|
+
*/ export function siteCareRosterMember(roster, sender, options = {}) {
|
|
196
|
+
var _bySignIn_find;
|
|
197
|
+
const exact = emailAddressOf(sender);
|
|
198
|
+
const matches = (address)=>options.exactOnly ? Boolean(exact) && emailAddressOf(address) === exact : siteCareAddressMatches(sender, address);
|
|
199
|
+
const bySignIn = roster.filter((member)=>matches(member.email));
|
|
200
|
+
if (bySignIn.length === 1) return bySignIn[0];
|
|
201
|
+
if (bySignIn.length > 1) return (_bySignIn_find = bySignIn.find((member)=>member.email === exact)) != null ? _bySignIn_find : null;
|
|
202
|
+
const byAlias = roster.filter((member)=>{
|
|
203
|
+
var _member_verifiedAliases;
|
|
204
|
+
return ((_member_verifiedAliases = member.verifiedAliases) != null ? _member_verifiedAliases : []).some((alias)=>matches(alias));
|
|
205
|
+
});
|
|
206
|
+
return byAlias.length === 1 ? byAlias[0] : null;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* How many Site Care workspaces the roster pass reads at most. It runs only
|
|
210
|
+
* for mail the account lookups could not place, and each workspace costs two
|
|
211
|
+
* reads, so the bound is what keeps a busy support inbox from costing more
|
|
212
|
+
* than a lookup should.
|
|
213
|
+
*/ export const SITE_CARE_ROSTER_SCAN_MAX = 200;
|
|
214
|
+
/**
|
|
215
|
+
* The second pass, for what no account lookup can answer: a Gmail owner
|
|
216
|
+
* whose sign-in is `first.last@gmail.com` writing as `firstlast@gmail.com`
|
|
217
|
+
* (an account is found by its exact address only), and an address a member
|
|
218
|
+
* confirmed as theirs in the workspace itself rather than on the account.
|
|
219
|
+
* Reads the roster and the confirmed aliases of each workspace that bought
|
|
220
|
+
* Site Care, and keeps the ones where exactly one member is the sender.
|
|
221
|
+
* `exactOnly` when the address as written is somebody's sign-in: that
|
|
222
|
+
* person is who wrote, and a look-alike on a roster is not.
|
|
223
|
+
*/ async function siteCareRosterMatches(firestore, sender, exactOnly) {
|
|
224
|
+
const bought = await firestore.collection('orgs').where('seatAddons.siteCare', '>=', 1).limit(SITE_CARE_ROSTER_SCAN_MAX).get();
|
|
225
|
+
const matches = [];
|
|
226
|
+
for (const orgId of bought.docs.map((doc)=>doc.id).sort()){
|
|
227
|
+
const orgRef = firestore.collection('orgs').doc(orgId);
|
|
228
|
+
const [members, aliases] = await Promise.all([
|
|
229
|
+
orgRef.collection('members').get(),
|
|
230
|
+
orgRef.collection(MEMBER_EMAIL_ALIASES_COLLECTION).get()
|
|
231
|
+
]);
|
|
232
|
+
const rows = members.docs.map((doc)=>{
|
|
233
|
+
var _doc_data;
|
|
234
|
+
return _extends({}, (_doc_data = doc.data()) != null ? _doc_data : {}, {
|
|
235
|
+
$id: doc.id
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
const roster = memberAddressRoster(rows, new Map(aliases.docs.map((doc)=>[
|
|
239
|
+
String(doc.id),
|
|
240
|
+
doc.data()
|
|
241
|
+
])));
|
|
242
|
+
const member = siteCareRosterMember(roster, sender, {
|
|
243
|
+
exactOnly
|
|
244
|
+
});
|
|
245
|
+
if (!member) continue;
|
|
111
246
|
const org = await readSiteCareOrg(firestore, orgId);
|
|
112
|
-
if (org && orgHasSiteCare(org))
|
|
247
|
+
if (org && orgHasSiteCare(org)) matches.push({
|
|
113
248
|
orgId,
|
|
114
249
|
org,
|
|
115
|
-
uid:
|
|
116
|
-
email
|
|
117
|
-
};
|
|
250
|
+
uid: member.uid,
|
|
251
|
+
email: sender
|
|
252
|
+
});
|
|
118
253
|
}
|
|
119
|
-
return
|
|
254
|
+
return matches;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* EVERY Site Care workspace a sender belongs to, by workspace id (AGL-4031).
|
|
258
|
+
*
|
|
259
|
+
* First the account the sender's address signs in with, in any pool or as a
|
|
260
|
+
* confirmed account address, trying the address's tiers in order
|
|
261
|
+
* ({@link siteCareSenderCandidates}); then the workspaces that account is a
|
|
262
|
+
* member of with Site Care in force. When that places the sender nowhere,
|
|
263
|
+
* the rosters of the workspaces that bought Site Care are read for the
|
|
264
|
+
* sender's mailbox ({@link siteCareRosterMatches}).
|
|
265
|
+
*
|
|
266
|
+
* All of them, not the first: which one a message is filed on, when there
|
|
267
|
+
* are several, is the caller's choice.
|
|
268
|
+
*/ export async function findSiteCareWorkspacesForSender(firestore, findAccount, sender) {
|
|
269
|
+
const email = emailAddressOf(sender);
|
|
270
|
+
if (!email) return [];
|
|
271
|
+
let uids = [];
|
|
272
|
+
let foundAtTier = -1;
|
|
273
|
+
for (const [index, tier] of siteCareSenderCandidates(email).entries()){
|
|
274
|
+
const found = await Promise.all(tier.map((address)=>findAccount(address).catch(()=>null)));
|
|
275
|
+
uids = [
|
|
276
|
+
...new Set(found.filter((user)=>Boolean(user)).map((user)=>user.uid))
|
|
277
|
+
];
|
|
278
|
+
if (uids.length) {
|
|
279
|
+
foundAtTier = index;
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const matches = [];
|
|
284
|
+
for (const uid of uids){
|
|
285
|
+
const memberships = await firestore.collection('users').doc(uid).collection('orgs').limit(25).get();
|
|
286
|
+
for (const orgId of memberships.docs.map((doc)=>doc.id).sort()){
|
|
287
|
+
if (matches.some((match)=>match.orgId === orgId)) continue;
|
|
288
|
+
const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(uid).get();
|
|
289
|
+
if (!member.exists) continue;
|
|
290
|
+
const org = await readSiteCareOrg(firestore, orgId);
|
|
291
|
+
if (org && orgHasSiteCare(org)) matches.push({
|
|
292
|
+
orgId,
|
|
293
|
+
org,
|
|
294
|
+
uid,
|
|
295
|
+
email
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (matches.length) return matches.sort((a, b)=>a.orgId < b.orgId ? -1 : a.orgId > b.orgId ? 1 : 0);
|
|
300
|
+
return siteCareRosterMatches(firestore, email, foundAtTier === 0);
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* The Site Care workspace a sender's new request is filed on: the first of
|
|
304
|
+
* {@link findSiteCareWorkspacesForSender}'s, by workspace id, so the choice
|
|
305
|
+
* is stable. A sender in several Site Care workspaces files on the lowest
|
|
306
|
+
* id, with every candidate recorded for staff, who move the request when it
|
|
307
|
+
* belongs to another (AGL-4031, `moveSiteCareRequest`).
|
|
308
|
+
*/ export async function findSiteCareWorkspaceForSender(firestore, findAccount, sender) {
|
|
309
|
+
var _;
|
|
310
|
+
return (_ = (await findSiteCareWorkspacesForSender(firestore, findAccount, sender))[0]) != null ? _ : null;
|
|
120
311
|
}
|
|
121
312
|
/** The words of a message, above any quoted history. */ export function siteCareMessageBody(message) {
|
|
122
313
|
var _message_text;
|
|
@@ -129,7 +320,7 @@ import { findUserByEmailAcrossPools } from "./auth-pools.js";
|
|
|
129
320
|
* not file for: a message to the support address is still in the support
|
|
130
321
|
* inbox, answered there like any other.
|
|
131
322
|
*/ export async function fileSiteCareInboundEmail(firestore, input, deps = {}) {
|
|
132
|
-
var _input_addresses, _input_findAccount;
|
|
323
|
+
var _input_addresses, _input_findAccount, _matches_;
|
|
133
324
|
const { message } = input;
|
|
134
325
|
const machine = siteCareMachineMail(message, (_input_addresses = input.addresses) != null ? _input_addresses : siteCareInboundAddresses());
|
|
135
326
|
if (machine) return {
|
|
@@ -139,14 +330,25 @@ import { findUserByEmailAcrossPools } from "./auth-pools.js";
|
|
|
139
330
|
const body = siteCareMessageBody(message);
|
|
140
331
|
const sender = emailAddressOf(message.from);
|
|
141
332
|
const findAccount = (_input_findAccount = input.findAccount) != null ? _input_findAccount : findSiteCareAccount;
|
|
142
|
-
const
|
|
333
|
+
const matches = sender ? await findSiteCareWorkspacesForSender(firestore, findAccount, sender) : [];
|
|
334
|
+
// A new request files on the first workspace by id (see
|
|
335
|
+
// findSiteCareWorkspaceForSender); every candidate is recorded with it.
|
|
336
|
+
const match = (_matches_ = matches[0]) != null ? _matches_ : null;
|
|
143
337
|
if (input.target.kind === 'reply' && match) {
|
|
144
338
|
var _ticket_get;
|
|
145
339
|
const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get();
|
|
146
340
|
const orgId = String((_ticket_get = ticket.get('orgId')) != null ? _ticket_get : '');
|
|
147
341
|
// Only a member of the request's own workspace may add to it.
|
|
148
|
-
|
|
149
|
-
|
|
342
|
+
let author = null;
|
|
343
|
+
for (const uid of orgId ? [
|
|
344
|
+
...new Set(matches.map((each)=>each.uid))
|
|
345
|
+
] : []){
|
|
346
|
+
if ((await firestore.collection('orgs').doc(orgId).collection('members').doc(uid).get()).exists) {
|
|
347
|
+
author = uid;
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (ticket.exists && author) {
|
|
150
352
|
if (!body) return {
|
|
151
353
|
outcome: 'ignored',
|
|
152
354
|
reason: 'empty'
|
|
@@ -154,7 +356,7 @@ import { findUserByEmailAcrossPools } from "./auth-pools.js";
|
|
|
154
356
|
await appendSiteCareReply(firestore, {
|
|
155
357
|
ticketId: ticket.id,
|
|
156
358
|
from: {
|
|
157
|
-
uid:
|
|
359
|
+
uid: author,
|
|
158
360
|
email: match.email
|
|
159
361
|
},
|
|
160
362
|
body,
|
|
@@ -186,7 +388,15 @@ import { findUserByEmailAcrossPools } from "./auth-pools.js";
|
|
|
186
388
|
email: match.email
|
|
187
389
|
},
|
|
188
390
|
source: 'email',
|
|
189
|
-
dedupeKey: message.messageId || message.id
|
|
391
|
+
dedupeKey: message.messageId || message.id,
|
|
392
|
+
candidates: matches.map((each)=>{
|
|
393
|
+
var _each_org_name;
|
|
394
|
+
return {
|
|
395
|
+
orgId: each.orgId,
|
|
396
|
+
name: String((_each_org_name = each.org['name']) != null ? _each_org_name : '') || each.orgId,
|
|
397
|
+
uid: each.uid
|
|
398
|
+
};
|
|
399
|
+
})
|
|
190
400
|
}, deps);
|
|
191
401
|
return {
|
|
192
402
|
outcome: 'opened',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-inbound.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 { inboundMailDomain } from '@aglyn/aglyn/app-utils/inbound-mail-domain'\nimport {\n emailAddressOf,\n htmlToPlainText,\n stripQuotedHistory,\n threadSubject,\n} from '@aglyn/aglyn/app-utils/email-text'\nimport { SITE_CARE_INBOUND_LOCAL_PART, siteCareSupportAddress } from '@aglyn/aglyn/app-utils/site-care'\nimport { getEmailConfig, type ReceivedEmail } from '@aglyn/shared-util-email'\nimport {\n appendSiteCareReply,\n openSiteCareRequest,\n orgHasSiteCare,\n readSiteCareOrg,\n type SiteCareDeps,\n} from './site-care-requests'\nimport { findUserByEmailAcrossPools } from './auth-pools'\n\n/**\n * SITE CARE MAIL ARRIVES AT THE SUPPORT ADDRESS (AGL-3959, AGL-3997).\n *\n * Site Care has no address of its own. An owner emails the support address\n * they already know, and the support mailbox delivers a copy of each message\n * to `support@<inbound mail domain>`, where the mail provider announces it.\n * A message to either address from a member of a workspace with Site Care\n * becomes a Site Care request on that workspace, matched by the sender's\n * address against the members of workspaces that have Site Care. A reply to\n * any Site Care email goes to `support+<requestId>@…` and joins that\n * request's thread, when the sender is a member of its workspace.\n *\n * Everything else is acknowledged and left alone: nothing is filed and\n * nothing is sent back, and a message to the support address stays in the\n * support inbox as ordinary support mail. That includes the platform's own\n * mail and anything a machine sent: an out-of-office answering a Site Care\n * email would otherwise join the request, and one answering anything that\n * replies to support would open one.\n */\n\n/** What a received message was addressed to: a new request, or a reply on one. */\nexport type SiteCareInboundTarget = { kind: 'new' } | { kind: 'reply'; requestId: string }\n\n/** The addresses the intake reads as the platform's own. */\nexport interface SiteCareInboundAddresses {\n /** The inbound mail domain: `support@` and `support+<requestId>@` it. */\n domain: string\n /** The operator's support address, or null when the deployment publishes none. */\n supportEmail: string | null\n /** The address the platform sends from, `USAGE_EMAIL_FROM`'s, or null. */\n platformSender: string | null\n}\n\n/** This deployment's {@link SiteCareInboundAddresses}, read per call. */\nexport function siteCareInboundAddresses(): SiteCareInboundAddresses {\n return {\n domain: inboundMailDomain(),\n supportEmail: emailAddressOf(siteCareSupportAddress()),\n platformSender: emailAddressOf(getEmailConfig().from),\n }\n}\n\n/** The Site Care target among a message's recipients, or null. */\nexport function siteCareInboundTarget(\n recipients: readonly string[],\n addresses: Pick<SiteCareInboundAddresses, 'domain' | 'supportEmail'>,\n): SiteCareInboundTarget | null {\n const domain = addresses.domain.toLowerCase()\n const support = emailAddressOf(addresses.supportEmail)\n let found: SiteCareInboundTarget | null = null\n for (const value of recipients) {\n // Validated (and lowercased) for the comparison, but the local part is\n // read as written: a request id is a case-sensitive Firestore id, and\n // lowercasing `support+AbC…` would look up a ticket that does not exist.\n const address = emailAddressOf(value)\n if (!address) continue\n if (support && address === support) {\n found = found ?? { kind: 'new' }\n continue\n }\n const raw = String(value ?? '').trim()\n const written = (/<([^<>]+)>\\s*$/.exec(raw)?.[1] ?? raw).trim()\n const at = written.lastIndexOf('@')\n if (at <= 0 || address.slice(address.lastIndexOf('@') + 1) !== domain) continue\n const local = written.slice(0, at)\n if (local.toLowerCase() === SITE_CARE_INBOUND_LOCAL_PART) {\n found = found ?? { kind: 'new' }\n continue\n }\n const prefix = `${SITE_CARE_INBOUND_LOCAL_PART}+`\n if (local.toLowerCase().startsWith(prefix)) {\n const requestId = local.slice(prefix.length)\n // Firestore ids: 20 characters of [A-Za-z0-9]; anything else by shape\n // is refused rather than looked up.\n if (/^[A-Za-z0-9]{10,40}$/.test(requestId)) return { kind: 'reply', requestId }\n }\n }\n return found\n}\n\n/** Why a message is ignored without a lookup: the platform wrote it, or a machine did. */\nexport type SiteCareMachineMail = 'ours' | 'automatic'\n\n/**\n * Whether a message is not a person writing in: from the support address,\n * the platform's sender or any address on the inbound mail domain, or one\n * its headers say a machine sent. Null when it may be a person.\n */\nexport function siteCareMachineMail(\n message: Pick<ReceivedEmail, 'from' | 'autoSubmitted'>,\n addresses: SiteCareInboundAddresses,\n): SiteCareMachineMail | null {\n const sender = emailAddressOf(message.from)\n if (sender) {\n const own = [addresses.supportEmail, addresses.platformSender].map((value) => emailAddressOf(value))\n if (own.includes(sender)) return 'ours'\n if (sender.slice(sender.lastIndexOf('@') + 1) === addresses.domain.toLowerCase()) return 'ours'\n }\n return message.autoSubmitted ? 'automatic' : null\n}\n\nexport interface SiteCareSenderMatch {\n orgId: string\n org: Record<string, unknown>\n uid: string\n email: string\n}\n\n/** The account an address signs in with: its uid, or null when it has none. */\nexport type SiteCareAccountLookup = (email: string) => Promise<{ uid: string } | null>\n\n/**\n * Every pool, not only the project's: an owner who signs in through SSO is a\n * GCIP tenant user the project pool never returns (AGL-1122), and their mail\n * would be read as a stranger's.\n */\nexport const findSiteCareAccount: SiteCareAccountLookup = async (email) => {\n const found = await findUserByEmailAcrossPools(email).catch(() => null)\n return found ? { uid: found.record.uid } : null\n}\n\n/**\n * The Site Care workspace a sender belongs to: the account their address\n * signs in with (in any pool), then the workspaces it is a member of, the\n * first with Site Care in force (by id, so the choice is stable).\n */\nexport async function findSiteCareWorkspaceForSender(\n firestore: FirebaseFirestore.Firestore,\n findAccount: SiteCareAccountLookup,\n sender: string,\n): Promise<SiteCareSenderMatch | null> {\n const email = emailAddressOf(sender)\n if (!email) return null\n const user = await findAccount(email).catch(() => null)\n if (!user) return null\n const memberships = await firestore.collection('users').doc(user.uid).collection('orgs').limit(25).get()\n const orgIds = memberships.docs.map((doc) => doc.id).sort()\n for (const orgId of orgIds) {\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(user.uid).get()\n if (!member.exists) continue\n const org = await readSiteCareOrg(firestore, orgId)\n if (org && orgHasSiteCare(org)) return { orgId, org, uid: user.uid, email }\n }\n return null\n}\n\n/** The words of a message, above any quoted history. */\nexport function siteCareMessageBody(message: Pick<ReceivedEmail, 'text' | 'html'>): string {\n const plain = (message.text?.trim() ? message.text : htmlToPlainText(message.html)).replace(/\\r\\n?/g, '\\n')\n return stripQuotedHistory(plain).trim()\n}\n\n/** Why a message was acknowledged and left alone. */\nexport type SiteCareIgnoredReason =\n /** No workspace with Site Care has the sender as a member: ordinary support mail. */\n | 'not-a-member'\n /** The platform's own address wrote it. */\n | 'ours'\n /** Its headers say a machine sent it. */\n | 'automatic'\n /** A member wrote, but said nothing. */\n | 'empty'\n\nexport type SiteCareInboundOutcome =\n | { outcome: 'opened'; requestId: string }\n | { outcome: 'replied'; requestId: string }\n | { outcome: 'ignored'; reason: SiteCareIgnoredReason }\n\n/**\n * Files one received message addressed to the support address or to a\n * request's reply address. Nothing is ever sent back to a sender it does\n * not file for: a message to the support address is still in the support\n * inbox, answered there like any other.\n */\nexport async function fileSiteCareInboundEmail(\n firestore: FirebaseFirestore.Firestore,\n input: {\n target: SiteCareInboundTarget\n message: ReceivedEmail\n /** The platform's own addresses; this deployment's by default. */\n addresses?: SiteCareInboundAddresses\n /** The seam a spec replaces; every auth pool by default. */\n findAccount?: SiteCareAccountLookup\n },\n deps: SiteCareDeps = {},\n): Promise<SiteCareInboundOutcome> {\n const { message } = input\n const machine = siteCareMachineMail(message, input.addresses ?? siteCareInboundAddresses())\n if (machine) return { outcome: 'ignored', reason: machine }\n const body = siteCareMessageBody(message)\n const sender = emailAddressOf(message.from)\n const findAccount = input.findAccount ?? findSiteCareAccount\n const match = sender ? await findSiteCareWorkspaceForSender(firestore, findAccount, sender) : null\n if (input.target.kind === 'reply' && match) {\n const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get()\n const orgId = String(ticket.get('orgId') ?? '')\n // Only a member of the request's own workspace may add to it.\n const member = orgId\n ? (await firestore.collection('orgs').doc(orgId).collection('members').doc(match.uid).get()).exists\n : false\n if (ticket.exists && member) {\n if (!body) return { outcome: 'ignored', reason: 'empty' }\n await appendSiteCareReply(\n firestore,\n {\n ticketId: ticket.id,\n from: { uid: match.uid, email: match.email },\n body,\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'replied', requestId: ticket.id }\n }\n // A reply that cannot join its request is read as a new one below.\n }\n if (!match) return { outcome: 'ignored', reason: 'not-a-member' }\n if (!body && !threadSubject(message.subject)) return { outcome: 'ignored', reason: 'empty' }\n const opened = await openSiteCareRequest(\n firestore,\n {\n orgId: match.orgId,\n org: match.org,\n hostId: null,\n subject: threadSubject(message.subject) || body.split('\\n')[0].slice(0, 150) || 'A change by email',\n body: body || threadSubject(message.subject),\n requester: { uid: match.uid, email: match.email },\n source: 'email',\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'opened', requestId: opened.ticketId }\n}\n"],"names":["inboundMailDomain","emailAddressOf","htmlToPlainText","stripQuotedHistory","threadSubject","SITE_CARE_INBOUND_LOCAL_PART","siteCareSupportAddress","getEmailConfig","appendSiteCareReply","openSiteCareRequest","orgHasSiteCare","readSiteCareOrg","findUserByEmailAcrossPools","siteCareInboundAddresses","domain","supportEmail","platformSender","from","siteCareInboundTarget","recipients","addresses","toLowerCase","support","found","value","address","kind","raw","String","trim","written","exec","at","lastIndexOf","slice","local","prefix","startsWith","requestId","length","test","siteCareMachineMail","message","sender","own","map","includes","autoSubmitted","findSiteCareAccount","email","catch","uid","record","findSiteCareWorkspaceForSender","firestore","findAccount","user","memberships","collection","doc","limit","get","orgIds","docs","id","sort","orgId","member","exists","org","siteCareMessageBody","plain","text","html","replace","fileSiteCareInboundEmail","input","deps","machine","outcome","reason","body","match","target","ticket","ticketId","dedupeKey","messageId","subject","opened","hostId","split","requester","source"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,cAAc,EACdC,eAAe,EACfC,kBAAkB,EAClBC,aAAa,QACR,oCAAmC;AAC1C,SAASC,4BAA4B,EAAEC,sBAAsB,QAAQ,mCAAkC;AACvG,SAASC,cAAc,QAA4B,2BAA0B;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,cAAc,EACdC,eAAe,QAEV,0BAAsB;AAC7B,SAASC,0BAA0B,QAAQ,kBAAc;AAmCzD,uEAAuE,GACvE,OAAO,SAASC;IACd,OAAO;QACLC,QAAQd;QACRe,cAAcd,eAAeK;QAC7BU,gBAAgBf,eAAeM,iBAAiBU,IAAI;IACtD;AACF;AAEA,gEAAgE,GAChE,OAAO,SAASC,sBACdC,UAA6B,EAC7BC,SAAoE;IAEpE,MAAMN,SAASM,UAAUN,MAAM,CAACO,WAAW;IAC3C,MAAMC,UAAUrB,eAAemB,UAAUL,YAAY;IACrD,IAAIQ,QAAsC;IAC1C,KAAK,MAAMC,SAASL,WAAY;;YAWb;QAVjB,uEAAuE;QACvE,sEAAsE;QACtE,yEAAyE;QACzE,MAAMM,UAAUxB,eAAeuB;Q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ACA;gBACE+B,UAAUD,OAAOpB,EAAE;gBACnB/C,MAAM;oBAAEkC,KAAK+B,MAAM/B,GAAG;oBAAEF,OAAOiC,MAAMjC,KAAK;gBAAC;gBAC3CgC;gBACAK,WAAW5C,QAAQ6C,SAAS,IAAI7C,QAAQsB,EAAE;YAC5C,GACAa;YAEF,OAAO;gBAAEE,SAAS;gBAAWzC,WAAW8C,OAAOpB,EAAE;YAAC;QACpD;IACA,mEAAmE;IACrE;IACA,IAAI,CAACkB,OAAO,OAAO;QAAEH,SAAS;QAAWC,QAAQ;IAAe;IAChE,IAAI,CAACC,QAAQ,CAAC7E,cAAcsC,QAAQ8C,OAAO,GAAG,OAAO;QAAET,SAAS;QAAWC,QAAQ;IAAQ;IAC3F,MAAMS,SAAS,MAAMhF,oBACnB6C,WACA;QACEY,OAAOgB,MAAMhB,KAAK;QAClBG,KAAKa,MAAMb,GAAG;QACdqB,QAAQ;QACRF,SAASpF,cAAcsC,QAAQ8C,OAAO,KAAKP,KAAKU,KAAK,CAAC,KAAK,CAAC,EAAE,CAACzD,KAAK,CAAC,GAAG,QAAQ;QAChF+C,MAAMA,QAAQ7E,cAAcsC,QAAQ8C,OAAO;QAC3CI,WAAW;YAAEzC,KAAK+B,MAAM/B,GAAG;YAAEF,OAAOiC,MAAMjC,KAAK;QAAC;QAChD4C,QAAQ;QACRP,WAAW5C,QAAQ6C,SAAS,IAAI7C,QAAQsB,EAAE;IAC5C,GACAa;IAEF,OAAO;QAAEE,SAAS;QAAUzC,WAAWmD,OAAOJ,QAAQ;IAAC;AACzD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-inbound.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 { inboundMailDomain } from '@aglyn/aglyn/app-utils/inbound-mail-domain'\nimport {\n emailAddressOf,\n htmlToPlainText,\n stripQuotedHistory,\n threadSubject,\n} from '@aglyn/aglyn/app-utils/email-text'\nimport {\n MEMBER_EMAIL_ALIASES_COLLECTION,\n memberAddressRoster,\n type RosterMember,\n type RosterRow,\n} from '@aglyn/aglyn/app-utils/member-email-aliases'\nimport { SITE_CARE_INBOUND_LOCAL_PART, siteCareSupportAddress } from '@aglyn/aglyn/app-utils/site-care'\nimport { getEmailConfig, type ReceivedEmail } from '@aglyn/shared-util-email'\nimport {\n appendSiteCareReply,\n openSiteCareRequest,\n orgHasSiteCare,\n readSiteCareOrg,\n type SiteCareDeps,\n} from './site-care-requests'\nimport { findAccountByVerifiedAlias } from './account-emails'\nimport { findUserByEmailAcrossPools } from './auth-pools'\n\n/**\n * SITE CARE MAIL ARRIVES AT THE SUPPORT ADDRESS (AGL-3959, AGL-3997).\n *\n * Site Care has no address of its own. An owner emails the support address\n * they already know, and the support mailbox delivers a copy of each message\n * to `support@<inbound mail domain>`, where the mail provider announces it.\n * A message to either address from a member of a workspace with Site Care\n * becomes a Site Care request on that workspace, matched by the sender's\n * address against the members of workspaces that have Site Care. A reply to\n * any Site Care email goes to `support+<requestId>@…` and joins that\n * request's thread, when the sender is a member of its workspace.\n *\n * The sender is matched as a mailbox, not as a string (AGL-4031): case does\n * not matter, a `+tag` is dropped, Gmail's dots and its two domains are one\n * mailbox, and an address a member confirmed (on their account, or in the\n * workspace) counts as theirs. This is looser than the account and alias\n * stores, which keep `a+b@x.com` and `a@x.com` apart on purpose, and it can\n * afford to be: it only places mail from somebody already on a workspace's\n * roster, grants nothing, and never crosses from one domain to another except\n * between Gmail's two.\n *\n * Everything else is acknowledged and left alone: nothing is filed and\n * nothing is sent back, and a message to the support address stays in the\n * support inbox as ordinary support mail. That includes the platform's own\n * mail and anything a machine sent: an out-of-office answering a Site Care\n * email would otherwise join the request, and one answering anything that\n * replies to support would open one.\n */\n\n/** What a received message was addressed to: a new request, or a reply on one. */\nexport type SiteCareInboundTarget = { kind: 'new' } | { kind: 'reply'; requestId: string }\n\n/** The addresses the intake reads as the platform's own. */\nexport interface SiteCareInboundAddresses {\n /** The inbound mail domain: `support@` and `support+<requestId>@` it. */\n domain: string\n /** The operator's support address, or null when the deployment publishes none. */\n supportEmail: string | null\n /** The address the platform sends from, `USAGE_EMAIL_FROM`'s, or null. */\n platformSender: string | null\n}\n\n/** This deployment's {@link SiteCareInboundAddresses}, read per call. */\nexport function siteCareInboundAddresses(): SiteCareInboundAddresses {\n return {\n domain: inboundMailDomain(),\n supportEmail: emailAddressOf(siteCareSupportAddress()),\n platformSender: emailAddressOf(getEmailConfig().from),\n }\n}\n\n/** The Site Care target among a message's recipients, or null. */\nexport function siteCareInboundTarget(\n recipients: readonly string[],\n addresses: Pick<SiteCareInboundAddresses, 'domain' | 'supportEmail'>,\n): SiteCareInboundTarget | null {\n const domain = addresses.domain.toLowerCase()\n const support = emailAddressOf(addresses.supportEmail)\n let found: SiteCareInboundTarget | null = null\n for (const value of recipients) {\n // Validated (and lowercased) for the comparison, but the local part is\n // read as written: a request id is a case-sensitive Firestore id, and\n // lowercasing `support+AbC…` would look up a ticket that does not exist.\n const address = emailAddressOf(value)\n if (!address) continue\n if (support && address === support) {\n found = found ?? { kind: 'new' }\n continue\n }\n const raw = String(value ?? '').trim()\n const written = (/<([^<>]+)>\\s*$/.exec(raw)?.[1] ?? raw).trim()\n const at = written.lastIndexOf('@')\n if (at <= 0 || address.slice(address.lastIndexOf('@') + 1) !== domain) continue\n const local = written.slice(0, at)\n if (local.toLowerCase() === SITE_CARE_INBOUND_LOCAL_PART) {\n found = found ?? { kind: 'new' }\n continue\n }\n const prefix = `${SITE_CARE_INBOUND_LOCAL_PART}+`\n if (local.toLowerCase().startsWith(prefix)) {\n const requestId = local.slice(prefix.length)\n // Firestore ids: 20 characters of [A-Za-z0-9]; anything else by shape\n // is refused rather than looked up.\n if (/^[A-Za-z0-9]{10,40}$/.test(requestId)) return { kind: 'reply', requestId }\n }\n }\n return found\n}\n\n/** Why a message is ignored without a lookup: the platform wrote it, or a machine did. */\nexport type SiteCareMachineMail = 'ours' | 'automatic'\n\n/**\n * Whether a message is not a person writing in: from the support address,\n * the platform's sender or any address on the inbound mail domain, or one\n * its headers say a machine sent. Null when it may be a person.\n */\nexport function siteCareMachineMail(\n message: Pick<ReceivedEmail, 'from' | 'autoSubmitted'>,\n addresses: SiteCareInboundAddresses,\n): SiteCareMachineMail | null {\n const sender = emailAddressOf(message.from)\n if (sender) {\n const own = [addresses.supportEmail, addresses.platformSender].map((value) => emailAddressOf(value))\n if (own.includes(sender)) return 'ours'\n if (sender.slice(sender.lastIndexOf('@') + 1) === addresses.domain.toLowerCase()) return 'ours'\n }\n return message.autoSubmitted ? 'automatic' : null\n}\n\nexport interface SiteCareSenderMatch {\n orgId: string\n org: Record<string, unknown>\n uid: string\n email: string\n}\n\n/** The account an address signs in with: its uid, or null when it has none. */\nexport type SiteCareAccountLookup = (email: string) => Promise<{ uid: string } | null>\n\n/**\n * Every pool, not only the project's: an owner who signs in through SSO is a\n * GCIP tenant user the project pool never returns (AGL-1122), and their mail\n * would be read as a stranger's. Then the account addresses people add to\n * their account and CONFIRM (AGL-2486): a confirmed address is one of that\n * account's sign-in identifiers, held by no other account, so mail from it is\n * that person's (AGL-4031). An address only typed, never confirmed, is not in\n * that index and is never read as anyone's.\n */\nexport const findSiteCareAccount: SiteCareAccountLookup = async (email) => {\n const found = await findUserByEmailAcrossPools(email).catch(() => null)\n if (found) return { uid: found.record.uid }\n const alias = await findAccountByVerifiedAlias(email).catch(() => null)\n return alias ? { uid: alias.uid } : null\n}\n\n// ── Which addresses are the same mailbox ────────────────────────────────────\n\n/** The two spellings of Google's consumer mail domain: one mailbox under either. */\nconst GMAIL_DOMAINS: readonly string[] = ['gmail.com', 'googlemail.com']\n\nfunction splitAddress(address: string): { local: string; domain: string } {\n const at = address.lastIndexOf('@')\n return { local: address.slice(0, at), domain: address.slice(at + 1) }\n}\n\n/** The local part before any `+tag`; the whole of it when that would leave nothing. */\nfunction untagged(local: string): string {\n const plus = local.indexOf('+')\n return plus > 0 ? local.slice(0, plus) : local\n}\n\n/** A Gmail mailbox as Gmail delivers it: no tag, no dots, one domain. */\nfunction gmailMailbox(local: string): string {\n return `${untagged(local).replace(/\\./g, '')}@gmail.com`\n}\n\n/**\n * The addresses a sender may be signed in under, in the order they are tried\n * (AGL-4031). Each tier is tried only when every earlier one named nobody, so\n * an address that is itself somebody's sign-in is never read as somebody\n * else's that merely looks like it:\n *\n * 1. the address as written (compared lower-cased, as every member address is);\n * 2. without its `+tag`: `avery+site@example.com` is `avery@example.com`'s\n * mailbox wherever plus-addressing is offered, and the tag is how people\n * sort mail, not a second identity;\n * 3. for Gmail only, the same mailbox's other spellings: Gmail ignores the\n * dots in a local part and delivers `gmail.com` and `googlemail.com` to one\n * inbox. No other domain's dots are folded, and no tier ever leaves the\n * sender's own domain except between those two.\n */\nexport function siteCareSenderCandidates(sender: unknown): string[][] {\n const address = emailAddressOf(sender)\n if (!address) return []\n const { local, domain } = splitAddress(address)\n const seen = new Set<string>([address])\n const tiers: string[][] = [[address]]\n const tier = (values: string[]) => {\n const fresh = values.filter((value) => !seen.has(value))\n fresh.forEach((value) => seen.add(value))\n if (fresh.length) tiers.push(fresh)\n }\n tier([`${untagged(local)}@${domain}`])\n if (GMAIL_DOMAINS.includes(domain)) {\n const dotless = untagged(local).replace(/\\./g, '')\n const written = untagged(local)\n tier(GMAIL_DOMAINS.flatMap((gmail) => [`${written}@${gmail}`, `${dotless}@${gmail}`]))\n }\n return tiers\n}\n\n/**\n * Whether mail from `sender` came from the mailbox `memberAddress` names, by\n * the same rules as {@link siteCareSenderCandidates}: the address itself,\n * the sender's `+tag` dropped onto the member's untagged address, and, for\n * Gmail alone, dots and the domain's two spellings ignored. A member's own\n * tagged address is matched only as written: `avery+site@` signing in does\n * not make every `avery+…@` theirs.\n */\nexport function siteCareAddressMatches(sender: unknown, memberAddress: unknown): boolean {\n const from = emailAddressOf(sender)\n const member = emailAddressOf(memberAddress)\n if (!from || !member) return false\n if (from === member) return true\n const a = splitAddress(from)\n const b = splitAddress(member)\n if (GMAIL_DOMAINS.includes(a.domain) && GMAIL_DOMAINS.includes(b.domain)) {\n return gmailMailbox(a.local) === gmailMailbox(b.local)\n }\n return a.domain === b.domain && untagged(a.local) === b.local\n}\n\n/**\n * The one member of a roster a sender is, or null: a member who signs in\n * with the sender's mailbox first, then the one member who confirmed it as\n * an alias in that workspace (AGL-2975). Two members who both match are a\n * guess, and a guess files nothing — the message stays ordinary support mail.\n */\nexport function siteCareRosterMember(\n roster: readonly RosterMember[],\n sender: unknown,\n options: { exactOnly?: boolean } = {},\n): RosterMember | null {\n const exact = emailAddressOf(sender)\n const matches = (address: unknown) =>\n options.exactOnly ? Boolean(exact) && emailAddressOf(address) === exact : siteCareAddressMatches(sender, address)\n const bySignIn = roster.filter((member) => matches(member.email))\n if (bySignIn.length === 1) return bySignIn[0]\n if (bySignIn.length > 1) return bySignIn.find((member) => member.email === exact) ?? null\n const byAlias = roster.filter((member) => (member.verifiedAliases ?? []).some((alias) => matches(alias)))\n return byAlias.length === 1 ? byAlias[0] : null\n}\n\n/**\n * How many Site Care workspaces the roster pass reads at most. It runs only\n * for mail the account lookups could not place, and each workspace costs two\n * reads, so the bound is what keeps a busy support inbox from costing more\n * than a lookup should.\n */\nexport const SITE_CARE_ROSTER_SCAN_MAX = 200\n\n/**\n * The second pass, for what no account lookup can answer: a Gmail owner\n * whose sign-in is `first.last@gmail.com` writing as `firstlast@gmail.com`\n * (an account is found by its exact address only), and an address a member\n * confirmed as theirs in the workspace itself rather than on the account.\n * Reads the roster and the confirmed aliases of each workspace that bought\n * Site Care, and keeps the ones where exactly one member is the sender.\n * `exactOnly` when the address as written is somebody's sign-in: that\n * person is who wrote, and a look-alike on a roster is not.\n */\nasync function siteCareRosterMatches(\n firestore: FirebaseFirestore.Firestore,\n sender: string,\n exactOnly: boolean,\n): Promise<SiteCareSenderMatch[]> {\n const bought = await firestore\n .collection('orgs')\n .where('seatAddons.siteCare', '>=', 1)\n .limit(SITE_CARE_ROSTER_SCAN_MAX)\n .get()\n const matches: SiteCareSenderMatch[] = []\n for (const orgId of bought.docs.map((doc) => doc.id).sort()) {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const [members, aliases] = await Promise.all([\n orgRef.collection('members').get(),\n orgRef.collection(MEMBER_EMAIL_ALIASES_COLLECTION).get(),\n ])\n const rows: RosterRow[] = members.docs.map((doc) => ({\n ...((doc.data() ?? {}) as Omit<RosterRow, '$id'>),\n $id: doc.id,\n }))\n const roster = memberAddressRoster(rows, new Map(aliases.docs.map((doc) => [String(doc.id), doc.data()])))\n const member = siteCareRosterMember(roster, sender, { exactOnly })\n if (!member) continue\n const org = await readSiteCareOrg(firestore, orgId)\n if (org && orgHasSiteCare(org)) matches.push({ orgId, org, uid: member.uid, email: sender })\n }\n return matches\n}\n\n/**\n * EVERY Site Care workspace a sender belongs to, by workspace id (AGL-4031).\n *\n * First the account the sender's address signs in with, in any pool or as a\n * confirmed account address, trying the address's tiers in order\n * ({@link siteCareSenderCandidates}); then the workspaces that account is a\n * member of with Site Care in force. When that places the sender nowhere,\n * the rosters of the workspaces that bought Site Care are read for the\n * sender's mailbox ({@link siteCareRosterMatches}).\n *\n * All of them, not the first: which one a message is filed on, when there\n * are several, is the caller's choice.\n */\nexport async function findSiteCareWorkspacesForSender(\n firestore: FirebaseFirestore.Firestore,\n findAccount: SiteCareAccountLookup,\n sender: string,\n): Promise<SiteCareSenderMatch[]> {\n const email = emailAddressOf(sender)\n if (!email) return []\n let uids: string[] = []\n let foundAtTier = -1\n for (const [index, tier] of siteCareSenderCandidates(email).entries()) {\n const found = await Promise.all(tier.map((address) => findAccount(address).catch(() => null)))\n uids = [...new Set(found.filter((user): user is { uid: string } => Boolean(user)).map((user) => user.uid))]\n if (uids.length) {\n foundAtTier = index\n break\n }\n }\n const matches: SiteCareSenderMatch[] = []\n for (const uid of uids) {\n const memberships = await firestore.collection('users').doc(uid).collection('orgs').limit(25).get()\n for (const orgId of memberships.docs.map((doc) => doc.id).sort()) {\n if (matches.some((match) => match.orgId === orgId)) continue\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(uid).get()\n if (!member.exists) continue\n const org = await readSiteCareOrg(firestore, orgId)\n if (org && orgHasSiteCare(org)) matches.push({ orgId, org, uid, email })\n }\n }\n if (matches.length) return matches.sort((a, b) => (a.orgId < b.orgId ? -1 : a.orgId > b.orgId ? 1 : 0))\n return siteCareRosterMatches(firestore, email, foundAtTier === 0)\n}\n\n/**\n * The Site Care workspace a sender's new request is filed on: the first of\n * {@link findSiteCareWorkspacesForSender}'s, by workspace id, so the choice\n * is stable. A sender in several Site Care workspaces files on the lowest\n * id, with every candidate recorded for staff, who move the request when it\n * belongs to another (AGL-4031, `moveSiteCareRequest`).\n */\nexport async function findSiteCareWorkspaceForSender(\n firestore: FirebaseFirestore.Firestore,\n findAccount: SiteCareAccountLookup,\n sender: string,\n): Promise<SiteCareSenderMatch | null> {\n return (await findSiteCareWorkspacesForSender(firestore, findAccount, sender))[0] ?? null\n}\n\n/** The words of a message, above any quoted history. */\nexport function siteCareMessageBody(message: Pick<ReceivedEmail, 'text' | 'html'>): string {\n const plain = (message.text?.trim() ? message.text : htmlToPlainText(message.html)).replace(/\\r\\n?/g, '\\n')\n return stripQuotedHistory(plain).trim()\n}\n\n/** Why a message was acknowledged and left alone. */\nexport type SiteCareIgnoredReason =\n /** No workspace with Site Care has the sender as a member: ordinary support mail. */\n | 'not-a-member'\n /** The platform's own address wrote it. */\n | 'ours'\n /** Its headers say a machine sent it. */\n | 'automatic'\n /** A member wrote, but said nothing. */\n | 'empty'\n\nexport type SiteCareInboundOutcome =\n | { outcome: 'opened'; requestId: string }\n | { outcome: 'replied'; requestId: string }\n | { outcome: 'ignored'; reason: SiteCareIgnoredReason }\n\n/**\n * Files one received message addressed to the support address or to a\n * request's reply address. Nothing is ever sent back to a sender it does\n * not file for: a message to the support address is still in the support\n * inbox, answered there like any other.\n */\nexport async function fileSiteCareInboundEmail(\n firestore: FirebaseFirestore.Firestore,\n input: {\n target: SiteCareInboundTarget\n message: ReceivedEmail\n /** The platform's own addresses; this deployment's by default. */\n addresses?: SiteCareInboundAddresses\n /** The seam a spec replaces; every auth pool by default. */\n findAccount?: SiteCareAccountLookup\n },\n deps: SiteCareDeps = {},\n): Promise<SiteCareInboundOutcome> {\n const { message } = input\n const machine = siteCareMachineMail(message, input.addresses ?? siteCareInboundAddresses())\n if (machine) return { outcome: 'ignored', reason: machine }\n const body = siteCareMessageBody(message)\n const sender = emailAddressOf(message.from)\n const findAccount = input.findAccount ?? findSiteCareAccount\n const matches = sender ? await findSiteCareWorkspacesForSender(firestore, findAccount, sender) : []\n // A new request files on the first workspace by id (see\n // findSiteCareWorkspaceForSender); every candidate is recorded with it.\n const match = matches[0] ?? null\n if (input.target.kind === 'reply' && match) {\n const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get()\n const orgId = String(ticket.get('orgId') ?? '')\n // Only a member of the request's own workspace may add to it.\n let author: string | null = null\n for (const uid of orgId ? [...new Set(matches.map((each) => each.uid))] : []) {\n if ((await firestore.collection('orgs').doc(orgId).collection('members').doc(uid).get()).exists) {\n author = uid\n break\n }\n }\n if (ticket.exists && author) {\n if (!body) return { outcome: 'ignored', reason: 'empty' }\n await appendSiteCareReply(\n firestore,\n {\n ticketId: ticket.id,\n from: { uid: author, email: match.email },\n body,\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'replied', requestId: ticket.id }\n }\n // A reply that cannot join its request is read as a new one below.\n }\n if (!match) return { outcome: 'ignored', reason: 'not-a-member' }\n if (!body && !threadSubject(message.subject)) return { outcome: 'ignored', reason: 'empty' }\n const opened = await openSiteCareRequest(\n firestore,\n {\n orgId: match.orgId,\n org: match.org,\n hostId: null,\n subject: threadSubject(message.subject) || body.split('\\n')[0].slice(0, 150) || 'A change by email',\n body: body || threadSubject(message.subject),\n requester: { uid: match.uid, email: match.email },\n source: 'email',\n dedupeKey: message.messageId || message.id,\n candidates: matches.map((each) => ({\n orgId: each.orgId,\n name: String(each.org['name'] ?? '') || each.orgId,\n uid: each.uid,\n })),\n },\n deps,\n )\n return { outcome: 'opened', requestId: opened.ticketId }\n}\n"],"names":["inboundMailDomain","emailAddressOf","htmlToPlainText","stripQuotedHistory","threadSubject","MEMBER_EMAIL_ALIASES_COLLECTION","memberAddressRoster","SITE_CARE_INBOUND_LOCAL_PART","siteCareSupportAddress","getEmailConfig","appendSiteCareReply","openSiteCareRequest","orgHasSiteCare","readSiteCareOrg","findAccountByVerifiedAlias","findUserByEmailAcrossPools","siteCareInboundAddresses","domain","supportEmail","platformSender","from","siteCareInboundTarget","recipients","addresses","toLowerCase","support","found","value","address","kind","raw","String","trim","written","exec","at","lastIndexOf","slice","local","prefix","startsWith","requestId","length","test","siteCareMachineMail","message","sender","own","map","includes","autoSubmitted","findSiteCareAccount","email","catch","uid","record","alias","GMAIL_DOMAINS","splitAddress","untagged","plus","indexOf","gmailMailbox","replace","siteCareSenderCandidates","seen","Set","tiers","tier","values","fresh","filter","has","forEach","add","push","dotless","flatMap","gmail","siteCareAddressMatches","memberAddress","member","a","b","siteCareRosterMember","roster","options","bySignIn","exact","matches","exactOnly","Boolean","find","byAlias","verifiedAliases","some","SITE_CARE_ROSTER_SCAN_MAX","siteCareRosterMatches","firestore","bought","collection","where","limit","get","orgId","docs","doc","id","sort","orgRef","members","aliases","Promise","all","rows","data","$id","Map","org","findSiteCareWorkspacesForSender","findAccount","uids","foundAtTier","index","entries","user","memberships","match","exists","findSiteCareWorkspaceForSender","siteCareMessageBody","plain","text","html","fileSiteCareInboundEmail","input","deps","machine","outcome","reason","body","target","ticket","author","each","ticketId","dedupeKey","messageId","subject","opened","hostId","split","requester","source","candidates","name"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,cAAc,EACdC,eAAe,EACfC,kBAAkB,EAClBC,aAAa,QACR,oCAAmC;AAC1C,SACEC,+BAA+B,EAC/BC,mBAAmB,QAGd,8CAA6C;AACpD,SAASC,4BAA4B,EAAEC,sBAAsB,QAAQ,mCAAkC;AACvG,SAASC,cAAc,QAA4B,2BAA0B;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,cAAc,EACdC,eAAe,QAEV,0BAAsB;AAC7B,SAASC,0BAA0B,QAAQ,sBAAkB;AAC7D,SAASC,0BAA0B,QAAQ,kBAAc;AA4CzD,uEAAuE,GACvE,OAAO,SAASC;IACd,OAAO;QACLC,QAAQjB;QACRkB,cAAcjB,eAAeO;QAC7BW,gBAAgBlB,eAAeQ,iBAAiBW,IAAI;IACtD;AACF;AAEA,gEAAgE,GAChE,OAAO,SAASC,sBACdC,UAA6B,EAC7BC,SAAoE;IAEpE,MAAMN,SAASM,UAAUN,MAAM,CAACO,WAAW;IAC3C,MAAMC,UAAUxB,eAAesB,UAAUL,YAAY;IACrD,IAAIQ,QAAsC;IAC1C,KAAK,MAAMC,SAASL,WAAY;;YAWb;QAVjB,uEAAuE;QACvE,sEAAsE;QACtE,yEAAyE;QACzE,MAAMM,UAAU3B,eAAe0B;QAC/B,IAAI,CAACC,SAAS;QACd,IAAIH,WAAWG,YAAYH,SAAS;YAClCC,QAAQA,gBAAAA,QAAS;gBAAEG,MAAM;YAAM;YAC/B;QACF;QACA,MAAMC,MAAMC,OAAOJ,gBAAAA,QAAS,IAAIK,IAAI;QACpC,MAAMC,UAAU,UAAC,QAAA,iBAAiBC,IAAI,CAACJ,yBAAtB,KAA4B,CAAC,EAAE,mBAAIA,KAAKE,IAAI;QAC7D,MAAMG,KAAKF,QAAQG,WAAW,CAAC;QAC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|
* `failed` one still owing hours;
|
|
37
37
|
* - an item somebody edited in the Stripe dashboard: amount, quantity or
|
|
38
38
|
* description that no longer match the request.
|
|
39
|
+
*
|
|
40
|
+
* ## And against our own ledger (AGL-4031)
|
|
41
|
+
*
|
|
42
|
+
* Comparing a charge with Stripe proves the two copies agree; it cannot
|
|
43
|
+
* prove either is right. So every closed request is also checked against
|
|
44
|
+
* the facts its charge is derived from — the minutes logged, how they were
|
|
45
|
+
* counted against the included hour, the owner's recorded approval — by the
|
|
46
|
+
* same arithmetic the close uses (`allocateSiteCareMinutes`'s counting and
|
|
47
|
+
* `siteCareCloseVerdict`): $79 per STARTED hour of over-time, whole hours,
|
|
48
|
+
* never below the hours approved, nothing without an approval unless it was
|
|
49
|
+
* absorbed. A request, a charge, a Stripe item or a month total that does
|
|
50
|
+
* not come to that number is a finding, whichever side it is on.
|
|
39
51
|
*/
|
|
40
|
-
export type SiteCareFindingCode = 'charge-stuck' | 'charge-failed' | 'item-missing' | 'item-mismatch' | 'item-not-voided' | 'item-without-row' | 'hours-mismatch' | 'month-total' | 'no-customer' | SiteCareProjectFindingCode;
|
|
52
|
+
export type SiteCareFindingCode = 'charge-stuck' | 'charge-failed' | 'item-missing' | 'item-mismatch' | 'item-not-voided' | 'item-without-row' | 'hours-mismatch' | 'month-total' | 'no-customer' | 'ledger-minutes' | 'ledger-unapproved' | 'ledger-hours' | 'ledger-amount' | 'month-ledger' | SiteCareProjectFindingCode;
|
|
41
53
|
export interface SiteCareFinding {
|
|
42
54
|
orgId: string;
|
|
43
55
|
month: string;
|
|
@@ -61,7 +73,27 @@ interface RequestRow {
|
|
|
61
73
|
subject: string;
|
|
62
74
|
request: SiteCareRequest;
|
|
63
75
|
}
|
|
64
|
-
/**
|
|
76
|
+
/**
|
|
77
|
+
* The whole hours a closed request should bill, from its own minutes and
|
|
78
|
+
* approval: the close's verdict, re-run. `null` when no approval covers the
|
|
79
|
+
* over-time and it was not absorbed — nothing may bill, and the request
|
|
80
|
+
* should not have closed that way.
|
|
81
|
+
*/
|
|
82
|
+
export declare function siteCareLedgerHours(request: SiteCareRequest): number | null;
|
|
83
|
+
/**
|
|
84
|
+
* One workspace's closed requests against their own ledger. Pure, and needs
|
|
85
|
+
* no Stripe: a workspace whose charges cannot be listed is still checked.
|
|
86
|
+
*/
|
|
87
|
+
export declare function compareSiteCareLedger(input: {
|
|
88
|
+
orgId: string;
|
|
89
|
+
requests: readonly RequestRow[];
|
|
90
|
+
/** Goodwill minutes per month, from the month documents; 0 when absent. */
|
|
91
|
+
goodwillByMonth?: ReadonlyMap<string, number>;
|
|
92
|
+
}): SiteCareFinding[];
|
|
93
|
+
/**
|
|
94
|
+
* Compares one workspace's requests with its Stripe items, and with their
|
|
95
|
+
* own ledger ({@link compareSiteCareLedger}). Pure.
|
|
96
|
+
*/
|
|
65
97
|
export declare function compareSiteCareCharges(input: {
|
|
66
98
|
orgId: string;
|
|
67
99
|
requests: readonly RequestRow[];
|
|
@@ -71,6 +103,8 @@ export declare function compareSiteCareCharges(input: {
|
|
|
71
103
|
deleted: boolean;
|
|
72
104
|
item: StripeExtraTimeItem | null;
|
|
73
105
|
}>;
|
|
106
|
+
/** Goodwill minutes per month, from the month documents; 0 when absent. */
|
|
107
|
+
goodwillByMonth?: ReadonlyMap<string, number>;
|
|
74
108
|
}): SiteCareFinding[];
|
|
75
109
|
/** Runs the check over the current and previous month. */
|
|
76
110
|
export declare function reconcileSiteCare(firestore: FirebaseFirestore.Firestore, input: {
|