secureagentbase 1.4.7 → 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.
- package/dist/commands/destroy.js +4 -1
- package/dist/commands/init.js +6 -3
- package/dist/index.js +9 -3
- package/dist/lib/auth.d.ts +29 -0
- package/dist/lib/auth.js +219 -3
- package/package.json +1 -1
package/dist/commands/destroy.js
CHANGED
|
@@ -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
|
{
|
package/dist/commands/init.js
CHANGED
|
@@ -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
|
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
|
-
|
|
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('
|
|
12
|
-
.version(
|
|
17
|
+
.description('SecureAgentBase CLI')
|
|
18
|
+
.version(pkgJson.version);
|
|
13
19
|
program
|
|
14
20
|
.command('init')
|
|
15
21
|
.description('Run the setup wizard')
|
package/dist/lib/auth.d.ts
CHANGED
|
@@ -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
|
-
|
|
19
|
-
|
|
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
|
+
}
|