sedum-cli 0.1.0-alpha.18 → 0.1.0-alpha.21
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 +65 -0
- package/dist/{affected-selection-DAQPGKOZ.js → affected-selection-NTBVWIK5.js} +10 -50
- package/dist/auth-command-TSTYIWGX.js +634 -0
- package/dist/chunk-CGDXQY2Y.js +208 -0
- package/dist/{chunk-SI2F6MBN.js → chunk-DXNJ3PGB.js} +44 -18
- package/dist/{chunk-FG46OUHT.js → chunk-FOGLJA3Z.js} +4 -2
- package/dist/{chunk-KZF4NZ6M.js → chunk-J7CLCLHW.js} +267 -354
- package/dist/chunk-JYWNBHN7.js +109 -0
- package/dist/chunk-NIUOM3FA.js +50 -0
- package/dist/{chunk-EPXLY5Q4.js → chunk-PX6PJ7U2.js} +291 -174
- package/dist/{chunk-6ILFLNDI.js → chunk-QVCT63FH.js} +1 -1
- package/dist/cli.js +10 -3
- package/dist/cloud-command-YYQ47FTU.js +329 -0
- package/dist/cloud-upload-IGNNU5WX.js +243 -0
- package/dist/{doctor-command-7IBKI5YO.js → doctor-command-OFMURNPN.js} +5 -2
- package/dist/{explore-command-QZCKFDYM.js → explore-command-KMS6UAPM.js} +3 -2
- package/dist/index.d.ts +21 -0
- package/dist/index.js +5 -3
- package/dist/{init-command-MBTLGU5J.js → init-command-IXR3YUQW.js} +3 -2
- package/dist/{run-command-P55TKTX3.js → run-command-6UTIJAHU.js} +39 -22
- package/package.json +6 -5
|
@@ -0,0 +1,634 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AuthError,
|
|
3
|
+
cloudOrigin,
|
|
4
|
+
membershipSchema,
|
|
5
|
+
parse,
|
|
6
|
+
request,
|
|
7
|
+
tokenResult,
|
|
8
|
+
tokensSchema
|
|
9
|
+
} from "./chunk-JYWNBHN7.js";
|
|
10
|
+
|
|
11
|
+
// src/auth-command.ts
|
|
12
|
+
import { spawn } from "child_process";
|
|
13
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
14
|
+
import { z as z2 } from "zod";
|
|
15
|
+
|
|
16
|
+
// src/auth-store.ts
|
|
17
|
+
import { constants, readlinkSync, unlinkSync } from "fs";
|
|
18
|
+
import {
|
|
19
|
+
link,
|
|
20
|
+
lstat,
|
|
21
|
+
mkdir,
|
|
22
|
+
open,
|
|
23
|
+
readFile,
|
|
24
|
+
rename,
|
|
25
|
+
unlink,
|
|
26
|
+
writeFile
|
|
27
|
+
} from "fs/promises";
|
|
28
|
+
import { homedir, hostname } from "os";
|
|
29
|
+
import path from "path";
|
|
30
|
+
import { randomUUID } from "crypto";
|
|
31
|
+
import { pathToFileURL } from "url";
|
|
32
|
+
import { z } from "zod";
|
|
33
|
+
var stateSchema = z.object({
|
|
34
|
+
selectedOrigin: z.string().optional(),
|
|
35
|
+
selections: z.record(
|
|
36
|
+
z.string(),
|
|
37
|
+
z.object({
|
|
38
|
+
organization: z.string().optional(),
|
|
39
|
+
project: z.string().optional()
|
|
40
|
+
})
|
|
41
|
+
),
|
|
42
|
+
sessions: z.record(
|
|
43
|
+
z.string(),
|
|
44
|
+
tokensSchema.extend({ expiresAt: z.number().finite() })
|
|
45
|
+
)
|
|
46
|
+
});
|
|
47
|
+
function configRoot(directory) {
|
|
48
|
+
const platformRoot = process.platform === "win32" ? process.env.APPDATA ?? homedir() : path.join(homedir(), ".config");
|
|
49
|
+
return path.resolve(
|
|
50
|
+
directory ?? path.join(process.env.XDG_CONFIG_HOME ?? platformRoot, "sedum")
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
function ownerOnly(info) {
|
|
54
|
+
if (process.platform === "win32") return true;
|
|
55
|
+
return (info.mode & 63) === 0 && info.uid === process.getuid?.();
|
|
56
|
+
}
|
|
57
|
+
function missing(error) {
|
|
58
|
+
return error.code === "ENOENT";
|
|
59
|
+
}
|
|
60
|
+
async function rejectSymlink(file) {
|
|
61
|
+
try {
|
|
62
|
+
if ((await lstat(file)).isSymbolicLink())
|
|
63
|
+
throw new AuthError(
|
|
64
|
+
"Unsafe credential directory: symbolic links are not allowed."
|
|
65
|
+
);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (!missing(error)) throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async function rejectCheckout(marker) {
|
|
71
|
+
try {
|
|
72
|
+
await lstat(marker);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (missing(error)) return;
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
throw new AuthError(
|
|
78
|
+
"Credential storage must be outside a Git checkout. Set XDG_CONFIG_HOME to an external user config directory."
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
async function prepareDirectory(root) {
|
|
82
|
+
let current = path.parse(root).root;
|
|
83
|
+
for (const part of root.slice(current.length).split(path.sep)) {
|
|
84
|
+
current = path.join(current, part);
|
|
85
|
+
await rejectSymlink(current);
|
|
86
|
+
await rejectCheckout(pathToFileURL(path.join(current, ".git")));
|
|
87
|
+
}
|
|
88
|
+
await mkdir(root, { recursive: true, mode: 448 });
|
|
89
|
+
const info = await lstat(root);
|
|
90
|
+
if (!info.isDirectory() || !ownerOnly(info))
|
|
91
|
+
throw new AuthError(
|
|
92
|
+
"Credential directory must be owned by you with mode 0700."
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
var lockedMessage = "Authentication store is locked. Wait for other auth commands; if none are running, remove auth.lock (and auth.lock.break, if present) from your Sedum user config directory.";
|
|
96
|
+
var lockOwnerSchema = z.object({
|
|
97
|
+
pid: z.number().int().positive(),
|
|
98
|
+
host: z.string(),
|
|
99
|
+
pidNamespace: z.string().optional()
|
|
100
|
+
});
|
|
101
|
+
function currentPidNamespace() {
|
|
102
|
+
try {
|
|
103
|
+
return readlinkSync("/proc/self/ns/pid");
|
|
104
|
+
} catch {
|
|
105
|
+
return void 0;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
var lockOwner = JSON.stringify({
|
|
109
|
+
pid: process.pid,
|
|
110
|
+
host: hostname(),
|
|
111
|
+
pidNamespace: currentPidNamespace()
|
|
112
|
+
});
|
|
113
|
+
var abandonedGuardMs = 1e4;
|
|
114
|
+
var heldLocks = /* @__PURE__ */ new Set();
|
|
115
|
+
process.on("exit", () => {
|
|
116
|
+
for (const file of heldLocks) {
|
|
117
|
+
try {
|
|
118
|
+
unlinkSync(file);
|
|
119
|
+
} catch {
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
async function acquireLock(file) {
|
|
124
|
+
const temporary = `${file}-${randomUUID()}`;
|
|
125
|
+
await writeFile(temporary, lockOwner, { flag: "wx", mode: 384 });
|
|
126
|
+
try {
|
|
127
|
+
await link(temporary, file);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
if (error.code === "EEXIST") return void 0;
|
|
130
|
+
throw error;
|
|
131
|
+
} finally {
|
|
132
|
+
await unlink(temporary);
|
|
133
|
+
}
|
|
134
|
+
heldLocks.add(file);
|
|
135
|
+
return async () => {
|
|
136
|
+
heldLocks.delete(file);
|
|
137
|
+
await unlink(file);
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function ownerAlive(pid) {
|
|
141
|
+
try {
|
|
142
|
+
process.kill(pid, 0);
|
|
143
|
+
return true;
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return error.code !== "ESRCH";
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async function ownerDied(file) {
|
|
149
|
+
let content;
|
|
150
|
+
try {
|
|
151
|
+
content = await readFile(file, "utf8");
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (missing(error)) return true;
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
let owner;
|
|
157
|
+
try {
|
|
158
|
+
owner = JSON.parse(content);
|
|
159
|
+
} catch {
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
const parsed = lockOwnerSchema.safeParse(owner);
|
|
163
|
+
if (!parsed.success) return false;
|
|
164
|
+
const { pid, host, pidNamespace } = parsed.data;
|
|
165
|
+
if (host !== hostname() || pidNamespace !== currentPidNamespace())
|
|
166
|
+
return false;
|
|
167
|
+
return !ownerAlive(pid);
|
|
168
|
+
}
|
|
169
|
+
function ignoreMissing(error) {
|
|
170
|
+
if (!missing(error)) throw error;
|
|
171
|
+
}
|
|
172
|
+
async function acquireGuard(guard) {
|
|
173
|
+
const release = await acquireLock(guard);
|
|
174
|
+
if (release) return release;
|
|
175
|
+
const age = await lstat(guard).then(
|
|
176
|
+
(info) => Date.now() - info.mtimeMs,
|
|
177
|
+
(error) => {
|
|
178
|
+
ignoreMissing(error);
|
|
179
|
+
return Infinity;
|
|
180
|
+
}
|
|
181
|
+
);
|
|
182
|
+
if (age < abandonedGuardMs || !await ownerDied(guard)) return void 0;
|
|
183
|
+
await unlink(guard).catch(ignoreMissing);
|
|
184
|
+
return acquireLock(guard);
|
|
185
|
+
}
|
|
186
|
+
async function breakDeadLock(file) {
|
|
187
|
+
const releaseGuard = await acquireGuard(`${file}.break`);
|
|
188
|
+
if (!releaseGuard) return false;
|
|
189
|
+
try {
|
|
190
|
+
if (!await ownerDied(file)) return false;
|
|
191
|
+
await unlink(file).catch(ignoreMissing);
|
|
192
|
+
return true;
|
|
193
|
+
} finally {
|
|
194
|
+
await releaseGuard();
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async function lockStore(root) {
|
|
198
|
+
const lockPath = path.join(root, "auth.lock");
|
|
199
|
+
const release = await acquireLock(lockPath) ?? (await breakDeadLock(lockPath) ? await acquireLock(lockPath) : void 0);
|
|
200
|
+
if (!release) throw new AuthError(lockedMessage);
|
|
201
|
+
return release;
|
|
202
|
+
}
|
|
203
|
+
function safeFile(info) {
|
|
204
|
+
if (!info.isFile()) return false;
|
|
205
|
+
if (info.nlink !== 1) return false;
|
|
206
|
+
return ownerOnly(info);
|
|
207
|
+
}
|
|
208
|
+
async function readState(file) {
|
|
209
|
+
try {
|
|
210
|
+
const info = await lstat(file);
|
|
211
|
+
if (!safeFile(info))
|
|
212
|
+
throw new AuthError(
|
|
213
|
+
"Unsafe credential file; require an owner-only regular file."
|
|
214
|
+
);
|
|
215
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
216
|
+
try {
|
|
217
|
+
const actual = await handle.stat();
|
|
218
|
+
if (!safeFile(actual))
|
|
219
|
+
throw new AuthError(
|
|
220
|
+
"Unsafe credential file; require an owner-only regular file."
|
|
221
|
+
);
|
|
222
|
+
return stateSchema.parse(JSON.parse(await handle.readFile("utf8")));
|
|
223
|
+
} finally {
|
|
224
|
+
await handle.close();
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (!missing(error)) throw error;
|
|
228
|
+
return { selections: {}, sessions: {} };
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
async function writeState(root, state) {
|
|
232
|
+
const temporary = path.join(root, `.auth-${randomUUID()}`);
|
|
233
|
+
const handle = await open(temporary, "wx", 384);
|
|
234
|
+
try {
|
|
235
|
+
await handle.writeFile(JSON.stringify(state));
|
|
236
|
+
await handle.sync();
|
|
237
|
+
await handle.close();
|
|
238
|
+
await rename(temporary, path.join(root, "auth.json"));
|
|
239
|
+
} finally {
|
|
240
|
+
await handle.close().catch(() => {
|
|
241
|
+
});
|
|
242
|
+
await unlink(temporary).catch(() => {
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
async function withAuthStore(directory, action) {
|
|
247
|
+
const root = configRoot(directory);
|
|
248
|
+
const unlock = await storageOperation(async () => {
|
|
249
|
+
await prepareDirectory(root);
|
|
250
|
+
return lockStore(root);
|
|
251
|
+
});
|
|
252
|
+
try {
|
|
253
|
+
const state = await storageOperation(
|
|
254
|
+
() => readState(pathToFileURL(path.join(root, "auth.json")))
|
|
255
|
+
);
|
|
256
|
+
return await action(
|
|
257
|
+
state,
|
|
258
|
+
() => storageOperation(() => writeState(root, state))
|
|
259
|
+
);
|
|
260
|
+
} finally {
|
|
261
|
+
await storageOperation(unlock);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
async function storageOperation(operation) {
|
|
265
|
+
try {
|
|
266
|
+
return await operation();
|
|
267
|
+
} catch (error) {
|
|
268
|
+
if (error instanceof AuthError) throw error;
|
|
269
|
+
throw new AuthError(
|
|
270
|
+
"Cannot safely access authentication storage. Check your Sedum user config directory and its permissions."
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// src/auth-command.ts
|
|
276
|
+
function openBrowser(url) {
|
|
277
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32.exe" : "xdg-open";
|
|
278
|
+
const child = spawn(
|
|
279
|
+
command,
|
|
280
|
+
process.platform === "win32" ? ["url.dll,FileProtocolHandler", url.href] : [url.href],
|
|
281
|
+
{ stdio: "ignore", shell: false }
|
|
282
|
+
);
|
|
283
|
+
child.on("error", () => {
|
|
284
|
+
});
|
|
285
|
+
child.unref();
|
|
286
|
+
}
|
|
287
|
+
function verification(url, origin) {
|
|
288
|
+
try {
|
|
289
|
+
if (url.origin !== origin) throw new Error();
|
|
290
|
+
if ([url.username, url.password, url.hash].some(Boolean)) throw new Error();
|
|
291
|
+
return url;
|
|
292
|
+
} catch {
|
|
293
|
+
throw new AuthError(
|
|
294
|
+
"Cloud returned an unsafe verification URL; login stopped."
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
var deviceSchema = z2.object({
|
|
299
|
+
device_code: z2.string().min(1),
|
|
300
|
+
user_code: z2.string().min(1).regex(/^[\w -]+$/),
|
|
301
|
+
verification_uri: z2.string(),
|
|
302
|
+
verification_uri_complete: z2.string(),
|
|
303
|
+
expires_in: z2.number().positive().max(600),
|
|
304
|
+
interval: z2.number().positive().max(600)
|
|
305
|
+
});
|
|
306
|
+
function showActivation(device, origin, context) {
|
|
307
|
+
const activation = verification(new URL(device.verification_uri), origin);
|
|
308
|
+
const complete = verification(
|
|
309
|
+
new URL(device.verification_uri_complete),
|
|
310
|
+
origin
|
|
311
|
+
);
|
|
312
|
+
context.write(
|
|
313
|
+
`Open ${activation}
|
|
314
|
+
Enter code: ${device.user_code}
|
|
315
|
+
Waiting for browser approval. Press Ctrl-C to cancel.
|
|
316
|
+
`
|
|
317
|
+
);
|
|
318
|
+
if (context.options.browser === false) return;
|
|
319
|
+
try {
|
|
320
|
+
if (context.runtime.openBrowser) context.runtime.openBrowser(complete.href);
|
|
321
|
+
else openBrowser(complete);
|
|
322
|
+
} catch {
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
function pollInterval(result, interval) {
|
|
326
|
+
if (result.status === 429) return Math.max(interval, result.retryMs);
|
|
327
|
+
if (result.status !== 400)
|
|
328
|
+
throw new AuthError(
|
|
329
|
+
"Cloud rejected device login. Start `sedum auth login` again."
|
|
330
|
+
);
|
|
331
|
+
const error = parse(z2.object({ error: z2.string() }), result.body).error;
|
|
332
|
+
if (error === "authorization_pending") return interval;
|
|
333
|
+
if (error === "slow_down") return interval + 5e3;
|
|
334
|
+
throw deviceFailure(error);
|
|
335
|
+
}
|
|
336
|
+
function deviceFailure(error) {
|
|
337
|
+
if (error === "access_denied")
|
|
338
|
+
return new AuthError("Login was denied in the browser.");
|
|
339
|
+
if (["expired_token", "invalid_grant"].includes(error)) return expired();
|
|
340
|
+
return new AuthError(
|
|
341
|
+
"Cloud rejected device login. Start `sedum auth login` again."
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
function expired() {
|
|
345
|
+
return new AuthError("Device login expired. Run `sedum auth login` again.");
|
|
346
|
+
}
|
|
347
|
+
async function deviceLogin(origin, context) {
|
|
348
|
+
const response = await request(
|
|
349
|
+
origin,
|
|
350
|
+
"/api/oauth/device/code",
|
|
351
|
+
context.signal,
|
|
352
|
+
{ form: {} }
|
|
353
|
+
);
|
|
354
|
+
if (!response.ok)
|
|
355
|
+
throw new AuthError(
|
|
356
|
+
"Cloud could not start device login. Check the instance configuration."
|
|
357
|
+
);
|
|
358
|
+
const device = parse(deviceSchema, response.body);
|
|
359
|
+
showActivation(device, origin, context);
|
|
360
|
+
const deadline = performance.now() + device.expires_in * 1e3;
|
|
361
|
+
let interval = device.interval * 1e3;
|
|
362
|
+
let delay = Math.max(interval, response.retryMs);
|
|
363
|
+
while (performance.now() < deadline) {
|
|
364
|
+
const nextPoll = performance.now() + delay;
|
|
365
|
+
while (performance.now() < Math.min(nextPoll, deadline)) {
|
|
366
|
+
await sleep(
|
|
367
|
+
Math.max(1, Math.min(nextPoll, deadline) - performance.now()),
|
|
368
|
+
void 0,
|
|
369
|
+
{
|
|
370
|
+
signal: context.signal
|
|
371
|
+
}
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
if (performance.now() >= deadline) break;
|
|
375
|
+
const result = await pollDevice(
|
|
376
|
+
{ origin, deadline, deviceCode: device.device_code },
|
|
377
|
+
context
|
|
378
|
+
);
|
|
379
|
+
if (result.ok) return tokenResult(result.body);
|
|
380
|
+
interval = pollInterval(result, interval);
|
|
381
|
+
delay = Math.max(interval, result.retryMs);
|
|
382
|
+
}
|
|
383
|
+
throw expired();
|
|
384
|
+
}
|
|
385
|
+
async function pollDevice(device, context) {
|
|
386
|
+
const remaining = Math.max(1, Math.ceil(device.deadline - performance.now()));
|
|
387
|
+
const signal = AbortSignal.any([
|
|
388
|
+
context.signal,
|
|
389
|
+
AbortSignal.timeout(remaining)
|
|
390
|
+
]);
|
|
391
|
+
try {
|
|
392
|
+
return await request(device.origin, "/api/oauth/token", signal, {
|
|
393
|
+
form: {
|
|
394
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
395
|
+
device_code: device.deviceCode
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
} catch (error) {
|
|
399
|
+
if (!context.signal.aborted && signal.aborted) throw expired();
|
|
400
|
+
throw error;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
function explicitChoice(kind, choices, value) {
|
|
404
|
+
const ids = choices.filter((item) => item.id === value);
|
|
405
|
+
const matches = ids.length ? ids : choices.filter((item) => item.name === value);
|
|
406
|
+
if (matches.length !== 1)
|
|
407
|
+
throw new AuthError(
|
|
408
|
+
`--${kind} must match a current ID or unambiguous name.`
|
|
409
|
+
);
|
|
410
|
+
return matches[0];
|
|
411
|
+
}
|
|
412
|
+
async function select(kind, choices, previous, context) {
|
|
413
|
+
const explicit = context.options[kind];
|
|
414
|
+
if (explicit) return explicitChoice(kind, choices, explicit);
|
|
415
|
+
const found = choices.find((item) => item.id === previous);
|
|
416
|
+
if (found) return found;
|
|
417
|
+
if (choices.length <= 1) return choices[0];
|
|
418
|
+
if (!context.runtime.choose)
|
|
419
|
+
throw new AuthError(
|
|
420
|
+
`Multiple ${kind} choices. Rerun with --${kind} <ID or unambiguous name>.`
|
|
421
|
+
);
|
|
422
|
+
const id = await context.runtime.choose(kind, choices, context.signal);
|
|
423
|
+
return explicitChoice(kind, choices, id);
|
|
424
|
+
}
|
|
425
|
+
async function logout(store, context) {
|
|
426
|
+
const session = store.state.sessions[store.origin];
|
|
427
|
+
if (session && !await revoke(store, session, context))
|
|
428
|
+
context.writeErr(
|
|
429
|
+
"Warning: remote revocation could not be confirmed. Local credentials removed; the remote session may remain active until its 30-day expiry.\n"
|
|
430
|
+
);
|
|
431
|
+
delete store.state.sessions[store.origin];
|
|
432
|
+
delete store.state.selections[store.origin];
|
|
433
|
+
await store.save();
|
|
434
|
+
context.write("Logged out locally.\n");
|
|
435
|
+
}
|
|
436
|
+
async function revoke(store, session, context) {
|
|
437
|
+
try {
|
|
438
|
+
const result = await request(
|
|
439
|
+
store.origin,
|
|
440
|
+
"/api/oauth/revoke",
|
|
441
|
+
context.signal,
|
|
442
|
+
{
|
|
443
|
+
form: { token: session.refresh_token }
|
|
444
|
+
}
|
|
445
|
+
);
|
|
446
|
+
return result.ok;
|
|
447
|
+
} catch {
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
async function login(store, context) {
|
|
452
|
+
const previous = store.state.sessions[store.origin];
|
|
453
|
+
const next = await deviceLogin(store.origin, context);
|
|
454
|
+
store.state.sessions[store.origin] = next;
|
|
455
|
+
store.state.selectedOrigin = store.origin;
|
|
456
|
+
await store.save();
|
|
457
|
+
if (previous && !await revoke(store, previous, context))
|
|
458
|
+
context.writeErr(
|
|
459
|
+
"Warning: your previous CLI session could not be revoked and may remain active until its 30-day expiry. The new login is saved.\n"
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
async function currentSession(store, context) {
|
|
463
|
+
const session = store.state.sessions[store.origin];
|
|
464
|
+
if (!session)
|
|
465
|
+
throw new AuthError(
|
|
466
|
+
"Not logged in to this instance. Run `sedum auth login`."
|
|
467
|
+
);
|
|
468
|
+
if (session.expiresAt > Date.now()) return session;
|
|
469
|
+
return refreshSession(store, session, context);
|
|
470
|
+
}
|
|
471
|
+
async function refreshSession(store, session, context) {
|
|
472
|
+
const refreshed = await request(
|
|
473
|
+
store.origin,
|
|
474
|
+
"/api/oauth/token",
|
|
475
|
+
context.signal,
|
|
476
|
+
{
|
|
477
|
+
form: {
|
|
478
|
+
grant_type: "refresh_token",
|
|
479
|
+
refresh_token: session.refresh_token
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
);
|
|
483
|
+
if (!refreshed.ok)
|
|
484
|
+
throw new AuthError(
|
|
485
|
+
"Session could not be refreshed. Run `sedum auth login` again."
|
|
486
|
+
);
|
|
487
|
+
const next = tokenResult(refreshed.body);
|
|
488
|
+
store.state.sessions[store.origin] = next;
|
|
489
|
+
await store.save();
|
|
490
|
+
return next;
|
|
491
|
+
}
|
|
492
|
+
async function authenticatedGet(store, context, endpoint) {
|
|
493
|
+
const session = await currentSession(store, context);
|
|
494
|
+
let response = await request(store.origin, endpoint, context.signal, {
|
|
495
|
+
access: session.access_token
|
|
496
|
+
});
|
|
497
|
+
if (response.status === 401) {
|
|
498
|
+
const next = await refreshSession(store, session, context);
|
|
499
|
+
response = await request(store.origin, endpoint, context.signal, {
|
|
500
|
+
access: next.access_token
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
return response;
|
|
504
|
+
}
|
|
505
|
+
async function membership(store, context) {
|
|
506
|
+
const response = await authenticatedGet(store, context, "/api/auth/me");
|
|
507
|
+
if (!response.ok)
|
|
508
|
+
throw new AuthError(
|
|
509
|
+
"Cloud could not validate this session or current membership. Run `sedum auth login` again."
|
|
510
|
+
);
|
|
511
|
+
return parse(membershipSchema, response.body);
|
|
512
|
+
}
|
|
513
|
+
async function readCloudProject(options, runtime, signal, read) {
|
|
514
|
+
return withAuthStore(runtime.configDirectory, async (state, save) => {
|
|
515
|
+
const store = { state, save, origin: selectedOrigin(options, state) };
|
|
516
|
+
const context = {
|
|
517
|
+
options,
|
|
518
|
+
runtime: {},
|
|
519
|
+
signal,
|
|
520
|
+
write: () => {
|
|
521
|
+
},
|
|
522
|
+
writeErr: () => {
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
const me = await membership(store, context);
|
|
526
|
+
const previous = state.selections[store.origin];
|
|
527
|
+
const organization = await select(
|
|
528
|
+
"organization",
|
|
529
|
+
me.organizations,
|
|
530
|
+
previous?.organization,
|
|
531
|
+
context
|
|
532
|
+
);
|
|
533
|
+
const project = await select(
|
|
534
|
+
"project",
|
|
535
|
+
organization?.projects ?? [],
|
|
536
|
+
previous?.project,
|
|
537
|
+
context
|
|
538
|
+
);
|
|
539
|
+
if (!organization || !project)
|
|
540
|
+
throw new AuthError(
|
|
541
|
+
"No current project available. Select --organization and --project or create a Cloud project."
|
|
542
|
+
);
|
|
543
|
+
return read({
|
|
544
|
+
origin: store.origin,
|
|
545
|
+
organization,
|
|
546
|
+
project,
|
|
547
|
+
get: (endpoint) => authenticatedGet(store, context, endpoint)
|
|
548
|
+
});
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
async function status(store, context) {
|
|
552
|
+
const me = await membership(store, context);
|
|
553
|
+
const previous = store.state.selections[store.origin];
|
|
554
|
+
delete store.state.selections[store.origin];
|
|
555
|
+
await store.save();
|
|
556
|
+
context.write(
|
|
557
|
+
`Signed in to ${store.origin} as ${JSON.stringify(me.user.email ?? me.user.name ?? me.user.id)}.
|
|
558
|
+
`
|
|
559
|
+
);
|
|
560
|
+
const organization = await select(
|
|
561
|
+
"organization",
|
|
562
|
+
me.organizations,
|
|
563
|
+
previous?.organization,
|
|
564
|
+
context
|
|
565
|
+
);
|
|
566
|
+
const project = await select(
|
|
567
|
+
"project",
|
|
568
|
+
organization?.projects ?? [],
|
|
569
|
+
previous?.project,
|
|
570
|
+
context
|
|
571
|
+
);
|
|
572
|
+
store.state.selections[store.origin] = {
|
|
573
|
+
organization: organization?.id,
|
|
574
|
+
project: project?.id
|
|
575
|
+
};
|
|
576
|
+
store.state.selectedOrigin = store.origin;
|
|
577
|
+
await store.save();
|
|
578
|
+
showSelection(organization, project, context);
|
|
579
|
+
}
|
|
580
|
+
function showSelection(organization, project, context) {
|
|
581
|
+
if (!organization || !project) {
|
|
582
|
+
context.write(
|
|
583
|
+
"Account login saved. Open your Cloud instance to create or join an organization and create a project, then run `sedum auth status`.\n"
|
|
584
|
+
);
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
context.write(
|
|
588
|
+
`Organization: ${JSON.stringify(organization.name)} (${JSON.stringify(organization.id)})
|
|
589
|
+
Project: ${JSON.stringify(project.name)} (${JSON.stringify(project.id)})
|
|
590
|
+
`
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
function selectedOrigin(options, state) {
|
|
594
|
+
const configured = options.url ?? process.env.SEDUM_CLOUD_URL ?? state.selectedOrigin;
|
|
595
|
+
if (!configured)
|
|
596
|
+
throw new AuthError(
|
|
597
|
+
"No Cloud instance selected. Use `sedum auth login --url <your Cloud origin>` or set SEDUM_CLOUD_URL."
|
|
598
|
+
);
|
|
599
|
+
return cloudOrigin(configured);
|
|
600
|
+
}
|
|
601
|
+
async function authenticate(command, context) {
|
|
602
|
+
return withAuthStore(context.runtime.configDirectory, async (state, save) => {
|
|
603
|
+
const origin = selectedOrigin(context.options, state);
|
|
604
|
+
const store = { state, save, origin };
|
|
605
|
+
if (command === "logout") return logout(store, context);
|
|
606
|
+
if (command === "login") await login(store, context);
|
|
607
|
+
await status(store, context);
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
async function executeAuthCommand(command, context, externalSignal) {
|
|
611
|
+
const controller = new AbortController();
|
|
612
|
+
const cancel = () => controller.abort();
|
|
613
|
+
process.on("SIGINT", cancel);
|
|
614
|
+
const signal = externalSignal ? AbortSignal.any([externalSignal, controller.signal]) : controller.signal;
|
|
615
|
+
try {
|
|
616
|
+
await authenticate(command, { ...context, signal });
|
|
617
|
+
return 0;
|
|
618
|
+
} catch (error) {
|
|
619
|
+
context.writeErr(`${authMessage(error, signal)}
|
|
620
|
+
`);
|
|
621
|
+
return 3;
|
|
622
|
+
} finally {
|
|
623
|
+
process.removeListener("SIGINT", cancel);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
function authMessage(error, signal) {
|
|
627
|
+
if (signal.aborted) return "Authentication cancelled.";
|
|
628
|
+
if (error instanceof AuthError) return error.message;
|
|
629
|
+
return "Authentication failed safely; no server error details were printed.";
|
|
630
|
+
}
|
|
631
|
+
export {
|
|
632
|
+
executeAuthCommand,
|
|
633
|
+
readCloudProject
|
|
634
|
+
};
|