@classytic/access 0.1.1 → 0.2.0

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