@classytic/access 0.4.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 CHANGED
@@ -1,108 +1,7 @@
1
1
  # Changelog
2
2
 
3
- ## 0.4.0 — 2026-10-11
3
+ ## Unreleased
4
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
-
33
- ## 0.3.0 — 2026-09-13
34
-
35
- ### Added — `indexes`: the host declares the indexes this package cannot know about
36
-
37
- The gate indexes the entitlement collection by (subject, resource) and by
38
- resource; a host's creator roster sorts by activity, progress or name within a
39
- course, its rank rollup counts purchased grants per org, and its retention
40
- sweep spans every tenant. None of those can be known here, and before this
41
- seam the only way to add one was a `collection.createIndex()` after bind, which
42
- the deploy step cannot see and the next `syncIndexes` drops.
43
-
44
- `AccessShape.indexes` takes `IndexDeclaration`s from `@classytic/mongokit/tenant`:
45
- `scope: 'tenant'` (default) is prefixed exactly like the package's own,
46
- `scope: 'global'` is kept as written for a read that has no tenant to give and
47
- must be named. A bad declaration is refused at describe time. Reported on
48
- `engine.config.indexes`.
49
-
50
- ### Changed — tenant injection is `@classytic/mongokit/tenant`'s
51
-
52
- `src/models/inject-tenant.ts` re-exports the shared implementation (PACKAGE_RULES
53
- P11) instead of carrying a copy. Behaviour is unchanged for the package's own
54
- indexes. Requires `@classytic/mongokit >=3.39.0`.
55
-
56
- ### Changed — peer floors raised to current
57
-
58
- - `@classytic/primitives` `>=0.23.0` → **`>=0.28.0`**
59
- - `@classytic/repo-core` `>=0.24.0` → **`>=0.28.0`**
60
-
61
- ## 0.2.0 — 2026-08-17
62
-
63
- ### Added
64
- - `defineAccess` describe/bind API replacing `createAccess`
65
-
66
- ### Changed
67
- - `entitlement.model`, `entitlement.repository`, domain errors, dispatch, in-process bus updated; outbox-store consolidated
68
-
69
- ## 0.1.3 - 2026-07-22 (unpublished)
70
-
71
- ### Changed
72
- - 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`.
73
-
74
- ## 0.1.1
75
-
76
- Patch — §P8.1 session guard (UnmanagedSessionError), ISO 4217 currency gate via CURRENCY_PATTERN.
77
-
78
- ## 0.1.0
79
-
80
- Initial release — the access **entitlement** engine.
81
-
82
- - `Entitlement` model: a durable, polymorphic (subject ⇄ resource) grant with a
83
- window (`notBefore` / `accessExpiresAt`), optional metering (`usage`), and
84
- polymorphic provenance (`originRef` / `originModel`). No TTL index — expiry is
85
- modelled as a CAS state transition so the row survives as a record.
86
- - `evaluateAccess` — the pure decision, published at the `@classytic/access/decision`
87
- subpath (no mongoose) so the same rule runs on the server, edge, and UI.
88
- - `EntitlementRepository` verbs: `grant` (idempotent, renewing), `check` (hot
89
- path), `consume` (race-proof metered spend), `extend`, `suspend` / `resume`,
90
- `revoke`, `expireDue` (sweeper), `refundByOrigin` (cascade), `listForSubject`.
91
- - Events: `access:granted | extended | suspended | resumed | revoked | expired |
92
- exhausted | refunded`, with a Zod-source `accessEventDefinitions` catalog.
93
- - Engine factory `createAccess`, capability boot gate, multi-tenant plugin,
94
- soft delete, in-process event fallback, P4/P8 outbox seams.
95
- - 30 tests: decision truth table, FSM, event-catalog no-drift, tenant probe,
96
- and three scenarios (time-bound course access + renewal, metered API quota
97
- with a concurrency race, lifecycle + refund cascade).
98
-
99
- ## [0.1.2] — 2026-07-16
100
-
101
- ### Fixed
102
-
103
- - injectTenantField no longer force-indexes the tenant field: the compound
104
- prepend makes the tenant the leading key of every index, so the bare single
105
- was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
106
- index audit). A dedicated tenant index is still created when a schema
107
- declares no compounds to prepend. Index-declaration change only.
5
+ ## 0.4.1 — 2026-11-28
108
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.
@@ -46,22 +46,22 @@ declare const Granted: AccessEventDefinition<z.ZodObject<{
46
46
  scopeKey: z.ZodString;
47
47
  status: z.ZodEnum<{
48
48
  active: "active";
49
- expired: "expired";
50
49
  suspended: "suspended";
50
+ expired: "expired";
51
+ consumed: "consumed";
51
52
  revoked: "revoked";
52
53
  refunded: "refunded";
53
- consumed: "consumed";
54
54
  }>;
55
55
  allowed: z.ZodBoolean;
56
56
  reason: z.ZodEnum<{
57
57
  active: "active";
58
- not_found: "not_found";
59
- not_yet_active: "not_yet_active";
60
- expired: "expired";
61
58
  suspended: "suspended";
59
+ expired: "expired";
60
+ consumed: "consumed";
62
61
  revoked: "revoked";
63
62
  refunded: "refunded";
64
- consumed: "consumed";
63
+ not_found: "not_found";
64
+ not_yet_active: "not_yet_active";
65
65
  quota_exhausted: "quota_exhausted";
66
66
  invalid_grant: "invalid_grant";
67
67
  }>;
@@ -81,22 +81,22 @@ declare const Extended: AccessEventDefinition<z.ZodObject<{
81
81
  scopeKey: z.ZodString;
82
82
  status: z.ZodEnum<{
83
83
  active: "active";
84
- expired: "expired";
85
84
  suspended: "suspended";
85
+ expired: "expired";
86
+ consumed: "consumed";
86
87
  revoked: "revoked";
87
88
  refunded: "refunded";
88
- consumed: "consumed";
89
89
  }>;
90
90
  allowed: z.ZodBoolean;
91
91
  reason: z.ZodEnum<{
92
92
  active: "active";
93
- not_found: "not_found";
94
- not_yet_active: "not_yet_active";
95
- expired: "expired";
96
93
  suspended: "suspended";
94
+ expired: "expired";
95
+ consumed: "consumed";
97
96
  revoked: "revoked";
98
97
  refunded: "refunded";
99
- consumed: "consumed";
98
+ not_found: "not_found";
99
+ not_yet_active: "not_yet_active";
100
100
  quota_exhausted: "quota_exhausted";
101
101
  invalid_grant: "invalid_grant";
102
102
  }>;
@@ -116,22 +116,22 @@ declare const Suspended: AccessEventDefinition<z.ZodObject<{
116
116
  scopeKey: z.ZodString;
117
117
  status: z.ZodEnum<{
118
118
  active: "active";
119
- expired: "expired";
120
119
  suspended: "suspended";
120
+ expired: "expired";
121
+ consumed: "consumed";
121
122
  revoked: "revoked";
122
123
  refunded: "refunded";
123
- consumed: "consumed";
124
124
  }>;
125
125
  allowed: z.ZodBoolean;
126
126
  reason: z.ZodEnum<{
127
127
  active: "active";
128
- not_found: "not_found";
129
- not_yet_active: "not_yet_active";
130
- expired: "expired";
131
128
  suspended: "suspended";
129
+ expired: "expired";
130
+ consumed: "consumed";
132
131
  revoked: "revoked";
133
132
  refunded: "refunded";
134
- consumed: "consumed";
133
+ not_found: "not_found";
134
+ not_yet_active: "not_yet_active";
135
135
  quota_exhausted: "quota_exhausted";
136
136
  invalid_grant: "invalid_grant";
137
137
  }>;
@@ -151,22 +151,22 @@ declare const Resumed: AccessEventDefinition<z.ZodObject<{
151
151
  scopeKey: z.ZodString;
152
152
  status: z.ZodEnum<{
153
153
  active: "active";
154
- expired: "expired";
155
154
  suspended: "suspended";
155
+ expired: "expired";
156
+ consumed: "consumed";
156
157
  revoked: "revoked";
157
158
  refunded: "refunded";
158
- consumed: "consumed";
159
159
  }>;
160
160
  allowed: z.ZodBoolean;
161
161
  reason: z.ZodEnum<{
162
162
  active: "active";
163
- not_found: "not_found";
164
- not_yet_active: "not_yet_active";
165
- expired: "expired";
166
163
  suspended: "suspended";
164
+ expired: "expired";
165
+ consumed: "consumed";
167
166
  revoked: "revoked";
168
167
  refunded: "refunded";
169
- consumed: "consumed";
168
+ not_found: "not_found";
169
+ not_yet_active: "not_yet_active";
170
170
  quota_exhausted: "quota_exhausted";
171
171
  invalid_grant: "invalid_grant";
172
172
  }>;
@@ -186,22 +186,22 @@ declare const Revoked: AccessEventDefinition<z.ZodObject<{
186
186
  scopeKey: z.ZodString;
187
187
  status: z.ZodEnum<{
188
188
  active: "active";
189
- expired: "expired";
190
189
  suspended: "suspended";
190
+ expired: "expired";
191
+ consumed: "consumed";
191
192
  revoked: "revoked";
192
193
  refunded: "refunded";
193
- consumed: "consumed";
194
194
  }>;
195
195
  allowed: z.ZodBoolean;
196
196
  reason: z.ZodEnum<{
197
197
  active: "active";
198
- not_found: "not_found";
199
- not_yet_active: "not_yet_active";
200
- expired: "expired";
201
198
  suspended: "suspended";
199
+ expired: "expired";
200
+ consumed: "consumed";
202
201
  revoked: "revoked";
203
202
  refunded: "refunded";
204
- consumed: "consumed";
203
+ not_found: "not_found";
204
+ not_yet_active: "not_yet_active";
205
205
  quota_exhausted: "quota_exhausted";
206
206
  invalid_grant: "invalid_grant";
207
207
  }>;
@@ -221,22 +221,22 @@ declare const Expired: AccessEventDefinition<z.ZodObject<{
221
221
  scopeKey: z.ZodString;
222
222
  status: z.ZodEnum<{
223
223
  active: "active";
224
- expired: "expired";
225
224
  suspended: "suspended";
225
+ expired: "expired";
226
+ consumed: "consumed";
226
227
  revoked: "revoked";
227
228
  refunded: "refunded";
228
- consumed: "consumed";
229
229
  }>;
230
230
  allowed: z.ZodBoolean;
231
231
  reason: z.ZodEnum<{
232
232
  active: "active";
233
- not_found: "not_found";
234
- not_yet_active: "not_yet_active";
235
- expired: "expired";
236
233
  suspended: "suspended";
234
+ expired: "expired";
235
+ consumed: "consumed";
237
236
  revoked: "revoked";
238
237
  refunded: "refunded";
239
- consumed: "consumed";
238
+ not_found: "not_found";
239
+ not_yet_active: "not_yet_active";
240
240
  quota_exhausted: "quota_exhausted";
241
241
  invalid_grant: "invalid_grant";
242
242
  }>;
@@ -256,22 +256,22 @@ declare const Consumed: AccessEventDefinition<z.ZodObject<{
256
256
  scopeKey: z.ZodString;
257
257
  status: z.ZodEnum<{
258
258
  active: "active";
259
- expired: "expired";
260
259
  suspended: "suspended";
260
+ expired: "expired";
261
+ consumed: "consumed";
261
262
  revoked: "revoked";
262
263
  refunded: "refunded";
263
- consumed: "consumed";
264
264
  }>;
265
265
  allowed: z.ZodBoolean;
266
266
  reason: z.ZodEnum<{
267
267
  active: "active";
268
- not_found: "not_found";
269
- not_yet_active: "not_yet_active";
270
- expired: "expired";
271
268
  suspended: "suspended";
269
+ expired: "expired";
270
+ consumed: "consumed";
272
271
  revoked: "revoked";
273
272
  refunded: "refunded";
274
- consumed: "consumed";
273
+ not_found: "not_found";
274
+ not_yet_active: "not_yet_active";
275
275
  quota_exhausted: "quota_exhausted";
276
276
  invalid_grant: "invalid_grant";
277
277
  }>;
@@ -293,22 +293,22 @@ declare const Exhausted: AccessEventDefinition<z.ZodObject<{
293
293
  scopeKey: z.ZodString;
294
294
  status: z.ZodEnum<{
295
295
  active: "active";
296
- expired: "expired";
297
296
  suspended: "suspended";
297
+ expired: "expired";
298
+ consumed: "consumed";
298
299
  revoked: "revoked";
299
300
  refunded: "refunded";
300
- consumed: "consumed";
301
301
  }>;
302
302
  allowed: z.ZodBoolean;
303
303
  reason: z.ZodEnum<{
304
304
  active: "active";
305
- not_found: "not_found";
306
- not_yet_active: "not_yet_active";
307
- expired: "expired";
308
305
  suspended: "suspended";
306
+ expired: "expired";
307
+ consumed: "consumed";
309
308
  revoked: "revoked";
310
309
  refunded: "refunded";
311
- consumed: "consumed";
310
+ not_found: "not_found";
311
+ not_yet_active: "not_yet_active";
312
312
  quota_exhausted: "quota_exhausted";
313
313
  invalid_grant: "invalid_grant";
314
314
  }>;
@@ -328,22 +328,22 @@ declare const Refunded: AccessEventDefinition<z.ZodObject<{
328
328
  scopeKey: z.ZodString;
329
329
  status: z.ZodEnum<{
330
330
  active: "active";
331
- expired: "expired";
332
331
  suspended: "suspended";
332
+ expired: "expired";
333
+ consumed: "consumed";
333
334
  revoked: "revoked";
334
335
  refunded: "refunded";
335
- consumed: "consumed";
336
336
  }>;
337
337
  allowed: z.ZodBoolean;
338
338
  reason: z.ZodEnum<{
339
339
  active: "active";
340
- not_found: "not_found";
341
- not_yet_active: "not_yet_active";
342
- expired: "expired";
343
340
  suspended: "suspended";
341
+ expired: "expired";
342
+ consumed: "consumed";
344
343
  revoked: "revoked";
345
344
  refunded: "refunded";
346
- consumed: "consumed";
345
+ not_found: "not_found";
346
+ not_yet_active: "not_yet_active";
347
347
  quota_exhausted: "quota_exhausted";
348
348
  invalid_grant: "invalid_grant";
349
349
  }>;
@@ -1,2 +1,2 @@
1
- import { a as Expired, c as Refunded, d as Suspended, f as accessEventDefinitions, i as Exhausted, l as Resumed, n as AccessEventSchema, o as Extended, r as Consumed, s as Granted, t as AccessEventDefinition, u as Revoked } from "../event-catalog-CkIizOxb.mjs";
1
+ import { a as Expired, c as Refunded, d as Suspended, f as accessEventDefinitions, i as Exhausted, l as Resumed, n as AccessEventSchema, o as Extended, r as Consumed, s as Granted, t as AccessEventDefinition, u as Revoked } from "../event-catalog-DarRYj3Y.mjs";
2
2
  export { AccessEventDefinition, AccessEventSchema, Consumed, Exhausted, Expired, Extended, Granted, Refunded, Resumed, Revoked, Suspended, accessEventDefinitions };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ACCESS_REASONS, AccessDecision, AccessGrantState, AccessReason, evaluateAccess, hasAccess } from "./domain/access-decision.mjs";
2
- import { f as accessEventDefinitions, m as AccessEventName, p as ACCESS_EVENTS, t as AccessEventDefinition } from "./event-catalog-CkIizOxb.mjs";
2
+ import { f as accessEventDefinitions, m as AccessEventName, p as ACCESS_EVENTS, t as AccessEventDefinition } from "./event-catalog-DarRYj3Y.mjs";
3
3
  import { ModelBlueprint, MultiTenantOptions, PluginType, Repository } from "@classytic/mongokit";
4
4
  import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
5
5
  import { InProcessEventBus, InProcessEventBusOptions } from "@classytic/primitives/event-infra";
package/llms.txt ADDED
@@ -0,0 +1,27 @@
1
+ # @classytic/access (skill: skills/access/SKILL.md)
2
+
3
+ Entitlement engine: durable, time-bound or metered grants; access is computed, rows are never deleted.
4
+
5
+ | Need | Use |
6
+ |---|---|
7
+ | Build the engine | `defineAccess(shape).bind(connection, runtime)` |
8
+ | Gate a request (server) | `entitlement.check(target, ctx)` |
9
+ | Same rule at edge / UI | `evaluateAccess(grant)` from `@classytic/access/decision` |
10
+ | Many capabilities, one query | `checkMany(subject, capabilities, ctx)` |
11
+ | Grant on purchase / plan | `grant(input, ctx)` |
12
+ | Redelivery-safe grant from an event | `grantByOrigin(input, ctx)` |
13
+ | Plan change diff | `reconcileEntitlementSet(input, ctx)` |
14
+ | Spend metered units | `consume(target, { key, amount }, ctx)` |
15
+ | Renew | `extend(id, { accessExpiresAt } or { addMs }, ctx)` |
16
+ | Pause / lift / pull | `suspend`, `resume`, `revoke`, `refund` |
17
+ | Cascade from an order | `refundByOrigin`, `setStateByOrigin`, `extendByOrigin` |
18
+ | "My access" | `listForSubject(subject, options, ctx)` |
19
+ | Renewal worklist / churn | `expiringBetween`, `churnBetween` |
20
+ | Cron | `expireDue`, `autoResumeDue` |
21
+ | Statuses and transitions | `ENTITLEMENT_STATUS`, `ENTITLEMENT_MACHINE`, `canEntitlementTransition()` |
22
+ | Deny reasons | `ACCESS_REASONS` |
23
+ | Events | `ACCESS_EVENTS`; `accessEventDefinitions` from `@classytic/access/events` |
24
+ | Body validation | `@classytic/access/schemas/entitlement` (`grantSchema`, `checkSchema`, `consumeSchema`, `extendSchema`, `reasonSchema`) |
25
+ | Errors | `AccessError` subclasses, `instanceof` |
26
+
27
+ Rules: identity tuple = subjectModel + subjectRef + resourceType + resourceRef (+ scopeKey). `consume` needs an idempotency key. `purchase` / `subscription` grants need originModel + originRef. Never delete rows or TTL them.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/access",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Access ENTITLEMENT engine - time-bound (or lifetime) grants of access to any resource: course enrollment, file download, API access, membership, feature flag, any service. Like a session, but durable: the grant is a permanent record, the RIGHT to access is COMPUTED (never TTL-deleted). Single responsibility: it answers 'does this subject currently hold a live grant to this resource', NOT the purchase (@classytic/order), the money (@classytic/revenue), or the catalog item (@classytic/catalog). Powered by @classytic/mongokit.",
5
5
  "author": "Classytic",
6
6
  "license": "MIT",
@@ -39,7 +39,9 @@
39
39
  "files": [
40
40
  "dist",
41
41
  "README.md",
42
- "CHANGELOG.md"
42
+ "CHANGELOG.md",
43
+ "skills",
44
+ "llms.txt"
43
45
  ],
44
46
  "scripts": {
45
47
  "build": "tsdown",
@@ -50,25 +52,26 @@
50
52
  "test:scenarios": "vitest run --project scenarios",
51
53
  "test:watch": "vitest --project unit --project integration",
52
54
  "test:all": "vitest run",
53
- "prepublishOnly": "npm run typecheck && npm test && npm run build",
55
+ "prepublishOnly": "npm run typecheck && npm test && npm run build && npm run check-skills",
56
+ "check-skills": "node scripts/check-skills.mjs",
54
57
  "push": "classytic-push"
55
58
  },
56
59
  "peerDependencies": {
57
- "@classytic/mongokit": ">=3.41.0",
58
- "@classytic/primitives": ">=0.31.1",
59
- "@classytic/repo-core": ">=0.31.0",
60
- "mongoose": ">=9.11.0",
60
+ "@classytic/mongokit": ">=3.47.0",
61
+ "@classytic/primitives": ">=0.39.0",
62
+ "@classytic/repo-core": ">=0.39.0",
63
+ "mongoose": ">=9.13.1",
61
64
  "zod": ">=4.0.0"
62
65
  },
63
66
  "devDependencies": {
64
67
  "@classytic/dev-tools": "^0.2.0",
65
- "@classytic/mongokit": "^3.41.0",
66
- "@classytic/primitives": ">=0.31.1",
67
- "@classytic/repo-core": ">=0.31.0",
68
+ "@classytic/mongokit": "^3.47.0",
69
+ "@classytic/primitives": ">=0.39.0",
70
+ "@classytic/repo-core": "^0.39.0",
68
71
  "@types/node": "^22.19.21",
69
72
  "@vitest/coverage-v8": "^4.1.9",
70
73
  "mongodb-memory-server": "^11.2.0",
71
- "mongoose": "^9.11.1",
74
+ "mongoose": "^9.13.1",
72
75
  "publint": "^0.3.23",
73
76
  "tsdown": "^0.22.14",
74
77
  "typescript": "^6.0.3",
@@ -0,0 +1,116 @@
1
+ ---
2
+ name: access
3
+ description: "@classytic/access entitlement engine: durable time-bound or metered grants of access to any resource, a pure decision (evaluateAccess), idempotent grant/check/consume, expiry sweep, events. Use for gating, memberships, quotas, API keys, downloads. Triggers: entitlement, grant access, check access, quota, consume, expiry."
4
+ metadata:
5
+ minVersion: "0.4.0"
6
+ ---
7
+
8
+ # @classytic/access
9
+
10
+ A grant is a permanent ledger row; the RIGHT to access is computed by `evaluateAccess`, never TTL-deleted. It answers one question: does this subject hold a live grant to this resource now. Purchase, money and catalog live elsewhere and call in through events. Peers: mongoose, mongokit, repo-core, primitives, zod v4.
11
+
12
+ ## Do not hand-roll
13
+
14
+ | Need | Use |
15
+ |---|---|
16
+ | Build the engine | `defineAccess(shape).bind(connection, runtime)` |
17
+ | "Can X use Y now" (server) | `entitlement.check(target, ctx)` |
18
+ | Same rule at edge, UI, on a wire row | `evaluateAccess(grant)` / `hasAccess(grant)` from `@classytic/access/decision` |
19
+ | Many capabilities, one subject | `checkMany(subject, capabilities, ctx)` (max `MAX_CAPABILITIES_PER_CHECK`) |
20
+ | Grant on purchase or plan | `grant(input, ctx)` (idempotent per live subject+resource+scope) |
21
+ | Event-driven grant (redelivery safe) | `grantByOrigin(input, ctx)` |
22
+ | Plan change (grant new, revoke extra) | `reconcileEntitlementSet(input, ctx)` |
23
+ | Spend metered units | `consume(target, { key, amount }, ctx)` |
24
+ | Usage history | `listConsumptions(id, { limit }, ctx)` |
25
+ | Renew or push the window | `extend(id, { accessExpiresAt } or { addMs }, ctx)` |
26
+ | Pause / lift / pull | `suspend`, `resume`, `revoke`, `refund` |
27
+ | Cascade from an order or payment | `refundByOrigin`, `setStateByOrigin`, `extendByOrigin` |
28
+ | "My access" list | `listForSubject(subject, options, ctx)` |
29
+ | Renewal worklist / churn | `expiringBetween(range, options, ctx)` / `churnBetween(range, options, ctx)` |
30
+ | Cron sweeps | `expireDue(opts, ctx)`, `autoResumeDue(opts, ctx)` |
31
+ | Status vocabulary, transitions | `ENTITLEMENT_STATUS`, `ENTITLEMENT_MACHINE`, `canEntitlementTransition()` |
32
+ | Closed deny reasons | `ACCESS_REASONS` |
33
+ | Event names, registry defs | `ACCESS_EVENTS`; `accessEventDefinitions` from `@classytic/access/events` |
34
+ | Body validation | `grantSchema`, `checkSchema`, `consumeSchema`, `extendSchema`, `reasonSchema` from `@classytic/access/schemas/entitlement` |
35
+ | Failures | `AccessError` subclasses (`.code`, `.status`), match with `instanceof` |
36
+
37
+ ## Golden path
38
+
39
+ ```ts
40
+ import mongoose from 'mongoose';
41
+ import { defineAccess } from '@classytic/access';
42
+
43
+ const access = defineAccess({ tenant: { fieldType: 'objectId' } }) // tenant: false = platform-wide
44
+ .bind(mongoose.connection, { eventTransport, timezone: 'UTC' });
45
+ await access.syncIndexes(); // on deploy
46
+
47
+ const entitlements = access.repositories.entitlement;
48
+ const ctx = { organizationId, actorId };
49
+ ```
50
+
51
+ Grant (`purchase` and `subscription` need `originModel` + `originRef`; other sources need an origin or `ctx.actorId`):
52
+
53
+ ```ts
54
+ await entitlements.grant(
55
+ { subjectModel: 'user', subjectRef: userId, resourceType: 'report', resourceRef: reportId,
56
+ source: 'purchase', originModel: 'Order', originRef: orderId,
57
+ accessExpiresAt: new Date(Date.now() + 365 * 864e5) },
58
+ ctx,
59
+ );
60
+ ```
61
+
62
+ Gate (complete identity tuple or `{ id }`; a partial tuple throws `InvalidCheckRequestError`):
63
+
64
+ ```ts
65
+ const { allowed, reason } = await entitlements.check(
66
+ { subjectModel: 'user', subjectRef: userId, resourceType: 'report', resourceRef: reportId },
67
+ ctx,
68
+ );
69
+ if (!allowed) return reply.code(403).send({ code: `access.${reason}` });
70
+ ```
71
+
72
+ Metered (the key is REQUIRED; a replayed key spends nothing and returns `replayed: true`):
73
+
74
+ ```ts
75
+ const g = await entitlements.grant({ subjectModel: 'apiKey', subjectRef: keyId, resourceType: 'api',
76
+ resourceRef: 'reports', scopeKey: 'read', usageLimit: 1000, source: 'subscription',
77
+ originModel: 'Plan', originRef: planId }, ctx);
78
+ await entitlements.consume({ id: String(g._id) }, { key: requestId, amount: 1 }, ctx);
79
+ ```
80
+
81
+ Sweeps (host cron; the gate never waits for them): `await entitlements.expireDue({ limit: 500 }, ctx)`.
82
+
83
+ Edge or UI, no mongoose import:
84
+
85
+ ```ts
86
+ import { evaluateAccess } from '@classytic/access/decision';
87
+ const { allowed } = evaluateAccess({ status: row.status, accessExpiresAt: row.accessExpiresAt, usage: row.usage });
88
+ ```
89
+
90
+ Tests: replica-set in-memory Mongo, `defineAccess({ forceRecreate: true }).bind(connection, { clock })`; pin `clock`, never sleep.
91
+
92
+ ## Gotchas
93
+
94
+ - `evaluateAccess` fails closed: unknown status, bad date or non-integer quota gives `invalid_grant`; alert on it.
95
+ - `check` derives expiry; stored `expired` appears only after `expireDue`.
96
+ - `consume` takes `{ key, amount? }`, not a number.
97
+ - Re-`grant` on a live grant renews (window never shortens); metered renewal `quotaMode` is `'reset'` (default) or `'add'` (top-up).
98
+ - Replays are no-ops per origin: per-cycle renewals need a cycle-scoped `originRef`.
99
+ - Revoked and refunded free the live-unique slot; a new grant inserts a fresh row. Rows are never deleted.
100
+ - An `outbox` needs `transactionalSave: true` and a replica set; dev standalone: `allowNonTransactional: true`.
101
+ - Ranges prefer civil dates (`{ from: '2026-08-01', to: '2026-08-31' }`, bound to `timezone`); mixing dates and instants throws.
102
+ - `multiTenant` / `tenantFieldType` shape keys are refused; use `tenant`.
103
+ - Event payloads carry `allowed` and `reason`; read them, keep no event-to-liveness table.
104
+
105
+ ## Never
106
+
107
+ - Delete or TTL entitlement rows; revoke, or let the window lapse.
108
+ - Add host indexes with `createIndex`; pass `indexes` in the shape.
109
+ - Close a shared `eventTransport` (the engine closes only the bus it created).
110
+ - Read `node_modules` for the API.
111
+
112
+ ## References
113
+
114
+ - `references/repository.md`: read for verb signatures, options, sweeps, origin cascades, reconcile, status machine.
115
+ - `references/events-errors.md`: read when subscribing, registering events with arc, or mapping errors to HTTP.
116
+ - `references/wiring.md`: read when wiring tenancy, outbox, arc resources, schemas, tests.
@@ -0,0 +1,46 @@
1
+ # Events and errors
2
+
3
+ ## Events
4
+
5
+ Names via `ACCESS_EVENTS` (from `@classytic/access`): `GRANTED` access:granted, `EXTENDED` access:extended, `SUSPENDED`, `RESUMED`, `REVOKED`, `EXPIRED`, `CONSUMED` access:consumed, `EXHAUSTED`, `REFUNDED`. Subscribe by constant, never a literal.
6
+
7
+ Every payload is the entitlement snapshot: `entitlementId, organizationId?, subjectRef, subjectModel, resourceRef, resourceType, scopeKey, status, allowed, reason, originModel?, originRef?, accessExpiresAt?, usageLimit?, usageUsed?`. `access:consumed` adds `consumptionKey` and `amount`. Branch on `allowed`.
8
+
9
+ ```ts
10
+ const unsub = await access.events.subscribe('access:*', (e) => handle(e)); // glob match
11
+ ```
12
+
13
+ Register with an arc registry (publish-time validation and OpenAPI):
14
+
15
+ ```ts
16
+ import { accessEventDefinitions } from '@classytic/access/events';
17
+ for (const def of accessEventDefinitions) registry.register(def); // def.name, def.schema, def.payloadSchema, def.create()
18
+ ```
19
+
20
+ Delivery: with `runtime.outbox` the event row is saved first, in the same transaction as the mutation (a save failure rolls it back); then a live publish to `eventTransport` (failure is logged, the relay redelivers). Under a caller-owned `ctx.session` the live publish is skipped and the relay delivers after commit; a session without an outbox throws `UnmanagedSessionError`. Handlers must be idempotent (at-least-once).
21
+
22
+ ## Errors
23
+
24
+ All extend `AccessError` with `.code` and `.status`; branch with `instanceof`.
25
+
26
+ | Error | code | status |
27
+ |---|---|---|
28
+ | `EntitlementNotFoundError` | access.entitlement.not_found | 404 |
29
+ | `QuotaExhaustedError` | access.entitlement.quota_exhausted | 409 |
30
+ | `EntitlementNotUsableError` | access.entitlement.not_usable.`<reason>` | 409 |
31
+ | `InvalidEntitlementTransitionError` | access.invalid_transition | 409 |
32
+ | `SuspensionRefusedError` | access.suspension.`<refusal>` | 409 |
33
+ | `VersionMismatchError` | access.concurrency.version_mismatch | 409 |
34
+ | `GrantProvenanceRequiredError` | access.grant.provenance_required | 400 |
35
+ | `ConsumptionKeyRequiredError` | access.consume.key_required | 400 |
36
+ | `ConsumptionKeyConflictError` | access.consume.key_conflict | 409 |
37
+ | `ConsumptionInFlightError` | access.consume.in_flight | 409 |
38
+ | `InvalidConsumeAmountError` | access.consume.invalid_amount | 400 |
39
+ | `InvalidExtensionError` | access.extend.invalid | 400 |
40
+ | `InvalidCheckRequestError` | access.check.invalid | 400 |
41
+ | `InvalidExpiryWindowError` | access.entitlement.invalid_expiry_window | 400 |
42
+ | `UnmanagedSessionError` | access.session.unmanaged | session without outbox |
43
+ | `SessionNotInTransactionError` | access.session.not_in_transaction | bare session |
44
+ | `AccessCapabilityError` | access.engine.missing_capabilities | boot misconfiguration |
45
+
46
+ `ConsumptionInFlightError` means a concurrent duplicate of the same key; retry the same key. A reused key with a different amount is `ConsumptionKeyConflictError`.
@@ -0,0 +1,72 @@
1
+ # Repository verbs (EntitlementRepository)
2
+
3
+ `access.repositories.entitlement` extends the mongokit `Repository` (so `getById`, `findAll`, `count` exist). Every domain verb takes an `AccessContext` last: `{ organizationId?, actorId?, actorKind?, session?, signal?, retryPolicy? }`.
4
+
5
+ ## Identity
6
+
7
+ ```ts
8
+ type AccessSubject = { subjectModel: string; subjectRef: string };
9
+ type AccessCapability = { resourceType: string; resourceRef: string; scopeKey?: string }; // scopeKey default ''
10
+ type EntitlementTarget = { id: string } | (AccessSubject & AccessCapability);
11
+ ```
12
+
13
+ Both halves of subject and resource are required so two namespaces sharing an id never collide.
14
+
15
+ ## Verbs
16
+
17
+ | Verb | Signature | Returns |
18
+ |---|---|---|
19
+ | `grant` | `(input: GrantInput, ctx)` | `EntitlementDocument` |
20
+ | `grantByOrigin` | `(input & { originModel, originRef }, ctx)` | `{ grant, created }` |
21
+ | `check` | `(target, ctx)` | `{ allowed, reason, expiresAt, remaining, entitlement }` |
22
+ | `checkMany` | `(subject, capabilities[], ctx)` | results in input order; empty list refused; max 100 |
23
+ | `consume` | `(target, { key, amount? }, ctx)` | `{ entitlement, replayed, amount, remaining }` |
24
+ | `listConsumptions` | `(entitlementId, { limit? }, ctx)` | usage ledger, newest first, limit 1..200 |
25
+ | `extend` | `(id, { accessExpiresAt } or { addMs }, ctx)` | document |
26
+ | `suspend` | `(id, { reason?, policy?, endsAt? }, ctx)` | document |
27
+ | `resume` | `(id, { creditFrozenDays? }, ctx)` | document |
28
+ | `revoke` / `refund` | `(id, { reason? }, ctx)` | document (window cut to now) |
29
+ | `expireDue` | `({ now?, limit? }, ctx)` | `{ swept }` |
30
+ | `autoResumeDue` | `({ now?, limit? }, ctx)` | `{ resumed, failed }` |
31
+ | `refundByOrigin` | `(originModel, originRef, { reason? }, ctx)` | `{ refunded }` |
32
+ | `setStateByOrigin` | `(originModel, originRef, 'suspend' or 'resume' or 'revoke', { reason? }, ctx)` | `{ changed }` |
33
+ | `extendByOrigin` | `(originModel, originRef, accessExpiresAt or null, ctx)` | `{ changed, matched }` |
34
+ | `listForSubject` | `(subject, { resourceType?, liveOnly?, limit?, page? }, ctx)` | page with `.data`, cap 200 |
35
+ | `expiringBetween` | `(range, { resourceType?, resourceRef?, subjectModel?, scopeKey?, includeSuspended?, limit?, page? }, ctx)` | renewal worklist, soonest first |
36
+ | `churnBetween` | `(range, { graceDays?, resourceType?, ... }, ctx)` | lapsed with no replacement inside `graceDays` (default `DEFAULT_CHURN_GRACE_DAYS`) |
37
+ | `reconcileEntitlementSet` | `({ subject, agreementRef, desired[], source?, mutationRef? }, ctx)` | `{ granted, revoked, retained }` |
38
+
39
+ `range` is `{ from, to }`: civil dates (`'2026-08-01'`) bound to the engine `timezone`, or `Date` instants; not mixed (`InvalidExpiryWindowError`).
40
+
41
+ `reconcileEntitlementSet` diffs a subject's grants from one origin (`originModel` is fixed to `'Agreement'`, `originRef` is `agreementRef`) against `desired` (each item names its `organizationId`): grants the missing, revokes the extra, retains matches. Idempotent by the diff; the caller checks authority.
42
+
43
+ ## GrantInput
44
+
45
+ `subjectRef, subjectModel, resourceRef, resourceType, source` required. `source`: `purchase | subscription | trial | grant | manual | system`. Optional: `subjectEmail, scopeKey, notBefore, accessExpiresAt (null = lifetime), usageLimit (null = unlimited), originRef, originModel, amount, currency (ISO 4217), metadata, renew (default true), quotaMode ('reset' | 'add')`.
46
+
47
+ Provenance: `purchase` and `subscription` need `originModel` + `originRef`; others need an origin or `ctx.actorId`, else `GrantProvenanceRequiredError`.
48
+
49
+ Behaviour on a live grant for the same subject+resource+scope:
50
+ - Same origin already applied: no-op (replay).
51
+ - Otherwise with `renew !== false`: window refreshed, never shortened; quota follows `quotaMode`; emits `access:extended`.
52
+ - `renew: false`: pure idempotency.
53
+
54
+ ## Metered access
55
+
56
+ `usageLimit` makes a grant metered. `consume` is atomic (capacity guard inside the update), so N concurrent spends against K units let exactly K through; the rest throw `QuotaExhaustedError`. At the cap the status flips to `consumed` and `access:exhausted` is emitted. Top up a live metered grant with `grant(..., quotaMode: 'add')` (limit grows, `used` kept); a new period uses `'reset'`.
57
+
58
+ ## Suspension
59
+
60
+ `suspend` without `policy`: `endsAt` is the explicit auto-resume deadline (omit for open-ended). With a `policy` (`SuspensionPolicy` from `@classytic/primitives/suspension`) the allowance is enforced against the grant's own history and the resume time is derived; a refusal throws `SuspensionRefusedError`. `resume` credits the frozen time onto the window when `creditFrozenDays` is true (default: the promise stored at suspend time). Run `autoResumeDue` from the same cron as `expireDue`.
61
+
62
+ ## Status machine
63
+
64
+ `active -> suspended | expired | consumed | revoked | refunded`; `suspended -> active | expired | revoked | refunded`; `expired -> active`; `consumed -> active`; `revoked` and `refunded` terminal. Illegal moves throw `InvalidEntitlementTransitionError`. `LIVE_STATUSES` is `active` and `suspended`.
65
+
66
+ ## evaluateAccess
67
+
68
+ `evaluateAccess(grant or null, now?)` returns `{ allowed, reason, expiresAt, remaining }`. Input shape: `{ status, notBefore?, accessExpiresAt?, usage?: { limit, used } }`; `null` gives `not_found`. Reasons are the closed `ACCESS_REASONS` list; `active` is the only allow.
69
+
70
+ ## Sweeps
71
+
72
+ `expireDue` and `autoResumeDue` are CAS per row, one transaction each, safe to run concurrently and repeatedly. A lost CAS never aborts the sweep.
@@ -0,0 +1,60 @@
1
+ # Wiring: tenancy, outbox, arc, schemas, tests
2
+
3
+ ## Shape (describe time, pure) vs runtime (bind time)
4
+
5
+ ```ts
6
+ const blueprint = defineAccess({
7
+ tenant: { fieldType: 'objectId' }, // default; false = platform-wide; extras: skipOperations, skipWhen, resolveContext, allowDataInjection, onMismatch
8
+ collectionPrefix: 'app_',
9
+ autoIndex: true,
10
+ indexes: [], // IndexDeclaration[] from @classytic/mongokit/tenant
11
+ });
12
+ blueprint.modelNames; // known without a connection
13
+ const access = blueprint.bind(connection, {
14
+ eventTransport, outbox, timezone: 'Asia/Dhaka', clock: () => new Date(),
15
+ logger, allowNonTransactional: false, repositoryPlugins: { entitlement: [] },
16
+ });
17
+ ```
18
+
19
+ `bind` is synchronous, validates capabilities (`getOrCreate`, `upsert`, transactions when an outbox is set) and throws `AccessCapabilityError` at boot. Bind after `mongoose.connect` so the topology can be read. Engine: `config`, `models` (`Entitlement`, `EntitlementConsumption`), `repositories.entitlement`, `events`, `outbox`, `syncIndexes()`, `close()`.
20
+
21
+ `defineAccessModels(config)` returns the model blueprint alone (for schema tooling).
22
+
23
+ ## Outbox
24
+
25
+ Pass an `OutboxStore` from `@classytic/primitives/outbox` that declares `transactionalSave: true`. Grants and consumes then commit with their event row. Requires a replica set. Dev standalone: `allowNonTransactional: true`.
26
+
27
+ ## Caller-owned transaction
28
+
29
+ Pass `ctx.session`; it must be inside an active transaction (`session.withTransaction`) when an outbox is wired, else `SessionNotInTransactionError`.
30
+
31
+ ## Arc resource
32
+
33
+ ```ts
34
+ import { defineResource } from '@classytic/arc';
35
+ import { createAdapter } from '@classytic/arc/adapter';
36
+ import { requireAuth, requireRoles } from '@classytic/arc/permissions';
37
+
38
+ const repo = access.repositories.entitlement;
39
+ export default defineResource({
40
+ name: 'entitlement',
41
+ prefix: '/access/entitlements',
42
+ adapter: createAdapter(access.models.Entitlement, repo),
43
+ permissions: { list: requireAuth(), get: requireAuth(), create: requireRoles('admin') },
44
+ actions: {
45
+ revoke: { handler: (id, d, req) => repo.revoke(id, d, req.scope) },
46
+ extend: { handler: (id, d, req) => repo.extend(id, d, req.scope) },
47
+ consume: { handler: (id, d, req) => repo.consume({ id }, { key: d.key, amount: d.amount }, req.scope) },
48
+ },
49
+ });
50
+ ```
51
+
52
+ See the `arc` skill for action schemas and permissions. Validate bodies with the strict zod schemas from `@classytic/access/schemas/entitlement` (`grantSchema`, `checkSchema`, `consumeSchema`, `extendSchema`, `reasonSchema`); they refuse unknown keys and coerce dates.
53
+
54
+ ## Tests
55
+
56
+ Use a one-node `MongoMemoryReplSet`, `defineAccess({ tenant: { fieldType: 'objectId' }, forceRecreate: true }).bind(connection)`, then `await engine.models.Entitlement.createIndexes()`. Pin time with `runtime.clock` (never sleep). Clear collections between tests; `engine.close()` in teardown. Use a fresh `originRef` per grant so renewals are not replays.
57
+
58
+ ## Index discipline
59
+
60
+ The package owns the indexes for the gate (subject+resource, resource) and the live-unique partial index. A host read that needs another sort or a cross-tenant sweep declares it in `shape.indexes` (`scope: 'tenant'` default, `'global'` pairs with a `bypassTenant` read). Run `syncIndexes()` on deploy.