@agenthippo-ai/agenthippo 0.2.3-dataplane → 1.110.9

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 (130) hide show
  1. package/out/analytics/dashboard/provider.js +13 -2
  2. package/out/analytics/dashboard/webview/panel.js +3 -2
  3. package/out/analytics/identity.js +0 -0
  4. package/out/analytics/service.js +23 -25
  5. package/out/analytics/sessionEvents.js +98 -23
  6. package/out/auth/authBaseUrl.js +59 -0
  7. package/out/auth/bootstrapApply.js +9 -10
  8. package/out/auth/brokerClient.js +48 -14
  9. package/out/auth/provider.js +8 -21
  10. package/out/auth/sessionStore.js +3 -40
  11. package/out/auth/signInFlow.js +2 -1
  12. package/out/auth-broker/config.js +50 -5
  13. package/out/auth-broker/server.js +122 -26
  14. package/out/auth-broker/store.js +25 -24
  15. package/out/authority/warrant.js +206 -0
  16. package/out/branding.js +27 -1
  17. package/out/cli/commands/conformance.js +249 -0
  18. package/out/cli/commands/data-plane.js +67 -0
  19. package/out/cli/commands/deploy.js +1 -0
  20. package/out/cli/commands/gateway.js +4 -0
  21. package/out/cli/commands/pack.js +182 -3
  22. package/out/cli/commands/sandbox.js +332 -0
  23. package/out/cli/commands/serve.js +875 -52
  24. package/out/cli/commands/store.js +12 -4
  25. package/out/cli/data-plane/gateway.js +28 -5
  26. package/out/cli/data-plane/index.js +17 -2
  27. package/out/cli/data-plane/registry.js +9 -0
  28. package/out/cli/data-plane/remote.js +106 -0
  29. package/out/cli/data-plane/sidecar.js +161 -0
  30. package/out/cli/deploy/layers/identity.js +85 -4
  31. package/out/cli/deploy-init.js +89 -24
  32. package/out/cli/deps.js +106 -2
  33. package/out/cli/idp-init.js +35 -0
  34. package/out/cli/index.js +155 -16
  35. package/out/cli/pack-install-ref.js +15 -0
  36. package/out/cli/pack-loader.js +8 -1
  37. package/out/cli/pack-runtime.js +61 -0
  38. package/out/cli/runtime.js +35 -1
  39. package/out/cli/serve-hardening.js +80 -3
  40. package/out/cli/utils.js +12 -1
  41. package/out/engines/base.js +32 -3
  42. package/out/engines/claude.js +33 -15
  43. package/out/engines/codex.js +110 -26
  44. package/out/engines/custom.js +8 -0
  45. package/out/evidence/sessionShip.js +610 -0
  46. package/out/extension.js +11 -2
  47. package/out/gateway/bridge.js +40 -2
  48. package/out/gateway/client.js +34 -1
  49. package/out/gateway/installSource.js +68 -0
  50. package/out/gateway/lifecycle.js +185 -51
  51. package/out/gateway/outboundPaths.js +4 -1
  52. package/out/gateway/secretsPreflight.js +90 -0
  53. package/out/gateway/service.js +7 -2
  54. package/out/headless/index.js +17 -1
  55. package/out/live-e2e/mcp-demo/server.mjs +32 -0
  56. package/out/mcp.js +30 -0
  57. package/out/pack/caps.js +271 -0
  58. package/out/pack/governor.js +309 -0
  59. package/out/pack/lease-schema.js +270 -0
  60. package/out/pack/lease.js +640 -0
  61. package/out/pack/reconcile.js +217 -0
  62. package/out/pack/signature.js +839 -0
  63. package/out/remote/handleRemoteChat.js +44 -3
  64. package/out/remote/remoteTrust.js +277 -0
  65. package/out/remote/serveClient.js +52 -5
  66. package/out/runner/host.js +131 -0
  67. package/out/runner/protocol.js +108 -0
  68. package/out/runner/remoteEngine.js +130 -0
  69. package/out/runtime/interfaces/edit-tracker.js +2 -0
  70. package/out/runtime/vscode/vscode-edit-tracker.js +2 -0
  71. package/out/sandbox/containerDriver.js +570 -0
  72. package/out/sandbox/processDriver.js +315 -0
  73. package/out/sandbox/sandboxRunner.js +191 -0
  74. package/out/sandbox/support.js +301 -0
  75. package/out/sandbox/types.js +55 -0
  76. package/out/scripts/agentide-litellm.sh +67 -5
  77. package/out/scripts/agentide_litellm_hooks_v1.py +182 -21
  78. package/out/scripts/analytics/agentide-litellm-otel.config.yaml +94 -132
  79. package/out/scripts/analytics/setup-analytics.ps1 +37 -13
  80. package/out/scripts/analytics/setup-analytics.sh +93 -13
  81. package/out/scripts/analytics/start-analytics.sh +86 -14
  82. package/out/scripts/gateway/setup-gateway.sh +72 -32
  83. package/out/shared/models.js +11 -110
  84. package/out/spotlight/install.js +7 -1
  85. package/out/store/index.js +41 -10
  86. package/out/sync.js +3 -1
  87. package/out/test/analytics.test.js +162 -23
  88. package/out/test/auth-baseurl.test.js +132 -0
  89. package/out/test/auth-bootstrapApply.test.js +27 -6
  90. package/out/test/auth-broker-hardening.test.js +227 -0
  91. package/out/test/auth-broker.test.js +59 -9
  92. package/out/test/branding.test.js +13 -0
  93. package/out/test/caps-governor.test.js +455 -0
  94. package/out/test/codex-new-file-survival.test.js +119 -0
  95. package/out/test/configuration-scopes.test.js +131 -0
  96. package/out/test/data-plane.test.js +67 -0
  97. package/out/test/deploy-init.test.js +40 -0
  98. package/out/test/gateway-client.test.js +28 -0
  99. package/out/test/gateway-install-source.test.js +111 -0
  100. package/out/test/gateway-lifecycle.test.js +1 -1
  101. package/out/test/gateway-outbound.test.js +7 -0
  102. package/out/test/gateway-secrets-preflight.test.js +127 -0
  103. package/out/test/gateway-session-routing.test.js +18 -0
  104. package/out/test/governor-hardening.test.js +217 -0
  105. package/out/test/headless-sync.test.js +22 -0
  106. package/out/test/lease-signature.test.js +357 -0
  107. package/out/test/lease-trust-root.test.js +273 -0
  108. package/out/test/lease-validation.test.js +169 -0
  109. package/out/test/lease.test.js +114 -0
  110. package/out/test/mcp.test.js +27 -1
  111. package/out/test/pack-admission.test.js +216 -0
  112. package/out/test/pack-digest-parity.test.js +140 -0
  113. package/out/test/pack-reconcile.test.js +183 -0
  114. package/out/test/pack-signature-artifact.test.js +103 -0
  115. package/out/test/pack-signature.test.js +176 -0
  116. package/out/test/pack-trust-root.test.js +202 -0
  117. package/out/test/remote-trust.test.js +242 -0
  118. package/out/test/runner-protocol.test.js +249 -0
  119. package/out/test/sandbox-driver.test.js +553 -0
  120. package/out/test/sandbox-hardening.test.js +395 -0
  121. package/out/test/sandbox-runner.test.js +343 -0
  122. package/out/test/serve-hardening.test.js +45 -6
  123. package/out/test/serveClient.test.js +6 -5
  124. package/out/test/sessionShip.test.js +560 -0
  125. package/out/test/spotlightPublish.test.js +28 -0
  126. package/out/test/store-install-safe.test.js +69 -0
  127. package/out/test/tls-bypass.test.js +90 -0
  128. package/out/test/warrant.test.js +138 -0
  129. package/out/utils.js +46 -9
  130. package/package.json +1 -1
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Governor hardening: kill that means kill (or says it does not), budgets that survive a kill,
4
+ * session stops that survive session_id rotation, and one constant for the poll interval.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ require("mocha");
41
+ const assert = __importStar(require("assert"));
42
+ const governor_1 = require("../pack/governor");
43
+ const lease_1 = require("../pack/lease");
44
+ function fakeSandboxes(initial = [], supportsInFlightTermination = true) {
45
+ const state = {
46
+ live: [...initial],
47
+ destroyed: [],
48
+ revoked: [],
49
+ supportsInFlightTermination,
50
+ sandboxes() { return state.live.map((sessionKey) => ({ sessionKey, sandboxId: `sandbox-${sessionKey}` })); },
51
+ async destroySession(sessionKey) {
52
+ state.destroyed.push(sessionKey);
53
+ state.live = state.live.filter((s) => s !== sessionKey);
54
+ },
55
+ async revokeRoute(sessionKey, what) {
56
+ state.revoked.push({ sessionKey, what });
57
+ },
58
+ };
59
+ return state;
60
+ }
61
+ const liveLease = (over = {}) => ({
62
+ pack: 'joker1',
63
+ enabled: true,
64
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
65
+ ...over,
66
+ });
67
+ suite('kill never silently degrades to drain', () => {
68
+ test('without a sandbox driver, kill is REPORTED as the drain it actually is', async () => {
69
+ const lines = [];
70
+ const events = [];
71
+ const sandboxes = fakeSandboxes([], false);
72
+ const gov = (0, governor_1.createGovernor)({
73
+ caps: {}, sandboxes, pack: 'joker1',
74
+ getLease: async () => liveLease({ deny: [{ scope: 'session', match: 's1', mode: 'kill' }] }),
75
+ logger: { info: (m) => lines.push(m), warn: (m) => lines.push(m) },
76
+ audit: (event, fields) => events.push({ event, fields }),
77
+ });
78
+ await gov.refresh();
79
+ assert.ok(lines.some((l) => /DEGRADED TO DRAIN/.test(l)), 'the console must not claim kill when it means drain');
80
+ assert.ok(events.some((e) => e.event === 'deny_kill_degraded' && e.fields.effectiveMode === 'drain'));
81
+ // The substance still holds: the NEXT turn is refused.
82
+ assert.strictEqual((await gov.admitTurn('s1')).allowed, false);
83
+ });
84
+ test('the warning is once per rule, not once per poll', async () => {
85
+ const lines = [];
86
+ const sandboxes = fakeSandboxes([], false);
87
+ const gov = (0, governor_1.createGovernor)({
88
+ caps: {}, sandboxes, pack: 'joker1',
89
+ getLease: async () => liveLease({ deny: [{ scope: 'session', match: 's1', mode: 'kill' }] }),
90
+ logger: { info: (m) => lines.push(m), warn: (m) => lines.push(m) },
91
+ });
92
+ await gov.refresh();
93
+ await gov.refresh();
94
+ await gov.refresh();
95
+ assert.strictEqual(lines.filter((l) => /DEGRADED TO DRAIN/.test(l)).length, 1);
96
+ });
97
+ test('with a driver, kill still ends running work', async () => {
98
+ const sandboxes = fakeSandboxes(['s1'], true);
99
+ const gov = (0, governor_1.createGovernor)({
100
+ caps: {}, sandboxes, pack: 'joker1',
101
+ getLease: async () => liveLease({ deny: [{ scope: 'session', match: 's1', mode: 'kill' }] }),
102
+ });
103
+ await gov.refresh();
104
+ assert.deepStrictEqual(sandboxes.destroyed, ['s1']);
105
+ });
106
+ test('the kill switch itself says so when it can only refuse new work', async () => {
107
+ const lines = [];
108
+ const gov = (0, governor_1.createGovernor)({
109
+ caps: {}, sandboxes: fakeSandboxes([], false),
110
+ logger: { info: (m) => lines.push(m), warn: (m) => lines.push(m) },
111
+ });
112
+ await gov.killAll('drill');
113
+ assert.ok(lines.some((l) => /nothing running can be stopped/.test(l)));
114
+ });
115
+ test('effectiveDenyMode is the one place that decides', () => {
116
+ assert.strictEqual((0, governor_1.effectiveDenyMode)('kill', true), 'kill');
117
+ assert.strictEqual((0, governor_1.effectiveDenyMode)('kill', false), 'drain');
118
+ assert.strictEqual((0, governor_1.effectiveDenyMode)('drain', false), 'drain');
119
+ assert.strictEqual((0, governor_1.effectiveDenyMode)(undefined, false), undefined);
120
+ });
121
+ });
122
+ suite('a kill does not hand back budgets', () => {
123
+ /**
124
+ * `killAll` called `meter.forget` on every session it killed, so a kill-then-restore (a billing
125
+ * hold lifted, a drill, an operator toggling the switch) gave every session a brand-new turn and
126
+ * duration budget. The cheapest way past a cap was to trip the kill switch. The cap-breach path
127
+ * deliberately did NOT do this, and explains why.
128
+ */
129
+ test('a session over its turn cap is still over it after a kill and a restore', async () => {
130
+ const sandboxes = fakeSandboxes(['s1']);
131
+ let lease = liveLease({ caps: { maxTurnsPerSession: 2 } });
132
+ const gov = (0, governor_1.createGovernor)({ caps: {}, sandboxes, getLease: async () => lease });
133
+ await gov.refresh();
134
+ assert.ok((await gov.admitTurn('s1')).allowed);
135
+ gov.recordTurn('s1');
136
+ assert.ok((await gov.admitTurn('s1')).allowed);
137
+ gov.recordTurn('s1');
138
+ lease = liveLease({ enabled: false, caps: { maxTurnsPerSession: 2 } });
139
+ await gov.refresh();
140
+ lease = liveLease({ caps: { maxTurnsPerSession: 2 } });
141
+ await gov.refresh();
142
+ const after = await gov.admitTurn('s1');
143
+ assert.strictEqual(after.allowed, false, 'the kill must not renew the budget');
144
+ assert.match(after.reason ?? '', /turn cap reached/);
145
+ });
146
+ test('a deny(kill) does not renew the budget either', async () => {
147
+ const sandboxes = fakeSandboxes(['s1']);
148
+ let lease = liveLease({ caps: { maxTurnsPerSession: 1 } });
149
+ const gov = (0, governor_1.createGovernor)({ caps: {}, sandboxes, pack: 'joker1', getLease: async () => lease });
150
+ await gov.refresh();
151
+ assert.ok((await gov.admitTurn('s1')).allowed);
152
+ gov.recordTurn('s1');
153
+ lease = liveLease({ caps: { maxTurnsPerSession: 1 }, deny: [{ scope: 'session', match: 's1', mode: 'kill' }] });
154
+ await gov.refresh();
155
+ lease = liveLease({ caps: { maxTurnsPerSession: 1 } });
156
+ await gov.refresh();
157
+ const after = await gov.admitTurn('s1');
158
+ assert.strictEqual(after.allowed, false);
159
+ assert.match(after.reason ?? '', /turn cap reached/);
160
+ });
161
+ });
162
+ suite('session-scoped stops and the client-supplied session_id', () => {
163
+ test('a session rule bound to a user does not match another account replaying the id', () => {
164
+ const lease = liveLease({ deny: [{ scope: 'session', match: 'ticket-42', mode: 'kill', user: 'alice@x.com' }] });
165
+ assert.ok((0, lease_1.denyVerdict)(lease, { sessionKey: 'uH--ticket-42', pack: 'joker1', userId: 'alice@x.com' }).denied);
166
+ assert.ok(!(0, lease_1.denyVerdict)(lease, { sessionKey: 'uH--ticket-42', pack: 'joker1', userId: 'mallory@x.com' }).denied);
167
+ });
168
+ test('rotating session_id does not escape a session stop once the user is known', async () => {
169
+ const sandboxes = fakeSandboxes();
170
+ let lease = liveLease();
171
+ const gov = (0, governor_1.createGovernor)({ caps: {}, sandboxes, pack: 'joker1', getLease: async () => lease });
172
+ // The turn path teaches the governor which user 'ticket-42' belongs to.
173
+ await gov.admitTurn('uH--ticket-42', 'alice@x.com');
174
+ lease = liveLease({ deny: [{ scope: 'session', match: 'ticket-42', mode: 'kill', reason: 'runaway' }] });
175
+ await gov.refresh();
176
+ assert.strictEqual((await gov.admitTurn('uH--ticket-42', 'alice@x.com')).allowed, false, 'the named session');
177
+ const rotated = await gov.admitTurn('uH--brand-new-id', 'alice@x.com');
178
+ assert.strictEqual(rotated.allowed, false, 'a fresh session_id from the same user must not escape');
179
+ assert.strictEqual((await gov.admitTurn('uH--someone-else', 'bob@x.com')).allowed, true, 'and nobody else is caught');
180
+ });
181
+ test('followUser: false keeps a genuinely id-only stop', async () => {
182
+ const sandboxes = fakeSandboxes();
183
+ let lease = liveLease();
184
+ const gov = (0, governor_1.createGovernor)({ caps: {}, sandboxes, pack: 'joker1', getLease: async () => lease });
185
+ await gov.admitTurn('uH--ticket-42', 'alice@x.com');
186
+ lease = liveLease({ deny: [{ scope: 'session', match: 'ticket-42', mode: 'drain', followUser: false }] });
187
+ await gov.refresh();
188
+ assert.strictEqual((await gov.admitTurn('uH--ticket-42', 'alice@x.com')).allowed, false);
189
+ assert.strictEqual((await gov.admitTurn('uH--another', 'alice@x.com')).allowed, true);
190
+ });
191
+ test('with no verified identity the stop is id-only — the documented limitation', () => {
192
+ const lease = liveLease({ deny: [{ scope: 'session', match: 'anon-1', mode: 'kill' }] });
193
+ assert.ok((0, lease_1.denyVerdict)(lease, { sessionKey: 'anon-1', pack: 'joker1' }).denied);
194
+ assert.ok(!(0, lease_1.denyVerdict)(lease, { sessionKey: 'anon-2', pack: 'joker1' }).denied);
195
+ });
196
+ test('resolveFollowedUsers ignores spent rules and respects explicit user binding', () => {
197
+ const past = Math.floor(Date.now() / 1000) - 1;
198
+ const sessions = new Map([['uH--t42', 'alice@x.com']]);
199
+ assert.strictEqual((0, lease_1.resolveFollowedUsers)(liveLease({ deny: [{ scope: 'session', match: 't42', mode: 'kill', until: past }] }), sessions).size, 0);
200
+ assert.strictEqual((0, lease_1.resolveFollowedUsers)(liveLease({ deny: [{ scope: 'session', match: 't42', mode: 'kill', user: 'bob@x.com' }] }), sessions).size, 0, 'a rule bound to bob must not widen itself to alice');
201
+ });
202
+ });
203
+ suite('poll interval and the advertised kill latency', () => {
204
+ test('one constant drives poll and cache — they can no longer disagree', () => {
205
+ assert.strictEqual((0, lease_1.resolveLeasePollSeconds)(undefined), lease_1.DEFAULT_LEASE_POLL_SECONDS);
206
+ assert.strictEqual((0, lease_1.leaseCacheSecondsFor)((0, lease_1.resolveLeasePollSeconds)(undefined)), lease_1.DEFAULT_LEASE_POLL_SECONDS);
207
+ });
208
+ test('the printed kill latency is the TRUE worst case (poll + cache), not the poll alone', () => {
209
+ assert.strictEqual((0, lease_1.effectiveKillLatencySeconds)(30), 60);
210
+ assert.strictEqual((0, lease_1.effectiveKillLatencySeconds)(10), 20);
211
+ });
212
+ test('a nonsense or tiny poll is floored, not honoured', () => {
213
+ assert.strictEqual((0, lease_1.resolveLeasePollSeconds)(0), 5);
214
+ assert.strictEqual((0, lease_1.resolveLeasePollSeconds)(-1), 5);
215
+ assert.strictEqual((0, lease_1.resolveLeasePollSeconds)(NaN), lease_1.DEFAULT_LEASE_POLL_SECONDS);
216
+ });
217
+ });
@@ -51,6 +51,8 @@ const os = __importStar(require("os"));
51
51
  const sync_1 = require("../headless/sync");
52
52
  const shared_1 = require("../shared");
53
53
  const paths_1 = require("../agentpack/paths");
54
+ const branding_1 = require("../branding");
55
+ const utils_1 = require("../utils");
54
56
  // -------------------------------------------------------------------------
55
57
  // Test Helpers
56
58
  // -------------------------------------------------------------------------
@@ -175,6 +177,26 @@ suite('Headless Sync - syncPackToWorkspace', () => {
175
177
  assert.ok(content.includes('.claude'), '.gitignore should include .claude');
176
178
  assert.ok(content.includes('.codex'), '.gitignore should include .codex');
177
179
  });
180
+ test('creates .gitignore with custom engine workspace dirs', async () => {
181
+ const cursorEngineDir = path.join(workspaceRoot, branding_1.AGENTIDE_DIR_NAME, 'engines', 'cursor');
182
+ await fs_1.promises.mkdir(cursorEngineDir, { recursive: true });
183
+ await fs_1.promises.writeFile(path.join(cursorEngineDir, 'engine.manifest.json'), JSON.stringify({
184
+ version: 2,
185
+ id: 'cursor',
186
+ entry: './engine.mjs',
187
+ workspaceSync: {
188
+ enabled: true,
189
+ dir: '.cursor',
190
+ rulesFile: 'CURSOR.md',
191
+ includeSkills: true,
192
+ includeRules: true,
193
+ },
194
+ promptInjection: { mode: 'none' },
195
+ }));
196
+ await (0, utils_1.ensureWorkspaceGitAndGitignore)(workspaceRoot, logger);
197
+ const content = await fs_1.promises.readFile(path.join(workspaceRoot, '.gitignore'), 'utf8');
198
+ assert.ok(content.includes('.cursor'), '.gitignore should include custom engine workspace dir');
199
+ });
178
200
  test('handles empty pack (no AGENTS.md)', async () => {
179
201
  // Pack with no files should not throw
180
202
  await (0, sync_1.syncPackToWorkspace)(workspaceRoot, packPath, 'test-pack', 'claude', logger);
@@ -0,0 +1,357 @@
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Signed leases, lease validation, and the staleness ceiling.
4
+ *
5
+ * The whole governance story — kill switch, deny rules, caps, version pin, pack signing — was
6
+ * rooted in an UNSIGNED document fetched over an unauthenticated channel and `JSON.parse`d
7
+ * straight into policy. Anyone who could answer AGENTHIPPO_LEASE_URL could lift the kill switch;
8
+ * anyone who could drop packets to it could keep a revoked fleet running indefinitely.
9
+ *--------------------------------------------------------------------------------------------*/
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ require("mocha");
45
+ const assert = __importStar(require("assert"));
46
+ const warrant_1 = require("../authority/warrant");
47
+ const lease_1 = require("../pack/lease");
48
+ const key = (0, warrant_1.generateWarrantKeypair)('lease-k1');
49
+ const keys = { 'lease-k1': key.publicKeyPem };
50
+ const NOW = 1_800_000_000;
51
+ const lease = { pack: 'analyst', expiresAt: NOW + 3600, enabled: true };
52
+ const bodyResponse = (text) => ({
53
+ ok: true,
54
+ status: 200,
55
+ text: async () => text,
56
+ json: async () => JSON.parse(text),
57
+ });
58
+ const collectLogs = () => {
59
+ const lines = [];
60
+ return { lines, logger: { info: (m) => lines.push(m), warn: (m) => lines.push(m) } };
61
+ };
62
+ suite('signed lease — envelope verification', () => {
63
+ test('a lease signed by a trusted key verifies, and the policy survives intact', () => {
64
+ const token = (0, lease_1.signLease)(lease, key, { instanceId: 'inst-1', nowSeconds: NOW });
65
+ const res = (0, lease_1.verifySignedLease)(token, keys, { instanceId: 'inst-1', nowSeconds: NOW });
66
+ assert.ok(res.ok, res.ok ? '' : res.reason);
67
+ assert.deepStrictEqual(res.lease, lease);
68
+ });
69
+ test('an empty keyring never verifies — the same rule packs get', () => {
70
+ const token = (0, lease_1.signLease)(lease, key, { nowSeconds: NOW });
71
+ const res = (0, lease_1.verifySignedLease)(token, {}, { nowSeconds: NOW });
72
+ assert.strictEqual(res.ok, false);
73
+ });
74
+ test('a key we do not trust is refused, never trusted-on-first-use', () => {
75
+ const stranger = (0, warrant_1.generateWarrantKeypair)('evil');
76
+ const token = (0, lease_1.signLease)({ ...lease, enabled: true }, stranger, { nowSeconds: NOW });
77
+ const res = (0, lease_1.verifySignedLease)(token, keys, { nowSeconds: NOW });
78
+ assert.strictEqual(res.ok, false);
79
+ assert.match(res.reason, /unknown kid/);
80
+ });
81
+ test('a tampered payload breaks the signature', () => {
82
+ const token = (0, lease_1.signLease)({ ...lease, enabled: false }, key, { nowSeconds: NOW });
83
+ const [h, , s] = token.split('.');
84
+ const forged = Buffer.from(JSON.stringify({
85
+ lease: { ...lease, enabled: true }, aud: '*', sub: 'analyst', iat: NOW, exp: NOW + 300,
86
+ })).toString('base64url');
87
+ const res = (0, lease_1.verifySignedLease)(`${h}.${forged}.${s}`, keys, { nowSeconds: NOW });
88
+ assert.strictEqual(res.ok, false);
89
+ assert.match(res.reason, /bad signature/);
90
+ });
91
+ test('a lease for another instance does not verify here (audience binding)', () => {
92
+ const token = (0, lease_1.signLease)(lease, key, { instanceId: 'inst-other', nowSeconds: NOW });
93
+ const res = (0, lease_1.verifySignedLease)(token, keys, { instanceId: 'inst-1', nowSeconds: NOW });
94
+ assert.strictEqual(res.ok, false);
95
+ assert.match(res.reason, /for instance inst-other/);
96
+ });
97
+ test('a fleet-wide (*) lease is accepted by any instance', () => {
98
+ const token = (0, lease_1.signLease)(lease, key, { nowSeconds: NOW });
99
+ assert.ok((0, lease_1.verifySignedLease)(token, keys, { instanceId: 'inst-1', nowSeconds: NOW }).ok);
100
+ });
101
+ test('an expired envelope is refused even though the LEASE has not expired', () => {
102
+ const token = (0, lease_1.signLease)(lease, key, { nowSeconds: NOW, ttlSeconds: 60 });
103
+ const res = (0, lease_1.verifySignedLease)(token, keys, { nowSeconds: NOW + 3600 });
104
+ assert.strictEqual(res.ok, false);
105
+ assert.match(res.reason, /envelope expired/);
106
+ });
107
+ test('envelope TTL is capped — a lease refresh must not become a credential', () => {
108
+ const token = (0, lease_1.signLease)(lease, key, { nowSeconds: NOW, ttlSeconds: 99_999 });
109
+ // The cap is applied at signing; verification also refuses anything longer.
110
+ const res = (0, lease_1.verifySignedLease)(token, keys, { nowSeconds: NOW + lease_1.MAX_LEASE_ENVELOPE_TTL_SECONDS - 1 });
111
+ assert.ok(res.ok, 'inside the capped lifetime it is still valid');
112
+ assert.strictEqual((0, lease_1.verifySignedLease)(token, keys, { nowSeconds: NOW + lease_1.MAX_LEASE_ENVELOPE_TTL_SECONDS + 120 }).ok, false);
113
+ });
114
+ /**
115
+ * The binding that matters most. `governor.checkLease` treats a restored lease as "lease
116
+ * restored — accepting turns again", so replaying an older `enabled: true` envelope does not
117
+ * merely delay a kill: it LIFTS one that has already latched.
118
+ */
119
+ test('an older envelope is refused as a rollback replay', () => {
120
+ const older = (0, lease_1.signLease)(lease, key, { nowSeconds: NOW });
121
+ const newer = (0, lease_1.signLease)({ ...lease, enabled: false }, key, { nowSeconds: NOW + 100 });
122
+ assert.ok((0, lease_1.verifySignedLease)(newer, keys, { nowSeconds: NOW + 100 }).ok);
123
+ const replay = (0, lease_1.verifySignedLease)(older, keys, { nowSeconds: NOW + 120, minIat: NOW + 100 });
124
+ assert.strictEqual(replay.ok, false);
125
+ assert.match(replay.reason, /replay\/rollback/);
126
+ });
127
+ test('a pack signature cannot be replayed as a lease under the same key (typ binding)', () => {
128
+ // A JWT-typed token signed by the same key must not pass as a lease envelope.
129
+ const notALease = require('../authority/warrant').signCompactJws({ typ: 'JWT', kid: 'lease-k1' }, { lease, aud: '*', sub: 'analyst', iat: NOW, exp: NOW + 300 }, key.privateKeyPem);
130
+ const res = (0, lease_1.verifySignedLease)(notALease, keys, { nowSeconds: NOW });
131
+ assert.strictEqual(res.ok, false);
132
+ assert.match(res.reason, /unexpected token type/);
133
+ });
134
+ test('a signed lease carrying a malformed policy is refused, not half-adopted', () => {
135
+ const token = (0, lease_1.signLease)({ ...lease, caps: { maxTurnsPerSession: 'lots' } }, key, { nowSeconds: NOW });
136
+ const res = (0, lease_1.verifySignedLease)(token, keys, { nowSeconds: NOW });
137
+ assert.strictEqual(res.ok, false);
138
+ assert.match(res.reason, /malformed/);
139
+ });
140
+ });
141
+ suite('requireSignedLease is tighten-only', () => {
142
+ test('either side may demand it; neither may waive the other', () => {
143
+ assert.strictEqual((0, lease_1.requireSignedLease)(undefined, undefined), false);
144
+ assert.strictEqual((0, lease_1.requireSignedLease)(true, undefined), true);
145
+ assert.strictEqual((0, lease_1.requireSignedLease)(undefined, true), true);
146
+ assert.strictEqual((0, lease_1.requireSignedLease)(false, true), true);
147
+ });
148
+ });
149
+ suite('lease source — signature enforcement', () => {
150
+ test('a signed lease is accepted and reported as signed', async () => {
151
+ const token = (0, lease_1.signLease)(lease, key, { instanceId: 'inst-1', nowSeconds: NOW });
152
+ const src = (0, lease_1.createLeaseSource)({
153
+ url: 'https://plane.example/lease',
154
+ cacheSeconds: 0,
155
+ instanceId: 'inst-1',
156
+ signingKeys: () => keys,
157
+ fetchImpl: (async () => bodyResponse(JSON.stringify({ lease: token }))),
158
+ });
159
+ assert.deepStrictEqual(await src.get(NOW), lease);
160
+ assert.strictEqual(src.status(NOW).signed, true);
161
+ });
162
+ test('a bare compact-JWS body works too', async () => {
163
+ const token = (0, lease_1.signLease)(lease, key, { nowSeconds: NOW });
164
+ const src = (0, lease_1.createLeaseSource)({
165
+ url: 'https://plane.example/lease',
166
+ cacheSeconds: 0,
167
+ signingKeys: () => keys,
168
+ fetchImpl: (async () => bodyResponse(token)),
169
+ });
170
+ assert.deepStrictEqual(await src.get(NOW), lease);
171
+ });
172
+ test('an unsigned lease still works, and says so LOUDLY, when signing is not required', async () => {
173
+ const { lines, logger } = collectLogs();
174
+ const src = (0, lease_1.createLeaseSource)({
175
+ url: 'https://plane.example/lease',
176
+ cacheSeconds: 0,
177
+ logger,
178
+ fetchImpl: (async () => bodyResponse(JSON.stringify(lease))),
179
+ });
180
+ assert.deepStrictEqual(await src.get(NOW), lease);
181
+ assert.ok(lines.some((l) => /UNSIGNED lease/.test(l)), 'back-compat must not be silent');
182
+ });
183
+ test('an unsigned lease is REFUSED when signing is required — and the last good lease stands', async () => {
184
+ const token = (0, lease_1.signLease)(lease, key, { nowSeconds: NOW });
185
+ let signed = true;
186
+ const src = (0, lease_1.createLeaseSource)({
187
+ url: 'https://plane.example/lease',
188
+ cacheSeconds: 0,
189
+ requireSignedLease: true,
190
+ signingKeys: () => keys,
191
+ fetchImpl: (async () => bodyResponse(signed ? token : JSON.stringify({ ...lease, enabled: true }))),
192
+ });
193
+ assert.deepStrictEqual(await src.get(NOW), lease);
194
+ signed = false;
195
+ // A downgrade to unsigned must not install new policy.
196
+ const after = await src.get(NOW + 1);
197
+ assert.deepStrictEqual(after, lease, 'the verified lease is kept; the unsigned one is rejected');
198
+ });
199
+ test('lease.requireSignedLease LATCHES — a later unsigned response cannot undo it', async () => {
200
+ const demanding = (0, lease_1.signLease)({ ...lease, requireSignedLease: true }, key, { nowSeconds: NOW });
201
+ let phase = 'signed';
202
+ const { lines, logger } = collectLogs();
203
+ const src = (0, lease_1.createLeaseSource)({
204
+ url: 'https://plane.example/lease',
205
+ cacheSeconds: 0,
206
+ logger,
207
+ signingKeys: () => keys,
208
+ fetchImpl: (async () => bodyResponse(phase === 'signed' ? demanding : JSON.stringify({ ...lease, enabled: true, version: '9.9.9' }))),
209
+ });
210
+ const first = await src.get(NOW);
211
+ assert.strictEqual(first?.requireSignedLease, true);
212
+ phase = 'unsigned';
213
+ const second = await src.get(NOW + 1);
214
+ assert.strictEqual(second?.version, undefined, 'the unsigned downgrade must not take effect');
215
+ assert.ok(lines.some((l) => /signed lease is required/.test(l)));
216
+ });
217
+ });
218
+ /**
219
+ * The insecure-channel warning, which for one shape did not exist.
220
+ *
221
+ * `createLeaseSource` carried a `leaseUrlRefused` flag, declared and read but never assigned — its
222
+ * comment promised "we never poll it at all", a refusal the file elsewhere argues explicitly
223
+ * against (refusing to poll a plaintext lease URL disables the kill switch, which fails OPEN).
224
+ * Worse, the warning next to it was guarded by `else if (!signingRequired())`, so the one operator
225
+ * who most needed to hear it — one who has demanded signed leases and therefore believes the
226
+ * channel is accounted for — was the only one who heard nothing at all.
227
+ */
228
+ suite('lease source — a plaintext lease URL warns, always, and never stops the poll', () => {
229
+ // An explicit empty env: the ambient ALLOW_INSECURE_TRUST_ROOT escape hatch must not decide
230
+ // what these tests observe.
231
+ const noEnv = {};
232
+ test('http + signing NOT required — warns, and keeps polling', async () => {
233
+ const { lines, logger } = collectLogs();
234
+ const src = (0, lease_1.createLeaseSource)({
235
+ url: 'http://plane.example/lease',
236
+ cacheSeconds: 0,
237
+ env: noEnv,
238
+ logger,
239
+ fetchImpl: (async () => bodyResponse(JSON.stringify(lease))),
240
+ });
241
+ assert.deepStrictEqual(await src.get(NOW), lease, 'refusing to poll would disable the kill switch');
242
+ assert.ok(lines.some((l) => /INSECURE LEASE CHANNEL/.test(l)));
243
+ });
244
+ test('http + signing REQUIRED — still warns; this was the silent case', async () => {
245
+ const token = (0, lease_1.signLease)(lease, key, { nowSeconds: NOW });
246
+ const { lines, logger } = collectLogs();
247
+ const src = (0, lease_1.createLeaseSource)({
248
+ url: 'http://plane.example/lease',
249
+ cacheSeconds: 0,
250
+ env: noEnv,
251
+ logger,
252
+ requireSignedLease: true,
253
+ signingKeys: () => keys,
254
+ fetchImpl: (async () => bodyResponse(token)),
255
+ });
256
+ assert.deepStrictEqual(await src.get(NOW), lease, 'a signed lease over http is still polled');
257
+ const warning = lines.find((l) => /INSECURE LEASE CHANNEL/.test(l));
258
+ assert.ok(warning, 'signing-required over plaintext must not be the quiet case');
259
+ // And it must say what signing does NOT buy, rather than repeating "set requireSignedLease"
260
+ // at an operator who already did.
261
+ assert.match(warning, /not a substitute for https/i);
262
+ });
263
+ test('https warns about nothing', async () => {
264
+ const { lines, logger } = collectLogs();
265
+ const src = (0, lease_1.createLeaseSource)({
266
+ url: 'https://plane.example/lease',
267
+ cacheSeconds: 0,
268
+ env: noEnv,
269
+ logger,
270
+ fetchImpl: (async () => bodyResponse(JSON.stringify(lease))),
271
+ });
272
+ assert.deepStrictEqual(await src.get(NOW), lease);
273
+ assert.ok(!lines.some((l) => /INSECURE LEASE CHANNEL/.test(l)));
274
+ });
275
+ });
276
+ suite('lease source — a garbled document is not policy', () => {
277
+ const badBodies = [
278
+ ['non-numeric cap', JSON.stringify({ ...lease, caps: { maxTurnsPerSession: 'lots' } })],
279
+ ['negative cap', JSON.stringify({ ...lease, caps: { maxSessionSeconds: -5 } })],
280
+ ['string enabled', JSON.stringify({ ...lease, enabled: 'false' })],
281
+ ['unknown deny scope', JSON.stringify({ ...lease, deny: [{ scope: 'tenant', match: 'x', mode: 'kill' }] })],
282
+ ['not an object', '"hello"'],
283
+ ['not JSON at all', '<html>502</html>'],
284
+ ];
285
+ for (const [name, body] of badBodies) {
286
+ test(`${name} is rejected and the previous lease is kept`, async () => {
287
+ let good = true;
288
+ const { lines, logger } = collectLogs();
289
+ const src = (0, lease_1.createLeaseSource)({
290
+ url: 'https://plane.example/lease',
291
+ cacheSeconds: 0,
292
+ logger,
293
+ fetchImpl: (async () => bodyResponse(good ? JSON.stringify(lease) : body)),
294
+ });
295
+ assert.deepStrictEqual(await src.get(NOW), lease);
296
+ good = false;
297
+ assert.deepStrictEqual(await src.get(NOW + 1), lease, 'junk must never replace a validated lease');
298
+ assert.ok(lines.some((l) => /fetch failed/.test(l)), 'and the rejection must be logged');
299
+ });
300
+ }
301
+ test('a NaN cap cannot reach the meter — where every comparison would be false', async () => {
302
+ const src = (0, lease_1.createLeaseSource)({
303
+ url: 'https://plane.example/lease',
304
+ cacheSeconds: 0,
305
+ fetchImpl: (async () => bodyResponse(JSON.stringify({ ...lease, caps: { maxTurnsPerSession: null } }))),
306
+ });
307
+ const got = await src.get(NOW);
308
+ assert.strictEqual(got?.caps?.maxTurnsPerSession, undefined, 'null is dropped, never carried through as a cap');
309
+ });
310
+ });
311
+ suite('lease source — staleness ceiling (kill switch under network denial)', () => {
312
+ test('past the ceiling, the instance fails CLOSED with an actionable reason', async () => {
313
+ let alive = true;
314
+ const { lines, logger } = collectLogs();
315
+ const src = (0, lease_1.createLeaseSource)({
316
+ url: 'https://plane.example/lease',
317
+ cacheSeconds: 0,
318
+ maxStalenessSeconds: 100,
319
+ logger,
320
+ fetchImpl: (async () => {
321
+ if (!alive) {
322
+ throw new Error('control plane unreachable');
323
+ }
324
+ return bodyResponse(JSON.stringify(lease));
325
+ }),
326
+ });
327
+ assert.deepStrictEqual(await src.get(NOW), lease);
328
+ alive = false;
329
+ assert.strictEqual((await src.get(NOW + 50))?.enabled, true, 'inside the ceiling we still fail OPEN on transport');
330
+ const stale = await src.get(NOW + 200);
331
+ assert.strictEqual(stale?.enabled, false, 'past the ceiling the kill switch can no longer be starved out');
332
+ assert.match(stale?.reason ?? '', /staleness ceiling/);
333
+ assert.ok(lines.some((l) => /STALENESS CEILING PASSED/.test(l)));
334
+ assert.strictEqual(src.status(NOW + 200).failClosed, true);
335
+ });
336
+ test('0 disables the ceiling — an operator can explicitly accept unbounded staleness', async () => {
337
+ let alive = true;
338
+ const src = (0, lease_1.createLeaseSource)({
339
+ url: 'https://plane.example/lease',
340
+ cacheSeconds: 0,
341
+ maxStalenessSeconds: 0,
342
+ fetchImpl: (async () => {
343
+ if (!alive) {
344
+ throw new Error('down');
345
+ }
346
+ return bodyResponse(JSON.stringify(lease));
347
+ }),
348
+ });
349
+ await src.get(NOW);
350
+ alive = false;
351
+ assert.strictEqual((await src.get(NOW + 10_000_000))?.enabled, true);
352
+ });
353
+ test('an unmanaged deployment (no lease URL) is untouched by any of this', async () => {
354
+ const src = (0, lease_1.createLeaseSource)({ maxStalenessSeconds: 1 });
355
+ assert.strictEqual(await src.get(NOW + 1_000_000), undefined);
356
+ });
357
+ });