@classytic/access 0.3.0 → 0.4.1
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 +3 -74
- 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-DarRYj3Y.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 +203 -438
- package/dist/index.mjs +598 -1133
- package/dist/schemas/entitlement.d.mts +16 -10
- package/dist/schemas/entitlement.mjs +19 -14
- package/llms.txt +27 -0
- package/package.json +18 -11
- package/skills/access/SKILL.md +116 -0
- package/skills/access/references/events-errors.md +46 -0
- package/skills/access/references/repository.md +72 -0
- package/skills/access/references/wiring.md +60 -0
- 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,9 +1,9 @@
|
|
|
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-DarRYj3Y.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
8
|
import { IndexDeclaration, IndexDeclaration as IndexDeclaration$1 } from "@classytic/mongokit/tenant";
|
|
9
9
|
import { StatusHistory } from "@classytic/primitives/status-history";
|
|
@@ -14,6 +14,20 @@ import { OffsetPaginationResult } from "@classytic/repo-core/pagination";
|
|
|
14
14
|
import { OperationContext } from "@classytic/primitives/context";
|
|
15
15
|
import { RetryPolicy } from "@classytic/repo-core/repository";
|
|
16
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
|
|
17
31
|
//#region src/domain/enums/entitlement-status.enum.d.ts
|
|
18
32
|
/**
|
|
19
33
|
* Entitlement lifecycle status.
|
|
@@ -244,9 +258,11 @@ interface EntitlementDocument extends Document {
|
|
|
244
258
|
}
|
|
245
259
|
//#endregion
|
|
246
260
|
//#region src/models/create-models.d.ts
|
|
247
|
-
type AccessModelName = 'Entitlement';
|
|
261
|
+
type AccessModelName = 'Entitlement' | 'EntitlementConsumption';
|
|
248
262
|
interface AccessModels {
|
|
249
263
|
Entitlement: Model<EntitlementDocument>;
|
|
264
|
+
/** The consumption ledger — one row per idempotent `consume()`. */
|
|
265
|
+
EntitlementConsumption: Model<EntitlementConsumptionDocument>;
|
|
250
266
|
}
|
|
251
267
|
interface DefineAccessModelsConfig {
|
|
252
268
|
/** Resolved tenant shape — `defineAccess` resolves it once (pure) and passes it here. */
|
|
@@ -287,6 +303,8 @@ interface AccessContext extends OperationContext {
|
|
|
287
303
|
organizationId?: string;
|
|
288
304
|
actorId?: string;
|
|
289
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;
|
|
290
308
|
/** Cooperative cancellation — threaded into every repo call. */
|
|
291
309
|
signal?: AbortSignal | undefined;
|
|
292
310
|
/** Driver round-trip retry policy — threaded into every repo call. */
|
|
@@ -294,7 +312,27 @@ interface AccessContext extends OperationContext {
|
|
|
294
312
|
}
|
|
295
313
|
//#endregion
|
|
296
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;
|
|
297
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;
|
|
298
336
|
/** One desired entitlement in a reconcile set — carries its target org. */
|
|
299
337
|
interface EntitlementDesiredItem {
|
|
300
338
|
resourceType: string;
|
|
@@ -305,29 +343,15 @@ interface EntitlementDesiredItem {
|
|
|
305
343
|
organizationId: string;
|
|
306
344
|
}
|
|
307
345
|
interface ReconcileEntitlementSetInput {
|
|
308
|
-
subject:
|
|
309
|
-
subjectModel: string;
|
|
310
|
-
subjectRef: string;
|
|
311
|
-
};
|
|
346
|
+
subject: AccessSubject;
|
|
312
347
|
/** The origin whose projected entitlements are reconciled (an Agreement id). */
|
|
313
348
|
agreementRef: string;
|
|
314
349
|
desired: readonly EntitlementDesiredItem[];
|
|
315
350
|
/** Grant source for newly-created rights. Default `'subscription'`. */
|
|
316
351
|
source?: EntitlementSource | undefined;
|
|
317
352
|
/**
|
|
318
|
-
*
|
|
319
|
-
*
|
|
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").
|
|
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.
|
|
331
355
|
*/
|
|
332
356
|
mutationRef?: string | undefined;
|
|
333
357
|
}
|
|
@@ -344,6 +368,10 @@ interface GrantInput {
|
|
|
344
368
|
resourceType: string;
|
|
345
369
|
/** Sub-scope inside the resource. Defaults to '' (the whole resource). */
|
|
346
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
|
+
*/
|
|
347
375
|
source: EntitlementSource;
|
|
348
376
|
/** Access opens at this instant (scheduled / early access). */
|
|
349
377
|
notBefore?: Date | null | undefined;
|
|
@@ -356,66 +384,36 @@ interface GrantInput {
|
|
|
356
384
|
amount?: number | null | undefined;
|
|
357
385
|
currency?: string | undefined;
|
|
358
386
|
metadata?: Record<string, unknown> | undefined;
|
|
359
|
-
/**
|
|
360
|
-
* When a live grant already exists, refresh its window/quota (a re-purchase
|
|
361
|
-
* restarts the clock). Default true. Set false for pure idempotency.
|
|
362
|
-
*/
|
|
387
|
+
/** When a live grant already exists, refresh it. Default true; `false` = pure idempotency. */
|
|
363
388
|
renew?: boolean | undefined;
|
|
364
389
|
/**
|
|
365
|
-
*
|
|
366
|
-
*
|
|
367
|
-
*
|
|
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.
|
|
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'`.
|
|
388
393
|
*/
|
|
389
394
|
quotaMode?: 'reset' | 'add' | undefined;
|
|
390
395
|
}
|
|
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
|
-
*/
|
|
400
|
-
type EntitlementTarget = {
|
|
401
|
-
id: string;
|
|
402
|
-
} | {
|
|
403
|
-
subjectRef: string;
|
|
404
|
-
subjectModel?: string | undefined;
|
|
405
|
-
resourceRef: string;
|
|
406
|
-
resourceType?: string | undefined;
|
|
407
|
-
scopeKey?: string | undefined;
|
|
408
|
-
};
|
|
409
396
|
interface CheckResult extends AccessDecision {
|
|
410
397
|
entitlement: EntitlementDocument | null;
|
|
411
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
|
+
}
|
|
412
414
|
/**
|
|
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.
|
|
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.
|
|
419
417
|
*/
|
|
420
418
|
interface ExpiryWindow {
|
|
421
419
|
from: Date | string;
|
|
@@ -423,6 +421,8 @@ interface ExpiryWindow {
|
|
|
423
421
|
}
|
|
424
422
|
interface EntitlementRepositoryConfig {
|
|
425
423
|
model: Model<EntitlementDocument>;
|
|
424
|
+
/** The consumption ledger — REQUIRED: `consume()` is idempotent only through it. */
|
|
425
|
+
consumptions: Repository<EntitlementConsumptionDocument>;
|
|
426
426
|
plugins?: PluginType[];
|
|
427
427
|
eventTransport?: EventTransport | undefined;
|
|
428
428
|
outbox?: OutboxStore | undefined;
|
|
@@ -432,148 +432,77 @@ interface EntitlementRepositoryConfig {
|
|
|
432
432
|
} | undefined;
|
|
433
433
|
/** Standalone-mongod escape — see `AccessRuntime.allowNonTransactional`. Opt-IN. */
|
|
434
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
|
-
*/
|
|
435
|
+
/** IANA business zone for calendar ranges and pause-allowance days. Default `'UTC'`. */
|
|
448
436
|
timezone?: string | undefined;
|
|
437
|
+
/** The clock. Default `() => new Date()`. */
|
|
438
|
+
clock?: (() => Date) | undefined;
|
|
449
439
|
}
|
|
450
440
|
declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
441
|
+
private readonly consumptions;
|
|
451
442
|
private readonly eventTransport;
|
|
452
443
|
private readonly outbox;
|
|
453
444
|
private readonly pkgLogger;
|
|
454
445
|
private readonly allowNonTransactional;
|
|
455
|
-
/** IANA business zone — see `EntitlementRepositoryConfig.timezone`. */
|
|
456
446
|
private readonly timezone;
|
|
457
|
-
|
|
447
|
+
private readonly clock;
|
|
448
|
+
/** Warn ONCE per repository, not once per grant. */
|
|
458
449
|
private warnedNonTransactional;
|
|
459
450
|
constructor(config: EntitlementRepositoryConfig);
|
|
451
|
+
/** The current instant from the injected clock. A clock returning an invalid date throws. */
|
|
452
|
+
now(): Date;
|
|
460
453
|
/**
|
|
461
|
-
* Grant access. Idempotent per (subject, resource, scope) live grant via
|
|
462
|
-
*
|
|
463
|
-
* the window
|
|
464
|
-
* `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.
|
|
465
458
|
*/
|
|
466
459
|
grant(input: GrantInput, ctx: AccessContext): Promise<EntitlementDocument>;
|
|
467
460
|
private grantInner;
|
|
468
461
|
/**
|
|
469
|
-
* Decide access RIGHT NOW. Read-only
|
|
470
|
-
*
|
|
471
|
-
* 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.
|
|
472
464
|
*/
|
|
473
465
|
check(target: EntitlementTarget, ctx: AccessContext): Promise<CheckResult>;
|
|
474
466
|
/**
|
|
475
|
-
*
|
|
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.
|
|
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.
|
|
489
469
|
*/
|
|
490
|
-
|
|
491
|
-
subjectModel: string;
|
|
492
|
-
subjectRef: string;
|
|
493
|
-
resourceType: string;
|
|
494
|
-
resourceRef: string;
|
|
495
|
-
scopeKey?: string | undefined;
|
|
496
|
-
}, ctx: AccessContext): Promise<CheckResult>;
|
|
470
|
+
checkMany(subject: AccessSubject, capabilities: readonly AccessCapability[], ctx: AccessContext): Promise<CheckResult[]>;
|
|
497
471
|
/**
|
|
498
|
-
* Spend
|
|
499
|
-
*
|
|
500
|
-
*
|
|
501
|
-
* is
|
|
502
|
-
* `
|
|
503
|
-
*
|
|
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.
|
|
504
479
|
*/
|
|
505
|
-
consume(target: EntitlementTarget,
|
|
480
|
+
consume(target: EntitlementTarget, input: ConsumeInput, ctx: AccessContext): Promise<ConsumeResult>;
|
|
506
481
|
private consumeInner;
|
|
482
|
+
/** The answer for a key that already spent: same amount → replay; different → conflict. */
|
|
483
|
+
private replayed;
|
|
484
|
+
private notUsable;
|
|
507
485
|
/**
|
|
508
|
-
* Pause access
|
|
509
|
-
*
|
|
510
|
-
*
|
|
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.
|
|
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).
|
|
521
489
|
*/
|
|
522
490
|
suspend(id: string, options?: {
|
|
523
491
|
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
|
-
*/
|
|
492
|
+
/** The pause rulebook. When supplied, `autoResumeAt` / `creditWindowOnResume` are ignored. */
|
|
533
493
|
policy?: SuspensionPolicy | undefined;
|
|
534
494
|
/** Requested end. Omit for open-ended — the allowance then decides. */
|
|
535
495
|
endsAt?: Date | null | undefined;
|
|
536
496
|
/** For the notice check. Defaults to now. */
|
|
537
497
|
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
498
|
autoResumeAt?: Date | null | undefined;
|
|
546
499
|
creditWindowOnResume?: boolean | undefined;
|
|
547
500
|
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
548
501
|
/**
|
|
549
|
-
* Lift a suspension (suspended → active)
|
|
550
|
-
*
|
|
551
|
-
*
|
|
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.
|
|
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.
|
|
577
506
|
*/
|
|
578
507
|
resume(id: string, options?: {
|
|
579
508
|
creditFrozenDays?: boolean | undefined;
|
|
@@ -588,9 +517,10 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
588
517
|
reason?: string | undefined;
|
|
589
518
|
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
590
519
|
/**
|
|
591
|
-
* Extend
|
|
592
|
-
*
|
|
593
|
-
* 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`.
|
|
594
524
|
*/
|
|
595
525
|
extend(id: string, options: {
|
|
596
526
|
accessExpiresAt?: Date | null | undefined;
|
|
@@ -598,26 +528,8 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
598
528
|
}, ctx?: AccessContext): Promise<EntitlementDocument>;
|
|
599
529
|
private extendInner;
|
|
600
530
|
/**
|
|
601
|
-
* Resume suspensions
|
|
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.
|
|
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.
|
|
621
533
|
*/
|
|
622
534
|
autoResumeDue(options?: {
|
|
623
535
|
now?: Date | undefined;
|
|
@@ -627,124 +539,32 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
627
539
|
failed: number;
|
|
628
540
|
}>;
|
|
629
541
|
/**
|
|
630
|
-
* The RENEWAL WORKLIST — grants whose
|
|
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.
|
|
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.
|
|
673
544
|
*/
|
|
674
545
|
expiringBetween(range: ExpiryWindow, options?: {
|
|
675
|
-
/** Narrow to one product/plan. */
|
|
676
546
|
resourceType?: string | undefined;
|
|
677
547
|
resourceRef?: string | undefined;
|
|
678
|
-
/** Narrow to one population (`'Party'`, `'GymMember'`). */
|
|
679
548
|
subjectModel?: string | undefined;
|
|
680
549
|
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
|
-
*/
|
|
550
|
+
/** Include frozen memberships. Default TRUE — a suspended grant still lapses. */
|
|
685
551
|
includeSuspended?: boolean | undefined;
|
|
686
552
|
limit?: number | undefined;
|
|
687
553
|
page?: number | undefined;
|
|
688
554
|
}, ctx?: AccessContext): Promise<OffsetPaginationResult<EntitlementDocument>>;
|
|
689
555
|
/**
|
|
690
|
-
* CHURN — grants that lapsed in a
|
|
691
|
-
*
|
|
692
|
-
*
|
|
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.
|
|
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.
|
|
736
560
|
*/
|
|
737
561
|
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
|
-
*/
|
|
562
|
+
/** Days after the lapse in which a renewal still counts. Default {@link DEFAULT_CHURN_GRACE_DAYS}. */
|
|
742
563
|
graceDays?: number | undefined;
|
|
743
564
|
resourceType?: string | undefined;
|
|
744
565
|
resourceRef?: string | undefined;
|
|
745
566
|
subjectModel?: string | undefined;
|
|
746
567
|
scopeKey?: string | undefined;
|
|
747
|
-
/** Injectable clock, for {@link unsettledDays}. Tests pin it. */
|
|
748
568
|
now?: Date | undefined;
|
|
749
569
|
}, ctx?: AccessContext): Promise<{
|
|
750
570
|
lapsed: number;
|
|
@@ -753,28 +573,11 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
753
573
|
graceDays: number;
|
|
754
574
|
unsettledDays: number;
|
|
755
575
|
}>;
|
|
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
|
-
*/
|
|
576
|
+
/** Resolve an {@link ExpiryWindow} in the business zone. A mixed civil/instant pair throws. */
|
|
767
577
|
private resolveExpiryWindow;
|
|
768
578
|
/**
|
|
769
|
-
* Sweep grants
|
|
770
|
-
* `access:expired
|
|
771
|
-
* "model expiry as a state transition" rule, not a TTL-delete. The CAS
|
|
772
|
-
* `where` re-guards the window so a concurrent `extend` is never clobbered.
|
|
773
|
-
* Drive it from a host cron. Returns how many were swept.
|
|
774
|
-
*
|
|
775
|
-
* Read-time `check()` already denies a lapsed grant before the sweep runs —
|
|
776
|
-
* this pass exists to fire the event and make `status: 'expired'` queryable,
|
|
777
|
-
* 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.
|
|
778
581
|
*/
|
|
779
582
|
expireDue(options?: {
|
|
780
583
|
now?: Date | undefined;
|
|
@@ -782,23 +585,17 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
782
585
|
}, ctx?: AccessContext): Promise<{
|
|
783
586
|
swept: number;
|
|
784
587
|
}>;
|
|
785
|
-
/**
|
|
786
|
-
* Refund cascade — when an order/transaction is reversed, mark every live
|
|
787
|
-
* grant it produced as refunded. Looks up by the polymorphic origin ref.
|
|
788
|
-
*/
|
|
588
|
+
/** Refund every live grant one origin produced. Drained until empty. */
|
|
789
589
|
refundByOrigin(originModel: string, originRef: string, options?: {
|
|
790
590
|
reason?: string | undefined;
|
|
791
591
|
}, ctx?: AccessContext): Promise<{
|
|
792
592
|
refunded: number;
|
|
793
593
|
}>;
|
|
794
594
|
/**
|
|
795
|
-
* Grant idempotently PER ORIGIN.
|
|
796
|
-
*
|
|
797
|
-
*
|
|
798
|
-
*
|
|
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.
|
|
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.
|
|
802
599
|
*/
|
|
803
600
|
grantByOrigin(input: GrantInput & {
|
|
804
601
|
originModel: string;
|
|
@@ -808,14 +605,8 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
808
605
|
created: boolean;
|
|
809
606
|
}>;
|
|
810
607
|
/**
|
|
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.
|
|
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.
|
|
819
610
|
*/
|
|
820
611
|
setStateByOrigin(originModel: string, originRef: string, effect: 'suspend' | 'resume' | 'revoke', options?: {
|
|
821
612
|
reason?: string | undefined;
|
|
@@ -823,106 +614,56 @@ declare class EntitlementRepository extends Repository<EntitlementDocument> {
|
|
|
823
614
|
changed: number;
|
|
824
615
|
}>;
|
|
825
616
|
/**
|
|
826
|
-
* Push the expiry of every live grant from one origin.
|
|
827
|
-
*
|
|
828
|
-
*
|
|
829
|
-
* value: setting the same expiry twice changes nothing, so a redelivery is safe
|
|
830
|
-
* 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.
|
|
831
620
|
*/
|
|
832
621
|
extendByOrigin(originModel: string, originRef: string, accessExpiresAt: Date | null, ctx?: AccessContext): Promise<{
|
|
833
622
|
changed: number;
|
|
834
623
|
matched: number;
|
|
835
624
|
}>;
|
|
836
|
-
/**
|
|
837
|
-
listForSubject(
|
|
838
|
-
subjectModel?: string | undefined;
|
|
625
|
+
/** One subject's grants, newest first ("my access"). Filtered in the query, capped at 200. */
|
|
626
|
+
listForSubject(subject: AccessSubject, options: {
|
|
839
627
|
resourceType?: string | undefined;
|
|
840
628
|
liveOnly?: boolean | undefined;
|
|
841
629
|
limit?: number | undefined;
|
|
842
|
-
|
|
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>;
|
|
843
643
|
private transition;
|
|
844
|
-
private transitionInner;
|
|
845
644
|
/**
|
|
846
|
-
*
|
|
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.
|
|
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.
|
|
853
647
|
*/
|
|
648
|
+
private transitionInner;
|
|
649
|
+
/** Load a grant for a WRITE, WITH its status history (`select: false` otherwise). */
|
|
854
650
|
private load;
|
|
855
|
-
/** Resolve the live (active
|
|
651
|
+
/** Resolve the live (active preferred over suspended) grant for a target, or null. */
|
|
856
652
|
private findLive;
|
|
857
653
|
private targetLabel;
|
|
858
654
|
private emitLifecycle;
|
|
859
655
|
/**
|
|
860
656
|
* Run a mutation + its event emission as ONE atomic unit.
|
|
861
657
|
*
|
|
862
|
-
*
|
|
863
|
-
*
|
|
864
|
-
*
|
|
865
|
-
*
|
|
866
|
-
*
|
|
867
|
-
*
|
|
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.
|
|
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).
|
|
910
664
|
*/
|
|
911
|
-
reconcileEntitlementSet(input: ReconcileEntitlementSetInput, ctx: AccessContext): Promise<ReconcileResult>;
|
|
912
665
|
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
|
-
*/
|
|
666
|
+
/** A session with no outbox has no correct event path — refuse BEFORE any write. */
|
|
926
667
|
private preflightDispatch;
|
|
927
668
|
private get channels();
|
|
928
669
|
}
|
|
@@ -968,22 +709,12 @@ interface AccessShape {
|
|
|
968
709
|
interface AccessRuntime {
|
|
969
710
|
eventTransport?: EventTransport | undefined;
|
|
970
711
|
/**
|
|
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.
|
|
712
|
+
* The BUSINESS timezone, IANA (`'Asia/Dhaka'`). Calendar ranges (renewal worklist, churn) and
|
|
713
|
+
* pause-allowance day boundaries resolve against it. Defaults to `'UTC'`.
|
|
985
714
|
*/
|
|
986
715
|
timezone?: string | undefined;
|
|
716
|
+
/** The clock every decision and timestamp reads. Default `() => new Date()`; tests pin it. */
|
|
717
|
+
clock?: (() => Date) | undefined;
|
|
987
718
|
outbox?: OutboxStore | undefined;
|
|
988
719
|
logger?: AccessLogger | undefined;
|
|
989
720
|
/**
|
|
@@ -1117,8 +848,8 @@ declare class InvalidConsumeAmountError extends AccessError {
|
|
|
1117
848
|
* state conflicts with the spend.
|
|
1118
849
|
*/
|
|
1119
850
|
declare class EntitlementNotUsableError extends AccessError {
|
|
1120
|
-
readonly reason:
|
|
1121
|
-
constructor(id: string, reason:
|
|
851
|
+
readonly reason: AccessReason;
|
|
852
|
+
constructor(id: string, reason: AccessReason);
|
|
1122
853
|
}
|
|
1123
854
|
/**
|
|
1124
855
|
* A caller passed `ctx.session` that is NOT inside an active transaction.
|
|
@@ -1176,6 +907,40 @@ declare class AccessCapabilityError extends AccessError {
|
|
|
1176
907
|
declare class InvalidExpiryWindowError extends AccessError {
|
|
1177
908
|
constructor(message: string);
|
|
1178
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
|
+
}
|
|
1179
944
|
//#endregion
|
|
1180
945
|
//#region src/events/in-process-bus.d.ts
|
|
1181
946
|
type InProcessAccessBusOptions = InProcessEventBusOptions;
|
|
@@ -1183,4 +948,4 @@ declare class InProcessAccessBus extends InProcessEventBus {
|
|
|
1183
948
|
constructor(options?: InProcessAccessBusOptions);
|
|
1184
949
|
}
|
|
1185
950
|
//#endregion
|
|
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 };
|
|
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 };
|