@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,332 @@
1
+ import { PairCompleteRequestV1Schema, ApproveRunRequestV1Schema, CancelPendingRunRequestV1Schema, RunDecisionResponseV1Schema, PairCompleteResponseV1Schema, PrepareIntentRequestStdinV1Schema, PrepareIntentResponseV1Schema, RunCancelAcceptedResponseV1Schema, PROMPT_MAX_UTF8_BYTES, PROMPT_MAX_UTF8_BYTES_STDIN_V1, RunStatusResponseV1Schema, RunStatusReadRequestV1Schema, PrepareReturnRequestV1Schema, ReturnSnapshotResponseV1Schema, SCHEMA_VERSION_V1, CORRELATION_HEADER, newCorrelationId, validCorrelationId, } from '../../../../../packages/contracts/dist/index.js';
2
+ import { PairedAuthority } from '../../projects/pairedAuthority.js';
3
+ import { IdempotencyConflictError } from '../../runs/durableIntentCoordinator.js';
4
+ import { decideReturnSnapshot } from '../../artifacts/returnSnapshots.js';
5
+ import { DiagnosticLog } from '../../storage/diagnosticLog.js';
6
+ import { WORKFLOW_BROWSER_PATHS, registerWorkflowRoutes } from './workflowRoutes.js';
7
+ /** Secure-mode body limit (bytes). */
8
+ export const SECURE_HTTP_BODY_LIMIT_BYTES = 65536;
9
+ const BEARER = /^Bearer ([A-Za-z0-9_-]{1,512})$/;
10
+ const ctxs = new WeakMap();
11
+ const ctxOf = (req) => {
12
+ let c = ctxs.get(req);
13
+ if (!c) {
14
+ c = { corr: validCorrelationId(req.headers[CORRELATION_HEADER]) ?? newCorrelationId(), startedAt: Date.now() };
15
+ ctxs.set(req, c);
16
+ }
17
+ return c;
18
+ };
19
+ /** `fields` (names + a fixed reason vocabulary, never values) is the only extra the wire body ever carries. `detail` is for the private log only. */
20
+ function fail(reply, status, code, extra) {
21
+ const c = ctxOf(reply.request);
22
+ c.code = code;
23
+ if (extra?.detail)
24
+ c.detail = extra.detail;
25
+ return reply.code(status).header('cache-control', 'no-store').send({ error: { code, ...(extra?.fields && extra.fields.length > 0 ? { fields: extra.fields } : {}) } });
26
+ }
27
+ /** Safe field-level detail from a Zod error: field names and a fixed reason only. The received value is NEVER read. */
28
+ export function fieldIssues(err) {
29
+ const out = [];
30
+ for (const i of err.issues) {
31
+ const base = i.path.map((p) => (typeof p === 'number' ? `[${p}]` : String(p))).join('.').split('.[').join('[');
32
+ const add = (field, reason) => { if (out.length < 8 && !out.some((o) => o.field === field))
33
+ out.push({ field: (field || '(body)').slice(0, 64), reason }); };
34
+ const x = i;
35
+ if (x.code === 'unrecognized_keys') {
36
+ for (const k of x.keys ?? [])
37
+ add(base ? `${base}.${k}` : k, 'UNEXPECTED_FIELD');
38
+ continue;
39
+ }
40
+ if (x.code === 'invalid_type')
41
+ add(base, /received undefined/i.test(x.message ?? '') ? 'MISSING' : 'WRONG_TYPE');
42
+ else if (x.code === 'too_small')
43
+ add(base, Number(x.minimum) <= 1 && x.origin === 'string' ? 'EMPTY' : 'TOO_SHORT');
44
+ else if (x.code === 'too_big')
45
+ add(base, 'TOO_LONG');
46
+ else if (x.code === 'invalid_value')
47
+ add(base, 'NOT_ALLOWED');
48
+ else
49
+ add(base, 'BAD_FORMAT');
50
+ }
51
+ return out;
52
+ }
53
+ const validationFail = (reply, err) => {
54
+ const fields = fieldIssues(err);
55
+ return fail(reply, 400, 'VALIDATION_FAILED', { fields, detail: { fields: fields.map((f) => `${f.field}:${f.reason}`).join(',') } });
56
+ };
57
+ function originOf(req) {
58
+ const o = req.headers.origin;
59
+ return typeof o === 'string' ? o : undefined;
60
+ }
61
+ function bearerOf(req) {
62
+ const h = req.headers.authorization;
63
+ if (typeof h !== 'string')
64
+ return undefined;
65
+ const m = BEARER.exec(h);
66
+ return m ? m[1] : undefined;
67
+ }
68
+ /** Echo only an exact, already-known extension origin; never '*' and never a reflected foreign origin. */
69
+ function allowOrigin(reply, origin) {
70
+ reply
71
+ .header('access-control-allow-origin', origin)
72
+ .header('vary', 'Origin');
73
+ }
74
+ export function registerSecureRoutes(app, deps) {
75
+ const { authority, coordinator, launcher } = deps;
76
+ const diag = deps.diag ?? new DiagnosticLog();
77
+ const routeOp = (req) => `${req.method} ${req.routeOptions?.url ?? '(unmatched)'}`;
78
+ const note = (req, level, component, operation, event, outcome, meta) => {
79
+ diag.log(level, component, operation, event, { correlationId: ctxOf(req).corr, outcome, ...(meta ? { meta } : {}) });
80
+ };
81
+ // SW-062: every request gets (or keeps, when well-formed) a correlation id, echoed on the response; one summary event per request.
82
+ app.addHook('onRequest', async (req, reply) => {
83
+ const c = ctxOf(req);
84
+ reply.header(CORRELATION_HEADER, c.corr).header('access-control-expose-headers', CORRELATION_HEADER);
85
+ });
86
+ app.addHook('onResponse', async (req, reply) => {
87
+ const c = ctxOf(req);
88
+ const status = reply.statusCode;
89
+ const level = status >= 500 ? 'ERROR' : status >= 400 ? 'WARN' : 'INFO';
90
+ diag.log(level, 'DAEMON', routeOp(req), c.code ?? 'HTTP_RESPONSE', {
91
+ correlationId: c.corr, outcome: status < 400 ? 'OK' : 'FAILED', elapsedMs: Date.now() - c.startedAt, meta: { status, ...(c.detail ?? {}) },
92
+ });
93
+ });
94
+ app.setErrorHandler((err, req, reply) => {
95
+ const status = err.statusCode;
96
+ if (status === 413)
97
+ return fail(reply, 413, 'PAYLOAD_TOO_LARGE');
98
+ if (status === 400 || status === 415)
99
+ return fail(reply, 400, 'MALFORMED_REQUEST');
100
+ // An unknown internal failure is logged with its error class only (never its message, which may hold paths or content) and stays INTERNAL_ERROR.
101
+ note(req, 'ERROR', 'DAEMON', routeOp(req), 'INTERNAL_ERROR', 'FAILED', { errorClass: err?.name ?? 'Error' });
102
+ return fail(reply, 500, 'INTERNAL_ERROR');
103
+ });
104
+ app.setNotFoundHandler((_req, reply) => fail(reply, 404, 'NOT_FOUND'));
105
+ app.get('/health', async (_req, reply) => reply.header('cache-control', 'no-store').send({ status: 'ok' }));
106
+ const preflightPaths = ['/v1/pairing/complete', '/v1/runs/prepare', '/v1/runs/:runId', '/v1/runs/:runId/status', '/v1/runs/:runId/return', '/v1/runs/:runId/approve', '/v1/runs/:runId/cancel', ...(deps.workflow ? WORKFLOW_BROWSER_PATHS : [])];
107
+ for (const path of preflightPaths) {
108
+ app.options(path, async (req, reply) => {
109
+ const origin = originOf(req);
110
+ // Pairing state must not be observable: every well-formed extension origin gets the identical
111
+ // preflight answer whether or not it is paired. Real requests still need exact Origin and bearer.
112
+ if (!PairedAuthority.isValidExtensionOrigin(origin))
113
+ return fail(reply, 403, 'ORIGIN_DENIED');
114
+ allowOrigin(reply, origin);
115
+ return reply
116
+ .code(204)
117
+ .header('access-control-allow-methods', path === '/v1/runs/:runId' ? 'GET' : 'POST')
118
+ .header('access-control-allow-headers', `authorization, content-type, ${CORRELATION_HEADER}`)
119
+ .header('access-control-max-age', '60')
120
+ .send();
121
+ });
122
+ }
123
+ app.post('/v1/pairing/complete', async (req, reply) => {
124
+ const origin = originOf(req);
125
+ if (!PairedAuthority.isValidExtensionOrigin(origin))
126
+ return fail(reply, 403, 'ORIGIN_DENIED');
127
+ const body = PairCompleteRequestV1Schema.safeParse(req.body);
128
+ if (!body.success)
129
+ return validationFail(reply, body.error);
130
+ const res = authority.completePairing(body.data.challengeId, body.data.code, origin);
131
+ if (!res.ok) {
132
+ // The wire answer is identical for every refusal (no oracle). The precise internal reason goes to the PRIVATE log only.
133
+ note(req, 'WARN', 'AUTH', 'pairing.complete', 'PAIRING_DENIED', 'DENIED', { internalReason: res.reason, challengeId: body.data.challengeId });
134
+ return fail(reply, 403, 'PAIRING_DENIED', { detail: { internalReason: res.reason } });
135
+ }
136
+ note(req, 'INFO', 'AUTH', 'pairing.complete', 'PAIRING_COMPLETED', 'OK', { principalId: res.principalId });
137
+ allowOrigin(reply, origin);
138
+ return reply.code(200).header('cache-control', 'no-store').send(PairCompleteResponseV1Schema.parse({
139
+ schemaVersion: SCHEMA_VERSION_V1,
140
+ principalId: res.principalId,
141
+ bearerToken: res.bearerToken,
142
+ pairedOrigin: res.pairedOrigin,
143
+ expiresAt: res.expiresAt,
144
+ }));
145
+ });
146
+ function authenticate(req, reply) {
147
+ const auth = authority.authenticate(bearerOf(req), originOf(req));
148
+ if (!auth.ok) {
149
+ note(req, 'WARN', 'AUTH', routeOp(req), auth.reason, 'DENIED');
150
+ fail(reply, auth.reason === 'ORIGIN_DENIED' ? 403 : 401, auth.reason === 'ORIGIN_DENIED' ? 'ORIGIN_DENIED' : 'UNAUTHENTICATED');
151
+ return undefined;
152
+ }
153
+ allowOrigin(reply, auth.principal.origin);
154
+ ctxOf(req).principalId = auth.principal.principalId;
155
+ return auth.principal;
156
+ }
157
+ app.post('/v1/runs/prepare', async (req, reply) => {
158
+ const principal = authenticate(req, reply);
159
+ if (!principal)
160
+ return reply;
161
+ // Parse with the largest legal ceiling, then apply the per-operation cap: a larger prompt is accepted only for an operation the trusted
162
+ // composition says allows it. Oversize never reaches the coordinator and is never truncated. Total body stays under the 64 KiB limit.
163
+ const body = PrepareIntentRequestStdinV1Schema.safeParse(req.body);
164
+ if (!body.success)
165
+ return validationFail(reply, body.error);
166
+ const r = body.data;
167
+ const cap = deps.promptCapBytes?.(r.pluginId, r.operationId);
168
+ const allowed = cap !== undefined && Number.isInteger(cap) && cap > PROMPT_MAX_UTF8_BYTES ? Math.min(cap, PROMPT_MAX_UTF8_BYTES_STDIN_V1) : PROMPT_MAX_UTF8_BYTES;
169
+ if (Buffer.byteLength(r.params.prompt, 'utf8') > allowed)
170
+ return fail(reply, 400, 'VALIDATION_FAILED');
171
+ if (!authority.authorize(principal.principalId, r.projectId, r.pluginId, r.operationId)) {
172
+ note(req, 'WARN', 'AUTH', 'run.prepare', 'GRANT_DENIED', 'DENIED', { principalId: principal.principalId, projectId: r.projectId, pluginId: r.pluginId, operationId: r.operationId });
173
+ return fail(reply, 403, 'GRANT_DENIED');
174
+ }
175
+ try {
176
+ const out = coordinator.prepareIntent(principal.principalId, r);
177
+ note(req, 'INFO', 'RUN', 'run.prepare', out.duplicate ? 'RUN_PREPARE_DUPLICATE' : 'RUN_PREPARED', 'OK', { runId: out.runId, pluginId: r.pluginId, operationId: r.operationId });
178
+ return reply.code(out.duplicate ? 200 : 202).header('cache-control', 'no-store').send(PrepareIntentResponseV1Schema.parse({
179
+ schemaVersion: SCHEMA_VERSION_V1,
180
+ requestId: r.requestId,
181
+ runId: out.runId,
182
+ lifecycleState: 'AWAITING_USER_APPROVAL',
183
+ duplicate: out.duplicate,
184
+ createdAt: out.createdAt,
185
+ }));
186
+ }
187
+ catch (err) {
188
+ if (err instanceof IdempotencyConflictError)
189
+ return fail(reply, 409, 'IDEMPOTENCY_CONFLICT');
190
+ throw err;
191
+ }
192
+ });
193
+ /** Read-only status lookup shared by GET and POST: same principal scoping, same 404, same serializer. */
194
+ function sendStatus(reply, principalId, runId) {
195
+ const run = coordinator.getStatus(principalId, runId);
196
+ if (!run)
197
+ return fail(reply, 404, 'NOT_FOUND');
198
+ return reply.code(200).header('cache-control', 'no-store').send(RunStatusResponseV1Schema.parse({
199
+ schemaVersion: SCHEMA_VERSION_V1,
200
+ runId: run.runId,
201
+ lifecycleState: run.lifecycleState,
202
+ createdAt: run.createdAt,
203
+ updatedAt: run.updatedAt,
204
+ }));
205
+ }
206
+ app.get('/v1/runs/:runId', async (req, reply) => {
207
+ const principal = authenticate(req, reply);
208
+ if (!principal)
209
+ return reply;
210
+ const { runId } = req.params;
211
+ return sendStatus(reply, principal.principalId, runId);
212
+ });
213
+ // Extension-compatible status: a JSON POST makes Chromium attach the exact extension Origin that the GET
214
+ // form never receives. Authentication and non-disclosure are identical; nothing is written.
215
+ app.post('/v1/runs/:runId/status', async (req, reply) => {
216
+ const principal = authenticate(req, reply);
217
+ if (!principal)
218
+ return reply;
219
+ const body = RunStatusReadRequestV1Schema.safeParse(req.body);
220
+ if (!body.success)
221
+ return validationFail(reply, body.error);
222
+ const { runId } = req.params;
223
+ return sendStatus(reply, principal.principalId, runId);
224
+ });
225
+ // B05: prepare (or idempotently re-read) the immutable return snapshot of one COMPLETED run owned by the caller. A JSON POST so Chromium attaches the
226
+ // exact extension Origin. It creates no run and starts nothing; it only stores and returns the run's reported final text, and only to its owner.
227
+ app.post('/v1/runs/:runId/return', async (req, reply) => {
228
+ const principal = authenticate(req, reply);
229
+ if (!principal)
230
+ return reply;
231
+ const body = PrepareReturnRequestV1Schema.safeParse(req.body);
232
+ if (!body.success)
233
+ return validationFail(reply, body.error);
234
+ const { runId } = req.params;
235
+ const run = deps.ledger.getRunDetailForPrincipal(principal.principalId, runId);
236
+ if (!run)
237
+ return fail(reply, 404, 'NOT_FOUND'); // foreign and unknown runs are indistinguishable
238
+ // The result is project data: the caller must STILL hold a current grant for the operation that produced it.
239
+ if (!authority.authorize(principal.principalId, run.projectId, run.pluginId, run.operationId)) {
240
+ note(req, 'WARN', 'AUTH', 'run.return', 'GRANT_DENIED', 'DENIED', { runId, principalId: principal.principalId });
241
+ return fail(reply, 403, 'GRANT_DENIED');
242
+ }
243
+ const out = deps.ledger.prepareReturnSnapshot(principal.principalId, runId, new Date().toISOString(), (r, ev) => decideReturnSnapshot(r.runId, r.lifecycleState, ev));
244
+ switch (out.kind) {
245
+ case 'NOT_FOUND': return fail(reply, 404, 'NOT_FOUND');
246
+ case 'REFUSED': return fail(reply, 409, 'RETURN_NOT_AVAILABLE', { detail: { runId } });
247
+ case 'CONFLICT': return fail(reply, 409, 'RETURN_CONFLICT', { detail: { runId } });
248
+ case 'OK':
249
+ note(req, 'INFO', 'SNAPSHOT', 'run.return', out.duplicate ? 'RETURN_REREAD' : 'RETURN_PREPARED', 'OK', { runId, bytes: out.snapshot.bytes, sha256: out.snapshot.sha256 });
250
+ // SW-062: a run that came from a durable capture gets its ORIGIN return target (the tab/document of the gesture) recorded once.
251
+ if (deps.workflow) {
252
+ try {
253
+ deps.workflow.ensureOriginTarget(principal.principalId, out.snapshot);
254
+ }
255
+ catch {
256
+ note(req, 'WARN', 'SNAPSHOT', 'run.return', 'RETURN_TARGET_UNAVAILABLE', 'FAILED', { runId });
257
+ }
258
+ }
259
+ return reply.code(out.duplicate ? 200 : 201).header('cache-control', 'no-store').send(ReturnSnapshotResponseV1Schema.parse({
260
+ schemaVersion: SCHEMA_VERSION_V1, returnId: out.snapshot.returnId, runId: out.snapshot.runId, text: out.snapshot.text, sha256: out.snapshot.sha256,
261
+ bytes: out.snapshot.bytes, provenance: 'RUN_FINAL_MESSAGE_AGENT_REPORTED', createdAt: out.snapshot.createdAt, duplicate: out.duplicate,
262
+ }));
263
+ }
264
+ });
265
+ function sendDecision(reply, out, action) {
266
+ const req = reply.request;
267
+ switch (out.kind) {
268
+ case 'NOT_FOUND': return fail(reply, 404, 'NOT_FOUND', { detail: { action } });
269
+ case 'DENIED':
270
+ note(req, 'WARN', 'AUTH', `run.${action}`, out.code, 'DENIED');
271
+ return fail(reply, 403, out.code, { detail: { action } });
272
+ case 'CONFLICT': return fail(reply, 409, 'STATE_CONFLICT', { detail: { action } });
273
+ case 'OK':
274
+ note(req, 'INFO', 'RUN', `run.${action}`, action === 'approve' ? 'RUN_APPROVED' : 'RUN_CANCELLED', 'OK', { runId: out.runId, state: out.lifecycleState, duplicate: out.duplicate });
275
+ return reply.code(200).header('cache-control', 'no-store').send(RunDecisionResponseV1Schema.parse({
276
+ schemaVersion: SCHEMA_VERSION_V1,
277
+ runId: out.runId,
278
+ lifecycleState: out.lifecycleState,
279
+ updatedAt: out.updatedAt,
280
+ duplicate: out.duplicate,
281
+ }));
282
+ }
283
+ }
284
+ app.post('/v1/runs/:runId/approve', async (req, reply) => {
285
+ const principal = authenticate(req, reply);
286
+ if (!principal)
287
+ return reply;
288
+ const body = ApproveRunRequestV1Schema.safeParse(req.body);
289
+ if (!body.success)
290
+ return validationFail(reply, body.error);
291
+ const { runId } = req.params;
292
+ const out = coordinator.approveRun(principal.principalId, runId, body.data.approvalId, body.data.approvalCode);
293
+ // Only the first approval that committed QUEUED hands the run to the launcher; a replayed approval never relaunches.
294
+ if (launcher && out.kind === 'OK' && out.lifecycleState === 'QUEUED' && !out.duplicate) {
295
+ try {
296
+ launcher.launch(principal.principalId, runId);
297
+ note(req, 'INFO', 'RUN', 'run.launch', 'RUN_LAUNCH_REQUESTED', 'OK', { runId });
298
+ }
299
+ catch {
300
+ note(req, 'ERROR', 'RUN', 'run.launch', 'RUN_LAUNCH_FAILED', 'FAILED', { runId }); /* the owner records launch failures; the approval already committed */
301
+ }
302
+ }
303
+ return sendDecision(reply, out, 'approve');
304
+ });
305
+ registerWorkflowRoutes(app, {
306
+ diag,
307
+ authority, coordinator, ledger: deps.ledger, ...(deps.codingWorkflow ? { codingWorkflow: deps.codingWorkflow } : {}), ...(deps.workflow ? { workflow: deps.workflow } : {}), ...(launcher ? { launcher } : {}),
308
+ h: { authenticate, fail, validationFail, note },
309
+ });
310
+ app.post('/v1/runs/:runId/cancel', async (req, reply) => {
311
+ const principal = authenticate(req, reply);
312
+ if (!principal)
313
+ return reply;
314
+ const body = CancelPendingRunRequestV1Schema.safeParse(req.body);
315
+ if (!body.success)
316
+ return validationFail(reply, body.error);
317
+ const { runId } = req.params;
318
+ const out = coordinator.cancelRun(principal.principalId, runId);
319
+ if (out.kind === 'CONFLICT' && launcher) {
320
+ // Not pending/queued: it may be starting or running under the launcher, which persists CANCEL_REQUESTED before signalling.
321
+ const c = await launcher.cancel(principal.principalId, runId);
322
+ if (c === 'NOT_FOUND')
323
+ return fail(reply, 404, 'NOT_FOUND');
324
+ if (c === 'REQUESTED') {
325
+ const st = coordinator.getStatus(principal.principalId, runId);
326
+ return reply.code(202).header('cache-control', 'no-store').send(RunCancelAcceptedResponseV1Schema.parse({ schemaVersion: SCHEMA_VERSION_V1, runId, lifecycleState: 'CANCEL_REQUESTED', updatedAt: st?.updatedAt ?? new Date().toISOString() }));
327
+ }
328
+ }
329
+ return sendDecision(reply, out, 'cancel');
330
+ });
331
+ }
332
+ //# sourceMappingURL=secureRoutes.js.map
@@ -0,0 +1,41 @@
1
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
2
+ import type { DiagnosticLog } from '../../storage/diagnosticLog.js';
3
+ import type { ZodError } from 'zod';
4
+ import type { AuthenticatedPrincipal, PairedAuthority } from '../../projects/pairedAuthority.js';
5
+ import type { DurableIntentCoordinator } from '../../runs/durableIntentCoordinator.js';
6
+ import { type WorkflowService } from '../../runs/workflowService.js';
7
+ import type { CodingWorkflowService } from '../../runs/codingWorkflowService.js';
8
+ import type { SqliteLedger } from '../../storage/sqliteLedger.js';
9
+ import type { QueuedRunLauncher } from './secureRoutes.js';
10
+ /**
11
+ * C02 routes for SW-062 (registered by registerSecureRoutes, so they share its hooks: correlation ids, one summary log line, error mapping, body limit).
12
+ *
13
+ * Browser-facing (exact extension Origin + bearer, exactly like every B02 route):
14
+ * POST /v1/captures store the user-gesture capture (encrypted, TTL) POST /v1/captures/:captureId/run idempotent capture -> run
15
+ * POST /v1/workflow/current resume snapshot (the worker is stateless) POST /v1/workflow/preference default operation
16
+ * POST /v1/workflow/dismiss start over POST /v1/runs/:runId/wait bounded long-poll push
17
+ * POST /v1/returns/:returnId/receipt return state machine POST /v1/returns/:returnId/rebind explicit new target
18
+ * Native-host-facing (NO Origin and no browser fetch metadata at all; the installation secret is the proof; no CORS answer is ever produced):
19
+ * POST /v1/bootstrap/session short-lived bearer for the installation's principal
20
+ * POST /v1/bootstrap/pending|confirm local risk confirmation used by the setup CLI (`centcom confirm`)
21
+ */
22
+ export interface WorkflowRouteHelpers {
23
+ authenticate(req: FastifyRequest, reply: FastifyReply): AuthenticatedPrincipal | undefined;
24
+ fail(reply: FastifyReply, status: number, code: string, extra?: {
25
+ detail?: Record<string, unknown>;
26
+ }): FastifyReply;
27
+ validationFail(reply: FastifyReply, err: ZodError): FastifyReply;
28
+ note(req: FastifyRequest, level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR', component: 'AUTH' | 'RUN' | 'SNAPSHOT' | 'DAEMON', operation: string, event: string, outcome: 'OK' | 'FAILED' | 'DENIED' | 'REFUSED', meta?: Record<string, unknown>): void;
29
+ }
30
+ export declare const WORKFLOW_BROWSER_PATHS: readonly ["/v1/runs/:runId/activity", "/v1/coding/:runId/status", "/v1/coding/:runId/proposal", "/v1/coding/:runId/action", "/v1/coding/:runId/reviewed-patch", "/v1/coding/:runId/commit-review", "/v1/coding/:runId/reviewed-commit", "/v1/coding/trusted-consent", "/v1/captures/:captureId/coding", "/v1/captures", "/v1/captures/:captureId/run", "/v1/workflow/current", "/v1/workflow/preference", "/v1/workflow/dismiss", "/v1/runs/:runId/wait", "/v1/returns/:returnId/receipt", "/v1/returns/:returnId/rebind"];
31
+ export declare function registerWorkflowRoutes(app: FastifyInstance, deps: {
32
+ diag?: DiagnosticLog;
33
+ ledger: SqliteLedger;
34
+ codingWorkflow?: () => Promise<CodingWorkflowService>;
35
+ authority: PairedAuthority;
36
+ coordinator: DurableIntentCoordinator;
37
+ workflow?: WorkflowService;
38
+ launcher?: QueuedRunLauncher;
39
+ h: WorkflowRouteHelpers;
40
+ }): void;
41
+ //# sourceMappingURL=workflowRoutes.d.ts.map