@forgezero/access 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -1,115 +1,408 @@
1
+ <!--
2
+ GENERATED FILE — do not edit.
3
+
4
+ Change tools/generate-guides.ts or its typed sources, run `bun run guides`,
5
+ and commit the generator and rendered files together.
6
+ -->
7
+
1
8
  # @forgezero/access
2
9
 
3
- **Who may call what, decided from one table instead of scattered `if` statements.**
10
+ Declare your security posture as seven lists. Handlers hold business logic only.
4
11
 
5
- You declare every route once — the session it needs, the roles that reach it, the
6
- factors it demands — and the same declaration authorises the request, renders the
7
- navigation and fails the build when the two disagree.
12
+ ## Package overview
8
13
 
9
- Zero runtime dependencies. Bun, Node 18+, Deno, Cloudflare Workers, browsers
10
- anywhere `fetch` and Web Crypto exist.
14
+ Anyone building a service on our request shape: one declared matrix of routes and factors, enforced by one pipeline whatever the framework. Imports no sibling at all, so it can be adopted on its own. Supported runtimes: bun, node, workers, deno. Package root: @forgezero/access. The sections below show the actual named imports emitted by each declaration entry point; wildcard imports are intentionally not used in the documentation.
11
15
 
12
- ```bash
16
+ ```text
13
17
  bun add @forgezero/access
14
18
  ```
15
19
 
16
- ## The idea in twelve lines
20
+ ## ForgeZero package family
21
+
22
+ The five packages are installation boundaries. Choose a package by who installs it; choose a subpath by the capability used in that file.
23
+
24
+ | package | short description | runtimes | documentation |
25
+ |---|---|---|---|
26
+ | @forgezero/vault | Scoped secret access with Agent, API-key and systemd-credential sources. | bun, node, workers, deno | [Open](https://www.forgezero.net/docs/vault-package) |
27
+ | @forgezero/access | Typed route, principal, factor, RBAC and request-pipeline contracts. | bun, node, workers, deno | [Open](https://www.forgezero.net/docs/access) |
28
+ | @forgezero/providers | Typed external providers with priority, health and classified fallback. | bun, node, workers, deno | [Open](https://www.forgezero.net/docs/providers) |
29
+ | @forgezero/runtime | Portable runtime primitives for queries, jobs, events, schemas and finance. | bun, node | [Open](https://www.forgezero.net/docs/runtime) |
30
+ | @forgezero/agent | Operator CLI and managed-node agent for bootstrap, deploy and lifecycle. | bun, node | [Open](https://www.forgezero.net/docs/agent) |
31
+
32
+ ## @forgezero/access public imports and commands
33
+
34
+ Every row links to the detailed explanation and named-import/example area below. This table and those details are generated from the package inventory and emitted declarations.
35
+
36
+ | public entry | short description | runtime | details |
37
+ |---|---|---|---|
38
+ | @forgezero/access | Declare routes, factors and policies as orthogonal lists; authorise against them. | portable | [Details + example](#forgezero-access) |
39
+ | @forgezero/access/conditions | The twelve guards every project writes into `before`, each with the status its refusal deserves. | portable | [Details + example](#forgezero-access-conditions) |
40
+ | @forgezero/access/effects | Audit, emit, meter, invalidate and notify — what happens after a request is decided, never failing it. | portable | [Details + example](#forgezero-access-effects) |
41
+ | @forgezero/access/security | Constant-time comparison, CSPRNG tokens, HMAC, HKDF, AES-GCM sealing and redaction. Web Crypto only. | portable | [Details + example](#forgezero-access-security) |
42
+ | @forgezero/access/rate-limit | Request counters over a window — in memory, in Redis, or in a Durable Object. | portable | [Details + example](#forgezero-access-rate-limit) |
43
+ | @forgezero/access/fetch | A Fetch-native adapter over the declared access pipeline. | portable | [Details + example](#forgezero-access-fetch) |
44
+ | @forgezero/access/pipeline | The framework-neutral route, principal, factor, policy, rate-limit and effects pipeline. | portable | [Details + example](#forgezero-access-pipeline) |
45
+ | @forgezero/access/elysia | Elysia integration over the same access pipeline and route declarations. | portable | [Details + example](#forgezero-access-elysia) |
46
+ | @forgezero/access/client | Typed client helpers that fulfil factors without duplicating the security matrix. | portable | [Details + example](#forgezero-access-client) |
47
+ | @forgezero/access/testing | Deterministic access-pipeline fixtures and assertions for consumer tests. | portable | [Details + example](#forgezero-access-testing) |
48
+ | @forgezero/access/header | Strict configurable header-identity extraction with canonical names and bounded values. | portable | [Details + example](#forgezero-access-header) |
49
+ | @forgezero/access/principal | Generic principal-source resolution for browser, API-key, attestation or future identity adapters. | portable | [Details + example](#forgezero-access-principal) |
50
+ | @forgezero/access/principal-session | Short-lived scope-bound delegated-principal sessions with sliding and absolute expiry. | portable | [Details + example](#forgezero-access-principal-session) |
51
+ | @forgezero/access/authenticator | Authentication-source contracts for adding identity mechanisms without changing route policy. | portable | [Details + example](#forgezero-access-authenticator) |
52
+ | @forgezero/access/ceremony-modes | Named security-ceremony modes and their session/action fulfilment semantics. | portable | [Details + example](#forgezero-access-ceremony-modes) |
53
+
54
+ ## Commands
55
+
56
+ bun add @forgezero/access — Install the framework-neutral access contracts and adapters.
57
+
58
+ ```text
59
+ bun add @forgezero/access
60
+ ```
61
+
62
+ <a id="forgezero-access"></a>
63
+ ## @forgezero/access
64
+
65
+ Declare routes, factors and policies as orthogonal lists; authorise against them. Named value imports: AccessError, Refusal, SCHEMA_VERSION, Settled, VERSION, action, assertReadable, authorise, codePolicy, defineAccessControl, defineFactors, defineRoutes, externalPolicy, fulfilledActionFactors, grantsRoute, impactOfDisabling, isRefusal, isSettled, page, resolveActionFactors, stemOf. Named type imports: AccessControl, AccessControlConfig, ActionPolicy, ActionRoute, AfterHandler, BeforeHandler, Binding, FactorContext, FactorKind, FactorRegistry, FactorSpec, GrantOptions, Method, Outcome, PageRoute, PolicySource, Problem, RatePolicy, RequestContext, Role, RouteBase, RouteContract, RouteRegistry, RouteSpec, SessionContext, SessionPolicy, Versioned. Import only the names used by this file.
66
+
67
+ ```text
68
+ import { AccessError, Refusal, SCHEMA_VERSION, Settled, VERSION, action } from '@forgezero/access';
69
+ import { assertReadable, authorise, codePolicy, defineAccessControl, defineFactors, defineRoutes } from '@forgezero/access';
70
+ import { externalPolicy, fulfilledActionFactors, grantsRoute, impactOfDisabling, isRefusal, isSettled } from '@forgezero/access';
71
+ import { page, resolveActionFactors, stemOf } from '@forgezero/access';
72
+ import type { AccessControl, AccessControlConfig, ActionPolicy, ActionRoute, AfterHandler, BeforeHandler } from '@forgezero/access';
73
+ import type { Binding, FactorContext, FactorKind, FactorRegistry, FactorSpec, GrantOptions } from '@forgezero/access';
74
+ import type { Method, Outcome, PageRoute, PolicySource, Problem, RatePolicy } from '@forgezero/access';
75
+ import type { RequestContext, Role, RouteBase, RouteContract, RouteRegistry, RouteSpec } from '@forgezero/access';
76
+ import type { SessionContext, SessionPolicy, Versioned } from '@forgezero/access';
77
+ ```
78
+
79
+ ## @forgezero/access — Declare routes before handlers
17
80
 
18
- ```ts
19
- import { defineRoutes, authorise } from '@forgezero/access';
81
+ Routes and their access policy are data; Fetch and Elysia adapters enforce the same declaration.
20
82
 
21
- const ACCESS = defineRoutes({
22
- 'api/invoices': { group: 'session', factors: ['passkey'] },
23
- 'api/invoices/refund': { group: 'admin', factors: ['passkey'], actionFactors: ['passkey'] }
83
+ ```text
84
+ import { defineRoutes, action, page } from '@forgezero/access';
85
+
86
+ export const routes = defineRoutes({
87
+ orders: page('Orders'),
88
+ 'api/orders': action('List orders', 'GET', { page: 'orders' })
24
89
  });
90
+ ```
91
+
92
+ <a id="forgezero-access-conditions"></a>
93
+ ## @forgezero/access/conditions
94
+
95
+ The twelve guards every project writes into `before`, each with the status its refusal deserves. Named value imports: assertDeclaredRefusals, loadTarget, refusalsFor, requireApproval, requireBalance, requireIdempotency, requireNotFrozen, requireOwner, requireQuota, requireService, requireState, requireTier, requireUnlocked, requireVersion. Named type imports: ApprovalState, Condition, IdempotencyStore, LoadTargetOptions, RefusalSpec, RequireApprovalOptions, RequireBalanceOptions, RequireIdempotencyOptions, RequireNotFrozenOptions, RequireOwnerOptions, RequireQuotaOptions, RequireServiceOptions, RequireStateOptions, RequireTierOptions, RequireUnlockedOptions, RequireVersionOptions. Import only the names used by this file.
96
+
97
+ ```text
98
+ import { assertDeclaredRefusals, loadTarget, refusalsFor, requireApproval, requireBalance, requireIdempotency } from '@forgezero/access/conditions';
99
+ import { requireNotFrozen, requireOwner, requireQuota, requireService, requireState, requireTier } from '@forgezero/access/conditions';
100
+ import { requireUnlocked, requireVersion } from '@forgezero/access/conditions';
101
+ import type { ApprovalState, Condition, IdempotencyStore, LoadTargetOptions, RefusalSpec, RequireApprovalOptions } from '@forgezero/access/conditions';
102
+ import type { RequireBalanceOptions, RequireIdempotencyOptions, RequireNotFrozenOptions, RequireOwnerOptions, RequireQuotaOptions, RequireServiceOptions } from '@forgezero/access/conditions';
103
+ import type { RequireStateOptions, RequireTierOptions, RequireUnlockedOptions, RequireVersionOptions } from '@forgezero/access/conditions';
104
+ ```
105
+
106
+ <a id="forgezero-access-effects"></a>
107
+ ## @forgezero/access/effects
108
+
109
+ Audit, emit, meter, invalidate and notify — what happens after a request is decided, never failing it. Named value imports: audit, emit, invalidate, meter, notify, settlementOf. Named type imports: AuditOptions, AuditRecord, AuditSink, CacheInvalidator, Effect, EmitOptions, InvalidateOptions, MeterOptions, Notification, Notifier, NotifyOptions, Outbox, OutboxEvent, Settlement, UsageMeter. Import only the names used by this file.
110
+
111
+ ```text
112
+ import { audit, emit, invalidate, meter, notify, settlementOf } from '@forgezero/access/effects';
113
+ import type { AuditOptions, AuditRecord, AuditSink, CacheInvalidator, Effect, EmitOptions } from '@forgezero/access/effects';
114
+ import type { InvalidateOptions, MeterOptions, Notification, Notifier, NotifyOptions, Outbox } from '@forgezero/access/effects';
115
+ import type { OutboxEvent, Settlement, UsageMeter } from '@forgezero/access/effects';
116
+ ```
117
+
118
+ <a id="forgezero-access-security"></a>
119
+ ## @forgezero/access/security
120
+
121
+ Constant-time comparison, CSPRNG tokens, HMAC, HKDF, AES-GCM sealing and redaction. Web Crypto only. Named value imports: fromBase64Url, fromHex, hashToken, hkdf, hmacSha256, isLive, nowSeconds, open, randomDigits, randomHex, randomInt, randomToken, redact, seal, secretFieldPattern, sha256, timingSafeEqual, toBase64Url, toHex, verifyHmac. Named type imports: Sealed. Import only the names used by this file.
122
+
123
+ ```text
124
+ import { fromBase64Url, fromHex, hashToken, hkdf, hmacSha256, isLive } from '@forgezero/access/security';
125
+ import { nowSeconds, open, randomDigits, randomHex, randomInt, randomToken } from '@forgezero/access/security';
126
+ import { redact, seal, secretFieldPattern, sha256, timingSafeEqual, toBase64Url } from '@forgezero/access/security';
127
+ import { toHex, verifyHmac } from '@forgezero/access/security';
128
+ import type { Sealed } from '@forgezero/access/security';
129
+ ```
130
+
131
+ <a id="forgezero-access-rate-limit"></a>
132
+ ## @forgezero/access/rate-limit
133
+
134
+ Request counters over a window — in memory, in Redis, or in a Durable Object. Named value imports: durableObjectStore, memoryStore, redisStore, slidingWindowStore. Named type imports: DurableStorageLike, RedisLike. Import only the names used by this file.
135
+
136
+ ```text
137
+ import { durableObjectStore, memoryStore, redisStore, slidingWindowStore } from '@forgezero/access/rate-limit';
138
+ import type { DurableStorageLike, RedisLike } from '@forgezero/access/rate-limit';
139
+ ```
140
+
141
+ <a id="forgezero-access-fetch"></a>
142
+ ## @forgezero/access/fetch
143
+
144
+ A Fetch-native adapter over the declared access pipeline. Named value imports: compileRoute, matchRoute, toFetch. Named type imports: FetchHandler. Import only the names used by this file.
145
+
146
+ ```text
147
+ import { compileRoute, matchRoute, toFetch } from '@forgezero/access/fetch';
148
+ import type { FetchHandler } from '@forgezero/access/fetch';
149
+ ```
150
+
151
+ <a id="forgezero-access-pipeline"></a>
152
+ ## @forgezero/access/pipeline
153
+
154
+ The framework-neutral route, principal, factor, policy, rate-limit and effects pipeline. Named value imports: createPipeline, defineHandlers, windowSeconds. Named type imports: Handler, HandlerRegistry, Pipeline, PipelineOptions, RateStore, SessionResolver, StepUpStore, Telemetry, Validator. Import only the names used by this file.
155
+
156
+ ```text
157
+ import { createPipeline, defineHandlers, windowSeconds } from '@forgezero/access/pipeline';
158
+ import type { Handler, HandlerRegistry, Pipeline, PipelineOptions, RateStore, SessionResolver } from '@forgezero/access/pipeline';
159
+ import type { StepUpStore, Telemetry, Validator } from '@forgezero/access/pipeline';
160
+ ```
161
+
162
+ <a id="forgezero-access-elysia"></a>
163
+ ## @forgezero/access/elysia
164
+
165
+ Elysia integration over the same access pipeline and route declarations. Named value imports: elysia, forbiddenTelemetryAttribute, telemetryFrom, toElysiaPath. Named type imports: ElysiaAdapterOptions, OtelTracer. Import only the names used by this file.
166
+
167
+ ```text
168
+ import { elysia, forbiddenTelemetryAttribute, telemetryFrom, toElysiaPath } from '@forgezero/access/elysia';
169
+ import type { ElysiaAdapterOptions, OtelTracer } from '@forgezero/access/elysia';
170
+ ```
171
+
172
+ <a id="forgezero-access-client"></a>
173
+ ## @forgezero/access/client
174
+
175
+ Typed client helpers that fulfil factors without duplicating the security matrix. Named value imports: buildPath, createClient. Named type imports: ChallengeHandler, ClientOptions, ClientResult, Problem, RequestArgs, SecurityChallenge. Import only the names used by this file.
176
+
177
+ ```text
178
+ import { buildPath, createClient } from '@forgezero/access/client';
179
+ import type { ChallengeHandler, ClientOptions, ClientResult, Problem, RequestArgs, SecurityChallenge } from '@forgezero/access/client';
180
+ ```
181
+
182
+ <a id="forgezero-access-testing"></a>
183
+ ## @forgezero/access/testing
184
+
185
+ Deterministic access-pipeline fixtures and assertions for consumer tests. Named value imports: reachableRoutes, simulate, unreachableRoutes. Named type imports: SimulateArgs, Verdict. Import only the names used by this file.
186
+
187
+ ```text
188
+ import { reachableRoutes, simulate, unreachableRoutes } from '@forgezero/access/testing';
189
+ import type { SimulateArgs, Verdict } from '@forgezero/access/testing';
190
+ ```
191
+
192
+ <a id="forgezero-access-header"></a>
193
+ ## @forgezero/access/header
194
+
195
+ Strict configurable header-identity extraction with canonical names and bounded values. Named value imports: defineHeaderIdentitySources, headerIdentityResolver. Named type imports: HeaderAssignmentResolver, HeaderIdentity, HeaderIdentitySource, HeaderPrincipal. Import only the names used by this file.
196
+
197
+ ```text
198
+ import { defineHeaderIdentitySources, headerIdentityResolver } from '@forgezero/access/header';
199
+ import type { HeaderAssignmentResolver, HeaderIdentity, HeaderIdentitySource, HeaderPrincipal } from '@forgezero/access/header';
200
+ ```
201
+
202
+ <a id="forgezero-access-principal"></a>
203
+ ## @forgezero/access/principal
204
+
205
+ Generic principal-source resolution for browser, API-key, attestation or future identity adapters. Named value imports: assignmentIsActive, decidePrincipalAccess, defineRbacPrincipal, touchPrincipalAssignment. Named type imports: PrincipalAccessDecision, PrincipalAssignment, RbacPrincipal. Import only the names used by this file.
206
+
207
+ ```text
208
+ import { assignmentIsActive, decidePrincipalAccess, defineRbacPrincipal, touchPrincipalAssignment } from '@forgezero/access/principal';
209
+ import type { PrincipalAccessDecision, PrincipalAssignment, RbacPrincipal } from '@forgezero/access/principal';
210
+ ```
211
+
212
+ <a id="forgezero-access-principal-session"></a>
213
+ ## @forgezero/access/principal-session
214
+
215
+ Short-lived scope-bound delegated-principal sessions with sliding and absolute expiry. Named value imports: DEFAULT_PRINCIPAL_ABSOLUTE_TTL_MS, DEFAULT_PRINCIPAL_IDLE_TTL_MS, MAX_PRINCIPAL_ABSOLUTE_TTL_MS, MAX_PRINCIPAL_IDLE_TTL_MS, authenticatePrincipalSession, issuePrincipalSession, principalSessionIsActive, touchPrincipalSession. Named type imports: IssuedPrincipalSession, PrincipalSessionRecord. Import only the names used by this file.
216
+
217
+ ```text
218
+ import { DEFAULT_PRINCIPAL_ABSOLUTE_TTL_MS, DEFAULT_PRINCIPAL_IDLE_TTL_MS, MAX_PRINCIPAL_ABSOLUTE_TTL_MS, MAX_PRINCIPAL_IDLE_TTL_MS, authenticatePrincipalSession, issuePrincipalSession } from '@forgezero/access/principal-session';
219
+ import { principalSessionIsActive, touchPrincipalSession } from '@forgezero/access/principal-session';
220
+ import type { IssuedPrincipalSession, PrincipalSessionRecord } from '@forgezero/access/principal-session';
221
+ ```
25
222
 
26
- // A ROLE IS A SET OF ROUTE KEYS. There is no second permission vocabulary to
27
- // keep in sync, and a role naming a route that no longer exists is a type error.
28
- const FINANCE = ['api/invoices', 'api/invoices/refund'] as const;
29
-
30
- authorise(ACCESS, 'api/invoices/refund', session); // → allowed | Refusal
31
- ```
32
-
33
- ## What it gives you that a middleware does not
34
-
35
- **Two layers, and the second never trusts the first.** A session factor is proved
36
- once and persists — it answers *who is this*. An action factor is proved per call
37
- and never persists — it answers *is this a human, now, for this record*. A
38
- five-minute "recently verified" timestamp looks equivalent and is not: a
39
- timestamp **is** a persisted factor, so a left-open laptop replays the privileged
40
- action. `fulfilledActionFactors()` returns `[]` always, by design.
41
-
42
- **A refusal that says what happened.** `401` no session · `403` role lacks the
43
- route · `404` route exists but not in this stage · `409` a condition refused ·
44
- `423` locked, a human must act · `428` a factor is missing, and the headers name
45
- which. Every one is distinct because "403" for all of them is how a support
46
- queue fills up.
47
-
48
- **Twelve guards already written.** `requireBalance`, `requireApproval`,
49
- `requireQuota`, `requireFreshness` and the rest the conditions every project
50
- writes by hand, each already carrying the right status code.
51
-
52
- **Testable with no server.** `@forgezero/access/testing` builds sessions and
53
- asserts the decision directly, so the truth table is a unit test rather than an
54
- integration suite.
55
-
56
- ## Subpaths
57
-
58
- | import | what it is |
59
- |---|---|
60
- | `@forgezero/access` | the matrix, roles, `authorise`, `Refusal` |
61
- | `/conditions` | the twelve guards, each with its own status |
62
- | `/effects` | audit, emit, meter, invalidate, notify — after the decision |
63
- | `/security` | constant-time compare, CSPRNG tokens, HMAC, HKDF, AES-GCM sealing |
64
- | `/rate-limit` | counters over a window — memory, Redis, or a Durable Object |
65
- | `/elysia` · `/fetch` | adapters |
66
- | `/client` | the browser half, including the 428 replay |
67
- | `/testing` | decide without a server |
68
- | `/pipeline` · `/authenticator` | the resolver, and WebAuthn |
69
- | `/header` | verified header identities with fresh, host-owned RBAC assignments |
70
- | `/principal` | generic multi-assignment principals, route groups, methods and expiry |
71
- | `/principal-session` | short-lived server sessions bound to an opaque client identity |
72
-
73
- Header identities are a separate principal, not a browser session. A source
74
- verifier authenticates one configured header and returns only a stable subject;
75
- the host resolves that subject's role assignments on every request. Roles are
76
- never accepted from the header value, and a header principal cannot satisfy a
77
- session or fresh-action factor. Multiple source adapters can coexist, but a
78
- request presenting more than one source is refused as ambiguous.
79
-
80
- `accessGroup` is the single open, host-defined route classification used by
81
- generic principal assignments—`public`, `user`, `admin`, `custody`,
82
- `orchestration`, or any future product vocabulary. Session policies remain the
83
- generic package's authentication boundary; ForgeZero additionally requires its
84
- `public` group to use anonymous authentication and rejects contradictions at
85
- boot. The package does not hard-code a purpose or identity type.
86
-
87
- ```ts
88
- import { headerIdentityResolver } from '@forgezero/access/header';
89
- import { decidePrincipalAccess } from '@forgezero/access/principal';
90
-
91
- const resolveHeader = headerIdentityResolver(
92
- [{
93
- key: 'partner-sso',
94
- header: 'x-partner-identity',
95
- verify: ({ value, request }) => verifyPartnerAssertion(value, request)
96
- }],
97
- // Read the current admin/custodian assignment. Do not cache it in the token.
98
- ({ principalKey }) => memberships.assignments(principalKey)
99
- );
100
-
101
- const principal = await resolveHeader(request);
102
- const decision = decidePrincipalAccess({
103
- access, principal, roles: await policy.roles(), routeKey: 'api/orders/write', method: 'POST'
223
+ <a id="forgezero-access-authenticator"></a>
224
+ ## @forgezero/access/authenticator
225
+
226
+ Authentication-source contracts for adding identity mechanisms without changing route policy. Named value imports: createAuthenticator, encoding. Named type imports: AuthenticationOptions, AuthenticationResponse, Authenticator, AuthenticatorOptions, Credential, RegistrationOptions, RegistrationResponse. Import only the names used by this file.
227
+
228
+ ```text
229
+ import { createAuthenticator, encoding } from '@forgezero/access/authenticator';
230
+ import type { AuthenticationOptions, AuthenticationResponse, Authenticator, AuthenticatorOptions, Credential, RegistrationOptions } from '@forgezero/access/authenticator';
231
+ import type { RegistrationResponse } from '@forgezero/access/authenticator';
232
+ ```
233
+
234
+ <a id="forgezero-access-ceremony-modes"></a>
235
+ ## @forgezero/access/ceremony-modes
236
+
237
+ Named security-ceremony modes and their session/action fulfilment semantics. Named value imports: MAX_CUSTODIANS, THRESHOLD_MODES, thresholdMode. Named type imports: ThresholdMode, ThresholdModeId. Import only the names used by this file.
238
+
239
+ ```text
240
+ import { MAX_CUSTODIANS, THRESHOLD_MODES, thresholdMode } from '@forgezero/access/ceremony-modes';
241
+ import type { ThresholdMode, ThresholdModeId } from '@forgezero/access/ceremony-modes';
242
+ ```
243
+
244
+ ## 1. Install
245
+
246
+ Zero runtime dependencies. The core is fetch types plus plain JSON Schema, so it runs on Bun, Node 18+, Cloudflare Workers, Deno and every edge runtime.
247
+
248
+ ```text
249
+ bun add @forgezero/access
250
+ ```
251
+
252
+ ## 2. Declare routes and who may reach them
253
+
254
+ Routes carry their contract — label, method, and the shapes they accept and return. WHO may reach them is a separate list, because the two change for different reasons and on different schedules.
255
+
256
+ ```text
257
+ import { defineRoutes, defineAccessControl, page, action } from '@forgezero/access';
258
+
259
+ export const ROUTES = defineRoutes({
260
+ orders: page('Orders'),
261
+ 'api/orders': action('List', 'GET', { page: 'orders' }),
262
+ 'api/orders/[id]/refund': action('Refund', 'POST', { page: 'orders' })
104
263
  });
105
- if (!decision.allow) {
106
- return new Response('Forbidden', { status: 403 });
264
+
265
+ export const ACCESS = defineAccessControl({
266
+ factors: FACTORS,
267
+ routes: ROUTES,
268
+ sessionPolicies: {
269
+ member: { factors: ['passkey'], routes: ['orders', 'api/orders'] },
270
+ admin: { factors: ['passkey'], routes: ['api/orders/[id]/refund'] }
271
+ }
272
+ });
273
+ ```
274
+
275
+ ## 3. Mount it
276
+
277
+ One line per runtime. The pipeline is written once and shared, so an adapter never re-decides anything.
278
+
279
+ ```text
280
+ // anywhere fetch exists — Workers, Deno, Node, Bun
281
+ import { toFetch } from '@forgezero/access/fetch';
282
+ export default { fetch: toFetch({ access: ACCESS, handlers: HANDLERS }) };
283
+
284
+ // Elysia
285
+ import { elysia } from '@forgezero/access/elysia';
286
+ app.use(elysia({ access: ACCESS, handlers: HANDLERS, Elysia }));
287
+ ```
288
+
289
+ ## Every route needs a session policy, or the build fails
290
+
291
+ Exactly one policy must cover each route. A route nobody classified is a route whose security nobody decided — and adding a route is precisely when that happens. This is the rule that catches omission rather than typos, and it is why forgetting is not possible rather than merely discouraged.
292
+
293
+ ```text
294
+ SESSION_INCOMPLETE: No session policy covers: api/orders/export.
295
+ Every route needs exactly one.
296
+ ```
297
+
298
+ ## Fresh proof for dangerous actions
299
+
300
+ actionFactorsRequired is a COUNT: 1 is any-one, the list length is all-of, and anything between is M-of-N with no special case. The proof binds to the record your before-handler loaded, so a key minted to refund order A cannot refund order B.
301
+
302
+ ```text
303
+ actionPolicies: {
304
+ sensitive: {
305
+ factors: ['passkey', 'telegram', 'totp'],
306
+ required: 2, // any 2 of the 3
307
+ target: 'orders',
308
+ routes: ['api/orders/[id]/refund']
309
+ }
310
+ }
311
+ ```
312
+
313
+ ## A session factor NEVER satisfies an action factor
314
+
315
+ fulfilledActionFactors() returns an empty array, always. A five-minute verified-at timestamp looks equivalent and is not: a timestamp IS a persisted factor, so a left-open laptop or a stolen cookie replays the privileged action. Returning nothing makes that impossible by construction rather than by policy.
316
+
317
+ ## Disabling a factor tells you what it breaks, first
318
+
319
+ The effective pool is the route factors intersected with the factors you have enabled. If that falls below the required count the route becomes UNAVAILABLE — never quietly weakened to whatever remains. Ask before saving rather than discovering it during an incident.
320
+
321
+ ```text
322
+ impactOfDisabling(ACCESS, ['passkey'])
323
+ // [{ route: 'api/orders/[id]/refund', available: 1, required: 2 }]
324
+ ```
325
+
326
+ ## Test it without a server
327
+
328
+ simulate() reports which policy decided, which a browser 403 never tells you. reachableRoutes() answers what a role can actually do — worth running, because stem inheritance grants more than a grant list reads like.
329
+
330
+ ```text
331
+ import { simulate, reachableRoutes } from '@forgezero/access/testing';
332
+
333
+ simulate(ACCESS, { route: 'api/settings', roles, as: 'member' });
334
+ // { allowed: false, status: 403, reason: 'ACCESS_DENIED', sessionPolicy: 'admin' }
335
+
336
+ reachableRoutes(ACCESS, roles, ['member']);
337
+ // holding 'orders' also grants api/orders/[id]/refund — stems inherit
338
+ ```
339
+
340
+ ## Conditions: the guards, already written
341
+
342
+ Every project writes the same dozen checks into its before-handlers. These are those checks, each declaring the status it refuses with. requireOwner answers 404 rather than 403 on purpose — a 403 confirms the record exists, which turns sequential identifiers into an enumeration oracle.
343
+
344
+ ```text
345
+ import { loadTarget, requireOwner, requireState, requireBalance }
346
+ from '@forgezero/access/conditions';
347
+
348
+ beforeHandlers: {
349
+ load: loadTarget({ routes: ['api/orders/[id]/refund'], load: findOrder }),
350
+ mine: requireOwner({ routes: ['api/orders/[id]/refund'], owner: o => o.userKey }),
351
+ payable: requireState({ routes: ['api/orders/[id]/refund'],
352
+ status: o => o.status, allowed: ['paid'] })
107
353
  }
108
354
  ```
109
355
 
110
- Full documentation: **https://www.forgezero.net/docs/access**
356
+ ## A refusal keeps its own status
357
+
358
+ A condition throws a Refusal carrying the status the client deserves, so "already refunded" is a 409 the UI can explain rather than a 500 that tells the client to retry. An idempotent replay throws Settled instead and returns the original answer — because a retrying client needs to learn the transfer succeeded, which no error code can tell it.
111
359
 
112
- ## Licence
360
+ ```text
361
+ throw new Refusal(409, 'STATE_INVALID', 'Already refunded.', { status: 'refunded' });
362
+
363
+ // idempotent replay — the ORIGINAL result, not an error
364
+ throw new Settled({ ok: true, id: 'ref_1' }, 201);
365
+ ```
366
+
367
+ ## Undeclared refusals fail the build
368
+
369
+ Each condition knows which statuses it can produce, so the set a route can answer is derivable. Add a quota check to a route whose contract never mentions 409 and the build stops — rather than a client rendering "an unexpected error" for the one refusal a user could have acted on.
370
+
371
+ ```text
372
+ assertDeclaredRefusals({ routes: ROUTES, conditions: CONDITIONS });
373
+ // Undeclared refusals:
374
+ // api/wallet/withdraw can 409 (requireQuota) but does not declare it
375
+ ```
376
+
377
+ ## Effects: what happens once it is decided
378
+
379
+ Audit, emit, meter, invalidate and notify. None can fail the request — a dead audit sink must not turn a completed transfer into a 500. Audit records denials as well as successes, because a run of 403s from one session is the signal an incident is reconstructed from. Every payload is redacted first.
380
+
381
+ ```text
382
+ import { audit, emit, meter } from '@forgezero/access/effects';
383
+
384
+ afterHandlers: {
385
+ trail: audit({ routes: [...], sink }),
386
+ event: emit({ routes: [...], outbox, type: 'order.refunded',
387
+ payload: (ctx, result) => ({ id: result.id }) }),
388
+ usage: meter({ routes: [...], meter, unit: 'request' }) // successes only
389
+ }
390
+ ```
391
+
392
+ ## Response codes, and what each means
393
+
394
+ A 428 is not a rejection: it names the missing proof and the same request succeeds on replay. A 404 for a route outside its stage is deliberate — a 403 would confirm the route exists.
395
+
396
+ ```text
397
+ 401 no session
398
+ 403 session is fine, the role lacks this route
399
+ 404 route exists but not in this stage, realm or feature
400
+ 409 a condition refused — state, balance, quota or approval
401
+ 412 the record changed since you read it
402
+ 422 the request did not match what the route accepts
403
+ 423 locked — a human must act, unlike 503
404
+ 428 a factor is missing — headers name which
405
+ 429 rate limited
406
+ ```
113
407
 
114
- MIT. Part of [ForgeZero](https://www.forgezero.net) — secrets, attested compute and
115
- deploys — and usable entirely on its own, with no ForgeZero account.
408
+ Full rendered documentation: https://www.forgezero.net/docs/access
@@ -26,46 +26,7 @@ export interface ThresholdMode {
26
26
  * cannot read it uniformly across the set. */
27
27
  recommended: boolean;
28
28
  }
29
- export declare const THRESHOLD_MODES: readonly [{
30
- readonly id: "1-of-2";
31
- readonly threshold: 1;
32
- readonly total: 2;
33
- readonly label: "1 of 2";
34
- readonly description: "Either custodian can unlock alone. Survives losing one person, but a single compromised custodian is enough to open the vault.";
35
- readonly replicated: true;
36
- readonly recommended: false;
37
- }, {
38
- readonly id: "1-of-3";
39
- readonly threshold: 1;
40
- readonly total: 3;
41
- readonly label: "1 of 3";
42
- readonly description: "Any custodian can unlock alone. Maximum availability, minimum protection against an insider.";
43
- readonly replicated: true;
44
- readonly recommended: false;
45
- }, {
46
- readonly id: "2-of-3";
47
- readonly threshold: 2;
48
- readonly total: 3;
49
- readonly label: "2 of 3";
50
- readonly description: "Two of three must convene. Survives losing one custodian, and no single person can unlock. The smallest genuinely split arrangement.";
51
- readonly replicated: false;
52
- readonly recommended: true;
53
- }, {
54
- readonly id: "3-of-5";
55
- readonly threshold: 3;
56
- readonly total: 5;
57
- readonly label: "3 of 5";
58
- readonly description: "Three of five must convene. Survives losing two custodians.";
59
- readonly replicated: false;
60
- readonly recommended: false;
61
- }, {
62
- readonly id: "4-of-7";
63
- readonly threshold: 4;
64
- readonly total: 7;
65
- readonly label: "4 of 7";
66
- readonly description: "Four of seven must convene. For larger governance groups.";
67
- readonly replicated: false;
68
- readonly recommended: false;
69
- }];
70
- export type ThresholdModeId = (typeof THRESHOLD_MODES)[number]['id'];
29
+ export declare const MAX_CUSTODIANS = 32;
30
+ export declare const THRESHOLD_MODES: readonly ThresholdMode[];
31
+ export type ThresholdModeId = `${number}-of-${number}`;
71
32
  export declare function thresholdMode(id: string): ThresholdMode | undefined;
@@ -1,5 +1,28 @@
1
1
  // src/ceremony-modes.ts
2
+ var MAX_CUSTODIANS = 32;
3
+ var majorityPreset = (threshold) => {
4
+ const total = threshold * 2 - 1;
5
+ return {
6
+ id: `${threshold}-of-${total}`,
7
+ threshold,
8
+ total,
9
+ label: `${threshold} of ${total}`,
10
+ description: `${threshold} of ${total} custodians must convene. Survives losing ${total - threshold} custodians.`,
11
+ replicated: false,
12
+ recommended: threshold === 2
13
+ };
14
+ };
15
+ var MAJORITY_PRESETS = Array.from({ length: 15 }, (_, index) => majorityPreset(index + 2));
2
16
  var THRESHOLD_MODES = [
17
+ {
18
+ id: "1-of-1",
19
+ threshold: 1,
20
+ total: 1,
21
+ label: "1 of 1",
22
+ description: "Bootstrap only: the first platform custodian brings custody online alone, then rotates to the long-term quorum.",
23
+ replicated: true,
24
+ recommended: false
25
+ },
3
26
  {
4
27
  id: "1-of-2",
5
28
  threshold: 1,
@@ -18,38 +41,31 @@ var THRESHOLD_MODES = [
18
41
  replicated: true,
19
42
  recommended: false
20
43
  },
21
- {
22
- id: "2-of-3",
23
- threshold: 2,
24
- total: 3,
25
- label: "2 of 3",
26
- description: "Two of three must convene. Survives losing one custodian, and no single person can unlock. The smallest genuinely split arrangement.",
27
- replicated: false,
28
- recommended: true
29
- },
30
- {
31
- id: "3-of-5",
32
- threshold: 3,
33
- total: 5,
34
- label: "3 of 5",
35
- description: "Three of five must convene. Survives losing two custodians.",
36
- replicated: false,
37
- recommended: false
38
- },
39
- {
40
- id: "4-of-7",
41
- threshold: 4,
42
- total: 7,
43
- label: "4 of 7",
44
- description: "Four of seven must convene. For larger governance groups.",
45
- replicated: false,
46
- recommended: false
47
- }
44
+ ...MAJORITY_PRESETS
48
45
  ];
49
46
  function thresholdMode(id) {
50
- return THRESHOLD_MODES.find((mode) => mode.id === id);
47
+ const preset = THRESHOLD_MODES.find((mode) => mode.id === id);
48
+ if (preset)
49
+ return preset;
50
+ const match = /^(\d{1,2})-of-(\d{1,2})$/.exec(id);
51
+ if (!match)
52
+ return;
53
+ const threshold = Number(match[1]);
54
+ const total = Number(match[2]);
55
+ if (!Number.isSafeInteger(threshold) || !Number.isSafeInteger(total) || threshold < 1 || total < 1 || threshold > total || total > MAX_CUSTODIANS)
56
+ return;
57
+ return {
58
+ id: `${threshold}-of-${total}`,
59
+ threshold,
60
+ total,
61
+ label: `${threshold} of ${total}`,
62
+ description: threshold === 1 ? `Any one of ${total} custodians can unlock alone.` : `${threshold} of ${total} custodians must convene.`,
63
+ replicated: threshold === 1,
64
+ recommended: false
65
+ };
51
66
  }
52
67
  export {
53
68
  thresholdMode,
54
- THRESHOLD_MODES
69
+ THRESHOLD_MODES,
70
+ MAX_CUSTODIANS
55
71
  };
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/conditions.ts
281
281
  function define(condition, routes, refusals, run) {
package/dist/effects.js CHANGED
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/security.ts
281
281
  var HEX = Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0"));
package/dist/elysia.js CHANGED
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/pipeline.ts
281
281
  function defineHandlers(routes, handlers) {
package/dist/fetch.js CHANGED
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/pipeline.ts
281
281
  function defineHandlers(routes, handlers) {
package/dist/header.js CHANGED
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/principal.ts
281
281
  var ATOM = /^[A-Za-z0-9][A-Za-z0-9_.:@/-]{0,255}$/;
package/dist/index.d.ts CHANGED
@@ -379,4 +379,4 @@ export declare function impactOfDisabling<R extends RouteRegistry>(access: Acces
379
379
  available: number;
380
380
  required: number;
381
381
  }[];
382
- export declare const VERSION = "0.1.0";
382
+ export declare const VERSION = "0.1.4";
package/dist/index.js CHANGED
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
  export {
280
280
  stemOf,
281
281
  resolveActionFactors,
package/dist/pipeline.js CHANGED
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/pipeline.ts
281
281
  function defineHandlers(routes, handlers) {
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/security.ts
281
281
  var HEX = Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0"));
package/dist/principal.js CHANGED
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/principal.ts
281
281
  var ATOM = /^[A-Za-z0-9][A-Za-z0-9_.:@/-]{0,255}$/;
package/dist/testing.js CHANGED
@@ -275,7 +275,7 @@ function impactOfDisabling(access, enabledAfter) {
275
275
  }
276
276
  return broken;
277
277
  }
278
- var VERSION = "0.1.0";
278
+ var VERSION = "0.1.4";
279
279
 
280
280
  // src/testing.ts
281
281
  function nameOf(policies, route) {
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@forgezero/access",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public",
7
- "provenance": true
7
+ "provenance": false
8
8
  },
9
9
  "exports": {
10
10
  ".": {
@@ -68,17 +68,16 @@
68
68
  "default": "./dist/ceremony-modes.js"
69
69
  }
70
70
  },
71
- "scripts": {
72
- "check": "tsc --noEmit",
73
- "prebuild": "rm -rf dist",
74
- "build": "bun build src/index.ts src/fetch.ts src/pipeline.ts src/elysia.ts src/client.ts src/testing.ts src/rate-limit.ts src/security.ts src/header.ts src/principal.ts src/principal-session.ts src/conditions.ts src/effects.ts src/authenticator.ts src/ceremony-modes.ts --root src --outdir dist --target browser --format esm --packages external && tsc --emitDeclarationOnly --declaration --noEmit false --outDir dist",
75
- "prepublishOnly": "bun run check && bun run build"
71
+ "scripts": {
72
+ "check": "tsc --noEmit",
73
+ "build": "bun ../tools/package-task.ts build access",
74
+ "prepublishOnly": "bun ../tools/package-task.ts prepublish access"
76
75
  },
77
76
  "devDependencies": {
78
77
  "typescript": "^5.6.0",
79
78
  "@types/bun": "latest"
80
79
  },
81
- "description": "Route matrix, RBAC and security factors. Zero runtime dependencies \u2014 runs anywhere fetch does.",
80
+ "description": "Route matrix, RBAC and security factors. Zero runtime dependencies runs anywhere fetch does.",
82
81
  "keywords": [
83
82
  "rbac",
84
83
  "authorization",