@classytic/access 0.1.1 → 0.2.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/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.md +150 -140
- package/dist/domain/access-decision.d.mts +28 -6
- package/dist/domain/access-decision.mjs +49 -5
- package/dist/{event-catalog-BGFNnlNJ.d.mts → event-catalog-Dxo3cxR3.d.mts} +0 -1
- package/dist/events/event-catalog.d.mts +1 -1
- package/dist/index.d.mts +849 -59
- package/dist/index.mjs +1531 -243
- package/dist/schemas/common.d.mts +0 -1
- package/dist/schemas/entitlement.d.mts +0 -1
- package/package.json +11 -11
package/dist/index.d.mts
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { AccessDecision, AccessGrantState, AccessReason, evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
|
|
2
|
-
import { d as accessEventDefinitions, f as ACCESS_EVENTS, p as AccessEventName, t as AccessEventDefinition } from "./event-catalog-
|
|
3
|
-
import { MultiTenantOptions, PluginType, Repository } from "@classytic/mongokit";
|
|
2
|
+
import { d as accessEventDefinitions, f as ACCESS_EVENTS, p as AccessEventName, t as AccessEventDefinition } from "./event-catalog-Dxo3cxR3.mjs";
|
|
3
|
+
import { ModelBlueprint, MultiTenantOptions, PluginType, Repository } from "@classytic/mongokit";
|
|
4
4
|
import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
|
|
5
|
+
import { InProcessEventBus, InProcessEventBusOptions } from "@classytic/primitives/event-infra";
|
|
5
6
|
import { Connection, Document, Model, Schema, Types } from "mongoose";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
7
|
+
import { StateMachine } from "@classytic/primitives/state-machine";
|
|
8
|
+
import { StatusHistory } from "@classytic/primitives/status-history";
|
|
9
|
+
import { SuspensionPolicy } from "@classytic/primitives/suspension";
|
|
10
|
+
import { EventTransport } from "@classytic/primitives/events";
|
|
11
|
+
import { OutboxStore } from "@classytic/primitives/outbox";
|
|
8
12
|
import { OffsetPaginationResult } from "@classytic/repo-core/pagination";
|
|
9
13
|
import { OperationContext } from "@classytic/primitives/context";
|
|
10
14
|
import { RetryPolicy } from "@classytic/repo-core/repository";
|
|
11
15
|
import { HttpError } from "@classytic/repo-core/errors";
|
|
12
|
-
|
|
13
16
|
//#region src/domain/enums/entitlement-status.enum.d.ts
|
|
14
17
|
/**
|
|
15
18
|
* Entitlement lifecycle status.
|
|
@@ -43,7 +46,67 @@ type EntitlementStatus = (typeof ENTITLEMENT_STATUS_VALUES)[number];
|
|
|
43
46
|
/** Statuses where the grant is still "live" (subject of the one-active-per-resource rule). */
|
|
44
47
|
declare const LIVE_STATUSES: readonly ["active", "suspended"];
|
|
45
48
|
declare const isEntitlementStatus: (v: unknown) => v is EntitlementStatus;
|
|
49
|
+
declare const ENTITLEMENT_TRANSITIONS: Record<EntitlementStatus, readonly EntitlementStatus[]>;
|
|
50
|
+
/**
|
|
51
|
+
* The lifecycle as a STATE MACHINE, over the same {@link ENTITLEMENT_TRANSITIONS}
|
|
52
|
+
* table above.
|
|
53
|
+
*
|
|
54
|
+
* ## Why a machine and not just the predicate
|
|
55
|
+
*
|
|
56
|
+
* The table was already declared and already enforced — `transitionInner` is the
|
|
57
|
+
* single write funnel and it refuses an illegal move. What was missing is
|
|
58
|
+
* everything DERIVED from the table, which every consumer was left to re-derive:
|
|
59
|
+
*
|
|
60
|
+
* - **`terminal`** — computed from the empty outgoing lists, so `revoked` and
|
|
61
|
+
* `refunded` are terminal and nothing else is. A reporting layer asking "is
|
|
62
|
+
* this grant finished" must not carry its own list; two lists drift, and the
|
|
63
|
+
* one in the report is the one nobody tests.
|
|
64
|
+
* - **`validTargets` / `validSources`** — for a UI offering the legal next moves,
|
|
65
|
+
* instead of a hardcoded button set that silently diverges from the table.
|
|
66
|
+
* - **`assertTransition`** — the shape `@classytic/mongokit`'s `applyTransition`
|
|
67
|
+
* consumes, so a CAS write can pre-flight legality from the same source.
|
|
68
|
+
*
|
|
69
|
+
* ## What this says about churn, and it matters
|
|
70
|
+
*
|
|
71
|
+
* `expired → active` is LEGAL: a renewal restarts the window. So `expired` is not
|
|
72
|
+
* terminal, and **an expired membership is not a churned one** — it is a lapsed
|
|
73
|
+
* one that may still come back. Any churn metric that counts `expired` as lost
|
|
74
|
+
* is counting people who renew a week late. The machine is the authority for that
|
|
75
|
+
* distinction rather than a definition retyped in a dashboard.
|
|
76
|
+
*
|
|
77
|
+
* `errorFactory` returns this package's own {@link InvalidEntitlementTransitionError}
|
|
78
|
+
* (409) so the wire contract is unchanged — the machine replaces the predicate,
|
|
79
|
+
* not the error.
|
|
80
|
+
*/
|
|
81
|
+
declare const ENTITLEMENT_MACHINE: StateMachine<EntitlementStatus>;
|
|
82
|
+
/**
|
|
83
|
+
* Delegates to {@link ENTITLEMENT_MACHINE}.
|
|
84
|
+
*
|
|
85
|
+
* Kept as a named export because it is part of the published surface; the body is
|
|
86
|
+
* now one line so the table cannot be consulted two different ways.
|
|
87
|
+
*/
|
|
46
88
|
declare function canEntitlementTransition(from: EntitlementStatus, to: EntitlementStatus): boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Is this grant finished for good? `revoked` / `refunded` only.
|
|
91
|
+
*
|
|
92
|
+
* Derived from the machine, never from a second list. `expired` and `consumed`
|
|
93
|
+
* are deliberately NOT terminal — both can return to `active` (renewal, top-up),
|
|
94
|
+
* and treating them as endings is how a report turns a late renewal into churn.
|
|
95
|
+
*/
|
|
96
|
+
declare function isTerminalEntitlementStatus(status: EntitlementStatus): boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Days after a lapse in which a renewal still counts as a renewal, not churn.
|
|
99
|
+
*
|
|
100
|
+
* 30 because a monthly membership renews monthly: a member who pays a week or two
|
|
101
|
+
* late is the ordinary case, not a loss. Shorter, and the number reports churn
|
|
102
|
+
* that walks back in the door; much longer, and a genuine loss stays uncounted
|
|
103
|
+
* for a quarter.
|
|
104
|
+
*
|
|
105
|
+
* A KERNEL default, not a host literal — the grace period is a business rule, and
|
|
106
|
+
* a threshold retyped per screen is how a dashboard and an export disagree about
|
|
107
|
+
* the same month. Override per call where a deployment genuinely differs.
|
|
108
|
+
*/
|
|
109
|
+
declare const DEFAULT_CHURN_GRACE_DAYS = 30;
|
|
47
110
|
//#endregion
|
|
48
111
|
//#region src/models/entitlement.model.d.ts
|
|
49
112
|
interface EntitlementUsage {
|
|
@@ -64,6 +127,62 @@ interface EntitlementDocument extends Document {
|
|
|
64
127
|
/** Sub-scope within the resource ('' = the whole resource; e.g. an API scope). */
|
|
65
128
|
scopeKey: string;
|
|
66
129
|
status: EntitlementStatus;
|
|
130
|
+
/**
|
|
131
|
+
* Mirror of `status ∈ {active, suspended}`, maintained by the repository's
|
|
132
|
+
* single transition funnel.
|
|
133
|
+
*
|
|
134
|
+
* Exists because the live-uniqueness rule must cover BOTH live statuses and a
|
|
135
|
+
* `partialFilterExpression` can only express equality portably. The earlier
|
|
136
|
+
* index covered `status: 'active'` alone, which left a hole an attacker (or an
|
|
137
|
+
* innocent re-purchase) could walk through: suspend a grant, call `grant()`
|
|
138
|
+
* again, and a SECOND active row appears for the same (subject, resource) —
|
|
139
|
+
* `check()` prefers the active one, so the suspension is silently bypassed.
|
|
140
|
+
* A gym freezes a member for non-payment; the member buys a day pass; the
|
|
141
|
+
* freeze stops meaning anything.
|
|
142
|
+
*
|
|
143
|
+
* `true` while live, `null` otherwise (never `false` — the partial index
|
|
144
|
+
* matches `live: true`, and null keeps terminal rows out of it so a
|
|
145
|
+
* re-purchase after expiry/refund still inserts freely). Same mirror-boolean
|
|
146
|
+
* pattern as DeviceCommand.`open`.
|
|
147
|
+
*
|
|
148
|
+
* ## ⚠ REQUIRED BACKFILL before deploying this version
|
|
149
|
+
*
|
|
150
|
+
* Rows written by an earlier version have NO `live` field. The default only
|
|
151
|
+
* applies to new documents, so those rows sit outside the partial unique
|
|
152
|
+
* index AND outside `grant()`'s live-keyed lookup — which would make `grant()`
|
|
153
|
+
* insert a DUPLICATE live row for an existing member, re-opening the very
|
|
154
|
+
* double-grant hole this field closes. Run once, per collection, before
|
|
155
|
+
* serving traffic:
|
|
156
|
+
*
|
|
157
|
+
* ```js
|
|
158
|
+
* db.entitlements.updateMany(
|
|
159
|
+
* { live: { $exists: false }, status: { $in: ['active', 'suspended'] } },
|
|
160
|
+
* { $set: { live: true } },
|
|
161
|
+
* );
|
|
162
|
+
* db.entitlements.updateMany(
|
|
163
|
+
* { live: { $exists: false } }, // everything terminal
|
|
164
|
+
* { $set: { live: null } },
|
|
165
|
+
* );
|
|
166
|
+
* ```
|
|
167
|
+
*
|
|
168
|
+
* Build the new index AFTER the backfill: creating a unique index over
|
|
169
|
+
* partially-populated data can fail on legitimate duplicates that the old
|
|
170
|
+
* (active-only) index allowed, and that failure is the signal to reconcile
|
|
171
|
+
* those rows by hand rather than to drop the constraint.
|
|
172
|
+
*/
|
|
173
|
+
live?: boolean | null;
|
|
174
|
+
/**
|
|
175
|
+
* Every origin that has been APPLIED to this grant — `"Model:ref"` keys,
|
|
176
|
+
* `$addToSet` on grant and on each renewal.
|
|
177
|
+
*
|
|
178
|
+
* This is what makes `grantByOrigin` replay-safe across renewals. The
|
|
179
|
+
* `originModel`/`originRef` fields hold only the LATEST paying origin, so
|
|
180
|
+
* after order B renews a grant first created by order A, a redelivered event
|
|
181
|
+
* for A would no longer find its origin on the row — and would re-run the
|
|
182
|
+
* renewal with A's STALE window. Membership in this set is the durable fact
|
|
183
|
+
* "this origin already did its work", checked before any renewal runs.
|
|
184
|
+
*/
|
|
185
|
+
appliedOrigins?: string[];
|
|
67
186
|
/** How the grant came to be — drives reporting, not access. */
|
|
68
187
|
source: 'purchase' | 'subscription' | 'trial' | 'grant' | 'manual' | 'system';
|
|
69
188
|
grantedAt: Date;
|
|
@@ -80,12 +199,44 @@ interface EntitlementDocument extends Document {
|
|
|
80
199
|
renewedFromRef?: string;
|
|
81
200
|
reason?: string;
|
|
82
201
|
suspendedAt?: Date;
|
|
202
|
+
/**
|
|
203
|
+
* Append-only log of every status change — `primitives/status-history`.
|
|
204
|
+
*
|
|
205
|
+
* Load-bearing for the pause ALLOWANCE, not just an audit nicety. `suspendedAt`
|
|
206
|
+
* is a single field each new freeze overwrites, so "60 days per year" is
|
|
207
|
+
* unenforceable from it: a member's eleventh freeze looks identical to their
|
|
208
|
+
* first. Every pause and resume is already a transition, so the log IS the
|
|
209
|
+
* history, and `primitives/suspension.spansFromStatusHistory` turns it into the
|
|
210
|
+
* spans the allowance maths needs — no second denormalisation to keep in step.
|
|
211
|
+
*/
|
|
212
|
+
statusHistory?: StatusHistory<EntitlementStatus>;
|
|
213
|
+
/**
|
|
214
|
+
* When a suspension MUST end — the auto-resume deadline.
|
|
215
|
+
*
|
|
216
|
+
* Computed by the CALLER from its pause policy
|
|
217
|
+
* (`primitives/suspension.evaluateSuspension`) and stored here, so the sweep
|
|
218
|
+
* acts on the date the member was actually told. Re-deriving it at sweep time
|
|
219
|
+
* would silently move that date whenever the policy changed.
|
|
220
|
+
*
|
|
221
|
+
* `null` = an open-ended pause with no bound. Deliberate but worth alerting on:
|
|
222
|
+
* an unbounded freeze is a subscription that stopped earning with nothing
|
|
223
|
+
* looking broken.
|
|
224
|
+
*/
|
|
225
|
+
autoResumeAt?: Date | null;
|
|
226
|
+
/**
|
|
227
|
+
* Whether the auto-resume should CREDIT the frozen days back onto the window.
|
|
228
|
+
*
|
|
229
|
+
* Stored WITH the suspension rather than read from policy at resume time, for
|
|
230
|
+
* the same reason as `autoResumeAt`: it is a promise made when the freeze began.
|
|
231
|
+
* A prepaid term credits; a rolling subscription that paused billing does not
|
|
232
|
+
* (see `resume`).
|
|
233
|
+
*/
|
|
234
|
+
creditWindowOnResume?: boolean;
|
|
83
235
|
revokedAt?: Date;
|
|
84
236
|
expiredAt?: Date;
|
|
85
237
|
consumedAt?: Date;
|
|
86
238
|
refundedAt?: Date;
|
|
87
239
|
metadata?: Record<string, unknown>;
|
|
88
|
-
deletedAt?: Date | null;
|
|
89
240
|
createdAt: Date;
|
|
90
241
|
updatedAt: Date;
|
|
91
242
|
version: number;
|
|
@@ -93,19 +244,24 @@ interface EntitlementDocument extends Document {
|
|
|
93
244
|
//#endregion
|
|
94
245
|
//#region src/models/create-models.d.ts
|
|
95
246
|
type AccessModelName = 'Entitlement';
|
|
96
|
-
interface
|
|
247
|
+
interface AccessModels {
|
|
97
248
|
Entitlement: Model<EntitlementDocument>;
|
|
98
249
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
250
|
+
interface DefineAccessModelsConfig {
|
|
251
|
+
/** Resolved tenant shape — `defineAccess` resolves it once (pure) and passes it here. */
|
|
252
|
+
tenant: ResolvedTenantConfig;
|
|
253
|
+
/** Mongoose auto-index builds. Default (undefined) leaves the schema default. */
|
|
254
|
+
autoIndex?: boolean | Partial<Record<AccessModelName, boolean>> | undefined;
|
|
255
|
+
/** Prepended to every collection name (multi-instance isolation). */
|
|
105
256
|
collectionPrefix?: string | undefined;
|
|
257
|
+
/** On a name collision: `false` (default) throws; `true` re-registers (test/dev fixtures). */
|
|
106
258
|
forceRecreate?: boolean | undefined;
|
|
107
259
|
}
|
|
108
|
-
|
|
260
|
+
/**
|
|
261
|
+
* Describe the Access model set as a connection-free blueprint. Pure — builds no schema and
|
|
262
|
+
* registers nothing until `.bind(connection)`.
|
|
263
|
+
*/
|
|
264
|
+
declare function defineAccessModels(config: DefineAccessModelsConfig): ModelBlueprint<AccessModels>;
|
|
109
265
|
//#endregion
|
|
110
266
|
//#region src/domain/ports/common.d.ts
|
|
111
267
|
/**
|
|
@@ -129,6 +285,47 @@ interface AccessContext extends OperationContext {
|
|
|
129
285
|
//#endregion
|
|
130
286
|
//#region src/repositories/entitlement.repository.d.ts
|
|
131
287
|
type EntitlementSource = 'purchase' | 'subscription' | 'trial' | 'grant' | 'manual' | 'system';
|
|
288
|
+
/** One desired entitlement in a reconcile set — carries its target org. */
|
|
289
|
+
interface EntitlementDesiredItem {
|
|
290
|
+
resourceType: string;
|
|
291
|
+
resourceRef: string;
|
|
292
|
+
scopeKey?: string | undefined;
|
|
293
|
+
usageLimit?: number | null | undefined;
|
|
294
|
+
accessExpiresAt?: Date | null | undefined;
|
|
295
|
+
organizationId: string;
|
|
296
|
+
}
|
|
297
|
+
interface ReconcileEntitlementSetInput {
|
|
298
|
+
subject: {
|
|
299
|
+
subjectModel: string;
|
|
300
|
+
subjectRef: string;
|
|
301
|
+
};
|
|
302
|
+
/** The origin whose projected entitlements are reconciled (an Agreement id). */
|
|
303
|
+
agreementRef: string;
|
|
304
|
+
desired: readonly EntitlementDesiredItem[];
|
|
305
|
+
/** Grant source for newly-created rights. Default `'subscription'`. */
|
|
306
|
+
source?: EntitlementSource | undefined;
|
|
307
|
+
/**
|
|
308
|
+
* AUDIT / PROVENANCE only - the amendment mutation ref, recorded in revoke
|
|
309
|
+
* reasons so a removal can be traced to the change that caused it.
|
|
310
|
+
*
|
|
311
|
+
* NOT an idempotency key, and deliberately so. This used to be documented as an
|
|
312
|
+
* "idempotency stamp", which was wrong in a way that mattered: nothing reads it
|
|
313
|
+
* as a key, and `spine-contract`'s `EntitlementPort` was written against that
|
|
314
|
+
* claim. Reconcile's idempotency comes from the DESIRED-SET DIFF plus the
|
|
315
|
+
* live-unique index - a replay finds the desired rows already live and retains
|
|
316
|
+
* them - which is stronger here, because a recovery re-drive legitimately carries
|
|
317
|
+
* a FRESH ref for the same desired state and ref-keyed dedup would refuse it.
|
|
318
|
+
*
|
|
319
|
+
* Pinned by `tests/integration/reconcile-entitlement-set.test.ts` ("idempotent by
|
|
320
|
+
* the DESIRED-SET DIFF, not by remembering mutationRef").
|
|
321
|
+
*/
|
|
322
|
+
mutationRef?: string | undefined;
|
|
323
|
+
}
|
|
324
|
+
interface ReconcileResult {
|
|
325
|
+
granted: number;
|
|
326
|
+
revoked: number;
|
|
327
|
+
retained: number;
|
|
328
|
+
}
|
|
132
329
|
interface GrantInput {
|
|
133
330
|
subjectRef: string;
|
|
134
331
|
subjectModel: string;
|
|
@@ -154,12 +351,47 @@ interface GrantInput {
|
|
|
154
351
|
* restarts the clock). Default true. Set false for pure idempotency.
|
|
155
352
|
*/
|
|
156
353
|
renew?: boolean | undefined;
|
|
354
|
+
/**
|
|
355
|
+
* What a re-grant does to the QUOTA when a live grant already exists.
|
|
356
|
+
*
|
|
357
|
+
* `'reset'` (default) — RENEWAL. A new period restarts the allowance:
|
|
358
|
+
* `usage.limit = usageLimit`, `usage.used = 0`. Correct for a monthly membership.
|
|
359
|
+
*
|
|
360
|
+
* `'add'` — TOP-UP. The buyer acquired MORE of the same thing, so the allowance grows and
|
|
361
|
+
* consumption is preserved: `usage.limit += usageLimit`, `usage.used` untouched.
|
|
362
|
+
*
|
|
363
|
+
* ## Why this had to become the caller's declaration
|
|
364
|
+
*
|
|
365
|
+
* Only the caller knows which act occurred, and getting it wrong silently destroys paid
|
|
366
|
+
* access. Two lines of an 8-session pack in ONE order both matched the same live row (the
|
|
367
|
+
* live-unique key is `(subjectModel, subjectRef, resourceType, resourceRef, scopeKey)`), so
|
|
368
|
+
* the second `'reset'` OVERWROTE the first: 16 sessions were paid for and 8 were enforceable,
|
|
369
|
+
* with `appliedOrigins` correctly listing both lines while `usage.limit` recorded one. The
|
|
370
|
+
* order-line ledger totalled 16, but enforcement reads the ENTITLEMENT, so the ledger was
|
|
371
|
+
* not the gate.
|
|
372
|
+
*
|
|
373
|
+
* `'reset'` also zeroes `usage.used`, which on a top-up silently UN-CONSUMES redemptions the
|
|
374
|
+
* member already spent.
|
|
375
|
+
*
|
|
376
|
+
* Defaulting to `'reset'` keeps every existing consumer's behaviour unchanged — a subscription
|
|
377
|
+
* renewal genuinely should reset — so this widens the contract without moving anyone.
|
|
378
|
+
*/
|
|
379
|
+
quotaMode?: 'reset' | 'add' | undefined;
|
|
157
380
|
}
|
|
158
|
-
/**
|
|
381
|
+
/**
|
|
382
|
+
* Identify the grant to check/consume: by id, or by (subject, resource).
|
|
383
|
+
*
|
|
384
|
+
* `resourceType` and `subjectModel` are optional for back-compat but SHOULD be
|
|
385
|
+
* passed by polymorphic hosts: two resource types sharing a `resourceRef` (a
|
|
386
|
+
* product id doubling as a facility key), or two subject namespaces sharing an
|
|
387
|
+
* id, are indistinguishable without them — and `check()` would answer for
|
|
388
|
+
* whichever row sorts first. When present they narrow the lookup exactly.
|
|
389
|
+
*/
|
|
159
390
|
type EntitlementTarget = {
|
|
160
391
|
id: string;
|
|
161
392
|
} | {
|
|
162
393
|
subjectRef: string;
|
|
394
|
+
subjectModel?: string | undefined;
|
|
163
395
|
resourceRef: string;
|
|
164
396
|
resourceType?: string | undefined;
|
|
165
397
|
scopeKey?: string | undefined;
|
|
@@ -167,19 +399,53 @@ type EntitlementTarget = {
|
|
|
167
399
|
interface CheckResult extends AccessDecision {
|
|
168
400
|
entitlement: EntitlementDocument | null;
|
|
169
401
|
}
|
|
402
|
+
/**
|
|
403
|
+
* The calendar window a reporting read covers.
|
|
404
|
+
*
|
|
405
|
+
* **Prefer the civil-date form** (`{ from: '2026-08-01', to: '2026-08-31' }`) — a
|
|
406
|
+
* period is a calendar span, and the repository resolves it against its own
|
|
407
|
+
* business zone. Passing instants makes the CALLER own that boundary, and every
|
|
408
|
+
* caller that owns it can get it wrong differently.
|
|
409
|
+
*/
|
|
410
|
+
interface ExpiryWindow {
|
|
411
|
+
from: Date | string;
|
|
412
|
+
to: Date | string;
|
|
413
|
+
}
|
|
170
414
|
interface EntitlementRepositoryConfig {
|
|
171
415
|
model: Model<EntitlementDocument>;
|
|
172
416
|
plugins?: PluginType[];
|
|
173
417
|
eventTransport?: EventTransport | undefined;
|
|
174
|
-
outbox?: OutboxStore
|
|
418
|
+
outbox?: OutboxStore | undefined;
|
|
175
419
|
logger?: {
|
|
176
420
|
error(message: string, ...args: unknown[]): void;
|
|
421
|
+
warn?(message: string, ...args: unknown[]): void;
|
|
177
422
|
} | undefined;
|
|
423
|
+
/** Standalone-mongod escape — see `AccessRuntime.allowNonTransactional`. Opt-IN. */
|
|
424
|
+
allowNonTransactional?: boolean | undefined;
|
|
425
|
+
/**
|
|
426
|
+
* The BUSINESS timezone, IANA (`'Asia/Dhaka'`) — the authority for resolving a
|
|
427
|
+
* calendar range into instants.
|
|
428
|
+
*
|
|
429
|
+
* Deliberately an IANA zone, not the `offsetMinutes` this package's suspension
|
|
430
|
+
* paths take per call: a fixed offset cannot be DST-correct, so in any zone that
|
|
431
|
+
* observes DST it is wrong for part of the year, and the failure is a window
|
|
432
|
+
* shifted by an hour that still returns a plausible list. `offsetMinutes` stays
|
|
433
|
+
* supported where it already is; new period-shaped reads use this.
|
|
434
|
+
*
|
|
435
|
+
* Defaults to `'UTC'`, which makes a deployment that never sets one behave
|
|
436
|
+
* exactly as it does today.
|
|
437
|
+
*/
|
|
438
|
+
timezone?: string | undefined;
|
|
178
439
|
}
|
|
179
440
|
declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
180
441
|
private readonly eventTransport;
|
|
181
442
|
private readonly outbox;
|
|
182
443
|
private readonly pkgLogger;
|
|
444
|
+
private readonly allowNonTransactional;
|
|
445
|
+
/** IANA business zone — see `EntitlementRepositoryConfig.timezone`. */
|
|
446
|
+
private readonly timezone;
|
|
447
|
+
/** Warn ONCE per repository, not once per grant — a per-tap log is noise nobody reads. */
|
|
448
|
+
private warnedNonTransactional;
|
|
183
449
|
constructor(config: EntitlementRepositoryConfig);
|
|
184
450
|
/**
|
|
185
451
|
* Grant access. Idempotent per (subject, resource, scope) live grant via
|
|
@@ -188,12 +454,36 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
188
454
|
* `access:granted` on first grant, `access:extended` on renewal.
|
|
189
455
|
*/
|
|
190
456
|
grant(input: GrantInput, ctx: AccessContext): Promise<EntitlementDocument>;
|
|
457
|
+
private grantInner;
|
|
191
458
|
/**
|
|
192
459
|
* Decide access RIGHT NOW. Read-only: loads the live grant (active or
|
|
193
460
|
* suspended) and runs `evaluateAccess`. Returns `{ allowed, reason, ... }`
|
|
194
461
|
* plus the entitlement (or null when none exists).
|
|
195
462
|
*/
|
|
196
463
|
check(target: EntitlementTarget, ctx: AccessContext): Promise<CheckResult>;
|
|
464
|
+
/**
|
|
465
|
+
* `check()` with the COMPLETE identity tuple required.
|
|
466
|
+
*
|
|
467
|
+
* Prefer this at any security boundary. `check()` keeps `subjectModel` and
|
|
468
|
+
* `resourceType` optional for back-compat, which means a polymorphic
|
|
469
|
+
* deployment can accidentally ask an ambiguous question: two subject
|
|
470
|
+
* namespaces sharing an id (a `user` and an `apiKey` both keyed `42`), or two
|
|
471
|
+
* resource types sharing a ref (a product id doubling as a facility key),
|
|
472
|
+
* resolve to whichever row sorts first. That is a silent wrong-grant answer,
|
|
473
|
+
* and it fails OPEN when the other namespace happens to hold a live grant.
|
|
474
|
+
*
|
|
475
|
+
* Rather than break every existing caller, the complete tuple is available as
|
|
476
|
+
* its own verb: a reviewer can see at the call site which question was asked,
|
|
477
|
+
* and `EntitlementTarget`'s optionality can be tightened in a future major
|
|
478
|
+
* without a silent behaviour change now.
|
|
479
|
+
*/
|
|
480
|
+
checkExact(target: {
|
|
481
|
+
subjectModel: string;
|
|
482
|
+
subjectRef: string;
|
|
483
|
+
resourceType: string;
|
|
484
|
+
resourceRef: string;
|
|
485
|
+
scopeKey?: string | undefined;
|
|
486
|
+
}, ctx: AccessContext): Promise<CheckResult>;
|
|
197
487
|
/**
|
|
198
488
|
* Spend `amount` metered units (a download, an API call, a seat). Atomic and
|
|
199
489
|
* race-safe: a metered grant only succeeds while `used + amount <= limit`
|
|
@@ -203,12 +493,82 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
203
493
|
* Throws `QuotaExhaustedError` when no unit is left.
|
|
204
494
|
*/
|
|
205
495
|
consume(target: EntitlementTarget, amount?: number, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
206
|
-
|
|
496
|
+
private consumeInner;
|
|
497
|
+
/**
|
|
498
|
+
* Pause access without ending it (active → suspended).
|
|
499
|
+
*
|
|
500
|
+
* `autoResumeAt` and `creditWindowOnResume` are the caller's POLICY DECISION,
|
|
501
|
+
* computed once here and stored on the grant — see the fields' docblocks. This
|
|
502
|
+
* kernel deliberately does not own the rulebook (max days per year, minimum
|
|
503
|
+
* length, notice) because those differ per product and per deployment;
|
|
504
|
+
* `primitives/suspension.evaluateSuspension` computes them and the host passes
|
|
505
|
+
* the answers in.
|
|
506
|
+
*
|
|
507
|
+
* Omitting `autoResumeAt` leaves the pause OPEN-ENDED, which is the pre-policy
|
|
508
|
+
* behaviour and still legal — but it is the shape where a freeze quietly stops
|
|
509
|
+
* the business earning, so a deployment with any allowance at all should always
|
|
510
|
+
* pass one.
|
|
511
|
+
*/
|
|
207
512
|
suspend(id: string, options?: {
|
|
208
513
|
reason?: string | undefined;
|
|
514
|
+
/**
|
|
515
|
+
* The pause RULEBOOK. Supply it and this method enforces the allowance and
|
|
516
|
+
* DERIVES `autoResumeAt` — the caller no longer computes a date by hand.
|
|
517
|
+
*
|
|
518
|
+
* Evaluation happens HERE rather than in a caller for the same reason
|
|
519
|
+
* muster evaluates admission inside its check-in: the allowance is a function
|
|
520
|
+
* of this aggregate's own history, and only the thing holding the aggregate
|
|
521
|
+
* can read it without a second round trip and a race.
|
|
522
|
+
*/
|
|
523
|
+
policy?: SuspensionPolicy | undefined;
|
|
524
|
+
/** Requested end. Omit for open-ended — the allowance then decides. */
|
|
525
|
+
endsAt?: Date | null | undefined;
|
|
526
|
+
/** For the notice check. Defaults to now. */
|
|
527
|
+
requestedAt?: Date | undefined;
|
|
528
|
+
/** Business-timezone offset for day boundaries. */
|
|
529
|
+
offsetMinutes?: number | undefined;
|
|
530
|
+
/**
|
|
531
|
+
* Explicit deadline, for a caller with no policy (the pre-policy path) or an
|
|
532
|
+
* operator override. IGNORED when `policy` is supplied — two sources for one
|
|
533
|
+
* date is how they drift.
|
|
534
|
+
*/
|
|
535
|
+
autoResumeAt?: Date | null | undefined;
|
|
536
|
+
creditWindowOnResume?: boolean | undefined;
|
|
537
|
+
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
538
|
+
/**
|
|
539
|
+
* Lift a suspension (suspended → active), optionally CREDITING the frozen time.
|
|
540
|
+
*
|
|
541
|
+
* ## Why `creditFrozenDays` exists, and why it is not the default
|
|
542
|
+
*
|
|
543
|
+
* A freeze on a PREPAID term is worthless without it. Consider a Jan–Jun
|
|
544
|
+
* membership (`accessExpiresAt = 1 Jul`) paused on 1 Feb and resumed on 1 Jul:
|
|
545
|
+
* without a credit the window is untouched, so the member resumes into an
|
|
546
|
+
* already-elapsed grant, is refused immediately, and the sweep flips it to
|
|
547
|
+
* `expired`. They paid for six months, used one, and got nothing back.
|
|
548
|
+
*
|
|
549
|
+
* (Note the sweep only touches `active` rows, so pausing does at least PROTECT
|
|
550
|
+
* the grant from expiring mid-freeze — it just comes back worthless.)
|
|
551
|
+
*
|
|
552
|
+
* But crediting is NOT universally right, which is why the caller must choose:
|
|
553
|
+
*
|
|
554
|
+
* - **Prepaid term** — money is already collected, so push the window out by
|
|
555
|
+
* the frozen duration. `creditFrozenDays: true`.
|
|
556
|
+
* - **Rolling subscription** — billing was PAUSED instead, so there is no end
|
|
557
|
+
* date to extend. Crediting here would hand out a free month.
|
|
558
|
+
*
|
|
559
|
+
* Getting it wrong in either direction is a real complaint: credit AND keep
|
|
560
|
+
* billing means the member paid for frozen time; neither means they lost it. The
|
|
561
|
+
* decision belongs to whoever knows the product type, so this kernel takes it as
|
|
562
|
+
* a parameter rather than guessing — and a host reads it from its pause policy,
|
|
563
|
+
* never from a literal.
|
|
564
|
+
*
|
|
565
|
+
* Emits `access:extended` in addition to `access:resumed` when it credits, so a
|
|
566
|
+
* credential-sync subscriber sees the new window.
|
|
567
|
+
*/
|
|
568
|
+
resume(id: string, options?: {
|
|
569
|
+
creditFrozenDays?: boolean | undefined;
|
|
209
570
|
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
210
|
-
|
|
211
|
-
resume(id: string, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
571
|
+
private resumeInner;
|
|
212
572
|
/** Pull access permanently (active|suspended → revoked). Window cut to now. */
|
|
213
573
|
revoke(id: string, options?: {
|
|
214
574
|
reason?: string | undefined;
|
|
@@ -226,6 +586,175 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
226
586
|
accessExpiresAt?: Date | null | undefined;
|
|
227
587
|
addMs?: number | undefined;
|
|
228
588
|
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
589
|
+
private extendInner;
|
|
590
|
+
/**
|
|
591
|
+
* Resume suspensions that have reached their deadline.
|
|
592
|
+
*
|
|
593
|
+
* ## Why this sweep is a revenue control, not housekeeping
|
|
594
|
+
*
|
|
595
|
+
* A freeze with no automatic end is an indefinite free hold. The member pauses in
|
|
596
|
+
* February, the business stops earning, and nothing looks broken — so nobody
|
|
597
|
+
* files a bug and it is found by an audit months later, if at all. This closes
|
|
598
|
+
* that: the pause ends on the date it was capped at, whether or not the member
|
|
599
|
+
* ever comes back.
|
|
600
|
+
*
|
|
601
|
+
* ## It uses the STORED decision, never a fresh one
|
|
602
|
+
*
|
|
603
|
+
* Both `autoResumeAt` and `creditWindowOnResume` are read off the grant, not
|
|
604
|
+
* recomputed from current policy. They are promises made when the freeze began,
|
|
605
|
+
* and re-deriving them would silently move a date the member was told the moment
|
|
606
|
+
* an operator edited the rulebook. (`primitives/suspension.dueForAutoResume`
|
|
607
|
+
* documents the same rule for the pure form.)
|
|
608
|
+
*
|
|
609
|
+
* Per-row failures are collected, not thrown: one grant whose credit maths hits a
|
|
610
|
+
* VersionMismatch must not abort the sweep and leave the rest suspended.
|
|
611
|
+
*/
|
|
612
|
+
autoResumeDue(options?: {
|
|
613
|
+
now?: Date | undefined;
|
|
614
|
+
limit?: number | undefined;
|
|
615
|
+
}, ctx?: AccessContext): Promise<{
|
|
616
|
+
resumed: number;
|
|
617
|
+
failed: number;
|
|
618
|
+
}>;
|
|
619
|
+
/**
|
|
620
|
+
* The RENEWAL WORKLIST — grants whose access window closes inside a calendar
|
|
621
|
+
* range, soonest first.
|
|
622
|
+
*
|
|
623
|
+
* ## Why this is a domain verb and not a `getAll` the caller could write
|
|
624
|
+
*
|
|
625
|
+
* Three decisions live here that every caller would otherwise re-derive, and
|
|
626
|
+
* would eventually re-derive differently:
|
|
627
|
+
*
|
|
628
|
+
* 1. **Which statuses are renewable.** `active` AND `suspended`. A frozen
|
|
629
|
+
* membership still has an expiry date and still needs renewing — dropping it
|
|
630
|
+
* silently shortens the worklist, and the members missing from it are
|
|
631
|
+
* exactly the ones already at risk of leaving. `expired` is deliberately NOT
|
|
632
|
+
* here: lapsed grants are a different, later conversation (win-back), and
|
|
633
|
+
* mixing them makes "how many renewals are due" unanswerable.
|
|
634
|
+
* 2. **Open-ended grants are excluded.** `accessExpiresAt: null` means access
|
|
635
|
+
* does not lapse, so such a member never belongs on a renewal list.
|
|
636
|
+
*
|
|
637
|
+
* The `$ne: null` below is EXPLICIT, not load-bearing: a `$gte`/`$lte` date
|
|
638
|
+
* comparison already excludes `null` in MongoDB, so removing it changes
|
|
639
|
+
* nothing today. It is kept because the exclusion is a domain decision that
|
|
640
|
+
* should be readable at the filter rather than inferred from BSON comparison
|
|
641
|
+
* order — and because a future sentinel value (a far-future date standing in
|
|
642
|
+
* for "lifetime") would satisfy the range and silently reappear.
|
|
643
|
+
*
|
|
644
|
+
* An earlier draft of this docblock claimed the guard was what kept those
|
|
645
|
+
* rows out. Falsifying the filter disproved it; the claim is corrected here
|
|
646
|
+
* rather than left as a rationale that does not hold.
|
|
647
|
+
* 3. **The range is a CALENDAR range**, resolved against this repository's own
|
|
648
|
+
* business zone. "Expiring this month" is a business-month question; built
|
|
649
|
+
* from `Date.UTC` it disagrees with the filing month at both ends by the
|
|
650
|
+
* zone offset — six hours in Asia/Dhaka — so the first and last day of every
|
|
651
|
+
* window silently gain or lose members.
|
|
652
|
+
*
|
|
653
|
+
* ## Rows, not a count, and bounded
|
|
654
|
+
*
|
|
655
|
+
* A worklist is only useful as rows — the point is who to call. But it is
|
|
656
|
+
* paginated through the inherited `getAll`, so tenancy, soft-delete and the
|
|
657
|
+
* limit all apply; an unbounded list on an operator-facing screen is a
|
|
658
|
+
* self-inflicted load problem.
|
|
659
|
+
*
|
|
660
|
+
* Read-only: this never transitions anything. `expireDue` is the sweep that
|
|
661
|
+
* flips a lapsed grant to `expired`, and the two must not be confused — asking
|
|
662
|
+
* "who is about to lapse" must never cause a lapse.
|
|
663
|
+
*/
|
|
664
|
+
expiringBetween(range: ExpiryWindow, options?: {
|
|
665
|
+
/** Narrow to one product/plan. */
|
|
666
|
+
resourceType?: string | undefined;
|
|
667
|
+
resourceRef?: string | undefined;
|
|
668
|
+
/** Narrow to one population (`'Party'`, `'GymMember'`). */
|
|
669
|
+
subjectModel?: string | undefined;
|
|
670
|
+
scopeKey?: string | undefined;
|
|
671
|
+
/**
|
|
672
|
+
* Include frozen memberships. Default TRUE — see decision (1). Pass `false`
|
|
673
|
+
* only when the caller genuinely means "renewable right now".
|
|
674
|
+
*/
|
|
675
|
+
includeSuspended?: boolean | undefined;
|
|
676
|
+
limit?: number | undefined;
|
|
677
|
+
page?: number | undefined;
|
|
678
|
+
}, ctx?: AccessContext): Promise<OffsetPaginationResult<EntitlementDocument>>;
|
|
679
|
+
/**
|
|
680
|
+
* CHURN — grants that lapsed in a window and were NOT renewed within grace.
|
|
681
|
+
*
|
|
682
|
+
* ## The definition, and why it is this one
|
|
683
|
+
*
|
|
684
|
+
* Three things get called churn, and they give different numbers from the same
|
|
685
|
+
* data:
|
|
686
|
+
*
|
|
687
|
+
* | | counts | why not here |
|
|
688
|
+
* |---|---|---|
|
|
689
|
+
* | snapshot | active last period minus active this period | needs historical actives, which current rows cannot reconstruct |
|
|
690
|
+
* | cohort retention | of those who joined in M, how many at M+n | a different question (a retention curve), not "who did we lose" |
|
|
691
|
+
* | **lapsed-not-renewed** | expired in the window with no live grant inside grace | **this one** |
|
|
692
|
+
*
|
|
693
|
+
* The third, because {@link ENTITLEMENT_MACHINE} makes `expired -> active`
|
|
694
|
+
* LEGAL: a renewal restarts the window, so `expired` is not terminal and an
|
|
695
|
+
* expired grant is not by itself a loss. People renew late. A metric that counts
|
|
696
|
+
* them as churned reports losses that already walked back in, and an operator
|
|
697
|
+
* learns to distrust it.
|
|
698
|
+
*
|
|
699
|
+
* ## Why this needs no fact projection
|
|
700
|
+
*
|
|
701
|
+
* Expiry is a state TRANSITION, never a TTL-delete — the row survives (see
|
|
702
|
+
* `entitlement-status.enum.ts`: terminal states free the live-uniqueness slot,
|
|
703
|
+
* they do not remove history). So both sides of the question are in live data
|
|
704
|
+
* and this is a self-join.
|
|
705
|
+
*
|
|
706
|
+
* The historical ACTIVE COUNT is the part that genuinely needs a projection
|
|
707
|
+
* ("how many were active on 1 March" is not derivable from current rows). That
|
|
708
|
+
* is a separate build; conflating the two is what made this look bigger than it
|
|
709
|
+
* is.
|
|
710
|
+
*
|
|
711
|
+
* ## What counts as renewed
|
|
712
|
+
*
|
|
713
|
+
* A live grant (`active` or `suspended`) for the SAME subject and resource,
|
|
714
|
+
* granted no later than `lapse + graceDays`, whose own window outlasts the lapse
|
|
715
|
+
* (or never ends).
|
|
716
|
+
*
|
|
717
|
+
* Deliberately NOT "granted after the lapse": a member who pays early renews
|
|
718
|
+
* BEFORE expiry, so requiring the later date would count the most diligent
|
|
719
|
+
* members as churned.
|
|
720
|
+
*
|
|
721
|
+
* ## What is excluded from the lapse population
|
|
722
|
+
*
|
|
723
|
+
* `revoked` and `refunded` are terminal by decision — an admin pull, a dispute,
|
|
724
|
+
* a chargeback. Real losses, but not FAILURES TO RENEW, and folding them in
|
|
725
|
+
* makes the number unactionable: you cannot win back someone you ejected.
|
|
726
|
+
*/
|
|
727
|
+
churnBetween(range: ExpiryWindow, options?: {
|
|
728
|
+
/**
|
|
729
|
+
* Days after the lapse in which a renewal still counts. Defaults to
|
|
730
|
+
* {@link DEFAULT_CHURN_GRACE_DAYS}.
|
|
731
|
+
*/
|
|
732
|
+
graceDays?: number | undefined;
|
|
733
|
+
resourceType?: string | undefined;
|
|
734
|
+
resourceRef?: string | undefined;
|
|
735
|
+
subjectModel?: string | undefined;
|
|
736
|
+
scopeKey?: string | undefined;
|
|
737
|
+
/** Injectable clock, for {@link unsettledDays}. Tests pin it. */
|
|
738
|
+
now?: Date | undefined;
|
|
739
|
+
}, ctx?: AccessContext): Promise<{
|
|
740
|
+
lapsed: number;
|
|
741
|
+
renewed: number;
|
|
742
|
+
churned: number;
|
|
743
|
+
graceDays: number;
|
|
744
|
+
unsettledDays: number;
|
|
745
|
+
}>;
|
|
746
|
+
/**
|
|
747
|
+
* Resolve an {@link ExpiryWindow} to instants using THIS repository's business
|
|
748
|
+
* zone.
|
|
749
|
+
*
|
|
750
|
+
* Civil dates are the preferred form because a period is a calendar span;
|
|
751
|
+
* instants are accepted so a caller that already holds them (a cron with a
|
|
752
|
+
* computed cutoff) is not forced to round-trip through strings. A MIXED pair is
|
|
753
|
+
* refused rather than guessed — `{ from: '2026-08-01', to: someDate }` has no
|
|
754
|
+
* single obvious meaning, and silently picking one produces a window nobody
|
|
755
|
+
* asked for.
|
|
756
|
+
*/
|
|
757
|
+
private resolveExpiryWindow;
|
|
229
758
|
/**
|
|
230
759
|
* Sweep grants whose window has lapsed: CAS active → expired, emit
|
|
231
760
|
* `access:expired` per row. The row SURVIVES (audit / renewal); this is the
|
|
@@ -252,14 +781,134 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
252
781
|
}, ctx?: AccessContext): Promise<{
|
|
253
782
|
refunded: number;
|
|
254
783
|
}>;
|
|
784
|
+
/**
|
|
785
|
+
* Grant idempotently PER ORIGIN.
|
|
786
|
+
*
|
|
787
|
+
* `grant()` is already idempotent per (subject, resource, scope) — but it
|
|
788
|
+
* REFRESHES the window on a repeat, which is right for a genuine renewal and
|
|
789
|
+
* wrong for a redelivered event: an at-least-once bus would silently extend a
|
|
790
|
+
* membership every time it replayed. Keying on the origin separates the two —
|
|
791
|
+
* the same order never grants twice, a new order still renews.
|
|
792
|
+
*/
|
|
793
|
+
grantByOrigin(input: GrantInput & {
|
|
794
|
+
originModel: string;
|
|
795
|
+
originRef: string;
|
|
796
|
+
}, ctx: AccessContext): Promise<{
|
|
797
|
+
grant: EntitlementDocument;
|
|
798
|
+
created: boolean;
|
|
799
|
+
}>;
|
|
800
|
+
/**
|
|
801
|
+
* Move every live grant from one origin to `suspended` / `active` / `revoked`.
|
|
802
|
+
*
|
|
803
|
+
* Mirrors `refundByOrigin`: a CAS `claim` per row so a concurrent human action
|
|
804
|
+
* cannot be clobbered, and the lifecycle event emitted only when the claim won
|
|
805
|
+
* (so a redelivery emits nothing).
|
|
806
|
+
*
|
|
807
|
+
* `resume` deliberately only lifts SUSPENDED grants — resuming an expired or
|
|
808
|
+
* revoked one would resurrect access the domain already ended.
|
|
809
|
+
*/
|
|
810
|
+
setStateByOrigin(originModel: string, originRef: string, effect: 'suspend' | 'resume' | 'revoke', options?: {
|
|
811
|
+
reason?: string | undefined;
|
|
812
|
+
}, ctx?: AccessContext): Promise<{
|
|
813
|
+
changed: number;
|
|
814
|
+
}>;
|
|
815
|
+
/**
|
|
816
|
+
* Push the expiry of every live grant from one origin.
|
|
817
|
+
*
|
|
818
|
+
* Used when the SOURCE extends — a renewed subscription cycle. Idempotent by
|
|
819
|
+
* value: setting the same expiry twice changes nothing, so a redelivery is safe
|
|
820
|
+
* without needing to remember it was seen.
|
|
821
|
+
*/
|
|
822
|
+
extendByOrigin(originModel: string, originRef: string, accessExpiresAt: Date | null, ctx?: AccessContext): Promise<{
|
|
823
|
+
changed: number;
|
|
824
|
+
matched: number;
|
|
825
|
+
}>;
|
|
255
826
|
/** A subject's grants, newest-first ("my access"). */
|
|
256
827
|
listForSubject(subjectRef: string, ctx: AccessContext): Promise<OffsetPaginationResult<EntitlementDocument>>;
|
|
257
828
|
private transition;
|
|
829
|
+
private transitionInner;
|
|
830
|
+
/**
|
|
831
|
+
* Load a grant for a WRITE.
|
|
832
|
+
*
|
|
833
|
+
* `+statusHistory` overrides the schema's `select: false`. Every mutating path
|
|
834
|
+
* comes through here, and two of them require the log: `transition` appends to it,
|
|
835
|
+
* and `suspend` derives the pause allowance from it. Reading without it would make
|
|
836
|
+
* `transition` overwrite the whole array with a single entry — a silent history
|
|
837
|
+
* wipe that would then under-count every future allowance.
|
|
838
|
+
*/
|
|
258
839
|
private load;
|
|
259
840
|
/** Resolve the live (active|suspended) grant for a target, or null. */
|
|
260
841
|
private findLive;
|
|
261
842
|
private targetLabel;
|
|
262
843
|
private emitLifecycle;
|
|
844
|
+
/**
|
|
845
|
+
* Run a mutation + its event emission as ONE atomic unit.
|
|
846
|
+
*
|
|
847
|
+
* ## Why documentation was not enough
|
|
848
|
+
*
|
|
849
|
+
* With an outbox wired and no caller session, the mutation committed and then
|
|
850
|
+
* `outbox.save` ran. A save failure threw — leaving state changed and the
|
|
851
|
+
* event permanently missing. The previous docblock claimed this was safe to
|
|
852
|
+
* retry because every verb is CAS-guarded. That claim was WRONG, and in the
|
|
853
|
+
* most dangerous direction:
|
|
854
|
+
*
|
|
855
|
+
* - `consume()` is atomic but NOT idempotent — a retry spends the units AGAIN.
|
|
856
|
+
* - `resume()` retried hits an invalid transition (already active) and never
|
|
857
|
+
* re-emits, so the credential-sync subscriber never learns the member is back.
|
|
858
|
+
* - `revoke()` / `refund()` retried hit a terminal status — same lost event,
|
|
859
|
+
* and this one means a door stays open after a refund.
|
|
860
|
+
*
|
|
861
|
+
* So the fix is a real transaction, not better wording. The mutation and the
|
|
862
|
+
* outbox row now commit or roll back together, which is what the
|
|
863
|
+
* transactional-outbox pattern actually requires.
|
|
864
|
+
*
|
|
865
|
+
* ## Two pass-through cases, both deliberate
|
|
866
|
+
*
|
|
867
|
+
* - **No outbox** — there is no second write to be atomic WITH, and taxing
|
|
868
|
+
* every door-tap check with a session would buy nothing.
|
|
869
|
+
* - **Caller supplied `ctx.session`** — the host owns a wider unit of work;
|
|
870
|
+
* opening our own here would either nest or silently commit a slice of
|
|
871
|
+
* theirs. Passing through is also what makes this safe to apply at several
|
|
872
|
+
* layers: an outer `resume` wraps once, and the inner `transition` sees the
|
|
873
|
+
* session and does not re-wrap.
|
|
874
|
+
*
|
|
875
|
+
* Requires a replica set (this deployment already mandates one for POS and
|
|
876
|
+
* muster). A single-node mongod without one cannot start a session, which
|
|
877
|
+
* surfaces at the first write rather than silently degrading.
|
|
878
|
+
*/
|
|
879
|
+
/**
|
|
880
|
+
* Reconcile a subject's entitlements from ONE origin (typically an
|
|
881
|
+
* `Agreement`) to a DESIRED SET — the primitive a plan change drives. It
|
|
882
|
+
* computes the diff against the live entitlements currently projected from
|
|
883
|
+
* that origin and, in ONE atomic unit (transactional outbox), GRANTS the
|
|
884
|
+
* missing, REVOKES the extra, and RETAINS the matches. Idempotent: re-running
|
|
885
|
+
* the same desired set is a no-op (grant-by-origin dedupes; only live rows are
|
|
886
|
+
* revoked).
|
|
887
|
+
*
|
|
888
|
+
* ORG-PARTITIONED: each desired item carries its target `organizationId`, and
|
|
889
|
+
* the current set is discovered across orgs (a downgrade may drop a right in a
|
|
890
|
+
* different branch). Every write runs under an org-scoped ctx that reuses the
|
|
891
|
+
* single session, so a Gold→floor+pool bundle across branches still applies or
|
|
892
|
+
* rolls back as a unit. Authority (who may reconcile) is the caller's to
|
|
893
|
+
* check; a caller-supplied org is only ever a WRITE target, never trusted as
|
|
894
|
+
* identity.
|
|
895
|
+
*/
|
|
896
|
+
reconcileEntitlementSet(input: ReconcileEntitlementSetInput, ctx: AccessContext): Promise<ReconcileResult>;
|
|
897
|
+
private atomically;
|
|
898
|
+
/**
|
|
899
|
+
* Assert the event path is usable BEFORE any mutation.
|
|
900
|
+
*
|
|
901
|
+
* `emitDomainEvent` throws `UnmanagedSessionError` when a host passes a
|
|
902
|
+
* session with no outbox — but every verb emits AFTER writing, so the guard
|
|
903
|
+
* used to fire with the entitlement already persisted (review #6): the
|
|
904
|
+
* caller saw a failure while the grant quietly existed, and outside a
|
|
905
|
+
* transaction nothing rolled it back. The same condition checked here turns
|
|
906
|
+
* that into a clean refusal with nothing written.
|
|
907
|
+
*
|
|
908
|
+
* Mirrors dispatch exactly: no channels at all → nothing will emit, nothing
|
|
909
|
+
* to guard; session + outbox → the legal relay-only mode.
|
|
910
|
+
*/
|
|
911
|
+
private preflightDispatch;
|
|
263
912
|
private get channels();
|
|
264
913
|
}
|
|
265
914
|
//#endregion
|
|
@@ -268,46 +917,114 @@ type AccessTenantOptions = TenantConfig & Pick<MultiTenantOptions, 'skipOperatio
|
|
|
268
917
|
interface AccessLogger {
|
|
269
918
|
error(message: string, ...args: unknown[]): void;
|
|
270
919
|
}
|
|
271
|
-
|
|
272
|
-
|
|
920
|
+
/**
|
|
921
|
+
* DESCRIBE-time shape — everything that determines the persistence SHAPE and needs no
|
|
922
|
+
* connection or I/O to inspect. Nothing here opens a socket or reads a secret.
|
|
923
|
+
*/
|
|
924
|
+
interface AccessShape {
|
|
273
925
|
/**
|
|
274
926
|
* Tenant scoping. Pass `false` for company-wide grants (a user's platform
|
|
275
927
|
* API key has no org). Default `{ fieldType: 'objectId' }` matches Better
|
|
276
928
|
* Auth's `organization._id`.
|
|
277
929
|
*/
|
|
278
930
|
tenant?: AccessTenantOptions | boolean | undefined;
|
|
279
|
-
|
|
280
|
-
outbox?: OutboxStore$1 | undefined;
|
|
281
|
-
repositoryPlugins?: {
|
|
282
|
-
entitlement?: PluginType[] | undefined;
|
|
283
|
-
} | undefined;
|
|
284
|
-
/** Keep soft-deleted grants for this many days (default ~7y, audit floor). */
|
|
285
|
-
softDeleteTtlDays?: number | undefined;
|
|
931
|
+
/** Mongoose auto-index builds. Leave unset for the schema default (`true` in dev). */
|
|
286
932
|
autoIndex?: boolean | Partial<Record<AccessModelName, boolean>> | undefined;
|
|
933
|
+
/** Prepended to every collection name (multi-instance isolation). */
|
|
287
934
|
collectionPrefix?: string | undefined;
|
|
935
|
+
/**
|
|
936
|
+
* On a model-name collision: default throws; `true` re-registers (test/dev fixtures).
|
|
937
|
+
* Maps to mongokit's `replace` policy, which itself throws under `NODE_ENV=production`.
|
|
938
|
+
*/
|
|
288
939
|
forceRecreate?: boolean | undefined;
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* BIND-time runtime collaborators — the live connection is the first `bind` arg; these are
|
|
943
|
+
* the rest. A transport, outbox store, logger or host-supplied plugin belongs here, not in
|
|
944
|
+
* the shape.
|
|
945
|
+
*/
|
|
946
|
+
interface AccessRuntime {
|
|
947
|
+
eventTransport?: EventTransport | undefined;
|
|
948
|
+
/**
|
|
949
|
+
* The BUSINESS timezone, IANA (`'Asia/Dhaka'`).
|
|
950
|
+
*
|
|
951
|
+
* The authority for resolving a CALENDAR range into instants — the renewal
|
|
952
|
+
* worklist asks "expiring this month", and a month built from `Date.UTC`
|
|
953
|
+
* disagrees with the business month at both ends by the zone offset. Six hours
|
|
954
|
+
* in Dhaka, so the first and last day of every window silently gain or lose
|
|
955
|
+
* members while the list still looks reasonable.
|
|
956
|
+
*
|
|
957
|
+
* Deliberately IANA rather than the `offsetMinutes` the suspension paths take
|
|
958
|
+
* per call: a fixed offset cannot be DST-correct, so in a DST zone it is wrong
|
|
959
|
+
* for part of the year.
|
|
960
|
+
*
|
|
961
|
+
* Defaults to `'UTC'` — a deployment that never sets one behaves as it does
|
|
962
|
+
* today.
|
|
963
|
+
*/
|
|
964
|
+
timezone?: string | undefined;
|
|
965
|
+
outbox?: OutboxStore | undefined;
|
|
289
966
|
logger?: AccessLogger | undefined;
|
|
967
|
+
/**
|
|
968
|
+
* Accept a NON-TRANSACTIONAL deployment — a standalone `mongod` with no replica set.
|
|
969
|
+
*
|
|
970
|
+
* ## Why this exists, and why it is opt-IN
|
|
971
|
+
*
|
|
972
|
+
* `atomically()` wraps a grant/consume plus its outbox row in one transaction, so the
|
|
973
|
+
* event can only exist if the right does. Without a replica set MongoDB has no
|
|
974
|
+
* transactions, and the deliberate answer was to refuse — a GHOST entitlement event is
|
|
975
|
+
* worse than a lost one, because a door opens on a right that was never granted.
|
|
976
|
+
*
|
|
977
|
+
* That is correct for production and unusable for development: every OTHER kernel in
|
|
978
|
+
* this platform (order, revenue, pos, flow, catalog, party, ledger, muster) offers this
|
|
979
|
+
* escape and hosts derive it from `!isProduction`, so access was the one engine a dev
|
|
980
|
+
* box could not run. The symptom was not a boot failure but a silent one — a gym sale
|
|
981
|
+
* committed, the money was recorded, `chargeStatus` went `full`, and only the
|
|
982
|
+
* entitlement dead-lettered with "does not support retryable writes". A member paid and
|
|
983
|
+
* got no access, and nothing at boot said so.
|
|
984
|
+
*
|
|
985
|
+
* `true` degrades atomicity to BEST EFFORT and warns once per engine. Absent means
|
|
986
|
+
* REQUIRED — a general default must never override a specific one, so production keeps
|
|
987
|
+
* failing loudly whether or not anyone remembers this field.
|
|
988
|
+
*/
|
|
989
|
+
allowNonTransactional?: boolean | undefined;
|
|
990
|
+
repositoryPlugins?: {
|
|
991
|
+
entitlement?: PluginType[] | undefined;
|
|
992
|
+
} | undefined;
|
|
290
993
|
}
|
|
291
994
|
interface AccessRepositories {
|
|
292
995
|
entitlement: EntitlementRepository;
|
|
293
996
|
}
|
|
997
|
+
/** The frozen, resolved configuration an engine reports at `engine.config`. */
|
|
998
|
+
interface ResolvedAccessConfig {
|
|
999
|
+
readonly tenant: ResolvedTenantConfig;
|
|
1000
|
+
readonly autoIndex: boolean | Partial<Record<AccessModelName, boolean>> | undefined;
|
|
1001
|
+
readonly collectionPrefix: string | undefined;
|
|
1002
|
+
}
|
|
294
1003
|
interface AccessEngine {
|
|
295
|
-
readonly config:
|
|
296
|
-
readonly models:
|
|
1004
|
+
readonly config: ResolvedAccessConfig;
|
|
1005
|
+
readonly models: AccessModels;
|
|
297
1006
|
readonly repositories: AccessRepositories;
|
|
298
1007
|
readonly events: EventTransport;
|
|
299
|
-
readonly outbox: OutboxStore
|
|
1008
|
+
readonly outbox: OutboxStore | undefined;
|
|
300
1009
|
syncIndexes(): Promise<void>;
|
|
301
|
-
|
|
1010
|
+
close(): Promise<void>;
|
|
302
1011
|
}
|
|
303
1012
|
//#endregion
|
|
304
|
-
//#region src/engine/
|
|
1013
|
+
//#region src/engine/define-access.d.ts
|
|
1014
|
+
interface AccessBlueprint {
|
|
1015
|
+
readonly id: 'access';
|
|
1016
|
+
/** The model names this blueprint registers — known without a connection. */
|
|
1017
|
+
readonly modelNames: readonly string[];
|
|
1018
|
+
/**
|
|
1019
|
+
* Assert boot capabilities, compile + register the model on `connection`, wire the engine,
|
|
1020
|
+
* verify repository capabilities. Synchronous: access construction performs no async work.
|
|
1021
|
+
*/
|
|
1022
|
+
bind(connection: Connection, runtime?: AccessRuntime): AccessEngine;
|
|
1023
|
+
}
|
|
305
1024
|
/**
|
|
306
|
-
*
|
|
307
|
-
* access to any resource (course, download, API, membership, feature, service).
|
|
308
|
-
* No purchase (order), no money (revenue), no catalog — those compose around it.
|
|
1025
|
+
* Describe the access engine. Pure — registers no model, builds no schema, performs no I/O.
|
|
309
1026
|
*/
|
|
310
|
-
declare function
|
|
1027
|
+
declare function defineAccess(shape?: AccessShape): AccessBlueprint;
|
|
311
1028
|
//#endregion
|
|
312
1029
|
//#region src/domain/errors/access.errors.d.ts
|
|
313
1030
|
declare class AccessError extends Error implements HttpError {
|
|
@@ -322,6 +1039,25 @@ declare class EntitlementNotFoundError extends AccessError {
|
|
|
322
1039
|
declare class QuotaExhaustedError extends AccessError {
|
|
323
1040
|
constructor(id: string, limit: number);
|
|
324
1041
|
}
|
|
1042
|
+
/**
|
|
1043
|
+
* A pause request the POLICY refused — not an invalid transition.
|
|
1044
|
+
*
|
|
1045
|
+
* Separate from `InvalidEntitlementTransitionError` because the causes are
|
|
1046
|
+
* different in kind and the caller does different things with them: an illegal
|
|
1047
|
+
* transition is a bug or a lost race, while this is a legitimate request that the
|
|
1048
|
+
* rulebook declines, and the member is owed the reason ("your 60 days are used
|
|
1049
|
+
* up"). Carrying the machine-readable `refusal` plus the operator-facing message
|
|
1050
|
+
* means a UI can explain it without string-matching.
|
|
1051
|
+
*
|
|
1052
|
+
* 409, not 400: the request is well-formed; it conflicts with the subject's
|
|
1053
|
+
* current allowance state.
|
|
1054
|
+
*/
|
|
1055
|
+
declare class SuspensionRefusedError extends AccessError {
|
|
1056
|
+
readonly refusal: string;
|
|
1057
|
+
readonly daysUsedInPeriod: number | undefined;
|
|
1058
|
+
readonly daysRemainingInPeriod: number | null | undefined;
|
|
1059
|
+
constructor(refusal: string, message: string, daysUsedInPeriod?: number, daysRemainingInPeriod?: number | null);
|
|
1060
|
+
}
|
|
325
1061
|
declare class InvalidEntitlementTransitionError extends AccessError {
|
|
326
1062
|
constructor(from: string, to: string);
|
|
327
1063
|
}
|
|
@@ -335,38 +1071,92 @@ declare class InvalidEntitlementTransitionError extends AccessError {
|
|
|
335
1071
|
declare class UnmanagedSessionError extends AccessError {
|
|
336
1072
|
constructor();
|
|
337
1073
|
}
|
|
1074
|
+
/**
|
|
1075
|
+
* A `consume()` whose amount is not a positive integer.
|
|
1076
|
+
*
|
|
1077
|
+
* Enforced in the DOMAIN method, not only in a route schema, because the
|
|
1078
|
+
* repository is a public API: a host calling it directly (a queue worker, a
|
|
1079
|
+
* migration) bypasses HTTP validation entirely. The dangerous case is not the
|
|
1080
|
+
* obvious `0` — it is a NEGATIVE amount, which `$inc`s `usage.used` downward
|
|
1081
|
+
* and silently restores quota without any top-up operation being recorded.
|
|
1082
|
+
*/
|
|
1083
|
+
declare class InvalidConsumeAmountError extends AccessError {
|
|
1084
|
+
constructor(amount: unknown);
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* A `consume()` against a grant the decision refuses RIGHT NOW — scheduled but
|
|
1088
|
+
* not yet open, expired, suspended, or otherwise unusable.
|
|
1089
|
+
*
|
|
1090
|
+
* Carries the decision's `reason` in both the code and a field, because the
|
|
1091
|
+
* caller's follow-up differs by cause: `not_yet_active` is "come back at the
|
|
1092
|
+
* start date", `expired` is "renew". 409, not 404 — the grant exists; its
|
|
1093
|
+
* state conflicts with the spend.
|
|
1094
|
+
*/
|
|
1095
|
+
declare class EntitlementNotUsableError extends AccessError {
|
|
1096
|
+
readonly reason: string;
|
|
1097
|
+
constructor(id: string, reason: string);
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* A caller passed `ctx.session` that is NOT inside an active transaction.
|
|
1101
|
+
*
|
|
1102
|
+
* Distinct from `UnmanagedSessionError` (session with no outbox) because the fix
|
|
1103
|
+
* is different and the mistake is easy to make: a bare `startSession()` looks
|
|
1104
|
+
* like it buys atomicity and buys NOTHING — each write commits independently, so
|
|
1105
|
+
* a failing `outbox.save` leaves the mutation standing and the event lost. The
|
|
1106
|
+
* session must be driven by `session.withTransaction(...)` (or an explicit
|
|
1107
|
+
* `startTransaction()`), which is what actually makes the pair atomic.
|
|
1108
|
+
*/
|
|
1109
|
+
declare class SessionNotInTransactionError extends AccessError {
|
|
1110
|
+
constructor();
|
|
1111
|
+
}
|
|
338
1112
|
declare class VersionMismatchError extends AccessError {
|
|
339
1113
|
constructor(id: string, expectedVersion: number);
|
|
340
1114
|
}
|
|
341
1115
|
/**
|
|
342
|
-
*
|
|
343
|
-
*
|
|
344
|
-
*
|
|
345
|
-
*
|
|
1116
|
+
* A capability `defineAccess.bind` requires is missing. Two unrelated things
|
|
1117
|
+
* raise it:
|
|
1118
|
+
*
|
|
1119
|
+
* - **the BACKEND's** `getOrCreate` / guarded increment — granting is idempotent
|
|
1120
|
+
* via atomic `getOrCreate` (upsert), without which two concurrent grants on one
|
|
1121
|
+
* (subject, resource) double-provision, and metered `consume` needs an atomic
|
|
1122
|
+
* guarded increment;
|
|
1123
|
+
* - **an injected OUTBOX's** `transactionalSave` — without which the event row
|
|
1124
|
+
* survives a rolled-back mutation, so a ghost `entitlement:granted` describes
|
|
1125
|
+
* access that was never granted and a credential sync acts on it.
|
|
1126
|
+
*
|
|
1127
|
+
* The backend remedy is therefore CONDITIONAL on a backend flag actually being in
|
|
1128
|
+
* `missing`. It used to be appended unconditionally, so an outbox failure printed
|
|
1129
|
+
* "the backend must support them (mongokit 3.16+ / repo-core 0.6+)" — plausible
|
|
1130
|
+
* instruction pointing at a layer that was never involved, for a problem the
|
|
1131
|
+
* backend does not have. The remedy for `outbox.*` is to supply an OutboxStore
|
|
1132
|
+
* that enlists `ctx.session`; upgrading mongokit changes nothing.
|
|
1133
|
+
*
|
|
1134
|
+
* `missing` is always joined into the message verbatim: the flag NAMES are what
|
|
1135
|
+
* make the refusal actionable (and are what `outbox-requires-transactional-save`
|
|
1136
|
+
* asserts on), so no branch may drop them.
|
|
1137
|
+
*
|
|
1138
|
+
* @param missing - capability flags that were not provided. Flags prefixed
|
|
1139
|
+
* `outbox.` describe the injected OutboxStore, not the database.
|
|
346
1140
|
*/
|
|
347
1141
|
declare class AccessCapabilityError extends AccessError {
|
|
348
1142
|
constructor(missing: readonly string[]);
|
|
349
1143
|
}
|
|
350
|
-
//#endregion
|
|
351
|
-
//#region src/events/in-process-bus.d.ts
|
|
352
|
-
interface InProcessAccessBusOptions {
|
|
353
|
-
logger?: {
|
|
354
|
-
error(message: string, ...args: unknown[]): void;
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
1144
|
/**
|
|
358
|
-
*
|
|
359
|
-
*
|
|
360
|
-
*
|
|
1145
|
+
* A reporting window that cannot be resolved — a mixed civil/instant pair, an
|
|
1146
|
+
* inverted range, or a date the calendar rejects (`2026-02-31`).
|
|
1147
|
+
*
|
|
1148
|
+
* 400, not 500: the caller's range is unusable. Answering with an empty list
|
|
1149
|
+
* instead would read as "nothing is expiring", which is the opposite of the
|
|
1150
|
+
* truth and the kind of plausible wrong answer this package exists to avoid.
|
|
361
1151
|
*/
|
|
362
|
-
declare class
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
1152
|
+
declare class InvalidExpiryWindowError extends AccessError {
|
|
1153
|
+
constructor(message: string);
|
|
1154
|
+
}
|
|
1155
|
+
//#endregion
|
|
1156
|
+
//#region src/events/in-process-bus.d.ts
|
|
1157
|
+
type InProcessAccessBusOptions = InProcessEventBusOptions;
|
|
1158
|
+
declare class InProcessAccessBus extends InProcessEventBus {
|
|
366
1159
|
constructor(options?: InProcessAccessBusOptions);
|
|
367
|
-
publish(event: DomainEvent): Promise<void>;
|
|
368
|
-
subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
|
|
369
|
-
close(): Promise<void>;
|
|
370
1160
|
}
|
|
371
1161
|
//#endregion
|
|
372
|
-
export { ACCESS_EVENTS,
|
|
1162
|
+
export { ACCESS_EVENTS, type AccessBlueprint, AccessCapabilityError, type AccessContext, type AccessDecision, type AccessEngine, AccessError, type AccessEventDefinition, type AccessEventName, type AccessGrantState, type AccessLogger, type AccessModelName, type AccessModels, type AccessReason, type AccessRepositories, type AccessRuntime, type AccessShape, type AccessTenantOptions, type CheckResult, DEFAULT_CHURN_GRACE_DAYS, type DefineAccessModelsConfig, ENTITLEMENT_MACHINE, ENTITLEMENT_STATUS, ENTITLEMENT_STATUS_VALUES, ENTITLEMENT_TRANSITIONS, type EntitlementDesiredItem, type EntitlementDocument, EntitlementNotFoundError, EntitlementNotUsableError, EntitlementRepository, type EntitlementRepositoryConfig, type EntitlementSource, type EntitlementStatus, type EntitlementTarget, type EntitlementUsage, type GrantInput, InProcessAccessBus, InvalidConsumeAmountError, InvalidEntitlementTransitionError, InvalidExpiryWindowError, LIVE_STATUSES, QuotaExhaustedError, type ReconcileEntitlementSetInput, type ReconcileResult, type ResolvedAccessConfig, SessionNotInTransactionError, SuspensionRefusedError, UnmanagedSessionError, VersionMismatchError, accessEventDefinitions, canEntitlementTransition, defineAccess, defineAccessModels, evaluateAccess, hasAccess, isEntitlementStatus, isTerminalEntitlementStatus };
|