@tumbaland/backend-core 1.44.0 → 1.46.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 (123) hide show
  1. package/dist/fileService/client.d.ts +54 -0
  2. package/dist/fileService/client.d.ts.map +1 -0
  3. package/dist/fileService/client.js +137 -0
  4. package/dist/fileService/client.js.map +1 -0
  5. package/dist/fileService/index.d.ts +4 -0
  6. package/dist/fileService/index.d.ts.map +1 -0
  7. package/dist/fileService/index.js +40 -0
  8. package/dist/fileService/index.js.map +1 -0
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +6 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/middleware/corsMiddleware.d.ts.map +1 -1
  14. package/dist/middleware/corsMiddleware.js +4 -1
  15. package/dist/middleware/corsMiddleware.js.map +1 -1
  16. package/dist/middleware/errorHandler.d.ts.map +1 -1
  17. package/dist/middleware/errorHandler.js +5 -8
  18. package/dist/middleware/errorHandler.js.map +1 -1
  19. package/dist/utils/escapeRegex.d.ts +8 -0
  20. package/dist/utils/escapeRegex.d.ts.map +1 -0
  21. package/dist/utils/escapeRegex.js +12 -0
  22. package/dist/utils/escapeRegex.js.map +1 -0
  23. package/package.json +5 -1
  24. package/.versionrc.json +0 -7
  25. package/__mocks__/uuid.js +0 -8
  26. package/jest.config.js +0 -24
  27. package/src/apiKeys/ApiKey.test.ts +0 -142
  28. package/src/apiKeys/ApiKey.ts +0 -102
  29. package/src/apiKeys/crypto.test.ts +0 -161
  30. package/src/apiKeys/crypto.ts +0 -163
  31. package/src/apiKeys/index.test.ts +0 -72
  32. package/src/apiKeys/index.ts +0 -35
  33. package/src/apiKeys/middleware.test.ts +0 -651
  34. package/src/apiKeys/middleware.ts +0 -341
  35. package/src/apiKeys/service.test.ts +0 -401
  36. package/src/apiKeys/service.ts +0 -168
  37. package/src/apiKeys/types.test.ts +0 -41
  38. package/src/apiKeys/types.ts +0 -124
  39. package/src/app/createBaseApp.test.ts +0 -109
  40. package/src/app/createBaseApp.ts +0 -102
  41. package/src/app/shutdown.test.ts +0 -129
  42. package/src/app/shutdown.ts +0 -81
  43. package/src/audit/AuditEvent.ts +0 -123
  44. package/src/audit/actor.test.ts +0 -95
  45. package/src/audit/actor.ts +0 -68
  46. package/src/audit/context.test.ts +0 -91
  47. package/src/audit/context.ts +0 -83
  48. package/src/audit/index.ts +0 -11
  49. package/src/audit/plugin.test.ts +0 -258
  50. package/src/audit/plugin.ts +0 -254
  51. package/src/audit/reads.test.ts +0 -164
  52. package/src/audit/reads.ts +0 -88
  53. package/src/audit/service.test.ts +0 -115
  54. package/src/audit/service.ts +0 -95
  55. package/src/auth/session.test.ts +0 -89
  56. package/src/auth/session.ts +0 -75
  57. package/src/config/env.test.ts +0 -28
  58. package/src/config/env.ts +0 -13
  59. package/src/database/connection.test.ts +0 -188
  60. package/src/database/connection.ts +0 -90
  61. package/src/entitlements/UsageMeter.ts +0 -49
  62. package/src/entitlements/client.test.ts +0 -200
  63. package/src/entitlements/client.ts +0 -179
  64. package/src/entitlements/definitions.test.ts +0 -161
  65. package/src/entitlements/definitions.ts +0 -268
  66. package/src/entitlements/index.ts +0 -42
  67. package/src/entitlements/middleware.test.ts +0 -196
  68. package/src/entitlements/middleware.ts +0 -150
  69. package/src/entitlements/reconcile.test.ts +0 -333
  70. package/src/entitlements/reconcile.ts +0 -384
  71. package/src/entitlements/types.ts +0 -21
  72. package/src/entitlements/usage.test.ts +0 -314
  73. package/src/entitlements/usage.ts +0 -223
  74. package/src/errors/HttpError.test.ts +0 -76
  75. package/src/errors/HttpError.ts +0 -91
  76. package/src/groups/client.test.ts +0 -215
  77. package/src/groups/client.ts +0 -182
  78. package/src/groups/index.ts +0 -7
  79. package/src/groups/membership.test.ts +0 -84
  80. package/src/groups/membership.ts +0 -133
  81. package/src/groups/subject.test.ts +0 -85
  82. package/src/groups/subject.ts +0 -50
  83. package/src/health/createHealthCheck.test.ts +0 -89
  84. package/src/health/createHealthCheck.ts +0 -67
  85. package/src/health/healthController.test.ts +0 -113
  86. package/src/health/healthController.ts +0 -56
  87. package/src/index.ts +0 -88
  88. package/src/logging/logger.test.ts +0 -91
  89. package/src/logging/logger.ts +0 -103
  90. package/src/metrics/index.test.ts +0 -116
  91. package/src/metrics/index.ts +0 -111
  92. package/src/middleware/authMiddleware.test.ts +0 -275
  93. package/src/middleware/authMiddleware.ts +0 -91
  94. package/src/middleware/corsMiddleware.test.ts +0 -135
  95. package/src/middleware/corsMiddleware.ts +0 -65
  96. package/src/middleware/errorHandler.test.ts +0 -188
  97. package/src/middleware/errorHandler.ts +0 -103
  98. package/src/middleware/internalServiceAuth.test.ts +0 -173
  99. package/src/middleware/internalServiceAuth.ts +0 -96
  100. package/src/middleware/requestLogger.test.ts +0 -81
  101. package/src/middleware/requestLogger.ts +0 -48
  102. package/src/middleware/security.test.ts +0 -45
  103. package/src/middleware/security.ts +0 -43
  104. package/src/middleware/validate.test.ts +0 -72
  105. package/src/middleware/validate.ts +0 -23
  106. package/src/oauth/index.ts +0 -29
  107. package/src/oauth/models.ts +0 -164
  108. package/src/oauth/service.test.ts +0 -432
  109. package/src/oauth/service.ts +0 -299
  110. package/src/oauth/tokens.test.ts +0 -146
  111. package/src/oauth/tokens.ts +0 -186
  112. package/src/testing/serviceTestSetup.ts +0 -17
  113. package/src/tracing/index.test.ts +0 -272
  114. package/src/tracing/index.ts +0 -110
  115. package/src/types/auth.ts +0 -45
  116. package/src/utils/correlation.test.ts +0 -47
  117. package/src/utils/correlation.ts +0 -22
  118. package/src/utils/permissionUtils.test.ts +0 -47
  119. package/src/utils/permissionUtils.ts +0 -68
  120. package/src/utils/response.test.ts +0 -64
  121. package/src/utils/response.ts +0 -60
  122. package/tsconfig.build.json +0 -7
  123. 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
- }