@aglyn/tenant-data-admin 1.8.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/server/api-http.js +2 -1
- package/src/lib/server/api-http.js.map +1 -1
- package/src/lib/server/billing-addons.d.ts +19 -47
- package/src/lib/server/billing-addons.js +41 -85
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +3 -5
- package/src/lib/server/bundle-links.js +4 -5
- package/src/lib/server/bundle-links.js.map +1 -1
- package/src/lib/server/email-metering.d.ts +12 -4
- package/src/lib/server/email-metering.js +12 -4
- package/src/lib/server/email-metering.js.map +1 -1
- package/src/lib/server/email-transactional-ceiling.d.ts +122 -0
- package/src/lib/server/email-transactional-ceiling.js +244 -0
- package/src/lib/server/email-transactional-ceiling.js.map +1 -0
- package/src/lib/server/org-billing.d.ts +2 -4
- package/src/lib/server/org-billing.js +0 -5
- package/src/lib/server/org-billing.js.map +1 -1
- package/src/lib/server/sending-domains.d.ts +1 -0
- package/src/lib/server/sending-domains.js +13 -1
- package/src/lib/server/sending-domains.js.map +1 -1
- package/src/lib/server/upgrade-proposal.d.ts +3 -2
- package/src/lib/server/upgrade-proposal.js +3 -0
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/lib/server/upsert-contact.js +10 -4
- package/src/lib/server/upsert-contact.js.map +1 -1
- package/src/tenancy.d.ts +1 -0
- package/src/tenancy.js +5 -0
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1,244 @@
|
|
|
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
|
+
*/ /**
|
|
18
|
+
* The durable half of the daily transactional ceiling (AGL-4145): the
|
|
19
|
+
* counter a site's non-campaign mail is claimed against, and the record a
|
|
20
|
+
* refusal leaves for staff.
|
|
21
|
+
*
|
|
22
|
+
* Which messages are governed, and what the send seam does with a refusal,
|
|
23
|
+
* is `transactional-send-ceiling.ts` in `@aglyn/shared-util-email`. The
|
|
24
|
+
* figures are `transactional-email-ceiling.ts` in `@aglyn/aglyn`, and the one
|
|
25
|
+
* for a workspace is stamped on its sending identity by `hostSendingIdentity`
|
|
26
|
+
* from the org document it already read, so the count below is the only
|
|
27
|
+
* thing this costs a send.
|
|
28
|
+
*
|
|
29
|
+
* ## The counter
|
|
30
|
+
*
|
|
31
|
+
* `orgs/{orgId}/counters/transactionalEmailSends`, one field per UTC day
|
|
32
|
+
* (`YYYY-MM-DD`) holding a count — the shape `campaignEmailSends` beside it
|
|
33
|
+
* has per month, and ORG-scoped for the reason that one became org-scoped in
|
|
34
|
+
* AGL-2267: the ceiling is the organization's, and a per-site count would
|
|
35
|
+
* hand an org with N sites N ceilings. Each day is its own field, so the
|
|
36
|
+
* ceiling starts again at 00:00 UTC with nobody doing anything.
|
|
37
|
+
*
|
|
38
|
+
* It is the CEILING's count, not the cost meter. `emailSends` still counts
|
|
39
|
+
* every delivered message for COGS through `recordEmailSends`, exactly as
|
|
40
|
+
* before; this counts claims, and a claim whose message did not leave is
|
|
41
|
+
* handed back.
|
|
42
|
+
*
|
|
43
|
+
* ## A claim, not a check
|
|
44
|
+
*
|
|
45
|
+
* The transaction reads the day's figure and writes an ABSOLUTE value
|
|
46
|
+
* derived from that read, the campaign reservation's and the governor's
|
|
47
|
+
* shape: a read-then-increment would let two concurrent sends both pass the
|
|
48
|
+
* last slot. A refused claim writes nothing to the counter.
|
|
49
|
+
*
|
|
50
|
+
* ## A refusal is never silent
|
|
51
|
+
*
|
|
52
|
+
* Every refusal is logged and counted on
|
|
53
|
+
* `orgs/{orgId}/counters/transactionalEmailsRefused` (per day, with the
|
|
54
|
+
* ceiling it met and when) — the counters-document shape the form abuse
|
|
55
|
+
* ceiling's `formSubmissionsRefused` uses. The first refusal of the day
|
|
56
|
+
* raises the `deliverability.transactionalCeilingReached` operator alert,
|
|
57
|
+
* which is the staff console notification, the operator email and the
|
|
58
|
+
* webhook. Nothing goes to the workspace: the ceiling is not something its
|
|
59
|
+
* plan names, and no customer-facing surface changes.
|
|
60
|
+
*
|
|
61
|
+
* ## Fails open
|
|
62
|
+
*
|
|
63
|
+
* A counter that cannot be read or written allows the message, the posture
|
|
64
|
+
* of every control on the send path: an outage on the ceiling must not
|
|
65
|
+
* become an outage on every store's receipts.
|
|
66
|
+
*/ import { setTransactionalSendCeilingGate, transactionalCeilingDayKey, transactionalCeilingResetMs } from "@aglyn/shared-util-email";
|
|
67
|
+
import { checkTransactionalEmailCeiling } from "@aglyn/aglyn/app-utils/transactional-email-ceiling";
|
|
68
|
+
import { firebaseAdmin } from "./firebase-admin.js";
|
|
69
|
+
/** The ceiling's count, per organization per UTC day. */ export const TRANSACTIONAL_EMAIL_SENDS_COUNTER = 'transactionalEmailSends';
|
|
70
|
+
/** Refusals past the ceiling, per organization per UTC day. */ export const TRANSACTIONAL_EMAILS_REFUSED_COUNTER = 'transactionalEmailsRefused';
|
|
71
|
+
/** The operator alert the first refusal of a day raises. */ export const TRANSACTIONAL_CEILING_ALERT_TYPE = 'deliverability.transactionalCeilingReached';
|
|
72
|
+
/** `orgs/{orgId}/counters/{counter}`. */ function orgCounterRef(firestore, orgId, counter) {
|
|
73
|
+
return firestore.collection('orgs').doc(orgId).collection('counters').doc(counter);
|
|
74
|
+
}
|
|
75
|
+
/** A day field off a counter snapshot, clamped like every other counter read. */ function readDayField(snapshot, dayKey) {
|
|
76
|
+
var _ref;
|
|
77
|
+
const used = Number((_ref = (snapshot == null ? void 0 : snapshot.exists) ? snapshot.get(dayKey) : 0) != null ? _ref : 0);
|
|
78
|
+
return Number.isFinite(used) && used > 0 ? Math.floor(used) : 0;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Claims `count` messages against the organization's day, atomically.
|
|
82
|
+
*
|
|
83
|
+
* Allowed: the day's figure is raised by `count` and the claim comes back to
|
|
84
|
+
* be released if the message does not leave. Refused: nothing is written to
|
|
85
|
+
* the counter and `retryAtMs` is the next UTC midnight. The refusal's record
|
|
86
|
+
* is {@link recordTransactionalCeilingRefusal}, which the send seam asks for
|
|
87
|
+
* separately, outside the time budget it gives this claim.
|
|
88
|
+
*/ export async function claimTransactionalEmailSends(request) {
|
|
89
|
+
var _request_orgId;
|
|
90
|
+
const orgId = String((_request_orgId = request.orgId) != null ? _request_orgId : '').trim();
|
|
91
|
+
const nowMs = Number.isFinite(request.nowMs) ? request.nowMs : Date.now();
|
|
92
|
+
const count = Math.max(1, Math.floor(Number(request.count) || 0));
|
|
93
|
+
if (!orgId) return {
|
|
94
|
+
allowed: true,
|
|
95
|
+
claim: null
|
|
96
|
+
};
|
|
97
|
+
const dayKey = transactionalCeilingDayKey(nowMs);
|
|
98
|
+
try {
|
|
99
|
+
var _request_firestore;
|
|
100
|
+
const db = (_request_firestore = request.firestore) != null ? _request_firestore : firebaseAdmin.app().firestore();
|
|
101
|
+
const ref = orgCounterRef(db, orgId, TRANSACTIONAL_EMAIL_SENDS_COUNTER);
|
|
102
|
+
const verdict = await db.runTransaction(async (tx)=>{
|
|
103
|
+
const snapshot = await tx.get(ref);
|
|
104
|
+
const used = readDayField(snapshot, dayKey);
|
|
105
|
+
const decision = checkTransactionalEmailCeiling(used, count, request.ceiling);
|
|
106
|
+
if (decision.allowed) {
|
|
107
|
+
tx.set(ref, {
|
|
108
|
+
[dayKey]: used + count
|
|
109
|
+
}, {
|
|
110
|
+
merge: true
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
return decision;
|
|
114
|
+
});
|
|
115
|
+
if (verdict.allowed) {
|
|
116
|
+
return {
|
|
117
|
+
allowed: true,
|
|
118
|
+
ceiling: verdict.ceiling,
|
|
119
|
+
used: verdict.used,
|
|
120
|
+
claim: {
|
|
121
|
+
orgId,
|
|
122
|
+
dayKey,
|
|
123
|
+
count
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
allowed: false,
|
|
129
|
+
ceiling: verdict.ceiling,
|
|
130
|
+
used: verdict.used,
|
|
131
|
+
retryAtMs: transactionalCeilingResetMs(nowMs)
|
|
132
|
+
};
|
|
133
|
+
} catch (error) {
|
|
134
|
+
console.error('[transactional-ceiling] counter unavailable — allowing', error);
|
|
135
|
+
return {
|
|
136
|
+
allowed: true,
|
|
137
|
+
claim: null
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Gives back a claim whose message did not leave. Also a transaction, and
|
|
143
|
+
* also an absolute write from its own read, so a release computed from a
|
|
144
|
+
* stale figure cannot undo a claim another send took in the meantime. Never
|
|
145
|
+
* drives the day below zero and never throws: the cost of a failed release
|
|
146
|
+
* is a day counted a little high, which is the safe direction.
|
|
147
|
+
*/ export async function releaseTransactionalEmailSends(claim, firestore) {
|
|
148
|
+
var _ref;
|
|
149
|
+
const orgId = String((_ref = claim == null ? void 0 : claim.orgId) != null ? _ref : '').trim();
|
|
150
|
+
const count = Math.max(0, Math.floor(Number(claim == null ? void 0 : claim.count) || 0));
|
|
151
|
+
if (!orgId || !(claim == null ? void 0 : claim.dayKey) || count <= 0) return;
|
|
152
|
+
try {
|
|
153
|
+
const db = firestore != null ? firestore : firebaseAdmin.app().firestore();
|
|
154
|
+
const ref = orgCounterRef(db, orgId, TRANSACTIONAL_EMAIL_SENDS_COUNTER);
|
|
155
|
+
await db.runTransaction(async (tx)=>{
|
|
156
|
+
const snapshot = await tx.get(ref);
|
|
157
|
+
const used = readDayField(snapshot, claim.dayKey);
|
|
158
|
+
tx.set(ref, {
|
|
159
|
+
[claim.dayKey]: Math.max(0, used - count)
|
|
160
|
+
}, {
|
|
161
|
+
merge: true
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
} catch (error) {
|
|
165
|
+
console.error('[transactional-ceiling] release failed', error);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Makes a refusal observable: a log line, the day's refusal count, and — on
|
|
170
|
+
* the first refusal of the day only — the operator alert. An alert per
|
|
171
|
+
* refused message would be the flood again, delivered to staff.
|
|
172
|
+
*
|
|
173
|
+
* Best-effort throughout, like the form ceiling's bookkeeping: a failure here
|
|
174
|
+
* must not turn a contained refusal into a send failure of another kind.
|
|
175
|
+
*/ export async function recordTransactionalCeilingRefusal(input) {
|
|
176
|
+
var _input_context;
|
|
177
|
+
console.warn(`[transactional-ceiling] refused ${input.count} message(s) for workspace ` + `${input.orgId}${input.hostId ? ` (site ${input.hostId})` : ''} from ` + `${(_input_context = input.context) != null ? _input_context : 'an unnamed sender'}: ${input.used}/${input.ceiling} ` + `on ${input.dayKey}`);
|
|
178
|
+
try {
|
|
179
|
+
var _input_firestore, _input_context1, _input_context2;
|
|
180
|
+
const db = (_input_firestore = input.firestore) != null ? _input_firestore : firebaseAdmin.app().firestore();
|
|
181
|
+
const refusedRef = orgCounterRef(db, input.orgId, TRANSACTIONAL_EMAILS_REFUSED_COUNTER);
|
|
182
|
+
const before = readDayField(await refusedRef.get(), input.dayKey);
|
|
183
|
+
await refusedRef.set({
|
|
184
|
+
[input.dayKey]: firebaseAdmin.firestore.FieldValue.increment(input.count),
|
|
185
|
+
// Explicit values only — Firestore rejects `undefined`.
|
|
186
|
+
ceiling: input.ceiling,
|
|
187
|
+
lastRefusedAtMs: input.nowMs,
|
|
188
|
+
lastContext: (_input_context1 = input.context) != null ? _input_context1 : ''
|
|
189
|
+
}, {
|
|
190
|
+
merge: true
|
|
191
|
+
});
|
|
192
|
+
if (before > 0) return;
|
|
193
|
+
const orgSnapshot = await db.collection('orgs').doc(input.orgId).get().catch(()=>null);
|
|
194
|
+
const name = (orgSnapshot == null ? void 0 : orgSnapshot.exists) ? orgSnapshot.get('name') : null;
|
|
195
|
+
const orgName = typeof name === 'string' && name.trim() ? name.trim() : input.orgId;
|
|
196
|
+
const { raiseOperatorAlert } = await import("./operator-alerts.js");
|
|
197
|
+
await raiseOperatorAlert(TRANSACTIONAL_CEILING_ALERT_TYPE, _extends({
|
|
198
|
+
dedupeKey: `${input.orgId}:${input.dayKey}`,
|
|
199
|
+
orgId: input.orgId
|
|
200
|
+
}, input.hostId ? {
|
|
201
|
+
hostId: input.hostId
|
|
202
|
+
} : {}, {
|
|
203
|
+
context: {
|
|
204
|
+
orgId: input.orgId,
|
|
205
|
+
orgName,
|
|
206
|
+
used: input.used.toLocaleString('en-US'),
|
|
207
|
+
ceiling: input.ceiling.toLocaleString('en-US'),
|
|
208
|
+
context: (_input_context2 = input.context) != null ? _input_context2 : 'an unnamed sender'
|
|
209
|
+
}
|
|
210
|
+
}));
|
|
211
|
+
} catch (error) {
|
|
212
|
+
console.error('[transactional-ceiling] refusal bookkeeping failed', error);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Puts the durable ceiling on `sendEmail`'s path.
|
|
217
|
+
*
|
|
218
|
+
* Called at module load, from the bottom of this file, for the reason the
|
|
219
|
+
* governor's installer is: every server surface imports the
|
|
220
|
+
* `@aglyn/tenant-data-admin` barrel, so importing it is enough, and there is
|
|
221
|
+
* no installer for an entrypoint to forget. Idempotent; the state is the
|
|
222
|
+
* Firestore document.
|
|
223
|
+
*/ export function installTransactionalSendCeiling() {
|
|
224
|
+
setTransactionalSendCeilingGate({
|
|
225
|
+
claim: (request)=>claimTransactionalEmailSends(request),
|
|
226
|
+
release: (claim)=>releaseTransactionalEmailSends(claim),
|
|
227
|
+
refused: (request, verdict)=>{
|
|
228
|
+
var _request_hostId, _verdict_used, _verdict_ceiling, _request_context;
|
|
229
|
+
return recordTransactionalCeilingRefusal({
|
|
230
|
+
orgId: request.orgId,
|
|
231
|
+
hostId: (_request_hostId = request.hostId) != null ? _request_hostId : null,
|
|
232
|
+
dayKey: transactionalCeilingDayKey(request.nowMs),
|
|
233
|
+
count: Math.max(1, Math.floor(Number(request.count) || 0)),
|
|
234
|
+
used: Number((_verdict_used = verdict.used) != null ? _verdict_used : 0),
|
|
235
|
+
ceiling: Number((_verdict_ceiling = verdict.ceiling) != null ? _verdict_ceiling : request.ceiling),
|
|
236
|
+
context: (_request_context = request.context) != null ? _request_context : null,
|
|
237
|
+
nowMs: request.nowMs
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
installTransactionalSendCeiling();
|
|
243
|
+
|
|
244
|
+
//# sourceMappingURL=email-transactional-ceiling.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-transactional-ceiling.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The durable half of the daily transactional ceiling (AGL-4145): the\n * counter a site's non-campaign mail is claimed against, and the record a\n * refusal leaves for staff.\n *\n * Which messages are governed, and what the send seam does with a refusal,\n * is `transactional-send-ceiling.ts` in `@aglyn/shared-util-email`. The\n * figures are `transactional-email-ceiling.ts` in `@aglyn/aglyn`, and the one\n * for a workspace is stamped on its sending identity by `hostSendingIdentity`\n * from the org document it already read, so the count below is the only\n * thing this costs a send.\n *\n * ## The counter\n *\n * `orgs/{orgId}/counters/transactionalEmailSends`, one field per UTC day\n * (`YYYY-MM-DD`) holding a count — the shape `campaignEmailSends` beside it\n * has per month, and ORG-scoped for the reason that one became org-scoped in\n * AGL-2267: the ceiling is the organization's, and a per-site count would\n * hand an org with N sites N ceilings. Each day is its own field, so the\n * ceiling starts again at 00:00 UTC with nobody doing anything.\n *\n * It is the CEILING's count, not the cost meter. `emailSends` still counts\n * every delivered message for COGS through `recordEmailSends`, exactly as\n * before; this counts claims, and a claim whose message did not leave is\n * handed back.\n *\n * ## A claim, not a check\n *\n * The transaction reads the day's figure and writes an ABSOLUTE value\n * derived from that read, the campaign reservation's and the governor's\n * shape: a read-then-increment would let two concurrent sends both pass the\n * last slot. A refused claim writes nothing to the counter.\n *\n * ## A refusal is never silent\n *\n * Every refusal is logged and counted on\n * `orgs/{orgId}/counters/transactionalEmailsRefused` (per day, with the\n * ceiling it met and when) — the counters-document shape the form abuse\n * ceiling's `formSubmissionsRefused` uses. The first refusal of the day\n * raises the `deliverability.transactionalCeilingReached` operator alert,\n * which is the staff console notification, the operator email and the\n * webhook. Nothing goes to the workspace: the ceiling is not something its\n * plan names, and no customer-facing surface changes.\n *\n * ## Fails open\n *\n * A counter that cannot be read or written allows the message, the posture\n * of every control on the send path: an outage on the ceiling must not\n * become an outage on every store's receipts.\n */\n\nimport {\n setTransactionalSendCeilingGate,\n transactionalCeilingDayKey,\n transactionalCeilingResetMs,\n type TransactionalSendCeilingClaim,\n type TransactionalSendCeilingRequest,\n type TransactionalSendCeilingVerdict,\n} from '@aglyn/shared-util-email'\nimport { checkTransactionalEmailCeiling } from '@aglyn/aglyn/app-utils/transactional-email-ceiling'\nimport { firebaseAdmin } from './firebase-admin'\n\n/** The ceiling's count, per organization per UTC day. */\nexport const TRANSACTIONAL_EMAIL_SENDS_COUNTER = 'transactionalEmailSends'\n\n/** Refusals past the ceiling, per organization per UTC day. */\nexport const TRANSACTIONAL_EMAILS_REFUSED_COUNTER = 'transactionalEmailsRefused'\n\n/** The operator alert the first refusal of a day raises. */\nexport const TRANSACTIONAL_CEILING_ALERT_TYPE = 'deliverability.transactionalCeilingReached'\n\n/** `orgs/{orgId}/counters/{counter}`. */\nfunction orgCounterRef(firestore: any, orgId: string, counter: string): any {\n return firestore.collection('orgs').doc(orgId).collection('counters').doc(counter)\n}\n\n/** A day field off a counter snapshot, clamped like every other counter read. */\nfunction readDayField(snapshot: any, dayKey: string): number {\n const used = Number((snapshot?.exists ? snapshot.get(dayKey) : 0) ?? 0)\n return Number.isFinite(used) && used > 0 ? Math.floor(used) : 0\n}\n\n/**\n * Claims `count` messages against the organization's day, atomically.\n *\n * Allowed: the day's figure is raised by `count` and the claim comes back to\n * be released if the message does not leave. Refused: nothing is written to\n * the counter and `retryAtMs` is the next UTC midnight. The refusal's record\n * is {@link recordTransactionalCeilingRefusal}, which the send seam asks for\n * separately, outside the time budget it gives this claim.\n */\nexport async function claimTransactionalEmailSends(\n request: TransactionalSendCeilingRequest & { firestore?: any },\n): Promise<TransactionalSendCeilingVerdict> {\n const orgId = String(request.orgId ?? '').trim()\n const nowMs = Number.isFinite(request.nowMs) ? request.nowMs : Date.now()\n const count = Math.max(1, Math.floor(Number(request.count) || 0))\n if (!orgId) return { allowed: true, claim: null }\n const dayKey = transactionalCeilingDayKey(nowMs)\n try {\n const db = request.firestore ?? firebaseAdmin.app().firestore()\n const ref = orgCounterRef(db, orgId, TRANSACTIONAL_EMAIL_SENDS_COUNTER)\n const verdict = await db.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = readDayField(snapshot, dayKey)\n const decision = checkTransactionalEmailCeiling(used, count, request.ceiling)\n if (decision.allowed) {\n tx.set(ref, { [dayKey]: used + count }, { merge: true })\n }\n return decision\n })\n if (verdict.allowed) {\n return {\n allowed: true,\n ceiling: verdict.ceiling,\n used: verdict.used,\n claim: { orgId, dayKey, count },\n }\n }\n return {\n allowed: false,\n ceiling: verdict.ceiling,\n used: verdict.used,\n retryAtMs: transactionalCeilingResetMs(nowMs),\n }\n } catch (error) {\n console.error('[transactional-ceiling] counter unavailable — allowing', error)\n return { allowed: true, claim: null }\n }\n}\n\n/**\n * Gives back a claim whose message did not leave. Also a transaction, and\n * also an absolute write from its own read, so a release computed from a\n * stale figure cannot undo a claim another send took in the meantime. Never\n * drives the day below zero and never throws: the cost of a failed release\n * is a day counted a little high, which is the safe direction.\n */\nexport async function releaseTransactionalEmailSends(\n claim: TransactionalSendCeilingClaim | null | undefined,\n firestore?: any,\n): Promise<void> {\n const orgId = String(claim?.orgId ?? '').trim()\n const count = Math.max(0, Math.floor(Number(claim?.count) || 0))\n if (!orgId || !claim?.dayKey || count <= 0) return\n try {\n const db = firestore ?? firebaseAdmin.app().firestore()\n const ref = orgCounterRef(db, orgId, TRANSACTIONAL_EMAIL_SENDS_COUNTER)\n await db.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = readDayField(snapshot, claim.dayKey)\n tx.set(ref, { [claim.dayKey]: Math.max(0, used - count) }, { merge: true })\n })\n } catch (error) {\n console.error('[transactional-ceiling] release failed', error)\n }\n}\n\n/**\n * Makes a refusal observable: a log line, the day's refusal count, and — on\n * the first refusal of the day only — the operator alert. An alert per\n * refused message would be the flood again, delivered to staff.\n *\n * Best-effort throughout, like the form ceiling's bookkeeping: a failure here\n * must not turn a contained refusal into a send failure of another kind.\n */\nexport async function recordTransactionalCeilingRefusal(input: {\n orgId: string\n hostId: string | null\n dayKey: string\n count: number\n used: number\n ceiling: number\n context: string | null\n nowMs: number\n firestore?: any\n}): Promise<void> {\n console.warn(\n `[transactional-ceiling] refused ${input.count} message(s) for workspace ` +\n `${input.orgId}${input.hostId ? ` (site ${input.hostId})` : ''} from ` +\n `${input.context ?? 'an unnamed sender'}: ${input.used}/${input.ceiling} ` +\n `on ${input.dayKey}`,\n )\n try {\n const db = input.firestore ?? firebaseAdmin.app().firestore()\n const refusedRef = orgCounterRef(db, input.orgId, TRANSACTIONAL_EMAILS_REFUSED_COUNTER)\n const before = readDayField(await refusedRef.get(), input.dayKey)\n await refusedRef.set(\n {\n [input.dayKey]: firebaseAdmin.firestore.FieldValue.increment(input.count),\n // Explicit values only — Firestore rejects `undefined`.\n ceiling: input.ceiling,\n lastRefusedAtMs: input.nowMs,\n lastContext: input.context ?? '',\n },\n { merge: true },\n )\n if (before > 0) return\n const orgSnapshot = await db\n .collection('orgs')\n .doc(input.orgId)\n .get()\n .catch(() => null)\n const name = orgSnapshot?.exists ? orgSnapshot.get('name') : null\n const orgName = typeof name === 'string' && name.trim() ? name.trim() : input.orgId\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(TRANSACTIONAL_CEILING_ALERT_TYPE, {\n dedupeKey: `${input.orgId}:${input.dayKey}`,\n orgId: input.orgId,\n ...(input.hostId ? { hostId: input.hostId } : {}),\n context: {\n orgId: input.orgId,\n orgName,\n used: input.used.toLocaleString('en-US'),\n ceiling: input.ceiling.toLocaleString('en-US'),\n context: input.context ?? 'an unnamed sender',\n },\n })\n } catch (error) {\n console.error('[transactional-ceiling] refusal bookkeeping failed', error)\n }\n}\n\n/**\n * Puts the durable ceiling on `sendEmail`'s path.\n *\n * Called at module load, from the bottom of this file, for the reason the\n * governor's installer is: every server surface imports the\n * `@aglyn/tenant-data-admin` barrel, so importing it is enough, and there is\n * no installer for an entrypoint to forget. Idempotent; the state is the\n * Firestore document.\n */\nexport function installTransactionalSendCeiling(): void {\n setTransactionalSendCeilingGate({\n claim: (request) => claimTransactionalEmailSends(request),\n release: (claim) => releaseTransactionalEmailSends(claim),\n refused: (request, verdict) =>\n recordTransactionalCeilingRefusal({\n orgId: request.orgId,\n hostId: request.hostId ?? null,\n dayKey: transactionalCeilingDayKey(request.nowMs),\n count: Math.max(1, Math.floor(Number(request.count) || 0)),\n used: Number(verdict.used ?? 0),\n ceiling: Number(verdict.ceiling ?? request.ceiling),\n context: request.context ?? null,\n nowMs: request.nowMs,\n }),\n })\n}\n\ninstallTransactionalSendCeiling()\n"],"names":["setTransactionalSendCeilingGate","transactionalCeilingDayKey","transactionalCeilingResetMs","checkTransactionalEmailCeiling","firebaseAdmin","TRANSACTIONAL_EMAIL_SENDS_COUNTER","TRANSACTIONAL_EMAILS_REFUSED_COUNTER","TRANSACTIONAL_CEILING_ALERT_TYPE","orgCounterRef","firestore","orgId","counter","collection","doc","readDayField","snapshot","dayKey","used","Number","exists","get","isFinite","Math","floor","claimTransactionalEmailSends","request","String","trim","nowMs","Date","now","count","max","allowed","claim","db","app","ref","verdict","runTransaction","tx","decision","ceiling","set","merge","retryAtMs","error","console","releaseTransactionalEmailSends","recordTransactionalCeilingRefusal","input","warn","hostId","context","refusedRef","before","FieldValue","increment","lastRefusedAtMs","lastContext","orgSnapshot","catch","name","orgName","raiseOperatorAlert","dedupeKey","toLocaleString","installTransactionalSendCeiling","release","refused"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiDC,GAED,SACEA,+BAA+B,EAC/BC,0BAA0B,EAC1BC,2BAA2B,QAItB,2BAA0B;AACjC,SAASC,8BAA8B,QAAQ,qDAAoD;AACnG,SAASC,aAAa,QAAQ,sBAAkB;AAEhD,uDAAuD,GACvD,OAAO,MAAMC,oCAAoC,0BAAyB;AAE1E,6DAA6D,GAC7D,OAAO,MAAMC,uCAAuC,6BAA4B;AAEhF,0DAA0D,GAC1D,OAAO,MAAMC,mCAAmC,6CAA4C;AAE5F,uCAAuC,GACvC,SAASC,cAAcC,SAAc,EAAEC,KAAa,EAAEC,OAAe;IACnE,OAAOF,UAAUG,UAAU,CAAC,QAAQC,GAAG,CAACH,OAAOE,UAAU,CAAC,YAAYC,GAAG,CAACF;AAC5E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W,OAAO,GAAE5B,mBAAAA,QAAQ4B,OAAO,YAAf5B,mBAAmB;gBAC5BG,OAAOH,QAAQG,KAAK;YACtB;;IACJ;AACF;AAEAuC"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { hasInlineOrgBilling, type OrgBillingDoc, type OrgInlineBilling
|
|
17
|
+
import { hasInlineOrgBilling, type OrgBillingDoc, type OrgInlineBilling } from '@aglyn/aglyn/server';
|
|
18
18
|
/** `orgs/{orgId}/billing/stripe`. */
|
|
19
19
|
export declare function orgBillingRef(orgId: string): FirebaseFirestore.DocumentReference<FirebaseFirestore.DocumentData, FirebaseFirestore.DocumentData>;
|
|
20
20
|
/**
|
|
@@ -82,9 +82,7 @@ export declare function readOrgBillingCustomerModes(orgId: string): Promise<{
|
|
|
82
82
|
* a doc that no longer exists, and it is the only thing standing between an org
|
|
83
83
|
* the backfill somehow missed and a paying workspace rendering as Free.
|
|
84
84
|
*/
|
|
85
|
-
export declare function writeOrgBilling(orgId: string, patch: Partial<OrgBillingDoc> & Pick<OrgInlineBilling, 'seatAddons'
|
|
86
|
-
aiTier?: AiTierId | null;
|
|
87
|
-
}, options?: {
|
|
85
|
+
export declare function writeOrgBilling(orgId: string, patch: Partial<OrgBillingDoc> & Pick<OrgInlineBilling, 'seatAddons'>, options?: {
|
|
88
86
|
writeInline?: boolean;
|
|
89
87
|
}): Promise<void>;
|
|
90
88
|
/**
|
|
@@ -197,11 +197,6 @@ import { firebaseAdmin } from "./firebase-admin.js";
|
|
|
197
197
|
if (patch.seatAddons !== undefined) {
|
|
198
198
|
orgPatch['seatAddons'] = patch.seatAddons;
|
|
199
199
|
}
|
|
200
|
-
// Which Aglyn AI tier those quantities hold (AGL-3965), derived from the
|
|
201
|
-
// same items and read from the same document, so it travels with them.
|
|
202
|
-
if (patch.aiTier !== undefined) {
|
|
203
|
-
orgPatch['aiTier'] = patch.aiTier;
|
|
204
|
-
}
|
|
205
200
|
if (Object.keys(orgPatch).length) batch.set(orgRef, orgPatch, {
|
|
206
201
|
merge: true
|
|
207
202
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-billing.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 { deploymentLivemode } from '@aglyn/aglyn/app-utils/stripe-deployment-mode'\nimport {\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n STRIPE_CUSTOMER_ID_TEST_FIELD,\n STRIPE_CUSTOMER_INDEX_COLLECTION,\n hasInlineOrgBilling,\n orgBillingStatusFrom,\n pickOrgBillingFields,\n type OrgBillingDoc,\n type OrgInlineBilling,\n type AiTierId,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * Server-side accessors for the manager-gated billing document (AGL-1028).\n *\n * Every server surface that used to read `orgs/{orgId}.stripeCustomerId` /\n * `.subscription` / `.seatAddons` goes through here instead. All of them are\n * Admin SDK, so rules never applied to them — this is a path change, not a\n * permission change. The permission change is entirely in the rules, where the\n * new subcollection is gated on `canManageOrg()`.\n */\n\nconst db = () => firebaseAdmin.app().firestore()\n\n/**\n * Which PHYSICAL field holds this deployment's Stripe customer id (AGL-2486).\n *\n * Live keeps `stripeCustomerId`, so live behaviour is byte-identical to before\n * this existed and no stored document needs migrating. Test mode gets its own\n * slot, which starts empty on every org — the first test-mode checkout mints a\n * fresh test customer instead of sending a live `cus_…` to a `sk_test` key and\n * taking a 502.\n *\n * Read at call time rather than at module load: a spec flips\n * `process.env.STRIPE_SECRET_KEY` between cases, and a cached verdict would\n * make the second case answer for the first.\n */\nfunction customerIdField(): 'stripeCustomerId' | typeof STRIPE_CUSTOMER_ID_TEST_FIELD {\n return deploymentLivemode() ? 'stripeCustomerId' : STRIPE_CUSTOMER_ID_TEST_FIELD\n}\n\n/**\n * Collapse a stored billing document to the logical shape callers expect.\n *\n * `stripeCustomerId` on the RESULT always means \"the customer id for the mode\n * this deployment spends in\". The test id never leaks out under its physical\n * name, and — the part that matters — test mode does NOT fall back to the live\n * id when its own slot is empty. That fallback is precisely the bug: it is what\n * sent `cus_UuQjDdd1oxPMNH` to a `sk_test` key.\n */\nfunction projectBillingMode(doc: OrgBillingDoc): OrgBillingDoc {\n const stored = { ...(doc ?? {}) } as Record<string, unknown>\n const testId = stored[STRIPE_CUSTOMER_ID_TEST_FIELD]\n // The physical twin never reaches a caller in either mode: every reader\n // treats `stripeCustomerId` as THE customer, so a second field carrying a\n // second answer is exactly the ambiguity this fix removes.\n delete stored[STRIPE_CUSTOMER_ID_TEST_FIELD]\n if (deploymentLivemode()) return stored as OrgBillingDoc\n // No `??` fallback to the live id. That fallback IS the bug.\n stored['stripeCustomerId'] = (testId ?? null) as string | null\n return stored as OrgBillingDoc\n}\n\n/** `orgs/{orgId}/billing/stripe`. */\nexport function orgBillingRef(orgId: string) {\n return db()\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_BILLING_SUBCOLLECTION)\n .doc(ORG_BILLING_DOC_ID)\n}\n\n/**\n * Reads an org's commercial keys, falling back to the org doc.\n *\n * The fallback is what makes the migration safe to land in pieces: a reader\n * repointed here keeps working against an org that has not been backfilled\n * yet, and keeps working if the backfill missed one. It stops being reachable\n * only when the inline fields are finally deleted from the org doc — which is\n * the LAST step, taken once production has been observed reading from the new\n * location.\n *\n * Without it, the failure mode is silent and expensive: a missing billing doc\n * reads as `undefined`, which every caller downstream interprets as \"no\n * subscription\", i.e. a paying workspace rendered as Free.\n */\nexport async function readOrgBilling(orgId: string): Promise<OrgBillingDoc> {\n if (!orgId) return {}\n return projectBillingMode(await readStoredOrgBilling(orgId))\n}\n\n/**\n * The STORED document, before any mode projection — both physical ids intact.\n *\n * Private on purpose: a caller holding this holds two answers to \"which\n * customer\", which is the ambiguity `projectBillingMode` exists to remove. It\n * is factored out only so the mode census below reads the very same bytes\n * `readOrgBilling` reads, org-doc fallback included. Two separate reads would\n * be two chances to diverge, and the census exists precisely to explain what\n * `readOrgBilling` returned.\n */\nasync function readStoredOrgBilling(orgId: string): Promise<OrgBillingDoc> {\n const billingSnapshot = await orgBillingRef(orgId).get()\n if (billingSnapshot.exists) {\n return (billingSnapshot.data() ?? {}) as OrgBillingDoc\n }\n const orgSnapshot = await db().collection('orgs').doc(orgId).get()\n // The legacy inline fields predate mode-keying entirely, so anything found\n // there is a LIVE id by construction — the org doc was last written by a\n // `sk_live_` deployment. Projected by the caller all the same, so a\n // test-mode read of an un-backfilled org gets no customer rather than a live\n // one.\n return pickOrgBillingFields(orgSnapshot.data() as never) as OrgBillingDoc\n}\n\n/**\n * Which Stripe MODES this org has a stored customer for (AGL-2486, follow-up).\n *\n * `readOrgBilling` answering `stripeCustomerId: null` has two completely\n * different meanings — \"this workspace has never been billed\" and \"this\n * workspace's customer lives in the other Stripe world and THIS deployment\n * cannot see it\" — and every surface downstream rendered them as the same\n * sentence, \"No invoices yet.\" That is the swallowed-query-as-measured-zero\n * shape: nothing looks wrong, and the wrong reading is the reassuring one.\n *\n * The fix is NOT to fall back to the other mode's id — that fallback is the\n * original bug, and it stays deleted. It is to let a caller say which of the\n * two silences it is looking at.\n *\n * Returns BOOLEANS, never ids. A test-mode surface asking this question must\n * not come away holding a live `cus_…`: it would have no legitimate use for\n * one, and putting it in a JSON response would publish a live customer id to\n * every browser on a test deployment.\n */\nexport async function readOrgBillingCustomerModes(\n orgId: string,\n): Promise<{ live: boolean; test: boolean }> {\n if (!orgId) return { live: false, test: false }\n const stored = (await readStoredOrgBilling(orgId)) as Record<string, unknown>\n // A stored `null` (the webhook's \"Stripe says this is gone\") and an empty\n // string are both absences, so presence is a non-empty STRING — not `in`,\n // and not truthiness on an unknown.\n const present = (value: unknown) => typeof value === 'string' && value.length > 0\n return {\n live: present(stored['stripeCustomerId']),\n test: present(stored[STRIPE_CUSTOMER_ID_TEST_FIELD]),\n }\n}\n\n/**\n * Writes the commercial keys to the billing doc, and onto the org doc the\n * entitlement inputs that stay there.\n *\n * Three writes, one batch:\n *\n * 1. the billing doc itself, `merge: true` to match what the org-doc write did;\n * 2. the org doc, merged, with what entitlement resolution reads there:\n * `billingStatus`, so the AGL-275 dunning banner keeps working for\n * non-managers who can no longer read `subscription`; and `seatAddons`,\n * which never moved (`ORG_BILLING_MOVED_KEYS`), whenever the patch carries\n * the add-on quantities;\n * 3. the `stripeCustomers` reverse index, so the webhook can still resolve an\n * org from a Stripe customer id without a query.\n *\n * `writeInline` mirrored the keys back onto the org doc as well. It was on\n * during the migration so a rollback lost nothing, and is now OFF: writing them\n * inline is what the whole issue exists to stop, and leaving it on would let the\n * next Stripe webhook silently re-add the fields minutes after they were\n * deleted, re-opening the exposure with nothing to show for it.\n *\n * The option survives for a deliberate one-off rollback, and nothing passes it.\n *\n * The READ fallback in `readOrgBilling` deliberately stays. It costs one get on\n * a doc that no longer exists, and it is the only thing standing between an org\n * the backfill somehow missed and a paying workspace rendering as Free.\n */\nexport async function writeOrgBilling(\n orgId: string,\n patch: Partial<OrgBillingDoc> &\n Pick<OrgInlineBilling, 'seatAddons'> & { aiTier?: AiTierId | null },\n options: { writeInline?: boolean } = {},\n): Promise<void> {\n if (!orgId) return\n const { writeInline = false } = options\n const fields = pickOrgBillingFields(patch as never) as Record<string, unknown>\n // The logical key becomes the mode's PHYSICAL key (AGL-2486). A test-mode\n // write therefore cannot overwrite the live customer id — which it silently\n // did before this, destroying the live linkage on the first completed test\n // checkout.\n const field = customerIdField()\n if (field !== 'stripeCustomerId' && 'stripeCustomerId' in fields) {\n fields[field] = fields['stripeCustomerId']\n delete fields['stripeCustomerId']\n }\n const batch = db().batch()\n const orgRef = db().collection('orgs').doc(orgId)\n\n batch.set(orgBillingRef(orgId), fields, { merge: true })\n\n // The status mirror is derived, so it is only written when this patch\n // actually carries a subscription — otherwise a partial update (a seat-addon\n // change, say) would blank the banner's input.\n const orgPatch: Record<string, unknown> = writeInline ? { ...fields } : {}\n if (patch.subscription !== undefined) {\n orgPatch['billingStatus'] = orgBillingStatusFrom(patch)\n }\n // The add-on quantities are what grants and removes an add-on, and the org\n // doc is the only place they are read from: a subscription sync that wrote\n // them nowhere would charge for an add-on bought at checkout without\n // granting it, and leave a removed one in place. Merged with the rest of\n // this patch, so the explicit zeros of a sync converge while a key the\n // subscription items do not name survives.\n if (patch.seatAddons !== undefined) {\n orgPatch['seatAddons'] = patch.seatAddons\n }\n // Which Aglyn AI tier those quantities hold (AGL-3965), derived from the\n // same items and read from the same document, so it travels with them.\n if (patch.aiTier !== undefined) {\n orgPatch['aiTier'] = patch.aiTier\n }\n if (Object.keys(orgPatch).length) batch.set(orgRef, orgPatch, { merge: true })\n\n // Off the PHYSICAL field, so a test-mode write indexes its own customer.\n // The index needs no mode-keying of its own: it is keyed by the customer id,\n // and Stripe ids are unique across modes, so the live and test entries are\n // two documents that both resolve to this org.\n const customerId = fields[field]\n if (typeof customerId === 'string' && customerId) {\n batch.set(\n db().collection(STRIPE_CUSTOMER_INDEX_COLLECTION).doc(customerId),\n { orgId, updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp() },\n { merge: true },\n )\n }\n\n await batch.commit()\n}\n\n/**\n * Resolves an org id from a Stripe customer id.\n *\n * Prefers the reverse index; falls back to the legacy `where('stripeCustomerId')`\n * query on `orgs` for customers whose index entry has not been written yet.\n * The fallback disappears with the inline fields.\n */\nexport async function findOrgIdByStripeCustomer(\n customerId: string,\n): Promise<string | null> {\n if (!customerId) return null\n const indexed = await db()\n .collection(STRIPE_CUSTOMER_INDEX_COLLECTION)\n .doc(customerId)\n .get()\n const mapped = indexed.get('orgId')\n if (typeof mapped === 'string' && mapped) return mapped\n const legacy = await db()\n .collection('orgs')\n .where('stripeCustomerId', '==', customerId)\n .limit(1)\n .get()\n return legacy.docs[0]?.id ?? null\n}\n\n/** Re-exported so callers do not need a second import to test migration state. */\nexport { hasInlineOrgBilling }\n"],"names":["deploymentLivemode","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","STRIPE_CUSTOMER_ID_TEST_FIELD","STRIPE_CUSTOMER_INDEX_COLLECTION","hasInlineOrgBilling","orgBillingStatusFrom","pickOrgBillingFields","firebaseAdmin","db","app","firestore","customerIdField","projectBillingMode","doc","stored","testId","orgBillingRef","orgId","collection","readOrgBilling","readStoredOrgBilling","billingSnapshot","get","exists","data","orgSnapshot","readOrgBillingCustomerModes","live","test","present","value","length","writeOrgBilling","patch","options","writeInline","fields","field","batch","orgRef","set","merge","orgPatch","subscription","undefined","seatAddons","aiTier","Object","keys","customerId","updatedAt","FieldValue","serverTimestamp","commit","findOrgIdByStripeCustomer","legacy","indexed","mapped","where","limit","docs","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,gDAA+C;AAClF,SACEC,kBAAkB,EAClBC,yBAAyB,EACzBC,6BAA6B,EAC7BC,gCAAgC,EAChCC,mBAAmB,EACnBC,oBAAoB,EACpBC,oBAAoB,QAIf,sBAAqB;AAC5B,SAASC,aAAa,QAAQ,sBAAkB;AAEhD;;;;;;;;CAQC,GAED,MAAMC,KAAK,IAAMD,cAAcE,GAAG,GAAGC,SAAS;AAE9C;;;;;;;;;;;;CAYC,GACD,SAASC;IACP,OAAOZ,uBAAuB,qBAAqBG;AACrD;AAEA;;;;;;;;CAQC,GACD,SAASU,mBAAmBC,GAAkB;IAC5C,MAAMC,SAAS,aAAMD,cAAAA,MAAO,CAAC;IAC7B,MAAME,SAASD,MAAM,CAACZ,8BAA8B;I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E5E,yEAAyE;IACzE,6EAA6E;IAC7E,2EAA2E;IAC3E,+CAA+C;IAC/C,MAAMQ,aAAab,MAAM,CAACC,MAAM;IAChC,IAAI,OAAOY,eAAe,YAAYA,YAAY;QAChDX,MAAME,GAAG,CACPhC,KAAKU,UAAU,CAACf,kCAAkCU,GAAG,CAACoC,aACtD;YAAEhC;YAAOiC,WAAW3C,cAAcG,SAAS,CAACyC,UAAU,CAACC,eAAe;QAAG,GACzE;YAAEX,OAAO;QAAK;IAElB;IAEA,MAAMH,MAAMe,MAAM;AACpB;AAEA;;;;;;CAMC,GACD,OAAO,eAAeC,0BACpBL,UAAkB;;QAcXM;IAZP,IAAI,CAACN,YAAY,OAAO;IACxB,MAAMO,UAAU,MAAMhD,KACnBU,UAAU,CAACf,kCACXU,GAAG,CAACoC,YACJ3B,GAAG;IACN,MAAMmC,SAASD,QAAQlC,GAAG,CAAC;IAC3B,IAAI,OAAOmC,WAAW,YAAYA,QAAQ,OAAOA;IACjD,MAAMF,SAAS,MAAM/C,KAClBU,UAAU,CAAC,QACXwC,KAAK,CAAC,oBAAoB,MAAMT,YAChCU,KAAK,CAAC,GACNrC,GAAG;IACN,gBAAOiC,gBAAAA,OAAOK,IAAI,CAAC,EAAE,qBAAdL,cAAgBM,EAAE,mBAAI;AAC/B;AAEA,gFAAgF,GAChF,SAASzD,mBAAmB,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-billing.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 { deploymentLivemode } from '@aglyn/aglyn/app-utils/stripe-deployment-mode'\nimport {\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n STRIPE_CUSTOMER_ID_TEST_FIELD,\n STRIPE_CUSTOMER_INDEX_COLLECTION,\n hasInlineOrgBilling,\n orgBillingStatusFrom,\n pickOrgBillingFields,\n type OrgBillingDoc,\n type OrgInlineBilling,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * Server-side accessors for the manager-gated billing document (AGL-1028).\n *\n * Every server surface that used to read `orgs/{orgId}.stripeCustomerId` /\n * `.subscription` / `.seatAddons` goes through here instead. All of them are\n * Admin SDK, so rules never applied to them — this is a path change, not a\n * permission change. The permission change is entirely in the rules, where the\n * new subcollection is gated on `canManageOrg()`.\n */\n\nconst db = () => firebaseAdmin.app().firestore()\n\n/**\n * Which PHYSICAL field holds this deployment's Stripe customer id (AGL-2486).\n *\n * Live keeps `stripeCustomerId`, so live behaviour is byte-identical to before\n * this existed and no stored document needs migrating. Test mode gets its own\n * slot, which starts empty on every org — the first test-mode checkout mints a\n * fresh test customer instead of sending a live `cus_…` to a `sk_test` key and\n * taking a 502.\n *\n * Read at call time rather than at module load: a spec flips\n * `process.env.STRIPE_SECRET_KEY` between cases, and a cached verdict would\n * make the second case answer for the first.\n */\nfunction customerIdField(): 'stripeCustomerId' | typeof STRIPE_CUSTOMER_ID_TEST_FIELD {\n return deploymentLivemode() ? 'stripeCustomerId' : STRIPE_CUSTOMER_ID_TEST_FIELD\n}\n\n/**\n * Collapse a stored billing document to the logical shape callers expect.\n *\n * `stripeCustomerId` on the RESULT always means \"the customer id for the mode\n * this deployment spends in\". The test id never leaks out under its physical\n * name, and — the part that matters — test mode does NOT fall back to the live\n * id when its own slot is empty. That fallback is precisely the bug: it is what\n * sent `cus_UuQjDdd1oxPMNH` to a `sk_test` key.\n */\nfunction projectBillingMode(doc: OrgBillingDoc): OrgBillingDoc {\n const stored = { ...(doc ?? {}) } as Record<string, unknown>\n const testId = stored[STRIPE_CUSTOMER_ID_TEST_FIELD]\n // The physical twin never reaches a caller in either mode: every reader\n // treats `stripeCustomerId` as THE customer, so a second field carrying a\n // second answer is exactly the ambiguity this fix removes.\n delete stored[STRIPE_CUSTOMER_ID_TEST_FIELD]\n if (deploymentLivemode()) return stored as OrgBillingDoc\n // No `??` fallback to the live id. That fallback IS the bug.\n stored['stripeCustomerId'] = (testId ?? null) as string | null\n return stored as OrgBillingDoc\n}\n\n/** `orgs/{orgId}/billing/stripe`. */\nexport function orgBillingRef(orgId: string) {\n return db()\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_BILLING_SUBCOLLECTION)\n .doc(ORG_BILLING_DOC_ID)\n}\n\n/**\n * Reads an org's commercial keys, falling back to the org doc.\n *\n * The fallback is what makes the migration safe to land in pieces: a reader\n * repointed here keeps working against an org that has not been backfilled\n * yet, and keeps working if the backfill missed one. It stops being reachable\n * only when the inline fields are finally deleted from the org doc — which is\n * the LAST step, taken once production has been observed reading from the new\n * location.\n *\n * Without it, the failure mode is silent and expensive: a missing billing doc\n * reads as `undefined`, which every caller downstream interprets as \"no\n * subscription\", i.e. a paying workspace rendered as Free.\n */\nexport async function readOrgBilling(orgId: string): Promise<OrgBillingDoc> {\n if (!orgId) return {}\n return projectBillingMode(await readStoredOrgBilling(orgId))\n}\n\n/**\n * The STORED document, before any mode projection — both physical ids intact.\n *\n * Private on purpose: a caller holding this holds two answers to \"which\n * customer\", which is the ambiguity `projectBillingMode` exists to remove. It\n * is factored out only so the mode census below reads the very same bytes\n * `readOrgBilling` reads, org-doc fallback included. Two separate reads would\n * be two chances to diverge, and the census exists precisely to explain what\n * `readOrgBilling` returned.\n */\nasync function readStoredOrgBilling(orgId: string): Promise<OrgBillingDoc> {\n const billingSnapshot = await orgBillingRef(orgId).get()\n if (billingSnapshot.exists) {\n return (billingSnapshot.data() ?? {}) as OrgBillingDoc\n }\n const orgSnapshot = await db().collection('orgs').doc(orgId).get()\n // The legacy inline fields predate mode-keying entirely, so anything found\n // there is a LIVE id by construction — the org doc was last written by a\n // `sk_live_` deployment. Projected by the caller all the same, so a\n // test-mode read of an un-backfilled org gets no customer rather than a live\n // one.\n return pickOrgBillingFields(orgSnapshot.data() as never) as OrgBillingDoc\n}\n\n/**\n * Which Stripe MODES this org has a stored customer for (AGL-2486, follow-up).\n *\n * `readOrgBilling` answering `stripeCustomerId: null` has two completely\n * different meanings — \"this workspace has never been billed\" and \"this\n * workspace's customer lives in the other Stripe world and THIS deployment\n * cannot see it\" — and every surface downstream rendered them as the same\n * sentence, \"No invoices yet.\" That is the swallowed-query-as-measured-zero\n * shape: nothing looks wrong, and the wrong reading is the reassuring one.\n *\n * The fix is NOT to fall back to the other mode's id — that fallback is the\n * original bug, and it stays deleted. It is to let a caller say which of the\n * two silences it is looking at.\n *\n * Returns BOOLEANS, never ids. A test-mode surface asking this question must\n * not come away holding a live `cus_…`: it would have no legitimate use for\n * one, and putting it in a JSON response would publish a live customer id to\n * every browser on a test deployment.\n */\nexport async function readOrgBillingCustomerModes(\n orgId: string,\n): Promise<{ live: boolean; test: boolean }> {\n if (!orgId) return { live: false, test: false }\n const stored = (await readStoredOrgBilling(orgId)) as Record<string, unknown>\n // A stored `null` (the webhook's \"Stripe says this is gone\") and an empty\n // string are both absences, so presence is a non-empty STRING — not `in`,\n // and not truthiness on an unknown.\n const present = (value: unknown) => typeof value === 'string' && value.length > 0\n return {\n live: present(stored['stripeCustomerId']),\n test: present(stored[STRIPE_CUSTOMER_ID_TEST_FIELD]),\n }\n}\n\n/**\n * Writes the commercial keys to the billing doc, and onto the org doc the\n * entitlement inputs that stay there.\n *\n * Three writes, one batch:\n *\n * 1. the billing doc itself, `merge: true` to match what the org-doc write did;\n * 2. the org doc, merged, with what entitlement resolution reads there:\n * `billingStatus`, so the AGL-275 dunning banner keeps working for\n * non-managers who can no longer read `subscription`; and `seatAddons`,\n * which never moved (`ORG_BILLING_MOVED_KEYS`), whenever the patch carries\n * the add-on quantities;\n * 3. the `stripeCustomers` reverse index, so the webhook can still resolve an\n * org from a Stripe customer id without a query.\n *\n * `writeInline` mirrored the keys back onto the org doc as well. It was on\n * during the migration so a rollback lost nothing, and is now OFF: writing them\n * inline is what the whole issue exists to stop, and leaving it on would let the\n * next Stripe webhook silently re-add the fields minutes after they were\n * deleted, re-opening the exposure with nothing to show for it.\n *\n * The option survives for a deliberate one-off rollback, and nothing passes it.\n *\n * The READ fallback in `readOrgBilling` deliberately stays. It costs one get on\n * a doc that no longer exists, and it is the only thing standing between an org\n * the backfill somehow missed and a paying workspace rendering as Free.\n */\nexport async function writeOrgBilling(\n orgId: string,\n patch: Partial<OrgBillingDoc> &\n Pick<OrgInlineBilling, 'seatAddons'>,\n options: { writeInline?: boolean } = {},\n): Promise<void> {\n if (!orgId) return\n const { writeInline = false } = options\n const fields = pickOrgBillingFields(patch as never) as Record<string, unknown>\n // The logical key becomes the mode's PHYSICAL key (AGL-2486). A test-mode\n // write therefore cannot overwrite the live customer id — which it silently\n // did before this, destroying the live linkage on the first completed test\n // checkout.\n const field = customerIdField()\n if (field !== 'stripeCustomerId' && 'stripeCustomerId' in fields) {\n fields[field] = fields['stripeCustomerId']\n delete fields['stripeCustomerId']\n }\n const batch = db().batch()\n const orgRef = db().collection('orgs').doc(orgId)\n\n batch.set(orgBillingRef(orgId), fields, { merge: true })\n\n // The status mirror is derived, so it is only written when this patch\n // actually carries a subscription — otherwise a partial update (a seat-addon\n // change, say) would blank the banner's input.\n const orgPatch: Record<string, unknown> = writeInline ? { ...fields } : {}\n if (patch.subscription !== undefined) {\n orgPatch['billingStatus'] = orgBillingStatusFrom(patch)\n }\n // The add-on quantities are what grants and removes an add-on, and the org\n // doc is the only place they are read from: a subscription sync that wrote\n // them nowhere would charge for an add-on bought at checkout without\n // granting it, and leave a removed one in place. Merged with the rest of\n // this patch, so the explicit zeros of a sync converge while a key the\n // subscription items do not name survives.\n if (patch.seatAddons !== undefined) {\n orgPatch['seatAddons'] = patch.seatAddons\n }\n if (Object.keys(orgPatch).length) batch.set(orgRef, orgPatch, { merge: true })\n\n // Off the PHYSICAL field, so a test-mode write indexes its own customer.\n // The index needs no mode-keying of its own: it is keyed by the customer id,\n // and Stripe ids are unique across modes, so the live and test entries are\n // two documents that both resolve to this org.\n const customerId = fields[field]\n if (typeof customerId === 'string' && customerId) {\n batch.set(\n db().collection(STRIPE_CUSTOMER_INDEX_COLLECTION).doc(customerId),\n { orgId, updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp() },\n { merge: true },\n )\n }\n\n await batch.commit()\n}\n\n/**\n * Resolves an org id from a Stripe customer id.\n *\n * Prefers the reverse index; falls back to the legacy `where('stripeCustomerId')`\n * query on `orgs` for customers whose index entry has not been written yet.\n * The fallback disappears with the inline fields.\n */\nexport async function findOrgIdByStripeCustomer(\n customerId: string,\n): Promise<string | null> {\n if (!customerId) return null\n const indexed = await db()\n .collection(STRIPE_CUSTOMER_INDEX_COLLECTION)\n .doc(customerId)\n .get()\n const mapped = indexed.get('orgId')\n if (typeof mapped === 'string' && mapped) return mapped\n const legacy = await db()\n .collection('orgs')\n .where('stripeCustomerId', '==', customerId)\n .limit(1)\n .get()\n return legacy.docs[0]?.id ?? null\n}\n\n/** Re-exported so callers do not need a second import to test migration state. */\nexport { hasInlineOrgBilling }\n"],"names":["deploymentLivemode","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","STRIPE_CUSTOMER_ID_TEST_FIELD","STRIPE_CUSTOMER_INDEX_COLLECTION","hasInlineOrgBilling","orgBillingStatusFrom","pickOrgBillingFields","firebaseAdmin","db","app","firestore","customerIdField","projectBillingMode","doc","stored","testId","orgBillingRef","orgId","collection","readOrgBilling","readStoredOrgBilling","billingSnapshot","get","exists","data","orgSnapshot","readOrgBillingCustomerModes","live","test","present","value","length","writeOrgBilling","patch","options","writeInline","fields","field","batch","orgRef","set","merge","orgPatch","subscription","undefined","seatAddons","Object","keys","customerId","updatedAt","FieldValue","serverTimestamp","comm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,EAAE,mBAAI;AAC/B;AAEA,gFAAgF,GAChF,SAASxD,mBAAmB,GAAE"}
|
|
@@ -66,6 +66,7 @@
|
|
|
66
66
|
* has no signing key.
|
|
67
67
|
*/
|
|
68
68
|
import { type DmarcAssessment, type SendingDnsRecord, type SendingDomainRecord, type SendingIdentityPurpose, type SendingIdentityVerdict, type SendingVerification } from '@aglyn/shared-util-email';
|
|
69
|
+
import './email-transactional-ceiling';
|
|
69
70
|
/** Subcollection under the owning org. */
|
|
70
71
|
export declare const SENDING_DOMAINS_COLLECTION = "sendingDomains";
|
|
71
72
|
/**
|
|
@@ -75,6 +75,11 @@ import { getSiteLockdown } from "./tenant-write-lockdown.js";
|
|
|
75
75
|
// has therefore installed the gate the workspace stamped below is read by.
|
|
76
76
|
import { sendingWorkspaceFor } from "./outbound-send-review.js";
|
|
77
77
|
import { flagLookalikeDomain } from "./hosted-page-review.js";
|
|
78
|
+
import { resolveTransactionalEmailDailyCeiling } from "@aglyn/aglyn/app-utils/transactional-email-ceiling";
|
|
79
|
+
// Also INSTALLS the daily transactional ceiling's counter on `sendEmail`
|
|
80
|
+
// (AGL-4145), for the same reason: the ceiling stamped on the workspace below
|
|
81
|
+
// is only read by a send path that has the gate installed.
|
|
82
|
+
import "./email-transactional-ceiling.js";
|
|
78
83
|
const firestore = ()=>firebaseAdmin.app().firestore();
|
|
79
84
|
/** Subcollection under the owning org. */ export const SENDING_DOMAINS_COLLECTION = 'sendingDomains';
|
|
80
85
|
const domainRef = (orgId, domain)=>firestore().collection('orgs').doc(orgId).collection(SENDING_DOMAINS_COLLECTION).doc(domain);
|
|
@@ -735,11 +740,18 @@ export async function listSendingDomains(orgId) {
|
|
|
735
740
|
* any of them passing anything. Built from the two documents read above:
|
|
736
741
|
* the screen costs no read of its own.
|
|
737
742
|
*/ const verdict = _extends({}, resolved, {
|
|
738
|
-
workspace: sendingWorkspaceFor({
|
|
743
|
+
workspace: _extends({}, sendingWorkspaceFor({
|
|
739
744
|
hostId: id,
|
|
740
745
|
orgId: (_ref5 = owner == null ? void 0 : owner.orgId) != null ? _ref5 : null,
|
|
741
746
|
org: (_ref6 = owner == null ? void 0 : owner.org) != null ? _ref6 : null,
|
|
742
747
|
host: (snapshot == null ? void 0 : snapshot.exists) ? (_snapshot_data1 = snapshot.data()) != null ? _snapshot_data1 : null : null
|
|
748
|
+
}), {
|
|
749
|
+
/*
|
|
750
|
+
* THE DAILY TRANSACTIONAL CEILING (AGL-4145), from the same org
|
|
751
|
+
* document, so the send seam's count costs no read of its own. No
|
|
752
|
+
* organization read means no ceiling known, and none is applied —
|
|
753
|
+
* an unreadable org must not put a paying store on Free's figure.
|
|
754
|
+
*/ transactionalEmailsPerDay: (owner == null ? void 0 : owner.org) ? resolveTransactionalEmailDailyCeiling(owner.org) : null
|
|
743
755
|
})
|
|
744
756
|
}, siteSenderNames({
|
|
745
757
|
org: (_ref7 = owner == null ? void 0 : owner.org) != null ? _ref7 : null,
|