@classytic/access 0.1.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.
@@ -0,0 +1,362 @@
1
+ import { AccessDecision, AccessGrantState, AccessReason, evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
2
+ import { d as accessEventDefinitions, f as ACCESS_EVENTS, p as AccessEventName, t as AccessEventDefinition } from "./event-catalog-BGFNnlNJ.mjs";
3
+ import { MultiTenantOptions, PluginType, Repository } from "@classytic/mongokit";
4
+ import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
5
+ import { Connection, Document, Model, Schema, Types } from "mongoose";
6
+ import { DomainEvent, EventHandler, EventTransport } from "@classytic/primitives/events";
7
+ import { InvalidOutboxEventError, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxFailOptions, OutboxOwnershipError, OutboxStore, OutboxStore as OutboxStore$1, OutboxWriteOptions } from "@classytic/primitives/outbox";
8
+ import { OffsetPaginationResult } from "@classytic/repo-core/pagination";
9
+ import { OperationContext } from "@classytic/primitives/context";
10
+ import { RetryPolicy } from "@classytic/repo-core/repository";
11
+ import { HttpError } from "@classytic/repo-core/errors";
12
+
13
+ //#region src/domain/enums/entitlement-status.enum.d.ts
14
+ /**
15
+ * Entitlement lifecycle status.
16
+ *
17
+ * active ⇄ suspended
18
+ * active → expired (window lapsed; written by the sweeper — derived at read-time)
19
+ * active → consumed (metered quota exhausted)
20
+ * active → revoked (admin pull / dispute) ── terminal
21
+ * active → refunded (payment reversed) ── terminal
22
+ * expired → active (renewal restarts the window)
23
+ * consumed → active (top-up restores quota)
24
+ * suspended → expired | revoked | refunded
25
+ *
26
+ * IMPORTANT: `expired` and `consumed` are LIFECYCLE markers a sweeper /
27
+ * consume() writes so the row can be queried and an event emitted once. The
28
+ * buyer-facing gate never depends on them — `evaluateAccess` (access-decision.ts)
29
+ * derives expiry/exhaustion from the window + usage directly, so a grant is
30
+ * denied the instant it lapses, before any status write. The row is never
31
+ * deleted: terminal states free the live-uniqueness slot for a fresh grant.
32
+ */
33
+ declare const ENTITLEMENT_STATUS: {
34
+ readonly ACTIVE: "active";
35
+ readonly SUSPENDED: "suspended";
36
+ readonly EXPIRED: "expired";
37
+ readonly CONSUMED: "consumed";
38
+ readonly REVOKED: "revoked";
39
+ readonly REFUNDED: "refunded";
40
+ };
41
+ declare const ENTITLEMENT_STATUS_VALUES: readonly ["active", "suspended", "expired", "consumed", "revoked", "refunded"];
42
+ type EntitlementStatus = (typeof ENTITLEMENT_STATUS_VALUES)[number];
43
+ /** Statuses where the grant is still "live" (subject of the one-active-per-resource rule). */
44
+ declare const LIVE_STATUSES: readonly ["active", "suspended"];
45
+ declare const isEntitlementStatus: (v: unknown) => v is EntitlementStatus;
46
+ declare function canEntitlementTransition(from: EntitlementStatus, to: EntitlementStatus): boolean;
47
+ //#endregion
48
+ //#region src/models/entitlement.model.d.ts
49
+ interface EntitlementUsage {
50
+ /** Metered cap. `null` = unlimited (unmetered access). */
51
+ limit: number | null;
52
+ /** Units consumed (downloads taken, API calls made, seats used). */
53
+ used: number;
54
+ }
55
+ interface EntitlementDocument extends Document {
56
+ _id: Types.ObjectId;
57
+ organizationId: Types.ObjectId | string;
58
+ subjectRef: string;
59
+ subjectModel: string;
60
+ /** Frozen identity copy (guest grants + later identity merges). */
61
+ subjectEmail?: string;
62
+ resourceRef: string;
63
+ resourceType: string;
64
+ /** Sub-scope within the resource ('' = the whole resource; e.g. an API scope). */
65
+ scopeKey: string;
66
+ status: EntitlementStatus;
67
+ /** How the grant came to be — drives reporting, not access. */
68
+ source: 'purchase' | 'subscription' | 'trial' | 'grant' | 'manual' | 'system';
69
+ grantedAt: Date;
70
+ /** Access does not begin until this instant (scheduled / early-access). */
71
+ notBefore?: Date | null;
72
+ /** Access ends here. `null` = lifetime (never expires). */
73
+ accessExpiresAt?: Date | null;
74
+ usage: EntitlementUsage;
75
+ originRef?: string;
76
+ originModel?: string;
77
+ amount?: number | null;
78
+ currency?: string;
79
+ /** Links a renewal to the grant it superseded (audit chain). */
80
+ renewedFromRef?: string;
81
+ reason?: string;
82
+ suspendedAt?: Date;
83
+ revokedAt?: Date;
84
+ expiredAt?: Date;
85
+ consumedAt?: Date;
86
+ refundedAt?: Date;
87
+ metadata?: Record<string, unknown>;
88
+ deletedAt?: Date | null;
89
+ createdAt: Date;
90
+ updatedAt: Date;
91
+ version: number;
92
+ }
93
+ //#endregion
94
+ //#region src/models/create-models.d.ts
95
+ type AccessModelName = 'Entitlement';
96
+ interface AccessModelBundle {
97
+ Entitlement: Model<EntitlementDocument>;
98
+ }
99
+ declare class AccessModelCollisionError extends Error {
100
+ constructor(name: string);
101
+ }
102
+ interface CreateAccessModelsOptions {
103
+ tenant?: ResolvedTenantConfig | TenantConfig | boolean;
104
+ autoIndex?: boolean | Partial<Record<AccessModelName, boolean>>;
105
+ collectionPrefix?: string | undefined;
106
+ forceRecreate?: boolean | undefined;
107
+ }
108
+ declare function createAccessModels(connection: Connection, options?: CreateAccessModelsOptions): AccessModelBundle;
109
+ //#endregion
110
+ //#region src/domain/ports/common.d.ts
111
+ /**
112
+ * AccessContext — operation context threaded through every domain verb.
113
+ * Extends primitives' `OperationContext` (P3 — extend, never redeclare).
114
+ *
115
+ * `organizationId` is OPTIONAL: tenant-scoped grants (a creator's course)
116
+ * carry it; platform-level grants (a user's API key, when the engine runs
117
+ * `tenant: false`) do not. The `multiTenantPlugin` enforces presence at
118
+ * runtime when tenancy is enabled.
119
+ */
120
+ interface AccessContext extends OperationContext {
121
+ organizationId?: string;
122
+ actorId?: string;
123
+ actorKind?: 'user' | 'system' | 'service' | undefined;
124
+ /** Cooperative cancellation — threaded into every repo call. */
125
+ signal?: AbortSignal | undefined;
126
+ /** Driver round-trip retry policy — threaded into every repo call. */
127
+ retryPolicy?: RetryPolicy | undefined;
128
+ }
129
+ //#endregion
130
+ //#region src/repositories/entitlement.repository.d.ts
131
+ type EntitlementSource = 'purchase' | 'subscription' | 'trial' | 'grant' | 'manual' | 'system';
132
+ interface GrantInput {
133
+ subjectRef: string;
134
+ subjectModel: string;
135
+ subjectEmail?: string | undefined;
136
+ resourceRef: string;
137
+ resourceType: string;
138
+ /** Sub-scope inside the resource. Defaults to '' (the whole resource). */
139
+ scopeKey?: string | undefined;
140
+ source: EntitlementSource;
141
+ /** Access opens at this instant (scheduled / early access). */
142
+ notBefore?: Date | null | undefined;
143
+ /** Access ends here. `null` / omitted = lifetime. */
144
+ accessExpiresAt?: Date | null | undefined;
145
+ /** Metered cap; `null` / omitted = unlimited. */
146
+ usageLimit?: number | null | undefined;
147
+ originRef?: string | undefined;
148
+ originModel?: string | undefined;
149
+ amount?: number | null | undefined;
150
+ currency?: string | undefined;
151
+ metadata?: Record<string, unknown> | undefined;
152
+ /**
153
+ * When a live grant already exists, refresh its window/quota (a re-purchase
154
+ * restarts the clock). Default true. Set false for pure idempotency.
155
+ */
156
+ renew?: boolean | undefined;
157
+ }
158
+ /** Identify the grant to check/consume: by id, or by (subject, resource). */
159
+ type EntitlementTarget = {
160
+ id: string;
161
+ } | {
162
+ subjectRef: string;
163
+ resourceRef: string;
164
+ resourceType?: string | undefined;
165
+ scopeKey?: string | undefined;
166
+ };
167
+ interface CheckResult extends AccessDecision {
168
+ entitlement: EntitlementDocument | null;
169
+ }
170
+ interface EntitlementRepositoryConfig {
171
+ model: Model<EntitlementDocument>;
172
+ plugins?: PluginType[];
173
+ eventTransport?: EventTransport | undefined;
174
+ outbox?: OutboxStore$1 | undefined;
175
+ logger?: {
176
+ error(message: string, ...args: unknown[]): void;
177
+ } | undefined;
178
+ }
179
+ declare class EntitlementRepository extends Repository<EntitlementDocument> {
180
+ private readonly eventTransport;
181
+ private readonly outbox;
182
+ private readonly pkgLogger;
183
+ constructor(config: EntitlementRepositoryConfig);
184
+ /**
185
+ * Grant access. Idempotent per (subject, resource, scope) live grant via
186
+ * atomic `getOrCreate`. If a live grant already exists and `renew !== false`,
187
+ * the window/quota is refreshed (a re-purchase restarts the clock). Emits
188
+ * `access:granted` on first grant, `access:extended` on renewal.
189
+ */
190
+ grant(input: GrantInput, ctx: AccessContext): Promise<EntitlementDocument>;
191
+ /**
192
+ * Decide access RIGHT NOW. Read-only: loads the live grant (active or
193
+ * suspended) and runs `evaluateAccess`. Returns `{ allowed, reason, ... }`
194
+ * plus the entitlement (or null when none exists).
195
+ */
196
+ check(target: EntitlementTarget, ctx: AccessContext): Promise<CheckResult>;
197
+ /**
198
+ * Spend `amount` metered units (a download, an API call, a seat). Atomic and
199
+ * race-safe: a metered grant only succeeds while `used + amount <= limit`
200
+ * (guarded `$expr`), so N concurrent consumes never overshoot. When the cap
201
+ * is reached the grant CAS-transitions to `consumed` and emits
202
+ * `access:exhausted`. Unlimited grants (`limit: null`) just increment.
203
+ * Throws `QuotaExhaustedError` when no unit is left.
204
+ */
205
+ consume(target: EntitlementTarget, amount?: number, ctx?: AccessContext): Promise<EntitlementDocument>;
206
+ /** Pause access without ending it (active → suspended). */
207
+ suspend(id: string, options?: {
208
+ reason?: string | undefined;
209
+ }, ctx?: AccessContext): Promise<EntitlementDocument>;
210
+ /** Lift a suspension (suspended → active). */
211
+ resume(id: string, ctx?: AccessContext): Promise<EntitlementDocument>;
212
+ /** Pull access permanently (active|suspended → revoked). Window cut to now. */
213
+ revoke(id: string, options?: {
214
+ reason?: string | undefined;
215
+ }, ctx?: AccessContext): Promise<EntitlementDocument>;
216
+ /** Mark a grant refunded (active|suspended → refunded). Window cut to now. */
217
+ refund(id: string, options?: {
218
+ reason?: string | undefined;
219
+ }, ctx?: AccessContext): Promise<EntitlementDocument>;
220
+ /**
221
+ * Extend (or set) the access window — a renewal. Pass an absolute
222
+ * `accessExpiresAt`, or `addMs` to push the current window out. Reactivates
223
+ * an `expired` grant. Emits `access:extended`.
224
+ */
225
+ extend(id: string, options: {
226
+ accessExpiresAt?: Date | null | undefined;
227
+ addMs?: number | undefined;
228
+ }, ctx?: AccessContext): Promise<EntitlementDocument>;
229
+ /**
230
+ * Sweep grants whose window has lapsed: CAS active → expired, emit
231
+ * `access:expired` per row. The row SURVIVES (audit / renewal); this is the
232
+ * "model expiry as a state transition" rule, not a TTL-delete. The CAS
233
+ * `where` re-guards the window so a concurrent `extend` is never clobbered.
234
+ * Drive it from a host cron. Returns how many were swept.
235
+ *
236
+ * Read-time `check()` already denies a lapsed grant before the sweep runs —
237
+ * this pass exists to fire the event and make `status: 'expired'` queryable,
238
+ * not to enforce the gate.
239
+ */
240
+ expireDue(options?: {
241
+ now?: Date | undefined;
242
+ limit?: number | undefined;
243
+ }, ctx?: AccessContext): Promise<{
244
+ swept: number;
245
+ }>;
246
+ /**
247
+ * Refund cascade — when an order/transaction is reversed, mark every live
248
+ * grant it produced as refunded. Looks up by the polymorphic origin ref.
249
+ */
250
+ refundByOrigin(originModel: string, originRef: string, options?: {
251
+ reason?: string | undefined;
252
+ }, ctx?: AccessContext): Promise<{
253
+ refunded: number;
254
+ }>;
255
+ /** A subject's grants, newest-first ("my access"). */
256
+ listForSubject(subjectRef: string, ctx: AccessContext): Promise<OffsetPaginationResult<EntitlementDocument>>;
257
+ private transition;
258
+ private load;
259
+ /** Resolve the live (active|suspended) grant for a target, or null. */
260
+ private findLive;
261
+ private targetLabel;
262
+ private emitLifecycle;
263
+ private get channels();
264
+ }
265
+ //#endregion
266
+ //#region src/engine/engine-types.d.ts
267
+ type AccessTenantOptions = TenantConfig & Pick<MultiTenantOptions, 'skipOperations' | 'skipWhen' | 'resolveContext' | 'allowDataInjection' | 'onMismatch'>;
268
+ interface AccessLogger {
269
+ error(message: string, ...args: unknown[]): void;
270
+ }
271
+ interface AccessConfig {
272
+ connection: Connection;
273
+ /**
274
+ * Tenant scoping. Pass `false` for company-wide grants (a user's platform
275
+ * API key has no org). Default `{ fieldType: 'objectId' }` matches Better
276
+ * Auth's `organization._id`.
277
+ */
278
+ tenant?: AccessTenantOptions | boolean | undefined;
279
+ eventTransport?: EventTransport | undefined;
280
+ outbox?: OutboxStore$1 | undefined;
281
+ repositoryPlugins?: {
282
+ entitlement?: PluginType[] | undefined;
283
+ } | undefined;
284
+ /** Keep soft-deleted grants for this many days (default ~7y, audit floor). */
285
+ softDeleteTtlDays?: number | undefined;
286
+ autoIndex?: boolean | Partial<Record<AccessModelName, boolean>> | undefined;
287
+ collectionPrefix?: string | undefined;
288
+ forceRecreate?: boolean | undefined;
289
+ logger?: AccessLogger | undefined;
290
+ }
291
+ interface AccessRepositories {
292
+ entitlement: EntitlementRepository;
293
+ }
294
+ interface AccessEngine {
295
+ readonly config: Readonly<AccessConfig>;
296
+ readonly models: AccessModelBundle;
297
+ readonly repositories: AccessRepositories;
298
+ readonly events: EventTransport;
299
+ readonly outbox: OutboxStore$1 | undefined;
300
+ syncIndexes(): Promise<void>;
301
+ destroy(): Promise<void>;
302
+ }
303
+ //#endregion
304
+ //#region src/engine/create-access.d.ts
305
+ /**
306
+ * createAccess — the access ENTITLEMENT engine. Durable, time-bound grants of
307
+ * access to any resource (course, download, API, membership, feature, service).
308
+ * No purchase (order), no money (revenue), no catalog — those compose around it.
309
+ */
310
+ declare function createAccess(config: AccessConfig): Promise<AccessEngine>;
311
+ //#endregion
312
+ //#region src/domain/errors/access.errors.d.ts
313
+ declare class AccessError extends Error implements HttpError {
314
+ readonly code: string;
315
+ readonly status: number;
316
+ constructor(message: string, code: string, status: number);
317
+ }
318
+ declare class EntitlementNotFoundError extends AccessError {
319
+ constructor(id: string);
320
+ }
321
+ /** A consume() against a metered grant whose quota is already spent. */
322
+ declare class QuotaExhaustedError extends AccessError {
323
+ constructor(id: string, limit: number);
324
+ }
325
+ declare class InvalidEntitlementTransitionError extends AccessError {
326
+ constructor(from: string, to: string);
327
+ }
328
+ declare class VersionMismatchError extends AccessError {
329
+ constructor(id: string, expectedVersion: number);
330
+ }
331
+ /**
332
+ * The backend does not declare the capabilities the engine needs. Granting is
333
+ * idempotent via atomic `getOrCreate` (upsert); without it two concurrent
334
+ * grants on one (subject, resource) would double-provision. Metered `consume`
335
+ * needs an atomic guarded increment. Fail loud at boot, not at runtime.
336
+ */
337
+ declare class AccessCapabilityError extends AccessError {
338
+ constructor(missing: readonly string[]);
339
+ }
340
+ //#endregion
341
+ //#region src/events/in-process-bus.d.ts
342
+ interface InProcessAccessBusOptions {
343
+ logger?: {
344
+ error(message: string, ...args: unknown[]): void;
345
+ };
346
+ }
347
+ /**
348
+ * ~50-line in-process fallback transport (rule 13). Structurally identical to
349
+ * arc's `MemoryEventTransport`; delegates glob matching to primitives'
350
+ * `matchEventPattern`. Hosts that pass an `eventTransport` never construct it.
351
+ */
352
+ declare class InProcessAccessBus implements EventTransport {
353
+ readonly name = "in-process-access";
354
+ private handlers;
355
+ private logger;
356
+ constructor(options?: InProcessAccessBusOptions);
357
+ publish(event: DomainEvent): Promise<void>;
358
+ subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
359
+ close(): Promise<void>;
360
+ }
361
+ //#endregion
362
+ export { ACCESS_EVENTS, AccessCapabilityError, type AccessConfig, type AccessContext, type AccessDecision, type AccessEngine, AccessError, type AccessEventDefinition, type AccessEventName, type AccessGrantState, type AccessLogger, type AccessModelBundle, AccessModelCollisionError, type AccessModelName, type AccessReason, type AccessRepositories, type AccessTenantOptions, type CheckResult, ENTITLEMENT_STATUS, ENTITLEMENT_STATUS_VALUES, type EntitlementDocument, EntitlementNotFoundError, EntitlementRepository, type EntitlementRepositoryConfig, type EntitlementSource, type EntitlementStatus, type EntitlementTarget, type EntitlementUsage, type GrantInput, InProcessAccessBus, InvalidEntitlementTransitionError, InvalidOutboxEventError, LIVE_STATUSES, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxFailOptions, OutboxOwnershipError, type OutboxStore, type OutboxWriteOptions, QuotaExhaustedError, VersionMismatchError, accessEventDefinitions, canEntitlementTransition, createAccess, createAccessModels, evaluateAccess, hasAccess, isEntitlementStatus };