@classytic/access 0.1.1 → 0.3.0

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