@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,923 @@
|
|
|
1
|
+
import { cliRequestHeaders } from './http.js';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
4
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { homedir, hostname } from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
import { backendCacheKey, DEFAULT_BACKEND_URL, isDefaultBackend, sameBackend, toHttpUrl } from './backend-url.js';
|
|
9
|
+
import { findCloneRoot } from '../handover/clone.js';
|
|
10
|
+
import { CLIPBOARD_WORST_MS, copyToClipboard } from './clipboard.js';
|
|
11
|
+
import { acquireFileLock, LockWaitTimeoutError } from './file-lock.js';
|
|
12
|
+
import { API_REQUEST_TIMEOUT_MS, apiUrl, getJson } from './http.js';
|
|
13
|
+
export const CLI_CLIENT_ID = 'superpanel-cli';
|
|
14
|
+
const RENEW_BEFORE_MS = 5 * 60 * 1000;
|
|
15
|
+
const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
16
|
+
const REQUEST_TIMEOUT_MS = 10_000;
|
|
17
|
+
const EXCHANGE_TIMEOUT_MS = 15_000;
|
|
18
|
+
const LOCK_WAIT_MS = 15_000;
|
|
19
|
+
const LOCK_HOLD_MS = 30_000;
|
|
20
|
+
export const LOGIN_SAVE_WAIT_MS = LOCK_HOLD_MS + 15_000;
|
|
21
|
+
const STALE_LOCK_MS = 45_000;
|
|
22
|
+
export class LoginCancelledError extends Error {
|
|
23
|
+
constructor() {
|
|
24
|
+
super('logout cancelled this login');
|
|
25
|
+
this.name = 'LoginCancelledError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export class CliVersionRejectedError extends Error {
|
|
29
|
+
}
|
|
30
|
+
export class CliLoginRejectedError extends Error {
|
|
31
|
+
constructor(message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = 'CliLoginRejectedError';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function env(name) {
|
|
37
|
+
const value = process.env[name];
|
|
38
|
+
return value && value.length > 0 ? value : undefined;
|
|
39
|
+
}
|
|
40
|
+
const BACKEND_VARIABLE = 'SUPERPANEL_SDK_BACKEND_URL';
|
|
41
|
+
export const BACKEND_CONFIG_FILE = '.superpanel/config.json';
|
|
42
|
+
let backendVariableFromConfig = false;
|
|
43
|
+
export function backendConfigPath(dir) {
|
|
44
|
+
return path.join(dir, BACKEND_CONFIG_FILE);
|
|
45
|
+
}
|
|
46
|
+
export function parseBackendConfig(text) {
|
|
47
|
+
const parsed = JSON.parse(text.replace(/^\uFEFF/, ''));
|
|
48
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
49
|
+
throw new Error('expected an object');
|
|
50
|
+
const config = parsed;
|
|
51
|
+
if (!Object.prototype.hasOwnProperty.call(config, 'backendUrl'))
|
|
52
|
+
return { config };
|
|
53
|
+
if (typeof config.backendUrl !== 'string')
|
|
54
|
+
throw new Error('backendUrl is not a string');
|
|
55
|
+
return { config, backendUrl: config.backendUrl };
|
|
56
|
+
}
|
|
57
|
+
export function writeBackendConfig(config, url) {
|
|
58
|
+
const next = { ...(config ?? {}) };
|
|
59
|
+
if (url === null)
|
|
60
|
+
delete next.backendUrl;
|
|
61
|
+
else
|
|
62
|
+
next.backendUrl = url;
|
|
63
|
+
if (Object.keys(next).length === 0)
|
|
64
|
+
return null;
|
|
65
|
+
return `${JSON.stringify(next, null, 2)}\n`;
|
|
66
|
+
}
|
|
67
|
+
export function loadBackendFromConfig(dir = process.cwd(), warn = (line) => console.error(line)) {
|
|
68
|
+
backendVariableFromConfig = false;
|
|
69
|
+
if (process.env[BACKEND_VARIABLE]?.trim())
|
|
70
|
+
return;
|
|
71
|
+
delete process.env[BACKEND_VARIABLE];
|
|
72
|
+
const file = backendConfigPath(findCloneRoot(dir) ?? dir);
|
|
73
|
+
let bytes;
|
|
74
|
+
try {
|
|
75
|
+
bytes = readFileSync(file);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error?.code === 'ENOENT')
|
|
79
|
+
return;
|
|
80
|
+
warn(`superpanel: could not read ${file} (${error instanceof Error ? error.message : String(error)}); going on without it`);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff)) {
|
|
84
|
+
warn(`superpanel: ${file} is saved as UTF-16; save it as UTF-8 for the CLI to read it. Going on without it`);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
let parsed;
|
|
88
|
+
try {
|
|
89
|
+
parsed = parseBackendConfig(bytes.toString('utf8'));
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
warn(`superpanel: could not read ${file} (${error instanceof Error ? error.message : String(error)}); going on without it`);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (parsed.backendUrl === undefined)
|
|
96
|
+
return;
|
|
97
|
+
process.env[BACKEND_VARIABLE] = parsed.backendUrl;
|
|
98
|
+
backendVariableFromConfig = true;
|
|
99
|
+
}
|
|
100
|
+
export function resolveBackend(optionUrl) {
|
|
101
|
+
if (optionUrl !== undefined) {
|
|
102
|
+
const url = optionUrl.trim();
|
|
103
|
+
if (!url)
|
|
104
|
+
throw new Error('--url is empty; give the backend URL, or leave --url out');
|
|
105
|
+
return checkedBackend({ url, source: '--url' });
|
|
106
|
+
}
|
|
107
|
+
const fromVariable = env(BACKEND_VARIABLE)?.trim();
|
|
108
|
+
if (fromVariable)
|
|
109
|
+
return checkedBackend({
|
|
110
|
+
url: fromVariable,
|
|
111
|
+
source: backendVariableFromConfig ? '.superpanel/config.json' : BACKEND_VARIABLE,
|
|
112
|
+
});
|
|
113
|
+
if (backendVariableFromConfig)
|
|
114
|
+
throw new Error(`backendUrl in ${BACKEND_CONFIG_FILE} is empty; set it to the backend URL, or remove it`);
|
|
115
|
+
return { url: DEFAULT_BACKEND_URL, source: 'default' };
|
|
116
|
+
}
|
|
117
|
+
function checkedBackend(backend) {
|
|
118
|
+
try {
|
|
119
|
+
toHttpUrl(backend.url);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
const where = backend.source === '--url'
|
|
123
|
+
? '--url'
|
|
124
|
+
: backend.source === '.superpanel/config.json'
|
|
125
|
+
? `backendUrl in ${BACKEND_CONFIG_FILE}`
|
|
126
|
+
: `${BACKEND_VARIABLE} in the shell`;
|
|
127
|
+
throw new Error(`${where} is not a backend URL: "${backend.url}"; give it as http(s)://host[:port]`);
|
|
128
|
+
}
|
|
129
|
+
return backend;
|
|
130
|
+
}
|
|
131
|
+
export function shellBackendUrl() {
|
|
132
|
+
return backendVariableFromConfig ? undefined : env(BACKEND_VARIABLE)?.trim() || undefined;
|
|
133
|
+
}
|
|
134
|
+
export function resolveBackendUrl(optionUrl) {
|
|
135
|
+
return resolveBackend(optionUrl).url;
|
|
136
|
+
}
|
|
137
|
+
export function announceBackend(backend, say = console.log) {
|
|
138
|
+
if (backend.source !== 'default' && !isDefaultBackend(backend.url))
|
|
139
|
+
say(`Using backend ${backend.url} (from ${backend.source})`);
|
|
140
|
+
}
|
|
141
|
+
export function cliCommand(command, backendUrl) {
|
|
142
|
+
let plain;
|
|
143
|
+
try {
|
|
144
|
+
plain = resolveBackend(undefined).url;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
plain = undefined;
|
|
148
|
+
}
|
|
149
|
+
const reaches = plain !== undefined && sameBackend(plain, backendUrl);
|
|
150
|
+
const argument = /^[a-zA-Z0-9_./:@%-]+$/.test(backendUrl) ? backendUrl : `'${backendUrl.replace(/'/g, "'\\''")}'`;
|
|
151
|
+
return reaches ? `superpanel ${command}` : `superpanel ${command} --url ${argument}`;
|
|
152
|
+
}
|
|
153
|
+
export function loginCommand(backendUrl) {
|
|
154
|
+
return cliCommand('login', backendUrl);
|
|
155
|
+
}
|
|
156
|
+
export { backendCacheKey };
|
|
157
|
+
export function authorizationCachePath() {
|
|
158
|
+
return path.join(homedir(), '.superpanel', 'credentials.json');
|
|
159
|
+
}
|
|
160
|
+
function isCliAuthorization(value) {
|
|
161
|
+
if (!value || typeof value !== 'object')
|
|
162
|
+
return false;
|
|
163
|
+
const record = value;
|
|
164
|
+
const user = record.user;
|
|
165
|
+
return (typeof record.accessToken === 'string' &&
|
|
166
|
+
typeof record.accessTokenExpiresAt === 'number' &&
|
|
167
|
+
typeof record.refreshToken === 'string' &&
|
|
168
|
+
typeof record.companyId === 'string' &&
|
|
169
|
+
(record.companyName === null || typeof record.companyName === 'string') &&
|
|
170
|
+
Boolean(user) &&
|
|
171
|
+
typeof user === 'object' &&
|
|
172
|
+
typeof user.id === 'string' &&
|
|
173
|
+
typeof user.email === 'string');
|
|
174
|
+
}
|
|
175
|
+
function epochOf(cache, key) {
|
|
176
|
+
const value = cache.loginEpoch[key];
|
|
177
|
+
return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : 0;
|
|
178
|
+
}
|
|
179
|
+
function cachedLogin(cache, key) {
|
|
180
|
+
const value = cache.credentials[key];
|
|
181
|
+
return isCliAuthorization(value) ? value : undefined;
|
|
182
|
+
}
|
|
183
|
+
async function readAuthorizationCache(file) {
|
|
184
|
+
try {
|
|
185
|
+
const raw = JSON.parse(await readFile(file, 'utf8'));
|
|
186
|
+
if (raw.version !== 2 || !raw.credentials || typeof raw.credentials !== 'object') {
|
|
187
|
+
return { version: 2, credentials: {}, loginEpoch: {} };
|
|
188
|
+
}
|
|
189
|
+
const cache = {
|
|
190
|
+
...raw,
|
|
191
|
+
version: 2,
|
|
192
|
+
credentials: raw.credentials,
|
|
193
|
+
loginEpoch: raw.loginEpoch && typeof raw.loginEpoch === 'object' ? raw.loginEpoch : {},
|
|
194
|
+
};
|
|
195
|
+
for (const alias of new Set([...Object.keys(cache.credentials), ...Object.keys(cache.loginEpoch)])) {
|
|
196
|
+
if (!alias.endsWith('/'))
|
|
197
|
+
continue;
|
|
198
|
+
let key;
|
|
199
|
+
try {
|
|
200
|
+
key = backendCacheKey(alias);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (alias === key)
|
|
206
|
+
continue;
|
|
207
|
+
const previous = epochOf(cache, alias);
|
|
208
|
+
const current = epochOf(cache, key);
|
|
209
|
+
if (previous > current || (previous === current && !(key in cache.credentials) && !(key in cache.loginEpoch))) {
|
|
210
|
+
if (alias in cache.credentials)
|
|
211
|
+
cache.credentials[key] = cache.credentials[alias];
|
|
212
|
+
else
|
|
213
|
+
delete cache.credentials[key];
|
|
214
|
+
}
|
|
215
|
+
cache.loginEpoch[key] = Math.max(previous, current);
|
|
216
|
+
delete cache.credentials[alias];
|
|
217
|
+
delete cache.loginEpoch[alias];
|
|
218
|
+
}
|
|
219
|
+
return cache;
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
223
|
+
if (code === 'ENOENT' || error instanceof SyntaxError)
|
|
224
|
+
return { version: 2, credentials: {}, loginEpoch: {} };
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
function wait(ms) {
|
|
229
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
230
|
+
}
|
|
231
|
+
function errorCode(error) {
|
|
232
|
+
return error && typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
233
|
+
}
|
|
234
|
+
async function writeAuthorizationCache(cache, file) {
|
|
235
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
236
|
+
const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
237
|
+
await writeFile(temporary, `${JSON.stringify(cache, null, 2)}\n`, { mode: 0o600 });
|
|
238
|
+
for (let attempt = 1;; attempt += 1) {
|
|
239
|
+
try {
|
|
240
|
+
await rename(temporary, file);
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
if (attempt >= 5 || !['EPERM', 'EBUSY', 'EACCES'].includes(String(errorCode(error)))) {
|
|
245
|
+
await rm(temporary, { force: true });
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
await wait(50 * attempt);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
await chmod(file, 0o600).catch(() => undefined);
|
|
252
|
+
}
|
|
253
|
+
class CacheLockTimeoutError extends Error {
|
|
254
|
+
}
|
|
255
|
+
export async function withCacheLock(file, run, waitMs = LOCK_WAIT_MS) {
|
|
256
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
257
|
+
let lock;
|
|
258
|
+
try {
|
|
259
|
+
lock = await acquireFileLock(`${file}.lock`, { staleMs: STALE_LOCK_MS, waitMs, pollMs: 100 });
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
if (error instanceof LockWaitTimeoutError) {
|
|
263
|
+
throw new CacheLockTimeoutError('timed out waiting for another superpanel process to renew the login');
|
|
264
|
+
}
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
return await run(lock.held);
|
|
269
|
+
}
|
|
270
|
+
finally {
|
|
271
|
+
await lock.release().catch(() => undefined);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const LOGIN_MARK_HOLD_MS = 2 * REQUEST_TIMEOUT_MS +
|
|
275
|
+
LOGIN_SAVE_WAIT_MS +
|
|
276
|
+
REQUEST_TIMEOUT_MS +
|
|
277
|
+
REQUEST_TIMEOUT_MS +
|
|
278
|
+
CLIPBOARD_WORST_MS +
|
|
279
|
+
LOGIN_TIMEOUT_MS +
|
|
280
|
+
EXCHANGE_TIMEOUT_MS +
|
|
281
|
+
API_REQUEST_TIMEOUT_MS +
|
|
282
|
+
LOGIN_SAVE_WAIT_MS +
|
|
283
|
+
2 * REQUEST_TIMEOUT_MS;
|
|
284
|
+
const LOGIN_MARK_WAIT_MS = LOGIN_MARK_HOLD_MS + 30_000;
|
|
285
|
+
const LOGIN_MARK_STALE_MS = LOGIN_MARK_HOLD_MS + 60_000;
|
|
286
|
+
export function loginMarkPath(backendUrl, file = authorizationCachePath()) {
|
|
287
|
+
const digest = createHash('sha256').update(backendCacheKey(backendUrl)).digest('hex').slice(0, 16);
|
|
288
|
+
return path.join(path.dirname(file), `login-${digest}.lock`);
|
|
289
|
+
}
|
|
290
|
+
export async function withLoginMark(backendUrl, run, options = {}) {
|
|
291
|
+
const file = options.file ?? authorizationCachePath();
|
|
292
|
+
const say = options.say ?? ((line) => console.log(line));
|
|
293
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
294
|
+
let mark;
|
|
295
|
+
try {
|
|
296
|
+
mark = await acquireFileLock(loginMarkPath(backendUrl, file), {
|
|
297
|
+
staleMs: LOGIN_MARK_STALE_MS,
|
|
298
|
+
waitMs: LOGIN_MARK_WAIT_MS,
|
|
299
|
+
pollMs: 500,
|
|
300
|
+
onWait: () => {
|
|
301
|
+
say(`Another terminal is logging in to ${backendUrl}; finish there, or press Ctrl-C there to cancel. Waiting...`);
|
|
302
|
+
},
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
if (error instanceof LockWaitTimeoutError) {
|
|
307
|
+
throw new Error(`another login to ${backendUrl} on this machine is still running after ${(LOGIN_MARK_WAIT_MS / 60_000).toFixed(1)} minutes; stop it (Ctrl-C) and run \`${loginCommand(backendUrl)}\` again`);
|
|
308
|
+
}
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
try {
|
|
312
|
+
return await run(mark.waited);
|
|
313
|
+
}
|
|
314
|
+
finally {
|
|
315
|
+
await mark.release();
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
export async function readLoginEpoch(backendUrl, file = authorizationCachePath()) {
|
|
319
|
+
const cache = await readAuthorizationCache(file);
|
|
320
|
+
return epochOf(cache, backendCacheKey(backendUrl));
|
|
321
|
+
}
|
|
322
|
+
export async function beginLogout(backendUrl, file = authorizationCachePath()) {
|
|
323
|
+
return withCacheLock(file, async () => {
|
|
324
|
+
const cache = await readAuthorizationCache(file);
|
|
325
|
+
const key = backendCacheKey(backendUrl);
|
|
326
|
+
const previous = epochOf(cache, key);
|
|
327
|
+
cache.loginEpoch[key] = previous + 1;
|
|
328
|
+
const authorization = cachedLogin(cache, key);
|
|
329
|
+
if (authorization)
|
|
330
|
+
authorization.logoutId ??= randomBytes(16).toString('hex');
|
|
331
|
+
await writeAuthorizationCache(cache, file);
|
|
332
|
+
return { epoch: previous, authorization };
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
export async function loginStillCurrent(backendUrl, epoch, file = authorizationCachePath()) {
|
|
336
|
+
const cache = await readAuthorizationCache(file);
|
|
337
|
+
return epochOf(cache, backendCacheKey(backendUrl)) === epoch;
|
|
338
|
+
}
|
|
339
|
+
export async function cacheCliAuthorization(backendUrl, authorization, file = authorizationCachePath(), options = {}) {
|
|
340
|
+
await withCacheLock(file, async () => {
|
|
341
|
+
const cache = await readAuthorizationCache(file);
|
|
342
|
+
const key = backendCacheKey(backendUrl);
|
|
343
|
+
if (options.epoch !== undefined && epochOf(cache, key) !== options.epoch) {
|
|
344
|
+
throw new LoginCancelledError();
|
|
345
|
+
}
|
|
346
|
+
cache.credentials[key] = authorization;
|
|
347
|
+
await writeAuthorizationCache(cache, file);
|
|
348
|
+
}, options.waitMs);
|
|
349
|
+
}
|
|
350
|
+
export async function removeCachedCliAuthorization(backendUrl, options = {}, file = authorizationCachePath()) {
|
|
351
|
+
return withCacheLock(file, async () => {
|
|
352
|
+
const cache = await readAuthorizationCache(file);
|
|
353
|
+
const key = backendCacheKey(backendUrl);
|
|
354
|
+
const current = cachedLogin(cache, key);
|
|
355
|
+
if (!current ||
|
|
356
|
+
(options.refreshToken !== undefined &&
|
|
357
|
+
current.refreshToken !== options.refreshToken &&
|
|
358
|
+
!(options.logoutId && options.logoutId === current.logoutId)))
|
|
359
|
+
return false;
|
|
360
|
+
delete cache.credentials[key];
|
|
361
|
+
await writeAuthorizationCache(cache, file);
|
|
362
|
+
return true;
|
|
363
|
+
}, options.waitMs);
|
|
364
|
+
}
|
|
365
|
+
export async function readCliAuthorizationStatus(backendUrl, file = authorizationCachePath()) {
|
|
366
|
+
const authorization = cachedLogin(await readAuthorizationCache(file), backendCacheKey(backendUrl));
|
|
367
|
+
return authorization ? { loggedIn: true, authorization } : { loggedIn: false };
|
|
368
|
+
}
|
|
369
|
+
export async function discoverOAuthServer(backendUrl) {
|
|
370
|
+
const url = new URL('/.well-known/oauth-authorization-server', toHttpUrl(backendUrl));
|
|
371
|
+
let response;
|
|
372
|
+
try {
|
|
373
|
+
response = await fetch(url, {
|
|
374
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
375
|
+
headers: { Accept: 'application/json' },
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
throw new Error(`could not reach ${url.origin} (${error instanceof Error ? error.message : String(error)})`);
|
|
380
|
+
}
|
|
381
|
+
if (!response.ok)
|
|
382
|
+
throw new Error(`${url.origin} has no login server (${response.status} from ${url.pathname})`);
|
|
383
|
+
const metadata = (await response.json().catch(() => ({})));
|
|
384
|
+
if (typeof metadata.issuer !== 'string' ||
|
|
385
|
+
typeof metadata.device_authorization_endpoint !== 'string' ||
|
|
386
|
+
typeof metadata.token_endpoint !== 'string' ||
|
|
387
|
+
typeof metadata.revocation_endpoint !== 'string') {
|
|
388
|
+
throw new Error(`malformed login server metadata from ${url.origin}`);
|
|
389
|
+
}
|
|
390
|
+
return metadata;
|
|
391
|
+
}
|
|
392
|
+
export class OAuthRequestError extends Error {
|
|
393
|
+
code;
|
|
394
|
+
status;
|
|
395
|
+
constructor(code, message, status) {
|
|
396
|
+
super(message);
|
|
397
|
+
this.code = code;
|
|
398
|
+
this.status = status;
|
|
399
|
+
this.name = 'OAuthRequestError';
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
export function printable(text) {
|
|
403
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, '');
|
|
404
|
+
}
|
|
405
|
+
async function postForm(url, form, timeoutMs = REQUEST_TIMEOUT_MS, sendVersion = false) {
|
|
406
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
407
|
+
const response = await fetch(url, {
|
|
408
|
+
method: 'POST',
|
|
409
|
+
headers: cliRequestHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, sendVersion),
|
|
410
|
+
body: new URLSearchParams(form).toString(),
|
|
411
|
+
signal,
|
|
412
|
+
});
|
|
413
|
+
const payload = await response.json().catch(() => {
|
|
414
|
+
signal.throwIfAborted();
|
|
415
|
+
return {};
|
|
416
|
+
});
|
|
417
|
+
return {
|
|
418
|
+
status: response.status,
|
|
419
|
+
payload: payload && typeof payload === 'object' ? payload : {},
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
async function requestTokens(endpoint, form, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
423
|
+
const { status, payload } = await postForm(endpoint, form, timeoutMs);
|
|
424
|
+
if (status >= 200 && status < 300) {
|
|
425
|
+
if (typeof payload.access_token === 'string' && typeof payload.refresh_token === 'string') {
|
|
426
|
+
return {
|
|
427
|
+
access_token: payload.access_token,
|
|
428
|
+
refresh_token: payload.refresh_token,
|
|
429
|
+
expires_in: typeof payload.expires_in === 'number' ? payload.expires_in : 3600,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
throw new Error('the login server accepted the request but its reply did not arrive whole');
|
|
433
|
+
}
|
|
434
|
+
const code = typeof payload.error === 'string' ? payload.error : undefined;
|
|
435
|
+
const description = typeof payload.error_description === 'string' ? payload.error_description : (code ?? `HTTP ${status}`);
|
|
436
|
+
throw new OAuthRequestError(code, printable(description), status);
|
|
437
|
+
}
|
|
438
|
+
export async function revokeCliLogin(backendUrl, authorization) {
|
|
439
|
+
const server = await discoverOAuthServer(backendUrl);
|
|
440
|
+
const { status } = await postForm(server.revocation_endpoint, {
|
|
441
|
+
token: authorization.refreshToken,
|
|
442
|
+
client_id: CLI_CLIENT_ID,
|
|
443
|
+
});
|
|
444
|
+
if (status < 200 || status >= 300)
|
|
445
|
+
throw new Error(`could not log out on the backend (${status})`);
|
|
446
|
+
}
|
|
447
|
+
async function renewTokens(endpoint, form, deadline) {
|
|
448
|
+
const timeout = () => {
|
|
449
|
+
const left = deadline - Date.now();
|
|
450
|
+
if (left <= 0)
|
|
451
|
+
throw new Error('renewing the login took too long; try again');
|
|
452
|
+
return Math.min(REQUEST_TIMEOUT_MS, left);
|
|
453
|
+
};
|
|
454
|
+
try {
|
|
455
|
+
return await requestTokens(endpoint, form, timeout());
|
|
456
|
+
}
|
|
457
|
+
catch (error) {
|
|
458
|
+
if (error instanceof OAuthRequestError && error.status < 500)
|
|
459
|
+
throw error;
|
|
460
|
+
return requestTokens(endpoint, form, timeout());
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
function fresh(authorization) {
|
|
464
|
+
return authorization.accessTokenExpiresAt - Date.now() > RENEW_BEFORE_MS;
|
|
465
|
+
}
|
|
466
|
+
export async function getValidCliAuthorization(backendUrl, file = authorizationCachePath()) {
|
|
467
|
+
const key = backendCacheKey(backendUrl);
|
|
468
|
+
const cached = cachedLogin(await readAuthorizationCache(file), key);
|
|
469
|
+
if (!cached)
|
|
470
|
+
return null;
|
|
471
|
+
if (fresh(cached))
|
|
472
|
+
return cached;
|
|
473
|
+
const server = await discoverOAuthServer(backendUrl);
|
|
474
|
+
let renewed;
|
|
475
|
+
try {
|
|
476
|
+
renewed = await withCacheLock(file, async (held) => {
|
|
477
|
+
const deadline = Date.now() + LOCK_HOLD_MS;
|
|
478
|
+
let refused = '';
|
|
479
|
+
let refusedToken = '';
|
|
480
|
+
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
481
|
+
const cache = await readAuthorizationCache(file);
|
|
482
|
+
const current = cachedLogin(cache, key);
|
|
483
|
+
if (!current)
|
|
484
|
+
return { kind: 'gone' };
|
|
485
|
+
if (fresh(current))
|
|
486
|
+
return { kind: 'ok', authorization: current };
|
|
487
|
+
try {
|
|
488
|
+
const tokens = await renewTokens(server.token_endpoint, {
|
|
489
|
+
grant_type: 'refresh_token',
|
|
490
|
+
refresh_token: current.refreshToken,
|
|
491
|
+
client_id: CLI_CLIENT_ID,
|
|
492
|
+
resource: server.issuer,
|
|
493
|
+
}, deadline);
|
|
494
|
+
const next = {
|
|
495
|
+
...current,
|
|
496
|
+
accessToken: tokens.access_token,
|
|
497
|
+
accessTokenExpiresAt: Date.now() + tokens.expires_in * 1000,
|
|
498
|
+
refreshToken: tokens.refresh_token,
|
|
499
|
+
};
|
|
500
|
+
if (!(await held())) {
|
|
501
|
+
const now = cachedLogin(await readAuthorizationCache(file), key);
|
|
502
|
+
return { kind: 'ok', authorization: now && fresh(now) ? now : next };
|
|
503
|
+
}
|
|
504
|
+
cache.credentials[key] = next;
|
|
505
|
+
try {
|
|
506
|
+
await writeAuthorizationCache(cache, file);
|
|
507
|
+
}
|
|
508
|
+
catch (error) {
|
|
509
|
+
console.warn(`superpanel: could not save the renewed CLI login (${error instanceof Error ? error.message : String(error)})`);
|
|
510
|
+
}
|
|
511
|
+
return { kind: 'ok', authorization: next };
|
|
512
|
+
}
|
|
513
|
+
catch (error) {
|
|
514
|
+
if (!(error instanceof OAuthRequestError) || error.code !== 'invalid_grant')
|
|
515
|
+
throw error;
|
|
516
|
+
refused = error.message;
|
|
517
|
+
refusedToken = current.refreshToken;
|
|
518
|
+
if (attempt === 1)
|
|
519
|
+
await wait(200);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const cache = await readAuthorizationCache(file);
|
|
523
|
+
const now = cachedLogin(cache, key);
|
|
524
|
+
if (now && now.refreshToken !== refusedToken) {
|
|
525
|
+
return fresh(now) ? { kind: 'ok', authorization: now } : { kind: 'rejected', reason: refused };
|
|
526
|
+
}
|
|
527
|
+
if (now && (await held())) {
|
|
528
|
+
delete cache.credentials[key];
|
|
529
|
+
await writeAuthorizationCache(cache, file);
|
|
530
|
+
}
|
|
531
|
+
return { kind: 'rejected', reason: refused };
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
catch (error) {
|
|
535
|
+
if (error instanceof CacheLockTimeoutError && cached.accessTokenExpiresAt > Date.now() + 30_000)
|
|
536
|
+
return cached;
|
|
537
|
+
throw error;
|
|
538
|
+
}
|
|
539
|
+
if (renewed.kind === 'ok')
|
|
540
|
+
return renewed.authorization;
|
|
541
|
+
if (renewed.kind === 'gone')
|
|
542
|
+
return null;
|
|
543
|
+
throw new CliLoginRejectedError(`the CLI login ended (${renewed.reason}); run "${loginCommand(backendUrl)}"`);
|
|
544
|
+
}
|
|
545
|
+
export async function withCliLogin(backendUrl, call, file = authorizationCachePath()) {
|
|
546
|
+
const first = await getValidCliAuthorization(backendUrl, file);
|
|
547
|
+
if (!first)
|
|
548
|
+
throw new CliLoginRejectedError(`not logged in to ${backendUrl}; run "${loginCommand(backendUrl)}"`);
|
|
549
|
+
try {
|
|
550
|
+
return await call(first);
|
|
551
|
+
}
|
|
552
|
+
catch (error) {
|
|
553
|
+
if (!(error instanceof CliLoginRejectedError))
|
|
554
|
+
throw error;
|
|
555
|
+
const again = await getValidCliAuthorization(backendUrl, file);
|
|
556
|
+
if (!again || again.accessToken === first.accessToken)
|
|
557
|
+
throw error;
|
|
558
|
+
return call(again);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
export async function requestCliIdentity(backendUrl, accessToken, options) {
|
|
562
|
+
const { response, payload } = await getJson(apiUrl(backendUrl, 'me'), accessToken, options);
|
|
563
|
+
if (response.status === 426) {
|
|
564
|
+
const message = typeof payload?.error === 'string' && printable(payload.error);
|
|
565
|
+
throw new CliVersionRejectedError(message || 'Update the CLI with npm install -g @superpanel-sdk/cli@latest');
|
|
566
|
+
}
|
|
567
|
+
return { response, payload };
|
|
568
|
+
}
|
|
569
|
+
export async function fetchCliIdentity(backendUrl, accessToken, options) {
|
|
570
|
+
const { response, payload } = await requestCliIdentity(backendUrl, accessToken, options);
|
|
571
|
+
const error = typeof payload?.error === 'string' && payload.error ? printable(payload.error) : null;
|
|
572
|
+
if (response.status === 401)
|
|
573
|
+
throw new CliLoginRejectedError(error ?? 'CLI login rejected');
|
|
574
|
+
if (!response.ok || !payload.user?.companyId)
|
|
575
|
+
throw new Error(error ?? `could not read the login (${response.status})`);
|
|
576
|
+
return {
|
|
577
|
+
user: { id: payload.user.id, email: payload.user.email },
|
|
578
|
+
companyId: payload.user.companyId,
|
|
579
|
+
companyName: payload.user.companyDisplayName ?? payload.user.companyName,
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
export async function backendAcceptsCliLogin(backendUrl, accessToken) {
|
|
583
|
+
try {
|
|
584
|
+
await fetchCliIdentity(backendUrl, accessToken);
|
|
585
|
+
return true;
|
|
586
|
+
}
|
|
587
|
+
catch (error) {
|
|
588
|
+
if (error instanceof CliLoginRejectedError)
|
|
589
|
+
return false;
|
|
590
|
+
throw error;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
export async function listServeEnvironments(backendUrl, accessToken) {
|
|
594
|
+
const { response, payload } = await getJson(apiUrl(backendUrl, 'serve/environments'), accessToken);
|
|
595
|
+
if (response.status === 401) {
|
|
596
|
+
throw new CliLoginRejectedError(payload.error ?? 'CLI login rejected');
|
|
597
|
+
}
|
|
598
|
+
if (!response.ok) {
|
|
599
|
+
throw new Error(payload.error ?? `could not list environments (${response.status})`);
|
|
600
|
+
}
|
|
601
|
+
if (!Array.isArray(payload.environments)) {
|
|
602
|
+
throw new Error('malformed response from the backend (missing environments list)');
|
|
603
|
+
}
|
|
604
|
+
return payload.environments;
|
|
605
|
+
}
|
|
606
|
+
function openBrowser(url) {
|
|
607
|
+
const command = process.platform === 'darwin'
|
|
608
|
+
? { file: 'open', args: [url] }
|
|
609
|
+
: process.platform === 'win32'
|
|
610
|
+
? { file: 'rundll32', args: ['url.dll,FileProtocolHandler', url] }
|
|
611
|
+
: { file: 'xdg-open', args: [url] };
|
|
612
|
+
const child = spawn(command.file, command.args, { detached: true, stdio: 'ignore' });
|
|
613
|
+
child.once('error', () => undefined);
|
|
614
|
+
child.unref();
|
|
615
|
+
}
|
|
616
|
+
export function isRemoteSession(environment = process.env) {
|
|
617
|
+
return Boolean(environment.SSH_CONNECTION || environment.SSH_TTY || environment.SSH_CLIENT);
|
|
618
|
+
}
|
|
619
|
+
const NOT_SENT = new Set([
|
|
620
|
+
'ECONNREFUSED',
|
|
621
|
+
'ENOTFOUND',
|
|
622
|
+
'EAI_AGAIN',
|
|
623
|
+
'ENETUNREACH',
|
|
624
|
+
'EHOSTUNREACH',
|
|
625
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
626
|
+
'CERT_HAS_EXPIRED',
|
|
627
|
+
'DEPTH_ZERO_SELF_SIGNED_CERT',
|
|
628
|
+
'SELF_SIGNED_CERT_IN_CHAIN',
|
|
629
|
+
'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
|
|
630
|
+
'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
|
|
631
|
+
'ERR_TLS_CERT_ALTNAME_INVALID',
|
|
632
|
+
]);
|
|
633
|
+
export function neverSent(error) {
|
|
634
|
+
const cause = error?.cause;
|
|
635
|
+
if (cause instanceof AggregateError)
|
|
636
|
+
return true;
|
|
637
|
+
const code = cause?.code;
|
|
638
|
+
return typeof code === 'string' && NOT_SENT.has(code);
|
|
639
|
+
}
|
|
640
|
+
function reason(error) {
|
|
641
|
+
const cause = error?.cause;
|
|
642
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
643
|
+
if (cause instanceof AggregateError) {
|
|
644
|
+
const codes = cause.errors
|
|
645
|
+
.map((each) => String(each?.code ?? each))
|
|
646
|
+
.join(', ');
|
|
647
|
+
return `${message}: ${codes || cause.message}`;
|
|
648
|
+
}
|
|
649
|
+
return cause instanceof Error && cause.message ? `${message}: ${cause.message}` : message;
|
|
650
|
+
}
|
|
651
|
+
export function cliDeviceName() {
|
|
652
|
+
return hostname()
|
|
653
|
+
.replace(/[\u0000-\u001f\u007f]/g, '')
|
|
654
|
+
.trim()
|
|
655
|
+
.slice(0, 100);
|
|
656
|
+
}
|
|
657
|
+
export function timeOf(at) {
|
|
658
|
+
return at.toLocaleString([], {
|
|
659
|
+
month: 'short',
|
|
660
|
+
day: 'numeric',
|
|
661
|
+
hour: '2-digit',
|
|
662
|
+
minute: '2-digit',
|
|
663
|
+
timeZoneName: 'shortOffset',
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
export function loginLeftOnBackend(backendUrl, what, error, deviceName = cliDeviceName(), madeAt = new Date()) {
|
|
667
|
+
const span = madeAt instanceof Date ? { from: madeAt, to: madeAt } : madeAt;
|
|
668
|
+
const from = timeOf(span.from);
|
|
669
|
+
const to = timeOf(span.to);
|
|
670
|
+
const when = from === to ? `at about ${from}` : `between about ${from} and ${to}`;
|
|
671
|
+
return new Error(`${what} (${reason(error)}). Run \`${loginCommand(backendUrl)}\` again; then, on your account page in the web app under "Connected apps and devices", ` +
|
|
672
|
+
`disconnect the "Superpanel CLI · ${deviceName}" entry connected ${when} if there is one (not the one your new login makes).`);
|
|
673
|
+
}
|
|
674
|
+
export function loginNotFinished(backendUrl, what, error) {
|
|
675
|
+
return new Error(`${what} (${reason(error)}); it was ended on the backend, run \`${loginCommand(backendUrl)}\` again`);
|
|
676
|
+
}
|
|
677
|
+
const DEVICE_CODE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
|
|
678
|
+
const SLOW_DOWN_MS = 5_000;
|
|
679
|
+
const DEFAULT_INTERVAL_MS = 5_000;
|
|
680
|
+
const SHORTEST_INTERVAL_MS = 1_000;
|
|
681
|
+
export class UnconfirmedExchangeError extends Error {
|
|
682
|
+
}
|
|
683
|
+
export class AuthorizationPendingError extends Error {
|
|
684
|
+
reason = 'authorization_pending';
|
|
685
|
+
constructor(backendUrl) {
|
|
686
|
+
super(`A person has to approve this login in the browser. The link and code are above. After they approve, run \`${loginCommand(backendUrl)}\` again.`);
|
|
687
|
+
this.name = 'AuthorizationPendingError';
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function httpLink(value) {
|
|
691
|
+
if (typeof value !== 'string')
|
|
692
|
+
return null;
|
|
693
|
+
try {
|
|
694
|
+
const url = new URL(value);
|
|
695
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : null;
|
|
696
|
+
}
|
|
697
|
+
catch {
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
async function startDeviceLogin(backendUrl, server, deviceName, timing = {}) {
|
|
702
|
+
let reply;
|
|
703
|
+
try {
|
|
704
|
+
reply = await postForm(server.device_authorization_endpoint, {
|
|
705
|
+
client_id: CLI_CLIENT_ID,
|
|
706
|
+
resource: server.issuer,
|
|
707
|
+
device_name: deviceName,
|
|
708
|
+
}, REQUEST_TIMEOUT_MS, true);
|
|
709
|
+
}
|
|
710
|
+
catch (error) {
|
|
711
|
+
throw new Error(`could not reach the login server at ${new URL(server.device_authorization_endpoint).origin} (${reason(error)}); check the network and run \`${loginCommand(backendUrl)}\` again`);
|
|
712
|
+
}
|
|
713
|
+
const { status, payload } = reply;
|
|
714
|
+
if (status < 200 || status >= 300) {
|
|
715
|
+
const description = typeof payload.error_description === 'string'
|
|
716
|
+
? payload.error_description
|
|
717
|
+
: typeof payload.error === 'string'
|
|
718
|
+
? payload.error
|
|
719
|
+
: `HTTP ${status}`;
|
|
720
|
+
throw new Error(`the login server did not start a login (${printable(description)})`);
|
|
721
|
+
}
|
|
722
|
+
const link = httpLink(payload.verification_uri_complete);
|
|
723
|
+
if (typeof payload.device_code !== 'string' || typeof payload.user_code !== 'string' || !link) {
|
|
724
|
+
throw new Error('malformed reply from the login server (no device code or link)');
|
|
725
|
+
}
|
|
726
|
+
const intervalMs = typeof payload.interval === 'number' && payload.interval >= 0 ? payload.interval * 1000 : DEFAULT_INTERVAL_MS;
|
|
727
|
+
const expiresIn = typeof payload.expires_in === 'number' && payload.expires_in > 0 ? payload.expires_in : LOGIN_TIMEOUT_MS / 1000;
|
|
728
|
+
return {
|
|
729
|
+
deviceCode: payload.device_code,
|
|
730
|
+
userCode: printable(payload.user_code),
|
|
731
|
+
link,
|
|
732
|
+
intervalMs: intervalMs < (timing.floorMs ?? SHORTEST_INTERVAL_MS) ? DEFAULT_INTERVAL_MS : intervalMs,
|
|
733
|
+
expiresAt: Date.now() + expiresIn * 1000,
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
const MAYBE_MADE = 'the login may have been made on the backend, but its answer did not reach this machine';
|
|
737
|
+
function notFinishedWithin(backendUrl, ms) {
|
|
738
|
+
const minutes = Math.max(1, Math.round(ms / 60_000));
|
|
739
|
+
return new Error(`the login was not finished within ${minutes} minute${minutes === 1 ? '' : 's'}; run \`${loginCommand(backendUrl)}\` again`);
|
|
740
|
+
}
|
|
741
|
+
async function throwIfLoginCancelled(backendUrl, epoch) {
|
|
742
|
+
if (epoch === undefined)
|
|
743
|
+
return;
|
|
744
|
+
if (!(await loginStillCurrent(backendUrl, epoch)))
|
|
745
|
+
throw new LoginCancelledError();
|
|
746
|
+
}
|
|
747
|
+
async function pollDeviceLogin(backendUrl, server, login, deviceName, say, timing = {}, cancel, saveTiming) {
|
|
748
|
+
const startedAt = Date.now();
|
|
749
|
+
const deadline = Math.min(login.expiresAt, startedAt + LOGIN_TIMEOUT_MS);
|
|
750
|
+
const waitUntil = timing.maxWaitMs == null ? null : startedAt + timing.maxWaitMs;
|
|
751
|
+
let nextPollAt = login.nextPollAt ?? (waitUntil === null ? undefined : startedAt);
|
|
752
|
+
const slowDown = timing.slowDownMs ?? SLOW_DOWN_MS;
|
|
753
|
+
const origin = new URL(server.token_endpoint).origin;
|
|
754
|
+
let interval = login.intervalMs;
|
|
755
|
+
let lost = login.unconfirmedExchange
|
|
756
|
+
? {
|
|
757
|
+
from: new Date(login.unconfirmedExchange.from),
|
|
758
|
+
to: new Date(login.unconfirmedExchange.to),
|
|
759
|
+
error: new Error('incomplete token response'),
|
|
760
|
+
}
|
|
761
|
+
: null;
|
|
762
|
+
function stopPolling() {
|
|
763
|
+
if (lost)
|
|
764
|
+
throw new UnconfirmedExchangeError(loginLeftOnBackend(backendUrl, MAYBE_MADE, lost.error, deviceName, lost).message);
|
|
765
|
+
throw new AuthorizationPendingError(backendUrl);
|
|
766
|
+
}
|
|
767
|
+
let unreachable = null;
|
|
768
|
+
const form = {
|
|
769
|
+
grant_type: DEVICE_CODE_GRANT,
|
|
770
|
+
device_code: login.deviceCode,
|
|
771
|
+
client_id: CLI_CLIENT_ID,
|
|
772
|
+
device_name: deviceName,
|
|
773
|
+
};
|
|
774
|
+
for (;;) {
|
|
775
|
+
if (cancel)
|
|
776
|
+
await throwIfLoginCancelled(cancel.backendUrl, cancel.epoch);
|
|
777
|
+
if (waitUntil != null && nextPollAt !== undefined && nextPollAt > waitUntil) {
|
|
778
|
+
stopPolling();
|
|
779
|
+
}
|
|
780
|
+
const left = deadline - Date.now();
|
|
781
|
+
let pause = Math.min(nextPollAt === undefined ? interval : Math.max(0, nextPollAt - Date.now()), Math.max(0, left));
|
|
782
|
+
if (waitUntil != null)
|
|
783
|
+
pause = Math.min(pause, Math.max(0, waitUntil - Date.now()));
|
|
784
|
+
if (pause > 0)
|
|
785
|
+
await wait(pause);
|
|
786
|
+
if (Date.now() >= deadline) {
|
|
787
|
+
if (lost)
|
|
788
|
+
throw loginLeftOnBackend(backendUrl, MAYBE_MADE, lost.error, deviceName, lost);
|
|
789
|
+
if (unreachable) {
|
|
790
|
+
throw new Error(`could not reach the login server at ${origin} since ${timeOf(unreachable.since)} (${reason(unreachable.error)}); ` +
|
|
791
|
+
`nothing was made on the backend from here; check the network and run \`${loginCommand(backendUrl)}\` again`);
|
|
792
|
+
}
|
|
793
|
+
throw notFinishedWithin(backendUrl, deadline - startedAt);
|
|
794
|
+
}
|
|
795
|
+
const askedAt = new Date();
|
|
796
|
+
const timeLeft = Math.min(deadline, waitUntil ?? deadline) - askedAt.getTime();
|
|
797
|
+
if (timeLeft <= 0 && timing.maxWaitMs !== 0) {
|
|
798
|
+
stopPolling();
|
|
799
|
+
}
|
|
800
|
+
const timeout = Math.min(EXCHANGE_TIMEOUT_MS, Math.max(1, timeLeft));
|
|
801
|
+
try {
|
|
802
|
+
return { tokens: await requestTokens(server.token_endpoint, form, timeout), exchangedAt: askedAt };
|
|
803
|
+
}
|
|
804
|
+
catch (error) {
|
|
805
|
+
const throttled = error instanceof OAuthRequestError && (error.status === 429 || error.code === 'slow_down');
|
|
806
|
+
if (throttled)
|
|
807
|
+
interval += slowDown;
|
|
808
|
+
nextPollAt = Date.now() + interval;
|
|
809
|
+
if (error instanceof OAuthRequestError && error.code === 'authorization_pending')
|
|
810
|
+
lost = null;
|
|
811
|
+
else if (!neverSent(error) && !(error instanceof OAuthRequestError && error.status < 500)) {
|
|
812
|
+
if (lost)
|
|
813
|
+
lost.to = askedAt;
|
|
814
|
+
else
|
|
815
|
+
lost = { from: askedAt, to: askedAt, error };
|
|
816
|
+
}
|
|
817
|
+
if (saveTiming)
|
|
818
|
+
await saveTiming({
|
|
819
|
+
...login,
|
|
820
|
+
intervalMs: interval,
|
|
821
|
+
nextPollAt,
|
|
822
|
+
unconfirmedExchange: lost ? { from: lost.from.getTime(), to: lost.to.getTime() } : undefined,
|
|
823
|
+
});
|
|
824
|
+
if (neverSent(error)) {
|
|
825
|
+
if (!unreachable) {
|
|
826
|
+
unreachable = { since: askedAt, error };
|
|
827
|
+
say(`Cannot reach the login server at ${origin} (${reason(error)}); still trying until ${timeOf(new Date(deadline))}.`);
|
|
828
|
+
}
|
|
829
|
+
continue;
|
|
830
|
+
}
|
|
831
|
+
unreachable = null;
|
|
832
|
+
if (throttled)
|
|
833
|
+
continue;
|
|
834
|
+
if (error instanceof OAuthRequestError && error.status < 500) {
|
|
835
|
+
if (error.code === 'authorization_pending') {
|
|
836
|
+
if (waitUntil != null && Date.now() >= waitUntil)
|
|
837
|
+
throw new AuthorizationPendingError(backendUrl);
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
if (error.code === 'access_denied')
|
|
841
|
+
throw new Error('the login was declined in the browser');
|
|
842
|
+
if (error.code === 'expired_token')
|
|
843
|
+
throw notFinishedWithin(backendUrl, deadline - startedAt);
|
|
844
|
+
if (lost)
|
|
845
|
+
throw loginLeftOnBackend(backendUrl, MAYBE_MADE, lost.error, deviceName, lost);
|
|
846
|
+
throw new Error(`login failed: ${error.message}; run \`${loginCommand(backendUrl)}\` again`);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
export async function authorizeCli(backendUrl, options = {}) {
|
|
852
|
+
const say = options.say ?? ((line) => console.log(line));
|
|
853
|
+
const server = await discoverOAuthServer(backendUrl);
|
|
854
|
+
const deviceName = options.deviceName ?? cliDeviceName();
|
|
855
|
+
const cancel = options.epoch === undefined ? undefined : { backendUrl, epoch: options.epoch };
|
|
856
|
+
let exchange;
|
|
857
|
+
const login = options.resume ?? (await startDeviceLogin(backendUrl, server, deviceName, options.pollTiming));
|
|
858
|
+
if (options.resume && options.resume.expiresAt <= Date.now()) {
|
|
859
|
+
throw new Error(`the saved login expired; run \`${loginCommand(backendUrl)}\` again`);
|
|
860
|
+
}
|
|
861
|
+
await options.onStarted?.(login);
|
|
862
|
+
if (options.resume) {
|
|
863
|
+
say('Still waiting for approval in the browser. The code from the previous run still applies.');
|
|
864
|
+
say(` ${login.link}`);
|
|
865
|
+
say('Still waiting for the approval...');
|
|
866
|
+
exchange = await pollDeviceLogin(backendUrl, server, login, deviceName, say, options.pollTiming, cancel, options.onStarted);
|
|
867
|
+
}
|
|
868
|
+
else {
|
|
869
|
+
const remote = options.remote ?? isRemoteSession();
|
|
870
|
+
const check = `It shows the code ${login.userCode}; approve only if it matches.`;
|
|
871
|
+
if (!remote && options.openBrowser !== false) {
|
|
872
|
+
(options.open ?? openBrowser)(login.link);
|
|
873
|
+
say(`Opening your browser to log in. ${check} If it does not open, open this link:`);
|
|
874
|
+
say(` ${login.link}`);
|
|
875
|
+
}
|
|
876
|
+
else {
|
|
877
|
+
say(`Open this link in a browser and approve. ${check}`);
|
|
878
|
+
say(` ${login.link}`);
|
|
879
|
+
if (!remote) {
|
|
880
|
+
try {
|
|
881
|
+
copyToClipboard(login.link);
|
|
882
|
+
say('(The link is also on your clipboard.)');
|
|
883
|
+
}
|
|
884
|
+
catch {
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
if (options.pollTiming?.maxWaitMs != null)
|
|
889
|
+
throw new AuthorizationPendingError(backendUrl);
|
|
890
|
+
say('Waiting for the approval...');
|
|
891
|
+
exchange = await pollDeviceLogin(backendUrl, server, login, deviceName, say, options.pollTiming, cancel);
|
|
892
|
+
}
|
|
893
|
+
const { tokens, exchangedAt } = exchange;
|
|
894
|
+
try {
|
|
895
|
+
await throwIfLoginCancelled(backendUrl, options.epoch);
|
|
896
|
+
}
|
|
897
|
+
catch (error) {
|
|
898
|
+
if (error instanceof LoginCancelledError) {
|
|
899
|
+
await revokeCliLogin(backendUrl, { refreshToken: tokens.refresh_token }).catch(() => undefined);
|
|
900
|
+
}
|
|
901
|
+
throw error;
|
|
902
|
+
}
|
|
903
|
+
let identity;
|
|
904
|
+
try {
|
|
905
|
+
identity = await fetchCliIdentity(backendUrl, tokens.access_token);
|
|
906
|
+
}
|
|
907
|
+
catch (error) {
|
|
908
|
+
const ended = await revokeCliLogin(backendUrl, { refreshToken: tokens.refresh_token }).then(() => true, () => false);
|
|
909
|
+
if (ended)
|
|
910
|
+
throw error instanceof CliLoginRejectedError
|
|
911
|
+
? error
|
|
912
|
+
: loginNotFinished(backendUrl, 'the login could not be finished', error);
|
|
913
|
+
throw loginLeftOnBackend(backendUrl, 'the login was made on the backend, but this machine could neither finish it nor end it', error, deviceName, exchangedAt);
|
|
914
|
+
}
|
|
915
|
+
return {
|
|
916
|
+
accessToken: tokens.access_token,
|
|
917
|
+
accessTokenExpiresAt: Date.now() + tokens.expires_in * 1000,
|
|
918
|
+
refreshToken: tokens.refresh_token,
|
|
919
|
+
...identity,
|
|
920
|
+
connectedAt: exchangedAt.getTime(),
|
|
921
|
+
deviceName,
|
|
922
|
+
};
|
|
923
|
+
}
|