@mycadet/credential-executor 0.13.0-dev.202611141833.f5bfff5 → 0.13.0-dev.202611142201.aad87f9
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.
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +12 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/rpc.ts +33 -3
- package/node_modules/@mycadet/ces-client/package.json +3 -1
- package/node_modules/@mycadet/ces-client/src/index.ts +1 -1
- package/node_modules/@mycadet/ces-client/src/ipc-credentials.ts +14 -19
- package/node_modules/@mycadet/ces-client/src/log-export.ts +187 -0
- package/node_modules/@mycadet/ces-client/src/socket-path.ts +1 -1
- package/node_modules/@mycadet/ces-client/src/test-support.ts +280 -0
- package/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +12 -0
- package/node_modules/@mycadet/service-contracts/src/rpc.ts +33 -3
- package/package.json +1 -1
- package/src/__tests__/local-secure-key-backend.test.ts +57 -22
- package/src/__tests__/transport.test.ts +6 -10
- package/src/index.ts +1 -5
- package/src/log-export.ts +132 -0
- package/src/main.ts +39 -8
- package/src/paths.ts +1 -1
- package/src/records/metadata-store.ts +37 -0
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Wire contracts for the remote-web pairing flow — the RFC 8628-style
|
|
3
5
|
* device-code exchange that connects a browser (or the iOS app) to a
|
|
@@ -59,6 +61,16 @@ export interface RemoteWebPairingChallengeResponse {
|
|
|
59
61
|
intervalSeconds: number;
|
|
60
62
|
}
|
|
61
63
|
|
|
64
|
+
export const RemoteWebPairingChallengeResponseSchema = z.object({
|
|
65
|
+
deviceCode: z.string(),
|
|
66
|
+
userCode: z.string(),
|
|
67
|
+
verificationUri: z.string(),
|
|
68
|
+
publicBaseUrl: z.string(),
|
|
69
|
+
expiresAt: z.string(),
|
|
70
|
+
expiresInSeconds: z.number(),
|
|
71
|
+
intervalSeconds: z.number(),
|
|
72
|
+
}) satisfies z.ZodType<RemoteWebPairingChallengeResponse>;
|
|
73
|
+
|
|
62
74
|
/** `POST /v1/remote-web/pairing-verification` request body. */
|
|
63
75
|
export interface RemoteWebPairingVerificationRequest {
|
|
64
76
|
/** The `userCode` from the challenge, entered/scanned on the host. */
|
|
@@ -55,6 +55,8 @@ export const CesRpcMethod = {
|
|
|
55
55
|
ListCredentialRecords: "list_credential_records",
|
|
56
56
|
/** Bulk-import credential records. */
|
|
57
57
|
BulkSetCredentialRecords: "bulk_set_credential_records",
|
|
58
|
+
/** Collect CES's own log files for a diagnostic export (tar.gz, base64). */
|
|
59
|
+
ExportLogs: "export_logs",
|
|
58
60
|
} as const;
|
|
59
61
|
|
|
60
62
|
export type CesRpcMethod = (typeof CesRpcMethod)[keyof typeof CesRpcMethod];
|
|
@@ -72,9 +74,7 @@ export const UpdateCloudCredentialSchema = z.object({
|
|
|
72
74
|
*/
|
|
73
75
|
assistantId: z.string().optional(),
|
|
74
76
|
});
|
|
75
|
-
export type UpdateCloudCredential = z.infer<
|
|
76
|
-
typeof UpdateCloudCredentialSchema
|
|
77
|
-
>;
|
|
77
|
+
export type UpdateCloudCredential = z.infer<typeof UpdateCloudCredentialSchema>;
|
|
78
78
|
|
|
79
79
|
export const UpdateCloudCredentialResponseSchema = z.object({
|
|
80
80
|
/** Whether the cloud credential was successfully updated. */
|
|
@@ -302,6 +302,28 @@ export type BulkSetCredentialRecordsResponse = z.infer<
|
|
|
302
302
|
typeof BulkSetCredentialRecordsResponseSchema
|
|
303
303
|
>;
|
|
304
304
|
|
|
305
|
+
// ---------------------------------------------------------------------------
|
|
306
|
+
// export_logs
|
|
307
|
+
// ---------------------------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
export const ExportLogsSchema = z.object({
|
|
310
|
+
/** Inclusive range start (epoch ms); log files entirely before it are skipped. */
|
|
311
|
+
startTime: z.number().optional(),
|
|
312
|
+
/** Inclusive range end (epoch ms); log files entirely after it are skipped. */
|
|
313
|
+
endTime: z.number().optional(),
|
|
314
|
+
});
|
|
315
|
+
export type ExportLogs = z.infer<typeof ExportLogsSchema>;
|
|
316
|
+
|
|
317
|
+
export const ExportLogsResponseSchema = z.object({
|
|
318
|
+
/** tar.gz of the collected log files plus a manifest, base64-encoded. */
|
|
319
|
+
archiveBase64: z.string(),
|
|
320
|
+
/** Number of log files included in the archive. */
|
|
321
|
+
filesCollected: z.number(),
|
|
322
|
+
/** Cumulative size of the collected log files, before archiving. */
|
|
323
|
+
totalBytes: z.number(),
|
|
324
|
+
});
|
|
325
|
+
export type ExportLogsResponse = z.infer<typeof ExportLogsResponseSchema>;
|
|
326
|
+
|
|
305
327
|
// ---------------------------------------------------------------------------
|
|
306
328
|
// Full RPC contract type map
|
|
307
329
|
// ---------------------------------------------------------------------------
|
|
@@ -355,6 +377,10 @@ export interface CesRpcContract {
|
|
|
355
377
|
request: BulkSetCredentialRecords;
|
|
356
378
|
response: BulkSetCredentialRecordsResponse;
|
|
357
379
|
};
|
|
380
|
+
[CesRpcMethod.ExportLogs]: {
|
|
381
|
+
request: ExportLogs;
|
|
382
|
+
response: ExportLogsResponse;
|
|
383
|
+
};
|
|
358
384
|
}
|
|
359
385
|
|
|
360
386
|
/**
|
|
@@ -405,4 +431,8 @@ export const CesRpcSchemas = {
|
|
|
405
431
|
request: BulkSetCredentialRecordsSchema,
|
|
406
432
|
response: BulkSetCredentialRecordsResponseSchema,
|
|
407
433
|
},
|
|
434
|
+
[CesRpcMethod.ExportLogs]: {
|
|
435
|
+
request: ExportLogsSchema,
|
|
436
|
+
response: ExportLogsResponseSchema,
|
|
437
|
+
},
|
|
408
438
|
} as const;
|
|
@@ -9,9 +9,11 @@
|
|
|
9
9
|
"./http-credentials": "./src/http-credentials.ts",
|
|
10
10
|
"./http-log-export": "./src/http-log-export.ts",
|
|
11
11
|
"./ipc-credentials": "./src/ipc-credentials.ts",
|
|
12
|
+
"./log-export": "./src/log-export.ts",
|
|
12
13
|
"./rpc-client": "./src/rpc-client.ts",
|
|
13
14
|
"./credential-rpc": "./src/credential-rpc.ts",
|
|
14
|
-
"./socket-path": "./src/socket-path.ts"
|
|
15
|
+
"./socket-path": "./src/socket-path.ts",
|
|
16
|
+
"./test-support": "./src/test-support.ts"
|
|
15
17
|
},
|
|
16
18
|
"scripts": {
|
|
17
19
|
"typecheck": "bunx tsc --noEmit"
|
|
@@ -21,11 +21,8 @@ import type { CesRpcContract } from "@mycadet/service-contracts/credential-rpc";
|
|
|
21
21
|
import { CesRpcMethod } from "@mycadet/service-contracts/credential-rpc";
|
|
22
22
|
import type { CredentialRecord } from "@mycadet/service-contracts/credential-rpc";
|
|
23
23
|
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
createCesRpcClient,
|
|
27
|
-
type CesRpcClient,
|
|
28
|
-
} from "./rpc-client.js";
|
|
24
|
+
import { getCesSocketPath } from "./socket-path.js";
|
|
25
|
+
import { createCesRpcClient, type CesRpcClient } from "./rpc-client.js";
|
|
29
26
|
|
|
30
27
|
export type { CredentialRecord };
|
|
31
28
|
|
|
@@ -202,7 +199,7 @@ export function createCesIpcCredentialClient(
|
|
|
202
199
|
let lastFailedAttemptAt = 0;
|
|
203
200
|
|
|
204
201
|
function isAvailable(): boolean {
|
|
205
|
-
const socketPath =
|
|
202
|
+
const socketPath = getCesSocketPath();
|
|
206
203
|
return socketPath.startsWith("\\\\.\\pipe\\") || existsSync(socketPath);
|
|
207
204
|
}
|
|
208
205
|
|
|
@@ -221,7 +218,7 @@ export function createCesIpcCredentialClient(
|
|
|
221
218
|
}
|
|
222
219
|
if (!clientAttempt) {
|
|
223
220
|
clientAttempt = (async () => {
|
|
224
|
-
const socketPath =
|
|
221
|
+
const socketPath = getCesSocketPath();
|
|
225
222
|
const transport = await connectSocket(socketPath, logger);
|
|
226
223
|
const rpc = createCesRpcClient(transport, {
|
|
227
224
|
handshakeTimeoutMs: SOCKET_CONNECT_TIMEOUT_MS,
|
|
@@ -303,10 +300,9 @@ export function createCesIpcCredentialClient(
|
|
|
303
300
|
},
|
|
304
301
|
|
|
305
302
|
async bulkSet(credentials) {
|
|
306
|
-
const result = await callOrUnreachable(
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
);
|
|
303
|
+
const result = await callOrUnreachable(CesRpcMethod.BulkSetCredentials, {
|
|
304
|
+
credentials,
|
|
305
|
+
});
|
|
310
306
|
if (!result.ok) {
|
|
311
307
|
return credentials.map(({ account }) => ({ account, ok: false }));
|
|
312
308
|
}
|
|
@@ -320,19 +316,18 @@ export function createCesIpcCredentialClient(
|
|
|
320
316
|
},
|
|
321
317
|
|
|
322
318
|
async getRecord(account) {
|
|
323
|
-
const result = await callOrUnreachable(
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
);
|
|
319
|
+
const result = await callOrUnreachable(CesRpcMethod.GetCredentialRecord, {
|
|
320
|
+
account,
|
|
321
|
+
});
|
|
327
322
|
if (!result.ok) return { record: undefined, unreachable: true };
|
|
328
323
|
return { record: result.response.record, unreachable: false };
|
|
329
324
|
},
|
|
330
325
|
|
|
331
326
|
async setRecord(account, record) {
|
|
332
|
-
const result = await callOrUnreachable(
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
);
|
|
327
|
+
const result = await callOrUnreachable(CesRpcMethod.SetCredentialRecord, {
|
|
328
|
+
account,
|
|
329
|
+
record,
|
|
330
|
+
});
|
|
336
331
|
return result.ok && result.response.ok;
|
|
337
332
|
},
|
|
338
333
|
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IPC client for the CES log export.
|
|
3
|
+
*
|
|
4
|
+
* The IPC-only replacement for `http-log-export` — same result shape
|
|
5
|
+
* (`{ ok, data }` tar.gz bytes), different transport. Log collection is a
|
|
6
|
+
* rare diagnostic operation, so this opens a one-shot connection per export
|
|
7
|
+
* (connect, handshake, `export_logs`, close) instead of holding a session.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createConnection } from "node:net";
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { StringDecoder } from "node:string_decoder";
|
|
13
|
+
|
|
14
|
+
import { CesRpcMethod } from "@mycadet/service-contracts/credential-rpc";
|
|
15
|
+
|
|
16
|
+
import { createCesRpcClient } from "./rpc-client.js";
|
|
17
|
+
import { getCesSocketPath } from "./socket-path.js";
|
|
18
|
+
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// Types (shared with the HTTP client's shapes)
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
/** Options for a log export request. */
|
|
24
|
+
export interface CesLogExportOptions {
|
|
25
|
+
/** Start of the date range (epoch milliseconds). */
|
|
26
|
+
startTime?: number;
|
|
27
|
+
/** End of the date range (epoch milliseconds). */
|
|
28
|
+
endTime?: number;
|
|
29
|
+
/** Request timeout in milliseconds. Default: 120 000. */
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Successful log export result. */
|
|
34
|
+
export interface CesLogExportSuccess {
|
|
35
|
+
ok: true;
|
|
36
|
+
/** Raw tar.gz archive bytes. */
|
|
37
|
+
data: ArrayBuffer;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Failed log export result. */
|
|
41
|
+
export interface CesLogExportFailure {
|
|
42
|
+
ok: false;
|
|
43
|
+
/** Human-readable error message. */
|
|
44
|
+
error: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type CesLogExportResult = CesLogExportSuccess | CesLogExportFailure;
|
|
48
|
+
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
// Constants
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
54
|
+
|
|
55
|
+
const SOCKET_CONNECT_TIMEOUT_MS = 5_000;
|
|
56
|
+
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
// Client
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Fetch a tar.gz archive of CES logs over the shared Unix socket. The
|
|
63
|
+
* archive bytes are returned for the consumer to stage/extract as needed.
|
|
64
|
+
*/
|
|
65
|
+
export async function exportCesLogs(
|
|
66
|
+
options?: CesLogExportOptions,
|
|
67
|
+
): Promise<CesLogExportResult> {
|
|
68
|
+
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
69
|
+
const socketPath = getCesSocketPath();
|
|
70
|
+
|
|
71
|
+
if (!socketPath.startsWith("\\\\.\\pipe\\") && !existsSync(socketPath)) {
|
|
72
|
+
return { ok: false, error: `CES socket not found at ${socketPath}` };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let rpc: ReturnType<typeof createCesRpcClient> | undefined;
|
|
76
|
+
try {
|
|
77
|
+
const transport = await connectSocket(socketPath, timeoutMs);
|
|
78
|
+
rpc = createCesRpcClient(transport, {
|
|
79
|
+
handshakeTimeoutMs: SOCKET_CONNECT_TIMEOUT_MS,
|
|
80
|
+
requestTimeoutMs: timeoutMs,
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const { accepted, reason } = await rpc.handshake();
|
|
84
|
+
if (!accepted) {
|
|
85
|
+
return { ok: false, error: `CES handshake rejected: ${reason}` };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const result = await rpc.call(CesRpcMethod.ExportLogs, {
|
|
89
|
+
...(options?.startTime !== undefined
|
|
90
|
+
? { startTime: options.startTime }
|
|
91
|
+
: {}),
|
|
92
|
+
...(options?.endTime !== undefined ? { endTime: options.endTime } : {}),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
const archive = Buffer.from(result.archiveBase64, "base64");
|
|
96
|
+
const bytes = new ArrayBuffer(archive.byteLength);
|
|
97
|
+
new Uint8Array(bytes).set(archive);
|
|
98
|
+
return { ok: true, data: bytes };
|
|
99
|
+
} catch (err) {
|
|
100
|
+
return {
|
|
101
|
+
ok: false,
|
|
102
|
+
error: err instanceof Error ? err.message : String(err),
|
|
103
|
+
};
|
|
104
|
+
} finally {
|
|
105
|
+
rpc?.close();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
// One-shot socket transport
|
|
111
|
+
// ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
interface SocketTransport {
|
|
114
|
+
write(line: string): void;
|
|
115
|
+
onMessage(handler: (message: string) => void): void;
|
|
116
|
+
isAlive(): boolean;
|
|
117
|
+
close(): void;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function connectSocket(
|
|
121
|
+
socketPath: string,
|
|
122
|
+
timeoutMs: number,
|
|
123
|
+
): Promise<SocketTransport> {
|
|
124
|
+
return new Promise<SocketTransport>((resolve, reject) => {
|
|
125
|
+
const socket = createConnection({ path: socketPath });
|
|
126
|
+
const messageHandlers: Array<(message: string) => void> = [];
|
|
127
|
+
let buffer = "";
|
|
128
|
+
let closed = false;
|
|
129
|
+
const decoder = new StringDecoder("utf8");
|
|
130
|
+
|
|
131
|
+
const timer = setTimeout(
|
|
132
|
+
() => {
|
|
133
|
+
socket.destroy();
|
|
134
|
+
reject(
|
|
135
|
+
new Error(
|
|
136
|
+
`Connection to CES socket at ${socketPath} timed out after ${SOCKET_CONNECT_TIMEOUT_MS}ms`,
|
|
137
|
+
),
|
|
138
|
+
);
|
|
139
|
+
},
|
|
140
|
+
Math.min(SOCKET_CONNECT_TIMEOUT_MS, timeoutMs),
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
socket.on("connect", () => {
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
resolve({
|
|
146
|
+
write(line: string): void {
|
|
147
|
+
if (closed || socket.destroyed) {
|
|
148
|
+
throw new Error("CES socket transport is not alive");
|
|
149
|
+
}
|
|
150
|
+
socket.write(line + "\n");
|
|
151
|
+
},
|
|
152
|
+
onMessage(handler: (message: string) => void): void {
|
|
153
|
+
messageHandlers.push(handler);
|
|
154
|
+
},
|
|
155
|
+
isAlive(): boolean {
|
|
156
|
+
return !closed && !socket.destroyed;
|
|
157
|
+
},
|
|
158
|
+
close(): void {
|
|
159
|
+
closed = true;
|
|
160
|
+
socket.destroy();
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
socket.on("error", (err) => {
|
|
166
|
+
if (timer.hasRef?.()) {
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
socket.destroy();
|
|
169
|
+
reject(err);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
socket.on("data", (chunk: Buffer | string) => {
|
|
174
|
+
buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
|
|
175
|
+
let newlineIdx: number;
|
|
176
|
+
while ((newlineIdx = buffer.indexOf("\n")) !== -1) {
|
|
177
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
178
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
179
|
+
if (line) {
|
|
180
|
+
for (const handler of messageHandlers) {
|
|
181
|
+
handler(line);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
}
|
|
@@ -29,6 +29,6 @@ export function getCesSocketDir(): string {
|
|
|
29
29
|
* gateway dial the same path CES binds. Resolved through `resolveIpcEndpoint`
|
|
30
30
|
* so macOS AF_UNIX limits and Windows named pipes stay consistent.
|
|
31
31
|
*/
|
|
32
|
-
export function
|
|
32
|
+
export function getCesSocketPath(): string {
|
|
33
33
|
return resolveIpcEndpoint("ces", { workspaceDir: getCesSocketDir() }).path;
|
|
34
34
|
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process CES RPC test double served over a REAL unix socket.
|
|
3
|
+
*
|
|
4
|
+
* The production record backend discovers `ces.sock` under
|
|
5
|
+
* `CES_SOCKET_DIR` and speaks the newline-delimited JSON RPC
|
|
6
|
+
* protocol (`@mycadet/service-contracts` transport contract). This helper
|
|
7
|
+
* binds that socket and answers handshake + record/credential requests from
|
|
8
|
+
* an in-memory store — the real client, transport and discovery run
|
|
9
|
+
* unmocked.
|
|
10
|
+
*
|
|
11
|
+
* Two ways to use it:
|
|
12
|
+
* - `startTestCesRecordServer()` — self-contained: mints its own temp socket
|
|
13
|
+
* dir and patches `process.env.CES_SOCKET_DIR` so in-process callers dial
|
|
14
|
+
* the fake. Install BEFORE the first backend operation.
|
|
15
|
+
* - `startTestCesRecordServer({ socketDir })` — for tests that spawn a CHILD
|
|
16
|
+
* process (gateway, assistant) which must be given the socket dir in its
|
|
17
|
+
* env up front: bind a dir the caller chose and never touch `process.env`.
|
|
18
|
+
* Pass a dir that does not exist yet to simulate "CES will appear later".
|
|
19
|
+
*/
|
|
20
|
+
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
|
21
|
+
import { createServer, type Server, type Socket } from "node:net";
|
|
22
|
+
import { tmpdir } from "node:os";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
|
|
25
|
+
import { resolveIpcEndpoint } from "@mycadet/ipc-server-utils";
|
|
26
|
+
import { CES_PROTOCOL_VERSION } from "@mycadet/service-contracts";
|
|
27
|
+
import type { CredentialRecord } from "@mycadet/service-contracts/credential-rpc";
|
|
28
|
+
import { CesRpcMethod } from "@mycadet/service-contracts/credential-rpc";
|
|
29
|
+
|
|
30
|
+
export interface TestCesRecordServer {
|
|
31
|
+
/** Secret-value store backing get/set/delete/list_credential. */
|
|
32
|
+
secrets: Map<string, string>;
|
|
33
|
+
/** Record store backing the *_credential_record methods. */
|
|
34
|
+
records: Map<string, CredentialRecord>;
|
|
35
|
+
/** Every RPC request that reached the server, in order. */
|
|
36
|
+
calls: Array<{ method: CesRpcMethod; request: unknown }>;
|
|
37
|
+
/** Make every set/bulk-set RPC fail. */
|
|
38
|
+
failSet: boolean;
|
|
39
|
+
/** Make every list RPC throw (a transport-level outage). */
|
|
40
|
+
failList: boolean;
|
|
41
|
+
/** Whether the socket is currently listening. */
|
|
42
|
+
listening: boolean;
|
|
43
|
+
/** Drop every open connection (a CES bounce). */
|
|
44
|
+
dropConnections: () => void;
|
|
45
|
+
/** Stop listening and remove the temp socket dir (CES unreachable). */
|
|
46
|
+
stop: () => Promise<void>;
|
|
47
|
+
/** Listen again on a fresh socket dir (CES came back). */
|
|
48
|
+
start: () => void;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function startTestCesRecordServer(options?: {
|
|
52
|
+
socketDir?: string;
|
|
53
|
+
}): TestCesRecordServer {
|
|
54
|
+
const secrets = new Map<string, string>();
|
|
55
|
+
const records = new Map<string, CredentialRecord>();
|
|
56
|
+
const calls: Array<{ method: CesRpcMethod; request: unknown }> = [];
|
|
57
|
+
const state = { failSet: false, failList: false };
|
|
58
|
+
const ownsEnv = options?.socketDir === undefined;
|
|
59
|
+
|
|
60
|
+
const sockets = new Set<Socket>();
|
|
61
|
+
let server: Server | undefined;
|
|
62
|
+
let socketDir: string | undefined;
|
|
63
|
+
|
|
64
|
+
const listen = (): void => {
|
|
65
|
+
if (server) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
socketDir =
|
|
69
|
+
options?.socketDir ?? mkdtempSync(join(tmpdir(), "test-ces-socket-"));
|
|
70
|
+
if (ownsEnv) {
|
|
71
|
+
process.env.CES_SOCKET_DIR = socketDir;
|
|
72
|
+
}
|
|
73
|
+
mkdirSync(socketDir, { recursive: true });
|
|
74
|
+
const socketPath = resolveIpcEndpoint("ces", {
|
|
75
|
+
workspaceDir: socketDir,
|
|
76
|
+
}).path;
|
|
77
|
+
server = createServer((socket) => wire(socket));
|
|
78
|
+
server.listen(socketPath);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const handleRpc = (
|
|
82
|
+
id: string,
|
|
83
|
+
method: CesRpcMethod,
|
|
84
|
+
request: unknown,
|
|
85
|
+
): unknown => {
|
|
86
|
+
calls.push({ method, request });
|
|
87
|
+
const req = request as {
|
|
88
|
+
account?: string;
|
|
89
|
+
value?: string;
|
|
90
|
+
record?: CredentialRecord;
|
|
91
|
+
records?: Array<{ account: string; record: CredentialRecord }>;
|
|
92
|
+
credentials?: Array<{ account: string; value: string }>;
|
|
93
|
+
};
|
|
94
|
+
switch (method) {
|
|
95
|
+
case CesRpcMethod.GetCredential: {
|
|
96
|
+
const value =
|
|
97
|
+
req.account !== undefined ? secrets.get(req.account) : undefined;
|
|
98
|
+
return value !== undefined ? { found: true, value } : { found: false };
|
|
99
|
+
}
|
|
100
|
+
case CesRpcMethod.SetCredential: {
|
|
101
|
+
if (state.failSet || req.account === undefined) {
|
|
102
|
+
return { ok: false };
|
|
103
|
+
}
|
|
104
|
+
secrets.set(req.account, req.value ?? "");
|
|
105
|
+
return { ok: true };
|
|
106
|
+
}
|
|
107
|
+
case CesRpcMethod.DeleteCredential: {
|
|
108
|
+
if (req.account === undefined || !secrets.has(req.account)) {
|
|
109
|
+
return { result: "not-found" };
|
|
110
|
+
}
|
|
111
|
+
secrets.delete(req.account);
|
|
112
|
+
return { result: "deleted" };
|
|
113
|
+
}
|
|
114
|
+
case CesRpcMethod.ListCredentials: {
|
|
115
|
+
if (state.failList) {
|
|
116
|
+
throw new Error("credential list transport failed");
|
|
117
|
+
}
|
|
118
|
+
return { accounts: [...secrets.keys()] };
|
|
119
|
+
}
|
|
120
|
+
case CesRpcMethod.GetCredentialRecord: {
|
|
121
|
+
const record =
|
|
122
|
+
req.account !== undefined ? records.get(req.account) : undefined;
|
|
123
|
+
return record ? { found: true, record } : { found: false };
|
|
124
|
+
}
|
|
125
|
+
case CesRpcMethod.SetCredentialRecord: {
|
|
126
|
+
if (state.failSet || !req.account || !req.record) {
|
|
127
|
+
return { ok: false };
|
|
128
|
+
}
|
|
129
|
+
records.set(req.account, req.record);
|
|
130
|
+
return { ok: true };
|
|
131
|
+
}
|
|
132
|
+
case CesRpcMethod.DeleteCredentialRecord: {
|
|
133
|
+
if (!req.account || !records.has(req.account)) {
|
|
134
|
+
return { result: "not-found" };
|
|
135
|
+
}
|
|
136
|
+
records.delete(req.account);
|
|
137
|
+
return { result: "deleted" };
|
|
138
|
+
}
|
|
139
|
+
case CesRpcMethod.ListCredentialRecords: {
|
|
140
|
+
if (state.failList) {
|
|
141
|
+
throw new Error("record list transport failed");
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
records: [...records.entries()].map(([account, record]) => ({
|
|
145
|
+
account,
|
|
146
|
+
record,
|
|
147
|
+
})),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
case CesRpcMethod.BulkSetCredentialRecords: {
|
|
151
|
+
const results = (req.records ?? []).map((entry) => {
|
|
152
|
+
if (state.failSet) {
|
|
153
|
+
return { account: entry.account, ok: false };
|
|
154
|
+
}
|
|
155
|
+
records.set(entry.account, entry.record);
|
|
156
|
+
return { account: entry.account, ok: true };
|
|
157
|
+
});
|
|
158
|
+
return { results };
|
|
159
|
+
}
|
|
160
|
+
default:
|
|
161
|
+
return {};
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const wire = (socket: Socket): void => {
|
|
166
|
+
sockets.add(socket);
|
|
167
|
+
let buffer = "";
|
|
168
|
+
socket.on("data", (chunk) => {
|
|
169
|
+
buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
170
|
+
let newlineIdx: number;
|
|
171
|
+
while ((newlineIdx = buffer.indexOf("\n")) !== -1) {
|
|
172
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
173
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
174
|
+
if (!line) {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
let message: Record<string, unknown>;
|
|
178
|
+
try {
|
|
179
|
+
message = JSON.parse(line) as Record<string, unknown>;
|
|
180
|
+
} catch {
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (message.type === "handshake_request") {
|
|
184
|
+
socket.write(
|
|
185
|
+
`${JSON.stringify({
|
|
186
|
+
type: "handshake_ack",
|
|
187
|
+
protocolVersion: CES_PROTOCOL_VERSION,
|
|
188
|
+
sessionId: message.sessionId,
|
|
189
|
+
accepted: message.protocolVersion === CES_PROTOCOL_VERSION,
|
|
190
|
+
})}\n`,
|
|
191
|
+
);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (message.type === "rpc" && message.kind === "request") {
|
|
195
|
+
let payload: unknown;
|
|
196
|
+
try {
|
|
197
|
+
payload = handleRpc(
|
|
198
|
+
String(message.id),
|
|
199
|
+
message.method as CesRpcMethod,
|
|
200
|
+
message.payload,
|
|
201
|
+
);
|
|
202
|
+
} catch {
|
|
203
|
+
socket.write(
|
|
204
|
+
`${JSON.stringify({
|
|
205
|
+
kind: "response",
|
|
206
|
+
id: message.id,
|
|
207
|
+
error: {
|
|
208
|
+
code: "CES_INTERNAL",
|
|
209
|
+
message: "test server failure",
|
|
210
|
+
},
|
|
211
|
+
})}\n`,
|
|
212
|
+
);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
socket.write(
|
|
216
|
+
`${JSON.stringify({ kind: "response", id: message.id, payload })}\n`,
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
socket.on("error", () => {});
|
|
222
|
+
socket.on("close", () => sockets.delete(socket));
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
listen();
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
secrets,
|
|
229
|
+
records,
|
|
230
|
+
calls,
|
|
231
|
+
get failSet() {
|
|
232
|
+
return state.failSet;
|
|
233
|
+
},
|
|
234
|
+
set failSet(v: boolean) {
|
|
235
|
+
state.failSet = v;
|
|
236
|
+
},
|
|
237
|
+
get failList() {
|
|
238
|
+
return state.failList;
|
|
239
|
+
},
|
|
240
|
+
set failList(v: boolean) {
|
|
241
|
+
state.failList = v;
|
|
242
|
+
},
|
|
243
|
+
get listening() {
|
|
244
|
+
return !!server;
|
|
245
|
+
},
|
|
246
|
+
dropConnections: () => {
|
|
247
|
+
for (const socket of sockets) {
|
|
248
|
+
socket.destroy();
|
|
249
|
+
}
|
|
250
|
+
sockets.clear();
|
|
251
|
+
},
|
|
252
|
+
stop: async () => {
|
|
253
|
+
for (const socket of sockets) {
|
|
254
|
+
socket.destroy();
|
|
255
|
+
}
|
|
256
|
+
sockets.clear();
|
|
257
|
+
await new Promise<void>((resolve) => {
|
|
258
|
+
if (!server) {
|
|
259
|
+
resolve();
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
server.close(() => resolve());
|
|
263
|
+
});
|
|
264
|
+
server = undefined;
|
|
265
|
+
if (socketDir && ownsEnv) {
|
|
266
|
+
rmSync(socketDir, { recursive: true, force: true });
|
|
267
|
+
}
|
|
268
|
+
if (ownsEnv) {
|
|
269
|
+
// While stopped, discovery must NOT fall through to a live machine
|
|
270
|
+
// socket — point it at an empty dir.
|
|
271
|
+
const emptyDir = mkdtempSync(join(tmpdir(), "test-ces-empty-"));
|
|
272
|
+
process.env.CES_SOCKET_DIR = emptyDir;
|
|
273
|
+
socketDir = emptyDir;
|
|
274
|
+
} else {
|
|
275
|
+
socketDir = undefined;
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
start: listen,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Wire contracts for the remote-web pairing flow — the RFC 8628-style
|
|
3
5
|
* device-code exchange that connects a browser (or the iOS app) to a
|
|
@@ -59,6 +61,16 @@ export interface RemoteWebPairingChallengeResponse {
|
|
|
59
61
|
intervalSeconds: number;
|
|
60
62
|
}
|
|
61
63
|
|
|
64
|
+
export const RemoteWebPairingChallengeResponseSchema = z.object({
|
|
65
|
+
deviceCode: z.string(),
|
|
66
|
+
userCode: z.string(),
|
|
67
|
+
verificationUri: z.string(),
|
|
68
|
+
publicBaseUrl: z.string(),
|
|
69
|
+
expiresAt: z.string(),
|
|
70
|
+
expiresInSeconds: z.number(),
|
|
71
|
+
intervalSeconds: z.number(),
|
|
72
|
+
}) satisfies z.ZodType<RemoteWebPairingChallengeResponse>;
|
|
73
|
+
|
|
62
74
|
/** `POST /v1/remote-web/pairing-verification` request body. */
|
|
63
75
|
export interface RemoteWebPairingVerificationRequest {
|
|
64
76
|
/** The `userCode` from the challenge, entered/scanned on the host. */
|
|
@@ -55,6 +55,8 @@ export const CesRpcMethod = {
|
|
|
55
55
|
ListCredentialRecords: "list_credential_records",
|
|
56
56
|
/** Bulk-import credential records. */
|
|
57
57
|
BulkSetCredentialRecords: "bulk_set_credential_records",
|
|
58
|
+
/** Collect CES's own log files for a diagnostic export (tar.gz, base64). */
|
|
59
|
+
ExportLogs: "export_logs",
|
|
58
60
|
} as const;
|
|
59
61
|
|
|
60
62
|
export type CesRpcMethod = (typeof CesRpcMethod)[keyof typeof CesRpcMethod];
|
|
@@ -72,9 +74,7 @@ export const UpdateCloudCredentialSchema = z.object({
|
|
|
72
74
|
*/
|
|
73
75
|
assistantId: z.string().optional(),
|
|
74
76
|
});
|
|
75
|
-
export type UpdateCloudCredential = z.infer<
|
|
76
|
-
typeof UpdateCloudCredentialSchema
|
|
77
|
-
>;
|
|
77
|
+
export type UpdateCloudCredential = z.infer<typeof UpdateCloudCredentialSchema>;
|
|
78
78
|
|
|
79
79
|
export const UpdateCloudCredentialResponseSchema = z.object({
|
|
80
80
|
/** Whether the cloud credential was successfully updated. */
|
|
@@ -302,6 +302,28 @@ export type BulkSetCredentialRecordsResponse = z.infer<
|
|
|
302
302
|
typeof BulkSetCredentialRecordsResponseSchema
|
|
303
303
|
>;
|
|
304
304
|
|
|
305
|
+
// ---------------------------------------------------------------------------
|
|
306
|
+
// export_logs
|
|
307
|
+
// ---------------------------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
export const ExportLogsSchema = z.object({
|
|
310
|
+
/** Inclusive range start (epoch ms); log files entirely before it are skipped. */
|
|
311
|
+
startTime: z.number().optional(),
|
|
312
|
+
/** Inclusive range end (epoch ms); log files entirely after it are skipped. */
|
|
313
|
+
endTime: z.number().optional(),
|
|
314
|
+
});
|
|
315
|
+
export type ExportLogs = z.infer<typeof ExportLogsSchema>;
|
|
316
|
+
|
|
317
|
+
export const ExportLogsResponseSchema = z.object({
|
|
318
|
+
/** tar.gz of the collected log files plus a manifest, base64-encoded. */
|
|
319
|
+
archiveBase64: z.string(),
|
|
320
|
+
/** Number of log files included in the archive. */
|
|
321
|
+
filesCollected: z.number(),
|
|
322
|
+
/** Cumulative size of the collected log files, before archiving. */
|
|
323
|
+
totalBytes: z.number(),
|
|
324
|
+
});
|
|
325
|
+
export type ExportLogsResponse = z.infer<typeof ExportLogsResponseSchema>;
|
|
326
|
+
|
|
305
327
|
// ---------------------------------------------------------------------------
|
|
306
328
|
// Full RPC contract type map
|
|
307
329
|
// ---------------------------------------------------------------------------
|
|
@@ -355,6 +377,10 @@ export interface CesRpcContract {
|
|
|
355
377
|
request: BulkSetCredentialRecords;
|
|
356
378
|
response: BulkSetCredentialRecordsResponse;
|
|
357
379
|
};
|
|
380
|
+
[CesRpcMethod.ExportLogs]: {
|
|
381
|
+
request: ExportLogs;
|
|
382
|
+
response: ExportLogsResponse;
|
|
383
|
+
};
|
|
358
384
|
}
|
|
359
385
|
|
|
360
386
|
/**
|
|
@@ -405,4 +431,8 @@ export const CesRpcSchemas = {
|
|
|
405
431
|
request: BulkSetCredentialRecordsSchema,
|
|
406
432
|
response: BulkSetCredentialRecordsResponseSchema,
|
|
407
433
|
},
|
|
434
|
+
[CesRpcMethod.ExportLogs]: {
|
|
435
|
+
request: ExportLogsSchema,
|
|
436
|
+
response: ExportLogsResponseSchema,
|
|
437
|
+
},
|
|
408
438
|
} as const;
|
package/package.json
CHANGED
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
StoreUnavailableError,
|
|
29
29
|
} from "../materializers/local-secure-key-backend.js";
|
|
30
30
|
import { buildCrudHandlers } from "../main.js";
|
|
31
|
+
import { resetMetadataStoreForTests } from "../records/metadata-store.js";
|
|
31
32
|
|
|
32
33
|
// ---------------------------------------------------------------------------
|
|
33
34
|
// Helpers
|
|
@@ -293,29 +294,63 @@ describe("buildCrudHandlers audit logging", () => {
|
|
|
293
294
|
const ctx = { sessionId: "test-session" };
|
|
294
295
|
|
|
295
296
|
test("SetCredential emits an audit line with account + outcome, never the value", async () => {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
}
|
|
301
|
-
};
|
|
302
|
-
const handlers = buildCrudHandlers(
|
|
303
|
-
fakeBackend(),
|
|
304
|
-
audit as unknown as Parameters<typeof buildCrudHandlers>[1],
|
|
305
|
-
);
|
|
306
|
-
|
|
307
|
-
const res = await handlers[CesRpcMethod.SetCredential]!(
|
|
308
|
-
{ account: "cadet:assistant_api_key", value: "super-secret-value" },
|
|
309
|
-
ctx,
|
|
297
|
+
// SetCredential must also leave a metadata entry (the store-side
|
|
298
|
+
// invariant), so sandbox the CES data root the metadata store writes to.
|
|
299
|
+
const cesDataDir = join(
|
|
300
|
+
tmpdir(),
|
|
301
|
+
`ces-audit-${randomBytes(4).toString("hex")}`,
|
|
310
302
|
);
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
msg:
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
303
|
+
const savedCesDataDir = process.env.CES_DATA_DIR;
|
|
304
|
+
process.env.CES_DATA_DIR = cesDataDir;
|
|
305
|
+
resetMetadataStoreForTests();
|
|
306
|
+
try {
|
|
307
|
+
const calls: Array<{ obj: unknown; msg: string }> = [];
|
|
308
|
+
const audit = {
|
|
309
|
+
info: (obj: unknown, msg: string) => {
|
|
310
|
+
calls.push({ obj, msg });
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
const handlers = buildCrudHandlers(
|
|
314
|
+
fakeBackend(),
|
|
315
|
+
audit as unknown as Parameters<typeof buildCrudHandlers>[1],
|
|
316
|
+
);
|
|
317
|
+
|
|
318
|
+
const res = await handlers[CesRpcMethod.SetCredential]!(
|
|
319
|
+
{
|
|
320
|
+
account: "credential/cadet/assistant_api_key",
|
|
321
|
+
value: "super-secret-value",
|
|
322
|
+
},
|
|
323
|
+
ctx,
|
|
324
|
+
);
|
|
325
|
+
|
|
326
|
+
expect(res).toEqual({ ok: true });
|
|
327
|
+
expect(calls).toContainEqual({
|
|
328
|
+
obj: { account: "credential/cadet/assistant_api_key", ok: true },
|
|
329
|
+
msg: "CES credential set",
|
|
330
|
+
});
|
|
331
|
+
// The audit line must never carry the credential value.
|
|
332
|
+
expect(JSON.stringify(calls)).not.toContain("super-secret-value");
|
|
333
|
+
// The metadata invariant: the catalog can now see the account, and the
|
|
334
|
+
// value itself never lands in metadata.
|
|
335
|
+
const metadata = JSON.parse(
|
|
336
|
+
fs.readFileSync(join(cesDataDir, "metadata.json"), "utf-8"),
|
|
337
|
+
);
|
|
338
|
+
expect(
|
|
339
|
+
metadata.credentials.some(
|
|
340
|
+
(entry: { service: string; field: string }) =>
|
|
341
|
+
entry.service === "cadet" && entry.field === "assistant_api_key",
|
|
342
|
+
),
|
|
343
|
+
).toBe(true);
|
|
344
|
+
expect(JSON.stringify(metadata)).not.toContain("super-secret-value");
|
|
345
|
+
} finally {
|
|
346
|
+
resetMetadataStoreForTests();
|
|
347
|
+
if (savedCesDataDir === undefined) {
|
|
348
|
+
delete process.env.CES_DATA_DIR;
|
|
349
|
+
} else {
|
|
350
|
+
process.env.CES_DATA_DIR = savedCesDataDir;
|
|
351
|
+
}
|
|
352
|
+
fs.rmSync(cesDataDir, { recursive: true, force: true });
|
|
353
|
+
}
|
|
319
354
|
});
|
|
320
355
|
|
|
321
356
|
test("DeleteCredential emits an audit line with account + result", async () => {
|
|
@@ -24,11 +24,7 @@ import {
|
|
|
24
24
|
type RpcEnvelope,
|
|
25
25
|
} from "@mycadet/service-contracts/credential-rpc";
|
|
26
26
|
|
|
27
|
-
import {
|
|
28
|
-
getCesDataRoot,
|
|
29
|
-
getBootstrapSocketPath,
|
|
30
|
-
getHealthPort,
|
|
31
|
-
} from "../paths.js";
|
|
27
|
+
import { getCesDataRoot, getCesSocketPath, getHealthPort } from "../paths.js";
|
|
32
28
|
import { CesRpcServer, type RpcHandlerRegistry } from "../server.js";
|
|
33
29
|
|
|
34
30
|
// ---------------------------------------------------------------------------
|
|
@@ -380,11 +376,11 @@ describe("CES data paths", () => {
|
|
|
380
376
|
}
|
|
381
377
|
});
|
|
382
378
|
|
|
383
|
-
test("
|
|
379
|
+
test("getCesSocketPath defaults to /run/ces-ipc", () => {
|
|
384
380
|
const savedDir = process.env["CES_SOCKET_DIR"];
|
|
385
381
|
delete process.env["CES_SOCKET_DIR"];
|
|
386
382
|
try {
|
|
387
|
-
expect(
|
|
383
|
+
expect(getCesSocketPath()).toBe(
|
|
388
384
|
resolveIpcEndpoint("ces", {
|
|
389
385
|
workspaceDir: "/run/ces-ipc",
|
|
390
386
|
}).path,
|
|
@@ -398,18 +394,18 @@ describe("CES data paths", () => {
|
|
|
398
394
|
}
|
|
399
395
|
});
|
|
400
396
|
|
|
401
|
-
test("
|
|
397
|
+
test("getCesSocketPath uses CES_SOCKET_DIR via resolveIpcEndpoint", () => {
|
|
402
398
|
const savedDir = process.env["CES_SOCKET_DIR"];
|
|
403
399
|
const savedWorkspace = process.env["CADET_WORKSPACE_DIR"];
|
|
404
400
|
process.env["CES_SOCKET_DIR"] = "/tmp/ces-ipc";
|
|
405
401
|
process.env["CADET_WORKSPACE_DIR"] = "/tmp/ces-ws";
|
|
406
402
|
try {
|
|
407
|
-
expect(
|
|
403
|
+
expect(getCesSocketPath()).toBe(
|
|
408
404
|
resolveIpcEndpoint("ces", {
|
|
409
405
|
workspaceDir: "/tmp/ces-ipc",
|
|
410
406
|
}).path,
|
|
411
407
|
);
|
|
412
|
-
expect(
|
|
408
|
+
expect(getCesSocketPath()).not.toBe(
|
|
413
409
|
resolveIpcEndpoint("ces", { workspaceDir: "/tmp/ces-ws" }).path,
|
|
414
410
|
);
|
|
415
411
|
} finally {
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CES log export for the `export_logs` RPC method.
|
|
3
|
+
*
|
|
4
|
+
* Collects CES's own log files (optionally filtered by date range), archives
|
|
5
|
+
* them as a tar.gz, and returns the archive base64-encoded. The gateway's
|
|
6
|
+
* diagnostic log export calls this over the shared Unix socket — the
|
|
7
|
+
* IPC-only replacement for the deleted HTTP `/v1/logs/export` route.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { spawnSync } from "node:child_process";
|
|
11
|
+
import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
12
|
+
import { tmpdir } from "node:os";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
|
|
15
|
+
import { LOG_FILE_PATTERN } from "./logger.js";
|
|
16
|
+
import { getCesLogDir } from "./paths.js";
|
|
17
|
+
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
// Constants
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
/** Maximum cumulative size of collected log files (5 MB). */
|
|
23
|
+
const MAX_LOG_BYTES = 5 * 1024 * 1024;
|
|
24
|
+
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
// Collection
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
export interface CesLogExport {
|
|
30
|
+
/** tar.gz of the collected logs + manifest, base64-encoded. */
|
|
31
|
+
archiveBase64: string;
|
|
32
|
+
filesCollected: number;
|
|
33
|
+
totalBytes: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Collect CES log files into a staging directory, archive them, and return
|
|
38
|
+
* the base64 archive. Files entirely outside the requested range are
|
|
39
|
+
* skipped, as are files that would push the total past the size cap.
|
|
40
|
+
*/
|
|
41
|
+
export async function collectCesLogArchive(
|
|
42
|
+
startTime?: number,
|
|
43
|
+
endTime?: number,
|
|
44
|
+
): Promise<CesLogExport> {
|
|
45
|
+
const logDir = getCesLogDir();
|
|
46
|
+
const staging = join(
|
|
47
|
+
tmpdir(),
|
|
48
|
+
`ces-log-export-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
49
|
+
);
|
|
50
|
+
const logsStaging = join(staging, "ces-logs");
|
|
51
|
+
mkdirSync(logsStaging, { recursive: true });
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
let totalBytes = 0;
|
|
55
|
+
let filesCollected = 0;
|
|
56
|
+
|
|
57
|
+
if (existsSync(logDir)) {
|
|
58
|
+
for (const entry of readdirSync(logDir)) {
|
|
59
|
+
const dateMatch = LOG_FILE_PATTERN.exec(entry);
|
|
60
|
+
if (!dateMatch) continue;
|
|
61
|
+
|
|
62
|
+
// Filter by date when startTime/endTime are provided. Parse the
|
|
63
|
+
// date from the filename and compare start-of-day / end-of-day
|
|
64
|
+
// against the time bounds.
|
|
65
|
+
const fileDateStr = dateMatch[1]!;
|
|
66
|
+
const fileDayStartMs = new Date(
|
|
67
|
+
fileDateStr + "T00:00:00.000Z",
|
|
68
|
+
).getTime();
|
|
69
|
+
const fileDayEndMs = new Date(fileDateStr + "T23:59:59.999Z").getTime();
|
|
70
|
+
|
|
71
|
+
if (startTime !== undefined && fileDayEndMs < startTime) continue; // entire day before range
|
|
72
|
+
if (endTime !== undefined && fileDayStartMs > endTime) continue; // entire day after range
|
|
73
|
+
|
|
74
|
+
const filePath = join(logDir, entry);
|
|
75
|
+
try {
|
|
76
|
+
const stat = statSync(filePath);
|
|
77
|
+
if (!stat.isFile()) continue;
|
|
78
|
+
if (totalBytes + stat.size > MAX_LOG_BYTES) continue;
|
|
79
|
+
|
|
80
|
+
const content = await Bun.file(filePath).arrayBuffer();
|
|
81
|
+
await Bun.write(join(logsStaging, entry), content);
|
|
82
|
+
totalBytes += stat.size;
|
|
83
|
+
filesCollected++;
|
|
84
|
+
} catch {
|
|
85
|
+
// Skip unreadable files
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Always write a manifest so the consumer knows what was collected
|
|
91
|
+
const manifest = {
|
|
92
|
+
type: "ces-log-export",
|
|
93
|
+
exportedAt: new Date().toISOString(),
|
|
94
|
+
filesCollected,
|
|
95
|
+
totalBytes,
|
|
96
|
+
...(startTime !== undefined ? { startTime } : {}),
|
|
97
|
+
...(endTime !== undefined ? { endTime } : {}),
|
|
98
|
+
};
|
|
99
|
+
await Bun.write(
|
|
100
|
+
join(staging, "ces-export-manifest.json"),
|
|
101
|
+
JSON.stringify(manifest, null, 2),
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
// Create tar.gz archive of the staging directory
|
|
105
|
+
const proc = spawnSync("tar", ["czf", "-", "-C", staging, "."], {
|
|
106
|
+
maxBuffer: MAX_LOG_BYTES * 2, // allow headroom for tar overhead
|
|
107
|
+
timeout: 30_000,
|
|
108
|
+
windowsHide: true,
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
if (proc.status !== 0) {
|
|
112
|
+
const stderr = proc.stderr
|
|
113
|
+
? Buffer.isBuffer(proc.stderr)
|
|
114
|
+
? proc.stderr.toString("utf-8")
|
|
115
|
+
: String(proc.stderr)
|
|
116
|
+
: "unknown error";
|
|
117
|
+
throw new Error(`Failed to create archive: ${stderr}`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
archiveBase64: Buffer.from(proc.stdout).toString("base64"),
|
|
122
|
+
filesCollected,
|
|
123
|
+
totalBytes,
|
|
124
|
+
};
|
|
125
|
+
} finally {
|
|
126
|
+
try {
|
|
127
|
+
rmSync(staging, { recursive: true, force: true });
|
|
128
|
+
} catch {
|
|
129
|
+
// best-effort cleanup
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
package/src/main.ts
CHANGED
|
@@ -36,7 +36,7 @@ import {
|
|
|
36
36
|
pruneOldLogFiles,
|
|
37
37
|
} from "./logger.js";
|
|
38
38
|
import {
|
|
39
|
-
|
|
39
|
+
getCesSocketPath,
|
|
40
40
|
getCesDataRoot,
|
|
41
41
|
getCesLogDir,
|
|
42
42
|
getHealthPort,
|
|
@@ -45,8 +45,12 @@ import {
|
|
|
45
45
|
import { CesRpcServer, type RpcHandlerRegistry } from "./server.js";
|
|
46
46
|
import { CES_MIGRATIONS } from "./migrations/registry.js";
|
|
47
47
|
import { runCesMigrations } from "./migrations/runner.js";
|
|
48
|
+
import { collectCesLogArchive } from "./log-export.js";
|
|
48
49
|
import { buildRecordHandlers } from "./records/handlers.js";
|
|
49
|
-
import {
|
|
50
|
+
import {
|
|
51
|
+
getMetadataStore,
|
|
52
|
+
initMetadataStore,
|
|
53
|
+
} from "./records/metadata-store.js";
|
|
50
54
|
|
|
51
55
|
// ---------------------------------------------------------------------------
|
|
52
56
|
// Logging (module-level for early bootstrap + structured logging post-init)
|
|
@@ -90,6 +94,20 @@ export function buildCrudHandlers(
|
|
|
90
94
|
const ok = await secureKeyBackend.set(req.account, req.value);
|
|
91
95
|
// Audit the mutation: account name and outcome only, never the value.
|
|
92
96
|
audit.info({ account: req.account, ok }, "CES credential set");
|
|
97
|
+
if (!ok) {
|
|
98
|
+
return { ok };
|
|
99
|
+
}
|
|
100
|
+
// The store-side invariant: a secret in keys.enc must always have a
|
|
101
|
+
// metadata entry in ces-data, or the catalog cannot see the credential.
|
|
102
|
+
// A bare secret write (hatch provisioning, bulk import) lands here.
|
|
103
|
+
const metadataOk = getMetadataStore().ensureForAccount(req.account);
|
|
104
|
+
if (!metadataOk) {
|
|
105
|
+
audit.info(
|
|
106
|
+
{ account: req.account },
|
|
107
|
+
"CES credential set: metadata entry missing after write",
|
|
108
|
+
);
|
|
109
|
+
return { ok: false };
|
|
110
|
+
}
|
|
93
111
|
return { ok };
|
|
94
112
|
}) as (typeof handlers)[string];
|
|
95
113
|
|
|
@@ -112,8 +130,13 @@ export function buildCrudHandlers(
|
|
|
112
130
|
const results = [];
|
|
113
131
|
for (const { account, value } of req.credentials) {
|
|
114
132
|
const ok = await secureKeyBackend.set(account, value);
|
|
115
|
-
|
|
116
|
-
|
|
133
|
+
// Same invariant as set_credential: the metadata entry must exist.
|
|
134
|
+
const metadataOk = ok
|
|
135
|
+
? getMetadataStore().ensureForAccount(account)
|
|
136
|
+
: false;
|
|
137
|
+
const settled = ok && metadataOk;
|
|
138
|
+
audit.info({ account, ok: settled }, "CES credential set (bulk)");
|
|
139
|
+
results.push({ account, ok: settled });
|
|
117
140
|
}
|
|
118
141
|
return { results };
|
|
119
142
|
}) as (typeof handlers)[string];
|
|
@@ -357,17 +380,25 @@ async function main(): Promise<void> {
|
|
|
357
380
|
...buildCrudHandlers(secureKeyBackend),
|
|
358
381
|
...buildRecordHandlers(),
|
|
359
382
|
};
|
|
383
|
+
// Diagnostic log export (tar.gz, base64) — the gateway pulls CES logs
|
|
384
|
+
// through the same socket as everything else.
|
|
385
|
+
handlers[CesRpcMethod.ExportLogs] = (async (req: {
|
|
386
|
+
startTime?: number;
|
|
387
|
+
endTime?: number;
|
|
388
|
+
}) =>
|
|
389
|
+
await collectCesLogArchive(
|
|
390
|
+
req.startTime,
|
|
391
|
+
req.endTime,
|
|
392
|
+
)) as (typeof handlers)[string];
|
|
360
393
|
|
|
361
394
|
// -- Health server ----------------------------------------------------------
|
|
362
|
-
// Liveness/readiness probes only. Credential invocation is IPC-only
|
|
363
|
-
// every caller (assistant, gateway, CLI) dials the shared Unix socket, so
|
|
364
|
-
// there are no HTTP routes to protect and no CES_SERVICE_TOKEN to manage.
|
|
395
|
+
// Liveness/readiness probes only. Credential invocation is IPC-only.
|
|
365
396
|
const healthPort = getHealthPort();
|
|
366
397
|
startHealthServer(healthPort, controller.signal);
|
|
367
398
|
log.info(`Health server listening on port ${healthPort}`);
|
|
368
399
|
|
|
369
400
|
// -- Socket server ---------------------------------------------------------
|
|
370
|
-
const socketPath =
|
|
401
|
+
const socketPath = getCesSocketPath();
|
|
371
402
|
|
|
372
403
|
const rpcLog = getLogger("rpc");
|
|
373
404
|
const rpcLogger = {
|
package/src/paths.ts
CHANGED
|
@@ -128,6 +128,43 @@ export class CesMetadataStore {
|
|
|
128
128
|
return "deleted";
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
/**
|
|
132
|
+
* Guarantee a metadata entry exists for `account`, minting a default record
|
|
133
|
+
* when absent.
|
|
134
|
+
*
|
|
135
|
+
* This is the store-side half of the set-credential invariant: a secret in
|
|
136
|
+
* `keys.enc` with no `metadata.json` entry is unreadable through the
|
|
137
|
+
* catalog (list/get-record), so a bare secret write must never leave the
|
|
138
|
+
* vault in that state. Existing records are left untouched — policy
|
|
139
|
+
* updates go through `set_credential_record`.
|
|
140
|
+
*/
|
|
141
|
+
ensureForAccount(account: string): boolean {
|
|
142
|
+
const parsed = parseCredentialAccount(account);
|
|
143
|
+
if (!parsed) {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
const data = this.load();
|
|
147
|
+
const exists = data.credentials.some(
|
|
148
|
+
(entry) =>
|
|
149
|
+
entry.service === parsed.service && entry.field === parsed.field,
|
|
150
|
+
);
|
|
151
|
+
if (exists) {
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
const now = Date.now();
|
|
155
|
+
data.credentials.push({
|
|
156
|
+
credentialId: randomUUID(),
|
|
157
|
+
service: parsed.service,
|
|
158
|
+
field: parsed.field,
|
|
159
|
+
allowedTools: [],
|
|
160
|
+
allowedDomains: [],
|
|
161
|
+
createdAt: now,
|
|
162
|
+
updatedAt: now,
|
|
163
|
+
});
|
|
164
|
+
this.save(data);
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
|
|
131
168
|
list(): Array<{ account: string; record: CredentialRecord }> {
|
|
132
169
|
return this.load().credentials.map((record) => ({
|
|
133
170
|
account: accountForRecord(record),
|