@classytic/access 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,480 @@
1
+ import { ACCESS_REASONS } from "./domain/access-decision.mjs";
2
+ import { defineStateMachine } from "@classytic/primitives/state-machine";
3
+ import { createEvent } from "@classytic/primitives/events";
4
+ import { z } from "zod";
5
+ //#region src/domain/errors/access.errors.ts
6
+ var AccessError = class extends Error {
7
+ code;
8
+ status;
9
+ constructor(message, code, status) {
10
+ super(message);
11
+ this.name = this.constructor.name;
12
+ this.code = code;
13
+ this.status = status;
14
+ }
15
+ };
16
+ var EntitlementNotFoundError = class extends AccessError {
17
+ constructor(id) {
18
+ super(`Entitlement ${id} not found`, "access.entitlement.not_found", 404);
19
+ }
20
+ };
21
+ /** A consume() against a metered grant whose quota is already spent. */
22
+ var QuotaExhaustedError = class extends AccessError {
23
+ constructor(id, limit) {
24
+ super(`Entitlement ${id} quota exhausted (limit ${limit})`, "access.entitlement.quota_exhausted", 409);
25
+ }
26
+ };
27
+ /**
28
+ * A pause request the POLICY refused — not an invalid transition.
29
+ *
30
+ * Separate from `InvalidEntitlementTransitionError` because the causes are
31
+ * different in kind and the caller does different things with them: an illegal
32
+ * transition is a bug or a lost race, while this is a legitimate request that the
33
+ * rulebook declines, and the member is owed the reason ("your 60 days are used
34
+ * up"). Carrying the machine-readable `refusal` plus the operator-facing message
35
+ * means a UI can explain it without string-matching.
36
+ *
37
+ * 409, not 400: the request is well-formed; it conflicts with the subject's
38
+ * current allowance state.
39
+ */
40
+ var SuspensionRefusedError = class extends AccessError {
41
+ refusal;
42
+ daysUsedInPeriod;
43
+ daysRemainingInPeriod;
44
+ constructor(refusal, message, daysUsedInPeriod, daysRemainingInPeriod) {
45
+ super(message, `access.suspension.${refusal}`, 409);
46
+ this.refusal = refusal;
47
+ this.daysUsedInPeriod = daysUsedInPeriod;
48
+ this.daysRemainingInPeriod = daysRemainingInPeriod;
49
+ }
50
+ };
51
+ var InvalidEntitlementTransitionError = class extends AccessError {
52
+ constructor(from, to) {
53
+ super(`Invalid entitlement transition: ${from} → ${to}`, "access.invalid_transition", 409);
54
+ }
55
+ };
56
+ /**
57
+ * Thrown when a host passes `ctx.session` (it owns the outer transaction)
58
+ * but NO outbox is wired: there is no correct delivery path for the event.
59
+ * Publishing immediately would leak ghost events if the host rolls back;
60
+ * silently dropping loses the event entirely. Wire an `OutboxStore` —
61
+ * session + outbox is legal durable-relay-only mode (§P8.1).
62
+ */
63
+ var UnmanagedSessionError = class extends AccessError {
64
+ constructor() {
65
+ super("ctx.session provided but no OutboxStore is wired — events would be lost. Wire an outbox (durable relay delivers post-commit) or drop the session.", "access.session.unmanaged", 409);
66
+ }
67
+ };
68
+ /**
69
+ * A `consume()` whose amount is not a positive integer.
70
+ *
71
+ * Enforced in the DOMAIN method, not only in a route schema, because the
72
+ * repository is a public API: a host calling it directly (a queue worker, a
73
+ * migration) bypasses HTTP validation entirely. The dangerous case is not the
74
+ * obvious `0` — it is a NEGATIVE amount, which `$inc`s `usage.used` downward
75
+ * and silently restores quota without any top-up operation being recorded.
76
+ */
77
+ var InvalidConsumeAmountError = class extends AccessError {
78
+ constructor(amount) {
79
+ super(`consume() amount must be a positive integer, got ${String(amount)}`, "access.consume.invalid_amount", 400);
80
+ }
81
+ };
82
+ /**
83
+ * A `consume()` against a grant the decision refuses RIGHT NOW — scheduled but
84
+ * not yet open, expired, suspended, or otherwise unusable.
85
+ *
86
+ * Carries the decision's `reason` in both the code and a field, because the
87
+ * caller's follow-up differs by cause: `not_yet_active` is "come back at the
88
+ * start date", `expired` is "renew". 409, not 404 — the grant exists; its
89
+ * state conflicts with the spend.
90
+ */
91
+ var EntitlementNotUsableError = class extends AccessError {
92
+ reason;
93
+ constructor(id, reason) {
94
+ super(`Entitlement ${id} is not usable right now (${reason})`, `access.entitlement.not_usable.${reason}`, 409);
95
+ this.reason = reason;
96
+ }
97
+ };
98
+ /**
99
+ * A caller passed `ctx.session` that is NOT inside an active transaction.
100
+ *
101
+ * Distinct from `UnmanagedSessionError` (session with no outbox) because the fix
102
+ * is different and the mistake is easy to make: a bare `startSession()` looks
103
+ * like it buys atomicity and buys NOTHING — each write commits independently, so
104
+ * a failing `outbox.save` leaves the mutation standing and the event lost. The
105
+ * session must be driven by `session.withTransaction(...)` (or an explicit
106
+ * `startTransaction()`), which is what actually makes the pair atomic.
107
+ */
108
+ var SessionNotInTransactionError = class extends AccessError {
109
+ constructor() {
110
+ super("ctx.session was supplied but has no ACTIVE transaction — a bare session provides no atomicity (each write commits independently). Drive it with session.withTransaction(...) / startTransaction(), or omit the session and let the repository open its own transaction.", "access.session.not_in_transaction", 409);
111
+ }
112
+ };
113
+ var VersionMismatchError = class extends AccessError {
114
+ constructor(id, expectedVersion) {
115
+ super(`Concurrent modification on ${id} (expected version ${expectedVersion}) — retry.`, "access.concurrency.version_mismatch", 409);
116
+ }
117
+ };
118
+ /**
119
+ * A capability `defineAccess.bind` requires is missing. Two unrelated things
120
+ * raise it:
121
+ *
122
+ * - **the BACKEND's** `getOrCreate` / guarded increment — granting is idempotent
123
+ * via atomic `getOrCreate` (upsert), without which two concurrent grants on one
124
+ * (subject, resource) double-provision, and metered `consume` needs an atomic
125
+ * guarded increment;
126
+ * - **an injected OUTBOX's** `transactionalSave` — without which the event row
127
+ * survives a rolled-back mutation, so a ghost `entitlement:granted` describes
128
+ * access that was never granted and a credential sync acts on it.
129
+ *
130
+ * The backend remedy is therefore CONDITIONAL on a backend flag actually being in
131
+ * `missing`. It used to be appended unconditionally, so an outbox failure printed
132
+ * "the backend must support them (mongokit 3.16+ / repo-core 0.6+)" — plausible
133
+ * instruction pointing at a layer that was never involved, for a problem the
134
+ * backend does not have. The remedy for `outbox.*` is to supply an OutboxStore
135
+ * that enlists `ctx.session`; upgrading mongokit changes nothing.
136
+ *
137
+ * `missing` is always joined into the message verbatim: the flag NAMES are what
138
+ * make the refusal actionable (and are what `outbox-requires-transactional-save`
139
+ * asserts on), so no branch may drop them.
140
+ *
141
+ * @param missing - capability flags that were not provided. Flags prefixed
142
+ * `outbox.` describe the injected OutboxStore, not the database.
143
+ */
144
+ var AccessCapabilityError = class extends AccessError {
145
+ constructor(missing) {
146
+ const backendMissing = missing.filter((flag) => !flag.startsWith("outbox."));
147
+ super(`[access] missing required capabilities: ${missing.join(", ")}. Access fails loud at bind rather than provisioning entitlements nothing can reconcile (or emitting an event for access that was never granted).` + (backendMissing.length > 0 ? " 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);
148
+ }
149
+ };
150
+ /**
151
+ * A reporting window that cannot be resolved — a mixed civil/instant pair, an
152
+ * inverted range, or a date the calendar rejects (`2026-02-31`).
153
+ *
154
+ * 400, not 500: the caller's range is unusable. Answering with an empty list
155
+ * instead would read as "nothing is expiring", which is the opposite of the
156
+ * truth and the kind of plausible wrong answer this package exists to avoid.
157
+ */
158
+ var InvalidExpiryWindowError = class extends AccessError {
159
+ constructor(message) {
160
+ super(message, "access.entitlement.invalid_expiry_window", 400);
161
+ }
162
+ };
163
+ /**
164
+ * A grant with no provenance. Money-backed sources (`purchase`, `subscription`) need the
165
+ * paying document (`originModel` + `originRef`); every other source needs that or an actor
166
+ * (`ctx.actorId`). A right nobody can trace is a right nobody can reverse.
167
+ */
168
+ var GrantProvenanceRequiredError = class extends AccessError {
169
+ constructor(source, needs) {
170
+ super(`A '${source}' grant needs ${needs} — every entitlement must name what or who created it`, "access.grant.provenance_required", 400);
171
+ }
172
+ };
173
+ /** A consumption key reused with a different amount — a client bug, never a replay. */
174
+ var ConsumptionKeyConflictError = class extends AccessError {
175
+ constructor(key, appliedAmount, requestedAmount) {
176
+ super(`Consumption key '${key}' already spent ${appliedAmount} unit(s); a replay must ask for the same amount, got ${requestedAmount}`, "access.consume.key_conflict", 409);
177
+ }
178
+ };
179
+ /** A consume() with no consumption key, or one that is blank. */
180
+ var ConsumptionKeyRequiredError = class extends AccessError {
181
+ constructor() {
182
+ super("consume() requires a non-empty `key` (a scan id, event id or request key) so a retry cannot spend twice", "access.consume.key_required", 400);
183
+ }
184
+ };
185
+ /**
186
+ * An extend() that would not extend: no target given, `addMs` on a lifetime grant, a non-positive
187
+ * `addMs`, or an absolute expiry earlier than the current one. Shortening is revoke + re-grant.
188
+ */
189
+ var InvalidExtensionError = class extends AccessError {
190
+ constructor(message) {
191
+ super(message, "access.extend.invalid", 400);
192
+ }
193
+ };
194
+ /** A batch check that is empty, too large, or names a capability twice. */
195
+ var InvalidCheckRequestError = class extends AccessError {
196
+ constructor(message) {
197
+ super(message, "access.check.invalid", 400);
198
+ }
199
+ };
200
+ /**
201
+ * Two in-flight transactions raced on one consumption key. Retry: the retry finds the winner's
202
+ * key and returns it as a replay — nothing is spent twice.
203
+ */
204
+ var ConsumptionInFlightError = class extends AccessError {
205
+ constructor(key) {
206
+ super(`Consumption key '${key}' is being spent by a concurrent request — retry to read its result`, "access.consume.in_flight", 409);
207
+ }
208
+ };
209
+ //#endregion
210
+ //#region src/domain/enums/entitlement-status.enum.ts
211
+ /**
212
+ * Entitlement lifecycle status.
213
+ *
214
+ * active ⇄ suspended
215
+ * active → expired (window lapsed; written by the sweeper — derived at read-time)
216
+ * active → consumed (metered quota exhausted)
217
+ * active → revoked (admin pull / dispute) ── terminal
218
+ * active → refunded (payment reversed) ── terminal
219
+ * expired → active (renewal restarts the window)
220
+ * consumed → active (top-up restores quota)
221
+ * suspended → expired | revoked | refunded
222
+ *
223
+ * IMPORTANT: `expired` and `consumed` are LIFECYCLE markers a sweeper /
224
+ * consume() writes so the row can be queried and an event emitted once. The
225
+ * buyer-facing gate never depends on them — `evaluateAccess` (access-decision.ts)
226
+ * derives expiry/exhaustion from the window + usage directly, so a grant is
227
+ * denied the instant it lapses, before any status write. The row is never
228
+ * deleted: terminal states free the live-uniqueness slot for a fresh grant.
229
+ */
230
+ const ENTITLEMENT_STATUS = {
231
+ ACTIVE: "active",
232
+ SUSPENDED: "suspended",
233
+ EXPIRED: "expired",
234
+ CONSUMED: "consumed",
235
+ REVOKED: "revoked",
236
+ REFUNDED: "refunded"
237
+ };
238
+ const ENTITLEMENT_STATUS_VALUES = [
239
+ "active",
240
+ "suspended",
241
+ "expired",
242
+ "consumed",
243
+ "revoked",
244
+ "refunded"
245
+ ];
246
+ /** Statuses where the grant is still "live" (subject of the one-active-per-resource rule). */
247
+ const LIVE_STATUSES = ["active", "suspended"];
248
+ const SET = new Set(ENTITLEMENT_STATUS_VALUES);
249
+ const isEntitlementStatus = (v) => typeof v === "string" && SET.has(v);
250
+ const ENTITLEMENT_TRANSITIONS = {
251
+ active: [
252
+ "suspended",
253
+ "expired",
254
+ "consumed",
255
+ "revoked",
256
+ "refunded"
257
+ ],
258
+ suspended: [
259
+ "active",
260
+ "expired",
261
+ "revoked",
262
+ "refunded"
263
+ ],
264
+ expired: ["active"],
265
+ consumed: ["active"],
266
+ revoked: [],
267
+ refunded: []
268
+ };
269
+ /**
270
+ * The lifecycle as a STATE MACHINE, over the same {@link ENTITLEMENT_TRANSITIONS}
271
+ * table above.
272
+ *
273
+ * ## Why a machine and not just the predicate
274
+ *
275
+ * The table was already declared and already enforced — `transitionInner` is the
276
+ * single write funnel and it refuses an illegal move. What was missing is
277
+ * everything DERIVED from the table, which every consumer was left to re-derive:
278
+ *
279
+ * - **`terminal`** — computed from the empty outgoing lists, so `revoked` and
280
+ * `refunded` are terminal and nothing else is. A reporting layer asking "is
281
+ * this grant finished" must not carry its own list; two lists drift, and the
282
+ * one in the report is the one nobody tests.
283
+ * - **`validTargets` / `validSources`** — for a UI offering the legal next moves,
284
+ * instead of a hardcoded button set that silently diverges from the table.
285
+ * - **`assertTransition`** — the shape `@classytic/mongokit`'s `applyTransition`
286
+ * consumes, so a CAS write can pre-flight legality from the same source.
287
+ *
288
+ * ## What this says about churn, and it matters
289
+ *
290
+ * `expired → active` is LEGAL: a renewal restarts the window. So `expired` is not
291
+ * terminal, and **an expired membership is not a churned one** — it is a lapsed
292
+ * one that may still come back. Any churn metric that counts `expired` as lost
293
+ * is counting people who renew a week late. The machine is the authority for that
294
+ * distinction rather than a definition retyped in a dashboard.
295
+ *
296
+ * `errorFactory` returns this package's own {@link InvalidEntitlementTransitionError}
297
+ * (409) so the wire contract is unchanged — the machine replaces the predicate,
298
+ * not the error.
299
+ */
300
+ const ENTITLEMENT_MACHINE = defineStateMachine({
301
+ name: "Entitlement",
302
+ transitions: ENTITLEMENT_TRANSITIONS,
303
+ errorFactory: ({ from, to }) => new InvalidEntitlementTransitionError(from, to)
304
+ });
305
+ /**
306
+ * Delegates to {@link ENTITLEMENT_MACHINE}.
307
+ *
308
+ * Kept as a named export because it is part of the published surface; the body is
309
+ * now one line so the table cannot be consulted two different ways.
310
+ */
311
+ function canEntitlementTransition(from, to) {
312
+ return ENTITLEMENT_MACHINE.canTransition(from, to);
313
+ }
314
+ /**
315
+ * Is this grant finished for good? `revoked` / `refunded` only.
316
+ *
317
+ * Derived from the machine, never from a second list. `expired` and `consumed`
318
+ * are deliberately NOT terminal — both can return to `active` (renewal, top-up),
319
+ * and treating them as endings is how a report turns a late renewal into churn.
320
+ */
321
+ function isTerminalEntitlementStatus(status) {
322
+ return ENTITLEMENT_MACHINE.isTerminal(status);
323
+ }
324
+ /**
325
+ * Days after a lapse in which a renewal still counts as a renewal, not churn.
326
+ *
327
+ * 30 because a monthly membership renews monthly: a member who pays a week or two
328
+ * late is the ordinary case, not a loss. Shorter, and the number reports churn
329
+ * that walks back in the door; much longer, and a genuine loss stays uncounted
330
+ * for a quarter.
331
+ *
332
+ * A KERNEL default, not a host literal — the grace period is a business rule, and
333
+ * a threshold retyped per screen is how a dashboard and an export disagree about
334
+ * the same month. Override per call where a deployment genuinely differs.
335
+ */
336
+ const DEFAULT_CHURN_GRACE_DAYS = 30;
337
+ //#endregion
338
+ //#region src/events/event-constants.ts
339
+ /** ACCESS_EVENTS — the event names `@classytic/access` publishes. Subscribe by constant, never by literal. */
340
+ const ACCESS_EVENTS = {
341
+ GRANTED: "access:granted",
342
+ EXTENDED: "access:extended",
343
+ SUSPENDED: "access:suspended",
344
+ RESUMED: "access:resumed",
345
+ REVOKED: "access:revoked",
346
+ EXPIRED: "access:expired",
347
+ CONSUMED: "access:consumed",
348
+ EXHAUSTED: "access:exhausted",
349
+ REFUNDED: "access:refunded"
350
+ };
351
+ //#endregion
352
+ //#region src/events/event-catalog.ts
353
+ /**
354
+ * The access event catalog — one Zod schema per event is the contract; hosts register
355
+ * `accessEventDefinitions` with arc's `EventRegistry`. Every event carries the entitlement
356
+ * snapshot, so subscribers never re-fetch.
357
+ */
358
+ /** Zod → an object JSON Schema with single-typed properties; anything else throws at load. */
359
+ function toEventSchema(name, zodSchema) {
360
+ const json = z.toJSONSchema(zodSchema);
361
+ if (json.type !== "object") throw new Error(`[access] event ${name}: payload must be an object schema`);
362
+ const properties = {};
363
+ for (const [key, prop] of Object.entries(json.properties ?? {})) {
364
+ if (typeof prop === "boolean" || Array.isArray(prop.type)) throw new Error(`[access] event ${name}: property "${key}" must have one JSON type`);
365
+ const { type, ...rest } = prop;
366
+ properties[key] = type === void 0 ? rest : {
367
+ ...rest,
368
+ type
369
+ };
370
+ }
371
+ return {
372
+ type: "object",
373
+ properties,
374
+ ...json.required !== void 0 ? { required: [...json.required] } : {},
375
+ ...json.additionalProperties !== void 0 ? { additionalProperties: json.additionalProperties } : {}
376
+ };
377
+ }
378
+ function defineAccessEvent(input) {
379
+ const { name, description, version = 1, zodSchema } = input;
380
+ return {
381
+ name,
382
+ version,
383
+ description,
384
+ zodSchema,
385
+ payloadSchema: zodSchema,
386
+ schema: toEventSchema(name, zodSchema),
387
+ create(payload, meta) {
388
+ return createEvent(name, payload, {
389
+ resource: "entitlement",
390
+ source: "access",
391
+ ...meta
392
+ });
393
+ }
394
+ };
395
+ }
396
+ /**
397
+ * The entitlement snapshot every access event carries, INCLUDING the decision it now yields
398
+ * (`allowed` + `reason`). A consumer (credential sync, door controller) reads `allowed` instead of
399
+ * keeping its own event→liveness table, which drifts the day a new event is added.
400
+ */
401
+ const entitlementEventSchema = z.object({
402
+ entitlementId: z.string(),
403
+ organizationId: z.string().optional(),
404
+ subjectRef: z.string(),
405
+ subjectModel: z.string(),
406
+ resourceRef: z.string(),
407
+ resourceType: z.string(),
408
+ scopeKey: z.string(),
409
+ status: z.enum(ENTITLEMENT_STATUS_VALUES),
410
+ allowed: z.boolean(),
411
+ reason: z.enum(ACCESS_REASONS),
412
+ originModel: z.string().optional(),
413
+ originRef: z.string().optional(),
414
+ accessExpiresAt: z.iso.datetime().optional(),
415
+ usageLimit: z.number().optional(),
416
+ usageUsed: z.number().optional()
417
+ });
418
+ /** One idempotent spend — the snapshot plus what was spent under which key. */
419
+ const consumedEventSchema = entitlementEventSchema.extend({
420
+ consumptionKey: z.string(),
421
+ amount: z.number().int().positive()
422
+ });
423
+ const Granted = defineAccessEvent({
424
+ name: ACCESS_EVENTS.GRANTED,
425
+ description: "A subject was granted access to a resource for a window (or lifetime).",
426
+ zodSchema: entitlementEventSchema
427
+ });
428
+ const Extended = defineAccessEvent({
429
+ name: ACCESS_EVENTS.EXTENDED,
430
+ description: "An access window was pushed out / quota refreshed (a renewal or top-up).",
431
+ zodSchema: entitlementEventSchema
432
+ });
433
+ const Suspended = defineAccessEvent({
434
+ name: ACCESS_EVENTS.SUSPENDED,
435
+ description: "Access was paused without ending it (recoverable via access:resumed).",
436
+ zodSchema: entitlementEventSchema
437
+ });
438
+ const Resumed = defineAccessEvent({
439
+ name: ACCESS_EVENTS.RESUMED,
440
+ description: "A suspended grant was reactivated.",
441
+ zodSchema: entitlementEventSchema
442
+ });
443
+ const Revoked = defineAccessEvent({
444
+ name: ACCESS_EVENTS.REVOKED,
445
+ description: "Access was pulled permanently (admin action / dispute). Window cut to now.",
446
+ zodSchema: entitlementEventSchema
447
+ });
448
+ const Expired = defineAccessEvent({
449
+ name: ACCESS_EVENTS.EXPIRED,
450
+ description: "The access window lapsed and the sweeper marked the grant expired (renewable).",
451
+ zodSchema: entitlementEventSchema
452
+ });
453
+ const Consumed = defineAccessEvent({
454
+ name: ACCESS_EVENTS.CONSUMED,
455
+ description: "Metered units were spent under a consumption key (a usage record; never emitted for a replayed key).",
456
+ zodSchema: consumedEventSchema
457
+ });
458
+ const Exhausted = defineAccessEvent({
459
+ name: ACCESS_EVENTS.EXHAUSTED,
460
+ description: "A metered grant reached its quota and is consumed (downloads/API calls spent).",
461
+ zodSchema: entitlementEventSchema
462
+ });
463
+ const Refunded = defineAccessEvent({
464
+ name: ACCESS_EVENTS.REFUNDED,
465
+ description: "A grant was refunded (payment reversed). Access cut to now.",
466
+ zodSchema: entitlementEventSchema
467
+ });
468
+ const accessEventDefinitions = [
469
+ Granted,
470
+ Extended,
471
+ Suspended,
472
+ Resumed,
473
+ Revoked,
474
+ Expired,
475
+ Consumed,
476
+ Exhausted,
477
+ Refunded
478
+ ];
479
+ //#endregion
480
+ export { InvalidConsumeAmountError as A, ConsumptionInFlightError as C, EntitlementNotUsableError as D, EntitlementNotFoundError as E, SessionNotInTransactionError as F, SuspensionRefusedError as I, UnmanagedSessionError as L, InvalidExpiryWindowError as M, InvalidExtensionError as N, GrantProvenanceRequiredError as O, QuotaExhaustedError as P, VersionMismatchError as R, AccessError as S, ConsumptionKeyRequiredError as T, LIVE_STATUSES as _, Granted as a, isTerminalEntitlementStatus as b, Revoked as c, ACCESS_EVENTS as d, DEFAULT_CHURN_GRACE_DAYS as f, ENTITLEMENT_TRANSITIONS as g, ENTITLEMENT_STATUS_VALUES as h, Extended as i, InvalidEntitlementTransitionError as j, InvalidCheckRequestError as k, Suspended as l, ENTITLEMENT_STATUS as m, Exhausted as n, Refunded as o, ENTITLEMENT_MACHINE as p, Expired as r, Resumed as s, Consumed as t, accessEventDefinitions as u, canEntitlementTransition as v, ConsumptionKeyConflictError as w, AccessCapabilityError as x, isEntitlementStatus as y };