socialapi-cli 0.0.0-stage → 1.17.7
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/LICENSE +21 -0
- package/README.md +279 -2
- package/SKILL.md +99 -0
- package/bin/socialapi.mjs +4 -0
- package/generated/commands.json +6891 -0
- package/package.json +41 -4
- package/src/auth/api.mjs +103 -0
- package/src/auth/config.mjs +62 -0
- package/src/auth/login.mjs +312 -0
- package/src/auth/logout.mjs +41 -0
- package/src/auth/whoami.mjs +13 -0
- package/src/builtins/commands.mjs +36 -0
- package/src/builtins/completion.mjs +106 -0
- package/src/builtins/help.mjs +17 -0
- package/src/builtins/index.mjs +18 -0
- package/src/builtins/skill.mjs +12 -0
- package/src/builtins/version.mjs +12 -0
- package/src/credentials.mjs +22 -0
- package/src/errors.mjs +46 -0
- package/src/flags.mjs +19 -0
- package/src/help.mjs +83 -0
- package/src/http.mjs +72 -0
- package/src/main.mjs +87 -0
- package/src/manifest.mjs +6 -0
- package/src/naming.mjs +15 -0
- package/src/operation.mjs +346 -0
- package/src/output.mjs +19 -0
- package/src/suggest.mjs +40 -0
- package/src/version.mjs +4 -0
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "socialapi-cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.17.7",
|
|
4
|
+
"description": "Command-line client for the SocialAPI REST API, generated from its OpenAPI spec.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"socialapi": "bin/socialapi.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"generated",
|
|
13
|
+
"SKILL.md"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/SocialAPI-AI/socialapi-cli.git"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/SocialAPI-AI/socialapi-cli#readme",
|
|
24
|
+
"keywords": [
|
|
25
|
+
"socialapi",
|
|
26
|
+
"cli",
|
|
27
|
+
"social-media",
|
|
28
|
+
"api"
|
|
29
|
+
],
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"generate": "node scripts/generate.mjs",
|
|
35
|
+
"typecheck": "tsc --noEmit",
|
|
36
|
+
"test": "npm run generate && node scripts/test.mjs",
|
|
37
|
+
"prepack": "npm run generate"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/node": "^20.19.43",
|
|
41
|
+
"typescript": "^7.0.2"
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/auth/api.mjs
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Sign-in calls the API through the manifest by operationId, never by a hard-coded path,
|
|
2
|
+
// and through the single request function of src/http.mjs.
|
|
3
|
+
import { CliError, EXIT, responseError, usageError } from '../errors.mjs';
|
|
4
|
+
import { send } from '../http.mjs';
|
|
5
|
+
|
|
6
|
+
/** The only operations sign-in names. */
|
|
7
|
+
export const SIGN_IN_OPERATIONS = ['createApiKey', 'getCurrentUser', 'revokeApiKey'];
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {{ timeoutSeconds: number, verbose: boolean, stderr: { write(chunk: string): any } }} HttpOptions
|
|
11
|
+
* @typedef {import('../main.mjs').Context} Context
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The generated command of an operation sign-in needs.
|
|
16
|
+
* @param {Context['manifest']} manifest
|
|
17
|
+
* @param {string} operationId
|
|
18
|
+
*/
|
|
19
|
+
export function findOperation(manifest, operationId) {
|
|
20
|
+
const cmd = manifest.commands.find((c) => c.operationId === operationId);
|
|
21
|
+
if (!cmd) throw new CliError('unsupported_api', `This API has no ${operationId} operation, which sign-in needs. Install the latest socialapi-cli, or pass the API key with --api-key or SOCIALAPI_API_KEY.`);
|
|
22
|
+
return cmd;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Calls an operation and returns its JSON response; an API error throws with the API's body.
|
|
27
|
+
* @param {Context['manifest']} manifest
|
|
28
|
+
* @param {string} operationId
|
|
29
|
+
* @param {{ base: string, token: string, args?: string[], body?: any, http: HttpOptions }} request
|
|
30
|
+
*/
|
|
31
|
+
export async function callOperation(manifest, operationId, { base, token, args = [], body, http }) {
|
|
32
|
+
const cmd = findOperation(manifest, operationId);
|
|
33
|
+
const path = cmd.path.replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(args[cmd.args.findIndex((a) => a.name === name)]));
|
|
34
|
+
const response = await send({
|
|
35
|
+
method: cmd.method,
|
|
36
|
+
url: new URL(`${base}${path}`),
|
|
37
|
+
headers: body === undefined ? {} : { 'content-type': 'application/json' },
|
|
38
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
39
|
+
token,
|
|
40
|
+
...http,
|
|
41
|
+
});
|
|
42
|
+
return jsonOf(response);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The JSON body of a successful response.
|
|
47
|
+
* @param {import('../http.mjs').ApiResponse} response
|
|
48
|
+
*/
|
|
49
|
+
export function jsonOf(response) {
|
|
50
|
+
if (response.status >= 400) throw responseError(response);
|
|
51
|
+
try {
|
|
52
|
+
return response.body.length ? JSON.parse(response.body.toString('utf8')) : {};
|
|
53
|
+
} catch {
|
|
54
|
+
throw new CliError('invalid_response', `The server answered ${response.status} with a body that is not JSON. Check the base URL.`, EXIT.apiError);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Deletes a stored key on the API it was created for, using the key itself.
|
|
60
|
+
* A key the API no longer knows (401 or 404) counts as deleted.
|
|
61
|
+
* @param {Context['manifest']} manifest
|
|
62
|
+
* @param {import('./config.mjs').StoredKey} stored
|
|
63
|
+
* @param {HttpOptions} http
|
|
64
|
+
* @returns {Promise<string | null>} null when deleted, otherwise what went wrong
|
|
65
|
+
*/
|
|
66
|
+
export async function deleteStoredKey(manifest, stored, http) {
|
|
67
|
+
try {
|
|
68
|
+
await callOperation(manifest, 'revokeApiKey', { base: stored.base_url.replace(/\/+$/, ''), token: stored.api_key, args: [stored.key_id ?? ''], http });
|
|
69
|
+
return null;
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (!(error instanceof CliError)) throw error;
|
|
72
|
+
if (error.status === 401 || error.status === 404) return null;
|
|
73
|
+
return `${error.code}: ${error.message}`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Reads the flags of a sign-in command. Boolean flags take no value (or =true / =false).
|
|
79
|
+
* @param {string[]} args
|
|
80
|
+
* @param {Record<string, 'boolean' | 'value'>} accepted
|
|
81
|
+
* @param {string} usage
|
|
82
|
+
* @returns {Record<string, string | boolean>}
|
|
83
|
+
*/
|
|
84
|
+
export function parseFlags(args, accepted, usage) {
|
|
85
|
+
/** @type {Record<string, string | boolean>} */
|
|
86
|
+
const flags = {};
|
|
87
|
+
for (let i = 0; i < args.length; i++) {
|
|
88
|
+
const token = args[i];
|
|
89
|
+
if (!token.startsWith('--')) throw usageError(`Unexpected argument "${token}". Usage: socialapi ${usage}`);
|
|
90
|
+
const eq = token.indexOf('=');
|
|
91
|
+
const name = token.slice(2, eq === -1 ? undefined : eq);
|
|
92
|
+
const type = accepted[name];
|
|
93
|
+
if (!type) throw usageError(`Unknown flag --${name}. Usage: socialapi ${usage}`);
|
|
94
|
+
if (type === 'boolean') {
|
|
95
|
+
const value = eq === -1 ? 'true' : token.slice(eq + 1);
|
|
96
|
+
if (value !== 'true' && value !== 'false') throw usageError(`--${name} takes true or false, not "${value}".`);
|
|
97
|
+
flags[name] = value === 'true';
|
|
98
|
+
} else if (eq !== -1) flags[name] = token.slice(eq + 1);
|
|
99
|
+
else if (i + 1 < args.length) flags[name] = args[++i];
|
|
100
|
+
else throw usageError(`--${name} needs a value.`);
|
|
101
|
+
}
|
|
102
|
+
return flags;
|
|
103
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// The config store: one stored API key, in ${XDG_CONFIG_HOME:-~/.config}/socialapi/config.json
|
|
2
|
+
// (%APPDATA%\socialapi\config.json on Windows). The directory is 0700, the file 0600, written atomically.
|
|
3
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {{ base_url: string, api_key: string, key_id: string | null, created_by_login: boolean }} StoredKey
|
|
10
|
+
* @typedef {Record<string, string | undefined>} Env
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** @param {Env} env */
|
|
14
|
+
export function configPath(env, platform = process.platform) {
|
|
15
|
+
if (platform === 'win32') return join(env.APPDATA || join(env.USERPROFILE || homedir(), 'AppData', 'Roaming'), 'socialapi', 'config.json');
|
|
16
|
+
return join(env.XDG_CONFIG_HOME || join(env.HOME || homedir(), '.config'), 'socialapi', 'config.json');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The stored key, or null when there is none (or the file does not hold one).
|
|
21
|
+
* @param {Env} env
|
|
22
|
+
* @returns {StoredKey | null}
|
|
23
|
+
*/
|
|
24
|
+
export function readConfig(env) {
|
|
25
|
+
let stored;
|
|
26
|
+
try {
|
|
27
|
+
stored = JSON.parse(readFileSync(configPath(env), 'utf8'));
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
if (!stored || typeof stored.base_url !== 'string' || typeof stored.api_key !== 'string' || !stored.api_key) return null;
|
|
32
|
+
return { base_url: stored.base_url, api_key: stored.api_key, key_id: stored.key_id ?? null, created_by_login: stored.created_by_login === true };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Replaces the stored key: writes a temporary file with mode 0600, then renames it over config.json.
|
|
37
|
+
* @param {Env} env
|
|
38
|
+
* @param {StoredKey} entry
|
|
39
|
+
*/
|
|
40
|
+
export function writeConfig(env, entry) {
|
|
41
|
+
const file = configPath(env);
|
|
42
|
+
const dir = dirname(file);
|
|
43
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
44
|
+
chmodSync(dir, 0o700);
|
|
45
|
+
const temp = join(dir, `.config.json.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
|
|
46
|
+
try {
|
|
47
|
+
writeFileSync(temp, `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
48
|
+
renameSync(temp, file);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
rmSync(temp, { force: true });
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @param {Env} env */
|
|
56
|
+
export function removeConfig(env) {
|
|
57
|
+
try {
|
|
58
|
+
unlinkSync(configPath(env));
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// socialapi login: OAuth 2.1 in the browser (loopback callback, PKCE S256), then a named API key
|
|
2
|
+
// created with the OAuth access token is stored and the OAuth tokens are revoked.
|
|
3
|
+
// socialapi login --with-api-key: stores a key read from stdin or a hidden prompt.
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
6
|
+
import { createServer } from 'node:http';
|
|
7
|
+
import { hostname } from 'node:os';
|
|
8
|
+
import { text } from 'node:stream/consumers';
|
|
9
|
+
import { isSecureBaseUrl, send } from '../http.mjs';
|
|
10
|
+
import { CliError, EXIT, usageError } from '../errors.mjs';
|
|
11
|
+
import { parseBaseUrl, parseTimeout } from '../operation.mjs';
|
|
12
|
+
import { writeJson } from '../output.mjs';
|
|
13
|
+
import { SIGN_IN_OPERATIONS, callOperation, deleteStoredKey, findOperation, jsonOf, parseFlags } from './api.mjs';
|
|
14
|
+
import { readConfig, writeConfig } from './config.mjs';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {import('../main.mjs').Context} Context
|
|
18
|
+
* @typedef {import('./api.mjs').HttpOptions} HttpOptions
|
|
19
|
+
* @typedef {{ authorization_endpoint: string, token_endpoint: string, registration_endpoint: string, revocation_endpoint: string }} Endpoints
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const USAGE = 'login [--with-api-key] [--no-browser] [--base-url <url>]';
|
|
23
|
+
const REQUIRED_ENDPOINTS = ['authorization_endpoint', 'token_endpoint', 'registration_endpoint', 'revocation_endpoint'];
|
|
24
|
+
|
|
25
|
+
/** The command that opens a URL in the default browser. */
|
|
26
|
+
export function browserCommand(platform, url) {
|
|
27
|
+
if (platform === 'darwin') return { command: 'open', args: [url] };
|
|
28
|
+
if (platform === 'win32') return { command: 'cmd', args: ['/c', 'start', '""', `"${url}"`] };
|
|
29
|
+
return { command: 'xdg-open', args: [url] };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function openBrowser(url) {
|
|
33
|
+
const { command, args } = browserCommand(process.platform, url);
|
|
34
|
+
try {
|
|
35
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: true });
|
|
36
|
+
child.on('error', () => {});
|
|
37
|
+
child.unref();
|
|
38
|
+
} catch {
|
|
39
|
+
// The URL is printed too, so the person can open it by hand.
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const base64url = (bytes) => Buffer.from(bytes).toString('base64url');
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Reads the authorization server metadata and checks every endpoint is on the API origin.
|
|
47
|
+
* @param {string} authBase the base URL without /v1
|
|
48
|
+
* @param {HttpOptions} http
|
|
49
|
+
* @returns {Promise<Endpoints>}
|
|
50
|
+
*/
|
|
51
|
+
async function discover(authBase, http) {
|
|
52
|
+
const origin = new URL(authBase).origin;
|
|
53
|
+
const response = await send({ method: 'GET', url: new URL(`${authBase}/.well-known/oauth-authorization-server`), ...http });
|
|
54
|
+
const invalid = (detail) =>
|
|
55
|
+
new CliError('invalid_authorization_server', `The sign-in server at ${origin} ${detail}, so login stopped. Check the base URL, or sign in with socialapi login --with-api-key.`, EXIT.apiError);
|
|
56
|
+
if (response.status >= 400) throw invalid(`answered ${response.status} for its discovery document`);
|
|
57
|
+
let doc;
|
|
58
|
+
try {
|
|
59
|
+
doc = JSON.parse(response.body.toString('utf8'));
|
|
60
|
+
} catch {}
|
|
61
|
+
if (!doc || typeof doc !== 'object') throw invalid('has no valid discovery document');
|
|
62
|
+
for (const field of REQUIRED_ENDPOINTS) if (typeof doc[field] !== 'string') throw invalid(`lists no ${field}`);
|
|
63
|
+
for (const [field, value] of Object.entries(doc)) {
|
|
64
|
+
if (!field.endsWith('_endpoint') || typeof value !== 'string') continue;
|
|
65
|
+
let endpointOrigin;
|
|
66
|
+
try {
|
|
67
|
+
endpointOrigin = new URL(value).origin;
|
|
68
|
+
} catch {
|
|
69
|
+
throw invalid(`lists an invalid ${field}`);
|
|
70
|
+
}
|
|
71
|
+
if (endpointOrigin !== origin) throw invalid(`lists its ${field} on ${endpointOrigin}, another origin`);
|
|
72
|
+
}
|
|
73
|
+
return /** @type {Endpoints} */ (doc);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Posts a form to an OAuth endpoint and returns its JSON answer.
|
|
78
|
+
* @param {string} endpoint
|
|
79
|
+
* @param {Record<string, string>} fields
|
|
80
|
+
* @param {HttpOptions} http
|
|
81
|
+
*/
|
|
82
|
+
async function postForm(endpoint, fields, http) {
|
|
83
|
+
const response = await send({
|
|
84
|
+
method: 'POST',
|
|
85
|
+
url: new URL(endpoint),
|
|
86
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
87
|
+
body: new URLSearchParams(fields).toString(),
|
|
88
|
+
...http,
|
|
89
|
+
});
|
|
90
|
+
return jsonOf(response);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const page = (title, detail) =>
|
|
94
|
+
`<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family:sans-serif;margin:3em"><h1>${title}</h1><p>${detail}</p></body></html>`;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Listens on 127.0.0.1 with an OS-assigned port for one request to /callback.
|
|
98
|
+
* @returns {Promise<{ redirectUri: string, wait(check: (params: URLSearchParams) => string, timeoutMs: number): Promise<string>, close(): void }>}
|
|
99
|
+
*/
|
|
100
|
+
async function listenForCallback() {
|
|
101
|
+
const server = createServer();
|
|
102
|
+
await new Promise((resolve, reject) => {
|
|
103
|
+
server.once('error', reject);
|
|
104
|
+
server.listen(0, '127.0.0.1', () => resolve(undefined));
|
|
105
|
+
});
|
|
106
|
+
const { port } = /** @type {import('node:net').AddressInfo} */ (server.address());
|
|
107
|
+
const close = () => {
|
|
108
|
+
server.close();
|
|
109
|
+
server.closeAllConnections();
|
|
110
|
+
};
|
|
111
|
+
return {
|
|
112
|
+
redirectUri: `http://127.0.0.1:${port}/callback`,
|
|
113
|
+
close,
|
|
114
|
+
wait(check, timeoutMs) {
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
const timer = setTimeout(() => {
|
|
117
|
+
close();
|
|
118
|
+
reject(new CliError('login_timeout', `No sign-in arrived within ${Math.round(timeoutMs / 1000)} seconds. Run socialapi login again and finish signing in in the browser.`));
|
|
119
|
+
}, timeoutMs);
|
|
120
|
+
server.on('request', (req, res) => {
|
|
121
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
122
|
+
if (url.pathname !== '/callback') {
|
|
123
|
+
res.writeHead(404, { 'content-type': 'text/plain', connection: 'close' }).end('Not found');
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
const headers = { 'content-type': 'text/html; charset=utf-8', connection: 'close' };
|
|
128
|
+
try {
|
|
129
|
+
const code = check(url.searchParams);
|
|
130
|
+
res.writeHead(200, headers).end(page('Signed in to SocialAPI', 'You can close this tab and return to the terminal.'), close);
|
|
131
|
+
resolve(code);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
const reason = error instanceof CliError ? error.code : 'error';
|
|
134
|
+
res.writeHead(400, headers).end(page('Not signed in', `Sign-in stopped (${reason}). Return to the terminal for details.`), close);
|
|
135
|
+
reject(error);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The browser flow. Returns the created key; the OAuth client secret and tokens stay in memory.
|
|
145
|
+
* @param {Context} ctx
|
|
146
|
+
* @param {{ base: string, http: HttpOptions, noBrowser: boolean }} options
|
|
147
|
+
* @returns {Promise<{ apiKey: string, keyId: string, user: any }>}
|
|
148
|
+
*/
|
|
149
|
+
async function browserLogin(ctx, { base, http, noBrowser }) {
|
|
150
|
+
const authBase = base.replace(/\/v1$/, '');
|
|
151
|
+
const endpoints = await discover(authBase, http);
|
|
152
|
+
const callback = await listenForCallback();
|
|
153
|
+
let client;
|
|
154
|
+
let code;
|
|
155
|
+
const verifier = base64url(randomBytes(32));
|
|
156
|
+
try {
|
|
157
|
+
client = await jsonOf(
|
|
158
|
+
await send({
|
|
159
|
+
method: 'POST',
|
|
160
|
+
url: new URL(endpoints.registration_endpoint),
|
|
161
|
+
headers: { 'content-type': 'application/json' },
|
|
162
|
+
body: JSON.stringify({ client_name: `SocialAPI CLI (${hostname()})`, redirect_uris: [callback.redirectUri] }),
|
|
163
|
+
...http,
|
|
164
|
+
}),
|
|
165
|
+
);
|
|
166
|
+
if (typeof client.client_id !== 'string' || typeof client.client_secret !== 'string') {
|
|
167
|
+
throw new CliError('invalid_authorization_server', 'The sign-in server registered no client_id and client_secret. Sign in with socialapi login --with-api-key instead.', EXIT.apiError);
|
|
168
|
+
}
|
|
169
|
+
const state = base64url(randomBytes(24));
|
|
170
|
+
const authorize = new URL(endpoints.authorization_endpoint);
|
|
171
|
+
for (const [name, value] of Object.entries({
|
|
172
|
+
response_type: 'code',
|
|
173
|
+
client_id: client.client_id,
|
|
174
|
+
redirect_uri: callback.redirectUri,
|
|
175
|
+
scope: 'social:all',
|
|
176
|
+
state,
|
|
177
|
+
code_challenge: base64url(createHash('sha256').update(verifier).digest()),
|
|
178
|
+
code_challenge_method: 'S256',
|
|
179
|
+
})) {
|
|
180
|
+
authorize.searchParams.set(name, value);
|
|
181
|
+
}
|
|
182
|
+
ctx.stderr.write(
|
|
183
|
+
noBrowser
|
|
184
|
+
? `Open this URL in a browser to sign in to SocialAPI:\n${authorize.href}\n`
|
|
185
|
+
: `Opening the browser to sign in to SocialAPI. If it does not open, visit this URL:\n${authorize.href}\n`,
|
|
186
|
+
);
|
|
187
|
+
if (!noBrowser) openBrowser(authorize.href);
|
|
188
|
+
code = await callback.wait((params) => {
|
|
189
|
+
if (params.get('state') !== state) {
|
|
190
|
+
throw new CliError('invalid_state', 'The sign-in answer did not carry the state this login sent, so it was refused. Run socialapi login again.', EXIT.apiError);
|
|
191
|
+
}
|
|
192
|
+
const error = params.get('error');
|
|
193
|
+
if (error) throw new CliError(error, params.get('error_description') || `Sign-in ended with ${error}. Run socialapi login again.`, EXIT.apiError);
|
|
194
|
+
const received = params.get('code');
|
|
195
|
+
if (!received) throw new CliError('invalid_request', 'The sign-in answer carried no authorization code. Run socialapi login again.', EXIT.apiError);
|
|
196
|
+
return received;
|
|
197
|
+
}, ctx.loginTimeoutMs);
|
|
198
|
+
} finally {
|
|
199
|
+
callback.close();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const credentials = { client_id: client.client_id, client_secret: client.client_secret };
|
|
203
|
+
const tokens = await postForm(endpoints.token_endpoint, { grant_type: 'authorization_code', code, redirect_uri: callback.redirectUri, code_verifier: verifier, ...credentials }, http);
|
|
204
|
+
if (typeof tokens.access_token !== 'string') throw new CliError('invalid_grant', 'The sign-in server returned no access token. Run socialapi login again.', EXIT.apiError);
|
|
205
|
+
try {
|
|
206
|
+
const created = await callOperation(ctx.manifest, 'createApiKey', { base, token: tokens.access_token, body: { name: `SocialAPI CLI (${hostname()})` }, http });
|
|
207
|
+
if (typeof created.raw_key !== 'string' || typeof created.id !== 'string') {
|
|
208
|
+
throw new CliError('invalid_response', 'The API created a key but returned no raw_key and id. Run socialapi login again.', EXIT.apiError);
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
const user = await callOperation(ctx.manifest, 'getCurrentUser', { base, token: created.raw_key, http });
|
|
212
|
+
return { apiKey: created.raw_key, keyId: created.id, user };
|
|
213
|
+
} catch (error) {
|
|
214
|
+
await deleteStoredKey(ctx.manifest, { base_url: base, api_key: created.raw_key, key_id: created.id, created_by_login: true }, http);
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
} finally {
|
|
218
|
+
for (const [hint, token] of [['access_token', tokens.access_token], ['refresh_token', tokens.refresh_token]]) {
|
|
219
|
+
if (typeof token !== 'string') continue;
|
|
220
|
+
try {
|
|
221
|
+
await postForm(endpoints.revocation_endpoint, { token, token_type_hint: hint, ...credentials }, http);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (!(error instanceof CliError)) throw error;
|
|
224
|
+
ctx.stderr.write(`socialapi: the OAuth ${hint.replace('_', ' ')} could not be revoked (${error.code}); it stays valid until it expires.\n`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Reads a pasted key: all of stdin when piped, or a hidden prompt on a terminal.
|
|
232
|
+
* @param {Context} ctx
|
|
233
|
+
*/
|
|
234
|
+
async function readApiKey(ctx) {
|
|
235
|
+
const stdin = /** @type {any} */ (ctx.stdin);
|
|
236
|
+
if (!stdin.isTTY || typeof stdin.setRawMode !== 'function') return (await text(ctx.stdin)).trim();
|
|
237
|
+
ctx.stderr.write('API key: ');
|
|
238
|
+
return new Promise((resolve, reject) => {
|
|
239
|
+
let value = '';
|
|
240
|
+
const finish = () => {
|
|
241
|
+
stdin.off('data', onData);
|
|
242
|
+
stdin.setRawMode(false);
|
|
243
|
+
stdin.pause();
|
|
244
|
+
ctx.stderr.write('\n');
|
|
245
|
+
};
|
|
246
|
+
const onData = (chunk) => {
|
|
247
|
+
for (const ch of String(chunk)) {
|
|
248
|
+
if (ch === '\r' || ch === '\n') {
|
|
249
|
+
finish();
|
|
250
|
+
resolve(value.trim());
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (ch === '\u0003') {
|
|
254
|
+
finish();
|
|
255
|
+
reject(usageError('No API key was entered.'));
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (ch === '\u007f' || ch === '\b') value = value.slice(0, -1);
|
|
259
|
+
else if (ch >= ' ') value += ch;
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
stdin.setRawMode(true);
|
|
263
|
+
stdin.setEncoding('utf8');
|
|
264
|
+
stdin.on('data', onData);
|
|
265
|
+
stdin.resume();
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** @type {import('../builtins/index.mjs').Builtin} */
|
|
270
|
+
export const login = {
|
|
271
|
+
name: 'login',
|
|
272
|
+
usage: USAGE,
|
|
273
|
+
summary: 'Sign in in the browser and store a new API key, or store an existing key with --with-api-key.',
|
|
274
|
+
async run(args, ctx) {
|
|
275
|
+
const flags = parseFlags(args, { 'with-api-key': 'boolean', 'no-browser': 'boolean', 'base-url': 'value', timeout: 'value', verbose: 'boolean', pretty: 'boolean' }, USAGE);
|
|
276
|
+
const http = { timeoutSeconds: parseTimeout(/** @type {string | undefined} */ (flags.timeout)), verbose: flags.verbose === true, stderr: ctx.stderr };
|
|
277
|
+
const { base, url } = parseBaseUrl(flags['base-url'], ctx.env, ctx.manifest);
|
|
278
|
+
if (!isSecureBaseUrl(url)) {
|
|
279
|
+
throw new CliError('insecure_base_url', `Sign-in works only with an https:// base URL or localhost, and ${url.origin} is neither. Use an https:// base URL.`);
|
|
280
|
+
}
|
|
281
|
+
for (const id of SIGN_IN_OPERATIONS) findOperation(ctx.manifest, id);
|
|
282
|
+
|
|
283
|
+
let result;
|
|
284
|
+
if (flags['with-api-key']) {
|
|
285
|
+
const apiKey = await readApiKey(ctx);
|
|
286
|
+
if (!apiKey) throw usageError('No API key was given. Pipe the key on stdin, for example: socialapi login --with-api-key < key.txt');
|
|
287
|
+
const user = await callOperation(ctx.manifest, 'getCurrentUser', { base, token: apiKey, http });
|
|
288
|
+
result = { apiKey, keyId: null, user };
|
|
289
|
+
} else {
|
|
290
|
+
result = await browserLogin(ctx, { base, http, noBrowser: flags['no-browser'] === true });
|
|
291
|
+
}
|
|
292
|
+
await replaceStoredKey(ctx, { base_url: base, api_key: result.apiKey, key_id: result.keyId, created_by_login: !flags['with-api-key'] }, http);
|
|
293
|
+
writeJson(ctx.stdout, { logged_in: true, base_url: base, user: result.user }, flags.pretty === true || Boolean(ctx.stdout.isTTY));
|
|
294
|
+
return EXIT.ok;
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Stores the new key, then deletes the key an earlier login created (best effort, reported on stderr).
|
|
300
|
+
* @param {Context} ctx
|
|
301
|
+
* @param {import('./config.mjs').StoredKey} entry
|
|
302
|
+
* @param {HttpOptions} http
|
|
303
|
+
*/
|
|
304
|
+
async function replaceStoredKey(ctx, entry, http) {
|
|
305
|
+
const previous = readConfig(ctx.env);
|
|
306
|
+
writeConfig(ctx.env, entry);
|
|
307
|
+
if (!previous?.created_by_login || !previous.key_id || previous.api_key === entry.api_key) return;
|
|
308
|
+
const failure = await deleteStoredKey(ctx.manifest, previous, http);
|
|
309
|
+
if (failure) {
|
|
310
|
+
ctx.stderr.write(`socialapi: the previous API key ${previous.key_id} (on ${previous.base_url}) could not be deleted (${failure}). Delete it in the SocialAPI dashboard.\n`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// socialapi logout: removes the stored key, and deletes it on the API when `socialapi login` created it.
|
|
2
|
+
import { CliError, EXIT } from '../errors.mjs';
|
|
3
|
+
import { parseTimeout } from '../operation.mjs';
|
|
4
|
+
import { writeJson } from '../output.mjs';
|
|
5
|
+
import { deleteStoredKey, parseFlags } from './api.mjs';
|
|
6
|
+
import { readConfig, removeConfig } from './config.mjs';
|
|
7
|
+
|
|
8
|
+
const USAGE = 'logout';
|
|
9
|
+
|
|
10
|
+
/** @type {import('../builtins/index.mjs').Builtin} */
|
|
11
|
+
export const logout = {
|
|
12
|
+
name: 'logout',
|
|
13
|
+
usage: USAGE,
|
|
14
|
+
summary: 'Remove the stored API key, and delete it on the API when socialapi login created it.',
|
|
15
|
+
async run(args, ctx) {
|
|
16
|
+
const flags = parseFlags(args, { timeout: 'value', verbose: 'boolean', pretty: 'boolean' }, USAGE);
|
|
17
|
+
const http = { timeoutSeconds: parseTimeout(/** @type {string | undefined} */ (flags.timeout)), verbose: flags.verbose === true, stderr: ctx.stderr };
|
|
18
|
+
const pretty = flags.pretty === true || Boolean(ctx.stdout.isTTY);
|
|
19
|
+
const stored = readConfig(ctx.env);
|
|
20
|
+
if (!stored) {
|
|
21
|
+
removeConfig(ctx.env);
|
|
22
|
+
writeJson(ctx.stdout, { logged_out: false, message: 'No API key is stored, so there is nothing to remove.' }, pretty);
|
|
23
|
+
return EXIT.ok;
|
|
24
|
+
}
|
|
25
|
+
let failure = null;
|
|
26
|
+
try {
|
|
27
|
+
if (stored.created_by_login && stored.key_id) failure = await deleteStoredKey(ctx.manifest, stored, http);
|
|
28
|
+
} finally {
|
|
29
|
+
removeConfig(ctx.env);
|
|
30
|
+
}
|
|
31
|
+
if (failure) {
|
|
32
|
+
throw new CliError(
|
|
33
|
+
'key_not_deleted',
|
|
34
|
+
`The API key was removed from this computer, but deleting it on the API failed (${failure}). Delete the key ${stored.key_id} in the SocialAPI dashboard.`,
|
|
35
|
+
EXIT.apiError,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
writeJson(ctx.stdout, { logged_out: true, base_url: stored.base_url, key_deleted: stored.created_by_login }, pretty);
|
|
39
|
+
return EXIT.ok;
|
|
40
|
+
},
|
|
41
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// socialapi whoami: runs getCurrentUser with the resolved credential (flag, env or stored key).
|
|
2
|
+
import { runOperation } from '../operation.mjs';
|
|
3
|
+
import { findOperation } from './api.mjs';
|
|
4
|
+
|
|
5
|
+
/** @type {import('../builtins/index.mjs').Builtin} */
|
|
6
|
+
export const whoami = {
|
|
7
|
+
name: 'whoami',
|
|
8
|
+
usage: 'whoami',
|
|
9
|
+
summary: 'Show the account the current API key belongs to.',
|
|
10
|
+
run(args, ctx) {
|
|
11
|
+
return runOperation(findOperation(ctx.manifest, 'getCurrentUser'), args, ctx);
|
|
12
|
+
},
|
|
13
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { usageError } from '../errors.mjs';
|
|
2
|
+
import { columns, writeJson } from '../output.mjs';
|
|
3
|
+
|
|
4
|
+
/** The tag `commands` gives built-in commands. */
|
|
5
|
+
const BUILTIN_TAG = 'Built-in';
|
|
6
|
+
|
|
7
|
+
/** @type {import('./index.mjs').Builtin} */
|
|
8
|
+
export const commands = {
|
|
9
|
+
name: 'commands',
|
|
10
|
+
usage: 'commands [text] [--json]',
|
|
11
|
+
summary: 'List the commands (API operations, then built-ins), or those whose name, tag or summary contains every word of the text.',
|
|
12
|
+
run(args, ctx) {
|
|
13
|
+
const options = { json: false, pretty: false };
|
|
14
|
+
const words = [];
|
|
15
|
+
for (const arg of args) {
|
|
16
|
+
if (arg === '--json') options.json = true;
|
|
17
|
+
else if (arg === '--pretty') options.pretty = true;
|
|
18
|
+
else if (arg.startsWith('--')) throw usageError(`Unknown flag ${arg} for commands. Usage: socialapi commands [text] [--json]`);
|
|
19
|
+
else words.push(...arg.toLowerCase().split(/\s+/).filter(Boolean));
|
|
20
|
+
}
|
|
21
|
+
const all = [
|
|
22
|
+
...ctx.manifest.commands.map((c) => ({ name: c.name, tag: c.tag, summary: c.summary, method: c.method, path: c.path, arguments: c.args.map((a) => a.name) })),
|
|
23
|
+
...ctx.builtins.map((b) => ({ name: b.name, tag: BUILTIN_TAG, summary: b.summary, method: null, path: null, arguments: [] })),
|
|
24
|
+
];
|
|
25
|
+
const found = all.filter((c) => {
|
|
26
|
+
const haystack = `${c.name} ${c.tag} ${c.summary}`.toLowerCase();
|
|
27
|
+
return words.every((w) => haystack.includes(w));
|
|
28
|
+
});
|
|
29
|
+
if (options.json) {
|
|
30
|
+
writeJson(ctx.stdout, found, options.pretty || Boolean(ctx.stdout.isTTY));
|
|
31
|
+
} else if (found.length) {
|
|
32
|
+
ctx.stdout.write(`${columns(found.map((c) => [c.name, c.summary]), '')}\n`);
|
|
33
|
+
}
|
|
34
|
+
return 0;
|
|
35
|
+
},
|
|
36
|
+
};
|