@aglyn/tenant-data-admin 1.0.0-beta.269 → 1.0.0-beta.271
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/render-cache.d.ts +10 -3
- package/src/lib/render-cache.js +10 -3
- package/src/lib/render-cache.js.map +1 -1
- package/src/lib/server/append-only-history-write.d.ts +38 -0
- package/src/lib/server/append-only-history-write.js +60 -0
- package/src/lib/server/append-only-history-write.js.map +1 -0
- package/src/lib/server/billing-addons.d.ts +58 -30
- package/src/lib/server/billing-addons.js +102 -77
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +166 -0
- package/src/lib/server/bundle-links.js +286 -0
- package/src/lib/server/bundle-links.js.map +1 -0
- package/src/lib/server/client-build.d.ts +74 -0
- package/src/lib/server/client-build.js +264 -0
- package/src/lib/server/client-build.js.map +1 -0
- package/src/lib/server/configured-url-fetch.d.ts +26 -0
- package/src/lib/server/configured-url-fetch.js +68 -0
- package/src/lib/server/configured-url-fetch.js.map +1 -1
- package/src/lib/server/custom-domain-redirects.d.ts +50 -0
- package/src/lib/server/custom-domain-redirects.js +61 -0
- package/src/lib/server/custom-domain-redirects.js.map +1 -0
- package/src/lib/server/host-custom-domain.d.ts +125 -0
- package/src/lib/server/host-custom-domain.js +395 -0
- package/src/lib/server/host-custom-domain.js.map +1 -0
- package/src/lib/server/host-memberships.d.ts +35 -2
- package/src/lib/server/host-memberships.js +63 -2
- package/src/lib/server/host-memberships.js.map +1 -1
- package/src/lib/server/host-released-names.d.ts +1 -2
- package/src/lib/server/host-released-names.js +4 -2
- package/src/lib/server/host-released-names.js.map +1 -1
- package/src/lib/server/media-photo-links.d.ts +196 -0
- package/src/lib/server/media-photo-links.js +290 -0
- package/src/lib/server/media-photo-links.js.map +1 -0
- package/src/lib/server/org-billing.d.ts +4 -2
- package/src/lib/server/org-billing.js +5 -0
- package/src/lib/server/org-billing.js.map +1 -1
- package/src/lib/server/organizations.d.ts +25 -1
- package/src/lib/server/organizations.js +62 -2
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/personal-data-export.js +21 -1
- package/src/lib/server/personal-data-export.js.map +1 -1
- package/src/lib/server/push-delivery.js +32 -14
- package/src/lib/server/push-delivery.js.map +1 -1
- package/src/lib/server/site-care-emails.d.ts +52 -0
- package/src/lib/server/site-care-emails.js +97 -0
- package/src/lib/server/site-care-emails.js.map +1 -0
- package/src/lib/server/site-care-inbound.d.ts +80 -0
- package/src/lib/server/site-care-inbound.js +171 -0
- package/src/lib/server/site-care-inbound.js.map +1 -0
- package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
- package/src/lib/server/site-care-project-reconcile.js +211 -0
- package/src/lib/server/site-care-project-reconcile.js.map +1 -0
- package/src/lib/server/site-care-project-stripe.d.ts +114 -0
- package/src/lib/server/site-care-project-stripe.js +305 -0
- package/src/lib/server/site-care-project-stripe.js.map +1 -0
- package/src/lib/server/site-care-projects.d.ts +169 -0
- package/src/lib/server/site-care-projects.js +882 -0
- package/src/lib/server/site-care-projects.js.map +1 -0
- package/src/lib/server/site-care-reconcile.d.ts +81 -0
- package/src/lib/server/site-care-reconcile.js +349 -0
- package/src/lib/server/site-care-reconcile.js.map +1 -0
- package/src/lib/server/site-care-requests.d.ts +243 -0
- package/src/lib/server/site-care-requests.js +1414 -0
- package/src/lib/server/site-care-requests.js.map +1 -0
- package/src/lib/server/site-care-stripe.d.ts +175 -0
- package/src/lib/server/site-care-stripe.js +375 -0
- package/src/lib/server/site-care-stripe.js.map +1 -0
- package/src/lib/server/tenant-dns-check.d.ts +58 -0
- package/src/lib/server/tenant-dns-check.js +197 -0
- package/src/lib/server/tenant-dns-check.js.map +1 -0
- package/src/lib/server/upgrade-proposal.d.ts +40 -1
- package/src/lib/server/upgrade-proposal.js +92 -50
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/tenancy.d.ts +5 -0
- package/src/tenancy.js +10 -0
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
18
|
+
import { encodeMediaDisplay } from "./media-variants.js";
|
|
19
|
+
/**
|
|
20
|
+
* A SITE'S PHOTO LINK (AGL-3957): an address a site member hands to someone
|
|
21
|
+
* with photos on their phone — the owner of the business the site is being
|
|
22
|
+
* built for, at a booth or on a doorstep — so the photos land in the site's
|
|
23
|
+
* media library without a sign-in.
|
|
24
|
+
*
|
|
25
|
+
* The link is `{origin}/p/{linkId}#{secret}`, and the page composes the
|
|
26
|
+
* token `{linkId}.{secret}` from its path and its fragment. The secret rides
|
|
27
|
+
* in the FRAGMENT because a fragment never leaves the browser: no request
|
|
28
|
+
* line carries it, so no server or edge log, no analytics page view and no
|
|
29
|
+
* `Referer` header ever holds a working link. The page sends the token to
|
|
30
|
+
* the public route in a POST body. The database holds the SHA-256
|
|
31
|
+
* of the secret and never the secret, the same shape as an emailed
|
|
32
|
+
* confirmation link (`account-emails.ts`): a reader of the database cannot
|
|
33
|
+
* upload to anybody's site. A link lives seven days, takes a bounded number
|
|
34
|
+
* of photos and bytes, and can be revoked by any member who could have
|
|
35
|
+
* minted it. Every upload it takes is stored AS THE MEMBER WHO MINTED IT,
|
|
36
|
+
* through the media ingest's own door (`core.media-ingest`), so a member who
|
|
37
|
+
* lost the site, a locked site, a takedown and the storage band refuse the
|
|
38
|
+
* link's uploads exactly as they refuse that member's.
|
|
39
|
+
*
|
|
40
|
+
* Documents live in the top-level `photoLinks` collection, keyed by link id
|
|
41
|
+
* and carrying the site: a token alone names no site, and a top-level
|
|
42
|
+
* collection answers it in one read with no collection-group index. Only the
|
|
43
|
+
* Admin SDK reads or writes them.
|
|
44
|
+
*/ export const PHOTO_LINKS_COLLECTION = 'photoLinks';
|
|
45
|
+
/** Where the console serves the page a link opens. */ export const PHOTO_LINK_PATH = '/p';
|
|
46
|
+
/** How long a link takes photos, from its minting. */ export const PHOTO_LINK_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
47
|
+
/** The most photos one link takes. */ export const PHOTO_LINK_MAX_UPLOADS = 40;
|
|
48
|
+
/** The most bytes one link takes, over all its photos, after they are stored. */ export const PHOTO_LINK_MAX_BYTES = 200 * 1024 * 1024;
|
|
49
|
+
/** The folder the link's photos are filed in, created in the site's library when the first link is minted. */ export const PHOTO_LINK_FOLDER_NAME = 'From the owner';
|
|
50
|
+
/**
|
|
51
|
+
* What the page accepts from the phone. The page re-encodes what it picks
|
|
52
|
+
* (a HEIC, a 12 MB camera original) into one of these before it sends it, so
|
|
53
|
+
* a format a browser cannot draw never reaches the server.
|
|
54
|
+
*/ export const PHOTO_LINK_TYPES = new Set([
|
|
55
|
+
'image/jpeg',
|
|
56
|
+
'image/png',
|
|
57
|
+
'image/webp'
|
|
58
|
+
]);
|
|
59
|
+
/** The most bytes one photo may arrive as, before it is stored. */ export const PHOTO_LINK_PHOTO_MAX_BYTES = 8 * 1024 * 1024;
|
|
60
|
+
/** What one phone may ask of the link's page in a window, and how long the window is. */ export const PHOTO_LINK_RATE_LIMIT = Object.freeze({
|
|
61
|
+
limit: 80,
|
|
62
|
+
windowMs: 10 * 60 * 1000
|
|
63
|
+
});
|
|
64
|
+
/** A fresh token: the id the document is keyed by, the secret the link carries, and the digest the document keeps. */ export function mintPhotoLinkToken() {
|
|
65
|
+
const linkId = randomBytes(12).toString('hex');
|
|
66
|
+
const secret = randomBytes(24).toString('hex');
|
|
67
|
+
return {
|
|
68
|
+
linkId,
|
|
69
|
+
secret,
|
|
70
|
+
digest: photoLinkDigest(secret),
|
|
71
|
+
token: `${linkId}.${secret}`
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export function photoLinkDigest(secret) {
|
|
75
|
+
return createHash('sha256').update(secret).digest('hex');
|
|
76
|
+
}
|
|
77
|
+
/** The two halves of a token as the page received it, or null for anything that is not shaped like one. */ export function parsePhotoLinkToken(raw) {
|
|
78
|
+
const token = String(raw != null ? raw : '').trim();
|
|
79
|
+
const separator = token.indexOf('.');
|
|
80
|
+
if (separator <= 0) return null;
|
|
81
|
+
const linkId = token.slice(0, separator);
|
|
82
|
+
const secret = token.slice(separator + 1);
|
|
83
|
+
if (!/^[a-f0-9]{24}$/.test(linkId) || !/^[a-f0-9]{48}$/.test(secret)) return null;
|
|
84
|
+
return {
|
|
85
|
+
linkId,
|
|
86
|
+
secret
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/** Constant-time: the stored digest against the secret the page presented. */ export function photoLinkSecretMatches(digest, secret) {
|
|
90
|
+
const expected = photoLinkDigest(secret);
|
|
91
|
+
if (typeof digest !== 'string' || digest.length !== expected.length) return false;
|
|
92
|
+
return timingSafeEqual(Buffer.from(digest, 'hex'), Buffer.from(expected, 'hex'));
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The address the link opens, on the console origin given: the link id in
|
|
96
|
+
* the path, the secret in the fragment, which the browser never sends.
|
|
97
|
+
*/ export function photoLinkUrl(origin, linkId, secret) {
|
|
98
|
+
return `${origin.replace(/\/+$/, '')}${PHOTO_LINK_PATH}/${encodeURIComponent(linkId)}#${encodeURIComponent(secret)}`;
|
|
99
|
+
}
|
|
100
|
+
export function photoLinkState(doc, now = Date.now()) {
|
|
101
|
+
if (doc.revokedAt) return 'revoked';
|
|
102
|
+
if (now >= doc.expiresAt) return 'expired';
|
|
103
|
+
if (doc.uploads >= PHOTO_LINK_MAX_UPLOADS || doc.bytes >= PHOTO_LINK_MAX_BYTES) return 'full';
|
|
104
|
+
return 'live';
|
|
105
|
+
}
|
|
106
|
+
export function photoLinkSummary(linkId, doc, now = Date.now()) {
|
|
107
|
+
return {
|
|
108
|
+
linkId,
|
|
109
|
+
state: photoLinkState(doc, now),
|
|
110
|
+
createdAt: doc.createdAt,
|
|
111
|
+
expiresAt: doc.expiresAt,
|
|
112
|
+
uploads: doc.uploads,
|
|
113
|
+
bytes: doc.bytes,
|
|
114
|
+
remainingUploads: Math.max(0, PHOTO_LINK_MAX_UPLOADS - doc.uploads),
|
|
115
|
+
remainingBytes: Math.max(0, PHOTO_LINK_MAX_BYTES - doc.bytes)
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** The stored document, read defensively: a field the writer never set reads as its zero. */ export function readPhotoLinkDoc(data) {
|
|
119
|
+
if (!data || typeof data['hostId'] !== 'string' || typeof data['digest'] !== 'string') return null;
|
|
120
|
+
const number = (value)=>typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
|
121
|
+
return _extends({
|
|
122
|
+
hostId: data['hostId'],
|
|
123
|
+
createdBy: typeof data['createdBy'] === 'string' ? data['createdBy'] : '',
|
|
124
|
+
createdAt: number(data['createdAt']),
|
|
125
|
+
expiresAt: number(data['expiresAt'])
|
|
126
|
+
}, number(data['revokedAt']) ? {
|
|
127
|
+
revokedAt: number(data['revokedAt'])
|
|
128
|
+
} : {}, typeof data['revokedBy'] === 'string' ? {
|
|
129
|
+
revokedBy: data['revokedBy']
|
|
130
|
+
} : {}, {
|
|
131
|
+
digest: data['digest'],
|
|
132
|
+
folderId: typeof data['folderId'] === 'string' && data['folderId'] ? data['folderId'] : null,
|
|
133
|
+
uploads: number(data['uploads']),
|
|
134
|
+
bytes: number(data['bytes'])
|
|
135
|
+
}, number(data['lastUploadAt']) ? {
|
|
136
|
+
lastUploadAt: number(data['lastUploadAt'])
|
|
137
|
+
} : {});
|
|
138
|
+
}
|
|
139
|
+
export function photoLinkRef(firestore, linkId) {
|
|
140
|
+
return firestore.collection(PHOTO_LINKS_COLLECTION).doc(linkId);
|
|
141
|
+
}
|
|
142
|
+
/** Mints a link for the site as the member, and stores its document. The secret is returned once and never stored. */ export async function createPhotoLink(firestore, input) {
|
|
143
|
+
var _input_now;
|
|
144
|
+
const now = (_input_now = input.now) != null ? _input_now : Date.now();
|
|
145
|
+
const minted = mintPhotoLinkToken();
|
|
146
|
+
const doc = {
|
|
147
|
+
hostId: input.hostId,
|
|
148
|
+
createdBy: input.uid,
|
|
149
|
+
createdAt: now,
|
|
150
|
+
expiresAt: now + PHOTO_LINK_TTL_MS,
|
|
151
|
+
digest: minted.digest,
|
|
152
|
+
folderId: input.folderId,
|
|
153
|
+
uploads: 0,
|
|
154
|
+
bytes: 0
|
|
155
|
+
};
|
|
156
|
+
await photoLinkRef(firestore, minted.linkId).create(doc);
|
|
157
|
+
return {
|
|
158
|
+
linkId: minted.linkId,
|
|
159
|
+
secret: minted.secret,
|
|
160
|
+
token: minted.token,
|
|
161
|
+
expiresAt: doc.expiresAt
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The link a token names, when the token is well-formed, its document exists,
|
|
166
|
+
* its secret matches and the link still takes photos. Every other case is a
|
|
167
|
+
* refusal that says only what the page needs to tell the person holding the
|
|
168
|
+
* phone; an unknown id and a wrong secret read the same.
|
|
169
|
+
*/ export async function readPhotoLinkByToken(firestore, token, now = Date.now()) {
|
|
170
|
+
const parsed = parsePhotoLinkToken(token);
|
|
171
|
+
if (!parsed) return {
|
|
172
|
+
ok: false,
|
|
173
|
+
reason: 'invalid'
|
|
174
|
+
};
|
|
175
|
+
const ref = photoLinkRef(firestore, parsed.linkId);
|
|
176
|
+
const snapshot = await ref.get();
|
|
177
|
+
const doc = readPhotoLinkDoc(snapshot.exists ? snapshot.data() : undefined);
|
|
178
|
+
if (!doc || !photoLinkSecretMatches(doc.digest, parsed.secret)) return {
|
|
179
|
+
ok: false,
|
|
180
|
+
reason: 'invalid'
|
|
181
|
+
};
|
|
182
|
+
const state = photoLinkState(doc, now);
|
|
183
|
+
if (state !== 'live') return {
|
|
184
|
+
ok: false,
|
|
185
|
+
reason: state
|
|
186
|
+
};
|
|
187
|
+
return {
|
|
188
|
+
ok: true,
|
|
189
|
+
linkId: parsed.linkId,
|
|
190
|
+
ref,
|
|
191
|
+
doc,
|
|
192
|
+
summary: photoLinkSummary(parsed.linkId, doc, now)
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Claims one photo's place on the link before its bytes are stored, inside a
|
|
197
|
+
* transaction, so forty phones racing one link cannot store eighty photos.
|
|
198
|
+
* `releasePhotoLinkUpload` gives the place back when the store refused.
|
|
199
|
+
*/ export async function claimPhotoLinkUpload(firestore, ref, bytes, now = Date.now()) {
|
|
200
|
+
return firestore.runTransaction(async (transaction)=>{
|
|
201
|
+
const snapshot = await transaction.get(ref);
|
|
202
|
+
const doc = readPhotoLinkDoc(snapshot.exists ? snapshot.data() : undefined);
|
|
203
|
+
if (!doc) return {
|
|
204
|
+
ok: false,
|
|
205
|
+
reason: 'invalid'
|
|
206
|
+
};
|
|
207
|
+
const state = photoLinkState(doc, now);
|
|
208
|
+
if (state !== 'live') return {
|
|
209
|
+
ok: false,
|
|
210
|
+
reason: state
|
|
211
|
+
};
|
|
212
|
+
if (doc.bytes + bytes > PHOTO_LINK_MAX_BYTES) return {
|
|
213
|
+
ok: false,
|
|
214
|
+
reason: 'full'
|
|
215
|
+
};
|
|
216
|
+
transaction.update(ref, {
|
|
217
|
+
uploads: doc.uploads + 1,
|
|
218
|
+
bytes: doc.bytes + bytes,
|
|
219
|
+
lastUploadAt: now
|
|
220
|
+
});
|
|
221
|
+
return {
|
|
222
|
+
ok: true
|
|
223
|
+
};
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
export async function releasePhotoLinkUpload(firestore, ref, bytes) {
|
|
227
|
+
await firestore.runTransaction(async (transaction)=>{
|
|
228
|
+
const snapshot = await transaction.get(ref);
|
|
229
|
+
const doc = readPhotoLinkDoc(snapshot.exists ? snapshot.data() : undefined);
|
|
230
|
+
if (!doc) return;
|
|
231
|
+
transaction.update(ref, {
|
|
232
|
+
uploads: Math.max(0, doc.uploads - 1),
|
|
233
|
+
bytes: Math.max(0, doc.bytes - bytes)
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
/** Marks the link revoked. Idempotent; a link of another site is left alone and reported as not found. */ export async function revokePhotoLink(firestore, input) {
|
|
238
|
+
var _input_now;
|
|
239
|
+
const ref = photoLinkRef(firestore, input.linkId);
|
|
240
|
+
const snapshot = await ref.get();
|
|
241
|
+
const doc = readPhotoLinkDoc(snapshot.exists ? snapshot.data() : undefined);
|
|
242
|
+
if (!doc || doc.hostId !== input.hostId) return false;
|
|
243
|
+
if (doc.revokedAt) return true;
|
|
244
|
+
await ref.update({
|
|
245
|
+
revokedAt: (_input_now = input.now) != null ? _input_now : Date.now(),
|
|
246
|
+
revokedBy: input.uid
|
|
247
|
+
});
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
/** The site's links that still take photos, newest first. */ export async function listLivePhotoLinks(firestore, hostId, now = Date.now()) {
|
|
251
|
+
const snapshot = await firestore.collection(PHOTO_LINKS_COLLECTION).where('hostId', '==', hostId).where('expiresAt', '>', now).limit(50).get();
|
|
252
|
+
const live = [];
|
|
253
|
+
for (const document of snapshot.docs){
|
|
254
|
+
const doc = readPhotoLinkDoc(document.data());
|
|
255
|
+
if (!doc) continue;
|
|
256
|
+
const summary = photoLinkSummary(document.id, doc, now);
|
|
257
|
+
if (summary.state === 'live') live.push(summary);
|
|
258
|
+
}
|
|
259
|
+
return live.sort((a, b)=>b.createdAt - a.createdAt);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* The bytes a link's photo is stored as: oriented the way the phone held it,
|
|
263
|
+
* no wider than the delivery edge, and carrying no EXIF, XMP or IPTC — so a
|
|
264
|
+
* photo's GPS position, taken in somebody's driveway, never reaches the
|
|
265
|
+
* library. The display encoder already does exactly this for a delivery
|
|
266
|
+
* copy; here its answer IS the original. A photo that carries nothing and
|
|
267
|
+
* needs no turning is stored as it came.
|
|
268
|
+
*/ export async function storedPhotoLinkBytes(sharp, bytes, contentType) {
|
|
269
|
+
const display = await encodeMediaDisplay(sharp, bytes, contentType);
|
|
270
|
+
return display ? {
|
|
271
|
+
bytes: display.bytes,
|
|
272
|
+
contentType: display.copy.contentType
|
|
273
|
+
} : {
|
|
274
|
+
bytes,
|
|
275
|
+
contentType
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* The address a request to the link's page is counted under: the first
|
|
280
|
+
* forwarded address, which is the client's at Vercel's edge, else the
|
|
281
|
+
* literal `unknown`, which shares one budget rather than none.
|
|
282
|
+
*/ export function photoLinkCallerAddress(headers) {
|
|
283
|
+
var _headers_get;
|
|
284
|
+
var _forwarded_split_, _headers_get1;
|
|
285
|
+
const forwarded = (_headers_get = headers.get('x-forwarded-for')) != null ? _headers_get : '';
|
|
286
|
+
const first = (_forwarded_split_ = forwarded.split(',')[0]) == null ? void 0 : _forwarded_split_.trim();
|
|
287
|
+
return first || ((_headers_get1 = headers.get('x-real-ip')) == null ? void 0 : _headers_get1.trim()) || 'unknown';
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
//# sourceMappingURL=media-photo-links.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/media-photo-links.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 { createHash, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { encodeMediaDisplay, type loadSharp } from './media-variants'\n\n/** The sharp factory `loadSharp` answers. */\ntype SharpFactory = Awaited<ReturnType<typeof loadSharp>>\n\n/**\n * A SITE'S PHOTO LINK (AGL-3957): an address a site member hands to someone\n * with photos on their phone — the owner of the business the site is being\n * built for, at a booth or on a doorstep — so the photos land in the site's\n * media library without a sign-in.\n *\n * The link is `{origin}/p/{linkId}#{secret}`, and the page composes the\n * token `{linkId}.{secret}` from its path and its fragment. The secret rides\n * in the FRAGMENT because a fragment never leaves the browser: no request\n * line carries it, so no server or edge log, no analytics page view and no\n * `Referer` header ever holds a working link. The page sends the token to\n * the public route in a POST body. The database holds the SHA-256\n * of the secret and never the secret, the same shape as an emailed\n * confirmation link (`account-emails.ts`): a reader of the database cannot\n * upload to anybody's site. A link lives seven days, takes a bounded number\n * of photos and bytes, and can be revoked by any member who could have\n * minted it. Every upload it takes is stored AS THE MEMBER WHO MINTED IT,\n * through the media ingest's own door (`core.media-ingest`), so a member who\n * lost the site, a locked site, a takedown and the storage band refuse the\n * link's uploads exactly as they refuse that member's.\n *\n * Documents live in the top-level `photoLinks` collection, keyed by link id\n * and carrying the site: a token alone names no site, and a top-level\n * collection answers it in one read with no collection-group index. Only the\n * Admin SDK reads or writes them.\n */\n\nexport const PHOTO_LINKS_COLLECTION = 'photoLinks'\n\n/** Where the console serves the page a link opens. */\nexport const PHOTO_LINK_PATH = '/p'\n\n/** How long a link takes photos, from its minting. */\nexport const PHOTO_LINK_TTL_MS = 7 * 24 * 60 * 60 * 1000\n\n/** The most photos one link takes. */\nexport const PHOTO_LINK_MAX_UPLOADS = 40\n\n/** The most bytes one link takes, over all its photos, after they are stored. */\nexport const PHOTO_LINK_MAX_BYTES = 200 * 1024 * 1024\n\n/** The folder the link's photos are filed in, created in the site's library when the first link is minted. */\nexport const PHOTO_LINK_FOLDER_NAME = 'From the owner'\n\n/**\n * What the page accepts from the phone. The page re-encodes what it picks\n * (a HEIC, a 12 MB camera original) into one of these before it sends it, so\n * a format a browser cannot draw never reaches the server.\n */\nexport const PHOTO_LINK_TYPES: ReadonlySet<string> = new Set(['image/jpeg', 'image/png', 'image/webp'])\n\n/** The most bytes one photo may arrive as, before it is stored. */\nexport const PHOTO_LINK_PHOTO_MAX_BYTES = 8 * 1024 * 1024\n\n/** What one phone may ask of the link's page in a window, and how long the window is. */\nexport const PHOTO_LINK_RATE_LIMIT = Object.freeze({ limit: 80, windowMs: 10 * 60 * 1000 })\n\nexport interface PhotoLinkDoc {\n hostId: string\n /** The member the link's uploads are stored as. */\n createdBy: string\n createdAt: number\n expiresAt: number\n revokedAt?: number\n revokedBy?: string\n /** SHA-256 of the secret half of the token, hex. */\n digest: string\n /** The library folder the photos are filed in; null files them at the root. */\n folderId: string | null\n /** Photos stored through the link, and their stored bytes. */\n uploads: number\n bytes: number\n lastUploadAt?: number\n}\n\nexport type PhotoLinkState = 'live' | 'expired' | 'revoked' | 'full'\n\n/** What a link's page and its minter see of it. */\nexport interface PhotoLinkSummary {\n linkId: string\n state: PhotoLinkState\n createdAt: number\n expiresAt: number\n uploads: number\n bytes: number\n remainingUploads: number\n remainingBytes: number\n}\n\n/** A fresh token: the id the document is keyed by, the secret the link carries, and the digest the document keeps. */\nexport function mintPhotoLinkToken(): { linkId: string; secret: string; digest: string; token: string } {\n const linkId = randomBytes(12).toString('hex')\n const secret = randomBytes(24).toString('hex')\n return { linkId, secret, digest: photoLinkDigest(secret), token: `${linkId}.${secret}` }\n}\n\nexport function photoLinkDigest(secret: string): string {\n return createHash('sha256').update(secret).digest('hex')\n}\n\n/** The two halves of a token as the page received it, or null for anything that is not shaped like one. */\nexport function parsePhotoLinkToken(raw: unknown): { linkId: string; secret: string } | null {\n const token = String(raw ?? '').trim()\n const separator = token.indexOf('.')\n if (separator <= 0) return null\n const linkId = token.slice(0, separator)\n const secret = token.slice(separator + 1)\n if (!/^[a-f0-9]{24}$/.test(linkId) || !/^[a-f0-9]{48}$/.test(secret)) return null\n return { linkId, secret }\n}\n\n/** Constant-time: the stored digest against the secret the page presented. */\nexport function photoLinkSecretMatches(digest: unknown, secret: string): boolean {\n const expected = photoLinkDigest(secret)\n if (typeof digest !== 'string' || digest.length !== expected.length) return false\n return timingSafeEqual(Buffer.from(digest, 'hex'), Buffer.from(expected, 'hex'))\n}\n\n/**\n * The address the link opens, on the console origin given: the link id in\n * the path, the secret in the fragment, which the browser never sends.\n */\nexport function photoLinkUrl(origin: string, linkId: string, secret: string): string {\n return `${origin.replace(/\\/+$/, '')}${PHOTO_LINK_PATH}/${encodeURIComponent(linkId)}#${encodeURIComponent(secret)}`\n}\n\nexport function photoLinkState(doc: Pick<PhotoLinkDoc, 'expiresAt' | 'revokedAt' | 'uploads' | 'bytes'>, now = Date.now()): PhotoLinkState {\n if (doc.revokedAt) return 'revoked'\n if (now >= doc.expiresAt) return 'expired'\n if (doc.uploads >= PHOTO_LINK_MAX_UPLOADS || doc.bytes >= PHOTO_LINK_MAX_BYTES) return 'full'\n return 'live'\n}\n\nexport function photoLinkSummary(linkId: string, doc: PhotoLinkDoc, now = Date.now()): PhotoLinkSummary {\n return {\n linkId,\n state: photoLinkState(doc, now),\n createdAt: doc.createdAt,\n expiresAt: doc.expiresAt,\n uploads: doc.uploads,\n bytes: doc.bytes,\n remainingUploads: Math.max(0, PHOTO_LINK_MAX_UPLOADS - doc.uploads),\n remainingBytes: Math.max(0, PHOTO_LINK_MAX_BYTES - doc.bytes),\n }\n}\n\n/** The stored document, read defensively: a field the writer never set reads as its zero. */\nexport function readPhotoLinkDoc(data: Record<string, unknown> | undefined): PhotoLinkDoc | null {\n if (!data || typeof data['hostId'] !== 'string' || typeof data['digest'] !== 'string') return null\n const number = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)\n return {\n hostId: data['hostId'],\n createdBy: typeof data['createdBy'] === 'string' ? data['createdBy'] : '',\n createdAt: number(data['createdAt']),\n expiresAt: number(data['expiresAt']),\n ...(number(data['revokedAt']) ? { revokedAt: number(data['revokedAt']) } : {}),\n ...(typeof data['revokedBy'] === 'string' ? { revokedBy: data['revokedBy'] } : {}),\n digest: data['digest'],\n folderId: typeof data['folderId'] === 'string' && data['folderId'] ? data['folderId'] : null,\n uploads: number(data['uploads']),\n bytes: number(data['bytes']),\n ...(number(data['lastUploadAt']) ? { lastUploadAt: number(data['lastUploadAt']) } : {}),\n }\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport function photoLinkRef(firestore: Firestore, linkId: string): FirebaseFirestore.DocumentReference {\n return firestore.collection(PHOTO_LINKS_COLLECTION).doc(linkId)\n}\n\n/** Mints a link for the site as the member, and stores its document. The secret is returned once and never stored. */\nexport async function createPhotoLink(\n firestore: Firestore,\n input: { hostId: string; uid: string; folderId: string | null; now?: number },\n): Promise<{ linkId: string; secret: string; token: string; expiresAt: number }> {\n const now = input.now ?? Date.now()\n const minted = mintPhotoLinkToken()\n const doc: PhotoLinkDoc = {\n hostId: input.hostId,\n createdBy: input.uid,\n createdAt: now,\n expiresAt: now + PHOTO_LINK_TTL_MS,\n digest: minted.digest,\n folderId: input.folderId,\n uploads: 0,\n bytes: 0,\n }\n await photoLinkRef(firestore, minted.linkId).create(doc)\n return { linkId: minted.linkId, secret: minted.secret, token: minted.token, expiresAt: doc.expiresAt }\n}\n\nexport type PhotoLinkRefusal = 'invalid' | 'expired' | 'revoked' | 'full'\n\nexport type PhotoLinkLookup =\n | { ok: true; linkId: string; ref: FirebaseFirestore.DocumentReference; doc: PhotoLinkDoc; summary: PhotoLinkSummary }\n | { ok: false; reason: PhotoLinkRefusal }\n\n/**\n * The link a token names, when the token is well-formed, its document exists,\n * its secret matches and the link still takes photos. Every other case is a\n * refusal that says only what the page needs to tell the person holding the\n * phone; an unknown id and a wrong secret read the same.\n */\nexport async function readPhotoLinkByToken(firestore: Firestore, token: unknown, now = Date.now()): Promise<PhotoLinkLookup> {\n const parsed = parsePhotoLinkToken(token)\n if (!parsed) return { ok: false, reason: 'invalid' }\n const ref = photoLinkRef(firestore, parsed.linkId)\n const snapshot = await ref.get()\n const doc = readPhotoLinkDoc(snapshot.exists ? (snapshot.data() as Record<string, unknown>) : undefined)\n if (!doc || !photoLinkSecretMatches(doc.digest, parsed.secret)) return { ok: false, reason: 'invalid' }\n const state = photoLinkState(doc, now)\n if (state !== 'live') return { ok: false, reason: state }\n return { ok: true, linkId: parsed.linkId, ref, doc, summary: photoLinkSummary(parsed.linkId, doc, now) }\n}\n\n/**\n * Claims one photo's place on the link before its bytes are stored, inside a\n * transaction, so forty phones racing one link cannot store eighty photos.\n * `releasePhotoLinkUpload` gives the place back when the store refused.\n */\nexport async function claimPhotoLinkUpload(\n firestore: Firestore,\n ref: FirebaseFirestore.DocumentReference,\n bytes: number,\n now = Date.now(),\n): Promise<{ ok: true } | { ok: false; reason: PhotoLinkRefusal }> {\n return firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n const doc = readPhotoLinkDoc(snapshot.exists ? (snapshot.data() as Record<string, unknown>) : undefined)\n if (!doc) return { ok: false, reason: 'invalid' as const }\n const state = photoLinkState(doc, now)\n if (state !== 'live') return { ok: false, reason: state }\n if (doc.bytes + bytes > PHOTO_LINK_MAX_BYTES) return { ok: false, reason: 'full' as const }\n transaction.update(ref, { uploads: doc.uploads + 1, bytes: doc.bytes + bytes, lastUploadAt: now })\n return { ok: true as const }\n })\n}\n\nexport async function releasePhotoLinkUpload(\n firestore: Firestore,\n ref: FirebaseFirestore.DocumentReference,\n bytes: number,\n): Promise<void> {\n await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n const doc = readPhotoLinkDoc(snapshot.exists ? (snapshot.data() as Record<string, unknown>) : undefined)\n if (!doc) return\n transaction.update(ref, { uploads: Math.max(0, doc.uploads - 1), bytes: Math.max(0, doc.bytes - bytes) })\n })\n}\n\n/** Marks the link revoked. Idempotent; a link of another site is left alone and reported as not found. */\nexport async function revokePhotoLink(\n firestore: Firestore,\n input: { hostId: string; linkId: string; uid: string; now?: number },\n): Promise<boolean> {\n const ref = photoLinkRef(firestore, input.linkId)\n const snapshot = await ref.get()\n const doc = readPhotoLinkDoc(snapshot.exists ? (snapshot.data() as Record<string, unknown>) : undefined)\n if (!doc || doc.hostId !== input.hostId) return false\n if (doc.revokedAt) return true\n await ref.update({ revokedAt: input.now ?? Date.now(), revokedBy: input.uid })\n return true\n}\n\n/** The site's links that still take photos, newest first. */\nexport async function listLivePhotoLinks(firestore: Firestore, hostId: string, now = Date.now()): Promise<PhotoLinkSummary[]> {\n const snapshot = await firestore\n .collection(PHOTO_LINKS_COLLECTION)\n .where('hostId', '==', hostId)\n .where('expiresAt', '>', now)\n .limit(50)\n .get()\n const live: PhotoLinkSummary[] = []\n for (const document of snapshot.docs) {\n const doc = readPhotoLinkDoc(document.data() as Record<string, unknown>)\n if (!doc) continue\n const summary = photoLinkSummary(document.id, doc, now)\n if (summary.state === 'live') live.push(summary)\n }\n return live.sort((a, b) => b.createdAt - a.createdAt)\n}\n\n/**\n * The bytes a link's photo is stored as: oriented the way the phone held it,\n * no wider than the delivery edge, and carrying no EXIF, XMP or IPTC — so a\n * photo's GPS position, taken in somebody's driveway, never reaches the\n * library. The display encoder already does exactly this for a delivery\n * copy; here its answer IS the original. A photo that carries nothing and\n * needs no turning is stored as it came.\n */\nexport async function storedPhotoLinkBytes(\n sharp: SharpFactory,\n bytes: Buffer,\n contentType: string,\n): Promise<{ bytes: Buffer; contentType: string }> {\n const display = await encodeMediaDisplay(sharp, bytes, contentType)\n return display ? { bytes: display.bytes, contentType: display.copy.contentType } : { bytes, contentType }\n}\n\n/**\n * The address a request to the link's page is counted under: the first\n * forwarded address, which is the client's at Vercel's edge, else the\n * literal `unknown`, which shares one budget rather than none.\n */\nexport function photoLinkCallerAddress(headers: { get(name: string): string | null }): string {\n const forwarded = headers.get('x-forwarded-for') ?? ''\n const first = forwarded.split(',')[0]?.trim()\n return first || headers.get('x-real-ip')?.trim() || 'unknown'\n}\n"],"names":["createHash","randomBytes","timingSafeEqual","encodeMediaDisplay","PHOTO_LINKS_COLLECTION","PHOTO_LINK_PATH","PHOTO_LINK_TTL_MS","PHOTO_LINK_MAX_UPLOADS","PHOTO_LINK_MAX_BYTES","PHOTO_LINK_FOLDER_NAME","PHOTO_LINK_TYPES","Set","PHOTO_LINK_PHOTO_MAX_BYTES","PHOTO_LINK_RATE_LIMIT","Object","freeze","limit","windowMs","mintPhotoLinkToken","linkId","toString","secret","digest","photoLinkDigest","token","update","parsePhotoLinkToken","raw","String","trim","separator","indexOf","slice","test","photoLinkSecretMatches","expected","length","Buffer","from","photoLinkUrl","origin","replace","encodeURIComponent","photoLinkState","doc","now","Date","revokedAt","expiresAt","uploads","bytes","photoLinkSummary","state","createdAt","remainingUploads","Math","max","remainingBytes","readPhotoLinkDoc","data","number","value","Number","isFinite","hostId","createdBy","revokedBy","folderId","lastUploadAt","photoLinkRef","firestore","collection","createPhotoLink","input","minted","uid","create","readPhotoLinkByToken","parsed","ok","reason","ref","snapshot","get","exists","undefined","summary","claimPhotoLinkUpload","runTransaction","transaction","releasePhotoLinkUpload","revokePhotoLink","listLivePhotoLinks","where","live","document","docs","id","push","sort","a","b","storedPhotoLinkBytes","sharp","contentType","display","copy","photoLinkCallerAddress","headers","forwarded","first","split"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,WAAW,EAAEC,eAAe,QAAQ,cAAa;AACtE,SAASC,kBAAkB,QAAwB,sBAAkB;AAKrE;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GAED,OAAO,MAAMC,yBAAyB,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AASG,uBAAuBC,OAA6C;QAChEA;QACJC,mBACED;IAFhB,MAAMC,aAAYD,eAAAA,QAAQzB,GAAG,CAAC,8BAAZyB,eAAkC;IACpD,MAAME,SAAQD,oBAAAA,UAAUE,KAAK,CAAC,IAAI,CAAC,EAAE,qBAAvBF,kBAAyBhF,IAAI;IAC3C,OAAOiF,WAASF,gBAAAA,QAAQzB,GAAG,CAAC,iCAAZyB,cAA0B/E,IAAI,OAAM;AACtD"}
|
|
@@ -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 } from '@aglyn/aglyn/server';
|
|
17
|
+
import { hasInlineOrgBilling, type OrgBillingDoc, type OrgInlineBilling, type AiTierId } 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,7 +82,9 @@ 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'
|
|
85
|
+
export declare function writeOrgBilling(orgId: string, patch: Partial<OrgBillingDoc> & Pick<OrgInlineBilling, 'seatAddons'> & {
|
|
86
|
+
aiTier?: AiTierId | null;
|
|
87
|
+
}, options?: {
|
|
86
88
|
writeInline?: boolean;
|
|
87
89
|
}): Promise<void>;
|
|
88
90
|
/**
|
|
@@ -197,6 +197,11 @@ 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
|
+
}
|
|
200
205
|
if (Object.keys(orgPatch).length) batch.set(orgRef, orgPatch, {
|
|
201
206
|
merge: true
|
|
202
207
|
});
|
|
@@ -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} 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> & 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","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,QAGf,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,CA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AaZ,MAAM,CAACC,MAAM;IAChC,IAAI,OAAOW,eAAe,YAAYA,YAAY;QAChDV,MAAME,GAAG,CACPhC,KAAKU,UAAU,CAACf,kCAAkCU,GAAG,CAACmC,aACtD;YAAE/B;YAAOgC,WAAW1C,cAAcG,SAAS,CAACwC,UAAU,CAACC,eAAe;QAAG,GACzE;YAAEV,OAAO;QAAK;IAElB;IAEA,MAAMH,MAAMc,MAAM;AACpB;AAEA;;;;;;CAMC,GACD,OAAO,eAAeC,0BACpBL,UAAkB;;QAcXM;IAZP,IAAI,CAACN,YAAY,OAAO;IACxB,MAAMO,UAAU,MAAM/C,KACnBU,UAAU,CAACf,kCACXU,GAAG,CAACmC,YACJ1B,GAAG;IACN,MAAMkC,SAASD,QAAQjC,GAAG,CAAC;IAC3B,IAAI,OAAOkC,WAAW,YAAYA,QAAQ,OAAOA;IACjD,MAAMF,SAAS,MAAM9C,KAClBU,UAAU,CAAC,QACXuC,KAAK,CAAC,oBAAoB,MAAMT,YAChCU,KAAK,CAAC,GACNpC,GAAG;IACN,gBAAOgC,gBAAAA,OAAOK,IAAI,CAAC,EAAE,qBAAdL,cAAgBM,EAAE,mBAAI;AAC/B;AAEA,gFAAgF,GAChF,SAASxD,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 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;IACpD,wEAAwE;IACxE,0EAA0E;IAC1E,2DAA2D;IAC3D,OAAOY,MAAM,CAACZ,8BAA8B;IAC5C,IAAIH,sBAAsB,OAAOe;IACjC,6DAA6D;IAC7DA,MAAM,CAAC,mBAAmB,GAAIC,iBAAAA,SAAU;IACxC,OAAOD;AACT;AAEA,mCAAmC,GACnC,OAAO,SAASE,cAAcC,KAAa;IACzC,OAAOT,KACJU,UAAU,CAAC,QACXL,GAAG,CAACI,OACJC,UAAU,CAACjB,2BACXY,GAAG,CAACb;AACT;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAemB,eAAeF,KAAa;IAChD,IAAI,CAACA,OAAO,OAAO,CAAC;IACpB,OAAOL,mBAAmB,MAAMQ,qBAAqBH;AACvD;AAEA;;;;;;;;;CASC,GACD,eAAeG,qBAAqBH,KAAa;IAC/C,MAAMI,kBAAkB,MAAML,cAAcC,OAAOK,GAAG;IACtD,IAAID,gBAAgBE,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A,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"}
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
* and the projections the security rules authorize against are never
|
|
21
21
|
* client-writable (docs/MULTI_TENANT_FIRESTORE.md §8).
|
|
22
22
|
*/
|
|
23
|
-
import { type ConsentGroup, type AglynOrganization, type AglynOrgBilling, type AglynOrgMember, type HostAccessRole, type OrgPermission, type OrgRole, type OwnerHandoffPreviousOwner } from '@aglyn/aglyn/server';
|
|
23
|
+
import { type ConsentGroup, type AglynOrganization, type AglynOrgBilling, type AglynOrgMember, type HostAccessRole, type OrgPermission, type OrgPlan, type OrgRole, type OwnerHandoffPreviousOwner } from '@aglyn/aglyn/server';
|
|
24
|
+
import type { OrgOverrideReasonCode } from '@aglyn/aglyn/app-utils/org-override-reason';
|
|
24
25
|
import type { PluginActivityTargetType } from '@aglyn/aglyn/plugin-manager/plugin-activity-actions';
|
|
25
26
|
import type { HostActivityActor } from '@aglyn/aglyn/app-utils/activity-presenter';
|
|
26
27
|
export declare class OrgSlugTakenError extends Error {
|
|
@@ -109,6 +110,29 @@ export interface CreateOrganizationOptions {
|
|
|
109
110
|
* leaves the prospect's one Free seat free for the prospect.
|
|
110
111
|
*/
|
|
111
112
|
ownerStaffSeat?: boolean;
|
|
113
|
+
/**
|
|
114
|
+
* A staff comp granted at birth (AGL-3952).
|
|
115
|
+
*
|
|
116
|
+
* A workspace staff build for a prospect used to be two trips: create it
|
|
117
|
+
* from the picker, then open its staff page and grant the comp from the
|
|
118
|
+
* override dialog. The second trip is the one a booth build cannot afford,
|
|
119
|
+
* and nothing about it needs the workspace to exist first — so the comp
|
|
120
|
+
* rides the creation transaction, as `entitlements.planComp` on the org
|
|
121
|
+
* document and an `org.override` audit row beside it, exactly as the
|
|
122
|
+
* override route would have written them a minute later.
|
|
123
|
+
*
|
|
124
|
+
* Always capped: this is a sales trial, and an uncapped comp is for an
|
|
125
|
+
* internal workspace. Only `/api/orgs/create` sets it, from a token with
|
|
126
|
+
* the `staff` claim; a self-serve caller can never reach it.
|
|
127
|
+
*/
|
|
128
|
+
planComp?: {
|
|
129
|
+
plan: OrgPlan;
|
|
130
|
+
reason: OrgOverrideReasonCode;
|
|
131
|
+
/** Staff-only rationale; explicit `null` when none was given. */
|
|
132
|
+
note: string | null;
|
|
133
|
+
/** The staff uid that granted it — the creator. */
|
|
134
|
+
grantedBy: string;
|
|
135
|
+
};
|
|
112
136
|
}
|
|
113
137
|
/**
|
|
114
138
|
* Creates an org in one transaction: slug reservation (uniqueness), org
|
|
@@ -33,6 +33,7 @@ import { ORG_LANDED_AT_PATH } from "@aglyn/aglyn/app-utils/health-report";
|
|
|
33
33
|
import { runPluginDeclarationsRepair } from "@aglyn/aglyn/plugin-manager/plugin-declarations-repair";
|
|
34
34
|
import { FieldValue } from "firebase-admin/firestore";
|
|
35
35
|
import { cache } from "react";
|
|
36
|
+
import { setAdminAudit } from "./admin-audit-write.js";
|
|
36
37
|
import { findUserByUidAcrossPools } from "./auth-pools.js";
|
|
37
38
|
import firebaseAdmin from "./firebase-admin.js";
|
|
38
39
|
import { enforceFreeWorkspaceCapInTransaction, readFreeWorkspaceCapConfig } from "./free-workspace-cap.js";
|
|
@@ -225,7 +226,7 @@ reservation, now = Date.now()) {
|
|
|
225
226
|
* this case anyway. `writeOrgBilling` merge-sets, so the first real
|
|
226
227
|
* subscription composes with this rather than racing it.
|
|
227
228
|
*/ tx.set(db.collection('orgs').doc(orgId).collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID), {});
|
|
228
|
-
tx.set(db.collection('orgs').doc(orgId), {
|
|
229
|
+
tx.set(db.collection('orgs').doc(orgId), _extends({
|
|
229
230
|
name,
|
|
230
231
|
/*
|
|
231
232
|
* The searchable form of `name`, written beside it (AGL-2501).
|
|
@@ -274,7 +275,66 @@ reservation, now = Date.now()) {
|
|
|
274
275
|
// (`ORG_LANDED_AT_PATH`). Written `null`, not left out, because a
|
|
275
276
|
// missing field is how the check recognizes an org made before it.
|
|
276
277
|
[ORG_LANDED_AT_PATH]: null
|
|
277
|
-
}
|
|
278
|
+
}, options.planComp ? {
|
|
279
|
+
entitlements: {
|
|
280
|
+
planComp: {
|
|
281
|
+
plan: options.planComp.plan,
|
|
282
|
+
uncapped: false,
|
|
283
|
+
reason: options.planComp.reason,
|
|
284
|
+
note: options.planComp.note,
|
|
285
|
+
grantedBy: options.planComp.grantedBy,
|
|
286
|
+
grantedAt: FieldValue.serverTimestamp()
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
} : {}));
|
|
290
|
+
if (options.planComp) {
|
|
291
|
+
// The row that explains the comp, in the same transaction as the org
|
|
292
|
+
// (AGL-1784's property, kept): the Audit Log reads a booth build like a
|
|
293
|
+
// comp granted by hand, with `before` the nothing a new org is and
|
|
294
|
+
// `planEffect` saying what the act left it on.
|
|
295
|
+
setAdminAudit(tx, db, {
|
|
296
|
+
actorUid: options.planComp.grantedBy,
|
|
297
|
+
action: 'org.override',
|
|
298
|
+
target: `orgs/${orgId}`,
|
|
299
|
+
before: {
|
|
300
|
+
plan: null,
|
|
301
|
+
entitlements: null,
|
|
302
|
+
releaseFlags: null
|
|
303
|
+
},
|
|
304
|
+
after: {
|
|
305
|
+
plan: null,
|
|
306
|
+
entitlements: {
|
|
307
|
+
planComp: {
|
|
308
|
+
plan: options.planComp.plan,
|
|
309
|
+
uncapped: false,
|
|
310
|
+
reason: options.planComp.reason,
|
|
311
|
+
note: options.planComp.note,
|
|
312
|
+
grantedBy: options.planComp.grantedBy,
|
|
313
|
+
grantedAt: FieldValue.serverTimestamp()
|
|
314
|
+
}
|
|
315
|
+
},
|
|
316
|
+
releaseFlags: null
|
|
317
|
+
},
|
|
318
|
+
reason: options.planComp.reason,
|
|
319
|
+
note: options.planComp.note,
|
|
320
|
+
planEffect: {
|
|
321
|
+
before: {
|
|
322
|
+
effectivePlan: 'free',
|
|
323
|
+
decidedBy: 'no-plan',
|
|
324
|
+
uncapped: false
|
|
325
|
+
},
|
|
326
|
+
after: {
|
|
327
|
+
effectivePlan: options.planComp.plan,
|
|
328
|
+
decidedBy: 'comp',
|
|
329
|
+
compInForce: true,
|
|
330
|
+
uncapped: false
|
|
331
|
+
},
|
|
332
|
+
compChange: 'granted',
|
|
333
|
+
planChange: 'unchanged'
|
|
334
|
+
},
|
|
335
|
+
at: FieldValue.serverTimestamp()
|
|
336
|
+
});
|
|
337
|
+
}
|
|
278
338
|
tx.set(db.collection('orgs').doc(orgId).collection('members').doc(ownerUid), _extends({
|
|
279
339
|
role: 'owner',
|
|
280
340
|
allHosts: true,
|