@molecule/api-entitlements 1.0.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/LICENSE +115 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +19 -0
- package/dist/browser-guard.js.map +1 -0
- package/dist/cache.d.ts +120 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +163 -0
- package/dist/cache.js.map +1 -0
- package/dist/error.d.ts +43 -0
- package/dist/error.d.ts.map +1 -0
- package/dist/error.js +55 -0
- package/dist/error.js.map +1 -0
- package/dist/index.d.ts +101 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +101 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +129 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +155 -0
- package/dist/middleware.js.map +1 -0
- package/dist/provider.d.ts +35 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +51 -0
- package/dist/provider.js.map +1 -0
- package/dist/registry.d.ts +41 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +88 -0
- package/dist/registry.js.map +1 -0
- package/dist/types.d.ts +177 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +18 -0
- package/dist/types.js.map +1 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-entitlements` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-entitlements is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
19
|
+
//# sourceMappingURL=browser-guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.js","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,GAAG,UAIT,CAAA;AACD,IAAI,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IACrF,MAAM,IAAI,KAAK,CACb,qGAAqG;QACnG,sFAAsF;QACtF,iFAAiF;QACjF,0CAA0C,CAC7C,CAAA;AACH,CAAC"}
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-process plan-key cache.
|
|
3
|
+
*
|
|
4
|
+
* Resolving a user's effective plan key on every request would saturate the
|
|
5
|
+
* database connection pool under load. The plan cache holds a short-lived
|
|
6
|
+
* mapping from `userId` → effective plan key (with anonymous and expired-plan
|
|
7
|
+
* handling already applied), evicted by TTL and bounded by a max-entries cap.
|
|
8
|
+
*
|
|
9
|
+
* The cache is a module-level singleton — there is one cache per process,
|
|
10
|
+
* which is what production deployments want. Tests should call
|
|
11
|
+
* `clearPlanCache()` between cases to avoid cross-test contamination.
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* App-specific hook that maps a stored `(planKey, planExpiresAt)` pair to the
|
|
17
|
+
* EFFECTIVE plan key — applied by {@link getCachedPlanKey} on every cache miss
|
|
18
|
+
* before the value is cached, so the cached (hot-path) result already reflects
|
|
19
|
+
* the app's plan-key semantics.
|
|
20
|
+
*
|
|
21
|
+
* The cache itself only knows the generic expiry rule (a past `planExpiresAt`
|
|
22
|
+
* demotes to default). Conventions like "an in-app-purchase key with no expiry
|
|
23
|
+
* is unverified → demote to free" are APP-specific (the `apple*`/`google*`
|
|
24
|
+
* prefix set is defined by the app, not this package). Apps inject that rule
|
|
25
|
+
* here so the hot path and the app's own `resolveEffectivePlanKey` cannot
|
|
26
|
+
* diverge — there is one demotion implementation, reused.
|
|
27
|
+
*
|
|
28
|
+
* @param planKey - The user's stored plan key (or `null` when unset).
|
|
29
|
+
* @param planExpiresAt - The user's stored plan expiry, or `null`.
|
|
30
|
+
* @returns The effective plan key (possibly demoted), or `null` for default tier.
|
|
31
|
+
*/
|
|
32
|
+
export type EffectivePlanKeyResolver = (planKey: string | null, planExpiresAt: string | null | undefined) => string | null;
|
|
33
|
+
/** Configuration options for the plan cache. */
|
|
34
|
+
export interface PlanCacheOptions {
|
|
35
|
+
/** Cache entry TTL in milliseconds. Defaults to 5 minutes. */
|
|
36
|
+
ttlMs?: number;
|
|
37
|
+
/**
|
|
38
|
+
* Max number of cached entries. When exceeded, the oldest insertion-order
|
|
39
|
+
* entry is evicted on the next write. Defaults to 50,000.
|
|
40
|
+
*/
|
|
41
|
+
maxEntries?: number;
|
|
42
|
+
/**
|
|
43
|
+
* App-specific effective-plan-key demotion (see
|
|
44
|
+
* {@link EffectivePlanKeyResolver}). Applied on every cache MISS so the cached
|
|
45
|
+
* hot-path result already reflects the app's plan-key semantics — e.g. an
|
|
46
|
+
* in-app-purchase key with no expiry demoting to free. Defaults to identity.
|
|
47
|
+
* Pass `null` to clear a previously-set resolver back to identity.
|
|
48
|
+
*/
|
|
49
|
+
effectivePlanKeyResolver?: EffectivePlanKeyResolver | null;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Reconfigures the plan cache. Existing entries remain; only future
|
|
53
|
+
* insertions and TTL checks observe the new settings.
|
|
54
|
+
*
|
|
55
|
+
* @param options - Optional overrides for TTL, maxEntries, and the
|
|
56
|
+
* effective-plan-key resolver.
|
|
57
|
+
*/
|
|
58
|
+
export declare const configurePlanCache: (options?: PlanCacheOptions) => void;
|
|
59
|
+
/**
|
|
60
|
+
* Drops every cached plan-key entry. Intended for tests and graceful
|
|
61
|
+
* shutdown — production code should not need to call this.
|
|
62
|
+
*/
|
|
63
|
+
export declare const clearPlanCache: () => void;
|
|
64
|
+
/**
|
|
65
|
+
* Returns the number of currently cached entries. Mainly useful for tests
|
|
66
|
+
* and operational metrics.
|
|
67
|
+
*
|
|
68
|
+
* @returns Current cache size.
|
|
69
|
+
*/
|
|
70
|
+
export declare const planCacheSize: () => number;
|
|
71
|
+
/**
|
|
72
|
+
* Resolve the effective plan key for a user, hitting the cache on warm reads
|
|
73
|
+
* and falling back to a DB lookup on cache miss.
|
|
74
|
+
*
|
|
75
|
+
* The effective plan key:
|
|
76
|
+
* - Returns `'anonymous'` for users flagged as anonymous, regardless of stored plan.
|
|
77
|
+
* - Returns `null` for users whose `planExpiresAt` is in the past — callers
|
|
78
|
+
* should treat this as the default tier.
|
|
79
|
+
* - Returns the stored plan key otherwise (or `null` if none was stored).
|
|
80
|
+
*
|
|
81
|
+
* @param userId - The user ID to look up.
|
|
82
|
+
* @returns The effective plan key, or `null` for default-tier users.
|
|
83
|
+
*/
|
|
84
|
+
export declare const getCachedPlanKey: (userId: string) => Promise<string | null>;
|
|
85
|
+
/**
|
|
86
|
+
* Resolve a user's effective plan key AND the plan expiry it was derived from,
|
|
87
|
+
* hitting the same cache {@link getCachedPlanKey} uses.
|
|
88
|
+
*
|
|
89
|
+
* Exists because the expiry is already read on every cache miss: a consumer
|
|
90
|
+
* that needs the subscription's period boundary — an allowance that refreshes
|
|
91
|
+
* with the billing period, a renewal countdown — can have it for free instead
|
|
92
|
+
* of issuing its own per-request user lookup, which is precisely the database
|
|
93
|
+
* load this cache was introduced to remove.
|
|
94
|
+
*
|
|
95
|
+
* `planExpiresAt` is the STORED value, not an effective one: it is `null` for
|
|
96
|
+
* anonymous/free users and may be in the past for a plan that has just lapsed
|
|
97
|
+
* (in which case `planKey` is already demoted to `null`).
|
|
98
|
+
*
|
|
99
|
+
* @param userId - The user ID to look up.
|
|
100
|
+
* @returns The effective plan key and the stored plan expiry.
|
|
101
|
+
*/
|
|
102
|
+
export declare const getCachedPlanState: (userId: string) => Promise<{
|
|
103
|
+
planKey: string | null;
|
|
104
|
+
planExpiresAt: string | null;
|
|
105
|
+
}>;
|
|
106
|
+
/**
|
|
107
|
+
* Invalidate a single user's cached plan-key entry. Call this immediately
|
|
108
|
+
* after writing a new `planKey` / `planExpiresAt` to the user record (e.g.
|
|
109
|
+
* from a webhook handler) so the next request reflects the change without
|
|
110
|
+
* waiting out the TTL.
|
|
111
|
+
*
|
|
112
|
+
* @param userId - The user ID whose cache entry should be evicted.
|
|
113
|
+
*/
|
|
114
|
+
export declare const invalidateCachedPlanKey: (userId: string) => void;
|
|
115
|
+
/**
|
|
116
|
+
* Sweep expired entries from the cache. Safe to call from a recurring
|
|
117
|
+
* cleanup interval; idempotent and O(n) in cache size.
|
|
118
|
+
*/
|
|
119
|
+
export declare const sweepExpiredPlanCacheEntries: () => void;
|
|
120
|
+
//# sourceMappingURL=cache.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAsBH;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,wBAAwB,GAAG,CACrC,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,aAAa,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,KACrC,MAAM,GAAG,IAAI,CAAA;AAElB,gDAAgD;AAChD,MAAM,WAAW,gBAAgB;IAC/B,8DAA8D;IAC9D,KAAK,CAAC,EAAE,MAAM,CAAA;IAEd;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IAEnB;;;;;;OAMG;IACH,wBAAwB,CAAC,EAAE,wBAAwB,GAAG,IAAI,CAAA;CAC3D;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,GAAI,UAAS,gBAAqB,KAAG,IAMnE,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,QAAO,IAEjC,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,aAAa,QAAO,MAEhC,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,gBAAgB,GAAU,QAAQ,MAAM,KAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAE5E,CAAA;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,kBAAkB,GAC7B,QAAQ,MAAM,KACb,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAkDlE,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,uBAAuB,GAAI,QAAQ,MAAM,KAAG,IAExD,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,4BAA4B,QAAO,IAK/C,CAAA"}
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-process plan-key cache.
|
|
3
|
+
*
|
|
4
|
+
* Resolving a user's effective plan key on every request would saturate the
|
|
5
|
+
* database connection pool under load. The plan cache holds a short-lived
|
|
6
|
+
* mapping from `userId` → effective plan key (with anonymous and expired-plan
|
|
7
|
+
* handling already applied), evicted by TTL and bounded by a max-entries cap.
|
|
8
|
+
*
|
|
9
|
+
* The cache is a module-level singleton — there is one cache per process,
|
|
10
|
+
* which is what production deployments want. Tests should call
|
|
11
|
+
* `clearPlanCache()` between cases to avoid cross-test contamination.
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
import { findById } from '@molecule/api-database';
|
|
16
|
+
const DEFAULT_TTL_MS = 300_000; // 5 minutes
|
|
17
|
+
const DEFAULT_MAX_ENTRIES = 50_000;
|
|
18
|
+
let ttlMs = DEFAULT_TTL_MS;
|
|
19
|
+
let maxEntries = DEFAULT_MAX_ENTRIES;
|
|
20
|
+
/**
|
|
21
|
+
* Optional app-specific demotion applied to the freshly-resolved
|
|
22
|
+
* `(planKey, planExpiresAt)` on a cache MISS, before the result is cached.
|
|
23
|
+
* Defaults to identity (no demotion). See {@link EffectivePlanKeyResolver} and
|
|
24
|
+
* {@link configurePlanCache}.
|
|
25
|
+
*/
|
|
26
|
+
let resolveEffective = (planKey) => planKey;
|
|
27
|
+
const cache = new Map();
|
|
28
|
+
/**
|
|
29
|
+
* Reconfigures the plan cache. Existing entries remain; only future
|
|
30
|
+
* insertions and TTL checks observe the new settings.
|
|
31
|
+
*
|
|
32
|
+
* @param options - Optional overrides for TTL, maxEntries, and the
|
|
33
|
+
* effective-plan-key resolver.
|
|
34
|
+
*/
|
|
35
|
+
export const configurePlanCache = (options = {}) => {
|
|
36
|
+
if (options.ttlMs != null)
|
|
37
|
+
ttlMs = options.ttlMs;
|
|
38
|
+
if (options.maxEntries != null)
|
|
39
|
+
maxEntries = options.maxEntries;
|
|
40
|
+
if (options.effectivePlanKeyResolver !== undefined) {
|
|
41
|
+
resolveEffective = options.effectivePlanKeyResolver ?? ((planKey) => planKey);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Drops every cached plan-key entry. Intended for tests and graceful
|
|
46
|
+
* shutdown — production code should not need to call this.
|
|
47
|
+
*/
|
|
48
|
+
export const clearPlanCache = () => {
|
|
49
|
+
cache.clear();
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Returns the number of currently cached entries. Mainly useful for tests
|
|
53
|
+
* and operational metrics.
|
|
54
|
+
*
|
|
55
|
+
* @returns Current cache size.
|
|
56
|
+
*/
|
|
57
|
+
export const planCacheSize = () => {
|
|
58
|
+
return cache.size;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Resolve the effective plan key for a user, hitting the cache on warm reads
|
|
62
|
+
* and falling back to a DB lookup on cache miss.
|
|
63
|
+
*
|
|
64
|
+
* The effective plan key:
|
|
65
|
+
* - Returns `'anonymous'` for users flagged as anonymous, regardless of stored plan.
|
|
66
|
+
* - Returns `null` for users whose `planExpiresAt` is in the past — callers
|
|
67
|
+
* should treat this as the default tier.
|
|
68
|
+
* - Returns the stored plan key otherwise (or `null` if none was stored).
|
|
69
|
+
*
|
|
70
|
+
* @param userId - The user ID to look up.
|
|
71
|
+
* @returns The effective plan key, or `null` for default-tier users.
|
|
72
|
+
*/
|
|
73
|
+
export const getCachedPlanKey = async (userId) => {
|
|
74
|
+
return (await getCachedPlanState(userId)).planKey;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Resolve a user's effective plan key AND the plan expiry it was derived from,
|
|
78
|
+
* hitting the same cache {@link getCachedPlanKey} uses.
|
|
79
|
+
*
|
|
80
|
+
* Exists because the expiry is already read on every cache miss: a consumer
|
|
81
|
+
* that needs the subscription's period boundary — an allowance that refreshes
|
|
82
|
+
* with the billing period, a renewal countdown — can have it for free instead
|
|
83
|
+
* of issuing its own per-request user lookup, which is precisely the database
|
|
84
|
+
* load this cache was introduced to remove.
|
|
85
|
+
*
|
|
86
|
+
* `planExpiresAt` is the STORED value, not an effective one: it is `null` for
|
|
87
|
+
* anonymous/free users and may be in the past for a plan that has just lapsed
|
|
88
|
+
* (in which case `planKey` is already demoted to `null`).
|
|
89
|
+
*
|
|
90
|
+
* @param userId - The user ID to look up.
|
|
91
|
+
* @returns The effective plan key and the stored plan expiry.
|
|
92
|
+
*/
|
|
93
|
+
export const getCachedPlanState = async (userId) => {
|
|
94
|
+
const now = Date.now();
|
|
95
|
+
const cached = cache.get(userId);
|
|
96
|
+
if (cached && cached.expiresAt > now) {
|
|
97
|
+
return { planKey: cached.planKey, planExpiresAt: cached.planExpiresAt };
|
|
98
|
+
}
|
|
99
|
+
const user = await findById('users', userId);
|
|
100
|
+
let planKey;
|
|
101
|
+
if (user?.isAnonymous) {
|
|
102
|
+
planKey = 'anonymous';
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
planKey = user?.planKey ?? null;
|
|
106
|
+
if (planKey && user?.planExpiresAt) {
|
|
107
|
+
const expiresAt = new Date(user.planExpiresAt).getTime();
|
|
108
|
+
if (Number.isFinite(expiresAt) && expiresAt < now) {
|
|
109
|
+
planKey = null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
// Apply the app-specific effective-plan-key demotion (identity by default).
|
|
113
|
+
// Reuses the app's own `resolveEffectivePlanKey` so the hot path and the
|
|
114
|
+
// app cannot diverge — e.g. an `apple*`/`google*` IAP key with NO expiry is
|
|
115
|
+
// unverified and demotes to free here, exactly as it does off the hot path.
|
|
116
|
+
// (Anonymous keeps its 'anonymous' key — the resolver only sees real plans.)
|
|
117
|
+
planKey = resolveEffective(planKey, user?.planExpiresAt ?? null);
|
|
118
|
+
}
|
|
119
|
+
if (cache.size >= maxEntries) {
|
|
120
|
+
const firstKey = cache.keys().next().value;
|
|
121
|
+
if (firstKey != null)
|
|
122
|
+
cache.delete(firstKey);
|
|
123
|
+
}
|
|
124
|
+
// [C6-1] Cap the cache entry at the plan's actual expiry, not just the flat TTL: without
|
|
125
|
+
// this, a paid plan that lapses inside a warm window keeps returning the elevated planKey
|
|
126
|
+
// (and its higher tier limits) for up to a full TTL after the subscription ended — there
|
|
127
|
+
// is no event-based invalidation at the expiry instant. A finite future planExpiresAt is a
|
|
128
|
+
// deterministic demotion time; clamp to it so the cache demotes exactly when the plan
|
|
129
|
+
// lapses. (Lapsed plans already resolved to null above; anonymous/no-expiry keep the TTL.)
|
|
130
|
+
let expiresAt = now + ttlMs;
|
|
131
|
+
if (planKey && planKey !== 'anonymous' && user?.planExpiresAt) {
|
|
132
|
+
const planExpiry = new Date(user.planExpiresAt).getTime();
|
|
133
|
+
if (Number.isFinite(planExpiry) && planExpiry > now) {
|
|
134
|
+
expiresAt = Math.min(expiresAt, planExpiry);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const planExpiresAt = user?.planExpiresAt ?? null;
|
|
138
|
+
cache.set(userId, { planKey, expiresAt, planExpiresAt });
|
|
139
|
+
return { planKey, planExpiresAt };
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* Invalidate a single user's cached plan-key entry. Call this immediately
|
|
143
|
+
* after writing a new `planKey` / `planExpiresAt` to the user record (e.g.
|
|
144
|
+
* from a webhook handler) so the next request reflects the change without
|
|
145
|
+
* waiting out the TTL.
|
|
146
|
+
*
|
|
147
|
+
* @param userId - The user ID whose cache entry should be evicted.
|
|
148
|
+
*/
|
|
149
|
+
export const invalidateCachedPlanKey = (userId) => {
|
|
150
|
+
cache.delete(userId);
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* Sweep expired entries from the cache. Safe to call from a recurring
|
|
154
|
+
* cleanup interval; idempotent and O(n) in cache size.
|
|
155
|
+
*/
|
|
156
|
+
export const sweepExpiredPlanCacheEntries = () => {
|
|
157
|
+
const now = Date.now();
|
|
158
|
+
for (const [key, entry] of cache) {
|
|
159
|
+
if (entry.expiresAt <= now)
|
|
160
|
+
cache.delete(key);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
//# sourceMappingURL=cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.js","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AAIjD,MAAM,cAAc,GAAG,OAAO,CAAA,CAAC,YAAY;AAC3C,MAAM,mBAAmB,GAAG,MAAM,CAAA;AAElC,IAAI,KAAK,GAAG,cAAc,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a
|
|
5
|
+
* `LimitErrorPayload` so the client can render a typed upgrade prompt
|
|
6
|
+
* (current tier, current limit, next tier, upgraded limit, upgrade vs signup).
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import type { LimitErrorPayload, LimitType } from './types.js';
|
|
11
|
+
/** Options for building a limit error payload. */
|
|
12
|
+
export interface BuildLimitErrorOptions<TLimits = unknown> {
|
|
13
|
+
/** Identifier for the limit that was hit (e.g. `'maxProjects'`). */
|
|
14
|
+
limitType: LimitType;
|
|
15
|
+
/** The current user's tier category (e.g. `'free'`, `'anonymous'`). */
|
|
16
|
+
category: string;
|
|
17
|
+
/** The numeric limit that was exceeded. */
|
|
18
|
+
currentLimit: number;
|
|
19
|
+
/**
|
|
20
|
+
* Optional accessor that maps the next-up tier's `limits` to the relevant
|
|
21
|
+
* numeric value. When omitted, `upgradedLimit` is `null` and the upgrade
|
|
22
|
+
* prompt simply names the next tier without a number.
|
|
23
|
+
*/
|
|
24
|
+
resolveUpgradedLimit?: (nextLimits: TLimits) => number | null | undefined;
|
|
25
|
+
/** Seconds until the client should retry, when applicable. */
|
|
26
|
+
retryAfter?: number;
|
|
27
|
+
/** Optional override for the localized error message. */
|
|
28
|
+
message?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Build a `LimitErrorPayload` describing a tier-limit violation.
|
|
32
|
+
*
|
|
33
|
+
* Reads the bonded entitlements registry to resolve the next-up category and
|
|
34
|
+
* (optionally) the upgraded limit value. Anonymous users are flagged with
|
|
35
|
+
* `requiresSignup: true` so the client can offer a sign-up prompt rather than
|
|
36
|
+
* an upgrade prompt.
|
|
37
|
+
*
|
|
38
|
+
* @param options - The limit type, current tier category, current limit, and
|
|
39
|
+
* optional upgrade-limit resolver / retry-after / message override.
|
|
40
|
+
* @returns A structured payload safe to send as a 429 / 403 response body.
|
|
41
|
+
*/
|
|
42
|
+
export declare const buildLimitError: <TLimits = unknown>(options: BuildLimitErrorOptions<TLimits>) => LimitErrorPayload;
|
|
43
|
+
//# sourceMappingURL=error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAE9D,kDAAkD;AAClD,MAAM,WAAW,sBAAsB,CAAC,OAAO,GAAG,OAAO;IACvD,oEAAoE;IACpE,SAAS,EAAE,SAAS,CAAA;IAEpB,uEAAuE;IACvE,QAAQ,EAAE,MAAM,CAAA;IAEhB,2CAA2C;IAC3C,YAAY,EAAE,MAAM,CAAA;IAEpB;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,CAAC,UAAU,EAAE,OAAO,KAAK,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;IAEzE,8DAA8D;IAC9D,UAAU,CAAC,EAAE,MAAM,CAAA;IAEnB,yDAAyD;IACzD,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,GAAI,OAAO,GAAG,OAAO,EAC/C,SAAS,sBAAsB,CAAC,OAAO,CAAC,KACvC,iBAsCF,CAAA"}
|
package/dist/error.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured limit-error helpers.
|
|
3
|
+
*
|
|
4
|
+
* When a tier limit is exceeded, handlers and middleware return a
|
|
5
|
+
* `LimitErrorPayload` so the client can render a typed upgrade prompt
|
|
6
|
+
* (current tier, current limit, next tier, upgraded limit, upgrade vs signup).
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import { t } from '@molecule/api-i18n';
|
|
11
|
+
import { getProvider } from './provider.js';
|
|
12
|
+
/**
|
|
13
|
+
* Build a `LimitErrorPayload` describing a tier-limit violation.
|
|
14
|
+
*
|
|
15
|
+
* Reads the bonded entitlements registry to resolve the next-up category and
|
|
16
|
+
* (optionally) the upgraded limit value. Anonymous users are flagged with
|
|
17
|
+
* `requiresSignup: true` so the client can offer a sign-up prompt rather than
|
|
18
|
+
* an upgrade prompt.
|
|
19
|
+
*
|
|
20
|
+
* @param options - The limit type, current tier category, current limit, and
|
|
21
|
+
* optional upgrade-limit resolver / retry-after / message override.
|
|
22
|
+
* @returns A structured payload safe to send as a 429 / 403 response body.
|
|
23
|
+
*/
|
|
24
|
+
export const buildLimitError = (options) => {
|
|
25
|
+
const { limitType, category, currentLimit, resolveUpgradedLimit, retryAfter, message } = options;
|
|
26
|
+
const registry = getProvider();
|
|
27
|
+
const nextCategory = registry.getNextCategory(category);
|
|
28
|
+
const requiresSignup = category === 'anonymous';
|
|
29
|
+
let upgradedLimit = null;
|
|
30
|
+
if (nextCategory && resolveUpgradedLimit) {
|
|
31
|
+
const nextTier = registry.getAllTiers().find((tier) => tier.category === nextCategory);
|
|
32
|
+
if (nextTier) {
|
|
33
|
+
const value = resolveUpgradedLimit(nextTier.limits);
|
|
34
|
+
if (typeof value === 'number')
|
|
35
|
+
upgradedLimit = value;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const localizedMessage = message ??
|
|
39
|
+
t('entitlements.error.limitExceeded', { limitType, currentLimit, currentTier: category }, {
|
|
40
|
+
defaultValue: requiresSignup
|
|
41
|
+
? `Limit reached (${currentLimit}). Create a free account for more.`
|
|
42
|
+
: `Limit reached (${currentLimit}). Upgrade your plan for more.`,
|
|
43
|
+
});
|
|
44
|
+
return {
|
|
45
|
+
error: localizedMessage,
|
|
46
|
+
limitType,
|
|
47
|
+
currentLimit,
|
|
48
|
+
upgradedLimit,
|
|
49
|
+
currentTier: category,
|
|
50
|
+
upgradeTier: nextCategory,
|
|
51
|
+
requiresSignup,
|
|
52
|
+
...(retryAfter != null ? { retryAfter } : {}),
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
//# sourceMappingURL=error.js.map
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,CAAA;IAEH,OAAO;QACL,KAAK,EAAE,gBAAgB;QACvB,SAAS;QACT,YAAY;QACZ,aAAa;QACb,WAAW,EAAE,QAAQ;QACrB,WAAW,EAAE,YAAY;QACzB,cAAc;QACd,GAAG,CAAC,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC9C,CAAA;AACH,CAAC,CAAA"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tier-based entitlements core for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Provides the typed `Tier<TLimits>` / `TierRegistry<TLimits>` shapes, a
|
|
5
|
+
* per-process plan-key cache, and Express middleware factories that gate
|
|
6
|
+
* endpoints by tier category or quantitative limit.
|
|
7
|
+
*
|
|
8
|
+
* Apps declare their own `TLimits` shape, construct a registry via
|
|
9
|
+
* `defineTiers(...)`, and bond it via `setProvider(...)` at startup. The
|
|
10
|
+
* webhook glue that maps Stripe / Apple / Google subscription events to
|
|
11
|
+
* `users.planKey` already lives in `@molecule/api-resource-user`.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { defineTiers, setProvider, enforceLimit, requireCategoryAtLeast } from '@molecule/api-entitlements'
|
|
16
|
+
* import { count } from '@molecule/api-database'
|
|
17
|
+
*
|
|
18
|
+
* interface BlogLimits {
|
|
19
|
+
* maxPosts: number
|
|
20
|
+
* maxCommentsPerDay: number
|
|
21
|
+
* }
|
|
22
|
+
*
|
|
23
|
+
* const registry = defineTiers<BlogLimits>({
|
|
24
|
+
* tiers: {
|
|
25
|
+
* free: { planKey: 'free', category: 'free', name: 'Free', limits: { maxPosts: 5, maxCommentsPerDay: 50 } },
|
|
26
|
+
* stripeMonthly: { planKey: 'stripeMonthly', category: 'pro', name: 'Pro', limits: { maxPosts: 100, maxCommentsPerDay: 1000 } },
|
|
27
|
+
* },
|
|
28
|
+
* defaultPlanKey: 'free',
|
|
29
|
+
* categoryOrder: ['free', 'pro'],
|
|
30
|
+
* })
|
|
31
|
+
*
|
|
32
|
+
* setProvider(registry)
|
|
33
|
+
*
|
|
34
|
+
* // Gate the API routes — the SERVER enforces tiers, never the UI alone:
|
|
35
|
+
* router.post('/posts',
|
|
36
|
+
* enforceLimit<BlogLimits>({
|
|
37
|
+
* limitType: 'maxPosts',
|
|
38
|
+
* getLimit: (limits) => limits.maxPosts,
|
|
39
|
+
* getCurrent: (userId) => count('posts', [{ field: 'userId', operator: '=', value: userId }]),
|
|
40
|
+
* }),
|
|
41
|
+
* handlers.createPost,
|
|
42
|
+
* )
|
|
43
|
+
* router.get('/analytics', requireCategoryAtLeast('pro'), handlers.analytics)
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* @remarks
|
|
47
|
+
* - **Enforcement is middleware on the API route** (`requireCategory`,
|
|
48
|
+
* `requireCategoryAtLeast`, `enforceLimit`) — hiding a button in the UI is
|
|
49
|
+
* not entitlement enforcement. The middleware reads the authenticated user
|
|
50
|
+
* from `res.locals.session.userId`, so it must be registered AFTER the auth
|
|
51
|
+
* middleware; unauthenticated requests get a 401.
|
|
52
|
+
* - **`enforceLimit` blocks at `current >= limit`** and responds with a
|
|
53
|
+
* structured `LimitErrorPayload` (default 403; pass `status: 429` for
|
|
54
|
+
* usage-style limits) that the app's limit/upgrade notice renders — don't
|
|
55
|
+
* swallow it into a generic error page.
|
|
56
|
+
* - **It is a SOFT ceiling — `getCurrent` COUNTS, then the handler CREATES the
|
|
57
|
+
* resource afterwards.** Under concurrency N requests can all read the same
|
|
58
|
+
* `current < limit` and all create, so the limit can be exceeded by a few.
|
|
59
|
+
* That is fine for plan limits (max projects / seats / collaborators — a
|
|
60
|
+
* bounded, harmless overshoot). It is NOT enough for a HARD limit where going
|
|
61
|
+
* over is a real loss: money / wallet balances, physical inventory (stock,
|
|
62
|
+
* tickets, seats), or metered credits. Enforce THOSE atomically at the write
|
|
63
|
+
* with a conditional `UPDATE ... WHERE remaining >= $n RETURNING` that affects
|
|
64
|
+
* 0 rows when it wouldn't fit (or an advisory-lock reserve for a ledger SUM) —
|
|
65
|
+
* never a count-then-allow middleware.
|
|
66
|
+
* - **Plan keys are cached per process** (default 5-minute TTL). The
|
|
67
|
+
* resource-user payment webhook glue invalidates on plan change; any custom
|
|
68
|
+
* path that mutates a user's `planKey` must call
|
|
69
|
+
* `invalidateCachedPlanKey(userId)` or the old tier lingers until TTL.
|
|
70
|
+
* - Unknown, expired, or missing plan keys resolve to the `defaultPlanKey`
|
|
71
|
+
* tier — make the default tier's limits the safe floor.
|
|
72
|
+
* - The middleware factories are connect/Express-shaped conveniences. Other
|
|
73
|
+
* stacks (queues, websockets, non-Express frameworks) enforce the same tiers
|
|
74
|
+
* directly via `getProvider()` + `getCachedPlanKey(userId)`.
|
|
75
|
+
*
|
|
76
|
+
* @e2e
|
|
77
|
+
* Integration checklist — drive the real UI (live preview, no mocks), adapt
|
|
78
|
+
* each item to this app's actual screens/flows, and check every box off one
|
|
79
|
+
* by one. A box you can't check is an integration bug to fix — not a skip:
|
|
80
|
+
* - [ ] The pricing/plans surface lists every tier with its name, price, and limits
|
|
81
|
+
* (rendered from `/api/billing/tiers`, not hardcoded).
|
|
82
|
+
* - [ ] A free-tier user who hits a quantitative limit (e.g. creates the max
|
|
83
|
+
* allowed items, then one more) gets a visible limit/upgrade notice — never a
|
|
84
|
+
* silent failure, a blank page, or a raw 500.
|
|
85
|
+
* - [ ] The blocked action really is blocked server-side: after a full page reload
|
|
86
|
+
* the over-limit item was NOT created.
|
|
87
|
+
* - [ ] A higher-tier user (seed or upgrade one) can perform the same action that
|
|
88
|
+
* was blocked on the free tier.
|
|
89
|
+
* - [ ] Tier-gated features/sections are hidden or clearly locked for tiers that
|
|
90
|
+
* lack them, and usable for tiers that have them.
|
|
91
|
+
*
|
|
92
|
+
* @module
|
|
93
|
+
*/
|
|
94
|
+
export * from './browser-guard.js';
|
|
95
|
+
export * from './cache.js';
|
|
96
|
+
export * from './error.js';
|
|
97
|
+
export * from './middleware.js';
|
|
98
|
+
export * from './provider.js';
|
|
99
|
+
export * from './registry.js';
|
|
100
|
+
export * from './types.js';
|
|
101
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4FG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,YAAY,CAAA;AAC1B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA;AAC/B,cAAc,eAAe,CAAA;AAC7B,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
|