@devfellowship/access 0.0.0-stage → 0.2.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.
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Rule bindings: which capability runs which rule, with which inputs, where (S2-T6).
3
+ *
4
+ * A binding is the second level of a write (parent plan "Two levels on a write"): after the
5
+ * grant, the command evaluates the bound rule with `evaluateRule`. The rule file is a copy of
6
+ * dfl-flows-definitions at the pinned commit (src/rules.generated.ts), so the command, the
7
+ * gateway (S3) and IAM "Try it" (S4-T6B, `POST /v1/access/explain` with a rule input) run the
8
+ * same table at the same version, in their own process, without the engine on the hot path.
9
+ *
10
+ * The pilot binding (parent ADR-13, Q5 = A): `work.task.create` runs `task_create_points`.
11
+ * - input `role`: from the VERIFIED context only (`verifiedRoleOf`), never from the body;
12
+ * - input `points`: from the request body, a number;
13
+ * - scope: the Smoke Lab business unit only (Tainan, Q5 note: "a ideia aqui é apenas provar
14
+ * o ponto. essa rule nao será usada"). Outside the scope the binding does not apply.
15
+ *
16
+ * Pure: no I/O.
17
+ */
18
+ import type { InputSource, RuleRef } from "./rule.js";
19
+ /** The rule key of the pilot (dfl-flows-definitions `policies/manifest.json`). */
20
+ export declare const TASK_CREATE_POINTS = "task_create_points";
21
+ /**
22
+ * The Smoke Lab business unit of the work domain (`public.business_units`, the table that
23
+ * `work.projects.business_unit_id` points at; tags smoke-lab, test, do-not-use). A test unit:
24
+ * real work never goes in it. Its strategy twin is `strategy.business_units`
25
+ * d32d7385-ae90-4e50-98f4-ac7f8cccb4bf (the CLAUDE_SMOKE fixture).
26
+ */
27
+ export declare const SMOKE_LAB_WORK_BUSINESS_UNIT_ID = "4835b42f-f9c2-451c-bce7-502cce7dac49";
28
+ /** The role that the rule input `role` takes: from the verified caller, never from the body. */
29
+ export type VerifiedRole = "admin" | "member";
30
+ /** `admin` when the caller is a global admin (IAM level >= 80, `iam.is_global_admin()`), else `member`. */
31
+ export declare function verifiedRoleOf(isGlobalAdmin: boolean): VerifiedRole;
32
+ export interface RuleBinding {
33
+ /** The capability of the catalog, for example `work.task.create`. */
34
+ capability: string;
35
+ /** The manifest key of the rule. */
36
+ rule_key: string;
37
+ /** One source per input of the decision table (RuleRef.inputs). */
38
+ inputs: Readonly<Record<string, InputSource>>;
39
+ /**
40
+ * Where the binding applies. `business_unit_ids`: only a target in one of these business
41
+ * units. null: everywhere.
42
+ */
43
+ scope: {
44
+ business_unit_ids: readonly string[];
45
+ } | null;
46
+ /** The role that approves an `ask` when the rule output names none. */
47
+ default_approver_role: string;
48
+ }
49
+ export declare const RULE_BINDINGS: Readonly<Record<string, RuleBinding>>;
50
+ /** The binding of a capability, or null when the capability has no rule. */
51
+ export declare function ruleBindingOf(capability: string): RuleBinding | null;
52
+ /** Does the binding apply to this target? A scoped binding needs a business unit in its list. */
53
+ export declare function bindingApplies(binding: RuleBinding, target: {
54
+ business_unit_id?: string | null;
55
+ }): boolean;
56
+ /**
57
+ * The RuleRef of a capability (the vendored table plus the binding inputs), or null when the
58
+ * capability has no binding. Throws when a binding names a rule that is not vendored: a build
59
+ * error, never a silent allow.
60
+ */
61
+ export declare function ruleRefOf(capability: string): RuleRef | null;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Rule bindings: which capability runs which rule, with which inputs, where (S2-T6).
3
+ *
4
+ * A binding is the second level of a write (parent plan "Two levels on a write"): after the
5
+ * grant, the command evaluates the bound rule with `evaluateRule`. The rule file is a copy of
6
+ * dfl-flows-definitions at the pinned commit (src/rules.generated.ts), so the command, the
7
+ * gateway (S3) and IAM "Try it" (S4-T6B, `POST /v1/access/explain` with a rule input) run the
8
+ * same table at the same version, in their own process, without the engine on the hot path.
9
+ *
10
+ * The pilot binding (parent ADR-13, Q5 = A): `work.task.create` runs `task_create_points`.
11
+ * - input `role`: from the VERIFIED context only (`verifiedRoleOf`), never from the body;
12
+ * - input `points`: from the request body, a number;
13
+ * - scope: the Smoke Lab business unit only (Tainan, Q5 note: "a ideia aqui é apenas provar
14
+ * o ponto. essa rule nao será usada"). Outside the scope the binding does not apply.
15
+ *
16
+ * Pure: no I/O.
17
+ */
18
+ import { VENDORED_RULES } from "./rules.generated.js";
19
+ /** The rule key of the pilot (dfl-flows-definitions `policies/manifest.json`). */
20
+ export const TASK_CREATE_POINTS = "task_create_points";
21
+ /**
22
+ * The Smoke Lab business unit of the work domain (`public.business_units`, the table that
23
+ * `work.projects.business_unit_id` points at; tags smoke-lab, test, do-not-use). A test unit:
24
+ * real work never goes in it. Its strategy twin is `strategy.business_units`
25
+ * d32d7385-ae90-4e50-98f4-ac7f8cccb4bf (the CLAUDE_SMOKE fixture).
26
+ */
27
+ export const SMOKE_LAB_WORK_BUSINESS_UNIT_ID = "4835b42f-f9c2-451c-bce7-502cce7dac49";
28
+ /** `admin` when the caller is a global admin (IAM level >= 80, `iam.is_global_admin()`), else `member`. */
29
+ export function verifiedRoleOf(isGlobalAdmin) {
30
+ return isGlobalAdmin ? "admin" : "member";
31
+ }
32
+ export const RULE_BINDINGS = Object.freeze({
33
+ "work.task.create": Object.freeze({
34
+ capability: "work.task.create",
35
+ rule_key: TASK_CREATE_POINTS,
36
+ inputs: Object.freeze({
37
+ role: Object.freeze({
38
+ from: "verified",
39
+ path: "role",
40
+ type: "string",
41
+ }),
42
+ points: Object.freeze({
43
+ from: "body",
44
+ path: "points",
45
+ type: "number",
46
+ }),
47
+ }),
48
+ scope: Object.freeze({
49
+ business_unit_ids: Object.freeze([SMOKE_LAB_WORK_BUSINESS_UNIT_ID]),
50
+ }),
51
+ default_approver_role: "admin",
52
+ }),
53
+ });
54
+ /** The binding of a capability, or null when the capability has no rule. */
55
+ export function ruleBindingOf(capability) {
56
+ return Object.hasOwn(RULE_BINDINGS, capability)
57
+ ? (RULE_BINDINGS[capability] ?? null)
58
+ : null;
59
+ }
60
+ /** Does the binding apply to this target? A scoped binding needs a business unit in its list. */
61
+ export function bindingApplies(binding, target) {
62
+ if (!binding.scope)
63
+ return true;
64
+ const bu = target.business_unit_id?.toLowerCase() ?? null;
65
+ return bu !== null && binding.scope.business_unit_ids.includes(bu);
66
+ }
67
+ /**
68
+ * The RuleRef of a capability (the vendored table plus the binding inputs), or null when the
69
+ * capability has no binding. Throws when a binding names a rule that is not vendored: a build
70
+ * error, never a silent allow.
71
+ */
72
+ export function ruleRefOf(capability) {
73
+ const binding = ruleBindingOf(capability);
74
+ if (!binding)
75
+ return null;
76
+ const rule = Object.hasOwn(VENDORED_RULES, binding.rule_key)
77
+ ? VENDORED_RULES[binding.rule_key]
78
+ : undefined;
79
+ if (!rule)
80
+ throw new Error(`binding ${capability} names rule '${binding.rule_key}', which is not vendored`);
81
+ return {
82
+ path: rule.path,
83
+ version: rule.version,
84
+ definition: rule.definition,
85
+ decision_id: rule.decision_id,
86
+ inputs: binding.inputs,
87
+ };
88
+ }
package/dist/can.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * can(): the one fleet access decision (parent plan
3
+ * 20261115-fleet-access-iam-gateway-flows-rules, ADR-5 and ADR-16).
4
+ *
5
+ * Rules:
6
+ * 1. Deny wins. Among the lines in force that match, deny beats ask and ask
7
+ * beats allow. No matching line: deny (default deny).
8
+ * 2. A line matches when its capability (exact or pattern) covers the
9
+ * request and its scope covers the target.
10
+ * 3. A revoked or expired line is ignored.
11
+ * 4. An agent never exceeds its owner:
12
+ * effective(agent) = (agent role bundles ∪ agent lines) ∩ effective(owner).
13
+ * Deny wins at each layer; an ask on either side gives ask.
14
+ *
15
+ * Pure: no I/O, no clock read, no input mutation.
16
+ */
17
+ import type { CanInput, Decision, PermissionLine, Principal } from "./types.js";
18
+ /** The owner chain is at most this long (agent → owner → ...). A longer chain is denied. */
19
+ export declare const MAX_OWNER_DEPTH = 4;
20
+ /** The lines that belong to this principal: its own lines and the lines of its role bundles. */
21
+ export declare function linesOf(principal: Principal, lines: readonly PermissionLine[]): PermissionLine[];
22
+ /** The lines of this principal that are in force and cover the capability and the target. */
23
+ export declare function matchingLines(principal: Principal, input: Omit<CanInput, "principal">): PermissionLine[];
24
+ /** Can this principal do this capability on this target, at `now`? */
25
+ export declare function can(input: CanInput): Decision;
package/dist/can.js ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * can(): the one fleet access decision (parent plan
3
+ * 20261115-fleet-access-iam-gateway-flows-rules, ADR-5 and ADR-16).
4
+ *
5
+ * Rules:
6
+ * 1. Deny wins. Among the lines in force that match, deny beats ask and ask
7
+ * beats allow. No matching line: deny (default deny).
8
+ * 2. A line matches when its capability (exact or pattern) covers the
9
+ * request and its scope covers the target.
10
+ * 3. A revoked or expired line is ignored.
11
+ * 4. An agent never exceeds its owner:
12
+ * effective(agent) = (agent role bundles ∪ agent lines) ∩ effective(owner).
13
+ * Deny wins at each layer; an ask on either side gives ask.
14
+ *
15
+ * Pure: no I/O, no clock read, no input mutation.
16
+ */
17
+ import { isValidCapability, matchesCapability } from "./capability.js";
18
+ import { isLineActive, matchesScope } from "./line.js";
19
+ /** The owner chain is at most this long (agent → owner → ...). A longer chain is denied. */
20
+ export const MAX_OWNER_DEPTH = 4;
21
+ /** The order in which effects decide. The first effect with a matching line wins. */
22
+ const PRECEDENCE = ["deny", "ask", "allow"];
23
+ const REASON_BY_EFFECT = {
24
+ deny: "deny_line",
25
+ ask: "ask_line",
26
+ allow: "allow_line",
27
+ };
28
+ /** The lines that belong to this principal: its own lines and the lines of its role bundles. */
29
+ export function linesOf(principal, lines) {
30
+ const roles = new Set(principal.role_ids ?? []);
31
+ return lines.filter((line) => (line.principal_actor_id != null &&
32
+ line.principal_actor_id === principal.actor_id) ||
33
+ (line.principal_role_id != null && roles.has(line.principal_role_id)));
34
+ }
35
+ /** The lines of this principal that are in force and cover the capability and the target. */
36
+ export function matchingLines(principal, input) {
37
+ return linesOf(principal, input.lines).filter((line) => isLineActive(line, input.now) &&
38
+ matchesCapability(line.capability, input.capability) &&
39
+ matchesScope(line, input.target));
40
+ }
41
+ /** Lowest id first, so the deciding line does not depend on the input order. */
42
+ function first(lines) {
43
+ return [...lines].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))[0];
44
+ }
45
+ /** One principal alone, without the owner cap. */
46
+ function decideLayer(principal, input) {
47
+ const matched = matchingLines(principal, input);
48
+ for (const effect of PRECEDENCE) {
49
+ const line = first(matched.filter((l) => l.effect === effect));
50
+ if (line) {
51
+ return {
52
+ outcome: effect,
53
+ decided_by: `permission:${line.id}`,
54
+ reason: REASON_BY_EFFECT[effect],
55
+ line,
56
+ };
57
+ }
58
+ }
59
+ return { outcome: "deny", decided_by: null, reason: "no_match" };
60
+ }
61
+ /** agent ∩ owner. Deny wins over ask; ask wins over allow. */
62
+ function capByOwner(agent, owner) {
63
+ if (agent.outcome === "deny")
64
+ return { ...agent, owner };
65
+ if (owner.outcome === "deny") {
66
+ return {
67
+ outcome: "deny",
68
+ decided_by: "owner_cap",
69
+ reason: "owner_cap",
70
+ owner,
71
+ };
72
+ }
73
+ if (agent.outcome === "ask")
74
+ return { ...agent, owner };
75
+ if (owner.outcome === "ask") {
76
+ return {
77
+ outcome: "ask",
78
+ decided_by: "owner_cap",
79
+ reason: "owner_cap",
80
+ owner,
81
+ };
82
+ }
83
+ return { ...agent, owner };
84
+ }
85
+ function decide(principal, input, depth) {
86
+ if (depth > MAX_OWNER_DEPTH) {
87
+ return {
88
+ outcome: "deny",
89
+ decided_by: "owner_cap",
90
+ reason: "owner_depth_exceeded",
91
+ };
92
+ }
93
+ const own = decideLayer(principal, input);
94
+ if (principal.kind !== "agent")
95
+ return own;
96
+ if (!principal.owner) {
97
+ return {
98
+ outcome: "deny",
99
+ decided_by: "owner_cap",
100
+ reason: "owner_missing",
101
+ };
102
+ }
103
+ const owner = decide(principal.owner, input, depth + 1);
104
+ return capByOwner(own, owner);
105
+ }
106
+ /** Can this principal do this capability on this target, at `now`? */
107
+ export function can(input) {
108
+ if (!isValidCapability(input.capability)) {
109
+ return { outcome: "deny", decided_by: null, reason: "invalid_capability" };
110
+ }
111
+ const { principal, ...rest } = input;
112
+ return decide(principal, rest, 0);
113
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Capability names and patterns.
3
+ *
4
+ * A name is dot-separated segments: `<domain>.<entity>.<verb>`, for example
5
+ * `work.task.create` (or `work.tasks.insert` for a table write that has no
6
+ * command yet). A segment is lower-case letters, digits, `_` or `-`.
7
+ *
8
+ * A pattern is a name where a segment may be `*`:
9
+ * - a `*` in the last position matches ONE OR MORE remaining segments
10
+ * (`work.*` matches `work.task.create`, but not `work`);
11
+ * - a `*` in any other position matches exactly one segment
12
+ * (`work.*.create` matches `work.task.create`);
13
+ * - `*` alone matches every capability.
14
+ * A malformed pattern matches nothing. The access module (S2-T4) refuses
15
+ * to write one, so a malformed line cannot exist in `iam.permissions`.
16
+ */
17
+ export declare function isValidCapability(name: string): boolean;
18
+ export declare function isValidCapabilityPattern(pattern: string): boolean;
19
+ /** True when the line capability (exact or pattern) covers the requested capability. */
20
+ export declare function matchesCapability(pattern: string, capability: string): boolean;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Capability names and patterns.
3
+ *
4
+ * A name is dot-separated segments: `<domain>.<entity>.<verb>`, for example
5
+ * `work.task.create` (or `work.tasks.insert` for a table write that has no
6
+ * command yet). A segment is lower-case letters, digits, `_` or `-`.
7
+ *
8
+ * A pattern is a name where a segment may be `*`:
9
+ * - a `*` in the last position matches ONE OR MORE remaining segments
10
+ * (`work.*` matches `work.task.create`, but not `work`);
11
+ * - a `*` in any other position matches exactly one segment
12
+ * (`work.*.create` matches `work.task.create`);
13
+ * - `*` alone matches every capability.
14
+ * A malformed pattern matches nothing. The access module (S2-T4) refuses
15
+ * to write one, so a malformed line cannot exist in `iam.permissions`.
16
+ */
17
+ const SEGMENT = /^[a-z0-9_-]+$/;
18
+ export function isValidCapability(name) {
19
+ if (typeof name !== "string" || name.length === 0)
20
+ return false;
21
+ return name.split(".").every((segment) => SEGMENT.test(segment));
22
+ }
23
+ export function isValidCapabilityPattern(pattern) {
24
+ if (typeof pattern !== "string" || pattern.length === 0)
25
+ return false;
26
+ return pattern
27
+ .split(".")
28
+ .every((segment) => segment === "*" || SEGMENT.test(segment));
29
+ }
30
+ /** True when the line capability (exact or pattern) covers the requested capability. */
31
+ export function matchesCapability(pattern, capability) {
32
+ if (!isValidCapabilityPattern(pattern) || !isValidCapability(capability)) {
33
+ return false;
34
+ }
35
+ const p = pattern.split(".");
36
+ const c = capability.split(".");
37
+ for (let i = 0; i < p.length; i++) {
38
+ const segment = p[i];
39
+ if (segment === "*") {
40
+ const isLast = i === p.length - 1;
41
+ if (isLast)
42
+ return c.length > i;
43
+ if (c[i] === undefined)
44
+ return false;
45
+ continue;
46
+ }
47
+ if (segment !== c[i])
48
+ return false;
49
+ }
50
+ return p.length === c.length;
51
+ }
@@ -0,0 +1,14 @@
1
+ export type { RuleBinding, VerifiedRole } from "./bindings.js";
2
+ export { bindingApplies, RULE_BINDINGS, ruleBindingOf, ruleRefOf, SMOKE_LAB_WORK_BUSINESS_UNIT_ID, TASK_CREATE_POINTS, verifiedRoleOf, } from "./bindings.js";
3
+ export { can, linesOf, MAX_OWNER_DEPTH, matchingLines } from "./can.js";
4
+ export { isValidCapability, isValidCapabilityPattern, matchesCapability, } from "./capability.js";
5
+ export { isLineActive, matchesScope } from "./line.js";
6
+ export type { ActorRow, ActorType, OwnerResolution, PrincipalReads, ResolvedPrincipal, } from "./principal.js";
7
+ export { resolvePrincipal } from "./principal.js";
8
+ export type { InputSource, RuleDecision, RuleReason, RuleRef, RuleRequest, VerifiedContext, WriteDecision, } from "./rule.js";
9
+ export { buildRuleInput, decideWrite, evaluateRule } from "./rule.js";
10
+ export type { VendoredRule } from "./rules.generated.js";
11
+ export { RULES_COMMIT, VENDORED_RULES } from "./rules.generated.js";
12
+ export type { DecisionTable, DmnDefinition, DmnResult, HitPolicy, InputClause, MatchedRule, OutputClause, } from "./runtime.js";
13
+ export { DmnError, evaluateDefinition } from "./runtime.js";
14
+ export type { CanInput, Decision, DecisionReason, Effect, Instant, Outcome, PermissionLine, Principal, ScopeKind, Target, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { bindingApplies, RULE_BINDINGS, ruleBindingOf, ruleRefOf, SMOKE_LAB_WORK_BUSINESS_UNIT_ID, TASK_CREATE_POINTS, verifiedRoleOf, } from "./bindings.js";
2
+ export { can, linesOf, MAX_OWNER_DEPTH, matchingLines } from "./can.js";
3
+ export { isValidCapability, isValidCapabilityPattern, matchesCapability, } from "./capability.js";
4
+ export { isLineActive, matchesScope } from "./line.js";
5
+ export { resolvePrincipal } from "./principal.js";
6
+ export { buildRuleInput, decideWrite, evaluateRule } from "./rule.js";
7
+ export { RULES_COMMIT, VENDORED_RULES } from "./rules.generated.js";
8
+ export { DmnError, evaluateDefinition } from "./runtime.js";
package/dist/line.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Per-line checks: is the line still in force, and does its scope cover the target.
3
+ */
4
+ import type { PermissionLine, Target } from "./types.js";
5
+ /**
6
+ * A line is in force when it is not revoked and not expired.
7
+ *
8
+ * - `revoked_at` set: ignored (a revoke is immediate; the row stays for history).
9
+ * - `expires_at` at or before `now`: ignored.
10
+ * - `expires_at` unparseable: a restrictive line (deny, ask) stays in force and an
11
+ * allow line is ignored. A bad timestamp never opens access.
12
+ */
13
+ export declare function isLineActive(line: PermissionLine, now: Date): boolean;
14
+ /**
15
+ * True when the line scope covers the target.
16
+ *
17
+ * - `all`: every target.
18
+ * - `business_unit`: the target is in that business unit.
19
+ * - `item`: the target is that item.
20
+ * A scoped line without `scope_id`, or an unknown scope kind, covers nothing.
21
+ */
22
+ export declare function matchesScope(line: PermissionLine, target: Target | undefined): boolean;
package/dist/line.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Per-line checks: is the line still in force, and does its scope cover the target.
3
+ */
4
+ function toMillis(value) {
5
+ const ms = value instanceof Date ? value.getTime() : Date.parse(value);
6
+ return Number.isNaN(ms) ? null : ms;
7
+ }
8
+ /**
9
+ * A line is in force when it is not revoked and not expired.
10
+ *
11
+ * - `revoked_at` set: ignored (a revoke is immediate; the row stays for history).
12
+ * - `expires_at` at or before `now`: ignored.
13
+ * - `expires_at` unparseable: a restrictive line (deny, ask) stays in force and an
14
+ * allow line is ignored. A bad timestamp never opens access.
15
+ */
16
+ export function isLineActive(line, now) {
17
+ if (line.revoked_at != null)
18
+ return false;
19
+ if (line.expires_at == null)
20
+ return true;
21
+ const expiresAt = toMillis(line.expires_at);
22
+ if (expiresAt === null)
23
+ return line.effect !== "allow";
24
+ const isExpired = expiresAt <= now.getTime();
25
+ return !isExpired;
26
+ }
27
+ /**
28
+ * True when the line scope covers the target.
29
+ *
30
+ * - `all`: every target.
31
+ * - `business_unit`: the target is in that business unit.
32
+ * - `item`: the target is that item.
33
+ * A scoped line without `scope_id`, or an unknown scope kind, covers nothing.
34
+ */
35
+ export function matchesScope(line, target) {
36
+ switch (line.scope_kind) {
37
+ case "all":
38
+ return true;
39
+ case "business_unit":
40
+ return (line.scope_id != null && target?.business_unit_id === line.scope_id);
41
+ case "item":
42
+ return line.scope_id != null && target?.item_id === line.scope_id;
43
+ default:
44
+ return false;
45
+ }
46
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * resolvePrincipal(): the `Principal` of `can()` from the rows a caller can read.
3
+ *
4
+ * Moved from dfl-os-commands (S2-T4) into the package (plan
5
+ * 20261116-fleet-access-s3-gateway-decision, ADR-1), so the gateway and the
6
+ * service build the principal with one copy of the rules: the actor, its role
7
+ * bundles, and for an agent its owner (the delegator of its one ACTIVE
8
+ * delegation). The chain is read up to MAX_OWNER_DEPTH layers; a deeper owner
9
+ * is a stub that `can()` refuses.
10
+ *
11
+ * No I/O of its own: the caller passes the four reads (SQL in a caller
12
+ * transaction in the service, PostgREST with the caller's token in the
13
+ * gateway, an in-memory snapshot in the tests).
14
+ */
15
+ import type { PermissionLine, Principal } from "./types.js";
16
+ /** `public.actors.type`. */
17
+ export type ActorType = "human" | "agent" | "service";
18
+ /** One row of `public.actors`. */
19
+ export interface ActorRow {
20
+ id: string;
21
+ type: ActorType;
22
+ display_name: string | null;
23
+ }
24
+ /** How the owner of one layer was found. */
25
+ export type OwnerResolution = "not_agent" | "one" | "none" | "ambiguous";
26
+ /** The four reads of resolvePrincipal. Each runs with the caller's own token. */
27
+ export interface PrincipalReads<L extends PermissionLine = PermissionLine> {
28
+ readActor(id: string): Promise<ActorRow | null>;
29
+ /** The `iam.user_roles` role ids of the auth users linked to the actor. */
30
+ readActorRoles(actorId: string): Promise<string[]>;
31
+ /** The delegator actors of the ACTIVE delegations to this actor. */
32
+ readActorOwners(actorId: string): Promise<string[]>;
33
+ /** Unrevoked lines of these actors and these roles (expired lines included). */
34
+ readLines(actorIds: readonly string[], roleIds: readonly string[]): Promise<L[]>;
35
+ }
36
+ export interface ResolvedPrincipal<L extends PermissionLine = PermissionLine> {
37
+ principal: Principal;
38
+ /** One entry per layer: the principal, then its owner chain. */
39
+ layers: {
40
+ actor: ActorRow;
41
+ role_ids: string[];
42
+ owner_resolution: OwnerResolution;
43
+ owner_candidates?: string[];
44
+ }[];
45
+ /** The unrevoked lines of every layer (own lines and role lines). */
46
+ lines: L[];
47
+ }
48
+ /** Null when the actor is not visible to the caller. */
49
+ export declare function resolvePrincipal<L extends PermissionLine>(reads: PrincipalReads<L>, actorId: string): Promise<ResolvedPrincipal<L> | null>;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * resolvePrincipal(): the `Principal` of `can()` from the rows a caller can read.
3
+ *
4
+ * Moved from dfl-os-commands (S2-T4) into the package (plan
5
+ * 20261116-fleet-access-s3-gateway-decision, ADR-1), so the gateway and the
6
+ * service build the principal with one copy of the rules: the actor, its role
7
+ * bundles, and for an agent its owner (the delegator of its one ACTIVE
8
+ * delegation). The chain is read up to MAX_OWNER_DEPTH layers; a deeper owner
9
+ * is a stub that `can()` refuses.
10
+ *
11
+ * No I/O of its own: the caller passes the four reads (SQL in a caller
12
+ * transaction in the service, PostgREST with the caller's token in the
13
+ * gateway, an in-memory snapshot in the tests).
14
+ */
15
+ import { MAX_OWNER_DEPTH } from "./can.js";
16
+ const KIND = {
17
+ human: "person",
18
+ agent: "agent",
19
+ service: "service",
20
+ };
21
+ /** Null when the actor is not visible to the caller. */
22
+ export async function resolvePrincipal(reads, actorId) {
23
+ const layers = [];
24
+ const seen = new Set();
25
+ const build = async (id, depth) => {
26
+ const actor = await reads.readActor(id);
27
+ if (!actor)
28
+ return null;
29
+ const roleIds = await reads.readActorRoles(id);
30
+ const layer = {
31
+ actor,
32
+ role_ids: roleIds,
33
+ owner_resolution: "not_agent",
34
+ };
35
+ layers.push(layer);
36
+ seen.add(id);
37
+ const principal = {
38
+ actor_id: actor.id,
39
+ kind: KIND[actor.type] ?? "service",
40
+ role_ids: roleIds,
41
+ };
42
+ if (actor.type !== "agent")
43
+ return principal;
44
+ const owners = (await reads.readActorOwners(id)).filter((o) => o !== id);
45
+ if (owners.length === 0) {
46
+ layer.owner_resolution = "none";
47
+ principal.owner = null;
48
+ }
49
+ else if (owners.length > 1) {
50
+ layer.owner_resolution = "ambiguous";
51
+ layer.owner_candidates = owners;
52
+ principal.owner = null;
53
+ }
54
+ else {
55
+ layer.owner_resolution = "one";
56
+ const ownerId = owners[0];
57
+ // Past the limit, or a cycle: a stub owner without rows. can() denies it
58
+ // (owner_depth_exceeded past the limit, owner_missing on a cycle). No more reads.
59
+ principal.owner =
60
+ depth + 1 > MAX_OWNER_DEPTH || seen.has(ownerId)
61
+ ? { actor_id: ownerId, kind: "agent", owner: null }
62
+ : await build(ownerId, depth + 1);
63
+ }
64
+ return principal;
65
+ };
66
+ const principal = await build(actorId, 0);
67
+ if (!principal)
68
+ return null;
69
+ const actorIds = layers.map((l) => l.actor.id);
70
+ const roleIds = [...new Set(layers.flatMap((l) => l.role_ids))];
71
+ const lines = await reads.readLines(actorIds, roleIds);
72
+ return { principal, layers, lines };
73
+ }