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