secureagentbase 1.4.5 → 1.4.6

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.
@@ -1,7 +1,7 @@
1
1
  import * as crypto from 'node:crypto';
2
2
  import inquirer from 'inquirer';
3
3
  import { createAuth } from '../lib/auth.js';
4
- import { listProjects, createProject, getProject, enableApi, createServiceAccount, grantRole, createVm, fetchVmLogs, cleanupVmByName, } from '../lib/gcp.js';
4
+ import { listProjects, createProject, getProject, enableApi, createServiceAccount, grantRole, grantRoleOnServiceAccount, createVm, fetchVmLogs, cleanupVmByName, smWriteSecret, smFetchSecret, smMember, } from '../lib/gcp.js';
5
5
  import { setupFirebaseProject } from '../lib/firebase.js';
6
6
  import { ensureRepo, setGitHubVariable, setupOidc, validatePat } from '../lib/github.js';
7
7
  import { fetchBillingAccounts, linkBillingAccount, isBillingEnabled } from '../lib/billing.js';
@@ -38,7 +38,7 @@ export async function runInit(args) {
38
38
  }
39
39
  // Step 6: Discord bot
40
40
  if (args.discordToken) {
41
- await stepDiscord(config, args);
41
+ await stepDiscord(auth, config, args);
42
42
  }
43
43
  else {
44
44
  info('Skipping Discord setup (no --discord-token provided)');
@@ -119,11 +119,37 @@ async function stepServiceAccount(auth, config, _args) {
119
119
  'roles/iam.workloadIdentityPoolAdmin',
120
120
  'roles/iam.securityAdmin',
121
121
  'roles/firebase.admin',
122
+ // Agent SA must read the 2 SM secrets via the metadata-server identity at
123
+ // VM boot (map #36 decision #7). Per-secret accessors are also bound at
124
+ // write time, but the project role covers the legacy default-compute-SA
125
+ // fallback and any re-run that re-fetches secrets.
126
+ 'roles/secretmanager.secretAccessor',
122
127
  ];
123
128
  for (const role of roles) {
124
129
  await grantRole(auth, `projects/${projectId}`, `serviceAccount:${email}`, role);
125
130
  info(` Granted ${role}`);
126
131
  }
132
+ // Operator needs full Secret Manager control to create secrets, add
133
+ // versions, and bind per-secret accessors during init (map #36).
134
+ const operatorEmail = await auth.getClientEmail();
135
+ if (operatorEmail) {
136
+ await grantRole(auth, `projects/${projectId}`, smMember(operatorEmail), 'roles/secretmanager.admin').catch((e) => {
137
+ warn(`Could not grant roles/secretmanager.admin to ${operatorEmail}: ${e.message}`);
138
+ });
139
+ info(` Granted roles/secretmanager.admin to ${operatorEmail}`);
140
+ // The operator also needs iam.serviceAccountUser ON the agent SA to
141
+ // attach it to the VM at Step 7 (GCE requires the VM creator to have
142
+ // serviceAccountUser on the SA it attaches). Without it the create
143
+ // operation fails with SERVICE_ACCOUNT_ACCESS_DENIED and GCE tears the
144
+ // instance down to STOPPING within seconds.
145
+ await grantRoleOnServiceAccount(auth, projectId, accountId, smMember(operatorEmail), 'roles/iam.serviceAccountUser').catch((e) => {
146
+ warn(`Could not grant roles/iam.serviceAccountUser on ${email} to ${operatorEmail}: ${e.message}`);
147
+ });
148
+ info(` Granted roles/iam.serviceAccountUser on ${email} to ${operatorEmail}`);
149
+ }
150
+ else {
151
+ warn('Could not identify the operator (ADC identity has no email). Skipping roles/secretmanager.admin + iam.serviceAccountUser grants — the calling identity must already have them (e.g. granted via the staging deploy workflow) or SM writes / VM creation will fail (403 / SERVICE_ACCOUNT_ACCESS_DENIED).');
152
+ }
127
153
  saveConfig(config);
128
154
  success('Service account configured');
129
155
  }
@@ -187,11 +213,19 @@ async function stepBilling(auth, config, args) {
187
213
  }
188
214
  async function stepGitHub(auth, config, args) {
189
215
  heading('Step 5: GitHub + OIDC Setup');
190
- if (args.githubPat) {
191
- config.githubPat = args.githubPat;
216
+ const projectId = config.gcpProjectId;
217
+ // Secret values are written to Secret Manager and used only in-memory during
218
+ // this run (map #36 decision #7/#8: config carries references only).
219
+ let pat = args.githubPat || '';
220
+ if (!pat) {
221
+ // Re-run with an existing ref → read on demand from SM instead of prompting.
222
+ if (config.smSecrets?.githubPat) {
223
+ info('Reading GitHub PAT from Secret Manager...');
224
+ pat = (await smFetchSecret(auth, projectId, 'github-pat')) || '';
225
+ }
192
226
  }
193
- else if (!config.githubPat) {
194
- const { pat } = await inquirer.prompt([
227
+ if (!pat) {
228
+ const { pat: entered } = await inquirer.prompt([
195
229
  {
196
230
  type: 'password',
197
231
  name: 'pat',
@@ -199,9 +233,17 @@ async function stepGitHub(auth, config, args) {
199
233
  validate: (v) => v.length > 0 || 'Required',
200
234
  },
201
235
  ]);
202
- config.githubPat = pat;
236
+ pat = entered;
237
+ }
238
+ // Activate SM API (idempotent) before writing.
239
+ await enableApi(auth, projectId, 'secretmanager.googleapis.com');
240
+ const members = await buildSmMembers(auth, config);
241
+ if (members.length === 0) {
242
+ throw new CLIError('Cannot store GitHub PAT: no service account or operator identity found.');
203
243
  }
204
- const userInfo = await validatePat(config.githubPat);
244
+ const secretRef = await smWriteSecret(auth, projectId, 'github-pat', pat, members, info);
245
+ config.smSecrets = { ...(config.smSecrets || {}), githubPat: secretRef };
246
+ const userInfo = await validatePat(pat);
205
247
  info(`GitHub user: ${userInfo.login}`);
206
248
  const repoName = args.repoName || (await inquirer.prompt([
207
249
  {
@@ -213,7 +255,7 @@ async function stepGitHub(auth, config, args) {
213
255
  ])).repoName;
214
256
  const repoFull = `${userInfo.login}/${repoName}`;
215
257
  info(`Ensuring repo: ${repoFull}`);
216
- await ensureRepo(config.githubPat, repoFull);
258
+ await ensureRepo(pat, repoFull);
217
259
  config.githubRepo = repoFull;
218
260
  info('Setting up OIDC infrastructure...');
219
261
  const oidcData = await setupOidc(auth, config.gcpProjectId, repoFull);
@@ -230,7 +272,7 @@ async function stepGitHub(auth, config, args) {
230
272
  ];
231
273
  for (const [name, value] of varConfigs) {
232
274
  if (value) {
233
- await setGitHubVariable(config.githubPat, repoFull, name, value).catch(() => {
275
+ await setGitHubVariable(pat, repoFull, name, value).catch(() => {
234
276
  warn(`Could not set GitHub variable ${name} (may already exist)`);
235
277
  });
236
278
  }
@@ -243,22 +285,42 @@ async function stepGitHub(auth, config, args) {
243
285
  for (const field of firebaseFields) {
244
286
  const upperField = field.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
245
287
  if (configData[field]) {
246
- await setGitHubVariable(config.githubPat, repoFull, `FIREBASE_${upperField}_${env}`, configData[field]).catch(() => { });
288
+ await setGitHubVariable(pat, repoFull, `FIREBASE_${upperField}_${env}`, configData[field]).catch(() => { });
247
289
  }
248
290
  }
249
- await setGitHubVariable(config.githubPat, repoFull, `FIREBASE_PROJECT_ID_${env}`, configData.projectId).catch(() => { });
291
+ await setGitHubVariable(pat, repoFull, `FIREBASE_PROJECT_ID_${env}`, configData.projectId).catch(() => { });
250
292
  }
251
293
  }
252
294
  saveConfig(config);
253
295
  success(`GitHub repo ready: ${repoFull}`);
254
296
  }
255
- async function stepDiscord(config, args) {
297
+ // Per-secret accessors for the 2 SM secrets (map #36): the operator (ADC
298
+ // identity, user or service account) and the identity-only agent SA. The agent
299
+ // SA is what the VM boots with; the operator is for re-run fetches.
300
+ async function buildSmMembers(auth, config) {
301
+ const members = [];
302
+ if (config.saEmail)
303
+ members.push(`serviceAccount:${config.saEmail}`);
304
+ try {
305
+ const email = await auth.getClientEmail();
306
+ if (email)
307
+ members.push(smMember(email));
308
+ }
309
+ catch {
310
+ // ADC may not expose an email — agent SA membership is enough.
311
+ }
312
+ return members;
313
+ }
314
+ async function stepDiscord(auth, config, args) {
256
315
  heading('Step 6: Discord Bot');
257
- if (args.discordToken) {
258
- config.discordBotToken = args.discordToken;
259
- config.discordGuildId = args.discordGuild || '';
316
+ const projectId = config.gcpProjectId;
317
+ // Secret value used in-memory only (map #36 decision #7/#8).
318
+ let token = args.discordToken || '';
319
+ if (!token && config.smSecrets?.discordBotToken) {
320
+ info('Reading Discord bot token from Secret Manager...');
321
+ token = (await smFetchSecret(auth, projectId, 'discord-bot-token')) || '';
260
322
  }
261
- else if (!config.discordBotToken) {
323
+ if (!token) {
262
324
  const { botToken } = await inquirer.prompt([
263
325
  {
264
326
  type: 'password',
@@ -267,13 +329,21 @@ async function stepDiscord(config, args) {
267
329
  validate: (v) => v.length > 0 || 'Required',
268
330
  },
269
331
  ]);
270
- config.discordBotToken = botToken;
332
+ token = botToken;
333
+ }
334
+ // Write to the same SM store the web wizard uses; config keeps only the ref.
335
+ await enableApi(auth, projectId, 'secretmanager.googleapis.com');
336
+ const members = await buildSmMembers(auth, config);
337
+ if (members.length === 0) {
338
+ throw new CLIError('Cannot store Discord bot token: no service account or operator identity found.');
271
339
  }
340
+ const secretRef = await smWriteSecret(auth, projectId, 'discord-bot-token', token, members, info);
341
+ config.smSecrets = { ...(config.smSecrets || {}), discordBotToken: secretRef };
272
342
  if (args.discordGuild) {
273
343
  config.discordGuildId = args.discordGuild;
274
344
  }
275
- // Decode client ID from token
276
- const decoded = Buffer.from(config.discordBotToken.split('.')[0], 'base64').toString();
345
+ // Decode client ID from the in-memory token.
346
+ const decoded = Buffer.from(token.split('.')[0], 'base64').toString();
277
347
  const clientIdMatch = decoded.match(/"(?:id|client_id)"\s*:\s*"(\d+)"/);
278
348
  if (clientIdMatch) {
279
349
  info(`Bot Client ID: ${clientIdMatch[1]}`);
@@ -281,9 +351,10 @@ async function stepDiscord(config, args) {
281
351
  if (!config.discordGuildId) {
282
352
  if (args.yes) {
283
353
  info('No guild ID provided, skipping guild prompt (-y mode)');
354
+ config.discordGuildId = '';
284
355
  }
285
356
  else {
286
- const inviteUrl = `https://discord.com/oauth2/authorize?client_id=${Buffer.from(config.discordBotToken.split('.')[0], 'base64').toString().match(/"(\d+)"/)?.[1] || 'UNKNOWN'}&permissions=8&integration_type=0&scope=bot%20applications.commands`;
357
+ const inviteUrl = `https://discord.com/oauth2/authorize?client_id=${decoded.match(/"(\d+)"/)?.[1] || 'UNKNOWN'}&permissions=8&integration_type=0&scope=bot%20applications.commands`;
287
358
  warn(`Invite your bot to a server: ${inviteUrl}`);
288
359
  const { guildId } = await inquirer.prompt([
289
360
  {
@@ -306,11 +377,12 @@ async function stepCreateVm(auth, config, args) {
306
377
  await enableApi(auth, projectId, 'compute.googleapis.com');
307
378
  info('Enabling IAM Credentials API...');
308
379
  await enableApi(auth, projectId, 'iamcredentials.googleapis.com');
309
- // Build metadata (same as web wizard's buildVmMetadata)
380
+ // Build metadata (same as the web wizard's buildVmMetadata). Secret VALUES
381
+ // are NOT carried here (map #36 decision #9): the startup script fetches
382
+ // github-pat + discord-bot-token from Secret Manager via the metadata-server
383
+ // identity (the agent SA attached below).
310
384
  const metadata = {
311
- github_pat: config.githubPat || '',
312
385
  github_repo: config.githubRepo || '',
313
- discord_bot_token: config.discordBotToken || '',
314
386
  discord_guild_id: config.discordGuildId || '',
315
387
  firebase_staging: config.firebaseStaging?.projectId || '',
316
388
  firebase_production: config.firebaseProduction?.projectId || '',
@@ -341,7 +413,7 @@ async function stepCreateVm(auth, config, args) {
341
413
  for (const zone of zones) {
342
414
  try {
343
415
  info(`Attempting VM creation in ${zone}...`);
344
- vmResult = await createVm(auth, projectId, zone, 'secureagent-manager', metadata);
416
+ vmResult = await createVm(auth, projectId, zone, 'secureagent-manager', metadata, config.saEmail);
345
417
  config.vmIp = vmResult.ip;
346
418
  config.vmZone = vmResult.zone;
347
419
  break;
@@ -12,6 +12,10 @@ export async function runStatus() {
12
12
  kv('Staging Firebase', config.firebaseStaging?.projectId || '-');
13
13
  kv('Production Firebase', config.firebaseProduction?.projectId || '-');
14
14
  kv('GitHub Repo', config.githubRepo || '-');
15
+ kv('Discord Guild', config.discordGuildId || '-');
15
16
  kv('VM IP', config.vmIp || '-');
16
17
  kv('VM Zone', config.vmZone || '-');
18
+ // Secret references only — never values (map #36 decision #8).
19
+ kv('GitHub PAT (SM)', config.smSecrets?.githubPat || 'not stored');
20
+ kv('Discord Bot Token (SM)', config.smSecrets?.discordBotToken || 'not stored');
17
21
  }
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ program
21
21
  .option('--repo-name <name>', 'GitHub repo name (requires --github-pat)')
22
22
  .option('--discord-token <token>', 'Discord bot token')
23
23
  .option('--discord-guild <id>', 'Discord guild ID')
24
- .option('--vm-zone <zone>', 'VM zone (default: us-central1-a)')
24
+ .option('--vm-zone <zone>', 'VM zone (default: us-central1-a, falls back across regions)')
25
25
  .option('--no-vm', 'Skip VM creation')
26
26
  .option('-y, --yes', 'Skip all confirmations (non-interactive mode)')
27
27
  .action(async (opts) => {
@@ -35,7 +35,7 @@ program
35
35
  repoName: opts.repoName,
36
36
  discordToken: opts.discordToken,
37
37
  discordGuild: opts.discordGuild,
38
- vmZone: opts.vmZone || 'us-central1-a',
38
+ vmZone: opts.vmZone,
39
39
  yes: opts.yes,
40
40
  vm: opts.vm,
41
41
  });
package/dist/lib/gcp.d.ts CHANGED
@@ -13,10 +13,17 @@ export declare function createServiceAccount(auth: AuthClient, projectId: string
13
13
  email: string;
14
14
  }>;
15
15
  export declare function grantRole(auth: AuthClient, resource: string, member: string, role: string): Promise<void>;
16
- export declare function createVm(auth: AuthClient, projectId: string, zone: string, instanceName: string, metadata: Record<string, string>): Promise<{
16
+ export declare function grantRoleOnServiceAccount(auth: AuthClient, projectId: string, accountId: string, member: string, role: string): Promise<void>;
17
+ export declare function createVm(auth: AuthClient, projectId: string, zone: string, instanceName: string, metadata: Record<string, string>, saEmail?: string): Promise<{
17
18
  ip: string;
18
19
  zone: string;
19
20
  }>;
20
21
  export declare function deleteVm(auth: AuthClient, projectId: string, zone: string, instanceName: string): Promise<void>;
21
22
  export declare function cleanupVmByName(auth: AuthClient, projectId: string, instanceName: string): Promise<void>;
22
23
  export declare function fetchVmLogs(auth: AuthClient, projectId: string, zone: string, instanceName: string): Promise<string>;
24
+ export declare const smMember: (email: string) => string;
25
+ export declare const smEnsureSecret: (auth: AuthClient, projectId: string, secretId: string) => Promise<string>;
26
+ export declare const smAddVersion: (auth: AuthClient, projectId: string, secretId: string, value: string) => Promise<string>;
27
+ export declare const smSetSecretAccess: (auth: AuthClient, projectId: string, secretId: string, members: string[]) => Promise<void>;
28
+ export declare const smWriteSecret: (auth: AuthClient, projectId: string, secretId: string, value: string, members: string[], log?: (msg: string) => void) => Promise<string>;
29
+ export declare const smFetchSecret: (auth: AuthClient, projectId: string, secretId: string) => Promise<string | null>;
package/dist/lib/gcp.js CHANGED
@@ -97,8 +97,32 @@ export async function grantRole(auth, resource, member, role) {
97
97
  body: { policy: { bindings, etag: policy.etag } },
98
98
  });
99
99
  }
100
- export async function createVm(auth, projectId, zone, instanceName, metadata) {
100
+ // Grants a role ON a service account resource (e.g. iam.serviceAccountUser on
101
+ // the agent SA so a VM creator can attach it). The IAM API is used instead of
102
+ // cloudresourcemanager because the latter only supports projects/folders.
103
+ export async function grantRoleOnServiceAccount(auth, projectId, accountId, member, role) {
104
+ const base = `https://iam.googleapis.com/v1/projects/${projectId}/serviceAccounts/${accountId}`;
105
+ const policy = await gcpFetch(auth, `${base}:getIamPolicy`, { method: 'POST' });
106
+ const bindings = policy.bindings || [];
107
+ const existing = bindings.find((b) => b.role === role);
108
+ if (!existing) {
109
+ bindings.push({ role, members: [member] });
110
+ }
111
+ else if (!existing.members.includes(member)) {
112
+ existing.members.push(member);
113
+ }
114
+ else {
115
+ return; // Already has the role
116
+ }
117
+ await gcpFetch(auth, `${base}:setIamPolicy`, {
118
+ method: 'POST',
119
+ body: { policy: { bindings, etag: policy.etag } },
120
+ });
121
+ }
122
+ export async function createVm(auth, projectId, zone, instanceName, metadata, saEmail) {
101
123
  const url = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances`;
124
+ // The VM boots with the identity-only agent SA (map #36 decision #3) so the
125
+ // startup script can fetch the 2 secrets via the metadata-server identity.
102
126
  const body = {
103
127
  name: instanceName,
104
128
  // Default to e2-small — same default as the web wizard (see
@@ -118,7 +142,11 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
118
142
  networkInterfaces: [
119
143
  {
120
144
  network: 'global/networks/default',
121
- accessConfigs: [{ type: 'ONE_TO_ONE_NAT', name: 'External NAT' }],
145
+ // No explicit name: GCE defaults the access config to 'external-nat'.
146
+ // An explicit name like 'External NAT' (space/uppercase) is invalid
147
+ // and GCE rejects the create operation, tearing the VM down to
148
+ // STOPPING within seconds (observed across all 12 zones).
149
+ accessConfigs: [{ type: 'ONE_TO_ONE_NAT' }],
122
150
  },
123
151
  ],
124
152
  metadata: {
@@ -128,6 +156,11 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
128
156
  })),
129
157
  },
130
158
  };
159
+ if (saEmail) {
160
+ body.serviceAccounts = [
161
+ { email: saEmail, scopes: ['https://www.googleapis.com/auth/cloud-platform'] },
162
+ ];
163
+ }
131
164
  // Try to delete any existing VM with this name in the target zone
132
165
  const existingUrl = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`;
133
166
  try {
@@ -146,7 +179,36 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
146
179
  catch {
147
180
  // VM doesn't exist — that's fine
148
181
  }
149
- const result = await gcpFetch(auth, url, { method: 'POST', body });
182
+ // POST create returns an Operation; poll it to DONE. If the operation
183
+ // fails, its error is the ground truth for why the VM never becomes
184
+ // RUNNING (GCE otherwise tears the instance down to STOPPING/TERMINATED
185
+ // with no obvious cause from the instance resource itself).
186
+ const op = await gcpFetch(auth, url, { method: 'POST', body });
187
+ const opName = op?.name;
188
+ const opSelfLink = op?.selfLink;
189
+ let opBase;
190
+ if (opName) {
191
+ opBase = opSelfLink?.includes('global/operations')
192
+ ? `https://compute.googleapis.com/compute/v1/projects/${projectId}/global/operations/${opName}`
193
+ : `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/operations/${opName}`;
194
+ for (let o = 0; o < 60; o++) {
195
+ await new Promise((r) => setTimeout(r, 3000));
196
+ let status;
197
+ try {
198
+ status = await gcpFetch(auth, opBase);
199
+ }
200
+ catch {
201
+ continue; // Operation not visible yet
202
+ }
203
+ if (status?.status === 'DONE') {
204
+ if (status?.error) {
205
+ const detail = JSON.stringify(status.error.errors || status.error).slice(0, 2000);
206
+ throw new Error(`VM create operation failed: ${detail}`);
207
+ }
208
+ break;
209
+ }
210
+ }
211
+ }
150
212
  // Poll until VM is RUNNING (up to 10 minutes)
151
213
  for (let i = 0; i < 120; i++) {
152
214
  await new Promise((r) => setTimeout(r, 5000));
@@ -159,6 +221,25 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
159
221
  if (instance.status === 'STOPPING' || instance.status === 'TERMINATED') {
160
222
  // VM is dying — abort early, delete it, and let the caller try the next zone
161
223
  console.log(` VM is ${instance.status}, aborting and trying next zone...`);
224
+ // Dump the create operation error if we still have one, plus the
225
+ // serial console, for ground truth on why the VM stopped.
226
+ if (opName && opBase) {
227
+ try {
228
+ const opNow = await gcpFetch(auth, opBase);
229
+ if (opNow?.error) {
230
+ console.log(` create operation error: ${JSON.stringify(opNow.error.errors || opNow.error).slice(0, 2000)}`);
231
+ }
232
+ }
233
+ catch { }
234
+ }
235
+ try {
236
+ const serial = await fetchVmLogs(auth, projectId, zone, instanceName);
237
+ const tail = serial.split('\n').filter((l) => l.trim()).slice(-30).join('\n');
238
+ console.log(` --- serial console (last 30 lines) ---\n${tail}\n ----------------------------------------`);
239
+ }
240
+ catch (e) {
241
+ console.log(` (serial console unavailable: ${e.message})`);
242
+ }
162
243
  try {
163
244
  await gcpFetch(auth, existingUrl, { method: 'DELETE' });
164
245
  }
@@ -170,7 +251,7 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
170
251
  }
171
252
  }
172
253
  catch (e) {
173
- if (e.message?.includes('aborting') || e.message?.includes('STOPPING') || e.message?.includes('TERMINATED'))
254
+ if (e.message?.includes('aborting') || e.message?.includes('STOPPING') || e.message?.includes('TERMINATED') || e.message?.includes('operation failed'))
174
255
  throw e;
175
256
  // Instance not yet available
176
257
  }
@@ -223,3 +304,96 @@ export async function fetchVmLogs(auth, projectId, zone, instanceName) {
223
304
  const result = await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}/serialPort?port=1`);
224
305
  return (result.contents || '').split('\n').map((l) => atob(l)).join('\n');
225
306
  }
307
+ // ---------------------------------------------------------------------------
308
+ // Secret Manager helpers (map #36 decision #7). The CLI writes the 2 secrets
309
+ // (github-pat, discord-bot-token) to the SAME SM store the web wizard uses, at
310
+ // prompt time. The operator (ADC identity) must have roles/secretmanager.admin
311
+ // — granted in stepServiceAccount — and per-secret secretAccessor is bound to
312
+ // the operator + the identity-only agent SA (the VM's metadata identity).
313
+ // Mirrors src/framework/infra-setup/api.ts.
314
+ // ---------------------------------------------------------------------------
315
+ const SM_BASE = 'https://secretmanager.googleapis.com/v1';
316
+ const base64Encode = (value) => Buffer.from(value, 'utf-8').toString('base64');
317
+ // Project-level member prefix: service accounts end in *.gserviceaccount.com,
318
+ // everything else (gcloud ADC user, WIF-federated user) is a `user:`.
319
+ export const smMember = (email) => email.endsWith('.gserviceaccount.com') ? `serviceAccount:${email}` : `user:${email}`;
320
+ export const smEnsureSecret = async (auth, projectId, secretId) => {
321
+ // The API-enable loop activates secretmanager.googleapis.com before writing,
322
+ // but GCP can lag a few seconds past the status poll. Retry briefly on
323
+ // SERVICE_DISABLED so a brand-new project doesn't 403 on the first write.
324
+ for (let attempt = 0; attempt < 3; attempt++) {
325
+ try {
326
+ const secret = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets?secretId=${encodeURIComponent(secretId)}`, {
327
+ method: 'POST',
328
+ body: { replication: { automatic: {} } },
329
+ });
330
+ return secret.name;
331
+ }
332
+ catch (e) {
333
+ if (e.message?.includes('SERVICE_DISABLED')) {
334
+ if (attempt < 2) {
335
+ await new Promise((r) => setTimeout(r, 5000));
336
+ continue;
337
+ }
338
+ throw new Error(`Secret Manager API is not active for project ${projectId}: ${e.message}`);
339
+ }
340
+ // 409 ALREADY_EXISTS — fetch the existing secret instead.
341
+ if (!e.message?.includes('409'))
342
+ throw e;
343
+ const existing = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}`);
344
+ return existing.name;
345
+ }
346
+ }
347
+ throw new Error(`Secret Manager API did not activate for project ${projectId}`);
348
+ };
349
+ export const smAddVersion = async (auth, projectId, secretId, value) => {
350
+ const added = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:addVersion`, {
351
+ method: 'POST',
352
+ body: { payload: { data: base64Encode(value) } },
353
+ });
354
+ return added.name;
355
+ };
356
+ export const smSetSecretAccess = async (auth, projectId, secretId, members) => {
357
+ const policy = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:getIamPolicy`);
358
+ const bindings = policy.bindings || [];
359
+ let binding = bindings.find((b) => b.role === 'roles/secretmanager.secretAccessor');
360
+ if (!binding) {
361
+ binding = { role: 'roles/secretmanager.secretAccessor', members: [] };
362
+ bindings.push(binding);
363
+ }
364
+ for (const member of members) {
365
+ if (!binding.members.includes(member))
366
+ binding.members.push(member);
367
+ }
368
+ await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:setIamPolicy`, {
369
+ method: 'POST',
370
+ body: { policy: { bindings, etag: policy.etag } },
371
+ });
372
+ };
373
+ // Idempotent write: create-or-get the secret, add a new version, and bind the
374
+ // per-secret accessors (operator + agent SA). Returns the secret resource name
375
+ // used as a config reference.
376
+ export const smWriteSecret = async (auth, projectId, secretId, value, members, log) => {
377
+ const secretName = await smEnsureSecret(auth, projectId, secretId);
378
+ await smAddVersion(auth, projectId, secretId, value);
379
+ await smSetSecretAccess(auth, projectId, secretId, members);
380
+ log?.(`Secret ${secretId} stored in Secret Manager (${secretName})`);
381
+ return secretName;
382
+ };
383
+ // Read the latest version on demand (decision #7). Used for re-runs that need
384
+ // the in-memory value (e.g. re-validate a PAT). Returns null if the secret
385
+ // does not exist (404) so callers can fall back to a prompt.
386
+ export const smFetchSecret = async (auth, projectId, secretId) => {
387
+ try {
388
+ const result = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}/versions/latest:access`);
389
+ const b64 = result?.payload?.data;
390
+ if (!b64)
391
+ return null;
392
+ return Buffer.from(b64, 'base64').toString('utf-8');
393
+ }
394
+ catch (e) {
395
+ if (e.message?.includes('404') || e.message?.includes('403'))
396
+ return null;
397
+ throw e;
398
+ }
399
+ };
@@ -29,12 +29,13 @@ GCP_SA_PRODUCTION=$(curl -sf "http://metadata.google.internal/computeMetadata/v1
29
29
  FIREBASE_STAGING_CONFIG=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_staging_config" -H "Metadata-Flavor: Google")
30
30
  FIREBASE_PRODUCTION_CONFIG=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_production_config" -H "Metadata-Flavor: Google")
31
31
  VITE_APP_NAME=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/vite_app_name" -H "Metadata-Flavor: Google")
32
- GCP_SA_KEY=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcp_sa_key" -H "Metadata-Flavor: Google")
33
32
  # Secret values (GITHUB_PAT / DISCORD_BOT_TOKEN) are NOT carried in VM metadata —
34
33
  # they are fetched from Secret Manager below via the metadata-server identity.
34
+ # The agent SA is identity-only (map #36 decision #6): no gcp_sa_key
35
+ # metadata, no key file on disk — the SA authenticates via the metadata server.
35
36
 
36
37
  # Clean up any potential HTML responses from failed requests or unconfigured metadata
37
- for var in FIREBASE_STAGING FIREBASE_PRODUCTION DISCORD_GUILD_ID GCP_WIF_PROVIDER GCP_SA_STAGING GCP_SA_PRODUCTION FIREBASE_STAGING_CONFIG FIREBASE_PRODUCTION_CONFIG VITE_APP_NAME GCP_SA_KEY; do
38
+ for var in FIREBASE_STAGING FIREBASE_PRODUCTION DISCORD_GUILD_ID GCP_WIF_PROVIDER GCP_SA_STAGING GCP_SA_PRODUCTION FIREBASE_STAGING_CONFIG FIREBASE_PRODUCTION_CONFIG VITE_APP_NAME; do
38
39
  val=${!var}
39
40
  if [[ "$val" =~ "<html" || "$val" =~ "<!" || "$val" =~ "<HTML" ]]; then
40
41
  eval "$var=\"\""
@@ -362,12 +363,6 @@ NODE_ENV=production
362
363
  ENVEOF
363
364
  chmod 600 /root/.kimaki/env
364
365
 
365
- # Write GCP service account key from metadata (if provided) to a restricted file
366
- if [ -n "$GCP_SA_KEY" ]; then
367
- echo "$GCP_SA_KEY" > /root/.kimaki/gcp-sa-key.json
368
- chmod 600 /root/.kimaki/gcp-sa-key.json
369
- fi
370
-
371
366
  # Create systemd service for Kimaki (no-clobber — never overwrite a running unit)
372
367
  KIMAKI_PATH=$(command -v kimaki || true)
373
368
  # Resolve node explicitly: the pinned tarball installs to /usr/local/bin while
@@ -3,9 +3,11 @@ export interface Config {
3
3
  saEmail?: string;
4
4
  firebaseStaging?: Record<string, string>;
5
5
  firebaseProduction?: Record<string, string>;
6
- githubPat?: string;
6
+ smSecrets?: {
7
+ githubPat?: string;
8
+ discordBotToken?: string;
9
+ };
7
10
  githubRepo?: string;
8
- discordBotToken?: string;
9
11
  discordGuildId?: string;
10
12
  vmIp?: string;
11
13
  vmZone?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "secureagentbase",
3
- "version": "1.4.5",
3
+ "version": "1.4.6",
4
4
  "description": "CLI tool to deploy and manage SecureAgentBase on GCP",
5
5
  "type": "module",
6
6
  "bin": {