secureagentbase 1.3.0 → 1.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/destroy.d.ts +0 -1
- package/dist/commands/destroy.js +1 -1
- package/dist/commands/init.d.ts +0 -1
- package/dist/commands/init.js +119 -95
- package/dist/commands/status.js +5 -1
- package/dist/index.js +3 -6
- package/dist/lib/auth.d.ts +1 -1
- package/dist/lib/auth.js +5 -85
- package/dist/lib/gcp.d.ts +8 -1
- package/dist/lib/gcp.js +178 -4
- package/dist/lib/startup-script.sh +57 -14
- package/dist/utils/config.d.ts +4 -3
- package/package.json +1 -1
package/dist/commands/destroy.js
CHANGED
|
@@ -23,7 +23,7 @@ export async function runDestroy(args) {
|
|
|
23
23
|
return;
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
|
-
const auth =
|
|
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');
|
package/dist/commands/init.d.ts
CHANGED
package/dist/commands/init.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
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';
|
|
5
|
-
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';
|
|
6
5
|
import { setupFirebaseProject } from '../lib/firebase.js';
|
|
7
6
|
import { ensureRepo, setGitHubVariable, setupOidc, validatePat } from '../lib/github.js';
|
|
8
7
|
import { fetchBillingAccounts, linkBillingAccount, isBillingEnabled } from '../lib/billing.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 =
|
|
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();
|
|
@@ -39,7 +38,7 @@ export async function runInit(args) {
|
|
|
39
38
|
}
|
|
40
39
|
// Step 6: Discord bot
|
|
41
40
|
if (args.discordToken) {
|
|
42
|
-
await stepDiscord(config, args);
|
|
41
|
+
await stepDiscord(auth, config, args);
|
|
43
42
|
}
|
|
44
43
|
else {
|
|
45
44
|
info('Skipping Discord setup (no --discord-token provided)');
|
|
@@ -100,77 +99,56 @@ async function stepProject(auth, config, args) {
|
|
|
100
99
|
saveConfig(config);
|
|
101
100
|
success(`Project: ${config.gcpProjectId}`);
|
|
102
101
|
}
|
|
103
|
-
async function stepServiceAccount(auth, config,
|
|
102
|
+
async function stepServiceAccount(auth, config, _args) {
|
|
104
103
|
heading('Step 2: Service Account');
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
+
// 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',
|
|
127
|
+
];
|
|
128
|
+
for (const role of roles) {
|
|
129
|
+
await grantRole(auth, `projects/${projectId}`, `serviceAccount:${email}`, role);
|
|
130
|
+
info(` Granted ${role}`);
|
|
130
131
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
validate: (v) => fs.existsSync(v) || 'File not found',
|
|
149
|
-
},
|
|
150
|
-
]);
|
|
151
|
-
config.saKeyPath = keyPath;
|
|
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}`);
|
|
152
149
|
}
|
|
153
150
|
else {
|
|
154
|
-
|
|
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
|
-
}
|
|
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).');
|
|
174
152
|
}
|
|
175
153
|
saveConfig(config);
|
|
176
154
|
success('Service account configured');
|
|
@@ -235,11 +213,19 @@ async function stepBilling(auth, config, args) {
|
|
|
235
213
|
}
|
|
236
214
|
async function stepGitHub(auth, config, args) {
|
|
237
215
|
heading('Step 5: GitHub + OIDC Setup');
|
|
238
|
-
|
|
239
|
-
|
|
216
|
+
const projectId = config.gcpProjectId;
|
|
217
|
+
// Secret values are written to Secret Manager and used only in-memory during
|
|
218
|
+
// this run (map #36 decision #7/#8: config carries references only).
|
|
219
|
+
let pat = args.githubPat || '';
|
|
220
|
+
if (!pat) {
|
|
221
|
+
// Re-run with an existing ref → read on demand from SM instead of prompting.
|
|
222
|
+
if (config.smSecrets?.githubPat) {
|
|
223
|
+
info('Reading GitHub PAT from Secret Manager...');
|
|
224
|
+
pat = (await smFetchSecret(auth, projectId, 'github-pat')) || '';
|
|
225
|
+
}
|
|
240
226
|
}
|
|
241
|
-
|
|
242
|
-
const { pat } = await inquirer.prompt([
|
|
227
|
+
if (!pat) {
|
|
228
|
+
const { pat: entered } = await inquirer.prompt([
|
|
243
229
|
{
|
|
244
230
|
type: 'password',
|
|
245
231
|
name: 'pat',
|
|
@@ -247,9 +233,17 @@ async function stepGitHub(auth, config, args) {
|
|
|
247
233
|
validate: (v) => v.length > 0 || 'Required',
|
|
248
234
|
},
|
|
249
235
|
]);
|
|
250
|
-
|
|
236
|
+
pat = entered;
|
|
237
|
+
}
|
|
238
|
+
// Activate SM API (idempotent) before writing.
|
|
239
|
+
await enableApi(auth, projectId, 'secretmanager.googleapis.com');
|
|
240
|
+
const members = await buildSmMembers(auth, config);
|
|
241
|
+
if (members.length === 0) {
|
|
242
|
+
throw new CLIError('Cannot store GitHub PAT: no service account or operator identity found.');
|
|
251
243
|
}
|
|
252
|
-
const
|
|
244
|
+
const secretRef = await smWriteSecret(auth, projectId, 'github-pat', pat, members, info);
|
|
245
|
+
config.smSecrets = { ...(config.smSecrets || {}), githubPat: secretRef };
|
|
246
|
+
const userInfo = await validatePat(pat);
|
|
253
247
|
info(`GitHub user: ${userInfo.login}`);
|
|
254
248
|
const repoName = args.repoName || (await inquirer.prompt([
|
|
255
249
|
{
|
|
@@ -261,7 +255,7 @@ async function stepGitHub(auth, config, args) {
|
|
|
261
255
|
])).repoName;
|
|
262
256
|
const repoFull = `${userInfo.login}/${repoName}`;
|
|
263
257
|
info(`Ensuring repo: ${repoFull}`);
|
|
264
|
-
await ensureRepo(
|
|
258
|
+
await ensureRepo(pat, repoFull);
|
|
265
259
|
config.githubRepo = repoFull;
|
|
266
260
|
info('Setting up OIDC infrastructure...');
|
|
267
261
|
const oidcData = await setupOidc(auth, config.gcpProjectId, repoFull);
|
|
@@ -278,7 +272,7 @@ async function stepGitHub(auth, config, args) {
|
|
|
278
272
|
];
|
|
279
273
|
for (const [name, value] of varConfigs) {
|
|
280
274
|
if (value) {
|
|
281
|
-
await setGitHubVariable(
|
|
275
|
+
await setGitHubVariable(pat, repoFull, name, value).catch(() => {
|
|
282
276
|
warn(`Could not set GitHub variable ${name} (may already exist)`);
|
|
283
277
|
});
|
|
284
278
|
}
|
|
@@ -291,22 +285,42 @@ async function stepGitHub(auth, config, args) {
|
|
|
291
285
|
for (const field of firebaseFields) {
|
|
292
286
|
const upperField = field.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
|
|
293
287
|
if (configData[field]) {
|
|
294
|
-
await setGitHubVariable(
|
|
288
|
+
await setGitHubVariable(pat, repoFull, `FIREBASE_${upperField}_${env}`, configData[field]).catch(() => { });
|
|
295
289
|
}
|
|
296
290
|
}
|
|
297
|
-
await setGitHubVariable(
|
|
291
|
+
await setGitHubVariable(pat, repoFull, `FIREBASE_PROJECT_ID_${env}`, configData.projectId).catch(() => { });
|
|
298
292
|
}
|
|
299
293
|
}
|
|
300
294
|
saveConfig(config);
|
|
301
295
|
success(`GitHub repo ready: ${repoFull}`);
|
|
302
296
|
}
|
|
303
|
-
|
|
297
|
+
// Per-secret accessors for the 2 SM secrets (map #36): the operator (ADC
|
|
298
|
+
// identity, user or service account) and the identity-only agent SA. The agent
|
|
299
|
+
// SA is what the VM boots with; the operator is for re-run fetches.
|
|
300
|
+
async function buildSmMembers(auth, config) {
|
|
301
|
+
const members = [];
|
|
302
|
+
if (config.saEmail)
|
|
303
|
+
members.push(`serviceAccount:${config.saEmail}`);
|
|
304
|
+
try {
|
|
305
|
+
const email = await auth.getClientEmail();
|
|
306
|
+
if (email)
|
|
307
|
+
members.push(smMember(email));
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
// ADC may not expose an email — agent SA membership is enough.
|
|
311
|
+
}
|
|
312
|
+
return members;
|
|
313
|
+
}
|
|
314
|
+
async function stepDiscord(auth, config, args) {
|
|
304
315
|
heading('Step 6: Discord Bot');
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
316
|
+
const projectId = config.gcpProjectId;
|
|
317
|
+
// Secret value used in-memory only (map #36 decision #7/#8).
|
|
318
|
+
let token = args.discordToken || '';
|
|
319
|
+
if (!token && config.smSecrets?.discordBotToken) {
|
|
320
|
+
info('Reading Discord bot token from Secret Manager...');
|
|
321
|
+
token = (await smFetchSecret(auth, projectId, 'discord-bot-token')) || '';
|
|
308
322
|
}
|
|
309
|
-
|
|
323
|
+
if (!token) {
|
|
310
324
|
const { botToken } = await inquirer.prompt([
|
|
311
325
|
{
|
|
312
326
|
type: 'password',
|
|
@@ -315,13 +329,21 @@ async function stepDiscord(config, args) {
|
|
|
315
329
|
validate: (v) => v.length > 0 || 'Required',
|
|
316
330
|
},
|
|
317
331
|
]);
|
|
318
|
-
|
|
332
|
+
token = botToken;
|
|
333
|
+
}
|
|
334
|
+
// Write to the same SM store the web wizard uses; config keeps only the ref.
|
|
335
|
+
await enableApi(auth, projectId, 'secretmanager.googleapis.com');
|
|
336
|
+
const members = await buildSmMembers(auth, config);
|
|
337
|
+
if (members.length === 0) {
|
|
338
|
+
throw new CLIError('Cannot store Discord bot token: no service account or operator identity found.');
|
|
319
339
|
}
|
|
340
|
+
const secretRef = await smWriteSecret(auth, projectId, 'discord-bot-token', token, members, info);
|
|
341
|
+
config.smSecrets = { ...(config.smSecrets || {}), discordBotToken: secretRef };
|
|
320
342
|
if (args.discordGuild) {
|
|
321
343
|
config.discordGuildId = args.discordGuild;
|
|
322
344
|
}
|
|
323
|
-
// Decode client ID from token
|
|
324
|
-
const decoded = Buffer.from(
|
|
345
|
+
// Decode client ID from the in-memory token.
|
|
346
|
+
const decoded = Buffer.from(token.split('.')[0], 'base64').toString();
|
|
325
347
|
const clientIdMatch = decoded.match(/"(?:id|client_id)"\s*:\s*"(\d+)"/);
|
|
326
348
|
if (clientIdMatch) {
|
|
327
349
|
info(`Bot Client ID: ${clientIdMatch[1]}`);
|
|
@@ -329,9 +351,10 @@ async function stepDiscord(config, args) {
|
|
|
329
351
|
if (!config.discordGuildId) {
|
|
330
352
|
if (args.yes) {
|
|
331
353
|
info('No guild ID provided, skipping guild prompt (-y mode)');
|
|
354
|
+
config.discordGuildId = '';
|
|
332
355
|
}
|
|
333
356
|
else {
|
|
334
|
-
const inviteUrl = `https://discord.com/oauth2/authorize?client_id=${
|
|
357
|
+
const inviteUrl = `https://discord.com/oauth2/authorize?client_id=${decoded.match(/"(\d+)"/)?.[1] || 'UNKNOWN'}&permissions=8&integration_type=0&scope=bot%20applications.commands`;
|
|
335
358
|
warn(`Invite your bot to a server: ${inviteUrl}`);
|
|
336
359
|
const { guildId } = await inquirer.prompt([
|
|
337
360
|
{
|
|
@@ -354,11 +377,12 @@ async function stepCreateVm(auth, config, args) {
|
|
|
354
377
|
await enableApi(auth, projectId, 'compute.googleapis.com');
|
|
355
378
|
info('Enabling IAM Credentials API...');
|
|
356
379
|
await enableApi(auth, projectId, 'iamcredentials.googleapis.com');
|
|
357
|
-
// Build metadata (same as web wizard's buildVmMetadata)
|
|
380
|
+
// Build metadata (same as the web wizard's buildVmMetadata). Secret VALUES
|
|
381
|
+
// are NOT carried here (map #36 decision #9): the startup script fetches
|
|
382
|
+
// github-pat + discord-bot-token from Secret Manager via the metadata-server
|
|
383
|
+
// identity (the agent SA attached below).
|
|
358
384
|
const metadata = {
|
|
359
|
-
github_pat: config.githubPat || '',
|
|
360
385
|
github_repo: config.githubRepo || '',
|
|
361
|
-
discord_bot_token: config.discordBotToken || '',
|
|
362
386
|
discord_guild_id: config.discordGuildId || '',
|
|
363
387
|
firebase_staging: config.firebaseStaging?.projectId || '',
|
|
364
388
|
firebase_production: config.firebaseProduction?.projectId || '',
|
|
@@ -389,7 +413,7 @@ async function stepCreateVm(auth, config, args) {
|
|
|
389
413
|
for (const zone of zones) {
|
|
390
414
|
try {
|
|
391
415
|
info(`Attempting VM creation in ${zone}...`);
|
|
392
|
-
vmResult = await createVm(auth, projectId, zone, 'secureagent-manager', metadata);
|
|
416
|
+
vmResult = await createVm(auth, projectId, zone, 'secureagent-manager', metadata, config.saEmail);
|
|
393
417
|
config.vmIp = vmResult.ip;
|
|
394
418
|
config.vmZone = vmResult.zone;
|
|
395
419
|
break;
|
package/dist/commands/status.js
CHANGED
|
@@ -8,10 +8,14 @@ export async function runStatus() {
|
|
|
8
8
|
return;
|
|
9
9
|
}
|
|
10
10
|
kv('GCP Project', config.gcpProjectId || '-');
|
|
11
|
-
kv('Service Account', config.saEmail ||
|
|
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 || '-');
|
|
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
|
@@ -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')
|
|
@@ -22,13 +21,12 @@ program
|
|
|
22
21
|
.option('--repo-name <name>', 'GitHub repo name (requires --github-pat)')
|
|
23
22
|
.option('--discord-token <token>', 'Discord bot token')
|
|
24
23
|
.option('--discord-guild <id>', 'Discord guild ID')
|
|
25
|
-
.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)')
|
|
26
25
|
.option('--no-vm', 'Skip VM creation')
|
|
27
26
|
.option('-y, --yes', 'Skip all confirmations (non-interactive mode)')
|
|
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,
|
|
@@ -37,7 +35,7 @@ program
|
|
|
37
35
|
repoName: opts.repoName,
|
|
38
36
|
discordToken: opts.discordToken,
|
|
39
37
|
discordGuild: opts.discordGuild,
|
|
40
|
-
vmZone: opts.vmZone
|
|
38
|
+
vmZone: opts.vmZone,
|
|
41
39
|
yes: opts.yes,
|
|
42
40
|
vm: opts.vm,
|
|
43
41
|
});
|
|
@@ -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
|
|
64
|
+
await runDestroy({ yes: opts.yes });
|
|
68
65
|
}
|
|
69
66
|
catch (err) {
|
|
70
67
|
handleError(err);
|
package/dist/lib/auth.d.ts
CHANGED
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
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
}
|
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
|
|
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
|
-
|
|
100
|
+
// Grants a role ON a service account resource (e.g. iam.serviceAccountUser on
|
|
101
|
+
// the agent SA so a VM creator can attach it). The IAM API is used instead of
|
|
102
|
+
// cloudresourcemanager because the latter only supports projects/folders.
|
|
103
|
+
export async function grantRoleOnServiceAccount(auth, projectId, accountId, member, role) {
|
|
104
|
+
const base = `https://iam.googleapis.com/v1/projects/${projectId}/serviceAccounts/${accountId}`;
|
|
105
|
+
const policy = await gcpFetch(auth, `${base}:getIamPolicy`, { method: 'POST' });
|
|
106
|
+
const bindings = policy.bindings || [];
|
|
107
|
+
const existing = bindings.find((b) => b.role === role);
|
|
108
|
+
if (!existing) {
|
|
109
|
+
bindings.push({ role, members: [member] });
|
|
110
|
+
}
|
|
111
|
+
else if (!existing.members.includes(member)) {
|
|
112
|
+
existing.members.push(member);
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
return; // Already has the role
|
|
116
|
+
}
|
|
117
|
+
await gcpFetch(auth, `${base}:setIamPolicy`, {
|
|
118
|
+
method: 'POST',
|
|
119
|
+
body: { policy: { bindings, etag: policy.etag } },
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
export async function createVm(auth, projectId, zone, instanceName, metadata, saEmail) {
|
|
101
123
|
const url = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances`;
|
|
124
|
+
// The VM boots with the identity-only agent SA (map #36 decision #3) so the
|
|
125
|
+
// startup script can fetch the 2 secrets via the metadata-server identity.
|
|
102
126
|
const body = {
|
|
103
127
|
name: instanceName,
|
|
104
128
|
// Default to e2-small — same default as the web wizard (see
|
|
@@ -118,7 +142,11 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
|
|
|
118
142
|
networkInterfaces: [
|
|
119
143
|
{
|
|
120
144
|
network: 'global/networks/default',
|
|
121
|
-
|
|
145
|
+
// No explicit name: GCE defaults the access config to 'external-nat'.
|
|
146
|
+
// An explicit name like 'External NAT' (space/uppercase) is invalid
|
|
147
|
+
// and GCE rejects the create operation, tearing the VM down to
|
|
148
|
+
// STOPPING within seconds (observed across all 12 zones).
|
|
149
|
+
accessConfigs: [{ type: 'ONE_TO_ONE_NAT' }],
|
|
122
150
|
},
|
|
123
151
|
],
|
|
124
152
|
metadata: {
|
|
@@ -128,6 +156,11 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
|
|
|
128
156
|
})),
|
|
129
157
|
},
|
|
130
158
|
};
|
|
159
|
+
if (saEmail) {
|
|
160
|
+
body.serviceAccounts = [
|
|
161
|
+
{ email: saEmail, scopes: ['https://www.googleapis.com/auth/cloud-platform'] },
|
|
162
|
+
];
|
|
163
|
+
}
|
|
131
164
|
// Try to delete any existing VM with this name in the target zone
|
|
132
165
|
const existingUrl = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`;
|
|
133
166
|
try {
|
|
@@ -146,7 +179,36 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
|
|
|
146
179
|
catch {
|
|
147
180
|
// VM doesn't exist — that's fine
|
|
148
181
|
}
|
|
149
|
-
|
|
182
|
+
// POST create returns an Operation; poll it to DONE. If the operation
|
|
183
|
+
// fails, its error is the ground truth for why the VM never becomes
|
|
184
|
+
// RUNNING (GCE otherwise tears the instance down to STOPPING/TERMINATED
|
|
185
|
+
// with no obvious cause from the instance resource itself).
|
|
186
|
+
const op = await gcpFetch(auth, url, { method: 'POST', body });
|
|
187
|
+
const opName = op?.name;
|
|
188
|
+
const opSelfLink = op?.selfLink;
|
|
189
|
+
let opBase;
|
|
190
|
+
if (opName) {
|
|
191
|
+
opBase = opSelfLink?.includes('global/operations')
|
|
192
|
+
? `https://compute.googleapis.com/compute/v1/projects/${projectId}/global/operations/${opName}`
|
|
193
|
+
: `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/operations/${opName}`;
|
|
194
|
+
for (let o = 0; o < 60; o++) {
|
|
195
|
+
await new Promise((r) => setTimeout(r, 3000));
|
|
196
|
+
let status;
|
|
197
|
+
try {
|
|
198
|
+
status = await gcpFetch(auth, opBase);
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
continue; // Operation not visible yet
|
|
202
|
+
}
|
|
203
|
+
if (status?.status === 'DONE') {
|
|
204
|
+
if (status?.error) {
|
|
205
|
+
const detail = JSON.stringify(status.error.errors || status.error).slice(0, 2000);
|
|
206
|
+
throw new Error(`VM create operation failed: ${detail}`);
|
|
207
|
+
}
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
150
212
|
// Poll until VM is RUNNING (up to 10 minutes)
|
|
151
213
|
for (let i = 0; i < 120; i++) {
|
|
152
214
|
await new Promise((r) => setTimeout(r, 5000));
|
|
@@ -159,6 +221,25 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
|
|
|
159
221
|
if (instance.status === 'STOPPING' || instance.status === 'TERMINATED') {
|
|
160
222
|
// VM is dying — abort early, delete it, and let the caller try the next zone
|
|
161
223
|
console.log(` VM is ${instance.status}, aborting and trying next zone...`);
|
|
224
|
+
// Dump the create operation error if we still have one, plus the
|
|
225
|
+
// serial console, for ground truth on why the VM stopped.
|
|
226
|
+
if (opName && opBase) {
|
|
227
|
+
try {
|
|
228
|
+
const opNow = await gcpFetch(auth, opBase);
|
|
229
|
+
if (opNow?.error) {
|
|
230
|
+
console.log(` create operation error: ${JSON.stringify(opNow.error.errors || opNow.error).slice(0, 2000)}`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
catch { }
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
const serial = await fetchVmLogs(auth, projectId, zone, instanceName);
|
|
237
|
+
const tail = serial.split('\n').filter((l) => l.trim()).slice(-30).join('\n');
|
|
238
|
+
console.log(` --- serial console (last 30 lines) ---\n${tail}\n ----------------------------------------`);
|
|
239
|
+
}
|
|
240
|
+
catch (e) {
|
|
241
|
+
console.log(` (serial console unavailable: ${e.message})`);
|
|
242
|
+
}
|
|
162
243
|
try {
|
|
163
244
|
await gcpFetch(auth, existingUrl, { method: 'DELETE' });
|
|
164
245
|
}
|
|
@@ -170,7 +251,7 @@ export async function createVm(auth, projectId, zone, instanceName, metadata) {
|
|
|
170
251
|
}
|
|
171
252
|
}
|
|
172
253
|
catch (e) {
|
|
173
|
-
if (e.message?.includes('aborting') || e.message?.includes('STOPPING') || e.message?.includes('TERMINATED'))
|
|
254
|
+
if (e.message?.includes('aborting') || e.message?.includes('STOPPING') || e.message?.includes('TERMINATED') || e.message?.includes('operation failed'))
|
|
174
255
|
throw e;
|
|
175
256
|
// Instance not yet available
|
|
176
257
|
}
|
|
@@ -223,3 +304,96 @@ export async function fetchVmLogs(auth, projectId, zone, instanceName) {
|
|
|
223
304
|
const result = await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}/serialPort?port=1`);
|
|
224
305
|
return (result.contents || '').split('\n').map((l) => atob(l)).join('\n');
|
|
225
306
|
}
|
|
307
|
+
// ---------------------------------------------------------------------------
|
|
308
|
+
// Secret Manager helpers (map #36 decision #7). The CLI writes the 2 secrets
|
|
309
|
+
// (github-pat, discord-bot-token) to the SAME SM store the web wizard uses, at
|
|
310
|
+
// prompt time. The operator (ADC identity) must have roles/secretmanager.admin
|
|
311
|
+
// — granted in stepServiceAccount — and per-secret secretAccessor is bound to
|
|
312
|
+
// the operator + the identity-only agent SA (the VM's metadata identity).
|
|
313
|
+
// Mirrors src/framework/infra-setup/api.ts.
|
|
314
|
+
// ---------------------------------------------------------------------------
|
|
315
|
+
const SM_BASE = 'https://secretmanager.googleapis.com/v1';
|
|
316
|
+
const base64Encode = (value) => Buffer.from(value, 'utf-8').toString('base64');
|
|
317
|
+
// Project-level member prefix: service accounts end in *.gserviceaccount.com,
|
|
318
|
+
// everything else (gcloud ADC user, WIF-federated user) is a `user:`.
|
|
319
|
+
export const smMember = (email) => email.endsWith('.gserviceaccount.com') ? `serviceAccount:${email}` : `user:${email}`;
|
|
320
|
+
export const smEnsureSecret = async (auth, projectId, secretId) => {
|
|
321
|
+
// The API-enable loop activates secretmanager.googleapis.com before writing,
|
|
322
|
+
// but GCP can lag a few seconds past the status poll. Retry briefly on
|
|
323
|
+
// SERVICE_DISABLED so a brand-new project doesn't 403 on the first write.
|
|
324
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
325
|
+
try {
|
|
326
|
+
const secret = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets?secretId=${encodeURIComponent(secretId)}`, {
|
|
327
|
+
method: 'POST',
|
|
328
|
+
body: { replication: { automatic: {} } },
|
|
329
|
+
});
|
|
330
|
+
return secret.name;
|
|
331
|
+
}
|
|
332
|
+
catch (e) {
|
|
333
|
+
if (e.message?.includes('SERVICE_DISABLED')) {
|
|
334
|
+
if (attempt < 2) {
|
|
335
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
throw new Error(`Secret Manager API is not active for project ${projectId}: ${e.message}`);
|
|
339
|
+
}
|
|
340
|
+
// 409 ALREADY_EXISTS — fetch the existing secret instead.
|
|
341
|
+
if (!e.message?.includes('409'))
|
|
342
|
+
throw e;
|
|
343
|
+
const existing = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}`);
|
|
344
|
+
return existing.name;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
throw new Error(`Secret Manager API did not activate for project ${projectId}`);
|
|
348
|
+
};
|
|
349
|
+
export const smAddVersion = async (auth, projectId, secretId, value) => {
|
|
350
|
+
const added = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:addVersion`, {
|
|
351
|
+
method: 'POST',
|
|
352
|
+
body: { payload: { data: base64Encode(value) } },
|
|
353
|
+
});
|
|
354
|
+
return added.name;
|
|
355
|
+
};
|
|
356
|
+
export const smSetSecretAccess = async (auth, projectId, secretId, members) => {
|
|
357
|
+
const policy = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:getIamPolicy`);
|
|
358
|
+
const bindings = policy.bindings || [];
|
|
359
|
+
let binding = bindings.find((b) => b.role === 'roles/secretmanager.secretAccessor');
|
|
360
|
+
if (!binding) {
|
|
361
|
+
binding = { role: 'roles/secretmanager.secretAccessor', members: [] };
|
|
362
|
+
bindings.push(binding);
|
|
363
|
+
}
|
|
364
|
+
for (const member of members) {
|
|
365
|
+
if (!binding.members.includes(member))
|
|
366
|
+
binding.members.push(member);
|
|
367
|
+
}
|
|
368
|
+
await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}:setIamPolicy`, {
|
|
369
|
+
method: 'POST',
|
|
370
|
+
body: { policy: { bindings, etag: policy.etag } },
|
|
371
|
+
});
|
|
372
|
+
};
|
|
373
|
+
// Idempotent write: create-or-get the secret, add a new version, and bind the
|
|
374
|
+
// per-secret accessors (operator + agent SA). Returns the secret resource name
|
|
375
|
+
// used as a config reference.
|
|
376
|
+
export const smWriteSecret = async (auth, projectId, secretId, value, members, log) => {
|
|
377
|
+
const secretName = await smEnsureSecret(auth, projectId, secretId);
|
|
378
|
+
await smAddVersion(auth, projectId, secretId, value);
|
|
379
|
+
await smSetSecretAccess(auth, projectId, secretId, members);
|
|
380
|
+
log?.(`Secret ${secretId} stored in Secret Manager (${secretName})`);
|
|
381
|
+
return secretName;
|
|
382
|
+
};
|
|
383
|
+
// Read the latest version on demand (decision #7). Used for re-runs that need
|
|
384
|
+
// the in-memory value (e.g. re-validate a PAT). Returns null if the secret
|
|
385
|
+
// does not exist (404) so callers can fall back to a prompt.
|
|
386
|
+
export const smFetchSecret = async (auth, projectId, secretId) => {
|
|
387
|
+
try {
|
|
388
|
+
const result = await gcpFetch(auth, `${SM_BASE}/projects/${projectId}/secrets/${encodeURIComponent(secretId)}/versions/latest:access`);
|
|
389
|
+
const b64 = result?.payload?.data;
|
|
390
|
+
if (!b64)
|
|
391
|
+
return null;
|
|
392
|
+
return Buffer.from(b64, 'base64').toString('utf-8');
|
|
393
|
+
}
|
|
394
|
+
catch (e) {
|
|
395
|
+
if (e.message?.includes('404') || e.message?.includes('403'))
|
|
396
|
+
return null;
|
|
397
|
+
throw e;
|
|
398
|
+
}
|
|
399
|
+
};
|
|
@@ -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")
|
|
@@ -31,10 +29,13 @@ GCP_SA_PRODUCTION=$(curl -sf "http://metadata.google.internal/computeMetadata/v1
|
|
|
31
29
|
FIREBASE_STAGING_CONFIG=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_staging_config" -H "Metadata-Flavor: Google")
|
|
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
|
+
# Secret values (GITHUB_PAT / DISCORD_BOT_TOKEN) are NOT carried in VM metadata —
|
|
33
|
+
# they are fetched from Secret Manager below via the metadata-server identity.
|
|
34
|
+
# The agent SA is identity-only (map #36 decision #6): no gcp_sa_key
|
|
35
|
+
# metadata, no key file on disk — the SA authenticates via the metadata server.
|
|
35
36
|
|
|
36
37
|
# Clean up any potential HTML responses from failed requests or unconfigured metadata
|
|
37
|
-
for var in FIREBASE_STAGING FIREBASE_PRODUCTION
|
|
38
|
+
for var in FIREBASE_STAGING FIREBASE_PRODUCTION DISCORD_GUILD_ID GCP_WIF_PROVIDER GCP_SA_STAGING GCP_SA_PRODUCTION FIREBASE_STAGING_CONFIG FIREBASE_PRODUCTION_CONFIG VITE_APP_NAME; do
|
|
38
39
|
val=${!var}
|
|
39
40
|
if [[ "$val" =~ "<html" || "$val" =~ "<!" || "$val" =~ "<HTML" ]]; then
|
|
40
41
|
eval "$var=\"\""
|
|
@@ -66,6 +67,45 @@ check_disk
|
|
|
66
67
|
sudo apt-get update -y > /dev/null 2>&1 || true
|
|
67
68
|
sudo apt-get install -y curl git jq apt-transport-https ca-certificates gnupg2 ufw unzip > /dev/null 2>&1 || true
|
|
68
69
|
|
|
70
|
+
# Fetch secrets from Secret Manager via the metadata-server identity (map #36).
|
|
71
|
+
# No secret values ride in VM metadata; the VM's attached service account holds
|
|
72
|
+
# per-secret roles/secretmanager.secretAccessor. IAM grants are eventually
|
|
73
|
+
# consistent — fresh grants can 403 for several minutes, so retry with backoff.
|
|
74
|
+
# A missing secret (404) fails fast: provisioning continues without it, exactly
|
|
75
|
+
# as it did when the metadata value was absent.
|
|
76
|
+
GCP_PROJECT_ID=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google")
|
|
77
|
+
fetch_sm_secret() {
|
|
78
|
+
local secret_id="$1"
|
|
79
|
+
[ -z "$GCP_PROJECT_ID" ] && return 1
|
|
80
|
+
local token
|
|
81
|
+
for i in $(seq 1 14); do
|
|
82
|
+
# --max-time bounds each attempt: a stalled metadata/API endpoint must
|
|
83
|
+
# not hang the boot indefinitely (the retry loop below covers flakes).
|
|
84
|
+
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')
|
|
85
|
+
if [ -n "$token" ]; then
|
|
86
|
+
local resp code body
|
|
87
|
+
resp=$(curl -s --max-time 15 -w '\n%{http_code}' -H "Authorization: Bearer $token" \
|
|
88
|
+
"https://secretmanager.googleapis.com/v1/projects/${GCP_PROJECT_ID}/secrets/${secret_id}/versions/latest:access")
|
|
89
|
+
code=$(printf '%s' "$resp" | tail -n1)
|
|
90
|
+
body=$(printf '%s' "$resp" | head -n -1)
|
|
91
|
+
if [ "$code" = "200" ]; then
|
|
92
|
+
printf '%s' "$body" | jq -r '.payload.data // empty' | base64 -d 2>/dev/null
|
|
93
|
+
return 0
|
|
94
|
+
fi
|
|
95
|
+
if [ "$code" = "404" ]; then
|
|
96
|
+
# Secret not configured — do not stall the boot waiting for it.
|
|
97
|
+
return 1
|
|
98
|
+
fi
|
|
99
|
+
# 403/5xx — IAM propagation or transient error, retry with backoff.
|
|
100
|
+
fi
|
|
101
|
+
sleep $((i * 3))
|
|
102
|
+
done
|
|
103
|
+
return 1
|
|
104
|
+
}
|
|
105
|
+
GITHUB_PAT=$(fetch_sm_secret "github-pat")
|
|
106
|
+
DISCORD_BOT_TOKEN=$(fetch_sm_secret "discord-bot-token")
|
|
107
|
+
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)"
|
|
108
|
+
|
|
69
109
|
# Install Node.js 20.x — pinned binary release with checksum verification
|
|
70
110
|
NODE_VERSION="20.18.0"
|
|
71
111
|
NODE_TARBALL="node-v${NODE_VERSION}-linux-x64.tar.gz"
|
|
@@ -323,19 +363,21 @@ NODE_ENV=production
|
|
|
323
363
|
ENVEOF
|
|
324
364
|
chmod 600 /root/.kimaki/env
|
|
325
365
|
|
|
326
|
-
# Write GCP service account key from metadata (if provided) to a restricted file
|
|
327
|
-
if [ -n "$GCP_SA_KEY" ]; then
|
|
328
|
-
echo "$GCP_SA_KEY" > /root/.kimaki/gcp-sa-key.json
|
|
329
|
-
chmod 600 /root/.kimaki/gcp-sa-key.json
|
|
330
|
-
fi
|
|
331
|
-
|
|
332
366
|
# Create systemd service for Kimaki (no-clobber — never overwrite a running unit)
|
|
333
367
|
KIMAKI_PATH=$(command -v kimaki || true)
|
|
368
|
+
# Resolve node explicitly: the pinned tarball installs to /usr/local/bin while
|
|
369
|
+
# the apt fallback uses /usr/bin — hardcoding /usr/bin/node breaks the unit on
|
|
370
|
+
# tarball VMs (203/EXEC, "Failed to locate executable /usr/bin/node").
|
|
371
|
+
NODE_PATH=$(command -v node || true)
|
|
334
372
|
if [ -z "$KIMAKI_PATH" ] || [ ! -x "$KIMAKI_PATH" ]; then
|
|
335
373
|
echo "KIMAKI_MISSING" > /dev/ttyS0 2>/dev/null || true
|
|
336
374
|
echo "WARNING: kimaki binary not found, defaulting to /usr/bin/kimaki" >&2
|
|
337
375
|
KIMAKI_PATH=/usr/bin/kimaki
|
|
338
376
|
fi
|
|
377
|
+
if [ -z "$NODE_PATH" ] || [ ! -x "$NODE_PATH" ]; then
|
|
378
|
+
echo "WARNING: node binary not found, defaulting to /usr/bin/node" >&2
|
|
379
|
+
NODE_PATH=/usr/bin/node
|
|
380
|
+
fi
|
|
339
381
|
if [ ! -f /etc/systemd/system/kimaki.service ]; then
|
|
340
382
|
cat > /etc/systemd/system/kimaki.service << SERVICEEOF
|
|
341
383
|
[Unit]
|
|
@@ -346,7 +388,7 @@ After=network.target
|
|
|
346
388
|
Type=simple
|
|
347
389
|
User=root
|
|
348
390
|
WorkingDirectory=/root/.kimaki/projects/$REPO_NAME
|
|
349
|
-
ExecStart
|
|
391
|
+
ExecStart=$NODE_PATH $KIMAKI_PATH
|
|
350
392
|
Restart=on-failure
|
|
351
393
|
RestartSec=10
|
|
352
394
|
EnvironmentFile=/root/.kimaki/env
|
|
@@ -356,9 +398,10 @@ Environment=NODE_ENV=production
|
|
|
356
398
|
WantedBy=multi-user.target
|
|
357
399
|
SERVICEEOF
|
|
358
400
|
|
|
359
|
-
# Verify the ExecStart line actually references a script (an empty
|
|
360
|
-
# would write `ExecStart
|
|
361
|
-
|
|
401
|
+
# Verify the ExecStart line actually references a script (an empty
|
|
402
|
+
# NODE_PATH/KIMAKI_PATH would write `ExecStart= ` and exit status=0 in
|
|
403
|
+
# ~30ms with no error — the defaults above prevent that).
|
|
404
|
+
grep -q "ExecStart=$NODE_PATH $KIMAKI_PATH" /etc/systemd/system/kimaki.service \
|
|
362
405
|
|| echo "WARNING: kimaki.service ExecStart may be broken" >&2
|
|
363
406
|
|
|
364
407
|
systemctl daemon-reload
|
package/dist/utils/config.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
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
|
+
smSecrets?: {
|
|
7
|
+
githubPat?: string;
|
|
8
|
+
discordBotToken?: string;
|
|
9
|
+
};
|
|
8
10
|
githubRepo?: string;
|
|
9
|
-
discordBotToken?: string;
|
|
10
11
|
discordGuildId?: string;
|
|
11
12
|
vmIp?: string;
|
|
12
13
|
vmZone?: string;
|