@classytic/access 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,174 +1,16 @@
1
- import { evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
2
- import { l as accessEventDefinitions, u as ACCESS_EVENTS } from "./event-catalog-BVD_rFlc.mjs";
1
+ import { ACCESS_REASONS, evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
2
+ import { A as InvalidConsumeAmountError, C as ConsumptionInFlightError, D as EntitlementNotUsableError, E as EntitlementNotFoundError, F as SessionNotInTransactionError, I as SuspensionRefusedError, L as UnmanagedSessionError, M as InvalidExpiryWindowError, N as InvalidExtensionError, O as GrantProvenanceRequiredError, P as QuotaExhaustedError, R as VersionMismatchError, S as AccessError, T as ConsumptionKeyRequiredError, _ as LIVE_STATUSES, b as isTerminalEntitlementStatus, d as ACCESS_EVENTS, f as DEFAULT_CHURN_GRACE_DAYS, g as ENTITLEMENT_TRANSITIONS, h as ENTITLEMENT_STATUS_VALUES, j as InvalidEntitlementTransitionError, k as InvalidCheckRequestError, m as ENTITLEMENT_STATUS, p as ENTITLEMENT_MACHINE, u as accessEventDefinitions, v as canEntitlementTransition, w as ConsumptionKeyConflictError, x as AccessCapabilityError, y as isEntitlementStatus } from "./event-catalog-CIxQavRC.mjs";
3
3
  import { Repository, createOptionsExtractor, defineModels, multiTenantPlugin, transactionResolutionOf, withTransaction } from "@classytic/mongokit";
4
4
  import { assertNoLegacyTenantKeys, resolveTenantConfig } from "@classytic/repo-core/tenant";
5
5
  import { InProcessEventBus } from "@classytic/primitives/event-infra";
6
+ import { Schema } from "mongoose";
6
7
  import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
7
- import mongoose, { Schema } from "mongoose";
8
- import { defineStateMachine } from "@classytic/primitives/state-machine";
8
+ import { assertIndexDeclaration, injectTenantField } from "@classytic/mongokit/tenant";
9
9
  import { appendStatus } from "@classytic/primitives/status-history";
10
10
  import { inclusiveEnd, resolveDateSpan } from "@classytic/primitives/period";
11
11
  import { evaluateSuspension, spansFromStatusHistory } from "@classytic/primitives/suspension";
12
+ import { zoneOffsetMinutes } from "@classytic/primitives/timezone";
12
13
  import { createEvent } from "@classytic/primitives/events";
13
- //#region src/domain/errors/access.errors.ts
14
- var AccessError = class extends Error {
15
- code;
16
- status;
17
- constructor(message, code, status) {
18
- super(message);
19
- this.name = this.constructor.name;
20
- this.code = code;
21
- this.status = status;
22
- }
23
- };
24
- var EntitlementNotFoundError = class extends AccessError {
25
- constructor(id) {
26
- super(`Entitlement ${id} not found`, "access.entitlement.not_found", 404);
27
- }
28
- };
29
- /** A consume() against a metered grant whose quota is already spent. */
30
- var QuotaExhaustedError = class extends AccessError {
31
- constructor(id, limit) {
32
- super(`Entitlement ${id} quota exhausted (limit ${limit})`, "access.entitlement.quota_exhausted", 409);
33
- }
34
- };
35
- /**
36
- * A pause request the POLICY refused — not an invalid transition.
37
- *
38
- * Separate from `InvalidEntitlementTransitionError` because the causes are
39
- * different in kind and the caller does different things with them: an illegal
40
- * transition is a bug or a lost race, while this is a legitimate request that the
41
- * rulebook declines, and the member is owed the reason ("your 60 days are used
42
- * up"). Carrying the machine-readable `refusal` plus the operator-facing message
43
- * means a UI can explain it without string-matching.
44
- *
45
- * 409, not 400: the request is well-formed; it conflicts with the subject's
46
- * current allowance state.
47
- */
48
- var SuspensionRefusedError = class extends AccessError {
49
- refusal;
50
- daysUsedInPeriod;
51
- daysRemainingInPeriod;
52
- constructor(refusal, message, daysUsedInPeriod, daysRemainingInPeriod) {
53
- super(message, `access.suspension.${refusal}`, 409);
54
- this.refusal = refusal;
55
- this.daysUsedInPeriod = daysUsedInPeriod;
56
- this.daysRemainingInPeriod = daysRemainingInPeriod;
57
- }
58
- };
59
- var InvalidEntitlementTransitionError = class extends AccessError {
60
- constructor(from, to) {
61
- super(`Invalid entitlement transition: ${from} → ${to}`, "access.invalid_transition", 409);
62
- }
63
- };
64
- /**
65
- * Thrown when a host passes `ctx.session` (it owns the outer transaction)
66
- * but NO outbox is wired: there is no correct delivery path for the event.
67
- * Publishing immediately would leak ghost events if the host rolls back;
68
- * silently dropping loses the event entirely. Wire an `OutboxStore` —
69
- * session + outbox is legal durable-relay-only mode (§P8.1).
70
- */
71
- var UnmanagedSessionError = class extends AccessError {
72
- constructor() {
73
- super("ctx.session provided but no OutboxStore is wired — events would be lost. Wire an outbox (durable relay delivers post-commit) or drop the session.", "access.session.unmanaged", 409);
74
- }
75
- };
76
- /**
77
- * A `consume()` whose amount is not a positive integer.
78
- *
79
- * Enforced in the DOMAIN method, not only in a route schema, because the
80
- * repository is a public API: a host calling it directly (a queue worker, a
81
- * migration) bypasses HTTP validation entirely. The dangerous case is not the
82
- * obvious `0` — it is a NEGATIVE amount, which `$inc`s `usage.used` downward
83
- * and silently restores quota without any top-up operation being recorded.
84
- */
85
- var InvalidConsumeAmountError = class extends AccessError {
86
- constructor(amount) {
87
- super(`consume() amount must be a positive integer, got ${String(amount)}`, "access.consume.invalid_amount", 400);
88
- }
89
- };
90
- /**
91
- * A `consume()` against a grant the decision refuses RIGHT NOW — scheduled but
92
- * not yet open, expired, suspended, or otherwise unusable.
93
- *
94
- * Carries the decision's `reason` in both the code and a field, because the
95
- * caller's follow-up differs by cause: `not_yet_active` is "come back at the
96
- * start date", `expired` is "renew". 409, not 404 — the grant exists; its
97
- * state conflicts with the spend.
98
- */
99
- var EntitlementNotUsableError = class extends AccessError {
100
- reason;
101
- constructor(id, reason) {
102
- super(`Entitlement ${id} is not usable right now (${reason})`, `access.entitlement.not_usable.${reason}`, 409);
103
- this.reason = reason;
104
- }
105
- };
106
- /**
107
- * A caller passed `ctx.session` that is NOT inside an active transaction.
108
- *
109
- * Distinct from `UnmanagedSessionError` (session with no outbox) because the fix
110
- * is different and the mistake is easy to make: a bare `startSession()` looks
111
- * like it buys atomicity and buys NOTHING — each write commits independently, so
112
- * a failing `outbox.save` leaves the mutation standing and the event lost. The
113
- * session must be driven by `session.withTransaction(...)` (or an explicit
114
- * `startTransaction()`), which is what actually makes the pair atomic.
115
- */
116
- var SessionNotInTransactionError = class extends AccessError {
117
- constructor() {
118
- super("ctx.session was supplied but has no ACTIVE transaction — a bare session provides no atomicity (each write commits independently). Drive it with session.withTransaction(...) / startTransaction(), or omit the session and let the repository open its own transaction.", "access.session.not_in_transaction", 409);
119
- }
120
- };
121
- var VersionMismatchError = class extends AccessError {
122
- constructor(id, expectedVersion) {
123
- super(`Concurrent modification on ${id} (expected version ${expectedVersion}) — retry.`, "access.concurrency.version_mismatch", 409);
124
- }
125
- };
126
- /**
127
- * A capability `defineAccess.bind` requires is missing. Two unrelated things
128
- * raise it:
129
- *
130
- * - **the BACKEND's** `getOrCreate` / guarded increment — granting is idempotent
131
- * via atomic `getOrCreate` (upsert), without which two concurrent grants on one
132
- * (subject, resource) double-provision, and metered `consume` needs an atomic
133
- * guarded increment;
134
- * - **an injected OUTBOX's** `transactionalSave` — without which the event row
135
- * survives a rolled-back mutation, so a ghost `entitlement:granted` describes
136
- * access that was never granted and a credential sync acts on it.
137
- *
138
- * The backend remedy is therefore CONDITIONAL on a backend flag actually being in
139
- * `missing`. It used to be appended unconditionally, so an outbox failure printed
140
- * "the backend must support them (mongokit 3.16+ / repo-core 0.6+)" — plausible
141
- * instruction pointing at a layer that was never involved, for a problem the
142
- * backend does not have. The remedy for `outbox.*` is to supply an OutboxStore
143
- * that enlists `ctx.session`; upgrading mongokit changes nothing.
144
- *
145
- * `missing` is always joined into the message verbatim: the flag NAMES are what
146
- * make the refusal actionable (and are what `outbox-requires-transactional-save`
147
- * asserts on), so no branch may drop them.
148
- *
149
- * @param missing - capability flags that were not provided. Flags prefixed
150
- * `outbox.` describe the injected OutboxStore, not the database.
151
- */
152
- var AccessCapabilityError = class extends AccessError {
153
- constructor(missing) {
154
- const backendMissing = missing.filter((flag) => !flag.startsWith("outbox."));
155
- super(`[access] missing required capabilities: ${missing.join(", ")}. Access fails loud at bind rather than provisioning entitlements nothing can reconcile (or emitting an event for access that was never granted).` + (backendMissing.length > 0 ? " Grants use atomic getOrCreate (upsert) for idempotency and a guarded increment for metered consume; the backend must support them (mongokit 3.16+ / repo-core 0.6+)." : ""), "access.engine.missing_capabilities", 500);
156
- }
157
- };
158
- /**
159
- * A reporting window that cannot be resolved — a mixed civil/instant pair, an
160
- * inverted range, or a date the calendar rejects (`2026-02-31`).
161
- *
162
- * 400, not 500: the caller's range is unusable. Answering with an empty list
163
- * instead would read as "nothing is expiring", which is the opposite of the
164
- * truth and the kind of plausible wrong answer this package exists to avoid.
165
- */
166
- var InvalidExpiryWindowError = class extends AccessError {
167
- constructor(message) {
168
- super(message, "access.entitlement.invalid_expiry_window", 400);
169
- }
170
- };
171
- //#endregion
172
14
  //#region src/events/in-process-bus.ts
173
15
  /**
174
16
  * In-process fan-out transport — the default when the host injects none.
@@ -191,133 +33,59 @@ var InProcessAccessBus = class extends InProcessEventBus {
191
33
  }
192
34
  };
193
35
  //#endregion
194
- //#region src/domain/enums/entitlement-status.enum.ts
195
- /**
196
- * Entitlement lifecycle status.
197
- *
198
- * active ⇄ suspended
199
- * active → expired (window lapsed; written by the sweeper — derived at read-time)
200
- * active → consumed (metered quota exhausted)
201
- * active → revoked (admin pull / dispute) ── terminal
202
- * active → refunded (payment reversed) ── terminal
203
- * expired → active (renewal restarts the window)
204
- * consumed → active (top-up restores quota)
205
- * suspended → expired | revoked | refunded
206
- *
207
- * IMPORTANT: `expired` and `consumed` are LIFECYCLE markers a sweeper /
208
- * consume() writes so the row can be queried and an event emitted once. The
209
- * buyer-facing gate never depends on them — `evaluateAccess` (access-decision.ts)
210
- * derives expiry/exhaustion from the window + usage directly, so a grant is
211
- * denied the instant it lapses, before any status write. The row is never
212
- * deleted: terminal states free the live-uniqueness slot for a fresh grant.
213
- */
214
- const ENTITLEMENT_STATUS = {
215
- ACTIVE: "active",
216
- SUSPENDED: "suspended",
217
- EXPIRED: "expired",
218
- CONSUMED: "consumed",
219
- REVOKED: "revoked",
220
- REFUNDED: "refunded"
221
- };
222
- const ENTITLEMENT_STATUS_VALUES = [
223
- "active",
224
- "suspended",
225
- "expired",
226
- "consumed",
227
- "revoked",
228
- "refunded"
229
- ];
230
- /** Statuses where the grant is still "live" (subject of the one-active-per-resource rule). */
231
- const LIVE_STATUSES = ["active", "suspended"];
232
- const SET = new Set(ENTITLEMENT_STATUS_VALUES);
233
- const isEntitlementStatus = (v) => typeof v === "string" && SET.has(v);
234
- const ENTITLEMENT_TRANSITIONS = {
235
- active: [
236
- "suspended",
237
- "expired",
238
- "consumed",
239
- "revoked",
240
- "refunded"
241
- ],
242
- suspended: [
243
- "active",
244
- "expired",
245
- "revoked",
246
- "refunded"
247
- ],
248
- expired: ["active"],
249
- consumed: ["active"],
250
- revoked: [],
251
- refunded: []
252
- };
253
- /**
254
- * The lifecycle as a STATE MACHINE, over the same {@link ENTITLEMENT_TRANSITIONS}
255
- * table above.
256
- *
257
- * ## Why a machine and not just the predicate
258
- *
259
- * The table was already declared and already enforced — `transitionInner` is the
260
- * single write funnel and it refuses an illegal move. What was missing is
261
- * everything DERIVED from the table, which every consumer was left to re-derive:
262
- *
263
- * - **`terminal`** — computed from the empty outgoing lists, so `revoked` and
264
- * `refunded` are terminal and nothing else is. A reporting layer asking "is
265
- * this grant finished" must not carry its own list; two lists drift, and the
266
- * one in the report is the one nobody tests.
267
- * - **`validTargets` / `validSources`** — for a UI offering the legal next moves,
268
- * instead of a hardcoded button set that silently diverges from the table.
269
- * - **`assertTransition`** — the shape `@classytic/mongokit`'s `applyTransition`
270
- * consumes, so a CAS write can pre-flight legality from the same source.
271
- *
272
- * ## What this says about churn, and it matters
273
- *
274
- * `expired → active` is LEGAL: a renewal restarts the window. So `expired` is not
275
- * terminal, and **an expired membership is not a churned one** — it is a lapsed
276
- * one that may still come back. Any churn metric that counts `expired` as lost
277
- * is counting people who renew a week late. The machine is the authority for that
278
- * distinction rather than a definition retyped in a dashboard.
279
- *
280
- * `errorFactory` returns this package's own {@link InvalidEntitlementTransitionError}
281
- * (409) so the wire contract is unchanged — the machine replaces the predicate,
282
- * not the error.
283
- */
284
- const ENTITLEMENT_MACHINE = defineStateMachine({
285
- name: "Entitlement",
286
- transitions: ENTITLEMENT_TRANSITIONS,
287
- errorFactory: ({ from, to }) => new InvalidEntitlementTransitionError(from, to)
288
- });
289
- /**
290
- * Delegates to {@link ENTITLEMENT_MACHINE}.
291
- *
292
- * Kept as a named export because it is part of the published surface; the body is
293
- * now one line so the table cannot be consulted two different ways.
294
- */
295
- function canEntitlementTransition(from, to) {
296
- return ENTITLEMENT_MACHINE.canTransition(from, to);
297
- }
36
+ //#region src/models/entitlement-consumption.model.ts
298
37
  /**
299
- * Is this grant finished for good? `revoked` / `refunded` only.
38
+ * EntitlementConsumption — the usage record of ONE metered spend, keyed by the caller's
39
+ * consumption key. The unique `(entitlementId, key)` index is what makes `consume()`
40
+ * idempotent: a door double-scan or a redelivered webhook finds its key and spends nothing.
300
41
  *
301
- * Derived from the machine, never from a second list. `expired` and `consumed`
302
- * are deliberately NOT terminal — both can return to `active` (renewal, top-up),
303
- * and treating them as endings is how a report turns a late renewal into churn.
42
+ * Append-only. It is also the audit trail of who spent what, when (Stripe/Chargebee usage
43
+ * records): `usage.used` on the entitlement is the running total, these rows are its ledger.
304
44
  */
305
- function isTerminalEntitlementStatus(status) {
306
- return ENTITLEMENT_MACHINE.isTerminal(status);
45
+ function buildEntitlementConsumptionSchema() {
46
+ const schema = new Schema({
47
+ entitlementId: {
48
+ type: String,
49
+ required: true,
50
+ trim: true
51
+ },
52
+ key: {
53
+ type: String,
54
+ required: true,
55
+ trim: true,
56
+ minlength: 1,
57
+ maxlength: 256
58
+ },
59
+ amount: {
60
+ type: Number,
61
+ required: true,
62
+ validate: {
63
+ validator: (v) => typeof v === "number" && Number.isInteger(v) && v > 0,
64
+ message: "amount must be a positive integer"
65
+ }
66
+ },
67
+ consumedAt: {
68
+ type: Date,
69
+ required: true
70
+ },
71
+ actorId: {
72
+ type: String,
73
+ trim: true
74
+ }
75
+ }, { timestamps: true });
76
+ schema.index({
77
+ entitlementId: 1,
78
+ key: 1
79
+ }, {
80
+ unique: true,
81
+ name: "entitlement_consumption_unique_key"
82
+ });
83
+ schema.index({
84
+ entitlementId: 1,
85
+ consumedAt: -1
86
+ }, { name: "entitlement_consumption_by_grant" });
87
+ return schema;
307
88
  }
308
- /**
309
- * Days after a lapse in which a renewal still counts as a renewal, not churn.
310
- *
311
- * 30 because a monthly membership renews monthly: a member who pays a week or two
312
- * late is the ordinary case, not a loss. Shorter, and the number reports churn
313
- * that walks back in the door; much longer, and a genuine loss stays uncounted
314
- * for a quarter.
315
- *
316
- * A KERNEL default, not a host literal — the grace period is a business rule, and
317
- * a threshold retyped per screen is how a dashboard and an export disagree about
318
- * the same month. Override per call where a deployment genuinely differs.
319
- */
320
- const DEFAULT_CHURN_GRACE_DAYS = 30;
321
89
  //#endregion
322
90
  //#region src/models/entitlement.model.ts
323
91
  /**
@@ -527,18 +295,17 @@ function buildEntitlementSchema() {
527
295
  * carries both fields, and mirroring into `$set` would conflict with the
528
296
  * insert path.
529
297
  */
530
- const deriveLive = function() {
298
+ schema.pre([
299
+ "updateOne",
300
+ "updateMany",
301
+ "findOneAndUpdate"
302
+ ], function() {
531
303
  const update = this.getUpdate();
532
- if (!update) return;
533
- for (const operator of ["$set", "$setOnInsert"]) {
534
- const status = update[operator]?.status;
535
- if (typeof status !== "string") continue;
536
- if (operator === "$set") update.$set.live = LIVE_STATUSES.includes(status) ? true : null;
537
- }
538
- };
539
- schema.pre("updateOne", deriveLive);
540
- schema.pre("updateMany", deriveLive);
541
- schema.pre("findOneAndUpdate", deriveLive);
304
+ if (!update || Array.isArray(update)) return;
305
+ const status = update.$set?.status ?? update.status;
306
+ if (typeof status !== "string") return;
307
+ this.set("live", LIVE_STATUSES.includes(status) ? true : null);
308
+ });
542
309
  schema.index({
543
310
  subjectModel: 1,
544
311
  subjectRef: 1,
@@ -566,11 +333,13 @@ function buildEntitlementSchema() {
566
333
  }, { name: "entitlement_by_resource" });
567
334
  schema.index({
568
335
  status: 1,
569
- accessExpiresAt: 1
336
+ accessExpiresAt: 1,
337
+ _id: 1
570
338
  }, { name: "entitlement_due_for_expiry" });
571
339
  schema.index({
572
340
  status: 1,
573
- autoResumeAt: 1
341
+ autoResumeAt: 1,
342
+ _id: 1
574
343
  }, { name: "entitlement_due_for_resume" });
575
344
  schema.index({
576
345
  originModel: 1,
@@ -579,33 +348,6 @@ function buildEntitlementSchema() {
579
348
  return schema;
580
349
  }
581
350
  //#endregion
582
- //#region src/models/inject-tenant.ts
583
- /**
584
- * Mongoose adapter around `@classytic/repo-core/tenant.resolveTenantConfig`.
585
- * Thin (rule P11) — repo-core owns resolution; this handles schema mutations
586
- * only: adds the tenant field with the engine-configured type, and prepends
587
- * the tenant key to every existing compound index (rule 36).
588
- */
589
- function injectTenantField(schema, tenant) {
590
- const isFieldStrategy = tenant.strategy === "field";
591
- const isObjectId = tenant.fieldType === "objectId";
592
- schema.add({ [tenant.tenantField]: {
593
- type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
594
- ...tenant.enabled && tenant.required ? { required: true } : {},
595
- ...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
596
- } });
597
- if (!tenant.enabled || !isFieldStrategy) return;
598
- const existingIndexes = schema._indexes;
599
- if (existingIndexes && existingIndexes.length > 0) for (const indexEntry of existingIndexes) {
600
- const fields = indexEntry[0];
601
- if (fields[tenant.tenantField] !== void 0) continue;
602
- const newFields = { [tenant.tenantField]: 1 };
603
- for (const [key, val] of Object.entries(fields)) newFields[key] = val;
604
- indexEntry[0] = newFields;
605
- }
606
- if (!(existingIndexes ?? []).some(([fields]) => Object.keys(fields)[0] === tenant.tenantField)) schema.index({ [tenant.tenantField]: 1 });
607
- }
608
- //#endregion
609
351
  //#region src/models/create-models.ts
610
352
  /**
611
353
  * Access model specification — the ONE authoritative place the Entitlement model is
@@ -616,11 +358,13 @@ function injectTenantField(schema, tenant) {
616
358
  * prefix, auto-index and collision policy live here once. A name collision surfaces as
617
359
  * mongokit's typed `ModelCollisionError` (no kernel-specific wrapper).
618
360
  *
619
- * Access has a SINGLE model (`Entitlement`) — no optional model families — so the spec
620
- * array has one entry. Were a future family added, it would be a CONDITIONAL `ModelSpec`
621
- * pushed onto `models` only when its shape flag is enabled (Kernel Construction Standard §5.2).
361
+ * Two models, both always registered: `Entitlement` (the grant) and `EntitlementConsumption`
362
+ * (the idempotent usage ledger `consume()` writes in the same unit of work).
622
363
  */
623
- const DEFAULT_COLLECTIONS = { Entitlement: "entitlements" };
364
+ const DEFAULT_COLLECTIONS = {
365
+ Entitlement: "entitlements",
366
+ EntitlementConsumption: "entitlement_consumptions"
367
+ };
624
368
  function resolveAutoIndex(name, autoIndex) {
625
369
  if (autoIndex === void 0) return void 0;
626
370
  return typeof autoIndex === "boolean" ? autoIndex : autoIndex[name];
@@ -631,13 +375,14 @@ function resolveAutoIndex(name, autoIndex) {
631
375
  */
632
376
  function defineAccessModels(config) {
633
377
  const prefix = config.collectionPrefix ?? "";
378
+ for (const declaration of config.indexes ?? []) assertIndexDeclaration(declaration, config.tenant);
634
379
  return defineModels({
635
380
  models: [{
636
381
  name: "Entitlement",
637
382
  collection: prefix + DEFAULT_COLLECTIONS.Entitlement,
638
383
  schema: () => {
639
384
  const schema = buildEntitlementSchema();
640
- injectTenantField(schema, config.tenant);
385
+ injectTenantField(schema, config.tenant, { ...config.indexes ? { indexes: config.indexes } : {} });
641
386
  const ai = resolveAutoIndex("Entitlement", config.autoIndex);
642
387
  if (ai !== void 0) schema.set("autoIndex", ai);
643
388
  return schema;
@@ -646,8 +391,25 @@ function defineAccessModels(config) {
646
391
  mode: "replace",
647
392
  environment: "test"
648
393
  } : { mode: "throw" }
394
+ }, {
395
+ name: "EntitlementConsumption",
396
+ collection: prefix + DEFAULT_COLLECTIONS.EntitlementConsumption,
397
+ schema: () => {
398
+ const schema = buildEntitlementConsumptionSchema();
399
+ injectTenantField(schema, config.tenant);
400
+ const ai = resolveAutoIndex("EntitlementConsumption", config.autoIndex);
401
+ if (ai !== void 0) schema.set("autoIndex", ai);
402
+ return schema;
403
+ },
404
+ existing: config.forceRecreate ? {
405
+ mode: "replace",
406
+ environment: "test"
407
+ } : { mode: "throw" }
649
408
  }],
650
- assemble: (models) => Object.freeze({ Entitlement: models.get("Entitlement") })
409
+ assemble: (models) => Object.freeze({
410
+ Entitlement: models.get("Entitlement"),
411
+ EntitlementConsumption: models.get("EntitlementConsumption")
412
+ })
651
413
  });
652
414
  }
653
415
  //#endregion
@@ -678,9 +440,7 @@ async function emitDomainEvent(channels, type, payload, ctx, resourceId) {
678
440
  if (ctx.idempotencyKey !== void 0) meta.idempotencyKey = ctx.idempotencyKey;
679
441
  const event = createEvent$1(type, payload, ctx, meta);
680
442
  if (channels.outbox) try {
681
- const saveOptions = {};
682
- if (ctx.session !== void 0) saveOptions.session = ctx.session;
683
- await channels.outbox.save(event, saveOptions);
443
+ await channels.outbox.save(event, ctx.session !== void 0 ? { session: ctx.session } : {});
684
444
  } catch (err) {
685
445
  channels.logger.error(`[access] outbox.save failed for ${event.type}:`, err);
686
446
  throw err;
@@ -714,78 +474,75 @@ const repoOptionsFromCtx = createOptionsExtractor([
714
474
  //#endregion
715
475
  //#region src/repositories/entitlement.repository.ts
716
476
  /**
717
- * EntitlementRepository — grant / check / consume / lifecycle for durable,
718
- * time-bound access. Every state move is an atomic CAS (`claim` / `claimVersion`
719
- * / guarded `findOneAndUpdate`) — never read-modify-write. Expiry is modelled as
720
- * a CAS transition (the `expireDue` sweeper), never a TTL-delete, so the row
721
- * survives as an auditable record (PACKAGE_RULES Concurrency House Rules).
477
+ * EntitlementRepository — grant / check / consume / lifecycle for durable, time-bound access.
722
478
  *
723
- * The hot path is `check()`: a read that runs `evaluateAccess` and returns a
724
- * decision. It mutates nothing, so it stays cheap and the same rule can run on
725
- * an edge node or in the UI via the `@classytic/access/decision` subpath.
726
- */
727
- /**
728
- * Batch size REQUESTED per drain-loop page. The backend may clamp it to its own
729
- * maximum (mongokit does), which is exactly why no loop below uses page size as
730
- * a termination signal — only an EMPTY page proves drainage. This constant only
731
- * bounds per-iteration memory.
479
+ * Rules every method here follows:
480
+ * - Every state move is a CAS (`claim` / `claimVersion` / guarded `findOneAndUpdate`) with the
481
+ * guard IN the write filter — never read-check-write.
482
+ * - Every decision runs `evaluateAccess` at the injected clock's `now` (fail closed).
483
+ * - Every grant names its provenance; every consumption names its idempotency key.
484
+ * - A mutation and its event commit together (`atomically`) whenever an outbox is wired.
732
485
  */
486
+ /** Rows per drain page. Only an EMPTY page proves drainage — the backend may clamp the size. */
733
487
  const BATCH_SIZE = 500;
488
+ /** Upper bound on one `checkMany` — one query, bounded `$or`. */
489
+ const MAX_CAPABILITIES_PER_CHECK = 100;
490
+ const MONEY_SOURCES = /* @__PURE__ */ new Set(["purchase", "subscription"]);
734
491
  /** The applied-origins ledger key, or null when the input carries no origin. */
735
492
  function grantOriginKey(input) {
736
493
  return input.originModel !== void 0 && input.originRef !== void 0 ? `${input.originModel}:${input.originRef}` : null;
737
494
  }
495
+ /** The later of two expiries; `null` (lifetime) beats any instant. */
496
+ function laterExpiry(a, b) {
497
+ if (a === null || b === null) return null;
498
+ return a.getTime() >= b.getTime() ? a : b;
499
+ }
738
500
  var EntitlementRepository = class extends Repository {
501
+ consumptions;
739
502
  eventTransport;
740
503
  outbox;
741
504
  pkgLogger;
742
505
  allowNonTransactional;
743
- /** IANA business zone — see `EntitlementRepositoryConfig.timezone`. */
744
506
  timezone;
745
- /** Warn ONCE per repository, not once per grant — a per-tap log is noise nobody reads. */
507
+ clock;
508
+ /** Warn ONCE per repository, not once per grant. */
746
509
  warnedNonTransactional = false;
747
510
  constructor(config) {
748
511
  super(config.model, config.plugins ?? []);
512
+ this.consumptions = config.consumptions;
749
513
  this.eventTransport = config.eventTransport;
750
514
  this.outbox = config.outbox;
751
515
  this.pkgLogger = config.logger ?? console;
752
516
  this.allowNonTransactional = config.allowNonTransactional === true;
753
517
  this.timezone = config.timezone ?? "UTC";
518
+ this.clock = config.clock ?? (() => /* @__PURE__ */ new Date());
519
+ }
520
+ /** The current instant from the injected clock. A clock returning an invalid date throws. */
521
+ now() {
522
+ const at = this.clock();
523
+ if (!(at instanceof Date) || Number.isNaN(at.getTime())) throw new AccessCapabilityError(["clock (the injected clock returned an invalid Date)"]);
524
+ return at;
754
525
  }
755
526
  /**
756
- * Grant access. Idempotent per (subject, resource, scope) live grant via
757
- * atomic `getOrCreate`. If a live grant already exists and `renew !== false`,
758
- * the window/quota is refreshed (a re-purchase restarts the clock). Emits
759
- * `access:granted` on first grant, `access:extended` on renewal.
527
+ * Grant access. Idempotent per (subject, resource, scope) live grant via atomic `getOrCreate`.
528
+ * On an existing live grant: a REPLAY of an origin already applied changes nothing; otherwise
529
+ * (`renew !== false`) the window is refreshed — never shortened — and the quota follows
530
+ * `quotaMode`. Emits `access:granted` on create, `access:extended` on renewal.
760
531
  */
761
532
  async grant(input, ctx) {
762
533
  return this.atomically(ctx, (inner) => this.grantInner(input, inner));
763
534
  }
764
535
  async grantInner(input, ctx) {
765
536
  this.preflightDispatch(ctx);
766
- /**
767
- * Invariants enforced HERE, at the domain boundary, because the write path
768
- * is an UPSERT: mongoose runs document middleware (`pre('validate')`) only
769
- * on `save()`, so the schema-level checks never see a `getOrCreate`. The
770
- * schema hook still guards direct model writes; this guards the API.
771
- */
772
537
  if (input.notBefore instanceof Date && input.accessExpiresAt instanceof Date && input.notBefore.getTime() > input.accessExpiresAt.getTime()) throw new Error("notBefore must not be after accessExpiresAt");
773
538
  if (input.originRef === void 0 !== (input.originModel === void 0)) throw new Error("originRef and originModel must be set together (polymorphic ref)");
774
539
  if (input.usageLimit !== void 0 && input.usageLimit !== null && (!Number.isInteger(input.usageLimit) || input.usageLimit < 0)) throw new Error("usageLimit must be null (unlimited) or a non-negative integer");
540
+ const originKey = grantOriginKey(input);
541
+ if (MONEY_SOURCES.has(input.source) && originKey === null) throw new GrantProvenanceRequiredError(input.source, "originModel + originRef (the paying document)");
542
+ if (originKey === null && (ctx.actorId === void 0 || ctx.actorId === "")) throw new GrantProvenanceRequiredError(input.source, "an origin or ctx.actorId");
775
543
  const scopeKey = input.scopeKey ?? "";
776
544
  const opts = repoOptionsFromCtx(ctx);
777
- const originKey = grantOriginKey(input);
778
- /**
779
- * Idempotency is keyed on `live: true`, NOT `status: 'active'`.
780
- *
781
- * Keying on active alone was the suspend-bypass (review #2): a SUSPENDED
782
- * grant matched nothing, so this call inserted a SECOND active row for the
783
- * same (subject, resource) and `check()` preferred it — a frozen member
784
- * bought their way back in by simply re-purchasing. With the live key, the
785
- * suspended grant is FOUND instead: the renewal below refreshes its window
786
- * but never touches its status, so the suspension keeps meaning what it
787
- * says until someone with the authority to resume does so.
788
- */
545
+ const now = this.now();
789
546
  const { doc, created } = await this.getOrCreate({
790
547
  subjectModel: input.subjectModel,
791
548
  subjectRef: input.subjectRef,
@@ -804,7 +561,7 @@ var EntitlementRepository = class extends Repository {
804
561
  status: ENTITLEMENT_STATUS.ACTIVE,
805
562
  live: true,
806
563
  source: input.source,
807
- grantedAt: /* @__PURE__ */ new Date(),
564
+ grantedAt: now,
808
565
  notBefore: input.notBefore ?? null,
809
566
  accessExpiresAt: input.accessExpiresAt ?? null,
810
567
  usage: {
@@ -822,128 +579,139 @@ var EntitlementRepository = class extends Repository {
822
579
  await this.emitLifecycle(ACCESS_EVENTS.GRANTED, doc, ctx);
823
580
  return doc;
824
581
  }
582
+ if (originKey !== null && (doc.appliedOrigins ?? []).includes(originKey)) return doc;
825
583
  if (input.renew === false) return doc;
826
- const set = { accessExpiresAt: input.accessExpiresAt ?? null };
584
+ const set = { accessExpiresAt: laterExpiry(doc.accessExpiresAt ?? null, input.accessExpiresAt ?? null) };
827
585
  if (input.notBefore !== void 0) set.notBefore = input.notBefore;
828
- /**
829
- * TOP-UP vs RENEWAL — see `quotaMode`. A top-up GROWS the allowance and preserves
830
- * consumption; a renewal restarts both. `$inc` is used for the top-up so two concurrent
831
- * grants of the same pack cannot lose one another's units to a read-modify-write.
832
- */
833
586
  const inc = {};
834
587
  if (input.usageLimit !== void 0) {
835
588
  if (input.quotaMode === "add") {
836
- /**
837
- * `null` limit means UNLIMITED. Incrementing unlimited is meaningless and `$inc` on
838
- * null would corrupt it to a number, narrowing access that was total — so leave it.
839
- */
840
589
  if (input.usageLimit !== null && doc.usage?.limit !== null) inc["usage.limit"] = input.usageLimit;
841
590
  } else {
842
591
  set["usage.limit"] = input.usageLimit;
843
592
  set["usage.used"] = 0;
844
593
  }
845
594
  }
846
- /**
847
- * A renewal RE-ATTRIBUTES the grant to the paying origin.
848
- *
849
- * `originRef`/`originModel` name the order currently paying for the live
850
- * window (so refunding the OLD order does not revoke access the NEW order
851
- * paid for), while `appliedOrigins` accumulates every origin that ever
852
- * applied — the durable replay ledger `grantByOrigin` checks. Without the
853
- * ledger, a redelivered event for the old order would no longer find its
854
- * origin on the row and would re-run this renewal with the old, stale window.
855
- */
856
595
  if (input.originRef !== void 0) set.originRef = input.originRef;
857
596
  if (input.originModel !== void 0) set.originModel = input.originModel;
858
- const renewed = await this.claimVersion(String(doc._id), { from: doc.version }, {
597
+ const renewed = await this.claimVersion(String(doc._id), {
598
+ from: doc.version,
599
+ ...originKey !== null ? { where: { appliedOrigins: { $ne: originKey } } } : {}
600
+ }, {
859
601
  $set: set,
860
602
  ...Object.keys(inc).length > 0 ? { $inc: inc } : {},
861
603
  ...originKey !== null ? { $addToSet: { appliedOrigins: originKey } } : {}
862
604
  }, opts);
863
- if (!renewed) throw new VersionMismatchError(String(doc._id), doc.version);
605
+ if (!renewed) {
606
+ if (originKey !== null) {
607
+ const fresh = await this.getById(String(doc._id), {
608
+ ...opts,
609
+ throwOnNotFound: false
610
+ });
611
+ if (fresh && (fresh.appliedOrigins ?? []).includes(originKey)) return fresh;
612
+ }
613
+ throw new VersionMismatchError(String(doc._id), doc.version);
614
+ }
864
615
  await this.emitLifecycle(ACCESS_EVENTS.EXTENDED, renewed, ctx);
865
616
  return renewed;
866
617
  }
867
618
  /**
868
- * Decide access RIGHT NOW. Read-only: loads the live grant (active or
869
- * suspended) and runs `evaluateAccess`. Returns `{ allowed, reason, ... }`
870
- * plus the entitlement (or null when none exists).
619
+ * Decide access RIGHT NOW. Read-only. By id, or by the COMPLETE identity tuple — a partial
620
+ * tuple cannot be expressed, so two namespaces sharing an id never answer for each other.
871
621
  */
872
622
  async check(target, ctx) {
873
623
  const grant = await this.findLive(target, ctx);
874
624
  return {
875
- ...evaluateAccess(grant),
625
+ ...evaluateAccess(grant, this.now().getTime()),
876
626
  entitlement: grant
877
627
  };
878
628
  }
879
629
  /**
880
- * `check()` with the COMPLETE identity tuple required.
881
- *
882
- * Prefer this at any security boundary. `check()` keeps `subjectModel` and
883
- * `resourceType` optional for back-compat, which means a polymorphic
884
- * deployment can accidentally ask an ambiguous question: two subject
885
- * namespaces sharing an id (a `user` and an `apiKey` both keyed `42`), or two
886
- * resource types sharing a ref (a product id doubling as a facility key),
887
- * resolve to whichever row sorts first. That is a silent wrong-grant answer,
888
- * and it fails OPEN when the other namespace happens to hold a live grant.
889
- *
890
- * Rather than break every existing caller, the complete tuple is available as
891
- * its own verb: a reviewer can see at the call site which question was asked,
892
- * and `EntitlementTarget`'s optionality can be tightened in a future major
893
- * without a silent behaviour change now.
630
+ * Decide many capabilities for ONE subject in ONE query. Results are in input order.
631
+ * Empty, oversize (> {@link MAX_CAPABILITIES_PER_CHECK}) or duplicate capabilities throw.
894
632
  */
895
- async checkExact(target, ctx) {
896
- return this.check({
897
- subjectModel: target.subjectModel,
898
- subjectRef: target.subjectRef,
899
- resourceType: target.resourceType,
900
- resourceRef: target.resourceRef,
901
- scopeKey: target.scopeKey ?? ""
902
- }, ctx);
633
+ async checkMany(subject, capabilities, ctx) {
634
+ if (capabilities.length === 0) throw new InvalidCheckRequestError("checkMany needs at least one capability");
635
+ if (capabilities.length > 100) throw new InvalidCheckRequestError(`checkMany takes at most 100 capabilities, got ${capabilities.length}`);
636
+ assertSubject(subject);
637
+ for (const capability of capabilities) assertCapability(capability);
638
+ const keys = capabilities.map((c) => capabilityKey(c));
639
+ if (new Set(keys).size !== keys.length) throw new InvalidCheckRequestError("checkMany received the same capability twice");
640
+ const rows = await this.findAll({
641
+ subjectModel: subject.subjectModel,
642
+ subjectRef: subject.subjectRef,
643
+ status: { $in: LIVE_STATUSES },
644
+ $or: capabilities.map((c) => ({
645
+ resourceType: c.resourceType,
646
+ resourceRef: c.resourceRef,
647
+ scopeKey: c.scopeKey ?? ""
648
+ }))
649
+ }, repoOptionsFromCtx(ctx));
650
+ const byKey = /* @__PURE__ */ new Map();
651
+ for (const row of rows) {
652
+ const key = capabilityKey(row);
653
+ const held = byKey.get(key);
654
+ if (!held || held.status !== ENTITLEMENT_STATUS.ACTIVE && row.status === ENTITLEMENT_STATUS.ACTIVE) byKey.set(key, row);
655
+ }
656
+ const at = this.now().getTime();
657
+ return keys.map((key) => {
658
+ const grant = byKey.get(key) ?? null;
659
+ return {
660
+ ...evaluateAccess(grant, at),
661
+ entitlement: grant
662
+ };
663
+ });
903
664
  }
904
665
  /**
905
- * Spend `amount` metered units (a download, an API call, a seat). Atomic and
906
- * race-safe: a metered grant only succeeds while `used + amount <= limit`
907
- * (guarded `$expr`), so N concurrent consumes never overshoot. When the cap
908
- * is reached the grant CAS-transitions to `consumed` and emits
909
- * `access:exhausted`. Unlimited grants (`limit: null`) just increment.
910
- * Throws `QuotaExhaustedError` when no unit is left.
666
+ * Spend metered units, idempotently per `input.key`.
667
+ *
668
+ * The key is claimed in the consumption ledger (unique per grant) BEFORE the spend, and the
669
+ * spend is one guarded `$inc` whose filter re-asserts status, window and `used + amount <=
670
+ * limit` — so a replayed key spends nothing and N concurrent spends never overshoot. A spend
671
+ * that reaches the cap CAS-transitions the grant to `consumed`. Emits `access:consumed` per
672
+ * spend and `access:exhausted` at the cap.
911
673
  */
912
- async consume(target, amount = 1, ctx = {}) {
913
- return this.atomically(ctx, (inner) => this.consumeInner(target, amount, inner));
674
+ async consume(target, input, ctx) {
675
+ return this.atomically(ctx, (inner) => this.consumeInner(target, input, inner));
914
676
  }
915
- async consumeInner(target, amount, ctx) {
677
+ async consumeInner(target, input, ctx) {
916
678
  this.preflightDispatch(ctx);
917
- /**
918
- * Validated HERE, not only in a route schema — this is a public repository
919
- * API and a queue worker calling it directly never met the HTTP validator.
920
- * The dangerous case is not `0`: a NEGATIVE amount `$inc`s `usage.used`
921
- * downward, silently restoring quota with no top-up operation recorded
922
- * (review #4). NaN passes every `$lte` comparison as false and corrupts
923
- * the counter it lands in.
924
- */
679
+ const amount = input.amount ?? 1;
925
680
  if (!Number.isInteger(amount) || amount <= 0) throw new InvalidConsumeAmountError(amount);
681
+ const key = typeof input.key === "string" ? input.key.trim() : "";
682
+ if (key.length === 0 || key.length > 256) throw new ConsumptionKeyRequiredError();
926
683
  const grant = await this.findLive(target, ctx);
927
684
  if (!grant) throw new EntitlementNotFoundError(this.targetLabel(target));
928
- /**
929
- * The full ACCESS DECISION gates the spend, not the stored status alone.
930
- *
931
- * Checking only `status === 'active'` let a caller consume a scheduled
932
- * grant before `notBefore` opened, and an expired grant in the gap before
933
- * the sweeper wrote `status: 'expired'` (review #3). For paid downloads or
934
- * admissions that is an authorization hole, not a bookkeeping one. The
935
- * decision is re-asserted atomically in the update filter below — this
936
- * precheck exists to throw the PRECISE error.
937
- */
938
- const gate = evaluateAccess(grant);
939
- if (!gate.allowed) {
940
- const meterFull = grant.usage.limit !== null && grant.usage.used >= grant.usage.limit;
941
- if (gate.reason === "quota_exhausted" || gate.reason === "consumed" && meterFull) throw new QuotaExhaustedError(String(grant._id), grant.usage.limit);
942
- throw new EntitlementNotUsableError(String(grant._id), gate.reason);
943
- }
685
+ const entitlementId = String(grant._id);
944
686
  const opts = repoOptionsFromCtx(ctx);
687
+ const prior = await this.consumptions.getOne({
688
+ entitlementId,
689
+ key
690
+ }, opts);
691
+ if (prior) return this.replayed(grant, prior, amount, ctx);
692
+ const now = this.now();
693
+ const gate = evaluateAccess(grant, now.getTime());
694
+ if (!gate.allowed) throw this.notUsable(grant, gate.reason);
695
+ try {
696
+ await this.consumptions.create({
697
+ ...ctx.organizationId !== void 0 ? { organizationId: ctx.organizationId } : {},
698
+ entitlementId,
699
+ key,
700
+ amount,
701
+ consumedAt: now,
702
+ ...ctx.actorId !== void 0 ? { actorId: String(ctx.actorId) } : {}
703
+ }, opts);
704
+ } catch (err) {
705
+ if (!this.consumptions.isDuplicateKeyError(err)) throw err;
706
+ if (ctx.session) throw new ConsumptionInFlightError(key);
707
+ const winner = await this.consumptions.getOne({
708
+ entitlementId,
709
+ key
710
+ }, opts);
711
+ if (!winner) throw err;
712
+ return this.replayed(grant, winner, amount, ctx);
713
+ }
945
714
  const metered = grant.usage.limit !== null;
946
- const now = /* @__PURE__ */ new Date();
947
715
  const filter = {
948
716
  _id: grant._id,
949
717
  status: ENTITLEMENT_STATUS.ACTIVE,
@@ -956,52 +724,74 @@ var EntitlementRepository = class extends Repository {
956
724
  } };
957
725
  const updated = await this.findOneAndUpdate(filter, update, {
958
726
  ...opts,
959
- new: true
727
+ returnDocument: "after"
960
728
  });
961
729
  if (!updated) {
730
+ await this.consumptions.Model.deleteOne({
731
+ entitlementId,
732
+ key
733
+ }, ctx.session ? { session: ctx.session } : {});
962
734
  const fresh = await this.findLive(target, ctx);
963
- const freshGate = evaluateAccess(fresh);
964
- if (metered && (freshGate.allowed || freshGate.reason === "quota_exhausted" || freshGate.reason === "consumed")) throw new QuotaExhaustedError(String(grant._id), grant.usage.limit);
965
- if (!fresh) throw new EntitlementNotFoundError(String(grant._id));
735
+ const freshGate = evaluateAccess(fresh, this.now().getTime());
736
+ if (metered && (freshGate.allowed || freshGate.reason === "quota_exhausted" || freshGate.reason === "consumed")) throw new QuotaExhaustedError(entitlementId, grant.usage.limit ?? 0);
737
+ if (!fresh) throw new EntitlementNotFoundError(entitlementId);
966
738
  throw new EntitlementNotUsableError(String(fresh._id), freshGate.reason);
967
739
  }
968
740
  const limit = updated.usage.limit;
741
+ let result = updated;
969
742
  if (limit !== null && updated.usage.used >= limit) {
970
- const consumed = await this.claim(String(updated._id), {
743
+ const consumed = await this.claim(entitlementId, {
971
744
  field: "status",
972
745
  from: ENTITLEMENT_STATUS.ACTIVE,
973
746
  to: ENTITLEMENT_STATUS.CONSUMED
974
747
  }, {
975
748
  $set: {
976
- consumedAt: /* @__PURE__ */ new Date(),
749
+ consumedAt: now,
977
750
  live: null
978
751
  },
979
752
  $inc: { version: 1 }
980
753
  }, opts);
981
- if (consumed) {
982
- await this.emitLifecycle(ACCESS_EVENTS.EXHAUSTED, consumed, ctx);
983
- return consumed;
984
- }
754
+ if (consumed) result = consumed;
985
755
  }
986
- return updated;
756
+ await this.emitLifecycle(ACCESS_EVENTS.CONSUMED, result, ctx, {
757
+ consumptionKey: key,
758
+ amount
759
+ });
760
+ if (result !== updated) await this.emitLifecycle(ACCESS_EVENTS.EXHAUSTED, result, ctx);
761
+ return {
762
+ entitlement: result,
763
+ replayed: false,
764
+ amount,
765
+ remaining: limit === null ? null : Math.max(0, limit - result.usage.used)
766
+ };
767
+ }
768
+ /** The answer for a key that already spent: same amount → replay; different → conflict. */
769
+ async replayed(grant, prior, amount, ctx) {
770
+ if (prior.amount !== amount) throw new ConsumptionKeyConflictError(prior.key, prior.amount, amount);
771
+ const fresh = await this.getById(String(grant._id), {
772
+ ...repoOptionsFromCtx(ctx),
773
+ throwOnNotFound: false
774
+ }) ?? grant;
775
+ const limit = fresh.usage.limit;
776
+ return {
777
+ entitlement: fresh,
778
+ replayed: true,
779
+ amount,
780
+ remaining: limit === null ? null : Math.max(0, limit - fresh.usage.used)
781
+ };
782
+ }
783
+ notUsable(grant, reason) {
784
+ const meterFull = grant.usage.limit !== null && grant.usage.used >= grant.usage.limit;
785
+ if (reason === "quota_exhausted" || reason === "consumed" && meterFull) return new QuotaExhaustedError(String(grant._id), grant.usage.limit ?? 0);
786
+ return new EntitlementNotUsableError(String(grant._id), reason);
987
787
  }
988
788
  /**
989
- * Pause access without ending it (active → suspended).
990
- *
991
- * `autoResumeAt` and `creditWindowOnResume` are the caller's POLICY DECISION,
992
- * computed once here and stored on the grant — see the fields' docblocks. This
993
- * kernel deliberately does not own the rulebook (max days per year, minimum
994
- * length, notice) because those differ per product and per deployment;
995
- * `primitives/suspension.evaluateSuspension` computes them and the host passes
996
- * the answers in.
997
- *
998
- * Omitting `autoResumeAt` leaves the pause OPEN-ENDED, which is the pre-policy
999
- * behaviour and still legal — but it is the shape where a freeze quietly stops
1000
- * the business earning, so a deployment with any allowance at all should always
1001
- * pass one.
789
+ * Pause access (active → suspended). With `policy`, the allowance is enforced against the
790
+ * grant's own status history and `autoResumeAt` is DERIVED (day boundaries in the business
791
+ * zone); without it, `autoResumeAt` is the caller's explicit deadline (omitted = open-ended).
1002
792
  */
1003
793
  async suspend(id, options = {}, ctx = {}) {
1004
- const startsAt = /* @__PURE__ */ new Date();
794
+ const startsAt = this.now();
1005
795
  let autoResumeAt = options.autoResumeAt;
1006
796
  let creditWindowOnResume = options.creditWindowOnResume;
1007
797
  if (options.policy !== void 0) {
@@ -1011,7 +801,7 @@ var EntitlementRepository = class extends Repository {
1011
801
  startsAt,
1012
802
  ...options.endsAt !== void 0 ? { endsAt: options.endsAt } : {},
1013
803
  ...options.requestedAt !== void 0 ? { requestedAt: options.requestedAt } : {}
1014
- }, spans, options.policy, ...options.offsetMinutes !== void 0 ? [{ offsetMinutes: options.offsetMinutes }] : []);
804
+ }, spans, options.policy, { offsetMinutes: zoneOffsetMinutes(startsAt, this.timezone) });
1015
805
  if (!decision.allowed) throw new SuspensionRefusedError(decision.reason, decision.message ?? `Pause refused (${decision.reason})`, decision.daysUsedInPeriod, decision.daysRemainingInPeriod);
1016
806
  autoResumeAt = decision.autoResumeAt ?? null;
1017
807
  creditWindowOnResume = options.policy.creditsWindow === true;
@@ -1024,69 +814,20 @@ var EntitlementRepository = class extends Repository {
1024
814
  });
1025
815
  }
1026
816
  /**
1027
- * Lift a suspension (suspended → active), optionally CREDITING the frozen time.
1028
- *
1029
- * ## Why `creditFrozenDays` exists, and why it is not the default
1030
- *
1031
- * A freeze on a PREPAID term is worthless without it. Consider a Jan–Jun
1032
- * membership (`accessExpiresAt = 1 Jul`) paused on 1 Feb and resumed on 1 Jul:
1033
- * without a credit the window is untouched, so the member resumes into an
1034
- * already-elapsed grant, is refused immediately, and the sweep flips it to
1035
- * `expired`. They paid for six months, used one, and got nothing back.
1036
- *
1037
- * (Note the sweep only touches `active` rows, so pausing does at least PROTECT
1038
- * the grant from expiring mid-freeze — it just comes back worthless.)
1039
- *
1040
- * But crediting is NOT universally right, which is why the caller must choose:
1041
- *
1042
- * - **Prepaid term** — money is already collected, so push the window out by
1043
- * the frozen duration. `creditFrozenDays: true`.
1044
- * - **Rolling subscription** — billing was PAUSED instead, so there is no end
1045
- * date to extend. Crediting here would hand out a free month.
1046
- *
1047
- * Getting it wrong in either direction is a real complaint: credit AND keep
1048
- * billing means the member paid for frozen time; neither means they lost it. The
1049
- * decision belongs to whoever knows the product type, so this kernel takes it as
1050
- * a parameter rather than guessing — and a host reads it from its pause policy,
1051
- * never from a literal.
1052
- *
1053
- * Emits `access:extended` in addition to `access:resumed` when it credits, so a
1054
- * credential-sync subscriber sees the new window.
817
+ * Lift a suspension (suspended → active). The frozen time is credited onto the window in the
818
+ * SAME CAS when `creditFrozenDays` is true — default: the `creditWindowOnResume` promise stored
819
+ * at suspend time (a client cannot award itself an extension). Prepaid terms credit; rolling
820
+ * subscriptions whose billing paused do not.
1055
821
  */
1056
822
  async resume(id, options = {}, ctx = {}) {
1057
823
  return this.atomically(ctx, (inner) => this.resumeInner(id, options, inner));
1058
824
  }
1059
825
  async resumeInner(id, options, ctx) {
1060
826
  const before = await this.load(id, ctx);
1061
- /**
1062
- * Default the decision from the GRANT, not from the caller.
1063
- *
1064
- * `suspend` stored `creditWindowOnResume` when the freeze began — it is a
1065
- * promise made to the member. Omitting the option therefore honours that
1066
- * promise, so a spine action does not have to re-read the doc (and a client
1067
- * cannot flip it at resume time, which would be a free window extension for
1068
- * anyone able to call the endpoint). An EXPLICIT `false` still overrides, for a
1069
- * deliberate operator correction.
1070
- */
1071
827
  const shouldCredit = options.creditFrozenDays ?? before.creditWindowOnResume === true;
1072
- /**
1073
- * The credit is computed BEFORE the transition and folded into the SAME
1074
- * guarded update (review #10). The previous shape — transition, then a
1075
- * separate `extend()` — had a gap: if the extend lost its version race or
1076
- * the process died between the two writes, the grant came back ACTIVE with
1077
- * its window UNCREDITED, and a prepaid member resumed straight into
1078
- * `expired`. One CAS means the member is either still suspended (retry
1079
- * safely) or active WITH the promised time — never the third state.
1080
- *
1081
- * A lifetime grant (`accessExpiresAt: null`) has no window to push out, and
1082
- * a grant with no `suspendedAt` was never actually frozen — crediting
1083
- * either would invent time from nothing. Negative `frozenMs` (NTP
1084
- * correction, a hand-edited `suspendedAt`) is refused because a negative
1085
- * credit would SHORTEN a paying member's window.
1086
- */
1087
828
  let creditedExpiry = null;
1088
829
  if (shouldCredit && before.suspendedAt && before.accessExpiresAt != null) {
1089
- const frozenMs = Date.now() - before.suspendedAt.getTime();
830
+ const frozenMs = this.now().getTime() - before.suspendedAt.getTime();
1090
831
  if (frozenMs > 0) creditedExpiry = new Date(before.accessExpiresAt.getTime() + frozenMs);
1091
832
  }
1092
833
  const resumed = await this.transition(id, ENTITLEMENT_STATUS.ACTIVE, ACCESS_EVENTS.RESUMED, ctx, {
@@ -1098,90 +839,93 @@ var EntitlementRepository = class extends Repository {
1098
839
  }
1099
840
  /** Pull access permanently (active|suspended → revoked). Window cut to now. */
1100
841
  async revoke(id, options = {}, ctx = {}) {
842
+ const now = this.now();
1101
843
  return this.transition(id, ENTITLEMENT_STATUS.REVOKED, ACCESS_EVENTS.REVOKED, ctx, {
1102
- revokedAt: /* @__PURE__ */ new Date(),
1103
- accessExpiresAt: /* @__PURE__ */ new Date(),
844
+ revokedAt: now,
845
+ accessExpiresAt: now,
1104
846
  ...options.reason !== void 0 ? { reason: options.reason } : {}
1105
847
  });
1106
848
  }
1107
849
  /** Mark a grant refunded (active|suspended → refunded). Window cut to now. */
1108
850
  async refund(id, options = {}, ctx = {}) {
851
+ const now = this.now();
1109
852
  return this.transition(id, ENTITLEMENT_STATUS.REFUNDED, ACCESS_EVENTS.REFUNDED, ctx, {
1110
- refundedAt: /* @__PURE__ */ new Date(),
1111
- accessExpiresAt: /* @__PURE__ */ new Date(),
853
+ refundedAt: now,
854
+ accessExpiresAt: now,
1112
855
  ...options.reason !== void 0 ? { reason: options.reason } : {}
1113
856
  });
1114
857
  }
1115
858
  /**
1116
- * Extend (or set) the access window — a renewal. Pass an absolute
1117
- * `accessExpiresAt`, or `addMs` to push the current window out. Reactivates
1118
- * an `expired` grant. Emits `access:extended`.
859
+ * Extend the access window — exactly ONE of an absolute `accessExpiresAt` (`null` = lifetime)
860
+ * or a positive `addMs`. Never shortens (that is revoke + re-grant), refuses `addMs` on a
861
+ * lifetime grant, and reactivates an `expired` grant only into a window that is still open
862
+ * (`addMs` then counts from now). Emits `access:extended`.
1119
863
  */
1120
864
  async extend(id, options, ctx = {}) {
1121
865
  return this.atomically(ctx, (inner) => this.extendInner(id, options, inner));
1122
866
  }
1123
867
  async extendInner(id, options, ctx) {
1124
868
  this.preflightDispatch(ctx);
869
+ const hasAbsolute = options.accessExpiresAt !== void 0;
870
+ const hasRelative = options.addMs !== void 0;
871
+ if (hasAbsolute === hasRelative) throw new InvalidExtensionError("extend() takes exactly one of `accessExpiresAt` or `addMs`");
1125
872
  const grant = await this.load(id, ctx);
1126
873
  const opts = repoOptionsFromCtx(ctx);
1127
- const newExpiry = options.accessExpiresAt !== void 0 ? options.accessExpiresAt : options.addMs != null ? new Date((grant.accessExpiresAt?.getTime() ?? Date.now()) + options.addMs) : null;
874
+ const now = this.now();
875
+ const current = grant.accessExpiresAt ?? null;
876
+ let newExpiry;
877
+ if (hasRelative) {
878
+ const addMs = options.addMs ?? 0;
879
+ if (!Number.isInteger(addMs) || addMs <= 0) throw new InvalidExtensionError("`addMs` must be a positive integer");
880
+ if (current === null) throw new InvalidExtensionError("a lifetime grant has no window to extend");
881
+ const base = grant.status === ENTITLEMENT_STATUS.EXPIRED ? Math.max(now.getTime(), current.getTime()) : current.getTime();
882
+ newExpiry = new Date(base + addMs);
883
+ } else {
884
+ newExpiry = options.accessExpiresAt ?? null;
885
+ if (newExpiry !== null && Number.isNaN(newExpiry.getTime())) throw new InvalidExtensionError("`accessExpiresAt` is not a valid date");
886
+ if (current !== null && newExpiry !== null && newExpiry.getTime() < current.getTime()) throw new InvalidExtensionError("extend() never shortens a window — revoke and re-grant to cut access");
887
+ }
1128
888
  let updated;
1129
- if (grant.status === ENTITLEMENT_STATUS.EXPIRED) updated = await this.claim(id, {
1130
- field: "status",
1131
- from: ENTITLEMENT_STATUS.EXPIRED,
1132
- to: ENTITLEMENT_STATUS.ACTIVE
1133
- }, {
1134
- $set: {
1135
- accessExpiresAt: newExpiry,
1136
- expiredAt: null,
1137
- live: true
1138
- },
1139
- $inc: { version: 1 }
1140
- }, opts);
1141
- else if (grant.status === ENTITLEMENT_STATUS.ACTIVE || grant.status === ENTITLEMENT_STATUS.SUSPENDED) updated = await this.claimVersion(id, { from: grant.version }, { $set: { accessExpiresAt: newExpiry } }, opts);
889
+ if (grant.status === ENTITLEMENT_STATUS.EXPIRED) {
890
+ if (newExpiry !== null && newExpiry.getTime() <= now.getTime()) throw new InvalidExtensionError("reactivating an expired grant needs a window that is still open");
891
+ updated = await this.claim(id, {
892
+ field: "status",
893
+ from: ENTITLEMENT_STATUS.EXPIRED,
894
+ to: ENTITLEMENT_STATUS.ACTIVE
895
+ }, {
896
+ $set: {
897
+ accessExpiresAt: newExpiry,
898
+ expiredAt: null,
899
+ live: true
900
+ },
901
+ $inc: { version: 1 }
902
+ }, opts);
903
+ } else if (grant.status === ENTITLEMENT_STATUS.ACTIVE || grant.status === ENTITLEMENT_STATUS.SUSPENDED) updated = await this.claimVersion(id, { from: grant.version }, { $set: { accessExpiresAt: newExpiry } }, opts);
1142
904
  else throw new InvalidEntitlementTransitionError(grant.status, ENTITLEMENT_STATUS.ACTIVE);
1143
905
  if (!updated) throw new VersionMismatchError(id, grant.version);
1144
906
  await this.emitLifecycle(ACCESS_EVENTS.EXTENDED, updated, ctx);
1145
907
  return updated;
1146
908
  }
1147
909
  /**
1148
- * Resume suspensions that have reached their deadline.
1149
- *
1150
- * ## Why this sweep is a revenue control, not housekeeping
1151
- *
1152
- * A freeze with no automatic end is an indefinite free hold. The member pauses in
1153
- * February, the business stops earning, and nothing looks broken — so nobody
1154
- * files a bug and it is found by an audit months later, if at all. This closes
1155
- * that: the pause ends on the date it was capped at, whether or not the member
1156
- * ever comes back.
1157
- *
1158
- * ## It uses the STORED decision, never a fresh one
1159
- *
1160
- * Both `autoResumeAt` and `creditWindowOnResume` are read off the grant, not
1161
- * recomputed from current policy. They are promises made when the freeze began,
1162
- * and re-deriving them would silently move a date the member was told the moment
1163
- * an operator edited the rulebook. (`primitives/suspension.dueForAutoResume`
1164
- * documents the same rule for the pure form.)
1165
- *
1166
- * Per-row failures are collected, not thrown: one grant whose credit maths hits a
1167
- * VersionMismatch must not abort the sweep and leave the rest suspended.
910
+ * Resume suspensions past their stored `autoResumeAt`, honouring the stored credit promise.
911
+ * A lost CAS on one row counts as `failed` and never aborts the sweep.
1168
912
  */
1169
913
  async autoResumeDue(options = {}, ctx = {}) {
1170
- const cutoff = options.now ?? /* @__PURE__ */ new Date();
1171
- const due = await this.getAll({
1172
- filters: {
1173
- status: ENTITLEMENT_STATUS.SUSPENDED,
1174
- autoResumeAt: {
1175
- $ne: null,
1176
- $lte: cutoff
1177
- }
1178
- },
914
+ const cutoff = options.now ?? this.now();
915
+ const due = await this.findAll({
916
+ status: ENTITLEMENT_STATUS.SUSPENDED,
917
+ autoResumeAt: {
918
+ $ne: null,
919
+ $lte: cutoff
920
+ }
921
+ }, {
922
+ ...repoOptionsFromCtx(ctx),
1179
923
  sort: { autoResumeAt: 1 },
1180
- limit: options.limit ?? 500
1181
- }, repoOptionsFromCtx(ctx));
924
+ limit: options.limit ?? BATCH_SIZE
925
+ });
1182
926
  let resumed = 0;
1183
927
  let failed = 0;
1184
- for (const grant of due.data) try {
928
+ for (const grant of due) try {
1185
929
  await this.resume(String(grant._id), { creditFrozenDays: grant.creditWindowOnResume === true }, ctx);
1186
930
  resumed += 1;
1187
931
  } catch {
@@ -1193,54 +937,14 @@ var EntitlementRepository = class extends Repository {
1193
937
  };
1194
938
  }
1195
939
  /**
1196
- * The RENEWAL WORKLIST — grants whose access window closes inside a calendar
1197
- * range, soonest first.
1198
- *
1199
- * ## Why this is a domain verb and not a `getAll` the caller could write
1200
- *
1201
- * Three decisions live here that every caller would otherwise re-derive, and
1202
- * would eventually re-derive differently:
1203
- *
1204
- * 1. **Which statuses are renewable.** `active` AND `suspended`. A frozen
1205
- * membership still has an expiry date and still needs renewing — dropping it
1206
- * silently shortens the worklist, and the members missing from it are
1207
- * exactly the ones already at risk of leaving. `expired` is deliberately NOT
1208
- * here: lapsed grants are a different, later conversation (win-back), and
1209
- * mixing them makes "how many renewals are due" unanswerable.
1210
- * 2. **Open-ended grants are excluded.** `accessExpiresAt: null` means access
1211
- * does not lapse, so such a member never belongs on a renewal list.
1212
- *
1213
- * The `$ne: null` below is EXPLICIT, not load-bearing: a `$gte`/`$lte` date
1214
- * comparison already excludes `null` in MongoDB, so removing it changes
1215
- * nothing today. It is kept because the exclusion is a domain decision that
1216
- * should be readable at the filter rather than inferred from BSON comparison
1217
- * order — and because a future sentinel value (a far-future date standing in
1218
- * for "lifetime") would satisfy the range and silently reappear.
1219
- *
1220
- * An earlier draft of this docblock claimed the guard was what kept those
1221
- * rows out. Falsifying the filter disproved it; the claim is corrected here
1222
- * rather than left as a rationale that does not hold.
1223
- * 3. **The range is a CALENDAR range**, resolved against this repository's own
1224
- * business zone. "Expiring this month" is a business-month question; built
1225
- * from `Date.UTC` it disagrees with the filing month at both ends by the
1226
- * zone offset — six hours in Asia/Dhaka — so the first and last day of every
1227
- * window silently gain or lose members.
1228
- *
1229
- * ## Rows, not a count, and bounded
1230
- *
1231
- * A worklist is only useful as rows — the point is who to call. But it is
1232
- * paginated through the inherited `getAll`, so tenancy, soft-delete and the
1233
- * limit all apply; an unbounded list on an operator-facing screen is a
1234
- * self-inflicted load problem.
1235
- *
1236
- * Read-only: this never transitions anything. `expireDue` is the sweep that
1237
- * flips a lapsed grant to `expired`, and the two must not be confused — asking
1238
- * "who is about to lapse" must never cause a lapse.
940
+ * The RENEWAL WORKLIST — live (active AND, by default, suspended) grants whose window closes
941
+ * inside a calendar range, soonest first. Lifetime grants are excluded. Read-only.
1239
942
  */
1240
943
  async expiringBetween(range, options = {}, ctx = {}) {
1241
944
  const { from, to } = this.resolveExpiryWindow(range);
1242
945
  const statuses = options.includeSuspended === false ? [ENTITLEMENT_STATUS.ACTIVE] : [ENTITLEMENT_STATUS.ACTIVE, ENTITLEMENT_STATUS.SUSPENDED];
1243
- return await this.getAll({
946
+ return this.getAll({
947
+ mode: "offset",
1244
948
  filters: {
1245
949
  status: { $in: statuses },
1246
950
  accessExpiresAt: {
@@ -1259,52 +963,10 @@ var EntitlementRepository = class extends Repository {
1259
963
  }, repoOptionsFromCtx(ctx));
1260
964
  }
1261
965
  /**
1262
- * CHURN — grants that lapsed in a window and were NOT renewed within grace.
1263
- *
1264
- * ## The definition, and why it is this one
1265
- *
1266
- * Three things get called churn, and they give different numbers from the same
1267
- * data:
1268
- *
1269
- * | | counts | why not here |
1270
- * |---|---|---|
1271
- * | snapshot | active last period minus active this period | needs historical actives, which current rows cannot reconstruct |
1272
- * | cohort retention | of those who joined in M, how many at M+n | a different question (a retention curve), not "who did we lose" |
1273
- * | **lapsed-not-renewed** | expired in the window with no live grant inside grace | **this one** |
1274
- *
1275
- * The third, because {@link ENTITLEMENT_MACHINE} makes `expired -> active`
1276
- * LEGAL: a renewal restarts the window, so `expired` is not terminal and an
1277
- * expired grant is not by itself a loss. People renew late. A metric that counts
1278
- * them as churned reports losses that already walked back in, and an operator
1279
- * learns to distrust it.
1280
- *
1281
- * ## Why this needs no fact projection
1282
- *
1283
- * Expiry is a state TRANSITION, never a TTL-delete — the row survives (see
1284
- * `entitlement-status.enum.ts`: terminal states free the live-uniqueness slot,
1285
- * they do not remove history). So both sides of the question are in live data
1286
- * and this is a self-join.
1287
- *
1288
- * The historical ACTIVE COUNT is the part that genuinely needs a projection
1289
- * ("how many were active on 1 March" is not derivable from current rows). That
1290
- * is a separate build; conflating the two is what made this look bigger than it
1291
- * is.
1292
- *
1293
- * ## What counts as renewed
1294
- *
1295
- * A live grant (`active` or `suspended`) for the SAME subject and resource,
1296
- * granted no later than `lapse + graceDays`, whose own window outlasts the lapse
1297
- * (or never ends).
1298
- *
1299
- * Deliberately NOT "granted after the lapse": a member who pays early renews
1300
- * BEFORE expiry, so requiring the later date would count the most diligent
1301
- * members as churned.
1302
- *
1303
- * ## What is excluded from the lapse population
1304
- *
1305
- * `revoked` and `refunded` are terminal by decision — an admin pull, a dispute,
1306
- * a chargeback. Real losses, but not FAILURES TO RENEW, and folding them in
1307
- * makes the number unactionable: you cannot win back someone you ejected.
966
+ * CHURN — grants that lapsed (`expired`) in a calendar range with no live replacement for the
967
+ * same subject × resource granted within `graceDays` of the lapse. Revoked / refunded grants
968
+ * are not failures to renew and are excluded. `unsettledDays > 0` means the figure can still
969
+ * fall as late renewals land.
1308
970
  */
1309
971
  async churnBetween(range, options = {}, ctx = {}) {
1310
972
  const { from, to } = this.resolveExpiryWindow(range);
@@ -1364,7 +1026,7 @@ var EntitlementRepository = class extends Repository {
1364
1026
  ], repoOptionsFromCtx(ctx));
1365
1027
  const lapsed = rows[0]?.lapsed ?? 0;
1366
1028
  const renewed = rows[0]?.renewed ?? 0;
1367
- const unsettledMs = to.getTime() + graceMs - (options.now ?? /* @__PURE__ */ new Date()).getTime();
1029
+ const unsettledMs = to.getTime() + graceMs - (options.now ?? this.now()).getTime();
1368
1030
  const unsettledDays = unsettledMs <= 0 ? 0 : Math.ceil(unsettledMs / 864e5);
1369
1031
  return {
1370
1032
  lapsed,
@@ -1374,31 +1036,11 @@ var EntitlementRepository = class extends Repository {
1374
1036
  unsettledDays
1375
1037
  };
1376
1038
  }
1377
- /**
1378
- * Resolve an {@link ExpiryWindow} to instants using THIS repository's business
1379
- * zone.
1380
- *
1381
- * Civil dates are the preferred form because a period is a calendar span;
1382
- * instants are accepted so a caller that already holds them (a cron with a
1383
- * computed cutoff) is not forced to round-trip through strings. A MIXED pair is
1384
- * refused rather than guessed — `{ from: '2026-08-01', to: someDate }` has no
1385
- * single obvious meaning, and silently picking one produces a window nobody
1386
- * asked for.
1387
- */
1039
+ /** Resolve an {@link ExpiryWindow} in the business zone. A mixed civil/instant pair throws. */
1388
1040
  resolveExpiryWindow(range) {
1389
- const fromCivil = typeof range.from === "string";
1390
- if (fromCivil !== (typeof range.to === "string")) throw new InvalidExpiryWindowError("`from` and `to` must both be civil dates or both be instants.");
1391
- if (!fromCivil) {
1392
- const from = range.from;
1393
- const to = range.to;
1394
- if (from.getTime() > to.getTime()) throw new InvalidExpiryWindowError("`from` must not be after `to`.");
1395
- return {
1396
- from,
1397
- to
1398
- };
1399
- }
1400
- try {
1401
- const span = resolveDateSpan(range.from, range.to, this.timezone);
1041
+ const { from: rawFrom, to: rawTo } = range;
1042
+ if (typeof rawFrom === "string" && typeof rawTo === "string") try {
1043
+ const span = resolveDateSpan(rawFrom, rawTo, this.timezone);
1402
1044
  return {
1403
1045
  from: span.start,
1404
1046
  to: inclusiveEnd(span)
@@ -1406,35 +1048,35 @@ var EntitlementRepository = class extends Repository {
1406
1048
  } catch (err) {
1407
1049
  throw new InvalidExpiryWindowError(err instanceof Error ? err.message : "invalid expiry window");
1408
1050
  }
1051
+ if (rawFrom instanceof Date && rawTo instanceof Date) {
1052
+ if (rawFrom.getTime() > rawTo.getTime()) throw new InvalidExpiryWindowError("`from` must not be after `to`.");
1053
+ return {
1054
+ from: rawFrom,
1055
+ to: rawTo
1056
+ };
1057
+ }
1058
+ throw new InvalidExpiryWindowError("`from` and `to` must both be civil dates or both be instants.");
1409
1059
  }
1410
1060
  /**
1411
- * Sweep grants whose window has lapsed: CAS active → expired, emit
1412
- * `access:expired` per row. The row SURVIVES (audit / renewal); this is the
1413
- * "model expiry as a state transition" rule, not a TTL-delete. The CAS
1414
- * `where` re-guards the window so a concurrent `extend` is never clobbered.
1415
- * Drive it from a host cron. Returns how many were swept.
1416
- *
1417
- * Read-time `check()` already denies a lapsed grant before the sweep runs —
1418
- * this pass exists to fire the event and make `status: 'expired'` queryable,
1419
- * not to enforce the gate.
1061
+ * Sweep lapsed grants: CAS active → expired (window re-guarded in the filter) and emit
1062
+ * `access:expired`, one transaction per row. The gate never waits for this — it derives expiry.
1420
1063
  */
1421
1064
  async expireDue(options = {}, ctx = {}) {
1422
1065
  this.preflightDispatch(ctx);
1423
- const cutoff = options.now ?? /* @__PURE__ */ new Date();
1424
- const opts = repoOptionsFromCtx(ctx);
1425
- const due = await this.getAll({
1426
- filters: {
1427
- status: ENTITLEMENT_STATUS.ACTIVE,
1428
- accessExpiresAt: {
1429
- $ne: null,
1430
- $lte: cutoff
1431
- }
1432
- },
1066
+ const cutoff = options.now ?? this.now();
1067
+ const due = await this.findAll({
1068
+ status: ENTITLEMENT_STATUS.ACTIVE,
1069
+ accessExpiresAt: {
1070
+ $ne: null,
1071
+ $lte: cutoff
1072
+ }
1073
+ }, {
1074
+ ...repoOptionsFromCtx(ctx),
1433
1075
  sort: { accessExpiresAt: 1 },
1434
- limit: options.limit ?? 500
1435
- }, opts);
1076
+ limit: options.limit ?? BATCH_SIZE
1077
+ });
1436
1078
  let swept = 0;
1437
- for (const grant of due.data) if (await this.atomically(ctx, async (inner) => {
1079
+ for (const grant of due) if (await this.atomically(ctx, async (inner) => {
1438
1080
  const claimed = await this.claim(String(grant._id), {
1439
1081
  field: "status",
1440
1082
  from: ENTITLEMENT_STATUS.ACTIVE,
@@ -1442,7 +1084,7 @@ var EntitlementRepository = class extends Repository {
1442
1084
  where: { accessExpiresAt: { $lte: cutoff } }
1443
1085
  }, {
1444
1086
  $set: {
1445
- expiredAt: /* @__PURE__ */ new Date(),
1087
+ expiredAt: this.now(),
1446
1088
  live: null
1447
1089
  },
1448
1090
  $inc: { version: 1 }
@@ -1452,138 +1094,53 @@ var EntitlementRepository = class extends Repository {
1452
1094
  })) swept += 1;
1453
1095
  return { swept };
1454
1096
  }
1455
- /**
1456
- * Refund cascade — when an order/transaction is reversed, mark every live
1457
- * grant it produced as refunded. Looks up by the polymorphic origin ref.
1458
- */
1097
+ /** Refund every live grant one origin produced. Drained until empty. */
1459
1098
  async refundByOrigin(originModel, originRef, options = {}, ctx = {}) {
1460
1099
  this.preflightDispatch(ctx);
1461
- /**
1462
- * DRAINED in batches until the filter returns nothing (review #9). A single
1463
- * `getAll` page silently capped the cascade at the backend's default page
1464
- * size — a refund of a bulk order would revoke the first page of grants and
1465
- * leave the rest LIVE, which is precisely the failure a refund cascade
1466
- * exists to prevent. Each processed row leaves the filter (its status
1467
- * changes), so re-querying page one until empty terminates.
1468
- *
1469
- * Rows go through `transition()` — the single funnel — so the status
1470
- * history is appended and the live mirror maintained; a lost CAS (a human
1471
- * revoked concurrently) throws InvalidTransition for THAT row and is
1472
- * counted as skipped rather than aborting the batch.
1473
- */
1474
1100
  let refunded = 0;
1475
1101
  for (;;) {
1476
- const live = await this.getAll({
1477
- filters: {
1478
- originModel,
1479
- originRef,
1480
- status: { $in: LIVE_STATUSES }
1481
- },
1102
+ const live = await this.findAll({
1103
+ originModel,
1104
+ originRef,
1105
+ status: { $in: LIVE_STATUSES }
1106
+ }, {
1107
+ ...repoOptionsFromCtx(ctx),
1482
1108
  limit: BATCH_SIZE
1483
- }, repoOptionsFromCtx(ctx));
1484
- if (live.data.length === 0) break;
1485
- for (const grant of live.data) try {
1486
- await this.transition(String(grant._id), ENTITLEMENT_STATUS.REFUNDED, ACCESS_EVENTS.REFUNDED, ctx, {
1487
- refundedAt: /* @__PURE__ */ new Date(),
1488
- accessExpiresAt: /* @__PURE__ */ new Date(),
1489
- ...options.reason !== void 0 ? { reason: options.reason } : {}
1490
- });
1491
- refunded += 1;
1492
- } catch (err) {
1493
- if (!(err instanceof InvalidEntitlementTransitionError)) throw err;
1109
+ });
1110
+ if (live.length === 0) break;
1111
+ for (const grant of live) {
1112
+ const now = this.now();
1113
+ try {
1114
+ await this.transition(String(grant._id), ENTITLEMENT_STATUS.REFUNDED, ACCESS_EVENTS.REFUNDED, ctx, {
1115
+ refundedAt: now,
1116
+ accessExpiresAt: now,
1117
+ ...options.reason !== void 0 ? { reason: options.reason } : {}
1118
+ });
1119
+ refunded += 1;
1120
+ } catch (err) {
1121
+ if (!(err instanceof InvalidEntitlementTransitionError)) throw err;
1122
+ }
1494
1123
  }
1495
1124
  }
1496
1125
  return { refunded };
1497
1126
  }
1498
1127
  /**
1499
- * Grant idempotently PER ORIGIN.
1500
- *
1501
- * `grant()` is already idempotent per (subject, resource, scope) — but it
1502
- * REFRESHES the window on a repeat, which is right for a genuine renewal and
1503
- * wrong for a redelivered event: an at-least-once bus would silently extend a
1504
- * membership every time it replayed. Keying on the origin separates the two —
1505
- * the same order never grants twice, a new order still renews.
1128
+ * Grant idempotently PER ORIGIN + RESOURCE. A redelivered event finds its origin in
1129
+ * `appliedOrigins` — across EVERY status, so a refunded or revoked grant is never resurrected
1130
+ * by a replay — and returns it with `created: false`. A per-cycle renewal therefore needs a
1131
+ * cycle-scoped origin ref.
1506
1132
  */
1507
1133
  async grantByOrigin(input, ctx) {
1508
- const opts = repoOptionsFromCtx(ctx);
1509
- /**
1510
- * Identity = ORIGIN **plus the RESOURCE**.
1511
- *
1512
- * Matching on the origin alone was correct only while one source projected one
1513
- * right. It does not survive a BUNDLE: a Gold membership line that confers gym
1514
- * floor + pool + spa is three distinct entitlements from one origin, and an
1515
- * origin-only match would treat the second and third as replays of the first —
1516
- * so the pool and spa rights would silently never exist.
1517
- *
1518
- * The resource is what makes them different things, so the resource belongs in the
1519
- * identity. The alternative — encoding it into the `originRef` string
1520
- * (`ORD-1:L1#pool`) — pushes the discriminator into every consumer as a stringly
1521
- * typed convention, and conventions drift.
1522
- *
1523
- * ## The deliberate asymmetry with the reversal verbs
1524
- *
1525
- * `setStateByOrigin` / `refundByOrigin` still cascade over the ORIGIN ALONE, and
1526
- * that is not an oversight:
1527
- *
1528
- * - GRANT asks "have I already projected THIS right from THIS source?" → needs
1529
- * the resource, or a bundle collapses.
1530
- * - REVERSAL asks "undo everything that came from this source" → must NOT filter
1531
- * by resource, or refunding a Gold membership would revoke the floor right and
1532
- * leave the pool and spa live.
1533
- *
1534
- * Same shape for a hotel booking granting room + breakfast + spa, or an HR
1535
- * onboarding granting badge + locker + parking.
1536
- */
1537
- /**
1538
- * The replay check reads the APPLIED-ORIGINS ledger, not the origin fields.
1539
- *
1540
- * `originRef`/`originModel` hold only the LATEST paying origin — after order
1541
- * B renews a grant first created by order A, a redelivered event for A would
1542
- * find nothing there and re-run the renewal with A's STALE window, silently
1543
- * shortening what B paid for (review #8). Ledger membership is the durable
1544
- * fact "this origin already did its work", written in the same update that
1545
- * did the work.
1546
- *
1547
- * Concurrency: two first deliveries of the SAME origin can both miss this
1548
- * read; both then call `grant()`, whose atomic `getOrCreate` (backed by the
1549
- * live-unique index) converges them on ONE document — the loser lands on the
1550
- * renewal path and adds an already-present ledger key with an identical
1551
- * window. Converged state, at-least-once events; no double-provision.
1552
- */
1553
1134
  const originKey = `${input.originModel}:${input.originRef}`;
1554
- /**
1555
- * Checked across EVERY status — deliberately NOT narrowed to the live ones.
1556
- *
1557
- * Narrowing to live was a resurrection hole: refund (or revoke, or expiry,
1558
- * or exhaustion) leaves the grant terminal, so a redelivered ORD-1 event
1559
- * found no LIVE match, fell through to `grant()`, and — because a terminal
1560
- * row holds no live-uniqueness slot — inserted a FRESH ACTIVE grant.
1561
- * Access that was deliberately terminated came back, triggered by nothing
1562
- * more than an at-least-once bus doing its job. A refunded member walks
1563
- * back in.
1564
- *
1565
- * The ledger records "this origin already did its work", and that is a
1566
- * PERMANENT fact about a past event, not a statement about current access.
1567
- * Terminal status is an ANSWER, not an absence.
1568
- *
1569
- * ## What this means for subscription renewals
1570
- *
1571
- * A per-cycle renewal must therefore carry a CYCLE-SCOPED origin ref
1572
- * (`ORD-1:L1#c2`), not reuse the order's — reusing it means "the same event
1573
- * again", which this now correctly refuses. Same lesson as the bundle fix:
1574
- * whatever makes two grants DIFFERENT things belongs in the identity.
1575
- * Pushing an existing window out is `extendByOrigin`, which is idempotent
1576
- * by value and unaffected.
1577
- */
1578
- const existing = await this.getAll({
1579
- filters: {
1580
- appliedOrigins: originKey,
1581
- resourceType: input.resourceType,
1582
- resourceRef: input.resourceRef
1583
- },
1135
+ const existing = await this.findAll({
1136
+ appliedOrigins: originKey,
1137
+ resourceType: input.resourceType,
1138
+ resourceRef: input.resourceRef
1139
+ }, {
1140
+ ...repoOptionsFromCtx(ctx),
1584
1141
  sort: { updatedAt: -1 }
1585
- }, opts);
1586
- const already = existing.data.find((row) => LIVE_STATUSES.includes(row.status)) ?? existing.data[0];
1142
+ });
1143
+ const already = existing.find((row) => LIVE_STATUSES.includes(row.status)) ?? existing[0];
1587
1144
  if (already) return {
1588
1145
  grant: already,
1589
1146
  created: false
@@ -1594,110 +1151,72 @@ var EntitlementRepository = class extends Repository {
1594
1151
  };
1595
1152
  }
1596
1153
  /**
1597
- * Move every live grant from one origin to `suspended` / `active` / `revoked`.
1598
- *
1599
- * Mirrors `refundByOrigin`: a CAS `claim` per row so a concurrent human action
1600
- * cannot be clobbered, and the lifecycle event emitted only when the claim won
1601
- * (so a redelivery emits nothing).
1602
- *
1603
- * `resume` deliberately only lifts SUSPENDED grants — resuming an expired or
1604
- * revoked one would resurrect access the domain already ended.
1154
+ * Move every live grant from one origin to `suspended` / `active` / `revoked`. `resume` lifts
1155
+ * only SUSPENDED grants. Already-there rows are excluded in the query; drained until empty.
1605
1156
  */
1606
1157
  async setStateByOrigin(originModel, originRef, effect, options = {}, ctx = {}) {
1607
1158
  this.preflightDispatch(ctx);
1608
- const opts = repoOptionsFromCtx(ctx);
1609
1159
  const from = effect === "resume" ? [ENTITLEMENT_STATUS.SUSPENDED] : [ENTITLEMENT_STATUS.ACTIVE, ENTITLEMENT_STATUS.SUSPENDED];
1610
1160
  const to = effect === "suspend" ? ENTITLEMENT_STATUS.SUSPENDED : effect === "resume" ? ENTITLEMENT_STATUS.ACTIVE : ENTITLEMENT_STATUS.REVOKED;
1611
1161
  const event = effect === "suspend" ? ACCESS_EVENTS.SUSPENDED : effect === "resume" ? ACCESS_EVENTS.RESUMED : ACCESS_EVENTS.REVOKED;
1612
- /**
1613
- * Already-there rows are excluded IN THE QUERY, not skipped in the loop —
1614
- * with the drain loop below, a loop-side skip would re-fetch the same page
1615
- * forever once it held more than BATCH_SIZE already-done rows. Drained
1616
- * until empty (review #9): a single page silently capped the cascade, so
1617
- * suspending a bulk origin left every row past the page size LIVE.
1618
- *
1619
- * Rows route through `transition()` so the status history is appended
1620
- * (the suspension ALLOWANCE is derived from it — a cascade that skipped the
1621
- * log would undercount every future pause) and the live mirror moves with
1622
- * the status. A lost CAS throws InvalidTransition for that row only.
1623
- */
1624
1162
  const queryFrom = from.filter((status) => status !== to);
1625
1163
  let changed = 0;
1626
1164
  for (;;) {
1627
- const rows = await this.getAll({
1628
- filters: {
1629
- originModel,
1630
- originRef,
1631
- status: { $in: queryFrom }
1632
- },
1165
+ const rows = await this.findAll({
1166
+ originModel,
1167
+ originRef,
1168
+ status: { $in: queryFrom }
1169
+ }, {
1170
+ ...repoOptionsFromCtx(ctx),
1633
1171
  limit: BATCH_SIZE
1634
- }, opts);
1635
- if (rows.data.length === 0) break;
1636
- for (const grant of rows.data) try {
1637
- await this.transition(String(grant._id), to, event, ctx, {
1638
- ...effect === "suspend" ? { suspendedAt: /* @__PURE__ */ new Date() } : {},
1639
- ...effect === "resume" ? { autoResumeAt: null } : {},
1640
- ...effect === "revoke" ? {
1641
- revokedAt: /* @__PURE__ */ new Date(),
1642
- accessExpiresAt: /* @__PURE__ */ new Date()
1643
- } : {},
1644
- ...options.reason !== void 0 ? { reason: options.reason } : {}
1645
- });
1646
- changed += 1;
1647
- } catch (err) {
1648
- if (!(err instanceof InvalidEntitlementTransitionError)) throw err;
1172
+ });
1173
+ if (rows.length === 0) break;
1174
+ for (const grant of rows) {
1175
+ const now = this.now();
1176
+ try {
1177
+ await this.transition(String(grant._id), to, event, ctx, {
1178
+ ...effect === "suspend" ? { suspendedAt: now } : {},
1179
+ ...effect === "resume" ? { autoResumeAt: null } : {},
1180
+ ...effect === "revoke" ? {
1181
+ revokedAt: now,
1182
+ accessExpiresAt: now
1183
+ } : {},
1184
+ ...options.reason !== void 0 ? { reason: options.reason } : {}
1185
+ });
1186
+ changed += 1;
1187
+ } catch (err) {
1188
+ if (!(err instanceof InvalidEntitlementTransitionError)) throw err;
1189
+ }
1649
1190
  }
1650
1191
  }
1651
1192
  return { changed };
1652
1193
  }
1653
1194
  /**
1654
- * Push the expiry of every live grant from one origin.
1655
- *
1656
- * Used when the SOURCE extends — a renewed subscription cycle. Idempotent by
1657
- * value: setting the same expiry twice changes nothing, so a redelivery is safe
1658
- * without needing to remember it was seen.
1195
+ * Push the expiry of every live grant from one origin — idempotent by value. `matched` is the
1196
+ * live-grant count BEFORE the at-target filter: `changed: 0, matched: 0` is a wrong origin (a
1197
+ * renewal that bought no access), `changed: 0, matched > 0` a replay.
1659
1198
  */
1660
1199
  async extendByOrigin(originModel, originRef, accessExpiresAt, ctx = {}) {
1661
1200
  this.preflightDispatch(ctx);
1662
1201
  const opts = repoOptionsFromCtx(ctx);
1663
- /**
1664
- * `matched` — live grants under this origin, BEFORE the already-at-target
1665
- * filter. Reported because `changed` alone cannot distinguish the two ways
1666
- * this call does nothing, and they mean opposite things:
1667
- *
1668
- * - a REPLAY: every grant already carries the target expiry, so the `$ne`
1669
- * filter excludes them all. `changed: 0` is correct and expected.
1670
- * - a WRONG ORIGIN: no grant was ever projected under this pair, so there
1671
- * is nothing to extend and the caller's renewal quietly bought no access.
1672
- *
1673
- * Both return `changed: 0`. Only `matched` separates them, and the second is
1674
- * a member locked out of a facility they just paid for — see the callers'
1675
- * `matched === 0` handling.
1676
- */
1677
1202
  const matched = await this.count({
1678
1203
  originModel,
1679
1204
  originRef,
1680
1205
  status: { $in: LIVE_STATUSES }
1681
1206
  }, opts);
1682
- /**
1683
- * Already-at-target rows are excluded in the FILTER (`$ne`) rather than by
1684
- * a `continue` in the loop: combined with the drain, a loop-side skip would
1685
- * re-fetch the same already-applied page forever. Drained until empty — a
1686
- * single page capped the cascade at the default page size (review #9).
1687
- */
1688
1207
  let changed = 0;
1689
1208
  for (;;) {
1690
- const rows = await this.getAll({
1691
- filters: {
1692
- originModel,
1693
- originRef,
1694
- status: { $in: LIVE_STATUSES },
1695
- accessExpiresAt: { $ne: accessExpiresAt }
1696
- },
1209
+ const rows = await this.findAll({
1210
+ originModel,
1211
+ originRef,
1212
+ status: { $in: LIVE_STATUSES },
1213
+ accessExpiresAt: { $ne: accessExpiresAt }
1214
+ }, {
1215
+ ...opts,
1697
1216
  limit: BATCH_SIZE
1698
- }, opts);
1699
- if (rows.data.length === 0) break;
1700
- for (const grant of rows.data) {
1217
+ });
1218
+ if (rows.length === 0) break;
1219
+ for (const grant of rows) {
1701
1220
  await this.extend(String(grant._id), { accessExpiresAt }, ctx);
1702
1221
  changed += 1;
1703
1222
  }
@@ -1707,43 +1226,115 @@ var EntitlementRepository = class extends Repository {
1707
1226
  matched
1708
1227
  };
1709
1228
  }
1710
- /** A subject's grants, newest-first ("my access"). */
1711
- async listForSubject(subjectRef, ctx) {
1712
- return await this.getAll({
1713
- filters: { subjectRef },
1714
- sort: { updatedAt: -1 }
1229
+ /** One subject's grants, newest first ("my access"). Filtered in the query, capped at 200. */
1230
+ async listForSubject(subject, options, ctx) {
1231
+ return this.getAll({
1232
+ mode: "offset",
1233
+ filters: {
1234
+ subjectModel: subject.subjectModel,
1235
+ subjectRef: subject.subjectRef,
1236
+ ...options.resourceType !== void 0 ? { resourceType: options.resourceType } : {},
1237
+ ...options.liveOnly === true ? { live: true } : {}
1238
+ },
1239
+ sort: { updatedAt: -1 },
1240
+ limit: Math.min(Math.max(options.limit ?? 100, 1), 200),
1241
+ ...options.page !== void 0 ? { page: options.page } : {}
1715
1242
  }, repoOptionsFromCtx(ctx));
1716
1243
  }
1244
+ /** The consumption ledger of one grant, newest first. */
1245
+ async listConsumptions(entitlementId, options, ctx) {
1246
+ return this.consumptions.findAll({ entitlementId }, {
1247
+ ...repoOptionsFromCtx(ctx),
1248
+ sort: { consumedAt: -1 },
1249
+ limit: Math.min(Math.max(options.limit ?? 100, 1), 200)
1250
+ });
1251
+ }
1252
+ /**
1253
+ * Reconcile a subject's entitlements from ONE agreement to a DESIRED SET in one atomic unit:
1254
+ * grant the missing, revoke the extra, retain the matches. Idempotent by the diff.
1255
+ * ORG-PARTITIONED: each desired item names its target org; the current set is read across
1256
+ * orgs. Authority (who may reconcile) is the caller's to check.
1257
+ */
1258
+ async reconcileEntitlementSet(input, ctx) {
1259
+ const originModel = "Agreement";
1260
+ const originRef = input.agreementRef;
1261
+ const source = input.source ?? "subscription";
1262
+ const key = (x) => `${x.resourceType}\u0000${x.resourceRef}\u0000${x.scopeKey ?? ""}`;
1263
+ return this.atomically(ctx, async (inner) => {
1264
+ const current = await this.findAll({
1265
+ subjectModel: input.subject.subjectModel,
1266
+ subjectRef: input.subject.subjectRef,
1267
+ originModel,
1268
+ originRef,
1269
+ status: { $in: LIVE_STATUSES }
1270
+ }, {
1271
+ ...repoOptionsFromCtx(inner),
1272
+ bypassTenant: true,
1273
+ limit: BATCH_SIZE
1274
+ });
1275
+ const orgs = /* @__PURE__ */ new Set();
1276
+ for (const item of input.desired) orgs.add(item.organizationId);
1277
+ for (const row of current) orgs.add(String(row.organizationId));
1278
+ let granted = 0;
1279
+ let revoked = 0;
1280
+ let retained = 0;
1281
+ for (const org of orgs) {
1282
+ const orgCtx = {
1283
+ ...inner,
1284
+ organizationId: org
1285
+ };
1286
+ const desiredInOrg = input.desired.filter((d) => d.organizationId === org);
1287
+ const currentInOrg = current.filter((c) => String(c.organizationId) === org);
1288
+ const currentByKey = new Map(currentInOrg.map((c) => [key(c), c]));
1289
+ const desiredKeys = new Set(desiredInOrg.map(key));
1290
+ for (const item of desiredInOrg) {
1291
+ if (currentByKey.has(key(item))) {
1292
+ retained += 1;
1293
+ continue;
1294
+ }
1295
+ await this.grant({
1296
+ subjectModel: input.subject.subjectModel,
1297
+ subjectRef: input.subject.subjectRef,
1298
+ resourceType: item.resourceType,
1299
+ resourceRef: item.resourceRef,
1300
+ ...item.scopeKey !== void 0 ? { scopeKey: item.scopeKey } : {},
1301
+ ...item.usageLimit !== void 0 ? { usageLimit: item.usageLimit } : {},
1302
+ ...item.accessExpiresAt !== void 0 ? { accessExpiresAt: item.accessExpiresAt } : {},
1303
+ source,
1304
+ originModel,
1305
+ originRef
1306
+ }, orgCtx);
1307
+ granted += 1;
1308
+ }
1309
+ for (const row of currentInOrg) {
1310
+ if (desiredKeys.has(key(row))) continue;
1311
+ await this.revoke(String(row._id), { reason: `reconcile:${input.mutationRef ?? originRef}` }, orgCtx);
1312
+ revoked += 1;
1313
+ }
1314
+ }
1315
+ return {
1316
+ granted,
1317
+ revoked,
1318
+ retained
1319
+ };
1320
+ });
1321
+ }
1717
1322
  async transition(id, to, event, ctx, patch) {
1718
1323
  return this.atomically(ctx, (inner) => this.transitionInner(id, to, event, inner, patch));
1719
1324
  }
1325
+ /**
1326
+ * The single funnel for every status move: legality from the machine, then ONE CAS that moves
1327
+ * status, the `live` mirror and the status-history append together.
1328
+ */
1720
1329
  async transitionInner(id, to, event, ctx, patch) {
1721
1330
  this.preflightDispatch(ctx);
1722
1331
  const grant = await this.load(id, ctx);
1723
1332
  ENTITLEMENT_MACHINE.assertTransition(String(grant._id), grant.status, to);
1724
- /**
1725
- * Append to the status log in the SAME update as the status change.
1726
- *
1727
- * `transition` is the single funnel for every state move on this aggregate, so
1728
- * this is the one place the log can be written without a path that skips it —
1729
- * and a skipped append is worse than no log, because the allowance maths would
1730
- * silently under-count the pauses it missed.
1731
- *
1732
- * Computed from the doc we already loaded rather than with `$push`, because
1733
- * `appendStatus` derives `durationInPriorMs` from the previous entry — arithmetic
1734
- * Mongo cannot do in an update expression.
1735
- */
1736
1333
  const statusHistory = appendStatus(grant.statusHistory ?? [], to, {
1334
+ at: this.now(),
1737
1335
  ...typeof patch.reason === "string" ? { note: patch.reason } : {},
1738
1336
  ...ctx.actorId !== void 0 ? { by: String(ctx.actorId) } : {}
1739
1337
  });
1740
- /**
1741
- * The live mirror moves IN the same CAS as the status. It backs the
1742
- * live-uniqueness index (the suspend-bypass fix), and a mirror updated in a
1743
- * second write would have a window where a terminal grant still holds the
1744
- * uniqueness slot — blocking the legitimate re-purchase — or where a live
1745
- * one has released it, re-opening the double-grant hole.
1746
- */
1747
1338
  const live = LIVE_STATUSES.includes(to) ? true : null;
1748
1339
  const updated = await this.claim(String(grant._id), {
1749
1340
  field: "status",
@@ -1761,15 +1352,7 @@ var EntitlementRepository = class extends Repository {
1761
1352
  await this.emitLifecycle(event, updated, ctx);
1762
1353
  return updated;
1763
1354
  }
1764
- /**
1765
- * Load a grant for a WRITE.
1766
- *
1767
- * `+statusHistory` overrides the schema's `select: false`. Every mutating path
1768
- * comes through here, and two of them require the log: `transition` appends to it,
1769
- * and `suspend` derives the pause allowance from it. Reading without it would make
1770
- * `transition` overwrite the whole array with a single entry — a silent history
1771
- * wipe that would then under-count every future allowance.
1772
- */
1355
+ /** Load a grant for a WRITE, WITH its status history (`select: false` otherwise). */
1773
1356
  async load(id, ctx) {
1774
1357
  const grant = await this.getById(id, {
1775
1358
  ...repoOptionsFromCtx(ctx),
@@ -1779,31 +1362,36 @@ var EntitlementRepository = class extends Repository {
1779
1362
  if (!grant) throw new EntitlementNotFoundError(id);
1780
1363
  return grant;
1781
1364
  }
1782
- /** Resolve the live (active|suspended) grant for a target, or null. */
1365
+ /** Resolve the live (active preferred over suspended) grant for a target, or null. */
1783
1366
  async findLive(target, ctx) {
1784
1367
  const opts = repoOptionsFromCtx(ctx);
1785
- if ("id" in target) return await this.getById(target.id, {
1786
- ...opts,
1787
- throwOnNotFound: false
1788
- }) ?? null;
1789
- const filters = {
1368
+ if ("id" in target) {
1369
+ assertIdentityPart("id", target.id);
1370
+ return await this.getById(target.id, {
1371
+ ...opts,
1372
+ throwOnNotFound: false
1373
+ }) ?? null;
1374
+ }
1375
+ assertSubject(target);
1376
+ assertCapability(target);
1377
+ const rows = await this.findAll({
1378
+ subjectModel: target.subjectModel,
1790
1379
  subjectRef: target.subjectRef,
1380
+ resourceType: target.resourceType,
1791
1381
  resourceRef: target.resourceRef,
1792
1382
  scopeKey: target.scopeKey ?? "",
1793
1383
  status: { $in: LIVE_STATUSES }
1794
- };
1795
- if (target.resourceType !== void 0) filters.resourceType = target.resourceType;
1796
- if (target.subjectModel !== void 0) filters.subjectModel = target.subjectModel;
1797
- const rows = (await this.getAll({
1798
- filters,
1384
+ }, {
1385
+ ...opts,
1799
1386
  sort: { updatedAt: -1 }
1800
- }, opts)).data;
1387
+ });
1801
1388
  return rows.find((r) => r.status === ENTITLEMENT_STATUS.ACTIVE) ?? rows[0] ?? null;
1802
1389
  }
1803
1390
  targetLabel(target) {
1804
- return "id" in target ? target.id : `${target.subjectRef}→${target.resourceRef}`;
1391
+ return "id" in target ? target.id : `${target.subjectModel}:${target.subjectRef}→${target.resourceType}:${target.resourceRef}`;
1805
1392
  }
1806
- async emitLifecycle(event, doc, ctx) {
1393
+ async emitLifecycle(event, doc, ctx, extra = {}) {
1394
+ const decision = evaluateAccess(doc, this.now().getTime());
1807
1395
  await emitDomainEvent(this.channels, event, {
1808
1396
  entitlementId: String(doc._id),
1809
1397
  ...doc.organizationId !== void 0 ? { organizationId: String(doc.organizationId) } : {},
@@ -1813,192 +1401,35 @@ var EntitlementRepository = class extends Repository {
1813
1401
  resourceType: doc.resourceType,
1814
1402
  scopeKey: doc.scopeKey,
1815
1403
  status: doc.status,
1404
+ allowed: decision.allowed,
1405
+ reason: decision.reason,
1406
+ ...doc.originModel !== void 0 ? { originModel: doc.originModel } : {},
1407
+ ...doc.originRef !== void 0 ? { originRef: doc.originRef } : {},
1816
1408
  ...doc.accessExpiresAt ? { accessExpiresAt: doc.accessExpiresAt.toISOString() } : {},
1817
1409
  ...doc.usage.limit !== null ? {
1818
1410
  usageLimit: doc.usage.limit,
1819
1411
  usageUsed: doc.usage.used
1820
- } : {}
1412
+ } : {},
1413
+ ...extra
1821
1414
  }, ctx, String(doc._id));
1822
1415
  }
1823
1416
  /**
1824
1417
  * Run a mutation + its event emission as ONE atomic unit.
1825
1418
  *
1826
- * ## Why documentation was not enough
1827
- *
1828
- * With an outbox wired and no caller session, the mutation committed and then
1829
- * `outbox.save` ran. A save failure threw — leaving state changed and the
1830
- * event permanently missing. The previous docblock claimed this was safe to
1831
- * retry because every verb is CAS-guarded. That claim was WRONG, and in the
1832
- * most dangerous direction:
1833
- *
1834
- * - `consume()` is atomic but NOT idempotent — a retry spends the units AGAIN.
1835
- * - `resume()` retried hits an invalid transition (already active) and never
1836
- * re-emits, so the credential-sync subscriber never learns the member is back.
1837
- * - `revoke()` / `refund()` retried hit a terminal status — same lost event,
1838
- * and this one means a door stays open after a refund.
1839
- *
1840
- * So the fix is a real transaction, not better wording. The mutation and the
1841
- * outbox row now commit or roll back together, which is what the
1842
- * transactional-outbox pattern actually requires.
1843
- *
1844
- * ## Two pass-through cases, both deliberate
1845
- *
1846
- * - **No outbox** — there is no second write to be atomic WITH, and taxing
1847
- * every door-tap check with a session would buy nothing.
1848
- * - **Caller supplied `ctx.session`** — the host owns a wider unit of work;
1849
- * opening our own here would either nest or silently commit a slice of
1850
- * theirs. Passing through is also what makes this safe to apply at several
1851
- * layers: an outer `resume` wraps once, and the inner `transition` sees the
1852
- * session and does not re-wrap.
1853
- *
1854
- * Requires a replica set (this deployment already mandates one for POS and
1855
- * muster). A single-node mongod without one cannot start a session, which
1856
- * surfaces at the first write rather than silently degrading.
1857
- */
1858
- /**
1859
- * Reconcile a subject's entitlements from ONE origin (typically an
1860
- * `Agreement`) to a DESIRED SET — the primitive a plan change drives. It
1861
- * computes the diff against the live entitlements currently projected from
1862
- * that origin and, in ONE atomic unit (transactional outbox), GRANTS the
1863
- * missing, REVOKES the extra, and RETAINS the matches. Idempotent: re-running
1864
- * the same desired set is a no-op (grant-by-origin dedupes; only live rows are
1865
- * revoked).
1866
- *
1867
- * ORG-PARTITIONED: each desired item carries its target `organizationId`, and
1868
- * the current set is discovered across orgs (a downgrade may drop a right in a
1869
- * different branch). Every write runs under an org-scoped ctx that reuses the
1870
- * single session, so a Gold→floor+pool bundle across branches still applies or
1871
- * rolls back as a unit. Authority (who may reconcile) is the caller's to
1872
- * check; a caller-supplied org is only ever a WRITE target, never trusted as
1873
- * identity.
1419
+ * - No outbox → pass through (nothing to be atomic with).
1420
+ * - The outbox must declare `transactionalSave`, or this throws.
1421
+ * - A caller session must be IN a transaction (`inTransaction()`), or this throws — a bare
1422
+ * session buys no atomicity.
1423
+ * - `allowNonTransactional` (dev only) degrades to best effort, warning once.
1424
+ * - Otherwise opens its own transaction via mongokit's `withTransaction` (no fallback).
1874
1425
  */
1875
- async reconcileEntitlementSet(input, ctx) {
1876
- const originModel = "Agreement";
1877
- const originRef = input.agreementRef;
1878
- const source = input.source ?? "subscription";
1879
- const key = (x) => `${x.resourceType}\u0000${x.resourceRef}\u0000${x.scopeKey ?? ""}`;
1880
- return this.atomically(ctx, async (inner) => {
1881
- const current = await this.getAll({
1882
- filters: {
1883
- subjectModel: input.subject.subjectModel,
1884
- subjectRef: input.subject.subjectRef,
1885
- originModel,
1886
- originRef,
1887
- status: { $in: LIVE_STATUSES }
1888
- },
1889
- limit: 500
1890
- }, {
1891
- ...repoOptionsFromCtx(inner),
1892
- bypassTenant: true
1893
- });
1894
- const orgs = /* @__PURE__ */ new Set();
1895
- for (const item of input.desired) orgs.add(item.organizationId);
1896
- for (const row of current.data) orgs.add(String(row.organizationId));
1897
- let granted = 0;
1898
- let revoked = 0;
1899
- let retained = 0;
1900
- for (const org of orgs) {
1901
- const orgCtx = {
1902
- ...inner,
1903
- organizationId: org
1904
- };
1905
- const desiredInOrg = input.desired.filter((d) => d.organizationId === org);
1906
- const currentInOrg = current.data.filter((c) => String(c.organizationId) === org);
1907
- const currentByKey = new Map(currentInOrg.map((c) => [key(c), c]));
1908
- const desiredKeys = new Set(desiredInOrg.map(key));
1909
- for (const item of desiredInOrg) {
1910
- if (currentByKey.has(key(item))) {
1911
- retained += 1;
1912
- continue;
1913
- }
1914
- await this.grant({
1915
- subjectModel: input.subject.subjectModel,
1916
- subjectRef: input.subject.subjectRef,
1917
- resourceType: item.resourceType,
1918
- resourceRef: item.resourceRef,
1919
- ...item.scopeKey !== void 0 ? { scopeKey: item.scopeKey } : {},
1920
- ...item.usageLimit !== void 0 ? { usageLimit: item.usageLimit } : {},
1921
- ...item.accessExpiresAt !== void 0 ? { accessExpiresAt: item.accessExpiresAt } : {},
1922
- source,
1923
- originModel,
1924
- originRef
1925
- }, orgCtx);
1926
- granted += 1;
1927
- }
1928
- for (const row of currentInOrg) {
1929
- if (desiredKeys.has(key(row))) continue;
1930
- await this.revoke(String(row._id), { reason: `reconcile:${input.mutationRef ?? originRef}` }, orgCtx);
1931
- revoked += 1;
1932
- }
1933
- }
1934
- return {
1935
- granted,
1936
- revoked,
1937
- retained
1938
- };
1939
- });
1940
- }
1941
1426
  async atomically(ctx, fn) {
1942
1427
  if (!this.outbox) return fn(ctx);
1943
- /**
1944
- * The store must DECLARE that it enlists our session.
1945
- *
1946
- * `OutboxWriteOptions.session` is best-effort by contract ("stores may ignore
1947
- * fields they don't support"), so the presence of an outbox proves nothing
1948
- * about atomicity. A Redis-backed store, one on a second Mongo connection, or
1949
- * one that simply drops the option persists the event and then watches our
1950
- * transaction roll back — a GHOST event describing access that was never
1951
- * granted. Downstream ACTS on that: a credential sync would provision a card.
1952
- *
1953
- * Checked once per call and thrown as a capability error, matching how this
1954
- * package already refuses a backend without atomic `getOrCreate`. A host on a
1955
- * non-transactional store must pass `ctx.session` from its own unit of work,
1956
- * which puts the decision where the knowledge is.
1957
- */
1958
1428
  if (this.outbox.transactionalSave !== true) throw new AccessCapabilityError(["outbox.transactionalSave"]);
1959
- /**
1960
- * A caller-supplied session is honoured — but VERIFIED first.
1961
- *
1962
- * The earlier shape short-circuited on `ctx.session` before either check,
1963
- * which meant a host could bypass both simply by passing a session: a
1964
- * non-transactional outbox went unchallenged, and — the subtler one — a BARE
1965
- * session (from `startSession()` with no `withTransaction`) was accepted as
1966
- * proof of atomicity when it provides none. Each write commits
1967
- * independently, so a failing `outbox.save` left the mutation standing and
1968
- * the event lost: precisely the bug this whole mechanism exists to prevent,
1969
- * reachable by a caller trying to be careful.
1970
- *
1971
- * `inTransaction()` is the driver's own answer, so this cannot drift from
1972
- * what Mongo actually thinks.
1973
- */
1974
1429
  if (ctx.session) {
1975
- const session = ctx.session;
1976
- if (typeof session.inTransaction !== "function" || !session.inTransaction()) throw new SessionNotInTransactionError();
1430
+ if (!ctx.session.inTransaction()) throw new SessionNotInTransactionError();
1977
1431
  return fn(ctx);
1978
1432
  }
1979
- /**
1980
- * Otherwise open our own, via mongokit's helper rather than a hand-rolled
1981
- * `startSession()` + `withTransaction()` + `finally endSession()`.
1982
- *
1983
- * The kit owns retry semantics (`TransientTransactionError`,
1984
- * `UnknownTransactionCommitResult`) and session lifecycle in ONE place;
1985
- * re-implementing them here would be a second copy to keep in step, and the
1986
- * retry details are exactly the part that is easy to get subtly wrong.
1987
- *
1988
- * `allowFallback` is deliberately NOT set: the kit can degrade to a
1989
- * non-transactional run on a standalone mongod, which is a sensible default
1990
- * for ordinary CRUD and the wrong one here — it would silently restore the
1991
- * ghost-event path this method exists to close. A deployment without a
1992
- * replica set must fail loudly instead.
1993
- */
1994
- /**
1995
- * The explicit escape for a deployment with no replica set.
1996
- *
1997
- * Checked HERE — after the outbox contract assertion above, and only when the host
1998
- * asked for it — so the ordering stays "specific beats general": a store that does not
1999
- * declare `transactionalSave` still fails, because that is a wiring mistake rather than
2000
- * a deployment fact, and no flag should paper over it.
2001
- */
2002
1433
  if (this.allowNonTransactional) {
2003
1434
  if (!this.warnedNonTransactional) {
2004
1435
  this.warnedNonTransactional = true;
@@ -2011,19 +1442,7 @@ var EntitlementRepository = class extends Repository {
2011
1442
  session
2012
1443
  }));
2013
1444
  }
2014
- /**
2015
- * Assert the event path is usable BEFORE any mutation.
2016
- *
2017
- * `emitDomainEvent` throws `UnmanagedSessionError` when a host passes a
2018
- * session with no outbox — but every verb emits AFTER writing, so the guard
2019
- * used to fire with the entitlement already persisted (review #6): the
2020
- * caller saw a failure while the grant quietly existed, and outside a
2021
- * transaction nothing rolled it back. The same condition checked here turns
2022
- * that into a clean refusal with nothing written.
2023
- *
2024
- * Mirrors dispatch exactly: no channels at all → nothing will emit, nothing
2025
- * to guard; session + outbox → the legal relay-only mode.
2026
- */
1445
+ /** A session with no outbox has no correct event path — refuse BEFORE any write. */
2027
1446
  preflightDispatch(ctx) {
2028
1447
  if (ctx.session && this.eventTransport && !this.outbox) throw new UnmanagedSessionError();
2029
1448
  }
@@ -2035,6 +1454,26 @@ var EntitlementRepository = class extends Repository {
2035
1454
  };
2036
1455
  }
2037
1456
  };
1457
+ /**
1458
+ * Identity parts must be non-empty strings AT RUNTIME: a wire or JS caller omitting one would
1459
+ * otherwise send `{ subjectModel: undefined }` to the query, which narrows nothing.
1460
+ */
1461
+ function assertIdentityPart(name, value) {
1462
+ if (typeof value !== "string" || value.length === 0) throw new InvalidCheckRequestError(`\`${name}\` must be a non-empty string`);
1463
+ }
1464
+ function assertSubject(subject) {
1465
+ assertIdentityPart("subjectModel", subject.subjectModel);
1466
+ assertIdentityPart("subjectRef", subject.subjectRef);
1467
+ }
1468
+ function assertCapability(capability) {
1469
+ assertIdentityPart("resourceType", capability.resourceType);
1470
+ assertIdentityPart("resourceRef", capability.resourceRef);
1471
+ if (capability.scopeKey !== void 0 && typeof capability.scopeKey !== "string") throw new InvalidCheckRequestError("`scopeKey` must be a string when present");
1472
+ }
1473
+ /** The NUL-delimited identity of a capability (rows default `scopeKey` to `''`). */
1474
+ function capabilityKey(c) {
1475
+ return `${c.resourceType}\u0000${c.resourceRef}\u0000${c.scopeKey ?? ""}`;
1476
+ }
2038
1477
  //#endregion
2039
1478
  //#region src/engine/define-access.ts
2040
1479
  /** Repository capabilities asserted at boot. */
@@ -2050,6 +1489,7 @@ function defineAccess(shape = {}) {
2050
1489
  tenant,
2051
1490
  ...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
2052
1491
  ...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
1492
+ ...shape.indexes !== void 0 ? { indexes: shape.indexes } : {},
2053
1493
  forceRecreate
2054
1494
  });
2055
1495
  return {
@@ -2074,7 +1514,7 @@ function defineAccess(shape = {}) {
2074
1514
  const logger = runtime.logger ?? console;
2075
1515
  const ownsTransport = runtime.eventTransport === void 0;
2076
1516
  const events = runtime.eventTransport ?? new InProcessAccessBus({ logger });
2077
- const tenantPlugins = (() => {
1517
+ const tenantPlugins = () => {
2078
1518
  if (!tenant.enabled || tenant.strategy !== "field") return [];
2079
1519
  const extras = typeof shape.tenant === "object" ? shape.tenant : void 0;
2080
1520
  return [multiTenantPlugin({
@@ -2088,7 +1528,7 @@ function defineAccess(shape = {}) {
2088
1528
  ...extras?.allowDataInjection !== void 0 ? { allowDataInjection: extras.allowDataInjection } : {},
2089
1529
  ...extras?.onMismatch !== void 0 ? { onMismatch: extras.onMismatch } : {}
2090
1530
  })];
2091
- })();
1531
+ };
2092
1532
  /**
2093
1533
  * NO soft delete (removed 2026-08-14). The entitlement LIFECYCLE is the retention
2094
1534
  * record: revoke is a status transition (`active|suspended -> revoked`, terminal
@@ -2100,14 +1540,17 @@ function defineAccess(shape = {}) {
2100
1540
  * not hiding rows.
2101
1541
  */
2102
1542
  const repoPlugins = runtime.repositoryPlugins ?? {};
1543
+ const consumptions = new Repository(models.EntitlementConsumption, tenantPlugins());
2103
1544
  const entitlement = new EntitlementRepository({
2104
1545
  model: models.Entitlement,
2105
- plugins: [...tenantPlugins, ...repoPlugins.entitlement ?? []],
1546
+ consumptions,
1547
+ plugins: [...tenantPlugins(), ...repoPlugins.entitlement ?? []],
2106
1548
  eventTransport: events,
2107
1549
  outbox: runtime.outbox,
2108
1550
  logger,
2109
1551
  allowNonTransactional: runtime.allowNonTransactional === true,
2110
- ...runtime.timezone !== void 0 ? { timezone: runtime.timezone } : {}
1552
+ ...runtime.timezone !== void 0 ? { timezone: runtime.timezone } : {},
1553
+ ...runtime.clock !== void 0 ? { clock: runtime.clock } : {}
2111
1554
  });
2112
1555
  const caps = entitlement.capabilities;
2113
1556
  if (!caps) throw new AccessCapabilityError(["capabilities descriptor (repo-core 0.6 / mongokit 3.16+)"]);
@@ -2131,11 +1574,15 @@ function defineAccess(shape = {}) {
2131
1574
  * and an unobserved answer is never a positive one. The message distinguishes the two
2132
1575
  * because the operator's fix differs — bind after connecting, versus run a replica set.
2133
1576
  */
2134
- if (runtime.outbox && caps.transactions !== true && runtime.allowNonTransactional !== true) throw new AccessCapabilityError([transactionResolutionOf(caps) === "unknown" ? "transactions (it could NOT be determined whether the backend supports multi-document transactions — bind AFTER `await mongoose.connect(...)`, or run MongoDB as a replica set. An unconfirmed answer is treated as unsupported because an entitlement event that survives a rolled-back grant opens a door on a right nobody granted)" : "transactions (the backend does not support multi-document transactions, so an entitlement write and its outbox row cannot commit together. Run MongoDB as a replica set (or mongos), remove the outbox, or accept partial writes explicitly with `allowNonTransactional: true` in the runtime)"]);
1577
+ if (runtime.outbox && caps.transactions !== true && runtime.allowNonTransactional !== true) {
1578
+ const indeterminate = transactionResolutionOf(caps) === "unknown";
1579
+ throw new AccessCapabilityError([indeterminate ? "transactions (it could NOT be determined whether the backend supports multi-document transactions — bind AFTER `await mongoose.connect(...)`, or run MongoDB as a replica set. An unconfirmed answer is treated as unsupported because an entitlement event that survives a rolled-back grant opens a door on a right nobody granted)" : "transactions (the backend does not support multi-document transactions, so an entitlement write and its outbox row cannot commit together. Run MongoDB as a replica set (or mongos), remove the outbox, or accept partial writes explicitly with `allowNonTransactional: true` in the runtime)"]);
1580
+ }
2135
1581
  const resolved = Object.freeze({
2136
1582
  tenant,
2137
1583
  autoIndex: shape.autoIndex,
2138
1584
  collectionPrefix: shape.collectionPrefix,
1585
+ indexes: shape.indexes,
2139
1586
  forceRecreate
2140
1587
  });
2141
1588
  return Object.freeze({
@@ -2146,6 +1593,7 @@ function defineAccess(shape = {}) {
2146
1593
  outbox: runtime.outbox,
2147
1594
  async syncIndexes() {
2148
1595
  await models.Entitlement.syncIndexes();
1596
+ await models.EntitlementConsumption.syncIndexes();
2149
1597
  },
2150
1598
  async close() {
2151
1599
  if (ownsTransport) await events.close?.();
@@ -2155,4 +1603,4 @@ function defineAccess(shape = {}) {
2155
1603
  };
2156
1604
  }
2157
1605
  //#endregion
2158
- export { ACCESS_EVENTS, AccessCapabilityError, AccessError, DEFAULT_CHURN_GRACE_DAYS, ENTITLEMENT_MACHINE, ENTITLEMENT_STATUS, ENTITLEMENT_STATUS_VALUES, ENTITLEMENT_TRANSITIONS, EntitlementNotFoundError, EntitlementNotUsableError, EntitlementRepository, InProcessAccessBus, InvalidConsumeAmountError, InvalidEntitlementTransitionError, InvalidExpiryWindowError, LIVE_STATUSES, QuotaExhaustedError, SessionNotInTransactionError, SuspensionRefusedError, UnmanagedSessionError, VersionMismatchError, accessEventDefinitions, canEntitlementTransition, defineAccess, defineAccessModels, evaluateAccess, hasAccess, isEntitlementStatus, isTerminalEntitlementStatus };
1606
+ export { ACCESS_EVENTS, ACCESS_REASONS, AccessCapabilityError, AccessError, ConsumptionInFlightError, ConsumptionKeyConflictError, ConsumptionKeyRequiredError, DEFAULT_CHURN_GRACE_DAYS, ENTITLEMENT_MACHINE, ENTITLEMENT_STATUS, ENTITLEMENT_STATUS_VALUES, ENTITLEMENT_TRANSITIONS, EntitlementNotFoundError, EntitlementNotUsableError, EntitlementRepository, GrantProvenanceRequiredError, InProcessAccessBus, InvalidCheckRequestError, InvalidConsumeAmountError, InvalidEntitlementTransitionError, InvalidExpiryWindowError, InvalidExtensionError, LIVE_STATUSES, MAX_CAPABILITIES_PER_CHECK, QuotaExhaustedError, SessionNotInTransactionError, SuspensionRefusedError, UnmanagedSessionError, VersionMismatchError, accessEventDefinitions, canEntitlementTransition, defineAccess, defineAccessModels, evaluateAccess, hasAccess, isEntitlementStatus, isTerminalEntitlementStatus };