secureagentbase 1.2.13
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/bin/secureagentbase.js +2 -0
- package/dist/commands/destroy.d.ts +4 -0
- package/dist/commands/destroy.js +34 -0
- package/dist/commands/init.d.ts +15 -0
- package/dist/commands/init.js +426 -0
- package/dist/commands/status.d.ts +1 -0
- package/dist/commands/status.js +17 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +73 -0
- package/dist/lib/auth.d.ts +6 -0
- package/dist/lib/auth.js +136 -0
- package/dist/lib/billing.d.ts +6 -0
- package/dist/lib/billing.js +60 -0
- package/dist/lib/firebase.d.ts +13 -0
- package/dist/lib/firebase.js +84 -0
- package/dist/lib/gcp.d.ts +22 -0
- package/dist/lib/gcp.js +222 -0
- package/dist/lib/github.d.ts +17 -0
- package/dist/lib/github.js +151 -0
- package/dist/lib/startup-script.d.ts +1 -0
- package/dist/lib/startup-script.js +9 -0
- package/dist/lib/startup-script.sh +452 -0
- package/dist/utils/config.d.ts +22 -0
- package/dist/utils/config.js +25 -0
- package/dist/utils/errors.d.ts +4 -0
- package/dist/utils/errors.js +22 -0
- package/dist/utils/output.d.ts +6 -0
- package/dist/utils/output.js +21 -0
- package/package.json +48 -0
package/dist/lib/auth.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { GoogleAuth } from 'google-auth-library';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
// Least-privilege scope policy — must stay in sync with the web wizard's SA
|
|
4
|
+
// 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
|
+
const SCOPES = [
|
|
9
|
+
'https://www.googleapis.com/auth/cloud-platform',
|
|
10
|
+
'https://www.googleapis.com/auth/compute',
|
|
11
|
+
'https://www.googleapis.com/auth/devstorage.read_write',
|
|
12
|
+
'https://www.googleapis.com/auth/cloud-billing.readonly',
|
|
13
|
+
];
|
|
14
|
+
class ADCAuthClient {
|
|
15
|
+
auth;
|
|
16
|
+
projectId = null;
|
|
17
|
+
clientEmail = null;
|
|
18
|
+
constructor() {
|
|
19
|
+
this.auth = new GoogleAuth({ scopes: SCOPES });
|
|
20
|
+
}
|
|
21
|
+
async getToken() {
|
|
22
|
+
const client = await this.auth.getClient();
|
|
23
|
+
const tokenResponse = await client.getAccessToken();
|
|
24
|
+
if (!tokenResponse.token)
|
|
25
|
+
throw new Error('Failed to get access token from ADC');
|
|
26
|
+
return tokenResponse.token;
|
|
27
|
+
}
|
|
28
|
+
async getProjectId() {
|
|
29
|
+
if (this.projectId)
|
|
30
|
+
return this.projectId;
|
|
31
|
+
try {
|
|
32
|
+
this.projectId = await this.auth.getProjectId() || null;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
this.projectId = null;
|
|
36
|
+
}
|
|
37
|
+
return this.projectId;
|
|
38
|
+
}
|
|
39
|
+
async getClientEmail() {
|
|
40
|
+
if (this.clientEmail)
|
|
41
|
+
return this.clientEmail;
|
|
42
|
+
try {
|
|
43
|
+
const client = await this.auth.getClient();
|
|
44
|
+
if ('email' in client && typeof client.email === 'string') {
|
|
45
|
+
this.clientEmail = client.email;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
this.clientEmail = null;
|
|
50
|
+
}
|
|
51
|
+
return this.clientEmail;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
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
|
+
}
|
|
135
|
+
return new ADCAuthClient();
|
|
136
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AuthClient } from './auth.js';
|
|
2
|
+
export declare function fetchBillingAccounts(auth: AuthClient, projectId: string): Promise<any[]>;
|
|
3
|
+
export declare function getBillingInfo(auth: AuthClient, projectId: string): Promise<any>;
|
|
4
|
+
export declare function linkBillingAccount(auth: AuthClient, projectId: string, billingAccountId: string): Promise<void>;
|
|
5
|
+
export declare function isBillingEnabled(auth: AuthClient, projectId: string): Promise<boolean>;
|
|
6
|
+
export declare function enableBillingApi(auth: AuthClient, projectId: string): Promise<void>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { gcpFetch } from './gcp.js';
|
|
2
|
+
export async function fetchBillingAccounts(auth, projectId) {
|
|
3
|
+
const token = await auth.getToken();
|
|
4
|
+
const response = await fetch('https://cloudbilling.googleapis.com/v1/billingAccounts', {
|
|
5
|
+
headers: {
|
|
6
|
+
'Authorization': `Bearer ${token}`,
|
|
7
|
+
'Content-Type': 'application/json',
|
|
8
|
+
'x-goog-user-project': projectId,
|
|
9
|
+
},
|
|
10
|
+
});
|
|
11
|
+
if (!response.ok) {
|
|
12
|
+
const err = await response.text();
|
|
13
|
+
throw new Error(`Failed to list billing accounts (${response.status}): ${err}`);
|
|
14
|
+
}
|
|
15
|
+
const data = await response.json();
|
|
16
|
+
return data.billingAccounts || [];
|
|
17
|
+
}
|
|
18
|
+
export async function getBillingInfo(auth, projectId) {
|
|
19
|
+
return gcpFetch(auth, `https://cloudbilling.googleapis.com/v1/projects/${projectId}/billingInfo`, {
|
|
20
|
+
headers: { 'x-goog-user-project': projectId },
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
export async function linkBillingAccount(auth, projectId, billingAccountId) {
|
|
24
|
+
await gcpFetch(auth, `https://cloudbilling.googleapis.com/v1/projects/${projectId}/billingInfo`, {
|
|
25
|
+
method: 'PUT',
|
|
26
|
+
body: { billingAccountName: `billingAccounts/${billingAccountId}` },
|
|
27
|
+
headers: { 'x-goog-user-project': projectId },
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
export async function isBillingEnabled(auth, projectId) {
|
|
31
|
+
try {
|
|
32
|
+
const info = await getBillingInfo(auth, projectId);
|
|
33
|
+
return !!info.billingAccountName;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export async function enableBillingApi(auth, projectId) {
|
|
40
|
+
try {
|
|
41
|
+
await gcpFetch(auth, `https://serviceusage.googleapis.com/v1/projects/${projectId}/services/cloudbilling.googleapis.com:enable`, {
|
|
42
|
+
method: 'POST',
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// May already be enabled
|
|
47
|
+
}
|
|
48
|
+
// Poll for propagation
|
|
49
|
+
for (let i = 0; i < 24; i++) {
|
|
50
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
51
|
+
try {
|
|
52
|
+
const accounts = await fetchBillingAccounts(auth, projectId);
|
|
53
|
+
if (accounts.length > 0)
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// Not ready yet
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AuthClient } from './auth.js';
|
|
2
|
+
export declare function listFirebaseProjects(auth: AuthClient): Promise<any[]>;
|
|
3
|
+
export declare function addFirebaseToProject(auth: AuthClient, projectId: string): Promise<boolean>;
|
|
4
|
+
export declare function listWebApps(auth: AuthClient, projectId: string): Promise<any[]>;
|
|
5
|
+
export declare function createWebApp(auth: AuthClient, projectId: string, displayName: string): Promise<any>;
|
|
6
|
+
export declare function getWebAppConfig(auth: AuthClient, projectId: string, appId: string): Promise<Record<string, string>>;
|
|
7
|
+
export declare function updateAuthDomains(auth: AuthClient, projectId: string, domains: string[]): Promise<void>;
|
|
8
|
+
export interface FirebaseSetupResult {
|
|
9
|
+
projectId: string;
|
|
10
|
+
config: Record<string, string>;
|
|
11
|
+
appId: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function setupFirebaseProject(auth: AuthClient, gcpProjectId: string, displayName: string): Promise<FirebaseSetupResult>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { gcpFetch } from './gcp.js';
|
|
2
|
+
export async function listFirebaseProjects(auth) {
|
|
3
|
+
const data = await gcpFetch(auth, 'https://firebase.googleapis.com/v1beta1/projects');
|
|
4
|
+
return data.results || [];
|
|
5
|
+
}
|
|
6
|
+
export async function addFirebaseToProject(auth, projectId) {
|
|
7
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
8
|
+
try {
|
|
9
|
+
await gcpFetch(auth, `https://firebase.googleapis.com/v1beta1/projects/${projectId}:addFirebase`, {
|
|
10
|
+
method: 'POST',
|
|
11
|
+
});
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
catch (e) {
|
|
15
|
+
if (e.message?.includes('ALREADY_EXISTS') || e.message?.includes('already exist') || e.message?.includes('INVALID_ARGUMENT'))
|
|
16
|
+
return true;
|
|
17
|
+
if (e.message?.includes('403') && attempt < 5) {
|
|
18
|
+
await new Promise((r) => setTimeout(r, 5000 * (attempt + 1)));
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
throw e;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
export async function listWebApps(auth, projectId) {
|
|
27
|
+
const data = await gcpFetch(auth, `https://firebase.googleapis.com/v1beta1/projects/${projectId}/webApps`);
|
|
28
|
+
return data.apps || [];
|
|
29
|
+
}
|
|
30
|
+
export async function createWebApp(auth, projectId, displayName) {
|
|
31
|
+
try {
|
|
32
|
+
return await gcpFetch(auth, `https://firebase.googleapis.com/v1beta1/projects/${projectId}/webApps`, {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
body: { displayName },
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
catch (e) {
|
|
38
|
+
if (e.message?.includes('ALREADY_EXISTS') || e.message?.includes('already exist')) {
|
|
39
|
+
const apps = await listWebApps(auth, projectId);
|
|
40
|
+
const existing = apps.find((a) => a.displayName === displayName);
|
|
41
|
+
if (existing)
|
|
42
|
+
return existing;
|
|
43
|
+
}
|
|
44
|
+
throw e;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export async function getWebAppConfig(auth, projectId, appId) {
|
|
48
|
+
return gcpFetch(auth, `https://firebase.googleapis.com/v1beta1/projects/${projectId}/webApps/${appId}/config`);
|
|
49
|
+
}
|
|
50
|
+
export async function updateAuthDomains(auth, projectId, domains) {
|
|
51
|
+
try {
|
|
52
|
+
const config = await gcpFetch(auth, `https://identitytoolkit.googleapis.com/v2/projects/${projectId}/config`);
|
|
53
|
+
const existing = config.authorizedDomains || [];
|
|
54
|
+
const merged = [...new Set([...existing, ...domains])];
|
|
55
|
+
await gcpFetch(auth, `https://identitytoolkit.googleapis.com/v2/projects/${projectId}/config?updateMask=authorizedDomains`, {
|
|
56
|
+
method: 'PATCH',
|
|
57
|
+
body: { authorizedDomains: merged },
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// Identity Toolkit may not be enabled yet
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export async function setupFirebaseProject(auth, gcpProjectId, displayName) {
|
|
65
|
+
// Add Firebase to the GCP project
|
|
66
|
+
await addFirebaseToProject(auth, gcpProjectId);
|
|
67
|
+
// Wait for Firebase to be ready
|
|
68
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
69
|
+
// Create or find web app
|
|
70
|
+
let apps = await listWebApps(auth, gcpProjectId);
|
|
71
|
+
let webApp = apps.find((a) => a.displayName === displayName);
|
|
72
|
+
if (!webApp) {
|
|
73
|
+
webApp = await createWebApp(auth, gcpProjectId, displayName);
|
|
74
|
+
}
|
|
75
|
+
// Get SDK config
|
|
76
|
+
const config = await getWebAppConfig(auth, gcpProjectId, webApp.appId);
|
|
77
|
+
// Update auth domains
|
|
78
|
+
await updateAuthDomains(auth, gcpProjectId, [
|
|
79
|
+
'localhost',
|
|
80
|
+
'*.web.app',
|
|
81
|
+
'*.firebaseapp.com',
|
|
82
|
+
]);
|
|
83
|
+
return { projectId: gcpProjectId, config, appId: webApp.appId };
|
|
84
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AuthClient } from './auth.js';
|
|
2
|
+
export declare function gcpFetch(auth: AuthClient, url: string, opts?: {
|
|
3
|
+
method?: string;
|
|
4
|
+
body?: any;
|
|
5
|
+
headers?: Record<string, string>;
|
|
6
|
+
}): Promise<any>;
|
|
7
|
+
export declare function listProjects(auth: AuthClient): Promise<any[]>;
|
|
8
|
+
export declare function createProject(auth: AuthClient, projectId: string, displayName: string): Promise<any>;
|
|
9
|
+
export declare function getProject(auth: AuthClient, projectId: string): Promise<any | null>;
|
|
10
|
+
export declare function enableApi(auth: AuthClient, projectId: string, apiName: string): Promise<void>;
|
|
11
|
+
export declare function checkApiEnabled(auth: AuthClient, projectId: string, apiName: string): Promise<boolean>;
|
|
12
|
+
export declare function createServiceAccount(auth: AuthClient, projectId: string, accountId: string, displayName: string): Promise<{
|
|
13
|
+
email: string;
|
|
14
|
+
}>;
|
|
15
|
+
export declare function grantRole(auth: AuthClient, resource: string, member: string, role: string): Promise<void>;
|
|
16
|
+
export declare function createVm(auth: AuthClient, projectId: string, zone: string, instanceName: string, metadata: Record<string, string>): Promise<{
|
|
17
|
+
ip: string;
|
|
18
|
+
zone: string;
|
|
19
|
+
}>;
|
|
20
|
+
export declare function deleteVm(auth: AuthClient, projectId: string, zone: string, instanceName: string): Promise<void>;
|
|
21
|
+
export declare function cleanupVmByName(auth: AuthClient, projectId: string, instanceName: string): Promise<void>;
|
|
22
|
+
export declare function fetchVmLogs(auth: AuthClient, projectId: string, zone: string, instanceName: string): Promise<string>;
|
package/dist/lib/gcp.js
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
export async function gcpFetch(auth, url, opts) {
|
|
2
|
+
const token = await auth.getToken();
|
|
3
|
+
const method = opts?.method || 'GET';
|
|
4
|
+
const hasBody = opts?.body != null;
|
|
5
|
+
const headers = {
|
|
6
|
+
'Authorization': `Bearer ${token}`,
|
|
7
|
+
...opts?.headers,
|
|
8
|
+
};
|
|
9
|
+
if (hasBody) {
|
|
10
|
+
headers['Content-Type'] = 'application/json';
|
|
11
|
+
}
|
|
12
|
+
const response = await fetch(url, {
|
|
13
|
+
method,
|
|
14
|
+
headers,
|
|
15
|
+
body: hasBody ? JSON.stringify(opts.body) : undefined,
|
|
16
|
+
});
|
|
17
|
+
if (!response.ok) {
|
|
18
|
+
const err = await response.text().catch(() => response.statusText);
|
|
19
|
+
throw new Error(`GCP API error (${response.status}): ${err}`);
|
|
20
|
+
}
|
|
21
|
+
if (response.status === 204)
|
|
22
|
+
return {};
|
|
23
|
+
const text = await response.text();
|
|
24
|
+
return text ? JSON.parse(text) : {};
|
|
25
|
+
}
|
|
26
|
+
export async function listProjects(auth) {
|
|
27
|
+
const data = await gcpFetch(auth, 'https://cloudresourcemanager.googleapis.com/v1/projects');
|
|
28
|
+
return data.projects || [];
|
|
29
|
+
}
|
|
30
|
+
export async function createProject(auth, projectId, displayName) {
|
|
31
|
+
return gcpFetch(auth, 'https://cloudresourcemanager.googleapis.com/v1/projects', {
|
|
32
|
+
method: 'POST',
|
|
33
|
+
body: { projectId, name: displayName },
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
export async function getProject(auth, projectId) {
|
|
37
|
+
try {
|
|
38
|
+
return await gcpFetch(auth, `https://cloudresourcemanager.googleapis.com/v1/projects/${projectId}`);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export async function enableApi(auth, projectId, apiName) {
|
|
45
|
+
const url = `https://serviceusage.googleapis.com/v1/projects/${projectId}/services/${apiName}:enable`;
|
|
46
|
+
try {
|
|
47
|
+
await gcpFetch(auth, url, { method: 'POST', body: {} });
|
|
48
|
+
}
|
|
49
|
+
catch (e) {
|
|
50
|
+
if (!e.message?.includes('already enabled'))
|
|
51
|
+
throw e;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export async function checkApiEnabled(auth, projectId, apiName) {
|
|
55
|
+
try {
|
|
56
|
+
const result = await gcpFetch(auth, `https://serviceusage.googleapis.com/v1/projects/${projectId}/services/${apiName}`);
|
|
57
|
+
return result.state === 'ENABLED';
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export async function createServiceAccount(auth, projectId, accountId, displayName) {
|
|
64
|
+
const url = `https://iam.googleapis.com/v1/projects/${projectId}/serviceAccounts`;
|
|
65
|
+
try {
|
|
66
|
+
const sa = await gcpFetch(auth, url, {
|
|
67
|
+
method: 'POST',
|
|
68
|
+
body: { accountId, serviceAccount: { displayName } },
|
|
69
|
+
});
|
|
70
|
+
return { email: sa.email };
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
if (e.message?.includes('409')) {
|
|
74
|
+
const email = `${accountId}@${projectId}.iam.gserviceaccount.com`;
|
|
75
|
+
return { email };
|
|
76
|
+
}
|
|
77
|
+
throw e;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
export async function grantRole(auth, resource, member, role) {
|
|
81
|
+
const url = `https://cloudresourcemanager.googleapis.com/v1/${resource}:getIamPolicy`;
|
|
82
|
+
const policy = await gcpFetch(auth, url, { method: 'POST' });
|
|
83
|
+
const bindings = policy.bindings || [];
|
|
84
|
+
const existing = bindings.find((b) => b.role === role);
|
|
85
|
+
if (!existing) {
|
|
86
|
+
bindings.push({ role, members: [member] });
|
|
87
|
+
}
|
|
88
|
+
else if (!existing.members.includes(member)) {
|
|
89
|
+
existing.members.push(member);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
return; // Already has the role
|
|
93
|
+
}
|
|
94
|
+
const setUrl = `https://cloudresourcemanager.googleapis.com/v1/${resource}:setIamPolicy`;
|
|
95
|
+
await gcpFetch(auth, setUrl, {
|
|
96
|
+
method: 'POST',
|
|
97
|
+
body: { policy: { bindings, etag: policy.etag } },
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
export async function createVm(auth, projectId, zone, instanceName, metadata) {
|
|
101
|
+
const url = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances`;
|
|
102
|
+
const body = {
|
|
103
|
+
name: instanceName,
|
|
104
|
+
machineType: `zones/${zone}/machineTypes/e2-medium`,
|
|
105
|
+
disks: [
|
|
106
|
+
{
|
|
107
|
+
boot: true,
|
|
108
|
+
autoDelete: true,
|
|
109
|
+
initializeParams: {
|
|
110
|
+
sourceImage: 'projects/debian-cloud/global/images/family/debian-11',
|
|
111
|
+
diskSizeGb: '10',
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
],
|
|
115
|
+
networkInterfaces: [
|
|
116
|
+
{
|
|
117
|
+
network: 'global/networks/default',
|
|
118
|
+
accessConfigs: [{ type: 'ONE_TO_ONE_NAT', name: 'External NAT' }],
|
|
119
|
+
},
|
|
120
|
+
],
|
|
121
|
+
metadata: {
|
|
122
|
+
items: Object.entries(metadata).map(([key, value]) => ({
|
|
123
|
+
key,
|
|
124
|
+
value,
|
|
125
|
+
})),
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
// Try to delete any existing VM with this name in the target zone
|
|
129
|
+
const existingUrl = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`;
|
|
130
|
+
try {
|
|
131
|
+
await gcpFetch(auth, existingUrl, { method: 'DELETE' });
|
|
132
|
+
// Poll until deletion completes (up to 3 min)
|
|
133
|
+
for (let d = 0; d < 36; d++) {
|
|
134
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
135
|
+
try {
|
|
136
|
+
await gcpFetch(auth, existingUrl);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
break; // Gone
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// VM doesn't exist — that's fine
|
|
145
|
+
}
|
|
146
|
+
const result = await gcpFetch(auth, url, { method: 'POST', body });
|
|
147
|
+
// Poll until VM is RUNNING (up to 10 minutes)
|
|
148
|
+
for (let i = 0; i < 120; i++) {
|
|
149
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
150
|
+
try {
|
|
151
|
+
const instance = await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`);
|
|
152
|
+
if (instance.status === 'RUNNING') {
|
|
153
|
+
const ip = instance.networkInterfaces?.[0]?.accessConfigs?.[0]?.natIP;
|
|
154
|
+
return { ip, zone };
|
|
155
|
+
}
|
|
156
|
+
if (instance.status === 'STOPPING' || instance.status === 'TERMINATED') {
|
|
157
|
+
// VM is dying — abort early, delete it, and let the caller try the next zone
|
|
158
|
+
console.log(` VM is ${instance.status}, aborting and trying next zone...`);
|
|
159
|
+
try {
|
|
160
|
+
await gcpFetch(auth, existingUrl, { method: 'DELETE' });
|
|
161
|
+
}
|
|
162
|
+
catch { }
|
|
163
|
+
throw new Error(`VM entered ${instance.status} state`);
|
|
164
|
+
}
|
|
165
|
+
if (i % 6 === 0) {
|
|
166
|
+
console.log(` VM status: ${instance.status} (attempt ${i + 1}/120)`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
catch (e) {
|
|
170
|
+
if (e.message?.includes('aborting') || e.message?.includes('STOPPING') || e.message?.includes('TERMINATED'))
|
|
171
|
+
throw e;
|
|
172
|
+
// Instance not yet available
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
throw new Error('VM did not start within 10 minutes');
|
|
176
|
+
}
|
|
177
|
+
export async function deleteVm(auth, projectId, zone, instanceName) {
|
|
178
|
+
try {
|
|
179
|
+
await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`, { method: 'DELETE' });
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
// VM may not exist
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
export async function cleanupVmByName(auth, projectId, instanceName) {
|
|
186
|
+
const zones = [
|
|
187
|
+
'us-central1-a', 'us-central1-b', 'us-central1-c',
|
|
188
|
+
'us-west1-a', 'us-west1-b',
|
|
189
|
+
'us-east1-b', 'us-east1-c', 'us-east1-d',
|
|
190
|
+
'europe-west1-b', 'europe-west1-c', 'europe-west1-d',
|
|
191
|
+
'asia-east1-a',
|
|
192
|
+
];
|
|
193
|
+
for (const zone of zones) {
|
|
194
|
+
try {
|
|
195
|
+
const inst = await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`);
|
|
196
|
+
if (inst && inst.status) {
|
|
197
|
+
console.log(` Found existing VM "${instanceName}" in ${zone} (${inst.status}), deleting...`);
|
|
198
|
+
await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`, { method: 'DELETE' });
|
|
199
|
+
// Poll until deletion completes (up to 3 min)
|
|
200
|
+
for (let d = 0; d < 36; d++) {
|
|
201
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
202
|
+
try {
|
|
203
|
+
await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}`);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
break; // Deleted
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
catch (e) {
|
|
212
|
+
// VM not in this zone (404) or other error
|
|
213
|
+
if (e.message && !e.message.includes('404')) {
|
|
214
|
+
console.log(` Warning: failed to check zone ${zone}: ${e.message}`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
export async function fetchVmLogs(auth, projectId, zone, instanceName) {
|
|
220
|
+
const result = await gcpFetch(auth, `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances/${instanceName}/serialPort?port=1`);
|
|
221
|
+
return (result.contents || '').split('\n').map((l) => atob(l)).join('\n');
|
|
222
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AuthClient } from './auth.js';
|
|
2
|
+
export declare function githubFetch(pat: string, path: string, opts?: {
|
|
3
|
+
method?: string;
|
|
4
|
+
body?: any;
|
|
5
|
+
}): Promise<any>;
|
|
6
|
+
export declare function validatePat(pat: string): Promise<{
|
|
7
|
+
login: string;
|
|
8
|
+
scopes: string[];
|
|
9
|
+
}>;
|
|
10
|
+
export declare function ensureRepo(pat: string, repoFull: string): Promise<void>;
|
|
11
|
+
export declare function setGitHubVariable(pat: string, repoFull: string, name: string, value: string): Promise<void>;
|
|
12
|
+
export declare function setupOidc(auth: AuthClient, projectId: string, repoFullName: string): Promise<{
|
|
13
|
+
wifPoolName: string;
|
|
14
|
+
wifProviderName: string;
|
|
15
|
+
saStagingEmail: string;
|
|
16
|
+
saProductionEmail: string;
|
|
17
|
+
}>;
|