@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.
package/dist/index.mjs ADDED
@@ -0,0 +1,854 @@
1
+ import { evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
2
+ import { l as accessEventDefinitions, u as ACCESS_EVENTS } from "./event-catalog-BVD_rFlc.mjs";
3
+ import { Repository, createOptionsExtractor, multiTenantPlugin, softDeletePlugin } from "@classytic/mongokit";
4
+ import { resolveTenantConfig } from "@classytic/repo-core/tenant";
5
+ import mongoose, { Schema } from "mongoose";
6
+ import { createEvent, matchEventPattern } from "@classytic/primitives/events";
7
+ import { InvalidOutboxEventError, OutboxOwnershipError } from "@classytic/primitives/outbox";
8
+ //#region src/domain/enums/entitlement-status.enum.ts
9
+ /**
10
+ * Entitlement lifecycle status.
11
+ *
12
+ * active ⇄ suspended
13
+ * active → expired (window lapsed; written by the sweeper — derived at read-time)
14
+ * active → consumed (metered quota exhausted)
15
+ * active → revoked (admin pull / dispute) ── terminal
16
+ * active → refunded (payment reversed) ── terminal
17
+ * expired → active (renewal restarts the window)
18
+ * consumed → active (top-up restores quota)
19
+ * suspended → expired | revoked | refunded
20
+ *
21
+ * IMPORTANT: `expired` and `consumed` are LIFECYCLE markers a sweeper /
22
+ * consume() writes so the row can be queried and an event emitted once. The
23
+ * buyer-facing gate never depends on them — `evaluateAccess` (access-decision.ts)
24
+ * derives expiry/exhaustion from the window + usage directly, so a grant is
25
+ * denied the instant it lapses, before any status write. The row is never
26
+ * deleted: terminal states free the live-uniqueness slot for a fresh grant.
27
+ */
28
+ const ENTITLEMENT_STATUS = {
29
+ ACTIVE: "active",
30
+ SUSPENDED: "suspended",
31
+ EXPIRED: "expired",
32
+ CONSUMED: "consumed",
33
+ REVOKED: "revoked",
34
+ REFUNDED: "refunded"
35
+ };
36
+ const ENTITLEMENT_STATUS_VALUES = [
37
+ "active",
38
+ "suspended",
39
+ "expired",
40
+ "consumed",
41
+ "revoked",
42
+ "refunded"
43
+ ];
44
+ /** Statuses where the grant is still "live" (subject of the one-active-per-resource rule). */
45
+ const LIVE_STATUSES = ["active", "suspended"];
46
+ const SET = new Set(ENTITLEMENT_STATUS_VALUES);
47
+ const isEntitlementStatus = (v) => typeof v === "string" && SET.has(v);
48
+ const ENTITLEMENT_TRANSITIONS = {
49
+ active: [
50
+ "suspended",
51
+ "expired",
52
+ "consumed",
53
+ "revoked",
54
+ "refunded"
55
+ ],
56
+ suspended: [
57
+ "active",
58
+ "expired",
59
+ "revoked",
60
+ "refunded"
61
+ ],
62
+ expired: ["active"],
63
+ consumed: ["active"],
64
+ revoked: [],
65
+ refunded: []
66
+ };
67
+ function canEntitlementTransition(from, to) {
68
+ return ENTITLEMENT_TRANSITIONS[from].includes(to);
69
+ }
70
+ //#endregion
71
+ //#region src/models/entitlement.model.ts
72
+ /**
73
+ * Entitlement — a durable grant of access from a SUBJECT to a RESOURCE for a
74
+ * WINDOW. The single source of truth for "does this person/key/team hold a
75
+ * live grant to this thing". Polymorphic on both ends (String + bridge, rule 7)
76
+ * so the same model serves a course enrollment, a file download, an API key's
77
+ * scope, a membership, a feature flag, or any service grant.
78
+ *
79
+ * The grant is a PERMANENT record. The RIGHT to access is computed by
80
+ * `evaluateAccess` (access-decision.ts) from `accessExpiresAt` / `notBefore` /
81
+ * `usage`; expiry is never modelled by deleting the row (PACKAGE_RULES:
82
+ * self-healing CAS expiry over TTL-delete). Terminal statuses free the
83
+ * live-uniqueness slot so a re-purchase inserts a fresh grant.
84
+ */
85
+ function buildEntitlementSchema() {
86
+ const schema = new Schema({
87
+ subjectRef: {
88
+ type: String,
89
+ required: true,
90
+ trim: true,
91
+ index: true
92
+ },
93
+ subjectModel: {
94
+ type: String,
95
+ required: true,
96
+ trim: true
97
+ },
98
+ subjectEmail: {
99
+ type: String,
100
+ trim: true,
101
+ lowercase: true
102
+ },
103
+ resourceRef: {
104
+ type: String,
105
+ required: true,
106
+ trim: true,
107
+ index: true
108
+ },
109
+ resourceType: {
110
+ type: String,
111
+ required: true,
112
+ trim: true
113
+ },
114
+ scopeKey: {
115
+ type: String,
116
+ default: "",
117
+ trim: true
118
+ },
119
+ status: {
120
+ type: String,
121
+ enum: ENTITLEMENT_STATUS_VALUES,
122
+ default: ENTITLEMENT_STATUS.ACTIVE,
123
+ required: true,
124
+ index: true
125
+ },
126
+ source: {
127
+ type: String,
128
+ enum: [
129
+ "purchase",
130
+ "subscription",
131
+ "trial",
132
+ "grant",
133
+ "manual",
134
+ "system"
135
+ ],
136
+ required: true
137
+ },
138
+ grantedAt: {
139
+ type: Date,
140
+ default: Date.now,
141
+ required: true
142
+ },
143
+ notBefore: {
144
+ type: Date,
145
+ default: null
146
+ },
147
+ accessExpiresAt: {
148
+ type: Date,
149
+ default: null
150
+ },
151
+ usage: {
152
+ limit: {
153
+ type: Number,
154
+ default: null
155
+ },
156
+ used: {
157
+ type: Number,
158
+ default: 0,
159
+ min: 0
160
+ }
161
+ },
162
+ originRef: {
163
+ type: String,
164
+ trim: true
165
+ },
166
+ originModel: {
167
+ type: String,
168
+ trim: true
169
+ },
170
+ amount: {
171
+ type: Number,
172
+ default: null
173
+ },
174
+ currency: {
175
+ type: String,
176
+ trim: true
177
+ },
178
+ renewedFromRef: {
179
+ type: String,
180
+ trim: true
181
+ },
182
+ reason: { type: String },
183
+ suspendedAt: { type: Date },
184
+ revokedAt: { type: Date },
185
+ expiredAt: { type: Date },
186
+ consumedAt: { type: Date },
187
+ refundedAt: { type: Date },
188
+ metadata: { type: Schema.Types.Mixed },
189
+ deletedAt: {
190
+ type: Date,
191
+ default: null
192
+ },
193
+ version: {
194
+ type: Number,
195
+ default: 0
196
+ }
197
+ }, {
198
+ timestamps: true,
199
+ minimize: false,
200
+ optimisticConcurrency: true
201
+ });
202
+ schema.index({
203
+ subjectModel: 1,
204
+ subjectRef: 1,
205
+ resourceType: 1,
206
+ resourceRef: 1,
207
+ scopeKey: 1
208
+ }, {
209
+ unique: true,
210
+ partialFilterExpression: {
211
+ status: ENTITLEMENT_STATUS.ACTIVE,
212
+ deletedAt: null
213
+ },
214
+ name: "entitlement_unique_active_grant"
215
+ });
216
+ schema.index({
217
+ subjectRef: 1,
218
+ status: 1,
219
+ updatedAt: -1
220
+ }, { name: "entitlement_by_subject" });
221
+ schema.index({
222
+ resourceType: 1,
223
+ resourceRef: 1,
224
+ status: 1
225
+ }, { name: "entitlement_by_resource" });
226
+ schema.index({
227
+ status: 1,
228
+ accessExpiresAt: 1
229
+ }, { name: "entitlement_due_for_expiry" });
230
+ schema.index({
231
+ originModel: 1,
232
+ originRef: 1
233
+ }, { name: "entitlement_by_origin" });
234
+ return schema;
235
+ }
236
+ //#endregion
237
+ //#region src/models/inject-tenant.ts
238
+ /**
239
+ * Mongoose adapter around `@classytic/repo-core/tenant.resolveTenantConfig`.
240
+ * Thin (rule P11) — repo-core owns resolution; this handles schema mutations
241
+ * only: adds the tenant field with the engine-configured type, and prepends
242
+ * the tenant key to every existing compound index (rule 36).
243
+ */
244
+ function injectTenantField(schema, tenant) {
245
+ const isFieldStrategy = tenant.strategy === "field";
246
+ const isObjectId = tenant.fieldType === "objectId";
247
+ schema.add({ [tenant.tenantField]: {
248
+ type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
249
+ ...tenant.enabled && tenant.required ? { required: true } : {},
250
+ index: true,
251
+ ...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
252
+ } });
253
+ if (!tenant.enabled || !isFieldStrategy) return;
254
+ const existingIndexes = schema._indexes;
255
+ if (existingIndexes && existingIndexes.length > 0) for (const indexEntry of existingIndexes) {
256
+ const fields = indexEntry[0];
257
+ if (fields[tenant.tenantField] !== void 0) continue;
258
+ const newFields = { [tenant.tenantField]: 1 };
259
+ for (const [key, val] of Object.entries(fields)) newFields[key] = val;
260
+ indexEntry[0] = newFields;
261
+ }
262
+ }
263
+ //#endregion
264
+ //#region src/models/create-models.ts
265
+ const ACCESS_MODEL_NAMES = ["Entitlement"];
266
+ const DEFAULT_COLLECTIONS = { Entitlement: "entitlements" };
267
+ var AccessModelCollisionError = class extends Error {
268
+ constructor(name) {
269
+ super(`[access] Mongoose model "${name}" already exists on this connection. For hot-reload / test fixtures, pass \`forceRecreate: true\`. For two access engines, use two Mongoose connections (\`mongoose.createConnection(...)\`).`);
270
+ this.name = "AccessModelCollisionError";
271
+ }
272
+ };
273
+ function isResolvedTenant(value) {
274
+ return typeof value === "object" && value !== null && "strategy" in value && "tenantField" in value;
275
+ }
276
+ function createAccessModels(connection, options = {}) {
277
+ if (options.forceRecreate) {
278
+ for (const name of ACCESS_MODEL_NAMES) if (connection.models[name]) connection.deleteModel(name);
279
+ } else for (const name of ACCESS_MODEL_NAMES) if (connection.models[name]) throw new AccessModelCollisionError(name);
280
+ const tenant = options.tenant !== void 0 && isResolvedTenant(options.tenant) ? options.tenant : resolveTenantConfig(options.tenant);
281
+ const entitlementSchema = buildEntitlementSchema();
282
+ injectTenantField(entitlementSchema, tenant);
283
+ const prefix = options.collectionPrefix ?? "";
284
+ const bundle = { Entitlement: connection.model("Entitlement", entitlementSchema, prefix + DEFAULT_COLLECTIONS.Entitlement) };
285
+ applyAutoIndex(bundle, options.autoIndex);
286
+ return bundle;
287
+ }
288
+ function applyAutoIndex(models, autoIndex) {
289
+ if (autoIndex === void 0) return;
290
+ for (const [name, model] of Object.entries(models)) {
291
+ const value = typeof autoIndex === "boolean" ? autoIndex : autoIndex[name] ?? void 0;
292
+ if (value !== void 0) model.schema.set("autoIndex", value);
293
+ }
294
+ }
295
+ //#endregion
296
+ //#region src/domain/errors/access.errors.ts
297
+ var AccessError = class extends Error {
298
+ code;
299
+ status;
300
+ constructor(message, code, status) {
301
+ super(message);
302
+ this.name = this.constructor.name;
303
+ this.code = code;
304
+ this.status = status;
305
+ }
306
+ };
307
+ var EntitlementNotFoundError = class extends AccessError {
308
+ constructor(id) {
309
+ super(`Entitlement ${id} not found`, "access.entitlement.not_found", 404);
310
+ }
311
+ };
312
+ /** A consume() against a metered grant whose quota is already spent. */
313
+ var QuotaExhaustedError = class extends AccessError {
314
+ constructor(id, limit) {
315
+ super(`Entitlement ${id} quota exhausted (limit ${limit})`, "access.entitlement.quota_exhausted", 409);
316
+ }
317
+ };
318
+ var InvalidEntitlementTransitionError = class extends AccessError {
319
+ constructor(from, to) {
320
+ super(`Invalid entitlement transition: ${from} → ${to}`, "access.invalid_transition", 409);
321
+ }
322
+ };
323
+ var VersionMismatchError = class extends AccessError {
324
+ constructor(id, expectedVersion) {
325
+ super(`Concurrent modification on ${id} (expected version ${expectedVersion}) — retry.`, "access.concurrency.version_mismatch", 409);
326
+ }
327
+ };
328
+ /**
329
+ * The backend does not declare the capabilities the engine needs. Granting is
330
+ * idempotent via atomic `getOrCreate` (upsert); without it two concurrent
331
+ * grants on one (subject, resource) would double-provision. Metered `consume`
332
+ * needs an atomic guarded increment. Fail loud at boot, not at runtime.
333
+ */
334
+ var AccessCapabilityError = class extends AccessError {
335
+ constructor(missing) {
336
+ super(`[access] backend missing required capabilities: ${missing.join(", ")}. Grants use atomic getOrCreate (upsert) for idempotency and a guarded increment for metered consume; the backend must support them (mongokit 3.16+ / repo-core 0.6+).`, "access.engine.missing_capabilities", 500);
337
+ }
338
+ };
339
+ //#endregion
340
+ //#region src/events/helpers.ts
341
+ /**
342
+ * Thin typed wrapper around `@classytic/primitives/events.createEvent`
343
+ * (PACKAGE_RULES rule 14). Narrows `type` to `AccessEventName` and fills
344
+ * meta from the access context.
345
+ */
346
+ function createEvent$1(type, payload, ctx, meta) {
347
+ return createEvent(type, payload, {
348
+ ...ctx?.actorKind === "user" && ctx.actorId !== void 0 ? { userId: String(ctx.actorId) } : {},
349
+ ...ctx?.organizationId !== void 0 ? { organizationId: String(ctx.organizationId) } : {},
350
+ ...ctx?.correlationId !== void 0 ? { correlationId: ctx.correlationId } : {},
351
+ ...meta
352
+ });
353
+ }
354
+ //#endregion
355
+ //#region src/events/dispatch.ts
356
+ async function emitDomainEvent(channels, type, payload, ctx, resourceId) {
357
+ if (!channels.eventTransport && !channels.outbox) return;
358
+ const meta = {
359
+ resource: "entitlement",
360
+ resourceId,
361
+ source: "access"
362
+ };
363
+ if (ctx.idempotencyKey !== void 0) meta.idempotencyKey = ctx.idempotencyKey;
364
+ const event = createEvent$1(type, payload, ctx, meta);
365
+ if (channels.outbox) try {
366
+ const saveOptions = {};
367
+ if (ctx.session !== void 0) saveOptions.session = ctx.session;
368
+ await channels.outbox.save(event, saveOptions);
369
+ } catch (err) {
370
+ channels.logger.error(`[access] outbox.save failed for ${event.type}:`, err);
371
+ throw err;
372
+ }
373
+ if (ctx.session) return;
374
+ if (channels.eventTransport) try {
375
+ await channels.eventTransport.publish(event);
376
+ } catch (err) {
377
+ channels.logger.error(`[access] publish failed for ${event.type}:`, err);
378
+ }
379
+ }
380
+ //#endregion
381
+ //#region src/repositories/repo-options.ts
382
+ /**
383
+ * AccessContext → mongokit options extractor, built on mongokit's typed
384
+ * `createOptionsExtractor`. Forwards tenant + audit fields plus the repo-core
385
+ * 0.6 cancellation/retry contract (`signal`, `retryPolicy`).
386
+ */
387
+ const repoOptionsFromCtx = createOptionsExtractor([
388
+ "organizationId",
389
+ "actorId",
390
+ "actorKind",
391
+ "correlationId",
392
+ "session",
393
+ "idempotencyKey",
394
+ "traceId",
395
+ "requestId",
396
+ "signal",
397
+ "retryPolicy"
398
+ ]);
399
+ //#endregion
400
+ //#region src/repositories/entitlement.repository.ts
401
+ /**
402
+ * EntitlementRepository — grant / check / consume / lifecycle for durable,
403
+ * time-bound access. Every state move is an atomic CAS (`claim` / `claimVersion`
404
+ * / guarded `findOneAndUpdate`) — never read-modify-write. Expiry is modelled as
405
+ * a CAS transition (the `expireDue` sweeper), never a TTL-delete, so the row
406
+ * survives as an auditable record (PACKAGE_RULES Concurrency House Rules).
407
+ *
408
+ * The hot path is `check()`: a read that runs `evaluateAccess` and returns a
409
+ * decision. It mutates nothing, so it stays cheap and the same rule can run on
410
+ * an edge node or in the UI via the `@classytic/access/decision` subpath.
411
+ */
412
+ var EntitlementRepository = class extends Repository {
413
+ eventTransport;
414
+ outbox;
415
+ pkgLogger;
416
+ constructor(config) {
417
+ super(config.model, config.plugins ?? []);
418
+ this.eventTransport = config.eventTransport;
419
+ this.outbox = config.outbox;
420
+ this.pkgLogger = config.logger ?? console;
421
+ }
422
+ /**
423
+ * Grant access. Idempotent per (subject, resource, scope) live grant via
424
+ * atomic `getOrCreate`. If a live grant already exists and `renew !== false`,
425
+ * the window/quota is refreshed (a re-purchase restarts the clock). Emits
426
+ * `access:granted` on first grant, `access:extended` on renewal.
427
+ */
428
+ async grant(input, ctx) {
429
+ const scopeKey = input.scopeKey ?? "";
430
+ const opts = repoOptionsFromCtx(ctx);
431
+ const { doc, created } = await this.getOrCreate({
432
+ subjectModel: input.subjectModel,
433
+ subjectRef: input.subjectRef,
434
+ resourceType: input.resourceType,
435
+ resourceRef: input.resourceRef,
436
+ scopeKey,
437
+ status: ENTITLEMENT_STATUS.ACTIVE
438
+ }, {
439
+ ...ctx.organizationId !== void 0 ? { organizationId: ctx.organizationId } : {},
440
+ subjectRef: input.subjectRef,
441
+ subjectModel: input.subjectModel,
442
+ ...input.subjectEmail !== void 0 ? { subjectEmail: input.subjectEmail } : {},
443
+ resourceRef: input.resourceRef,
444
+ resourceType: input.resourceType,
445
+ scopeKey,
446
+ status: ENTITLEMENT_STATUS.ACTIVE,
447
+ source: input.source,
448
+ grantedAt: /* @__PURE__ */ new Date(),
449
+ notBefore: input.notBefore ?? null,
450
+ accessExpiresAt: input.accessExpiresAt ?? null,
451
+ usage: {
452
+ limit: input.usageLimit ?? null,
453
+ used: 0
454
+ },
455
+ ...input.originRef !== void 0 ? { originRef: input.originRef } : {},
456
+ ...input.originModel !== void 0 ? { originModel: input.originModel } : {},
457
+ ...input.amount !== void 0 ? { amount: input.amount } : {},
458
+ ...input.currency !== void 0 ? { currency: input.currency } : {},
459
+ ...input.metadata !== void 0 ? { metadata: input.metadata } : {}
460
+ }, opts);
461
+ if (created) {
462
+ await this.emitLifecycle(ACCESS_EVENTS.GRANTED, doc, ctx);
463
+ return doc;
464
+ }
465
+ if (input.renew === false) return doc;
466
+ const set = { accessExpiresAt: input.accessExpiresAt ?? null };
467
+ if (input.notBefore !== void 0) set.notBefore = input.notBefore;
468
+ if (input.usageLimit !== void 0) {
469
+ set["usage.limit"] = input.usageLimit;
470
+ set["usage.used"] = 0;
471
+ }
472
+ const renewed = await this.claimVersion(String(doc._id), { from: doc.version }, { $set: set }, opts);
473
+ if (!renewed) throw new VersionMismatchError(String(doc._id), doc.version);
474
+ await this.emitLifecycle(ACCESS_EVENTS.EXTENDED, renewed, ctx);
475
+ return renewed;
476
+ }
477
+ /**
478
+ * Decide access RIGHT NOW. Read-only: loads the live grant (active or
479
+ * suspended) and runs `evaluateAccess`. Returns `{ allowed, reason, ... }`
480
+ * plus the entitlement (or null when none exists).
481
+ */
482
+ async check(target, ctx) {
483
+ const grant = await this.findLive(target, ctx);
484
+ return {
485
+ ...evaluateAccess(grant),
486
+ entitlement: grant
487
+ };
488
+ }
489
+ /**
490
+ * Spend `amount` metered units (a download, an API call, a seat). Atomic and
491
+ * race-safe: a metered grant only succeeds while `used + amount <= limit`
492
+ * (guarded `$expr`), so N concurrent consumes never overshoot. When the cap
493
+ * is reached the grant CAS-transitions to `consumed` and emits
494
+ * `access:exhausted`. Unlimited grants (`limit: null`) just increment.
495
+ * Throws `QuotaExhaustedError` when no unit is left.
496
+ */
497
+ async consume(target, amount = 1, ctx = {}) {
498
+ const grant = await this.findLive(target, ctx);
499
+ if (!grant) throw new EntitlementNotFoundError(this.targetLabel(target));
500
+ if (grant.status !== ENTITLEMENT_STATUS.ACTIVE) {
501
+ if (grant.usage.limit !== null && grant.usage.used >= grant.usage.limit) throw new QuotaExhaustedError(String(grant._id), grant.usage.limit);
502
+ throw new EntitlementNotFoundError(String(grant._id));
503
+ }
504
+ const opts = repoOptionsFromCtx(ctx);
505
+ const metered = grant.usage.limit !== null;
506
+ const filter = {
507
+ _id: grant._id,
508
+ status: ENTITLEMENT_STATUS.ACTIVE,
509
+ ...metered ? { $expr: { $lte: [{ $add: ["$usage.used", amount] }, "$usage.limit"] } } : {}
510
+ };
511
+ const update = { $inc: {
512
+ "usage.used": amount,
513
+ version: 1
514
+ } };
515
+ const updated = await this.findOneAndUpdate(filter, update, {
516
+ ...opts,
517
+ new: true
518
+ });
519
+ if (!updated) {
520
+ if (metered) throw new QuotaExhaustedError(String(grant._id), grant.usage.limit);
521
+ throw new EntitlementNotFoundError(String(grant._id));
522
+ }
523
+ const limit = updated.usage.limit;
524
+ if (limit !== null && updated.usage.used >= limit) {
525
+ const consumed = await this.claim(String(updated._id), {
526
+ field: "status",
527
+ from: ENTITLEMENT_STATUS.ACTIVE,
528
+ to: ENTITLEMENT_STATUS.CONSUMED
529
+ }, {
530
+ $set: { consumedAt: /* @__PURE__ */ new Date() },
531
+ $inc: { version: 1 }
532
+ }, opts);
533
+ if (consumed) {
534
+ await this.emitLifecycle(ACCESS_EVENTS.EXHAUSTED, consumed, ctx);
535
+ return consumed;
536
+ }
537
+ }
538
+ return updated;
539
+ }
540
+ /** Pause access without ending it (active → suspended). */
541
+ async suspend(id, options = {}, ctx = {}) {
542
+ return this.transition(id, ENTITLEMENT_STATUS.SUSPENDED, ACCESS_EVENTS.SUSPENDED, ctx, {
543
+ suspendedAt: /* @__PURE__ */ new Date(),
544
+ ...options.reason !== void 0 ? { reason: options.reason } : {}
545
+ });
546
+ }
547
+ /** Lift a suspension (suspended → active). */
548
+ async resume(id, ctx = {}) {
549
+ return this.transition(id, ENTITLEMENT_STATUS.ACTIVE, ACCESS_EVENTS.RESUMED, ctx, {});
550
+ }
551
+ /** Pull access permanently (active|suspended → revoked). Window cut to now. */
552
+ async revoke(id, options = {}, ctx = {}) {
553
+ return this.transition(id, ENTITLEMENT_STATUS.REVOKED, ACCESS_EVENTS.REVOKED, ctx, {
554
+ revokedAt: /* @__PURE__ */ new Date(),
555
+ accessExpiresAt: /* @__PURE__ */ new Date(),
556
+ ...options.reason !== void 0 ? { reason: options.reason } : {}
557
+ });
558
+ }
559
+ /** Mark a grant refunded (active|suspended → refunded). Window cut to now. */
560
+ async refund(id, options = {}, ctx = {}) {
561
+ return this.transition(id, ENTITLEMENT_STATUS.REFUNDED, ACCESS_EVENTS.REFUNDED, ctx, {
562
+ refundedAt: /* @__PURE__ */ new Date(),
563
+ accessExpiresAt: /* @__PURE__ */ new Date(),
564
+ ...options.reason !== void 0 ? { reason: options.reason } : {}
565
+ });
566
+ }
567
+ /**
568
+ * Extend (or set) the access window — a renewal. Pass an absolute
569
+ * `accessExpiresAt`, or `addMs` to push the current window out. Reactivates
570
+ * an `expired` grant. Emits `access:extended`.
571
+ */
572
+ async extend(id, options, ctx = {}) {
573
+ const grant = await this.load(id, ctx);
574
+ const opts = repoOptionsFromCtx(ctx);
575
+ const newExpiry = options.accessExpiresAt !== void 0 ? options.accessExpiresAt : options.addMs != null ? new Date((grant.accessExpiresAt?.getTime() ?? Date.now()) + options.addMs) : null;
576
+ let updated;
577
+ if (grant.status === ENTITLEMENT_STATUS.EXPIRED) updated = await this.claim(id, {
578
+ field: "status",
579
+ from: ENTITLEMENT_STATUS.EXPIRED,
580
+ to: ENTITLEMENT_STATUS.ACTIVE
581
+ }, {
582
+ $set: {
583
+ accessExpiresAt: newExpiry,
584
+ expiredAt: null
585
+ },
586
+ $inc: { version: 1 }
587
+ }, opts);
588
+ else if (grant.status === ENTITLEMENT_STATUS.ACTIVE || grant.status === ENTITLEMENT_STATUS.SUSPENDED) updated = await this.claimVersion(id, { from: grant.version }, { $set: { accessExpiresAt: newExpiry } }, opts);
589
+ else throw new InvalidEntitlementTransitionError(grant.status, ENTITLEMENT_STATUS.ACTIVE);
590
+ if (!updated) throw new VersionMismatchError(id, grant.version);
591
+ await this.emitLifecycle(ACCESS_EVENTS.EXTENDED, updated, ctx);
592
+ return updated;
593
+ }
594
+ /**
595
+ * Sweep grants whose window has lapsed: CAS active → expired, emit
596
+ * `access:expired` per row. The row SURVIVES (audit / renewal); this is the
597
+ * "model expiry as a state transition" rule, not a TTL-delete. The CAS
598
+ * `where` re-guards the window so a concurrent `extend` is never clobbered.
599
+ * Drive it from a host cron. Returns how many were swept.
600
+ *
601
+ * Read-time `check()` already denies a lapsed grant before the sweep runs —
602
+ * this pass exists to fire the event and make `status: 'expired'` queryable,
603
+ * not to enforce the gate.
604
+ */
605
+ async expireDue(options = {}, ctx = {}) {
606
+ const cutoff = options.now ?? /* @__PURE__ */ new Date();
607
+ const opts = repoOptionsFromCtx(ctx);
608
+ const due = await this.getAll({
609
+ filters: {
610
+ status: ENTITLEMENT_STATUS.ACTIVE,
611
+ accessExpiresAt: {
612
+ $ne: null,
613
+ $lte: cutoff
614
+ }
615
+ },
616
+ sort: { accessExpiresAt: 1 },
617
+ limit: options.limit ?? 500
618
+ }, opts);
619
+ let swept = 0;
620
+ for (const grant of due.data) {
621
+ const done = await this.claim(String(grant._id), {
622
+ field: "status",
623
+ from: ENTITLEMENT_STATUS.ACTIVE,
624
+ to: ENTITLEMENT_STATUS.EXPIRED,
625
+ where: { accessExpiresAt: { $lte: cutoff } }
626
+ }, {
627
+ $set: { expiredAt: /* @__PURE__ */ new Date() },
628
+ $inc: { version: 1 }
629
+ }, opts);
630
+ if (done) {
631
+ swept += 1;
632
+ await this.emitLifecycle(ACCESS_EVENTS.EXPIRED, done, ctx);
633
+ }
634
+ }
635
+ return { swept };
636
+ }
637
+ /**
638
+ * Refund cascade — when an order/transaction is reversed, mark every live
639
+ * grant it produced as refunded. Looks up by the polymorphic origin ref.
640
+ */
641
+ async refundByOrigin(originModel, originRef, options = {}, ctx = {}) {
642
+ const opts = repoOptionsFromCtx(ctx);
643
+ const live = await this.getAll({ filters: {
644
+ originModel,
645
+ originRef,
646
+ status: { $in: LIVE_STATUSES }
647
+ } }, opts);
648
+ let refunded = 0;
649
+ for (const grant of live.data) {
650
+ const done = await this.claim(String(grant._id), {
651
+ field: "status",
652
+ from: grant.status,
653
+ to: ENTITLEMENT_STATUS.REFUNDED
654
+ }, {
655
+ $set: {
656
+ refundedAt: /* @__PURE__ */ new Date(),
657
+ accessExpiresAt: /* @__PURE__ */ new Date(),
658
+ ...options.reason !== void 0 ? { reason: options.reason } : {}
659
+ },
660
+ $inc: { version: 1 }
661
+ }, opts);
662
+ if (done) {
663
+ refunded += 1;
664
+ await this.emitLifecycle(ACCESS_EVENTS.REFUNDED, done, ctx);
665
+ }
666
+ }
667
+ return { refunded };
668
+ }
669
+ /** A subject's grants, newest-first ("my access"). */
670
+ async listForSubject(subjectRef, ctx) {
671
+ return await this.getAll({
672
+ filters: { subjectRef },
673
+ sort: { updatedAt: -1 }
674
+ }, repoOptionsFromCtx(ctx));
675
+ }
676
+ async transition(id, to, event, ctx, patch) {
677
+ const grant = await this.load(id, ctx);
678
+ if (!canEntitlementTransition(grant.status, to)) throw new InvalidEntitlementTransitionError(grant.status, to);
679
+ const updated = await this.claim(String(grant._id), {
680
+ field: "status",
681
+ from: grant.status,
682
+ to
683
+ }, {
684
+ $set: patch,
685
+ $inc: { version: 1 }
686
+ }, repoOptionsFromCtx(ctx));
687
+ if (!updated) throw new InvalidEntitlementTransitionError(grant.status, to);
688
+ await this.emitLifecycle(event, updated, ctx);
689
+ return updated;
690
+ }
691
+ async load(id, ctx) {
692
+ const grant = await this.getById(id, {
693
+ ...repoOptionsFromCtx(ctx),
694
+ throwOnNotFound: false
695
+ });
696
+ if (!grant) throw new EntitlementNotFoundError(id);
697
+ return grant;
698
+ }
699
+ /** Resolve the live (active|suspended) grant for a target, or null. */
700
+ async findLive(target, ctx) {
701
+ const opts = repoOptionsFromCtx(ctx);
702
+ if ("id" in target) return await this.getById(target.id, {
703
+ ...opts,
704
+ throwOnNotFound: false
705
+ }) ?? null;
706
+ const filters = {
707
+ subjectRef: target.subjectRef,
708
+ resourceRef: target.resourceRef,
709
+ scopeKey: target.scopeKey ?? "",
710
+ status: { $in: LIVE_STATUSES }
711
+ };
712
+ if (target.resourceType !== void 0) filters.resourceType = target.resourceType;
713
+ const rows = (await this.getAll({
714
+ filters,
715
+ sort: { updatedAt: -1 }
716
+ }, opts)).data;
717
+ return rows.find((r) => r.status === ENTITLEMENT_STATUS.ACTIVE) ?? rows[0] ?? null;
718
+ }
719
+ targetLabel(target) {
720
+ return "id" in target ? target.id : `${target.subjectRef}→${target.resourceRef}`;
721
+ }
722
+ async emitLifecycle(event, doc, ctx) {
723
+ await emitDomainEvent(this.channels, event, {
724
+ entitlementId: String(doc._id),
725
+ ...doc.organizationId !== void 0 ? { organizationId: String(doc.organizationId) } : {},
726
+ subjectRef: doc.subjectRef,
727
+ subjectModel: doc.subjectModel,
728
+ resourceRef: doc.resourceRef,
729
+ resourceType: doc.resourceType,
730
+ scopeKey: doc.scopeKey,
731
+ status: doc.status,
732
+ ...doc.accessExpiresAt ? { accessExpiresAt: doc.accessExpiresAt.toISOString() } : {},
733
+ ...doc.usage.limit !== null ? {
734
+ usageLimit: doc.usage.limit,
735
+ usageUsed: doc.usage.used
736
+ } : {}
737
+ }, ctx, String(doc._id));
738
+ }
739
+ get channels() {
740
+ return {
741
+ eventTransport: this.eventTransport,
742
+ outbox: this.outbox,
743
+ logger: this.pkgLogger
744
+ };
745
+ }
746
+ };
747
+ //#endregion
748
+ //#region src/events/in-process-bus.ts
749
+ /**
750
+ * ~50-line in-process fallback transport (rule 13). Structurally identical to
751
+ * arc's `MemoryEventTransport`; delegates glob matching to primitives'
752
+ * `matchEventPattern`. Hosts that pass an `eventTransport` never construct it.
753
+ */
754
+ var InProcessAccessBus = class {
755
+ name = "in-process-access";
756
+ handlers = /* @__PURE__ */ new Map();
757
+ logger;
758
+ constructor(options = {}) {
759
+ this.logger = options.logger ?? console;
760
+ }
761
+ async publish(event) {
762
+ const matched = /* @__PURE__ */ new Set();
763
+ for (const [pattern, handlers] of this.handlers.entries()) if (matchEventPattern(pattern, event.type)) for (const h of handlers) matched.add(h);
764
+ for (const handler of matched) try {
765
+ await handler(event);
766
+ } catch (err) {
767
+ this.logger.error(`[access] handler error for ${event.type}:`, err);
768
+ }
769
+ }
770
+ async subscribe(pattern, handler) {
771
+ let set = this.handlers.get(pattern);
772
+ if (!set) {
773
+ set = /* @__PURE__ */ new Set();
774
+ this.handlers.set(pattern, set);
775
+ }
776
+ set.add(handler);
777
+ return () => {
778
+ const s = this.handlers.get(pattern);
779
+ if (!s) return;
780
+ s.delete(handler);
781
+ if (s.size === 0) this.handlers.delete(pattern);
782
+ };
783
+ }
784
+ async close() {
785
+ this.handlers.clear();
786
+ }
787
+ };
788
+ //#endregion
789
+ //#region src/engine/create-access.ts
790
+ /** Runtime capabilities the access verbs require at boot (PACKAGE_RULES "Runtime capabilities"). */
791
+ const REQUIRED_CAPABILITIES = ["getOrCreate", "upsert"];
792
+ /**
793
+ * createAccess — the access ENTITLEMENT engine. Durable, time-bound grants of
794
+ * access to any resource (course, download, API, membership, feature, service).
795
+ * No purchase (order), no money (revenue), no catalog — those compose around it.
796
+ */
797
+ async function createAccess(config) {
798
+ if (!config.connection) throw new Error("createAccess: config.connection is required");
799
+ const tenant = resolveTenantConfig(config.tenant);
800
+ const logger = config.logger ?? console;
801
+ const events = config.eventTransport ?? new InProcessAccessBus({ logger });
802
+ const modelsOptions = { tenant };
803
+ if (config.autoIndex !== void 0) modelsOptions.autoIndex = config.autoIndex;
804
+ if (config.collectionPrefix !== void 0) modelsOptions.collectionPrefix = config.collectionPrefix;
805
+ if (config.forceRecreate !== void 0) modelsOptions.forceRecreate = config.forceRecreate;
806
+ const models = createAccessModels(config.connection, modelsOptions);
807
+ const tenantPlugins = (() => {
808
+ if (!tenant.enabled || tenant.strategy !== "field") return [];
809
+ const extras = typeof config.tenant === "object" ? config.tenant : void 0;
810
+ return [multiTenantPlugin({
811
+ tenantField: tenant.tenantField,
812
+ fieldType: tenant.fieldType,
813
+ contextKey: tenant.contextKey,
814
+ required: tenant.required,
815
+ ...extras?.skipOperations !== void 0 ? { skipOperations: extras.skipOperations } : {},
816
+ ...extras?.skipWhen !== void 0 ? { skipWhen: extras.skipWhen } : {},
817
+ ...extras?.resolveContext !== void 0 ? { resolveContext: extras.resolveContext } : {},
818
+ ...extras?.allowDataInjection !== void 0 ? { allowDataInjection: extras.allowDataInjection } : {},
819
+ ...extras?.onMismatch !== void 0 ? { onMismatch: extras.onMismatch } : {}
820
+ })];
821
+ })();
822
+ const softDelete = softDeletePlugin({ ttlDays: config.softDeleteTtlDays ?? 2555 });
823
+ const repoPlugins = config.repositoryPlugins ?? {};
824
+ const entitlement = new EntitlementRepository({
825
+ model: models.Entitlement,
826
+ plugins: [
827
+ ...tenantPlugins,
828
+ softDelete,
829
+ ...repoPlugins.entitlement ?? []
830
+ ],
831
+ eventTransport: events,
832
+ outbox: config.outbox,
833
+ logger
834
+ });
835
+ const caps = entitlement.capabilities;
836
+ if (!caps) throw new AccessCapabilityError(["capabilities descriptor (repo-core 0.6 / mongokit 3.16+)"]);
837
+ const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
838
+ if (missing.length > 0) throw new AccessCapabilityError(missing);
839
+ return {
840
+ config: Object.freeze({ ...config }),
841
+ models,
842
+ repositories: { entitlement },
843
+ events,
844
+ outbox: config.outbox,
845
+ async syncIndexes() {
846
+ await models.Entitlement.syncIndexes();
847
+ },
848
+ async destroy() {
849
+ await events.close?.();
850
+ }
851
+ };
852
+ }
853
+ //#endregion
854
+ export { ACCESS_EVENTS, AccessCapabilityError, AccessError, AccessModelCollisionError, ENTITLEMENT_STATUS, ENTITLEMENT_STATUS_VALUES, EntitlementNotFoundError, EntitlementRepository, InProcessAccessBus, InvalidEntitlementTransitionError, InvalidOutboxEventError, LIVE_STATUSES, OutboxOwnershipError, QuotaExhaustedError, VersionMismatchError, accessEventDefinitions, canEntitlementTransition, createAccess, createAccessModels, evaluateAccess, hasAccess, isEntitlementStatus };