runcloud 0.2.240 → 0.2.243
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/image.js +2 -1
- 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.243.tgz +0 -0
- package/skills/run-cloud-ios-simulator/SKILL.md +30 -0
- package/runcloud-0.2.240.tgz +0 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { appendFileSync, chmodSync, mkdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { ConfigError } from './config.js';
|
|
4
|
+
import { expandHome, groupItems } from './items.js';
|
|
5
|
+
import { pidAlive, readLockPid } from './lockFile.js';
|
|
6
|
+
import { dueGroups, groupKeyOf } from './schedule.js';
|
|
7
|
+
export { readLockPid };
|
|
8
|
+
const TICK_MS = 60_000;
|
|
9
|
+
const DEBOUNCE_MS = 2_000;
|
|
10
|
+
const FAILED_RETRY_MS = 5 * 60_000;
|
|
11
|
+
const LOG_ROTATE_BYTES = 1024 * 1024;
|
|
12
|
+
export function formatResultLine(at, result) {
|
|
13
|
+
let line = `${at.toISOString()} ${groupKeyOf({ groups: [] }, result.group, result.org)} ${result.outcome}`;
|
|
14
|
+
if (result.pushed.length > 0 || result.deleted.length > 0) {
|
|
15
|
+
line += ` pushed=${result.pushed.length} deleted=${result.deleted.length}`;
|
|
16
|
+
}
|
|
17
|
+
if (result.warnings.length > 0)
|
|
18
|
+
line += ` warnings: ${result.warnings.join('; ')}`;
|
|
19
|
+
return line;
|
|
20
|
+
}
|
|
21
|
+
function filePaths(config) {
|
|
22
|
+
const paths = new Set();
|
|
23
|
+
for (const group of config.groups) {
|
|
24
|
+
for (const item of groupItems(group))
|
|
25
|
+
if (item.kind === 'file')
|
|
26
|
+
paths.add(expandHome(item.from));
|
|
27
|
+
}
|
|
28
|
+
return [...paths].sort();
|
|
29
|
+
}
|
|
30
|
+
export async function runAgent(deps) {
|
|
31
|
+
const tickMs = deps.tickMs ?? TICK_MS;
|
|
32
|
+
const debounceMs = deps.debounceMs ?? DEBOUNCE_MS;
|
|
33
|
+
const state = { commandLastRun: {}, fileMtimes: {} };
|
|
34
|
+
let config = null;
|
|
35
|
+
let lastConfigError = null;
|
|
36
|
+
let lastConfigText = null;
|
|
37
|
+
let watched = '';
|
|
38
|
+
let unwatch = () => { };
|
|
39
|
+
let debounce;
|
|
40
|
+
let chain = Promise.resolve();
|
|
41
|
+
let cleanupRetryAt = null;
|
|
42
|
+
const stamp = () => new Date(Date.now());
|
|
43
|
+
const reload = () => {
|
|
44
|
+
try {
|
|
45
|
+
config = deps.loadConfig();
|
|
46
|
+
lastConfigError = null;
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
const text = error instanceof ConfigError ? error.problems.join('; ') : error instanceof Error ? error.message.split('\n')[0] : 'unknown error';
|
|
50
|
+
if (text !== lastConfigError)
|
|
51
|
+
deps.log(`${stamp().toISOString()} config error: ${text}`);
|
|
52
|
+
lastConfigError = text;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const syncWatch = (paths) => {
|
|
56
|
+
const id = paths.join('\n');
|
|
57
|
+
if (id === watched)
|
|
58
|
+
return;
|
|
59
|
+
unwatch();
|
|
60
|
+
watched = id;
|
|
61
|
+
unwatch = paths.length > 0 ? deps.watch(paths, onChange) : () => { };
|
|
62
|
+
};
|
|
63
|
+
const record = (cfg, keys, mtimes, failed) => {
|
|
64
|
+
const now = Date.now();
|
|
65
|
+
for (const group of cfg.groups) {
|
|
66
|
+
const key = groupKeyOf(cfg, group.name, group.org);
|
|
67
|
+
if (keys && !keys.includes(key))
|
|
68
|
+
continue;
|
|
69
|
+
groupItems(group).forEach((item, index) => {
|
|
70
|
+
if (item.kind === 'command') {
|
|
71
|
+
const early = failed.has(key) ? item.refreshMs - Math.min(item.refreshMs, FAILED_RETRY_MS) : 0;
|
|
72
|
+
state.commandLastRun[`${key}#${index}`] = now - early;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
const path = expandHome(item.from);
|
|
76
|
+
if (!failed.has(key) && mtimes[path] !== undefined)
|
|
77
|
+
state.fileMtimes[path] = mtimes[path];
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
const cycle = async (full) => {
|
|
83
|
+
if (deps.signal.aborted)
|
|
84
|
+
return;
|
|
85
|
+
reload();
|
|
86
|
+
const cfg = config;
|
|
87
|
+
if (!cfg)
|
|
88
|
+
return;
|
|
89
|
+
const configText = JSON.stringify(cfg);
|
|
90
|
+
if (configText !== lastConfigText) {
|
|
91
|
+
full = true;
|
|
92
|
+
lastConfigText = configText;
|
|
93
|
+
}
|
|
94
|
+
const paths = filePaths(cfg);
|
|
95
|
+
syncWatch(paths);
|
|
96
|
+
const mtimes = {};
|
|
97
|
+
for (const path of paths) {
|
|
98
|
+
const mtime = await deps.statMtime(path);
|
|
99
|
+
if (mtime !== null)
|
|
100
|
+
mtimes[path] = mtime;
|
|
101
|
+
}
|
|
102
|
+
if (cleanupRetryAt !== null && Date.now() >= cleanupRetryAt)
|
|
103
|
+
full = true;
|
|
104
|
+
const keys = full ? undefined : dueGroups(cfg, state, Date.now(), mtimes);
|
|
105
|
+
if (keys && keys.length === 0)
|
|
106
|
+
return;
|
|
107
|
+
const failed = new Set();
|
|
108
|
+
try {
|
|
109
|
+
let cleanupFailed = false;
|
|
110
|
+
for (const result of await deps.push(keys, cfg)) {
|
|
111
|
+
deps.log(formatResultLine(stamp(), result));
|
|
112
|
+
if (result.outcome !== 'failed')
|
|
113
|
+
continue;
|
|
114
|
+
if (result.removed)
|
|
115
|
+
cleanupFailed = true;
|
|
116
|
+
else
|
|
117
|
+
failed.add(groupKeyOf(cfg, result.group, result.org));
|
|
118
|
+
}
|
|
119
|
+
if (!keys)
|
|
120
|
+
cleanupRetryAt = cleanupFailed ? Date.now() + FAILED_RETRY_MS : null;
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
for (const group of cfg.groups)
|
|
124
|
+
failed.add(groupKeyOf(cfg, group.name, group.org));
|
|
125
|
+
deps.log(`${stamp().toISOString()} push error: ${error instanceof Error ? error.message.split('\n')[0] : 'unknown error'}`);
|
|
126
|
+
}
|
|
127
|
+
record(cfg, keys, mtimes, failed);
|
|
128
|
+
};
|
|
129
|
+
const enqueue = (full) => {
|
|
130
|
+
chain = chain.then(() => cycle(full)).catch(() => { });
|
|
131
|
+
};
|
|
132
|
+
function onChange() {
|
|
133
|
+
clearTimeout(debounce);
|
|
134
|
+
debounce = setTimeout(() => enqueue(false), debounceMs);
|
|
135
|
+
}
|
|
136
|
+
enqueue(true);
|
|
137
|
+
const timer = setInterval(() => enqueue(false), tickMs);
|
|
138
|
+
await new Promise((resolve) => {
|
|
139
|
+
if (deps.signal.aborted)
|
|
140
|
+
resolve();
|
|
141
|
+
else
|
|
142
|
+
deps.signal.addEventListener('abort', () => resolve(), { once: true });
|
|
143
|
+
});
|
|
144
|
+
clearInterval(timer);
|
|
145
|
+
clearTimeout(debounce);
|
|
146
|
+
unwatch();
|
|
147
|
+
await chain;
|
|
148
|
+
}
|
|
149
|
+
export function acquireAgentLock(path) {
|
|
150
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
151
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
152
|
+
try {
|
|
153
|
+
writeFileSync(path, String(process.pid), { flag: 'wx', mode: 0o600 });
|
|
154
|
+
return () => {
|
|
155
|
+
if (readLockPid(path) === process.pid)
|
|
156
|
+
rmSync(path, { force: true });
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
if (error.code !== 'EEXIST')
|
|
161
|
+
throw error;
|
|
162
|
+
const holder = readLockPid(path);
|
|
163
|
+
if (holder !== null && pidAlive(holder))
|
|
164
|
+
return null;
|
|
165
|
+
rmSync(path, { force: true });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
export function appendLog(path, line) {
|
|
171
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
172
|
+
try {
|
|
173
|
+
if (statSync(path).size >= LOG_ROTATE_BYTES)
|
|
174
|
+
renameSync(path, `${path}.1`);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
}
|
|
178
|
+
appendFileSync(path, `${line}\n`, { mode: 0o600 });
|
|
179
|
+
chmodSync(path, 0o600);
|
|
180
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { isMap, isSeq, parseDocument, YAMLMap, YAMLSeq } from 'yaml';
|
|
4
|
+
import { credentialsHome } from '../config.js';
|
|
5
|
+
import { presetOptionsProblem } from './presets.js';
|
|
6
|
+
import { writePrivateFileAtomic } from './privateFile.js';
|
|
7
|
+
const PRESET_IDS = ['gcloud', 'aws', 'github', 'claude'];
|
|
8
|
+
export class ConfigError extends Error {
|
|
9
|
+
problems;
|
|
10
|
+
constructor(problems) {
|
|
11
|
+
super(`credentials config is invalid:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
|
|
12
|
+
this.problems = problems;
|
|
13
|
+
this.name = 'ConfigError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const MIN_REFRESH_MS = 60_000;
|
|
17
|
+
const DEFAULT_REFRESH_MS = 3_600_000;
|
|
18
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
19
|
+
const GROUP_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/;
|
|
20
|
+
export const ENV_NAME_RE = /^[A-Za-z][A-Za-z0-9_]{0,127}$/;
|
|
21
|
+
const FILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
22
|
+
export function envNameProblem(name) {
|
|
23
|
+
if (!ENV_NAME_RE.test(name))
|
|
24
|
+
return `env name "${name}" must match ${ENV_NAME_RE}`;
|
|
25
|
+
if (name.startsWith('SBX_'))
|
|
26
|
+
return `env name "${name}" must not start with SBX_ (reserved)`;
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
export function fileNameProblem(name) {
|
|
30
|
+
return FILE_NAME_RE.test(name) ? null : `file name "${name}" must match ${FILE_NAME_RE}`;
|
|
31
|
+
}
|
|
32
|
+
export function sandboxPathProblem(path) {
|
|
33
|
+
if (path.length === 0)
|
|
34
|
+
return 'path is empty';
|
|
35
|
+
if (path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path))
|
|
36
|
+
return `path "${path}" must be relative`;
|
|
37
|
+
if (path.split(/[\\/]/).includes('..'))
|
|
38
|
+
return `path "${path}" must not contain ".."`;
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
export function credentialsConfigPath() {
|
|
42
|
+
return join(credentialsHome(), 'credentials.yaml');
|
|
43
|
+
}
|
|
44
|
+
const DURATION_UNITS = { s: 1000, m: 60_000, h: 3_600_000 };
|
|
45
|
+
export function parseDuration(text) {
|
|
46
|
+
const m = /^(\d+)([smh])$/.exec(String(text).trim());
|
|
47
|
+
if (!m || Number(m[1]) <= 0)
|
|
48
|
+
throw new Error(`invalid duration "${text}" (use for example 45s, 30m, 2h)`);
|
|
49
|
+
return Number(m[1]) * DURATION_UNITS[m[2]];
|
|
50
|
+
}
|
|
51
|
+
const ITEM_KEYS = ['env', 'to', 'name', 'encoding'];
|
|
52
|
+
const FILE_KEYS = new Set(['file', ...ITEM_KEYS]);
|
|
53
|
+
const COMMAND_KEYS = new Set(['command', 'format', 'refresh', 'timeout', ...ITEM_KEYS]);
|
|
54
|
+
function isRecord(v) {
|
|
55
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
56
|
+
}
|
|
57
|
+
function parseEntry(raw, where, problems) {
|
|
58
|
+
const start = problems.length;
|
|
59
|
+
const bad = (msg) => problems.push(`${where}: ${msg}`);
|
|
60
|
+
if (!isRecord(raw)) {
|
|
61
|
+
bad('entry must be a mapping');
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
const kinds = ['preset', 'file', 'command'].filter((k) => k in raw);
|
|
65
|
+
if (kinds.length !== 1) {
|
|
66
|
+
bad('needs exactly one of preset, file or command');
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
const kind = kinds[0];
|
|
70
|
+
if (kind === 'preset') {
|
|
71
|
+
const id = raw.preset;
|
|
72
|
+
if (typeof id !== 'string' || !PRESET_IDS.includes(id)) {
|
|
73
|
+
bad(`unknown preset "${String(id)}" (expected ${PRESET_IDS.join(', ')})`);
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
const options = {};
|
|
77
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
78
|
+
if (key === 'preset')
|
|
79
|
+
continue;
|
|
80
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
|
|
81
|
+
options[key] = String(value);
|
|
82
|
+
else
|
|
83
|
+
bad(`option "${key}" must be a string`);
|
|
84
|
+
}
|
|
85
|
+
const optionsProblem = presetOptionsProblem(id, options);
|
|
86
|
+
if (optionsProblem)
|
|
87
|
+
bad(optionsProblem);
|
|
88
|
+
return problems.length > start ? null : { kind: 'preset', preset: id, options };
|
|
89
|
+
}
|
|
90
|
+
const allowed = kind === 'file' ? FILE_KEYS : COMMAND_KEYS;
|
|
91
|
+
for (const key of Object.keys(raw))
|
|
92
|
+
if (!allowed.has(key))
|
|
93
|
+
bad(`unknown key "${key}"`);
|
|
94
|
+
const source = raw[kind];
|
|
95
|
+
if (typeof source !== 'string' || source.trim() === '')
|
|
96
|
+
bad(`${kind} must be a non-empty string`);
|
|
97
|
+
const optString = (key) => {
|
|
98
|
+
const v = raw[key];
|
|
99
|
+
if (v === undefined)
|
|
100
|
+
return undefined;
|
|
101
|
+
if (typeof v !== 'string') {
|
|
102
|
+
bad(`${key} must be a string`);
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
return v;
|
|
106
|
+
};
|
|
107
|
+
const env = optString('env');
|
|
108
|
+
const to = optString('to');
|
|
109
|
+
const name = optString('name');
|
|
110
|
+
const encodingRaw = optString('encoding');
|
|
111
|
+
const formatRaw = kind === 'command' ? optString('format') : undefined;
|
|
112
|
+
if (encodingRaw !== undefined && kind === 'command')
|
|
113
|
+
bad('encoding: base64 is only for file sources');
|
|
114
|
+
else if (encodingRaw !== undefined && encodingRaw !== 'base64')
|
|
115
|
+
bad('encoding must be base64');
|
|
116
|
+
if (formatRaw !== undefined && formatRaw !== 'raw' && formatRaw !== 'dotenv')
|
|
117
|
+
bad('format must be raw or dotenv');
|
|
118
|
+
const dotenv = formatRaw === 'dotenv';
|
|
119
|
+
if (dotenv) {
|
|
120
|
+
if (env !== undefined || to !== undefined)
|
|
121
|
+
bad('format dotenv takes neither env nor to (the output names its variables)');
|
|
122
|
+
}
|
|
123
|
+
else if (env === undefined && to === undefined)
|
|
124
|
+
bad('needs env or to');
|
|
125
|
+
else if (env !== undefined && to !== undefined)
|
|
126
|
+
bad('use env or to, not both');
|
|
127
|
+
if (env !== undefined) {
|
|
128
|
+
const p = envNameProblem(env);
|
|
129
|
+
if (p)
|
|
130
|
+
bad(p);
|
|
131
|
+
}
|
|
132
|
+
if (to !== undefined) {
|
|
133
|
+
const p = sandboxPathProblem(to);
|
|
134
|
+
if (p)
|
|
135
|
+
bad(p);
|
|
136
|
+
}
|
|
137
|
+
if (name !== undefined) {
|
|
138
|
+
const p = fileNameProblem(name);
|
|
139
|
+
if (p)
|
|
140
|
+
bad(p);
|
|
141
|
+
}
|
|
142
|
+
let refreshMs = DEFAULT_REFRESH_MS;
|
|
143
|
+
let timeoutMs = DEFAULT_TIMEOUT_MS;
|
|
144
|
+
if (kind === 'command') {
|
|
145
|
+
for (const key of ['refresh', 'timeout']) {
|
|
146
|
+
const v = raw[key];
|
|
147
|
+
if (v === undefined)
|
|
148
|
+
continue;
|
|
149
|
+
try {
|
|
150
|
+
const ms = parseDuration(String(v));
|
|
151
|
+
if (key === 'refresh') {
|
|
152
|
+
if (ms < MIN_REFRESH_MS)
|
|
153
|
+
bad('refresh must be at least 1m');
|
|
154
|
+
refreshMs = ms;
|
|
155
|
+
}
|
|
156
|
+
else
|
|
157
|
+
timeoutMs = ms;
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
bad(`${key} "${String(v)}" is not a duration (use for example 45s, 30m, 2h)`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (problems.length > start)
|
|
165
|
+
return null;
|
|
166
|
+
const common = {
|
|
167
|
+
...(env !== undefined && { env }),
|
|
168
|
+
...(to !== undefined && { to }),
|
|
169
|
+
...(name !== undefined && { name }),
|
|
170
|
+
};
|
|
171
|
+
if (kind === 'file')
|
|
172
|
+
return { kind: 'file', from: source, ...common, ...(encodingRaw === 'base64' && { encoding: 'base64' }) };
|
|
173
|
+
return {
|
|
174
|
+
kind: 'command',
|
|
175
|
+
command: source,
|
|
176
|
+
format: dotenv ? 'dotenv' : 'raw',
|
|
177
|
+
...common,
|
|
178
|
+
refreshMs,
|
|
179
|
+
timeoutMs,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
export function parseCredentialsConfig(text) {
|
|
183
|
+
const problems = [];
|
|
184
|
+
const doc = parseDocument(text);
|
|
185
|
+
for (const e of doc.errors)
|
|
186
|
+
problems.push(e.message.split('\n')[0]);
|
|
187
|
+
if (problems.length > 0)
|
|
188
|
+
throw new ConfigError(problems);
|
|
189
|
+
const root = doc.toJS() ?? {};
|
|
190
|
+
if (!isRecord(root))
|
|
191
|
+
throw new ConfigError(['top level must be a mapping']);
|
|
192
|
+
for (const key of Object.keys(root))
|
|
193
|
+
if (key !== 'org' && key !== 'groups')
|
|
194
|
+
problems.push(`unknown top-level key "${key}"`);
|
|
195
|
+
if (root.org !== undefined && typeof root.org !== 'string')
|
|
196
|
+
problems.push('org must be a string');
|
|
197
|
+
const groupsRaw = root.groups ?? {};
|
|
198
|
+
if (!isRecord(groupsRaw)) {
|
|
199
|
+
problems.push('groups must be a mapping of group name to entries');
|
|
200
|
+
throw new ConfigError(problems);
|
|
201
|
+
}
|
|
202
|
+
const groups = [];
|
|
203
|
+
for (const [name, value] of Object.entries(groupsRaw)) {
|
|
204
|
+
const label = `group "${name}"`;
|
|
205
|
+
if (!GROUP_NAME_RE.test(name))
|
|
206
|
+
problems.push(`${label}: name must match ${GROUP_NAME_RE}`);
|
|
207
|
+
let org;
|
|
208
|
+
let list = value;
|
|
209
|
+
if (isRecord(value)) {
|
|
210
|
+
for (const key of Object.keys(value))
|
|
211
|
+
if (key !== 'org' && key !== 'credentials')
|
|
212
|
+
problems.push(`${label}: unknown key "${key}"`);
|
|
213
|
+
if (value.org !== undefined) {
|
|
214
|
+
if (typeof value.org === 'string')
|
|
215
|
+
org = value.org;
|
|
216
|
+
else
|
|
217
|
+
problems.push(`${label}: org must be a string`);
|
|
218
|
+
}
|
|
219
|
+
list = value.credentials;
|
|
220
|
+
}
|
|
221
|
+
if (!Array.isArray(list)) {
|
|
222
|
+
problems.push(`${label}: needs a list of entries`);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const entries = [];
|
|
226
|
+
list.forEach((raw, i) => {
|
|
227
|
+
const entry = parseEntry(raw, `${label} entry ${i}`, problems);
|
|
228
|
+
if (entry)
|
|
229
|
+
entries.push(entry);
|
|
230
|
+
});
|
|
231
|
+
groups.push({ name, ...(org !== undefined && { org }), entries });
|
|
232
|
+
}
|
|
233
|
+
if (problems.length > 0)
|
|
234
|
+
throw new ConfigError(problems);
|
|
235
|
+
return { ...(typeof root.org === 'string' && { org: root.org }), groups };
|
|
236
|
+
}
|
|
237
|
+
export function loadCredentialsConfig(path = credentialsConfigPath()) {
|
|
238
|
+
if (!existsSync(path))
|
|
239
|
+
return null;
|
|
240
|
+
return parseCredentialsConfig(readFileSync(path, 'utf8'));
|
|
241
|
+
}
|
|
242
|
+
function groupSeq(doc, group, create) {
|
|
243
|
+
let groups = doc.get('groups', true);
|
|
244
|
+
if (!isMap(groups)) {
|
|
245
|
+
if (!create)
|
|
246
|
+
return null;
|
|
247
|
+
groups = new YAMLMap();
|
|
248
|
+
doc.set('groups', groups);
|
|
249
|
+
}
|
|
250
|
+
const map = groups;
|
|
251
|
+
let node = map.get(group, true);
|
|
252
|
+
if (node === undefined || node === null) {
|
|
253
|
+
if (!create)
|
|
254
|
+
return null;
|
|
255
|
+
node = new YAMLSeq();
|
|
256
|
+
map.set(group, node);
|
|
257
|
+
}
|
|
258
|
+
if (isMap(node)) {
|
|
259
|
+
let inner = node.get('credentials', true);
|
|
260
|
+
if (!isSeq(inner)) {
|
|
261
|
+
if (!create)
|
|
262
|
+
return null;
|
|
263
|
+
inner = new YAMLSeq();
|
|
264
|
+
node.set('credentials', inner);
|
|
265
|
+
}
|
|
266
|
+
return inner;
|
|
267
|
+
}
|
|
268
|
+
return isSeq(node) ? node : null;
|
|
269
|
+
}
|
|
270
|
+
export function addEntry(text, group, entry) {
|
|
271
|
+
const doc = parseDocument(text ?? '');
|
|
272
|
+
if (doc.errors.length > 0)
|
|
273
|
+
throw new ConfigError(doc.errors.map((e) => e.message.split('\n')[0]));
|
|
274
|
+
if (doc.contents === null)
|
|
275
|
+
doc.contents = doc.createNode({});
|
|
276
|
+
const seq = groupSeq(doc, group, true);
|
|
277
|
+
if (!seq)
|
|
278
|
+
throw new ConfigError([`group "${group}" is not a list of entries`]);
|
|
279
|
+
seq.add(doc.createNode(entry));
|
|
280
|
+
return doc.toString();
|
|
281
|
+
}
|
|
282
|
+
export function removeEntry(text, group, index) {
|
|
283
|
+
const doc = parseDocument(text);
|
|
284
|
+
if (doc.errors.length > 0)
|
|
285
|
+
throw new ConfigError(doc.errors.map((e) => e.message.split('\n')[0]));
|
|
286
|
+
if (index === undefined) {
|
|
287
|
+
const groups = doc.get('groups', true);
|
|
288
|
+
if (!isMap(groups) || !groups.has(group))
|
|
289
|
+
throw new ConfigError([`group "${group}" not found`]);
|
|
290
|
+
groups.delete(group);
|
|
291
|
+
return doc.toString();
|
|
292
|
+
}
|
|
293
|
+
const seq = groupSeq(doc, group, false);
|
|
294
|
+
if (!seq)
|
|
295
|
+
throw new ConfigError([`group "${group}" not found`]);
|
|
296
|
+
if (!Number.isInteger(index) || index < 0 || index >= seq.items.length) {
|
|
297
|
+
throw new ConfigError([`group "${group}" has no entry ${index}`]);
|
|
298
|
+
}
|
|
299
|
+
seq.delete(index);
|
|
300
|
+
return doc.toString();
|
|
301
|
+
}
|
|
302
|
+
export function writeCredentialsConfig(text, path = credentialsConfigPath()) {
|
|
303
|
+
writePrivateFileAtomic(path, text);
|
|
304
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { ApiError } from '../api.js';
|
|
2
|
+
import { readGroup } from './items.js';
|
|
3
|
+
import { groupKey, parseGroupKey, sha256 } from './state.js';
|
|
4
|
+
export { groupKey, sha256 };
|
|
5
|
+
const SIZE_WARN_BYTES = 48 * 1024;
|
|
6
|
+
const FORBIDDEN_WARNING = 'admin or owner role required to write secrets in this org';
|
|
7
|
+
function forbiddenWarning(org) {
|
|
8
|
+
return org ? `refused (403): needs admin or owner role in this org, or org "${org}" is not one you belong to` : FORBIDDEN_WARNING;
|
|
9
|
+
}
|
|
10
|
+
function apiReason(err) {
|
|
11
|
+
return err instanceof ApiError ? String(err.status) : 'network error';
|
|
12
|
+
}
|
|
13
|
+
function query(org, extra = {}) {
|
|
14
|
+
const params = new URLSearchParams(extra);
|
|
15
|
+
if (org)
|
|
16
|
+
params.set('orgId', org);
|
|
17
|
+
const text = params.toString();
|
|
18
|
+
return text ? `?${text}` : '';
|
|
19
|
+
}
|
|
20
|
+
export function createEngineApi(client) {
|
|
21
|
+
return {
|
|
22
|
+
async putSecret(org, group, s) {
|
|
23
|
+
const body = { group, value: s.value, kind: s.kind };
|
|
24
|
+
if (s.kind === 'file')
|
|
25
|
+
body.filePath = s.filePath;
|
|
26
|
+
await client.put(`/run-cloud/secrets/${encodeURIComponent(s.name)}${query(org)}`, body);
|
|
27
|
+
},
|
|
28
|
+
async deleteSecret(org, group, name) {
|
|
29
|
+
await client.delete(`/run-cloud/secrets/${encodeURIComponent(name)}${query(org, { group })}`);
|
|
30
|
+
},
|
|
31
|
+
async listSecretNames(org, group) {
|
|
32
|
+
const data = await client.get(`/run-cloud/secrets${query(org)}`);
|
|
33
|
+
const rows = (data?.secrets ?? []);
|
|
34
|
+
return rows.filter((r) => r.group === group).map((r) => r.name);
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function itemHash(s) {
|
|
39
|
+
return sha256(`${s.kind}\0${s.filePath ?? ''}\0${s.value}`);
|
|
40
|
+
}
|
|
41
|
+
function failureWarning(name, org, err) {
|
|
42
|
+
if (err instanceof ApiError && err.status === 403)
|
|
43
|
+
return forbiddenWarning(org);
|
|
44
|
+
return `push failed for ${name}: ${apiReason(err)}`;
|
|
45
|
+
}
|
|
46
|
+
async function deleteName(api, org, group, name) {
|
|
47
|
+
try {
|
|
48
|
+
await api.deleteSecret(org, group, name);
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
if (err instanceof ApiError && err.status === 404)
|
|
53
|
+
return null;
|
|
54
|
+
return err instanceof ApiError && err.status === 403 ? forbiddenWarning(org) : `delete failed for ${name}: ${apiReason(err)}`;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export async function pushGroups(config, state, deps, opts = {}) {
|
|
58
|
+
const now = deps.now ?? (() => new Date());
|
|
59
|
+
carryOverRekeyedGroups(config, state);
|
|
60
|
+
const results = [];
|
|
61
|
+
for (const group of config.groups) {
|
|
62
|
+
const org = group.org ?? config.org;
|
|
63
|
+
const key = groupKey(org, group.name);
|
|
64
|
+
if (opts.groups && !opts.groups.some((g) => g === group.name || g === key))
|
|
65
|
+
continue;
|
|
66
|
+
const gs = (state.groups[key] ??= { adopted: false, written: {}, warnings: [] });
|
|
67
|
+
const result = { group: group.name, org, outcome: 'unchanged', pushed: [], deleted: [], warnings: [] };
|
|
68
|
+
const warn = (w) => {
|
|
69
|
+
if (!result.warnings.includes(w))
|
|
70
|
+
result.warnings.push(w);
|
|
71
|
+
};
|
|
72
|
+
const finish = (outcome) => {
|
|
73
|
+
result.outcome = outcome;
|
|
74
|
+
gs.lastAttemptAt = now().toISOString();
|
|
75
|
+
gs.lastOutcome = outcome;
|
|
76
|
+
gs.warnings = [...result.warnings];
|
|
77
|
+
results.push(result);
|
|
78
|
+
};
|
|
79
|
+
const read = await readGroup(group, deps.run, deps.readFile);
|
|
80
|
+
read.failures.forEach(warn);
|
|
81
|
+
read.warnings.forEach(warn);
|
|
82
|
+
const readFailed = read.failures.length > 0;
|
|
83
|
+
if (readFailed && read.secrets.length === 0) {
|
|
84
|
+
finish('failed');
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const bytes = read.secrets.reduce((sum, s) => sum + Buffer.byteLength(s.value, 'utf8'), 0);
|
|
88
|
+
if (bytes > SIZE_WARN_BYTES) {
|
|
89
|
+
warn(`group ${group.name} is ${bytes} bytes; sandboxes have a 64 KiB limit across all groups they take`);
|
|
90
|
+
}
|
|
91
|
+
if (!gs.adopted && Object.keys(gs.written).length === 0 && !opts.adopt) {
|
|
92
|
+
let existing;
|
|
93
|
+
try {
|
|
94
|
+
existing = await deps.api.listSecretNames(org, group.name);
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
warn(err instanceof ApiError && err.status === 403 ? forbiddenWarning(org) : `could not check group ${group.name}: ${apiReason(err)}`);
|
|
98
|
+
finish('failed');
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (existing.length > 0) {
|
|
102
|
+
warn(`group ${group.name} already has secrets this sync did not write; run: runcloud credentials push --adopt ${group.name}`);
|
|
103
|
+
finish('not-adopted');
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
let failed = false;
|
|
108
|
+
for (const secret of read.secrets) {
|
|
109
|
+
const hash = itemHash(secret);
|
|
110
|
+
const bytes = Buffer.byteLength(secret.value, 'utf8');
|
|
111
|
+
const known = gs.written[secret.name];
|
|
112
|
+
if (!opts.force && known?.hash === hash) {
|
|
113
|
+
if (known.bytes === undefined)
|
|
114
|
+
known.bytes = bytes;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
await deps.api.putSecret(org, group.name, secret);
|
|
119
|
+
gs.written[secret.name] = { hash, pushedAt: now().toISOString(), bytes };
|
|
120
|
+
result.pushed.push(secret.name);
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
failed = true;
|
|
124
|
+
warn(failureWarning(secret.name, org, err));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const unread = read.itemNames.filter((i) => !i.read);
|
|
128
|
+
if (!failed && !unread.some((i) => i.names === null)) {
|
|
129
|
+
const keep = new Set([...read.secrets.map((s) => s.name), ...unread.flatMap((i) => i.names ?? [])]);
|
|
130
|
+
for (const name of Object.keys(gs.written)) {
|
|
131
|
+
if (keep.has(name))
|
|
132
|
+
continue;
|
|
133
|
+
const problem = await deleteName(deps.api, org, group.name, name);
|
|
134
|
+
if (problem) {
|
|
135
|
+
failed = true;
|
|
136
|
+
warn(problem);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
delete gs.written[name];
|
|
140
|
+
result.deleted.push(name);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (!failed && result.pushed.length > 0)
|
|
144
|
+
gs.adopted = true;
|
|
145
|
+
finish(failed || readFailed ? 'failed' : result.pushed.length > 0 || result.deleted.length > 0 ? 'pushed' : 'unchanged');
|
|
146
|
+
}
|
|
147
|
+
if (!opts.groups)
|
|
148
|
+
results.push(...(await cleanUpRemovedGroups(config, state, deps)));
|
|
149
|
+
return results;
|
|
150
|
+
}
|
|
151
|
+
function carryOverRekeyedGroups(config, state) {
|
|
152
|
+
const configured = new Set(config.groups.map((g) => groupKey(g.org ?? config.org, g.name)));
|
|
153
|
+
for (const group of config.groups) {
|
|
154
|
+
const key = groupKey(group.org ?? config.org, group.name);
|
|
155
|
+
if (state.groups[key])
|
|
156
|
+
continue;
|
|
157
|
+
const old = Object.keys(state.groups).filter((k) => !configured.has(k) && parseGroupKey(k).name === group.name);
|
|
158
|
+
if (old.length !== 1)
|
|
159
|
+
continue;
|
|
160
|
+
state.groups[key] = state.groups[old[0]];
|
|
161
|
+
delete state.groups[old[0]];
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async function cleanUpRemovedGroups(config, state, deps) {
|
|
165
|
+
const now = deps.now ?? (() => new Date());
|
|
166
|
+
const configured = new Set(config.groups.map((g) => groupKey(g.org ?? config.org, g.name)));
|
|
167
|
+
const configuredNames = new Set(config.groups.map((g) => g.name));
|
|
168
|
+
const results = [];
|
|
169
|
+
for (const [key, gs] of Object.entries(state.groups)) {
|
|
170
|
+
if (configured.has(key))
|
|
171
|
+
continue;
|
|
172
|
+
const { org, name } = parseGroupKey(key);
|
|
173
|
+
if (configuredNames.has(name)) {
|
|
174
|
+
delete state.groups[key];
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const result = {
|
|
178
|
+
group: name,
|
|
179
|
+
...(org !== undefined && { org }),
|
|
180
|
+
outcome: 'pushed',
|
|
181
|
+
pushed: [],
|
|
182
|
+
deleted: [],
|
|
183
|
+
warnings: [],
|
|
184
|
+
removed: true,
|
|
185
|
+
};
|
|
186
|
+
for (const secret of Object.keys(gs.written)) {
|
|
187
|
+
const problem = await deleteName(deps.api, org, name, secret);
|
|
188
|
+
if (problem) {
|
|
189
|
+
if (!result.warnings.includes(problem))
|
|
190
|
+
result.warnings.push(problem);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
delete gs.written[secret];
|
|
194
|
+
result.deleted.push(secret);
|
|
195
|
+
}
|
|
196
|
+
if (Object.keys(gs.written).length === 0) {
|
|
197
|
+
delete state.groups[key];
|
|
198
|
+
if (result.deleted.length > 0)
|
|
199
|
+
results.push(result);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
result.outcome = 'failed';
|
|
203
|
+
gs.lastAttemptAt = now().toISOString();
|
|
204
|
+
gs.lastOutcome = 'failed';
|
|
205
|
+
gs.warnings = [...result.warnings];
|
|
206
|
+
results.push(result);
|
|
207
|
+
}
|
|
208
|
+
return results;
|
|
209
|
+
}
|