@classytic/access 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 — 2026-09-13
4
+
5
+ ### Added — `indexes`: the host declares the indexes this package cannot know about
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
+
3
44
  ## 0.1.1
4
45
 
5
46
  Patch — §P8.1 session guard (UnmanagedSessionError), ISO 4217 currency gate via CURRENCY_PATTERN.
@@ -24,3 +65,14 @@ Initial release — the access **entitlement** engine.
24
65
  - 30 tests: decision truth table, FSM, event-catalog no-drift, tenant probe,
25
66
  and three scenarios (time-bound course access + renewal, metered API quota
26
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.
78
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Classytic LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,140 +1,150 @@
1
- # @classytic/access
2
-
3
- Access **entitlement** engine. Durable, time-bound (or lifetime) grants of access to **any** resource: a course enrollment, a file download, an API key's scope, a membership, a feature flag, any service. Like a session, but the grant is a **permanent record** and the **right** to access is **computed**, never TTL-deleted.
4
-
5
- Single responsibility: it answers *"does this subject hold a live grant to this resource, right now?"*. It does **not** model the purchase (`@classytic/order`), the money (`@classytic/revenue`), or the catalog item (`@classytic/catalog`) — those compose around it via events and bridges.
6
-
7
- ```
8
- order completes ──▶ access.grant({ subject, resource, accessExpiresAt })
9
- │
10
- gate / middleware ─▶ access.check(...) ──▶ { allowed, reason, expiresAt, remaining }
11
- │
12
- host cron ─────────▶ access.expireDue() (CAS active→expired, emits access:expired)
13
- refund ────────────▶ access.refundByOrigin('Order', id)
14
- ```
15
-
16
- ## The one idea: separate the record from the right
17
-
18
- An entitlement row is a **ledger entry**: "this subject was granted access to this resource, via this order, for this window." Whether access is usable **right now** is decided by a pure function over the window + status, never by deleting the row.
19
-
20
- This is deliberate (PACKAGE_RULES Concurrency House Rules: *"self-healing CAS expiry over TTL-delete indexes — model expiry as a state transition so the row survives as a record"*). A TTL-delete would destroy learner progress, revoke earned certificates, and kill the "renew" upsell. Here:
21
-
22
- - **Stored `status`** records only explicit lifecycle events: `active`, `suspended`, `revoked`, `refunded`, `consumed`, `expired`.
23
- - **`expired`** is **derived** at read time from the window — the gate denies the instant a window lapses, before any sweeper runs. A background `expireDue()` sweep later CAS-writes `status: 'expired'` and emits `access:expired` so downstream reacts once. The row is never deleted; terminal states free the live-uniqueness slot so a re-purchase inserts a fresh grant.
24
-
25
- ## The pure decision (`@classytic/access/decision`)
26
-
27
- `evaluateAccess` is a pure function with **no mongoose import**, published as its own subpath so the exact same rule runs on the server, at an edge node, and in the UI:
28
-
29
- ```ts
30
- import { evaluateAccess, hasAccess } from '@classytic/access/decision';
31
-
32
- const d = evaluateAccess({ status: 'active', accessExpiresAt: '2027-01-01T00:00:00Z' });
33
- // { allowed: true, reason: 'active', expiresAt: 1798761600000, remaining: null }
34
-
35
- evaluateAccess({ status: 'active', accessExpiresAt: yesterday }); // { allowed: false, reason: 'expired' }
36
- evaluateAccess({ status: 'active', usage: { limit: 3, used: 3 } }); // { allowed: false, reason: 'quota_exhausted' }
37
- ```
38
-
39
- Deny precedence (most-terminal first): `revoked` → `refunded` → `suspended` → `consumed` → `not_yet_active` → `expired` → `quota_exhausted` → `active`.
40
-
41
- ## Quick start
42
-
43
- ```ts
44
- import mongoose from 'mongoose';
45
- import { createAccess } from '@classytic/access';
46
-
47
- const access = await createAccess({
48
- connection: mongoose.connection,
49
- tenant: { fieldType: 'objectId' }, // Better Auth organization._id; pass `false` for platform-wide grants
50
- // eventTransport: new RedisEventTransport({ url }), // any arc transport drops in
51
- });
52
-
53
- // Grant a 1-year course on purchase
54
- await access.repositories.entitlement.grant(
55
- {
56
- subjectRef: userId, subjectModel: 'user',
57
- resourceRef: courseId, resourceType: 'course',
58
- source: 'purchase',
59
- accessExpiresAt: new Date(Date.now() + 365 * 864e5),
60
- originRef: orderId, originModel: 'Order',
61
- },
62
- { organizationId: orgId },
63
- );
64
-
65
- // Gate a lesson
66
- const { allowed, reason } = await access.repositories.entitlement.check(
67
- { subjectRef: userId, resourceRef: courseId },
68
- { organizationId: orgId },
69
- );
70
- if (!allowed) return reply.code(403).send({ code: `access.${reason}` });
71
- ```
72
-
73
- ## Repository verbs
74
-
75
- | Verb | Purpose |
76
- |---|---|
77
- | `grant(input, ctx)` | Idempotent grant (atomic `getOrCreate` per live subject+resource+scope). Re-grant restarts the window. Emits `access:granted` / `access:extended`. |
78
- | `check(target, ctx)` | **Hot path.** Read-only `evaluateAccess` → `{ allowed, reason, expiresAt, remaining, entitlement }`. Target by `{ id }` or `{ subjectRef, resourceRef }`. |
79
- | `consume(target, amount, ctx)` | Spend metered units (download / API call / seat). Race-proof `$expr` capacity guard; flips to `consumed` + emits `access:exhausted` at the cap. |
80
- | `extend(id, { accessExpiresAt \| addMs }, ctx)` | Renew — push the window out / reactivate an `expired` grant. Emits `access:extended`. |
81
- | `suspend` / `resume` | Pause and restore (membership freeze). |
82
- | `revoke(id, { reason }, ctx)` | Pull access permanently (terminal). |
83
- | `expireDue({ now, limit }, ctx)` | **Sweeper** (host cron): CAS `active → expired` for lapsed windows, emits `access:expired`. The row survives. |
84
- | `refundByOrigin(model, ref, ctx)` | Cascade: mark every live grant from an order/transaction `refunded`. |
85
- | `listForSubject(subjectRef, ctx)` | A subject's grants, newest-first ("my access"). |
86
-
87
- ## Metered access (API / downloads / seats)
88
-
89
- `usageLimit` makes a grant metered. `consume` is atomic and never overshoots:
90
-
91
- ```ts
92
- const e = await access.repositories.entitlement.grant(
93
- { subjectRef: keyId, subjectModel: 'apiKey', resourceRef: 'reports', resourceType: 'api',
94
- scopeKey: 'reports:read', usageLimit: 1000, source: 'subscription' },
95
- ctx,
96
- );
97
- await access.repositories.entitlement.consume({ id: String(e._id) }, 1, ctx); // 999 left
98
- // 1000 concurrent consumes → exactly 1000 succeed, the rest throw QuotaExhaustedError
99
- ```
100
-
101
- ## Arc integration
102
-
103
- ```ts
104
- import { defineResource } from '@classytic/arc';
105
- import { createAdapter } from '@classytic/arc/adapter';
106
- import { requireAuth, requireRoles } from '@classytic/arc/permissions';
107
-
108
- export default defineResource({
109
- name: 'entitlement',
110
- prefix: '/access/entitlements',
111
- adapter: createAdapter(access.models.Entitlement, access.repositories.entitlement),
112
- permissions: { list: requireAuth(), get: requireAuth(), create: requireRoles('admin') },
113
- actions: {
114
- suspend: { handler: (id, _d, req) => access.repositories.entitlement.suspend(id, {}, req.scope) },
115
- resume: { handler: (id, _d, req) => access.repositories.entitlement.resume(id, req.scope) },
116
- revoke: { handler: (id, d, req) => access.repositories.entitlement.revoke(id, d, req.scope) },
117
- extend: { handler: (id, d, req) => access.repositories.entitlement.extend(id, d, req.scope) },
118
- consume: { handler: (id, d, req) => access.repositories.entitlement.consume({ id }, d.amount, req.scope) },
119
- },
120
- });
121
-
122
- // Event catalog → arc EventRegistry (publish-time validation + OpenAPI)
123
- import { accessEventDefinitions } from '@classytic/access/events';
124
- for (const def of accessEventDefinitions) registry.register(def);
125
- ```
126
-
127
- ## Events
128
-
129
- `access:granted` · `access:extended` · `access:suspended` · `access:resumed` · `access:revoked` · `access:expired` · `access:exhausted` · `access:refunded`. Every payload carries the entitlement snapshot. Subscribe glob-style; drop in any arc `EventTransport`.
130
-
131
- ## Design notes
132
-
133
- - **Polymorphic** subject and resource (`String + bridge`, rule 7) — one model serves user/apiKey/team subjects and course/download/api/membership/feature resources.
134
- - **Tenant-scoped** by `multiTenantPlugin` (`tenant: false` for platform-wide grants like a user's API key).
135
- - **No TTL index, no cron required for the gate** — expiry is lazy at read time; `expireDue` exists only to emit events and make `status` queryable.
136
- - **Indexes** are race-proof: one active grant per `(org, subject, resource, scope)` via a partial unique index; terminal states free the slot.
137
-
138
- ## License
139
-
140
- MIT
1
+ # @classytic/access
2
+
3
+ Access **entitlement** engine. Durable, time-bound (or lifetime) grants of access to **any** resource: a course enrollment, a file download, an API key's scope, a membership, a feature flag, any service. Like a session, but the grant is a **permanent record** and the **right** to access is **computed**, never TTL-deleted.
4
+
5
+ Single responsibility: it answers *"does this subject hold a live grant to this resource, right now?"*. It does **not** model the purchase (`@classytic/order`), the money (`@classytic/revenue`), or the catalog item (`@classytic/catalog`) — those compose around it via events and bridges.
6
+
7
+ ```
8
+ order completes ──▶ access.grant({ subject, resource, accessExpiresAt })
9
+ │
10
+ gate / middleware ─▶ access.check(...) ──▶ { allowed, reason, expiresAt, remaining }
11
+ │
12
+ host cron ─────────▶ access.expireDue() (CAS active→expired, emits access:expired)
13
+ refund ────────────▶ access.refundByOrigin('Order', id)
14
+ ```
15
+
16
+ ## The one idea: separate the record from the right
17
+
18
+ An entitlement row is a **ledger entry**: "this subject was granted access to this resource, via this order, for this window." Whether access is usable **right now** is decided by a pure function over the window + status, never by deleting the row.
19
+
20
+ This is deliberate (PACKAGE_RULES Concurrency House Rules: *"self-healing CAS expiry over TTL-delete indexes — model expiry as a state transition so the row survives as a record"*). A TTL-delete would destroy learner progress, revoke earned certificates, and kill the "renew" upsell. Here:
21
+
22
+ - **Stored `status`** records only explicit lifecycle events: `active`, `suspended`, `revoked`, `refunded`, `consumed`, `expired`.
23
+ - **`expired`** is **derived** at read time from the window — the gate denies the instant a window lapses, before any sweeper runs. A background `expireDue()` sweep later CAS-writes `status: 'expired'` and emits `access:expired` so downstream reacts once. The row is never deleted; terminal states free the live-uniqueness slot so a re-purchase inserts a fresh grant.
24
+
25
+ ## The pure decision (`@classytic/access/decision`)
26
+
27
+ `evaluateAccess` is a pure function with **no mongoose import**, published as its own subpath so the exact same rule runs on the server, at an edge node, and in the UI:
28
+
29
+ ```ts
30
+ import { evaluateAccess, hasAccess } from '@classytic/access/decision';
31
+
32
+ const d = evaluateAccess({ status: 'active', accessExpiresAt: '2027-01-01T00:00:00Z' });
33
+ // { allowed: true, reason: 'active', expiresAt: 1798761600000, remaining: null }
34
+
35
+ evaluateAccess({ status: 'active', accessExpiresAt: yesterday }); // { allowed: false, reason: 'expired' }
36
+ evaluateAccess({ status: 'active', usage: { limit: 3, used: 3 } }); // { allowed: false, reason: 'quota_exhausted' }
37
+ ```
38
+
39
+ Deny precedence (most-terminal first): `revoked` → `refunded` → `suspended` → `consumed` → `not_yet_active` → `expired` → `quota_exhausted` → `active`.
40
+
41
+ ## Quick start
42
+
43
+ ```ts
44
+ import mongoose from 'mongoose';
45
+ import { createAccess } from '@classytic/access';
46
+
47
+ const access = await createAccess({
48
+ connection: mongoose.connection,
49
+ tenant: { fieldType: 'objectId' }, // Better Auth organization._id; pass `false` for platform-wide grants
50
+ // eventTransport: new RedisEventTransport({ url }), // any arc transport drops in
51
+ });
52
+
53
+ // Grant a 1-year course on purchase
54
+ await access.repositories.entitlement.grant(
55
+ {
56
+ subjectRef: userId, subjectModel: 'user',
57
+ resourceRef: courseId, resourceType: 'course',
58
+ source: 'purchase',
59
+ accessExpiresAt: new Date(Date.now() + 365 * 864e5),
60
+ originRef: orderId, originModel: 'Order',
61
+ },
62
+ { organizationId: orgId },
63
+ );
64
+
65
+ // Gate a lesson — use checkExact() at any security boundary.
66
+ // The COMPLETE identity tuple is required, so two subject namespaces sharing an
67
+ // id (a `user` and an `apiKey` both keyed `42`), or two resource types sharing a
68
+ // ref, cannot resolve to each other's grant. The loose `check()` form below
69
+ // leaves those optional and answers for whichever row sorts first — which fails
70
+ // OPEN when the other namespace happens to hold a live grant.
71
+ const { allowed, reason } = await access.repositories.entitlement.checkExact(
72
+ { subjectModel: 'user', subjectRef: userId, resourceType: 'course', resourceRef: courseId },
73
+ { organizationId: orgId },
74
+ );
75
+ if (!allowed) return reply.code(403).send({ code: `access.${reason}` });
76
+ ```
77
+
78
+ ## Repository verbs
79
+
80
+ | Verb | Purpose |
81
+ |---|---|
82
+ | `grant(input, ctx)` | Idempotent grant (atomic `getOrCreate` per live subject+resource+scope). Re-grant restarts the window. Emits `access:granted` / `access:extended`. |
83
+ | `checkExact(target, ctx)` | **Use this at security boundaries.** Same as `check`, but the full identity tuple (`subjectModel` + `subjectRef` + `resourceType` + `resourceRef`) is REQUIRED, so shared ids across namespaces cannot resolve to the wrong grant. |
84
+ | `check(target, ctx)` | **Hot path.** Read-only `evaluateAccess` → `{ allowed, reason, expiresAt, remaining, entitlement }`. Target by `{ id }`, or by subject+resource — where `subjectModel`/`resourceType` are optional for back-compat. **Legacy for polymorphic hosts:** an incomplete tuple is an ambiguous question. Prefer `checkExact`. |
85
+ | `consume(target, amount, ctx)` | Spend metered units (download / API call / seat). Race-proof `$expr` capacity guard; flips to `consumed` + emits `access:exhausted` at the cap. |
86
+ | `extend(id, { accessExpiresAt \| addMs }, ctx)` | Renew — push the window out / reactivate an `expired` grant. Emits `access:extended`. |
87
+ | `suspend` / `resume` | Pause and restore (membership freeze). |
88
+ | `revoke(id, { reason }, ctx)` | Pull access permanently (terminal). |
89
+ | `expireDue({ now, limit }, ctx)` | **Sweeper** (host cron): CAS `active → expired` for lapsed windows, emits `access:expired`. The row survives. |
90
+ | `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. |
92
+
93
+ ## Metered access (API / downloads / seats)
94
+
95
+ `usageLimit` makes a grant metered. `consume` is atomic and never overshoots:
96
+
97
+ ```ts
98
+ const e = await access.repositories.entitlement.grant(
99
+ { subjectRef: keyId, subjectModel: 'apiKey', resourceRef: 'reports', resourceType: 'api',
100
+ scopeKey: 'reports:read', usageLimit: 1000, source: 'subscription' },
101
+ ctx,
102
+ );
103
+ await access.repositories.entitlement.consume({ id: String(e._id) }, 1, ctx); // 999 left
104
+ // 1000 concurrent consumes → exactly 1000 succeed, the rest throw QuotaExhaustedError
105
+ ```
106
+
107
+ ## Arc integration
108
+
109
+ ```ts
110
+ import { defineResource } from '@classytic/arc';
111
+ import { createAdapter } from '@classytic/arc/adapter';
112
+ import { requireAuth, requireRoles } from '@classytic/arc/permissions';
113
+
114
+ export default defineResource({
115
+ name: 'entitlement',
116
+ prefix: '/access/entitlements',
117
+ adapter: createAdapter(access.models.Entitlement, access.repositories.entitlement),
118
+ permissions: { list: requireAuth(), get: requireAuth(), create: requireRoles('admin') },
119
+ actions: {
120
+ suspend: { handler: (id, _d, req) => access.repositories.entitlement.suspend(id, {}, req.scope) },
121
+ resume: { handler: (id, _d, req) => access.repositories.entitlement.resume(id, req.scope) },
122
+ revoke: { handler: (id, d, req) => access.repositories.entitlement.revoke(id, d, req.scope) },
123
+ 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) },
125
+ },
126
+ });
127
+
128
+ // Event catalog → arc EventRegistry (publish-time validation + OpenAPI)
129
+ import { accessEventDefinitions } from '@classytic/access/events';
130
+ for (const def of accessEventDefinitions) registry.register(def);
131
+ ```
132
+
133
+ ## Events
134
+
135
+ `access:granted` · `access:extended` · `access:suspended` · `access:resumed` · `access:revoked` · `access:expired` · `access:exhausted` · `access:refunded`. Every payload carries the entitlement snapshot. Subscribe glob-style; drop in any arc `EventTransport`.
136
+
137
+ ## Design notes
138
+
139
+ - **Polymorphic** subject and resource (`String + bridge`, rule 7) — one model serves user/apiKey/team subjects and course/download/api/membership/feature resources.
140
+ - **Tenant-scoped** by `multiTenantPlugin` (`tenant: false` for platform-wide grants like a user's API key).
141
+ - **No TTL index, no cron required for the gate** — expiry is lazy at read time; `expireDue` exists only to emit events and make `status` queryable.
142
+ - **Indexes** are race-proof: one active grant per `(org, subject, resource, scope)` via a partial unique index; terminal states free the slot.
143
+
144
+ ## License
145
+
146
+ MIT
147
+
148
+ ## Trademark
149
+
150
+ Code is MIT-licensed. "Classytic"/"arc" names + logos are trademarks of Classytic LLC — see [TRADEMARK.md](TRADEMARK.md).
@@ -8,23 +8,45 @@
8
8
  * exact same rule runs on the server hot path, in an edge/middleware check,
9
9
  * and in the UI — one source of truth, zero drift.
10
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
+ *
11
27
  * ── Why a function and not a stored flag ──────────────────────────────────
12
28
  * An entitlement's stored `status` records only explicit LIFECYCLE events
13
29
  * (granted → active, suspended, revoked, refunded, consumed). Expiry is NEVER
14
30
  * written by the buyer-facing path: it is DERIVED here from the window. That is
15
31
  * what lets the row survive as a permanent record (audit, renewal, "renew"
16
- * upsell) instead of being TTL-deleted (PACKAGE_RULES Concurrency House Rules:
17
- * "Self-healing CAS expiry over TTL-delete indexes — model expiry as a state
18
- * transition so the row survives as a record"). A background sweeper may later
19
- * CAS the stored status to `expired` and emit `access:expired`, but the gate
20
- * never waits for it: a grant past its window evaluates to `expired` here the
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
21
35
  * instant it lapses, covering the sweep lag.
22
36
  *
23
37
  * Deny precedence is explicit and ordered (most-terminal first) so the reason
24
38
  * a host surfaces is the most meaningful one.
25
39
  */
26
40
  /** Why a grant is or isn't usable right now. `active` is the only allow. */
27
- type AccessReason = 'active' | 'not_found' | 'not_yet_active' | 'expired' | 'suspended' | 'revoked' | 'refunded' | 'consumed' | 'quota_exhausted';
41
+ type AccessReason = 'active' | 'not_found' | 'not_yet_active' | 'expired' | 'suspended' | 'revoked' | 'refunded' | 'consumed' | 'quota_exhausted' |
42
+ /**
43
+ * The grant exists but cannot be trusted: a status this engine does not
44
+ * recognise, an unparseable date, a non-finite quota. Distinct from
45
+ * `not_found` so a host can ALERT on it — an `invalid_grant` in production
46
+ * means corrupted data or a version skew, and both deserve a page, not a
47
+ * silent deny that reads like a lapsed membership.
48
+ */
49
+ 'invalid_grant';
28
50
  /**
29
51
  * The minimal shape `evaluateAccess` reads. A full `EntitlementDocument`
30
52
  * structurally satisfies it, and so does a hand-built object on the wire — the
@@ -4,12 +4,29 @@ const TERMINAL_DENY = {
4
4
  revoked: "revoked",
5
5
  refunded: "refunded",
6
6
  suspended: "suspended",
7
- consumed: "consumed"
7
+ consumed: "consumed",
8
+ /**
9
+ * Stored `expired` denies EXPLICITLY, not via window math. The sweeper wrote
10
+ * it because the window had lapsed — but the window field can be nulled or
11
+ * mangled afterwards (a bad migration, a hand edit), and the earlier code
12
+ * then re-derived "no boundary" and allowed. The status is a lifecycle fact
13
+ * in its own right; only `extend()` (which CAS-transitions back to active)
14
+ * may reopen the grant.
15
+ */
16
+ expired: "expired"
8
17
  };
18
+ /** Sentinel distinguishing "present but unparseable" from "absent". */
19
+ const INVALID = Symbol("invalid-date");
20
+ /**
21
+ * Absent (`null`/`undefined`) → `null` (no boundary — a deliberate choice).
22
+ * Present but unparseable → `INVALID` (deny — the row cannot be trusted).
23
+ * Collapsing the two was finding #5: `accessExpiresAt: 'garbage'` became
24
+ * lifetime access.
25
+ */
9
26
  function toEpoch(value) {
10
27
  if (value === null || value === void 0) return null;
11
28
  const ms = value instanceof Date ? value.getTime() : new Date(value).getTime();
12
- return Number.isNaN(ms) ? null : ms;
29
+ return Number.isNaN(ms) ? INVALID : ms;
13
30
  }
14
31
  function decision(allowed, reason, expiresAt, remaining) {
15
32
  return {
@@ -27,15 +44,42 @@ function decision(allowed, reason, expiresAt, remaining) {
27
44
  */
28
45
  function evaluateAccess(grant, now = Date.now()) {
29
46
  if (!grant || !grant.status) return decision(false, "not_found", null, null);
47
+ /**
48
+ * A non-finite `now` bypasses every time comparison below (`NaN > x` and
49
+ * `NaN <= x` are both false), so a scheduled grant would read as open and a
50
+ * lapsed one as live. This function is published for edge/UI/wire callers
51
+ * where `now` may come from a header or a parsed timestamp, so it is checked
52
+ * rather than assumed.
53
+ */
54
+ if (!Number.isFinite(now)) return decision(false, "invalid_grant", null, null);
55
+ const expiresAtRaw = toEpoch(grant.accessExpiresAt);
56
+ const notBeforeRaw = toEpoch(grant.notBefore);
57
+ if (expiresAtRaw === INVALID || notBeforeRaw === INVALID) return decision(false, "invalid_grant", null, null);
58
+ const expiresAt = expiresAtRaw;
30
59
  const limit = grant.usage?.limit ?? null;
31
60
  const used = grant.usage?.used ?? 0;
61
+ if (!(Number.isInteger(used) && used >= 0 && (limit === null || Number.isInteger(limit) && limit >= 0))) return decision(false, "invalid_grant", expiresAt, null);
32
62
  const remaining = limit === null ? null : Math.max(0, limit - used);
33
- const expiresAt = toEpoch(grant.accessExpiresAt);
34
63
  const terminal = TERMINAL_DENY[grant.status];
35
64
  if (terminal) return decision(false, terminal, expiresAt, remaining);
36
- const notBefore = toEpoch(grant.notBefore);
37
- if (notBefore !== null && notBefore > now) return decision(false, "not_yet_active", expiresAt, remaining);
65
+ if (grant.status !== "active") return decision(false, "invalid_grant", expiresAt, remaining);
66
+ if (notBeforeRaw !== null && notBeforeRaw > now) return decision(false, "not_yet_active", expiresAt, remaining);
38
67
  if (expiresAt !== null && expiresAt <= now) return decision(false, "expired", expiresAt, remaining);
68
+ /**
69
+ * 5. Metered access exhausted (derived; a consume() may later flip the stored
70
+ * status to `consumed`, which step 1 then short-circuits).
71
+ *
72
+ * `used > limit` — strictly over, not merely at — is reported as
73
+ * `quota_exhausted` rather than `invalid_grant`, a deliberate divergence from
74
+ * the review's suggestion. Both DENY, so there is no security difference; the
75
+ * choice is about who gets woken up. `consume`'s capacity guard makes
76
+ * overshoot impossible, but an admin LOWERING `usage.limit` below the units
77
+ * already spent produces the same shape legitimately. Paging an engineer for
78
+ * a supported admin action is worse than reporting the actionable reason ("out
79
+ * of credits — top up"), which is true either way. Negative and fractional
80
+ * counters, which no operation can produce, are the ones treated as corruption
81
+ * above.
82
+ */
39
83
  if (limit !== null && used >= limit) return decision(false, "quota_exhausted", expiresAt, 0);
40
84
  return decision(true, "active", expiresAt, remaining);
41
85
  }
@@ -1,6 +1,5 @@
1
1
  import { DomainEvent, EventMeta } from "@classytic/primitives/events";
2
2
  import { z } from "zod";
3
-
4
3
  //#region src/events/event-constants.d.ts
5
4
  /**
6
5
  * ACCESS_EVENTS — domain event constants. Prefix `access:` per
@@ -1,2 +1,2 @@
1
- import { a as Extended, c as Resumed, d as accessEventDefinitions, i as Expired, l as Revoked, n as AccessEventSchema, o as Granted, r as Exhausted, s as Refunded, t as AccessEventDefinition, u as Suspended } from "../event-catalog-BGFNnlNJ.mjs";
1
+ import { a as Extended, c as Resumed, d as accessEventDefinitions, i as Expired, l as Revoked, n as AccessEventSchema, o as Granted, r as Exhausted, s as Refunded, t as AccessEventDefinition, u as Suspended } from "../event-catalog-Dxo3cxR3.mjs";
2
2
  export { AccessEventDefinition, AccessEventSchema, Exhausted, Expired, Extended, Granted, Refunded, Resumed, Revoked, Suspended, accessEventDefinitions };