@classytic/access 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3 -74
- package/README.md +11 -13
- package/dist/domain/access-decision.d.mts +13 -44
- package/dist/domain/access-decision.mjs +40 -18
- package/dist/event-catalog-CIxQavRC.mjs +480 -0
- package/dist/event-catalog-DarRYj3Y.d.mts +358 -0
- package/dist/events/event-catalog.d.mts +2 -2
- package/dist/events/event-catalog.mjs +2 -2
- package/dist/index.d.mts +203 -438
- package/dist/index.mjs +598 -1133
- package/dist/schemas/entitlement.d.mts +16 -10
- package/dist/schemas/entitlement.mjs +19 -14
- package/llms.txt +27 -0
- package/package.json +18 -11
- package/skills/access/SKILL.md +116 -0
- package/skills/access/references/events-errors.md +46 -0
- package/skills/access/references/repository.md +72 -0
- package/skills/access/references/wiring.md +60 -0
- package/dist/event-catalog-BVD_rFlc.mjs +0 -111
- package/dist/event-catalog-Dxo3cxR3.d.mts +0 -136
package/CHANGELOG.md
CHANGED
|
@@ -1,78 +1,7 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## Unreleased
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
The gate indexes the entitlement collection by (subject, resource) and by
|
|
8
|
-
resource; a host's creator roster sorts by activity, progress or name within a
|
|
9
|
-
course, its rank rollup counts purchased grants per org, and its retention
|
|
10
|
-
sweep spans every tenant. None of those can be known here, and before this
|
|
11
|
-
seam the only way to add one was a `collection.createIndex()` after bind, which
|
|
12
|
-
the deploy step cannot see and the next `syncIndexes` drops.
|
|
13
|
-
|
|
14
|
-
`AccessShape.indexes` takes `IndexDeclaration`s from `@classytic/mongokit/tenant`:
|
|
15
|
-
`scope: 'tenant'` (default) is prefixed exactly like the package's own,
|
|
16
|
-
`scope: 'global'` is kept as written for a read that has no tenant to give and
|
|
17
|
-
must be named. A bad declaration is refused at describe time. Reported on
|
|
18
|
-
`engine.config.indexes`.
|
|
19
|
-
|
|
20
|
-
### Changed — tenant injection is `@classytic/mongokit/tenant`'s
|
|
21
|
-
|
|
22
|
-
`src/models/inject-tenant.ts` re-exports the shared implementation (PACKAGE_RULES
|
|
23
|
-
P11) instead of carrying a copy. Behaviour is unchanged for the package's own
|
|
24
|
-
indexes. Requires `@classytic/mongokit >=3.39.0`.
|
|
25
|
-
|
|
26
|
-
### Changed — peer floors raised to current
|
|
27
|
-
|
|
28
|
-
- `@classytic/primitives` `>=0.23.0` → **`>=0.28.0`**
|
|
29
|
-
- `@classytic/repo-core` `>=0.24.0` → **`>=0.28.0`**
|
|
30
|
-
|
|
31
|
-
## 0.2.0 — 2026-08-17
|
|
32
|
-
|
|
33
|
-
### Added
|
|
34
|
-
- `defineAccess` describe/bind API replacing `createAccess`
|
|
35
|
-
|
|
36
|
-
### Changed
|
|
37
|
-
- `entitlement.model`, `entitlement.repository`, domain errors, dispatch, in-process bus updated; outbox-store consolidated
|
|
38
|
-
|
|
39
|
-
## 0.1.3 - 2026-07-22 (unpublished)
|
|
40
|
-
|
|
41
|
-
### Changed
|
|
42
|
-
- Internal: `InProcess*Bus` is now a thin subclass of `@classytic/primitives/event-infra`'s shared `InProcessEventBus` (dedup / error-isolation / close semantics unchanged); `MemoryOutboxStore` re-exported from the shared runtime where applicable. No public API, event-name, or wire-envelope change. Requires `@classytic/primitives >=0.13.0`.
|
|
43
|
-
|
|
44
|
-
## 0.1.1
|
|
45
|
-
|
|
46
|
-
Patch — §P8.1 session guard (UnmanagedSessionError), ISO 4217 currency gate via CURRENCY_PATTERN.
|
|
47
|
-
|
|
48
|
-
## 0.1.0
|
|
49
|
-
|
|
50
|
-
Initial release — the access **entitlement** engine.
|
|
51
|
-
|
|
52
|
-
- `Entitlement` model: a durable, polymorphic (subject ⇄ resource) grant with a
|
|
53
|
-
window (`notBefore` / `accessExpiresAt`), optional metering (`usage`), and
|
|
54
|
-
polymorphic provenance (`originRef` / `originModel`). No TTL index — expiry is
|
|
55
|
-
modelled as a CAS state transition so the row survives as a record.
|
|
56
|
-
- `evaluateAccess` — the pure decision, published at the `@classytic/access/decision`
|
|
57
|
-
subpath (no mongoose) so the same rule runs on the server, edge, and UI.
|
|
58
|
-
- `EntitlementRepository` verbs: `grant` (idempotent, renewing), `check` (hot
|
|
59
|
-
path), `consume` (race-proof metered spend), `extend`, `suspend` / `resume`,
|
|
60
|
-
`revoke`, `expireDue` (sweeper), `refundByOrigin` (cascade), `listForSubject`.
|
|
61
|
-
- Events: `access:granted | extended | suspended | resumed | revoked | expired |
|
|
62
|
-
exhausted | refunded`, with a Zod-source `accessEventDefinitions` catalog.
|
|
63
|
-
- Engine factory `createAccess`, capability boot gate, multi-tenant plugin,
|
|
64
|
-
soft delete, in-process event fallback, P4/P8 outbox seams.
|
|
65
|
-
- 30 tests: decision truth table, FSM, event-catalog no-drift, tenant probe,
|
|
66
|
-
and three scenarios (time-bound course access + renewal, metered API quota
|
|
67
|
-
with a concurrency race, lifecycle + refund cascade).
|
|
68
|
-
|
|
69
|
-
## [0.1.2] — 2026-07-16
|
|
70
|
-
|
|
71
|
-
### Fixed
|
|
72
|
-
|
|
73
|
-
- injectTenantField no longer force-indexes the tenant field: the compound
|
|
74
|
-
prepend makes the tenant the leading key of every index, so the bare single
|
|
75
|
-
was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
|
|
76
|
-
index audit). A dedicated tenant index is still created when a schema
|
|
77
|
-
declares no compounds to prepend. Index-declaration change only.
|
|
5
|
+
## 0.4.1 — 2026-11-28
|
|
78
6
|
|
|
7
|
+
- Peer floors raised to what the package is tested against: `@classytic/mongokit >=3.47.0`, `@classytic/primitives >=0.39.0`, `@classytic/repo-core >=0.39.0`, `mongoose >=9.13.1`; the `skills/` references ship current. Consumers: none to change.
|
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
|
|
66
|
-
//
|
|
67
|
-
//
|
|
68
|
-
|
|
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
|
-
| `
|
|
84
|
-
| `check(target, ctx)` | **Hot path.** Read-only `evaluateAccess` → `{ allowed, reason, expiresAt, remaining, entitlement }`.
|
|
85
|
-
| `consume(target, amount, ctx)` | Spend metered units (download / API call / seat)
|
|
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
|
-
*
|
|
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
|
-
* `
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
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
|
-
|
|
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
|
-
/**
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
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 };
|