@moxo/cli 0.0.0-stage → 0.1.0
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/CHANGELOG.md +19 -0
- package/LICENSE +201 -0
- package/README.md +61 -2
- package/dist/args.d.ts +25 -0
- package/dist/args.d.ts.map +1 -0
- package/dist/args.js +71 -0
- package/dist/args.js.map +1 -0
- package/dist/catalog.d.ts +30 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +33 -0
- package/dist/catalog.js.map +1 -0
- package/dist/cli.d.ts +8 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +15 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/api.d.ts +18 -0
- package/dist/commands/api.d.ts.map +1 -0
- package/dist/commands/api.js +84 -0
- package/dist/commands/api.js.map +1 -0
- package/dist/commands/auth.d.ts +16 -0
- package/dist/commands/auth.d.ts.map +1 -0
- package/dist/commands/auth.js +173 -0
- package/dist/commands/auth.js.map +1 -0
- package/dist/commands/generated.d.ts +31 -0
- package/dist/commands/generated.d.ts.map +1 -0
- package/dist/commands/generated.js +147 -0
- package/dist/commands/generated.js.map +1 -0
- package/dist/commands/help.d.ts +34 -0
- package/dist/commands/help.d.ts.map +1 -0
- package/dist/commands/help.js +117 -0
- package/dist/commands/help.js.map +1 -0
- package/dist/commands/templates.d.ts +59 -0
- package/dist/commands/templates.d.ts.map +1 -0
- package/dist/commands/templates.js +388 -0
- package/dist/commands/templates.js.map +1 -0
- package/dist/config.d.ts +63 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +104 -0
- package/dist/config.js.map +1 -0
- package/dist/confirm.d.ts +11 -0
- package/dist/confirm.d.ts.map +1 -0
- package/dist/confirm.js +21 -0
- package/dist/confirm.js.map +1 -0
- package/dist/context.d.ts +53 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +129 -0
- package/dist/context.js.map +1 -0
- package/dist/credentials.d.ts +50 -0
- package/dist/credentials.d.ts.map +1 -0
- package/dist/credentials.js +148 -0
- package/dist/credentials.js.map +1 -0
- package/dist/errors.d.ts +43 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +61 -0
- package/dist/errors.js.map +1 -0
- package/dist/fields.d.ts +49 -0
- package/dist/fields.d.ts.map +1 -0
- package/dist/fields.js +280 -0
- package/dist/fields.js.map +1 -0
- package/dist/main.d.ts +20 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +189 -0
- package/dist/main.js.map +1 -0
- package/dist/oauth.d.ts +62 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/oauth.js +156 -0
- package/dist/oauth.js.map +1 -0
- package/dist/render.d.ts +10 -0
- package/dist/render.d.ts.map +1 -0
- package/dist/render.js +46 -0
- package/dist/render.js.map +1 -0
- package/dist/session.d.ts +91 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +235 -0
- package/dist/session.js.map +1 -0
- package/dist/spec.d.ts +72 -0
- package/dist/spec.d.ts.map +1 -0
- package/dist/spec.js +171 -0
- package/dist/spec.js.map +1 -0
- package/dist/version.d.ts +7 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +7 -0
- package/dist/version.js.map +1 -0
- package/npm-shrinkwrap.json +3868 -0
- package/package.json +46 -4
package/dist/oauth.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser sign-in for a terminal: the OAuth 2.0 device authorization grant
|
|
3
|
+
* (RFC 8628), found through the server's authorization server metadata
|
|
4
|
+
* (RFC 8414), renewed with its refresh token and revoked on logout (RFC 7009).
|
|
5
|
+
*
|
|
6
|
+
* The CLI is a public client: it has no secret. It shows a short code and an
|
|
7
|
+
* address; the person signs in to Moxo in the browser, chooses the
|
|
8
|
+
* organization and approves the CLI; the CLI then receives a short-lived
|
|
9
|
+
* token for that one organization.
|
|
10
|
+
*/
|
|
11
|
+
import type { Context } from './context.js';
|
|
12
|
+
/** The CLI's client id, unless MOXO_OAUTH_CLIENT_ID names another. */
|
|
13
|
+
export declare const DEFAULT_CLIENT_ID = "moxo-cli";
|
|
14
|
+
export interface ServerMetadata {
|
|
15
|
+
issuer?: string;
|
|
16
|
+
device_authorization_endpoint?: string;
|
|
17
|
+
token_endpoint?: string;
|
|
18
|
+
revocation_endpoint?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface TokenSet {
|
|
21
|
+
accessToken: string;
|
|
22
|
+
refreshToken?: string;
|
|
23
|
+
expiresAt?: number;
|
|
24
|
+
}
|
|
25
|
+
export declare function clientId(ctx: Pick<Context, 'env'>): string;
|
|
26
|
+
/**
|
|
27
|
+
* Holds a sign-in description to the host it was read from: the issuer is
|
|
28
|
+
* that host (RFC 8414 §3.3), and every endpoint the CLI sends a code or a
|
|
29
|
+
* token to is on it. Anything else is refused before a code is asked for.
|
|
30
|
+
*/
|
|
31
|
+
export declare function checkMetadata(metadata: ServerMetadata, host: string): void;
|
|
32
|
+
/** The server's sign-in description, or undefined when it publishes none. */
|
|
33
|
+
export declare function discover(ctx: Pick<Context, 'fetch'>, host: string): Promise<ServerMetadata | undefined>;
|
|
34
|
+
export interface DeviceSignInPrompt {
|
|
35
|
+
userCode: string;
|
|
36
|
+
verificationUri: string;
|
|
37
|
+
verificationUriComplete?: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Runs the device grant: asks for a code, tells the person where to enter it
|
|
41
|
+
* (`show`), and waits for the approval. Answers the token, or throws a
|
|
42
|
+
* sign-in error saying what happened.
|
|
43
|
+
*/
|
|
44
|
+
export declare function deviceSignIn(ctx: Pick<Context, 'fetch' | 'now' | 'sleep' | 'env'>, metadata: ServerMetadata, show: (prompt: DeviceSignInPrompt) => void): Promise<TokenSet>;
|
|
45
|
+
/**
|
|
46
|
+
* What a refresh answered: new tokens; refused (sign in again); or busy, when
|
|
47
|
+
* Moxo couldn't renew just then, as when another renewal of the same sign-in
|
|
48
|
+
* won a race (`temporarily_unavailable`): try again, never sign in again.
|
|
49
|
+
*/
|
|
50
|
+
export type RefreshAnswer = {
|
|
51
|
+
kind: 'renewed';
|
|
52
|
+
set: TokenSet;
|
|
53
|
+
} | {
|
|
54
|
+
kind: 'refused';
|
|
55
|
+
} | {
|
|
56
|
+
kind: 'busy';
|
|
57
|
+
};
|
|
58
|
+
/** A new access token from a refresh token. */
|
|
59
|
+
export declare function refresh(ctx: Pick<Context, 'fetch' | 'now'>, tokenEndpoint: string, client: string, refreshToken: string): Promise<RefreshAnswer>;
|
|
60
|
+
/** Revokes a token where the server offers it; a failure is not an error (the local copy is deleted anyway). */
|
|
61
|
+
export declare function revoke(ctx: Pick<Context, 'fetch'>, endpoint: string, client: string, token: string, hint: 'access_token' | 'refresh_token'): Promise<void>;
|
|
62
|
+
//# sourceMappingURL=oauth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../src/oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAG5C,sEAAsE;AACtE,eAAO,MAAM,iBAAiB,aAAa,CAAC;AAI5C,MAAM,WAAW,cAAc;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6BAA6B,CAAC,EAAE,MAAM,CAAC;IACvC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,MAAM,WAAW,QAAQ;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,MAAM,CAE1D;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAA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|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser sign-in for a terminal: the OAuth 2.0 device authorization grant
|
|
3
|
+
* (RFC 8628), found through the server's authorization server metadata
|
|
4
|
+
* (RFC 8414), renewed with its refresh token and revoked on logout (RFC 7009).
|
|
5
|
+
*
|
|
6
|
+
* The CLI is a public client: it has no secret. It shows a short code and an
|
|
7
|
+
* address; the person signs in to Moxo in the browser, chooses the
|
|
8
|
+
* organization and approves the CLI; the CLI then receives a short-lived
|
|
9
|
+
* token for that one organization.
|
|
10
|
+
*/
|
|
11
|
+
import { CliError, EXIT } from './errors.js';
|
|
12
|
+
/** The CLI's client id, unless MOXO_OAUTH_CLIENT_ID names another. */
|
|
13
|
+
export const DEFAULT_CLIENT_ID = 'moxo-cli';
|
|
14
|
+
const DEVICE_CODE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
|
|
15
|
+
export function clientId(ctx) {
|
|
16
|
+
return ctx.env.MOXO_OAUTH_CLIENT_ID || DEFAULT_CLIENT_ID;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Holds a sign-in description to the host it was read from: the issuer is
|
|
20
|
+
* that host (RFC 8414 §3.3), and every endpoint the CLI sends a code or a
|
|
21
|
+
* token to is on it. Anything else is refused before a code is asked for.
|
|
22
|
+
*/
|
|
23
|
+
export function checkMetadata(metadata, host) {
|
|
24
|
+
const origin = new URL(host).origin;
|
|
25
|
+
if (metadata.issuer !== undefined && metadata.issuer.replace(/\/+$/, '') !== origin) {
|
|
26
|
+
throw new CliError(`${host} described its sign-in as ${metadata.issuer}'s, another site. Nothing was sent. Sign in with a personal access token instead: moxo login --token.`, EXIT.SIGN_IN);
|
|
27
|
+
}
|
|
28
|
+
for (const endpoint of [metadata.device_authorization_endpoint, metadata.token_endpoint, metadata.revocation_endpoint]) {
|
|
29
|
+
if (endpoint === undefined)
|
|
30
|
+
continue;
|
|
31
|
+
let at;
|
|
32
|
+
try {
|
|
33
|
+
at = new URL(endpoint).origin;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
at = endpoint;
|
|
37
|
+
}
|
|
38
|
+
if (at !== origin) {
|
|
39
|
+
throw new CliError(`${host} named a sign-in address on another site (${at}). Nothing was sent. Sign in with a personal access token instead: moxo login --token.`, EXIT.SIGN_IN);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** The server's sign-in description, or undefined when it publishes none. */
|
|
44
|
+
export async function discover(ctx, host) {
|
|
45
|
+
let res;
|
|
46
|
+
try {
|
|
47
|
+
res = await ctx.fetch(`${host}/.well-known/oauth-authorization-server`, { headers: { accept: 'application/json' } });
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new CliError(`Couldn't reach ${host}. Check the address and your connection.`);
|
|
51
|
+
}
|
|
52
|
+
if (!res.ok)
|
|
53
|
+
return undefined;
|
|
54
|
+
try {
|
|
55
|
+
return (await res.json());
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async function postForm(ctx, url, form) {
|
|
62
|
+
let res;
|
|
63
|
+
try {
|
|
64
|
+
res = await ctx.fetch(url, {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
67
|
+
body: new URLSearchParams(form).toString(),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
throw new CliError(`Couldn't reach ${new URL(url).origin}. Check your connection.`);
|
|
72
|
+
}
|
|
73
|
+
let body = {};
|
|
74
|
+
try {
|
|
75
|
+
body = (await res.json());
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// An answer with no JSON is read by its status alone.
|
|
79
|
+
}
|
|
80
|
+
return { status: res.status, body };
|
|
81
|
+
}
|
|
82
|
+
function tokenSetOf(body, now) {
|
|
83
|
+
if (typeof body.access_token !== 'string' || body.access_token.length === 0) {
|
|
84
|
+
throw new CliError('Moxo answered the sign-in without a token. Try again.', EXIT.SIGN_IN);
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
accessToken: body.access_token,
|
|
88
|
+
...(typeof body.refresh_token === 'string' ? { refreshToken: body.refresh_token } : {}),
|
|
89
|
+
...(typeof body.expires_in === 'number' ? { expiresAt: now + body.expires_in * 1000 } : {}),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Runs the device grant: asks for a code, tells the person where to enter it
|
|
94
|
+
* (`show`), and waits for the approval. Answers the token, or throws a
|
|
95
|
+
* sign-in error saying what happened.
|
|
96
|
+
*/
|
|
97
|
+
export async function deviceSignIn(ctx, metadata, show) {
|
|
98
|
+
if (!metadata.device_authorization_endpoint || !metadata.token_endpoint) {
|
|
99
|
+
throw new CliError('This Moxo server does not offer browser sign-in yet. Sign in with a personal access token instead: moxo login --token (it reads the token from standard input).', EXIT.SIGN_IN);
|
|
100
|
+
}
|
|
101
|
+
const client = clientId(ctx);
|
|
102
|
+
const start = await postForm(ctx, metadata.device_authorization_endpoint, { client_id: client });
|
|
103
|
+
const b = start.body;
|
|
104
|
+
if (start.status !== 200 || typeof b.device_code !== 'string' || typeof b.user_code !== 'string' || typeof b.verification_uri !== 'string') {
|
|
105
|
+
throw new CliError(`Moxo refused to start the sign-in${typeof b.error === 'string' ? ` (${b.error})` : ''}. Try again, or sign in with a personal access token: moxo login --token.`, EXIT.SIGN_IN);
|
|
106
|
+
}
|
|
107
|
+
show({
|
|
108
|
+
userCode: b.user_code,
|
|
109
|
+
verificationUri: b.verification_uri,
|
|
110
|
+
...(typeof b.verification_uri_complete === 'string' ? { verificationUriComplete: b.verification_uri_complete } : {}),
|
|
111
|
+
});
|
|
112
|
+
let interval = (typeof b.interval === 'number' && b.interval > 0 ? b.interval : 5) * 1000;
|
|
113
|
+
const expiresAt = ctx.now() + (typeof b.expires_in === 'number' ? b.expires_in : 900) * 1000;
|
|
114
|
+
while (ctx.now() < expiresAt) {
|
|
115
|
+
await ctx.sleep(interval);
|
|
116
|
+
const poll = await postForm(ctx, metadata.token_endpoint, { grant_type: DEVICE_CODE_GRANT, device_code: b.device_code, client_id: client });
|
|
117
|
+
if (poll.status === 200)
|
|
118
|
+
return tokenSetOf(poll.body, ctx.now());
|
|
119
|
+
switch (poll.body.error) {
|
|
120
|
+
case 'authorization_pending':
|
|
121
|
+
continue;
|
|
122
|
+
case 'slow_down':
|
|
123
|
+
// RFC 8628 §3.5: add 5 seconds to the interval for this and every later poll.
|
|
124
|
+
interval += 5000;
|
|
125
|
+
continue;
|
|
126
|
+
case 'access_denied':
|
|
127
|
+
throw new CliError('The sign-in was declined in the browser. Nothing was saved.', EXIT.SIGN_IN);
|
|
128
|
+
case 'expired_token':
|
|
129
|
+
throw new CliError('The code expired before it was approved. Run moxo login again.', EXIT.SIGN_IN);
|
|
130
|
+
default:
|
|
131
|
+
throw new CliError(`Moxo refused the sign-in${typeof poll.body.error === 'string' ? ` (${poll.body.error})` : ''}. Run moxo login again.`, EXIT.SIGN_IN);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
throw new CliError('The code expired before it was approved. Run moxo login again.', EXIT.SIGN_IN);
|
|
135
|
+
}
|
|
136
|
+
/** A new access token from a refresh token. */
|
|
137
|
+
export async function refresh(ctx, tokenEndpoint, client, refreshToken) {
|
|
138
|
+
const r = await postForm(ctx, tokenEndpoint, { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: client });
|
|
139
|
+
if (r.status === 200) {
|
|
140
|
+
const set = tokenSetOf(r.body, ctx.now());
|
|
141
|
+
return { kind: 'renewed', set: { ...set, refreshToken: set.refreshToken ?? refreshToken } };
|
|
142
|
+
}
|
|
143
|
+
if (r.body.error === 'temporarily_unavailable' || r.status === 503)
|
|
144
|
+
return { kind: 'busy' };
|
|
145
|
+
return { kind: 'refused' };
|
|
146
|
+
}
|
|
147
|
+
/** Revokes a token where the server offers it; a failure is not an error (the local copy is deleted anyway). */
|
|
148
|
+
export async function revoke(ctx, endpoint, client, token, hint) {
|
|
149
|
+
try {
|
|
150
|
+
await postForm(ctx, endpoint, { token, token_type_hint: hint, client_id: client });
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
// Revoking is a courtesy; the token stops working when it expires.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
//# sourceMappingURL=oauth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth.js","sourceRoot":"","sources":["../src/oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAE7C,sEAAsE;AACtE,MAAM,CAAC,MAAM,iBAAiB,GAAG,UAAU,CAAC;AAE5C,MAAM,iBAAiB,GAAG,8CAA8C,CAAC;AAezE,MAAM,UAAU,QAAQ,CAAC,GAAyB;IAChD,OAAO,GAAG,CAAC,GAAG,CAAC,oBAAoB,IAAI,iBAAiB,CAAC;AAC3D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,QAAwB,EAAE,IAAY;IAClE,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC;IACpC,IAAI,QAAQ,CAAC,MAAM,KAAK,SAAS,IAAI,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,KAAK,MAAM,EAAE,CAAC;QACpF,MAAM,IAAI,QAAQ,CAAC,GAAG,IAAI,6BAA6B,QAAQ,CAAC,MAAM,uGAAuG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC/L,CAAC;IACD,KAAK,MAAM,QAAQ,IAAI,CAAC,QAAQ,CAAC,6BAA6B,EAAE,QAAQ,CAAC,cAAc,EAAE,QAAQ,CAAC,mBAAmB,CAAC,EAAE,CAAC;QACvH,IAAI,QAAQ,KAAK,SAAS;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they did not ask for --json: a list as a table of
|
|
3
|
+
* its most telling columns, anything else as indented JSON. With --json, the
|
|
4
|
+
* answer's `data` (and `pagination`, when the list has one) as Moxo sent it.
|
|
5
|
+
*/
|
|
6
|
+
import type { Output } from './context.js';
|
|
7
|
+
export declare function table(rows: ReadonlyArray<Record<string, unknown>>, columns?: readonly string[]): string;
|
|
8
|
+
/** Prints a successful JSON answer. */
|
|
9
|
+
export declare function printAnswer(out: Output, json: unknown, asJson: boolean): void;
|
|
10
|
+
//# sourceMappingURL=render.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAU3C,wBAAgB,KAAK,CAAC,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAQvG;AAED,uCAAuC;AACvC,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI,CAkB7E"}
|
package/dist/render.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a person reads when they did not ask for --json: a list as a table of
|
|
3
|
+
* its most telling columns, anything else as indented JSON. With --json, the
|
|
4
|
+
* answer's `data` (and `pagination`, when the list has one) as Moxo sent it.
|
|
5
|
+
*/
|
|
6
|
+
const PREFERRED_COLUMNS = ['id', 'name', 'title', 'email', 'status', 'type', 'kind', 'version', 'dueAt', 'updatedAt'];
|
|
7
|
+
function cell(v) {
|
|
8
|
+
if (v === null || v === undefined)
|
|
9
|
+
return '';
|
|
10
|
+
if (typeof v === 'object')
|
|
11
|
+
return JSON.stringify(v);
|
|
12
|
+
return String(v).replace(/\s+/g, ' ');
|
|
13
|
+
}
|
|
14
|
+
export function table(rows, columns) {
|
|
15
|
+
if (rows.length === 0)
|
|
16
|
+
return '(none)';
|
|
17
|
+
const cols = columns ?? PREFERRED_COLUMNS.filter((c) => rows.some((r) => r[c] !== undefined && r[c] !== null && typeof r[c] !== 'object')).slice(0, 5);
|
|
18
|
+
if (cols.length === 0)
|
|
19
|
+
return rows.map((r) => JSON.stringify(r)).join('\n');
|
|
20
|
+
const cells = rows.map((r) => cols.map((c) => cell(r[c]).slice(0, 60)));
|
|
21
|
+
const widths = cols.map((c, i) => Math.max(c.length, ...cells.map((r) => r[i].length)));
|
|
22
|
+
const line = (vals) => vals.map((v, i) => (i === vals.length - 1 ? v : v.padEnd(widths[i]))).join(' ').trimEnd();
|
|
23
|
+
return [line(cols.map((c) => c.toUpperCase())), ...cells.map(line)].join('\n');
|
|
24
|
+
}
|
|
25
|
+
/** Prints a successful JSON answer. */
|
|
26
|
+
export function printAnswer(out, json, asJson) {
|
|
27
|
+
const body = json;
|
|
28
|
+
const data = body && typeof body === 'object' && 'data' in body ? body.data : json;
|
|
29
|
+
if (asJson) {
|
|
30
|
+
out.json(body && typeof body === 'object' && 'pagination' in body ? { data, pagination: body.pagination } : data);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (Array.isArray(data) && data.every((r) => r && typeof r === 'object')) {
|
|
34
|
+
out.out(table(data));
|
|
35
|
+
const p = body?.pagination;
|
|
36
|
+
if (p?.hasMore)
|
|
37
|
+
out.err(`More: ${p.nextCursor ? `--cursor ${p.nextCursor}` : 'use --offset and --limit'}${typeof p.total === 'number' ? ` (${p.total} in all)` : ''}.`);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (data === undefined) {
|
|
41
|
+
out.out('Done.');
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
out.out(typeof data === 'string' ? data : JSON.stringify(data, null, 2));
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=render.js.map
|
|
@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**
|
|
2
|
+
* Who this run acts as: the token, the host, the profile, and a client that
|
|
3
|
+
* calls Moxo's /v1 API with them.
|
|
4
|
+
*
|
|
5
|
+
* Every call takes its organization from the token. The CLI sends no
|
|
6
|
+
* organization header, so a profile reaches the one organization its token
|
|
7
|
+
* was made for, and nothing a command does can move it to another.
|
|
8
|
+
*/
|
|
9
|
+
import type { Context, Output } from './context.js';
|
|
10
|
+
import { type Profile } from './config.js';
|
|
11
|
+
import { CliError } from './errors.js';
|
|
12
|
+
export type TokenSource = 'MOXO_TOKEN' | 'keychain' | 'file';
|
|
13
|
+
export interface Session {
|
|
14
|
+
host: string;
|
|
15
|
+
profile: string;
|
|
16
|
+
/** The saved profile, when the token came from one. */
|
|
17
|
+
saved?: Profile;
|
|
18
|
+
token: string;
|
|
19
|
+
source: TokenSource;
|
|
20
|
+
/**
|
|
21
|
+
* For a browser sign-in: a new access token when Moxo says the one sent
|
|
22
|
+
* (`expired`) has expired. Uses one another moxo command already saved, or
|
|
23
|
+
* renews with the refresh token.
|
|
24
|
+
*/
|
|
25
|
+
renew?: (expired: string) => Promise<string>;
|
|
26
|
+
}
|
|
27
|
+
export interface GlobalOptions {
|
|
28
|
+
profile?: string;
|
|
29
|
+
host?: string;
|
|
30
|
+
region?: string;
|
|
31
|
+
json: boolean;
|
|
32
|
+
yes: boolean;
|
|
33
|
+
}
|
|
34
|
+
export declare function resolveSession(ctx: Context, out: Output, globals: GlobalOptions): Promise<Session>;
|
|
35
|
+
export interface RequestOptions {
|
|
36
|
+
query?: Record<string, string | string[]>;
|
|
37
|
+
/** A JSON body. */
|
|
38
|
+
body?: unknown;
|
|
39
|
+
/** A multipart body (a file upload); fetch sets its content type. */
|
|
40
|
+
form?: FormData;
|
|
41
|
+
headers?: Record<string, string>;
|
|
42
|
+
accept?: string;
|
|
43
|
+
}
|
|
44
|
+
export interface ApiResponse {
|
|
45
|
+
status: number;
|
|
46
|
+
headers: Headers;
|
|
47
|
+
/** The parsed body when it is JSON. */
|
|
48
|
+
json?: unknown;
|
|
49
|
+
/** The body's bytes when it is not JSON (a file). */
|
|
50
|
+
bytes?: Buffer;
|
|
51
|
+
}
|
|
52
|
+
/** What Moxo said when it refused a call. */
|
|
53
|
+
export interface Refusal {
|
|
54
|
+
status: number;
|
|
55
|
+
code?: string;
|
|
56
|
+
message: string;
|
|
57
|
+
error?: Record<string, unknown>;
|
|
58
|
+
data?: unknown;
|
|
59
|
+
/** The answer's other top-level keys, e.g. a VERSION_CONFLICT's `changedSince`. */
|
|
60
|
+
extra?: Record<string, unknown>;
|
|
61
|
+
}
|
|
62
|
+
export declare function refusalOf(res: ApiResponse): Refusal;
|
|
63
|
+
export declare function refusalError(r: Refusal): CliError;
|
|
64
|
+
export declare class ApiClient {
|
|
65
|
+
private readonly ctx;
|
|
66
|
+
readonly session: Session;
|
|
67
|
+
/** The access token calls carry; renewed once if Moxo says it has expired. */
|
|
68
|
+
private token;
|
|
69
|
+
constructor(ctx: Context, session: Session);
|
|
70
|
+
/** The address of a path on the sign-in's host. Never another host: the token goes with it. */
|
|
71
|
+
url(path: string, query?: RequestOptions['query']): string;
|
|
72
|
+
/**
|
|
73
|
+
* Calls Moxo. Answers every status; `call` throws on a refusal. Redirects
|
|
74
|
+
* are followed by hand: on the sign-in's host with the token, elsewhere (a
|
|
75
|
+
* signed download address) a GET without it, and a write never. A browser
|
|
76
|
+
* sign-in's token that Moxo answers `TOKEN_EXPIRED` is renewed once and the
|
|
77
|
+
* call sent again: Moxo did nothing with the first one.
|
|
78
|
+
*/
|
|
79
|
+
request(method: string, path: string, opts?: RequestOptions): Promise<ApiResponse>;
|
|
80
|
+
private send;
|
|
81
|
+
/** Calls Moxo and answers the response, or throws Moxo's refusal as a CliError. */
|
|
82
|
+
call(method: string, path: string, opts?: RequestOptions): Promise<ApiResponse>;
|
|
83
|
+
/** `data` of a successful JSON answer. */
|
|
84
|
+
data<T = unknown>(method: string, path: string, opts?: RequestOptions): Promise<T>;
|
|
85
|
+
}
|
|
86
|
+
/** The organization a write will change, named before it runs (the plan's "changing organization X" line). */
|
|
87
|
+
export declare function organizationName(client: ApiClient): Promise<string | undefined>;
|
|
88
|
+
export declare function announceWrite(client: ApiClient, out: Output): Promise<void>;
|
|
89
|
+
/** Saves what a sign-in learned about the profile. */
|
|
90
|
+
export declare function saveProfile(ctx: Context, name: string, profile: Profile, makeDefault: boolean): void;
|
|
91
|
+
//# sourceMappingURL=session.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAoE,KAAK,OAAO,EAAE,MAAM,aAAa,CAAC;AAE7G,OAAO,EAAE,QAAQ,EAAwB,MAAM,aAAa,CAAC;AAI7D,MAAM,MAAM,WAAW,GAAG,YAAY,GAAG,UAAU,GAAG,MAAM,CAAC;AAE7D,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,uDAAuD;IACvD,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,WAAW,CAAC;IACpB;;;;OAIG;IACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CAC9C;AAED,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;IACd,GAAG,EAAE,OAAO,CAAC;CACd;AAiBD,wBAAsB,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC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,CAAC,EAAE,cAAc,CAAC,OAAO,CAAC,GAAG,MAAM;IAO1D;;;;;;OAMG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,cAAmB,GAAG,OAAO,CAAC,WAAW,CAAC;YAO9E,IAAI;IAiDlB,mFAAmF;IAC7E,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,cAAmB,GAAG,OAAO,CAAC,WAAW,CAAC;IAMzF,0CAA0C;IACpC,IAAI,CAAC,CAAC,GAAG,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,cAAmB,GAAG,OAAO,CAAC,CAAC,CAAC;CAI7F;AAED,8GAA8G;AAC9G,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CASrF;AAED,wBAAsB,aAAa,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAIjF;AAED,sDAAsD;AACtD,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,GAAG,IAAI,CAKpG"}
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who this run acts as: the token, the host, the profile, and a client that
|
|
3
|
+
* calls Moxo's /v1 API with them.
|
|
4
|
+
*
|
|
5
|
+
* Every call takes its organization from the token. The CLI sends no
|
|
6
|
+
* organization header, so a profile reaches the one organization its token
|
|
7
|
+
* was made for, and nothing a command does can move it to another.
|
|
8
|
+
*/
|
|
9
|
+
import { DEFAULT_HOST, loadConfig, profileName, requestedHost, saveConfig } from './config.js';
|
|
10
|
+
import { credentialStore } from './credentials.js';
|
|
11
|
+
import { CliError, EXIT, exitForRefusal } from './errors.js';
|
|
12
|
+
import { clientId, refresh } from './oauth.js';
|
|
13
|
+
import { VERSION } from './version.js';
|
|
14
|
+
/** This machine: the one place a call may go over plain http. */
|
|
15
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
16
|
+
/** How many redirects one call follows. */
|
|
17
|
+
const MAX_REDIRECTS = 3;
|
|
18
|
+
const NOT_SIGNED_IN = 'You are not signed in. Run moxo login, or set MOXO_TOKEN to a personal access token (in CI).';
|
|
19
|
+
/** Renews an OAuth token that expires within this long. */
|
|
20
|
+
const RENEW_WITHIN_MS = 60_000;
|
|
21
|
+
/** A renewal Moxo answers busy is tried this many times, this far apart. */
|
|
22
|
+
const RENEW_ATTEMPTS = 3;
|
|
23
|
+
const RENEW_RETRY_MS = 1_000;
|
|
24
|
+
export async function resolveSession(ctx, out, globals) {
|
|
25
|
+
const config = loadConfig(ctx);
|
|
26
|
+
const profile = profileName(ctx, globals.profile, config);
|
|
27
|
+
const saved = config.profiles[profile];
|
|
28
|
+
const named = requestedHost(globals, ctx.env);
|
|
29
|
+
const envToken = ctx.env.MOXO_TOKEN?.trim();
|
|
30
|
+
if (envToken) {
|
|
31
|
+
out.hide(envToken);
|
|
32
|
+
return { host: named ?? saved?.host ?? DEFAULT_HOST, profile, token: envToken, source: 'MOXO_TOKEN' };
|
|
33
|
+
}
|
|
34
|
+
if (!saved)
|
|
35
|
+
throw new CliError(globals.profile ? `There is no profile "${profile}". Sign in to it with moxo login --profile ${profile}.` : NOT_SIGNED_IN, EXIT.SIGN_IN);
|
|
36
|
+
// A saved token goes only to the host it was made for: a different --host, --region or MOXO_HOST is refused, never followed.
|
|
37
|
+
if (named && named !== saved.host) {
|
|
38
|
+
throw new CliError(`Profile ${profile} is signed in to ${saved.host}, not ${named}. To use ${named}, sign in to it under another profile: moxo login --host ${named} --profile <name>.`, EXIT.SIGN_IN);
|
|
39
|
+
}
|
|
40
|
+
const store = credentialStore(ctx, saved.store);
|
|
41
|
+
let cred = await store.get(profile);
|
|
42
|
+
if (!cred)
|
|
43
|
+
throw new CliError(NOT_SIGNED_IN, EXIT.SIGN_IN);
|
|
44
|
+
out.hide(cred.token);
|
|
45
|
+
out.hide(cred.refreshToken);
|
|
46
|
+
if (cred.expiresAt !== undefined && cred.expiresAt - ctx.now() < RENEW_WITHIN_MS) {
|
|
47
|
+
cred = await renew(ctx, out, profile, saved, cred);
|
|
48
|
+
}
|
|
49
|
+
const renewable = cred.refreshToken !== undefined;
|
|
50
|
+
const renewOnExpiry = async (expired) => {
|
|
51
|
+
const stored = await store.get(profile);
|
|
52
|
+
if (stored && stored.token !== expired) {
|
|
53
|
+
// Another moxo command renewed this sign-in first: its token is the one to use.
|
|
54
|
+
out.hide(stored.token);
|
|
55
|
+
out.hide(stored.refreshToken);
|
|
56
|
+
return stored.token;
|
|
57
|
+
}
|
|
58
|
+
return (await renew(ctx, out, profile, saved, stored ?? cred)).token;
|
|
59
|
+
};
|
|
60
|
+
return { host: saved.host, profile, saved, token: cred.token, source: store.kind, ...(renewable ? { renew: renewOnExpiry } : {}) };
|
|
61
|
+
}
|
|
62
|
+
async function renew(ctx, out, profile, saved, cred) {
|
|
63
|
+
if (!cred.refreshToken || !saved.tokenEndpoint || new URL(saved.tokenEndpoint).origin !== new URL(saved.host).origin) {
|
|
64
|
+
throw new CliError('Your sign-in has expired. Run moxo login again.', EXIT.SIGN_IN);
|
|
65
|
+
}
|
|
66
|
+
const store = credentialStore(ctx, saved.store);
|
|
67
|
+
let current = cred;
|
|
68
|
+
for (let attempt = 1; attempt <= RENEW_ATTEMPTS; attempt++) {
|
|
69
|
+
const answer = await refresh(ctx, saved.tokenEndpoint, saved.clientId ?? clientId(ctx), current.refreshToken);
|
|
70
|
+
if (answer.kind === 'refused')
|
|
71
|
+
throw new CliError('Your sign-in has expired or was revoked. Run moxo login again.', EXIT.SIGN_IN);
|
|
72
|
+
if (answer.kind === 'renewed') {
|
|
73
|
+
const set = answer.set;
|
|
74
|
+
// Each refresh token works once: keep the new one the answer carries (refresh() keeps the old one only if none came).
|
|
75
|
+
const next = { token: set.accessToken, refreshToken: set.refreshToken, ...(set.expiresAt ? { expiresAt: set.expiresAt } : {}) };
|
|
76
|
+
out.hide(next.token);
|
|
77
|
+
out.hide(next.refreshToken);
|
|
78
|
+
await store.set(profile, next);
|
|
79
|
+
return next;
|
|
80
|
+
}
|
|
81
|
+
// Busy: most often another moxo command renewing this sign-in at the same moment won. It saves
|
|
82
|
+
// the new tokens, so use those; otherwise try again (Moxo takes the same refresh token again briefly).
|
|
83
|
+
await ctx.sleep(RENEW_RETRY_MS);
|
|
84
|
+
const stored = await store.get(profile);
|
|
85
|
+
if (stored?.refreshToken && stored.refreshToken !== current.refreshToken) {
|
|
86
|
+
out.hide(stored.token);
|
|
87
|
+
out.hide(stored.refreshToken);
|
|
88
|
+
if (stored.expiresAt === undefined || stored.expiresAt - ctx.now() >= RENEW_WITHIN_MS)
|
|
89
|
+
return stored;
|
|
90
|
+
current = stored;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
throw new CliError("Moxo couldn't renew your sign-in just now. Try again in a moment; you don't need to sign in again.");
|
|
94
|
+
}
|
|
95
|
+
export function refusalOf(res) {
|
|
96
|
+
const body = (res.json ?? {});
|
|
97
|
+
const error = body.error && typeof body.error === 'object' ? body.error : undefined;
|
|
98
|
+
const code = typeof error?.code === 'string' ? error.code : undefined;
|
|
99
|
+
const message = typeof error?.message === 'string' ? error.message : `Moxo answered ${res.status}.`;
|
|
100
|
+
// What a refusal says beside its error (a VERSION_CONFLICT's changedSince, draftRevision and fileRevision).
|
|
101
|
+
const { success: _success, error: _error, data, ...extra } = body;
|
|
102
|
+
return { status: res.status, code, message, error, data, ...(Object.keys(extra).length > 0 ? { extra } : {}) };
|
|
103
|
+
}
|
|
104
|
+
export function refusalError(r) {
|
|
105
|
+
const exit = exitForRefusal(r.status, r.code);
|
|
106
|
+
const message = exit === EXIT.SIGN_IN ? `${r.message} Sign in again with moxo login, or check MOXO_TOKEN.` : r.message;
|
|
107
|
+
return new CliError(message, exit, r.code, { status: r.status, ...(r.error ? { error: r.error } : {}), ...(r.data !== undefined ? { data: r.data } : {}), ...r.extra });
|
|
108
|
+
}
|
|
109
|
+
export class ApiClient {
|
|
110
|
+
ctx;
|
|
111
|
+
session;
|
|
112
|
+
/** The access token calls carry; renewed once if Moxo says it has expired. */
|
|
113
|
+
token;
|
|
114
|
+
constructor(ctx, session) {
|
|
115
|
+
this.ctx = ctx;
|
|
116
|
+
this.session = session;
|
|
117
|
+
this.token = session.token;
|
|
118
|
+
}
|
|
119
|
+
/** The address of a path on the sign-in's host. Never another host: the token goes with it. */
|
|
120
|
+
url(path, query) {
|
|
121
|
+
const u = new URL(path.startsWith('/') ? path : `/${path}`, this.session.host);
|
|
122
|
+
if (u.origin !== new URL(this.session.host).origin)
|
|
123
|
+
throw new CliError(`Won't send your token to ${u.origin}: Moxo calls go to ${this.session.host} only.`);
|
|
124
|
+
for (const [k, v] of Object.entries(query ?? {}))
|
|
125
|
+
for (const one of Array.isArray(v) ? v : [v])
|
|
126
|
+
u.searchParams.append(k, one);
|
|
127
|
+
return u.toString();
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Calls Moxo. Answers every status; `call` throws on a refusal. Redirects
|
|
131
|
+
* are followed by hand: on the sign-in's host with the token, elsewhere (a
|
|
132
|
+
* signed download address) a GET without it, and a write never. A browser
|
|
133
|
+
* sign-in's token that Moxo answers `TOKEN_EXPIRED` is renewed once and the
|
|
134
|
+
* call sent again: Moxo did nothing with the first one.
|
|
135
|
+
*/
|
|
136
|
+
async request(method, path, opts = {}) {
|
|
137
|
+
const res = await this.send(method, path, opts);
|
|
138
|
+
if (res.status !== 401 || !this.session.renew || refusalOf(res).code !== 'TOKEN_EXPIRED')
|
|
139
|
+
return res;
|
|
140
|
+
this.token = await this.session.renew(this.token);
|
|
141
|
+
return this.send(method, path, opts);
|
|
142
|
+
}
|
|
143
|
+
async send(method, path, opts) {
|
|
144
|
+
const headers = {
|
|
145
|
+
authorization: `Bearer ${this.token}`,
|
|
146
|
+
accept: opts.accept ?? 'application/json',
|
|
147
|
+
'user-agent': `moxo-cli/${VERSION} node/${process.versions.node}`,
|
|
148
|
+
...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
149
|
+
...opts.headers,
|
|
150
|
+
};
|
|
151
|
+
const own = new URL(this.session.host).origin;
|
|
152
|
+
let target = this.url(path, opts.query);
|
|
153
|
+
let res;
|
|
154
|
+
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
155
|
+
const away = new URL(target).origin !== own;
|
|
156
|
+
try {
|
|
157
|
+
res = await this.ctx.fetch(target, {
|
|
158
|
+
method,
|
|
159
|
+
headers: away ? { accept: headers.accept, 'user-agent': headers['user-agent'] } : headers,
|
|
160
|
+
redirect: 'manual',
|
|
161
|
+
...(opts.body !== undefined && !away ? { body: JSON.stringify(opts.body) } : {}),
|
|
162
|
+
...(opts.form !== undefined && !away ? { body: opts.form } : {}),
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
throw new CliError(`Couldn't reach ${away ? new URL(target).origin : this.session.host}. Check your connection, or the address with moxo whoami.`);
|
|
167
|
+
}
|
|
168
|
+
const location = res.status >= 300 && res.status < 400 ? res.headers.get('location') : null;
|
|
169
|
+
if (!location)
|
|
170
|
+
break;
|
|
171
|
+
const next = new URL(location, target);
|
|
172
|
+
if (next.origin !== own && method !== 'GET')
|
|
173
|
+
throw new CliError(`Moxo sent this ${method} on to another site (${next.origin}). Nothing more was sent.`);
|
|
174
|
+
if (next.origin !== own && next.protocol !== 'https:' && !LOOPBACK_HOSTS.has(next.hostname)) {
|
|
175
|
+
throw new CliError(`Moxo sent this call on to ${next.origin}, which is not https. Nothing more was sent.`);
|
|
176
|
+
}
|
|
177
|
+
target = next.toString();
|
|
178
|
+
if (hop === MAX_REDIRECTS)
|
|
179
|
+
throw new CliError('Moxo sent this call on too many times.');
|
|
180
|
+
}
|
|
181
|
+
res = res;
|
|
182
|
+
const type = res.headers.get('content-type') ?? '';
|
|
183
|
+
if (type.includes('json')) {
|
|
184
|
+
const text = await res.text();
|
|
185
|
+
let json;
|
|
186
|
+
try {
|
|
187
|
+
json = text.length > 0 ? JSON.parse(text) : undefined;
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
json = undefined;
|
|
191
|
+
}
|
|
192
|
+
return { status: res.status, headers: res.headers, json };
|
|
193
|
+
}
|
|
194
|
+
return { status: res.status, headers: res.headers, bytes: Buffer.from(await res.arrayBuffer()) };
|
|
195
|
+
}
|
|
196
|
+
/** Calls Moxo and answers the response, or throws Moxo's refusal as a CliError. */
|
|
197
|
+
async call(method, path, opts = {}) {
|
|
198
|
+
const res = await this.request(method, path, opts);
|
|
199
|
+
if (res.status >= 400)
|
|
200
|
+
throw refusalError(refusalOf(res));
|
|
201
|
+
return res;
|
|
202
|
+
}
|
|
203
|
+
/** `data` of a successful JSON answer. */
|
|
204
|
+
async data(method, path, opts = {}) {
|
|
205
|
+
const res = await this.call(method, path, opts);
|
|
206
|
+
return (res.json?.data ?? res.json);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** The organization a write will change, named before it runs (the plan's "changing organization X" line). */
|
|
210
|
+
export async function organizationName(client) {
|
|
211
|
+
const saved = client.session.saved?.organization?.name;
|
|
212
|
+
if (saved)
|
|
213
|
+
return saved;
|
|
214
|
+
try {
|
|
215
|
+
const org = await client.data('GET', '/v1/organization');
|
|
216
|
+
return org?.name;
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
export async function announceWrite(client, out) {
|
|
223
|
+
const name = await organizationName(client);
|
|
224
|
+
const who = client.session.source === 'MOXO_TOKEN' ? 'MOXO_TOKEN' : `profile ${client.session.profile}`;
|
|
225
|
+
out.err(`Changing ${name ? `organization ${name}` : 'your organization'} (${who}).`);
|
|
226
|
+
}
|
|
227
|
+
/** Saves what a sign-in learned about the profile. */
|
|
228
|
+
export function saveProfile(ctx, name, profile, makeDefault) {
|
|
229
|
+
const config = loadConfig(ctx);
|
|
230
|
+
config.profiles[name] = profile;
|
|
231
|
+
if (makeDefault || !config.defaultProfile)
|
|
232
|
+
config.defaultProfile = name;
|
|
233
|
+
saveConfig(ctx, config);
|
|
234
|
+
}
|
|
235
|
+
//# sourceMappingURL=session.js.map
|