@superpanel-sdk/cli 0.0.0-stage → 0.1.1

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.
Files changed (78) hide show
  1. package/README.md +16 -2
  2. package/bin/superpanel.mjs +23 -0
  3. package/dist/api/platform.d.ts +31 -0
  4. package/dist/api/platform.js +39 -0
  5. package/dist/auth/auth.d.ts +162 -0
  6. package/dist/auth/auth.js +923 -0
  7. package/dist/auth/backend-url.d.ts +7 -0
  8. package/dist/auth/backend-url.js +41 -0
  9. package/dist/auth/cli-login.d.ts +8 -0
  10. package/dist/auth/cli-login.js +92 -0
  11. package/dist/auth/clipboard.d.ts +8 -0
  12. package/dist/auth/clipboard.js +42 -0
  13. package/dist/auth/file-lock.d.ts +25 -0
  14. package/dist/auth/file-lock.js +173 -0
  15. package/dist/auth/http.d.ts +34 -0
  16. package/dist/auth/http.js +48 -0
  17. package/dist/auth/index.d.ts +13 -0
  18. package/dist/auth/index.js +117 -0
  19. package/dist/auth/origin-guard.d.ts +4 -0
  20. package/dist/auth/origin-guard.js +9 -0
  21. package/dist/auth/origin.d.ts +17 -0
  22. package/dist/auth/origin.js +142 -0
  23. package/dist/auth/pending-login.d.ts +5 -0
  24. package/dist/auth/pending-login.js +67 -0
  25. package/dist/commands/auth-token.d.ts +26 -0
  26. package/dist/commands/auth-token.js +71 -0
  27. package/dist/commands/git-method.d.ts +54 -0
  28. package/dist/commands/git-method.js +180 -0
  29. package/dist/commands/setup.d.ts +88 -0
  30. package/dist/commands/setup.js +366 -0
  31. package/dist/commands/skill.d.ts +29 -0
  32. package/dist/commands/skill.js +169 -0
  33. package/dist/commands/ssh-key.d.ts +13 -0
  34. package/dist/commands/ssh-key.js +83 -0
  35. package/dist/git/credential.d.ts +7 -0
  36. package/dist/git/credential.js +66 -0
  37. package/dist/git/index.d.ts +36 -0
  38. package/dist/git/index.js +119 -0
  39. package/dist/git/run.d.ts +13 -0
  40. package/dist/git/run.js +32 -0
  41. package/dist/git/setup.d.ts +97 -0
  42. package/dist/git/setup.js +471 -0
  43. package/dist/handover/clone.d.ts +8 -0
  44. package/dist/handover/clone.js +39 -0
  45. package/dist/handover/repo-help.d.ts +7 -0
  46. package/dist/handover/repo-help.js +55 -0
  47. package/dist/handover/run.d.ts +5 -0
  48. package/dist/handover/run.js +67 -0
  49. package/dist/inbound/index.d.ts +44 -0
  50. package/dist/inbound/index.js +129 -0
  51. package/dist/index.d.ts +3 -0
  52. package/dist/index.js +251 -0
  53. package/dist/logs/index.d.ts +19 -0
  54. package/dist/logs/index.js +132 -0
  55. package/dist/npm-launch.d.ts +19 -0
  56. package/dist/npm-launch.js +80 -0
  57. package/dist/ops/agent.d.ts +3 -0
  58. package/dist/ops/agent.js +14 -0
  59. package/dist/ops/cache.d.ts +18 -0
  60. package/dist/ops/cache.js +92 -0
  61. package/dist/ops/parse.d.ts +6 -0
  62. package/dist/ops/parse.js +106 -0
  63. package/dist/ops/register.d.ts +18 -0
  64. package/dist/ops/register.js +174 -0
  65. package/dist/ops/run.d.ts +20 -0
  66. package/dist/ops/run.js +127 -0
  67. package/dist/ops/types.d.ts +41 -0
  68. package/dist/ops/types.js +16 -0
  69. package/dist/protocol.d.ts +4 -0
  70. package/dist/protocol.js +17 -0
  71. package/dist/reserved.d.ts +4 -0
  72. package/dist/reserved.js +25 -0
  73. package/dist/turns/index.d.ts +20 -0
  74. package/dist/turns/index.js +108 -0
  75. package/dist/version.d.ts +2 -0
  76. package/dist/version.js +11 -0
  77. package/package.json +48 -4
  78. package/skill/SKILL.md +17 -0
@@ -0,0 +1,471 @@
1
+ import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir, hostname, tmpdir, userInfo } from 'node:os';
4
+ import path from 'node:path';
5
+ import { globalCliPath } from '../commands/git-method.js';
6
+ import { jsEntryFromCmd } from '../npm-launch.js';
7
+ import { run as defaultRun } from './run.js';
8
+ export const NOT_INSTALLED = 'Git needs a working global Superpanel CLI credential helper. Run "npm install -g @superpanel-sdk/cli@latest", then set up git again.';
9
+ function shellQuote(value) {
10
+ return `'${value.replace(/'/g, `'\\''`)}'`;
11
+ }
12
+ export function credentialHelperValue(backendUrl, nodePath, cliEntry) {
13
+ return `!${shellQuote(nodePath)} ${shellQuote(cliEntry)} git-credential --url ${shellQuote(backendUrl)}`;
14
+ }
15
+ export function credentialCliEntry(found) {
16
+ const resolved = (() => {
17
+ try {
18
+ return realpathSync(found);
19
+ }
20
+ catch {
21
+ return found;
22
+ }
23
+ })();
24
+ if (!/\.(?:cmd|bat)$/i.test(resolved) && !/\.(?:cmd|bat)$/i.test(found))
25
+ return resolved;
26
+ const cmd = /\.(?:cmd|bat)$/i.test(found) ? found : resolved;
27
+ const entry = jsEntryFromCmd(cmd, path, existsSync, (file) => readFileSync(file, 'utf8'), path.join(path.dirname(cmd), 'node_modules', '@superpanel-sdk', 'cli', 'bin', 'superpanel.mjs'));
28
+ if (!entry)
29
+ return resolved;
30
+ try {
31
+ return realpathSync(entry);
32
+ }
33
+ catch {
34
+ return entry;
35
+ }
36
+ }
37
+ export function shellPath(pathValue) {
38
+ return pathValue
39
+ .split(path.delimiter)
40
+ .filter((dir) => dir && !/[\\/]node_modules[\\/]\.bin[\\/]?$/.test(dir) && !/[\\/]_npx[\\/]/.test(dir))
41
+ .join(path.delimiter);
42
+ }
43
+ export function findOnPath(command, pathValue) {
44
+ const names = process.platform === 'win32' ? [`${command}.cmd`, `${command}.exe`, command] : [command];
45
+ for (const dir of pathValue.split(path.delimiter)) {
46
+ if (!dir)
47
+ continue;
48
+ for (const name of names) {
49
+ const full = path.join(dir, name);
50
+ try {
51
+ if (!statSync(full).isFile())
52
+ continue;
53
+ accessSync(full, constants.X_OK);
54
+ return full;
55
+ }
56
+ catch {
57
+ }
58
+ }
59
+ }
60
+ return null;
61
+ }
62
+ export async function configureHttpsGit(input, deps = {}) {
63
+ const run = deps.run ?? defaultRun;
64
+ const origin = new URL(input.httpsCloneUrl).origin;
65
+ const found = (deps.globalCli ?? globalCliPath)();
66
+ if (!found) {
67
+ return { origin, verified: false, installed: false, detail: NOT_INSTALLED };
68
+ }
69
+ const entry = credentialCliEntry(found);
70
+ const ready = await run(process.execPath, [entry, 'git-credential', '--help']);
71
+ if (ready.code !== 0)
72
+ return { origin, verified: false, installed: false, detail: NOT_INSTALLED };
73
+ const key = `credential.${origin}.helper`;
74
+ const helper = credentialHelperValue(input.backendUrl, process.execPath, entry);
75
+ const check = await isolatedGit(['-c', key + '=', '-c', key + '=' + helper, 'ls-remote', '--heads', input.httpsCloneUrl], deps, 30_000);
76
+ if (check.code !== 0)
77
+ return {
78
+ origin,
79
+ verified: false,
80
+ installed: false,
81
+ detail: lastLines(check.stderr) || 'git could not read the company repository',
82
+ };
83
+ await run('git', ['config', '--global', '--unset-all', key]);
84
+ for (const value of ['', helper]) {
85
+ const added = await run('git', ['config', '--global', '--add', key, value]);
86
+ if (added.code !== 0)
87
+ throw new Error(`git config failed: ${added.stderr.trim() || `exit ${added.code}`}`);
88
+ }
89
+ return { origin, verified: true, installed: true, detail: 'git can read the repo over HTTPS' };
90
+ }
91
+ export async function isolatedGit(args, deps = {}, timeoutMs = 0) {
92
+ const cwd = await mkdtemp(path.join(tmpdir(), 'superpanel-git-probe-'));
93
+ try {
94
+ const env = {
95
+ ...process.env,
96
+ PATH: shellPath(deps.pathValue ?? process.env.PATH ?? ''),
97
+ GIT_TERMINAL_PROMPT: '0',
98
+ GIT_CEILING_DIRECTORIES: path.dirname(cwd),
99
+ };
100
+ delete env.GIT_DIR;
101
+ delete env.GIT_WORK_TREE;
102
+ delete env.GIT_COMMON_DIR;
103
+ return await (deps.run ?? defaultRun)('git', args, { cwd, env, timeoutMs });
104
+ }
105
+ finally {
106
+ await rm(cwd, { recursive: true, force: true });
107
+ }
108
+ }
109
+ function lastLines(text, count = 3) {
110
+ return text.trim().split('\n').slice(-count).join(' ').trim();
111
+ }
112
+ export async function probeSsh(input, deps = {}) {
113
+ const run = deps.run ?? defaultRun;
114
+ const result = await run('ssh', [
115
+ '-T',
116
+ ...(input.port ? ['-p', String(input.port)] : []),
117
+ '-o',
118
+ 'BatchMode=yes',
119
+ '-o',
120
+ input.readOnly ? 'StrictHostKeyChecking=yes' : 'StrictHostKeyChecking=accept-new',
121
+ ...(input.readOnly ? ['-o', 'UpdateHostKeys=no'] : []),
122
+ '-o',
123
+ 'ConnectTimeout=10',
124
+ `git@${input.host}`,
125
+ ], { timeoutMs: 25_000 });
126
+ const output = `${result.stdout}\n${result.stderr}`;
127
+ const hi = /Hi there,\s*([^!\s]+)!/.exec(output);
128
+ if (hi)
129
+ return { kind: 'user', username: hi[1] };
130
+ if (/Permission denied|Too many authentication failures/i.test(output))
131
+ return { kind: 'denied', detail: lastLines(output) };
132
+ return { kind: 'error', detail: lastLines(output) || `ssh exited ${result.code}` };
133
+ }
134
+ export function keyBody(line) {
135
+ return line.trim().split(/\s+/).slice(0, 2).join(' ');
136
+ }
137
+ const PUBLIC_KEY_LINE = /^(ssh-|ecdsa-|sk-)/;
138
+ const CERTIFICATE_LINE = /^\S+-cert-v0\d@openssh\.com\s/;
139
+ function expandHome(file, home) {
140
+ if (file === '~')
141
+ return home;
142
+ if (file.startsWith('~/'))
143
+ return path.join(home, file.slice(2));
144
+ return file.replace(/%d/g, home);
145
+ }
146
+ function expandTokens(file, values) {
147
+ const local = (() => {
148
+ try {
149
+ return userInfo().username;
150
+ }
151
+ catch {
152
+ return '';
153
+ }
154
+ })();
155
+ const tokens = {
156
+ '%': '%',
157
+ d: values.home,
158
+ h: values.hostname,
159
+ n: values.host,
160
+ r: values.user,
161
+ p: values.port,
162
+ u: local,
163
+ l: hostname().split('.')[0] ?? '',
164
+ L: hostname().split('.')[0] ?? '',
165
+ };
166
+ return expandHome(file.replace(/%([%dhnrpulL])/g, (_, token) => tokens[token] ?? `%${token}`), values.home);
167
+ }
168
+ async function publicKeyOf(privatePath, deps) {
169
+ if (existsSync(`${privatePath}.pub`))
170
+ return keyBody(await readFile(`${privatePath}.pub`, 'utf8'));
171
+ const derived = await (deps.run ?? defaultRun)('ssh-keygen', ['-y', '-P', '', '-f', privatePath]);
172
+ return derived.code === 0 && PUBLIC_KEY_LINE.test(derived.stdout.trim()) ? keyBody(derived.stdout) : null;
173
+ }
174
+ export async function firstOfferedKey(input, deps = {}) {
175
+ const run = deps.run ?? defaultRun;
176
+ const home = deps.home ?? homedir();
177
+ const config = await run('ssh', ['-G', '-p', String(input.port), `git@${input.host}`]);
178
+ const lines = config.code === 0 ? config.stdout.split('\n').map((line) => line.trim()) : [];
179
+ const setting = (name) => lines.map((line) => new RegExp(`^${name}\\s+(.+)$`, 'i').exec(line)?.[1]).find(Boolean);
180
+ const identitiesOnly = lines.some((line) => /^identitiesonly\s+yes$/i.test(line));
181
+ const agentSetting = setting('identityagent');
182
+ const tokenValues = {
183
+ home,
184
+ host: input.host,
185
+ hostname: setting('hostname') ?? input.host,
186
+ user: setting('user') ?? 'git',
187
+ port: setting('port') ?? String(input.port),
188
+ };
189
+ const files = lines
190
+ .map((line) => /^identityfile\s+(.+)$/i.exec(line)?.[1])
191
+ .filter((file) => Boolean(file))
192
+ .map((file) => expandTokens(file.replace(/^"(.*)"$/, '$1'), tokenValues));
193
+ let agentKeys = [];
194
+ if (agentSetting?.toLowerCase() !== 'none') {
195
+ const socket = agentSetting && agentSetting !== 'SSH_AUTH_SOCK'
196
+ ? expandHome(agentSetting.replace(/^"(.*)"$/, '$1'), home)
197
+ : undefined;
198
+ const agent = await run('ssh-add', ['-L'], socket ? { env: { ...process.env, SSH_AUTH_SOCK: socket } } : {});
199
+ if (agent.code === 0)
200
+ agentKeys = agent.stdout
201
+ .split('\n')
202
+ .filter((line) => PUBLIC_KEY_LINE.test(line.trim()) && !CERTIFICATE_LINE.test(line.trim()))
203
+ .map(keyBody);
204
+ if (!identitiesOnly && agentKeys[0])
205
+ return { source: 'agent', publicKey: agentKeys[0] };
206
+ }
207
+ for (const file of files) {
208
+ if (!existsSync(file))
209
+ continue;
210
+ const content = statSync(file).size < 16_384 ? await readFile(file, 'utf8').catch(() => '') : '';
211
+ if (PUBLIC_KEY_LINE.test(content.trim()) && !CERTIFICATE_LINE.test(content.trim())) {
212
+ return { source: 'file', publicKey: keyBody(content) };
213
+ }
214
+ const publicKey = await publicKeyOf(file, deps);
215
+ if (publicKey && agentKeys.includes(publicKey))
216
+ return { source: 'agent', publicKey };
217
+ return publicKey
218
+ ? { source: 'file', publicKey, privatePath: file }
219
+ : { source: 'file', privatePath: file, locked: true };
220
+ }
221
+ return null;
222
+ }
223
+ export async function keyNeedsPassphrase(privatePath, deps = {}) {
224
+ const run = deps.run ?? defaultRun;
225
+ return (await run('ssh-keygen', ['-y', '-P', '', '-f', privatePath])).code !== 0;
226
+ }
227
+ async function generateKey(privatePath, comment, deps) {
228
+ const run = deps.run ?? defaultRun;
229
+ await mkdir(path.dirname(privatePath), { recursive: true, mode: 0o700 });
230
+ const made = await run('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', comment, '-f', privatePath]);
231
+ if (made.code !== 0)
232
+ throw new Error(`ssh-keygen failed: ${lastLines(made.stderr) || `exit ${made.code}`}`);
233
+ return keyBody(await readFile(`${privatePath}.pub`, 'utf8'));
234
+ }
235
+ export function sshAlias(username) {
236
+ return `superpanel-${username}`;
237
+ }
238
+ export function orgPrefix(sshCloneUrl) {
239
+ const cut = sshCloneUrl.lastIndexOf('/');
240
+ if (cut < 0)
241
+ return null;
242
+ const prefix = sshCloneUrl.slice(0, cut + 1);
243
+ const org = /([^/:]+)\/$/.exec(prefix)?.[1];
244
+ return org ? { prefix, org } : null;
245
+ }
246
+ const blockStart = (username) => `# >>> superpanel ${username} (added by superpanel setup-git)`;
247
+ const blockEnd = (username) => `# <<< superpanel ${username}`;
248
+ export function hasSshConfigBlock(username, deps = {}) {
249
+ const file = path.join(deps.home ?? homedir(), '.ssh', 'config');
250
+ return existsSync(file)
251
+ ? readFile(file, 'utf8').then((text) => text.includes(blockStart(username)))
252
+ : Promise.resolve(false);
253
+ }
254
+ export async function writeSshConfigBlock(input, deps = {}) {
255
+ const home = deps.home ?? homedir();
256
+ const file = path.join(home, '.ssh', 'config');
257
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
258
+ const existing = existsSync(file) ? await readFile(file, 'utf8') : '';
259
+ const start = blockStart(input.username);
260
+ const end = blockEnd(input.username);
261
+ const startAt = existing.indexOf(start);
262
+ const endAt = startAt >= 0 ? existing.indexOf(end, startAt) : -1;
263
+ const rest = startAt >= 0 && endAt >= 0
264
+ ? existing.slice(0, startAt) + existing.slice(endAt + end.length).replace(/^\n/, '')
265
+ : existing;
266
+ const block = [
267
+ start,
268
+ `Host ${sshAlias(input.username)}`,
269
+ ` HostName ${input.host}`,
270
+ ` Port ${input.port}`,
271
+ ' User git',
272
+ ` IdentityFile ~/.ssh/superpanel_${input.username}`,
273
+ ' IdentitiesOnly yes',
274
+ 'Match all',
275
+ end,
276
+ '',
277
+ ].join('\n');
278
+ await writeFile(file, `${block}${rest}`, { mode: 0o600 });
279
+ await chmod(file, 0o600);
280
+ return file;
281
+ }
282
+ function escapeRegExp(text) {
283
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
284
+ }
285
+ async function removeRewrites(prefix, deps, keep) {
286
+ const run = deps.run ?? defaultRun;
287
+ const listed = await run('git', ['config', '--global', '--get-regexp', '^url\\..*\\.insteadof$']);
288
+ for (const line of listed.code === 0 ? listed.stdout.split('\n') : []) {
289
+ const match = /^(\S+)\s(.*)$/.exec(line);
290
+ if (!match || match[2] !== prefix || match[1].toLowerCase() === keep?.toLowerCase())
291
+ continue;
292
+ await run('git', ['config', '--global', '--unset-all', match[1], `^${escapeRegExp(prefix)}$`]);
293
+ }
294
+ }
295
+ async function ensureInsteadOf(username, sshCloneUrl, deps) {
296
+ const run = deps.run ?? defaultRun;
297
+ const parts = orgPrefix(sshCloneUrl);
298
+ if (!parts)
299
+ throw new Error(`cannot read the org from ${sshCloneUrl}`);
300
+ const key = `url.ssh://git@${sshAlias(username)}/${parts.org}/.insteadOf`;
301
+ await removeRewrites(parts.prefix, deps, key);
302
+ const current = await run('git', ['config', '--global', '--get-all', key]);
303
+ if (!current.stdout.split('\n').includes(parts.prefix)) {
304
+ const added = await run('git', ['config', '--global', '--add', key, parts.prefix]);
305
+ if (added.code !== 0)
306
+ throw new Error(`git config failed: ${added.stderr.trim() || `exit ${added.code}`}`);
307
+ }
308
+ return parts.prefix;
309
+ }
310
+ function sshTargetOf(url) {
311
+ if (url.startsWith('ssh://')) {
312
+ try {
313
+ const parsed = new URL(url);
314
+ return { host: parsed.hostname.replace(/^\[(.*)\]$/, '$1'), port: parsed.port ? Number(parsed.port) : undefined };
315
+ }
316
+ catch {
317
+ return null;
318
+ }
319
+ }
320
+ const scp = /^(?:[^@\s/]+@)?(\[[^\]]+\]|[^:\s/]+):/.exec(url);
321
+ return scp ? { host: scp[1].replace(/^\[(.*)\]$/, '$1') } : null;
322
+ }
323
+ export async function resolvedSshTarget(sshCloneUrl, deps = {}) {
324
+ const run = deps.run ?? defaultRun;
325
+ const resolved = await run('git', ['ls-remote', '--get-url', sshCloneUrl]);
326
+ const url = resolved.code === 0 && resolved.stdout.trim() ? resolved.stdout.trim() : sshCloneUrl;
327
+ const target = sshTargetOf(url) ?? sshTargetOf(sshCloneUrl) ?? { host: '' };
328
+ return { ...target, rewritten: url !== sshCloneUrl };
329
+ }
330
+ export class KeyOnAnotherAccountError extends Error {
331
+ constructor() {
332
+ super('this key is already on another Git account');
333
+ this.name = 'KeyOnAnotherAccountError';
334
+ }
335
+ }
336
+ function sshAddAdvice(keyPath) {
337
+ return `ssh-add ${keyPath} (macOS: ssh-add --apple-use-keychain ${keyPath})`;
338
+ }
339
+ export async function sshSetupQuestions(account, allowConfig, deps = {}) {
340
+ const resolved = await resolvedSshTarget(account.sshCloneUrl, deps);
341
+ const probe = await probeSsh({ ...resolved, readOnly: true }, deps);
342
+ if (probe.kind === 'user' && probe.username === account.username)
343
+ return [];
344
+ const endpoint = { host: account.sshHost, port: account.sshPort };
345
+ const direct = resolved.rewritten ? await probeSsh({ ...endpoint, readOnly: true }, deps) : probe;
346
+ if (direct.kind === 'user') {
347
+ if (direct.username === account.username || allowConfig)
348
+ return [];
349
+ return [
350
+ `SSH signs in as ${direct.username}. Ask permission to configure a dedicated key for ${account.username}, then rerun with --allow-ssh-config "<their words>".`,
351
+ ];
352
+ }
353
+ const key = await firstOfferedKey(endpoint, deps);
354
+ return key?.privatePath && (key.locked || (await keyNeedsPassphrase(key.privatePath, deps)))
355
+ ? [`Unlock the SSH key, then rerun setup: ${sshAddAdvice(key.privatePath)}`]
356
+ : [];
357
+ }
358
+ export async function setupSshGit(input, deps = {}) {
359
+ const home = deps.home ?? homedir();
360
+ const endpoint = { host: input.account.sshHost, port: input.account.sshPort };
361
+ const title = `superpanel ${deps.hostname ?? hostname()}`;
362
+ const target = input.account.username;
363
+ const alias = sshAlias(target);
364
+ const resolved = await resolvedSshTarget(input.account.sshCloneUrl, deps);
365
+ if (resolved.rewritten) {
366
+ if (resolved.host === alias && (await hasSshConfigBlock(target, deps))) {
367
+ const viaAlias = await probeSsh({ host: alias }, deps);
368
+ if (viaAlias.kind === 'user' && viaAlias.username === target) {
369
+ await ensureInsteadOf(target, input.account.sshCloneUrl, deps);
370
+ return { status: 'ready', detail: `ssh signs in to Git as ${target} through the ${alias} host alias` };
371
+ }
372
+ }
373
+ const parts = orgPrefix(input.account.sshCloneUrl);
374
+ if (parts)
375
+ await removeRewrites(parts.prefix, deps);
376
+ }
377
+ const first = await probeSsh(endpoint, deps);
378
+ if (first.kind === 'user' && first.username === target) {
379
+ return { status: 'ready', detail: `ssh already signs in to Git as ${target}` };
380
+ }
381
+ if (first.kind === 'error')
382
+ return { status: 'failed', detail: `could not reach Git over SSH: ${first.detail}` };
383
+ if (first.kind === 'user')
384
+ return dedicated(`ssh signs in to Git as ${first.username}, not ${target}`);
385
+ let candidate = await firstOfferedKey(endpoint, deps);
386
+ if (candidate?.privatePath && (candidate.locked || (await keyNeedsPassphrase(candidate.privatePath, deps)))) {
387
+ return {
388
+ status: 'needs-ssh-add',
389
+ keyPath: candidate.privatePath,
390
+ detail: `${candidate.privatePath} has a passphrase; run once: ${sshAddAdvice(candidate.privatePath)}, then set up again`,
391
+ };
392
+ }
393
+ if (!candidate?.publicKey) {
394
+ const privatePath = path.join(home, '.ssh', 'id_ed25519');
395
+ if (existsSync(privatePath)) {
396
+ return {
397
+ status: 'failed',
398
+ detail: `${privatePath} exists but ssh does not offer it for this host; check ~/.ssh/config`,
399
+ };
400
+ }
401
+ candidate = {
402
+ source: 'file',
403
+ privatePath,
404
+ publicKey: await generateKey(privatePath, `${input.account.email} superpanel`, deps),
405
+ };
406
+ }
407
+ try {
408
+ await input.addKey(candidate.publicKey, title);
409
+ }
410
+ catch (error) {
411
+ if (error instanceof KeyOnAnotherAccountError)
412
+ return dedicated('the key ssh offers is on another Git account');
413
+ throw error;
414
+ }
415
+ const second = await probeSsh(endpoint, deps);
416
+ if (second.kind === 'user' && second.username === target) {
417
+ return {
418
+ status: 'ready',
419
+ detail: `registered ${candidate.privatePath ?? 'the ssh-agent key'} on Git account ${target}; ssh now signs in`,
420
+ };
421
+ }
422
+ if (second.kind === 'user')
423
+ return dedicated(`ssh signs in to Git as ${second.username}, not ${target}`);
424
+ if (candidate.privatePath && (await keyNeedsPassphrase(candidate.privatePath, deps))) {
425
+ return {
426
+ status: 'needs-ssh-add',
427
+ keyPath: candidate.privatePath,
428
+ detail: `the key is registered but has a passphrase; run once: ${sshAddAdvice(candidate.privatePath)}, or run git clone yourself in a terminal`,
429
+ };
430
+ }
431
+ return { status: 'failed', detail: `the key is registered but ssh still cannot sign in: ${second.detail}` };
432
+ async function dedicated(reason) {
433
+ const parts = orgPrefix(input.account.sshCloneUrl);
434
+ const plan = `A dedicated key fixes this: setup creates ~/.ssh/superpanel_${target}, puts a "Host ${alias}" block at the top of ~/.ssh/config, and adds a git setting that sends ${parts?.prefix ?? "this company's SSH addresses"} (this company's repos only) through that alias. Other accounts on ${endpoint.host} keep working as before.`;
435
+ if (!input.allowSshConfig)
436
+ return { status: 'needs-confirmation', detail: `${reason}. ${plan}` };
437
+ const privatePath = path.join(home, '.ssh', `superpanel_${target}`);
438
+ let publicKey = existsSync(privatePath) ? await publicKeyOf(privatePath, deps) : null;
439
+ if (!publicKey) {
440
+ if (existsSync(privatePath))
441
+ return { status: 'failed', detail: `${privatePath} exists but its public key cannot be read` };
442
+ publicKey = await generateKey(privatePath, `${input.account.email} superpanel`, deps);
443
+ }
444
+ try {
445
+ await input.addKey(publicKey, `${title} (${target})`);
446
+ }
447
+ catch (error) {
448
+ if (error instanceof KeyOnAnotherAccountError) {
449
+ return {
450
+ status: 'failed',
451
+ detail: `${privatePath} is on another Git account; remove it there or delete the file, then set up again`,
452
+ };
453
+ }
454
+ throw error;
455
+ }
456
+ const config = await writeSshConfigBlock({ ...endpoint, username: target }, deps);
457
+ const prefix = await ensureInsteadOf(target, input.account.sshCloneUrl, deps);
458
+ const used = await resolvedSshTarget(input.account.sshCloneUrl, deps);
459
+ const probe = await probeSsh({ host: used.host, port: used.port }, deps);
460
+ if (probe.kind === 'user' && probe.username === target) {
461
+ return {
462
+ status: 'ready',
463
+ detail: `${reason}: created ${privatePath}, added the ${alias} block to ${config} and sent ${prefix} through it; ssh now signs in as ${target}`,
464
+ };
465
+ }
466
+ return {
467
+ status: 'failed',
468
+ detail: `created ${privatePath} and the ${alias} block in ${config}, but ssh still cannot sign in: ${probe.kind === 'user' ? `signed in as ${probe.username}` : probe.detail}`,
469
+ };
470
+ }
471
+ }
@@ -0,0 +1,8 @@
1
+ export type RuntimePackage = {
2
+ root: string;
3
+ bin: string;
4
+ protocols: number[];
5
+ };
6
+ export declare function findCloneRoot(start: string): string | null;
7
+ export declare function runtimePackage(root: string): RuntimePackage | null;
8
+ //# sourceMappingURL=clone.d.ts.map
@@ -0,0 +1,39 @@
1
+ import { readFileSync, existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ function readPackage(file) {
4
+ try {
5
+ return JSON.parse(readFileSync(file, 'utf8'));
6
+ }
7
+ catch {
8
+ return null;
9
+ }
10
+ }
11
+ export function findCloneRoot(start) {
12
+ let dir = path.resolve(start);
13
+ for (;;) {
14
+ const pkg = readPackage(path.join(dir, 'package.json'));
15
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies, ...pkg?.optionalDependencies };
16
+ if (deps['@superpanel-sdk/runtime'])
17
+ return dir;
18
+ const parent = path.dirname(dir);
19
+ if (parent === dir)
20
+ return null;
21
+ dir = parent;
22
+ }
23
+ }
24
+ export function runtimePackage(root) {
25
+ const pkgPath = path.join(root, 'node_modules', '@superpanel-sdk', 'runtime', 'package.json');
26
+ if (!existsSync(pkgPath))
27
+ return null;
28
+ const pkg = readPackage(pkgPath);
29
+ if (!pkg)
30
+ return null;
31
+ const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.['superpanel-sdk-runtime'];
32
+ if (!bin)
33
+ return null;
34
+ return {
35
+ root,
36
+ bin: path.resolve(path.dirname(pkgPath), bin),
37
+ protocols: pkg.superpanel?.cliProtocol ?? [],
38
+ };
39
+ }
@@ -0,0 +1,7 @@
1
+ export type RepoCommand = {
2
+ path: string;
3
+ summary: string;
4
+ };
5
+ export declare function repoHelpText(cwd?: string): string;
6
+ export declare function formatRepoCommands(commands: RepoCommand[]): string;
7
+ //# sourceMappingURL=repo-help.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { negotiateProtocol } from '../protocol.js';
3
+ import { findCloneRoot, runtimePackage } from './clone.js';
4
+ const OUTSIDE = 'Company-repo commands are available inside a company repo.';
5
+ export function repoHelpText(cwd = process.cwd()) {
6
+ const root = findCloneRoot(cwd);
7
+ if (!root)
8
+ return OUTSIDE;
9
+ const runtime = runtimePackage(root);
10
+ if (!runtime)
11
+ return 'This repo has no installed @superpanel-sdk/runtime. Run npm install in the repo.';
12
+ const protocol = negotiateProtocol(runtime.protocols);
13
+ if (protocol === null) {
14
+ return runtime.protocols.length === 0
15
+ ? "This repo's @superpanel-sdk/runtime predates CLI handover. Run npm install @superpanel-sdk/runtime@latest, then read node_modules/@superpanel-sdk/runtime/docs/upgrading.md."
16
+ : "This CLI and the repo's runtime share no protocol. Update the CLI, or upgrade the repo's runtime.";
17
+ }
18
+ const commands = readRepoCommands(runtime, protocol);
19
+ if (!commands)
20
+ return "This repo's runtime did not list its commands. Upgrade @superpanel-sdk/runtime.";
21
+ return formatRepoCommands(commands);
22
+ }
23
+ export function formatRepoCommands(commands) {
24
+ const width = commands.reduce((longest, command) => Math.max(longest, command.path.length), 0);
25
+ const lines = commands.map((command) => ` ${command.path.padEnd(width)} ${command.summary}`);
26
+ return ['In the company repo:', ...lines].join('\n');
27
+ }
28
+ function readRepoCommands(runtime, protocol) {
29
+ const result = spawnSync(process.execPath, [runtime.bin, 'commands', '--json', '--protocol', String(protocol)], {
30
+ encoding: 'utf8',
31
+ cwd: runtime.root,
32
+ timeout: 20_000,
33
+ });
34
+ if (result.status !== 0)
35
+ return null;
36
+ try {
37
+ const body = JSON.parse(result.stdout);
38
+ if (body.version !== protocol || !Array.isArray(body.commands))
39
+ return null;
40
+ const commands = [];
41
+ for (const command of body.commands) {
42
+ if (!command || typeof command !== 'object')
43
+ return null;
44
+ const path = 'path' in command ? command.path : undefined;
45
+ const summary = 'summary' in command ? command.summary : undefined;
46
+ if (typeof path !== 'string' || typeof summary !== 'string')
47
+ return null;
48
+ commands.push({ path, summary });
49
+ }
50
+ return commands;
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ }
@@ -0,0 +1,5 @@
1
+ export type HandoverResult = {
2
+ status: number;
3
+ };
4
+ export declare function handover(args: string[], cwd?: string): Promise<HandoverResult>;
5
+ //# sourceMappingURL=run.d.ts.map
@@ -0,0 +1,67 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { negotiateProtocol } from '../protocol.js';
7
+ import { findCloneRoot, runtimePackage } from './clone.js';
8
+ const entry = fileURLToPath(new URL('../../bin/superpanel.mjs', import.meta.url));
9
+ export function handover(args, cwd = process.cwd()) {
10
+ const root = findCloneRoot(cwd);
11
+ if (!root) {
12
+ console.error('Run this in a company repo (no repo yet: superpanel setup).');
13
+ return Promise.resolve({ status: 1 });
14
+ }
15
+ const runtime = runtimePackage(root);
16
+ if (!runtime) {
17
+ console.error('This repo has no installed @superpanel-sdk/runtime. Run npm install in the repo.');
18
+ return Promise.resolve({ status: 1 });
19
+ }
20
+ const protocol = negotiateProtocol(runtime.protocols);
21
+ if (protocol === null) {
22
+ console.error(runtime.protocols.length === 0
23
+ ? "This repo's @superpanel-sdk/runtime predates CLI handover. Run npm install @superpanel-sdk/runtime@latest, then read node_modules/@superpanel-sdk/runtime/docs/upgrading.md."
24
+ : "This CLI and the repo's runtime share no protocol. Update the CLI, or upgrade the repo's runtime.");
25
+ return Promise.resolve({ status: 1 });
26
+ }
27
+ const resultFile = path.join(mkdtempSync(path.join(tmpdir(), 'superpanel-')), 'result.json');
28
+ return new Promise((resolve) => {
29
+ const child = spawn(process.execPath, [runtime.bin, ...args], {
30
+ cwd: root,
31
+ stdio: ['inherit', 'inherit', 'inherit', 'pipe'],
32
+ env: {
33
+ ...process.env,
34
+ SUPERPANEL_CLI: entry,
35
+ SUPERPANEL_CLI_PROTOCOL: String(protocol),
36
+ INIT_CWD: cwd,
37
+ SUPERPANEL_AGENT: process.env.SUPERPANEL_AGENT ?? '',
38
+ SUPERPANEL_CLI_RESULT: resultFile,
39
+ SUPERPANEL_CLI_LIFETIME_FD: '3',
40
+ },
41
+ });
42
+ const lifetime = child.stdio[3];
43
+ lifetime?.unref?.();
44
+ child.on('exit', (code) => {
45
+ lifetime?.destroy?.();
46
+ let status = code ?? 1;
47
+ let confirmed = false;
48
+ try {
49
+ const body = JSON.parse(readFileSync(resultFile, 'utf8'));
50
+ confirmed = body.version === 1 && body.status === 'confirmation_required';
51
+ }
52
+ catch {
53
+ confirmed = false;
54
+ }
55
+ if (confirmed)
56
+ status = 2;
57
+ else if (status === 2)
58
+ status = 1;
59
+ try {
60
+ rmSync(path.dirname(resultFile), { recursive: true, force: true });
61
+ }
62
+ catch {
63
+ }
64
+ resolve({ status });
65
+ });
66
+ });
67
+ }