@tumbaland/backend-core 1.23.0 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/createBaseApp.d.ts +24 -0
- package/dist/app/createBaseApp.d.ts.map +1 -1
- package/dist/app/createBaseApp.js +20 -1
- package/dist/app/createBaseApp.js.map +1 -1
- package/dist/entitlements/UsageMeter.d.ts +30 -0
- package/dist/entitlements/UsageMeter.d.ts.map +1 -0
- package/dist/entitlements/UsageMeter.js +27 -0
- package/dist/entitlements/UsageMeter.js.map +1 -0
- package/dist/entitlements/client.d.ts +17 -0
- package/dist/entitlements/client.d.ts.map +1 -0
- package/dist/entitlements/client.js +142 -0
- package/dist/entitlements/client.js.map +1 -0
- package/dist/entitlements/definitions.d.ts +124 -0
- package/dist/entitlements/definitions.d.ts.map +1 -0
- package/dist/entitlements/definitions.js +210 -0
- package/dist/entitlements/definitions.js.map +1 -0
- package/dist/entitlements/index.d.ts +12 -0
- package/dist/entitlements/index.d.ts.map +1 -0
- package/dist/entitlements/index.js +43 -0
- package/dist/entitlements/index.js.map +1 -0
- package/dist/entitlements/middleware.d.ts +54 -0
- package/dist/entitlements/middleware.d.ts.map +1 -0
- package/dist/entitlements/middleware.js +109 -0
- package/dist/entitlements/middleware.js.map +1 -0
- package/dist/entitlements/mode.d.ts +10 -0
- package/dist/entitlements/mode.d.ts.map +1 -0
- package/dist/entitlements/mode.js +32 -0
- package/dist/entitlements/mode.js.map +1 -0
- package/dist/entitlements/types.d.ts +29 -0
- package/dist/entitlements/types.d.ts.map +1 -0
- package/dist/entitlements/types.js +3 -0
- package/dist/entitlements/types.js.map +1 -0
- package/dist/entitlements/usage.d.ts +56 -0
- package/dist/entitlements/usage.d.ts.map +1 -0
- package/dist/entitlements/usage.js +159 -0
- package/dist/entitlements/usage.js.map +1 -0
- package/dist/errors/HttpError.d.ts +30 -1
- package/dist/errors/HttpError.d.ts.map +1 -1
- package/dist/errors/HttpError.js +20 -2
- package/dist/errors/HttpError.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +26 -2
- package/dist/index.js.map +1 -1
- package/dist/middleware/errorHandler.d.ts.map +1 -1
- package/dist/middleware/errorHandler.js +4 -1
- package/dist/middleware/errorHandler.js.map +1 -1
- package/dist/middleware/internalServiceAuth.d.ts +44 -0
- package/dist/middleware/internalServiceAuth.d.ts.map +1 -0
- package/dist/middleware/internalServiceAuth.js +86 -0
- package/dist/middleware/internalServiceAuth.js.map +1 -0
- package/package.json +2 -1
- package/src/app/createBaseApp.test.ts +31 -0
- package/src/app/createBaseApp.ts +28 -1
- package/src/entitlements/UsageMeter.ts +49 -0
- package/src/entitlements/client.test.ts +170 -0
- package/src/entitlements/client.ts +162 -0
- package/src/entitlements/definitions.test.ts +161 -0
- package/src/entitlements/definitions.ts +261 -0
- package/src/entitlements/index.ts +40 -0
- package/src/entitlements/middleware.test.ts +179 -0
- package/src/entitlements/middleware.ts +136 -0
- package/src/entitlements/mode.test.ts +50 -0
- package/src/entitlements/mode.ts +28 -0
- package/src/entitlements/types.ts +30 -0
- package/src/entitlements/usage.test.ts +271 -0
- package/src/entitlements/usage.ts +189 -0
- package/src/errors/HttpError.test.ts +39 -1
- package/src/errors/HttpError.ts +35 -1
- package/src/index.ts +13 -1
- package/src/middleware/errorHandler.test.ts +43 -1
- package/src/middleware/errorHandler.ts +6 -1
- package/src/middleware/internalServiceAuth.test.ts +173 -0
- package/src/middleware/internalServiceAuth.ts +96 -0
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The entitlement *vocabulary*: which meters and features exist, what they
|
|
3
|
+
* mean, and what a plan gets when nothing else says otherwise.
|
|
4
|
+
*
|
|
5
|
+
* The actual per-plan numbers are NOT here — they live on the `Plan` document
|
|
6
|
+
* in Mongo and are editable by an admin at runtime (see payment-service's
|
|
7
|
+
* `Plan.limits` and `PUT /api/plans/:code/limits`). Shipping a code change to
|
|
8
|
+
* move a limit from 50 GB to 75 GB would be absurd, and a hardcoded table
|
|
9
|
+
* would immediately drift from what the pricing page renders.
|
|
10
|
+
*
|
|
11
|
+
* What code still owns:
|
|
12
|
+
* - the set of valid keys, so a typo in an admin form can't invent a meter
|
|
13
|
+
* that nothing enforces (`normalizeLimits` drops unknown keys);
|
|
14
|
+
* - `DEFAULT_PLAN_LIMITS`, the values used when a Plan document has no
|
|
15
|
+
* `limits` yet (fresh install, newly created plan) or when payment-service
|
|
16
|
+
* is unreachable and the client has to fail closed;
|
|
17
|
+
* - `ENTITLEMENT_CATALOG`, the metadata an admin UI renders its form from,
|
|
18
|
+
* so adding a meter needs no frontend change.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export type MeterKey = 'storageBytes' | 'aiJobs' | 'trackedTickers' | 'seats';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Deliberately small. The portfolio planner is NOT a feature flag — it is gated
|
|
25
|
+
* by `retentionDays` via the price-history range, because the planner runs
|
|
26
|
+
* entirely client-side and a boolean flag would be bypassable from devtools.
|
|
27
|
+
*/
|
|
28
|
+
export type FeatureKey = 'cleanExport';
|
|
29
|
+
|
|
30
|
+
/** `ALL` = counts up forever (storage, seats). `MONTH` = resets each calendar month (UTC). */
|
|
31
|
+
export type MeterPeriod = 'ALL' | 'MONTH';
|
|
32
|
+
|
|
33
|
+
/** Sentinel for "no ceiling". Chosen over `Infinity` because it survives JSON and BSON. */
|
|
34
|
+
export const UNLIMITED = -1;
|
|
35
|
+
|
|
36
|
+
export interface MeterDefinition {
|
|
37
|
+
key: MeterKey;
|
|
38
|
+
label: string;
|
|
39
|
+
/** Drives formatting in the admin form and in `<UsageMeter>`: bytes get humanized, counts don't. */
|
|
40
|
+
unit: 'bytes' | 'count';
|
|
41
|
+
period: MeterPeriod;
|
|
42
|
+
description: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface FeatureDefinition {
|
|
46
|
+
key: FeatureKey;
|
|
47
|
+
label: string;
|
|
48
|
+
description: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const METER_DEFINITIONS: readonly MeterDefinition[] = [
|
|
52
|
+
{
|
|
53
|
+
key: 'storageBytes',
|
|
54
|
+
label: 'Storage',
|
|
55
|
+
unit: 'bytes',
|
|
56
|
+
period: 'ALL',
|
|
57
|
+
description: 'Total bytes of uploaded photos and files held for the user.'
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
key: 'aiJobs',
|
|
61
|
+
label: 'AI analyses',
|
|
62
|
+
unit: 'count',
|
|
63
|
+
period: 'MONTH',
|
|
64
|
+
description: 'Segmentation and object-detection jobs dispatched per calendar month.'
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
key: 'trackedTickers',
|
|
68
|
+
label: 'Tracked tickers',
|
|
69
|
+
unit: 'count',
|
|
70
|
+
period: 'ALL',
|
|
71
|
+
description: 'Instruments followed for price history. Each one spends the deployment-wide market-data budget.'
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
key: 'seats',
|
|
75
|
+
label: 'Group seats',
|
|
76
|
+
unit: 'count',
|
|
77
|
+
period: 'ALL',
|
|
78
|
+
description: 'Members that may join groups owned by the user, including the owner.'
|
|
79
|
+
}
|
|
80
|
+
] as const;
|
|
81
|
+
|
|
82
|
+
export const FEATURE_DEFINITIONS: readonly FeatureDefinition[] = [
|
|
83
|
+
{
|
|
84
|
+
key: 'cleanExport',
|
|
85
|
+
label: 'Clean export',
|
|
86
|
+
description: 'Exports and downloads without a watermark.'
|
|
87
|
+
}
|
|
88
|
+
] as const;
|
|
89
|
+
|
|
90
|
+
export const METER_KEYS: readonly MeterKey[] = METER_DEFINITIONS.map(m => m.key);
|
|
91
|
+
export const FEATURE_KEYS: readonly FeatureKey[] = FEATURE_DEFINITIONS.map(f => f.key);
|
|
92
|
+
|
|
93
|
+
const METER_PERIODS = Object.fromEntries(
|
|
94
|
+
METER_DEFINITIONS.map(m => [m.key, m.period])
|
|
95
|
+
) as Record<MeterKey, MeterPeriod>;
|
|
96
|
+
|
|
97
|
+
export function meterPeriod(meter: MeterKey): MeterPeriod {
|
|
98
|
+
return METER_PERIODS[meter] ?? 'ALL';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function isMeterKey(value: string): value is MeterKey {
|
|
102
|
+
return (METER_KEYS as readonly string[]).includes(value);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function isFeatureKey(value: string): value is FeatureKey {
|
|
106
|
+
return (FEATURE_KEYS as readonly string[]).includes(value);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface PlanLimits {
|
|
110
|
+
/** `-1` (UNLIMITED) means no ceiling. */
|
|
111
|
+
meters: Record<MeterKey, number>;
|
|
112
|
+
features: Record<FeatureKey, boolean>;
|
|
113
|
+
/** How far back reads may reach. `-1` (UNLIMITED) means the full history. */
|
|
114
|
+
retentionDays: number;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** What an admin form or an API caller may send: any subset, in any order. */
|
|
118
|
+
export interface PartialPlanLimits {
|
|
119
|
+
meters?: Partial<Record<string, number>>;
|
|
120
|
+
features?: Partial<Record<string, boolean>>;
|
|
121
|
+
retentionDays?: number;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const GB = 1024 * 1024 * 1024;
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Bootstrap values only — a Plan document's own `limits` wins over anything
|
|
128
|
+
* here. These are what a plan gets before an admin has ever touched it, and
|
|
129
|
+
* what the entitlement client falls back to when payment-service is down.
|
|
130
|
+
*
|
|
131
|
+
* Keep `free` conservative for exactly that reason: an outage degrades paying
|
|
132
|
+
* users to these numbers, and the alternative (fail-open) gives the product
|
|
133
|
+
* away for the length of the outage.
|
|
134
|
+
*/
|
|
135
|
+
export const DEFAULT_PLAN_LIMITS: Readonly<Record<string, PlanLimits>> = {
|
|
136
|
+
free: {
|
|
137
|
+
meters: { storageBytes: 1 * GB, aiJobs: 25, trackedTickers: 3, seats: 1 },
|
|
138
|
+
features: { cleanExport: false },
|
|
139
|
+
retentionDays: 90
|
|
140
|
+
},
|
|
141
|
+
personal: {
|
|
142
|
+
meters: { storageBytes: 50 * GB, aiJobs: 200, trackedTickers: 25, seats: 1 },
|
|
143
|
+
features: { cleanExport: true },
|
|
144
|
+
retentionDays: UNLIMITED
|
|
145
|
+
},
|
|
146
|
+
family: {
|
|
147
|
+
meters: { storageBytes: 250 * GB, aiJobs: 600, trackedTickers: 100, seats: 5 },
|
|
148
|
+
features: { cleanExport: true },
|
|
149
|
+
retentionDays: UNLIMITED
|
|
150
|
+
},
|
|
151
|
+
/**
|
|
152
|
+
* Everything unlimited, for the maintainers and for comped friends. Held as a
|
|
153
|
+
* real plan with a real subscription rather than an exemption branch in the
|
|
154
|
+
* code, so the people running the product go through the identical
|
|
155
|
+
* enforcement path as a paying customer — an `if (isStaff) skipEverything`
|
|
156
|
+
* flag would mean the paywall is never exercised by anyone who could notice
|
|
157
|
+
* it was broken.
|
|
158
|
+
*
|
|
159
|
+
* Kept off the public catalog through `Plan.isPublic = false`.
|
|
160
|
+
*/
|
|
161
|
+
staff: {
|
|
162
|
+
meters: { storageBytes: UNLIMITED, aiJobs: UNLIMITED, trackedTickers: UNLIMITED, seats: UNLIMITED },
|
|
163
|
+
features: { cleanExport: true },
|
|
164
|
+
retentionDays: UNLIMITED
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
/** Plan code the seeded staff/comp plan uses. */
|
|
169
|
+
export const STAFF_PLAN = 'staff';
|
|
170
|
+
|
|
171
|
+
export const FALLBACK_PLAN = 'free';
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Code defaults for a plan code, with unknown codes resolving to free.
|
|
175
|
+
*
|
|
176
|
+
* That fallback is deliberate: a typo'd or newly-added plan code must never
|
|
177
|
+
* silently grant unlimited. Callers that want the admin-configured numbers
|
|
178
|
+
* read them from the Plan document and pass them through `normalizeLimits`;
|
|
179
|
+
* this function is the floor underneath that.
|
|
180
|
+
*/
|
|
181
|
+
export function resolveLimits(planCode?: string): PlanLimits {
|
|
182
|
+
const limits = DEFAULT_PLAN_LIMITS[planCode ?? FALLBACK_PLAN] ?? DEFAULT_PLAN_LIMITS[FALLBACK_PLAN];
|
|
183
|
+
return cloneLimits(limits);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function cloneLimits(limits: PlanLimits): PlanLimits {
|
|
187
|
+
return {
|
|
188
|
+
meters: { ...limits.meters },
|
|
189
|
+
features: { ...limits.features },
|
|
190
|
+
retentionDays: limits.retentionDays
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function normalizeCeiling(value: unknown, fallback: number): number {
|
|
195
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback;
|
|
196
|
+
// Anything negative means "unlimited"; nothing else is a meaningful ceiling.
|
|
197
|
+
if (value < 0) return UNLIMITED;
|
|
198
|
+
return Math.floor(value);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Layers a partial set of limits over a complete one.
|
|
203
|
+
*
|
|
204
|
+
* Entitlements resolve through three layers, each one partial and each one
|
|
205
|
+
* overriding the last: code defaults → the Plan document's `limits` → a
|
|
206
|
+
* per-user `EntitlementOverride`. This is the single step all three share.
|
|
207
|
+
*
|
|
208
|
+
* - unknown meter/feature keys are dropped — no store can invent enforcement;
|
|
209
|
+
* - missing keys keep the base value, so adding a new meter in code works
|
|
210
|
+
* everywhere before any stored document mentions it;
|
|
211
|
+
* - negative numbers normalize to `UNLIMITED`, fractions floor.
|
|
212
|
+
*/
|
|
213
|
+
export function applyLimits(base: PlanLimits, input?: PartialPlanLimits | null): PlanLimits {
|
|
214
|
+
const result = cloneLimits(base);
|
|
215
|
+
if (!input) return result;
|
|
216
|
+
|
|
217
|
+
for (const key of METER_KEYS) {
|
|
218
|
+
result.meters[key] = normalizeCeiling(input.meters?.[key], result.meters[key]);
|
|
219
|
+
}
|
|
220
|
+
for (const key of FEATURE_KEYS) {
|
|
221
|
+
const value = input.features?.[key];
|
|
222
|
+
result.features[key] = typeof value === 'boolean' ? value : result.features[key];
|
|
223
|
+
}
|
|
224
|
+
result.retentionDays = normalizeCeiling(input.retentionDays, result.retentionDays);
|
|
225
|
+
|
|
226
|
+
return result;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Turns whatever is stored on a Plan document (or arrived from an admin form)
|
|
231
|
+
* into a complete, valid `PlanLimits`, filling the gaps from that plan code's
|
|
232
|
+
* code defaults.
|
|
233
|
+
*/
|
|
234
|
+
export function normalizeLimits(input?: PartialPlanLimits | null, planCode?: string): PlanLimits {
|
|
235
|
+
return applyLimits(resolveLimits(planCode), input);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** True when `used + amount` fits under `limit`. `UNLIMITED` always fits. */
|
|
239
|
+
export function fitsWithin(limit: number, used: number, amount = 0): boolean {
|
|
240
|
+
if (limit === UNLIMITED || limit < 0) return true;
|
|
241
|
+
return used + amount <= limit;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Everything an admin UI needs to render a limits editor without hardcoding a
|
|
246
|
+
* single meter name — new keys appear in the form as soon as they exist here.
|
|
247
|
+
*/
|
|
248
|
+
export const ENTITLEMENT_CATALOG = {
|
|
249
|
+
unlimited: UNLIMITED,
|
|
250
|
+
meters: METER_DEFINITIONS,
|
|
251
|
+
features: FEATURE_DEFINITIONS,
|
|
252
|
+
retentionDays: {
|
|
253
|
+
key: 'retentionDays' as const,
|
|
254
|
+
label: 'History retention (days)',
|
|
255
|
+
unit: 'days' as const,
|
|
256
|
+
description:
|
|
257
|
+
'How far back reads may reach. Gates relationship history and, through the price-history range, the portfolio planner.'
|
|
258
|
+
},
|
|
259
|
+
defaults: DEFAULT_PLAN_LIMITS,
|
|
260
|
+
fallbackPlan: FALLBACK_PLAN
|
|
261
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export {
|
|
2
|
+
UNLIMITED,
|
|
3
|
+
FALLBACK_PLAN,
|
|
4
|
+
STAFF_PLAN,
|
|
5
|
+
applyLimits,
|
|
6
|
+
METER_KEYS,
|
|
7
|
+
FEATURE_KEYS,
|
|
8
|
+
METER_DEFINITIONS,
|
|
9
|
+
FEATURE_DEFINITIONS,
|
|
10
|
+
DEFAULT_PLAN_LIMITS,
|
|
11
|
+
ENTITLEMENT_CATALOG,
|
|
12
|
+
resolveLimits,
|
|
13
|
+
normalizeLimits,
|
|
14
|
+
meterPeriod,
|
|
15
|
+
isMeterKey,
|
|
16
|
+
isFeatureKey,
|
|
17
|
+
fitsWithin
|
|
18
|
+
} from './definitions';
|
|
19
|
+
export type {
|
|
20
|
+
MeterKey,
|
|
21
|
+
FeatureKey,
|
|
22
|
+
MeterPeriod,
|
|
23
|
+
MeterDefinition,
|
|
24
|
+
FeatureDefinition,
|
|
25
|
+
PlanLimits,
|
|
26
|
+
PartialPlanLimits
|
|
27
|
+
} from './definitions';
|
|
28
|
+
|
|
29
|
+
export type { Entitlements, EntitlementsMode } from './types';
|
|
30
|
+
export { getEntitlementsMode, resetEntitlementsModeWarning } from './mode';
|
|
31
|
+
|
|
32
|
+
export { UsageMeter, currentPeriod } from './UsageMeter';
|
|
33
|
+
export type { IUsageMeter } from './UsageMeter';
|
|
34
|
+
export { getUsage, getUsageSnapshot, checkQuota, consumeQuota, releaseQuota, setUsage } from './usage';
|
|
35
|
+
export type { QuotaRequest } from './usage';
|
|
36
|
+
|
|
37
|
+
export { getEntitlements, invalidateEntitlements, clearEntitlementsCache } from './client';
|
|
38
|
+
|
|
39
|
+
export { loadEntitlements, requireEntitlement, requireQuota, retentionFloor } from './middleware';
|
|
40
|
+
export type { EntitlementOptions, QuotaOptions, SubjectResolver } from './middleware';
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { Request, Response } from 'express';
|
|
2
|
+
|
|
3
|
+
jest.mock('../logging/logger', () => ({
|
|
4
|
+
__esModule: true,
|
|
5
|
+
default: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn(), http: jest.fn() }
|
|
6
|
+
}));
|
|
7
|
+
jest.mock('./client', () => ({ getEntitlements: jest.fn() }));
|
|
8
|
+
jest.mock('./usage', () => ({ checkQuota: jest.fn() }));
|
|
9
|
+
|
|
10
|
+
import logger from '../logging/logger';
|
|
11
|
+
import { getEntitlements } from './client';
|
|
12
|
+
import { checkQuota } from './usage';
|
|
13
|
+
import { loadEntitlements, requireEntitlement, requireQuota, retentionFloor } from './middleware';
|
|
14
|
+
import { Entitlements } from './types';
|
|
15
|
+
import { UNLIMITED, normalizeLimits } from './definitions';
|
|
16
|
+
|
|
17
|
+
const mockGetEntitlements = getEntitlements as jest.MockedFunction<typeof getEntitlements>;
|
|
18
|
+
const mockCheckQuota = checkQuota as jest.MockedFunction<typeof checkQuota>;
|
|
19
|
+
|
|
20
|
+
const ORIGINAL_ENV = process.env;
|
|
21
|
+
|
|
22
|
+
function entitlements(overrides: Partial<Entitlements> = {}): Entitlements {
|
|
23
|
+
return {
|
|
24
|
+
email: 'user@example.com',
|
|
25
|
+
planCode: 'free',
|
|
26
|
+
status: null,
|
|
27
|
+
limits: normalizeLimits(undefined, 'free'),
|
|
28
|
+
upgradeTo: 'personal',
|
|
29
|
+
...overrides
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function mockReq(overrides: Partial<Request> = {}): Request {
|
|
34
|
+
return { user: { email: 'user@example.com' }, originalUrl: '/api/photos', ...overrides } as Request;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
beforeEach(() => {
|
|
38
|
+
process.env = { ...ORIGINAL_ENV, ENTITLEMENTS_MODE: 'enforce' };
|
|
39
|
+
jest.clearAllMocks();
|
|
40
|
+
mockGetEntitlements.mockResolvedValue(entitlements());
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
afterAll(() => {
|
|
44
|
+
process.env = ORIGINAL_ENV;
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe('loadEntitlements', () => {
|
|
48
|
+
it('resolves once per request even across several checks', async () => {
|
|
49
|
+
const req = mockReq();
|
|
50
|
+
|
|
51
|
+
await loadEntitlements(req);
|
|
52
|
+
await loadEntitlements(req);
|
|
53
|
+
|
|
54
|
+
expect(mockGetEntitlements).toHaveBeenCalledTimes(1);
|
|
55
|
+
expect(req.entitlements?.planCode).toBe('free');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('rejects when there is no subject to bill', async () => {
|
|
59
|
+
await expect(loadEntitlements(mockReq({ user: undefined }))).rejects.toMatchObject({ statusCode: 401 });
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('bills the subject a resolver names, not the caller', async () => {
|
|
63
|
+
await loadEntitlements(mockReq(), () => 'owner@example.com');
|
|
64
|
+
|
|
65
|
+
expect(mockGetEntitlements).toHaveBeenCalledWith('owner@example.com');
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe('requireEntitlement', () => {
|
|
70
|
+
it('passes a plan that includes the feature', async () => {
|
|
71
|
+
mockGetEntitlements.mockResolvedValue(entitlements({ planCode: 'personal', limits: normalizeLimits(undefined, 'personal') }));
|
|
72
|
+
const next = jest.fn();
|
|
73
|
+
|
|
74
|
+
await requireEntitlement('cleanExport')(mockReq(), {} as Response, next);
|
|
75
|
+
|
|
76
|
+
expect(next).toHaveBeenCalledWith();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('rejects with a 402 naming the feature and the upgrade target', async () => {
|
|
80
|
+
const next = jest.fn();
|
|
81
|
+
|
|
82
|
+
await requireEntitlement('cleanExport')(mockReq(), {} as Response, next);
|
|
83
|
+
|
|
84
|
+
expect(next).toHaveBeenCalledWith(
|
|
85
|
+
expect.objectContaining({
|
|
86
|
+
statusCode: 402,
|
|
87
|
+
details: { code: 'FEATURE_NOT_IN_PLAN', feature: 'cleanExport', planCode: 'free', upgradeTo: 'personal' }
|
|
88
|
+
})
|
|
89
|
+
);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('logs instead of blocking in observe mode', async () => {
|
|
93
|
+
process.env.ENTITLEMENTS_MODE = 'observe';
|
|
94
|
+
const next = jest.fn();
|
|
95
|
+
|
|
96
|
+
await requireEntitlement('cleanExport')(mockReq(), {} as Response, next);
|
|
97
|
+
|
|
98
|
+
expect(next).toHaveBeenCalledWith();
|
|
99
|
+
expect(logger.info).toHaveBeenCalledWith('entitlement.would_block', expect.objectContaining({ feature: 'cleanExport' }));
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('does not even look entitlements up when the mode is off', async () => {
|
|
103
|
+
process.env.ENTITLEMENTS_MODE = 'off';
|
|
104
|
+
const next = jest.fn();
|
|
105
|
+
|
|
106
|
+
await requireEntitlement('cleanExport')(mockReq(), {} as Response, next);
|
|
107
|
+
|
|
108
|
+
expect(next).toHaveBeenCalledWith();
|
|
109
|
+
expect(mockGetEntitlements).not.toHaveBeenCalled();
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
describe('requireQuota', () => {
|
|
114
|
+
it('checks the meter for the amount the request costs', async () => {
|
|
115
|
+
const next = jest.fn();
|
|
116
|
+
const req = mockReq({ body: { sizeBytes: 2048 } } as Partial<Request>);
|
|
117
|
+
|
|
118
|
+
await requireQuota('storageBytes', { amount: r => (r.body as { sizeBytes: number }).sizeBytes })(
|
|
119
|
+
req,
|
|
120
|
+
{} as Response,
|
|
121
|
+
next
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
expect(mockCheckQuota).toHaveBeenCalledWith(
|
|
125
|
+
expect.objectContaining({ subjectId: 'user@example.com', meter: 'storageBytes', amount: 2048, route: '/api/photos' })
|
|
126
|
+
);
|
|
127
|
+
expect(next).toHaveBeenCalledWith();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('defaults the amount to one', async () => {
|
|
131
|
+
await requireQuota('trackedTickers')(mockReq(), {} as Response, jest.fn());
|
|
132
|
+
|
|
133
|
+
expect(mockCheckQuota).toHaveBeenCalledWith(expect.objectContaining({ amount: 1 }));
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('forwards a quota rejection to the error handler', async () => {
|
|
137
|
+
const denial = Object.assign(new Error('nope'), { statusCode: 402 });
|
|
138
|
+
mockCheckQuota.mockRejectedValue(denial);
|
|
139
|
+
const next = jest.fn();
|
|
140
|
+
|
|
141
|
+
await requireQuota('storageBytes')(mockReq(), {} as Response, next);
|
|
142
|
+
|
|
143
|
+
expect(next).toHaveBeenCalledWith(denial);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('is inert when the mode is off', async () => {
|
|
147
|
+
process.env.ENTITLEMENTS_MODE = 'off';
|
|
148
|
+
const next = jest.fn();
|
|
149
|
+
|
|
150
|
+
await requireQuota('storageBytes')(mockReq(), {} as Response, next);
|
|
151
|
+
|
|
152
|
+
expect(mockCheckQuota).not.toHaveBeenCalled();
|
|
153
|
+
expect(next).toHaveBeenCalledWith();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
describe('retentionFloor', () => {
|
|
158
|
+
const now = new Date('2026-08-09T00:00:00.000Z');
|
|
159
|
+
|
|
160
|
+
it('returns the cutoff date for a capped plan', async () => {
|
|
161
|
+
const floor = await retentionFloor('user@example.com', now);
|
|
162
|
+
|
|
163
|
+
expect(floor).toEqual(new Date('2026-05-11T00:00:00.000Z')); // 90 days back
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('returns null for an unlimited plan, so no $match is added', async () => {
|
|
167
|
+
mockGetEntitlements.mockResolvedValue(
|
|
168
|
+
entitlements({ planCode: 'family', limits: normalizeLimits({ retentionDays: UNLIMITED }, 'family') })
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
expect(await retentionFloor('user@example.com', now)).toBeNull();
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it('never truncates history outside enforce mode', async () => {
|
|
175
|
+
process.env.ENTITLEMENTS_MODE = 'observe';
|
|
176
|
+
|
|
177
|
+
expect(await retentionFloor('user@example.com', now)).toBeNull();
|
|
178
|
+
});
|
|
179
|
+
});
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { Request, RequestHandler } from 'express';
|
|
2
|
+
import logger from '../logging/logger';
|
|
3
|
+
import { PaymentRequiredError, UnauthorizedError } from '../errors/HttpError';
|
|
4
|
+
import { FeatureKey, MeterKey, UNLIMITED } from './definitions';
|
|
5
|
+
import { getEntitlements } from './client';
|
|
6
|
+
import { checkQuota } from './usage';
|
|
7
|
+
import { getEntitlementsMode } from './mode';
|
|
8
|
+
import { Entitlements } from './types';
|
|
9
|
+
|
|
10
|
+
declare global {
|
|
11
|
+
namespace Express {
|
|
12
|
+
interface Request {
|
|
13
|
+
/** Populated by the entitlement middlewares so controllers can read limits without a second lookup. */
|
|
14
|
+
entitlements?: Entitlements;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Who the check is billed to. Defaults to the authenticated user; group
|
|
21
|
+
* chokepoints override it with the group owner, since pooled quota belongs to
|
|
22
|
+
* whoever pays for the group.
|
|
23
|
+
*/
|
|
24
|
+
export type SubjectResolver = (req: Request) => string | undefined | Promise<string | undefined>;
|
|
25
|
+
|
|
26
|
+
export interface EntitlementOptions {
|
|
27
|
+
subject?: SubjectResolver;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const defaultSubject: SubjectResolver = req => req.user?.email;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Resolves and caches entitlements on the request. Two checks on one route
|
|
34
|
+
* (a feature gate plus a quota gate) therefore cost one lookup, not two.
|
|
35
|
+
*/
|
|
36
|
+
export async function loadEntitlements(req: Request, resolve: SubjectResolver = defaultSubject): Promise<Entitlements> {
|
|
37
|
+
if (req.entitlements) return req.entitlements;
|
|
38
|
+
|
|
39
|
+
const subject = await resolve(req);
|
|
40
|
+
if (!subject) throw new UnauthorizedError('Authentication required');
|
|
41
|
+
|
|
42
|
+
const entitlements = await getEntitlements(subject);
|
|
43
|
+
req.entitlements = entitlements;
|
|
44
|
+
return entitlements;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Gate a feature flag. Reads are never gated by design — use this on writes,
|
|
49
|
+
* dispatches and exports only.
|
|
50
|
+
*/
|
|
51
|
+
export function requireEntitlement(feature: FeatureKey, options: EntitlementOptions = {}): RequestHandler {
|
|
52
|
+
return async (req, _res, next) => {
|
|
53
|
+
try {
|
|
54
|
+
const mode = getEntitlementsMode();
|
|
55
|
+
if (mode === 'off') return next();
|
|
56
|
+
|
|
57
|
+
const entitlements = await loadEntitlements(req, options.subject);
|
|
58
|
+
if (entitlements.limits.features[feature]) return next();
|
|
59
|
+
|
|
60
|
+
if (mode === 'observe') {
|
|
61
|
+
logger.info('entitlement.would_block', {
|
|
62
|
+
event: 'entitlement.would_block',
|
|
63
|
+
feature,
|
|
64
|
+
subjectId: entitlements.email,
|
|
65
|
+
planCode: entitlements.planCode,
|
|
66
|
+
route: req.originalUrl,
|
|
67
|
+
stale: entitlements.stale === true
|
|
68
|
+
});
|
|
69
|
+
return next();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
throw new PaymentRequiredError(`Your plan does not include ${feature}`, {
|
|
73
|
+
code: 'FEATURE_NOT_IN_PLAN',
|
|
74
|
+
feature,
|
|
75
|
+
planCode: entitlements.planCode,
|
|
76
|
+
upgradeTo: entitlements.upgradeTo
|
|
77
|
+
});
|
|
78
|
+
} catch (err) {
|
|
79
|
+
next(err);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface QuotaOptions extends EntitlementOptions {
|
|
85
|
+
/**
|
|
86
|
+
* How much this request costs. A function when the amount is in the payload
|
|
87
|
+
* — an upload's `sizeBytes`, say — which is also why the storage gate sits on
|
|
88
|
+
* the signed-URL request: it is the only point where the size is known
|
|
89
|
+
* *before* the bytes are written.
|
|
90
|
+
*/
|
|
91
|
+
amount?: number | ((req: Request) => number);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Read-only quota gate. Records nothing — the increment belongs at the point
|
|
96
|
+
* the resource actually comes into existence, via `consumeQuota`.
|
|
97
|
+
*/
|
|
98
|
+
export function requireQuota(meter: MeterKey, options: QuotaOptions = {}): RequestHandler {
|
|
99
|
+
return async (req, _res, next) => {
|
|
100
|
+
try {
|
|
101
|
+
if (getEntitlementsMode() === 'off') return next();
|
|
102
|
+
|
|
103
|
+
const entitlements = await loadEntitlements(req, options.subject);
|
|
104
|
+
const amount = typeof options.amount === 'function' ? options.amount(req) : (options.amount ?? 1);
|
|
105
|
+
|
|
106
|
+
await checkQuota({
|
|
107
|
+
subjectId: entitlements.email,
|
|
108
|
+
meter,
|
|
109
|
+
amount,
|
|
110
|
+
entitlements,
|
|
111
|
+
route: req.originalUrl
|
|
112
|
+
});
|
|
113
|
+
next();
|
|
114
|
+
} catch (err) {
|
|
115
|
+
next(err);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The oldest timestamp a user may read, or `null` for unlimited history.
|
|
122
|
+
*
|
|
123
|
+
* Meant to be dropped straight into an aggregation `$match` — this is what
|
|
124
|
+
* gates the portfolio planner, since the planner runs entirely client-side and
|
|
125
|
+
* any `<PaywallGate>` around it is bypassable from devtools. Truncating the
|
|
126
|
+
* price history it depends on is not.
|
|
127
|
+
*/
|
|
128
|
+
export async function retentionFloor(email: string, now: Date = new Date()): Promise<Date | null> {
|
|
129
|
+
if (getEntitlementsMode() !== 'enforce') return null;
|
|
130
|
+
|
|
131
|
+
const { limits } = await getEntitlements(email);
|
|
132
|
+
const days = limits.retentionDays;
|
|
133
|
+
if (days === UNLIMITED || days < 0) return null;
|
|
134
|
+
|
|
135
|
+
return new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
|
|
136
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
jest.mock('../logging/logger', () => ({
|
|
2
|
+
__esModule: true,
|
|
3
|
+
default: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn(), http: jest.fn() }
|
|
4
|
+
}));
|
|
5
|
+
|
|
6
|
+
import logger from '../logging/logger';
|
|
7
|
+
import { getEntitlementsMode, resetEntitlementsModeWarning } from './mode';
|
|
8
|
+
|
|
9
|
+
const ORIGINAL_ENV = process.env;
|
|
10
|
+
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
process.env = { ...ORIGINAL_ENV };
|
|
13
|
+
delete process.env.ENTITLEMENTS_MODE;
|
|
14
|
+
resetEntitlementsModeWarning();
|
|
15
|
+
(logger.warn as jest.Mock).mockClear();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
afterAll(() => {
|
|
19
|
+
process.env = ORIGINAL_ENV;
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe('getEntitlementsMode', () => {
|
|
23
|
+
it('defaults to observe when unset', () => {
|
|
24
|
+
expect(getEntitlementsMode()).toBe('observe');
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('reads each valid mode, case- and whitespace-insensitively', () => {
|
|
28
|
+
process.env.ENTITLEMENTS_MODE = 'enforce';
|
|
29
|
+
expect(getEntitlementsMode()).toBe('enforce');
|
|
30
|
+
|
|
31
|
+
process.env.ENTITLEMENTS_MODE = ' Off ';
|
|
32
|
+
expect(getEntitlementsMode()).toBe('off');
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('falls back to observe and warns once on an invalid value', () => {
|
|
36
|
+
process.env.ENTITLEMENTS_MODE = 'enforcce';
|
|
37
|
+
|
|
38
|
+
expect(getEntitlementsMode()).toBe('observe');
|
|
39
|
+
expect(getEntitlementsMode()).toBe('observe');
|
|
40
|
+
expect(logger.warn).toHaveBeenCalledTimes(1);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('picks up a change without a restart of the module', () => {
|
|
44
|
+
process.env.ENTITLEMENTS_MODE = 'observe';
|
|
45
|
+
expect(getEntitlementsMode()).toBe('observe');
|
|
46
|
+
|
|
47
|
+
process.env.ENTITLEMENTS_MODE = 'enforce';
|
|
48
|
+
expect(getEntitlementsMode()).toBe('enforce');
|
|
49
|
+
});
|
|
50
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import logger from '../logging/logger';
|
|
2
|
+
import { EntitlementsMode } from './types';
|
|
3
|
+
|
|
4
|
+
const VALID_MODES: readonly EntitlementsMode[] = ['off', 'observe', 'enforce'];
|
|
5
|
+
|
|
6
|
+
let warnedAboutInvalidMode = false;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Read per call rather than cached at import time: a service can be flipped to
|
|
10
|
+
* `enforce` by restarting it with a new env value, and tests set the variable
|
|
11
|
+
* between cases. The cost is one `process.env` lookup per check.
|
|
12
|
+
*/
|
|
13
|
+
export function getEntitlementsMode(): EntitlementsMode {
|
|
14
|
+
const raw = (process.env.ENTITLEMENTS_MODE || '').trim().toLowerCase();
|
|
15
|
+
if (!raw) return 'observe';
|
|
16
|
+
if ((VALID_MODES as readonly string[]).includes(raw)) return raw as EntitlementsMode;
|
|
17
|
+
|
|
18
|
+
if (!warnedAboutInvalidMode) {
|
|
19
|
+
warnedAboutInvalidMode = true;
|
|
20
|
+
logger.warn('Invalid ENTITLEMENTS_MODE, falling back to observe', { value: raw });
|
|
21
|
+
}
|
|
22
|
+
return 'observe';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Test seam — the "already warned" latch would otherwise leak between cases. */
|
|
26
|
+
export function resetEntitlementsModeWarning(): void {
|
|
27
|
+
warnedAboutInvalidMode = false;
|
|
28
|
+
}
|