@classytic/access 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -0
- package/README.md +11 -13
- package/dist/domain/access-decision.d.mts +13 -44
- package/dist/domain/access-decision.mjs +40 -18
- package/dist/event-catalog-CIxQavRC.mjs +480 -0
- package/dist/event-catalog-CkIizOxb.d.mts +358 -0
- package/dist/events/event-catalog.d.mts +2 -2
- package/dist/events/event-catalog.mjs +2 -2
- package/dist/index.d.mts +225 -436
- package/dist/index.mjs +606 -1158
- package/dist/schemas/entitlement.d.mts +16 -10
- package/dist/schemas/entitlement.mjs +19 -14
- package/package.json +13 -9
- package/dist/event-catalog-BVD_rFlc.mjs +0 -111
- package/dist/event-catalog-Dxo3cxR3.d.mts +0 -136
package/dist/index.d.mts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { AccessDecision, AccessGrantState, AccessReason, evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
|
|
2
|
-
import {
|
|
1
|
+
import { ACCESS_REASONS, AccessDecision, AccessGrantState, AccessReason, evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
|
|
2
|
+
import { f as accessEventDefinitions, m as AccessEventName, p as ACCESS_EVENTS, t as AccessEventDefinition } from "./event-catalog-CkIizOxb.mjs";
|
|
3
3
|
import { ModelBlueprint, MultiTenantOptions, PluginType, Repository } from "@classytic/mongokit";
|
|
4
4
|
import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
|
|
5
5
|
import { InProcessEventBus, InProcessEventBusOptions } from "@classytic/primitives/event-infra";
|
|
6
|
-
import { Connection, Document, Model, Schema, Types } from "mongoose";
|
|
6
|
+
import { ClientSession, Connection, Document, Model, Schema, Types } from "mongoose";
|
|
7
7
|
import { StateMachine } from "@classytic/primitives/state-machine";
|
|
8
|
+
import { IndexDeclaration, IndexDeclaration as IndexDeclaration$1 } from "@classytic/mongokit/tenant";
|
|
8
9
|
import { StatusHistory } from "@classytic/primitives/status-history";
|
|
9
10
|
import { SuspensionPolicy } from "@classytic/primitives/suspension";
|
|
10
11
|
import { EventTransport } from "@classytic/primitives/events";
|
|
@@ -13,6 +14,20 @@ import { OffsetPaginationResult } from "@classytic/repo-core/pagination";
|
|
|
13
14
|
import { OperationContext } from "@classytic/primitives/context";
|
|
14
15
|
import { RetryPolicy } from "@classytic/repo-core/repository";
|
|
15
16
|
import { HttpError } from "@classytic/repo-core/errors";
|
|
17
|
+
//#region src/models/entitlement-consumption.model.d.ts
|
|
18
|
+
interface EntitlementConsumptionDocument extends Document {
|
|
19
|
+
_id: Types.ObjectId;
|
|
20
|
+
organizationId?: Types.ObjectId | string;
|
|
21
|
+
entitlementId: string;
|
|
22
|
+
/** Caller-supplied idempotency key — a scan id, an event id, a request key. */
|
|
23
|
+
key: string;
|
|
24
|
+
amount: number;
|
|
25
|
+
consumedAt: Date;
|
|
26
|
+
actorId?: string;
|
|
27
|
+
createdAt: Date;
|
|
28
|
+
updatedAt: Date;
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
16
31
|
//#region src/domain/enums/entitlement-status.enum.d.ts
|
|
17
32
|
/**
|
|
18
33
|
* Entitlement lifecycle status.
|
|
@@ -243,9 +258,11 @@ interface EntitlementDocument extends Document {
|
|
|
243
258
|
}
|
|
244
259
|
//#endregion
|
|
245
260
|
//#region src/models/create-models.d.ts
|
|
246
|
-
type AccessModelName = 'Entitlement';
|
|
261
|
+
type AccessModelName = 'Entitlement' | 'EntitlementConsumption';
|
|
247
262
|
interface AccessModels {
|
|
248
263
|
Entitlement: Model<EntitlementDocument>;
|
|
264
|
+
/** The consumption ledger — one row per idempotent `consume()`. */
|
|
265
|
+
EntitlementConsumption: Model<EntitlementConsumptionDocument>;
|
|
249
266
|
}
|
|
250
267
|
interface DefineAccessModelsConfig {
|
|
251
268
|
/** Resolved tenant shape — `defineAccess` resolves it once (pure) and passes it here. */
|
|
@@ -256,6 +273,15 @@ interface DefineAccessModelsConfig {
|
|
|
256
273
|
collectionPrefix?: string | undefined;
|
|
257
274
|
/** On a name collision: `false` (default) throws; `true` re-registers (test/dev fixtures). */
|
|
258
275
|
forceRecreate?: boolean | undefined;
|
|
276
|
+
/**
|
|
277
|
+
* Indexes the HOST needs on the entitlement collection that this package cannot know
|
|
278
|
+
* about: a creator roster sorted a way the gate never sorts, a retention sweep across
|
|
279
|
+
* every tenant. Applied through `@classytic/mongokit/tenant`, so `scope: 'tenant'` (the
|
|
280
|
+
* default) is led by the tenant field like the package's own and `scope: 'global'` is
|
|
281
|
+
* kept as written for a read that has no tenant to give. On the schema, so they build
|
|
282
|
+
* and verify with everything else.
|
|
283
|
+
*/
|
|
284
|
+
indexes?: readonly IndexDeclaration$1[] | undefined;
|
|
259
285
|
}
|
|
260
286
|
/**
|
|
261
287
|
* Describe the Access model set as a connection-free blueprint. Pure — builds no schema and
|
|
@@ -277,6 +303,8 @@ interface AccessContext extends OperationContext {
|
|
|
277
303
|
organizationId?: string;
|
|
278
304
|
actorId?: string;
|
|
279
305
|
actorKind?: 'user' | 'system' | 'service' | undefined;
|
|
306
|
+
/** A caller-owned session. Must be inside an active transaction when an outbox is wired. */
|
|
307
|
+
session?: ClientSession | undefined;
|
|
280
308
|
/** Cooperative cancellation — threaded into every repo call. */
|
|
281
309
|
signal?: AbortSignal | undefined;
|
|
282
310
|
/** Driver round-trip retry policy — threaded into every repo call. */
|
|
@@ -284,7 +312,27 @@ interface AccessContext extends OperationContext {
|
|
|
284
312
|
}
|
|
285
313
|
//#endregion
|
|
286
314
|
//#region src/repositories/entitlement.repository.d.ts
|
|
315
|
+
/** Upper bound on one `checkMany` — one query, bounded `$or`. */
|
|
316
|
+
declare const MAX_CAPABILITIES_PER_CHECK = 100;
|
|
287
317
|
type EntitlementSource = 'purchase' | 'subscription' | 'trial' | 'grant' | 'manual' | 'system';
|
|
318
|
+
/** WHO holds access — both halves required, so two subject namespaces never collide. */
|
|
319
|
+
interface AccessSubject {
|
|
320
|
+
subjectModel: string;
|
|
321
|
+
subjectRef: string;
|
|
322
|
+
}
|
|
323
|
+
/** WHAT is accessed — `resourceType` required, so two resource namespaces never collide. */
|
|
324
|
+
interface AccessCapability {
|
|
325
|
+
resourceType: string;
|
|
326
|
+
resourceRef: string;
|
|
327
|
+
/** Sub-scope inside the resource. Default `''` (the whole resource). */
|
|
328
|
+
scopeKey?: string | undefined;
|
|
329
|
+
}
|
|
330
|
+
/** The full identity tuple of a live grant. */
|
|
331
|
+
type EntitlementKey = AccessSubject & AccessCapability;
|
|
332
|
+
/** Identify the grant to check / consume: by id, or by its complete identity tuple. */
|
|
333
|
+
type EntitlementTarget = {
|
|
334
|
+
id: string;
|
|
335
|
+
} | EntitlementKey;
|
|
288
336
|
/** One desired entitlement in a reconcile set — carries its target org. */
|
|
289
337
|
interface EntitlementDesiredItem {
|
|
290
338
|
resourceType: string;
|
|
@@ -295,29 +343,15 @@ interface EntitlementDesiredItem {
|
|
|
295
343
|
organizationId: string;
|
|
296
344
|
}
|
|
297
345
|
interface ReconcileEntitlementSetInput {
|
|
298
|
-
subject:
|
|
299
|
-
subjectModel: string;
|
|
300
|
-
subjectRef: string;
|
|
301
|
-
};
|
|
346
|
+
subject: AccessSubject;
|
|
302
347
|
/** The origin whose projected entitlements are reconciled (an Agreement id). */
|
|
303
348
|
agreementRef: string;
|
|
304
349
|
desired: readonly EntitlementDesiredItem[];
|
|
305
350
|
/** Grant source for newly-created rights. Default `'subscription'`. */
|
|
306
351
|
source?: EntitlementSource | undefined;
|
|
307
352
|
/**
|
|
308
|
-
*
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
* NOT an idempotency key, and deliberately so. This used to be documented as an
|
|
312
|
-
* "idempotency stamp", which was wrong in a way that mattered: nothing reads it
|
|
313
|
-
* as a key, and `spine-contract`'s `EntitlementPort` was written against that
|
|
314
|
-
* claim. Reconcile's idempotency comes from the DESIRED-SET DIFF plus the
|
|
315
|
-
* live-unique index - a replay finds the desired rows already live and retains
|
|
316
|
-
* them - which is stronger here, because a recovery re-drive legitimately carries
|
|
317
|
-
* a FRESH ref for the same desired state and ref-keyed dedup would refuse it.
|
|
318
|
-
*
|
|
319
|
-
* Pinned by `tests/integration/reconcile-entitlement-set.test.ts` ("idempotent by
|
|
320
|
-
* the DESIRED-SET DIFF, not by remembering mutationRef").
|
|
353
|
+
* Provenance only — recorded in revoke reasons. NOT an idempotency key: reconcile is
|
|
354
|
+
* idempotent by the desired-set diff plus the live-unique index.
|
|
321
355
|
*/
|
|
322
356
|
mutationRef?: string | undefined;
|
|
323
357
|
}
|
|
@@ -334,6 +368,10 @@ interface GrantInput {
|
|
|
334
368
|
resourceType: string;
|
|
335
369
|
/** Sub-scope inside the resource. Defaults to '' (the whole resource). */
|
|
336
370
|
scopeKey?: string | undefined;
|
|
371
|
+
/**
|
|
372
|
+
* How the grant arose. `purchase` / `subscription` REQUIRE `originModel` + `originRef`;
|
|
373
|
+
* every other source requires an origin or `ctx.actorId`.
|
|
374
|
+
*/
|
|
337
375
|
source: EntitlementSource;
|
|
338
376
|
/** Access opens at this instant (scheduled / early access). */
|
|
339
377
|
notBefore?: Date | null | undefined;
|
|
@@ -346,66 +384,36 @@ interface GrantInput {
|
|
|
346
384
|
amount?: number | null | undefined;
|
|
347
385
|
currency?: string | undefined;
|
|
348
386
|
metadata?: Record<string, unknown> | undefined;
|
|
349
|
-
/**
|
|
350
|
-
* When a live grant already exists, refresh its window/quota (a re-purchase
|
|
351
|
-
* restarts the clock). Default true. Set false for pure idempotency.
|
|
352
|
-
*/
|
|
387
|
+
/** When a live grant already exists, refresh it. Default true; `false` = pure idempotency. */
|
|
353
388
|
renew?: boolean | undefined;
|
|
354
389
|
/**
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
* `usage.limit = usageLimit`, `usage.used = 0`. Correct for a monthly membership.
|
|
359
|
-
*
|
|
360
|
-
* `'add'` — TOP-UP. The buyer acquired MORE of the same thing, so the allowance grows and
|
|
361
|
-
* consumption is preserved: `usage.limit += usageLimit`, `usage.used` untouched.
|
|
362
|
-
*
|
|
363
|
-
* ## Why this had to become the caller's declaration
|
|
364
|
-
*
|
|
365
|
-
* Only the caller knows which act occurred, and getting it wrong silently destroys paid
|
|
366
|
-
* access. Two lines of an 8-session pack in ONE order both matched the same live row (the
|
|
367
|
-
* live-unique key is `(subjectModel, subjectRef, resourceType, resourceRef, scopeKey)`), so
|
|
368
|
-
* the second `'reset'` OVERWROTE the first: 16 sessions were paid for and 8 were enforceable,
|
|
369
|
-
* with `appliedOrigins` correctly listing both lines while `usage.limit` recorded one. The
|
|
370
|
-
* order-line ledger totalled 16, but enforcement reads the ENTITLEMENT, so the ledger was
|
|
371
|
-
* not the gate.
|
|
372
|
-
*
|
|
373
|
-
* `'reset'` also zeroes `usage.used`, which on a top-up silently UN-CONSUMES redemptions the
|
|
374
|
-
* member already spent.
|
|
375
|
-
*
|
|
376
|
-
* Defaulting to `'reset'` keeps every existing consumer's behaviour unchanged — a subscription
|
|
377
|
-
* renewal genuinely should reset — so this widens the contract without moving anyone.
|
|
390
|
+
* Quota on a renewal of a live grant: `'reset'` (default — a new period restarts limit and
|
|
391
|
+
* used) or `'add'` (a top-up — limit grows, used is preserved). Only the caller knows which
|
|
392
|
+
* act occurred; two packs on one order are `'add'`, a monthly renewal is `'reset'`.
|
|
378
393
|
*/
|
|
379
394
|
quotaMode?: 'reset' | 'add' | undefined;
|
|
380
395
|
}
|
|
381
|
-
/**
|
|
382
|
-
* Identify the grant to check/consume: by id, or by (subject, resource).
|
|
383
|
-
*
|
|
384
|
-
* `resourceType` and `subjectModel` are optional for back-compat but SHOULD be
|
|
385
|
-
* passed by polymorphic hosts: two resource types sharing a `resourceRef` (a
|
|
386
|
-
* product id doubling as a facility key), or two subject namespaces sharing an
|
|
387
|
-
* id, are indistinguishable without them — and `check()` would answer for
|
|
388
|
-
* whichever row sorts first. When present they narrow the lookup exactly.
|
|
389
|
-
*/
|
|
390
|
-
type EntitlementTarget = {
|
|
391
|
-
id: string;
|
|
392
|
-
} | {
|
|
393
|
-
subjectRef: string;
|
|
394
|
-
subjectModel?: string | undefined;
|
|
395
|
-
resourceRef: string;
|
|
396
|
-
resourceType?: string | undefined;
|
|
397
|
-
scopeKey?: string | undefined;
|
|
398
|
-
};
|
|
399
396
|
interface CheckResult extends AccessDecision {
|
|
400
397
|
entitlement: EntitlementDocument | null;
|
|
401
398
|
}
|
|
399
|
+
/** One spend. `key` makes it idempotent: the same key never spends twice. */
|
|
400
|
+
interface ConsumeInput {
|
|
401
|
+
/** Caller's idempotency key — a scan id, an event id, a request key. Required. */
|
|
402
|
+
key: string;
|
|
403
|
+
/** Units to spend. Default 1. Positive integer. */
|
|
404
|
+
amount?: number | undefined;
|
|
405
|
+
}
|
|
406
|
+
interface ConsumeResult {
|
|
407
|
+
entitlement: EntitlementDocument;
|
|
408
|
+
/** `true` when the key had already spent — nothing was spent this call. */
|
|
409
|
+
replayed: boolean;
|
|
410
|
+
amount: number;
|
|
411
|
+
/** Units left after the spend, or `null` when unmetered. */
|
|
412
|
+
remaining: number | null;
|
|
413
|
+
}
|
|
402
414
|
/**
|
|
403
|
-
* The calendar window a reporting read covers.
|
|
404
|
-
*
|
|
405
|
-
* **Prefer the civil-date form** (`{ from: '2026-08-01', to: '2026-08-31' }`) — a
|
|
406
|
-
* period is a calendar span, and the repository resolves it against its own
|
|
407
|
-
* business zone. Passing instants makes the CALLER own that boundary, and every
|
|
408
|
-
* caller that owns it can get it wrong differently.
|
|
415
|
+
* The calendar window a reporting read covers. Prefer civil dates
|
|
416
|
+
* (`{ from: '2026-08-01', to: '2026-08-31' }`): the repository binds them to its business zone.
|
|
409
417
|
*/
|
|
410
418
|
interface ExpiryWindow {
|
|
411
419
|
from: Date | string;
|
|
@@ -413,6 +421,8 @@ interface ExpiryWindow {
|
|
|
413
421
|
}
|
|
414
422
|
interface EntitlementRepositoryConfig {
|
|
415
423
|
model: Model<EntitlementDocument>;
|
|
424
|
+
/** The consumption ledger — REQUIRED: `consume()` is idempotent only through it. */
|
|
425
|
+
consumptions: Repository<EntitlementConsumptionDocument>;
|
|
416
426
|
plugins?: PluginType[];
|
|
417
427
|
eventTransport?: EventTransport | undefined;
|
|
418
428
|
outbox?: OutboxStore | undefined;
|
|
@@ -422,148 +432,77 @@ interface EntitlementRepositoryConfig {
|
|
|
422
432
|
} | undefined;
|
|
423
433
|
/** Standalone-mongod escape — see `AccessRuntime.allowNonTransactional`. Opt-IN. */
|
|
424
434
|
allowNonTransactional?: boolean | undefined;
|
|
425
|
-
/**
|
|
426
|
-
* The BUSINESS timezone, IANA (`'Asia/Dhaka'`) — the authority for resolving a
|
|
427
|
-
* calendar range into instants.
|
|
428
|
-
*
|
|
429
|
-
* Deliberately an IANA zone, not the `offsetMinutes` this package's suspension
|
|
430
|
-
* paths take per call: a fixed offset cannot be DST-correct, so in any zone that
|
|
431
|
-
* observes DST it is wrong for part of the year, and the failure is a window
|
|
432
|
-
* shifted by an hour that still returns a plausible list. `offsetMinutes` stays
|
|
433
|
-
* supported where it already is; new period-shaped reads use this.
|
|
434
|
-
*
|
|
435
|
-
* Defaults to `'UTC'`, which makes a deployment that never sets one behave
|
|
436
|
-
* exactly as it does today.
|
|
437
|
-
*/
|
|
435
|
+
/** IANA business zone for calendar ranges and pause-allowance days. Default `'UTC'`. */
|
|
438
436
|
timezone?: string | undefined;
|
|
437
|
+
/** The clock. Default `() => new Date()`. */
|
|
438
|
+
clock?: (() => Date) | undefined;
|
|
439
439
|
}
|
|
440
440
|
declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
441
|
+
private readonly consumptions;
|
|
441
442
|
private readonly eventTransport;
|
|
442
443
|
private readonly outbox;
|
|
443
444
|
private readonly pkgLogger;
|
|
444
445
|
private readonly allowNonTransactional;
|
|
445
|
-
/** IANA business zone — see `EntitlementRepositoryConfig.timezone`. */
|
|
446
446
|
private readonly timezone;
|
|
447
|
-
|
|
447
|
+
private readonly clock;
|
|
448
|
+
/** Warn ONCE per repository, not once per grant. */
|
|
448
449
|
private warnedNonTransactional;
|
|
449
450
|
constructor(config: EntitlementRepositoryConfig);
|
|
451
|
+
/** The current instant from the injected clock. A clock returning an invalid date throws. */
|
|
452
|
+
now(): Date;
|
|
450
453
|
/**
|
|
451
|
-
* Grant access. Idempotent per (subject, resource, scope) live grant via
|
|
452
|
-
*
|
|
453
|
-
* the window
|
|
454
|
-
* `access:granted` on
|
|
454
|
+
* Grant access. Idempotent per (subject, resource, scope) live grant via atomic `getOrCreate`.
|
|
455
|
+
* On an existing live grant: a REPLAY of an origin already applied changes nothing; otherwise
|
|
456
|
+
* (`renew !== false`) the window is refreshed — never shortened — and the quota follows
|
|
457
|
+
* `quotaMode`. Emits `access:granted` on create, `access:extended` on renewal.
|
|
455
458
|
*/
|
|
456
459
|
grant(input: GrantInput, ctx: AccessContext): Promise<EntitlementDocument>;
|
|
457
460
|
private grantInner;
|
|
458
461
|
/**
|
|
459
|
-
* Decide access RIGHT NOW. Read-only
|
|
460
|
-
*
|
|
461
|
-
* plus the entitlement (or null when none exists).
|
|
462
|
+
* Decide access RIGHT NOW. Read-only. By id, or by the COMPLETE identity tuple — a partial
|
|
463
|
+
* tuple cannot be expressed, so two namespaces sharing an id never answer for each other.
|
|
462
464
|
*/
|
|
463
465
|
check(target: EntitlementTarget, ctx: AccessContext): Promise<CheckResult>;
|
|
464
466
|
/**
|
|
465
|
-
*
|
|
466
|
-
*
|
|
467
|
-
* Prefer this at any security boundary. `check()` keeps `subjectModel` and
|
|
468
|
-
* `resourceType` optional for back-compat, which means a polymorphic
|
|
469
|
-
* deployment can accidentally ask an ambiguous question: two subject
|
|
470
|
-
* namespaces sharing an id (a `user` and an `apiKey` both keyed `42`), or two
|
|
471
|
-
* resource types sharing a ref (a product id doubling as a facility key),
|
|
472
|
-
* resolve to whichever row sorts first. That is a silent wrong-grant answer,
|
|
473
|
-
* and it fails OPEN when the other namespace happens to hold a live grant.
|
|
474
|
-
*
|
|
475
|
-
* Rather than break every existing caller, the complete tuple is available as
|
|
476
|
-
* its own verb: a reviewer can see at the call site which question was asked,
|
|
477
|
-
* and `EntitlementTarget`'s optionality can be tightened in a future major
|
|
478
|
-
* without a silent behaviour change now.
|
|
467
|
+
* Decide many capabilities for ONE subject in ONE query. Results are in input order.
|
|
468
|
+
* Empty, oversize (> {@link MAX_CAPABILITIES_PER_CHECK}) or duplicate capabilities throw.
|
|
479
469
|
*/
|
|
480
|
-
|
|
481
|
-
subjectModel: string;
|
|
482
|
-
subjectRef: string;
|
|
483
|
-
resourceType: string;
|
|
484
|
-
resourceRef: string;
|
|
485
|
-
scopeKey?: string | undefined;
|
|
486
|
-
}, ctx: AccessContext): Promise<CheckResult>;
|
|
470
|
+
checkMany(subject: AccessSubject, capabilities: readonly AccessCapability[], ctx: AccessContext): Promise<CheckResult[]>;
|
|
487
471
|
/**
|
|
488
|
-
* Spend
|
|
489
|
-
*
|
|
490
|
-
*
|
|
491
|
-
* is
|
|
492
|
-
* `
|
|
493
|
-
*
|
|
472
|
+
* Spend metered units, idempotently per `input.key`.
|
|
473
|
+
*
|
|
474
|
+
* The key is claimed in the consumption ledger (unique per grant) BEFORE the spend, and the
|
|
475
|
+
* spend is one guarded `$inc` whose filter re-asserts status, window and `used + amount <=
|
|
476
|
+
* limit` — so a replayed key spends nothing and N concurrent spends never overshoot. A spend
|
|
477
|
+
* that reaches the cap CAS-transitions the grant to `consumed`. Emits `access:consumed` per
|
|
478
|
+
* spend and `access:exhausted` at the cap.
|
|
494
479
|
*/
|
|
495
|
-
consume(target: EntitlementTarget,
|
|
480
|
+
consume(target: EntitlementTarget, input: ConsumeInput, ctx: AccessContext): Promise<ConsumeResult>;
|
|
496
481
|
private consumeInner;
|
|
482
|
+
/** The answer for a key that already spent: same amount → replay; different → conflict. */
|
|
483
|
+
private replayed;
|
|
484
|
+
private notUsable;
|
|
497
485
|
/**
|
|
498
|
-
* Pause access
|
|
499
|
-
*
|
|
500
|
-
*
|
|
501
|
-
* computed once here and stored on the grant — see the fields' docblocks. This
|
|
502
|
-
* kernel deliberately does not own the rulebook (max days per year, minimum
|
|
503
|
-
* length, notice) because those differ per product and per deployment;
|
|
504
|
-
* `primitives/suspension.evaluateSuspension` computes them and the host passes
|
|
505
|
-
* the answers in.
|
|
506
|
-
*
|
|
507
|
-
* Omitting `autoResumeAt` leaves the pause OPEN-ENDED, which is the pre-policy
|
|
508
|
-
* behaviour and still legal — but it is the shape where a freeze quietly stops
|
|
509
|
-
* the business earning, so a deployment with any allowance at all should always
|
|
510
|
-
* pass one.
|
|
486
|
+
* Pause access (active → suspended). With `policy`, the allowance is enforced against the
|
|
487
|
+
* grant's own status history and `autoResumeAt` is DERIVED (day boundaries in the business
|
|
488
|
+
* zone); without it, `autoResumeAt` is the caller's explicit deadline (omitted = open-ended).
|
|
511
489
|
*/
|
|
512
490
|
suspend(id: string, options?: {
|
|
513
491
|
reason?: string | undefined;
|
|
514
|
-
/**
|
|
515
|
-
* The pause RULEBOOK. Supply it and this method enforces the allowance and
|
|
516
|
-
* DERIVES `autoResumeAt` — the caller no longer computes a date by hand.
|
|
517
|
-
*
|
|
518
|
-
* Evaluation happens HERE rather than in a caller for the same reason
|
|
519
|
-
* muster evaluates admission inside its check-in: the allowance is a function
|
|
520
|
-
* of this aggregate's own history, and only the thing holding the aggregate
|
|
521
|
-
* can read it without a second round trip and a race.
|
|
522
|
-
*/
|
|
492
|
+
/** The pause rulebook. When supplied, `autoResumeAt` / `creditWindowOnResume` are ignored. */
|
|
523
493
|
policy?: SuspensionPolicy | undefined;
|
|
524
494
|
/** Requested end. Omit for open-ended — the allowance then decides. */
|
|
525
495
|
endsAt?: Date | null | undefined;
|
|
526
496
|
/** For the notice check. Defaults to now. */
|
|
527
497
|
requestedAt?: Date | undefined;
|
|
528
|
-
/** Business-timezone offset for day boundaries. */
|
|
529
|
-
offsetMinutes?: number | undefined;
|
|
530
|
-
/**
|
|
531
|
-
* Explicit deadline, for a caller with no policy (the pre-policy path) or an
|
|
532
|
-
* operator override. IGNORED when `policy` is supplied — two sources for one
|
|
533
|
-
* date is how they drift.
|
|
534
|
-
*/
|
|
535
498
|
autoResumeAt?: Date | null | undefined;
|
|
536
499
|
creditWindowOnResume?: boolean | undefined;
|
|
537
500
|
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
538
501
|
/**
|
|
539
|
-
* Lift a suspension (suspended → active)
|
|
540
|
-
*
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
* A freeze on a PREPAID term is worthless without it. Consider a Jan–Jun
|
|
544
|
-
* membership (`accessExpiresAt = 1 Jul`) paused on 1 Feb and resumed on 1 Jul:
|
|
545
|
-
* without a credit the window is untouched, so the member resumes into an
|
|
546
|
-
* already-elapsed grant, is refused immediately, and the sweep flips it to
|
|
547
|
-
* `expired`. They paid for six months, used one, and got nothing back.
|
|
548
|
-
*
|
|
549
|
-
* (Note the sweep only touches `active` rows, so pausing does at least PROTECT
|
|
550
|
-
* the grant from expiring mid-freeze — it just comes back worthless.)
|
|
551
|
-
*
|
|
552
|
-
* But crediting is NOT universally right, which is why the caller must choose:
|
|
553
|
-
*
|
|
554
|
-
* - **Prepaid term** — money is already collected, so push the window out by
|
|
555
|
-
* the frozen duration. `creditFrozenDays: true`.
|
|
556
|
-
* - **Rolling subscription** — billing was PAUSED instead, so there is no end
|
|
557
|
-
* date to extend. Crediting here would hand out a free month.
|
|
558
|
-
*
|
|
559
|
-
* Getting it wrong in either direction is a real complaint: credit AND keep
|
|
560
|
-
* billing means the member paid for frozen time; neither means they lost it. The
|
|
561
|
-
* decision belongs to whoever knows the product type, so this kernel takes it as
|
|
562
|
-
* a parameter rather than guessing — and a host reads it from its pause policy,
|
|
563
|
-
* never from a literal.
|
|
564
|
-
*
|
|
565
|
-
* Emits `access:extended` in addition to `access:resumed` when it credits, so a
|
|
566
|
-
* credential-sync subscriber sees the new window.
|
|
502
|
+
* Lift a suspension (suspended → active). The frozen time is credited onto the window in the
|
|
503
|
+
* SAME CAS when `creditFrozenDays` is true — default: the `creditWindowOnResume` promise stored
|
|
504
|
+
* at suspend time (a client cannot award itself an extension). Prepaid terms credit; rolling
|
|
505
|
+
* subscriptions whose billing paused do not.
|
|
567
506
|
*/
|
|
568
507
|
resume(id: string, options?: {
|
|
569
508
|
creditFrozenDays?: boolean | undefined;
|
|
@@ -578,9 +517,10 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
578
517
|
reason?: string | undefined;
|
|
579
518
|
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
580
519
|
/**
|
|
581
|
-
* Extend
|
|
582
|
-
*
|
|
583
|
-
* an `expired` grant
|
|
520
|
+
* Extend the access window — exactly ONE of an absolute `accessExpiresAt` (`null` = lifetime)
|
|
521
|
+
* or a positive `addMs`. Never shortens (that is revoke + re-grant), refuses `addMs` on a
|
|
522
|
+
* lifetime grant, and reactivates an `expired` grant only into a window that is still open
|
|
523
|
+
* (`addMs` then counts from now). Emits `access:extended`.
|
|
584
524
|
*/
|
|
585
525
|
extend(id: string, options: {
|
|
586
526
|
accessExpiresAt?: Date | null | undefined;
|
|
@@ -588,26 +528,8 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
588
528
|
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
589
529
|
private extendInner;
|
|
590
530
|
/**
|
|
591
|
-
* Resume suspensions
|
|
592
|
-
*
|
|
593
|
-
* ## Why this sweep is a revenue control, not housekeeping
|
|
594
|
-
*
|
|
595
|
-
* A freeze with no automatic end is an indefinite free hold. The member pauses in
|
|
596
|
-
* February, the business stops earning, and nothing looks broken — so nobody
|
|
597
|
-
* files a bug and it is found by an audit months later, if at all. This closes
|
|
598
|
-
* that: the pause ends on the date it was capped at, whether or not the member
|
|
599
|
-
* ever comes back.
|
|
600
|
-
*
|
|
601
|
-
* ## It uses the STORED decision, never a fresh one
|
|
602
|
-
*
|
|
603
|
-
* Both `autoResumeAt` and `creditWindowOnResume` are read off the grant, not
|
|
604
|
-
* recomputed from current policy. They are promises made when the freeze began,
|
|
605
|
-
* and re-deriving them would silently move a date the member was told the moment
|
|
606
|
-
* an operator edited the rulebook. (`primitives/suspension.dueForAutoResume`
|
|
607
|
-
* documents the same rule for the pure form.)
|
|
608
|
-
*
|
|
609
|
-
* Per-row failures are collected, not thrown: one grant whose credit maths hits a
|
|
610
|
-
* VersionMismatch must not abort the sweep and leave the rest suspended.
|
|
531
|
+
* Resume suspensions past their stored `autoResumeAt`, honouring the stored credit promise.
|
|
532
|
+
* A lost CAS on one row counts as `failed` and never aborts the sweep.
|
|
611
533
|
*/
|
|
612
534
|
autoResumeDue(options?: {
|
|
613
535
|
now?: Date | undefined;
|
|
@@ -617,124 +539,32 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
617
539
|
failed: number;
|
|
618
540
|
}>;
|
|
619
541
|
/**
|
|
620
|
-
* The RENEWAL WORKLIST — grants whose
|
|
621
|
-
* range, soonest first.
|
|
622
|
-
*
|
|
623
|
-
* ## Why this is a domain verb and not a `getAll` the caller could write
|
|
624
|
-
*
|
|
625
|
-
* Three decisions live here that every caller would otherwise re-derive, and
|
|
626
|
-
* would eventually re-derive differently:
|
|
627
|
-
*
|
|
628
|
-
* 1. **Which statuses are renewable.** `active` AND `suspended`. A frozen
|
|
629
|
-
* membership still has an expiry date and still needs renewing — dropping it
|
|
630
|
-
* silently shortens the worklist, and the members missing from it are
|
|
631
|
-
* exactly the ones already at risk of leaving. `expired` is deliberately NOT
|
|
632
|
-
* here: lapsed grants are a different, later conversation (win-back), and
|
|
633
|
-
* mixing them makes "how many renewals are due" unanswerable.
|
|
634
|
-
* 2. **Open-ended grants are excluded.** `accessExpiresAt: null` means access
|
|
635
|
-
* does not lapse, so such a member never belongs on a renewal list.
|
|
636
|
-
*
|
|
637
|
-
* The `$ne: null` below is EXPLICIT, not load-bearing: a `$gte`/`$lte` date
|
|
638
|
-
* comparison already excludes `null` in MongoDB, so removing it changes
|
|
639
|
-
* nothing today. It is kept because the exclusion is a domain decision that
|
|
640
|
-
* should be readable at the filter rather than inferred from BSON comparison
|
|
641
|
-
* order — and because a future sentinel value (a far-future date standing in
|
|
642
|
-
* for "lifetime") would satisfy the range and silently reappear.
|
|
643
|
-
*
|
|
644
|
-
* An earlier draft of this docblock claimed the guard was what kept those
|
|
645
|
-
* rows out. Falsifying the filter disproved it; the claim is corrected here
|
|
646
|
-
* rather than left as a rationale that does not hold.
|
|
647
|
-
* 3. **The range is a CALENDAR range**, resolved against this repository's own
|
|
648
|
-
* business zone. "Expiring this month" is a business-month question; built
|
|
649
|
-
* from `Date.UTC` it disagrees with the filing month at both ends by the
|
|
650
|
-
* zone offset — six hours in Asia/Dhaka — so the first and last day of every
|
|
651
|
-
* window silently gain or lose members.
|
|
652
|
-
*
|
|
653
|
-
* ## Rows, not a count, and bounded
|
|
654
|
-
*
|
|
655
|
-
* A worklist is only useful as rows — the point is who to call. But it is
|
|
656
|
-
* paginated through the inherited `getAll`, so tenancy, soft-delete and the
|
|
657
|
-
* limit all apply; an unbounded list on an operator-facing screen is a
|
|
658
|
-
* self-inflicted load problem.
|
|
659
|
-
*
|
|
660
|
-
* Read-only: this never transitions anything. `expireDue` is the sweep that
|
|
661
|
-
* flips a lapsed grant to `expired`, and the two must not be confused — asking
|
|
662
|
-
* "who is about to lapse" must never cause a lapse.
|
|
542
|
+
* The RENEWAL WORKLIST — live (active AND, by default, suspended) grants whose window closes
|
|
543
|
+
* inside a calendar range, soonest first. Lifetime grants are excluded. Read-only.
|
|
663
544
|
*/
|
|
664
545
|
expiringBetween(range: ExpiryWindow, options?: {
|
|
665
|
-
/** Narrow to one product/plan. */
|
|
666
546
|
resourceType?: string | undefined;
|
|
667
547
|
resourceRef?: string | undefined;
|
|
668
|
-
/** Narrow to one population (`'Party'`, `'GymMember'`). */
|
|
669
548
|
subjectModel?: string | undefined;
|
|
670
549
|
scopeKey?: string | undefined;
|
|
671
|
-
/**
|
|
672
|
-
* Include frozen memberships. Default TRUE — see decision (1). Pass `false`
|
|
673
|
-
* only when the caller genuinely means "renewable right now".
|
|
674
|
-
*/
|
|
550
|
+
/** Include frozen memberships. Default TRUE — a suspended grant still lapses. */
|
|
675
551
|
includeSuspended?: boolean | undefined;
|
|
676
552
|
limit?: number | undefined;
|
|
677
553
|
page?: number | undefined;
|
|
678
554
|
}, ctx?: AccessContext): Promise<OffsetPaginationResult<EntitlementDocument>>;
|
|
679
555
|
/**
|
|
680
|
-
* CHURN — grants that lapsed in a
|
|
681
|
-
*
|
|
682
|
-
*
|
|
683
|
-
*
|
|
684
|
-
* Three things get called churn, and they give different numbers from the same
|
|
685
|
-
* data:
|
|
686
|
-
*
|
|
687
|
-
* | | counts | why not here |
|
|
688
|
-
* |---|---|---|
|
|
689
|
-
* | snapshot | active last period minus active this period | needs historical actives, which current rows cannot reconstruct |
|
|
690
|
-
* | cohort retention | of those who joined in M, how many at M+n | a different question (a retention curve), not "who did we lose" |
|
|
691
|
-
* | **lapsed-not-renewed** | expired in the window with no live grant inside grace | **this one** |
|
|
692
|
-
*
|
|
693
|
-
* The third, because {@link ENTITLEMENT_MACHINE} makes `expired -> active`
|
|
694
|
-
* LEGAL: a renewal restarts the window, so `expired` is not terminal and an
|
|
695
|
-
* expired grant is not by itself a loss. People renew late. A metric that counts
|
|
696
|
-
* them as churned reports losses that already walked back in, and an operator
|
|
697
|
-
* learns to distrust it.
|
|
698
|
-
*
|
|
699
|
-
* ## Why this needs no fact projection
|
|
700
|
-
*
|
|
701
|
-
* Expiry is a state TRANSITION, never a TTL-delete — the row survives (see
|
|
702
|
-
* `entitlement-status.enum.ts`: terminal states free the live-uniqueness slot,
|
|
703
|
-
* they do not remove history). So both sides of the question are in live data
|
|
704
|
-
* and this is a self-join.
|
|
705
|
-
*
|
|
706
|
-
* The historical ACTIVE COUNT is the part that genuinely needs a projection
|
|
707
|
-
* ("how many were active on 1 March" is not derivable from current rows). That
|
|
708
|
-
* is a separate build; conflating the two is what made this look bigger than it
|
|
709
|
-
* is.
|
|
710
|
-
*
|
|
711
|
-
* ## What counts as renewed
|
|
712
|
-
*
|
|
713
|
-
* A live grant (`active` or `suspended`) for the SAME subject and resource,
|
|
714
|
-
* granted no later than `lapse + graceDays`, whose own window outlasts the lapse
|
|
715
|
-
* (or never ends).
|
|
716
|
-
*
|
|
717
|
-
* Deliberately NOT "granted after the lapse": a member who pays early renews
|
|
718
|
-
* BEFORE expiry, so requiring the later date would count the most diligent
|
|
719
|
-
* members as churned.
|
|
720
|
-
*
|
|
721
|
-
* ## What is excluded from the lapse population
|
|
722
|
-
*
|
|
723
|
-
* `revoked` and `refunded` are terminal by decision — an admin pull, a dispute,
|
|
724
|
-
* a chargeback. Real losses, but not FAILURES TO RENEW, and folding them in
|
|
725
|
-
* makes the number unactionable: you cannot win back someone you ejected.
|
|
556
|
+
* CHURN — grants that lapsed (`expired`) in a calendar range with no live replacement for the
|
|
557
|
+
* same subject × resource granted within `graceDays` of the lapse. Revoked / refunded grants
|
|
558
|
+
* are not failures to renew and are excluded. `unsettledDays > 0` means the figure can still
|
|
559
|
+
* fall as late renewals land.
|
|
726
560
|
*/
|
|
727
561
|
churnBetween(range: ExpiryWindow, options?: {
|
|
728
|
-
/**
|
|
729
|
-
* Days after the lapse in which a renewal still counts. Defaults to
|
|
730
|
-
* {@link DEFAULT_CHURN_GRACE_DAYS}.
|
|
731
|
-
*/
|
|
562
|
+
/** Days after the lapse in which a renewal still counts. Default {@link DEFAULT_CHURN_GRACE_DAYS}. */
|
|
732
563
|
graceDays?: number | undefined;
|
|
733
564
|
resourceType?: string | undefined;
|
|
734
565
|
resourceRef?: string | undefined;
|
|
735
566
|
subjectModel?: string | undefined;
|
|
736
567
|
scopeKey?: string | undefined;
|
|
737
|
-
/** Injectable clock, for {@link unsettledDays}. Tests pin it. */
|
|
738
568
|
now?: Date | undefined;
|
|
739
569
|
}, ctx?: AccessContext): Promise<{
|
|
740
570
|
lapsed: number;
|
|
@@ -743,28 +573,11 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
743
573
|
graceDays: number;
|
|
744
574
|
unsettledDays: number;
|
|
745
575
|
}>;
|
|
746
|
-
/**
|
|
747
|
-
* Resolve an {@link ExpiryWindow} to instants using THIS repository's business
|
|
748
|
-
* zone.
|
|
749
|
-
*
|
|
750
|
-
* Civil dates are the preferred form because a period is a calendar span;
|
|
751
|
-
* instants are accepted so a caller that already holds them (a cron with a
|
|
752
|
-
* computed cutoff) is not forced to round-trip through strings. A MIXED pair is
|
|
753
|
-
* refused rather than guessed — `{ from: '2026-08-01', to: someDate }` has no
|
|
754
|
-
* single obvious meaning, and silently picking one produces a window nobody
|
|
755
|
-
* asked for.
|
|
756
|
-
*/
|
|
576
|
+
/** Resolve an {@link ExpiryWindow} in the business zone. A mixed civil/instant pair throws. */
|
|
757
577
|
private resolveExpiryWindow;
|
|
758
578
|
/**
|
|
759
|
-
* Sweep grants
|
|
760
|
-
* `access:expired
|
|
761
|
-
* "model expiry as a state transition" rule, not a TTL-delete. The CAS
|
|
762
|
-
* `where` re-guards the window so a concurrent `extend` is never clobbered.
|
|
763
|
-
* Drive it from a host cron. Returns how many were swept.
|
|
764
|
-
*
|
|
765
|
-
* Read-time `check()` already denies a lapsed grant before the sweep runs —
|
|
766
|
-
* this pass exists to fire the event and make `status: 'expired'` queryable,
|
|
767
|
-
* not to enforce the gate.
|
|
579
|
+
* Sweep lapsed grants: CAS active → expired (window re-guarded in the filter) and emit
|
|
580
|
+
* `access:expired`, one transaction per row. The gate never waits for this — it derives expiry.
|
|
768
581
|
*/
|
|
769
582
|
expireDue(options?: {
|
|
770
583
|
now?: Date | undefined;
|
|
@@ -772,23 +585,17 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
772
585
|
}, ctx?: AccessContext): Promise<{
|
|
773
586
|
swept: number;
|
|
774
587
|
}>;
|
|
775
|
-
/**
|
|
776
|
-
* Refund cascade — when an order/transaction is reversed, mark every live
|
|
777
|
-
* grant it produced as refunded. Looks up by the polymorphic origin ref.
|
|
778
|
-
*/
|
|
588
|
+
/** Refund every live grant one origin produced. Drained until empty. */
|
|
779
589
|
refundByOrigin(originModel: string, originRef: string, options?: {
|
|
780
590
|
reason?: string | undefined;
|
|
781
591
|
}, ctx?: AccessContext): Promise<{
|
|
782
592
|
refunded: number;
|
|
783
593
|
}>;
|
|
784
594
|
/**
|
|
785
|
-
* Grant idempotently PER ORIGIN.
|
|
786
|
-
*
|
|
787
|
-
*
|
|
788
|
-
*
|
|
789
|
-
* wrong for a redelivered event: an at-least-once bus would silently extend a
|
|
790
|
-
* membership every time it replayed. Keying on the origin separates the two —
|
|
791
|
-
* the same order never grants twice, a new order still renews.
|
|
595
|
+
* Grant idempotently PER ORIGIN + RESOURCE. A redelivered event finds its origin in
|
|
596
|
+
* `appliedOrigins` — across EVERY status, so a refunded or revoked grant is never resurrected
|
|
597
|
+
* by a replay — and returns it with `created: false`. A per-cycle renewal therefore needs a
|
|
598
|
+
* cycle-scoped origin ref.
|
|
792
599
|
*/
|
|
793
600
|
grantByOrigin(input: GrantInput & {
|
|
794
601
|
originModel: string;
|
|
@@ -798,14 +605,8 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
798
605
|
created: boolean;
|
|
799
606
|
}>;
|
|
800
607
|
/**
|
|
801
|
-
* Move every live grant from one origin to `suspended` / `active` / `revoked`.
|
|
802
|
-
*
|
|
803
|
-
* Mirrors `refundByOrigin`: a CAS `claim` per row so a concurrent human action
|
|
804
|
-
* cannot be clobbered, and the lifecycle event emitted only when the claim won
|
|
805
|
-
* (so a redelivery emits nothing).
|
|
806
|
-
*
|
|
807
|
-
* `resume` deliberately only lifts SUSPENDED grants — resuming an expired or
|
|
808
|
-
* revoked one would resurrect access the domain already ended.
|
|
608
|
+
* Move every live grant from one origin to `suspended` / `active` / `revoked`. `resume` lifts
|
|
609
|
+
* only SUSPENDED grants. Already-there rows are excluded in the query; drained until empty.
|
|
809
610
|
*/
|
|
810
611
|
setStateByOrigin(originModel: string, originRef: string, effect: 'suspend' | 'resume' | 'revoke', options?: {
|
|
811
612
|
reason?: string | undefined;
|
|
@@ -813,101 +614,56 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
813
614
|
changed: number;
|
|
814
615
|
}>;
|
|
815
616
|
/**
|
|
816
|
-
* Push the expiry of every live grant from one origin.
|
|
817
|
-
*
|
|
818
|
-
*
|
|
819
|
-
* value: setting the same expiry twice changes nothing, so a redelivery is safe
|
|
820
|
-
* without needing to remember it was seen.
|
|
617
|
+
* Push the expiry of every live grant from one origin — idempotent by value. `matched` is the
|
|
618
|
+
* live-grant count BEFORE the at-target filter: `changed: 0, matched: 0` is a wrong origin (a
|
|
619
|
+
* renewal that bought no access), `changed: 0, matched > 0` a replay.
|
|
821
620
|
*/
|
|
822
621
|
extendByOrigin(originModel: string, originRef: string, accessExpiresAt: Date | null, ctx?: AccessContext): Promise<{
|
|
823
622
|
changed: number;
|
|
824
623
|
matched: number;
|
|
825
624
|
}>;
|
|
826
|
-
/**
|
|
827
|
-
listForSubject(
|
|
625
|
+
/** One subject's grants, newest first ("my access"). Filtered in the query, capped at 200. */
|
|
626
|
+
listForSubject(subject: AccessSubject, options: {
|
|
627
|
+
resourceType?: string | undefined;
|
|
628
|
+
liveOnly?: boolean | undefined;
|
|
629
|
+
limit?: number | undefined;
|
|
630
|
+
page?: number | undefined;
|
|
631
|
+
}, ctx: AccessContext): Promise<OffsetPaginationResult<EntitlementDocument>>;
|
|
632
|
+
/** The consumption ledger of one grant, newest first. */
|
|
633
|
+
listConsumptions(entitlementId: string, options: {
|
|
634
|
+
limit?: number | undefined;
|
|
635
|
+
}, ctx: AccessContext): Promise<EntitlementConsumptionDocument[]>;
|
|
636
|
+
/**
|
|
637
|
+
* Reconcile a subject's entitlements from ONE agreement to a DESIRED SET in one atomic unit:
|
|
638
|
+
* grant the missing, revoke the extra, retain the matches. Idempotent by the diff.
|
|
639
|
+
* ORG-PARTITIONED: each desired item names its target org; the current set is read across
|
|
640
|
+
* orgs. Authority (who may reconcile) is the caller's to check.
|
|
641
|
+
*/
|
|
642
|
+
reconcileEntitlementSet(input: ReconcileEntitlementSetInput, ctx: AccessContext): Promise<ReconcileResult>;
|
|
828
643
|
private transition;
|
|
829
|
-
private transitionInner;
|
|
830
644
|
/**
|
|
831
|
-
*
|
|
832
|
-
*
|
|
833
|
-
* `+statusHistory` overrides the schema's `select: false`. Every mutating path
|
|
834
|
-
* comes through here, and two of them require the log: `transition` appends to it,
|
|
835
|
-
* and `suspend` derives the pause allowance from it. Reading without it would make
|
|
836
|
-
* `transition` overwrite the whole array with a single entry — a silent history
|
|
837
|
-
* wipe that would then under-count every future allowance.
|
|
645
|
+
* The single funnel for every status move: legality from the machine, then ONE CAS that moves
|
|
646
|
+
* status, the `live` mirror and the status-history append together.
|
|
838
647
|
*/
|
|
648
|
+
private transitionInner;
|
|
649
|
+
/** Load a grant for a WRITE, WITH its status history (`select: false` otherwise). */
|
|
839
650
|
private load;
|
|
840
|
-
/** Resolve the live (active
|
|
651
|
+
/** Resolve the live (active preferred over suspended) grant for a target, or null. */
|
|
841
652
|
private findLive;
|
|
842
653
|
private targetLabel;
|
|
843
654
|
private emitLifecycle;
|
|
844
655
|
/**
|
|
845
656
|
* Run a mutation + its event emission as ONE atomic unit.
|
|
846
657
|
*
|
|
847
|
-
*
|
|
848
|
-
*
|
|
849
|
-
*
|
|
850
|
-
*
|
|
851
|
-
*
|
|
852
|
-
*
|
|
853
|
-
* most dangerous direction:
|
|
854
|
-
*
|
|
855
|
-
* - `consume()` is atomic but NOT idempotent — a retry spends the units AGAIN.
|
|
856
|
-
* - `resume()` retried hits an invalid transition (already active) and never
|
|
857
|
-
* re-emits, so the credential-sync subscriber never learns the member is back.
|
|
858
|
-
* - `revoke()` / `refund()` retried hit a terminal status — same lost event,
|
|
859
|
-
* and this one means a door stays open after a refund.
|
|
860
|
-
*
|
|
861
|
-
* So the fix is a real transaction, not better wording. The mutation and the
|
|
862
|
-
* outbox row now commit or roll back together, which is what the
|
|
863
|
-
* transactional-outbox pattern actually requires.
|
|
864
|
-
*
|
|
865
|
-
* ## Two pass-through cases, both deliberate
|
|
866
|
-
*
|
|
867
|
-
* - **No outbox** — there is no second write to be atomic WITH, and taxing
|
|
868
|
-
* every door-tap check with a session would buy nothing.
|
|
869
|
-
* - **Caller supplied `ctx.session`** — the host owns a wider unit of work;
|
|
870
|
-
* opening our own here would either nest or silently commit a slice of
|
|
871
|
-
* theirs. Passing through is also what makes this safe to apply at several
|
|
872
|
-
* layers: an outer `resume` wraps once, and the inner `transition` sees the
|
|
873
|
-
* session and does not re-wrap.
|
|
874
|
-
*
|
|
875
|
-
* Requires a replica set (this deployment already mandates one for POS and
|
|
876
|
-
* muster). A single-node mongod without one cannot start a session, which
|
|
877
|
-
* surfaces at the first write rather than silently degrading.
|
|
878
|
-
*/
|
|
879
|
-
/**
|
|
880
|
-
* Reconcile a subject's entitlements from ONE origin (typically an
|
|
881
|
-
* `Agreement`) to a DESIRED SET — the primitive a plan change drives. It
|
|
882
|
-
* computes the diff against the live entitlements currently projected from
|
|
883
|
-
* that origin and, in ONE atomic unit (transactional outbox), GRANTS the
|
|
884
|
-
* missing, REVOKES the extra, and RETAINS the matches. Idempotent: re-running
|
|
885
|
-
* the same desired set is a no-op (grant-by-origin dedupes; only live rows are
|
|
886
|
-
* revoked).
|
|
887
|
-
*
|
|
888
|
-
* ORG-PARTITIONED: each desired item carries its target `organizationId`, and
|
|
889
|
-
* the current set is discovered across orgs (a downgrade may drop a right in a
|
|
890
|
-
* different branch). Every write runs under an org-scoped ctx that reuses the
|
|
891
|
-
* single session, so a Gold→floor+pool bundle across branches still applies or
|
|
892
|
-
* rolls back as a unit. Authority (who may reconcile) is the caller's to
|
|
893
|
-
* check; a caller-supplied org is only ever a WRITE target, never trusted as
|
|
894
|
-
* identity.
|
|
658
|
+
* - No outbox → pass through (nothing to be atomic with).
|
|
659
|
+
* - The outbox must declare `transactionalSave`, or this throws.
|
|
660
|
+
* - A caller session must be IN a transaction (`inTransaction()`), or this throws — a bare
|
|
661
|
+
* session buys no atomicity.
|
|
662
|
+
* - `allowNonTransactional` (dev only) degrades to best effort, warning once.
|
|
663
|
+
* - Otherwise opens its own transaction via mongokit's `withTransaction` (no fallback).
|
|
895
664
|
*/
|
|
896
|
-
reconcileEntitlementSet(input: ReconcileEntitlementSetInput, ctx: AccessContext): Promise<ReconcileResult>;
|
|
897
665
|
private atomically;
|
|
898
|
-
/**
|
|
899
|
-
* Assert the event path is usable BEFORE any mutation.
|
|
900
|
-
*
|
|
901
|
-
* `emitDomainEvent` throws `UnmanagedSessionError` when a host passes a
|
|
902
|
-
* session with no outbox — but every verb emits AFTER writing, so the guard
|
|
903
|
-
* used to fire with the entitlement already persisted (review #6): the
|
|
904
|
-
* caller saw a failure while the grant quietly existed, and outside a
|
|
905
|
-
* transaction nothing rolled it back. The same condition checked here turns
|
|
906
|
-
* that into a clean refusal with nothing written.
|
|
907
|
-
*
|
|
908
|
-
* Mirrors dispatch exactly: no channels at all → nothing will emit, nothing
|
|
909
|
-
* to guard; session + outbox → the legal relay-only mode.
|
|
910
|
-
*/
|
|
666
|
+
/** A session with no outbox has no correct event path — refuse BEFORE any write. */
|
|
911
667
|
private preflightDispatch;
|
|
912
668
|
private get channels();
|
|
913
669
|
}
|
|
@@ -937,6 +693,13 @@ interface AccessShape {
|
|
|
937
693
|
* Maps to mongokit's `replace` policy, which itself throws under `NODE_ENV=production`.
|
|
938
694
|
*/
|
|
939
695
|
forceRecreate?: boolean | undefined;
|
|
696
|
+
/**
|
|
697
|
+
* Indexes the HOST needs on the entitlement collection that this package cannot know
|
|
698
|
+
* about (a roster sort, a cross-tenant sweep). `scope: 'tenant'` (default) is led by
|
|
699
|
+
* the tenant field like the package's own; `scope: 'global'` is kept as written and
|
|
700
|
+
* must be paired with a `bypassTenant` read. See `@classytic/mongokit/tenant`.
|
|
701
|
+
*/
|
|
702
|
+
indexes?: readonly IndexDeclaration[] | undefined;
|
|
940
703
|
}
|
|
941
704
|
/**
|
|
942
705
|
* BIND-time runtime collaborators — the live connection is the first `bind` arg; these are
|
|
@@ -946,22 +709,12 @@ interface AccessShape {
|
|
|
946
709
|
interface AccessRuntime {
|
|
947
710
|
eventTransport?: EventTransport | undefined;
|
|
948
711
|
/**
|
|
949
|
-
* The BUSINESS timezone, IANA (`'Asia/Dhaka'`).
|
|
950
|
-
*
|
|
951
|
-
* The authority for resolving a CALENDAR range into instants — the renewal
|
|
952
|
-
* worklist asks "expiring this month", and a month built from `Date.UTC`
|
|
953
|
-
* disagrees with the business month at both ends by the zone offset. Six hours
|
|
954
|
-
* in Dhaka, so the first and last day of every window silently gain or lose
|
|
955
|
-
* members while the list still looks reasonable.
|
|
956
|
-
*
|
|
957
|
-
* Deliberately IANA rather than the `offsetMinutes` the suspension paths take
|
|
958
|
-
* per call: a fixed offset cannot be DST-correct, so in a DST zone it is wrong
|
|
959
|
-
* for part of the year.
|
|
960
|
-
*
|
|
961
|
-
* Defaults to `'UTC'` — a deployment that never sets one behaves as it does
|
|
962
|
-
* today.
|
|
712
|
+
* The BUSINESS timezone, IANA (`'Asia/Dhaka'`). Calendar ranges (renewal worklist, churn) and
|
|
713
|
+
* pause-allowance day boundaries resolve against it. Defaults to `'UTC'`.
|
|
963
714
|
*/
|
|
964
715
|
timezone?: string | undefined;
|
|
716
|
+
/** The clock every decision and timestamp reads. Default `() => new Date()`; tests pin it. */
|
|
717
|
+
clock?: (() => Date) | undefined;
|
|
965
718
|
outbox?: OutboxStore | undefined;
|
|
966
719
|
logger?: AccessLogger | undefined;
|
|
967
720
|
/**
|
|
@@ -999,6 +752,8 @@ interface ResolvedAccessConfig {
|
|
|
999
752
|
readonly tenant: ResolvedTenantConfig;
|
|
1000
753
|
readonly autoIndex: boolean | Partial<Record<AccessModelName, boolean>> | undefined;
|
|
1001
754
|
readonly collectionPrefix: string | undefined;
|
|
755
|
+
/** The host's extra index declarations, as given. */
|
|
756
|
+
readonly indexes: readonly IndexDeclaration[] | undefined;
|
|
1002
757
|
}
|
|
1003
758
|
interface AccessEngine {
|
|
1004
759
|
readonly config: ResolvedAccessConfig;
|
|
@@ -1093,8 +848,8 @@ declare class InvalidConsumeAmountError extends AccessError {
|
|
|
1093
848
|
* state conflicts with the spend.
|
|
1094
849
|
*/
|
|
1095
850
|
declare class EntitlementNotUsableError extends AccessError {
|
|
1096
|
-
readonly reason:
|
|
1097
|
-
constructor(id: string, reason:
|
|
851
|
+
readonly reason: AccessReason;
|
|
852
|
+
constructor(id: string, reason: AccessReason);
|
|
1098
853
|
}
|
|
1099
854
|
/**
|
|
1100
855
|
* A caller passed `ctx.session` that is NOT inside an active transaction.
|
|
@@ -1152,6 +907,40 @@ declare class AccessCapabilityError extends AccessError {
|
|
|
1152
907
|
declare class InvalidExpiryWindowError extends AccessError {
|
|
1153
908
|
constructor(message: string);
|
|
1154
909
|
}
|
|
910
|
+
/**
|
|
911
|
+
* A grant with no provenance. Money-backed sources (`purchase`, `subscription`) need the
|
|
912
|
+
* paying document (`originModel` + `originRef`); every other source needs that or an actor
|
|
913
|
+
* (`ctx.actorId`). A right nobody can trace is a right nobody can reverse.
|
|
914
|
+
*/
|
|
915
|
+
declare class GrantProvenanceRequiredError extends AccessError {
|
|
916
|
+
constructor(source: string, needs: string);
|
|
917
|
+
}
|
|
918
|
+
/** A consumption key reused with a different amount — a client bug, never a replay. */
|
|
919
|
+
declare class ConsumptionKeyConflictError extends AccessError {
|
|
920
|
+
constructor(key: string, appliedAmount: number, requestedAmount: number);
|
|
921
|
+
}
|
|
922
|
+
/** A consume() with no consumption key, or one that is blank. */
|
|
923
|
+
declare class ConsumptionKeyRequiredError extends AccessError {
|
|
924
|
+
constructor();
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* An extend() that would not extend: no target given, `addMs` on a lifetime grant, a non-positive
|
|
928
|
+
* `addMs`, or an absolute expiry earlier than the current one. Shortening is revoke + re-grant.
|
|
929
|
+
*/
|
|
930
|
+
declare class InvalidExtensionError extends AccessError {
|
|
931
|
+
constructor(message: string);
|
|
932
|
+
}
|
|
933
|
+
/** A batch check that is empty, too large, or names a capability twice. */
|
|
934
|
+
declare class InvalidCheckRequestError extends AccessError {
|
|
935
|
+
constructor(message: string);
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Two in-flight transactions raced on one consumption key. Retry: the retry finds the winner's
|
|
939
|
+
* key and returns it as a replay — nothing is spent twice.
|
|
940
|
+
*/
|
|
941
|
+
declare class ConsumptionInFlightError extends AccessError {
|
|
942
|
+
constructor(key: string);
|
|
943
|
+
}
|
|
1155
944
|
//#endregion
|
|
1156
945
|
//#region src/events/in-process-bus.d.ts
|
|
1157
946
|
type InProcessAccessBusOptions = InProcessEventBusOptions;
|
|
@@ -1159,4 +948,4 @@ declare class InProcessAccessBus extends InProcessEventBus {
|
|
|
1159
948
|
constructor(options?: InProcessAccessBusOptions);
|
|
1160
949
|
}
|
|
1161
950
|
//#endregion
|
|
1162
|
-
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 };
|
|
951
|
+
export { ACCESS_EVENTS, ACCESS_REASONS, type AccessBlueprint, type AccessCapability, 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 AccessSubject, type AccessTenantOptions, type CheckResult, type ConsumeInput, type ConsumeResult, ConsumptionInFlightError, ConsumptionKeyConflictError, ConsumptionKeyRequiredError, DEFAULT_CHURN_GRACE_DAYS, type DefineAccessModelsConfig, ENTITLEMENT_MACHINE, ENTITLEMENT_STATUS, ENTITLEMENT_STATUS_VALUES, ENTITLEMENT_TRANSITIONS, type EntitlementConsumptionDocument, type EntitlementDesiredItem, type EntitlementDocument, type EntitlementKey, EntitlementNotFoundError, EntitlementNotUsableError, EntitlementRepository, type EntitlementRepositoryConfig, type EntitlementSource, type EntitlementStatus, type EntitlementTarget, type EntitlementUsage, type ExpiryWindow, type GrantInput, GrantProvenanceRequiredError, InProcessAccessBus, InvalidCheckRequestError, InvalidConsumeAmountError, InvalidEntitlementTransitionError, InvalidExpiryWindowError, InvalidExtensionError, LIVE_STATUSES, MAX_CAPABILITIES_PER_CHECK, QuotaExhaustedError, type ReconcileEntitlementSetInput, type ReconcileResult, type ResolvedAccessConfig, SessionNotInTransactionError, SuspensionRefusedError, UnmanagedSessionError, VersionMismatchError, accessEventDefinitions, canEntitlementTransition, defineAccess, defineAccessModels, evaluateAccess, hasAccess, isEntitlementStatus, isTerminalEntitlementStatus };
|