@dailephd/my-centcom 0.1.0 → 0.3.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 (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,403 @@
1
+ import { fileURLToPath as distributionFilePath } from 'node:url';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { randomBytes, createHash } from 'node:crypto';
4
+ import { isAbsolute, join, normalize, sep } from 'node:path';
5
+ import { WorkflowService } from '../runs/workflowService.js';
6
+ import { lazySealer, windowsDpapi } from '../storage/protectedSecrets.js';
7
+ import { createDaemonApp } from './app.js';
8
+ import { createOperatorConsole } from './operatorConsole.js';
9
+ import { PrivateDataRootError, assertOrInitializePrivateDataRoot, verifyPrivateDataFiles } from './privateDataRoot.js';
10
+ import { createOperationCatalog } from '../plugins/registry/operationCatalog.js';
11
+ import { createProvisionedExecution, reviewedTaskPresentation } from '../runtime/provisionedExecution.js';
12
+ import { ExecutionTelemetry } from '../storage/executionTelemetry.js';
13
+ import { PairedAuthority } from '../projects/pairedAuthority.js';
14
+ import { DurableIntentCoordinator } from '../runs/durableIntentCoordinator.js';
15
+ import { SqliteLedger } from '../storage/sqliteLedger.js';
16
+ import { DIAG_LOG_DIR_NAME, DiagnosticLog, formatDiagLine } from '../storage/diagnosticLog.js';
17
+ /**
18
+ * Nonexecuting secure startup (B02-C/B02-E). Composes the existing C03/C05/C09 owners through the single
19
+ * createDaemonApp factory in 'secure' mode. No driver, subprocess host, fixture token or
20
+ * environment-derived credential is involved, and nothing here can launch a process.
21
+ *
22
+ * Data roots: there is exactly ONE policy for every invocation (compiled main.js, tests, any local caller). The data
23
+ * root must be a strict canonical child of <projectRoot>\.switchyard-data that passes the private data root check
24
+ * (Windows DACL exactly {current user, SYSTEM}) before SQLite is opened, and the database files are verified again
25
+ * afterwards. There is no scratch, test or skip mode: the SW-034 scratch location is not a secure data root. The
26
+ * attended operator console is created only when the caller passes operatorConsole.
27
+ */
28
+ export const SECURE_DB_FILE_NAME = 'secure-ledger.db';
29
+ /** Default production data root, relative to the project root. A NEW directory so existing data is never rewritten. */
30
+ export const DEFAULT_PRIVATE_DATA_RELATIVE = join('.switchyard-data', 'private');
31
+ /** Operator grants are short-lived read grants that always require user confirmation. */
32
+ export const OPERATOR_GRANT_TTL_MS = 60 * 60 * 1000;
33
+ /** SW-062: the daemon's single-instance lock and runtime record live in <private data root>\run\ (never on a browser-reachable route). */
34
+ export const RUNTIME_DIR_NAME = 'run';
35
+ export const RUNTIME_RECORD_FILE = 'daemon.json';
36
+ export const RUNTIME_LOCK_FILE = 'daemon.lock';
37
+ function pidAlive(pid) {
38
+ if (!Number.isInteger(pid) || pid <= 0)
39
+ return false;
40
+ try {
41
+ process.kill(pid, 0);
42
+ return true;
43
+ }
44
+ catch (e) {
45
+ return e.code === 'EPERM';
46
+ }
47
+ }
48
+ /** Exclusive create; a lock left by a dead process is replaced, a live one refuses the start (one daemon per private data root). */
49
+ function acquireInstanceLock(dataDir, instanceId) {
50
+ const dir = join(dataDir, RUNTIME_DIR_NAME);
51
+ mkdirSync(dir, { recursive: true });
52
+ const lock = join(dir, RUNTIME_LOCK_FILE);
53
+ const body = JSON.stringify({ pid: process.pid, instanceId });
54
+ try {
55
+ writeFileSync(lock, body, { flag: 'wx' });
56
+ }
57
+ catch {
58
+ let holder = {};
59
+ try {
60
+ holder = JSON.parse(readFileSync(lock, 'utf8'));
61
+ }
62
+ catch { /* unreadable = stale */ }
63
+ if (typeof holder.pid === 'number' && holder.pid !== process.pid && pidAlive(holder.pid))
64
+ throw new SecureStartupError('ALREADY_RUNNING');
65
+ writeFileSync(lock, body);
66
+ }
67
+ return () => {
68
+ try {
69
+ const cur = JSON.parse(readFileSync(lock, 'utf8'));
70
+ if (cur.instanceId === instanceId)
71
+ rmSync(lock, { force: true });
72
+ }
73
+ catch { /* gone */ }
74
+ };
75
+ }
76
+ /** Sanitized: carries only a fixed code, never paths, tokens or driver messages. */
77
+ export class SecureStartupError extends Error {
78
+ code;
79
+ constructor(code) {
80
+ super(code);
81
+ this.code = code;
82
+ this.name = 'SecureStartupError';
83
+ }
84
+ }
85
+ const same = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);
86
+ const trimSep = (p) => p.replace(new RegExp(`\\${sep}+$`), '');
87
+ function canonicalExistingDir(p, code) {
88
+ if (typeof p !== 'string' || !isAbsolute(p) || p.split(/[\\/]+/).includes('..'))
89
+ throw new SecureStartupError(code);
90
+ try {
91
+ if (lstatSync(p).isSymbolicLink())
92
+ throw new SecureStartupError(code);
93
+ const real = trimSep(realpathSync.native(p));
94
+ if (!same(real, trimSep(normalize(p))))
95
+ throw new SecureStartupError(code); // alias / junction / short name
96
+ return real;
97
+ }
98
+ catch (e) {
99
+ if (e instanceof SecureStartupError)
100
+ throw e;
101
+ throw new SecureStartupError(code);
102
+ }
103
+ }
104
+ function verifyProjectRoot(projectRoot) {
105
+ const root = canonicalExistingDir(projectRoot, 'PROJECT_ROOT_INVALID');
106
+ try {
107
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
108
+ if (pkg.name !== '@dailephd/my-centcom' || root !== canonicalExistingDir(distributionFilePath(new URL('../../../../', import.meta.url)), 'PROJECT_ROOT_INVALID')) {
109
+ throw new SecureStartupError('PROJECT_ROOT_INVALID');
110
+ }
111
+ }
112
+ catch {
113
+ throw new SecureStartupError('PROJECT_ROOT_INVALID');
114
+ }
115
+ return root;
116
+ }
117
+ /**
118
+ * The single data-root policy. Returns the canonical, verified-private directory or throws a sanitized code.
119
+ * Nothing is created or opened before the checks pass; a rejected path leaves no trace.
120
+ */
121
+ function prepareDataRoot(root, requested) {
122
+ const dataParent = join(root, '.switchyard-data');
123
+ const target = requested === undefined ? join(root, DEFAULT_PRIVATE_DATA_RELATIVE) : requested;
124
+ if (typeof target !== 'string' || !isAbsolute(target) || target.split(/[\\/]+/).includes('..'))
125
+ throw new SecureStartupError('DATA_ROOT_INVALID');
126
+ const normalized = trimSep(normalize(target));
127
+ if (same(normalized, dataParent)) {
128
+ // The shared runtime-data directory (and any database already in it) inherits broad permissions and is never rewritten.
129
+ throw new SecureStartupError('PRODUCTION_DB_CONFIDENTIALITY_NOT_VERIFIED');
130
+ }
131
+ try {
132
+ // Strict-child, real-directory and exact-DACL checks all live in the private data root owner.
133
+ return assertOrInitializePrivateDataRoot({ projectRoot: root, dataRoot: normalized }).canonicalDataRoot;
134
+ }
135
+ catch (e) {
136
+ if (e instanceof PrivateDataRootError)
137
+ throw new SecureStartupError(e.code);
138
+ throw new SecureStartupError('PRODUCTION_DB_CONFIDENTIALITY_NOT_VERIFIED');
139
+ }
140
+ }
141
+ const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
142
+ /** Registers the approved project once through C03 (which validates a canonical, non-link Git root). */
143
+ function ensureApprovedProject(authority, ledger, p) {
144
+ if (typeof p?.projectId !== 'string' || !PROJECT_ID.test(p.projectId) || typeof p.root !== 'string')
145
+ throw new SecureStartupError('APPROVED_PROJECT_INVALID');
146
+ try {
147
+ const existing = ledger.getProjectRoot(p.projectId);
148
+ if (existing === undefined) {
149
+ authority.registerApprovedProject(p.projectId, p.root);
150
+ }
151
+ else if (!same(trimSep(realpathSync.native(p.root)), trimSep(existing))) {
152
+ throw new Error('PROJECT_ID_REBOUND');
153
+ }
154
+ return p.projectId;
155
+ }
156
+ catch {
157
+ throw new SecureStartupError('APPROVED_PROJECT_INVALID');
158
+ }
159
+ }
160
+ /**
161
+ * Adapts existing trusted C03/C04/C09 methods to the console's private actions. Nothing here decides policy:
162
+ * issuance, expiry, single use and digest-only storage stay in PairedAuthority; the catalog stays the only source
163
+ * of "verified"; the ledger only answers exact-id lookups.
164
+ */
165
+ function createOperatorActions(deps) {
166
+ const { authority, ledger, resolve, projectId, now, provisioned, diag } = deps;
167
+ return {
168
+ recentDiagnostics: (count, correlationId) => diag.recent(count, correlationId).map(formatDiagLine),
169
+ issuePairingCodeForExtension(extensionId) {
170
+ const c = authority.issuePairingChallenge(`chrome-extension://${extensionId}`);
171
+ diag.info('OPERATOR', 'pair.issue', 'PAIR_CHALLENGE_ISSUED', { outcome: 'OK', meta: { challengeId: c.challengeId, extensionId, expiresAt: c.expiresAt } });
172
+ return { challengeId: c.challengeId, code: c.code, expiresAt: c.expiresAt };
173
+ },
174
+ grantVerifiedOperation(principalId, pluginId, operationId) {
175
+ if (!projectId)
176
+ throw new Error('NO_APPROVED_PROJECT');
177
+ if (!ledger.principalIsEnabled(principalId))
178
+ throw new Error('PRINCIPAL_NOT_ACTIVE');
179
+ const def = resolve({ pluginId, operationId });
180
+ if (!def || def.verified !== true || def.effectClass !== 'read')
181
+ throw new Error('OPERATION_NOT_VERIFIED');
182
+ const expires = new Date(now() + OPERATOR_GRANT_TTL_MS);
183
+ authority.grantOperation(principalId, projectId, pluginId, operationId, 'read', expires, true);
184
+ diag.info('OPERATOR', 'grant', 'OPERATION_GRANTED', { outcome: 'OK', meta: { principalId, projectId, pluginId, operationId, expiresAt: expires.toISOString() } });
185
+ return { expiresAt: expires.toISOString() };
186
+ },
187
+ grantRunClickOperation(principalId, pluginId, operationId) {
188
+ if (!projectId)
189
+ throw new Error('NO_APPROVED_PROJECT');
190
+ if (!ledger.principalIsEnabled(principalId))
191
+ throw new Error('PRINCIPAL_NOT_ACTIVE');
192
+ const def = resolve({ pluginId, operationId });
193
+ if (!def || def.verified !== true || def.effectClass !== 'read')
194
+ throw new Error('OPERATION_NOT_VERIFIED');
195
+ const expires = new Date(now() + OPERATOR_GRANT_TTL_MS);
196
+ authority.grantOperation(principalId, projectId, pluginId, operationId, 'read', expires, true, 'RUN_CLICK');
197
+ diag.info('OPERATOR', 'grant', 'OPERATION_GRANTED', { outcome: 'OK', meta: { principalId, projectId, pluginId, operationId, consent: 'RUN_CLICK', expiresAt: expires.toISOString() } });
198
+ return { expiresAt: expires.toISOString() };
199
+ },
200
+ revokeOperationGrant(principalId, pluginId, operationId) {
201
+ if (!projectId)
202
+ throw new Error('NO_APPROVED_PROJECT');
203
+ let revoked = 0;
204
+ for (const g of ledger.findGrants(principalId, projectId, pluginId, operationId)) {
205
+ if (authority.revokeGrant(g.grantId))
206
+ revoked += 1;
207
+ }
208
+ diag.info('OPERATOR', 'revoke', 'OPERATION_GRANT_REVOKED', { outcome: 'OK', meta: { principalId, pluginId, operationId, revoked } });
209
+ return { revoked };
210
+ },
211
+ issuePendingRunApproval(runId) {
212
+ const owner = ledger.getRunOwnerPrincipalId(runId);
213
+ if (!owner)
214
+ throw new Error('RUN_NOT_FOUND');
215
+ const a = authority.issueLocalApprovalChallenge({ principalId: owner, runId });
216
+ diag.info('OPERATOR', 'approve.issue', 'APPROVAL_ISSUED', { outcome: 'OK', meta: { runId, approvalId: a.approvalId, expiresAt: a.expiresAt } });
217
+ return { approvalId: a.approvalId, approvalCode: a.approvalCode, expiresAt: a.expiresAt };
218
+ },
219
+ // SW-060: attended-operator provisioning. These only forward to the C06 composition owner, which validates and persists; nothing here decides policy.
220
+ provisionOperation: async (a) => {
221
+ const p = provisioned();
222
+ const t0 = Date.now();
223
+ if (!p) {
224
+ diag.warn('PROVISIONING', 'provision', 'PROVISION_NOT_AVAILABLE', { outcome: 'REFUSED' });
225
+ throw new Error('NOT_AVAILABLE');
226
+ }
227
+ try {
228
+ const r = await p.provisionOperation(a);
229
+ diag.info('PROVISIONING', 'provision', 'PROVISIONED', { outcome: 'OK', elapsedMs: Date.now() - t0, meta: { pluginId: a.pluginId, operationId: a.operationId, profileId: a.profileId, exeSha256: r.executableSha256 } });
230
+ return r;
231
+ }
232
+ catch (e) {
233
+ const code = e instanceof Error ? /^[A-Z][A-Z0-9_]{2,60}/.exec(e.message)?.[0] ?? 'ACTION_FAILED' : 'ACTION_FAILED';
234
+ diag.warn('PROVISIONING', 'provision', code, { outcome: 'FAILED', elapsedMs: Date.now() - t0, meta: { pluginId: a.pluginId, operationId: a.operationId, profileId: a.profileId } });
235
+ throw e;
236
+ }
237
+ },
238
+ listProvisioned: () => provisioned()?.listProvisioned() ?? [],
239
+ disableProvisioned: (pluginId, operationId) => {
240
+ const ok = provisioned()?.disableProvisioned(pluginId, operationId) ?? false;
241
+ diag.info('PROVISIONING', 'disable', ok ? 'PROVISION_DISABLED' : 'PROVISION_DISABLE_NOT_FOUND', { outcome: ok ? 'OK' : 'REFUSED', meta: { pluginId, operationId } });
242
+ return ok;
243
+ },
244
+ };
245
+ }
246
+ export async function startSecureDaemon(options) {
247
+ const root = verifyProjectRoot(options?.projectRoot);
248
+ const port = options.port === undefined ? 0 : options.port;
249
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
250
+ throw new SecureStartupError('PORT_INVALID');
251
+ const consoleOpts = options.operatorConsole;
252
+ if (consoleOpts !== undefined && (typeof consoleOpts?.input?.on !== 'function' || typeof consoleOpts?.output?.write !== 'function')) {
253
+ throw new SecureStartupError('OPERATOR_CONSOLE_INVALID');
254
+ }
255
+ const dataDir = prepareDataRoot(root, options.dataRoot); // verified private BEFORE SQLite is opened or a port is bound
256
+ const instanceId = `inst-run.${randomBytes(12).toString('hex')}`;
257
+ const releaseLock = options.publishRuntime === true ? acquireInstanceLock(dataDir, instanceId) : () => undefined;
258
+ // SW-062: the diagnostic log lives in <private data root>/logs (created after the root passed its checks, so it inherits the private DACL).
259
+ const diag = new DiagnosticLog({ dir: join(dataDir, DIAG_LOG_DIR_NAME), ...(options.diagnosticLogMaxBytes !== undefined ? { maxBytes: options.diagnosticLogMaxBytes } : {}), minLevel: options.diagnosticMinLevel ?? 'INFO' });
260
+ diag.info('DAEMON', 'startup', 'DAEMON_STARTING', { outcome: 'STARTED' });
261
+ let catalog;
262
+ try {
263
+ catalog = options.operationCatalog ?? createOperationCatalog();
264
+ if (typeof catalog?.resolve !== 'function')
265
+ throw new Error('bad catalog');
266
+ }
267
+ catch {
268
+ releaseLock();
269
+ throw new SecureStartupError('CATALOG_INVALID');
270
+ }
271
+ let ledger;
272
+ try {
273
+ ledger = new SqliteLedger(join(dataDir, SECURE_DB_FILE_NAME)); // reopens and migrates; never resets
274
+ }
275
+ catch {
276
+ releaseLock();
277
+ throw new SecureStartupError('LEDGER_OPEN_FAILED');
278
+ }
279
+ try {
280
+ verifyPrivateDataFiles(dataDir); // database, WAL and SHM as created
281
+ }
282
+ catch {
283
+ ledger.close();
284
+ releaseLock();
285
+ throw new SecureStartupError('PRODUCTION_DB_CONFIDENTIALITY_NOT_VERIFIED');
286
+ }
287
+ const now = options.now ?? Date.now;
288
+ let app;
289
+ let operator;
290
+ try {
291
+ let consoleRef;
292
+ let provisionedRef; // set after the owners exist; a static catalog entry always wins over a provisioned one
293
+ const resolveOperation = (op) => catalog.resolve(op) ?? provisionedRef?.resolve(op);
294
+ const authority = new PairedAuthority({
295
+ ledger,
296
+ now,
297
+ resolveVerifiedOperationEffect: resolveOperation,
298
+ onPairingCompleted: (r) => consoleRef?.notify(`NOTICE paired principal-id=${r.principalId} extension-id=${r.origin.slice('chrome-extension://'.length)}`),
299
+ });
300
+ const projectId = options.approvedProject ? ensureApprovedProject(authority, ledger, options.approvedProject) : undefined;
301
+ if (consoleOpts) {
302
+ operator = createOperatorConsole({
303
+ input: consoleOpts.input,
304
+ output: consoleOpts.output,
305
+ allowInjectedTestStreams: consoleOpts.allowInjectedTestStreams === true,
306
+ actions: createOperatorActions({ authority, ledger, resolve: resolveOperation, projectId, now, provisioned: () => provisionedRef, diag }),
307
+ });
308
+ consoleRef = operator;
309
+ }
310
+ const coordinator = new DurableIntentCoordinator(ledger, now, authority);
311
+ const recovered = coordinator.recoverOnStartup(); // exactly once, before any request is accepted
312
+ if (recovered > 0)
313
+ diag.warn('RUN', 'startup.recover', 'RUNS_MARKED_UNKNOWN', { outcome: 'OK', meta: { count: recovered } });
314
+ // SW-060: with no injected test seam, execution comes ONLY from operator-provisioned, re-verified ledger rows (none = launches nothing).
315
+ const telemetry = new ExecutionTelemetry(ledger, now); // SW-068: one evidence recorder for provisioning, execution and the workflow view
316
+ if (!options.createRunLauncher)
317
+ provisionedRef = await createProvisionedExecution({ ledger, authority, coordinator, now, projectRoot: root,
318
+ runtimeRoot: join(root, '.switchyard-data', 'execution', createHash('sha256').update(dataDir.toLowerCase()).digest('hex').slice(0, 24)), codingJournalRoot: join(dataDir, 'coding-journals'),
319
+ devSmokeProfiles: options.devSmokeProfiles === true, ...(options.devSmokeProfiles && options.devMockResponsesPort ? { devMockResponsesPort: options.devMockResponsesPort } : {}),
320
+ ...(options.syntheticTestAcceptance ? { syntheticTestAcceptance: options.syntheticTestAcceptance } : {}), telemetry });
321
+ const rawLauncher = options.createRunLauncher ? options.createRunLauncher({ ledger, authority, coordinator, now }) : provisionedRef?.launcher;
322
+ // SW-062: execution is observed at its single port. Process internals stay with the C06 owner; this records what was asked and what answered.
323
+ const launcher = rawLauncher === undefined ? undefined : {
324
+ launch: (principalId, runId) => { diag.info('RUN', 'execute.launch', 'EXECUTION_LAUNCH_REQUESTED', { outcome: 'STARTED', meta: { runId } }); rawLauncher.launch(principalId, runId); },
325
+ cancel: async (principalId, runId) => {
326
+ const r = await rawLauncher.cancel(principalId, runId);
327
+ diag.info('RUN', 'execute.cancel', `EXECUTION_CANCEL_${r}`, { outcome: r === 'REQUESTED' ? 'OK' : 'REFUSED', meta: { runId } });
328
+ return r;
329
+ },
330
+ };
331
+ if (launcher !== undefined && (typeof launcher.launch !== 'function' || typeof launcher.cancel !== 'function'))
332
+ throw new SecureStartupError('CATALOG_INVALID');
333
+ // SW-062: the durable workflow. The capture data key is created/unsealed with DPAPI only when the first capture is stored or read.
334
+ const workflow = new WorkflowService(ledger, authority, coordinator, lazySealer(dataDir, options.dpapi ?? windowsDpapi), now, telemetry, (pluginId, operationId) => {
335
+ const op = provisionedRef?.listProvisioned().find(o => o.pluginId === pluginId && o.operationId === operationId && o.enabled);
336
+ return op ? reviewedTaskPresentation(op.profileId) : undefined;
337
+ });
338
+ app = createDaemonApp({ mode: 'secure', dependencies: { authority, coordinator, ledger, diag, workflow, ...(provisionedRef ? { codingWorkflow: () => provisionedRef.codingWorkflow() } : {}), ...(launcher ? { launcher } : {}), ...(options.promptCapBytes ? { promptCapBytes: options.promptCapBytes } : provisionedRef ? { promptCapBytes: provisionedRef.promptCapBytes } : {}) } });
339
+ await app.listen({ host: '127.0.0.1', port });
340
+ const addr = app.server.address();
341
+ const boundPort = addr && typeof addr === 'object' ? addr.port : port;
342
+ const server = app;
343
+ const runtimeFile = join(dataDir, RUNTIME_DIR_NAME, RUNTIME_RECORD_FILE);
344
+ if (options.publishRuntime === true) {
345
+ // Atomic replace: a reader never sees a half-written record.
346
+ const tmp = `${runtimeFile}.${process.pid}.tmp`;
347
+ writeFileSync(tmp, JSON.stringify({ schemaVersion: 1, port: boundPort, pid: process.pid, instanceId, startedAt: new Date().toISOString() }));
348
+ renameSync(tmp, runtimeFile);
349
+ }
350
+ diag.info('DAEMON', 'startup', 'DAEMON_LISTENING', { outcome: 'OK', meta: { port: boundPort, recovered, published: options.publishRuntime === true } });
351
+ let closed = false;
352
+ const provisionedHandle = provisionedRef;
353
+ return {
354
+ port: boundPort,
355
+ url: `http://127.0.0.1:${boundPort}`,
356
+ app: server,
357
+ authority,
358
+ diag,
359
+ operator,
360
+ recovered,
361
+ workflow,
362
+ ledger,
363
+ instanceId,
364
+ ...(provisionedHandle ? { provisionedActions: { provisionOperation: (a) => provisionedHandle.provisionOperation(a), listProvisioned: () => provisionedHandle.listProvisioned(), disableProvisioned: (p, o) => provisionedHandle.disableProvisioned(p, o) } } : {}),
365
+ ...(provisionedRef ? { provisioned: { enabled: provisionedRef.enabledAtStartup, invalidated: provisionedRef.invalidatedAtStartup } } : {}),
366
+ close: async () => {
367
+ if (closed)
368
+ return;
369
+ closed = true;
370
+ diag.info('DAEMON', 'shutdown', 'DAEMON_STOPPING', { outcome: 'STARTED' });
371
+ await provisionedRef?.close?.();
372
+ operator?.close();
373
+ try {
374
+ await server.close();
375
+ }
376
+ finally {
377
+ ledger.close();
378
+ if (options.publishRuntime === true) {
379
+ try {
380
+ const cur = JSON.parse(readFileSync(runtimeFile, 'utf8'));
381
+ if (cur.instanceId === instanceId)
382
+ rmSync(runtimeFile, { force: true });
383
+ }
384
+ catch { /* gone */ }
385
+ }
386
+ releaseLock();
387
+ diag.info('DAEMON', 'shutdown', 'DAEMON_STOPPED', { outcome: 'OK' });
388
+ }
389
+ },
390
+ };
391
+ }
392
+ catch (e) {
393
+ operator?.close();
394
+ try {
395
+ await app?.close();
396
+ }
397
+ catch { /* not listening */ }
398
+ ledger.close();
399
+ releaseLock();
400
+ throw e instanceof SecureStartupError ? e : new SecureStartupError('LISTEN_FAILED');
401
+ }
402
+ }
403
+ //# sourceMappingURL=secureMain.js.map
@@ -0,0 +1,93 @@
1
+ import { type HostConfigV1, type InstallPaths } from './installLayout.js';
2
+ import { type Dpapi } from '../storage/protectedSecrets.js';
3
+ /**
4
+ * SW-062 ONE user-invoked setup entrypoint: npm run centcom -- <command> [options]
5
+ *
6
+ * plan (default) print exactly what `install` would do; changes nothing
7
+ * install one-time trusted installation: pinned-key extension build, installation record + DPAPI-protected secret, native host manifest/launcher,
8
+ * approved project and RUN_CLICK read grants. The HKCU registration is applied ONLY with --register-native-host --consent.
9
+ * update re-pin after a rebuild (daemon tree / node / extension); keeps the installation and its grants exactly as they were (never widened)
10
+ * status redacted inventory (no secrets)
11
+ * selftest isolated end-to-end check (own private test data root, benign reference operation, the REAL native host process); writes ONE report
12
+ * confirm local confirmation of a pending higher-risk run (attended terminal only)
13
+ * stop stop the background daemon of this installation
14
+ * uninstall revoke the installation and remove host files; the HKCU key only with --consent. The ledger is kept (user data).
15
+ *
16
+ * Nothing here runs a model or a real agent CLI, touches ChatGPT, copies any credential, or writes outside the project root (the only OS change outside it is
17
+ * the explicit, consented HKCU registry value). Every child process is hidden.
18
+ */
19
+ export interface RegistryPort {
20
+ query(key: string): string | undefined;
21
+ set(key: string, value: string): void;
22
+ remove(key: string): void;
23
+ }
24
+ export declare const windowsRegistry: RegistryPort;
25
+ export interface SetupDeps {
26
+ dpapi: Dpapi;
27
+ registry: RegistryPort;
28
+ out: (line: string) => void;
29
+ now: () => number;
30
+ }
31
+ export declare const productionSetupDeps: () => SetupDeps;
32
+ export declare class SetupError extends Error {
33
+ readonly code: string;
34
+ readonly action?: string | undefined;
35
+ constructor(code: string, action?: string | undefined);
36
+ }
37
+ export declare function projectRootFromHere(): string;
38
+ /** A disposable Git project for the benign smoke operation, inside the project's runtime data (never the user's real repositories). */
39
+ export declare function createScratchProject(dir: string, opts?: {
40
+ grantRestrictedRead?: boolean;
41
+ }): string;
42
+ export declare function stageBenignScript(root: string, targetDir: string): string;
43
+ export declare function writeHostFiles(p: InstallPaths, cfg: Omit<HostConfigV1, 'configMac'>, secret: string): HostConfigV1;
44
+ export interface InstallOptions {
45
+ approvedProjectRoot?: string;
46
+ createScratchProject?: boolean;
47
+ projectId?: string;
48
+ operations: Array<{
49
+ pluginId: string;
50
+ operationId: string;
51
+ }>;
52
+ devSmokeBenign?: boolean;
53
+ grantDays?: number;
54
+ registerNativeHost?: boolean;
55
+ consent?: boolean;
56
+ dataRoot?: string;
57
+ /** API only (tests): build the installed extension here instead of .switchyard-data/centcom-extension. */
58
+ extensionOutDir?: string;
59
+ }
60
+ /** install and update share this path; `update` requires an existing installation and never creates a new one. */
61
+ export declare function install(root: string, o: InstallOptions, deps: SetupDeps, mode?: 'install' | 'update'): Promise<{
62
+ extensionId: string;
63
+ installationId: string;
64
+ extensionDir: string;
65
+ registered: boolean;
66
+ }>;
67
+ export declare function uninstall(root: string, o: {
68
+ consent?: boolean;
69
+ dataRoot?: string;
70
+ }, deps: SetupDeps): Promise<void>;
71
+ export declare function status(root: string, deps: SetupDeps, dataRoot?: string): Record<string, string>;
72
+ export declare function stop(root: string, deps: SetupDeps, dataRoot?: string): boolean;
73
+ type StageStatus = 'PASS' | 'FAIL' | 'NOT_RUN' | 'INFO';
74
+ export interface SelfTestReport {
75
+ correlationId: string;
76
+ stages: Array<{
77
+ stage: string;
78
+ status: StageStatus;
79
+ detail: string;
80
+ ms: number;
81
+ }>;
82
+ ok: boolean;
83
+ reportPath: string;
84
+ }
85
+ /** Runs the REAL native host process exactly as Chrome does: launcher arguments + the caller origin, one framed message on stdin, one framed reply. */
86
+ export declare function callNativeHost(hostEntry: string, configPath: string, callerOrigin: string, message: unknown, timeoutMs?: number): Promise<unknown>;
87
+ export declare function selftest(root: string, deps: SetupDeps, o?: {
88
+ dataRoot?: string;
89
+ }): Promise<SelfTestReport>;
90
+ export declare function confirm(root: string, deps: SetupDeps, ask: (q: string) => Promise<string>, dataRoot?: string): Promise<number>;
91
+ export declare function cli(argv: string[], deps?: SetupDeps): Promise<number>;
92
+ export {};
93
+ //# sourceMappingURL=setup.d.ts.map