@tumbaland/backend-core 1.44.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.
- package/package.json +5 -1
- package/.versionrc.json +0 -7
- package/__mocks__/uuid.js +0 -8
- package/jest.config.js +0 -24
- package/src/apiKeys/ApiKey.test.ts +0 -142
- package/src/apiKeys/ApiKey.ts +0 -102
- package/src/apiKeys/crypto.test.ts +0 -161
- package/src/apiKeys/crypto.ts +0 -163
- package/src/apiKeys/index.test.ts +0 -72
- package/src/apiKeys/index.ts +0 -35
- package/src/apiKeys/middleware.test.ts +0 -651
- package/src/apiKeys/middleware.ts +0 -341
- package/src/apiKeys/service.test.ts +0 -401
- package/src/apiKeys/service.ts +0 -168
- package/src/apiKeys/types.test.ts +0 -41
- package/src/apiKeys/types.ts +0 -124
- package/src/app/createBaseApp.test.ts +0 -109
- package/src/app/createBaseApp.ts +0 -102
- package/src/app/shutdown.test.ts +0 -129
- package/src/app/shutdown.ts +0 -81
- package/src/audit/AuditEvent.ts +0 -123
- package/src/audit/actor.test.ts +0 -95
- package/src/audit/actor.ts +0 -68
- package/src/audit/context.test.ts +0 -91
- package/src/audit/context.ts +0 -83
- package/src/audit/index.ts +0 -11
- package/src/audit/plugin.test.ts +0 -258
- package/src/audit/plugin.ts +0 -254
- package/src/audit/reads.test.ts +0 -164
- package/src/audit/reads.ts +0 -88
- package/src/audit/service.test.ts +0 -115
- package/src/audit/service.ts +0 -95
- package/src/auth/session.test.ts +0 -89
- package/src/auth/session.ts +0 -75
- package/src/config/env.test.ts +0 -28
- package/src/config/env.ts +0 -13
- package/src/database/connection.test.ts +0 -188
- package/src/database/connection.ts +0 -90
- package/src/entitlements/UsageMeter.ts +0 -49
- package/src/entitlements/client.test.ts +0 -200
- package/src/entitlements/client.ts +0 -179
- package/src/entitlements/definitions.test.ts +0 -161
- package/src/entitlements/definitions.ts +0 -268
- package/src/entitlements/index.ts +0 -42
- package/src/entitlements/middleware.test.ts +0 -196
- package/src/entitlements/middleware.ts +0 -150
- package/src/entitlements/reconcile.test.ts +0 -333
- package/src/entitlements/reconcile.ts +0 -384
- package/src/entitlements/types.ts +0 -21
- package/src/entitlements/usage.test.ts +0 -314
- package/src/entitlements/usage.ts +0 -223
- package/src/errors/HttpError.test.ts +0 -76
- package/src/errors/HttpError.ts +0 -91
- package/src/groups/client.test.ts +0 -215
- package/src/groups/client.ts +0 -182
- package/src/groups/index.ts +0 -7
- package/src/groups/membership.test.ts +0 -84
- package/src/groups/membership.ts +0 -133
- package/src/groups/subject.test.ts +0 -85
- package/src/groups/subject.ts +0 -50
- package/src/health/createHealthCheck.test.ts +0 -89
- package/src/health/createHealthCheck.ts +0 -67
- package/src/health/healthController.test.ts +0 -113
- package/src/health/healthController.ts +0 -56
- package/src/index.ts +0 -88
- package/src/logging/logger.test.ts +0 -91
- package/src/logging/logger.ts +0 -103
- package/src/metrics/index.test.ts +0 -116
- package/src/metrics/index.ts +0 -111
- package/src/middleware/authMiddleware.test.ts +0 -275
- package/src/middleware/authMiddleware.ts +0 -91
- package/src/middleware/corsMiddleware.test.ts +0 -135
- package/src/middleware/corsMiddleware.ts +0 -65
- package/src/middleware/errorHandler.test.ts +0 -188
- package/src/middleware/errorHandler.ts +0 -103
- package/src/middleware/internalServiceAuth.test.ts +0 -173
- package/src/middleware/internalServiceAuth.ts +0 -96
- package/src/middleware/requestLogger.test.ts +0 -81
- package/src/middleware/requestLogger.ts +0 -48
- package/src/middleware/security.test.ts +0 -45
- package/src/middleware/security.ts +0 -43
- package/src/middleware/validate.test.ts +0 -72
- package/src/middleware/validate.ts +0 -23
- package/src/oauth/index.ts +0 -29
- package/src/oauth/models.ts +0 -164
- package/src/oauth/service.test.ts +0 -432
- package/src/oauth/service.ts +0 -299
- package/src/oauth/tokens.test.ts +0 -146
- package/src/oauth/tokens.ts +0 -186
- package/src/testing/serviceTestSetup.ts +0 -17
- package/src/tracing/index.test.ts +0 -272
- package/src/tracing/index.ts +0 -110
- package/src/types/auth.ts +0 -45
- package/src/utils/correlation.test.ts +0 -47
- package/src/utils/correlation.ts +0 -22
- package/src/utils/permissionUtils.test.ts +0 -47
- package/src/utils/permissionUtils.ts +0 -68
- package/src/utils/response.test.ts +0 -64
- package/src/utils/response.ts +0 -60
- package/tsconfig.build.json +0 -7
- package/tsconfig.json +0 -23
|
@@ -1,200 +0,0 @@
|
|
|
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 { clearEntitlementsCache, getEntitlements, invalidateEntitlements } from './client';
|
|
8
|
-
import { DEFAULT_PLAN_LIMITS } from './definitions';
|
|
9
|
-
|
|
10
|
-
const ORIGINAL_ENV = process.env;
|
|
11
|
-
const ORIGINAL_FETCH = global.fetch;
|
|
12
|
-
|
|
13
|
-
function jsonResponse(body: unknown, status = 200): Response {
|
|
14
|
-
return { ok: status >= 200 && status < 300, status, json: async () => body } as Response;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function paidResponse() {
|
|
18
|
-
return jsonResponse({
|
|
19
|
-
success: true,
|
|
20
|
-
planCode: 'support',
|
|
21
|
-
status: 'active',
|
|
22
|
-
limits: { meters: { storageBytes: 12345 } },
|
|
23
|
-
upgradeTo: 'support'
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
beforeEach(() => {
|
|
28
|
-
process.env = {
|
|
29
|
-
...ORIGINAL_ENV,
|
|
30
|
-
PAYMENT_API_URL: 'http://payment-service:5005',
|
|
31
|
-
INTERNAL_SERVICE_TOKEN: 'test-internal-token',
|
|
32
|
-
SERVICE_NAME: 'album-service'
|
|
33
|
-
};
|
|
34
|
-
clearEntitlementsCache();
|
|
35
|
-
global.fetch = jest.fn();
|
|
36
|
-
(logger.error as jest.Mock).mockClear();
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
afterAll(() => {
|
|
40
|
-
process.env = ORIGINAL_ENV;
|
|
41
|
-
global.fetch = ORIGINAL_FETCH;
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
describe('getEntitlements', () => {
|
|
45
|
-
it('calls the internal endpoint with the service token and normalizes the answer', async () => {
|
|
46
|
-
(global.fetch as jest.Mock).mockResolvedValue(paidResponse());
|
|
47
|
-
|
|
48
|
-
const result = await getEntitlements('User@Example.com');
|
|
49
|
-
|
|
50
|
-
expect(global.fetch).toHaveBeenCalledWith(
|
|
51
|
-
'http://payment-service:5005/internal/entitlements?email=user%40example.com',
|
|
52
|
-
expect.objectContaining({
|
|
53
|
-
headers: expect.objectContaining({ 'x-internal-token': 'test-internal-token', 'x-service-id': 'album-service' })
|
|
54
|
-
})
|
|
55
|
-
);
|
|
56
|
-
expect(result.planCode).toBe('support');
|
|
57
|
-
expect(result.upgradeTo).toBe('support');
|
|
58
|
-
expect(result.limits.meters.storageBytes).toBe(12345);
|
|
59
|
-
// Keys the payload omitted are filled from that plan's defaults rather than
|
|
60
|
-
// arriving undefined and comparing as NaN inside a quota check.
|
|
61
|
-
expect(result.limits.meters.seats).toBe(DEFAULT_PLAN_LIMITS.support.meters.seats);
|
|
62
|
-
expect(result.stale).toBeUndefined();
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
it('serves the cached answer within the TTL and refetches after it', async () => {
|
|
66
|
-
jest.useFakeTimers();
|
|
67
|
-
try {
|
|
68
|
-
(global.fetch as jest.Mock).mockResolvedValue(paidResponse());
|
|
69
|
-
|
|
70
|
-
await getEntitlements('user@example.com');
|
|
71
|
-
await getEntitlements('user@example.com');
|
|
72
|
-
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
73
|
-
|
|
74
|
-
jest.advanceTimersByTime(60_001);
|
|
75
|
-
await getEntitlements('user@example.com');
|
|
76
|
-
expect(global.fetch).toHaveBeenCalledTimes(2);
|
|
77
|
-
} finally {
|
|
78
|
-
jest.useRealTimers();
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
it('treats casing and surrounding whitespace as the same user', async () => {
|
|
83
|
-
(global.fetch as jest.Mock).mockResolvedValue(paidResponse());
|
|
84
|
-
|
|
85
|
-
await getEntitlements('user@example.com');
|
|
86
|
-
await getEntitlements(' User@Example.COM ');
|
|
87
|
-
|
|
88
|
-
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
it('collapses a concurrent burst for one user into a single request', async () => {
|
|
92
|
-
(global.fetch as jest.Mock).mockResolvedValue(paidResponse());
|
|
93
|
-
|
|
94
|
-
await Promise.all(Array.from({ length: 10 }, () => getEntitlements('user@example.com')));
|
|
95
|
-
|
|
96
|
-
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
it('drops the cached answer on invalidate', async () => {
|
|
100
|
-
(global.fetch as jest.Mock).mockResolvedValue(paidResponse());
|
|
101
|
-
|
|
102
|
-
await getEntitlements('user@example.com');
|
|
103
|
-
invalidateEntitlements('User@example.com');
|
|
104
|
-
await getEntitlements('user@example.com');
|
|
105
|
-
|
|
106
|
-
expect(global.fetch).toHaveBeenCalledTimes(2);
|
|
107
|
-
});
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
describe('when payment-service cannot be reached', () => {
|
|
111
|
-
it('fails closed to free limits rather than handing out the product', async () => {
|
|
112
|
-
(global.fetch as jest.Mock).mockRejectedValue(new Error('ECONNREFUSED'));
|
|
113
|
-
|
|
114
|
-
const result = await getEntitlements('user@example.com');
|
|
115
|
-
|
|
116
|
-
expect(result.planCode).toBe('free');
|
|
117
|
-
expect(result.limits).toEqual(DEFAULT_PLAN_LIMITS.free);
|
|
118
|
-
expect(result.stale).toBe(true);
|
|
119
|
-
expect(logger.error).toHaveBeenCalled();
|
|
120
|
-
});
|
|
121
|
-
|
|
122
|
-
it('fails closed on a non-2xx answer too', async () => {
|
|
123
|
-
(global.fetch as jest.Mock).mockResolvedValue(jsonResponse({ success: false }, 500));
|
|
124
|
-
|
|
125
|
-
const result = await getEntitlements('user@example.com');
|
|
126
|
-
|
|
127
|
-
expect(result.planCode).toBe('free');
|
|
128
|
-
expect(result.stale).toBe(true);
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
it('never caches a fallback, so recovery is immediate rather than a minute later', async () => {
|
|
132
|
-
(global.fetch as jest.Mock).mockRejectedValueOnce(new Error('ECONNREFUSED')).mockResolvedValue(paidResponse());
|
|
133
|
-
|
|
134
|
-
const failed = await getEntitlements('user@example.com');
|
|
135
|
-
const recovered = await getEntitlements('user@example.com');
|
|
136
|
-
|
|
137
|
-
expect(failed.stale).toBe(true);
|
|
138
|
-
expect(recovered.planCode).toBe('support');
|
|
139
|
-
});
|
|
140
|
-
|
|
141
|
-
it('fails closed without calling out at all when the channel is unconfigured', async () => {
|
|
142
|
-
delete process.env.PAYMENT_API_URL;
|
|
143
|
-
|
|
144
|
-
const result = await getEntitlements('user@example.com');
|
|
145
|
-
|
|
146
|
-
expect(global.fetch).not.toHaveBeenCalled();
|
|
147
|
-
expect(result.planCode).toBe('free');
|
|
148
|
-
expect(result.stale).toBe(true);
|
|
149
|
-
expect(logger.error).toHaveBeenCalledWith('Entitlement lookup not configured', expect.anything());
|
|
150
|
-
});
|
|
151
|
-
});
|
|
152
|
-
|
|
153
|
-
describe('base URL selection', () => {
|
|
154
|
-
it('prefers the container-network address over the public hostname', async () => {
|
|
155
|
-
process.env.PAYMENT_INTERNAL_URL = 'http://payment-service:5005';
|
|
156
|
-
process.env.PAYMENT_API_URL = 'https://payment-api.tumbaland.eu';
|
|
157
|
-
(global.fetch as jest.Mock).mockResolvedValue(paidResponse());
|
|
158
|
-
|
|
159
|
-
await getEntitlements('user@example.com');
|
|
160
|
-
|
|
161
|
-
// payment-front templates the public variable into the browser's
|
|
162
|
-
// config.json, so it cannot be pointed inward — hence the second variable.
|
|
163
|
-
expect(global.fetch).toHaveBeenCalledWith(
|
|
164
|
-
'http://payment-service:5005/internal/entitlements?email=user%40example.com',
|
|
165
|
-
expect.anything()
|
|
166
|
-
);
|
|
167
|
-
});
|
|
168
|
-
|
|
169
|
-
it('falls back to the public URL, so local dev and un-migrated deploys still work', async () => {
|
|
170
|
-
delete process.env.PAYMENT_INTERNAL_URL;
|
|
171
|
-
process.env.PAYMENT_API_URL = 'https://payment-api.tumbaland.eu';
|
|
172
|
-
(global.fetch as jest.Mock).mockResolvedValue(paidResponse());
|
|
173
|
-
|
|
174
|
-
await getEntitlements('user@example.com');
|
|
175
|
-
|
|
176
|
-
expect(global.fetch).toHaveBeenCalledWith(
|
|
177
|
-
'https://payment-api.tumbaland.eu/internal/entitlements?email=user%40example.com',
|
|
178
|
-
expect.anything()
|
|
179
|
-
);
|
|
180
|
-
});
|
|
181
|
-
});
|
|
182
|
-
|
|
183
|
-
describe('cache bounds', () => {
|
|
184
|
-
it('evicts the oldest entries instead of growing without limit', async () => {
|
|
185
|
-
(global.fetch as jest.Mock).mockResolvedValue(paidResponse());
|
|
186
|
-
|
|
187
|
-
for (let i = 0; i < 5_001; i++) {
|
|
188
|
-
await getEntitlements(`user${i}@example.com`);
|
|
189
|
-
}
|
|
190
|
-
const callsAfterFill = (global.fetch as jest.Mock).mock.calls.length;
|
|
191
|
-
|
|
192
|
-
// The very first user was evicted by the 5001st, so this is a refetch.
|
|
193
|
-
await getEntitlements('user0@example.com');
|
|
194
|
-
expect((global.fetch as jest.Mock).mock.calls.length).toBe(callsAfterFill + 1);
|
|
195
|
-
|
|
196
|
-
// The most recent user is still cached.
|
|
197
|
-
await getEntitlements('user5000@example.com');
|
|
198
|
-
expect((global.fetch as jest.Mock).mock.calls.length).toBe(callsAfterFill + 1);
|
|
199
|
-
});
|
|
200
|
-
});
|
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
import logger from '../logging/logger';
|
|
2
|
-
import { FALLBACK_PLAN, normalizeLimits, resolveLimits } from './definitions';
|
|
3
|
-
import { Entitlements } from './types';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Entitlements are read over the internal-service channel, not carried on the
|
|
7
|
-
* JWT.
|
|
8
|
-
*
|
|
9
|
-
* The JWT is signed for 24h and no service outside auth-service checks
|
|
10
|
-
* `tokenVersion`, so a plan embedded in it would be stale in both directions:
|
|
11
|
-
* a user who upgrades waits up to a day for what they just paid for, and a user
|
|
12
|
-
* who cancels keeps paid features for up to a day. A 60-second cache in front
|
|
13
|
-
* of a live lookup bounds that to a minute, and the enforcement points are
|
|
14
|
-
* writes and dispatches — low frequency — so the network cost is negligible.
|
|
15
|
-
*/
|
|
16
|
-
const CACHE_TTL_MS = 60_000;
|
|
17
|
-
|
|
18
|
-
/** Bounded so a service under enumeration can't grow the cache without limit. */
|
|
19
|
-
const MAX_CACHE_ENTRIES = 5_000;
|
|
20
|
-
|
|
21
|
-
const REQUEST_TIMEOUT_MS = 3_000;
|
|
22
|
-
|
|
23
|
-
interface CacheEntry {
|
|
24
|
-
value: Entitlements;
|
|
25
|
-
expiresAt: number;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const cache = new Map<string, CacheEntry>();
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Concurrent callers for the same email share one request. Without this, a
|
|
32
|
-
* burst of uploads from one user on a cold cache fans out into one
|
|
33
|
-
* payment-service call each.
|
|
34
|
-
*/
|
|
35
|
-
const inFlight = new Map<string, Promise<Entitlements>>();
|
|
36
|
-
|
|
37
|
-
function cacheKey(email: string): string {
|
|
38
|
-
return email.trim().toLowerCase();
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function putInCache(key: string, value: Entitlements): void {
|
|
42
|
-
if (cache.size >= MAX_CACHE_ENTRIES) {
|
|
43
|
-
// Map iterates in insertion order, so the first key is the oldest write.
|
|
44
|
-
const oldest = cache.keys().next();
|
|
45
|
-
if (!oldest.done) cache.delete(oldest.value);
|
|
46
|
-
}
|
|
47
|
-
cache.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Fail closed: an unreachable payment-service degrades everyone to free limits
|
|
52
|
-
* rather than handing the product out for the length of the outage. The blast
|
|
53
|
-
* radius is bounded by design — reads are never gated, only writes and
|
|
54
|
-
* dispatches — so the worst case is "cannot upload for a minute", not
|
|
55
|
-
* "cannot use the app".
|
|
56
|
-
*/
|
|
57
|
-
function fallbackEntitlements(email: string): Entitlements {
|
|
58
|
-
return {
|
|
59
|
-
email,
|
|
60
|
-
planCode: FALLBACK_PLAN,
|
|
61
|
-
status: null,
|
|
62
|
-
limits: resolveLimits(FALLBACK_PLAN),
|
|
63
|
-
stale: true
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
interface EntitlementResponse {
|
|
68
|
-
success?: boolean;
|
|
69
|
-
planCode?: string;
|
|
70
|
-
status?: string | null;
|
|
71
|
-
limits?: Parameters<typeof normalizeLimits>[0];
|
|
72
|
-
upgradeTo?: string;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Prefers the container-network address over the public hostname.
|
|
77
|
-
*
|
|
78
|
-
* `PAYMENT_API_URL` cannot simply be pointed inward: payment-front's entrypoint
|
|
79
|
-
* templates that same variable into the `config.json` the *browser* downloads,
|
|
80
|
-
* so a Docker-internal value there breaks the subscription and checkout pages.
|
|
81
|
-
* One variable, two consumers with incompatible needs — this is the server-side
|
|
82
|
-
* half of it.
|
|
83
|
-
*
|
|
84
|
-
* Falling back keeps local dev (where only `PAYMENT_API_URL` is set) and any
|
|
85
|
-
* un-migrated deployment working; it just takes the long way round, out through
|
|
86
|
-
* the proxy and back, carrying the internal token across the public edge.
|
|
87
|
-
*/
|
|
88
|
-
function internalPaymentUrl(): string | undefined {
|
|
89
|
-
return process.env.PAYMENT_INTERNAL_URL || process.env.PAYMENT_API_URL;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
async function fetchEntitlements(email: string): Promise<Entitlements> {
|
|
93
|
-
const baseUrl = internalPaymentUrl();
|
|
94
|
-
const token = process.env.INTERNAL_SERVICE_TOKEN;
|
|
95
|
-
const serviceId = process.env.SERVICE_NAME || 'unknown-service';
|
|
96
|
-
|
|
97
|
-
if (!baseUrl || !token) {
|
|
98
|
-
logger.error('Entitlement lookup not configured', {
|
|
99
|
-
hasPaymentApiUrl: Boolean(baseUrl),
|
|
100
|
-
hasInternalToken: Boolean(token)
|
|
101
|
-
});
|
|
102
|
-
return fallbackEntitlements(email);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
try {
|
|
106
|
-
const response = await fetch(`${baseUrl}/internal/entitlements?email=${encodeURIComponent(email)}`, {
|
|
107
|
-
method: 'GET',
|
|
108
|
-
headers: {
|
|
109
|
-
'Content-Type': 'application/json',
|
|
110
|
-
'x-internal-token': token,
|
|
111
|
-
'x-service-id': serviceId
|
|
112
|
-
},
|
|
113
|
-
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
if (!response.ok) {
|
|
117
|
-
logger.error('Entitlement lookup failed', { email, status: response.status });
|
|
118
|
-
return fallbackEntitlements(email);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const body = (await response.json()) as EntitlementResponse;
|
|
122
|
-
const planCode = body.planCode || FALLBACK_PLAN;
|
|
123
|
-
return {
|
|
124
|
-
email,
|
|
125
|
-
planCode,
|
|
126
|
-
status: body.status ?? null,
|
|
127
|
-
// Re-normalized on this side too: the payload crossed a network boundary
|
|
128
|
-
// and a partially-configured plan must not leave a meter undefined.
|
|
129
|
-
limits: normalizeLimits(body.limits, planCode),
|
|
130
|
-
upgradeTo: body.upgradeTo
|
|
131
|
-
};
|
|
132
|
-
} catch (err) {
|
|
133
|
-
logger.error('Entitlement lookup errored', { email, error: (err as Error)?.message });
|
|
134
|
-
return fallbackEntitlements(email);
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* The user's current plan and limits, cached for {@link CACHE_TTL_MS}.
|
|
140
|
-
*
|
|
141
|
-
* Failures are never cached — a fallback result would otherwise pin a paying
|
|
142
|
-
* user to free limits for a full minute after the outage ended.
|
|
143
|
-
*/
|
|
144
|
-
export async function getEntitlements(email: string): Promise<Entitlements> {
|
|
145
|
-
const key = cacheKey(email);
|
|
146
|
-
|
|
147
|
-
const cached = cache.get(key);
|
|
148
|
-
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
149
|
-
|
|
150
|
-
const pending = inFlight.get(key);
|
|
151
|
-
if (pending) return pending;
|
|
152
|
-
|
|
153
|
-
const request = fetchEntitlements(key)
|
|
154
|
-
.then(value => {
|
|
155
|
-
if (!value.stale) putInCache(key, value);
|
|
156
|
-
return value;
|
|
157
|
-
})
|
|
158
|
-
.finally(() => {
|
|
159
|
-
inFlight.delete(key);
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
inFlight.set(key, request);
|
|
163
|
-
return request;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/**
|
|
167
|
-
* Drop a user's cached entitlements. Call after anything that changes their
|
|
168
|
-
* plan (checkout completed, subscription canceled) to collapse the staleness
|
|
169
|
-
* window from 60s to zero for the user who is watching.
|
|
170
|
-
*/
|
|
171
|
-
export function invalidateEntitlements(email: string): void {
|
|
172
|
-
cache.delete(cacheKey(email));
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/** Empties the whole cache. Test seam, and a usable lever after a bulk plan edit. */
|
|
176
|
-
export function clearEntitlementsCache(): void {
|
|
177
|
-
cache.clear();
|
|
178
|
-
inFlight.clear();
|
|
179
|
-
}
|
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
DEFAULT_PLAN_LIMITS,
|
|
3
|
-
FALLBACK_PLAN,
|
|
4
|
-
FEATURE_KEYS,
|
|
5
|
-
METER_KEYS,
|
|
6
|
-
STAFF_PLAN,
|
|
7
|
-
UNLIMITED,
|
|
8
|
-
applyLimits,
|
|
9
|
-
fitsWithin,
|
|
10
|
-
isFeatureKey,
|
|
11
|
-
isMeterKey,
|
|
12
|
-
meterPeriod,
|
|
13
|
-
normalizeLimits,
|
|
14
|
-
resolveLimits
|
|
15
|
-
} from './definitions';
|
|
16
|
-
|
|
17
|
-
describe('resolveLimits', () => {
|
|
18
|
-
it('returns the defaults for a known plan code', () => {
|
|
19
|
-
expect(resolveLimits('support')).toEqual(DEFAULT_PLAN_LIMITS.support);
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
it('falls back to free for an unknown code, never to unlimited', () => {
|
|
23
|
-
expect(resolveLimits('enterprise-typo')).toEqual(DEFAULT_PLAN_LIMITS.free);
|
|
24
|
-
expect(resolveLimits(undefined)).toEqual(DEFAULT_PLAN_LIMITS[FALLBACK_PLAN]);
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
it('returns a copy, so a caller mutating limits cannot poison the defaults', () => {
|
|
28
|
-
const limits = resolveLimits('free');
|
|
29
|
-
limits.meters.storageBytes = 999;
|
|
30
|
-
limits.features.cleanExport = true;
|
|
31
|
-
|
|
32
|
-
expect(resolveLimits('free').meters.storageBytes).toBe(DEFAULT_PLAN_LIMITS.free.meters.storageBytes);
|
|
33
|
-
expect(resolveLimits('free').features.cleanExport).toBe(false);
|
|
34
|
-
});
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
describe('normalizeLimits', () => {
|
|
38
|
-
it('applies stored values over the plan defaults', () => {
|
|
39
|
-
const limits = normalizeLimits({ meters: { storageBytes: 123 }, retentionDays: 30 }, 'support');
|
|
40
|
-
|
|
41
|
-
expect(limits.meters.storageBytes).toBe(123);
|
|
42
|
-
expect(limits.retentionDays).toBe(30);
|
|
43
|
-
// Untouched keys keep the plan's defaults rather than resetting to free.
|
|
44
|
-
expect(limits.meters.trackedTickers).toBe(DEFAULT_PLAN_LIMITS.support.meters.trackedTickers);
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
it('drops keys that no code enforces', () => {
|
|
48
|
-
const limits = normalizeLimits(
|
|
49
|
-
{ meters: { storageBytes: 5, wormholes: 1000 }, features: { cleanExport: true, teleport: true } },
|
|
50
|
-
'free'
|
|
51
|
-
);
|
|
52
|
-
|
|
53
|
-
expect(limits.meters).not.toHaveProperty('wormholes');
|
|
54
|
-
expect(limits.features).not.toHaveProperty('teleport');
|
|
55
|
-
expect(Object.keys(limits.meters).sort()).toEqual([...METER_KEYS].sort());
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
it('normalizes any negative ceiling to UNLIMITED and floors fractions', () => {
|
|
59
|
-
const limits = normalizeLimits({ meters: { aiJobs: -5, trackedTickers: 7.9 }, retentionDays: -2 }, 'free');
|
|
60
|
-
|
|
61
|
-
expect(limits.meters.aiJobs).toBe(UNLIMITED);
|
|
62
|
-
expect(limits.meters.trackedTickers).toBe(7);
|
|
63
|
-
expect(limits.retentionDays).toBe(UNLIMITED);
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
it('ignores non-numeric and non-boolean junk instead of producing NaN limits', () => {
|
|
67
|
-
const limits = normalizeLimits(
|
|
68
|
-
{ meters: { seats: 'lots' as unknown as number }, features: { cleanExport: 'yes' as unknown as boolean } },
|
|
69
|
-
'support'
|
|
70
|
-
);
|
|
71
|
-
|
|
72
|
-
expect(limits.meters.seats).toBe(DEFAULT_PLAN_LIMITS.support.meters.seats);
|
|
73
|
-
expect(limits.features.cleanExport).toBe(true);
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
it('returns the plan defaults for an empty or missing payload', () => {
|
|
77
|
-
expect(normalizeLimits(undefined, 'support')).toEqual(DEFAULT_PLAN_LIMITS.support);
|
|
78
|
-
expect(normalizeLimits(null, 'support')).toEqual(DEFAULT_PLAN_LIMITS.support);
|
|
79
|
-
expect(normalizeLimits({}, 'support')).toEqual(DEFAULT_PLAN_LIMITS.support);
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
it('resolves an unknown plan code to free even when limits are stored', () => {
|
|
83
|
-
const limits = normalizeLimits({ meters: { seats: 3 } }, 'gold-tier-that-never-shipped');
|
|
84
|
-
|
|
85
|
-
expect(limits.meters.seats).toBe(3);
|
|
86
|
-
expect(limits.meters.storageBytes).toBe(DEFAULT_PLAN_LIMITS.free.meters.storageBytes);
|
|
87
|
-
expect(limits.features.cleanExport).toBe(false);
|
|
88
|
-
});
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
describe('applyLimits', () => {
|
|
92
|
-
it('layers a partial set over a complete one without mutating the base', () => {
|
|
93
|
-
const base = resolveLimits('free');
|
|
94
|
-
|
|
95
|
-
const layered = applyLimits(base, { meters: { storageBytes: 500 } });
|
|
96
|
-
|
|
97
|
-
expect(layered.meters.storageBytes).toBe(500);
|
|
98
|
-
expect(base.meters.storageBytes).toBe(DEFAULT_PLAN_LIMITS.free.meters.storageBytes);
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
it('stacks: defaults, then plan, then a per-user override', () => {
|
|
102
|
-
const planLimits = normalizeLimits({ meters: { storageBytes: 100, seats: 2 } }, 'free');
|
|
103
|
-
|
|
104
|
-
const withOverride = applyLimits(planLimits, { meters: { storageBytes: 5000 }, features: { cleanExport: true } });
|
|
105
|
-
|
|
106
|
-
expect(withOverride.meters.storageBytes).toBe(5000); // override wins
|
|
107
|
-
expect(withOverride.meters.seats).toBe(2); // plan wins where the override is silent
|
|
108
|
-
expect(withOverride.meters.aiJobs).toBe(DEFAULT_PLAN_LIMITS.free.meters.aiJobs); // default underneath both
|
|
109
|
-
expect(withOverride.features.cleanExport).toBe(true);
|
|
110
|
-
});
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
describe('the staff plan', () => {
|
|
114
|
-
it('grants every meter and feature without limit', () => {
|
|
115
|
-
const limits = resolveLimits(STAFF_PLAN);
|
|
116
|
-
|
|
117
|
-
for (const meter of METER_KEYS) {
|
|
118
|
-
expect(limits.meters[meter]).toBe(UNLIMITED);
|
|
119
|
-
}
|
|
120
|
-
expect(limits.retentionDays).toBe(UNLIMITED);
|
|
121
|
-
expect(limits.features.cleanExport).toBe(true);
|
|
122
|
-
});
|
|
123
|
-
});
|
|
124
|
-
|
|
125
|
-
describe('fitsWithin', () => {
|
|
126
|
-
it('treats UNLIMITED as always fitting', () => {
|
|
127
|
-
expect(fitsWithin(UNLIMITED, Number.MAX_SAFE_INTEGER, 1)).toBe(true);
|
|
128
|
-
});
|
|
129
|
-
|
|
130
|
-
it('allows landing exactly on the limit but not passing it', () => {
|
|
131
|
-
expect(fitsWithin(10, 9, 1)).toBe(true);
|
|
132
|
-
expect(fitsWithin(10, 10, 1)).toBe(false);
|
|
133
|
-
});
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
describe('key registry', () => {
|
|
137
|
-
it('recognizes only registered keys', () => {
|
|
138
|
-
expect(isMeterKey('storageBytes')).toBe(true);
|
|
139
|
-
expect(isMeterKey('storagebytes')).toBe(false);
|
|
140
|
-
expect(isFeatureKey('cleanExport')).toBe(true);
|
|
141
|
-
expect(isFeatureKey('planner')).toBe(false);
|
|
142
|
-
});
|
|
143
|
-
|
|
144
|
-
it('assigns every meter a period', () => {
|
|
145
|
-
expect(meterPeriod('aiJobs')).toBe('MONTH');
|
|
146
|
-
expect(meterPeriod('storageBytes')).toBe('ALL');
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
it('gives every registered plan a value for every registered key', () => {
|
|
150
|
-
for (const [code, limits] of Object.entries(DEFAULT_PLAN_LIMITS)) {
|
|
151
|
-
for (const meter of METER_KEYS) {
|
|
152
|
-
expect(typeof limits.meters[meter]).toBe(`number`);
|
|
153
|
-
}
|
|
154
|
-
for (const feature of FEATURE_KEYS) {
|
|
155
|
-
expect(typeof limits.features[feature]).toBe('boolean');
|
|
156
|
-
}
|
|
157
|
-
expect(typeof limits.retentionDays).toBe(`number`);
|
|
158
|
-
expect(code).toBeTruthy();
|
|
159
|
-
}
|
|
160
|
-
});
|
|
161
|
-
});
|