@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.
@@ -25,27 +25,33 @@ declare const grantSchema: z.ZodObject<{
25
25
  currency: z.ZodOptional<z.ZodString>;
26
26
  metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
27
27
  renew: z.ZodOptional<z.ZodBoolean>;
28
- }, z.core.$strip>;
29
- /** POST /access/check — read-only gate. */
28
+ quotaMode: z.ZodOptional<z.ZodEnum<{
29
+ reset: "reset";
30
+ add: "add";
31
+ }>>;
32
+ }, z.core.$strict>;
33
+ /** GET /access/entitlements/check — the COMPLETE identity tuple; unknown keys refused. */
30
34
  declare const checkSchema: z.ZodObject<{
31
35
  subjectRef: z.ZodString;
36
+ subjectModel: z.ZodString;
32
37
  resourceRef: z.ZodString;
33
- resourceType: z.ZodOptional<z.ZodString>;
38
+ resourceType: z.ZodString;
34
39
  scopeKey: z.ZodOptional<z.ZodString>;
35
- }, z.core.$strip>;
36
- /** POST /access/entitlements/:id/consume — spend metered units. */
40
+ }, z.core.$strict>;
41
+ /** POST /access/entitlements/:id/action consume — spend metered units under a key. */
37
42
  declare const consumeSchema: z.ZodObject<{
43
+ key: z.ZodString;
38
44
  amount: z.ZodDefault<z.ZodNumber>;
39
- }, z.core.$strip>;
40
- /** POST /access/entitlements/:id/extend — renew the window. */
45
+ }, z.core.$strict>;
46
+ /** POST /access/entitlements/:id/action extend — exactly one of the two. */
41
47
  declare const extendSchema: z.ZodObject<{
42
48
  accessExpiresAt: z.ZodOptional<z.ZodNullable<z.ZodCoercedDate<unknown>>>;
43
49
  addMs: z.ZodOptional<z.ZodNumber>;
44
- }, z.core.$strip>;
45
- /** POST /access/entitlements/:id/{suspend,revoke,refund} */
50
+ }, z.core.$strict>;
51
+ /** POST /access/entitlements/:id/action {suspend,revoke,refund} */
46
52
  declare const reasonSchema: z.ZodObject<{
47
53
  reason: z.ZodOptional<z.ZodString>;
48
- }, z.core.$strip>;
54
+ }, z.core.$strict>;
49
55
  type GrantBody = z.infer<typeof grantSchema>;
50
56
  type CheckBody = z.infer<typeof checkSchema>;
51
57
  type ConsumeBody = z.infer<typeof consumeSchema>;
@@ -3,11 +3,11 @@ import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
3
3
  import { z } from "zod";
4
4
  //#region src/schemas/entitlement.ts
5
5
  /**
6
- * Zod validators — `@classytic/access/schemas/entitlement`. Route bodies use
7
- * `z.coerce.date()` (rule 25) so ISO strings auto-convert to `Date`.
6
+ * Wire validators — `@classytic/access/schemas/entitlement`. Strict: an unknown key is refused,
7
+ * never stripped. Dates are `z.coerce.date()` so ISO strings arrive as `Date`.
8
8
  */
9
9
  /** POST /access/entitlements — grant access. */
10
- const grantSchema = z.object({
10
+ const grantSchema = z.strictObject({
11
11
  subjectRef: refSchema,
12
12
  subjectModel: modelSchema,
13
13
  subjectEmail: z.string().email().optional(),
@@ -23,23 +23,28 @@ const grantSchema = z.object({
23
23
  amount: z.number().int().nullable().optional(),
24
24
  currency: z.string().regex(CURRENCY_PATTERN, "ISO 4217 (3 uppercase letters)").optional(),
25
25
  metadata: metadataSchema.optional(),
26
- renew: z.boolean().optional()
26
+ renew: z.boolean().optional(),
27
+ quotaMode: z.enum(["reset", "add"]).optional()
27
28
  });
28
- /** POST /access/check — read-only gate. */
29
- const checkSchema = z.object({
29
+ /** GET /access/entitlements/check — the COMPLETE identity tuple; unknown keys refused. */
30
+ const checkSchema = z.strictObject({
30
31
  subjectRef: refSchema,
32
+ subjectModel: modelSchema,
31
33
  resourceRef: refSchema,
32
- resourceType: modelSchema.optional(),
34
+ resourceType: modelSchema,
33
35
  scopeKey: scopeKeySchema.optional()
34
36
  });
35
- /** POST /access/entitlements/:id/consume — spend metered units. */
36
- const consumeSchema = z.object({ amount: z.number().int().min(1).default(1) });
37
- /** POST /access/entitlements/:id/extend — renew the window. */
38
- const extendSchema = z.object({
37
+ /** POST /access/entitlements/:id/action consume — spend metered units under a key. */
38
+ const consumeSchema = z.strictObject({
39
+ key: z.string().trim().min(1).max(256),
40
+ amount: z.number().int().min(1).default(1)
41
+ });
42
+ /** POST /access/entitlements/:id/action extend — exactly one of the two. */
43
+ const extendSchema = z.strictObject({
39
44
  accessExpiresAt: z.coerce.date().nullable().optional(),
40
45
  addMs: z.number().int().min(1).optional()
41
- }).refine((v) => v.accessExpiresAt !== void 0 || v.addMs !== void 0, { message: "provide accessExpiresAt or addMs" });
42
- /** POST /access/entitlements/:id/{suspend,revoke,refund} */
43
- const reasonSchema = z.object({ reason: z.string().max(500).optional() });
46
+ }).refine((v) => v.accessExpiresAt !== void 0 !== (v.addMs !== void 0), { message: "provide exactly one of accessExpiresAt or addMs" });
47
+ /** POST /access/entitlements/:id/action {suspend,revoke,refund} */
48
+ const reasonSchema = z.strictObject({ reason: z.string().max(500).optional() });
44
49
  //#endregion
45
50
  export { checkSchema, consumeSchema, extendSchema, grantSchema, reasonSchema };
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.3.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",
@@ -14,18 +14,22 @@
14
14
  },
15
15
  "exports": {
16
16
  ".": {
17
+ "@classytic/source": "./src/index.ts",
17
18
  "types": "./dist/index.d.mts",
18
19
  "default": "./dist/index.mjs"
19
20
  },
20
21
  "./decision": {
22
+ "@classytic/source": "./src/domain/access-decision.ts",
21
23
  "types": "./dist/domain/access-decision.d.mts",
22
24
  "default": "./dist/domain/access-decision.mjs"
23
25
  },
24
26
  "./events": {
27
+ "@classytic/source": "./src/events/event-catalog.ts",
25
28
  "types": "./dist/events/event-catalog.d.mts",
26
29
  "default": "./dist/events/event-catalog.mjs"
27
30
  },
28
31
  "./schemas/*": {
32
+ "@classytic/source": "./src/schemas/*.ts",
29
33
  "types": "./dist/schemas/*.d.mts",
30
34
  "default": "./dist/schemas/*.mjs"
31
35
  }
@@ -35,7 +39,9 @@
35
39
  "files": [
36
40
  "dist",
37
41
  "README.md",
38
- "CHANGELOG.md"
42
+ "CHANGELOG.md",
43
+ "skills",
44
+ "llms.txt"
39
45
  ],
40
46
  "scripts": {
41
47
  "build": "tsdown",
@@ -46,25 +52,26 @@
46
52
  "test:scenarios": "vitest run --project scenarios",
47
53
  "test:watch": "vitest --project unit --project integration",
48
54
  "test:all": "vitest run",
49
- "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",
50
57
  "push": "classytic-push"
51
58
  },
52
59
  "peerDependencies": {
53
- "@classytic/mongokit": ">=3.39.0",
54
- "@classytic/primitives": ">=0.28.0",
55
- "@classytic/repo-core": ">=0.28.0",
56
- "mongoose": ">=9.4.1",
60
+ "@classytic/mongokit": ">=3.47.0",
61
+ "@classytic/primitives": ">=0.39.0",
62
+ "@classytic/repo-core": ">=0.39.0",
63
+ "mongoose": ">=9.13.1",
57
64
  "zod": ">=4.0.0"
58
65
  },
59
66
  "devDependencies": {
60
67
  "@classytic/dev-tools": "^0.2.0",
61
- "@classytic/mongokit": "^3.39.0",
62
- "@classytic/primitives": ">=0.28.0",
63
- "@classytic/repo-core": ">=0.28.0",
68
+ "@classytic/mongokit": "^3.47.0",
69
+ "@classytic/primitives": ">=0.39.0",
70
+ "@classytic/repo-core": "^0.39.0",
64
71
  "@types/node": "^22.19.21",
65
72
  "@vitest/coverage-v8": "^4.1.9",
66
73
  "mongodb-memory-server": "^11.2.0",
67
- "mongoose": "^9.4.1",
74
+ "mongoose": "^9.13.1",
68
75
  "publint": "^0.3.23",
69
76
  "tsdown": "^0.22.14",
70
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.
@@ -1,111 +0,0 @@
1
- import { createEvent } from "@classytic/primitives/events";
2
- import { z } from "zod";
3
- //#region src/events/event-constants.ts
4
- /**
5
- * ACCESS_EVENTS — domain event constants. Prefix `access:` per
6
- * PACKAGE_RULES §12. Hosts subscribe glob-style so typos are compile errors.
7
- */
8
- const ACCESS_EVENTS = {
9
- GRANTED: "access:granted",
10
- EXTENDED: "access:extended",
11
- SUSPENDED: "access:suspended",
12
- RESUMED: "access:resumed",
13
- REVOKED: "access:revoked",
14
- EXPIRED: "access:expired",
15
- EXHAUSTED: "access:exhausted",
16
- REFUNDED: "access:refunded"
17
- };
18
- //#endregion
19
- //#region src/events/event-catalog.ts
20
- /**
21
- * Zod-source event catalog (PACKAGE_RULES rule 18). One Zod schema per event
22
- * is the source of truth; hosts wire `accessEventDefinitions` into arc's
23
- * `EventRegistry`. Timestamps are `z.iso.datetime()` (rule 25).
24
- *
25
- * Every access event carries the same entitlement snapshot — a host subscriber
26
- * reacts to the lifecycle without re-fetching (grant a perk on `access:granted`,
27
- * email a "renew" nudge on `access:expired`, refill credits on `access:extended`).
28
- */
29
- function defineAccessEvent(input) {
30
- const { name, description, version = 1, zodSchema } = input;
31
- return {
32
- name,
33
- version,
34
- description,
35
- zodSchema,
36
- schema: z.toJSONSchema(zodSchema),
37
- create(payload, meta) {
38
- return createEvent(name, payload, {
39
- resource: "entitlement",
40
- source: "access",
41
- ...meta
42
- });
43
- }
44
- };
45
- }
46
- /** The entitlement snapshot every access event carries. */
47
- const entitlementEventSchema = z.object({
48
- entitlementId: z.string(),
49
- organizationId: z.string().optional(),
50
- subjectRef: z.string(),
51
- subjectModel: z.string(),
52
- resourceRef: z.string(),
53
- resourceType: z.string(),
54
- scopeKey: z.string(),
55
- status: z.string(),
56
- accessExpiresAt: z.iso.datetime().optional(),
57
- usageLimit: z.number().optional(),
58
- usageUsed: z.number().optional()
59
- });
60
- const Granted = defineAccessEvent({
61
- name: ACCESS_EVENTS.GRANTED,
62
- description: "A subject was granted access to a resource for a window (or lifetime).",
63
- zodSchema: entitlementEventSchema
64
- });
65
- const Extended = defineAccessEvent({
66
- name: ACCESS_EVENTS.EXTENDED,
67
- description: "An access window was pushed out / quota refreshed (a renewal or top-up).",
68
- zodSchema: entitlementEventSchema
69
- });
70
- const Suspended = defineAccessEvent({
71
- name: ACCESS_EVENTS.SUSPENDED,
72
- description: "Access was paused without ending it (recoverable via access:resumed).",
73
- zodSchema: entitlementEventSchema
74
- });
75
- const Resumed = defineAccessEvent({
76
- name: ACCESS_EVENTS.RESUMED,
77
- description: "A suspended grant was reactivated.",
78
- zodSchema: entitlementEventSchema
79
- });
80
- const Revoked = defineAccessEvent({
81
- name: ACCESS_EVENTS.REVOKED,
82
- description: "Access was pulled permanently (admin action / dispute). Window cut to now.",
83
- zodSchema: entitlementEventSchema
84
- });
85
- const Expired = defineAccessEvent({
86
- name: ACCESS_EVENTS.EXPIRED,
87
- description: "The access window lapsed and the sweeper marked the grant expired (renewable).",
88
- zodSchema: entitlementEventSchema
89
- });
90
- const Exhausted = defineAccessEvent({
91
- name: ACCESS_EVENTS.EXHAUSTED,
92
- description: "A metered grant reached its quota and is consumed (downloads/API calls spent).",
93
- zodSchema: entitlementEventSchema
94
- });
95
- const Refunded = defineAccessEvent({
96
- name: ACCESS_EVENTS.REFUNDED,
97
- description: "A grant was refunded (payment reversed). Access cut to now.",
98
- zodSchema: entitlementEventSchema
99
- });
100
- const accessEventDefinitions = [
101
- Granted,
102
- Extended,
103
- Suspended,
104
- Resumed,
105
- Revoked,
106
- Expired,
107
- Exhausted,
108
- Refunded
109
- ];
110
- //#endregion
111
- export { Refunded as a, Suspended as c, Granted as i, accessEventDefinitions as l, Expired as n, Resumed as o, Extended as r, Revoked as s, Exhausted as t, ACCESS_EVENTS as u };