@aglyn/tenant-data-admin 1.0.0-beta.268 → 1.0.0-beta.270

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/package.json +7 -7
  2. package/src/lib/render-cache.d.ts +10 -3
  3. package/src/lib/render-cache.js +10 -3
  4. package/src/lib/render-cache.js.map +1 -1
  5. package/src/lib/server/billing-addons.d.ts +8 -6
  6. package/src/lib/server/billing-addons.js +19 -8
  7. package/src/lib/server/billing-addons.js.map +1 -1
  8. package/src/lib/server/configured-url-fetch.d.ts +26 -0
  9. package/src/lib/server/configured-url-fetch.js +68 -0
  10. package/src/lib/server/configured-url-fetch.js.map +1 -1
  11. package/src/lib/server/custom-domain-redirects.d.ts +50 -0
  12. package/src/lib/server/custom-domain-redirects.js +61 -0
  13. package/src/lib/server/custom-domain-redirects.js.map +1 -0
  14. package/src/lib/server/host-custom-domain.d.ts +125 -0
  15. package/src/lib/server/host-custom-domain.js +395 -0
  16. package/src/lib/server/host-custom-domain.js.map +1 -0
  17. package/src/lib/server/host-released-names.d.ts +1 -2
  18. package/src/lib/server/host-released-names.js +4 -2
  19. package/src/lib/server/host-released-names.js.map +1 -1
  20. package/src/lib/server/media-photo-links.d.ts +196 -0
  21. package/src/lib/server/media-photo-links.js +290 -0
  22. package/src/lib/server/media-photo-links.js.map +1 -0
  23. package/src/lib/server/organizations.d.ts +25 -1
  24. package/src/lib/server/organizations.js +62 -2
  25. package/src/lib/server/organizations.js.map +1 -1
  26. package/src/lib/server/personal-data-export.js +21 -1
  27. package/src/lib/server/personal-data-export.js.map +1 -1
  28. package/src/lib/server/push-delivery.js +32 -14
  29. package/src/lib/server/push-delivery.js.map +1 -1
  30. package/src/lib/server/tenant-dns-check.d.ts +58 -0
  31. package/src/lib/server/tenant-dns-check.js +197 -0
  32. package/src/lib/server/tenant-dns-check.js.map +1 -0
  33. package/src/tenancy.d.ts +4 -0
  34. package/src/tenancy.js +8 -0
  35. package/src/tenancy.js.map +1 -1
@@ -0,0 +1,196 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type loadSharp } from './media-variants';
18
+ /** The sharp factory `loadSharp` answers. */
19
+ type SharpFactory = Awaited<ReturnType<typeof loadSharp>>;
20
+ /**
21
+ * A SITE'S PHOTO LINK (AGL-3957): an address a site member hands to someone
22
+ * with photos on their phone — the owner of the business the site is being
23
+ * built for, at a booth or on a doorstep — so the photos land in the site's
24
+ * media library without a sign-in.
25
+ *
26
+ * The link is `{origin}/p/{linkId}#{secret}`, and the page composes the
27
+ * token `{linkId}.{secret}` from its path and its fragment. The secret rides
28
+ * in the FRAGMENT because a fragment never leaves the browser: no request
29
+ * line carries it, so no server or edge log, no analytics page view and no
30
+ * `Referer` header ever holds a working link. The page sends the token to
31
+ * the public route in a POST body. The database holds the SHA-256
32
+ * of the secret and never the secret, the same shape as an emailed
33
+ * confirmation link (`account-emails.ts`): a reader of the database cannot
34
+ * upload to anybody's site. A link lives seven days, takes a bounded number
35
+ * of photos and bytes, and can be revoked by any member who could have
36
+ * minted it. Every upload it takes is stored AS THE MEMBER WHO MINTED IT,
37
+ * through the media ingest's own door (`core.media-ingest`), so a member who
38
+ * lost the site, a locked site, a takedown and the storage band refuse the
39
+ * link's uploads exactly as they refuse that member's.
40
+ *
41
+ * Documents live in the top-level `photoLinks` collection, keyed by link id
42
+ * and carrying the site: a token alone names no site, and a top-level
43
+ * collection answers it in one read with no collection-group index. Only the
44
+ * Admin SDK reads or writes them.
45
+ */
46
+ export declare const PHOTO_LINKS_COLLECTION = "photoLinks";
47
+ /** Where the console serves the page a link opens. */
48
+ export declare const PHOTO_LINK_PATH = "/p";
49
+ /** How long a link takes photos, from its minting. */
50
+ export declare const PHOTO_LINK_TTL_MS: number;
51
+ /** The most photos one link takes. */
52
+ export declare const PHOTO_LINK_MAX_UPLOADS = 40;
53
+ /** The most bytes one link takes, over all its photos, after they are stored. */
54
+ export declare const PHOTO_LINK_MAX_BYTES: number;
55
+ /** The folder the link's photos are filed in, created in the site's library when the first link is minted. */
56
+ export declare const PHOTO_LINK_FOLDER_NAME = "From the owner";
57
+ /**
58
+ * What the page accepts from the phone. The page re-encodes what it picks
59
+ * (a HEIC, a 12 MB camera original) into one of these before it sends it, so
60
+ * a format a browser cannot draw never reaches the server.
61
+ */
62
+ export declare const PHOTO_LINK_TYPES: ReadonlySet<string>;
63
+ /** The most bytes one photo may arrive as, before it is stored. */
64
+ export declare const PHOTO_LINK_PHOTO_MAX_BYTES: number;
65
+ /** What one phone may ask of the link's page in a window, and how long the window is. */
66
+ export declare const PHOTO_LINK_RATE_LIMIT: Readonly<{
67
+ limit: 80;
68
+ windowMs: number;
69
+ }>;
70
+ export interface PhotoLinkDoc {
71
+ hostId: string;
72
+ /** The member the link's uploads are stored as. */
73
+ createdBy: string;
74
+ createdAt: number;
75
+ expiresAt: number;
76
+ revokedAt?: number;
77
+ revokedBy?: string;
78
+ /** SHA-256 of the secret half of the token, hex. */
79
+ digest: string;
80
+ /** The library folder the photos are filed in; null files them at the root. */
81
+ folderId: string | null;
82
+ /** Photos stored through the link, and their stored bytes. */
83
+ uploads: number;
84
+ bytes: number;
85
+ lastUploadAt?: number;
86
+ }
87
+ export type PhotoLinkState = 'live' | 'expired' | 'revoked' | 'full';
88
+ /** What a link's page and its minter see of it. */
89
+ export interface PhotoLinkSummary {
90
+ linkId: string;
91
+ state: PhotoLinkState;
92
+ createdAt: number;
93
+ expiresAt: number;
94
+ uploads: number;
95
+ bytes: number;
96
+ remainingUploads: number;
97
+ remainingBytes: number;
98
+ }
99
+ /** A fresh token: the id the document is keyed by, the secret the link carries, and the digest the document keeps. */
100
+ export declare function mintPhotoLinkToken(): {
101
+ linkId: string;
102
+ secret: string;
103
+ digest: string;
104
+ token: string;
105
+ };
106
+ export declare function photoLinkDigest(secret: string): string;
107
+ /** The two halves of a token as the page received it, or null for anything that is not shaped like one. */
108
+ export declare function parsePhotoLinkToken(raw: unknown): {
109
+ linkId: string;
110
+ secret: string;
111
+ } | null;
112
+ /** Constant-time: the stored digest against the secret the page presented. */
113
+ export declare function photoLinkSecretMatches(digest: unknown, secret: string): boolean;
114
+ /**
115
+ * The address the link opens, on the console origin given: the link id in
116
+ * the path, the secret in the fragment, which the browser never sends.
117
+ */
118
+ export declare function photoLinkUrl(origin: string, linkId: string, secret: string): string;
119
+ export declare function photoLinkState(doc: Pick<PhotoLinkDoc, 'expiresAt' | 'revokedAt' | 'uploads' | 'bytes'>, now?: number): PhotoLinkState;
120
+ export declare function photoLinkSummary(linkId: string, doc: PhotoLinkDoc, now?: number): PhotoLinkSummary;
121
+ /** The stored document, read defensively: a field the writer never set reads as its zero. */
122
+ export declare function readPhotoLinkDoc(data: Record<string, unknown> | undefined): PhotoLinkDoc | null;
123
+ type Firestore = FirebaseFirestore.Firestore;
124
+ export declare function photoLinkRef(firestore: Firestore, linkId: string): FirebaseFirestore.DocumentReference;
125
+ /** Mints a link for the site as the member, and stores its document. The secret is returned once and never stored. */
126
+ export declare function createPhotoLink(firestore: Firestore, input: {
127
+ hostId: string;
128
+ uid: string;
129
+ folderId: string | null;
130
+ now?: number;
131
+ }): Promise<{
132
+ linkId: string;
133
+ secret: string;
134
+ token: string;
135
+ expiresAt: number;
136
+ }>;
137
+ export type PhotoLinkRefusal = 'invalid' | 'expired' | 'revoked' | 'full';
138
+ export type PhotoLinkLookup = {
139
+ ok: true;
140
+ linkId: string;
141
+ ref: FirebaseFirestore.DocumentReference;
142
+ doc: PhotoLinkDoc;
143
+ summary: PhotoLinkSummary;
144
+ } | {
145
+ ok: false;
146
+ reason: PhotoLinkRefusal;
147
+ };
148
+ /**
149
+ * The link a token names, when the token is well-formed, its document exists,
150
+ * its secret matches and the link still takes photos. Every other case is a
151
+ * refusal that says only what the page needs to tell the person holding the
152
+ * phone; an unknown id and a wrong secret read the same.
153
+ */
154
+ export declare function readPhotoLinkByToken(firestore: Firestore, token: unknown, now?: number): Promise<PhotoLinkLookup>;
155
+ /**
156
+ * Claims one photo's place on the link before its bytes are stored, inside a
157
+ * transaction, so forty phones racing one link cannot store eighty photos.
158
+ * `releasePhotoLinkUpload` gives the place back when the store refused.
159
+ */
160
+ export declare function claimPhotoLinkUpload(firestore: Firestore, ref: FirebaseFirestore.DocumentReference, bytes: number, now?: number): Promise<{
161
+ ok: true;
162
+ } | {
163
+ ok: false;
164
+ reason: PhotoLinkRefusal;
165
+ }>;
166
+ export declare function releasePhotoLinkUpload(firestore: Firestore, ref: FirebaseFirestore.DocumentReference, bytes: number): Promise<void>;
167
+ /** Marks the link revoked. Idempotent; a link of another site is left alone and reported as not found. */
168
+ export declare function revokePhotoLink(firestore: Firestore, input: {
169
+ hostId: string;
170
+ linkId: string;
171
+ uid: string;
172
+ now?: number;
173
+ }): Promise<boolean>;
174
+ /** The site's links that still take photos, newest first. */
175
+ export declare function listLivePhotoLinks(firestore: Firestore, hostId: string, now?: number): Promise<PhotoLinkSummary[]>;
176
+ /**
177
+ * The bytes a link's photo is stored as: oriented the way the phone held it,
178
+ * no wider than the delivery edge, and carrying no EXIF, XMP or IPTC — so a
179
+ * photo's GPS position, taken in somebody's driveway, never reaches the
180
+ * library. The display encoder already does exactly this for a delivery
181
+ * copy; here its answer IS the original. A photo that carries nothing and
182
+ * needs no turning is stored as it came.
183
+ */
184
+ export declare function storedPhotoLinkBytes(sharp: SharpFactory, bytes: Buffer, contentType: string): Promise<{
185
+ bytes: Buffer;
186
+ contentType: string;
187
+ }>;
188
+ /**
189
+ * The address a request to the link's page is counted under: the first
190
+ * forwarded address, which is the client's at Vercel's edge, else the
191
+ * literal `unknown`, which shares one budget rather than none.
192
+ */
193
+ export declare function photoLinkCallerAddress(headers: {
194
+ get(name: string): string | null;
195
+ }): string;
196
+ export {};
@@ -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,aAAY;AAElD,oDAAoD,GACpD,OAAO,MAAMC,kBAAkB,KAAI;AAEnC,oDAAoD,GACpD,OAAO,MAAMC,oBAAoB,IAAI,KAAK,KAAK,KAAK,KAAI;AAExD,oCAAoC,GACpC,OAAO,MAAMC,yBAAyB,GAAE;AAExC,+EAA+E,GAC/E,OAAO,MAAMC,uBAAuB,MAAM,OAAO,KAAI;AAErD,4GAA4G,GAC5G,OAAO,MAAMC,yBAAyB,iBAAgB;AAEtD;;;;CAIC,GACD,OAAO,MAAMC,mBAAwC,IAAIC,IAAI;IAAC;IAAc;IAAa;CAAa,EAAC;AAEvG,iEAAiE,GACjE,OAAO,MAAMC,6BAA6B,IAAI,OAAO,KAAI;AAEzD,uFAAuF,GACvF,OAAO,MAAMC,wBAAwBC,OAAOC,MAAM,CAAC;IAAEC,OAAO;IAAIC,UAAU,KAAK,KAAK;AAAK,GAAE;AAkC3F,oHAAoH,GACpH,OAAO,SAASC;IACd,MAAMC,SAASlB,YAAY,IAAImB,QAAQ,CAAC;IACxC,MAAMC,SAASpB,YAAY,IAAImB,QAAQ,CAAC;IACxC,OAAO;QAAED;QAAQE;QAAQC,QAAQC,gBAAgBF;QAASG,OAAO,GA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EAAE,EAAErD,KAAKC;QACnD,IAAIyC,QAAQlC,KAAK,KAAK,QAAQ0C,KAAKI,IAAI,CAACZ;IAC1C;IACA,OAAOQ,KAAKK,IAAI,CAAC,CAACC,GAAGC,IAAMA,EAAEhD,SAAS,GAAG+C,EAAE/C,SAAS;AACtD;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeiD,qBACpBC,KAAmB,EACnBrD,KAAa,EACbsD,WAAmB;IAEnB,MAAMC,UAAU,MAAMtG,mBAAmBoG,OAAOrD,OAAOsD;IACvD,OAAOC,UAAU;QAAEvD,OAAOuD,QAAQvD,KAAK;QAAEsD,aAAaC,QAAQC,IAAI,CAACF,WAAW;IAAC,IAAI;QAAEtD;QAAOsD;IAAY;AAC1G;AAEA;;;;CAIC,GACD,OAAO,SAASG,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"}
@@ -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,