secureagentbase 1.4.5 → 1.4.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.
@@ -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
  }
@@ -158,6 +184,14 @@ async function stepBilling(auth, config, args) {
158
184
  }
159
185
  const accounts = await fetchBillingAccounts(auth, projectId);
160
186
  if (accounts.length === 0) {
187
+ // -y means "skip all prompts (non-interactive mode)". Without this the
188
+ // inquirer prompt blocks forever in CI (no TTY to answer it), which
189
+ // deadlocks `init` until the caller's timeout kills it.
190
+ if (args.yes) {
191
+ warn('No billing accounts found — skipping billing link (-y mode).');
192
+ warn('Pass --billing-account <id> to link one, or grant the caller roles/billing.user on the billing account.');
193
+ return;
194
+ }
161
195
  warn('No billing accounts found');
162
196
  const { billingAccountId } = await inquirer.prompt([
163
197
  {
@@ -170,6 +204,15 @@ async function stepBilling(auth, config, args) {
170
204
  success(`Linked billing account: ${billingAccountId}`);
171
205
  }
172
206
  else {
207
+ if (args.yes) {
208
+ // Deterministic in -y mode: take the first account rather than
209
+ // prompting (prompts are what break non-interactive runs).
210
+ const accountId = accounts[0].name?.replace('billingAccounts/', '');
211
+ info(`Linking billing account: ${accountId} (-y mode)`);
212
+ await linkBillingAccount(auth, projectId, accountId);
213
+ success(`Linked billing account: ${accountId}`);
214
+ return;
215
+ }
173
216
  const { selectedAccount } = await inquirer.prompt([
174
217
  {
175
218
  type: 'list',
@@ -187,11 +230,19 @@ async function stepBilling(auth, config, args) {
187
230
  }
188
231
  async function stepGitHub(auth, config, args) {
189
232
  heading('Step 5: GitHub + OIDC Setup');
190
- if (args.githubPat) {
191
- config.githubPat = args.githubPat;
233
+ const projectId = config.gcpProjectId;
234
+ // Secret values are written to Secret Manager and used only in-memory during
235
+ // this run (map #36 decision #7/#8: config carries references only).
236
+ let pat = args.githubPat || '';
237
+ if (!pat) {
238
+ // Re-run with an existing ref → read on demand from SM instead of prompting.
239
+ if (config.smSecrets?.githubPat) {
240
+ info('Reading GitHub PAT from Secret Manager...');
241
+ pat = (await smFetchSecret(auth, projectId, 'github-pat')) || '';
242
+ }
192
243
  }
193
- else if (!config.githubPat) {
194
- const { pat } = await inquirer.prompt([
244
+ if (!pat) {
245
+ const { pat: entered } = await inquirer.prompt([
195
246
  {
196
247
  type: 'password',
197
248
  name: 'pat',
@@ -199,9 +250,17 @@ async function stepGitHub(auth, config, args) {
199
250
  validate: (v) => v.length > 0 || 'Required',
200
251
  },
201
252
  ]);
202
- config.githubPat = pat;
253
+ pat = entered;
254
+ }
255
+ // Activate SM API (idempotent) before writing.
256
+ await enableApi(auth, projectId, 'secretmanager.googleapis.com');
257
+ const members = await buildSmMembers(auth, config);
258
+ if (members.length === 0) {
259
+ throw new CLIError('Cannot store GitHub PAT: no service account or operator identity found.');
203
260
  }
204
- const userInfo = await validatePat(config.githubPat);
261
+ const secretRef = await smWriteSecret(auth, projectId, 'github-pat', pat, members, info);
262
+ config.smSecrets = { ...(config.smSecrets || {}), githubPat: secretRef };
263
+ const userInfo = await validatePat(pat);
205
264
  info(`GitHub user: ${userInfo.login}`);
206
265
  const repoName = args.repoName || (await inquirer.prompt([
207
266
  {
@@ -213,24 +272,27 @@ async function stepGitHub(auth, config, args) {
213
272
  ])).repoName;
214
273
  const repoFull = `${userInfo.login}/${repoName}`;
215
274
  info(`Ensuring repo: ${repoFull}`);
216
- await ensureRepo(config.githubPat, repoFull);
275
+ await ensureRepo(pat, repoFull);
217
276
  config.githubRepo = repoFull;
218
277
  info('Setting up OIDC infrastructure...');
219
278
  const oidcData = await setupOidc(auth, config.gcpProjectId, repoFull);
220
279
  config.oidc = oidcData;
221
280
  // Upload GitHub variables (best-effort — variables may already be set from prior run)
281
+ // NOTE: VITE_APP_MODE and VITE_APP_NAME are intentionally NOT set here.
282
+ // Copied apps run in template mode (the default) — which is where the posts
283
+ // feature lives — and display "Your App" until the user brands it (or sets
284
+ // the name via the VM's `vite_app_name` metadata). The SecureAgentBase
285
+ // product/template repo itself (app mode) blocks posts.
222
286
  const varConfigs = [
223
- ['VITE_APP_NAME', 'SecureAgentBase'],
224
287
  ['GCP_WIF_PROVIDER', oidcData.wifPoolName],
225
288
  ['GCP_SA_STAGING', oidcData.saStagingEmail],
226
289
  ['GCP_SA_PRODUCTION', oidcData.saProductionEmail],
227
290
  ['GCP_CLIENT_ID_STAGING', ''],
228
291
  ['GCP_CLIENT_ID_PRODUCTION', ''],
229
- ['VITE_APP_MODE', 'true'],
230
292
  ];
231
293
  for (const [name, value] of varConfigs) {
232
294
  if (value) {
233
- await setGitHubVariable(config.githubPat, repoFull, name, value).catch(() => {
295
+ await setGitHubVariable(pat, repoFull, name, value).catch(() => {
234
296
  warn(`Could not set GitHub variable ${name} (may already exist)`);
235
297
  });
236
298
  }
@@ -243,22 +305,42 @@ async function stepGitHub(auth, config, args) {
243
305
  for (const field of firebaseFields) {
244
306
  const upperField = field.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
245
307
  if (configData[field]) {
246
- await setGitHubVariable(config.githubPat, repoFull, `FIREBASE_${upperField}_${env}`, configData[field]).catch(() => { });
308
+ await setGitHubVariable(pat, repoFull, `FIREBASE_${upperField}_${env}`, configData[field]).catch(() => { });
247
309
  }
248
310
  }
249
- await setGitHubVariable(config.githubPat, repoFull, `FIREBASE_PROJECT_ID_${env}`, configData.projectId).catch(() => { });
311
+ await setGitHubVariable(pat, repoFull, `FIREBASE_PROJECT_ID_${env}`, configData.projectId).catch(() => { });
250
312
  }
251
313
  }
252
314
  saveConfig(config);
253
315
  success(`GitHub repo ready: ${repoFull}`);
254
316
  }
255
- async function stepDiscord(config, args) {
317
+ // Per-secret accessors for the 2 SM secrets (map #36): the operator (ADC
318
+ // identity, user or service account) and the identity-only agent SA. The agent
319
+ // SA is what the VM boots with; the operator is for re-run fetches.
320
+ async function buildSmMembers(auth, config) {
321
+ const members = [];
322
+ if (config.saEmail)
323
+ members.push(`serviceAccount:${config.saEmail}`);
324
+ try {
325
+ const email = await auth.getClientEmail();
326
+ if (email)
327
+ members.push(smMember(email));
328
+ }
329
+ catch {
330
+ // ADC may not expose an email — agent SA membership is enough.
331
+ }
332
+ return members;
333
+ }
334
+ async function stepDiscord(auth, config, args) {
256
335
  heading('Step 6: Discord Bot');
257
- if (args.discordToken) {
258
- config.discordBotToken = args.discordToken;
259
- config.discordGuildId = args.discordGuild || '';
336
+ const projectId = config.gcpProjectId;
337
+ // Secret value used in-memory only (map #36 decision #7/#8).
338
+ let token = args.discordToken || '';
339
+ if (!token && config.smSecrets?.discordBotToken) {
340
+ info('Reading Discord bot token from Secret Manager...');
341
+ token = (await smFetchSecret(auth, projectId, 'discord-bot-token')) || '';
260
342
  }
261
- else if (!config.discordBotToken) {
343
+ if (!token) {
262
344
  const { botToken } = await inquirer.prompt([
263
345
  {
264
346
  type: 'password',
@@ -267,13 +349,21 @@ async function stepDiscord(config, args) {
267
349
  validate: (v) => v.length > 0 || 'Required',
268
350
  },
269
351
  ]);
270
- config.discordBotToken = botToken;
352
+ token = botToken;
353
+ }
354
+ // Write to the same SM store the web wizard uses; config keeps only the ref.
355
+ await enableApi(auth, projectId, 'secretmanager.googleapis.com');
356
+ const members = await buildSmMembers(auth, config);
357
+ if (members.length === 0) {
358
+ throw new CLIError('Cannot store Discord bot token: no service account or operator identity found.');
271
359
  }
360
+ const secretRef = await smWriteSecret(auth, projectId, 'discord-bot-token', token, members, info);
361
+ config.smSecrets = { ...(config.smSecrets || {}), discordBotToken: secretRef };
272
362
  if (args.discordGuild) {
273
363
  config.discordGuildId = args.discordGuild;
274
364
  }
275
- // Decode client ID from token
276
- const decoded = Buffer.from(config.discordBotToken.split('.')[0], 'base64').toString();
365
+ // Decode client ID from the in-memory token.
366
+ const decoded = Buffer.from(token.split('.')[0], 'base64').toString();
277
367
  const clientIdMatch = decoded.match(/"(?:id|client_id)"\s*:\s*"(\d+)"/);
278
368
  if (clientIdMatch) {
279
369
  info(`Bot Client ID: ${clientIdMatch[1]}`);
@@ -281,9 +371,10 @@ async function stepDiscord(config, args) {
281
371
  if (!config.discordGuildId) {
282
372
  if (args.yes) {
283
373
  info('No guild ID provided, skipping guild prompt (-y mode)');
374
+ config.discordGuildId = '';
284
375
  }
285
376
  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`;
377
+ const inviteUrl = `https://discord.com/oauth2/authorize?client_id=${decoded.match(/"(\d+)"/)?.[1] || 'UNKNOWN'}&permissions=8&integration_type=0&scope=bot%20applications.commands`;
287
378
  warn(`Invite your bot to a server: ${inviteUrl}`);
288
379
  const { guildId } = await inquirer.prompt([
289
380
  {
@@ -306,11 +397,12 @@ async function stepCreateVm(auth, config, args) {
306
397
  await enableApi(auth, projectId, 'compute.googleapis.com');
307
398
  info('Enabling IAM Credentials API...');
308
399
  await enableApi(auth, projectId, 'iamcredentials.googleapis.com');
309
- // Build metadata (same as web wizard's buildVmMetadata)
400
+ // Build metadata (same as the web wizard's buildVmMetadata). Secret VALUES
401
+ // are NOT carried here (map #36 decision #9): the startup script fetches
402
+ // github-pat + discord-bot-token from Secret Manager via the metadata-server
403
+ // identity (the agent SA attached below).
310
404
  const metadata = {
311
- github_pat: config.githubPat || '',
312
405
  github_repo: config.githubRepo || '',
313
- discord_bot_token: config.discordBotToken || '',
314
406
  discord_guild_id: config.discordGuildId || '',
315
407
  firebase_staging: config.firebaseStaging?.projectId || '',
316
408
  firebase_production: config.firebaseProduction?.projectId || '',
@@ -341,7 +433,7 @@ async function stepCreateVm(auth, config, args) {
341
433
  for (const zone of zones) {
342
434
  try {
343
435
  info(`Attempting VM creation in ${zone}...`);
344
- vmResult = await createVm(auth, projectId, zone, 'secureagent-manager', metadata);
436
+ vmResult = await createVm(auth, projectId, zone, 'secureagent-manager', metadata, config.saEmail);
345
437
  config.vmIp = vmResult.ip;
346
438
  config.vmZone = vmResult.zone;
347
439
  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
@@ -110,7 +134,9 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
110
134
  boot: true,
111
135
  autoDelete: true,
112
136
  initializeParams: {
113
- sourceImage: 'projects/debian-cloud/global/images/family/debian-11',
137
+ // debian-11 hit EOS 2026-08-31 and its image family was removed —
138
+ // creating with it now 404s in every zone. debian-12 is GA to 2028.
139
+ sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
114
140
  diskSizeGb: '10',
115
141
  },
116
142
  },
@@ -118,7 +144,11 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
118
144
  networkInterfaces: [
119
145
  {
120
146
  network: 'global/networks/default',
121
- accessConfigs: [{ type: 'ONE_TO_ONE_NAT', name: 'External NAT' }],
147
+ // No explicit name: GCE defaults the access config to 'external-nat'.
148
+ // An explicit name like 'External NAT' (space/uppercase) is invalid
149
+ // and GCE rejects the create operation, tearing the VM down to
150
+ // STOPPING within seconds (observed across all 12 zones).
151
+ accessConfigs: [{ type: 'ONE_TO_ONE_NAT' }],
122
152
  },
123
153
  ],
124
154
  metadata: {
@@ -128,6 +158,11 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
128
158
  })),
129
159
  },
130
160
  };
161
+ if (saEmail) {
162
+ body.serviceAccounts = [
163
+ { email: saEmail, scopes: ['https://www.googleapis.com/auth/cloud-platform'] },
164
+ ];
165
+ }
131
166
  // Try to delete any existing VM with this name in the target zone
132
167
  const existingUrl = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`;
133
168
  try {
@@ -146,7 +181,36 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
146
181
  catch {
147
182
  // VM doesn't exist — that's fine
148
183
  }
149
- const result = await gcpFetch(auth, url, { method: 'POST', body });
184
+ // POST create returns an Operation; poll it to DONE. If the operation
185
+ // fails, its error is the ground truth for why the VM never becomes
186
+ // RUNNING (GCE otherwise tears the instance down to STOPPING/TERMINATED
187
+ // with no obvious cause from the instance resource itself).
188
+ const op = await gcpFetch(auth, url, { method: 'POST', body });
189
+ const opName = op?.name;
190
+ const opSelfLink = op?.selfLink;
191
+ let opBase;
192
+ if (opName) {
193
+ opBase = opSelfLink?.includes('global/operations')
194
+ ? `https://compute.googleapis.com/compute/v1/projects/${projectId}/global/operations/${opName}`
195
+ : `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/operations/${opName}`;
196
+ for (let o = 0; o < 60; o++) {
197
+ await new Promise((r) => setTimeout(r, 3000));
198
+ let status;
199
+ try {
200
+ status = await gcpFetch(auth, opBase);
201
+ }
202
+ catch {
203
+ continue; // Operation not visible yet
204
+ }
205
+ if (status?.status === 'DONE') {
206
+ if (status?.error) {
207
+ const detail = JSON.stringify(status.error.errors || status.error).slice(0, 2000);
208
+ throw new Error(`VM create operation failed: ${detail}`);
209
+ }
210
+ break;
211
+ }
212
+ }
213
+ }
150
214
  // Poll until VM is RUNNING (up to 10 minutes)
151
215
  for (let i = 0; i < 120; i++) {
152
216
  await new Promise((r) => setTimeout(r, 5000));
@@ -159,6 +223,25 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
159
223
  if (instance.status === 'STOPPING' || instance.status === 'TERMINATED') {
160
224
  // VM is dying — abort early, delete it, and let the caller try the next zone
161
225
  console.log(` VM is ${instance.status}, aborting and trying next zone...`);
226
+ // Dump the create operation error if we still have one, plus the
227
+ // serial console, for ground truth on why the VM stopped.
228
+ if (opName && opBase) {
229
+ try {
230
+ const opNow = await gcpFetch(auth, opBase);
231
+ if (opNow?.error) {
232
+ console.log(` create operation error: ${JSON.stringify(opNow.error.errors || opNow.error).slice(0, 2000)}`);
233
+ }
234
+ }
235
+ catch { }
236
+ }
237
+ try {
238
+ const serial = await fetchVmLogs(auth, projectId, zone, instanceName);
239
+ const tail = serial.split('\n').filter((l) => l.trim()).slice(-30).join('\n');
240
+ console.log(` --- serial console (last 30 lines) ---\n${tail}\n ----------------------------------------`);
241
+ }
242
+ catch (e) {
243
+ console.log(` (serial console unavailable: ${e.message})`);
244
+ }
162
245
  try {
163
246
  await gcpFetch(auth, existingUrl, { method: 'DELETE' });
164
247
  }
@@ -170,7 +253,7 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
170
253
  }
171
254
  }
172
255
  catch (e) {
173
- if (e.message?.includes('aborting') || e.message?.includes('STOPPING') || e.message?.includes('TERMINATED'))
256
+ if (e.message?.includes('aborting') || e.message?.includes('STOPPING') || e.message?.includes('TERMINATED') || e.message?.includes('operation failed'))
174
257
  throw e;
175
258
  // Instance not yet available
176
259
  }
@@ -223,3 +306,96 @@ export async function fetchVmLogs(auth, projectId, zone, instanceName) {
223
306
  const result = await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}/serialPort?port=1`);
224
307
  return (result.contents || '').split('\n').map((l) => atob(l)).join('\n');
225
308
  }
309
+ // ---------------------------------------------------------------------------
310
+ // Secret Manager helpers (map #36 decision #7). The CLI writes the 2 secrets
311
+ // (github-pat, discord-bot-token) to the SAME SM store the web wizard uses, at
312
+ // prompt time. The operator (ADC identity) must have roles/secretmanager.admin
313
+ // — granted in stepServiceAccount — and per-secret secretAccessor is bound to
314
+ // the operator + the identity-only agent SA (the VM's metadata identity).
315
+ // Mirrors src/framework/infra-setup/api.ts.
316
+ // ---------------------------------------------------------------------------
317
+ const SM_BASE = 'https://secretmanager.googleapis.com/v1';
318
+ const base64Encode = (value) => Buffer.from(value, 'utf-8').toString('base64');
319
+ // Project-level member prefix: service accounts end in *.gserviceaccount.com,
320
+ // everything else (gcloud ADC user, WIF-federated user) is a `user:`.
321
+ export const smMember = (email) => email.endsWith('.gserviceaccount.com') ? `serviceAccount:${email}` : `user:${email}`;
322
+ export const smEnsureSecret = async (auth, projectId, secretId) => {
323
+ // The API-enable loop activates secretmanager.googleapis.com before writing,
324
+ // but GCP can lag a few seconds past the status poll. Retry briefly on
325
+ // SERVICE_DISABLED so a brand-new project doesn't 403 on the first write.
326
+ for (let attempt = 0; attempt < 3; attempt++) {
327
+ try {
328
+ const secret = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets?secretId=${encodeURIComponent(secretId)}`, {
329
+ method: 'POST',
330
+ body: { replication: { automatic: {} } },
331
+ });
332
+ return secret.name;
333
+ }
334
+ catch (e) {
335
+ if (e.message?.includes('SERVICE_DISABLED')) {
336
+ if (attempt < 2) {
337
+ await new Promise((r) => setTimeout(r, 5000));
338
+ continue;
339
+ }
340
+ throw new Error(`Secret Manager API is not active for project ${projectId}: ${e.message}`);
341
+ }
342
+ // 409 ALREADY_EXISTS — fetch the existing secret instead.
343
+ if (!e.message?.includes('409'))
344
+ throw e;
345
+ const existing = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}`);
346
+ return existing.name;
347
+ }
348
+ }
349
+ throw new Error(`Secret Manager API did not activate for project ${projectId}`);
350
+ };
351
+ export const smAddVersion = async (auth, projectId, secretId, value) => {
352
+ const added = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:addVersion`, {
353
+ method: 'POST',
354
+ body: { payload: { data: base64Encode(value) } },
355
+ });
356
+ return added.name;
357
+ };
358
+ export const smSetSecretAccess = async (auth, projectId, secretId, members) => {
359
+ const policy = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:getIamPolicy`);
360
+ const bindings = policy.bindings || [];
361
+ let binding = bindings.find((b) => b.role === 'roles/secretmanager.secretAccessor');
362
+ if (!binding) {
363
+ binding = { role: 'roles/secretmanager.secretAccessor', members: [] };
364
+ bindings.push(binding);
365
+ }
366
+ for (const member of members) {
367
+ if (!binding.members.includes(member))
368
+ binding.members.push(member);
369
+ }
370
+ await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:setIamPolicy`, {
371
+ method: 'POST',
372
+ body: { policy: { bindings, etag: policy.etag } },
373
+ });
374
+ };
375
+ // Idempotent write: create-or-get the secret, add a new version, and bind the
376
+ // per-secret accessors (operator + agent SA). Returns the secret resource name
377
+ // used as a config reference.
378
+ export const smWriteSecret = async (auth, projectId, secretId, value, members, log) => {
379
+ const secretName = await smEnsureSecret(auth, projectId, secretId);
380
+ await smAddVersion(auth, projectId, secretId, value);
381
+ await smSetSecretAccess(auth, projectId, secretId, members);
382
+ log?.(`Secret ${secretId} stored in Secret Manager (${secretName})`);
383
+ return secretName;
384
+ };
385
+ // Read the latest version on demand (decision #7). Used for re-runs that need
386
+ // the in-memory value (e.g. re-validate a PAT). Returns null if the secret
387
+ // does not exist (404) so callers can fall back to a prompt.
388
+ export const smFetchSecret = async (auth, projectId, secretId) => {
389
+ try {
390
+ const result = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}/versions/latest:access`);
391
+ const b64 = result?.payload?.data;
392
+ if (!b64)
393
+ return null;
394
+ return Buffer.from(b64, 'base64').toString('utf-8');
395
+ }
396
+ catch (e) {
397
+ if (e.message?.includes('404') || e.message?.includes('403'))
398
+ return null;
399
+ throw e;
400
+ }
401
+ };
@@ -29,18 +29,42 @@ 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")
32
+ TEMPLATE_REPO=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/template_repo" -H "Metadata-Flavor: Google")
33
+ OPENCODE_MODEL=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/opencode_model" -H "Metadata-Flavor: Google")
34
+ OPENCODE_AUTH_JSON=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/opencode_auth_json" -H "Metadata-Flavor: Google")
33
35
  # Secret values (GITHUB_PAT / DISCORD_BOT_TOKEN) are NOT carried in VM metadata —
34
36
  # they are fetched from Secret Manager below via the metadata-server identity.
37
+ # The agent SA is identity-only (map #36 decision #6): no gcp_sa_key
38
+ # metadata, no key file on disk — the SA authenticates via the metadata server.
35
39
 
36
40
  # 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
41
+ 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 TEMPLATE_REPO OPENCODE_MODEL OPENCODE_AUTH_JSON; do
38
42
  val=${!var}
39
43
  if [[ "$val" =~ "<html" || "$val" =~ "<!" || "$val" =~ "<HTML" ]]; then
40
44
  eval "$var=\"\""
41
45
  fi
42
46
  done
43
47
 
48
+ # Template repo to clone as the app skeleton (default: this repo). The
49
+ # destination repo (github_repo) is usually created BY the VM below, so the
50
+ # clone must come from the template, not from the not-yet-existing target.
51
+ : "${TEMPLATE_REPO:=kallhoffa/SecureAgentBase}"
52
+ if [[ "$TEMPLATE_REPO" =~ ^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$ ]]; then
53
+ TEMPLATE_OWNER=$(echo "$TEMPLATE_REPO" | cut -d'/' -f1)
54
+ TEMPLATE_NAME=$(echo "$TEMPLATE_REPO" | cut -d'/' -f2)
55
+ else
56
+ echo "WARNING: Invalid template_repo metadata, using kallhoffa/SecureAgentBase"
57
+ TEMPLATE_OWNER="kallhoffa"
58
+ TEMPLATE_NAME="SecureAgentBase"
59
+ fi
60
+
61
+ # Model written into the project opencode.json (validated charset so it can be
62
+ # interpolated into JSON safely; the wizard or operator may override via metadata).
63
+ : "${OPENCODE_MODEL:=opencode/big-pickle}"
64
+ if [[ ! "$OPENCODE_MODEL" =~ ^[A-Za-z0-9._/-]{1,128}$ ]]; then
65
+ OPENCODE_MODEL="opencode/big-pickle"
66
+ fi
67
+
44
68
  # Idempotency guard — GCP re-runs the startup script on EVERY boot, not just first boot.
45
69
  # Skip all provisioning steps if this VM was already set up, so reboots are harmless.
46
70
  if [ -f /root/.kimaki/.provisioned ]; then
@@ -66,6 +90,39 @@ check_disk
66
90
  sudo apt-get update -y > /dev/null 2>&1 || true
67
91
  sudo apt-get install -y curl git jq apt-transport-https ca-certificates gnupg2 ufw unzip > /dev/null 2>&1 || true
68
92
 
93
+ # Swap file — small VMs (e.g. e2-small, 3.8 GB RAM) ship with NO swap, so a
94
+ # memory spike (npm installs, vitest, vite builds, opencode) can hard-freeze
95
+ # the box: the OOM killer cannot make progress without swap and the kernel
96
+ # stalls with no console output. Create a 2G swapfile once; it persists across
97
+ # reboots via /etc/fstab, and a re-run of this script (every boot) is a no-op.
98
+ if [ ! -f /swapfile ]; then
99
+ echo "Creating 2G swapfile..."
100
+ sudo fallocate -l 2G /swapfile 2>/dev/null \
101
+ || sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 2>/dev/null \
102
+ || true
103
+ sudo chmod 600 /swapfile
104
+ sudo mkswap /swapfile > /dev/null 2>&1 || true
105
+ sudo swapon /swapfile > /dev/null 2>&1 || true
106
+ grep -q '^/swapfile' /etc/fstab 2>/dev/null \
107
+ || echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab > /dev/null
108
+ fi
109
+ # Idempotent: if the file pre-existed but swap is currently off, turn it on.
110
+ grep -q '^/swapfile' /proc/swaps 2>/dev/null || sudo swapon /swapfile > /dev/null 2>&1 || true
111
+ grep -q '^/swapfile' /proc/swaps 2>/dev/null && echo "Swap enabled: $(grep '^/swapfile' /proc/swaps)"
112
+
113
+ # Upgrade git to >= 2.32 from the git-core PPA. The default Ubuntu 20.04/22.04
114
+ # repos ship git <= 2.30, which lacks `git add --sparse` — the opencode/kimaki
115
+ # agent snapshot flow fails every session with exit 129: "unknown option 'sparse'".
116
+ # Hardened keyring + sources.list.d pattern, same as the GitHub CLI install below.
117
+ # If the PPA fetch fails, everything is `|| true` and the default-repo git stays.
118
+ sudo mkdir -p /usr/share/keyrings
119
+ curl -fsSL "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xE1DD270288B4E6030699E45FA1715D88E1DF1F24" | sudo gpg --dearmor -o /usr/share/keyrings/git-core-ppa.gpg > /dev/null 2>&1 || true
120
+ UBUNTU_CODENAME=$(. /etc/os-release && echo "${VERSION_CODENAME:-focal}")
121
+ echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/git-core-ppa.gpg] https://ppa.launchpadcontent.net/git-core/ppa/ubuntu ${UBUNTU_CODENAME} main" | sudo tee /etc/apt/sources.list.d/git-core-ppa.list > /dev/null 2>&1 || true
122
+ sudo apt-get update -y > /dev/null 2>&1 || true
123
+ # Re-install so apt picks the higher PPA version (upgrades the git from above).
124
+ sudo apt-get install -y git > /dev/null 2>&1 || true
125
+
69
126
  # Fetch secrets from Secret Manager via the metadata-server identity (map #36).
70
127
  # No secret values ride in VM metadata; the VM's attached service account holds
71
128
  # per-secret roles/secretmanager.secretAccessor. IAM grants are eventually
@@ -145,16 +202,23 @@ if [ -d "$REPO_NAME/.git" ]; then
145
202
  REPO_CLONED=true
146
203
  else
147
204
  REPO_CLONED=false
205
+ # Clone the SecureAgentBase TEMPLATE repo (the app skeleton), NOT the
206
+ # destination repo. A fresh app's destination usually does not exist yet —
207
+ # the VM creates it below via the GitHub API, gh-independent. Cloning the
208
+ # destination used to 404, silently fall back to a 3-file placeholder repo,
209
+ # and then fail to push (no repo, no gh) on EVERY fresh VM.
148
210
  for i in 1 2 3; do
149
- if git clone --depth 1 "https://github.com/$REPO_OWNER/$REPO_NAME.git" "$REPO_NAME" > /dev/null 2>&1; then
211
+ if git clone --depth 1 "https://github.com/${TEMPLATE_OWNER}/${TEMPLATE_NAME}.git" "$REPO_NAME" > /dev/null 2>&1; then
150
212
  REPO_CLONED=true
151
213
  break
152
214
  fi
153
215
  sleep 5
154
216
  done
155
217
 
156
- # If clone failed, fall back to creating directory manually
218
+ # If the template clone failed (e.g. GitHub unreachable), fall back to an
219
+ # empty placeolder repo so provisioning still completes.
157
220
  if [ "$REPO_CLONED" != "true" ]; then
221
+ echo "TEMPLATE_CLONE=FALLBACK" > /dev/ttyS0 2>/dev/null || true
158
222
  mkdir -p "$REPO_NAME"
159
223
  cd "$REPO_NAME"
160
224
  git init
@@ -167,6 +231,7 @@ build/
167
231
  *.log
168
232
  GITEOF
169
233
  else
234
+ echo "TEMPLATE_CLONE=OK" > /dev/ttyS0 2>/dev/null || true
170
235
  cd "$REPO_NAME"
171
236
  rm -rf .git
172
237
  git init
@@ -175,38 +240,15 @@ fi
175
240
 
176
241
  git checkout -b main
177
242
 
178
- # Clean up wizard-specific files — users don't need the infra setup wizard
179
- rm -rf src/infra-setup.tsx src/create-app.tsx
180
- rm -rf src/framework/infra-setup/
181
- rm -rf src/admin/
182
- rm -rf cli/
183
- rm -rf tests/e2e/wizard.spec.js
184
- rm -rf src/_tests_/WizardSteps.test.jsx src/_tests_/create-app.test.tsx src/_tests_/StepHeader.test.jsx src/_tests_/api.test.ts src/_tests_/crypto.test.ts src/_tests_/scripts.test.ts
185
- rm -f WIZARD_DEV_NOTES.md
186
-
187
- # Fix App.tsx: remove wizard/admin imports and routes
188
- if [ -f src/App.tsx ]; then
189
- # Remove import lines for InfraSetup, CreateApp, AdminPanel
190
- sed -i "/import InfraSetup from '.\\/infra-setup';/d" src/App.tsx
191
- sed -i "/import CreateApp from '.\\/create-app';/d" src/App.tsx
192
- sed -i "/import AdminPanel from '.\\/admin\\/AdminPanel';/d" src/App.tsx
193
- # Remove Route elements for /infra-setup, /create-app, /admin/*
194
- sed -i '/<Route path="\\/infra-setup".*\\/>/d' src/App.tsx
195
- sed -i '/<Route path="\\/create-app".*\\/>/d' src/App.tsx
196
- sed -i '/<Route path="\\/admin/d' src/App.tsx
197
- # Clean up orphaned {isAppMode && ()} blocks left behind after Route deletion
198
- perl -i -0pe 's/\\{isAppMode && \\(\\s*\\n\\s*\\)\\}//gs' src/App.tsx
199
- echo "App.tsx cleaned of wizard/admin references"
200
- fi
201
-
202
- # Fix navigation-bar.tsx: remove admin link and useIsAdmin import
203
- if [ -f src/navigation-bar.tsx ]; then
204
- sed -i "/import { useIsAdmin } from '.\\/admin\\/useIsAdmin';/d" src/navigation-bar.tsx
205
- sed -i "/const { isAdmin } = useIsAdmin(db);/d" src/navigation-bar.tsx
206
- # Delete from {isAdmin && to the next closing )} on its own line
207
- sed -i '/{isAdmin &&/,/^[[:space:]]*)}/d' src/navigation-bar.tsx
208
- echo "navigation-bar.tsx cleaned of admin references"
209
- fi
243
+ # NOTE: We deliberately do NOT strip wizard/admin/cli files from the
244
+ # destination repo. The template's own CI workflows (ci.yml, security-scan.yml,
245
+ # firebase-deploy-staging.yml) build the cli/ and run the full test suite, and
246
+ # src/App.tsx imports the wizard/admin modules. Stripping produced a repo whose
247
+ # every workflow run failed: `cd cli && npm ci` had no cli/, and line-based sed
248
+ # cleanup of App.tsx left half-deleted multiline JSX (ReferenceError:
249
+ # InfraSetup/CreateApp is not defined). A byte-identical copy of the template
250
+ # is CI-green by construction — main is gated by the exact same CI — and the
251
+ # wizard/admin routes are inert in template mode (VITE_APP_MODE unset).
210
252
 
211
253
  # Write a CONTEXT.md scaffold for the domain-modeling/setup-project skills
212
254
  if [ ! -f CONTEXT.md ]; then
@@ -231,53 +273,106 @@ git commit -m "Initial commit of SecureAgentBase template"
231
273
  check_disk
232
274
  PUSH_RESULT="NOT_ATTEMPTED"
233
275
  if [ -n "$GITHUB_PAT" ]; then
234
- # Clear stale gh credentials first — a revoked PAT or old token causes 401s that
235
- # persist across boots because gh caches the failed login state.
236
- gh auth logout --hostname github.com 2>/dev/null || true
237
- echo "$GITHUB_PAT" | gh auth login --with-token 2>/dev/null
238
- gh auth setup-git 2>/dev/null || true
239
-
240
- # Create new repo or force-push if it already exists
241
- if gh repo view "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null; then
242
- git remote remove origin 2>/dev/null || true
243
- git remote add origin "https://github.com/${REPO_OWNER}/${REPO_NAME}.git" || true
244
- if git push -u origin main --force 2>&1; then
245
- PUSH_RESULT="PUSH_OK"
246
- else
247
- PUSH_RESULT="PUSH_FAILED"
248
- fi
249
- else
250
- if gh repo create "${REPO_OWNER}/${REPO_NAME}" --public --source=. --push 2>&1; then
251
- PUSH_RESULT="CREATE_OK"
252
- else
253
- # Fallback: try force-push (repo may exist but PAT can't view it)
254
- git remote remove origin 2>/dev/null || true
255
- git remote add origin "https://github.com/${REPO_OWNER}/${REPO_NAME}.git" || true
256
- if git push -u origin main --force 2>&1; then
257
- PUSH_RESULT="FALLBACK_PUSH_OK"
258
- else
259
- PUSH_RESULT="ALL_PUSH_FAILED"
260
- fi
261
- fi
262
- fi
263
-
264
- # Write push result marker to serial port (compact, survives buffer overflow)
265
- echo "PUSH_RESULT=$PUSH_RESULT" > /dev/ttyS0 2>/dev/null || true
276
+ # GH_TOKEN bypasses `gh auth login` entirely: gh's login flow VALIDATES the
277
+ # token against a user-scoped endpoint and rejects fine-grained PATs that
278
+ # carry no user permissions (exit 1, "error validating token"), leaving gh
279
+ # unauthenticated while the PAT itself is perfectly valid. All gh commands
280
+ # below read GH_TOKEN directly, with no login-time validation.
281
+ export GH_TOKEN="$GITHUB_PAT"
282
+
283
+ # Git-native credentials for the push itself. gh's git credential helper
284
+ # only works after a successful gh auth login, so the push previously
285
+ # inherited gh's login failure. git's own credential store authenticates
286
+ # the push with the PAT directly, independent of gh.
287
+ git config --global credential.helper store
288
+ printf 'https://x-access-token:%s@github.com\n' "$GITHUB_PAT" > /root/.git-credentials
289
+ chmod 600 /root/.git-credentials
290
+
291
+ # Probe PAT + transport health — verbose diagnostics to serial (no secrets).
292
+ # curl tests the raw PAT value against the repo API (gh-independent); the
293
+ # gh probe is diagnostic only (gh is not required anymore — repo creation
294
+ # and variable setting run through curl below).
295
+ # NOTE: no PAT type/token metadata is written to /dev/ttyS0 (serial console
296
+ # must never carry secrets or metadata about credentials).
297
+ # curl prints the HTTP status code, or 000 when the request itself fails
298
+ # (DNS/network/timeout) — no fallback echo needed.
299
+ CURL_CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 \
300
+ -H "Authorization: Bearer $GITHUB_PAT" \
301
+ "https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}" 2>/dev/null)
302
+ if gh api "repos/${REPO_OWNER}/${REPO_NAME}" >/dev/null 2>&1; then
303
+ GH_STATE="ok"
304
+ else
305
+ GH_STATE="FAIL"
306
+ GH_PROBE_ERR=$(gh api "repos/${REPO_OWNER}/${REPO_NAME}" 2>&1 | head -c 200 | tr '\n' ' ')
307
+ echo "GH_PROBE_ERR: ${GH_PROBE_ERR:-no output}" > /dev/ttyS0 2>/dev/null || true
308
+ fi
309
+ echo "GH_PROBE: curl=$CURL_CODE gh=$GH_STATE" > /dev/ttyS0 2>/dev/null || true
310
+
311
+ # Create the destination repo if it does not exist. The wizard does NOT
312
+ # create it browser-side — without this the push fails every time and the
313
+ # VM lands in ALL_PUSH_FAILED. No gh dependency (gh is not installed on the
314
+ # VM): repo creation needs only the PAT against the GitHub REST API.
315
+ REPO_CREATE="NOT_CHECKED"
316
+ if [ "$CURL_CODE" = "404" ]; then
317
+ code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 -X POST \
318
+ "https://api.github.com/user/repos" \
319
+ -H "Authorization: Bearer $GITHUB_PAT" -H "Accept: application/vnd.github+json" \
320
+ -d "$(jq -n --arg n "$REPO_NAME" '{name:$n, private:false}' 2>/dev/null)")
321
+ if [ "$code" = "201" ] || [ "$code" = "200" ]; then
322
+ REPO_CREATE="CREATED"
323
+ else
324
+ REPO_CREATE="FAIL"
325
+ fi
326
+ elif [ "$CURL_CODE" = "200" ]; then
327
+ REPO_CREATE="EXISTS"
328
+ fi
329
+ echo "REPO_CREATE=$REPO_CREATE" > /dev/ttyS0 2>/dev/null || true
266
330
 
267
- # Set GitHub variables
268
- gh auth status 2>/dev/null || true
331
+ # Push the template-derived repo to the destination.
332
+ git remote remove origin 2>/dev/null || true
333
+ git remote add origin "https://github.com/${REPO_OWNER}/${REPO_NAME}.git" || true
334
+ if git push -u origin main --force 2>&1; then
335
+ PUSH_RESULT="PUSH_OK"
336
+ else
337
+ PUSH_RESULT="ALL_PUSH_FAILED"
338
+ fi
339
+ echo "PUSH_RESULT=$PUSH_RESULT" > /dev/ttyS0 2>/dev/null || true
340
+
341
+ # gh-independent Actions variable setter (create-or-update via the GitHub
342
+ # REST API). Values are JSON-escaped with jq; empty names/values are skipped.
343
+ set_gh_variable() {
344
+ local name="$1" value="$2" code payload url
345
+ if [ -z "$name" ] || [ -z "$value" ]; then
346
+ return 0
347
+ fi
348
+ url="https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/actions/variables/$name"
349
+ code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 \
350
+ -H "Authorization: Bearer $GITHUB_PAT" "$url" 2>/dev/null)
351
+ if [ "$code" = "200" ]; then
352
+ payload=$(jq -n --arg v "$value" '{value:$v}' 2>/dev/null)
353
+ curl -s -o /dev/null --max-time 20 -X PATCH "$url" \
354
+ -H "Authorization: Bearer $GITHUB_PAT" -H "Accept: application/vnd.github+json" \
355
+ -d "$payload" 2>/dev/null || return 1
356
+ else
357
+ payload=$(jq -n --arg n "$name" --arg v "$value" '{name:$n,value:$v}' 2>/dev/null)
358
+ curl -s -o /dev/null --max-time 20 -X POST \
359
+ "https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/actions/variables" \
360
+ -H "Authorization: Bearer $GITHUB_PAT" -H "Accept: application/vnd.github+json" \
361
+ -d "$payload" 2>/dev/null || return 1
362
+ fi
363
+ }
269
364
 
270
365
  # Set Firebase project IDs as VARIABLES (workflow reads vars.FIREBASE_PROJECT_ID_STAGING)
271
- gh variable set FIREBASE_PROJECT_ID_STAGING --body "$FIREBASE_STAGING" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || echo "WARN: Failed to set FIREBASE_PROJECT_ID_STAGING"
272
- gh variable set FIREBASE_PROJECT_ID_PRODUCTION --body "$FIREBASE_PRODUCTION" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || echo "WARN: Failed to set FIREBASE_PROJECT_ID_PRODUCTION"
366
+ set_gh_variable FIREBASE_PROJECT_ID_STAGING "$FIREBASE_STAGING" || echo "WARN: Failed to set FIREBASE_PROJECT_ID_STAGING"
367
+ set_gh_variable FIREBASE_PROJECT_ID_PRODUCTION "$FIREBASE_PRODUCTION" || echo "WARN: Failed to set FIREBASE_PROJECT_ID_PRODUCTION"
273
368
 
274
369
  # Set OIDC variables (required by google-github-actions/auth)
275
- [ -n "$GCP_WIF_PROVIDER" ] && gh variable set GCP_WIF_PROVIDER --body "$GCP_WIF_PROVIDER" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
276
- [ -n "$GCP_SA_STAGING" ] && gh variable set GCP_SA_STAGING --body "$GCP_SA_STAGING" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
277
- [ -n "$GCP_SA_PRODUCTION" ] && gh variable set GCP_SA_PRODUCTION --body "$GCP_SA_PRODUCTION" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
370
+ [ -n "$GCP_WIF_PROVIDER" ] && set_gh_variable GCP_WIF_PROVIDER "$GCP_WIF_PROVIDER" || true
371
+ [ -n "$GCP_SA_STAGING" ] && set_gh_variable GCP_SA_STAGING "$GCP_SA_STAGING" || true
372
+ [ -n "$GCP_SA_PRODUCTION" ] && set_gh_variable GCP_SA_PRODUCTION "$GCP_SA_PRODUCTION" || true
278
373
 
279
374
  # Set VITE app variables
280
- [ -n "$VITE_APP_NAME" ] && gh variable set VITE_APP_NAME --body "$VITE_APP_NAME" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
375
+ [ -n "$VITE_APP_NAME" ] && set_gh_variable VITE_APP_NAME "$VITE_APP_NAME" || true
281
376
 
282
377
  # Set Firebase config variables from JSON configs (parse with jq)
283
378
  # Convert camelCase field names to SCREAMING_SNAKE_CASE for GitHub variable names
@@ -286,7 +381,7 @@ if [ -n "$GITHUB_PAT" ]; then
286
381
  val=$(echo "$FIREBASE_STAGING_CONFIG" | jq -r ".${field} // empty" 2>/dev/null)
287
382
  if [ -n "$val" ]; then
288
383
  upper_field=$(echo "${field}" | sed 's/\([a-z]\)\([A-Z]\)/\1_\2/g' | tr '[:lower:]' '[:upper:]')
289
- gh variable set "FIREBASE_${upper_field}_STAGING" --body "$val" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
384
+ set_gh_variable "FIREBASE_${upper_field}_STAGING" "$val" || true
290
385
  fi
291
386
  done
292
387
  fi
@@ -296,13 +391,19 @@ if [ -n "$GITHUB_PAT" ]; then
296
391
  val=$(echo "$FIREBASE_PRODUCTION_CONFIG" | jq -r ".${field} // empty" 2>/dev/null)
297
392
  if [ -n "$val" ]; then
298
393
  upper_field=$(echo "${field}" | sed 's/\([a-z]\)\([A-Z]\)/\1_\2/g' | tr '[:lower:]' '[:upper:]')
299
- gh variable set "FIREBASE_${upper_field}_PRODUCTION" --body "$val" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
394
+ set_gh_variable "FIREBASE_${upper_field}_PRODUCTION" "$val" || true
300
395
  fi
301
396
  done
302
397
  fi
303
398
 
304
399
  echo "VAR_RESULT=DONE" > /dev/ttyS0 2>/dev/null || true
305
400
  echo "GitHub variables set successfully" > /dev/null 2>&1
401
+
402
+ # Scrub the plaintext git credential — the push is done, and later reboots
403
+ # skip this entire block (.provisioned guard). GH_TOKEN stays scoped to
404
+ # this script run only (exported, not persisted).
405
+ rm -f /root/.git-credentials
406
+ unset GH_TOKEN
306
407
  fi
307
408
 
308
409
  # Install Kimaki globally and create its configuration
@@ -315,11 +416,13 @@ openai_api_key: ""
315
416
  github_token: ""
316
417
  KIMAKICONF
317
418
 
318
- # Write opencode.json with provider timeout settings (chatty upstream models)
419
+ # Write opencode.json with provider timeout settings (chatty upstream models).
420
+ # The quoted heredoc keeps the JSON literal exactly as written; the model
421
+ # placeholder is swapped below via sed (OPENCODE_MODEL was charset-validated).
319
422
  cat > "/root/.kimaki/projects/$REPO_NAME/opencode.json" << 'OPENCODEEOF'
320
423
  {
321
424
  "$schema": "https://opencode.ai/config.json",
322
- "model": "opencode-go/kimi-k2.6",
425
+ "model": "__OPENCODE_MODEL__",
323
426
  "provider": {
324
427
  "opencode-go": {
325
428
  "options": {
@@ -331,6 +434,20 @@ cat > "/root/.kimaki/projects/$REPO_NAME/opencode.json" << 'OPENCODEEOF'
331
434
  }
332
435
  }
333
436
  OPENCODEEOF
437
+ sed -i "s|__OPENCODE_MODEL__|$OPENCODE_MODEL|" "/root/.kimaki/projects/$REPO_NAME/opencode.json"
438
+
439
+ # Optional opencode provider credentials (free gateway tokens) passed as
440
+ # validated JSON via opencode_auth_json metadata. never written to the serial
441
+ # console — only a SET/UNSET marker. If absent, the operator provides them on
442
+ # the VM (SSH `opencode auth login`, or copy auth.json from another machine).
443
+ if [ -n "$OPENCODE_AUTH_JSON" ] && printf '%s' "$OPENCODE_AUTH_JSON" | jq -e . >/dev/null 2>&1; then
444
+ mkdir -p /root/.local/share/opencode
445
+ printf '%s' "$OPENCODE_AUTH_JSON" > /root/.local/share/opencode/auth.json
446
+ chmod 600 /root/.local/share/opencode/auth.json
447
+ echo "OPENCODE_AUTH=SET" > /dev/ttyS0 2>/dev/null || true
448
+ else
449
+ echo "OPENCODE_AUTH=UNSET" > /dev/ttyS0 2>/dev/null || true
450
+ fi
334
451
 
335
452
  # Install agent skills globally — opencode and Claude Code auto-discover these dirs.
336
453
  SKILLS_DIR=/root/.config/opencode/skills
@@ -362,12 +479,6 @@ NODE_ENV=production
362
479
  ENVEOF
363
480
  chmod 600 /root/.kimaki/env
364
481
 
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
482
  # Create systemd service for Kimaki (no-clobber — never overwrite a running unit)
372
483
  KIMAKI_PATH=$(command -v kimaki || true)
373
484
  # Resolve node explicitly: the pinned tarball installs to /usr/local/bin while
@@ -494,7 +605,8 @@ systemctl enable kimaki-register.service
494
605
  touch /root/.kimaki/.provisioned
495
606
 
496
607
  # Final compact marker — this is the LAST output before kimaki-register starts
497
- # Non-sensitive status only — no secrets or project identifiers leaked
498
- echo "SCRIPT_COMPLETE" > /dev/ttyS0 2>/dev/null || true
608
+ # Non-sensitive status only — push result is kept (survives buffer overflow)
609
+ # but no repo/owner/project identifiers are written to the serial console.
610
+ echo "SCRIPT_COMPLETE|PUSH=${PUSH_RESULT:-UNKNOWN}" > /dev/ttyS0 2>/dev/null || true
499
611
 
500
612
  systemctl start kimaki-register.service &
@@ -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.7",
4
4
  "description": "CLI tool to deploy and manage SecureAgentBase on GCP",
5
5
  "type": "module",
6
6
  "bin": {