@tumbaland/backend-core 1.43.0 → 1.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/package.json +5 -1
  2. package/.versionrc.json +0 -7
  3. package/__mocks__/uuid.js +0 -8
  4. package/jest.config.js +0 -24
  5. package/src/apiKeys/ApiKey.test.ts +0 -142
  6. package/src/apiKeys/ApiKey.ts +0 -102
  7. package/src/apiKeys/crypto.test.ts +0 -161
  8. package/src/apiKeys/crypto.ts +0 -163
  9. package/src/apiKeys/index.test.ts +0 -72
  10. package/src/apiKeys/index.ts +0 -35
  11. package/src/apiKeys/middleware.test.ts +0 -651
  12. package/src/apiKeys/middleware.ts +0 -341
  13. package/src/apiKeys/service.test.ts +0 -401
  14. package/src/apiKeys/service.ts +0 -168
  15. package/src/apiKeys/types.test.ts +0 -41
  16. package/src/apiKeys/types.ts +0 -124
  17. package/src/app/createBaseApp.test.ts +0 -109
  18. package/src/app/createBaseApp.ts +0 -102
  19. package/src/app/shutdown.test.ts +0 -129
  20. package/src/app/shutdown.ts +0 -81
  21. package/src/audit/AuditEvent.ts +0 -123
  22. package/src/audit/actor.test.ts +0 -95
  23. package/src/audit/actor.ts +0 -68
  24. package/src/audit/context.test.ts +0 -91
  25. package/src/audit/context.ts +0 -83
  26. package/src/audit/index.ts +0 -11
  27. package/src/audit/plugin.test.ts +0 -258
  28. package/src/audit/plugin.ts +0 -254
  29. package/src/audit/reads.test.ts +0 -164
  30. package/src/audit/reads.ts +0 -88
  31. package/src/audit/service.test.ts +0 -115
  32. package/src/audit/service.ts +0 -95
  33. package/src/auth/session.test.ts +0 -89
  34. package/src/auth/session.ts +0 -75
  35. package/src/config/env.test.ts +0 -28
  36. package/src/config/env.ts +0 -13
  37. package/src/database/connection.test.ts +0 -188
  38. package/src/database/connection.ts +0 -90
  39. package/src/entitlements/UsageMeter.ts +0 -49
  40. package/src/entitlements/client.test.ts +0 -200
  41. package/src/entitlements/client.ts +0 -179
  42. package/src/entitlements/definitions.test.ts +0 -161
  43. package/src/entitlements/definitions.ts +0 -268
  44. package/src/entitlements/index.ts +0 -42
  45. package/src/entitlements/middleware.test.ts +0 -196
  46. package/src/entitlements/middleware.ts +0 -150
  47. package/src/entitlements/reconcile.test.ts +0 -333
  48. package/src/entitlements/reconcile.ts +0 -384
  49. package/src/entitlements/types.ts +0 -21
  50. package/src/entitlements/usage.test.ts +0 -314
  51. package/src/entitlements/usage.ts +0 -223
  52. package/src/errors/HttpError.test.ts +0 -76
  53. package/src/errors/HttpError.ts +0 -91
  54. package/src/groups/client.test.ts +0 -215
  55. package/src/groups/client.ts +0 -182
  56. package/src/groups/index.ts +0 -7
  57. package/src/groups/membership.test.ts +0 -84
  58. package/src/groups/membership.ts +0 -133
  59. package/src/groups/subject.test.ts +0 -85
  60. package/src/groups/subject.ts +0 -50
  61. package/src/health/createHealthCheck.test.ts +0 -89
  62. package/src/health/createHealthCheck.ts +0 -67
  63. package/src/health/healthController.test.ts +0 -113
  64. package/src/health/healthController.ts +0 -56
  65. package/src/index.ts +0 -88
  66. package/src/logging/logger.test.ts +0 -91
  67. package/src/logging/logger.ts +0 -103
  68. package/src/metrics/index.test.ts +0 -116
  69. package/src/metrics/index.ts +0 -111
  70. package/src/middleware/authMiddleware.test.ts +0 -275
  71. package/src/middleware/authMiddleware.ts +0 -91
  72. package/src/middleware/corsMiddleware.test.ts +0 -135
  73. package/src/middleware/corsMiddleware.ts +0 -65
  74. package/src/middleware/errorHandler.test.ts +0 -188
  75. package/src/middleware/errorHandler.ts +0 -103
  76. package/src/middleware/internalServiceAuth.test.ts +0 -173
  77. package/src/middleware/internalServiceAuth.ts +0 -96
  78. package/src/middleware/requestLogger.test.ts +0 -81
  79. package/src/middleware/requestLogger.ts +0 -48
  80. package/src/middleware/security.test.ts +0 -45
  81. package/src/middleware/security.ts +0 -43
  82. package/src/middleware/validate.test.ts +0 -72
  83. package/src/middleware/validate.ts +0 -23
  84. package/src/oauth/index.ts +0 -29
  85. package/src/oauth/models.ts +0 -164
  86. package/src/oauth/service.test.ts +0 -432
  87. package/src/oauth/service.ts +0 -299
  88. package/src/oauth/tokens.test.ts +0 -146
  89. package/src/oauth/tokens.ts +0 -186
  90. package/src/testing/serviceTestSetup.ts +0 -17
  91. package/src/tracing/index.test.ts +0 -272
  92. package/src/tracing/index.ts +0 -110
  93. package/src/types/auth.ts +0 -45
  94. package/src/utils/correlation.test.ts +0 -47
  95. package/src/utils/correlation.ts +0 -22
  96. package/src/utils/permissionUtils.test.ts +0 -47
  97. package/src/utils/permissionUtils.ts +0 -68
  98. package/src/utils/response.test.ts +0 -64
  99. package/src/utils/response.ts +0 -60
  100. package/tsconfig.build.json +0 -7
  101. package/tsconfig.json +0 -23
@@ -1,384 +0,0 @@
1
- import mongoose from 'mongoose';
2
- import logger from '../logging/logger';
3
- import { MeterKey } from './definitions';
4
- import { UsageMeter, currentPeriod } from './UsageMeter';
5
-
6
- /**
7
- * Rebuild the cumulative usage meters from the data they describe.
8
- *
9
- * **Why this can exist at all:** every meter reconciled here is *derived*.
10
- * `storageBytes` is the sum of photo sizes, `trackedTickers` the count of
11
- * active symbols, `seats` the members of the groups a subject owns — in each
12
- * case the underlying collection is the record and the counter is only a cache
13
- * of it, kept hot because a quota check cannot afford the aggregation. So the
14
- * counter can always be recomputed, and reconciliation is cache invalidation.
15
- *
16
- * `aiJobs` is deliberately absent, and its absence is the same rule read the
17
- * other way: nothing records that a GPU job happened except the counter itself,
18
- * so there is no truth to recompute it from. That is precisely why
19
- * `consumeQuota` rolls its increment back on rejection rather than leaving it —
20
- * a leaked increment on that meter is permanent, where here it is temporary.
21
- *
22
- * **On racing with live writes:** a `consumeQuota` landing between the
23
- * aggregation and the write is lost. That is tolerable for exactly the reason
24
- * above — the next run re-derives the same number from source and converges —
25
- * so this is scheduled at a quiet hour rather than defended with a lock.
26
- *
27
- * Reads collections owned by other services through the raw driver rather than
28
- * mongoose models. They are not this library's documents to model, every
29
- * service shares one database, and going through the driver avoids registering
30
- * a second model for a schema that already exists elsewhere.
31
- */
32
-
33
- /** Meters whose value can be recomputed from source data. See the note above. */
34
- export const RECONCILED_METERS: readonly MeterKey[] = ['storageBytes', 'trackedTickers', 'seats'];
35
-
36
- export interface ReconcileOptions {
37
- /** Write the corrections. Default false — the caller must opt in to mutating. */
38
- apply?: boolean;
39
- /** Restrict to a single subject, for a targeted repair. */
40
- subject?: string;
41
- }
42
-
43
- export interface MeterChange {
44
- subjectId: string;
45
- meter: MeterKey;
46
- /** `null` when no counter existed yet. */
47
- from: number | null;
48
- to: number;
49
- }
50
-
51
- export interface OrphanedMeter {
52
- subjectId: string;
53
- meter: string;
54
- count: number;
55
- }
56
-
57
- export interface ReconcileReport {
58
- applied: boolean;
59
- scannedUsers: number;
60
- /** Subjects with any attributable usage, before any `subject` filter. */
61
- subjects: number;
62
- expected: Record<string, Record<MeterKey, number>>;
63
- changes: MeterChange[];
64
- written: number;
65
- orphanedMeters: OrphanedMeter[];
66
- warnings: string[];
67
- }
68
-
69
- const normalizeEmail = (value: unknown): string | undefined =>
70
- typeof value === 'string' && value.trim() ? value.trim().toLowerCase() : undefined;
71
-
72
- interface MemberRow {
73
- email?: string;
74
- role?: string;
75
- }
76
-
77
- interface GroupRow {
78
- _id: unknown;
79
- name?: string;
80
- createdBy?: string;
81
- members?: MemberRow[];
82
- deletedAt?: Date | null;
83
- }
84
-
85
- interface OwnedRow {
86
- _id: unknown;
87
- userId?: string;
88
- groupId?: string;
89
- }
90
-
91
- /**
92
- * Whoever currently holds the `owner` role — that is what group-service
93
- * authorizes against, and `updateMemberRole` can move it while `createdBy`
94
- * stays as first written. Several owners resolve to the lowest email so that a
95
- * re-run bills the same person twice rather than two people once.
96
- */
97
- function groupOwner(group: GroupRow, warnings: string[]): string | undefined {
98
- const owners = (group.members ?? [])
99
- .filter(m => m.role === 'owner')
100
- .map(m => normalizeEmail(m.email))
101
- .filter((e): e is string => Boolean(e))
102
- .sort();
103
-
104
- if (owners.length === 1) return owners[0];
105
-
106
- if (owners.length === 0) {
107
- const fallback = normalizeEmail(group.createdBy);
108
- warnings.push(
109
- `group ${group._id} ("${group.name}") has no member with role 'owner'; billing to createdBy=${fallback ?? 'MISSING'}`
110
- );
111
- return fallback;
112
- }
113
-
114
- warnings.push(`group ${group._id} ("${group.name}") has ${owners.length} owners (${owners.join(', ')}); billing to ${owners[0]}`);
115
- return owners[0];
116
- }
117
-
118
- interface Bucket {
119
- storageBytes: number;
120
- trackedTickers: Set<string>;
121
- seats: Set<string>;
122
- }
123
-
124
- async function computeExpected(): Promise<{
125
- expected: Map<string, Bucket>;
126
- warnings: string[];
127
- scannedUsers: number;
128
- }> {
129
- const db = mongoose.connection.db;
130
- if (!db) throw new Error('Cannot reconcile usage meters: no active database connection');
131
-
132
- const warnings: string[] = [];
133
-
134
- // Album.userId / TrackedTicker.userId hold `req.user.id`, which is the
135
- // auth-service User._id as a string, while a meter's subjectId is an email.
136
- // Nothing personal can be attributed without coming back through this map.
137
- const users = await db.collection('users').find({}, { projection: { email: 1 } }).toArray();
138
- const userIdToEmail = new Map<string, string>();
139
- for (const user of users) {
140
- const email = normalizeEmail(user.email);
141
- if (email) userIdToEmail.set(String(user._id), email);
142
- }
143
-
144
- const groups = (await db.collection('groups').find({}).toArray()) as unknown as GroupRow[];
145
- const groupsById = new Map<string, { doc: GroupRow; owner?: string; deleted: boolean }>();
146
- for (const group of groups) {
147
- groupsById.set(String(group._id), {
148
- doc: group,
149
- owner: groupOwner(group, warnings),
150
- deleted: group.deletedAt !== null && group.deletedAt !== undefined
151
- });
152
- }
153
-
154
- const expected = new Map<string, Bucket>();
155
- const bucket = (email: string): Bucket => {
156
- let existing = expected.get(email);
157
- if (!existing) {
158
- existing = { storageBytes: 0, trackedTickers: new Set(), seats: new Set() };
159
- expected.set(email, existing);
160
- }
161
- return existing;
162
- };
163
- // Every known user gets a bucket, so a user whose real usage is zero can
164
- // still correct a stale non-zero counter back down.
165
- for (const email of userIdToEmail.values()) bucket(email);
166
-
167
- /**
168
- * Group rows bill to the group owner: Family sells a pooled allowance, and
169
- * charging the uploader would spend their personal free tier on it instead.
170
- */
171
- const subjectFor = (row: OwnedRow, label: string): string | undefined => {
172
- const groupId = row.groupId ? String(row.groupId) : undefined;
173
- if (groupId) {
174
- const group = groupsById.get(groupId);
175
- if (group?.owner) return group.owner;
176
- // The group is gone but its rows are not. The uploader is the only
177
- // identity left, and dropping the bytes would understate real storage.
178
- const uploader = userIdToEmail.get(String(row.userId));
179
- warnings.push(`${label} ${row._id} references missing group ${groupId}; billing to uploader=${uploader ?? 'UNATTRIBUTED'}`);
180
- return uploader;
181
- }
182
- const owner = userIdToEmail.get(String(row.userId));
183
- if (!owner) warnings.push(`${label} ${row._id} has userId=${row.userId}, which matches no user; UNATTRIBUTED`);
184
- return owner;
185
- };
186
-
187
- // --- storageBytes ---------------------------------------------------------
188
- // Summed from the photos themselves rather than from the denormalized
189
- // Album.totalSize: that counter is what a drifting $inc would have corrupted,
190
- // so reconciling against it would re-import the drift instead of fixing it.
191
- const photoTotals = await db
192
- .collection('photos')
193
- .aggregate<{ _id: unknown; totalSize: number; photoCount: number }>(
194
- [{ $group: { _id: '$albumId', totalSize: { $sum: '$size' }, photoCount: { $sum: 1 } } }],
195
- { allowDiskUse: true }
196
- )
197
- .toArray();
198
- const sizeByAlbum = new Map(photoTotals.map(row => [String(row._id), row.totalSize || 0]));
199
-
200
- const albums = (await db
201
- .collection('albums')
202
- .find({}, { projection: { userId: 1, groupId: 1, totalSize: 1, name: 1 } })
203
- .toArray()) as unknown as (OwnedRow & { totalSize?: number; name?: string })[];
204
- const albumIds = new Set(albums.map(a => String(a._id)));
205
-
206
- for (const album of albums) {
207
- const realSize = sizeByAlbum.get(String(album._id)) ?? 0;
208
- if ((album.totalSize ?? 0) !== realSize) {
209
- warnings.push(
210
- `album ${album._id} ("${album.name}") totalSize=${album.totalSize} but photos sum to ${realSize}; ` +
211
- `metering the photo sum. The album counter is left alone — it is album-service's to maintain, ` +
212
- `and silently rewriting another service's denormalized field would hide the bug rather than surface it.`
213
- );
214
- }
215
- const subject = subjectFor(album, 'album');
216
- if (subject) bucket(subject).storageBytes += realSize;
217
- }
218
-
219
- for (const row of photoTotals) {
220
- if (!albumIds.has(String(row._id))) {
221
- warnings.push(`${row.photoCount} photo(s) totalling ${row.totalSize} B reference missing album ${row._id}; UNATTRIBUTED`);
222
- }
223
- }
224
-
225
- // --- trackedTickers -------------------------------------------------------
226
- // Distinct symbols, not rows: the daily Alpha Vantage spend this limit
227
- // recovers is one call per distinct active symbol, however many rows hold it.
228
- const tickers = (await db
229
- .collection('trackedtickers')
230
- .find({ isActive: true }, { projection: { userId: 1, groupId: 1, ticker: 1 } })
231
- .toArray()) as unknown as (OwnedRow & { ticker?: string })[];
232
-
233
- for (const ticker of tickers) {
234
- const subject = subjectFor(ticker, 'trackedTicker');
235
- if (subject && ticker.ticker) bucket(subject).trackedTickers.add(String(ticker.ticker).toUpperCase());
236
- }
237
-
238
- // --- seats ----------------------------------------------------------------
239
- // Distinct people across every live group the subject owns. Soft-deleted
240
- // groups are skipped: unlike storage and tickers they cost nothing and grant
241
- // nobody access, so charging for them would charge for nothing.
242
- for (const { doc, owner, deleted } of groupsById.values()) {
243
- if (deleted || !owner) continue;
244
- const seats = bucket(owner).seats;
245
- for (const member of doc.members ?? []) {
246
- const email = normalizeEmail(member.email);
247
- if (email) seats.add(email);
248
- }
249
- }
250
-
251
- return { expected, warnings, scannedUsers: users.length };
252
- }
253
-
254
- /**
255
- * Recompute every derived meter and, with `apply`, write back the ones that
256
- * disagree.
257
- *
258
- * Idempotent: it computes absolute values and writes only differences, so a
259
- * second run in a row is a no-op.
260
- */
261
- export async function reconcileUsageMeters(options: ReconcileOptions = {}): Promise<ReconcileReport> {
262
- const { apply = false, subject: only } = options;
263
- const onlySubject = normalizeEmail(only);
264
-
265
- const { expected, warnings, scannedUsers } = await computeExpected();
266
-
267
- const current = await UsageMeter.find({ meter: { $in: RECONCILED_METERS }, period: 'ALL' }).lean();
268
- const currentByKey = new Map(current.map(doc => [`${normalizeEmail(doc.subjectId)}::${doc.meter}`, doc]));
269
-
270
- const subjects = Array.from(expected.keys())
271
- .filter(email => !onlySubject || email === onlySubject)
272
- .sort();
273
-
274
- const changes: MeterChange[] = [];
275
- const ops = [];
276
-
277
- for (const subjectId of subjects) {
278
- const counts = expected.get(subjectId)!;
279
- const resolved: Record<MeterKey, number> = {
280
- storageBytes: counts.storageBytes,
281
- trackedTickers: counts.trackedTickers.size,
282
- seats: counts.seats.size
283
- } as Record<MeterKey, number>;
284
-
285
- for (const meter of RECONCILED_METERS) {
286
- const to = resolved[meter];
287
- const existing = currentByKey.get(`${subjectId}::${meter}`);
288
- const from = existing ? existing.count : null;
289
-
290
- if (from === to) continue;
291
- // Never create a row just to say zero — absence already reads as zero
292
- // everywhere. An *existing* row must still be corrected down to zero, or
293
- // a stale count outlives the data it was counting.
294
- if (from === null && to === 0) continue;
295
-
296
- changes.push({ subjectId, meter, from, to });
297
- ops.push({
298
- updateOne: {
299
- filter: { subjectId, meter, period: currentPeriod(meter) },
300
- update: {
301
- $set: { count: to, updatedAt: new Date() },
302
- $setOnInsert: { subjectId, meter, period: currentPeriod(meter), createdAt: new Date() }
303
- },
304
- upsert: true
305
- }
306
- });
307
- }
308
- }
309
-
310
- // Meters for subjects the scan no longer recognizes — a removed user, or a
311
- // subjectId written before an ownership change. Reported, never deleted: a
312
- // reconciliation that silently drops billing state is worse than the drift.
313
- const orphanedMeters: OrphanedMeter[] = current
314
- .filter(doc => !expected.has(normalizeEmail(doc.subjectId) ?? ''))
315
- .map(doc => ({ subjectId: doc.subjectId, meter: doc.meter, count: doc.count }));
316
-
317
- let written = 0;
318
- if (apply && ops.length > 0) {
319
- const result = await UsageMeter.bulkWrite(ops);
320
- written = result.modifiedCount + result.upsertedCount;
321
- }
322
-
323
- const expectedRecord: Record<string, Record<MeterKey, number>> = {};
324
- for (const subjectId of subjects) {
325
- const counts = expected.get(subjectId)!;
326
- expectedRecord[subjectId] = {
327
- storageBytes: counts.storageBytes,
328
- trackedTickers: counts.trackedTickers.size,
329
- seats: counts.seats.size
330
- } as Record<MeterKey, number>;
331
- }
332
-
333
- return {
334
- applied: apply,
335
- scannedUsers,
336
- subjects: expected.size,
337
- expected: expectedRecord,
338
- changes,
339
- written,
340
- orphanedMeters,
341
- warnings
342
- };
343
- }
344
-
345
- /**
346
- * Run a reconciliation and log the outcome. The scheduled entry point.
347
- *
348
- * Never throws: this runs from a cron callback with no caller to catch it, and
349
- * an unhandled rejection there takes the process down over a housekeeping job.
350
- */
351
- export async function runUsageReconciliation(): Promise<ReconcileReport | null> {
352
- const startedAt = Date.now();
353
- try {
354
- const report = await reconcileUsageMeters({ apply: true });
355
-
356
- // A correction is drift that already happened — the counter had gone wrong
357
- // and users were being metered against a wrong number until this ran.
358
- // Logged at `warn` so a persistent leak in consumeQuota/releaseQuota is
359
- // visible as a recurring signal rather than buried in an info line.
360
- const level = report.changes.length > 0 ? 'warn' : 'info';
361
- logger[level]('entitlement.reconciled', {
362
- event: 'entitlement.reconciled',
363
- subjects: report.subjects,
364
- corrected: report.changes.length,
365
- written: report.written,
366
- orphaned: report.orphanedMeters.length,
367
- warnings: report.warnings.length,
368
- durationMs: Date.now() - startedAt,
369
- changes: report.changes.slice(0, 20)
370
- });
371
-
372
- for (const warning of report.warnings.slice(0, 20)) {
373
- logger.warn('entitlement.reconcile_warning', { event: 'entitlement.reconcile_warning', detail: warning });
374
- }
375
-
376
- return report;
377
- } catch (err) {
378
- logger.error('Usage meter reconciliation failed', {
379
- error: (err as Error)?.message,
380
- durationMs: Date.now() - startedAt
381
- });
382
- return null;
383
- }
384
- }
@@ -1,21 +0,0 @@
1
- import { PlanLimits } from './definitions';
2
-
3
- /**
4
- * What payment-service answers for a user, and what the client caches.
5
- * `limits` is already normalized — consumers never merge defaults themselves.
6
- */
7
- export interface Entitlements {
8
- email: string;
9
- planCode: string;
10
- /** Subscription status backing the plan; `null` for users on the implicit free plan. */
11
- status: string | null;
12
- limits: PlanLimits;
13
- /** Cheapest active plan priced above the current one, for the upgrade dialog's CTA. */
14
- upgradeTo?: string;
15
- /**
16
- * Set when payment-service could not be reached and these are fallback
17
- * limits rather than the user's real ones. Enforcement still applies (fail
18
- * closed), but the value lets callers log the difference.
19
- */
20
- stale?: boolean;
21
- }