-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathprovision-cli.js
More file actions
168 lines (149 loc) · 5.58 KB
/
provision-cli.js
File metadata and controls
168 lines (149 loc) · 5.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env node
/**
* Provisioning CLI: the standalone runner for the owned, GitHub-native
* provisioning subsystem. Reads the roster of record, provisions every
* pending/failed learner idempotently, writes the roster back, and appends to
* the provisioning log. See SPEC.md sections 7 and 16, and admin/OWNED_PROVISIONING.md.
*
* Modes (PROVISIONING_MODE):
* github-app (production) mints a short-lived installation token from
* PROVISIONING_APP_ID + PROVISIONING_APP_PRIVATE_KEY
* + PROVISIONING_APP_INSTALLATION_ID.
* actions-bot (Phase 1 spike only) uses PROVISIONING_TOKEN, a least-privilege
* fine-grained PAT.
*
* Usage:
* node provision-cli.js --roster path/to/roster.json [--log path/to/log.json] [--dry-run]
*
* No third-party dependencies: uses Node built-ins and global fetch.
*/
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { parseRoster, serializeRoster } = require('./roster');
const { provisionRoster } = require('./provision-core');
const { createFetchClient, REQUIRED_WORKFLOWS } = require('./github-client');
const { mintInstallationToken } = require('./github-app-auth');
function parseArgs(argv) {
const args = { dryRun: false };
for (let i = 0; i < argv.length; i += 1) {
const a = argv[i];
if (a === '--roster') args.roster = argv[++i];
else if (a === '--log') args.log = argv[++i];
else if (a === '--dry-run') args.dryRun = true;
else if (a === '--help' || a === '-h') args.help = true;
}
return args;
}
function usage() {
return [
'Usage: node provision-cli.js --roster <file> [--log <file>] [--dry-run]',
'',
'Environment:',
' PROVISIONING_MODE github-app | actions-bot',
' LEARNING_ROOM_TEMPLATE_REPO owner/name of the template (required)',
' PROVISIONING_STUDENT_OWNER org/user that owns student repos (required)',
' GITHUB_API_URL default https://api.github.com',
' github-app mode:',
' PROVISIONING_APP_ID',
' PROVISIONING_APP_PRIVATE_KEY (PEM, or @path to a PEM file)',
' PROVISIONING_APP_INSTALLATION_ID',
' actions-bot mode:',
' PROVISIONING_TOKEN'
].join('\n');
}
function readPrivateKey(value) {
if (!value) return value;
if (value.startsWith('@')) {
return fs.readFileSync(value.slice(1), 'utf8');
}
// Support keys passed with literal \n escapes (common in CI secrets).
return value.includes('\\n') && !value.includes('\n')
? value.replace(/\\n/g, '\n')
: value;
}
async function resolveToken(env, apiBaseUrl) {
const mode = env.PROVISIONING_MODE || 'github-app';
if (mode === 'actions-bot') {
if (!env.PROVISIONING_TOKEN) throw new Error('actions-bot mode requires PROVISIONING_TOKEN');
return env.PROVISIONING_TOKEN;
}
if (mode === 'github-app') {
const { token } = await mintInstallationToken({
appId: env.PROVISIONING_APP_ID,
privateKey: readPrivateKey(env.PROVISIONING_APP_PRIVATE_KEY),
installationId: env.PROVISIONING_APP_INSTALLATION_ID,
apiBaseUrl
});
return token;
}
throw new Error(`Unknown PROVISIONING_MODE: ${mode}`);
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help || !args.roster) {
process.stdout.write(`${usage()}\n`);
process.exit(args.help ? 0 : 2);
}
const env = process.env;
const apiBaseUrl = env.GITHUB_API_URL || 'https://api.github.com';
const templateRepoFull = env.LEARNING_ROOM_TEMPLATE_REPO;
const studentOwner = env.PROVISIONING_STUDENT_OWNER;
if (!templateRepoFull) throw new Error('LEARNING_ROOM_TEMPLATE_REPO is required');
if (!studentOwner) throw new Error('PROVISIONING_STUDENT_OWNER is required');
const [templateOwner, templateRepo] = templateRepoFull.split('/');
if (!templateOwner || !templateRepo) {
throw new Error('LEARNING_ROOM_TEMPLATE_REPO must be owner/name');
}
const rosterJson = fs.readFileSync(args.roster, 'utf8');
const roster = parseRoster(rosterJson);
if (args.dryRun) {
const { entriesToProvision } = require('./roster');
const targets = entriesToProvision(roster);
process.stdout.write(
`Dry run: ${targets.length} learner(s) would be provisioned:\n` +
targets.map((t) => ` - ${t.github_handle} (${t.cohort_id})`).join('\n') +
'\n'
);
return;
}
const token = await resolveToken(env, apiBaseUrl);
const client = createFetchClient({ token, apiBaseUrl });
const { roster: updated, log, summary } = await provisionRoster({
roster,
client,
config: {
studentOwner,
templateOwner,
templateRepo,
requiredWorkflows: REQUIRED_WORKFLOWS
},
logger: (msg) => process.stdout.write(`${msg}\n`)
});
fs.writeFileSync(args.roster, serializeRoster(updated));
if (args.log) {
appendLog(args.log, log);
}
process.stdout.write(`\nProvisioning summary: ${JSON.stringify(summary)}\n`);
if (summary.error > 0) {
process.exitCode = 1;
}
}
function appendLog(logPath, entries) {
let existing = [];
if (fs.existsSync(logPath)) {
const raw = fs.readFileSync(logPath, 'utf8').trim();
if (raw) existing = JSON.parse(raw);
} else {
fs.mkdirSync(path.dirname(logPath), { recursive: true });
}
const merged = existing.concat(entries);
fs.writeFileSync(logPath, `${JSON.stringify(merged, null, 2)}\n`);
}
if (require.main === module) {
main().catch((err) => {
process.stderr.write(`Provisioning failed: ${err.message}\n`);
process.exit(1);
});
}
module.exports = { parseArgs, resolveToken, readPrivateKey, usage };