@vellumai/credential-executor 0.11.7-staging.1 → 0.11.7

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.
@@ -16,6 +16,13 @@
16
16
  * - `delete_credential` — Delete a credential by account name
17
17
  * - `list_credentials` — List all credential account names
18
18
  * - `bulk_set_credentials` — Store multiple credentials at once
19
+ *
20
+ * **Credential records** (non-secret identity + policy)
21
+ * - `get_credential_record` — Retrieve a credential record by account name
22
+ * - `set_credential_record` — Store or update a credential record
23
+ * - `delete_credential_record` — Delete a credential record by account name
24
+ * - `list_credential_records` — List all credential records
25
+ * - `bulk_set_credential_records` — Store multiple credential records at once
19
26
  */
20
27
 
21
28
  import { z } from "zod";
@@ -38,6 +45,16 @@ export const CesRpcMethod = {
38
45
  ListCredentials: "list_credentials",
39
46
  /** Bulk-import credentials (set multiple at once). */
40
47
  BulkSetCredentials: "bulk_set_credentials",
48
+ /** Retrieve a single credential record (identity + policy) by account name. */
49
+ GetCredentialRecord: "get_credential_record",
50
+ /** Store or update a credential record by account name. */
51
+ SetCredentialRecord: "set_credential_record",
52
+ /** Delete a credential record by account name. */
53
+ DeleteCredentialRecord: "delete_credential_record",
54
+ /** List all credential records. */
55
+ ListCredentialRecords: "list_credential_records",
56
+ /** Bulk-import credential records. */
57
+ BulkSetCredentialRecords: "bulk_set_credential_records",
41
58
  } as const;
42
59
 
43
60
  export type CesRpcMethod = (typeof CesRpcMethod)[keyof typeof CesRpcMethod];
@@ -168,6 +185,123 @@ export type BulkSetCredentialsResponse = z.infer<
168
185
  typeof BulkSetCredentialsResponseSchema
169
186
  >;
170
187
 
188
+ // ---------------------------------------------------------------------------
189
+ // Credential records (identity + policy, never secret values)
190
+ // ---------------------------------------------------------------------------
191
+
192
+ export const CredentialInjectionTemplateSchema = z.object({
193
+ hostPattern: z.string(),
194
+ injectionType: z.enum(["header", "query"]),
195
+ headerName: z.string().optional(),
196
+ valuePrefix: z.string().optional(),
197
+ queryParamName: z.string().optional(),
198
+ composeWith: z
199
+ .object({
200
+ service: z.string(),
201
+ field: z.string(),
202
+ separator: z.string(),
203
+ })
204
+ .optional(),
205
+ valueTransform: z.enum(["base64"]).optional(),
206
+ });
207
+ export type CredentialInjectionTemplate = z.infer<
208
+ typeof CredentialInjectionTemplateSchema
209
+ >;
210
+
211
+ export const CredentialRecordSchema = z.object({
212
+ credentialId: z.string(),
213
+ service: z.string(),
214
+ field: z.string(),
215
+ allowedTools: z.array(z.string()),
216
+ allowedDomains: z.array(z.string()),
217
+ usageDescription: z.string().optional(),
218
+ alias: z.string().optional(),
219
+ injectionTemplates: z.array(CredentialInjectionTemplateSchema).optional(),
220
+ createdAt: z.number(),
221
+ updatedAt: z.number(),
222
+ });
223
+ export type CredentialRecord = z.infer<typeof CredentialRecordSchema>;
224
+
225
+ export const GetCredentialRecordSchema = z.object({
226
+ /** The account name to look up (`credential/{service}/{field}`). */
227
+ account: z.string(),
228
+ });
229
+ export type GetCredentialRecord = z.infer<typeof GetCredentialRecordSchema>;
230
+
231
+ export const GetCredentialRecordResponseSchema = z.object({
232
+ found: z.boolean(),
233
+ record: CredentialRecordSchema.optional(),
234
+ });
235
+ export type GetCredentialRecordResponse = z.infer<
236
+ typeof GetCredentialRecordResponseSchema
237
+ >;
238
+
239
+ export const SetCredentialRecordSchema = z.object({
240
+ account: z.string(),
241
+ record: CredentialRecordSchema,
242
+ });
243
+ export type SetCredentialRecord = z.infer<typeof SetCredentialRecordSchema>;
244
+
245
+ export const SetCredentialRecordResponseSchema = z.object({
246
+ ok: z.boolean(),
247
+ });
248
+ export type SetCredentialRecordResponse = z.infer<
249
+ typeof SetCredentialRecordResponseSchema
250
+ >;
251
+
252
+ export const DeleteCredentialRecordSchema = z.object({
253
+ account: z.string(),
254
+ });
255
+ export type DeleteCredentialRecord = z.infer<
256
+ typeof DeleteCredentialRecordSchema
257
+ >;
258
+
259
+ export const DeleteCredentialRecordResponseSchema = z.object({
260
+ result: z.enum(["deleted", "not-found", "error"]),
261
+ });
262
+ export type DeleteCredentialRecordResponse = z.infer<
263
+ typeof DeleteCredentialRecordResponseSchema
264
+ >;
265
+
266
+ export const ListCredentialRecordsSchema = z.object({});
267
+ export type ListCredentialRecords = z.infer<typeof ListCredentialRecordsSchema>;
268
+
269
+ export const ListCredentialRecordsResponseSchema = z.object({
270
+ records: z.array(
271
+ z.object({
272
+ account: z.string(),
273
+ record: CredentialRecordSchema,
274
+ }),
275
+ ),
276
+ });
277
+ export type ListCredentialRecordsResponse = z.infer<
278
+ typeof ListCredentialRecordsResponseSchema
279
+ >;
280
+
281
+ export const BulkSetCredentialRecordsSchema = z.object({
282
+ records: z.array(
283
+ z.object({
284
+ account: z.string(),
285
+ record: CredentialRecordSchema,
286
+ }),
287
+ ),
288
+ });
289
+ export type BulkSetCredentialRecords = z.infer<
290
+ typeof BulkSetCredentialRecordsSchema
291
+ >;
292
+
293
+ export const BulkSetCredentialRecordsResponseSchema = z.object({
294
+ results: z.array(
295
+ z.object({
296
+ account: z.string(),
297
+ ok: z.boolean(),
298
+ }),
299
+ ),
300
+ });
301
+ export type BulkSetCredentialRecordsResponse = z.infer<
302
+ typeof BulkSetCredentialRecordsResponseSchema
303
+ >;
304
+
171
305
  // ---------------------------------------------------------------------------
172
306
  // Full RPC contract type map
173
307
  // ---------------------------------------------------------------------------
@@ -201,6 +335,26 @@ export interface CesRpcContract {
201
335
  request: BulkSetCredentials;
202
336
  response: BulkSetCredentialsResponse;
203
337
  };
338
+ [CesRpcMethod.GetCredentialRecord]: {
339
+ request: GetCredentialRecord;
340
+ response: GetCredentialRecordResponse;
341
+ };
342
+ [CesRpcMethod.SetCredentialRecord]: {
343
+ request: SetCredentialRecord;
344
+ response: SetCredentialRecordResponse;
345
+ };
346
+ [CesRpcMethod.DeleteCredentialRecord]: {
347
+ request: DeleteCredentialRecord;
348
+ response: DeleteCredentialRecordResponse;
349
+ };
350
+ [CesRpcMethod.ListCredentialRecords]: {
351
+ request: ListCredentialRecords;
352
+ response: ListCredentialRecordsResponse;
353
+ };
354
+ [CesRpcMethod.BulkSetCredentialRecords]: {
355
+ request: BulkSetCredentialRecords;
356
+ response: BulkSetCredentialRecordsResponse;
357
+ };
204
358
  }
205
359
 
206
360
  /**
@@ -231,4 +385,24 @@ export const CesRpcSchemas = {
231
385
  request: BulkSetCredentialsSchema,
232
386
  response: BulkSetCredentialsResponseSchema,
233
387
  },
388
+ [CesRpcMethod.GetCredentialRecord]: {
389
+ request: GetCredentialRecordSchema,
390
+ response: GetCredentialRecordResponseSchema,
391
+ },
392
+ [CesRpcMethod.SetCredentialRecord]: {
393
+ request: SetCredentialRecordSchema,
394
+ response: SetCredentialRecordResponseSchema,
395
+ },
396
+ [CesRpcMethod.DeleteCredentialRecord]: {
397
+ request: DeleteCredentialRecordSchema,
398
+ response: DeleteCredentialRecordResponseSchema,
399
+ },
400
+ [CesRpcMethod.ListCredentialRecords]: {
401
+ request: ListCredentialRecordsSchema,
402
+ response: ListCredentialRecordsResponseSchema,
403
+ },
404
+ [CesRpcMethod.BulkSetCredentialRecords]: {
405
+ request: BulkSetCredentialRecordsSchema,
406
+ response: BulkSetCredentialRecordsResponseSchema,
407
+ },
234
408
  } as const;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/credential-executor",
3
- "version": "0.11.7-staging.1",
3
+ "version": "0.11.7",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,91 @@
1
+ import { mkdtempSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ import { describe, expect, test } from "bun:test";
6
+
7
+ import type { CredentialRecord } from "@vellumai/service-contracts/credential-rpc";
8
+
9
+ import {
10
+ CesMetadataStore,
11
+ getMetadataPath,
12
+ parseCredentialAccount,
13
+ } from "../records/metadata-store.js";
14
+
15
+ function makeRecord(
16
+ service: string,
17
+ field: string,
18
+ extras?: Partial<CredentialRecord>,
19
+ ): CredentialRecord {
20
+ return {
21
+ credentialId: `id-${service}-${field}`,
22
+ service,
23
+ field,
24
+ allowedTools: ["bash"],
25
+ allowedDomains: [],
26
+ createdAt: 1,
27
+ updatedAt: 2,
28
+ ...extras,
29
+ };
30
+ }
31
+
32
+ describe("CesMetadataStore", () => {
33
+ test("round-trips a record by account key", () => {
34
+ const dir = mkdtempSync(join(tmpdir(), "ces-metadata-"));
35
+ const store = new CesMetadataStore(getMetadataPath(dir));
36
+ const record = makeRecord("github", "token", {
37
+ injectionTemplates: [
38
+ {
39
+ hostPattern: "github.com",
40
+ injectionType: "header",
41
+ headerName: "Authorization",
42
+ valuePrefix: "Bearer ",
43
+ },
44
+ ],
45
+ });
46
+ const account = "credential/github/token";
47
+
48
+ expect(store.setByAccount(account, record)).toBe(true);
49
+ expect(store.getByAccount(account)).toEqual(record);
50
+ expect(store.list()).toEqual([{ account, record }]);
51
+ expect(store.deleteByAccount(account)).toBe("deleted");
52
+ expect(store.getByAccount(account)).toBeUndefined();
53
+ });
54
+
55
+ test("rejects an account that does not match the record", () => {
56
+ const dir = mkdtempSync(join(tmpdir(), "ces-metadata-"));
57
+ const store = new CesMetadataStore(getMetadataPath(dir));
58
+ expect(
59
+ store.setByAccount(
60
+ "credential/github/token",
61
+ makeRecord("gitlab", "token"),
62
+ ),
63
+ ).toBe(false);
64
+ });
65
+
66
+ test("writes metadata.json under the CES data root", () => {
67
+ expect(getMetadataPath("/tmp/ces-data")).toBe("/tmp/ces-data/metadata.json");
68
+ });
69
+ });
70
+
71
+ describe("parseCredentialAccount", () => {
72
+ test("splits credential/{service}/{field}", () => {
73
+ expect(parseCredentialAccount("credential/github/token")).toEqual({
74
+ service: "github",
75
+ field: "token",
76
+ });
77
+ });
78
+
79
+ test("keeps slashes inside the service name", () => {
80
+ expect(
81
+ parseCredentialAccount("credential/integration:google/access_token"),
82
+ ).toEqual({
83
+ service: "integration:google",
84
+ field: "access_token",
85
+ });
86
+ });
87
+
88
+ test("rejects non-credential accounts", () => {
89
+ expect(parseCredentialAccount("oauth/google/access")).toBeUndefined();
90
+ });
91
+ });
@@ -0,0 +1,84 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ import type { CredentialRecord } from "@vellumai/service-contracts/credential-rpc";
7
+
8
+ import { handleMetadataRoute } from "../metadata-routes.js";
9
+ import {
10
+ initMetadataStore,
11
+ resetMetadataStoreForTests,
12
+ } from "../../records/metadata-store.js";
13
+
14
+ const SERVICE_TOKEN = "test-metadata-token";
15
+
16
+ function makeRecord(): CredentialRecord {
17
+ return {
18
+ credentialId: "id-1",
19
+ service: "github",
20
+ field: "token",
21
+ allowedTools: ["assistant_browser_fill_credential"],
22
+ allowedDomains: ["github.com"],
23
+ createdAt: 10,
24
+ updatedAt: 20,
25
+ };
26
+ }
27
+
28
+ function makeRequest(method: string, path: string, body?: unknown): Request {
29
+ return new Request(`http://localhost:8090${path}`, {
30
+ method,
31
+ headers: {
32
+ "Content-Type": "application/json",
33
+ Authorization: `Bearer ${SERVICE_TOKEN}`,
34
+ },
35
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
36
+ });
37
+ }
38
+
39
+ describe("credential metadata HTTP routes", () => {
40
+ afterEach(() => {
41
+ resetMetadataStoreForTests();
42
+ delete process.env.CES_SERVICE_TOKEN;
43
+ });
44
+
45
+ test("put, get, list, and delete a record", async () => {
46
+ const dir = mkdtempSync(join(tmpdir(), "ces-metadata-http-"));
47
+ initMetadataStore(dir);
48
+ process.env.CES_SERVICE_TOKEN = SERVICE_TOKEN;
49
+ const account = "credential/github/token";
50
+ const record = makeRecord();
51
+
52
+ const put = await handleMetadataRoute(
53
+ makeRequest("PUT", `/v1/metadata/${encodeURIComponent(account)}`, {
54
+ record,
55
+ }),
56
+ );
57
+ expect(put?.status).toBe(200);
58
+
59
+ const get = await handleMetadataRoute(
60
+ makeRequest("GET", `/v1/metadata/${encodeURIComponent(account)}`),
61
+ );
62
+ expect(get?.status).toBe(200);
63
+ expect(await get!.json()).toEqual({ account, record });
64
+
65
+ const list = await handleMetadataRoute(makeRequest("GET", "/v1/metadata"));
66
+ expect(list?.status).toBe(200);
67
+ expect(await list!.json()).toEqual({ records: [{ account, record }] });
68
+
69
+ const del = await handleMetadataRoute(
70
+ makeRequest("DELETE", `/v1/metadata/${encodeURIComponent(account)}`),
71
+ );
72
+ expect(del?.status).toBe(200);
73
+ });
74
+
75
+ test("rejects requests without a bearer token", async () => {
76
+ const dir = mkdtempSync(join(tmpdir(), "ces-metadata-http-"));
77
+ initMetadataStore(dir);
78
+ process.env.CES_SERVICE_TOKEN = SERVICE_TOKEN;
79
+ const res = await handleMetadataRoute(
80
+ new Request("http://localhost:8090/v1/metadata", { method: "GET" }),
81
+ );
82
+ expect(res?.status).toBe(401);
83
+ });
84
+ });
@@ -0,0 +1,197 @@
1
+ /**
2
+ * HTTP endpoints for CES credential metadata (identity + policy).
3
+ *
4
+ * - `GET /v1/metadata` : list records
5
+ * - `POST /v1/metadata/bulk` : bulk set records
6
+ * - `GET /v1/metadata/:account` : get one record
7
+ * - `PUT /v1/metadata/:account` : set one record
8
+ * - `DELETE /v1/metadata/:account` : delete one record
9
+ *
10
+ * Auth: same `CES_SERVICE_TOKEN` bearer as secret CRUD.
11
+ */
12
+
13
+ import { timingSafeEqual } from "node:crypto";
14
+
15
+ import { CredentialRecordSchema } from "@vellumai/service-contracts/credential-rpc";
16
+
17
+ import { getMetadataStore } from "../records/metadata-store.js";
18
+
19
+ const METADATA_PATH_PREFIX = "/v1/metadata";
20
+
21
+ function serviceToken(): string {
22
+ return process.env["CES_SERVICE_TOKEN"] ?? "";
23
+ }
24
+
25
+ function checkAuth(req: Request): Response | null {
26
+ const expectedToken = serviceToken();
27
+ if (!expectedToken) {
28
+ return new Response(JSON.stringify({ error: "Missing service token" }), {
29
+ status: 401,
30
+ headers: { "Content-Type": "application/json" },
31
+ });
32
+ }
33
+
34
+ const authHeader = req.headers.get("authorization");
35
+ if (!authHeader) {
36
+ return new Response(
37
+ JSON.stringify({ error: "Missing Authorization header" }),
38
+ { status: 401, headers: { "Content-Type": "application/json" } },
39
+ );
40
+ }
41
+
42
+ const parts = authHeader.split(" ");
43
+ if (parts.length !== 2 || parts[0]!.toLowerCase() !== "bearer") {
44
+ return new Response(
45
+ JSON.stringify({
46
+ error: "Invalid Authorization header format. Expected: Bearer <token>",
47
+ }),
48
+ { status: 401, headers: { "Content-Type": "application/json" } },
49
+ );
50
+ }
51
+
52
+ const provided = Buffer.from(parts[1]!);
53
+ const expected = Buffer.from(expectedToken);
54
+ if (
55
+ provided.length !== expected.length ||
56
+ !timingSafeEqual(provided, expected)
57
+ ) {
58
+ return new Response(JSON.stringify({ error: "Invalid service token" }), {
59
+ status: 403,
60
+ headers: { "Content-Type": "application/json" },
61
+ });
62
+ }
63
+
64
+ return null;
65
+ }
66
+
67
+ function json(body: unknown, status = 200): Response {
68
+ return new Response(JSON.stringify(body), {
69
+ status,
70
+ headers: { "Content-Type": "application/json" },
71
+ });
72
+ }
73
+
74
+ export async function handleMetadataRoute(
75
+ req: Request,
76
+ ): Promise<Response | null> {
77
+ const url = new URL(req.url);
78
+ const { pathname } = url;
79
+
80
+ if (!pathname.startsWith(METADATA_PATH_PREFIX)) {
81
+ return null;
82
+ }
83
+
84
+ const authError = checkAuth(req);
85
+ if (authError) {
86
+ return authError;
87
+ }
88
+
89
+ const recordStore = getMetadataStore();
90
+ const rest = pathname.slice(METADATA_PATH_PREFIX.length);
91
+
92
+ if ((rest === "" || rest === "/") && req.method === "GET") {
93
+ return json({ records: recordStore.list() });
94
+ }
95
+
96
+ if (rest === "/bulk" && req.method === "POST") {
97
+ let body: { records?: unknown };
98
+ try {
99
+ body = await req.json();
100
+ } catch {
101
+ return json({ error: "Invalid JSON body" }, 400);
102
+ }
103
+ if (!Array.isArray(body.records)) {
104
+ return json({ error: "Body must contain a 'records' array field" }, 400);
105
+ }
106
+ const results: Array<{ account: string; ok: boolean }> = [];
107
+ for (const entry of body.records) {
108
+ if (
109
+ typeof entry !== "object" ||
110
+ entry === null ||
111
+ typeof (entry as { account?: unknown }).account !== "string"
112
+ ) {
113
+ return json(
114
+ { error: "Each record entry must have a string 'account' field" },
115
+ 400,
116
+ );
117
+ }
118
+ const parsed = CredentialRecordSchema.safeParse(
119
+ (entry as { record?: unknown }).record,
120
+ );
121
+ if (!parsed.success) {
122
+ return json(
123
+ { error: "Each record entry must have a valid record" },
124
+ 400,
125
+ );
126
+ }
127
+ const account = (entry as { account: string }).account;
128
+ const ok = recordStore.setByAccount(account, parsed.data);
129
+ results.push({ account, ok });
130
+ }
131
+ return json({ results });
132
+ }
133
+
134
+ if (!rest.startsWith("/")) {
135
+ return null;
136
+ }
137
+
138
+ const rawAccount = decodeURIComponent(rest.slice(1));
139
+ if (!rawAccount) {
140
+ return json({ error: "Account name is required" }, 400);
141
+ }
142
+
143
+ switch (req.method) {
144
+ case "GET": {
145
+ const record = recordStore.getByAccount(rawAccount);
146
+ if (!record) {
147
+ return json(
148
+ { error: "Credential metadata not found", account: rawAccount },
149
+ 404,
150
+ );
151
+ }
152
+ return json({ account: rawAccount, record });
153
+ }
154
+ case "PUT": {
155
+ let body: { record?: unknown };
156
+ try {
157
+ body = await req.json();
158
+ } catch {
159
+ return json({ error: "Invalid JSON body" }, 400);
160
+ }
161
+ const parsed = CredentialRecordSchema.safeParse(body.record);
162
+ if (!parsed.success) {
163
+ return json({ error: "Body must contain a valid 'record'" }, 400);
164
+ }
165
+ const ok = recordStore.setByAccount(rawAccount, parsed.data);
166
+ if (!ok) {
167
+ return json(
168
+ {
169
+ error:
170
+ "Failed to set credential metadata (account must match record service/field)",
171
+ account: rawAccount,
172
+ },
173
+ 400,
174
+ );
175
+ }
176
+ return json({ ok: true, account: rawAccount });
177
+ }
178
+ case "DELETE": {
179
+ const result = recordStore.deleteByAccount(rawAccount);
180
+ if (result === "not-found") {
181
+ return json(
182
+ { error: "Credential metadata not found", account: rawAccount },
183
+ 404,
184
+ );
185
+ }
186
+ if (result === "error") {
187
+ return json(
188
+ { error: "Failed to delete credential metadata", account: rawAccount },
189
+ 400,
190
+ );
191
+ }
192
+ return json({ ok: true, account: rawAccount });
193
+ }
194
+ default:
195
+ return json({ error: "Method not allowed" }, 405);
196
+ }
197
+ }
package/src/main.ts CHANGED
@@ -51,8 +51,11 @@ import {
51
51
  type CredentialRouteDeps,
52
52
  } from "./http/credential-routes.js";
53
53
  import { handleLogExportRoute } from "./http/log-export-routes.js";
54
+ import { handleMetadataRoute } from "./http/metadata-routes.js";
54
55
  import { CES_MIGRATIONS } from "./migrations/registry.js";
55
56
  import { runCesMigrations } from "./migrations/runner.js";
57
+ import { buildRecordHandlers } from "./records/handlers.js";
58
+ import { initMetadataStore } from "./records/metadata-store.js";
56
59
 
57
60
  // ---------------------------------------------------------------------------
58
61
  // Logging (module-level for early bootstrap + structured logging post-init)
@@ -274,11 +277,17 @@ function startHealthServer(
274
277
 
275
278
  // Credential CRUD routes (only if service token is configured)
276
279
  if (credentialDeps) {
280
+ const metadataResponse = await handleMetadataRoute(req);
281
+ if (metadataResponse) {
282
+ return metadataResponse;
283
+ }
277
284
  const credentialResponse = await handleCredentialRoute(
278
285
  req,
279
286
  credentialDeps,
280
287
  );
281
- if (credentialResponse) return credentialResponse;
288
+ if (credentialResponse) {
289
+ return credentialResponse;
290
+ }
282
291
  }
283
292
 
284
293
  // Log export route
@@ -349,11 +358,16 @@ async function main(): Promise<void> {
349
358
  );
350
359
  log.info(`CES ${mode} startup: migrations complete`);
351
360
 
361
+ initMetadataStore(getCesDataRoot(mode));
362
+
352
363
  // -- Build handlers --------------------------------------------------------
353
364
  // The per-connection session ID lives in each CesRpcServer's SessionContext;
354
365
  // handlers read it at call time. The registry is shared across connections
355
366
  // and identical in both modes.
356
- const handlers = buildCrudHandlers(secureKeyBackend);
367
+ const handlers = {
368
+ ...buildCrudHandlers(secureKeyBackend),
369
+ ...buildRecordHandlers(),
370
+ };
357
371
 
358
372
  // -- Health server (managed only) -----------------------------------------
359
373
  if (mode === "managed") {
@@ -0,0 +1,58 @@
1
+ /**
2
+ * RPC handlers for CES credential metadata.
3
+ */
4
+
5
+ import { CesRpcMethod } from "@vellumai/service-contracts/credential-rpc";
6
+
7
+ import type { RpcHandlerRegistry } from "../server.js";
8
+ import {
9
+ getMetadataStore,
10
+ type CesMetadataStore,
11
+ } from "./metadata-store.js";
12
+
13
+ export function buildRecordHandlers(): RpcHandlerRegistry {
14
+ const handlers: RpcHandlerRegistry = {};
15
+
16
+ handlers[CesRpcMethod.GetCredentialRecord] = (async (req: {
17
+ account: string;
18
+ }) => {
19
+ const record = getMetadataStore().getByAccount(req.account);
20
+ return { found: record !== undefined, record };
21
+ }) as (typeof handlers)[string];
22
+
23
+ handlers[CesRpcMethod.SetCredentialRecord] = (async (req: {
24
+ account: string;
25
+ record: Parameters<CesMetadataStore["setByAccount"]>[1];
26
+ }) => {
27
+ const ok = getMetadataStore().setByAccount(req.account, req.record);
28
+ return { ok };
29
+ }) as (typeof handlers)[string];
30
+
31
+ handlers[CesRpcMethod.DeleteCredentialRecord] = (async (req: {
32
+ account: string;
33
+ }) => {
34
+ const result = getMetadataStore().deleteByAccount(req.account);
35
+ return { result };
36
+ }) as (typeof handlers)[string];
37
+
38
+ handlers[CesRpcMethod.ListCredentialRecords] = (async () => {
39
+ return { records: getMetadataStore().list() };
40
+ }) as (typeof handlers)[string];
41
+
42
+ handlers[CesRpcMethod.BulkSetCredentialRecords] = (async (req: {
43
+ records: Array<{
44
+ account: string;
45
+ record: Parameters<CesMetadataStore["setByAccount"]>[1];
46
+ }>;
47
+ }) => {
48
+ const store = getMetadataStore();
49
+ const results = [];
50
+ for (const { account, record } of req.records) {
51
+ const ok = store.setByAccount(account, record);
52
+ results.push({ account, ok });
53
+ }
54
+ return { results };
55
+ }) as (typeof handlers)[string];
56
+
57
+ return handlers;
58
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * CES-owned credential metadata store.
3
+ *
4
+ * Persists non-secret identity and policy (`allowedTools`, `allowedDomains`,
5
+ * `injectionTemplates`, plus catalog fields) at
6
+ * `<cesDataRoot>/metadata.json`. Secret values stay in `keys.enc`.
7
+ */
8
+
9
+ import { randomUUID } from "node:crypto";
10
+ import {
11
+ existsSync,
12
+ mkdirSync,
13
+ readFileSync,
14
+ renameSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { dirname, join } from "node:path";
18
+
19
+ import type { CredentialRecord } from "@vellumai/service-contracts/credential-rpc";
20
+
21
+ import { getCesDataRoot } from "../paths.js";
22
+
23
+ export const METADATA_FILENAME = "metadata.json";
24
+
25
+ const CURRENT_VERSION = 5;
26
+
27
+ interface MetadataFile {
28
+ version: typeof CURRENT_VERSION;
29
+ credentials: CredentialRecord[];
30
+ }
31
+
32
+ export function getMetadataPath(cesDataRoot: string): string {
33
+ return join(cesDataRoot, METADATA_FILENAME);
34
+ }
35
+
36
+ export function parseCredentialAccount(
37
+ account: string,
38
+ ): { service: string; field: string } | undefined {
39
+ const prefix = "credential/";
40
+ if (!account.startsWith(prefix)) {
41
+ return undefined;
42
+ }
43
+ const rest = account.slice(prefix.length);
44
+ const slashIdx = rest.lastIndexOf("/");
45
+ if (slashIdx < 1 || slashIdx === rest.length - 1) {
46
+ return undefined;
47
+ }
48
+ return {
49
+ service: rest.slice(0, slashIdx),
50
+ field: rest.slice(slashIdx + 1),
51
+ };
52
+ }
53
+
54
+ export function accountForRecord(
55
+ record: Pick<CredentialRecord, "service" | "field">,
56
+ ): string {
57
+ return `credential/${record.service}/${record.field}`;
58
+ }
59
+
60
+ function isRecord(value: unknown): value is CredentialRecord {
61
+ if (typeof value !== "object" || value == null) {
62
+ return false;
63
+ }
64
+ const record = value as Record<string, unknown>;
65
+ return (
66
+ typeof record.credentialId === "string" &&
67
+ typeof record.service === "string" &&
68
+ typeof record.field === "string" &&
69
+ Array.isArray(record.allowedTools) &&
70
+ Array.isArray(record.allowedDomains) &&
71
+ typeof record.createdAt === "number" &&
72
+ typeof record.updatedAt === "number"
73
+ );
74
+ }
75
+
76
+ export class CesMetadataStore {
77
+ constructor(private readonly metadataPath: string) {}
78
+
79
+ getPath(): string {
80
+ return this.metadataPath;
81
+ }
82
+
83
+ getByAccount(account: string): CredentialRecord | undefined {
84
+ const parsed = parseCredentialAccount(account);
85
+ if (!parsed) {
86
+ return undefined;
87
+ }
88
+ return this.load().credentials.find(
89
+ (record) =>
90
+ record.service === parsed.service && record.field === parsed.field,
91
+ );
92
+ }
93
+
94
+ setByAccount(account: string, record: CredentialRecord): boolean {
95
+ const parsed = parseCredentialAccount(account);
96
+ if (!parsed) {
97
+ return false;
98
+ }
99
+ if (parsed.service !== record.service || parsed.field !== record.field) {
100
+ return false;
101
+ }
102
+ const data = this.load();
103
+ const copy: CredentialRecord = { ...record };
104
+ const idx = data.credentials.findIndex(
105
+ (entry) =>
106
+ entry.service === record.service && entry.field === record.field,
107
+ );
108
+ if (idx === -1) {
109
+ data.credentials.push(copy);
110
+ } else {
111
+ data.credentials[idx] = copy;
112
+ }
113
+ this.save(data);
114
+ return true;
115
+ }
116
+
117
+ deleteByAccount(account: string): "deleted" | "not-found" | "error" {
118
+ const parsed = parseCredentialAccount(account);
119
+ if (!parsed) {
120
+ return "error";
121
+ }
122
+ const data = this.load();
123
+ const idx = data.credentials.findIndex(
124
+ (entry) =>
125
+ entry.service === parsed.service && entry.field === parsed.field,
126
+ );
127
+ if (idx === -1) {
128
+ return "not-found";
129
+ }
130
+ data.credentials.splice(idx, 1);
131
+ this.save(data);
132
+ return "deleted";
133
+ }
134
+
135
+ list(): Array<{ account: string; record: CredentialRecord }> {
136
+ return this.load().credentials.map((record) => ({
137
+ account: accountForRecord(record),
138
+ record,
139
+ }));
140
+ }
141
+
142
+ private load(): MetadataFile {
143
+ if (!existsSync(this.metadataPath)) {
144
+ return { version: CURRENT_VERSION, credentials: [] };
145
+ }
146
+ try {
147
+ const parsed = JSON.parse(readFileSync(this.metadataPath, "utf-8")) as {
148
+ credentials?: unknown;
149
+ };
150
+ const credentials = Array.isArray(parsed.credentials)
151
+ ? parsed.credentials.filter(isRecord)
152
+ : [];
153
+ return { version: CURRENT_VERSION, credentials };
154
+ } catch {
155
+ return { version: CURRENT_VERSION, credentials: [] };
156
+ }
157
+ }
158
+
159
+ private save(data: MetadataFile): void {
160
+ const dir = dirname(this.metadataPath);
161
+ if (!existsSync(dir)) {
162
+ mkdirSync(dir, { recursive: true });
163
+ }
164
+ const tmpPath = join(dir, `.tmp-${randomUUID()}`);
165
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), "utf-8");
166
+ renameSync(tmpPath, this.metadataPath);
167
+ }
168
+ }
169
+
170
+ let processStore: CesMetadataStore | undefined;
171
+
172
+ export function initMetadataStore(cesDataRoot: string): CesMetadataStore {
173
+ processStore = new CesMetadataStore(getMetadataPath(cesDataRoot));
174
+ return processStore;
175
+ }
176
+
177
+ export function getMetadataStore(): CesMetadataStore {
178
+ if (!processStore) {
179
+ processStore = new CesMetadataStore(getMetadataPath(getCesDataRoot()));
180
+ }
181
+ return processStore;
182
+ }
183
+
184
+ /** Test-only: drop the process store so the next init uses a fresh path. */
185
+ export function resetMetadataStoreForTests(): void {
186
+ processStore = undefined;
187
+ }