@kindgi/authz 0.0.0-bootstrap.0 → 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kindgi Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # @kindgi/authz
1
+ # `@kindgi/authz`
2
2
 
3
- A placeholder. Releases come from https://github.com/kindgi/kindgi-sdk.
3
+ Public authorization shape for Kindgi™: the vocabulary and interfaces that callers, policy enforcement points (PEPs) and policy executors share. Object types, actions and relation names follow an OpenFGA-style model; the FGA store and the check implementation are supplied by the deployment. [`@kindgi/api`](../api/) uses these types in its middleware and bindings.
4
+
5
+ ## Purpose
6
+
7
+ Give every enforcement site one vocabulary — which object types exist, which actions apply to each, how an action maps to an FGA relation, who the caller is — so a check means the same thing in every layer. The package is types and pure functions only; it holds no runtime state.
8
+
9
+ ## Exports
10
+
11
+ - **Vocabulary** — `OBJECT_TYPES` / `ObjectType`, `ACTIONS` / `Action`, `ACTION_TO_RELATION` (e.g. `read` → `can_read`), `OBJECT_ACTIONS` (the actions meaningful per object type, so a PEP can reject `rotate` on an agent before calling FGA), `ResourceRef`, `resourceKey(ref)`, `ref(type, id)`.
12
+ - **Principals** — `Principal` (`actor`, optional `onBehalfOf`, optional `scope`), `PrincipalRef`, `PrincipalKind` (`user`, `agent`, `service_account`, `system`), `DownscopedPermissions` (`allowedActions` / `deniedActions`).
13
+ - `userPrincipal`, `systemPrincipal`, `serviceAccountPrincipal`, `delegate(actor, onBehalfOf, scope?)` (throws on cross-tenant delegation), `downscope(principal, scope)`.
14
+ - `fgaSubject(ref)` — the FGA subject string for a principal; `system` maps to `user:system`.
15
+ - **PEP helpers** — `principalFromToken(token)` (a `userId` gives a user principal, else a `tokenId` gives a service-account principal, else it throws), `TokenLike`, `denyPayload(action, type, id, reason)` / `DenyPayload` (the structured 403 body, `code: 'permission-denied'`).
16
+ - **Decisions** — `AuthzCheckBinding` with `check(principal, action, resource, ctx?)` and `checkBatch(...)`, `AuthzCheckContext` (`correlationId`, `runId`), and `Decision` (`allowed`, `reason`, `failing`, `evidence`). The effective permission is the intersection of actor, `onBehalfOf` and `scope`.
17
+ - **Tuples** — `TupleIntent` and `TupleEnqueueHook` (the hook every content and config binding calls inside its write transaction).
18
+ - `tuplesForCreate(entity, creatorUserId?)` / `tuplesForDelete(entity)` over `EntityRef`; `tuplesForDelete` removes only the parent / scope tuple.
19
+ - Subject and object helpers (`userSubject`, `teamMemberSubject`, `tenantObject` … `runObject`, `scopeSubject`) and the tuple-side `Scope`.
20
+ - Membership and grants: `teamMembershipTuple`, `projectMembershipTuple`, `teamProjectGrantTuple` (`TeamRole`, `ProjectRole`), `machineAccessTuple` for `agent` / `service_account` subjects (`MachineSubject`, `AgentAccessResource`), and its agent shorthand `agentAccessTuple`.
21
+ - **Reviewer roles** — `ReviewerRole` (`standard`, `senior`, `admin`) and `REVIEWER_ROLE_RANK`, where a higher rank covers the lower ones.
22
+
23
+ ## Example
24
+
25
+ ```ts
26
+ import {
27
+ type AuthzCheckBinding,
28
+ type TupleEnqueueHook,
29
+ denyPayload,
30
+ principalFromToken,
31
+ ref,
32
+ tuplesForCreate,
33
+ } from '@kindgi/authz';
34
+ import type { ProjectId, TenantId, UserId } from '@kindgi/types';
35
+
36
+ const tenantId = 'acme' as TenantId;
37
+ const creator = 'user-1' as UserId;
38
+ const principal = principalFromToken({ tenantId, userId: creator });
39
+
40
+ // A project binding calls this inside its write transaction with the new row id:
41
+ // a `parent` tuple (tenant:acme → project) plus an `owner` tuple for the creator.
42
+ const enqueueTuples: TupleEnqueueHook = (rowId) =>
43
+ tuplesForCreate({ kind: 'project', id: rowId as ProjectId, tenantId }, creator);
44
+
45
+ // At a PEP: ask the decision point, and turn a deny into the structured 403 body.
46
+ async function authorizeDelete(authz: AuthzCheckBinding, projectId: string) {
47
+ const decision = await authz.check(principal, 'delete', ref('project', projectId), {
48
+ correlationId: 'req-42',
49
+ });
50
+ return decision.allowed ? undefined : denyPayload('delete', 'project', projectId, decision.reason);
51
+ }
52
+ ```
53
+
54
+ ## Non-goals
55
+
56
+ - **The check implementation and the FGA store.** `AuthzCheckBinding` is an interface; the authorization model, the store and the worker that applies queued tuples are supplied by the deployment.
57
+ - **HTTP middleware.** `principalFromToken` and `denyPayload` are framework-neutral; the Hono middleware lives in `@kindgi/api`.
58
+ - **Cross-tenant delegation.** `delegate` throws when the actor and `onBehalfOf` belong to different tenants.
59
+
60
+ ## Related
61
+
62
+ - [`@kindgi/api`](../api/) — the middleware, `TokenResolution`, and the bindings that call `TupleEnqueueHook`.
63
+ - [`@kindgi/types`](../types/) — the branded ids used in `EntityRef` and `PrincipalRef`.
64
+
65
+ ## License
66
+
67
+ Apache License 2.0 — see [LICENSE](./LICENSE).
@@ -0,0 +1,68 @@
1
+ import type { Principal } from './principal.js';
2
+ import type { Action, ObjectType, ResourceRef } from './types.js';
3
+ export interface Decision {
4
+ readonly allowed: boolean;
5
+ readonly reason: string;
6
+ /**
7
+ * Which link in the (actor, onBehalfOf, scope) chain caused the deny.
8
+ * Undefined when `allowed = true`.
9
+ */
10
+ readonly failing?: 'actor' | 'onBehalfOf' | 'scope' | 'unbootstrapped' | 'invalid-action';
11
+ /**
12
+ * Structured evidence for audit + debugging.
13
+ */
14
+ readonly evidence: {
15
+ readonly action: Action;
16
+ readonly relation: string;
17
+ readonly resource: string;
18
+ readonly actorSubject: string;
19
+ readonly onBehalfOfSubject?: string;
20
+ readonly storeId?: string;
21
+ };
22
+ }
23
+ /**
24
+ * Convenience constructor for a `ResourceRef`. The type parameter
25
+ * checks `type` against `ObjectType` at the call site; the return type
26
+ * is plain `ResourceRef` (it does not narrow to the given type).
27
+ */
28
+ export declare function ref<T extends ObjectType>(type: T, id: string): ResourceRef;
29
+ /**
30
+ * Per-call correlation context for `AuthzCheckBinding` methods.
31
+ * Threaded so the emitted audit event carries the request-scoped
32
+ * ids that let operators trace a deny back to the HTTP request or
33
+ * run that produced it.
34
+ */
35
+ export interface AuthzCheckContext {
36
+ /**
37
+ * Optional correlation id — e.g. the API request id from route
38
+ * middleware, or a run-scoped id. Attached to emitted audit events.
39
+ */
40
+ readonly correlationId?: string;
41
+ /**
42
+ * Optional run id — attached to emitted audit events when the check
43
+ * happens inside a run. Distinct from `correlationId` because the
44
+ * run id survives across HTTP requests (streamed responses, replays).
45
+ */
46
+ readonly runId?: string;
47
+ }
48
+ /**
49
+ * Policy Decision Point binding. Every enforcement site that wants
50
+ * to check authz (for example the @kindgi/api middleware) goes
51
+ * through this contract. The deployment supplies the implementation.
52
+ */
53
+ export interface AuthzCheckBinding {
54
+ /**
55
+ * Applies the principal's downscope filter first (cheap, no FGA
56
+ * round-trip), then calls FGA check for the actor and (if
57
+ * delegated) the `onBehalfOf`. Returns a `Decision` — allowed
58
+ * iff every check passes.
59
+ */
60
+ check(principal: Principal, action: Action, resource: ResourceRef, ctx?: AuthzCheckContext): Promise<Decision>;
61
+ /**
62
+ * List-filtering primitive. Given a set of resources, returns
63
+ * `Decision`s in the same order — used by `filterByCan` at the
64
+ * API layer to strip rows a caller can't read.
65
+ */
66
+ checkBatch(principal: Principal, action: Action, resources: readonly ResourceRef[], ctx?: AuthzCheckContext): Promise<readonly Decision[]>;
67
+ }
68
+ //# sourceMappingURL=check.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check.d.ts","sourceRoot":"","sources":["../src/check.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAElE,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,YAAY,GAAG,OAAO,GAAG,gBAAgB,GAAG,gBAAgB,CAAC;IAC1F;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE;QACjB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;QAC9B,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;QACpC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;KAC3B,CAAC;CACH;AAED;;;;GAIG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,WAAW,CAE1E;AAED;;;;;GAKG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;;OAKG;IACH,KAAK,CACH,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,WAAW,EACrB,GAAG,CAAC,EAAE,iBAAiB,GACtB,OAAO,CAAC,QAAQ,CAAC,CAAC;IAErB;;;;OAIG;IACH,UAAU,CACR,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,SAAS,WAAW,EAAE,EACjC,GAAG,CAAC,EAAE,iBAAiB,GACtB,OAAO,CAAC,SAAS,QAAQ,EAAE,CAAC,CAAC;CACjC"}
package/dist/check.js ADDED
@@ -0,0 +1,11 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ /**
4
+ * Convenience constructor for a `ResourceRef`. The type parameter
5
+ * checks `type` against `ObjectType` at the call site; the return type
6
+ * is plain `ResourceRef` (it does not narrow to the given type).
7
+ */
8
+ export function ref(type, id) {
9
+ return { type, id };
10
+ }
11
+ //# sourceMappingURL=check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check.js","sourceRoot":"","sources":["../src/check.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAmCjC;;;;GAIG;AACH,MAAM,UAAU,GAAG,CAAuB,IAAO,EAAE,EAAU;IAC3D,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;AACtB,CAAC"}
@@ -0,0 +1,28 @@
1
+ export interface TupleIntent {
2
+ readonly operation: 'write' | 'delete';
3
+ /** FGA subject, e.g. `user:alice` or `team:eng#member`. */
4
+ readonly user: string;
5
+ /** FGA relation, e.g. `admin` | `parent` | `editor`. */
6
+ readonly relation: string;
7
+ /** FGA object, e.g. `project:foo`. */
8
+ readonly object: string;
9
+ /**
10
+ * Optional per-tenant idempotency key. If set, the outbox rejects a
11
+ * duplicate enqueue (same tenantId + dedupKey) — safe to retry the
12
+ * caller without producing double-tuples.
13
+ */
14
+ readonly dedupKey?: string;
15
+ }
16
+ /**
17
+ * Callback that produces the tuples for an entity mutation. Bindings
18
+ * call this INSIDE their write transaction with the freshly-inserted
19
+ * (or freshly-resolved, for deletes) entity row's primary key. The
20
+ * binding then enqueues the returned intents in the same transaction.
21
+ *
22
+ * REQUIRED on every content + config binding's write methods. An
23
+ * optional hook would silently split the contract into "writes tuples"
24
+ * vs. "doesn't write tuples" impls — exactly the split-brain that makes
25
+ * PEP unreliable.
26
+ */
27
+ export type TupleEnqueueHook = (entityRowId: string) => readonly TupleIntent[];
28
+ //# sourceMappingURL=enqueue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enqueue.d.ts","sourceRoot":"","sources":["../src/enqueue.ts"],"names":[],"mappings":"AAcA,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,SAAS,EAAE,OAAO,GAAG,QAAQ,CAAC;IACvC,2DAA2D;IAC3D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,wDAAwD;IACxD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,sCAAsC;IACtC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;;;;;;GAUG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,WAAW,EAAE,MAAM,KAAK,SAAS,WAAW,EAAE,CAAC"}
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ export {};
4
+ //# sourceMappingURL=enqueue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enqueue.js","sourceRoot":"","sources":["../src/enqueue.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC"}
@@ -0,0 +1,8 @@
1
+ export * from './types.js';
2
+ export * from './principal.js';
3
+ export * from './pep.js';
4
+ export * from './tuples.js';
5
+ export * from './enqueue.js';
6
+ export * from './check.js';
7
+ export * from './reviewer.js';
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ export * from './types.js';
4
+ export * from './principal.js';
5
+ export * from './pep.js';
6
+ export * from './tuples.js';
7
+ export * from './enqueue.js';
8
+ export * from './check.js';
9
+ export * from './reviewer.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC"}
package/dist/pep.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import type { TenantId, UserId } from '@kindgi/types';
2
+ import type { Action, ObjectType } from '@kindgi/authz';
3
+ import { type Principal } from './principal.js';
4
+ /**
5
+ * Subset of `TokenResolution` (`@kindgi/api`) that principal construction
6
+ * actually needs. Any bearer/session middleware can adapt its shape
7
+ * to this before calling `principalFromToken`.
8
+ */
9
+ export interface TokenLike {
10
+ readonly tenantId: TenantId;
11
+ readonly userId?: UserId;
12
+ /**
13
+ * Stable id for a capability-only bearer (service account). When
14
+ * the token carries no `userId`, this becomes the actor id.
15
+ * Deployments typically hash the token or use a token-record uuid.
16
+ */
17
+ readonly tokenId?: string;
18
+ }
19
+ /**
20
+ * Map a resolved token to a Principal.
21
+ *
22
+ * Priority:
23
+ * 1. userId present → userPrincipal (human session)
24
+ * 2. tokenId present → serviceAccountPrincipal (integration key)
25
+ * 3. Neither → throw (unauthenticated shouldn't reach the PEP)
26
+ *
27
+ * Delegation chains (agent-on-behalf-of-user) are constructed by
28
+ * the caller after this returns — the token itself is always a
29
+ * single principal.
30
+ */
31
+ export declare function principalFromToken(token: TokenLike): Principal;
32
+ /**
33
+ * Canonical 403 body shape. Structured so clients can distinguish
34
+ * "you didn't have permission" from "your input was invalid" —
35
+ * different remediation flows. Avoids leaking full evidence (that
36
+ * belongs in the audit trail); reason is a human-readable summary
37
+ * safe to return.
38
+ */
39
+ export interface DenyPayload {
40
+ readonly code: 'permission-denied';
41
+ readonly action: Action;
42
+ readonly resource: string;
43
+ readonly reason: string;
44
+ }
45
+ export declare function denyPayload(action: Action, resourceType: ObjectType, resourceId: string, reason: string): DenyPayload;
46
+ //# sourceMappingURL=pep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pep.d.ts","sourceRoot":"","sources":["../src/pep.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAExD,OAAO,EAAE,KAAK,SAAS,EAA0C,MAAM,gBAAgB,CAAC;AAExF;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS,CAU9D;AAED;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAC;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,WAAW,CACzB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,UAAU,EACxB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GACb,WAAW,CAOb"}
package/dist/pep.js ADDED
@@ -0,0 +1,33 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ import { serviceAccountPrincipal, userPrincipal } from './principal.js';
4
+ /**
5
+ * Map a resolved token to a Principal.
6
+ *
7
+ * Priority:
8
+ * 1. userId present → userPrincipal (human session)
9
+ * 2. tokenId present → serviceAccountPrincipal (integration key)
10
+ * 3. Neither → throw (unauthenticated shouldn't reach the PEP)
11
+ *
12
+ * Delegation chains (agent-on-behalf-of-user) are constructed by
13
+ * the caller after this returns — the token itself is always a
14
+ * single principal.
15
+ */
16
+ export function principalFromToken(token) {
17
+ if (token.userId !== undefined) {
18
+ return userPrincipal(token.userId, token.tenantId);
19
+ }
20
+ if (token.tokenId !== undefined) {
21
+ return serviceAccountPrincipal(token.tokenId, token.tenantId);
22
+ }
23
+ throw new Error('principalFromToken: token has neither userId nor tokenId — bearer middleware should have rejected earlier');
24
+ }
25
+ export function denyPayload(action, resourceType, resourceId, reason) {
26
+ return {
27
+ code: 'permission-denied',
28
+ action,
29
+ resource: `${resourceType}:${resourceId}`,
30
+ reason,
31
+ };
32
+ }
33
+ //# sourceMappingURL=pep.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pep.js","sourceRoot":"","sources":["../src/pep.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAiBjC,OAAO,EAAkB,uBAAuB,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAkBxF;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAgB;IACjD,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAC/B,OAAO,aAAa,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IACrD,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QAChC,OAAO,uBAAuB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAChE,CAAC;IACD,MAAM,IAAI,KAAK,CACb,2GAA2G,CAC5G,CAAC;AACJ,CAAC;AAgBD,MAAM,UAAU,WAAW,CACzB,MAAc,EACd,YAAwB,EACxB,UAAkB,EAClB,MAAc;IAEd,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,MAAM;QACN,QAAQ,EAAE,GAAG,YAAY,IAAI,UAAU,EAAE;QACzC,MAAM;KACP,CAAC;AACJ,CAAC"}
@@ -0,0 +1,60 @@
1
+ import type { TenantId } from '@kindgi/types';
2
+ import type { Action } from '@kindgi/authz';
3
+ export type PrincipalKind = 'user' | 'agent' | 'service_account' | 'system';
4
+ export interface PrincipalRef {
5
+ readonly kind: PrincipalKind;
6
+ readonly id: string;
7
+ readonly tenantId: TenantId;
8
+ }
9
+ export interface DownscopedPermissions {
10
+ /**
11
+ * Whitelist. When set, only these actions are allowed regardless
12
+ * of what FGA says. Matches OAuth 2.0 scope-narrowing.
13
+ */
14
+ readonly allowedActions?: readonly Action[];
15
+ /**
16
+ * Blacklist. When set, these actions are denied even if FGA allows.
17
+ * Applied AFTER allowedActions.
18
+ */
19
+ readonly deniedActions?: readonly Action[];
20
+ }
21
+ export interface Principal {
22
+ readonly actor: PrincipalRef;
23
+ readonly onBehalfOf?: PrincipalRef;
24
+ readonly scope?: DownscopedPermissions;
25
+ }
26
+ export declare function userPrincipal(userId: string, tenantId: TenantId): Principal;
27
+ export declare function systemPrincipal(tenantId: TenantId): Principal;
28
+ /**
29
+ * Build a principal from a service-account token. `id` is typically
30
+ * the token id (or a stable identifier derived from it) so grants can
31
+ * be attached to a specific integration.
32
+ */
33
+ export declare function serviceAccountPrincipal(serviceAccountId: string, tenantId: TenantId): Principal;
34
+ /**
35
+ * Build a delegated principal: `actor` acting on behalf of `onBehalfOf`.
36
+ * Both must be in the same tenant (checked at construction; mismatches
37
+ * are configuration bugs, not runtime authz denials).
38
+ */
39
+ export declare function delegate(actor: PrincipalRef, onBehalfOf: PrincipalRef, scope?: DownscopedPermissions): Principal;
40
+ /**
41
+ * Narrow an existing principal's permissions further. Composable with
42
+ * delegation — an agent-on-behalf-of-user can be additionally scoped
43
+ * to read-only for a specific request.
44
+ */
45
+ export declare function downscope(principal: Principal, scope: DownscopedPermissions): Principal;
46
+ /**
47
+ * Return the FGA subject string for a PrincipalRef. This is the ONE
48
+ * place that decides how principal kinds map to FGA subjects.
49
+ *
50
+ * - `user` → `user:${id}` (real user UUID)
51
+ * - `agent` → `agent:${id}`
52
+ * - `service_account` → `service_account:${id}` (machine identity
53
+ * with narrow grants)
54
+ * - `system` → `user:system` (service identity the tenant's
55
+ * setup grants tenant admin; with one FGA store
56
+ * per tenant the string never crosses tenant
57
+ * boundaries)
58
+ */
59
+ export declare function fgaSubject(ref: PrincipalRef): string;
60
+ //# sourceMappingURL=principal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principal.d.ts","sourceRoot":"","sources":["../src/principal.ts"],"names":[],"mappings":"AAyCA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAM5C,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,OAAO,GAAG,iBAAiB,GAAG,QAAQ,CAAC;AAE5E,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAC7B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;CAC7B;AAED,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5C;AAED,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,YAAY,CAAC;IACnC,QAAQ,CAAC,KAAK,CAAC,EAAE,qBAAqB,CAAC;CACxC;AAMD,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAE3E;AAED,wBAAgB,eAAe,CAAC,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAE7D;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,gBAAgB,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAE/F;AAED;;;;GAIG;AACH,wBAAgB,QAAQ,CACtB,KAAK,EAAE,YAAY,EACnB,UAAU,EAAE,YAAY,EACxB,KAAK,CAAC,EAAE,qBAAqB,GAC5B,SAAS,CAWX;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,qBAAqB,GAAG,SAAS,CAEvF;AAMD;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAWpD"}