@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.
- package/README.md +16 -2
- package/bin/superpanel.mjs +23 -0
- package/dist/api/platform.d.ts +31 -0
- package/dist/api/platform.js +39 -0
- package/dist/auth/auth.d.ts +162 -0
- package/dist/auth/auth.js +923 -0
- package/dist/auth/backend-url.d.ts +7 -0
- package/dist/auth/backend-url.js +41 -0
- package/dist/auth/cli-login.d.ts +8 -0
- package/dist/auth/cli-login.js +92 -0
- package/dist/auth/clipboard.d.ts +8 -0
- package/dist/auth/clipboard.js +42 -0
- package/dist/auth/file-lock.d.ts +25 -0
- package/dist/auth/file-lock.js +173 -0
- package/dist/auth/http.d.ts +34 -0
- package/dist/auth/http.js +48 -0
- package/dist/auth/index.d.ts +13 -0
- package/dist/auth/index.js +117 -0
- package/dist/auth/origin-guard.d.ts +4 -0
- package/dist/auth/origin-guard.js +9 -0
- package/dist/auth/origin.d.ts +17 -0
- package/dist/auth/origin.js +142 -0
- package/dist/auth/pending-login.d.ts +5 -0
- package/dist/auth/pending-login.js +67 -0
- package/dist/commands/auth-token.d.ts +26 -0
- package/dist/commands/auth-token.js +71 -0
- package/dist/commands/git-method.d.ts +54 -0
- package/dist/commands/git-method.js +180 -0
- package/dist/commands/setup.d.ts +88 -0
- package/dist/commands/setup.js +366 -0
- package/dist/commands/skill.d.ts +29 -0
- package/dist/commands/skill.js +169 -0
- package/dist/commands/ssh-key.d.ts +13 -0
- package/dist/commands/ssh-key.js +83 -0
- package/dist/git/credential.d.ts +7 -0
- package/dist/git/credential.js +66 -0
- package/dist/git/index.d.ts +36 -0
- package/dist/git/index.js +119 -0
- package/dist/git/run.d.ts +13 -0
- package/dist/git/run.js +32 -0
- package/dist/git/setup.d.ts +97 -0
- package/dist/git/setup.js +471 -0
- package/dist/handover/clone.d.ts +8 -0
- package/dist/handover/clone.js +39 -0
- package/dist/handover/repo-help.d.ts +7 -0
- package/dist/handover/repo-help.js +55 -0
- package/dist/handover/run.d.ts +5 -0
- package/dist/handover/run.js +67 -0
- package/dist/inbound/index.d.ts +44 -0
- package/dist/inbound/index.js +129 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +251 -0
- package/dist/logs/index.d.ts +19 -0
- package/dist/logs/index.js +132 -0
- package/dist/npm-launch.d.ts +19 -0
- package/dist/npm-launch.js +80 -0
- package/dist/ops/agent.d.ts +3 -0
- package/dist/ops/agent.js +14 -0
- package/dist/ops/cache.d.ts +18 -0
- package/dist/ops/cache.js +92 -0
- package/dist/ops/parse.d.ts +6 -0
- package/dist/ops/parse.js +106 -0
- package/dist/ops/register.d.ts +18 -0
- package/dist/ops/register.js +174 -0
- package/dist/ops/run.d.ts +20 -0
- package/dist/ops/run.js +127 -0
- package/dist/ops/types.d.ts +41 -0
- package/dist/ops/types.js +16 -0
- package/dist/protocol.d.ts +4 -0
- package/dist/protocol.js +17 -0
- package/dist/reserved.d.ts +4 -0
- package/dist/reserved.js +25 -0
- package/dist/turns/index.d.ts +20 -0
- package/dist/turns/index.js +108 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +11 -0
- package/package.json +48 -4
- package/skill/SKILL.md +17 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function toWsUrl(raw: string): URL;
|
|
2
|
+
export declare function toHttpUrl(raw: string): URL;
|
|
3
|
+
export declare const DEFAULT_BACKEND_URL = "https://api.superpanel.io";
|
|
4
|
+
export declare function backendCacheKey(raw: string): string;
|
|
5
|
+
export declare function sameBackend(a: string, b: string): boolean;
|
|
6
|
+
export declare function isDefaultBackend(backendUrl: string): boolean;
|
|
7
|
+
//# sourceMappingURL=backend-url.d.ts.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export function toWsUrl(raw) {
|
|
2
|
+
const url = new URL(raw);
|
|
3
|
+
if (url.protocol === 'http:')
|
|
4
|
+
url.protocol = 'ws:';
|
|
5
|
+
else if (url.protocol === 'https:')
|
|
6
|
+
url.protocol = 'wss:';
|
|
7
|
+
else if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {
|
|
8
|
+
throw new Error(`unsupported backend url: ${raw}`);
|
|
9
|
+
}
|
|
10
|
+
return url;
|
|
11
|
+
}
|
|
12
|
+
export function toHttpUrl(raw) {
|
|
13
|
+
const url = new URL(raw);
|
|
14
|
+
if (url.protocol === 'ws:')
|
|
15
|
+
url.protocol = 'http:';
|
|
16
|
+
else if (url.protocol === 'wss:')
|
|
17
|
+
url.protocol = 'https:';
|
|
18
|
+
else if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
19
|
+
throw new Error(`unsupported backend url: ${raw}`);
|
|
20
|
+
}
|
|
21
|
+
return url;
|
|
22
|
+
}
|
|
23
|
+
export const DEFAULT_BACKEND_URL = 'https://api.superpanel.io';
|
|
24
|
+
export function backendCacheKey(raw) {
|
|
25
|
+
const url = toHttpUrl(raw);
|
|
26
|
+
url.pathname = url.pathname.replace(/\/+$/, '');
|
|
27
|
+
url.search = '';
|
|
28
|
+
url.hash = '';
|
|
29
|
+
return url.toString();
|
|
30
|
+
}
|
|
31
|
+
export function sameBackend(a, b) {
|
|
32
|
+
try {
|
|
33
|
+
return backendCacheKey(a) === backendCacheKey(b);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export function isDefaultBackend(backendUrl) {
|
|
40
|
+
return sameBackend(backendUrl, DEFAULT_BACKEND_URL);
|
|
41
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type AuthorizeCliOptions, type CliAuthorization } from './auth.js';
|
|
2
|
+
export declare function loginCli(backendUrl: string, options?: AuthorizeCliOptions & {
|
|
3
|
+
file?: string;
|
|
4
|
+
resumable?: boolean;
|
|
5
|
+
checkedLogin?: string | null;
|
|
6
|
+
}): Promise<CliAuthorization>;
|
|
7
|
+
export declare function forgetCliAuthorization(backendUrl: string, authorization: CliAuthorization): Promise<void>;
|
|
8
|
+
//# sourceMappingURL=cli-login.d.ts.map
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { AuthorizationPendingError, UnconfirmedExchangeError, authorizeCli, backendAcceptsCliLogin, cacheCliAuthorization, cliDeviceName, LoginCancelledError, LOGIN_SAVE_WAIT_MS, loginStillCurrent, readLoginEpoch, loginLeftOnBackend, loginNotFinished, readCliAuthorizationStatus, removeCachedCliAuthorization, revokeCliLogin, withLoginMark, } from './auth.js';
|
|
2
|
+
import { readPendingLogin, savePendingLogin, clearPendingLogin } from './pending-login.js';
|
|
3
|
+
const logger = {
|
|
4
|
+
warn(message, error) {
|
|
5
|
+
console.error(message, error instanceof Error ? error.message : error);
|
|
6
|
+
},
|
|
7
|
+
};
|
|
8
|
+
export async function loginCli(backendUrl, options = {}) {
|
|
9
|
+
const file = options.file;
|
|
10
|
+
const epoch = options.epoch ?? (await readLoginEpoch(backendUrl, file));
|
|
11
|
+
const before = await readCliAuthorizationStatus(backendUrl, file);
|
|
12
|
+
return withLoginMark(backendUrl, async (waited) => {
|
|
13
|
+
if (!(await loginStillCurrent(backendUrl, epoch, file)))
|
|
14
|
+
throw new LoginCancelledError();
|
|
15
|
+
const previous = await readCliAuthorizationStatus(backendUrl, file);
|
|
16
|
+
if (previous.loggedIn &&
|
|
17
|
+
options.checkedLogin !== undefined &&
|
|
18
|
+
previous.authorization.refreshToken !== options.checkedLogin) {
|
|
19
|
+
if (await backendAcceptsCliLogin(backendUrl, previous.authorization.accessToken))
|
|
20
|
+
return previous.authorization;
|
|
21
|
+
}
|
|
22
|
+
else if (waited &&
|
|
23
|
+
previous.loggedIn &&
|
|
24
|
+
(!before.loggedIn || previous.authorization.refreshToken !== before.authorization.refreshToken)) {
|
|
25
|
+
return previous.authorization;
|
|
26
|
+
}
|
|
27
|
+
if (previous.loggedIn) {
|
|
28
|
+
try {
|
|
29
|
+
await revokeCliLogin(backendUrl, previous.authorization);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
throw new Error(`could not end this machine's current login on ${backendUrl} (${error instanceof Error ? error.message : String(error)}); nothing was changed, try again when the backend can be reached`);
|
|
33
|
+
}
|
|
34
|
+
await removeCachedCliAuthorization(backendUrl, {
|
|
35
|
+
refreshToken: previous.authorization.refreshToken,
|
|
36
|
+
waitMs: LOGIN_SAVE_WAIT_MS,
|
|
37
|
+
}, file);
|
|
38
|
+
}
|
|
39
|
+
const deviceName = options.deviceName ?? cliDeviceName();
|
|
40
|
+
let authorization;
|
|
41
|
+
try {
|
|
42
|
+
authorization = await authorizeCli(backendUrl, {
|
|
43
|
+
...options,
|
|
44
|
+
deviceName,
|
|
45
|
+
epoch,
|
|
46
|
+
...(options.resumable
|
|
47
|
+
? {
|
|
48
|
+
resume: readPendingLogin(backendUrl, epoch) ?? undefined,
|
|
49
|
+
onStarted: (login) => savePendingLogin(backendUrl, login, epoch),
|
|
50
|
+
}
|
|
51
|
+
: {}),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (options.resumable &&
|
|
56
|
+
!(error instanceof AuthorizationPendingError) &&
|
|
57
|
+
!(error instanceof UnconfirmedExchangeError))
|
|
58
|
+
await clearPendingLogin(backendUrl, undefined, epoch);
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
const madeAt = new Date(authorization.connectedAt ?? Date.now());
|
|
62
|
+
try {
|
|
63
|
+
await cacheCliAuthorization(backendUrl, authorization, file, { waitMs: LOGIN_SAVE_WAIT_MS, epoch });
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error instanceof LoginCancelledError) {
|
|
67
|
+
await revokeCliLogin(backendUrl, authorization).catch(() => undefined);
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
logger.warn('could not cache the CLI login', error);
|
|
71
|
+
const saved = await readCliAuthorizationStatus(backendUrl, file).catch(() => ({ loggedIn: false }));
|
|
72
|
+
if (!(saved.loggedIn && saved.authorization.refreshToken === authorization.refreshToken)) {
|
|
73
|
+
const ended = await revokeCliLogin(backendUrl, authorization).then(() => true, () => false);
|
|
74
|
+
if (ended)
|
|
75
|
+
throw loginNotFinished(backendUrl, 'could not save the login on this machine', error);
|
|
76
|
+
throw loginLeftOnBackend(backendUrl, 'the login was made on the backend, but this machine could neither save it nor end it', error, deviceName, madeAt);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (options.resumable)
|
|
80
|
+
await clearPendingLogin(backendUrl, undefined, epoch);
|
|
81
|
+
return authorization;
|
|
82
|
+
}, { say: options.say, ...(file ? { file } : {}) });
|
|
83
|
+
}
|
|
84
|
+
export async function forgetCliAuthorization(backendUrl, authorization) {
|
|
85
|
+
await revokeCliLogin(backendUrl, authorization).catch(() => undefined);
|
|
86
|
+
try {
|
|
87
|
+
await removeCachedCliAuthorization(backendUrl, { refreshToken: authorization.refreshToken });
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
logger.warn('could not clear the cached CLI login', error);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type ClipboardCommand = {
|
|
2
|
+
file: string;
|
|
3
|
+
args: string[];
|
|
4
|
+
};
|
|
5
|
+
export declare function clipboardCommands(platform: NodeJS.Platform): ClipboardCommand[];
|
|
6
|
+
export declare const CLIPBOARD_WORST_MS: number;
|
|
7
|
+
export declare function copyToClipboard(text: string, platform?: NodeJS.Platform): void;
|
|
8
|
+
//# sourceMappingURL=clipboard.d.ts.map
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
export function clipboardCommands(platform) {
|
|
3
|
+
switch (platform) {
|
|
4
|
+
case 'darwin':
|
|
5
|
+
return [{ file: 'pbcopy', args: [] }];
|
|
6
|
+
case 'win32':
|
|
7
|
+
return [{ file: 'clip.exe', args: [] }];
|
|
8
|
+
case 'linux':
|
|
9
|
+
return [
|
|
10
|
+
{ file: 'wl-copy', args: [] },
|
|
11
|
+
{ file: 'xclip', args: ['-selection', 'clipboard'] },
|
|
12
|
+
{ file: 'xsel', args: ['--clipboard', '--input'] },
|
|
13
|
+
];
|
|
14
|
+
default:
|
|
15
|
+
return [];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const CLIPBOARD_TIMEOUT_MS = 3_000;
|
|
19
|
+
export const CLIPBOARD_WORST_MS = CLIPBOARD_TIMEOUT_MS * 3;
|
|
20
|
+
export function copyToClipboard(text, platform = process.platform) {
|
|
21
|
+
const commands = clipboardCommands(platform);
|
|
22
|
+
if (commands.length === 0)
|
|
23
|
+
throw new Error(`clipboard copy is not supported on ${platform}`);
|
|
24
|
+
const failures = [];
|
|
25
|
+
for (const command of commands) {
|
|
26
|
+
const result = spawnSync(command.file, command.args, {
|
|
27
|
+
input: text,
|
|
28
|
+
encoding: 'utf8',
|
|
29
|
+
stdio: ['pipe', 'ignore', 'ignore'],
|
|
30
|
+
timeout: CLIPBOARD_TIMEOUT_MS,
|
|
31
|
+
killSignal: 'SIGKILL',
|
|
32
|
+
});
|
|
33
|
+
if (!result.error && result.status === 0)
|
|
34
|
+
return;
|
|
35
|
+
const timedOut = result.error?.code === 'ETIMEDOUT';
|
|
36
|
+
const detail = timedOut
|
|
37
|
+
? `stopped after ${CLIPBOARD_TIMEOUT_MS / 1000} s`
|
|
38
|
+
: (result.error?.message ?? (result.signal ? `ended by ${result.signal}` : `exit ${result.status}`));
|
|
39
|
+
failures.push(`${command.file}: ${detail}`);
|
|
40
|
+
}
|
|
41
|
+
throw new Error(failures.join('; '));
|
|
42
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export type LockOwner = {
|
|
2
|
+
pid: number;
|
|
3
|
+
nonce: string;
|
|
4
|
+
at: number;
|
|
5
|
+
};
|
|
6
|
+
export type FileLockOptions = {
|
|
7
|
+
staleMs: number;
|
|
8
|
+
waitMs: number;
|
|
9
|
+
pollMs?: number;
|
|
10
|
+
onWait?: (owner: LockOwner) => void;
|
|
11
|
+
};
|
|
12
|
+
export type HeldLock = {
|
|
13
|
+
owner: LockOwner;
|
|
14
|
+
waited: boolean;
|
|
15
|
+
held: () => Promise<boolean>;
|
|
16
|
+
release: () => Promise<void>;
|
|
17
|
+
};
|
|
18
|
+
export declare class LockWaitTimeoutError extends Error {
|
|
19
|
+
readonly owner: LockOwner | null;
|
|
20
|
+
constructor(owner: LockOwner | null);
|
|
21
|
+
}
|
|
22
|
+
export declare function processGone(pid: number): boolean;
|
|
23
|
+
export declare function readLockOwner(file: string): Promise<LockOwner | null>;
|
|
24
|
+
export declare function acquireFileLock(file: string, options: FileLockOptions): Promise<HeldLock>;
|
|
25
|
+
//# sourceMappingURL=file-lock.d.ts.map
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { link, lstat, open, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
export class LockWaitTimeoutError extends Error {
|
|
4
|
+
owner;
|
|
5
|
+
constructor(owner) {
|
|
6
|
+
super('timed out waiting for another process to release the lock');
|
|
7
|
+
this.owner = owner;
|
|
8
|
+
this.name = 'LockWaitTimeoutError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
const BREAKER_STALE_MS = 5_000;
|
|
12
|
+
const NO_HARD_LINKS = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS']);
|
|
13
|
+
function errorCode(error) {
|
|
14
|
+
return error && typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
15
|
+
}
|
|
16
|
+
function wait(ms) {
|
|
17
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
18
|
+
}
|
|
19
|
+
export function processGone(pid) {
|
|
20
|
+
try {
|
|
21
|
+
process.kill(pid, 0);
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
return errorCode(error) === 'ESRCH';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function parseOwner(text) {
|
|
29
|
+
try {
|
|
30
|
+
const owner = JSON.parse(text);
|
|
31
|
+
return typeof owner.pid === 'number' && typeof owner.nonce === 'string' && typeof owner.at === 'number'
|
|
32
|
+
? owner
|
|
33
|
+
: null;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export async function readLockOwner(file) {
|
|
40
|
+
try {
|
|
41
|
+
return parseOwner(await readFile(file, 'utf8'));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async function observe(file) {
|
|
48
|
+
try {
|
|
49
|
+
const info = await lstat(file);
|
|
50
|
+
return { owner: await readLockOwner(file), ino: info.ino, mtimeMs: info.mtimeMs };
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (errorCode(error) === 'ENOENT')
|
|
54
|
+
return null;
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function sameLock(a, b) {
|
|
59
|
+
if (a.owner || b.owner)
|
|
60
|
+
return Boolean(a.owner && b.owner && a.owner.nonce === b.owner.nonce);
|
|
61
|
+
return a.ino === b.ino && a.mtimeMs === b.mtimeMs;
|
|
62
|
+
}
|
|
63
|
+
function leftOver(found, staleMs) {
|
|
64
|
+
if (found.owner && processGone(found.owner.pid))
|
|
65
|
+
return true;
|
|
66
|
+
return Date.now() - (found.owner?.at ?? found.mtimeMs) > staleMs;
|
|
67
|
+
}
|
|
68
|
+
function temporaryPath(file) {
|
|
69
|
+
return `${file}.${randomBytes(6).toString('hex')}.tmp`;
|
|
70
|
+
}
|
|
71
|
+
async function createWith(file, content, temporary) {
|
|
72
|
+
await writeFile(temporary, content, { mode: 0o600 });
|
|
73
|
+
try {
|
|
74
|
+
await link(temporary, file);
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (errorCode(error) === 'EEXIST')
|
|
79
|
+
return false;
|
|
80
|
+
if (!NO_HARD_LINKS.has(String(errorCode(error))))
|
|
81
|
+
throw error;
|
|
82
|
+
try {
|
|
83
|
+
const handle = await open(file, 'wx', 0o600);
|
|
84
|
+
try {
|
|
85
|
+
await handle.writeFile(content);
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
await handle.close();
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
catch (fallback) {
|
|
93
|
+
if (errorCode(fallback) === 'EEXIST')
|
|
94
|
+
return false;
|
|
95
|
+
throw fallback;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function newOwner() {
|
|
100
|
+
return { pid: process.pid, nonce: randomBytes(8).toString('hex'), at: Date.now() };
|
|
101
|
+
}
|
|
102
|
+
async function breakLock(file, found, staleMs) {
|
|
103
|
+
const breaker = `${file}.break`;
|
|
104
|
+
const me = newOwner();
|
|
105
|
+
const temporary = temporaryPath(breaker);
|
|
106
|
+
let created;
|
|
107
|
+
try {
|
|
108
|
+
created = await createWith(breaker, JSON.stringify(me), temporary);
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
await rm(temporary, { force: true });
|
|
112
|
+
}
|
|
113
|
+
if (!created) {
|
|
114
|
+
const other = await observe(breaker);
|
|
115
|
+
if (other && leftOver(other, BREAKER_STALE_MS))
|
|
116
|
+
await rm(breaker, { force: true });
|
|
117
|
+
else
|
|
118
|
+
await wait(10);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const now = await observe(file);
|
|
123
|
+
if (now && sameLock(now, found) && leftOver(now, staleMs))
|
|
124
|
+
await rm(file, { force: true });
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
if ((await readLockOwner(breaker))?.nonce === me.nonce)
|
|
128
|
+
await rm(breaker, { force: true });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
export async function acquireFileLock(file, options) {
|
|
132
|
+
const mine = newOwner();
|
|
133
|
+
const deadline = Date.now() + options.waitMs;
|
|
134
|
+
const temporary = temporaryPath(file);
|
|
135
|
+
let waited = false;
|
|
136
|
+
try {
|
|
137
|
+
for (;;) {
|
|
138
|
+
mine.at = Date.now();
|
|
139
|
+
if (await createWith(file, JSON.stringify(mine), temporary))
|
|
140
|
+
break;
|
|
141
|
+
const found = await observe(file);
|
|
142
|
+
if (!found)
|
|
143
|
+
continue;
|
|
144
|
+
if (found.owner?.nonce === mine.nonce)
|
|
145
|
+
break;
|
|
146
|
+
if (leftOver(found, options.staleMs)) {
|
|
147
|
+
await breakLock(file, found, options.staleMs);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (!waited) {
|
|
151
|
+
waited = true;
|
|
152
|
+
if (found.owner)
|
|
153
|
+
options.onWait?.(found.owner);
|
|
154
|
+
}
|
|
155
|
+
if (Date.now() >= deadline)
|
|
156
|
+
throw new LockWaitTimeoutError(found.owner);
|
|
157
|
+
await wait(options.pollMs ?? 100);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
await rm(temporary, { force: true });
|
|
162
|
+
}
|
|
163
|
+
const held = async () => (await readLockOwner(file))?.nonce === mine.nonce;
|
|
164
|
+
return {
|
|
165
|
+
owner: mine,
|
|
166
|
+
waited,
|
|
167
|
+
held,
|
|
168
|
+
release: async () => {
|
|
169
|
+
if (await held())
|
|
170
|
+
await rm(file, { force: true });
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export declare const API_REQUEST_TIMEOUT_MS = 15000;
|
|
2
|
+
export declare function apiUrl(backendUrl: string, path: string): string;
|
|
3
|
+
export declare function cliRequestHeaders(headers?: RequestInit['headers'], sendVersion?: boolean): Headers;
|
|
4
|
+
export declare function requestJson<T>(url: string, init: RequestInit, options?: {
|
|
5
|
+
cliVersion?: boolean;
|
|
6
|
+
}): Promise<{
|
|
7
|
+
response: Response;
|
|
8
|
+
payload: T & {
|
|
9
|
+
error?: string;
|
|
10
|
+
};
|
|
11
|
+
}>;
|
|
12
|
+
export declare function postJson<T>(url: string, body: unknown): Promise<{
|
|
13
|
+
response: Response;
|
|
14
|
+
payload: T & {
|
|
15
|
+
error?: string;
|
|
16
|
+
};
|
|
17
|
+
}>;
|
|
18
|
+
export declare function getJson<T>(url: string, token: string, options?: {
|
|
19
|
+
cliVersion?: boolean;
|
|
20
|
+
}): Promise<{
|
|
21
|
+
response: Response;
|
|
22
|
+
payload: T & {
|
|
23
|
+
error?: string;
|
|
24
|
+
};
|
|
25
|
+
}>;
|
|
26
|
+
export declare function sendJson<T>(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', url: string, token: string, body?: unknown, options?: {
|
|
27
|
+
cliVersion?: boolean;
|
|
28
|
+
}): Promise<{
|
|
29
|
+
response: Response;
|
|
30
|
+
payload: T & {
|
|
31
|
+
error?: string;
|
|
32
|
+
};
|
|
33
|
+
}>;
|
|
34
|
+
//# sourceMappingURL=http.d.ts.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { toHttpUrl } from './backend-url.js';
|
|
2
|
+
import { cliVersion } from '../version.js';
|
|
3
|
+
export const API_REQUEST_TIMEOUT_MS = 15_000;
|
|
4
|
+
export function apiUrl(backendUrl, path) {
|
|
5
|
+
const url = toHttpUrl(backendUrl);
|
|
6
|
+
url.pathname = `/api/${path.replace(/^\//, '')}`;
|
|
7
|
+
url.search = '';
|
|
8
|
+
url.hash = '';
|
|
9
|
+
return url.toString();
|
|
10
|
+
}
|
|
11
|
+
export function cliRequestHeaders(headers, sendVersion = true) {
|
|
12
|
+
const next = new Headers(headers);
|
|
13
|
+
if (sendVersion && !next.has('Superpanel-Cli-Version'))
|
|
14
|
+
next.set('Superpanel-Cli-Version', cliVersion());
|
|
15
|
+
return next;
|
|
16
|
+
}
|
|
17
|
+
export async function requestJson(url, init, options) {
|
|
18
|
+
const response = await fetch(url, {
|
|
19
|
+
...init,
|
|
20
|
+
headers: cliRequestHeaders(init.headers, options?.cliVersion !== false),
|
|
21
|
+
signal: AbortSignal.timeout(API_REQUEST_TIMEOUT_MS),
|
|
22
|
+
});
|
|
23
|
+
const payload = (await response.json().catch(() => ({})));
|
|
24
|
+
return { response, payload };
|
|
25
|
+
}
|
|
26
|
+
export async function postJson(url, body) {
|
|
27
|
+
return requestJson(url, {
|
|
28
|
+
method: 'POST',
|
|
29
|
+
headers: { 'Content-Type': 'application/json' },
|
|
30
|
+
body: JSON.stringify(body),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
export async function getJson(url, token, options) {
|
|
34
|
+
return requestJson(url, {
|
|
35
|
+
method: 'GET',
|
|
36
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
37
|
+
}, options);
|
|
38
|
+
}
|
|
39
|
+
export async function sendJson(method, url, token, body, options) {
|
|
40
|
+
return requestJson(url, {
|
|
41
|
+
method,
|
|
42
|
+
headers: {
|
|
43
|
+
Authorization: `Bearer ${token}`,
|
|
44
|
+
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
45
|
+
},
|
|
46
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
47
|
+
}, options);
|
|
48
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const LOGOUT_SCOPE = "MCP connections are not touched (see \"Connected apps and devices\" on your account page in the web app), nor are SSH keys on your Git account (in Gitea under Settings \u2192 SSH / GPG Keys).";
|
|
2
|
+
export declare function runLogin(options: {
|
|
3
|
+
url?: string;
|
|
4
|
+
open?: boolean;
|
|
5
|
+
waitSeconds?: number;
|
|
6
|
+
}): Promise<void>;
|
|
7
|
+
export declare function runLogout(options: {
|
|
8
|
+
url?: string;
|
|
9
|
+
}): Promise<void>;
|
|
10
|
+
export declare function runWhoami(options: {
|
|
11
|
+
url?: string;
|
|
12
|
+
}): Promise<void>;
|
|
13
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { announceBackend, cliCommand, backendAcceptsCliLogin, loginCommand, CliLoginRejectedError, CliVersionRejectedError, getValidCliAuthorization, beginLogout, LoginCancelledError, LOGIN_SAVE_WAIT_MS, readCliAuthorizationStatus, readLoginEpoch, removeCachedCliAuthorization, resolveBackend, resolveBackendUrl, revokeCliLogin, } from './auth.js';
|
|
2
|
+
import { loginCli } from './cli-login.js';
|
|
3
|
+
import { backendWhoamiText } from '../ops/register.js';
|
|
4
|
+
import { runningAsAgent, hasTerminal } from '../ops/agent.js';
|
|
5
|
+
import { AuthorizationPendingError } from './auth.js';
|
|
6
|
+
import { clearPendingLogin } from './pending-login.js';
|
|
7
|
+
export const LOGOUT_SCOPE = 'MCP connections are not touched (see "Connected apps and devices" on your account page in the web app), nor are SSH keys on your Git account (in Gitea under Settings → SSH / GPG Keys).';
|
|
8
|
+
function errorText(error) {
|
|
9
|
+
return error instanceof Error ? error.message : String(error);
|
|
10
|
+
}
|
|
11
|
+
function describe(authorization) {
|
|
12
|
+
return `${authorization.user.email} for ${authorization.companyName ?? authorization.companyId}`;
|
|
13
|
+
}
|
|
14
|
+
export async function runLogin(options) {
|
|
15
|
+
const backend = resolveBackend(options.url);
|
|
16
|
+
announceBackend(backend);
|
|
17
|
+
const backendUrl = backend.url;
|
|
18
|
+
const epoch = await readLoginEpoch(backendUrl);
|
|
19
|
+
const current = await getValidCliAuthorization(backendUrl).catch((error) => {
|
|
20
|
+
if (error instanceof CliLoginRejectedError)
|
|
21
|
+
return null;
|
|
22
|
+
throw error;
|
|
23
|
+
});
|
|
24
|
+
if (current && (await backendAcceptsCliLogin(backendUrl, current.accessToken))) {
|
|
25
|
+
console.log(`Already logged in as ${describe(current)}.`);
|
|
26
|
+
console.log(`To log in again (for example for another company), run \`${cliCommand('logout', backendUrl)}\`, then \`${loginCommand(backendUrl)}\`.`);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const agent = runningAsAgent() || !hasTerminal();
|
|
30
|
+
const waitSeconds = options.waitSeconds ?? 20;
|
|
31
|
+
let authorization;
|
|
32
|
+
try {
|
|
33
|
+
authorization = await loginCli(backendUrl, {
|
|
34
|
+
openBrowser: options.open,
|
|
35
|
+
checkedLogin: current?.refreshToken ?? null,
|
|
36
|
+
epoch,
|
|
37
|
+
...(agent ? { resumable: true, pollTiming: { maxWaitMs: waitSeconds * 1000 } } : {}),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (error instanceof AuthorizationPendingError)
|
|
42
|
+
throw error;
|
|
43
|
+
if (error instanceof LoginCancelledError) {
|
|
44
|
+
console.log('Logout cancelled this login before it was saved.');
|
|
45
|
+
process.exitCode = 1;
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
console.log(`Logged in as ${describe(authorization)}`);
|
|
51
|
+
}
|
|
52
|
+
export async function runLogout(options) {
|
|
53
|
+
const backendUrl = resolveBackendUrl(options.url);
|
|
54
|
+
const { epoch, authorization } = await beginLogout(backendUrl);
|
|
55
|
+
await clearPendingLogin(backendUrl, undefined, epoch);
|
|
56
|
+
if (!authorization) {
|
|
57
|
+
console.log(`Not logged in to ${backendUrl}`);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
await revokeCliLogin(backendUrl, authorization);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
console.log(`Could not reach ${backendUrl} (${errorText(error)}); you are still logged in. Run logout again when the backend can be reached.`);
|
|
65
|
+
process.exitCode = 1;
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
await removeCachedCliAuthorization(backendUrl, {
|
|
69
|
+
refreshToken: authorization.refreshToken,
|
|
70
|
+
logoutId: authorization.logoutId,
|
|
71
|
+
waitMs: LOGIN_SAVE_WAIT_MS,
|
|
72
|
+
});
|
|
73
|
+
console.log(`Logged out of ${backendUrl}. ${LOGOUT_SCOPE}`);
|
|
74
|
+
}
|
|
75
|
+
export async function runWhoami(options) {
|
|
76
|
+
const backendUrl = resolveBackendUrl(options.url);
|
|
77
|
+
const status = await readCliAuthorizationStatus(backendUrl);
|
|
78
|
+
if (!status.loggedIn) {
|
|
79
|
+
console.log(`Not logged in to ${backendUrl}`);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
console.log(`Backend: ${backendUrl}`);
|
|
83
|
+
console.log(`User: ${status.authorization.user.email}`);
|
|
84
|
+
console.log(`Company: ${status.authorization.companyName ?? status.authorization.companyId}`);
|
|
85
|
+
let accepted;
|
|
86
|
+
try {
|
|
87
|
+
const current = await getValidCliAuthorization(backendUrl);
|
|
88
|
+
accepted = current !== null && (await backendAcceptsCliLogin(backendUrl, current.accessToken));
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (error instanceof CliLoginRejectedError) {
|
|
92
|
+
console.log(`Session: ended (logged out elsewhere, disconnected, or unused for 30 days); run "${loginCommand(backendUrl)}"`);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (error instanceof CliVersionRejectedError) {
|
|
96
|
+
console.error(error.message);
|
|
97
|
+
process.exitCode = 1;
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
console.log(`Session: could not check with the backend (${errorText(error)})`);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
console.log(accepted
|
|
104
|
+
? 'Session: active; renews itself while in use (30 days unused and it ends)'
|
|
105
|
+
: `Session: refused by the backend (disconnected, or the company or your access is suspended); run "${loginCommand(backendUrl)}"`);
|
|
106
|
+
if (!accepted)
|
|
107
|
+
return;
|
|
108
|
+
try {
|
|
109
|
+
const text = await backendWhoamiText(backendUrl);
|
|
110
|
+
if (text)
|
|
111
|
+
console.log(`\n${text}`);
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
console.error(error instanceof Error ? error.message : error);
|
|
115
|
+
process.exitCode = 1;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { getGitAccount } from '../api/platform.js';
|
|
2
|
+
import { assertRepoMatchesLogin, findCompanyRepo } from './origin.js';
|
|
3
|
+
export async function guardNetworkedClone(start, backendUrl, token, options) {
|
|
4
|
+
const root = findCompanyRepo(start);
|
|
5
|
+
if (!root)
|
|
6
|
+
return;
|
|
7
|
+
const account = await getGitAccount(backendUrl, token, options);
|
|
8
|
+
await assertRepoMatchesLogin(root, account ?? { httpsCloneUrl: null, sshCloneUrl: null }, backendUrl);
|
|
9
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare function orgFromCloneUrl(cloneUrl: string): string | null;
|
|
2
|
+
export type RepoIdentity = {
|
|
3
|
+
httpsCloneUrl: string | null;
|
|
4
|
+
sshCloneUrl: string | null;
|
|
5
|
+
};
|
|
6
|
+
type Remote = {
|
|
7
|
+
protocol: string;
|
|
8
|
+
host: string;
|
|
9
|
+
port: string;
|
|
10
|
+
path: string;
|
|
11
|
+
};
|
|
12
|
+
export declare function parseRemote(value: string): Remote | null;
|
|
13
|
+
export declare function remotesMatch(origin: string, identity: RepoIdentity, sshConfigFile?: string): boolean;
|
|
14
|
+
export { findCloneRoot as findCompanyRepo } from '../handover/clone.js';
|
|
15
|
+
export declare function companyCloneStatus(root: string, identity: RepoIdentity): Promise<'missing' | 'different' | 'matches'>;
|
|
16
|
+
export declare function assertRepoMatchesLogin(root: string, identity: RepoIdentity, backendUrl: string): Promise<void>;
|
|
17
|
+
//# sourceMappingURL=origin.d.ts.map
|