secureagentbase 1.4.6 → 1.4.8

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,4 +1,4 @@
1
- import { createAuth } from '../lib/auth.js';
1
+ import { createAuth, ensureAdc } from '../lib/auth.js';
2
2
  import { deleteVm } from '../lib/gcp.js';
3
3
  import { loadConfig, clearConfig } from '../utils/config.js';
4
4
  import { heading, info, success, warn } from '../utils/output.js';
@@ -9,6 +9,9 @@ export async function runDestroy(args) {
9
9
  warn('No deployment found.');
10
10
  return;
11
11
  }
12
+ // Deleting the VM needs Google credentials just like init did; guide the user
13
+ // through the same ADC login instead of failing on a raw ADC error.
14
+ await ensureAdc({ auto: args.yes });
12
15
  if (!args.yes) {
13
16
  const { confirm } = await (await import('inquirer')).default.prompt([
14
17
  {
@@ -1,6 +1,6 @@
1
1
  import * as crypto from 'node:crypto';
2
2
  import inquirer from 'inquirer';
3
- import { createAuth } from '../lib/auth.js';
3
+ import { createAuth, ensureAdc } from '../lib/auth.js';
4
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';
@@ -11,9 +11,12 @@ import { CLIError } from '../utils/errors.js';
11
11
  import { getStartupScript } from '../lib/startup-script.js';
12
12
  export async function runInit(args) {
13
13
  heading('SecureAgentBase Init');
14
- // Auth (ADC-only — map #36 decision #6: no service account key support)
14
+ // Auth (ADC-only — map #36 decision #6: no service account key support).
15
+ // Ensure ADC up front and guide the user through `gcloud auth
16
+ // application-default login` when it is missing, so no later step ever dies
17
+ // on the bare google-auth-library "Could not load the default credentials".
18
+ const saEmail = await ensureAdc({ auto: args.yes });
15
19
  const auth = createAuth();
16
- const saEmail = await auth.getClientEmail();
17
20
  info(`Authenticated as ${saEmail || 'unknown (ADC)'}`);
18
21
  const config = loadConfig();
19
22
  // Step 1: Select or create GCP project
@@ -184,6 +187,14 @@ async function stepBilling(auth, config, args) {
184
187
  }
185
188
  const accounts = await fetchBillingAccounts(auth, projectId);
186
189
  if (accounts.length === 0) {
190
+ // -y means "skip all prompts (non-interactive mode)". Without this the
191
+ // inquirer prompt blocks forever in CI (no TTY to answer it), which
192
+ // deadlocks `init` until the caller's timeout kills it.
193
+ if (args.yes) {
194
+ warn('No billing accounts found — skipping billing link (-y mode).');
195
+ warn('Pass --billing-account <id> to link one, or grant the caller roles/billing.user on the billing account.');
196
+ return;
197
+ }
187
198
  warn('No billing accounts found');
188
199
  const { billingAccountId } = await inquirer.prompt([
189
200
  {
@@ -196,6 +207,15 @@ async function stepBilling(auth, config, args) {
196
207
  success(`Linked billing account: ${billingAccountId}`);
197
208
  }
198
209
  else {
210
+ if (args.yes) {
211
+ // Deterministic in -y mode: take the first account rather than
212
+ // prompting (prompts are what break non-interactive runs).
213
+ const accountId = accounts[0].name?.replace('billingAccounts/', '');
214
+ info(`Linking billing account: ${accountId} (-y mode)`);
215
+ await linkBillingAccount(auth, projectId, accountId);
216
+ success(`Linked billing account: ${accountId}`);
217
+ return;
218
+ }
199
219
  const { selectedAccount } = await inquirer.prompt([
200
220
  {
201
221
  type: 'list',
@@ -261,14 +281,17 @@ async function stepGitHub(auth, config, args) {
261
281
  const oidcData = await setupOidc(auth, config.gcpProjectId, repoFull);
262
282
  config.oidc = oidcData;
263
283
  // Upload GitHub variables (best-effort — variables may already be set from prior run)
284
+ // NOTE: VITE_APP_MODE and VITE_APP_NAME are intentionally NOT set here.
285
+ // Copied apps run in template mode (the default) — which is where the posts
286
+ // feature lives — and display "Your App" until the user brands it (or sets
287
+ // the name via the VM's `vite_app_name` metadata). The SecureAgentBase
288
+ // product/template repo itself (app mode) blocks posts.
264
289
  const varConfigs = [
265
- ['VITE_APP_NAME', 'SecureAgentBase'],
266
290
  ['GCP_WIF_PROVIDER', oidcData.wifPoolName],
267
291
  ['GCP_SA_STAGING', oidcData.saStagingEmail],
268
292
  ['GCP_SA_PRODUCTION', oidcData.saProductionEmail],
269
293
  ['GCP_CLIENT_ID_STAGING', ''],
270
294
  ['GCP_CLIENT_ID_PRODUCTION', ''],
271
- ['VITE_APP_MODE', 'true'],
272
295
  ];
273
296
  for (const [name, value] of varConfigs) {
274
297
  if (value) {
package/dist/index.js CHANGED
@@ -4,12 +4,18 @@ import { runInit } from './commands/init.js';
4
4
  import { runStatus } from './commands/status.js';
5
5
  import { runDestroy } from './commands/destroy.js';
6
6
  import { handleError } from './utils/errors.js';
7
- const pkg = { version: '0.1.0', name: 'secureagentbase' };
7
+ import { createRequire } from 'node:module';
8
+ // Read the real version from package.json so `--version` can never drift from
9
+ // the published artifact. Works from src/ (tsx dev) and dist/ (published) since
10
+ // both sit one level below the package root.
11
+ const require = createRequire(import.meta.url);
12
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
13
+ const pkgJson = require('../package.json');
8
14
  const program = new Command();
9
15
  program
10
16
  .name('secureagentbase')
11
- .description('CLI to deploy and manage SecureAgentBase on GCP')
12
- .version(pkg.version);
17
+ .description('SecureAgentBase CLI')
18
+ .version(pkgJson.version);
13
19
  program
14
20
  .command('init')
15
21
  .description('Run the setup wizard')
@@ -4,3 +4,32 @@ export interface AuthClient {
4
4
  getClientEmail(): Promise<string | null>;
5
5
  }
6
6
  export declare function createAuth(): AuthClient;
7
+ /**
8
+ * Raised when Google ADC is missing or unusable. Carries actionable remediation
9
+ * so callers guide the user through login instead of surfacing the bare
10
+ * google-auth-library "Could not load the default credentials" string.
11
+ */
12
+ export declare class MissingAdcError extends Error {
13
+ readonly detail: string;
14
+ readonly isMissingAdc = true;
15
+ constructor(detail: string, fix?: string, options?: {
16
+ cause?: unknown;
17
+ });
18
+ }
19
+ export interface AdcOptions {
20
+ /** Run the login without asking (used by `--yes` and non-TTY shells). */
21
+ auto?: boolean;
22
+ }
23
+ /**
24
+ * Ensures usable Google ADC exists, guiding the user through login when it does
25
+ * not — the CLI equivalent of the wizard's "Connect Google Cloud Account" button.
26
+ *
27
+ * Remediation order:
28
+ * 1. ADC works -> return the identity email (never prompt needlessly).
29
+ * 2. `gcloud` installed -> run `gcloud auth application-default login`.
30
+ * 3. `gcloud` missing -> print install instructions and stop.
31
+ *
32
+ * Returns the authenticated identity email when ADC exposes one (null for
33
+ * identity-less ADC, e.g. a bare metadata server or authorized-user file).
34
+ */
35
+ export declare function ensureAdc(options?: AdcOptions): Promise<string | null>;
package/dist/lib/auth.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import * as readline from 'node:readline';
1
3
  import { GoogleAuth } from 'google-auth-library';
2
4
  // Least-privilege scope policy — must stay in sync with the web wizard's SA
3
5
  // impersonation scopes (src/infra-setup.tsx, src/framework/infra-setup/api.ts).
@@ -7,6 +9,7 @@ const SCOPES = [
7
9
  'https://www.googleapis.com/auth/devstorage.read_write',
8
10
  'https://www.googleapis.com/auth/cloud-billing.readonly',
9
11
  ];
12
+ const LOGIN_DOCS = 'https://cloud.google.com/docs/authentication/getting-started';
10
13
  class ADCAuthClient {
11
14
  auth;
12
15
  projectId = null;
@@ -15,8 +18,28 @@ class ADCAuthClient {
15
18
  this.auth = new GoogleAuth({ scopes: SCOPES });
16
19
  }
17
20
  async getToken() {
18
- const client = await this.auth.getClient();
19
- const tokenResponse = await client.getAccessToken();
21
+ let client;
22
+ try {
23
+ client = await this.auth.getClient();
24
+ }
25
+ catch (error) {
26
+ if (isMissingAdc(error)) {
27
+ throw new MissingAdcError('No credential source is available.', undefined, { cause: error });
28
+ }
29
+ throw error;
30
+ }
31
+ let tokenResponse;
32
+ try {
33
+ tokenResponse = await client.getAccessToken();
34
+ }
35
+ catch (error) {
36
+ if (isUnusableAdc(error) || isMissingScopes(error)) {
37
+ throw new MissingAdcError('Stored credentials are expired or were revoked.', undefined, {
38
+ cause: error,
39
+ });
40
+ }
41
+ throw error;
42
+ }
20
43
  if (!tokenResponse.token)
21
44
  throw new Error('Failed to get access token from ADC');
22
45
  return tokenResponse.token;
@@ -25,7 +48,7 @@ class ADCAuthClient {
25
48
  if (this.projectId)
26
49
  return this.projectId;
27
50
  try {
28
- this.projectId = await this.auth.getProjectId() || null;
51
+ this.projectId = (await this.auth.getProjectId()) || null;
29
52
  }
30
53
  catch {
31
54
  this.projectId = null;
@@ -54,3 +77,196 @@ class ADCAuthClient {
54
77
  export function createAuth() {
55
78
  return new ADCAuthClient();
56
79
  }
80
+ /**
81
+ * Raised when Google ADC is missing or unusable. Carries actionable remediation
82
+ * so callers guide the user through login instead of surfacing the bare
83
+ * google-auth-library "Could not load the default credentials" string.
84
+ */
85
+ export class MissingAdcError extends Error {
86
+ detail;
87
+ isMissingAdc = true;
88
+ constructor(detail, fix, options) {
89
+ super(notLoggedIn(detail, fix), options);
90
+ this.detail = detail;
91
+ this.name = 'MissingAdcError';
92
+ }
93
+ }
94
+ function messageOf(error) {
95
+ return error instanceof Error ? error.message : String(error ?? '');
96
+ }
97
+ /** The deepest underlying error message, so classification survives wrapping. */
98
+ function rootMessage(error) {
99
+ if (error instanceof MissingAdcError && error.cause)
100
+ return rootMessage(error.cause);
101
+ return messageOf(error);
102
+ }
103
+ /** No credential source at all (no ADC file, no GCE metadata, no env var). */
104
+ function isMissingAdc(error) {
105
+ const message = rootMessage(error);
106
+ return (message.includes('Could not load the default credentials') ||
107
+ message.includes('NO_ADC_FOUND') ||
108
+ message.includes('Your default credentials were not found') ||
109
+ message.includes('Could not automatically determine credentials'));
110
+ }
111
+ /** The VM is up but its metadata identity has no OAuth scopes attached. */
112
+ function isMissingScopes(error) {
113
+ const message = rootMessage(error);
114
+ return (message.includes('does not have any permission scopes') ||
115
+ (message.includes('Compute Engine built-in service account') &&
116
+ message.includes('Could not refresh access token')));
117
+ }
118
+ /** A credential source exists but cannot mint a token (revoked/expired). */
119
+ function isUnusableAdc(error) {
120
+ const message = rootMessage(error);
121
+ return (message.includes('invalid_grant') ||
122
+ message.includes('invalid_rapt') ||
123
+ message.includes('Could not refresh access token') ||
124
+ message.includes('Reauthentication is needed') ||
125
+ message.includes('invalid authentication credentials'));
126
+ }
127
+ /**
128
+ * Multi-line, copy-pasteable "you are not signed in" guidance. The fix lines are
129
+ * overridable because some cases (running on a VM) must not tell the user to
130
+ * run the interactive login command.
131
+ */
132
+ function notLoggedIn(detail, fix) {
133
+ const lines = ['Not signed in to Google Cloud.', '', ` ${detail}`, ''];
134
+ if (fix) {
135
+ lines.push(` ${fix}`);
136
+ }
137
+ else {
138
+ lines.push(' Fix: gcloud auth application-default login');
139
+ lines.push(' Then: re-run this command');
140
+ }
141
+ lines.push(` Docs: ${LOGIN_DOCS}`);
142
+ return lines.join('\n');
143
+ }
144
+ /**
145
+ * Validates ADC by actually minting a token — not merely by finding a
146
+ * credential source, so stale or revoked credentials are caught up front.
147
+ */
148
+ async function probeAdc() {
149
+ const auth = new ADCAuthClient();
150
+ try {
151
+ await auth.getToken();
152
+ return { ok: true, email: await auth.getClientEmail() };
153
+ }
154
+ catch (error) {
155
+ const message = rootMessage(error);
156
+ if (isMissingAdc(error) || message.includes('NO_ADC_FOUND')) {
157
+ return { ok: false, detail: 'No credential source is available.' };
158
+ }
159
+ if (isMissingScopes(error)) {
160
+ return {
161
+ ok: false,
162
+ detail: 'The VM is running but its service account has no OAuth scopes, so Google will not issue a token.',
163
+ fix: 'Fix: give the VM a service account with cloud-platform scope, or set GOOGLE_APPLICATION_CREDENTIALS',
164
+ };
165
+ }
166
+ if (isUnusableAdc(error)) {
167
+ return { ok: false, detail: 'Stored credentials are expired or were revoked.' };
168
+ }
169
+ return { ok: false, detail: message };
170
+ }
171
+ }
172
+ /**
173
+ * Ensures usable Google ADC exists, guiding the user through login when it does
174
+ * not — the CLI equivalent of the wizard's "Connect Google Cloud Account" button.
175
+ *
176
+ * Remediation order:
177
+ * 1. ADC works -> return the identity email (never prompt needlessly).
178
+ * 2. `gcloud` installed -> run `gcloud auth application-default login`.
179
+ * 3. `gcloud` missing -> print install instructions and stop.
180
+ *
181
+ * Returns the authenticated identity email when ADC exposes one (null for
182
+ * identity-less ADC, e.g. a bare metadata server or authorized-user file).
183
+ */
184
+ export async function ensureAdc(options = {}) {
185
+ const before = await probeAdc();
186
+ if (before.ok)
187
+ return before.email;
188
+ // On a GCE VM, credentials come from the metadata server. Running
189
+ // `gcloud auth application-default login` there is harmful (it would
190
+ // overwrite the VM's ADC file and can expose a personal account to anyone
191
+ // with VM access), so never spawn it — explain the real fix instead.
192
+ if (before.fix) {
193
+ // Probe already identified the precise problem (e.g. a scope-less VM).
194
+ throw new MissingAdcError(before.detail, before.fix);
195
+ }
196
+ if (await isRunningOnGce()) {
197
+ throw new MissingAdcError('This looks like a Google Cloud VM, where credentials come from the metadata server. ' +
198
+ 'Check that the VM still has a service account attached and that the metadata server is reachable.', 'Fix: attach a service account to the VM (or set GOOGLE_APPLICATION_CREDENTIALS)');
199
+ }
200
+ const gcloud = findGcloud();
201
+ if (!gcloud) {
202
+ throw new MissingAdcError('The gcloud CLI was not found on PATH. Install the Google Cloud SDK first (https://cloud.google.com/sdk/docs/install).');
203
+ }
204
+ if (!options.auto && !(await runLoginPrompt(before.detail))) {
205
+ throw new MissingAdcError(`${before.detail} Login was skipped.`);
206
+ }
207
+ // `gcloud auth application-default login` is interactive (browser flow), so
208
+ // hand it the real stdio and let the user complete it.
209
+ const result = spawnSync(gcloud, ['auth', 'application-default', 'login'], { stdio: 'inherit' });
210
+ if (result.error) {
211
+ throw new MissingAdcError(`Could not run gcloud: ${messageOf(result.error)}`);
212
+ }
213
+ if (result.status !== 0) {
214
+ throw new MissingAdcError('`gcloud auth application-default login` exited with a failure (it may have been cancelled).');
215
+ }
216
+ const after = await probeAdc();
217
+ if (!after.ok) {
218
+ throw new MissingAdcError(`Login finished, but still unusable: ${after.detail}`, after.fix);
219
+ }
220
+ return after.email;
221
+ }
222
+ /**
223
+ * Detects a GCE VM by probing the metadata server. Used only on the failure
224
+ * path, so the short timeout costs nothing in the happy case.
225
+ */
226
+ async function isRunningOnGce() {
227
+ const host = process.env.GCE_METADATA_HOST;
228
+ if (host) {
229
+ // An explicit host still has to answer; a stale override should not be
230
+ // mistaken for a VM (and google-auth-library honours the same variable).
231
+ return metadataServerAnswers(host);
232
+ }
233
+ return metadataServerAnswers('169.254.169.254');
234
+ }
235
+ async function metadataServerAnswers(host) {
236
+ const controller = new AbortController();
237
+ const timer = setTimeout(() => controller.abort(), 1000);
238
+ try {
239
+ const res = await fetch(`http://${host}/computeMetadata/v1/instance/id`, {
240
+ headers: { 'Metadata-Flavor': 'Google' },
241
+ signal: controller.signal,
242
+ });
243
+ return res.ok;
244
+ }
245
+ catch {
246
+ return false;
247
+ }
248
+ finally {
249
+ clearTimeout(timer);
250
+ }
251
+ }
252
+ function findGcloud() {
253
+ const probe = spawnSync('gcloud', ['version', '--format=json'], {
254
+ stdio: 'ignore',
255
+ shell: process.platform === 'win32',
256
+ });
257
+ return probe.error || probe.status !== 0 ? null : 'gcloud';
258
+ }
259
+ function runLoginPrompt(detail) {
260
+ if (!process.stdin.isTTY) {
261
+ // Non-interactive shell (CI, pipes): never block on a prompt nobody can see.
262
+ return Promise.resolve(true);
263
+ }
264
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
265
+ return new Promise((resolve) => {
266
+ rl.question(`Not signed in to Google Cloud (${detail})\n` +
267
+ ' Sign in now with `gcloud auth application-default login`? [Y/n] ', (answer) => {
268
+ rl.close();
269
+ resolve(answer.trim().toLowerCase() !== 'n');
270
+ });
271
+ });
272
+ }
package/dist/lib/gcp.js CHANGED
@@ -134,7 +134,9 @@ export async function createVm(auth, projectId, zone, instanceName, metadata, sa
134
134
  boot: true,
135
135
  autoDelete: true,
136
136
  initializeParams: {
137
- 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',
138
140
  diskSizeGb: '10',
139
141
  },
140
142
  },
@@ -29,19 +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
+ 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")
32
35
  # Secret values (GITHUB_PAT / DISCORD_BOT_TOKEN) are NOT carried in VM metadata —
33
36
  # they are fetched from Secret Manager below via the metadata-server identity.
34
37
  # The agent SA is identity-only (map #36 decision #6): no gcp_sa_key
35
38
  # metadata, no key file on disk — the SA authenticates via the metadata server.
36
39
 
37
40
  # Clean up any potential HTML responses from failed requests or unconfigured metadata
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
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
39
42
  val=${!var}
40
43
  if [[ "$val" =~ "<html" || "$val" =~ "<!" || "$val" =~ "<HTML" ]]; then
41
44
  eval "$var=\"\""
42
45
  fi
43
46
  done
44
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
+
45
68
  # Idempotency guard — GCP re-runs the startup script on EVERY boot, not just first boot.
46
69
  # Skip all provisioning steps if this VM was already set up, so reboots are harmless.
47
70
  if [ -f /root/.kimaki/.provisioned ]; then
@@ -67,6 +90,39 @@ check_disk
67
90
  sudo apt-get update -y > /dev/null 2>&1 || true
68
91
  sudo apt-get install -y curl git jq apt-transport-https ca-certificates gnupg2 ufw unzip > /dev/null 2>&1 || true
69
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
+
70
126
  # Fetch secrets from Secret Manager via the metadata-server identity (map #36).
71
127
  # No secret values ride in VM metadata; the VM's attached service account holds
72
128
  # per-secret roles/secretmanager.secretAccessor. IAM grants are eventually
@@ -146,16 +202,23 @@ if [ -d "$REPO_NAME/.git" ]; then
146
202
  REPO_CLONED=true
147
203
  else
148
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.
149
210
  for i in 1 2 3; do
150
- 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
151
212
  REPO_CLONED=true
152
213
  break
153
214
  fi
154
215
  sleep 5
155
216
  done
156
217
 
157
- # 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.
158
220
  if [ "$REPO_CLONED" != "true" ]; then
221
+ echo "TEMPLATE_CLONE=FALLBACK" > /dev/ttyS0 2>/dev/null || true
159
222
  mkdir -p "$REPO_NAME"
160
223
  cd "$REPO_NAME"
161
224
  git init
@@ -168,6 +231,7 @@ build/
168
231
  *.log
169
232
  GITEOF
170
233
  else
234
+ echo "TEMPLATE_CLONE=OK" > /dev/ttyS0 2>/dev/null || true
171
235
  cd "$REPO_NAME"
172
236
  rm -rf .git
173
237
  git init
@@ -176,38 +240,15 @@ fi
176
240
 
177
241
  git checkout -b main
178
242
 
179
- # Clean up wizard-specific files — users don't need the infra setup wizard
180
- rm -rf src/infra-setup.tsx src/create-app.tsx
181
- rm -rf src/framework/infra-setup/
182
- rm -rf src/admin/
183
- rm -rf cli/
184
- rm -rf tests/e2e/wizard.spec.js
185
- 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
186
- rm -f WIZARD_DEV_NOTES.md
187
-
188
- # Fix App.tsx: remove wizard/admin imports and routes
189
- if [ -f src/App.tsx ]; then
190
- # Remove import lines for InfraSetup, CreateApp, AdminPanel
191
- sed -i "/import InfraSetup from '.\\/infra-setup';/d" src/App.tsx
192
- sed -i "/import CreateApp from '.\\/create-app';/d" src/App.tsx
193
- sed -i "/import AdminPanel from '.\\/admin\\/AdminPanel';/d" src/App.tsx
194
- # Remove Route elements for /infra-setup, /create-app, /admin/*
195
- sed -i '/<Route path="\\/infra-setup".*\\/>/d' src/App.tsx
196
- sed -i '/<Route path="\\/create-app".*\\/>/d' src/App.tsx
197
- sed -i '/<Route path="\\/admin/d' src/App.tsx
198
- # Clean up orphaned {isAppMode && ()} blocks left behind after Route deletion
199
- perl -i -0pe 's/\\{isAppMode && \\(\\s*\\n\\s*\\)\\}//gs' src/App.tsx
200
- echo "App.tsx cleaned of wizard/admin references"
201
- fi
202
-
203
- # Fix navigation-bar.tsx: remove admin link and useIsAdmin import
204
- if [ -f src/navigation-bar.tsx ]; then
205
- sed -i "/import { useIsAdmin } from '.\\/admin\\/useIsAdmin';/d" src/navigation-bar.tsx
206
- sed -i "/const { isAdmin } = useIsAdmin(db);/d" src/navigation-bar.tsx
207
- # Delete from {isAdmin && to the next closing )} on its own line
208
- sed -i '/{isAdmin &&/,/^[[:space:]]*)}/d' src/navigation-bar.tsx
209
- echo "navigation-bar.tsx cleaned of admin references"
210
- 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).
211
252
 
212
253
  # Write a CONTEXT.md scaffold for the domain-modeling/setup-project skills
213
254
  if [ ! -f CONTEXT.md ]; then
@@ -232,53 +273,106 @@ git commit -m "Initial commit of SecureAgentBase template"
232
273
  check_disk
233
274
  PUSH_RESULT="NOT_ATTEMPTED"
234
275
  if [ -n "$GITHUB_PAT" ]; then
235
- # Clear stale gh credentials first — a revoked PAT or old token causes 401s that
236
- # persist across boots because gh caches the failed login state.
237
- gh auth logout --hostname github.com 2>/dev/null || true
238
- echo "$GITHUB_PAT" | gh auth login --with-token 2>/dev/null
239
- gh auth setup-git 2>/dev/null || true
240
-
241
- # Create new repo or force-push if it already exists
242
- if gh repo view "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null; then
243
- git remote remove origin 2>/dev/null || true
244
- git remote add origin "https://github.com/${REPO_OWNER}/${REPO_NAME}.git" || true
245
- if git push -u origin main --force 2>&1; then
246
- PUSH_RESULT="PUSH_OK"
247
- else
248
- PUSH_RESULT="PUSH_FAILED"
249
- fi
250
- else
251
- if gh repo create "${REPO_OWNER}/${REPO_NAME}" --public --source=. --push 2>&1; then
252
- PUSH_RESULT="CREATE_OK"
253
- else
254
- # Fallback: try force-push (repo may exist but PAT can't view it)
255
- git remote remove origin 2>/dev/null || true
256
- git remote add origin "https://github.com/${REPO_OWNER}/${REPO_NAME}.git" || true
257
- if git push -u origin main --force 2>&1; then
258
- PUSH_RESULT="FALLBACK_PUSH_OK"
259
- else
260
- PUSH_RESULT="ALL_PUSH_FAILED"
261
- fi
262
- fi
263
- fi
264
-
265
- # Write push result marker to serial port (compact, survives buffer overflow)
266
- 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
267
330
 
268
- # Set GitHub variables
269
- 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
+ }
270
364
 
271
365
  # Set Firebase project IDs as VARIABLES (workflow reads vars.FIREBASE_PROJECT_ID_STAGING)
272
- 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"
273
- 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"
274
368
 
275
369
  # Set OIDC variables (required by google-github-actions/auth)
276
- [ -n "$GCP_WIF_PROVIDER" ] && gh variable set GCP_WIF_PROVIDER --body "$GCP_WIF_PROVIDER" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
277
- [ -n "$GCP_SA_STAGING" ] && gh variable set GCP_SA_STAGING --body "$GCP_SA_STAGING" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
278
- [ -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
279
373
 
280
374
  # Set VITE app variables
281
- [ -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
282
376
 
283
377
  # Set Firebase config variables from JSON configs (parse with jq)
284
378
  # Convert camelCase field names to SCREAMING_SNAKE_CASE for GitHub variable names
@@ -287,7 +381,7 @@ if [ -n "$GITHUB_PAT" ]; then
287
381
  val=$(echo "$FIREBASE_STAGING_CONFIG" | jq -r ".${field} // empty" 2>/dev/null)
288
382
  if [ -n "$val" ]; then
289
383
  upper_field=$(echo "${field}" | sed 's/\([a-z]\)\([A-Z]\)/\1_\2/g' | tr '[:lower:]' '[:upper:]')
290
- 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
291
385
  fi
292
386
  done
293
387
  fi
@@ -297,13 +391,19 @@ if [ -n "$GITHUB_PAT" ]; then
297
391
  val=$(echo "$FIREBASE_PRODUCTION_CONFIG" | jq -r ".${field} // empty" 2>/dev/null)
298
392
  if [ -n "$val" ]; then
299
393
  upper_field=$(echo "${field}" | sed 's/\([a-z]\)\([A-Z]\)/\1_\2/g' | tr '[:lower:]' '[:upper:]')
300
- 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
301
395
  fi
302
396
  done
303
397
  fi
304
398
 
305
399
  echo "VAR_RESULT=DONE" > /dev/ttyS0 2>/dev/null || true
306
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
307
407
  fi
308
408
 
309
409
  # Install Kimaki globally and create its configuration
@@ -316,11 +416,13 @@ openai_api_key: ""
316
416
  github_token: ""
317
417
  KIMAKICONF
318
418
 
319
- # 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).
320
422
  cat > "/root/.kimaki/projects/$REPO_NAME/opencode.json" << 'OPENCODEEOF'
321
423
  {
322
424
  "$schema": "https://opencode.ai/config.json",
323
- "model": "opencode-go/kimi-k2.6",
425
+ "model": "__OPENCODE_MODEL__",
324
426
  "provider": {
325
427
  "opencode-go": {
326
428
  "options": {
@@ -332,6 +434,20 @@ cat > "/root/.kimaki/projects/$REPO_NAME/opencode.json" << 'OPENCODEEOF'
332
434
  }
333
435
  }
334
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
335
451
 
336
452
  # Install agent skills globally — opencode and Claude Code auto-discover these dirs.
337
453
  SKILLS_DIR=/root/.config/opencode/skills
@@ -489,7 +605,8 @@ systemctl enable kimaki-register.service
489
605
  touch /root/.kimaki/.provisioned
490
606
 
491
607
  # Final compact marker — this is the LAST output before kimaki-register starts
492
- # Non-sensitive status only — no secrets or project identifiers leaked
493
- 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
494
611
 
495
612
  systemctl start kimaki-register.service &
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "secureagentbase",
3
- "version": "1.4.6",
3
+ "version": "1.4.8",
4
4
  "description": "CLI tool to deploy and manage SecureAgentBase on GCP",
5
5
  "type": "module",
6
6
  "bin": {