apcore-js 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.
Files changed (142) hide show
  1. package/.claude/settings.local.json +11 -0
  2. package/.gitmessage +60 -0
  3. package/.pre-commit-config.yaml +28 -0
  4. package/CHANGELOG.md +47 -0
  5. package/CLAUDE.md +68 -0
  6. package/README.md +131 -0
  7. package/apcore-logo.svg +79 -0
  8. package/package.json +37 -0
  9. package/planning/acl-system/overview.md +54 -0
  10. package/planning/acl-system/plan.md +92 -0
  11. package/planning/acl-system/state.json +76 -0
  12. package/planning/acl-system/tasks/acl-core.md +226 -0
  13. package/planning/acl-system/tasks/acl-rule.md +92 -0
  14. package/planning/acl-system/tasks/conditional-rules.md +259 -0
  15. package/planning/acl-system/tasks/pattern-matching.md +152 -0
  16. package/planning/acl-system/tasks/yaml-loading.md +271 -0
  17. package/planning/core-executor/overview.md +53 -0
  18. package/planning/core-executor/plan.md +88 -0
  19. package/planning/core-executor/state.json +76 -0
  20. package/planning/core-executor/tasks/async-support.md +106 -0
  21. package/planning/core-executor/tasks/execution-pipeline.md +113 -0
  22. package/planning/core-executor/tasks/redaction.md +85 -0
  23. package/planning/core-executor/tasks/safety-checks.md +65 -0
  24. package/planning/core-executor/tasks/setup.md +75 -0
  25. package/planning/decorator-bindings/overview.md +62 -0
  26. package/planning/decorator-bindings/plan.md +104 -0
  27. package/planning/decorator-bindings/state.json +87 -0
  28. package/planning/decorator-bindings/tasks/binding-directory.md +79 -0
  29. package/planning/decorator-bindings/tasks/binding-loader.md +148 -0
  30. package/planning/decorator-bindings/tasks/explicit-schemas.md +85 -0
  31. package/planning/decorator-bindings/tasks/function-module.md +127 -0
  32. package/planning/decorator-bindings/tasks/module-factory.md +89 -0
  33. package/planning/decorator-bindings/tasks/schema-modes.md +142 -0
  34. package/planning/middleware-system/overview.md +48 -0
  35. package/planning/middleware-system/plan.md +102 -0
  36. package/planning/middleware-system/state.json +65 -0
  37. package/planning/middleware-system/tasks/adapters.md +170 -0
  38. package/planning/middleware-system/tasks/base.md +115 -0
  39. package/planning/middleware-system/tasks/logging-middleware.md +304 -0
  40. package/planning/middleware-system/tasks/manager.md +313 -0
  41. package/planning/observability/overview.md +53 -0
  42. package/planning/observability/plan.md +119 -0
  43. package/planning/observability/state.json +98 -0
  44. package/planning/observability/tasks/context-logger.md +201 -0
  45. package/planning/observability/tasks/exporters.md +121 -0
  46. package/planning/observability/tasks/metrics-collector.md +162 -0
  47. package/planning/observability/tasks/metrics-middleware.md +141 -0
  48. package/planning/observability/tasks/obs-logging-middleware.md +179 -0
  49. package/planning/observability/tasks/span-model.md +120 -0
  50. package/planning/observability/tasks/tracing-middleware.md +179 -0
  51. package/planning/overview.md +81 -0
  52. package/planning/registry-system/overview.md +57 -0
  53. package/planning/registry-system/plan.md +114 -0
  54. package/planning/registry-system/state.json +109 -0
  55. package/planning/registry-system/tasks/dependencies.md +157 -0
  56. package/planning/registry-system/tasks/entry-point.md +148 -0
  57. package/planning/registry-system/tasks/metadata.md +198 -0
  58. package/planning/registry-system/tasks/registry-core.md +323 -0
  59. package/planning/registry-system/tasks/scanner.md +172 -0
  60. package/planning/registry-system/tasks/schema-export.md +261 -0
  61. package/planning/registry-system/tasks/types.md +124 -0
  62. package/planning/registry-system/tasks/validation.md +177 -0
  63. package/planning/schema-system/overview.md +56 -0
  64. package/planning/schema-system/plan.md +121 -0
  65. package/planning/schema-system/state.json +98 -0
  66. package/planning/schema-system/tasks/exporter.md +153 -0
  67. package/planning/schema-system/tasks/loader.md +106 -0
  68. package/planning/schema-system/tasks/ref-resolver.md +133 -0
  69. package/planning/schema-system/tasks/strict-mode.md +140 -0
  70. package/planning/schema-system/tasks/typebox-generation.md +133 -0
  71. package/planning/schema-system/tasks/types-and-annotations.md +160 -0
  72. package/planning/schema-system/tasks/validator.md +149 -0
  73. package/src/acl.ts +188 -0
  74. package/src/bindings.ts +208 -0
  75. package/src/config.ts +24 -0
  76. package/src/context.ts +75 -0
  77. package/src/decorator.ts +110 -0
  78. package/src/errors.ts +369 -0
  79. package/src/executor.ts +348 -0
  80. package/src/index.ts +81 -0
  81. package/src/middleware/adapters.ts +54 -0
  82. package/src/middleware/base.ts +33 -0
  83. package/src/middleware/index.ts +6 -0
  84. package/src/middleware/logging.ts +103 -0
  85. package/src/middleware/manager.ts +105 -0
  86. package/src/module.ts +41 -0
  87. package/src/observability/context-logger.ts +201 -0
  88. package/src/observability/index.ts +4 -0
  89. package/src/observability/metrics.ts +212 -0
  90. package/src/observability/tracing.ts +187 -0
  91. package/src/registry/dependencies.ts +99 -0
  92. package/src/registry/entry-point.ts +64 -0
  93. package/src/registry/index.ts +8 -0
  94. package/src/registry/metadata.ts +111 -0
  95. package/src/registry/registry.ts +314 -0
  96. package/src/registry/scanner.ts +150 -0
  97. package/src/registry/schema-export.ts +177 -0
  98. package/src/registry/types.ts +32 -0
  99. package/src/registry/validation.ts +38 -0
  100. package/src/schema/annotations.ts +67 -0
  101. package/src/schema/exporter.ts +93 -0
  102. package/src/schema/index.ts +14 -0
  103. package/src/schema/loader.ts +270 -0
  104. package/src/schema/ref-resolver.ts +235 -0
  105. package/src/schema/strict.ts +128 -0
  106. package/src/schema/types.ts +73 -0
  107. package/src/schema/validator.ts +82 -0
  108. package/src/utils/index.ts +1 -0
  109. package/src/utils/pattern.ts +30 -0
  110. package/tests/helpers.ts +30 -0
  111. package/tests/integration/test-acl-safety.test.ts +268 -0
  112. package/tests/integration/test-binding-executor.test.ts +194 -0
  113. package/tests/integration/test-e2e-flow.test.ts +117 -0
  114. package/tests/integration/test-error-propagation.test.ts +259 -0
  115. package/tests/integration/test-middleware-chain.test.ts +120 -0
  116. package/tests/integration/test-observability-integration.test.ts +438 -0
  117. package/tests/observability/test-context-logger.test.ts +123 -0
  118. package/tests/observability/test-metrics.test.ts +89 -0
  119. package/tests/observability/test-tracing.test.ts +131 -0
  120. package/tests/registry/test-dependencies.test.ts +70 -0
  121. package/tests/registry/test-entry-point.test.ts +133 -0
  122. package/tests/registry/test-metadata.test.ts +265 -0
  123. package/tests/registry/test-registry.test.ts +140 -0
  124. package/tests/registry/test-scanner.test.ts +257 -0
  125. package/tests/registry/test-schema-export.test.ts +224 -0
  126. package/tests/registry/test-validation.test.ts +75 -0
  127. package/tests/schema/test-loader.test.ts +97 -0
  128. package/tests/schema/test-ref-resolver.test.ts +105 -0
  129. package/tests/schema/test-strict.test.ts +139 -0
  130. package/tests/schema/test-validator.test.ts +64 -0
  131. package/tests/test-acl.test.ts +206 -0
  132. package/tests/test-bindings.test.ts +227 -0
  133. package/tests/test-config.test.ts +76 -0
  134. package/tests/test-context.test.ts +151 -0
  135. package/tests/test-decorator.test.ts +173 -0
  136. package/tests/test-errors.test.ts +204 -0
  137. package/tests/test-executor.test.ts +252 -0
  138. package/tests/test-middleware-manager.test.ts +185 -0
  139. package/tests/test-middleware.test.ts +86 -0
  140. package/tsconfig.build.json +8 -0
  141. package/tsconfig.json +20 -0
  142. package/vitest.config.ts +18 -0
@@ -0,0 +1,76 @@
1
+ {
2
+ "feature": "acl-system",
3
+ "created": "2026-02-16T00:00:00Z",
4
+ "updated": "2026-02-16T00:00:00Z",
5
+ "status": "completed",
6
+ "execution_order": [
7
+ "acl-rule",
8
+ "pattern-matching",
9
+ "conditional-rules",
10
+ "acl-core",
11
+ "yaml-loading"
12
+ ],
13
+ "progress": {
14
+ "total_tasks": 5,
15
+ "completed": 5,
16
+ "in_progress": 0,
17
+ "pending": 0
18
+ },
19
+ "tasks": [
20
+ {
21
+ "id": "acl-rule",
22
+ "file": "tasks/acl-rule.md",
23
+ "title": "ACLRule Interface Definition",
24
+ "status": "completed",
25
+ "started_at": "2026-02-16T08:00:00Z",
26
+ "completed_at": "2026-02-16T08:45:00Z",
27
+ "assignee": null,
28
+ "commits": []
29
+ },
30
+ {
31
+ "id": "pattern-matching",
32
+ "file": "tasks/pattern-matching.md",
33
+ "title": "matchPattern() Wildcard Matching (Algorithm A08)",
34
+ "status": "completed",
35
+ "started_at": "2026-02-16T08:45:00Z",
36
+ "completed_at": "2026-02-16T10:15:00Z",
37
+ "assignee": null,
38
+ "commits": []
39
+ },
40
+ {
41
+ "id": "conditional-rules",
42
+ "file": "tasks/conditional-rules.md",
43
+ "title": "Conditional Rule Evaluation (identity_types, roles, max_call_depth)",
44
+ "status": "completed",
45
+ "started_at": "2026-02-16T10:15:00Z",
46
+ "completed_at": "2026-02-16T11:45:00Z",
47
+ "assignee": null,
48
+ "commits": []
49
+ },
50
+ {
51
+ "id": "acl-core",
52
+ "file": "tasks/acl-core.md",
53
+ "title": "ACL Class with check(), addRule(), removeRule()",
54
+ "status": "completed",
55
+ "started_at": "2026-02-16T11:45:00Z",
56
+ "completed_at": "2026-02-16T14:00:00Z",
57
+ "assignee": null,
58
+ "commits": []
59
+ },
60
+ {
61
+ "id": "yaml-loading",
62
+ "file": "tasks/yaml-loading.md",
63
+ "title": "ACL.load() from YAML and reload() Support",
64
+ "status": "completed",
65
+ "started_at": "2026-02-16T14:00:00Z",
66
+ "completed_at": "2026-02-16T15:30:00Z",
67
+ "assignee": null,
68
+ "commits": []
69
+ }
70
+ ],
71
+ "metadata": {
72
+ "source_doc": "planning/features/acl-system.md",
73
+ "created_by": "code-forge",
74
+ "version": "1.0"
75
+ }
76
+ }
@@ -0,0 +1,226 @@
1
+ # Task: ACL Class with check(), addRule(), removeRule()
2
+
3
+ ## Goal
4
+
5
+ Implement the `ACL` class that manages an ordered list of `ACLRule` objects and provides first-match-wins permission evaluation via `check()`, runtime rule mutation via `addRule()` and `removeRule()`, and a configurable default effect.
6
+
7
+ ## Files Involved
8
+
9
+ - `src/acl.ts` -- ACL class implementation (~188 lines total including YAML loading)
10
+ - `src/errors.ts` -- `ACLDeniedError` (used by executor, not ACL directly)
11
+ - `src/context.ts` -- `Context` and `Identity` types consumed by `check()`
12
+
13
+ ## Steps (TDD)
14
+
15
+ ### 1. Write failing tests for ACL constructor and default behavior
16
+
17
+ ```typescript
18
+ // tests/acl.test.ts
19
+ import { describe, it, expect } from 'vitest';
20
+ import { ACL } from '../src/acl.js';
21
+ import type { ACLRule } from '../src/acl.js';
22
+
23
+ describe('ACL constructor', () => {
24
+ it('should default to deny when no rules match', () => {
25
+ const acl = new ACL([]);
26
+ expect(acl.check('moduleA', 'moduleB')).toBe(false);
27
+ });
28
+
29
+ it('should respect custom default effect', () => {
30
+ const acl = new ACL([], 'allow');
31
+ expect(acl.check('moduleA', 'moduleB')).toBe(true);
32
+ });
33
+ });
34
+ ```
35
+
36
+ ### 2. Implement constructor with rules copy and default effect
37
+
38
+ ```typescript
39
+ export class ACL {
40
+ private _rules: ACLRule[];
41
+ private _defaultEffect: string;
42
+
43
+ constructor(rules: ACLRule[], defaultEffect: string = 'deny') {
44
+ this._rules = [...rules];
45
+ this._defaultEffect = defaultEffect;
46
+ }
47
+ }
48
+ ```
49
+
50
+ ### 3. Write failing tests for check() first-match-wins
51
+
52
+ ```typescript
53
+ describe('ACL.check()', () => {
54
+ it('should allow when first matching rule has allow effect', () => {
55
+ const rules: ACLRule[] = [
56
+ { callers: ['moduleA'], targets: ['moduleB'], effect: 'allow', description: 'test' },
57
+ ];
58
+ const acl = new ACL(rules);
59
+ expect(acl.check('moduleA', 'moduleB')).toBe(true);
60
+ });
61
+
62
+ it('should deny when first matching rule has deny effect', () => {
63
+ const rules: ACLRule[] = [
64
+ { callers: ['moduleA'], targets: ['moduleB'], effect: 'deny', description: 'test' },
65
+ ];
66
+ const acl = new ACL(rules);
67
+ expect(acl.check('moduleA', 'moduleB')).toBe(false);
68
+ });
69
+
70
+ it('should normalize null caller to @external', () => {
71
+ const rules: ACLRule[] = [
72
+ { callers: ['@external'], targets: ['auth'], effect: 'allow', description: 'test' },
73
+ ];
74
+ const acl = new ACL(rules);
75
+ expect(acl.check(null, 'auth')).toBe(true);
76
+ });
77
+
78
+ it('should use first matching rule and ignore later rules', () => {
79
+ const rules: ACLRule[] = [
80
+ { callers: ['moduleA'], targets: ['moduleB'], effect: 'deny', description: 'deny first' },
81
+ { callers: ['moduleA'], targets: ['moduleB'], effect: 'allow', description: 'allow second' },
82
+ ];
83
+ const acl = new ACL(rules);
84
+ expect(acl.check('moduleA', 'moduleB')).toBe(false);
85
+ });
86
+
87
+ it('should fall through to default when no rules match', () => {
88
+ const rules: ACLRule[] = [
89
+ { callers: ['moduleX'], targets: ['moduleY'], effect: 'allow', description: 'unrelated' },
90
+ ];
91
+ const acl = new ACL(rules, 'deny');
92
+ expect(acl.check('moduleA', 'moduleB')).toBe(false);
93
+ });
94
+ });
95
+ ```
96
+
97
+ ### 4. Implement check() with _matchesRule and _matchPattern
98
+
99
+ ```typescript
100
+ check(callerId: string | null, targetId: string, context?: Context | null): boolean {
101
+ const effectiveCaller = callerId === null ? '@external' : callerId;
102
+ const rules = [...this._rules];
103
+
104
+ for (const rule of rules) {
105
+ if (this._matchesRule(rule, effectiveCaller, targetId, context ?? null)) {
106
+ return rule.effect === 'allow';
107
+ }
108
+ }
109
+
110
+ return this._defaultEffect === 'allow';
111
+ }
112
+
113
+ private _matchPattern(pattern: string, value: string, context: Context | null): boolean {
114
+ if (pattern === '@external') return value === '@external';
115
+ if (pattern === '@system') {
116
+ return context !== null && context.identity !== null && context.identity.type === 'system';
117
+ }
118
+ return matchPattern(pattern, value);
119
+ }
120
+
121
+ private _matchesRule(rule: ACLRule, caller: string, target: string, context: Context | null): boolean {
122
+ const callerMatch = rule.callers.some((p) => this._matchPattern(p, caller, context));
123
+ if (!callerMatch) return false;
124
+
125
+ const targetMatch = rule.targets.some((p) => this._matchPattern(p, target, context));
126
+ if (!targetMatch) return false;
127
+
128
+ if (rule.conditions != null) {
129
+ if (!this._checkConditions(rule.conditions, context)) return false;
130
+ }
131
+
132
+ return true;
133
+ }
134
+ ```
135
+
136
+ ### 5. Write failing tests for addRule() and removeRule()
137
+
138
+ ```typescript
139
+ describe('ACL.addRule()', () => {
140
+ it('should prepend rule to beginning of list', () => {
141
+ const acl = new ACL([
142
+ { callers: ['*'], targets: ['*'], effect: 'deny', description: 'deny all' },
143
+ ]);
144
+ acl.addRule({ callers: ['moduleA'], targets: ['moduleB'], effect: 'allow', description: 'allow A->B' });
145
+ // New rule is first, so it should match before the deny-all
146
+ expect(acl.check('moduleA', 'moduleB')).toBe(true);
147
+ });
148
+ });
149
+
150
+ describe('ACL.removeRule()', () => {
151
+ it('should remove rule matching callers and targets', () => {
152
+ const acl = new ACL([
153
+ { callers: ['moduleA'], targets: ['moduleB'], effect: 'allow', description: 'test' },
154
+ ]);
155
+ const removed = acl.removeRule(['moduleA'], ['moduleB']);
156
+ expect(removed).toBe(true);
157
+ expect(acl.check('moduleA', 'moduleB')).toBe(false); // falls to default deny
158
+ });
159
+
160
+ it('should return false when no matching rule found', () => {
161
+ const acl = new ACL([]);
162
+ expect(acl.removeRule(['moduleA'], ['moduleB'])).toBe(false);
163
+ });
164
+
165
+ it('should use JSON.stringify for array comparison', () => {
166
+ const acl = new ACL([
167
+ { callers: ['a', 'b'], targets: ['c'], effect: 'allow', description: 'test' },
168
+ ]);
169
+ // Different order should not match
170
+ expect(acl.removeRule(['b', 'a'], ['c'])).toBe(false);
171
+ // Same order should match
172
+ expect(acl.removeRule(['a', 'b'], ['c'])).toBe(true);
173
+ });
174
+ });
175
+ ```
176
+
177
+ ### 6. Implement addRule() and removeRule()
178
+
179
+ ```typescript
180
+ addRule(rule: ACLRule): void {
181
+ this._rules.unshift(rule);
182
+ }
183
+
184
+ removeRule(callers: string[], targets: string[]): boolean {
185
+ for (let i = 0; i < this._rules.length; i++) {
186
+ const rule = this._rules[i];
187
+ if (
188
+ JSON.stringify(rule.callers) === JSON.stringify(callers) &&
189
+ JSON.stringify(rule.targets) === JSON.stringify(targets)
190
+ ) {
191
+ this._rules.splice(i, 1);
192
+ return true;
193
+ }
194
+ }
195
+ return false;
196
+ }
197
+ ```
198
+
199
+ ### 7. Run full test suite and type-check
200
+
201
+ Run `tsc --noEmit` and `vitest` to confirm everything passes.
202
+
203
+ ## Acceptance Criteria
204
+
205
+ - [x] `ACL` constructor accepts `rules` array and optional `defaultEffect` (default `'deny'`)
206
+ - [x] Constructor shallow-copies the rules array to prevent external mutation
207
+ - [x] `check()` returns `boolean` using first-match-wins evaluation
208
+ - [x] Null `callerId` is normalized to `'@external'`
209
+ - [x] `@external` pattern matches only the `@external` sentinel value
210
+ - [x] `@system` pattern checks `context.identity.type === 'system'`
211
+ - [x] Non-special patterns delegate to `matchPattern()` from `utils/pattern.ts`
212
+ - [x] Falls through to `_defaultEffect` when no rule matches
213
+ - [x] `addRule()` prepends the rule to the beginning of the list
214
+ - [x] `removeRule()` uses `JSON.stringify` for caller/target array comparison and returns `boolean`
215
+ - [x] `removeRule()` only removes the first matching rule
216
+ - [x] All tests pass with `vitest`; zero errors from `tsc --noEmit`
217
+
218
+ ## Dependencies
219
+
220
+ - **acl-rule** -- ACLRule interface definition
221
+ - **pattern-matching** -- matchPattern() utility
222
+ - **conditional-rules** -- _checkConditions() method
223
+
224
+ ## Estimated Time
225
+
226
+ 3 hours
@@ -0,0 +1,92 @@
1
+ # Task: ACLRule Interface Definition
2
+
3
+ ## Goal
4
+
5
+ Define the `ACLRule` TypeScript interface that represents a single access control rule, specifying caller patterns, target patterns, an effect (allow/deny), a human-readable description, and optional conditions for conditional evaluation.
6
+
7
+ ## Files Involved
8
+
9
+ - `src/acl.ts` -- Interface definition exported alongside the ACL class
10
+
11
+ ## Steps (TDD)
12
+
13
+ ### 1. Write failing tests for ACLRule shape
14
+
15
+ ```typescript
16
+ // tests/acl.test.ts
17
+ import { describe, it, expect } from 'vitest';
18
+ import type { ACLRule } from '../src/acl.js';
19
+
20
+ describe('ACLRule interface', () => {
21
+ it('should accept a fully-specified rule', () => {
22
+ const rule: ACLRule = {
23
+ callers: ['moduleA', 'moduleB'],
24
+ targets: ['moduleC'],
25
+ effect: 'allow',
26
+ description: 'Allow A and B to call C',
27
+ conditions: { roles: ['admin'] },
28
+ };
29
+ expect(rule.callers).toEqual(['moduleA', 'moduleB']);
30
+ expect(rule.targets).toEqual(['moduleC']);
31
+ expect(rule.effect).toBe('allow');
32
+ expect(rule.description).toBe('Allow A and B to call C');
33
+ expect(rule.conditions).toEqual({ roles: ['admin'] });
34
+ });
35
+
36
+ it('should accept a rule with no conditions', () => {
37
+ const rule: ACLRule = {
38
+ callers: ['*'],
39
+ targets: ['*'],
40
+ effect: 'deny',
41
+ description: 'Deny all by default',
42
+ };
43
+ expect(rule.conditions).toBeUndefined();
44
+ });
45
+
46
+ it('should accept null conditions', () => {
47
+ const rule: ACLRule = {
48
+ callers: ['@external'],
49
+ targets: ['auth.*'],
50
+ effect: 'allow',
51
+ description: 'Allow external to auth modules',
52
+ conditions: null,
53
+ };
54
+ expect(rule.conditions).toBeNull();
55
+ });
56
+ });
57
+ ```
58
+
59
+ ### 2. Define the ACLRule interface
60
+
61
+ ```typescript
62
+ // src/acl.ts
63
+ export interface ACLRule {
64
+ callers: string[];
65
+ targets: string[];
66
+ effect: string;
67
+ description: string;
68
+ conditions?: Record<string, unknown> | null;
69
+ }
70
+ ```
71
+
72
+ ### 3. Verify type-check and tests pass
73
+
74
+ Run `tsc --noEmit` to confirm no type errors, then run `vitest` to confirm all tests pass.
75
+
76
+ ## Acceptance Criteria
77
+
78
+ - [x] `ACLRule` interface is exported from `src/acl.ts`
79
+ - [x] `callers` is `string[]` representing caller module ID patterns
80
+ - [x] `targets` is `string[]` representing target module ID patterns
81
+ - [x] `effect` is `string` (validated as `'allow'` | `'deny'` at runtime during YAML loading)
82
+ - [x] `description` is `string` for human-readable rule documentation
83
+ - [x] `conditions` is optional `Record<string, unknown> | null` for conditional evaluation
84
+ - [x] All tests pass with `vitest`; zero errors from `tsc --noEmit`
85
+
86
+ ## Dependencies
87
+
88
+ - None (this is a standalone type definition)
89
+
90
+ ## Estimated Time
91
+
92
+ 1 hour
@@ -0,0 +1,259 @@
1
+ # Task: Conditional Rule Evaluation (_checkConditions)
2
+
3
+ ## Goal
4
+
5
+ Implement the `_checkConditions()` private method on the `ACL` class that evaluates optional conditions attached to ACL rules. Conditions use AND logic: all present condition keys must pass for the rule to match. Supported conditions are `identity_types`, `roles`, and `max_call_depth`.
6
+
7
+ ## Files Involved
8
+
9
+ - `src/acl.ts` -- `_checkConditions()` private method on the ACL class
10
+ - `src/context.ts` -- `Context` class (provides `identity` and `callChain`) and `Identity` interface (provides `type` and `roles`)
11
+
12
+ ## Steps (TDD)
13
+
14
+ ### 1. Write failing tests for identity_types condition
15
+
16
+ ```typescript
17
+ // tests/acl.test.ts
18
+ import { describe, it, expect } from 'vitest';
19
+ import { ACL } from '../src/acl.js';
20
+ import type { ACLRule } from '../src/acl.js';
21
+ import type { Context } from '../src/context.js';
22
+
23
+ // Helper to create a minimal mock context
24
+ function mockContext(overrides: {
25
+ identityType?: string;
26
+ identityRoles?: string[];
27
+ callChainLength?: number;
28
+ } = {}): Context {
29
+ return {
30
+ identity: overrides.identityType !== undefined ? {
31
+ id: 'test-user',
32
+ type: overrides.identityType,
33
+ roles: overrides.identityRoles ?? [],
34
+ attrs: {},
35
+ } : null,
36
+ callChain: Array(overrides.callChainLength ?? 0).fill('module'),
37
+ } as unknown as Context;
38
+ }
39
+
40
+ describe('_checkConditions via check()', () => {
41
+ describe('identity_types condition', () => {
42
+ const rules: ACLRule[] = [
43
+ {
44
+ callers: ['*'],
45
+ targets: ['admin.*'],
46
+ effect: 'allow',
47
+ description: 'Allow system callers',
48
+ conditions: { identity_types: ['system', 'service'] },
49
+ },
50
+ ];
51
+
52
+ it('should allow when identity type matches', () => {
53
+ const acl = new ACL(rules);
54
+ const ctx = mockContext({ identityType: 'system' });
55
+ expect(acl.check('moduleA', 'admin.panel', ctx)).toBe(true);
56
+ });
57
+
58
+ it('should deny when identity type does not match', () => {
59
+ const acl = new ACL(rules);
60
+ const ctx = mockContext({ identityType: 'user' });
61
+ expect(acl.check('moduleA', 'admin.panel', ctx)).toBe(false);
62
+ });
63
+
64
+ it('should deny when identity is null', () => {
65
+ const acl = new ACL(rules);
66
+ const ctx = { identity: null, callChain: [] } as unknown as Context;
67
+ expect(acl.check('moduleA', 'admin.panel', ctx)).toBe(false);
68
+ });
69
+ });
70
+ });
71
+ ```
72
+
73
+ ### 2. Write failing tests for roles condition
74
+
75
+ ```typescript
76
+ describe('roles condition', () => {
77
+ const rules: ACLRule[] = [
78
+ {
79
+ callers: ['*'],
80
+ targets: ['admin.*'],
81
+ effect: 'allow',
82
+ description: 'Allow admin role',
83
+ conditions: { roles: ['admin', 'superadmin'] },
84
+ },
85
+ ];
86
+
87
+ it('should allow when identity has at least one matching role', () => {
88
+ const acl = new ACL(rules);
89
+ const ctx = mockContext({ identityType: 'user', identityRoles: ['admin'] });
90
+ expect(acl.check('moduleA', 'admin.panel', ctx)).toBe(true);
91
+ });
92
+
93
+ it('should deny when identity has no matching roles', () => {
94
+ const acl = new ACL(rules);
95
+ const ctx = mockContext({ identityType: 'user', identityRoles: ['viewer'] });
96
+ expect(acl.check('moduleA', 'admin.panel', ctx)).toBe(false);
97
+ });
98
+
99
+ it('should deny when identity is null', () => {
100
+ const acl = new ACL(rules);
101
+ const ctx = { identity: null, callChain: [] } as unknown as Context;
102
+ expect(acl.check('moduleA', 'admin.panel', ctx)).toBe(false);
103
+ });
104
+ });
105
+ ```
106
+
107
+ ### 3. Write failing tests for max_call_depth condition
108
+
109
+ ```typescript
110
+ describe('max_call_depth condition', () => {
111
+ const rules: ACLRule[] = [
112
+ {
113
+ callers: ['*'],
114
+ targets: ['recursive.*'],
115
+ effect: 'allow',
116
+ description: 'Allow with depth limit',
117
+ conditions: { max_call_depth: 3 },
118
+ },
119
+ ];
120
+
121
+ it('should allow when call chain is within limit', () => {
122
+ const acl = new ACL(rules);
123
+ const ctx = mockContext({ identityType: 'user', callChainLength: 2 });
124
+ expect(acl.check('moduleA', 'recursive.handler', ctx)).toBe(true);
125
+ });
126
+
127
+ it('should allow when call chain is exactly at limit', () => {
128
+ const acl = new ACL(rules);
129
+ const ctx = mockContext({ identityType: 'user', callChainLength: 3 });
130
+ expect(acl.check('moduleA', 'recursive.handler', ctx)).toBe(true);
131
+ });
132
+
133
+ it('should deny when call chain exceeds limit', () => {
134
+ const acl = new ACL(rules);
135
+ const ctx = mockContext({ identityType: 'user', callChainLength: 4 });
136
+ expect(acl.check('moduleA', 'recursive.handler', ctx)).toBe(false);
137
+ });
138
+ });
139
+ ```
140
+
141
+ ### 4. Write failing tests for AND logic across multiple conditions
142
+
143
+ ```typescript
144
+ describe('AND logic across conditions', () => {
145
+ const rules: ACLRule[] = [
146
+ {
147
+ callers: ['*'],
148
+ targets: ['sensitive.*'],
149
+ effect: 'allow',
150
+ description: 'Require admin role AND system type AND depth <= 2',
151
+ conditions: {
152
+ identity_types: ['system'],
153
+ roles: ['admin'],
154
+ max_call_depth: 2,
155
+ },
156
+ },
157
+ ];
158
+
159
+ it('should allow when all conditions pass', () => {
160
+ const acl = new ACL(rules);
161
+ const ctx = mockContext({ identityType: 'system', identityRoles: ['admin'], callChainLength: 1 });
162
+ expect(acl.check('moduleA', 'sensitive.data', ctx)).toBe(true);
163
+ });
164
+
165
+ it('should deny when one condition fails (wrong type)', () => {
166
+ const acl = new ACL(rules);
167
+ const ctx = mockContext({ identityType: 'user', identityRoles: ['admin'], callChainLength: 1 });
168
+ expect(acl.check('moduleA', 'sensitive.data', ctx)).toBe(false);
169
+ });
170
+
171
+ it('should deny when one condition fails (wrong role)', () => {
172
+ const acl = new ACL(rules);
173
+ const ctx = mockContext({ identityType: 'system', identityRoles: ['viewer'], callChainLength: 1 });
174
+ expect(acl.check('moduleA', 'sensitive.data', ctx)).toBe(false);
175
+ });
176
+
177
+ it('should deny when one condition fails (depth exceeded)', () => {
178
+ const acl = new ACL(rules);
179
+ const ctx = mockContext({ identityType: 'system', identityRoles: ['admin'], callChainLength: 5 });
180
+ expect(acl.check('moduleA', 'sensitive.data', ctx)).toBe(false);
181
+ });
182
+ });
183
+ ```
184
+
185
+ ### 5. Write failing test for null context with conditions
186
+
187
+ ```typescript
188
+ describe('null context with conditions', () => {
189
+ it('should deny when context is null and conditions are present', () => {
190
+ const rules: ACLRule[] = [
191
+ {
192
+ callers: ['*'],
193
+ targets: ['*'],
194
+ effect: 'allow',
195
+ description: 'conditional rule',
196
+ conditions: { roles: ['admin'] },
197
+ },
198
+ ];
199
+ const acl = new ACL(rules);
200
+ expect(acl.check('moduleA', 'moduleB', null)).toBe(false);
201
+ });
202
+ });
203
+ ```
204
+
205
+ ### 6. Implement _checkConditions()
206
+
207
+ ```typescript
208
+ private _checkConditions(conditions: Record<string, unknown>, context: Context | null): boolean {
209
+ // Null context cannot satisfy any conditions
210
+ if (context === null) return false;
211
+
212
+ // identity_types: caller's identity.type must be in the list
213
+ if ('identity_types' in conditions) {
214
+ const types = conditions['identity_types'] as string[];
215
+ if (context.identity === null || !types.includes(context.identity.type)) return false;
216
+ }
217
+
218
+ // roles: caller's identity must have at least one matching role (OR within roles, AND with other conditions)
219
+ if ('roles' in conditions) {
220
+ const roles = conditions['roles'] as string[];
221
+ if (context.identity === null) return false;
222
+ const identityRoles = new Set(context.identity.roles);
223
+ if (!roles.some((r) => identityRoles.has(r))) return false;
224
+ }
225
+
226
+ // max_call_depth: call chain length must not exceed the limit
227
+ if ('max_call_depth' in conditions) {
228
+ const maxDepth = conditions['max_call_depth'] as number;
229
+ if (context.callChain.length > maxDepth) return false;
230
+ }
231
+
232
+ return true;
233
+ }
234
+ ```
235
+
236
+ ### 7. Run full test suite and type-check
237
+
238
+ Run `tsc --noEmit` and `vitest` to confirm everything passes.
239
+
240
+ ## Acceptance Criteria
241
+
242
+ - [x] `_checkConditions()` returns `false` when context is `null`
243
+ - [x] `identity_types` condition checks `context.identity.type` is in the allowed list
244
+ - [x] `identity_types` returns `false` when `context.identity` is `null`
245
+ - [x] `roles` condition checks that at least one role in the condition list matches a role in `context.identity.roles` (OR within roles)
246
+ - [x] `roles` returns `false` when `context.identity` is `null`
247
+ - [x] `roles` uses `Set` for efficient lookup on the identity's roles
248
+ - [x] `max_call_depth` condition checks `context.callChain.length <= maxDepth`
249
+ - [x] Multiple conditions use AND logic: all present conditions must pass
250
+ - [x] Unknown condition keys are silently ignored (forward-compatible)
251
+ - [x] All tests pass with `vitest`; zero errors from `tsc --noEmit`
252
+
253
+ ## Dependencies
254
+
255
+ - **acl-rule** -- ACLRule interface (conditions field definition)
256
+
257
+ ## Estimated Time
258
+
259
+ 2 hours