runcloud 0.2.241 → 0.2.244
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/README.md +14 -0
- package/dist/commands/credentials.js +494 -0
- package/dist/commands/run-cloud.js +39 -10
- package/dist/commands/sandbox.js +3 -0
- package/dist/config.js +4 -1
- package/dist/credentials/agent.js +180 -0
- package/dist/credentials/config.js +304 -0
- package/dist/credentials/engine.js +209 -0
- package/dist/credentials/install.js +160 -0
- package/dist/credentials/items.js +232 -0
- package/dist/credentials/lockFile.js +23 -0
- package/dist/credentials/presets.js +106 -0
- package/dist/credentials/privateFile.js +10 -0
- package/dist/credentials/schedule.js +26 -0
- package/dist/credentials/state.js +83 -0
- package/dist/credentials/status.js +69 -0
- package/dist/credentials/tokenStore.js +87 -0
- package/dist/run-cloud.js +2 -0
- package/dist/version.js +1 -1
- package/package.json +3 -2
- package/runcloud-0.2.244.tgz +0 -0
- package/runcloud-0.2.241.tgz +0 -0
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { credentialsHome, loadCredentials, loadStoredCredentials } from '../config.js';
|
|
5
|
+
import { liveLockHolder } from './lockFile.js';
|
|
6
|
+
import { shellQuote } from './tokenStore.js';
|
|
7
|
+
const LABEL = 'cloud.run.credentials';
|
|
8
|
+
const SYSTEMD_UNIT = 'runcloud-credentials.service';
|
|
9
|
+
const COMMAND_TIMEOUT_MS = 15_000;
|
|
10
|
+
export function agentLogPath() {
|
|
11
|
+
return join(credentialsHome(), 'logs', 'credentials.log');
|
|
12
|
+
}
|
|
13
|
+
export function agentLockPath() {
|
|
14
|
+
return join(credentialsHome(), 'credentials-agent.lock');
|
|
15
|
+
}
|
|
16
|
+
function scriptArgument() {
|
|
17
|
+
const script = process.argv[1];
|
|
18
|
+
if (!script || script.startsWith('/$bunfs/'))
|
|
19
|
+
return [];
|
|
20
|
+
try {
|
|
21
|
+
const real = realpathSync(script);
|
|
22
|
+
if (!statSync(real).isFile() || real === realpathSync(process.execPath))
|
|
23
|
+
return [];
|
|
24
|
+
return [real];
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function agentProgram() {
|
|
31
|
+
return [process.execPath, ...scriptArgument(), 'credentials', 'sync', '--log-only'];
|
|
32
|
+
}
|
|
33
|
+
const xml = (text) => text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
34
|
+
export function renderLaunchdPlist(o) {
|
|
35
|
+
const env = [` <key>PATH</key>\n <string>${xml(o.path)}</string>`];
|
|
36
|
+
if (o.runCloudHome)
|
|
37
|
+
env.push(` <key>RUN_CLOUD_HOME</key>\n <string>${xml(o.runCloudHome)}</string>`);
|
|
38
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
39
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
40
|
+
<plist version="1.0">
|
|
41
|
+
<dict>
|
|
42
|
+
<key>Label</key>
|
|
43
|
+
<string>${LABEL}</string>
|
|
44
|
+
<key>ProgramArguments</key>
|
|
45
|
+
<array>
|
|
46
|
+
${o.program.map((arg) => ` <string>${xml(arg)}</string>`).join('\n')}
|
|
47
|
+
</array>
|
|
48
|
+
<key>EnvironmentVariables</key>
|
|
49
|
+
<dict>
|
|
50
|
+
${env.join('\n')}
|
|
51
|
+
</dict>
|
|
52
|
+
<key>RunAtLoad</key>
|
|
53
|
+
<true/>
|
|
54
|
+
<key>KeepAlive</key>
|
|
55
|
+
<true/>
|
|
56
|
+
<key>ThrottleInterval</key>
|
|
57
|
+
<integer>60</integer>
|
|
58
|
+
<key>StandardOutPath</key>
|
|
59
|
+
<string>${xml(`${o.logPath}.stdio`)}</string>
|
|
60
|
+
<key>StandardErrorPath</key>
|
|
61
|
+
<string>${xml(`${o.logPath}.stdio`)}</string>
|
|
62
|
+
</dict>
|
|
63
|
+
</plist>
|
|
64
|
+
`;
|
|
65
|
+
}
|
|
66
|
+
const systemdQuote = (arg) => `"${arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
|
|
67
|
+
const systemdEnv = (name, value) => {
|
|
68
|
+
const text = `${name}=${value.replace(/%/g, '%%')}`;
|
|
69
|
+
return /[\s"\\]/.test(text) ? `Environment=${systemdQuote(text.replace(/%%/g, '%'))}` : `Environment=${text}`;
|
|
70
|
+
};
|
|
71
|
+
export function renderSystemdUnit(o) {
|
|
72
|
+
const lines = [systemdEnv('PATH', o.path)];
|
|
73
|
+
if (o.runCloudHome)
|
|
74
|
+
lines.push(systemdEnv('RUN_CLOUD_HOME', o.runCloudHome));
|
|
75
|
+
return `[Unit]
|
|
76
|
+
Description=run.cloud credentials sync agent
|
|
77
|
+
|
|
78
|
+
[Service]
|
|
79
|
+
ExecStart=${o.program.map(systemdQuote).join(' ')}
|
|
80
|
+
${lines.join('\n')}
|
|
81
|
+
Restart=on-failure
|
|
82
|
+
RestartSec=30
|
|
83
|
+
|
|
84
|
+
[Install]
|
|
85
|
+
WantedBy=default.target
|
|
86
|
+
`;
|
|
87
|
+
}
|
|
88
|
+
export function loginProblemForAgent() {
|
|
89
|
+
const stored = loadStoredCredentials();
|
|
90
|
+
if (stored && stored.expiresAt === Number.MAX_SAFE_INTEGER)
|
|
91
|
+
return null;
|
|
92
|
+
if (!stored && loadCredentials()) {
|
|
93
|
+
return 'The background agent cannot see environment variables, so a token set there is not enough. '
|
|
94
|
+
+ 'Run: runcloud token create, then runcloud login --token <token>';
|
|
95
|
+
}
|
|
96
|
+
return 'The background agent needs a login that does not expire. Run: runcloud token create, then runcloud login --token <token>';
|
|
97
|
+
}
|
|
98
|
+
function unitPath(platform, home) {
|
|
99
|
+
if (platform === 'darwin')
|
|
100
|
+
return join(home, 'Library', 'LaunchAgents', `${LABEL}.plist`);
|
|
101
|
+
if (platform === 'linux')
|
|
102
|
+
return join(home, '.config', 'systemd', 'user', SYSTEMD_UNIT);
|
|
103
|
+
throw new Error('runcloud credentials supports macOS and Linux.');
|
|
104
|
+
}
|
|
105
|
+
const uid = () => process.getuid?.() ?? 0;
|
|
106
|
+
const quoteArg = (arg) => (/^[\w@%+=:,./-]+$/.test(arg) ? arg : shellQuote(arg));
|
|
107
|
+
async function exec(run, command) {
|
|
108
|
+
return run(command, { timeoutMs: COMMAND_TIMEOUT_MS });
|
|
109
|
+
}
|
|
110
|
+
function writeUnit(path, text) {
|
|
111
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
112
|
+
writeFileSync(path, text, { mode: 0o644 });
|
|
113
|
+
chmodSync(path, 0o644);
|
|
114
|
+
}
|
|
115
|
+
export async function installAgent(run, platform = process.platform, home = homedir()) {
|
|
116
|
+
const path = unitPath(platform, home);
|
|
117
|
+
const options = {
|
|
118
|
+
program: agentProgram(),
|
|
119
|
+
path: process.env.PATH ?? '',
|
|
120
|
+
...(process.env.RUN_CLOUD_HOME && { runCloudHome: process.env.RUN_CLOUD_HOME }),
|
|
121
|
+
logPath: agentLogPath(),
|
|
122
|
+
};
|
|
123
|
+
mkdirSync(dirname(options.logPath), { recursive: true, mode: 0o700 });
|
|
124
|
+
if (platform === 'darwin') {
|
|
125
|
+
closeSync(openSync(`${options.logPath}.stdio`, 'a', 0o600));
|
|
126
|
+
chmodSync(`${options.logPath}.stdio`, 0o600);
|
|
127
|
+
writeUnit(path, renderLaunchdPlist(options));
|
|
128
|
+
const bootstrap = `launchctl bootstrap gui/${uid()} ${quoteArg(path)}`;
|
|
129
|
+
if ((await exec(run, bootstrap)).code === 0)
|
|
130
|
+
return;
|
|
131
|
+
await exec(run, `launchctl bootout gui/${uid()}/${LABEL}`);
|
|
132
|
+
if ((await exec(run, bootstrap)).code !== 0)
|
|
133
|
+
throw new Error('launchctl bootstrap failed');
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
writeUnit(path, renderSystemdUnit(options));
|
|
137
|
+
if ((await exec(run, 'systemctl --user daemon-reload')).code !== 0)
|
|
138
|
+
throw new Error('systemctl --user daemon-reload failed');
|
|
139
|
+
if ((await exec(run, `systemctl --user enable --now ${SYSTEMD_UNIT}`)).code !== 0) {
|
|
140
|
+
throw new Error(`systemctl --user enable --now ${SYSTEMD_UNIT} failed`);
|
|
141
|
+
}
|
|
142
|
+
await exec(run, `systemctl --user restart ${SYSTEMD_UNIT}`);
|
|
143
|
+
}
|
|
144
|
+
export async function uninstallAgent(run, platform = process.platform, home = homedir()) {
|
|
145
|
+
const path = unitPath(platform, home);
|
|
146
|
+
await exec(run, platform === 'darwin' ? `launchctl bootout gui/${uid()}/${LABEL}` : `systemctl --user disable --now ${SYSTEMD_UNIT}`);
|
|
147
|
+
rmSync(path, { force: true });
|
|
148
|
+
if (platform === 'linux')
|
|
149
|
+
await exec(run, 'systemctl --user daemon-reload');
|
|
150
|
+
}
|
|
151
|
+
export async function agentStatus(platform = process.platform, home = homedir()) {
|
|
152
|
+
let installed;
|
|
153
|
+
try {
|
|
154
|
+
installed = existsSync(unitPath(platform, home));
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return { installed: false, running: false };
|
|
158
|
+
}
|
|
159
|
+
return { installed, running: liveLockHolder(agentLockPath()) !== null };
|
|
160
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { basename, join } from 'node:path';
|
|
4
|
+
import { ENV_NAME_RE, envNameProblem, fileNameProblem, sandboxPathProblem, } from './config.js';
|
|
5
|
+
import { expandPreset, presetOptionsProblem } from './presets.js';
|
|
6
|
+
const MAX_VALUE_BYTES = 32 * 1024;
|
|
7
|
+
const DOTENV_LINE_RE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
|
|
8
|
+
export function parseDotenv(text) {
|
|
9
|
+
const values = {};
|
|
10
|
+
for (const [index, rawLine] of text.split(/\r?\n/).entries()) {
|
|
11
|
+
const line = rawLine.trim();
|
|
12
|
+
if (line === '' || line.startsWith('#'))
|
|
13
|
+
continue;
|
|
14
|
+
const at = `line ${index + 1}`;
|
|
15
|
+
const match = DOTENV_LINE_RE.exec(line);
|
|
16
|
+
if (!match || match[2].trimStart().startsWith('='))
|
|
17
|
+
return { problem: `${at} is not KEY=VALUE` };
|
|
18
|
+
const key = match[1];
|
|
19
|
+
let value = match[2].trim();
|
|
20
|
+
if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])) {
|
|
21
|
+
value = value.slice(1, -1);
|
|
22
|
+
}
|
|
23
|
+
if (value === '')
|
|
24
|
+
return { problem: `${at} has an empty value` };
|
|
25
|
+
const nameProblem = envNameProblem(key);
|
|
26
|
+
if (nameProblem) {
|
|
27
|
+
return { problem: ENV_NAME_RE.test(key) ? nameProblem : `${at}: a variable name must start with a letter and have at most 128 letters, digits or underscores` };
|
|
28
|
+
}
|
|
29
|
+
values[key] = value;
|
|
30
|
+
}
|
|
31
|
+
return { values };
|
|
32
|
+
}
|
|
33
|
+
export function fileSecretName(path) {
|
|
34
|
+
const base = basename(path);
|
|
35
|
+
return base.startsWith('.') ? `dot-${base.slice(1)}` : base;
|
|
36
|
+
}
|
|
37
|
+
export function groupItems(group) {
|
|
38
|
+
return group.entries.flatMap((e) => (e.kind === 'preset' ? expandPreset(e.preset, e.options) : [e]));
|
|
39
|
+
}
|
|
40
|
+
export function expandHome(path) {
|
|
41
|
+
if (path === '~')
|
|
42
|
+
return homedir();
|
|
43
|
+
return path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;
|
|
44
|
+
}
|
|
45
|
+
export function planNames(group) {
|
|
46
|
+
const plan = [];
|
|
47
|
+
const taken = new Set();
|
|
48
|
+
for (const [entryIndex, entry] of group.entries.entries()) {
|
|
49
|
+
if (entry.kind === 'preset' && presetOptionsProblem(entry.preset, entry.options)) {
|
|
50
|
+
plan.push({ entryIndex, names: null });
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
for (const item of entry.kind === 'preset' ? expandPreset(entry.preset, entry.options) : [entry]) {
|
|
54
|
+
const name = plannedName(item, taken);
|
|
55
|
+
if (name !== null)
|
|
56
|
+
taken.add(name);
|
|
57
|
+
plan.push({ entryIndex, names: name === null ? null : [name] });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return plan;
|
|
61
|
+
}
|
|
62
|
+
function plannedName(item, taken) {
|
|
63
|
+
if (item.kind === 'command' && item.format === 'dotenv')
|
|
64
|
+
return null;
|
|
65
|
+
if (item.env !== undefined)
|
|
66
|
+
return item.env;
|
|
67
|
+
if (item.to === undefined)
|
|
68
|
+
return null;
|
|
69
|
+
if (item.name !== undefined)
|
|
70
|
+
return item.name;
|
|
71
|
+
const base = fileSecretName(item.kind === 'file' ? item.from : item.to);
|
|
72
|
+
let name = base;
|
|
73
|
+
for (let n = 2; taken.has(name); n++)
|
|
74
|
+
name = `${base}-${n}`;
|
|
75
|
+
return name;
|
|
76
|
+
}
|
|
77
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
78
|
+
function decodeText(buffer) {
|
|
79
|
+
try {
|
|
80
|
+
return utf8.decode(buffer);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async function readItem(item, run, readFileFn) {
|
|
87
|
+
let value;
|
|
88
|
+
if (item.kind === 'file') {
|
|
89
|
+
let buffer;
|
|
90
|
+
try {
|
|
91
|
+
buffer = await readFileFn(expandHome(item.from));
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
return { failure: e.code === 'ENOENT' ? 'missing' : 'unreadable' };
|
|
95
|
+
}
|
|
96
|
+
if (buffer.length === 0)
|
|
97
|
+
return { failure: 'empty output' };
|
|
98
|
+
if (item.encoding === 'base64')
|
|
99
|
+
value = buffer.toString('base64');
|
|
100
|
+
else {
|
|
101
|
+
const text = decodeText(buffer);
|
|
102
|
+
if (text === null)
|
|
103
|
+
return { failure: 'not text; set encoding: base64' };
|
|
104
|
+
value = text;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
const result = await run(item.command, { timeoutMs: item.timeoutMs });
|
|
109
|
+
if (result.timedOut)
|
|
110
|
+
return { failure: 'timed out' };
|
|
111
|
+
if (result.code !== 0)
|
|
112
|
+
return { failure: `exit ${result.code}` };
|
|
113
|
+
if (result.stdout.trim() === '')
|
|
114
|
+
return { failure: 'empty output' };
|
|
115
|
+
if (item.format === 'dotenv') {
|
|
116
|
+
const parsed = parseDotenv(result.stdout);
|
|
117
|
+
if ('problem' in parsed)
|
|
118
|
+
return { failure: parsed.problem };
|
|
119
|
+
const pairs = Object.entries(parsed.values);
|
|
120
|
+
if (pairs.length === 0)
|
|
121
|
+
return { failure: 'empty output' };
|
|
122
|
+
const secrets = [];
|
|
123
|
+
for (const [key, v] of pairs) {
|
|
124
|
+
const problem = sizeProblem(v);
|
|
125
|
+
if (problem)
|
|
126
|
+
return { failure: problem };
|
|
127
|
+
secrets.push({ name: key, kind: 'env', value: v });
|
|
128
|
+
}
|
|
129
|
+
return { secrets };
|
|
130
|
+
}
|
|
131
|
+
value = result.stdout.replace(/(?:\r?\n)+$/, '');
|
|
132
|
+
}
|
|
133
|
+
const size = sizeProblem(value);
|
|
134
|
+
if (size)
|
|
135
|
+
return { failure: size };
|
|
136
|
+
if (item.env !== undefined) {
|
|
137
|
+
const problem = envNameProblem(item.env);
|
|
138
|
+
return problem ? { failure: problem } : { secrets: [{ name: item.env, kind: 'env', value }] };
|
|
139
|
+
}
|
|
140
|
+
if (item.to !== undefined) {
|
|
141
|
+
const problem = sandboxPathProblem(item.to);
|
|
142
|
+
if (problem)
|
|
143
|
+
return { failure: problem };
|
|
144
|
+
const name = item.name ?? fileSecretName(item.kind === 'file' ? item.from : item.to);
|
|
145
|
+
return { secrets: [{ name, kind: 'file', value, filePath: item.to }] };
|
|
146
|
+
}
|
|
147
|
+
return { failure: 'needs env or to' };
|
|
148
|
+
}
|
|
149
|
+
function sizeProblem(value) {
|
|
150
|
+
const bytes = Buffer.byteLength(value, 'utf8');
|
|
151
|
+
return bytes > MAX_VALUE_BYTES ? `value is ${bytes} bytes (limit ${MAX_VALUE_BYTES})` : null;
|
|
152
|
+
}
|
|
153
|
+
function describeEntry(entry) {
|
|
154
|
+
if (entry.kind === 'preset')
|
|
155
|
+
return `preset ${entry.preset}`;
|
|
156
|
+
return entry.kind === 'file' ? `file ${entry.from}` : 'command';
|
|
157
|
+
}
|
|
158
|
+
function targetName(item) {
|
|
159
|
+
return item.env ?? item.to ?? (item.kind === 'file' ? item.from : 'output');
|
|
160
|
+
}
|
|
161
|
+
export async function readGroup(group, run, readFileFn = (path) => readFile(path)) {
|
|
162
|
+
const read = { secrets: [], failures: [], warnings: [], allRead: true, itemNames: [] };
|
|
163
|
+
const plan = planNames(group);
|
|
164
|
+
let planned = 0;
|
|
165
|
+
const owners = new Map();
|
|
166
|
+
for (const [index, entry] of group.entries.entries()) {
|
|
167
|
+
const label = `group "${group.name}" entry ${index} (${describeEntry(entry)})`;
|
|
168
|
+
const fail = (problem) => {
|
|
169
|
+
read.failures.push(`${label}: ${problem}`);
|
|
170
|
+
read.allRead = false;
|
|
171
|
+
};
|
|
172
|
+
let items;
|
|
173
|
+
if (entry.kind === 'preset') {
|
|
174
|
+
const problem = presetOptionsProblem(entry.preset, entry.options);
|
|
175
|
+
if (problem) {
|
|
176
|
+
fail(problem);
|
|
177
|
+
read.itemNames.push({ ...plan[planned++], read: false });
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
items = expandPreset(entry.preset, entry.options);
|
|
181
|
+
}
|
|
182
|
+
else
|
|
183
|
+
items = [entry];
|
|
184
|
+
const names = items.map(() => ({ ...plan[planned++], read: true }));
|
|
185
|
+
const entrySecrets = [];
|
|
186
|
+
const taken = (name) => owners.has(name) || entrySecrets.some((s) => s.name === name);
|
|
187
|
+
let problem = null;
|
|
188
|
+
for (const [i, item] of items.entries()) {
|
|
189
|
+
const resolved = await readItem(item, run, readFileFn);
|
|
190
|
+
if ('failure' in resolved) {
|
|
191
|
+
names[i].read = false;
|
|
192
|
+
if (item.kind === 'command' && item.optional) {
|
|
193
|
+
read.warnings.push(`${label}: ${targetName(item)} not read (${resolved.failure})`);
|
|
194
|
+
read.allRead = false;
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
problem = resolved.failure;
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
const plannedNames = names[i].names;
|
|
201
|
+
if (plannedNames === null)
|
|
202
|
+
names[i].names = resolved.secrets.map((s) => s.name);
|
|
203
|
+
else
|
|
204
|
+
resolved.secrets[0].name = plannedNames[0];
|
|
205
|
+
for (const secret of resolved.secrets) {
|
|
206
|
+
if (secret.kind === 'file') {
|
|
207
|
+
problem = fileNameProblem(secret.name);
|
|
208
|
+
if (problem)
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
if (taken(secret.name)) {
|
|
212
|
+
problem = `duplicate name ${secret.name}, also used by ${owners.get(secret.name) ?? 'this entry'}`;
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
entrySecrets.push(secret);
|
|
216
|
+
}
|
|
217
|
+
if (problem)
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
read.itemNames.push(...names);
|
|
221
|
+
if (problem) {
|
|
222
|
+
fail(problem);
|
|
223
|
+
for (const n of names)
|
|
224
|
+
n.read = false;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
for (const secret of entrySecrets)
|
|
228
|
+
owners.set(secret.name, label);
|
|
229
|
+
read.secrets.push(...entrySecrets);
|
|
230
|
+
}
|
|
231
|
+
return read;
|
|
232
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
export function readLockPid(path) {
|
|
3
|
+
try {
|
|
4
|
+
const pid = Number.parseInt(readFileSync(path, 'utf8').trim(), 10);
|
|
5
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export function pidAlive(pid) {
|
|
12
|
+
try {
|
|
13
|
+
process.kill(pid, 0);
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
return error.code === 'EPERM';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function liveLockHolder(path) {
|
|
21
|
+
const pid = readLockPid(path);
|
|
22
|
+
return pid !== null && pidAlive(pid) ? pid : null;
|
|
23
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { claudeTokenReadCommand, shellQuote } from './tokenStore.js';
|
|
3
|
+
export const defaultRunCommand = (command, opts) => new Promise((resolve) => {
|
|
4
|
+
const child = spawn('/bin/sh', ['-c', command], { detached: true, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
5
|
+
let stdout = '';
|
|
6
|
+
let settled = false;
|
|
7
|
+
const settle = (value) => {
|
|
8
|
+
if (settled)
|
|
9
|
+
return;
|
|
10
|
+
settled = true;
|
|
11
|
+
clearTimeout(timer);
|
|
12
|
+
resolve(value);
|
|
13
|
+
};
|
|
14
|
+
const timer = setTimeout(() => {
|
|
15
|
+
try {
|
|
16
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
child.kill('SIGKILL');
|
|
20
|
+
}
|
|
21
|
+
settle({ code: null, stdout: '', timedOut: true });
|
|
22
|
+
}, opts.timeoutMs);
|
|
23
|
+
child.stdout.setEncoding('utf8');
|
|
24
|
+
child.stdout.on('data', (chunk) => {
|
|
25
|
+
stdout += chunk;
|
|
26
|
+
});
|
|
27
|
+
child.stdin.on('error', () => { });
|
|
28
|
+
child.on('error', () => settle({ code: null, stdout: '', timedOut: false }));
|
|
29
|
+
child.on('close', (code) => settle({ code, stdout, timedOut: false }));
|
|
30
|
+
child.stdin.end(opts.input);
|
|
31
|
+
});
|
|
32
|
+
const TIMEOUT_MS = 30_000;
|
|
33
|
+
const HOUR_MS = 3_600_000;
|
|
34
|
+
const AWS_REFRESH_MS = 1_800_000;
|
|
35
|
+
const KNOWN_OPTIONS = {
|
|
36
|
+
aws: ['profile'],
|
|
37
|
+
gcloud: [],
|
|
38
|
+
github: [],
|
|
39
|
+
claude: [],
|
|
40
|
+
};
|
|
41
|
+
function command(cmd, extra) {
|
|
42
|
+
return { kind: 'command', command: cmd, format: 'raw', timeoutMs: TIMEOUT_MS, ...extra };
|
|
43
|
+
}
|
|
44
|
+
export function expandPreset(id, options, platform = process.platform) {
|
|
45
|
+
switch (id) {
|
|
46
|
+
case 'aws': {
|
|
47
|
+
const profile = shellQuote(options.profile ?? 'default');
|
|
48
|
+
return [
|
|
49
|
+
command(`aws configure export-credentials --profile ${profile} --format env-no-export`, {
|
|
50
|
+
format: 'dotenv',
|
|
51
|
+
refreshMs: AWS_REFRESH_MS,
|
|
52
|
+
}),
|
|
53
|
+
command(`aws configure get region --profile ${profile}`, { env: 'AWS_REGION', refreshMs: HOUR_MS, optional: true }),
|
|
54
|
+
];
|
|
55
|
+
}
|
|
56
|
+
case 'gcloud': {
|
|
57
|
+
const adc = {
|
|
58
|
+
kind: 'file',
|
|
59
|
+
from: '~/.config/gcloud/application_default_credentials.json',
|
|
60
|
+
to: '.config/gcloud/application_default_credentials.json',
|
|
61
|
+
};
|
|
62
|
+
return [adc, command('gcloud config get-value project', { env: 'CLOUDSDK_CORE_PROJECT', refreshMs: HOUR_MS, optional: true })];
|
|
63
|
+
}
|
|
64
|
+
case 'github':
|
|
65
|
+
return [command('gh auth token', { env: 'GH_TOKEN', refreshMs: HOUR_MS })];
|
|
66
|
+
case 'claude':
|
|
67
|
+
return [command(claudeTokenReadCommand(platform), { env: 'CLAUDE_CODE_OAUTH_TOKEN', refreshMs: HOUR_MS })];
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export function presetOptionsProblem(id, options) {
|
|
71
|
+
const known = KNOWN_OPTIONS[id];
|
|
72
|
+
for (const key of Object.keys(options)) {
|
|
73
|
+
if (!known.includes(key)) {
|
|
74
|
+
const expected = known.length > 0 ? `expected ${known.join(', ')}` : 'it takes no options';
|
|
75
|
+
return `preset ${id} has no option "${key}" (${expected})`;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
export async function checkPresetReady(id, options, run) {
|
|
81
|
+
let probe;
|
|
82
|
+
let message;
|
|
83
|
+
switch (id) {
|
|
84
|
+
case 'gcloud':
|
|
85
|
+
probe = 'gcloud auth application-default print-access-token';
|
|
86
|
+
message = 'gcloud has no application default credentials. Run: gcloud auth application-default login';
|
|
87
|
+
break;
|
|
88
|
+
case 'aws': {
|
|
89
|
+
const profile = options.profile ?? 'default';
|
|
90
|
+
probe = `aws configure export-credentials --profile ${shellQuote(profile)} --format env-no-export`;
|
|
91
|
+
message = `aws has no usable credentials for profile ${profile}. Run: aws sso login --profile ${profile}`;
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
case 'github':
|
|
95
|
+
probe = 'gh auth token';
|
|
96
|
+
message = 'gh is not signed in. Run: gh auth login';
|
|
97
|
+
break;
|
|
98
|
+
case 'claude':
|
|
99
|
+
probe = claudeTokenReadCommand();
|
|
100
|
+
message = 'No Claude token is stored. Run: runcloud credentials add <group> claude';
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
const result = await run(probe, { timeoutMs: TIMEOUT_MS });
|
|
104
|
+
const ready = result.code === 0 && !result.timedOut && (id !== 'claude' || result.stdout.trim() !== '');
|
|
105
|
+
return ready ? null : message;
|
|
106
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
export function writePrivateFileAtomic(path, text) {
|
|
4
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
5
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
6
|
+
writeFileSync(tmp, '', { mode: 0o600 });
|
|
7
|
+
chmodSync(tmp, 0o600);
|
|
8
|
+
writeFileSync(tmp, text);
|
|
9
|
+
renameSync(tmp, path);
|
|
10
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { expandHome, groupItems } from './items.js';
|
|
2
|
+
import { groupKey } from './state.js';
|
|
3
|
+
export function effectiveOrg(config, group) {
|
|
4
|
+
return group.org ?? config.org;
|
|
5
|
+
}
|
|
6
|
+
export function groupKeyOf(config, name, org) {
|
|
7
|
+
return groupKey(org ?? config.org, name);
|
|
8
|
+
}
|
|
9
|
+
export function dueGroups(config, s, now, mtimes) {
|
|
10
|
+
const due = [];
|
|
11
|
+
for (const group of config.groups) {
|
|
12
|
+
const key = groupKeyOf(config, group.name, group.org);
|
|
13
|
+
const isDue = groupItems(group).some((item, index) => {
|
|
14
|
+
if (item.kind === 'command') {
|
|
15
|
+
const last = s.commandLastRun[`${key}#${index}`];
|
|
16
|
+
return last === undefined || now - last >= item.refreshMs;
|
|
17
|
+
}
|
|
18
|
+
const path = expandHome(item.from);
|
|
19
|
+
const mtime = mtimes[path];
|
|
20
|
+
return mtime !== undefined && mtime !== s.fileMtimes[path];
|
|
21
|
+
});
|
|
22
|
+
if (isDue)
|
|
23
|
+
due.push(key);
|
|
24
|
+
}
|
|
25
|
+
return due;
|
|
26
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { credentialsHome } from '../config.js';
|
|
5
|
+
import { pidAlive, readLockPid } from './lockFile.js';
|
|
6
|
+
import { writePrivateFileAtomic } from './privateFile.js';
|
|
7
|
+
export function groupKey(org, name) {
|
|
8
|
+
return `${org ?? ''}/${name}`;
|
|
9
|
+
}
|
|
10
|
+
export function parseGroupKey(key) {
|
|
11
|
+
const slash = key.lastIndexOf('/');
|
|
12
|
+
const org = key.slice(0, slash);
|
|
13
|
+
return { ...(org !== '' && { org }), name: key.slice(slash + 1) };
|
|
14
|
+
}
|
|
15
|
+
export function sha256(value) {
|
|
16
|
+
return createHash('sha256').update(value).digest('hex');
|
|
17
|
+
}
|
|
18
|
+
function statePath() {
|
|
19
|
+
return join(credentialsHome(), 'credentials-state.json');
|
|
20
|
+
}
|
|
21
|
+
export function loadState() {
|
|
22
|
+
const path = statePath();
|
|
23
|
+
if (!existsSync(path))
|
|
24
|
+
return { version: 1, groups: {} };
|
|
25
|
+
try {
|
|
26
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
27
|
+
if (parsed?.version !== 1 || typeof parsed.groups !== 'object' || parsed.groups === null) {
|
|
28
|
+
throw new Error('unexpected shape');
|
|
29
|
+
}
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
throw new Error(`credentials state file ${path} is unreadable (${err.message}); fix or remove it by hand. Removing it forgets which secret names this sync owns.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function saveState(state) {
|
|
37
|
+
writePrivateFileAtomic(statePath(), JSON.stringify(state, null, 2) + '\n');
|
|
38
|
+
}
|
|
39
|
+
const LOCK_WAIT_MS = 15_000;
|
|
40
|
+
const LOCK_POLL_MS = 200;
|
|
41
|
+
const EMPTY_LOCK_STALE_MS = 5_000;
|
|
42
|
+
function stateLockPath() {
|
|
43
|
+
return join(credentialsHome(), 'credentials-state.lock');
|
|
44
|
+
}
|
|
45
|
+
function lockIsStale(path) {
|
|
46
|
+
const pid = readLockPid(path);
|
|
47
|
+
if (pid !== null)
|
|
48
|
+
return !pidAlive(pid);
|
|
49
|
+
try {
|
|
50
|
+
return Date.now() - statSync(path).mtimeMs > EMPTY_LOCK_STALE_MS;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
export async function withStateLock(fn, opts = {}) {
|
|
57
|
+
const path = stateLockPath();
|
|
58
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
59
|
+
const deadline = Date.now() + (opts.waitMs ?? LOCK_WAIT_MS);
|
|
60
|
+
for (;;) {
|
|
61
|
+
try {
|
|
62
|
+
writeFileSync(path, String(process.pid), { flag: 'wx', mode: 0o600 });
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code !== 'EEXIST')
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
if (lockIsStale(path)) {
|
|
70
|
+
rmSync(path, { force: true });
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (Date.now() >= deadline)
|
|
74
|
+
throw new Error('another credentials push is running');
|
|
75
|
+
await new Promise((resolve) => setTimeout(resolve, opts.pollMs ?? LOCK_POLL_MS));
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
return await fn();
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
rmSync(path, { force: true });
|
|
82
|
+
}
|
|
83
|
+
}
|