@classytic/access 0.1.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 +22 -0
- package/README.md +140 -0
- package/dist/domain/access-decision.d.mts +66 -0
- package/dist/domain/access-decision.mjs +47 -0
- package/dist/event-catalog-BGFNnlNJ.d.mts +137 -0
- package/dist/event-catalog-BVD_rFlc.mjs +111 -0
- package/dist/events/event-catalog.d.mts +2 -0
- package/dist/events/event-catalog.mjs +2 -0
- package/dist/index.d.mts +362 -0
- package/dist/index.mjs +854 -0
- package/dist/schemas/common.d.mts +19 -0
- package/dist/schemas/common.mjs +18 -0
- package/dist/schemas/entitlement.d.mts +56 -0
- package/dist/schemas/entitlement.mjs +44 -0
- package/package.json +87 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
Initial release — the access **entitlement** engine.
|
|
6
|
+
|
|
7
|
+
- `Entitlement` model: a durable, polymorphic (subject ⇄ resource) grant with a
|
|
8
|
+
window (`notBefore` / `accessExpiresAt`), optional metering (`usage`), and
|
|
9
|
+
polymorphic provenance (`originRef` / `originModel`). No TTL index — expiry is
|
|
10
|
+
modelled as a CAS state transition so the row survives as a record.
|
|
11
|
+
- `evaluateAccess` — the pure decision, published at the `@classytic/access/decision`
|
|
12
|
+
subpath (no mongoose) so the same rule runs on the server, edge, and UI.
|
|
13
|
+
- `EntitlementRepository` verbs: `grant` (idempotent, renewing), `check` (hot
|
|
14
|
+
path), `consume` (race-proof metered spend), `extend`, `suspend` / `resume`,
|
|
15
|
+
`revoke`, `expireDue` (sweeper), `refundByOrigin` (cascade), `listForSubject`.
|
|
16
|
+
- Events: `access:granted | extended | suspended | resumed | revoked | expired |
|
|
17
|
+
exhausted | refunded`, with a Zod-source `accessEventDefinitions` catalog.
|
|
18
|
+
- Engine factory `createAccess`, capability boot gate, multi-tenant plugin,
|
|
19
|
+
soft delete, in-process event fallback, P4/P8 outbox seams.
|
|
20
|
+
- 30 tests: decision truth table, FSM, event-catalog no-drift, tenant probe,
|
|
21
|
+
and three scenarios (time-bound course access + renewal, metered API quota
|
|
22
|
+
with a concurrency race, lifecycle + refund cascade).
|
package/README.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
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
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
//#region src/domain/access-decision.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The access decision — the heart of `@classytic/access`.
|
|
4
|
+
*
|
|
5
|
+
* `evaluateAccess` is a PURE function (no mongoose, no I/O) that answers the
|
|
6
|
+
* one question every gate asks: "does this subject hold a live grant RIGHT
|
|
7
|
+
* NOW?". It is published at the `@classytic/access/decision` subpath so the
|
|
8
|
+
* exact same rule runs on the server hot path, in an edge/middleware check,
|
|
9
|
+
* and in the UI — one source of truth, zero drift.
|
|
10
|
+
*
|
|
11
|
+
* ── Why a function and not a stored flag ──────────────────────────────────
|
|
12
|
+
* An entitlement's stored `status` records only explicit LIFECYCLE events
|
|
13
|
+
* (granted → active, suspended, revoked, refunded, consumed). Expiry is NEVER
|
|
14
|
+
* written by the buyer-facing path: it is DERIVED here from the window. That is
|
|
15
|
+
* 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
|
|
21
|
+
* instant it lapses, covering the sweep lag.
|
|
22
|
+
*
|
|
23
|
+
* Deny precedence is explicit and ordered (most-terminal first) so the reason
|
|
24
|
+
* a host surfaces is the most meaningful one.
|
|
25
|
+
*/
|
|
26
|
+
/** 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';
|
|
28
|
+
/**
|
|
29
|
+
* The minimal shape `evaluateAccess` reads. A full `EntitlementDocument`
|
|
30
|
+
* structurally satisfies it, and so does a hand-built object on the wire — the
|
|
31
|
+
* decision never needs the whole row. `Date | string | number | null` covers
|
|
32
|
+
* a live mongoose doc (Date), a JSON response (ISO string), and an epoch.
|
|
33
|
+
*/
|
|
34
|
+
interface AccessGrantState {
|
|
35
|
+
/** Lifecycle status. A missing/empty status is treated as no usable grant. */
|
|
36
|
+
status?: string | undefined;
|
|
37
|
+
/** Access does not begin until this instant (scheduled / early-access). */
|
|
38
|
+
notBefore?: Date | string | number | null | undefined;
|
|
39
|
+
/** Access ends at this instant. `null` / absent = lifetime (never expires). */
|
|
40
|
+
accessExpiresAt?: Date | string | number | null | undefined;
|
|
41
|
+
/** Metered access. `limit: null`/absent = unlimited; else deny once `used >= limit`. */
|
|
42
|
+
usage?: {
|
|
43
|
+
limit?: number | null | undefined;
|
|
44
|
+
used?: number | null | undefined;
|
|
45
|
+
} | null | undefined;
|
|
46
|
+
}
|
|
47
|
+
interface AccessDecision {
|
|
48
|
+
/** The single boolean a gate branches on. */
|
|
49
|
+
allowed: boolean;
|
|
50
|
+
reason: AccessReason;
|
|
51
|
+
/** Epoch ms when the window ends, or `null` for lifetime / no window. */
|
|
52
|
+
expiresAt: number | null;
|
|
53
|
+
/** Remaining metered units, or `null` when unlimited / unmetered. */
|
|
54
|
+
remaining: number | null;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Decide whether `grant` permits access at `now` (epoch ms, default `Date.now()`).
|
|
58
|
+
*
|
|
59
|
+
* `null` / `undefined` grant → `not_found` (the "no row at all" case), so a
|
|
60
|
+
* gate can do `evaluateAccess(await repo.find(...))` without a null guard.
|
|
61
|
+
*/
|
|
62
|
+
declare function evaluateAccess(grant: AccessGrantState | null | undefined, now?: number): AccessDecision;
|
|
63
|
+
/** Convenience boolean for the common gate. */
|
|
64
|
+
declare function hasAccess(grant: AccessGrantState | null | undefined, now?: number): boolean;
|
|
65
|
+
//#endregion
|
|
66
|
+
export { AccessDecision, AccessGrantState, AccessReason, evaluateAccess, hasAccess };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
//#region src/domain/access-decision.ts
|
|
2
|
+
/** Statuses that deny regardless of the window, mapped to their reason. */
|
|
3
|
+
const TERMINAL_DENY = {
|
|
4
|
+
revoked: "revoked",
|
|
5
|
+
refunded: "refunded",
|
|
6
|
+
suspended: "suspended",
|
|
7
|
+
consumed: "consumed"
|
|
8
|
+
};
|
|
9
|
+
function toEpoch(value) {
|
|
10
|
+
if (value === null || value === void 0) return null;
|
|
11
|
+
const ms = value instanceof Date ? value.getTime() : new Date(value).getTime();
|
|
12
|
+
return Number.isNaN(ms) ? null : ms;
|
|
13
|
+
}
|
|
14
|
+
function decision(allowed, reason, expiresAt, remaining) {
|
|
15
|
+
return {
|
|
16
|
+
allowed,
|
|
17
|
+
reason,
|
|
18
|
+
expiresAt,
|
|
19
|
+
remaining
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Decide whether `grant` permits access at `now` (epoch ms, default `Date.now()`).
|
|
24
|
+
*
|
|
25
|
+
* `null` / `undefined` grant → `not_found` (the "no row at all" case), so a
|
|
26
|
+
* gate can do `evaluateAccess(await repo.find(...))` without a null guard.
|
|
27
|
+
*/
|
|
28
|
+
function evaluateAccess(grant, now = Date.now()) {
|
|
29
|
+
if (!grant || !grant.status) return decision(false, "not_found", null, null);
|
|
30
|
+
const limit = grant.usage?.limit ?? null;
|
|
31
|
+
const used = grant.usage?.used ?? 0;
|
|
32
|
+
const remaining = limit === null ? null : Math.max(0, limit - used);
|
|
33
|
+
const expiresAt = toEpoch(grant.accessExpiresAt);
|
|
34
|
+
const terminal = TERMINAL_DENY[grant.status];
|
|
35
|
+
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);
|
|
38
|
+
if (expiresAt !== null && expiresAt <= now) return decision(false, "expired", expiresAt, remaining);
|
|
39
|
+
if (limit !== null && used >= limit) return decision(false, "quota_exhausted", expiresAt, 0);
|
|
40
|
+
return decision(true, "active", expiresAt, remaining);
|
|
41
|
+
}
|
|
42
|
+
/** Convenience boolean for the common gate. */
|
|
43
|
+
function hasAccess(grant, now = Date.now()) {
|
|
44
|
+
return evaluateAccess(grant, now).allowed;
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { evaluateAccess, hasAccess };
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { DomainEvent, EventMeta } from "@classytic/primitives/events";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/events/event-constants.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* ACCESS_EVENTS — domain event constants. Prefix `access:` per
|
|
7
|
+
* PACKAGE_RULES §12. Hosts subscribe glob-style so typos are compile errors.
|
|
8
|
+
*/
|
|
9
|
+
declare const ACCESS_EVENTS: {
|
|
10
|
+
readonly GRANTED: "access:granted";
|
|
11
|
+
readonly EXTENDED: "access:extended";
|
|
12
|
+
readonly SUSPENDED: "access:suspended";
|
|
13
|
+
readonly RESUMED: "access:resumed";
|
|
14
|
+
readonly REVOKED: "access:revoked";
|
|
15
|
+
readonly EXPIRED: "access:expired";
|
|
16
|
+
readonly EXHAUSTED: "access:exhausted";
|
|
17
|
+
readonly REFUNDED: "access:refunded";
|
|
18
|
+
};
|
|
19
|
+
type AccessEventName = (typeof ACCESS_EVENTS)[keyof typeof ACCESS_EVENTS];
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/events/event-catalog.d.ts
|
|
22
|
+
type AccessEventSchema = Record<string, unknown>;
|
|
23
|
+
interface AccessEventDefinition<TSchema extends z.ZodType = z.ZodType> {
|
|
24
|
+
name: AccessEventName;
|
|
25
|
+
version: number;
|
|
26
|
+
description: string;
|
|
27
|
+
zodSchema: TSchema;
|
|
28
|
+
schema: AccessEventSchema;
|
|
29
|
+
create(payload: z.infer<TSchema>, meta?: Partial<EventMeta>): DomainEvent<z.infer<TSchema>>;
|
|
30
|
+
}
|
|
31
|
+
declare const Granted: AccessEventDefinition<z.ZodObject<{
|
|
32
|
+
entitlementId: z.ZodString;
|
|
33
|
+
organizationId: z.ZodOptional<z.ZodString>;
|
|
34
|
+
subjectRef: z.ZodString;
|
|
35
|
+
subjectModel: z.ZodString;
|
|
36
|
+
resourceRef: z.ZodString;
|
|
37
|
+
resourceType: z.ZodString;
|
|
38
|
+
scopeKey: z.ZodString;
|
|
39
|
+
status: z.ZodString;
|
|
40
|
+
accessExpiresAt: z.ZodOptional<z.ZodISODateTime>;
|
|
41
|
+
usageLimit: z.ZodOptional<z.ZodNumber>;
|
|
42
|
+
usageUsed: z.ZodOptional<z.ZodNumber>;
|
|
43
|
+
}, z.core.$strip>>;
|
|
44
|
+
declare const Extended: AccessEventDefinition<z.ZodObject<{
|
|
45
|
+
entitlementId: z.ZodString;
|
|
46
|
+
organizationId: z.ZodOptional<z.ZodString>;
|
|
47
|
+
subjectRef: z.ZodString;
|
|
48
|
+
subjectModel: z.ZodString;
|
|
49
|
+
resourceRef: z.ZodString;
|
|
50
|
+
resourceType: z.ZodString;
|
|
51
|
+
scopeKey: z.ZodString;
|
|
52
|
+
status: z.ZodString;
|
|
53
|
+
accessExpiresAt: z.ZodOptional<z.ZodISODateTime>;
|
|
54
|
+
usageLimit: z.ZodOptional<z.ZodNumber>;
|
|
55
|
+
usageUsed: z.ZodOptional<z.ZodNumber>;
|
|
56
|
+
}, z.core.$strip>>;
|
|
57
|
+
declare const Suspended: AccessEventDefinition<z.ZodObject<{
|
|
58
|
+
entitlementId: z.ZodString;
|
|
59
|
+
organizationId: z.ZodOptional<z.ZodString>;
|
|
60
|
+
subjectRef: z.ZodString;
|
|
61
|
+
subjectModel: z.ZodString;
|
|
62
|
+
resourceRef: z.ZodString;
|
|
63
|
+
resourceType: z.ZodString;
|
|
64
|
+
scopeKey: z.ZodString;
|
|
65
|
+
status: z.ZodString;
|
|
66
|
+
accessExpiresAt: z.ZodOptional<z.ZodISODateTime>;
|
|
67
|
+
usageLimit: z.ZodOptional<z.ZodNumber>;
|
|
68
|
+
usageUsed: z.ZodOptional<z.ZodNumber>;
|
|
69
|
+
}, z.core.$strip>>;
|
|
70
|
+
declare const Resumed: AccessEventDefinition<z.ZodObject<{
|
|
71
|
+
entitlementId: z.ZodString;
|
|
72
|
+
organizationId: z.ZodOptional<z.ZodString>;
|
|
73
|
+
subjectRef: z.ZodString;
|
|
74
|
+
subjectModel: z.ZodString;
|
|
75
|
+
resourceRef: z.ZodString;
|
|
76
|
+
resourceType: z.ZodString;
|
|
77
|
+
scopeKey: z.ZodString;
|
|
78
|
+
status: z.ZodString;
|
|
79
|
+
accessExpiresAt: z.ZodOptional<z.ZodISODateTime>;
|
|
80
|
+
usageLimit: z.ZodOptional<z.ZodNumber>;
|
|
81
|
+
usageUsed: z.ZodOptional<z.ZodNumber>;
|
|
82
|
+
}, z.core.$strip>>;
|
|
83
|
+
declare const Revoked: AccessEventDefinition<z.ZodObject<{
|
|
84
|
+
entitlementId: z.ZodString;
|
|
85
|
+
organizationId: z.ZodOptional<z.ZodString>;
|
|
86
|
+
subjectRef: z.ZodString;
|
|
87
|
+
subjectModel: z.ZodString;
|
|
88
|
+
resourceRef: z.ZodString;
|
|
89
|
+
resourceType: z.ZodString;
|
|
90
|
+
scopeKey: z.ZodString;
|
|
91
|
+
status: z.ZodString;
|
|
92
|
+
accessExpiresAt: z.ZodOptional<z.ZodISODateTime>;
|
|
93
|
+
usageLimit: z.ZodOptional<z.ZodNumber>;
|
|
94
|
+
usageUsed: z.ZodOptional<z.ZodNumber>;
|
|
95
|
+
}, z.core.$strip>>;
|
|
96
|
+
declare const Expired: AccessEventDefinition<z.ZodObject<{
|
|
97
|
+
entitlementId: z.ZodString;
|
|
98
|
+
organizationId: z.ZodOptional<z.ZodString>;
|
|
99
|
+
subjectRef: z.ZodString;
|
|
100
|
+
subjectModel: z.ZodString;
|
|
101
|
+
resourceRef: z.ZodString;
|
|
102
|
+
resourceType: z.ZodString;
|
|
103
|
+
scopeKey: z.ZodString;
|
|
104
|
+
status: z.ZodString;
|
|
105
|
+
accessExpiresAt: z.ZodOptional<z.ZodISODateTime>;
|
|
106
|
+
usageLimit: z.ZodOptional<z.ZodNumber>;
|
|
107
|
+
usageUsed: z.ZodOptional<z.ZodNumber>;
|
|
108
|
+
}, z.core.$strip>>;
|
|
109
|
+
declare const Exhausted: AccessEventDefinition<z.ZodObject<{
|
|
110
|
+
entitlementId: z.ZodString;
|
|
111
|
+
organizationId: z.ZodOptional<z.ZodString>;
|
|
112
|
+
subjectRef: z.ZodString;
|
|
113
|
+
subjectModel: z.ZodString;
|
|
114
|
+
resourceRef: z.ZodString;
|
|
115
|
+
resourceType: z.ZodString;
|
|
116
|
+
scopeKey: z.ZodString;
|
|
117
|
+
status: z.ZodString;
|
|
118
|
+
accessExpiresAt: z.ZodOptional<z.ZodISODateTime>;
|
|
119
|
+
usageLimit: z.ZodOptional<z.ZodNumber>;
|
|
120
|
+
usageUsed: z.ZodOptional<z.ZodNumber>;
|
|
121
|
+
}, z.core.$strip>>;
|
|
122
|
+
declare const Refunded: AccessEventDefinition<z.ZodObject<{
|
|
123
|
+
entitlementId: z.ZodString;
|
|
124
|
+
organizationId: z.ZodOptional<z.ZodString>;
|
|
125
|
+
subjectRef: z.ZodString;
|
|
126
|
+
subjectModel: z.ZodString;
|
|
127
|
+
resourceRef: z.ZodString;
|
|
128
|
+
resourceType: z.ZodString;
|
|
129
|
+
scopeKey: z.ZodString;
|
|
130
|
+
status: z.ZodString;
|
|
131
|
+
accessExpiresAt: z.ZodOptional<z.ZodISODateTime>;
|
|
132
|
+
usageLimit: z.ZodOptional<z.ZodNumber>;
|
|
133
|
+
usageUsed: z.ZodOptional<z.ZodNumber>;
|
|
134
|
+
}, z.core.$strip>>;
|
|
135
|
+
declare const accessEventDefinitions: ReadonlyArray<AccessEventDefinition>;
|
|
136
|
+
//#endregion
|
|
137
|
+
export { Extended as a, Resumed as c, accessEventDefinitions as d, ACCESS_EVENTS as f, Expired as i, Revoked as l, AccessEventSchema as n, Granted as o, AccessEventName as p, Exhausted as r, Refunded as s, AccessEventDefinition as t, Suspended as u };
|
|
@@ -0,0 +1,111 @@
|
|
|
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 };
|
|
@@ -0,0 +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";
|
|
2
|
+
export { AccessEventDefinition, AccessEventSchema, Exhausted, Expired, Extended, Granted, Refunded, Resumed, Revoked, Suspended, accessEventDefinitions };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as Refunded, c as Suspended, i as Granted, l as accessEventDefinitions, n as Expired, o as Resumed, r as Extended, s as Revoked, t as Exhausted } from "../event-catalog-BVD_rFlc.mjs";
|
|
2
|
+
export { Exhausted, Expired, Extended, Granted, Refunded, Resumed, Revoked, Suspended, accessEventDefinitions };
|