@typeship-ax/cli 0.8.0 → 0.9.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/AGENTS.md +31 -0
- package/README.md +26 -9
- package/api.json +1875 -684
- package/api.md +352 -500
- package/dist/api-identity.d.ts +40 -0
- package/dist/api-identity.d.ts.map +1 -0
- package/dist/api-identity.js +128 -0
- package/dist/auth-profiles.d.ts +30 -0
- package/dist/auth-profiles.d.ts.map +1 -0
- package/dist/auth-profiles.js +138 -0
- package/dist/cli.js +522 -355
- package/dist/console-login-check.d.ts +21 -0
- package/dist/console-login-check.d.ts.map +1 -0
- package/dist/console-login-check.js +107 -0
- package/dist/console-login-contract.d.ts +45 -0
- package/dist/console-login-contract.d.ts.map +1 -0
- package/dist/console-login-contract.js +40 -0
- package/dist/core/http.d.ts +17 -2
- package/dist/core/http.d.ts.map +1 -1
- package/dist/core/http.js +78 -17
- package/dist/credential-storage.d.ts +24 -0
- package/dist/credential-storage.d.ts.map +1 -0
- package/dist/credential-storage.js +207 -0
- package/dist/docs.d.ts +25 -0
- package/dist/docs.d.ts.map +1 -1
- package/dist/docs.js +144 -0
- package/dist/errors.d.ts +18 -10
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +24 -14
- package/dist/index.d.ts +10 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -4
- package/dist/named-credentials.d.ts +21 -0
- package/dist/named-credentials.d.ts.map +1 -0
- package/dist/named-credentials.js +86 -0
- package/dist/oauth-login.d.ts +39 -0
- package/dist/oauth-login.d.ts.map +1 -0
- package/dist/oauth-login.js +171 -0
- package/dist/oauth-request.d.ts +21 -0
- package/dist/oauth-request.d.ts.map +1 -0
- package/dist/oauth-request.js +119 -0
- package/dist/oauth-session.d.ts +106 -0
- package/dist/oauth-session.d.ts.map +1 -0
- package/dist/oauth-session.js +244 -0
- package/dist/ops.d.ts +14 -1
- package/dist/ops.d.ts.map +1 -1
- package/dist/ops.js +30 -30
- package/dist/polling-login.d.ts +57 -0
- package/dist/polling-login.d.ts.map +1 -0
- package/dist/polling-login.js +204 -0
- package/dist/resources/account.d.ts +2 -2
- package/dist/resources/account.d.ts.map +1 -1
- package/dist/resources/account.js +1 -0
- package/dist/resources/api-keys.d.ts +3 -3
- package/dist/resources/api-keys.d.ts.map +1 -1
- package/dist/resources/api-keys.js +2 -0
- package/dist/resources/definition-revisions.d.ts +5 -5
- package/dist/resources/definition-revisions.d.ts.map +1 -1
- package/dist/resources/definition-revisions.js +4 -0
- package/dist/resources/definitions.d.ts +15 -4
- package/dist/resources/definitions.d.ts.map +1 -1
- package/dist/resources/definitions.js +11 -2
- package/dist/resources/generate.d.ts +14 -3
- package/dist/resources/generate.d.ts.map +1 -1
- package/dist/resources/generate.js +10 -2
- package/dist/resources/generations.d.ts +3 -3
- package/dist/resources/generations.d.ts.map +1 -1
- package/dist/resources/generations.js +2 -0
- package/dist/resources/projects.d.ts +56 -20
- package/dist/resources/projects.d.ts.map +1 -1
- package/dist/resources/projects.js +40 -4
- package/dist/resources/targets.d.ts +20 -9
- package/dist/resources/targets.d.ts.map +1 -1
- package/dist/resources/targets.js +14 -1
- package/dist/schemas.d.ts.map +1 -1
- package/dist/schemas.js +38 -22
- package/dist/types.d.ts +385 -119
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +11 -0
- package/package.json +2 -1
- package/src/api-identity.ts +98 -0
- package/src/auth-profiles.ts +114 -0
- package/src/cli.ts +444 -332
- package/src/console-login-check.ts +88 -0
- package/src/console-login-contract.ts +65 -0
- package/src/core/http.ts +88 -19
- package/src/credential-storage.ts +183 -0
- package/src/docs.ts +138 -0
- package/src/errors.ts +26 -15
- package/src/index.ts +29 -4
- package/src/named-credentials.ts +74 -0
- package/src/oauth-login.ts +184 -0
- package/src/oauth-request.ts +90 -0
- package/src/oauth-session.ts +258 -0
- package/src/ops.ts +44 -31
- package/src/polling-login.ts +165 -0
- package/src/resources/account.ts +3 -0
- package/src/resources/api-keys.ts +5 -0
- package/src/resources/definition-revisions.ts +9 -0
- package/src/resources/definitions.ts +25 -0
- package/src/resources/generate.ts +23 -0
- package/src/resources/generations.ts +5 -0
- package/src/resources/projects.ts +95 -7
- package/src/resources/targets.ts +32 -0
- package/src/schemas.ts +38 -22
- package/src/types.ts +404 -119
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Identity comes from the authenticated API response, including opaque-token APIs. */
|
|
2
|
+
export type IdentityKind = "subject" | "account" | "organization";
|
|
3
|
+
export type IdentityPolicy = Partial<Record<IdentityKind, string>>;
|
|
4
|
+
export type ApiIdentity = Partial<Record<IdentityKind, string | null>>;
|
|
5
|
+
export interface VerifiedIdentity {
|
|
6
|
+
values: ApiIdentity;
|
|
7
|
+
checkedAt: string;
|
|
8
|
+
}
|
|
9
|
+
export interface IdentityConfiguration {
|
|
10
|
+
operation: string;
|
|
11
|
+
fields: IdentityPolicy;
|
|
12
|
+
}
|
|
13
|
+
export declare function validateIdentityPointer(pointer: unknown): asserts pointer is string;
|
|
14
|
+
export declare function identityPolicyOf(auth?: {
|
|
15
|
+
identitySubject?: string | null;
|
|
16
|
+
identityAccount?: string | null;
|
|
17
|
+
identityOrganization?: string | null;
|
|
18
|
+
}): IdentityPolicy;
|
|
19
|
+
export declare function readApiIdentity(data: unknown, policy: IdentityPolicy): ApiIdentity;
|
|
20
|
+
export declare function assertApiIdentity(expected: ApiIdentity, actual: ApiIdentity): void;
|
|
21
|
+
/** No redirects, bounded decoded response, and one deadline including body reads. */
|
|
22
|
+
export declare function identityFetch(apiBaseUrl: string): typeof fetch;
|
|
23
|
+
type IdentityResult = {
|
|
24
|
+
ok: boolean;
|
|
25
|
+
data?: unknown;
|
|
26
|
+
error?: {
|
|
27
|
+
status?: number;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
export declare function identityResult(client: unknown, operation: {
|
|
31
|
+
resource: string;
|
|
32
|
+
method: string;
|
|
33
|
+
}): Promise<IdentityResult>;
|
|
34
|
+
export declare function verifyClientIdentity(createClient: (options: Record<string, unknown>) => unknown, options: Record<string, unknown>, operation: {
|
|
35
|
+
resource: string;
|
|
36
|
+
method: string;
|
|
37
|
+
}, policy: IdentityPolicy, expected?: ApiIdentity): Promise<VerifiedIdentity>;
|
|
38
|
+
export declare function verifyApiIdentity(read: (anonymous: boolean) => Promise<IdentityResult>, policy: IdentityPolicy, expected?: ApiIdentity): Promise<VerifiedIdentity>;
|
|
39
|
+
export {};
|
|
40
|
+
//# sourceMappingURL=api-identity.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-identity.d.ts","sourceRoot":"","sources":["../src/api-identity.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG,SAAS,GAAG,cAAc,CAAC;AAClE,MAAM,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC;AACnE,MAAM,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;AACvE,MAAM,WAAW,gBAAgB;IAAG,MAAM,EAAE,WAAW,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE;AAC5E,MAAM,WAAW,qBAAqB;IAAG,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,cAAc,CAAA;CAAE;AAEpF,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,MAAM,CAInF;AAED,wBAAgB,gBAAgB,CAAC,IAAI,GAAE;IAAE,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,oBAAoB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAO,GAAG,cAAc,CAKtK;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,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(pointer) || /~(?:[^01]|$)/.test(pointer)) {
|
|
3
|
+
throw new Error("Identity fields must be JSON Pointers starting with /, at most 512 characters, with ~0 and ~1 escapes.");
|
|
4
|
+
}
|
|
5
|
+
}
|
|
6
|
+
export function identityPolicyOf(auth = {}) {
|
|
7
|
+
const entries = [["subject", auth.identitySubject], ["account", auth.identityAccount], ["organization", auth.identityOrganization]];
|
|
8
|
+
const policy = {};
|
|
9
|
+
for (const [kind, pointer] of entries)
|
|
10
|
+
if (pointer !== undefined && pointer !== null) {
|
|
11
|
+
validateIdentityPointer(pointer);
|
|
12
|
+
policy[kind] = pointer;
|
|
13
|
+
}
|
|
14
|
+
return policy;
|
|
15
|
+
}
|
|
16
|
+
export function readApiIdentity(data, policy) {
|
|
17
|
+
const result = {};
|
|
18
|
+
if (!Object.keys(policy).length)
|
|
19
|
+
throw new Error("Configure at least one identity field before verifying a session.");
|
|
20
|
+
for (const [kind, pointer] of Object.entries(policy)) {
|
|
21
|
+
validateIdentityPointer(pointer);
|
|
22
|
+
let value = data;
|
|
23
|
+
for (const part of pointer.slice(1).split("/").map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"))) {
|
|
24
|
+
if (!value || typeof value !== "object" || !Object.hasOwn(value, part))
|
|
25
|
+
throw new Error("The API identity response is missing a configured field. Check the identity field mapping.");
|
|
26
|
+
value = value[part];
|
|
27
|
+
}
|
|
28
|
+
if (value === null && kind === "organization")
|
|
29
|
+
result[kind] = null;
|
|
30
|
+
else if ((typeof value === "string" && value.length > 0 && value.length <= 512 && !/[\x00-\x1f\x7f]/.test(value)) || (typeof value === "number" && Number.isSafeInteger(value)))
|
|
31
|
+
result[kind] = String(value);
|
|
32
|
+
else
|
|
33
|
+
throw new Error("The API identity field must return a nonempty ID string or safe integer. Only an organization may be null.");
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
export function assertApiIdentity(expected, actual) {
|
|
38
|
+
if (!Object.keys(expected).length || Object.entries(expected).some(([key, value]) => !Object.hasOwn(actual, key) || actual[key] !== value)) {
|
|
39
|
+
throw new Error("The authenticated account, subject or organization does not match this login. Sign in again with the intended account and organization.");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** No redirects, bounded decoded response, and one deadline including body reads. */
|
|
43
|
+
export function identityFetch(apiBaseUrl) {
|
|
44
|
+
const base = new URL(apiBaseUrl);
|
|
45
|
+
if ((base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname))) || base.username || base.password || base.search || base.hash)
|
|
46
|
+
throw new Error("Identity verification requires an HTTPS API URL; loopback HTTP is allowed for development.");
|
|
47
|
+
const basePath = base.pathname.replace(/\/+$/, "");
|
|
48
|
+
return async (input, init) => {
|
|
49
|
+
const url = new URL(input instanceof Request ? input.url : String(input));
|
|
50
|
+
if (url.origin !== base.origin || (url.pathname !== basePath && !url.pathname.startsWith(basePath + "/")) || url.username || url.password || url.hash)
|
|
51
|
+
throw new Error("The identity read must stay on the configured API.");
|
|
52
|
+
const abort = new AbortController();
|
|
53
|
+
const timeout = setTimeout(() => abort.abort(), 10_000);
|
|
54
|
+
try {
|
|
55
|
+
const signal = init?.signal ? AbortSignal.any([init.signal, abort.signal]) : abort.signal;
|
|
56
|
+
const response = await fetch(input, { ...init, redirect: "error", signal });
|
|
57
|
+
const reader = response.body?.getReader();
|
|
58
|
+
const chunks = [];
|
|
59
|
+
let size = 0;
|
|
60
|
+
if (reader) {
|
|
61
|
+
try {
|
|
62
|
+
while (true) {
|
|
63
|
+
const chunk = await reader.read();
|
|
64
|
+
if (chunk.done)
|
|
65
|
+
break;
|
|
66
|
+
size += chunk.value.byteLength;
|
|
67
|
+
if (size > 1_048_576) {
|
|
68
|
+
abort.abort();
|
|
69
|
+
throw new Error();
|
|
70
|
+
}
|
|
71
|
+
chunks.push(chunk.value);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
reader.releaseLock();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const bytes = new Uint8Array(size);
|
|
79
|
+
let offset = 0;
|
|
80
|
+
for (const chunk of chunks) {
|
|
81
|
+
bytes.set(chunk, offset);
|
|
82
|
+
offset += chunk.byteLength;
|
|
83
|
+
}
|
|
84
|
+
return new Response([204, 205, 304].includes(response.status) ? null : bytes, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
throw new Error("The API identity read failed. Check the API URL, connectivity and response size before signing in again.");
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
clearTimeout(timeout);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export async function identityResult(client, operation) {
|
|
95
|
+
const target = client[operation.resource];
|
|
96
|
+
if (!target?.[operation.method])
|
|
97
|
+
throw new Error("The configured identity operation is not available in this package.");
|
|
98
|
+
return target[operation.method]();
|
|
99
|
+
}
|
|
100
|
+
export function verifyClientIdentity(createClient, options, operation, policy, expected) {
|
|
101
|
+
if (typeof options.baseUrl !== "string")
|
|
102
|
+
throw new Error("Configure the API base URL before verifying identity.");
|
|
103
|
+
const shared = { baseUrl: options.baseUrl, environment: options.environment, fetch: identityFetch(options.baseUrl), maxRetries: 0, timeoutMs: 10_000 };
|
|
104
|
+
return verifyApiIdentity((anonymous) => identityResult(createClient(anonymous ? shared : { ...options, ...shared }), operation), policy, expected);
|
|
105
|
+
}
|
|
106
|
+
export async function verifyApiIdentity(read, policy, expected) {
|
|
107
|
+
let anonymous, authenticated;
|
|
108
|
+
try {
|
|
109
|
+
anonymous = await read(true);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
throw new Error("Could not verify that the identity read rejects anonymous access.");
|
|
113
|
+
}
|
|
114
|
+
if (anonymous.ok || ![401, 403].includes(anonymous.error?.status ?? 0))
|
|
115
|
+
throw new Error("The identity read must reject anonymous access with 401 or 403 before login can be verified.");
|
|
116
|
+
try {
|
|
117
|
+
authenticated = await read(false);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
throw new Error("The API identity read failed with the new credential. Check the API configuration and granted permissions.");
|
|
121
|
+
}
|
|
122
|
+
if (!authenticated.ok)
|
|
123
|
+
throw new Error("The API did not accept the new login credential for its identity read. Check the audience, scopes and account access.");
|
|
124
|
+
const values = readApiIdentity(authenticated.data, policy);
|
|
125
|
+
if (expected)
|
|
126
|
+
assertApiIdentity(expected, values);
|
|
127
|
+
return { values, checkedAt: new Date().toISOString() };
|
|
128
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface ProfileConfig {
|
|
2
|
+
baseUrl?: string;
|
|
3
|
+
environment?: string;
|
|
4
|
+
docsUrl?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ProfileContext {
|
|
7
|
+
name: string;
|
|
8
|
+
directory: string;
|
|
9
|
+
source: "flag" | "environment" | "selected" | "default";
|
|
10
|
+
}
|
|
11
|
+
export declare function profileName(value: string): string;
|
|
12
|
+
export declare function profileDirectory(root: string, name: string): string;
|
|
13
|
+
export declare function resolveProfile(root: string, options?: {
|
|
14
|
+
flag?: string;
|
|
15
|
+
environment?: string;
|
|
16
|
+
allowMissing?: boolean;
|
|
17
|
+
}): ProfileContext;
|
|
18
|
+
export declare function selectProfile(root: string, name: string): void;
|
|
19
|
+
export declare function readProfileConfig(directory: string): ProfileConfig;
|
|
20
|
+
export declare function updateProfileConfig(directory: string, change: (current: ProfileConfig) => ProfileConfig): Promise<void>;
|
|
21
|
+
export declare function listProfiles(root: string): {
|
|
22
|
+
name: string;
|
|
23
|
+
config: ProfileConfig;
|
|
24
|
+
hasSavedCredentials: boolean;
|
|
25
|
+
}[];
|
|
26
|
+
/** Removing a profile requires logout first. Hold the settings and both storage
|
|
27
|
+
* locks so a concurrent login cannot be deleted underneath its transaction. */
|
|
28
|
+
export declare function removeProfile(root: string, name: string): Promise<void>;
|
|
29
|
+
export declare function profileFlag(args: string[]): string | undefined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AAE,EAAE,CAYlH;AAED;+EAC+E;AAC/E,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAc7E;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS,CAS9D"}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { FileCredentialStore } from "./oauth-session.js";
|
|
5
|
+
export function profileName(value) {
|
|
6
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(value) || /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/.test(value))
|
|
7
|
+
throw new Error("Profile names use 1–64 lowercase letters, numbers, hyphens or underscores and cannot be reserved OS names.");
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
function json(path) {
|
|
11
|
+
try {
|
|
12
|
+
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
13
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
14
|
+
throw new Error();
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (error.code === "ENOENT")
|
|
19
|
+
return null;
|
|
20
|
+
throw new Error("Cannot read profile settings. Repair the settings file before retrying.");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function write(directory, file, value) {
|
|
24
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
25
|
+
const temporary = join(directory, ".profile-" + randomBytes(16).toString("hex") + ".tmp");
|
|
26
|
+
try {
|
|
27
|
+
writeFileSync(temporary, JSON.stringify(value, null, 2) + "\n", { flag: "wx", mode: 0o600, flush: true });
|
|
28
|
+
renameSync(temporary, join(directory, file));
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
rmSync(temporary, { force: true });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function profileDirectory(root, name) {
|
|
35
|
+
const directory = join(root, "profiles", profileName(name));
|
|
36
|
+
try {
|
|
37
|
+
const entry = lstatSync(directory);
|
|
38
|
+
if (entry.isSymbolicLink() || !entry.isDirectory())
|
|
39
|
+
throw new Error("A profile must be a directory, not a link or another file.");
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error.code !== "ENOENT")
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
return directory;
|
|
46
|
+
}
|
|
47
|
+
export function resolveProfile(root, options = {}) {
|
|
48
|
+
let name, source;
|
|
49
|
+
if (options.flag !== undefined) {
|
|
50
|
+
name = profileName(options.flag);
|
|
51
|
+
source = "flag";
|
|
52
|
+
}
|
|
53
|
+
else if (options.environment !== undefined) {
|
|
54
|
+
name = profileName(options.environment);
|
|
55
|
+
source = "environment";
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
const settings = json(join(root, "profiles.json"));
|
|
59
|
+
if (settings && typeof settings.selected !== "string")
|
|
60
|
+
throw new Error("The selected profile setting is invalid. Pass --profile default to recover.");
|
|
61
|
+
name = settings ? profileName(settings.selected) : "default";
|
|
62
|
+
source = settings ? "selected" : "default";
|
|
63
|
+
}
|
|
64
|
+
const directory = profileDirectory(root, name);
|
|
65
|
+
if (name !== "default" && !options.allowMissing && !existsSync(directory))
|
|
66
|
+
throw new Error("Profile '" + name + "' does not exist. Run login --profile " + name + " or configure that profile first.");
|
|
67
|
+
return { name, directory, source };
|
|
68
|
+
}
|
|
69
|
+
export function selectProfile(root, name) {
|
|
70
|
+
const directory = profileDirectory(root, name);
|
|
71
|
+
if (name !== "default" && !existsSync(directory))
|
|
72
|
+
throw new Error("Profile '" + name + "' does not exist. Log in or configure it before selecting it.");
|
|
73
|
+
write(root, "profiles.json", { selected: name });
|
|
74
|
+
}
|
|
75
|
+
export function readProfileConfig(directory) {
|
|
76
|
+
const value = json(join(directory, "config.json")) ?? {};
|
|
77
|
+
for (const [key, field] of Object.entries(value))
|
|
78
|
+
if (!["baseUrl", "environment", "docsUrl"].includes(key) || typeof field !== "string")
|
|
79
|
+
throw new Error("Profile settings contain an unknown field or a non-string value.");
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
export async function updateProfileConfig(directory, change) {
|
|
83
|
+
await new FileCredentialStore(join(directory, "config.json")).withLock(async () => { write(directory, "config.json", change(readProfileConfig(directory))); });
|
|
84
|
+
}
|
|
85
|
+
export function listProfiles(root) {
|
|
86
|
+
const names = new Set(["default"]);
|
|
87
|
+
try {
|
|
88
|
+
for (const entry of readdirSync(join(root, "profiles"), { withFileTypes: true })) {
|
|
89
|
+
if (!entry.isDirectory() || entry.isSymbolicLink())
|
|
90
|
+
continue;
|
|
91
|
+
try {
|
|
92
|
+
names.add(profileName(entry.name));
|
|
93
|
+
}
|
|
94
|
+
catch { /* unrelated directories are not profiles */ }
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error.code !== "ENOENT")
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
return [...names].sort().map((name) => {
|
|
102
|
+
const directory = profileDirectory(root, name);
|
|
103
|
+
return { name, config: readProfileConfig(directory), hasSavedCredentials: ["credentials.enc", "credentials.json"].some((file) => existsSync(join(directory, file))) };
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/** Removing a profile requires logout first. Hold the settings and both storage
|
|
107
|
+
* locks so a concurrent login cannot be deleted underneath its transaction. */
|
|
108
|
+
export async function removeProfile(root, name) {
|
|
109
|
+
const directory = profileDirectory(root, name);
|
|
110
|
+
if (!existsSync(directory))
|
|
111
|
+
throw new Error("Profile '" + name + "' does not exist.");
|
|
112
|
+
const paths = ["config.json", "credentials.enc", "credentials.json"].map((file) => join(directory, file));
|
|
113
|
+
await new FileCredentialStore(paths[0]).withLock(async () => {
|
|
114
|
+
await new FileCredentialStore(paths[1]).withLock(async () => {
|
|
115
|
+
await new FileCredentialStore(paths[2]).withLock(async () => {
|
|
116
|
+
if (paths.slice(1).some((path) => existsSync(path)))
|
|
117
|
+
throw new Error("Log out of both credential stores for profile '" + name + "' before removing it. Use logout --profile " + name + ".");
|
|
118
|
+
const selected = json(join(root, "profiles.json"));
|
|
119
|
+
if (selected?.selected === name)
|
|
120
|
+
selectProfile(root, "default");
|
|
121
|
+
rmSync(directory, { recursive: true });
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
export function profileFlag(args) {
|
|
127
|
+
let value;
|
|
128
|
+
for (let i = 0; i < args.length; i++) {
|
|
129
|
+
if (args[i] === "--profile") {
|
|
130
|
+
value = args[++i];
|
|
131
|
+
if (value === undefined || value.startsWith("--"))
|
|
132
|
+
throw new Error("--profile requires a profile name.");
|
|
133
|
+
}
|
|
134
|
+
else if (args[i].startsWith("--profile="))
|
|
135
|
+
value = args[i].slice("--profile=".length);
|
|
136
|
+
}
|
|
137
|
+
return value === undefined ? undefined : profileName(value);
|
|
138
|
+
}
|