secureagentbase 1.3.0 → 1.4.5

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,3 @@
1
1
  export declare function runDestroy(args: {
2
2
  yes?: boolean;
3
- saKey?: string;
4
3
  }): Promise<void>;
@@ -23,7 +23,7 @@ export async function runDestroy(args) {
23
23
  return;
24
24
  }
25
25
  }
26
- const auth = await createAuth(args.saKey);
26
+ const auth = createAuth();
27
27
  if (config.vmZone && config.vmIp) {
28
28
  info(`Deleting VM (${config.vmIp}) in ${config.vmZone}...`);
29
29
  await deleteVm(auth, config.gcpProjectId, config.vmZone, 'secureagent-manager');
@@ -1,5 +1,4 @@
1
1
  export interface InitArgs {
2
- saKey?: string;
3
2
  projectId?: string;
4
3
  autoSa?: boolean;
5
4
  firebase?: boolean;
@@ -1,4 +1,3 @@
1
- import * as fs from 'node:fs';
2
1
  import * as crypto from 'node:crypto';
3
2
  import inquirer from 'inquirer';
4
3
  import { createAuth } from '../lib/auth.js';
@@ -12,8 +11,8 @@ import { CLIError } from '../utils/errors.js';
12
11
  import { getStartupScript } from '../lib/startup-script.js';
13
12
  export async function runInit(args) {
14
13
  heading('SecureAgentBase Init');
15
- // Auth
16
- const auth = await createAuth(args.saKey);
14
+ // Auth (ADC-only — map #36 decision #6: no service account key support)
15
+ const auth = createAuth();
17
16
  const saEmail = await auth.getClientEmail();
18
17
  info(`Authenticated as ${saEmail || 'unknown (ADC)'}`);
19
18
  const config = loadConfig();
@@ -100,77 +99,30 @@ async function stepProject(auth, config, args) {
100
99
  saveConfig(config);
101
100
  success(`Project: ${config.gcpProjectId}`);
102
101
  }
103
- async function stepServiceAccount(auth, config, args) {
102
+ async function stepServiceAccount(auth, config, _args) {
104
103
  heading('Step 2: Service Account');
105
- if (args.autoSa) {
106
- // Auto-create SA (no user interaction)
107
- const projectId = config.gcpProjectId;
108
- const accountId = 'secureagent-manager';
109
- info('Creating service account...');
110
- const { email } = await createServiceAccount(auth, projectId, accountId, 'SecureAgent Manager');
111
- config.saEmail = email;
112
- info(`SA created: ${email}`);
113
- const roles = [
114
- 'roles/compute.admin',
115
- 'roles/iam.serviceAccountUser',
116
- 'roles/iam.serviceAccountTokenCreator',
117
- 'roles/billing.projectManager',
118
- 'roles/serviceusage.serviceUsageAdmin',
119
- 'roles/iam.workloadIdentityPoolAdmin',
120
- 'roles/iam.securityAdmin',
121
- 'roles/firebase.admin',
122
- ];
123
- for (const role of roles) {
124
- await grantRole(auth, `projects/${projectId}`, `serviceAccount:${email}`, role);
125
- info(` Granted ${role}`);
126
- }
127
- saveConfig(config);
128
- success('Service account configured');
129
- return;
130
- }
131
- const { choice } = await inquirer.prompt([
132
- {
133
- type: 'list',
134
- name: 'choice',
135
- message: 'Service account setup:',
136
- choices: [
137
- { name: 'Create service account programmatically', value: 'auto' },
138
- { name: 'Use existing service account key file', value: 'manual' },
139
- ],
140
- },
141
- ]);
142
- if (choice === 'manual') {
143
- const { keyPath } = await inquirer.prompt([
144
- {
145
- type: 'input',
146
- name: 'keyPath',
147
- message: 'Path to service account JSON key:',
148
- validate: (v) => fs.existsSync(v) || 'File not found',
149
- },
150
- ]);
151
- config.saKeyPath = keyPath;
152
- }
153
- else {
154
- const projectId = config.gcpProjectId;
155
- const accountId = 'secureagent-manager';
156
- info('Creating service account...');
157
- const { email } = await createServiceAccount(auth, projectId, accountId, 'SecureAgent Manager');
158
- config.saEmail = email;
159
- info(`SA created: ${email}`);
160
- const roles = [
161
- 'roles/compute.admin',
162
- 'roles/iam.serviceAccountUser',
163
- 'roles/iam.serviceAccountTokenCreator',
164
- 'roles/billing.projectManager',
165
- 'roles/serviceusage.serviceUsageAdmin',
166
- 'roles/iam.workloadIdentityPoolAdmin',
167
- 'roles/iam.securityAdmin',
168
- 'roles/firebase.admin',
169
- ];
170
- for (const role of roles) {
171
- await grantRole(auth, `projects/${projectId}`, `serviceAccount:${email}`, role);
172
- info(` Granted ${role}`);
173
- }
104
+ // Identity-only SA (map #36 decision #6): no key file is ever created or
105
+ // stored — the SA authenticates via ADC at runtime and via metadata server
106
+ // on the VM, so we always create it programmatically.
107
+ const projectId = config.gcpProjectId;
108
+ const accountId = 'secureagent-manager';
109
+ info('Creating service account...');
110
+ const { email } = await createServiceAccount(auth, projectId, accountId, 'SecureAgent Manager');
111
+ config.saEmail = email;
112
+ info(`SA created: ${email}`);
113
+ const roles = [
114
+ 'roles/compute.admin',
115
+ 'roles/iam.serviceAccountUser',
116
+ 'roles/iam.serviceAccountTokenCreator',
117
+ 'roles/billing.projectManager',
118
+ 'roles/serviceusage.serviceUsageAdmin',
119
+ 'roles/iam.workloadIdentityPoolAdmin',
120
+ 'roles/iam.securityAdmin',
121
+ 'roles/firebase.admin',
122
+ ];
123
+ for (const role of roles) {
124
+ await grantRole(auth, `projects/${projectId}`, `serviceAccount:${email}`, role);
125
+ info(` Granted ${role}`);
174
126
  }
175
127
  saveConfig(config);
176
128
  success('Service account configured');
@@ -8,7 +8,7 @@ export async function runStatus() {
8
8
  return;
9
9
  }
10
10
  kv('GCP Project', config.gcpProjectId || '-');
11
- kv('Service Account', config.saEmail || config.saKeyPath || '-');
11
+ kv('Service Account', config.saEmail || '-');
12
12
  kv('Staging Firebase', config.firebaseStaging?.projectId || '-');
13
13
  kv('Production Firebase', config.firebaseProduction?.projectId || '-');
14
14
  kv('GitHub Repo', config.githubRepo || '-');
package/dist/index.js CHANGED
@@ -13,7 +13,6 @@ program
13
13
  program
14
14
  .command('init')
15
15
  .description('Run the setup wizard')
16
- .option('--sa-key <path>', 'Path to a service account JSON key')
17
16
  .option('--project-id <id>', 'GCP project ID (skips project selection)')
18
17
  .option('--auto-sa', 'Create service account automatically (skips SA prompt)')
19
18
  .option('--no-firebase', 'Skip Firebase setup')
@@ -28,7 +27,6 @@ program
28
27
  .action(async (opts) => {
29
28
  try {
30
29
  await runInit({
31
- saKey: opts.saKey,
32
30
  projectId: opts.projectId,
33
31
  autoSa: opts.autoSa,
34
32
  firebase: opts.firebase !== false,
@@ -61,10 +59,9 @@ program
61
59
  .command('destroy')
62
60
  .description('Delete VM and clear configuration')
63
61
  .option('-y, --yes', 'Skip confirmation')
64
- .option('--sa-key <path>', 'Path to a service account JSON key')
65
62
  .action(async (opts) => {
66
63
  try {
67
- await runDestroy({ yes: opts.yes, saKey: opts.saKey });
64
+ await runDestroy({ yes: opts.yes });
68
65
  }
69
66
  catch (err) {
70
67
  handleError(err);
@@ -3,4 +3,4 @@ export interface AuthClient {
3
3
  getProjectId(): Promise<string | null>;
4
4
  getClientEmail(): Promise<string | null>;
5
5
  }
6
- export declare function createAuth(saKeyPath?: string): Promise<AuthClient>;
6
+ export declare function createAuth(): AuthClient;
package/dist/lib/auth.js CHANGED
@@ -1,10 +1,6 @@
1
1
  import { GoogleAuth } from 'google-auth-library';
2
- import * as fs from 'node:fs';
3
2
  // Least-privilege scope policy — must stay in sync with the web wizard's SA
4
3
  // impersonation scopes (src/infra-setup.tsx, src/framework/infra-setup/api.ts).
5
- // devstorage.read_write (not full_control): the SA key only uploads/overwrites
6
- // the app bundle in GCS; it never lists/deletes buckets. See architecture
7
- // review finding #6 — full_control was narrowed to match the web flow.
8
4
  const SCOPES = [
9
5
  'https://www.googleapis.com/auth/cloud-platform',
10
6
  'https://www.googleapis.com/auth/compute',
@@ -51,86 +47,10 @@ class ADCAuthClient {
51
47
  return this.clientEmail;
52
48
  }
53
49
  }
54
- class SAKeyAuthClient {
55
- keyPath;
56
- saKey;
57
- tokenCache = null;
58
- constructor(keyPath) {
59
- this.keyPath = keyPath;
60
- const raw = fs.readFileSync(keyPath, 'utf-8');
61
- this.saKey = JSON.parse(raw);
62
- if (!this.saKey.private_key || !this.saKey.client_email) {
63
- throw new Error('Invalid service account key file');
64
- }
65
- }
66
- async getToken() {
67
- if (this.tokenCache && Date.now() < this.tokenCache.expiresAt) {
68
- return this.tokenCache.token;
69
- }
70
- const token = await signJwtAndGetToken(this.saKey, SCOPES.join(' '));
71
- this.tokenCache = { token, expiresAt: Date.now() + 55 * 60 * 1000 };
72
- return token;
73
- }
74
- async getProjectId() {
75
- return this.saKey.project_id || null;
76
- }
77
- async getClientEmail() {
78
- return this.saKey.client_email || null;
79
- }
80
- }
81
- async function signJwtAndGetToken(saKey, scope) {
82
- const now = Math.floor(Date.now() / 1000);
83
- const payload = {
84
- iss: saKey.client_email,
85
- sub: saKey.client_email,
86
- aud: 'https://oauth2.googleapis.com/token',
87
- iat: now,
88
- exp: now + 3600,
89
- scope,
90
- };
91
- const header = { alg: 'RS256', typ: 'JWT' };
92
- const encodeBase64Url = (obj) => {
93
- return Buffer.from(JSON.stringify(obj))
94
- .toString('base64')
95
- .replace(/\+/g, '-')
96
- .replace(/\//g, '_')
97
- .replace(/=+$/, '');
98
- };
99
- const encodedHeader = encodeBase64Url(header);
100
- const encodedPayload = encodeBase64Url(payload);
101
- const signatureInput = `${encodedHeader}.${encodedPayload}`;
102
- const crypto = await import('node:crypto');
103
- const sign = crypto.createSign('RSA-SHA256');
104
- sign.update(signatureInput);
105
- const signature = sign.sign(saKey.private_key.replace(/\\n/g, '\n'), 'base64url');
106
- const jwt = `${signatureInput}.${signature}`;
107
- const response = await fetch('https://oauth2.googleapis.com/token', {
108
- method: 'POST',
109
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
110
- body: `grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${jwt}`,
111
- });
112
- if (!response.ok) {
113
- const err = await response.text();
114
- throw new Error(`Failed to exchange JWT for token: ${err}`);
115
- }
116
- const data = await response.json();
117
- return data.access_token;
118
- }
119
- export async function createAuth(saKeyPath) {
120
- if (saKeyPath) {
121
- return new SAKeyAuthClient(saKeyPath);
122
- }
123
- const adcPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;
124
- if (adcPath && fs.existsSync(adcPath)) {
125
- try {
126
- const key = JSON.parse(fs.readFileSync(adcPath, 'utf-8'));
127
- if (key.private_key) {
128
- return new SAKeyAuthClient(adcPath);
129
- }
130
- }
131
- catch {
132
- // Not a SA key, try ADC
133
- }
134
- }
50
+ // ADC-only (map #36 decision #6): service-account-key auth is gone. The CLI
51
+ // authenticates purely via Application Default Credentials (gcloud auth
52
+ // application-default login, Workload Identity Federation, or
53
+ // GOOGLE_APPLICATION_CREDENTIALS pointing at an ADC/authorized-user file).
54
+ export function createAuth() {
135
55
  return new ADCAuthClient();
136
56
  }
@@ -22,8 +22,6 @@ else
22
22
  fi
23
23
  FIREBASE_STAGING=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_staging" -H "Metadata-Flavor: Google")
24
24
  FIREBASE_PRODUCTION=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_production" -H "Metadata-Flavor: Google")
25
- GITHUB_PAT=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/github_pat" -H "Metadata-Flavor: Google")
26
- DISCORD_BOT_TOKEN=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/discord_bot_token" -H "Metadata-Flavor: Google")
27
25
  DISCORD_GUILD_ID=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/discord_guild_id" -H "Metadata-Flavor: Google")
28
26
  GCP_WIF_PROVIDER=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcp_wif_provider" -H "Metadata-Flavor: Google")
29
27
  GCP_SA_STAGING=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcp_sa_staging" -H "Metadata-Flavor: Google")
@@ -32,9 +30,11 @@ FIREBASE_STAGING_CONFIG=$(curl -sf "http://metadata.google.internal/computeMetad
32
30
  FIREBASE_PRODUCTION_CONFIG=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_production_config" -H "Metadata-Flavor: Google")
33
31
  VITE_APP_NAME=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/vite_app_name" -H "Metadata-Flavor: Google")
34
32
  GCP_SA_KEY=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcp_sa_key" -H "Metadata-Flavor: Google")
33
+ # Secret values (GITHUB_PAT / DISCORD_BOT_TOKEN) are NOT carried in VM metadata —
34
+ # they are fetched from Secret Manager below via the metadata-server identity.
35
35
 
36
36
  # Clean up any potential HTML responses from failed requests or unconfigured metadata
37
- for var in FIREBASE_STAGING FIREBASE_PRODUCTION GITHUB_PAT DISCORD_BOT_TOKEN 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
37
+ for var in FIREBASE_STAGING FIREBASE_PRODUCTION DISCORD_GUILD_ID GCP_WIF_PROVIDER GCP_SA_STAGING GCP_SA_PRODUCTION FIREBASE_STAGING_CONFIG FIREBASE_PRODUCTION_CONFIG VITE_APP_NAME GCP_SA_KEY; do
38
38
  val=${!var}
39
39
  if [[ "$val" =~ "<html" || "$val" =~ "<!" || "$val" =~ "<HTML" ]]; then
40
40
  eval "$var=\"\""
@@ -66,6 +66,45 @@ check_disk
66
66
  sudo apt-get update -y > /dev/null 2>&1 || true
67
67
  sudo apt-get install -y curl git jq apt-transport-https ca-certificates gnupg2 ufw unzip > /dev/null 2>&1 || true
68
68
 
69
+ # Fetch secrets from Secret Manager via the metadata-server identity (map #36).
70
+ # No secret values ride in VM metadata; the VM's attached service account holds
71
+ # per-secret roles/secretmanager.secretAccessor. IAM grants are eventually
72
+ # consistent — fresh grants can 403 for several minutes, so retry with backoff.
73
+ # A missing secret (404) fails fast: provisioning continues without it, exactly
74
+ # as it did when the metadata value was absent.
75
+ GCP_PROJECT_ID=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google")
76
+ fetch_sm_secret() {
77
+ local secret_id="$1"
78
+ [ -z "$GCP_PROJECT_ID" ] && return 1
79
+ local token
80
+ for i in $(seq 1 14); do
81
+ # --max-time bounds each attempt: a stalled metadata/API endpoint must
82
+ # not hang the boot indefinitely (the retry loop below covers flakes).
83
+ token=$(curl -sf --max-time 15 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" -H "Metadata-Flavor: Google" | jq -r '.access_token // empty')
84
+ if [ -n "$token" ]; then
85
+ local resp code body
86
+ resp=$(curl -s --max-time 15 -w '\n%{http_code}' -H "Authorization: Bearer $token" \
87
+ "https://secretmanager.googleapis.com/v1/projects/${GCP_PROJECT_ID}/secrets/${secret_id}/versions/latest:access")
88
+ code=$(printf '%s' "$resp" | tail -n1)
89
+ body=$(printf '%s' "$resp" | head -n -1)
90
+ if [ "$code" = "200" ]; then
91
+ printf '%s' "$body" | jq -r '.payload.data // empty' | base64 -d 2>/dev/null
92
+ return 0
93
+ fi
94
+ if [ "$code" = "404" ]; then
95
+ # Secret not configured — do not stall the boot waiting for it.
96
+ return 1
97
+ fi
98
+ # 403/5xx — IAM propagation or transient error, retry with backoff.
99
+ fi
100
+ sleep $((i * 3))
101
+ done
102
+ return 1
103
+ }
104
+ GITHUB_PAT=$(fetch_sm_secret "github-pat")
105
+ DISCORD_BOT_TOKEN=$(fetch_sm_secret "discord-bot-token")
106
+ echo "Secrets fetched from Secret Manager: GITHUB_PAT=$([ -n "$GITHUB_PAT" ] && echo set || echo missing) DISCORD_BOT_TOKEN=$([ -n "$DISCORD_BOT_TOKEN" ] && echo set || echo missing)"
107
+
69
108
  # Install Node.js 20.x — pinned binary release with checksum verification
70
109
  NODE_VERSION="20.18.0"
71
110
  NODE_TARBALL="node-v${NODE_VERSION}-linux-x64.tar.gz"
@@ -331,11 +370,19 @@ fi
331
370
 
332
371
  # Create systemd service for Kimaki (no-clobber — never overwrite a running unit)
333
372
  KIMAKI_PATH=$(command -v kimaki || true)
373
+ # Resolve node explicitly: the pinned tarball installs to /usr/local/bin while
374
+ # the apt fallback uses /usr/bin — hardcoding /usr/bin/node breaks the unit on
375
+ # tarball VMs (203/EXEC, "Failed to locate executable /usr/bin/node").
376
+ NODE_PATH=$(command -v node || true)
334
377
  if [ -z "$KIMAKI_PATH" ] || [ ! -x "$KIMAKI_PATH" ]; then
335
378
  echo "KIMAKI_MISSING" > /dev/ttyS0 2>/dev/null || true
336
379
  echo "WARNING: kimaki binary not found, defaulting to /usr/bin/kimaki" >&2
337
380
  KIMAKI_PATH=/usr/bin/kimaki
338
381
  fi
382
+ if [ -z "$NODE_PATH" ] || [ ! -x "$NODE_PATH" ]; then
383
+ echo "WARNING: node binary not found, defaulting to /usr/bin/node" >&2
384
+ NODE_PATH=/usr/bin/node
385
+ fi
339
386
  if [ ! -f /etc/systemd/system/kimaki.service ]; then
340
387
  cat > /etc/systemd/system/kimaki.service << SERVICEEOF
341
388
  [Unit]
@@ -346,7 +393,7 @@ After=network.target
346
393
  Type=simple
347
394
  User=root
348
395
  WorkingDirectory=/root/.kimaki/projects/$REPO_NAME
349
- ExecStart=/usr/bin/node $KIMAKI_PATH
396
+ ExecStart=$NODE_PATH $KIMAKI_PATH
350
397
  Restart=on-failure
351
398
  RestartSec=10
352
399
  EnvironmentFile=/root/.kimaki/env
@@ -356,9 +403,10 @@ Environment=NODE_ENV=production
356
403
  WantedBy=multi-user.target
357
404
  SERVICEEOF
358
405
 
359
- # Verify the ExecStart line actually references a script (an empty KIMAKI_PATH
360
- # would write `ExecStart=/usr/bin/node` and exit status=0 in ~30ms).
361
- grep -q "ExecStart=/usr/bin/node $KIMAKI_PATH" /etc/systemd/system/kimaki.service \
406
+ # Verify the ExecStart line actually references a script (an empty
407
+ # NODE_PATH/KIMAKI_PATH would write `ExecStart= ` and exit status=0 in
408
+ # ~30ms with no error — the defaults above prevent that).
409
+ grep -q "ExecStart=$NODE_PATH $KIMAKI_PATH" /etc/systemd/system/kimaki.service \
362
410
  || echo "WARNING: kimaki.service ExecStart may be broken" >&2
363
411
 
364
412
  systemctl daemon-reload
@@ -1,7 +1,6 @@
1
1
  export interface Config {
2
2
  gcpProjectId?: string;
3
3
  saEmail?: string;
4
- saKeyPath?: string;
5
4
  firebaseStaging?: Record<string, string>;
6
5
  firebaseProduction?: Record<string, string>;
7
6
  githubPat?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "secureagentbase",
3
- "version": "1.3.0",
3
+ "version": "1.4.5",
4
4
  "description": "CLI tool to deploy and manage SecureAgentBase on GCP",
5
5
  "type": "module",
6
6
  "bin": {