@classytic/access 0.1.1 → 0.3.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,11 +1,197 @@
1
1
  import { evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
2
2
  import { l as accessEventDefinitions, u as ACCESS_EVENTS } from "./event-catalog-BVD_rFlc.mjs";
3
- import { Repository, createOptionsExtractor, multiTenantPlugin, softDeletePlugin } from "@classytic/mongokit";
4
- import { resolveTenantConfig } from "@classytic/repo-core/tenant";
3
+ import { Repository, createOptionsExtractor, defineModels, multiTenantPlugin, transactionResolutionOf, withTransaction } from "@classytic/mongokit";
4
+ import { assertNoLegacyTenantKeys, resolveTenantConfig } from "@classytic/repo-core/tenant";
5
+ import { InProcessEventBus } from "@classytic/primitives/event-infra";
5
6
  import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
6
- import mongoose, { Schema } from "mongoose";
7
- import { createEvent, matchEventPattern } from "@classytic/primitives/events";
8
- import { InvalidOutboxEventError, OutboxOwnershipError } from "@classytic/primitives/outbox";
7
+ import { Schema } from "mongoose";
8
+ import { defineStateMachine } from "@classytic/primitives/state-machine";
9
+ import { assertIndexDeclaration, injectTenantField } from "@classytic/mongokit/tenant";
10
+ import { appendStatus } from "@classytic/primitives/status-history";
11
+ import { inclusiveEnd, resolveDateSpan } from "@classytic/primitives/period";
12
+ import { evaluateSuspension, spansFromStatusHistory } from "@classytic/primitives/suspension";
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
+ //#region src/events/in-process-bus.ts
174
+ /**
175
+ * In-process fan-out transport — the default when the host injects none.
176
+ *
177
+ * A thin subclass of `@classytic/primitives/event-infra`'s shared
178
+ * `InProcessEventBus` (the single implementation every kernel now defaults
179
+ * to). Prior semantics preserved exactly: glob matching via
180
+ * `matchEventPattern` (exact / `*` / `prefix.*` / `prefix:*`), Set-dedup so a
181
+ * handler matched by multiple patterns fires once, per-handler error
182
+ * isolation (errors logged; default `console`), idempotent `close()`.
183
+ * Structurally identical to arc's `MemoryEventTransport`.
184
+ */
185
+ var InProcessAccessBus = class extends InProcessEventBus {
186
+ constructor(options = {}) {
187
+ super({
188
+ name: "in-process-access",
189
+ logLabel: "access",
190
+ ...options
191
+ });
192
+ }
193
+ };
194
+ //#endregion
9
195
  //#region src/domain/enums/entitlement-status.enum.ts
10
196
  /**
11
197
  * Entitlement lifecycle status.
@@ -65,9 +251,74 @@ const ENTITLEMENT_TRANSITIONS = {
65
251
  revoked: [],
66
252
  refunded: []
67
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
+ */
68
296
  function canEntitlementTransition(from, to) {
69
- return ENTITLEMENT_TRANSITIONS[from].includes(to);
297
+ return ENTITLEMENT_MACHINE.canTransition(from, to);
298
+ }
299
+ /**
300
+ * Is this grant finished for good? `revoked` / `refunded` only.
301
+ *
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.
305
+ */
306
+ function isTerminalEntitlementStatus(status) {
307
+ return ENTITLEMENT_MACHINE.isTerminal(status);
70
308
  }
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;
71
322
  //#endregion
72
323
  //#region src/models/entitlement.model.ts
73
324
  /**
@@ -124,6 +375,14 @@ function buildEntitlementSchema() {
124
375
  required: true,
125
376
  index: true
126
377
  },
378
+ live: {
379
+ type: Boolean,
380
+ default: true
381
+ },
382
+ appliedOrigins: {
383
+ type: [String],
384
+ default: void 0
385
+ },
127
386
  source: {
128
387
  type: String,
129
388
  enum: [
@@ -152,7 +411,11 @@ function buildEntitlementSchema() {
152
411
  usage: {
153
412
  limit: {
154
413
  type: Number,
155
- default: null
414
+ default: null,
415
+ validate: {
416
+ validator: (v) => v === null || Number.isInteger(v) && v >= 0,
417
+ message: "usage.limit must be null (unlimited) or a non-negative integer"
418
+ }
156
419
  },
157
420
  used: {
158
421
  type: Number,
@@ -184,15 +447,33 @@ function buildEntitlementSchema() {
184
447
  },
185
448
  reason: { type: String },
186
449
  suspendedAt: { type: Date },
450
+ /**
451
+ * `select: false` — excluded from every read unless asked for.
452
+ *
453
+ * `check()` is the HOT path: every door tap, every zone admission, every API
454
+ * quota call. `evaluateAccess` never looks at the history, so shipping it on
455
+ * each check is pure transfer waste that grows with the member's lifetime.
456
+ * Only the two paths that genuinely need it opt in (`load()` — appending in
457
+ * `transition`, and the allowance derivation in `suspend`).
458
+ *
459
+ * Same reasoning as `Device.authTokenHash`: a field that most reads must not
460
+ * see is excluded at the schema, not remembered at each call site.
461
+ */
462
+ statusHistory: {
463
+ type: [Schema.Types.Mixed],
464
+ default: void 0,
465
+ select: false
466
+ },
467
+ autoResumeAt: {
468
+ type: Date,
469
+ default: null
470
+ },
471
+ creditWindowOnResume: { type: Boolean },
187
472
  revokedAt: { type: Date },
188
473
  expiredAt: { type: Date },
189
474
  consumedAt: { type: Date },
190
475
  refundedAt: { type: Date },
191
476
  metadata: { type: Schema.Types.Mixed },
192
- deletedAt: {
193
- type: Date,
194
- default: null
195
- },
196
477
  version: {
197
478
  type: Number,
198
479
  default: 0
@@ -202,6 +483,63 @@ function buildEntitlementSchema() {
202
483
  minimize: false,
203
484
  optimisticConcurrency: true
204
485
  });
486
+ /**
487
+ * A grant's window must be an interval, and provenance must be whole.
488
+ *
489
+ * `notBefore > accessExpiresAt` is a grant that can never be used but LOOKS
490
+ * scheduled; a lone `originRef` with no `originModel` is a polymorphic ref
491
+ * that no cascade can ever match. Both are caller bugs better rejected at
492
+ * write time than discovered as a member standing at a door.
493
+ */
494
+ schema.pre("validate", function() {
495
+ /**
496
+ * Derive `live` from `status` on every document save — not just on query
497
+ * updates.
498
+ *
499
+ * The query middleware below covers `updateOne`/`updateMany`/
500
+ * `findOneAndUpdate`, but `Model.create({ status: 'revoked' })` bypasses all
501
+ * three and takes the schema DEFAULT (`true`) — creating a terminal grant
502
+ * that occupies the live-uniqueness slot, so the member can never
503
+ * re-purchase. The mirror is derived here rather than trusted from input,
504
+ * which also means a caller CANNOT set it independently: there is no legal
505
+ * combination for them to get wrong.
506
+ */
507
+ this.live = LIVE_STATUSES.includes(this.status) ? true : null;
508
+ if (this.notBefore instanceof Date && this.accessExpiresAt instanceof Date && this.notBefore.getTime() > this.accessExpiresAt.getTime()) throw new Error("notBefore must not be after accessExpiresAt");
509
+ if (this.originRef == null !== (this.originModel == null)) throw new Error("originRef and originModel must be set together (polymorphic ref)");
510
+ });
511
+ /**
512
+ * Keep `live` DERIVED from `status` on every query-level update.
513
+ *
514
+ * `live` backs the unique index, so a write that moves `status` without
515
+ * moving `live` silently breaks the constraint in one of two directions:
516
+ * `{ status: 'revoked', live: true }` keeps a terminal grant holding the
517
+ * uniqueness slot, so the member can never re-purchase; `{ status:
518
+ * 'suspended', live: null }` releases it, re-opening the double-grant hole
519
+ * this field exists to close.
520
+ *
521
+ * The repository's own funnel already sets both together — but the class
522
+ * INHERITS generic `updateOne` / `updateMany` / `findOneAndUpdate` from
523
+ * mongokit, and a host (or a future method) can reach `status` through those.
524
+ * Deriving it here makes the invariant hold regardless of which door the
525
+ * write came through, which is the only version of it that survives.
526
+ *
527
+ * `$setOnInsert` is deliberately NOT touched: on an upsert the create payload
528
+ * carries both fields, and mirroring into `$set` would conflict with the
529
+ * insert path.
530
+ */
531
+ const deriveLive = function() {
532
+ 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);
205
543
  schema.index({
206
544
  subjectModel: 1,
207
545
  subjectRef: 1,
@@ -210,12 +548,13 @@ function buildEntitlementSchema() {
210
548
  scopeKey: 1
211
549
  }, {
212
550
  unique: true,
213
- partialFilterExpression: {
214
- status: ENTITLEMENT_STATUS.ACTIVE,
215
- deletedAt: null
216
- },
217
- name: "entitlement_unique_active_grant"
551
+ partialFilterExpression: { live: true },
552
+ name: "entitlement_unique_live_grant"
218
553
  });
554
+ schema.index({
555
+ appliedOrigins: 1,
556
+ status: 1
557
+ }, { name: "entitlement_by_applied_origin" });
219
558
  schema.index({
220
559
  subjectRef: 1,
221
560
  status: 1,
@@ -230,6 +569,10 @@ function buildEntitlementSchema() {
230
569
  status: 1,
231
570
  accessExpiresAt: 1
232
571
  }, { name: "entitlement_due_for_expiry" });
572
+ schema.index({
573
+ status: 1,
574
+ autoResumeAt: 1
575
+ }, { name: "entitlement_due_for_resume" });
233
576
  schema.index({
234
577
  originModel: 1,
235
578
  originRef: 1
@@ -237,120 +580,51 @@ function buildEntitlementSchema() {
237
580
  return schema;
238
581
  }
239
582
  //#endregion
240
- //#region src/models/inject-tenant.ts
583
+ //#region src/models/create-models.ts
241
584
  /**
242
- * Mongoose adapter around `@classytic/repo-core/tenant.resolveTenantConfig`.
243
- * Thin (rule P11) — repo-core owns resolution; this handles schema mutations
244
- * only: adds the tenant field with the engine-configured type, and prepends
245
- * the tenant key to every existing compound index (rule 36).
585
+ * Access model specification — the ONE authoritative place the Entitlement model is
586
+ * described.
587
+ *
588
+ * `defineAccessModels(config)` returns a connection-free mongokit `ModelBlueprint`;
589
+ * `defineAccess` binds it during engine construction. Tenant-field injection, collection
590
+ * prefix, auto-index and collision policy live here once. A name collision surfaces as
591
+ * mongokit's typed `ModelCollisionError` (no kernel-specific wrapper).
592
+ *
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).
246
596
  */
247
- function injectTenantField(schema, tenant) {
248
- const isFieldStrategy = tenant.strategy === "field";
249
- const isObjectId = tenant.fieldType === "objectId";
250
- schema.add({ [tenant.tenantField]: {
251
- type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
252
- ...tenant.enabled && tenant.required ? { required: true } : {},
253
- index: true,
254
- ...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
255
- } });
256
- if (!tenant.enabled || !isFieldStrategy) return;
257
- const existingIndexes = schema._indexes;
258
- if (existingIndexes && existingIndexes.length > 0) for (const indexEntry of existingIndexes) {
259
- const fields = indexEntry[0];
260
- if (fields[tenant.tenantField] !== void 0) continue;
261
- const newFields = { [tenant.tenantField]: 1 };
262
- for (const [key, val] of Object.entries(fields)) newFields[key] = val;
263
- indexEntry[0] = newFields;
264
- }
265
- }
266
- //#endregion
267
- //#region src/models/create-models.ts
268
- const ACCESS_MODEL_NAMES = ["Entitlement"];
269
597
  const DEFAULT_COLLECTIONS = { Entitlement: "entitlements" };
270
- var AccessModelCollisionError = class extends Error {
271
- constructor(name) {
272
- super(`[access] Mongoose model "${name}" already exists on this connection. For hot-reload / test fixtures, pass \`forceRecreate: true\`. For two access engines, use two Mongoose connections (\`mongoose.createConnection(...)\`).`);
273
- this.name = "AccessModelCollisionError";
274
- }
275
- };
276
- function isResolvedTenant(value) {
277
- return typeof value === "object" && value !== null && "strategy" in value && "tenantField" in value;
278
- }
279
- function createAccessModels(connection, options = {}) {
280
- if (options.forceRecreate) {
281
- for (const name of ACCESS_MODEL_NAMES) if (connection.models[name]) connection.deleteModel(name);
282
- } else for (const name of ACCESS_MODEL_NAMES) if (connection.models[name]) throw new AccessModelCollisionError(name);
283
- const tenant = options.tenant !== void 0 && isResolvedTenant(options.tenant) ? options.tenant : resolveTenantConfig(options.tenant);
284
- const entitlementSchema = buildEntitlementSchema();
285
- injectTenantField(entitlementSchema, tenant);
286
- const prefix = options.collectionPrefix ?? "";
287
- const bundle = { Entitlement: connection.model("Entitlement", entitlementSchema, prefix + DEFAULT_COLLECTIONS.Entitlement) };
288
- applyAutoIndex(bundle, options.autoIndex);
289
- return bundle;
598
+ function resolveAutoIndex(name, autoIndex) {
599
+ if (autoIndex === void 0) return void 0;
600
+ return typeof autoIndex === "boolean" ? autoIndex : autoIndex[name];
290
601
  }
291
- function applyAutoIndex(models, autoIndex) {
292
- if (autoIndex === void 0) return;
293
- for (const [name, model] of Object.entries(models)) {
294
- const value = typeof autoIndex === "boolean" ? autoIndex : autoIndex[name] ?? void 0;
295
- if (value !== void 0) model.schema.set("autoIndex", value);
296
- }
297
- }
298
- //#endregion
299
- //#region src/domain/errors/access.errors.ts
300
- var AccessError = class extends Error {
301
- code;
302
- status;
303
- constructor(message, code, status) {
304
- super(message);
305
- this.name = this.constructor.name;
306
- this.code = code;
307
- this.status = status;
308
- }
309
- };
310
- var EntitlementNotFoundError = class extends AccessError {
311
- constructor(id) {
312
- super(`Entitlement ${id} not found`, "access.entitlement.not_found", 404);
313
- }
314
- };
315
- /** A consume() against a metered grant whose quota is already spent. */
316
- var QuotaExhaustedError = class extends AccessError {
317
- constructor(id, limit) {
318
- super(`Entitlement ${id} quota exhausted (limit ${limit})`, "access.entitlement.quota_exhausted", 409);
319
- }
320
- };
321
- var InvalidEntitlementTransitionError = class extends AccessError {
322
- constructor(from, to) {
323
- super(`Invalid entitlement transition: ${from} → ${to}`, "access.invalid_transition", 409);
324
- }
325
- };
326
602
  /**
327
- * Thrown when a host passes `ctx.session` (it owns the outer transaction)
328
- * but NO outbox is wired: there is no correct delivery path for the event.
329
- * Publishing immediately would leak ghost events if the host rolls back;
330
- * silently dropping loses the event entirely. Wire an `OutboxStore` —
331
- * session + outbox is legal durable-relay-only mode (§P8.1).
603
+ * Describe the Access model set as a connection-free blueprint. Pure — builds no schema and
604
+ * registers nothing until `.bind(connection)`.
332
605
  */
333
- var UnmanagedSessionError = class extends AccessError {
334
- constructor() {
335
- super("access.session.unmanaged", "ctx.session provided but no OutboxStore is wired — events would be lost. Wire an outbox (durable relay delivers post-commit) or drop the session.", 409);
336
- }
337
- };
338
- var VersionMismatchError = class extends AccessError {
339
- constructor(id, expectedVersion) {
340
- super(`Concurrent modification on ${id} (expected version ${expectedVersion}) — retry.`, "access.concurrency.version_mismatch", 409);
341
- }
342
- };
343
- /**
344
- * The backend does not declare the capabilities the engine needs. Granting is
345
- * idempotent via atomic `getOrCreate` (upsert); without it two concurrent
346
- * grants on one (subject, resource) would double-provision. Metered `consume`
347
- * needs an atomic guarded increment. Fail loud at boot, not at runtime.
348
- */
349
- var AccessCapabilityError = class extends AccessError {
350
- constructor(missing) {
351
- super(`[access] backend missing required capabilities: ${missing.join(", ")}. 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);
352
- }
353
- };
606
+ function defineAccessModels(config) {
607
+ const prefix = config.collectionPrefix ?? "";
608
+ for (const declaration of config.indexes ?? []) assertIndexDeclaration(declaration, config.tenant);
609
+ return defineModels({
610
+ models: [{
611
+ name: "Entitlement",
612
+ collection: prefix + DEFAULT_COLLECTIONS.Entitlement,
613
+ schema: () => {
614
+ const schema = buildEntitlementSchema();
615
+ injectTenantField(schema, config.tenant, { ...config.indexes ? { indexes: config.indexes } : {} });
616
+ const ai = resolveAutoIndex("Entitlement", config.autoIndex);
617
+ if (ai !== void 0) schema.set("autoIndex", ai);
618
+ return schema;
619
+ },
620
+ existing: config.forceRecreate ? {
621
+ mode: "replace",
622
+ environment: "test"
623
+ } : { mode: "throw" }
624
+ }],
625
+ assemble: (models) => Object.freeze({ Entitlement: models.get("Entitlement") })
626
+ });
627
+ }
354
628
  //#endregion
355
629
  //#region src/events/helpers.ts
356
630
  /**
@@ -425,15 +699,33 @@ const repoOptionsFromCtx = createOptionsExtractor([
425
699
  * decision. It mutates nothing, so it stays cheap and the same rule can run on
426
700
  * an edge node or in the UI via the `@classytic/access/decision` subpath.
427
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.
707
+ */
708
+ const BATCH_SIZE = 500;
709
+ /** The applied-origins ledger key, or null when the input carries no origin. */
710
+ function grantOriginKey(input) {
711
+ return input.originModel !== void 0 && input.originRef !== void 0 ? `${input.originModel}:${input.originRef}` : null;
712
+ }
428
713
  var EntitlementRepository = class extends Repository {
429
714
  eventTransport;
430
715
  outbox;
431
716
  pkgLogger;
717
+ allowNonTransactional;
718
+ /** IANA business zone — see `EntitlementRepositoryConfig.timezone`. */
719
+ timezone;
720
+ /** Warn ONCE per repository, not once per grant — a per-tap log is noise nobody reads. */
721
+ warnedNonTransactional = false;
432
722
  constructor(config) {
433
723
  super(config.model, config.plugins ?? []);
434
724
  this.eventTransport = config.eventTransport;
435
725
  this.outbox = config.outbox;
436
726
  this.pkgLogger = config.logger ?? console;
727
+ this.allowNonTransactional = config.allowNonTransactional === true;
728
+ this.timezone = config.timezone ?? "UTC";
437
729
  }
438
730
  /**
439
731
  * Grant access. Idempotent per (subject, resource, scope) live grant via
@@ -442,15 +734,40 @@ var EntitlementRepository = class extends Repository {
442
734
  * `access:granted` on first grant, `access:extended` on renewal.
443
735
  */
444
736
  async grant(input, ctx) {
737
+ return this.atomically(ctx, (inner) => this.grantInner(input, inner));
738
+ }
739
+ async grantInner(input, ctx) {
740
+ 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
+ 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
+ if (input.originRef === void 0 !== (input.originModel === void 0)) throw new Error("originRef and originModel must be set together (polymorphic ref)");
749
+ 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");
445
750
  const scopeKey = input.scopeKey ?? "";
446
751
  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
+ */
447
764
  const { doc, created } = await this.getOrCreate({
448
765
  subjectModel: input.subjectModel,
449
766
  subjectRef: input.subjectRef,
450
767
  resourceType: input.resourceType,
451
768
  resourceRef: input.resourceRef,
452
769
  scopeKey,
453
- status: ENTITLEMENT_STATUS.ACTIVE
770
+ live: true
454
771
  }, {
455
772
  ...ctx.organizationId !== void 0 ? { organizationId: ctx.organizationId } : {},
456
773
  subjectRef: input.subjectRef,
@@ -460,6 +777,7 @@ var EntitlementRepository = class extends Repository {
460
777
  resourceType: input.resourceType,
461
778
  scopeKey,
462
779
  status: ENTITLEMENT_STATUS.ACTIVE,
780
+ live: true,
463
781
  source: input.source,
464
782
  grantedAt: /* @__PURE__ */ new Date(),
465
783
  notBefore: input.notBefore ?? null,
@@ -470,6 +788,7 @@ var EntitlementRepository = class extends Repository {
470
788
  },
471
789
  ...input.originRef !== void 0 ? { originRef: input.originRef } : {},
472
790
  ...input.originModel !== void 0 ? { originModel: input.originModel } : {},
791
+ ...originKey !== null ? { appliedOrigins: [originKey] } : {},
473
792
  ...input.amount !== void 0 ? { amount: input.amount } : {},
474
793
  ...input.currency !== void 0 ? { currency: input.currency } : {},
475
794
  ...input.metadata !== void 0 ? { metadata: input.metadata } : {}
@@ -481,11 +800,41 @@ var EntitlementRepository = class extends Repository {
481
800
  if (input.renew === false) return doc;
482
801
  const set = { accessExpiresAt: input.accessExpiresAt ?? null };
483
802
  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
+ const inc = {};
484
809
  if (input.usageLimit !== void 0) {
485
- set["usage.limit"] = input.usageLimit;
486
- set["usage.used"] = 0;
810
+ 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
+ if (input.usageLimit !== null && doc.usage?.limit !== null) inc["usage.limit"] = input.usageLimit;
816
+ } else {
817
+ set["usage.limit"] = input.usageLimit;
818
+ set["usage.used"] = 0;
819
+ }
487
820
  }
488
- const renewed = await this.claimVersion(String(doc._id), { from: doc.version }, { $set: set }, opts);
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
+ if (input.originRef !== void 0) set.originRef = input.originRef;
832
+ if (input.originModel !== void 0) set.originModel = input.originModel;
833
+ const renewed = await this.claimVersion(String(doc._id), { from: doc.version }, {
834
+ $set: set,
835
+ ...Object.keys(inc).length > 0 ? { $inc: inc } : {},
836
+ ...originKey !== null ? { $addToSet: { appliedOrigins: originKey } } : {}
837
+ }, opts);
489
838
  if (!renewed) throw new VersionMismatchError(String(doc._id), doc.version);
490
839
  await this.emitLifecycle(ACCESS_EVENTS.EXTENDED, renewed, ctx);
491
840
  return renewed;
@@ -503,6 +852,31 @@ var EntitlementRepository = class extends Repository {
503
852
  };
504
853
  }
505
854
  /**
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.
869
+ */
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);
878
+ }
879
+ /**
506
880
  * Spend `amount` metered units (a download, an API call, a seat). Atomic and
507
881
  * race-safe: a metered grant only succeeds while `used + amount <= limit`
508
882
  * (guarded `$expr`), so N concurrent consumes never overshoot. When the cap
@@ -511,17 +885,44 @@ var EntitlementRepository = class extends Repository {
511
885
  * Throws `QuotaExhaustedError` when no unit is left.
512
886
  */
513
887
  async consume(target, amount = 1, ctx = {}) {
888
+ return this.atomically(ctx, (inner) => this.consumeInner(target, amount, inner));
889
+ }
890
+ async consumeInner(target, amount, ctx) {
891
+ 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
+ */
900
+ if (!Number.isInteger(amount) || amount <= 0) throw new InvalidConsumeAmountError(amount);
514
901
  const grant = await this.findLive(target, ctx);
515
902
  if (!grant) throw new EntitlementNotFoundError(this.targetLabel(target));
516
- if (grant.status !== ENTITLEMENT_STATUS.ACTIVE) {
517
- if (grant.usage.limit !== null && grant.usage.used >= grant.usage.limit) throw new QuotaExhaustedError(String(grant._id), grant.usage.limit);
518
- throw new EntitlementNotFoundError(String(grant._id));
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);
519
918
  }
520
919
  const opts = repoOptionsFromCtx(ctx);
521
920
  const metered = grant.usage.limit !== null;
921
+ const now = /* @__PURE__ */ new Date();
522
922
  const filter = {
523
923
  _id: grant._id,
524
924
  status: ENTITLEMENT_STATUS.ACTIVE,
925
+ $and: [{ $or: [{ notBefore: null }, { notBefore: { $lte: now } }] }, { $or: [{ accessExpiresAt: null }, { accessExpiresAt: { $gt: now } }] }],
525
926
  ...metered ? { $expr: { $lte: [{ $add: ["$usage.used", amount] }, "$usage.limit"] } } : {}
526
927
  };
527
928
  const update = { $inc: {
@@ -533,8 +934,11 @@ var EntitlementRepository = class extends Repository {
533
934
  new: true
534
935
  });
535
936
  if (!updated) {
536
- if (metered) throw new QuotaExhaustedError(String(grant._id), grant.usage.limit);
537
- throw new EntitlementNotFoundError(String(grant._id));
937
+ 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));
941
+ throw new EntitlementNotUsableError(String(fresh._id), freshGate.reason);
538
942
  }
539
943
  const limit = updated.usage.limit;
540
944
  if (limit !== null && updated.usage.used >= limit) {
@@ -543,7 +947,10 @@ var EntitlementRepository = class extends Repository {
543
947
  from: ENTITLEMENT_STATUS.ACTIVE,
544
948
  to: ENTITLEMENT_STATUS.CONSUMED
545
949
  }, {
546
- $set: { consumedAt: /* @__PURE__ */ new Date() },
950
+ $set: {
951
+ consumedAt: /* @__PURE__ */ new Date(),
952
+ live: null
953
+ },
547
954
  $inc: { version: 1 }
548
955
  }, opts);
549
956
  if (consumed) {
@@ -553,16 +960,116 @@ var EntitlementRepository = class extends Repository {
553
960
  }
554
961
  return updated;
555
962
  }
556
- /** Pause access without ending it (active → suspended). */
963
+ /**
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.
977
+ */
557
978
  async suspend(id, options = {}, ctx = {}) {
979
+ const startsAt = /* @__PURE__ */ new Date();
980
+ let autoResumeAt = options.autoResumeAt;
981
+ let creditWindowOnResume = options.creditWindowOnResume;
982
+ if (options.policy !== void 0) {
983
+ const grant = await this.load(id, ctx);
984
+ const spans = spansFromStatusHistory(grant.statusHistory ?? [], ENTITLEMENT_STATUS.SUSPENDED, { currentStatus: grant.status });
985
+ const decision = evaluateSuspension({
986
+ startsAt,
987
+ ...options.endsAt !== void 0 ? { endsAt: options.endsAt } : {},
988
+ ...options.requestedAt !== void 0 ? { requestedAt: options.requestedAt } : {}
989
+ }, spans, options.policy, ...options.offsetMinutes !== void 0 ? [{ offsetMinutes: options.offsetMinutes }] : []);
990
+ if (!decision.allowed) throw new SuspensionRefusedError(decision.reason, decision.message ?? `Pause refused (${decision.reason})`, decision.daysUsedInPeriod, decision.daysRemainingInPeriod);
991
+ autoResumeAt = decision.autoResumeAt ?? null;
992
+ creditWindowOnResume = options.policy.creditsWindow === true;
993
+ }
558
994
  return this.transition(id, ENTITLEMENT_STATUS.SUSPENDED, ACCESS_EVENTS.SUSPENDED, ctx, {
559
- suspendedAt: /* @__PURE__ */ new Date(),
560
- ...options.reason !== void 0 ? { reason: options.reason } : {}
995
+ suspendedAt: startsAt,
996
+ ...options.reason !== void 0 ? { reason: options.reason } : {},
997
+ ...autoResumeAt !== void 0 ? { autoResumeAt } : {},
998
+ ...creditWindowOnResume !== void 0 ? { creditWindowOnResume } : {}
561
999
  });
562
1000
  }
563
- /** Lift a suspension (suspended → active). */
564
- async resume(id, ctx = {}) {
565
- return this.transition(id, ENTITLEMENT_STATUS.ACTIVE, ACCESS_EVENTS.RESUMED, ctx, {});
1001
+ /**
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.
1030
+ */
1031
+ async resume(id, options = {}, ctx = {}) {
1032
+ return this.atomically(ctx, (inner) => this.resumeInner(id, options, inner));
1033
+ }
1034
+ async resumeInner(id, options, ctx) {
1035
+ 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
+ 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
+ let creditedExpiry = null;
1063
+ if (shouldCredit && before.suspendedAt && before.accessExpiresAt != null) {
1064
+ const frozenMs = Date.now() - before.suspendedAt.getTime();
1065
+ if (frozenMs > 0) creditedExpiry = new Date(before.accessExpiresAt.getTime() + frozenMs);
1066
+ }
1067
+ const resumed = await this.transition(id, ENTITLEMENT_STATUS.ACTIVE, ACCESS_EVENTS.RESUMED, ctx, {
1068
+ autoResumeAt: null,
1069
+ ...creditedExpiry !== null ? { accessExpiresAt: creditedExpiry } : {}
1070
+ });
1071
+ if (creditedExpiry !== null) await this.emitLifecycle(ACCESS_EVENTS.EXTENDED, resumed, ctx);
1072
+ return resumed;
566
1073
  }
567
1074
  /** Pull access permanently (active|suspended → revoked). Window cut to now. */
568
1075
  async revoke(id, options = {}, ctx = {}) {
@@ -586,6 +1093,10 @@ var EntitlementRepository = class extends Repository {
586
1093
  * an `expired` grant. Emits `access:extended`.
587
1094
  */
588
1095
  async extend(id, options, ctx = {}) {
1096
+ return this.atomically(ctx, (inner) => this.extendInner(id, options, inner));
1097
+ }
1098
+ async extendInner(id, options, ctx) {
1099
+ this.preflightDispatch(ctx);
589
1100
  const grant = await this.load(id, ctx);
590
1101
  const opts = repoOptionsFromCtx(ctx);
591
1102
  const newExpiry = options.accessExpiresAt !== void 0 ? options.accessExpiresAt : options.addMs != null ? new Date((grant.accessExpiresAt?.getTime() ?? Date.now()) + options.addMs) : null;
@@ -597,7 +1108,8 @@ var EntitlementRepository = class extends Repository {
597
1108
  }, {
598
1109
  $set: {
599
1110
  accessExpiresAt: newExpiry,
600
- expiredAt: null
1111
+ expiredAt: null,
1112
+ live: true
601
1113
  },
602
1114
  $inc: { version: 1 }
603
1115
  }, opts);
@@ -608,6 +1120,269 @@ var EntitlementRepository = class extends Repository {
608
1120
  return updated;
609
1121
  }
610
1122
  /**
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.
1143
+ */
1144
+ 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
+ },
1154
+ sort: { autoResumeAt: 1 },
1155
+ limit: options.limit ?? 500
1156
+ }, repoOptionsFromCtx(ctx));
1157
+ let resumed = 0;
1158
+ let failed = 0;
1159
+ for (const grant of due.data) try {
1160
+ await this.resume(String(grant._id), { creditFrozenDays: grant.creditWindowOnResume === true }, ctx);
1161
+ resumed += 1;
1162
+ } catch {
1163
+ failed += 1;
1164
+ }
1165
+ return {
1166
+ resumed,
1167
+ failed
1168
+ };
1169
+ }
1170
+ /**
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.
1214
+ */
1215
+ async expiringBetween(range, options = {}, ctx = {}) {
1216
+ const { from, to } = this.resolveExpiryWindow(range);
1217
+ const statuses = options.includeSuspended === false ? [ENTITLEMENT_STATUS.ACTIVE] : [ENTITLEMENT_STATUS.ACTIVE, ENTITLEMENT_STATUS.SUSPENDED];
1218
+ return await this.getAll({
1219
+ filters: {
1220
+ status: { $in: statuses },
1221
+ accessExpiresAt: {
1222
+ $ne: null,
1223
+ $gte: from,
1224
+ $lte: to
1225
+ },
1226
+ ...options.resourceType !== void 0 ? { resourceType: options.resourceType } : {},
1227
+ ...options.resourceRef !== void 0 ? { resourceRef: options.resourceRef } : {},
1228
+ ...options.subjectModel !== void 0 ? { subjectModel: options.subjectModel } : {},
1229
+ ...options.scopeKey !== void 0 ? { scopeKey: options.scopeKey } : {}
1230
+ },
1231
+ sort: { accessExpiresAt: 1 },
1232
+ ...options.limit !== void 0 ? { limit: options.limit } : {},
1233
+ ...options.page !== void 0 ? { page: options.page } : {}
1234
+ }, repoOptionsFromCtx(ctx));
1235
+ }
1236
+ /**
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.
1283
+ */
1284
+ async churnBetween(range, options = {}, ctx = {}) {
1285
+ const { from, to } = this.resolveExpiryWindow(range);
1286
+ const graceDays = options.graceDays ?? 30;
1287
+ if (!Number.isInteger(graceDays) || graceDays < 0) throw new InvalidExpiryWindowError(`graceDays must be a non-negative whole number of days, got ${graceDays}`);
1288
+ const graceMs = graceDays * 24 * 60 * 60 * 1e3;
1289
+ const rows = await this.aggregatePipeline([
1290
+ { $match: {
1291
+ status: ENTITLEMENT_STATUS.EXPIRED,
1292
+ accessExpiresAt: {
1293
+ $ne: null,
1294
+ $gte: from,
1295
+ $lte: to
1296
+ },
1297
+ ...options.resourceType !== void 0 ? { resourceType: options.resourceType } : {},
1298
+ ...options.resourceRef !== void 0 ? { resourceRef: options.resourceRef } : {},
1299
+ ...options.subjectModel !== void 0 ? { subjectModel: options.subjectModel } : {},
1300
+ ...options.scopeKey !== void 0 ? { scopeKey: options.scopeKey } : {}
1301
+ } },
1302
+ { $lookup: {
1303
+ from: this.Model.collection.name,
1304
+ let: {
1305
+ sRef: "$subjectRef",
1306
+ sModel: "$subjectModel",
1307
+ rType: "$resourceType",
1308
+ rRef: "$resourceRef",
1309
+ sKey: "$scopeKey",
1310
+ lapsedAt: "$accessExpiresAt",
1311
+ selfId: "$_id"
1312
+ },
1313
+ pipeline: [
1314
+ { $match: { $expr: { $and: [
1315
+ { $eq: ["$subjectRef", "$$sRef"] },
1316
+ { $eq: ["$subjectModel", "$$sModel"] },
1317
+ { $eq: ["$resourceType", "$$rType"] },
1318
+ { $eq: ["$resourceRef", "$$rRef"] },
1319
+ { $eq: [{ $ifNull: ["$scopeKey", ""] }, { $ifNull: ["$$sKey", ""] }] },
1320
+ { $ne: ["$_id", "$$selfId"] },
1321
+ { $in: ["$status", [...LIVE_STATUSES]] },
1322
+ { $lte: ["$grantedAt", { $add: ["$$lapsedAt", graceMs] }] },
1323
+ { $or: [{ $eq: [{ $ifNull: ["$accessExpiresAt", null] }, null] }, { $gt: ["$accessExpiresAt", "$$lapsedAt"] }] }
1324
+ ] } } },
1325
+ { $limit: 1 },
1326
+ { $project: { _id: 1 } }
1327
+ ],
1328
+ as: "replacement"
1329
+ } },
1330
+ { $group: {
1331
+ _id: null,
1332
+ lapsed: { $sum: 1 },
1333
+ renewed: { $sum: { $cond: [
1334
+ { $gt: [{ $size: "$replacement" }, 0] },
1335
+ 1,
1336
+ 0
1337
+ ] } }
1338
+ } }
1339
+ ], repoOptionsFromCtx(ctx));
1340
+ const lapsed = rows[0]?.lapsed ?? 0;
1341
+ const renewed = rows[0]?.renewed ?? 0;
1342
+ const unsettledMs = to.getTime() + graceMs - (options.now ?? /* @__PURE__ */ new Date()).getTime();
1343
+ const unsettledDays = unsettledMs <= 0 ? 0 : Math.ceil(unsettledMs / 864e5);
1344
+ return {
1345
+ lapsed,
1346
+ renewed,
1347
+ churned: lapsed - renewed,
1348
+ graceDays,
1349
+ unsettledDays
1350
+ };
1351
+ }
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
+ */
1363
+ 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);
1377
+ return {
1378
+ from: span.start,
1379
+ to: inclusiveEnd(span)
1380
+ };
1381
+ } catch (err) {
1382
+ throw new InvalidExpiryWindowError(err instanceof Error ? err.message : "invalid expiry window");
1383
+ }
1384
+ }
1385
+ /**
611
1386
  * Sweep grants whose window has lapsed: CAS active → expired, emit
612
1387
  * `access:expired` per row. The row SURVIVES (audit / renewal); this is the
613
1388
  * "model expiry as a state transition" rule, not a TTL-delete. The CAS
@@ -619,6 +1394,7 @@ var EntitlementRepository = class extends Repository {
619
1394
  * not to enforce the gate.
620
1395
  */
621
1396
  async expireDue(options = {}, ctx = {}) {
1397
+ this.preflightDispatch(ctx);
622
1398
  const cutoff = options.now ?? /* @__PURE__ */ new Date();
623
1399
  const opts = repoOptionsFromCtx(ctx);
624
1400
  const due = await this.getAll({
@@ -633,21 +1409,22 @@ var EntitlementRepository = class extends Repository {
633
1409
  limit: options.limit ?? 500
634
1410
  }, opts);
635
1411
  let swept = 0;
636
- for (const grant of due.data) {
637
- const done = await this.claim(String(grant._id), {
1412
+ for (const grant of due.data) if (await this.atomically(ctx, async (inner) => {
1413
+ const claimed = await this.claim(String(grant._id), {
638
1414
  field: "status",
639
1415
  from: ENTITLEMENT_STATUS.ACTIVE,
640
1416
  to: ENTITLEMENT_STATUS.EXPIRED,
641
1417
  where: { accessExpiresAt: { $lte: cutoff } }
642
1418
  }, {
643
- $set: { expiredAt: /* @__PURE__ */ new Date() },
1419
+ $set: {
1420
+ expiredAt: /* @__PURE__ */ new Date(),
1421
+ live: null
1422
+ },
644
1423
  $inc: { version: 1 }
645
- }, opts);
646
- if (done) {
647
- swept += 1;
648
- await this.emitLifecycle(ACCESS_EVENTS.EXPIRED, done, ctx);
649
- }
650
- }
1424
+ }, repoOptionsFromCtx(inner));
1425
+ if (claimed) await this.emitLifecycle(ACCESS_EVENTS.EXPIRED, claimed, inner);
1426
+ return claimed;
1427
+ })) swept += 1;
651
1428
  return { swept };
652
1429
  }
653
1430
  /**
@@ -655,59 +1432,330 @@ var EntitlementRepository = class extends Repository {
655
1432
  * grant it produced as refunded. Looks up by the polymorphic origin ref.
656
1433
  */
657
1434
  async refundByOrigin(originModel, originRef, options = {}, ctx = {}) {
658
- const opts = repoOptionsFromCtx(ctx);
659
- const live = await this.getAll({ filters: {
660
- originModel,
661
- originRef,
662
- status: { $in: LIVE_STATUSES }
663
- } }, opts);
1435
+ 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
+ */
664
1449
  let refunded = 0;
665
- for (const grant of live.data) {
666
- const done = await this.claim(String(grant._id), {
667
- field: "status",
668
- from: grant.status,
669
- to: ENTITLEMENT_STATUS.REFUNDED
670
- }, {
671
- $set: {
1450
+ for (;;) {
1451
+ const live = await this.getAll({
1452
+ filters: {
1453
+ originModel,
1454
+ originRef,
1455
+ status: { $in: LIVE_STATUSES }
1456
+ },
1457
+ 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, {
672
1462
  refundedAt: /* @__PURE__ */ new Date(),
673
1463
  accessExpiresAt: /* @__PURE__ */ new Date(),
674
1464
  ...options.reason !== void 0 ? { reason: options.reason } : {}
675
- },
676
- $inc: { version: 1 }
677
- }, opts);
678
- if (done) {
1465
+ });
679
1466
  refunded += 1;
680
- await this.emitLifecycle(ACCESS_EVENTS.REFUNDED, done, ctx);
1467
+ } catch (err) {
1468
+ if (!(err instanceof InvalidEntitlementTransitionError)) throw err;
681
1469
  }
682
1470
  }
683
1471
  return { refunded };
684
1472
  }
1473
+ /**
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.
1481
+ */
1482
+ 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
+ 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
+ },
1559
+ sort: { updatedAt: -1 }
1560
+ }, opts);
1561
+ const already = existing.data.find((row) => LIVE_STATUSES.includes(row.status)) ?? existing.data[0];
1562
+ if (already) return {
1563
+ grant: already,
1564
+ created: false
1565
+ };
1566
+ return {
1567
+ grant: await this.grant(input, ctx),
1568
+ created: true
1569
+ };
1570
+ }
1571
+ /**
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.
1580
+ */
1581
+ async setStateByOrigin(originModel, originRef, effect, options = {}, ctx = {}) {
1582
+ this.preflightDispatch(ctx);
1583
+ const opts = repoOptionsFromCtx(ctx);
1584
+ const from = effect === "resume" ? [ENTITLEMENT_STATUS.SUSPENDED] : [ENTITLEMENT_STATUS.ACTIVE, ENTITLEMENT_STATUS.SUSPENDED];
1585
+ const to = effect === "suspend" ? ENTITLEMENT_STATUS.SUSPENDED : effect === "resume" ? ENTITLEMENT_STATUS.ACTIVE : ENTITLEMENT_STATUS.REVOKED;
1586
+ 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
+ const queryFrom = from.filter((status) => status !== to);
1600
+ let changed = 0;
1601
+ for (;;) {
1602
+ const rows = await this.getAll({
1603
+ filters: {
1604
+ originModel,
1605
+ originRef,
1606
+ status: { $in: queryFrom }
1607
+ },
1608
+ 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;
1624
+ }
1625
+ }
1626
+ return { changed };
1627
+ }
1628
+ /**
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.
1634
+ */
1635
+ async extendByOrigin(originModel, originRef, accessExpiresAt, ctx = {}) {
1636
+ this.preflightDispatch(ctx);
1637
+ 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
+ const matched = await this.count({
1653
+ originModel,
1654
+ originRef,
1655
+ status: { $in: LIVE_STATUSES }
1656
+ }, 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
+ let changed = 0;
1664
+ for (;;) {
1665
+ const rows = await this.getAll({
1666
+ filters: {
1667
+ originModel,
1668
+ originRef,
1669
+ status: { $in: LIVE_STATUSES },
1670
+ accessExpiresAt: { $ne: accessExpiresAt }
1671
+ },
1672
+ limit: BATCH_SIZE
1673
+ }, opts);
1674
+ if (rows.data.length === 0) break;
1675
+ for (const grant of rows.data) {
1676
+ await this.extend(String(grant._id), { accessExpiresAt }, ctx);
1677
+ changed += 1;
1678
+ }
1679
+ }
1680
+ return {
1681
+ changed,
1682
+ matched
1683
+ };
1684
+ }
685
1685
  /** A subject's grants, newest-first ("my access"). */
686
- async listForSubject(subjectRef, ctx) {
1686
+ async listForSubject(subjectRef, ctx, options = {}) {
687
1687
  return await this.getAll({
688
- filters: { subjectRef },
689
- sort: { updatedAt: -1 }
1688
+ filters: {
1689
+ subjectRef,
1690
+ ...options.subjectModel ? { subjectModel: options.subjectModel } : {},
1691
+ ...options.resourceType ? { resourceType: options.resourceType } : {},
1692
+ ...options.liveOnly ? { live: true } : {}
1693
+ },
1694
+ sort: { updatedAt: -1 },
1695
+ limit: Math.min(Math.max(options.limit ?? 100, 1), 200)
690
1696
  }, repoOptionsFromCtx(ctx));
691
1697
  }
692
1698
  async transition(id, to, event, ctx, patch) {
1699
+ return this.atomically(ctx, (inner) => this.transitionInner(id, to, event, inner, patch));
1700
+ }
1701
+ async transitionInner(id, to, event, ctx, patch) {
1702
+ this.preflightDispatch(ctx);
693
1703
  const grant = await this.load(id, ctx);
694
- if (!canEntitlementTransition(grant.status, to)) throw new InvalidEntitlementTransitionError(grant.status, to);
1704
+ 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
+ const statusHistory = appendStatus(grant.statusHistory ?? [], to, {
1718
+ ...typeof patch.reason === "string" ? { note: patch.reason } : {},
1719
+ ...ctx.actorId !== void 0 ? { by: String(ctx.actorId) } : {}
1720
+ });
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
+ const live = LIVE_STATUSES.includes(to) ? true : null;
695
1729
  const updated = await this.claim(String(grant._id), {
696
1730
  field: "status",
697
1731
  from: grant.status,
698
1732
  to
699
1733
  }, {
700
- $set: patch,
1734
+ $set: {
1735
+ ...patch,
1736
+ statusHistory,
1737
+ live
1738
+ },
701
1739
  $inc: { version: 1 }
702
1740
  }, repoOptionsFromCtx(ctx));
703
1741
  if (!updated) throw new InvalidEntitlementTransitionError(grant.status, to);
704
1742
  await this.emitLifecycle(event, updated, ctx);
705
1743
  return updated;
706
1744
  }
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
+ */
707
1754
  async load(id, ctx) {
708
1755
  const grant = await this.getById(id, {
709
1756
  ...repoOptionsFromCtx(ctx),
710
- throwOnNotFound: false
1757
+ throwOnNotFound: false,
1758
+ select: "+statusHistory"
711
1759
  });
712
1760
  if (!grant) throw new EntitlementNotFoundError(id);
713
1761
  return grant;
@@ -726,6 +1774,7 @@ var EntitlementRepository = class extends Repository {
726
1774
  status: { $in: LIVE_STATUSES }
727
1775
  };
728
1776
  if (target.resourceType !== void 0) filters.resourceType = target.resourceType;
1777
+ if (target.subjectModel !== void 0) filters.subjectModel = target.subjectModel;
729
1778
  const rows = (await this.getAll({
730
1779
  filters,
731
1780
  sort: { updatedAt: -1 }
@@ -752,6 +1801,213 @@ var EntitlementRepository = class extends Repository {
752
1801
  } : {}
753
1802
  }, ctx, String(doc._id));
754
1803
  }
1804
+ /**
1805
+ * Run a mutation + its event emission as ONE atomic unit.
1806
+ *
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.
1838
+ */
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
+ async atomically(ctx, fn) {
1923
+ 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
+ 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
+ if (ctx.session) {
1956
+ const session = ctx.session;
1957
+ if (typeof session.inTransaction !== "function" || !session.inTransaction()) throw new SessionNotInTransactionError();
1958
+ return fn(ctx);
1959
+ }
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
+ if (this.allowNonTransactional) {
1984
+ if (!this.warnedNonTransactional) {
1985
+ this.warnedNonTransactional = true;
1986
+ (this.pkgLogger.warn ?? this.pkgLogger.error).call(this.pkgLogger, "[access] allowNonTransactional=true: entitlement writes and their outbox rows are NOT atomic. A crash between them can leave a GHOST event (a door opens on a right that was never granted) or a lost one. Development only — production must run a replica set.");
1987
+ }
1988
+ return fn(ctx);
1989
+ }
1990
+ return withTransaction(this.Model.db, (session) => fn({
1991
+ ...ctx,
1992
+ session
1993
+ }));
1994
+ }
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
+ */
2008
+ preflightDispatch(ctx) {
2009
+ if (ctx.session && this.eventTransport && !this.outbox) throw new UnmanagedSessionError();
2010
+ }
755
2011
  get channels() {
756
2012
  return {
757
2013
  eventTransport: this.eventTransport,
@@ -761,110 +2017,125 @@ var EntitlementRepository = class extends Repository {
761
2017
  }
762
2018
  };
763
2019
  //#endregion
764
- //#region src/events/in-process-bus.ts
765
- /**
766
- * ~50-line in-process fallback transport (rule 13). Structurally identical to
767
- * arc's `MemoryEventTransport`; delegates glob matching to primitives'
768
- * `matchEventPattern`. Hosts that pass an `eventTransport` never construct it.
769
- */
770
- var InProcessAccessBus = class {
771
- name = "in-process-access";
772
- handlers = /* @__PURE__ */ new Map();
773
- logger;
774
- constructor(options = {}) {
775
- this.logger = options.logger ?? console;
776
- }
777
- async publish(event) {
778
- const matched = /* @__PURE__ */ new Set();
779
- for (const [pattern, handlers] of this.handlers.entries()) if (matchEventPattern(pattern, event.type)) for (const h of handlers) matched.add(h);
780
- for (const handler of matched) try {
781
- await handler(event);
782
- } catch (err) {
783
- this.logger.error(`[access] handler error for ${event.type}:`, err);
784
- }
785
- }
786
- async subscribe(pattern, handler) {
787
- let set = this.handlers.get(pattern);
788
- if (!set) {
789
- set = /* @__PURE__ */ new Set();
790
- this.handlers.set(pattern, set);
791
- }
792
- set.add(handler);
793
- return () => {
794
- const s = this.handlers.get(pattern);
795
- if (!s) return;
796
- s.delete(handler);
797
- if (s.size === 0) this.handlers.delete(pattern);
798
- };
799
- }
800
- async close() {
801
- this.handlers.clear();
802
- }
803
- };
804
- //#endregion
805
- //#region src/engine/create-access.ts
806
- /** Runtime capabilities the access verbs require at boot (PACKAGE_RULES "Runtime capabilities"). */
2020
+ //#region src/engine/define-access.ts
2021
+ /** Repository capabilities asserted at boot. */
807
2022
  const REQUIRED_CAPABILITIES = ["getOrCreate", "upsert"];
808
2023
  /**
809
- * createAccess — the access ENTITLEMENT engine. Durable, time-bound grants of
810
- * access to any resource (course, download, API, membership, feature, service).
811
- * No purchase (order), no money (revenue), no catalog — those compose around it.
2024
+ * Describe the access engine. Pure — registers no model, builds no schema, performs no I/O.
812
2025
  */
813
- async function createAccess(config) {
814
- if (!config.connection) throw new Error("createAccess: config.connection is required");
815
- const tenant = resolveTenantConfig(config.tenant);
816
- const logger = config.logger ?? console;
817
- const events = config.eventTransport ?? new InProcessAccessBus({ logger });
818
- const modelsOptions = { tenant };
819
- if (config.autoIndex !== void 0) modelsOptions.autoIndex = config.autoIndex;
820
- if (config.collectionPrefix !== void 0) modelsOptions.collectionPrefix = config.collectionPrefix;
821
- if (config.forceRecreate !== void 0) modelsOptions.forceRecreate = config.forceRecreate;
822
- const models = createAccessModels(config.connection, modelsOptions);
823
- const tenantPlugins = (() => {
824
- if (!tenant.enabled || tenant.strategy !== "field") return [];
825
- const extras = typeof config.tenant === "object" ? config.tenant : void 0;
826
- return [multiTenantPlugin({
827
- tenantField: tenant.tenantField,
828
- fieldType: tenant.fieldType,
829
- contextKey: tenant.contextKey,
830
- required: tenant.required,
831
- ...extras?.skipOperations !== void 0 ? { skipOperations: extras.skipOperations } : {},
832
- ...extras?.skipWhen !== void 0 ? { skipWhen: extras.skipWhen } : {},
833
- ...extras?.resolveContext !== void 0 ? { resolveContext: extras.resolveContext } : {},
834
- ...extras?.allowDataInjection !== void 0 ? { allowDataInjection: extras.allowDataInjection } : {},
835
- ...extras?.onMismatch !== void 0 ? { onMismatch: extras.onMismatch } : {}
836
- })];
837
- })();
838
- const softDelete = softDeletePlugin({ ttlDays: config.softDeleteTtlDays ?? 2555 });
839
- const repoPlugins = config.repositoryPlugins ?? {};
840
- const entitlement = new EntitlementRepository({
841
- model: models.Entitlement,
842
- plugins: [
843
- ...tenantPlugins,
844
- softDelete,
845
- ...repoPlugins.entitlement ?? []
846
- ],
847
- eventTransport: events,
848
- outbox: config.outbox,
849
- logger
2026
+ function defineAccess(shape = {}) {
2027
+ assertNoLegacyTenantKeys(shape, "defineAccess", [["tenantFieldType", "tenant.fieldType"]]);
2028
+ const tenant = resolveTenantConfig(shape.tenant);
2029
+ const forceRecreate = shape.forceRecreate ?? false;
2030
+ const modelBlueprint = defineAccessModels({
2031
+ tenant,
2032
+ ...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
2033
+ ...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
2034
+ ...shape.indexes !== void 0 ? { indexes: shape.indexes } : {},
2035
+ forceRecreate
850
2036
  });
851
- const caps = entitlement.capabilities;
852
- if (!caps) throw new AccessCapabilityError(["capabilities descriptor (repo-core 0.6 / mongokit 3.16+)"]);
853
- const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
854
- if (missing.length > 0) throw new AccessCapabilityError(missing);
855
2037
  return {
856
- config: Object.freeze({ ...config }),
857
- models,
858
- repositories: { entitlement },
859
- events,
860
- outbox: config.outbox,
861
- async syncIndexes() {
862
- await models.Entitlement.syncIndexes();
863
- },
864
- async destroy() {
865
- await events.close?.();
2038
+ id: "access",
2039
+ modelNames: modelBlueprint.modelNames,
2040
+ bind(connection, runtime = {}) {
2041
+ /**
2042
+ * Boot gate — an outbox that cannot join our transaction is a configuration
2043
+ * error, not a runtime surprise.
2044
+ *
2045
+ * FIRST statement on purpose: a pure config assertion must run before any resource is
2046
+ * allocated (before the model is even registered), or an unrelated guard downstream (a
2047
+ * model collision) reports first and hides the real problem.
2048
+ *
2049
+ * `OutboxWriteOptions.session` is best-effort by contract, so a store that ignores it
2050
+ * persists events for mutations that later roll back — ghost events describing access
2051
+ * never granted, which a credential sync acts on. The repository refuses per-call
2052
+ * anyway, but discovering that on the first membership sale is far worse than at boot.
2053
+ */
2054
+ if (runtime.outbox && runtime.outbox.transactionalSave !== true) throw new AccessCapabilityError(["outbox.transactionalSave (the configured OutboxStore does not declare that save() enlists ctx.session — see @classytic/primitives/outbox)"]);
2055
+ const models = modelBlueprint.bind(connection);
2056
+ const logger = runtime.logger ?? console;
2057
+ const ownsTransport = runtime.eventTransport === void 0;
2058
+ const events = runtime.eventTransport ?? new InProcessAccessBus({ logger });
2059
+ const tenantPlugins = (() => {
2060
+ if (!tenant.enabled || tenant.strategy !== "field") return [];
2061
+ const extras = typeof shape.tenant === "object" ? shape.tenant : void 0;
2062
+ return [multiTenantPlugin({
2063
+ tenantField: tenant.tenantField,
2064
+ fieldType: tenant.fieldType,
2065
+ contextKey: tenant.contextKey,
2066
+ required: tenant.required,
2067
+ ...extras?.skipOperations !== void 0 ? { skipOperations: extras.skipOperations } : {},
2068
+ ...extras?.skipWhen !== void 0 ? { skipWhen: extras.skipWhen } : {},
2069
+ ...extras?.resolveContext !== void 0 ? { resolveContext: extras.resolveContext } : {},
2070
+ ...extras?.allowDataInjection !== void 0 ? { allowDataInjection: extras.allowDataInjection } : {},
2071
+ ...extras?.onMismatch !== void 0 ? { onMismatch: extras.onMismatch } : {}
2072
+ })];
2073
+ })();
2074
+ /**
2075
+ * NO soft delete (removed 2026-08-14). The entitlement LIFECYCLE is the retention
2076
+ * record: revoke is a status transition (`active|suspended -> revoked`, terminal
2077
+ * statuses set `live: null`), so a pulled grant stays queryable as evidence forever.
2078
+ * Soft delete sat ON TOP of that as a second, redundant hidden state — and its
2079
+ * `deletedAt: null` clause in the live-unique index meant a hand-set `deletedAt`
2080
+ * could free the slot and resurrect the suspend-bypass hole that index exists to
2081
+ * close. Refusing wrong deletes is `onDelete: 'restrict'` (mongokit cascade plugin),
2082
+ * not hiding rows.
2083
+ */
2084
+ const repoPlugins = runtime.repositoryPlugins ?? {};
2085
+ const entitlement = new EntitlementRepository({
2086
+ model: models.Entitlement,
2087
+ plugins: [...tenantPlugins, ...repoPlugins.entitlement ?? []],
2088
+ eventTransport: events,
2089
+ outbox: runtime.outbox,
2090
+ logger,
2091
+ allowNonTransactional: runtime.allowNonTransactional === true,
2092
+ ...runtime.timezone !== void 0 ? { timezone: runtime.timezone } : {}
2093
+ });
2094
+ const caps = entitlement.capabilities;
2095
+ if (!caps) throw new AccessCapabilityError(["capabilities descriptor (repo-core 0.6 / mongokit 3.16+)"]);
2096
+ const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
2097
+ if (missing.length > 0) throw new AccessCapabilityError(missing);
2098
+ /**
2099
+ * ── THE TOPOLOGY GATE — fail at BOOT, not at the first membership ────────
2100
+ *
2101
+ * `atomically()` needs multi-document transactions, which MongoDB only offers on a
2102
+ * replica set. Without this check a PRODUCTION deployment on a standalone `mongod`
2103
+ * booted perfectly and then failed at the first grant — money taken, no access, and
2104
+ * the only evidence a dead-lettered event. That is the shape this codebase keeps
2105
+ * paying for: the requirement was real and nothing asserted it where an operator
2106
+ * would see it.
2107
+ *
2108
+ * Conditional on an outbox, because that is what makes the write transactional; and
2109
+ * skipped when the host has explicitly accepted partial writes, so a dev box still
2110
+ * boots. Absent flag + no transactions ⇒ REFUSE.
2111
+ *
2112
+ * `unknown` counts as unsupported: mongokit reports an unreadable topology that way,
2113
+ * and an unobserved answer is never a positive one. The message distinguishes the two
2114
+ * because the operator's fix differs — bind after connecting, versus run a replica set.
2115
+ */
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)"]);
2117
+ const resolved = Object.freeze({
2118
+ tenant,
2119
+ autoIndex: shape.autoIndex,
2120
+ collectionPrefix: shape.collectionPrefix,
2121
+ indexes: shape.indexes,
2122
+ forceRecreate
2123
+ });
2124
+ return Object.freeze({
2125
+ config: resolved,
2126
+ models,
2127
+ repositories: Object.freeze({ entitlement }),
2128
+ events,
2129
+ outbox: runtime.outbox,
2130
+ async syncIndexes() {
2131
+ await models.Entitlement.syncIndexes();
2132
+ },
2133
+ async close() {
2134
+ if (ownsTransport) await events.close?.();
2135
+ }
2136
+ });
866
2137
  }
867
2138
  };
868
2139
  }
869
2140
  //#endregion
870
- export { ACCESS_EVENTS, AccessCapabilityError, AccessError, AccessModelCollisionError, ENTITLEMENT_STATUS, ENTITLEMENT_STATUS_VALUES, EntitlementNotFoundError, EntitlementRepository, InProcessAccessBus, InvalidEntitlementTransitionError, InvalidOutboxEventError, LIVE_STATUSES, OutboxOwnershipError, QuotaExhaustedError, UnmanagedSessionError, VersionMismatchError, accessEventDefinitions, canEntitlementTransition, createAccess, createAccessModels, evaluateAccess, hasAccess, isEntitlementStatus };
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 };