@classytic/access 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 — 2026-10-11
4
+
5
+ ### ⚠ Changed — read before upgrading
6
+
7
+ - **`checkExact` is gone; `check` is exact.** The target is `{ id }` or the COMPLETE identity tuple (`subjectModel` + `subjectRef` + `resourceType` + `resourceRef`). A partial tuple is refused with `InvalidCheckRequestError` instead of resolving to whichever row sorts first. Replace `checkExact(x, ctx)` with `check(x, ctx)`.
8
+ - **`consume(target, { key, amount? }, ctx)` — the idempotency key is required.** It was `consume(target, amount, ctx)`. A replayed key spends nothing and returns the first result; a reused key with a different amount throws `ConsumptionKeyConflictError` (409); a missing key throws `ConsumptionKeyRequiredError`; a concurrent duplicate throws `ConsumptionInFlightError`.
9
+ - **Every grant needs provenance.** `purchase` and `subscription` grants need the paying document (`originModel` + `originRef`); every other source needs that or an actor (`ctx.actorId`). Otherwise `GrantProvenanceRequiredError` (`access.grant.provenance_required`, 400).
10
+ - **Wire schemas are strict.** `grantSchema`, `checkSchema`, `consumeSchema`, `extendSchema` and `reasonSchema` refuse unknown keys instead of stripping them. `checkSchema` requires `subjectModel` and `resourceType`; `consumeSchema` requires `key`; `extendSchema` takes EXACTLY ONE of `accessExpiresAt` / `addMs` (`InvalidExtensionError`).
11
+ - **`AccessError.reason` is typed `AccessReason`** (it was `string`). `AccessReason` is now derived from the closed `ACCESS_REASONS` list, exported alongside it.
12
+ - **Event registry shape.** `AccessEventSchema` is an object JSON Schema (`{ type: 'object', properties, required }`), not `Record<string, unknown>`; each event definition also carries `payloadSchema` (the Zod schema). A payload that is not a single-typed object schema throws at load. Every event now carries the decision it yields (`allowed` + `reason`), so a consumer reads `allowed` instead of keeping its own event-to-liveness table.
13
+ - **A new collection.** `EntitlementConsumption` (`entitlement_consumptions`, unique `(entitlementId, key)`) is always registered; run your index sync on deploy. `access.models` gains `EntitlementConsumption`.
14
+
15
+ ### Added
16
+
17
+ - `checkMany(subject, capabilities, ctx)` — decide many capabilities for one subject in one query; results in input order.
18
+ - `listConsumptions(entitlementId, { limit }, ctx)` — the append-only usage ledger (who spent what, when).
19
+ - `grant` accepts `quotaMode` on a renewal of a live metered grant: `'reset'` (default — a new period restarts the limit and `used`) or `'add'` (a top-up — the limit grows, `used` is preserved). Only the caller knows which act occurred: two packs on one order are `'add'`, a monthly renewal is `'reset'`.
20
+ - A caller-owned `session` on the access context; it must be inside an active transaction when an outbox is wired.
21
+ - `runtime.clock` — an injectable clock for expiry and window decisions.
22
+
23
+ ### Fixed
24
+
25
+ - `evaluateAccess` looked a status up in an object literal: a stored status of `'constructor'` or `'toString'` hit a prototype member and reported a reason outside the closed set. It is a `Map` now, and such a status denies as `invalid_grant`.
26
+ - A non-finite `now` or a non-integer quota denies (`invalid_grant`) instead of evaluating.
27
+ - The live-flag hook is registered once for `updateOne`, `updateMany` and `findOneAndUpdate`; each repository gets its own tenant-plugin instance.
28
+
29
+ ### Changed — peer floors raised to current
30
+
31
+ `@classytic/mongokit` `>=3.39.0` → **`>=3.41.0`**, `@classytic/primitives` `>=0.28.0` → **`>=0.31.1`**, `@classytic/repo-core` `>=0.28.0` → **`>=0.31.0`**, `mongoose` `>=9.4.1` → **`>=9.11.0`** (mongokit 3.41 requires it). Verified on a fresh install.
32
+
3
33
  ## 0.3.0 — 2026-09-13
4
34
 
5
35
  ### Added — `indexes`: the host declares the indexes this package cannot know about
package/README.md CHANGED
@@ -62,13 +62,10 @@ await access.repositories.entitlement.grant(
62
62
  { organizationId: orgId },
63
63
  );
64
64
 
65
- // Gate a lesson — use checkExact() at any security boundary.
66
- // The COMPLETE identity tuple is required, so two subject namespaces sharing an
67
- // id (a `user` and an `apiKey` both keyed `42`), or two resource types sharing a
68
- // ref, cannot resolve to each other's grant. The loose `check()` form below
69
- // leaves those optional and answers for whichever row sorts first — which fails
70
- // OPEN when the other namespace happens to hold a live grant.
71
- const { allowed, reason } = await access.repositories.entitlement.checkExact(
65
+ // Gate a lesson. The target is { id } or the COMPLETE identity tuple, so two subject
66
+ // namespaces sharing an id (a `user` and an `apiKey` both keyed `42`), or two resource types
67
+ // sharing a ref, cannot resolve to each other's grant.
68
+ const { allowed, reason } = await access.repositories.entitlement.check(
72
69
  { subjectModel: 'user', subjectRef: userId, resourceType: 'course', resourceRef: courseId },
73
70
  { organizationId: orgId },
74
71
  );
@@ -80,15 +77,16 @@ if (!allowed) return reply.code(403).send({ code: `access.${reason}` });
80
77
  | Verb | Purpose |
81
78
  |---|---|
82
79
  | `grant(input, ctx)` | Idempotent grant (atomic `getOrCreate` per live subject+resource+scope). Re-grant restarts the window. Emits `access:granted` / `access:extended`. |
83
- | `checkExact(target, ctx)` | **Use this at security boundaries.** Same as `check`, but the full identity tuple (`subjectModel` + `subjectRef` + `resourceType` + `resourceRef`) is REQUIRED, so shared ids across namespaces cannot resolve to the wrong grant. |
84
- | `check(target, ctx)` | **Hot path.** Read-only `evaluateAccess` → `{ allowed, reason, expiresAt, remaining, entitlement }`. Target by `{ id }`, or by subject+resource — where `subjectModel`/`resourceType` are optional for back-compat. **Legacy for polymorphic hosts:** an incomplete tuple is an ambiguous question. Prefer `checkExact`. |
85
- | `consume(target, amount, ctx)` | Spend metered units (download / API call / seat). Race-proof `$expr` capacity guard; flips to `consumed` + emits `access:exhausted` at the cap. |
80
+ | `checkMany(subject, capabilities, ctx)` | Decide many capabilities for ONE subject in ONE query. Results come back in input order; an empty list is refused. |
81
+ | `check(target, ctx)` | **Hot path.** Read-only `evaluateAccess` → `{ allowed, reason, expiresAt, remaining, entitlement }`. The target is `{ id }` or the COMPLETE identity tuple (`subjectModel` + `subjectRef` + `resourceType` + `resourceRef`); a partial tuple is refused (`InvalidCheckRequestError`), never resolved to "whichever row sorts first". |
82
+ | `consume(target, { key, amount? }, ctx)` | Spend metered units (download / API call / seat) under a REQUIRED idempotency key: a replayed key spends nothing, a reused key with a different amount throws `ConsumptionKeyConflictError`. Race-proof capacity guard; flips to `consumed` + emits `access:exhausted` at the cap. |
83
+ | `listConsumptions(entitlementId, { limit }, ctx)` | The append-only usage ledger of one grant (who spent what, when). |
86
84
  | `extend(id, { accessExpiresAt \| addMs }, ctx)` | Renew — push the window out / reactivate an `expired` grant. Emits `access:extended`. |
87
85
  | `suspend` / `resume` | Pause and restore (membership freeze). |
88
86
  | `revoke(id, { reason }, ctx)` | Pull access permanently (terminal). |
89
87
  | `expireDue({ now, limit }, ctx)` | **Sweeper** (host cron): CAS `active → expired` for lapsed windows, emits `access:expired`. The row survives. |
90
88
  | `refundByOrigin(model, ref, ctx)` | Cascade: mark every live grant from an order/transaction `refunded`. |
91
- | `listForSubject(subjectRef, ctx, options?)` | A bounded subject grant list, newest-first; options narrow subject model, resource type, and live grants. |
89
+ | `listForSubject(subjectRef, ctx, options?)` | A bounded subject grant list, newest-first; options narrow subject model, resource type, and live grants. |
92
90
 
93
91
  ## Metered access (API / downloads / seats)
94
92
 
@@ -100,7 +98,7 @@ const e = await access.repositories.entitlement.grant(
100
98
  scopeKey: 'reports:read', usageLimit: 1000, source: 'subscription' },
101
99
  ctx,
102
100
  );
103
- await access.repositories.entitlement.consume({ id: String(e._id) }, 1, ctx); // 999 left
101
+ await access.repositories.entitlement.consume({ id: String(e._id) }, { key: scanId, amount: 1 }, ctx); // 999 left; a repeat of `scanId` spends nothing
104
102
  // 1000 concurrent consumes → exactly 1000 succeed, the rest throw QuotaExhaustedError
105
103
  ```
106
104
 
@@ -121,7 +119,7 @@ export default defineResource({
121
119
  resume: { handler: (id, _d, req) => access.repositories.entitlement.resume(id, req.scope) },
122
120
  revoke: { handler: (id, d, req) => access.repositories.entitlement.revoke(id, d, req.scope) },
123
121
  extend: { handler: (id, d, req) => access.repositories.entitlement.extend(id, d, req.scope) },
124
- consume: { handler: (id, d, req) => access.repositories.entitlement.consume({ id }, d.amount, req.scope) },
122
+ consume: { handler: (id, d, req) => access.repositories.entitlement.consume({ id }, { key: d.key, amount: d.amount }, req.scope) },
125
123
  },
126
124
  });
127
125
 
@@ -1,52 +1,21 @@
1
1
  //#region src/domain/access-decision.d.ts
2
2
  /**
3
- * The access decision — the heart of `@classytic/access`.
3
+ * `evaluateAccess` — the ONE access rule: pure, no I/O, published at
4
+ * `@classytic/access/decision` so server, edge and UI evaluate identically.
4
5
  *
5
- * `evaluateAccess` is a PURE function (no mongoose, no I/O) that answers the
6
- * one question every gate asks: "does this subject hold a live grant RIGHT
7
- * NOW?". It is published at the `@classytic/access/decision` subpath so the
8
- * exact same rule runs on the server hot path, in an edge/middleware check,
9
- * and in the UI — one source of truth, zero drift.
10
- *
11
- * ── FAIL CLOSED, by construction ──────────────────────────────────────────
12
- * `active` is the ONLY status that can allow. Everything else — a terminal
13
- * status, a stored `expired`, a status this version has never heard of, a
14
- * malformed date, a NaN quota — denies. The earlier shape (deny-list four
15
- * statuses, allow the rest) failed OPEN: `status: 'disabled'` from a future
16
- * version, or a stored `expired` whose window field was later nulled, sailed
17
- * through to `allowed: true`. For an access engine that is the wrong default
18
- * in the same way an unlocked door is: the failure grants entry and leaves no
19
- * error to notice.
20
- *
21
- * The same rule covers malformed input. An unparseable `accessExpiresAt` used
22
- * to coerce to "no boundary" — lifetime access as the reward for data
23
- * corruption. Absence and invalidity are now DIFFERENT things: absent means
24
- * "no boundary" (a deliberate lifetime grant), invalid means "this row cannot
25
- * be trusted" and denies as `invalid_grant`.
26
- *
27
- * ── Why a function and not a stored flag ──────────────────────────────────
28
- * An entitlement's stored `status` records only explicit LIFECYCLE events
29
- * (granted → active, suspended, revoked, refunded, consumed). Expiry is NEVER
30
- * written by the buyer-facing path: it is DERIVED here from the window. That is
31
- * what lets the row survive as a permanent record (audit, renewal, "renew"
32
- * upsell) instead of being TTL-deleted. A background sweeper may later CAS the
33
- * stored status to `expired` and emit `access:expired`, but the gate never
34
- * waits for it: a grant past its window evaluates to `expired` here the
35
- * instant it lapses, covering the sweep lag.
36
- *
37
- * Deny precedence is explicit and ordered (most-terminal first) so the reason
38
- * a host surfaces is the most meaningful one.
6
+ * FAIL CLOSED: only `status: 'active'` inside its window with quota left allows. Every other
7
+ * status, an unknown status, an unparseable date, a non-integer quota or a non-finite `now`
8
+ * denies. Absent window fields mean "no boundary"; INVALID ones mean `invalid_grant`.
9
+ * Expiry is derived here, never waited on from the sweeper.
39
10
  */
40
- /** Why a grant is or isn't usable right now. `active` is the only allow. */
41
- type AccessReason = 'active' | 'not_found' | 'not_yet_active' | 'expired' | 'suspended' | 'revoked' | 'refunded' | 'consumed' | 'quota_exhausted' |
42
11
  /**
43
- * The grant exists but cannot be trusted: a status this engine does not
44
- * recognise, an unparseable date, a non-finite quota. Distinct from
45
- * `not_found` so a host can ALERT on it — an `invalid_grant` in production
46
- * means corrupted data or a version skew, and both deserve a page, not a
47
- * silent deny that reads like a lapsed membership.
12
+ * Every reason a decision can carry — a CLOSED set. `active` is the only allow.
13
+ * `invalid_grant` means a row that cannot be trusted (unknown status, unparseable date,
14
+ * non-integer quota): alert on it, it is corruption or version skew, not a lapsed member.
48
15
  */
49
- 'invalid_grant';
16
+ declare const ACCESS_REASONS: readonly ["active", "not_found", "not_yet_active", "expired", "suspended", "revoked", "refunded", "consumed", "quota_exhausted", "invalid_grant"];
17
+ /** Why a grant is or isn't usable right now. */
18
+ type AccessReason = (typeof ACCESS_REASONS)[number];
50
19
  /**
51
20
  * The minimal shape `evaluateAccess` reads. A full `EntitlementDocument`
52
21
  * structurally satisfies it, and so does a hand-built object on the wire — the
@@ -85,4 +54,4 @@ declare function evaluateAccess(grant: AccessGrantState | null | undefined, now?
85
54
  /** Convenience boolean for the common gate. */
86
55
  declare function hasAccess(grant: AccessGrantState | null | undefined, now?: number): boolean;
87
56
  //#endregion
88
- export { AccessDecision, AccessGrantState, AccessReason, evaluateAccess, hasAccess };
57
+ export { ACCESS_REASONS, AccessDecision, AccessGrantState, AccessReason, evaluateAccess, hasAccess };
@@ -1,20 +1,42 @@
1
1
  //#region src/domain/access-decision.ts
2
- /** Statuses that deny regardless of the window, mapped to their reason. */
3
- const TERMINAL_DENY = {
4
- revoked: "revoked",
5
- refunded: "refunded",
6
- suspended: "suspended",
7
- consumed: "consumed",
8
- /**
9
- * Stored `expired` denies EXPLICITLY, not via window math. The sweeper wrote
10
- * it because the window had lapsed — but the window field can be nulled or
11
- * mangled afterwards (a bad migration, a hand edit), and the earlier code
12
- * then re-derived "no boundary" and allowed. The status is a lifecycle fact
13
- * in its own right; only `extend()` (which CAS-transitions back to active)
14
- * may reopen the grant.
15
- */
16
- expired: "expired"
17
- };
2
+ /**
3
+ * `evaluateAccess` — the ONE access rule: pure, no I/O, published at
4
+ * `@classytic/access/decision` so server, edge and UI evaluate identically.
5
+ *
6
+ * FAIL CLOSED: only `status: 'active'` inside its window with quota left allows. Every other
7
+ * status, an unknown status, an unparseable date, a non-integer quota or a non-finite `now`
8
+ * denies. Absent window fields mean "no boundary"; INVALID ones mean `invalid_grant`.
9
+ * Expiry is derived here, never waited on from the sweeper.
10
+ */
11
+ /**
12
+ * Every reason a decision can carry — a CLOSED set. `active` is the only allow.
13
+ * `invalid_grant` means a row that cannot be trusted (unknown status, unparseable date,
14
+ * non-integer quota): alert on it, it is corruption or version skew, not a lapsed member.
15
+ */
16
+ const ACCESS_REASONS = [
17
+ "active",
18
+ "not_found",
19
+ "not_yet_active",
20
+ "expired",
21
+ "suspended",
22
+ "revoked",
23
+ "refunded",
24
+ "consumed",
25
+ "quota_exhausted",
26
+ "invalid_grant"
27
+ ];
28
+ /**
29
+ * Statuses that deny regardless of the window. A Map, not an object literal: a status of
30
+ * `'constructor'` or `'toString'` must miss here and fall to `invalid_grant`, not hit a
31
+ * prototype member and report a reason outside the closed set.
32
+ */
33
+ const TERMINAL_DENY = /* @__PURE__ */ new Map([
34
+ ["revoked", "revoked"],
35
+ ["refunded", "refunded"],
36
+ ["suspended", "suspended"],
37
+ ["consumed", "consumed"],
38
+ ["expired", "expired"]
39
+ ]);
18
40
  /** Sentinel distinguishing "present but unparseable" from "absent". */
19
41
  const INVALID = Symbol("invalid-date");
20
42
  /**
@@ -60,7 +82,7 @@ function evaluateAccess(grant, now = Date.now()) {
60
82
  const used = grant.usage?.used ?? 0;
61
83
  if (!(Number.isInteger(used) && used >= 0 && (limit === null || Number.isInteger(limit) && limit >= 0))) return decision(false, "invalid_grant", expiresAt, null);
62
84
  const remaining = limit === null ? null : Math.max(0, limit - used);
63
- const terminal = TERMINAL_DENY[grant.status];
85
+ const terminal = TERMINAL_DENY.get(grant.status);
64
86
  if (terminal) return decision(false, terminal, expiresAt, remaining);
65
87
  if (grant.status !== "active") return decision(false, "invalid_grant", expiresAt, remaining);
66
88
  if (notBeforeRaw !== null && notBeforeRaw > now) return decision(false, "not_yet_active", expiresAt, remaining);
@@ -88,4 +110,4 @@ function hasAccess(grant, now = Date.now()) {
88
110
  return evaluateAccess(grant, now).allowed;
89
111
  }
90
112
  //#endregion
91
- export { evaluateAccess, hasAccess };
113
+ export { ACCESS_REASONS, evaluateAccess, hasAccess };