@phantomcodes/cli 1.6.3 → 1.7.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/LICENSE +1 -2
- package/README.md +139 -118
- package/bin/phantom.mjs +37 -2
- package/dist/agents/command.d.mts +8 -27
- package/dist/agents/command.mjs +323 -59
- package/dist/agents/login.d.mts +3 -0
- package/dist/agents/login.mjs +97 -0
- package/dist/agents/opencode-check.d.mts +15 -0
- package/dist/agents/opencode-check.mjs +193 -0
- package/dist/agents/phantom-key.d.mts +7 -0
- package/dist/agents/phantom-key.mjs +40 -0
- package/dist/agents/proxy.d.mts +26 -28
- package/dist/agents/proxy.mjs +225 -33
- package/dist/chatgpt/command.d.mts +2 -0
- package/dist/chatgpt/command.mjs +119 -0
- package/dist/chatgpt/session.d.mts +87 -0
- package/dist/chatgpt/session.mjs +253 -0
- package/dist/cli/accounts.d.mts +21 -0
- package/dist/cli/accounts.mjs +96 -0
- package/dist/cli/app.d.mts +4 -24
- package/dist/cli/app.mjs +224 -139
- package/dist/cli/commands.d.mts +1 -16
- package/dist/cli/commands.mjs +144 -239
- package/dist/cli/help.d.mts +0 -19
- package/dist/cli/help.mjs +30 -55
- package/dist/cli/run.mjs +35 -79
- package/dist/cli/start.d.mts +2 -31
- package/dist/cli/start.mjs +13 -116
- package/dist/core/brand.d.mts +0 -7
- package/dist/core/brand.mjs +0 -8
- package/dist/core/errors.d.mts +0 -16
- package/dist/core/errors.mjs +0 -16
- package/dist/core/helpers.d.mts +0 -46
- package/dist/core/helpers.mjs +1 -64
- package/dist/core/node-trust.d.mts +0 -5
- package/dist/core/node-trust.mjs +0 -6
- package/dist/core/pick.d.mts +7 -55
- package/dist/core/pick.mjs +49 -106
- package/dist/core/request.d.mts +0 -46
- package/dist/core/request.mjs +1 -60
- package/dist/core/secrets.d.mts +0 -4
- package/dist/core/secrets.mjs +0 -10
- package/dist/core/state.d.mts +3 -1
- package/dist/core/state.mjs +147 -4
- package/dist/core/style.d.mts +0 -27
- package/dist/core/style.mjs +0 -20
- package/dist/core/version.d.mts +1 -2
- package/dist/core/version.mjs +1 -2
- package/dist/local/accounts.d.mts +25 -0
- package/dist/local/accounts.mjs +40 -0
- package/dist/local/agent-headers.d.mts +7 -0
- package/dist/local/agent-headers.mjs +44 -0
- package/dist/local/chatgpt-plan.d.mts +147 -0
- package/dist/local/chatgpt-plan.mjs +384 -0
- package/dist/local/command.d.mts +24 -0
- package/dist/local/command.mjs +211 -0
- package/dist/local/config.d.mts +49 -0
- package/dist/local/config.mjs +168 -0
- package/dist/local/decide.d.mts +37 -0
- package/dist/local/decide.mjs +201 -0
- package/dist/local/failure-signs.d.mts +4 -0
- package/dist/local/failure-signs.mjs +99 -0
- package/dist/local/keys.d.mts +32 -0
- package/dist/local/keys.mjs +239 -0
- package/dist/local/models.d.mts +53 -0
- package/dist/local/models.mjs +117 -0
- package/dist/local/replay.d.mts +59 -0
- package/dist/local/replay.mjs +143 -0
- package/dist/local/report.d.mts +43 -0
- package/dist/local/report.mjs +153 -0
- package/dist/local/request-log.d.mts +53 -0
- package/dist/local/request-log.mjs +69 -0
- package/dist/local/retry-after.d.mts +3 -0
- package/dist/local/retry-after.mjs +28 -0
- package/dist/local/rust-router.d.mts +39 -0
- package/dist/local/rust-router.mjs +54 -0
- package/dist/local/server.d.mts +27 -0
- package/dist/local/server.mjs +449 -0
- package/dist/local/status-line.d.mts +17 -0
- package/dist/local/status-line.mjs +81 -0
- package/dist/local/tiers.d.mts +3 -0
- package/dist/local/tiers.mjs +137 -0
- package/dist/local/traces.d.mts +69 -0
- package/dist/local/traces.mjs +341 -0
- package/dist/phantom.d.mts +0 -37
- package/dist/phantom.mjs +0 -31
- package/package.json +15 -9
- package/skills/phantom-ai/SKILL.md +28 -97
- package/dist/cli/screens.d.mts +0 -177
- package/dist/cli/screens.mjs +0 -398
- package/dist/core/free.d.mts +0 -13
- package/dist/core/free.mjs +0 -14
- package/dist/core/motion.d.mts +0 -47
- package/dist/core/motion.mjs +0 -156
- package/dist/core/shapes.d.mts +0 -13
- package/dist/core/shapes.mjs +0 -1
- package/dist/keys/command.d.mts +0 -16
- package/dist/keys/command.mjs +0 -143
- package/dist/keys/saved.d.mts +0 -96
- package/dist/keys/saved.mjs +0 -169
- package/dist/models/choice.d.mts +0 -7
- package/dist/models/choice.mjs +0 -27
- package/dist/models/command.d.mts +0 -8
- package/dist/models/command.mjs +0 -66
- package/dist/models/list.d.mts +0 -39
- package/dist/models/list.mjs +0 -39
- package/dist/receipts/command.d.mts +0 -7
- package/dist/receipts/command.mjs +0 -41
- package/dist/receipts/receipts.d.mts +0 -76
- package/dist/receipts/receipts.mjs +0 -118
- package/dist/setup/agents.d.mts +0 -149
- package/dist/setup/agents.mjs +0 -886
- package/dist/setup/apply.d.mts +0 -85
- package/dist/setup/apply.mjs +0 -301
- package/dist/setup/command.d.mts +0 -12
- package/dist/setup/command.mjs +0 -307
- package/dist/setup/editors.d.mts +0 -108
- package/dist/setup/editors.mjs +0 -500
- package/dist/setup/legacy.d.mts +0 -13
- package/dist/setup/legacy.mjs +0 -36
- package/dist/setup/plan.d.mts +0 -104
- package/dist/setup/plan.mjs +0 -132
- package/dist/setup/screen.d.mts +0 -30
- package/dist/setup/screen.mjs +0 -260
- package/dist/setup/shared.d.mts +0 -141
- package/dist/setup/shared.mjs +0 -88
- package/dist/setup/was.d.mts +0 -42
- package/dist/setup/was.mjs +0 -91
- package/dist/spend/command.d.mts +0 -5
- package/dist/spend/command.mjs +0 -235
- package/dist/spend/lineup.d.mts +0 -61
- package/dist/spend/lineup.mjs +0 -39
- package/dist/spend/reason.d.mts +0 -5
- package/dist/spend/reason.mjs +0 -60
- package/dist/spend/report.d.mts +0 -105
- package/dist/spend/report.mjs +0 -68
- package/dist/spend/routing.d.mts +0 -74
- package/dist/spend/routing.mjs +0 -57
- package/dist/workspace/command.d.mts +0 -59
- package/dist/workspace/command.mjs +0 -871
|
@@ -1,871 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { hostname } from 'node:os';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
5
|
-
import { DEFAULT_BASE_URL, REQUEST_TIMEOUT_MS, answerError, fetchAnswer, httpsOnly } from "../core/request.mjs";
|
|
6
|
-
import { stateDir } from "../core/state.mjs";
|
|
7
|
-
import { writeSecret, readSecret, removeSecret, keychainOn } from "../core/secrets.mjs";
|
|
8
|
-
import { keyCommand, loginCommand } from "../keys/command.mjs";
|
|
9
|
-
import { die, PhantomApiError } from "../core/errors.mjs";
|
|
10
|
-
import { limitFlag, openUrl, pickIo, showsScreen } from "../core/helpers.mjs";
|
|
11
|
-
import { BackToMenu, Cancelled, askText, cancelKeys, choose, keyboard } from "../core/pick.mjs";
|
|
12
|
-
import { spawnSync } from 'node:child_process';
|
|
13
|
-
import { onPath } from "../setup/shared.mjs";
|
|
14
|
-
import { colorOn, paint } from "../core/style.mjs";
|
|
15
|
-
import { closestCommand } from "../cli/start.mjs";
|
|
16
|
-
import { alreadySignedInScreen, fundScreen, keyChangeScreen, keysScreen, paymentScreen, signedInScreen, workspaceScreen } from "../cli/screens.mjs";
|
|
17
|
-
import { keyId, keyPath, listNamedKeys, namedKeyPath, readNamedKey, resolveApiKey, saveApiKey, saveNamedKey } from "../keys/saved.mjs";
|
|
18
|
-
const credentialPath = (env) => path.join(stateDir(env), 'workspace');
|
|
19
|
-
const base = (input) => httpsOnly(input.baseUrl || input.env.PHANTOM_BASE_URL || DEFAULT_BASE_URL).replace(/\/$/, '');
|
|
20
|
-
/**
|
|
21
|
-
* One call to the workspace API, with the limits every call shares ({@link fetchAnswer}): 30 seconds
|
|
22
|
-
* unless `timeoutMs` says less, and a plain message for a web page, an empty answer or no connection.
|
|
23
|
-
* @throws {@link PhantomApiError} when the API answers with an error status.
|
|
24
|
-
*/
|
|
25
|
-
export async function wire(url, method, endpoint, body, token, timeoutMs) {
|
|
26
|
-
const { res, answer } = await fetchAnswer(url + endpoint, {
|
|
27
|
-
method,
|
|
28
|
-
redirect: 'error',
|
|
29
|
-
headers: {
|
|
30
|
-
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
31
|
-
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
32
|
-
},
|
|
33
|
-
body: body === undefined ? undefined : JSON.stringify(body),
|
|
34
|
-
}, `${method} ${endpoint}`, timeoutMs);
|
|
35
|
-
if (!res.ok) {
|
|
36
|
-
const err = answerError(res.status, answer);
|
|
37
|
-
// A sign-in the server revoked answers 401 with words for a web page or the CLI alike ("run `phantom login`
|
|
38
|
-
// in the CLI, or sign in on /keys"). Here only the CLI is asking, so say it in the CLI's own words.
|
|
39
|
-
if (res.status === 401 && token && err.code === 'http_401') {
|
|
40
|
-
throw new PhantomApiError(401, err.code, 'This sign-in no longer works. Run phantom login to sign in again.');
|
|
41
|
-
}
|
|
42
|
-
throw err;
|
|
43
|
-
}
|
|
44
|
-
if (answer.kind === 'text')
|
|
45
|
-
die('Phantom AI sent a web page instead of data. Check PHANTOM_BASE_URL, and try again in a minute.', 'bad_answer');
|
|
46
|
-
return answer.json;
|
|
47
|
-
}
|
|
48
|
-
function credentials(input) {
|
|
49
|
-
const file = credentialPath(input.env);
|
|
50
|
-
if (!existsSync(file))
|
|
51
|
-
die('Not signed in to a workspace on this computer. Run phantom login to sign in.', 'workspace_missing');
|
|
52
|
-
const saved = JSON.parse(readSecret(input.env, file));
|
|
53
|
-
if (saved.base_url !== base(input))
|
|
54
|
-
die('This workspace belongs to a different API address. Run phantom login for this address.', 'workspace_origin');
|
|
55
|
-
return saved;
|
|
56
|
-
}
|
|
57
|
-
/** The workspace `phantom login` saved for this API address, or null when it saved none or saved one for another address. */
|
|
58
|
-
export function savedWorkspace(input) {
|
|
59
|
-
const file = credentialPath(input.env);
|
|
60
|
-
if (!existsSync(file))
|
|
61
|
-
return null;
|
|
62
|
-
const saved = JSON.parse(readSecret(input.env, file));
|
|
63
|
-
return saved.base_url === base(input) ? saved : null;
|
|
64
|
-
}
|
|
65
|
-
/** The management credential `phantom login` saved for this API address, or null when it saved none. */
|
|
66
|
-
export function savedManagement(input) {
|
|
67
|
-
return existsSync(credentialPath(input.env)) ? credentials(input).management_credential : null;
|
|
68
|
-
}
|
|
69
|
-
/** A read from the saved workspace, such as `/spend`, with its management credential. */
|
|
70
|
-
export async function workspaceGet(input, path) {
|
|
71
|
-
const saved = credentials(input);
|
|
72
|
-
return wire(saved.base_url, 'GET', '/workspaces/' + encodeURIComponent(saved.workspace_id) + path, undefined, saved.management_credential);
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Device authorization for accounts or guests, saving keys locally without copying a secret through the browser.
|
|
76
|
-
* With `inSetup`, `phantom setup` carries on once it is signed in, so it says that instead of printing the
|
|
77
|
-
* saved key's details and the next commands.
|
|
78
|
-
*/
|
|
79
|
-
export async function workspaceLogin(input, opts = {}) {
|
|
80
|
-
const { env, io, flags } = input;
|
|
81
|
-
if (flags.save === true)
|
|
82
|
-
die('--save requires a key name.');
|
|
83
|
-
const name = typeof flags.save === 'string' ? flags.save : 'default';
|
|
84
|
-
const target = name === 'default' ? keyPath(env) : namedKeyPath(env, name);
|
|
85
|
-
if (existsSync(target)) {
|
|
86
|
-
// Signing in again is a question ("am I signed in?"), so it gets an answer, not an error.
|
|
87
|
-
if (name === 'default')
|
|
88
|
-
return alreadySignedIn(input);
|
|
89
|
-
die(`A key named ${name} is already saved here. Pick another name with --save <name>; nothing was changed.`, 'key_exists');
|
|
90
|
-
}
|
|
91
|
-
// At a terminal, how to sign in is a choice; --no-browser or a pipe skips it.
|
|
92
|
-
const pick = flags['no-browser'] ? null : pickIo(input);
|
|
93
|
-
let noBrowser = Boolean(flags['no-browser']);
|
|
94
|
-
if (pick) {
|
|
95
|
-
const how = await choose(pick, 'How do you want to sign in?', [
|
|
96
|
-
{
|
|
97
|
-
label: 'Open the browser',
|
|
98
|
-
hint: 'approve there, and phantom saves your key',
|
|
99
|
-
value: 'browser',
|
|
100
|
-
},
|
|
101
|
-
{
|
|
102
|
-
label: 'Show the link',
|
|
103
|
-
hint: 'to open it yourself, or on another device',
|
|
104
|
-
value: 'link',
|
|
105
|
-
},
|
|
106
|
-
{
|
|
107
|
-
label: 'Paste a key I already have',
|
|
108
|
-
hint: 'starts with sk-phantom-',
|
|
109
|
-
value: 'paste',
|
|
110
|
-
},
|
|
111
|
-
]);
|
|
112
|
-
// Esc: back to the menu when it started this, otherwise stop without saving anything.
|
|
113
|
-
if (how === null && input.io.fromMenu)
|
|
114
|
-
throw new BackToMenu();
|
|
115
|
-
if (how === null) {
|
|
116
|
-
input.io.stderr(' Sign-in cancelled. Nothing was saved.\n');
|
|
117
|
-
return 0;
|
|
118
|
-
}
|
|
119
|
-
if (how === 'paste') {
|
|
120
|
-
await loginCommand({
|
|
121
|
-
...input,
|
|
122
|
-
subcommand: undefined,
|
|
123
|
-
flags: {},
|
|
124
|
-
io: opts.inSetup ? { ...input.io, stdout: input.io.stderr } : input.io,
|
|
125
|
-
});
|
|
126
|
-
return 0;
|
|
127
|
-
}
|
|
128
|
-
noBrowser = how === 'link';
|
|
129
|
-
}
|
|
130
|
-
const url = base(input);
|
|
131
|
-
const start = await wire(url, 'POST', '/auth/device', { client_name: `phantom on ${hostname()}` });
|
|
132
|
-
if (new URL(start.verification_uri_complete).origin !== new URL(url).origin)
|
|
133
|
-
die('The approval URL belongs to another site.', 'device_origin');
|
|
134
|
-
const lit = colorOn(env, io.isTTY);
|
|
135
|
-
const p = paint(env, lit);
|
|
136
|
-
io.stderr(`\n ${p.lime('◆')} ${p.bold('Sign in to Phantom AI')}\n\n` +
|
|
137
|
-
` ${p.dim('Open')} ${p.bold(start.verification_uri_complete)}\n` +
|
|
138
|
-
` ${p.dim('Code')} ${p.lime(p.bold(start.user_code))} ${p.dim('check that the page shows the same code, then approve')}\n\n` +
|
|
139
|
-
// In color the spinner below draws this line, so it moves while sign-in waits.
|
|
140
|
-
(lit ? '' : ` ${p.dim('Waiting for you to approve…')}\n`) +
|
|
141
|
-
(pick ? ` ${p.dim('esc or ctrl+c to cancel')}\n` : ''));
|
|
142
|
-
if (!noBrowser)
|
|
143
|
-
openUrl(start.verification_uri_complete);
|
|
144
|
-
const spinner = lit ? waiting(io.stderr, p) : null;
|
|
145
|
-
// At a terminal, Esc or Ctrl+C stops the wait, as they do everywhere else.
|
|
146
|
-
const cancel = pick ? cancelKeys((pick.keys ?? keyboard)()) : null;
|
|
147
|
-
try {
|
|
148
|
-
return await pollForApproval(input, opts, {
|
|
149
|
-
url,
|
|
150
|
-
start,
|
|
151
|
-
name,
|
|
152
|
-
spinner,
|
|
153
|
-
cancel: cancel?.pressed ?? null,
|
|
154
|
-
});
|
|
155
|
-
}
|
|
156
|
-
finally {
|
|
157
|
-
spinner?.stop();
|
|
158
|
-
cancel?.close();
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
/** `phantom login` on a computer that already has a key: which key, and how to use another. Exit 0. */
|
|
162
|
-
function alreadySignedIn(input) {
|
|
163
|
-
const { env, io } = input;
|
|
164
|
-
const key = resolveApiKey(env);
|
|
165
|
-
const result = {
|
|
166
|
-
signed_in: true,
|
|
167
|
-
already: true,
|
|
168
|
-
key_id: key ? keyId(key) : null,
|
|
169
|
-
};
|
|
170
|
-
if (showsScreen(input))
|
|
171
|
-
io.stdout(alreadySignedInScreen(result.key_id, {
|
|
172
|
-
env,
|
|
173
|
-
color: colorOn(env, io.stdoutIsTTY),
|
|
174
|
-
}) + '\n');
|
|
175
|
-
else
|
|
176
|
-
io.stdout(JSON.stringify(result) + '\n');
|
|
177
|
-
return 0;
|
|
178
|
-
}
|
|
179
|
-
/** A spinner on one line: `⠋ Waiting for you to approve…` until stopped, then `✓ Approved.` or nothing. */
|
|
180
|
-
function waiting(write, p, words = 'Waiting for you to approve…', doneWords = 'Approved.') {
|
|
181
|
-
const frames = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';
|
|
182
|
-
let k = 0;
|
|
183
|
-
const draw = () => write(`\r ${p.lime(frames[k++ % frames.length])} ${p.dim(words)}`);
|
|
184
|
-
draw();
|
|
185
|
-
const timer = setInterval(draw, 80);
|
|
186
|
-
// The spinner never keeps the process alive on its own.
|
|
187
|
-
timer.unref?.();
|
|
188
|
-
let stopped = false;
|
|
189
|
-
const stop = (line = '') => {
|
|
190
|
-
if (stopped)
|
|
191
|
-
return;
|
|
192
|
-
stopped = true;
|
|
193
|
-
clearInterval(timer);
|
|
194
|
-
write(`\r\x1b[2K${line}`);
|
|
195
|
-
};
|
|
196
|
-
return {
|
|
197
|
-
stop: () => stop(),
|
|
198
|
-
done: () => stop(` ${p.lime('✓')} ${doneWords}\n`),
|
|
199
|
-
};
|
|
200
|
-
}
|
|
201
|
-
/** Asks the server for the approved key until it comes, the code expires, or it fails. */
|
|
202
|
-
async function pollForApproval(input, opts, ctx) {
|
|
203
|
-
const { env, io } = input;
|
|
204
|
-
const { url, start, name, spinner, cancel } = ctx;
|
|
205
|
-
const p = paint(env, colorOn(env, io.isTTY));
|
|
206
|
-
let interval = Math.max(1, start.interval) * 1000;
|
|
207
|
-
const deadline = Date.now() + Math.min(600, start.expires_in) * 1000;
|
|
208
|
-
while (Date.now() < deadline) {
|
|
209
|
-
const key = await Promise.race([new Promise((r) => setTimeout(() => r(null), interval)), cancel ?? new Promise(() => { })]);
|
|
210
|
-
if (key) {
|
|
211
|
-
spinner?.stop();
|
|
212
|
-
if (key === 'ctrl-c')
|
|
213
|
-
throw new Cancelled();
|
|
214
|
-
if (input.io.fromMenu)
|
|
215
|
-
throw new BackToMenu();
|
|
216
|
-
io.stderr(' Sign-in cancelled. Nothing was saved.\n');
|
|
217
|
-
return 0;
|
|
218
|
-
}
|
|
219
|
-
// The sleep may have used up the time. One stuck request must not carry the wait past the deadline.
|
|
220
|
-
const left = deadline - Date.now();
|
|
221
|
-
if (left <= 0)
|
|
222
|
-
break;
|
|
223
|
-
let token;
|
|
224
|
-
try {
|
|
225
|
-
token = await wire(url, 'POST', '/auth/device/token', { device_code: start.device_code }, undefined, Math.min(REQUEST_TIMEOUT_MS, left));
|
|
226
|
-
}
|
|
227
|
-
catch (error) {
|
|
228
|
-
const code = error.code;
|
|
229
|
-
// One poll that got no answer is not the end: ask again until the deadline.
|
|
230
|
-
if (code === 'authorization_pending' || code === 'request_timeout')
|
|
231
|
-
continue;
|
|
232
|
-
if (code === 'slow_down') {
|
|
233
|
-
interval += 5000;
|
|
234
|
-
continue;
|
|
235
|
-
}
|
|
236
|
-
throw error;
|
|
237
|
-
}
|
|
238
|
-
spinner?.done();
|
|
239
|
-
const saved = {
|
|
240
|
-
version: 1,
|
|
241
|
-
workspace_id: token.workspace_id,
|
|
242
|
-
management_credential: token.management_token,
|
|
243
|
-
base_url: url,
|
|
244
|
-
recovery: token.recovery,
|
|
245
|
-
};
|
|
246
|
-
try {
|
|
247
|
-
writeSecret(env, credentialPath(env), JSON.stringify(saved));
|
|
248
|
-
if (name === 'default')
|
|
249
|
-
saveApiKey(env, token.api_key);
|
|
250
|
-
else
|
|
251
|
-
saveNamedKey(env, name, token.api_key);
|
|
252
|
-
}
|
|
253
|
-
catch (error) {
|
|
254
|
-
io.stderr('phantom signed you in but could not save the sign-in on this computer. Fix the error below and run phantom login again. Then revoke the key this sign-in made with phantom keys revoke.\n');
|
|
255
|
-
throw error;
|
|
256
|
-
}
|
|
257
|
-
if (opts.inSetup) {
|
|
258
|
-
io.stderr(` ${p.lime('✓')} Signed in. Setting up your agents next.\n\n`);
|
|
259
|
-
return 0;
|
|
260
|
-
}
|
|
261
|
-
const result = {
|
|
262
|
-
saved_as: name,
|
|
263
|
-
key_name: token.key_name,
|
|
264
|
-
workspace_id: token.workspace_id,
|
|
265
|
-
storage: keychainOn(env) ? 'macOS Keychain' : 'private files',
|
|
266
|
-
};
|
|
267
|
-
if (showsScreen(input)) {
|
|
268
|
-
io.stdout(signedInScreen(result, { env, color: colorOn(env, io.stdoutIsTTY) }) + '\n');
|
|
269
|
-
return 0;
|
|
270
|
-
}
|
|
271
|
-
io.stdout(JSON.stringify(result) + '\n');
|
|
272
|
-
io.stderr('Signed in. Start an agent with phantom claude, phantom codex or phantom pi. A guest workspace can save its recovery file with phantom workspace export --file <path>.\n');
|
|
273
|
-
return 0;
|
|
274
|
-
}
|
|
275
|
-
die('The sign-in code expired before it was approved. Run phantom login again.', 'login_expired');
|
|
276
|
-
}
|
|
277
|
-
/** The words `phantom workspace` takes. `fund` is here because `phantom fund` runs it. */
|
|
278
|
-
const WORKSPACE_WORDS = ['status', 'payment', 'export', 'import', 'revoke-access', 'delete', 'fund'];
|
|
279
|
-
/**
|
|
280
|
-
* A file phantom could not write, in a sentence that says what to do, instead of node's `EEXIST: file already
|
|
281
|
-
* exists, open '…'`.
|
|
282
|
-
*/
|
|
283
|
-
function writeFailure(err, file) {
|
|
284
|
-
const code = err.code;
|
|
285
|
-
if (code === 'EEXIST')
|
|
286
|
-
die(`There is already a file at ${file}. phantom won't overwrite it. Pick a path that doesn't exist yet.`, 'file_exists');
|
|
287
|
-
if (code === 'ENOENT')
|
|
288
|
-
die(`Could not save to ${file}: the folder doesn't exist. Make the folder first, or pick another path.`, 'file_unwritable');
|
|
289
|
-
if (code === 'EACCES' || code === 'EPERM')
|
|
290
|
-
die(`Could not save to ${file}: phantom has no permission to write there. Pick another path.`, 'file_unwritable');
|
|
291
|
-
if (code === 'EISDIR')
|
|
292
|
-
die(`Could not save to ${file}: that is a folder. Give a file path, such as ${path.join(file, 'recovery.json')}.`, 'file_unwritable');
|
|
293
|
-
die(`Could not save to ${file}. Pick another path.`, 'file_unwritable');
|
|
294
|
-
}
|
|
295
|
-
/**
|
|
296
|
-
* Reads a JSON file for a flag. A file that is missing or can't be read says so, and a file that is not
|
|
297
|
-
* JSON says `notJson`, instead of node's `ENOENT` or `Unexpected token`.
|
|
298
|
-
*/
|
|
299
|
-
function readJsonFile(file, notJson) {
|
|
300
|
-
let text;
|
|
301
|
-
try {
|
|
302
|
-
text = readFileSync(file, 'utf8');
|
|
303
|
-
}
|
|
304
|
-
catch (err) {
|
|
305
|
-
const code = err.code;
|
|
306
|
-
const why = code === 'ENOENT' ? 'there is no file at that path' : code === 'EISDIR' ? 'that is a folder' : code === 'EACCES' ? 'phantom has no permission to read it' : 'it could not be opened';
|
|
307
|
-
die(`Could not read ${file}: ${why}. Check the path.`, 'file_unreadable');
|
|
308
|
-
}
|
|
309
|
-
try {
|
|
310
|
-
return JSON.parse(text);
|
|
311
|
-
}
|
|
312
|
-
catch {
|
|
313
|
-
die(notJson, 'file_not_json');
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
/** One sign-in by its id or the start of it, at least 4 characters, as `phantom workspace` lists them. */
|
|
317
|
-
function findAccess(access, typed) {
|
|
318
|
-
const t = typed.trim().toLowerCase();
|
|
319
|
-
const exact = access.find((a) => a.id.toLowerCase() === t);
|
|
320
|
-
if (exact)
|
|
321
|
-
return exact.id;
|
|
322
|
-
if (t.length < 4)
|
|
323
|
-
die(`"${typed}" is too short. Type at least 4 characters of the id from phantom workspace.`, 'access_not_found');
|
|
324
|
-
const hits = access.filter((a) => a.id.toLowerCase().startsWith(t));
|
|
325
|
-
const label = (a) => `${a.kind ?? 'sign-in'} ${a.id.slice(0, 8)}`;
|
|
326
|
-
if (hits.length === 1)
|
|
327
|
-
return hits[0].id;
|
|
328
|
-
if (!hits.length)
|
|
329
|
-
die(`No sign-in matches "${typed}". Run phantom workspace to see them: ${access.map(label).join(', ') || 'none'}.`, 'access_not_found');
|
|
330
|
-
die(`"${typed}" matches more than one sign-in: ${hits.map(label).join(', ')}. Type more of the id.`, 'access_ambiguous');
|
|
331
|
-
}
|
|
332
|
-
/** What each way to pay takes: its name in a sentence, and the least it takes. Every way takes up to $10,000 (web/lib/pricing.ts). */
|
|
333
|
-
const FUND_WAYS = {
|
|
334
|
-
card: { label: 'Card payments take', min: 5 },
|
|
335
|
-
usdc: { label: 'USDC on Solana takes', min: 0.1 },
|
|
336
|
-
'usdc-base': { label: 'USDC on Base takes', min: 1 },
|
|
337
|
-
};
|
|
338
|
-
const FUND_MAX = 10_000;
|
|
339
|
-
/** Dollars as a person would write them: `$5`, `$0.10`, `$10,000`. */
|
|
340
|
-
const dollars = (n) => `$${Number.isInteger(n) ? n.toLocaleString('en-US') : n.toFixed(2)}`;
|
|
341
|
-
/** Refuses an amount the way to pay can't take, naming the range for that way, before anything is sent. The server checks it again. */
|
|
342
|
-
function checkFundAmount(method, amount) {
|
|
343
|
-
const way = FUND_WAYS[method];
|
|
344
|
-
if (!way || (amount >= way.min && amount <= FUND_MAX))
|
|
345
|
-
return;
|
|
346
|
-
const hint = amount < way.min ? (method === 'card' ? ` For less than ${dollars(way.min)}, pay with --coin usdc.` : '') : ' Add it in smaller payments.';
|
|
347
|
-
die(`${way.label} ${dollars(way.min)} to ${dollars(FUND_MAX)} at a time. You asked for ${dollars(amount)}.${hint}`, 'fund_usage');
|
|
348
|
-
}
|
|
349
|
-
/** Manage a workspace from the terminal: balance, keys, funding, recovery and revocation. */
|
|
350
|
-
export async function workspaceCommand(input) {
|
|
351
|
-
const { subcommand, flags, io, env, argv } = input;
|
|
352
|
-
if (argv[0] === 'workspace' && subcommand !== undefined && !WORKSPACE_WORDS.includes(subcommand)) {
|
|
353
|
-
const guess = closestCommand(subcommand, WORKSPACE_WORDS);
|
|
354
|
-
die(`Unknown phantom workspace subcommand "${subcommand}".${guess ? ` Did you mean phantom workspace ${guess}?` : ''} It takes: ${WORKSPACE_WORDS.join(', ')}.`, 'workspace_usage');
|
|
355
|
-
}
|
|
356
|
-
if (argv[0] === 'keys') {
|
|
357
|
-
if (subcommand === 'saved' || subcommand === 'save' || subcommand === 'show' || subcommand === 'rm') {
|
|
358
|
-
// Only the flags the key command reads pass through; --copy must, or `keys show --copy` would print the key.
|
|
359
|
-
return keyCommand({
|
|
360
|
-
...input,
|
|
361
|
-
flags: {
|
|
362
|
-
...(flags.balance ? { balance: flags.balance } : {}),
|
|
363
|
-
...(flags.copy ? { copy: flags.copy } : {}),
|
|
364
|
-
},
|
|
365
|
-
subcommand: subcommand === 'saved' ? 'list' : subcommand,
|
|
366
|
-
});
|
|
367
|
-
}
|
|
368
|
-
const remoteCommands = new Set(['list', 'create', 'rotate', 'revoke', 'set', undefined]);
|
|
369
|
-
if (!remoteCommands.has(subcommand)) {
|
|
370
|
-
return keyCommand({ ...input, subcommand });
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
const command = subcommand ?? 'status';
|
|
374
|
-
if (command === 'import' && argv[0] === 'workspace') {
|
|
375
|
-
if (typeof flags.file !== 'string')
|
|
376
|
-
die('Use phantom workspace import --file <recovery-file>.');
|
|
377
|
-
const notRecovery = `${flags.file} is not a recovery file from phantom workspace export.`;
|
|
378
|
-
const recovery = readJsonFile(flags.file, notRecovery);
|
|
379
|
-
if (!recovery || recovery.version !== 1)
|
|
380
|
-
die(notRecovery, 'file_not_json');
|
|
381
|
-
await wire(base(input), 'GET', '/workspaces/' + encodeURIComponent(recovery.workspace_id), undefined, recovery.management_credential);
|
|
382
|
-
writeSecret(env, credentialPath(env), JSON.stringify({ ...recovery, base_url: base(input), recovery }));
|
|
383
|
-
io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} Workspace restored. Make a new key with phantom keys create.\n` : JSON.stringify({ imported: true, workspace_id: recovery.workspace_id }) + '\n');
|
|
384
|
-
return 0;
|
|
385
|
-
}
|
|
386
|
-
const saved = credentials(input);
|
|
387
|
-
const endpoint = '/workspaces/' + encodeURIComponent(saved.workspace_id);
|
|
388
|
-
if (command === 'export') {
|
|
389
|
-
if (!saved.recovery)
|
|
390
|
-
die('This is an account workspace. Sign in to recover it on another computer.');
|
|
391
|
-
if (typeof flags.file !== 'string')
|
|
392
|
-
die('Use phantom workspace export --file <path>.');
|
|
393
|
-
try {
|
|
394
|
-
writeFileSync(flags.file, JSON.stringify(saved.recovery, null, 2), {
|
|
395
|
-
mode: 0o600,
|
|
396
|
-
flag: 'wx',
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
catch (err) {
|
|
400
|
-
writeFailure(err, flags.file);
|
|
401
|
-
}
|
|
402
|
-
const keepPrivate = 'Keep that file private: it can manage this workspace.';
|
|
403
|
-
io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} Recovery saved to ${flags.file}. ${keepPrivate}\n` : JSON.stringify({ exported: true, file: flags.file, note: keepPrivate }) + '\n');
|
|
404
|
-
return 0;
|
|
405
|
-
}
|
|
406
|
-
if (command === 'create' || command === 'rotate') {
|
|
407
|
-
if (flags.save === true)
|
|
408
|
-
die('--save requires a key name.');
|
|
409
|
-
// Checked before anything is sent: a mistyped limit must not turn into "no limit".
|
|
410
|
-
const typedLimit = limitFlag(flags, 'limit', true);
|
|
411
|
-
// keys create at a terminal with nothing given: a short form (name, then limit), and the key to hand over.
|
|
412
|
-
if (command === 'create' && flags.save === undefined && flags.limit === undefined) {
|
|
413
|
-
const pick = pickIo(input);
|
|
414
|
-
if (pick)
|
|
415
|
-
return newKeyForm(input, pick, saved, endpoint);
|
|
416
|
-
}
|
|
417
|
-
const which = command === 'rotate' ? await whichKey(input, saved, endpoint, 'rotate') : null;
|
|
418
|
-
if (command === 'rotate' && which === null)
|
|
419
|
-
return 0;
|
|
420
|
-
const id = which?.id ?? null;
|
|
421
|
-
// Rotating a key saved on this computer replaces that saved copy, whatever its name.
|
|
422
|
-
const mine = id ? savedNameFor(env, id) : null;
|
|
423
|
-
const name = typeof flags.save === 'string' ? flags.save : (mine ?? 'default');
|
|
424
|
-
const target = name === 'default' ? keyPath(env) : namedKeyPath(env, name);
|
|
425
|
-
const replacing = existsSync(target);
|
|
426
|
-
if (replacing && name !== mine)
|
|
427
|
-
die(`A key is already saved here as "${name}". Pick another name with --save <name>.`, 'key_exists');
|
|
428
|
-
const limit = typedLimit ?? null;
|
|
429
|
-
const result = await wire(saved.base_url, 'POST', command === 'create' ? endpoint + '/keys' : endpoint + '/keys/' + String(id), command === 'create' ? { name, limit_usd: limit } : { action: 'rotate' }, saved.management_credential);
|
|
430
|
-
saveIssuedKey(input, name, result.api_key, { replace: replacing, rotated: command === 'rotate' });
|
|
431
|
-
io.stdout(showsScreen(input)
|
|
432
|
-
? keyChangeScreen(command === 'create' ? 'created' : 'rotated', name, {
|
|
433
|
-
env,
|
|
434
|
-
color: colorOn(env, io.stdoutIsTTY),
|
|
435
|
-
storage: keychainOn(env) ? 'macOS Keychain' : 'private files',
|
|
436
|
-
limit,
|
|
437
|
-
}) + '\n'
|
|
438
|
-
: JSON.stringify({ saved_as: name }) + '\n');
|
|
439
|
-
return 0;
|
|
440
|
-
}
|
|
441
|
-
if (command === 'revoke') {
|
|
442
|
-
const which = await whichKey(input, saved, endpoint, 'revoke');
|
|
443
|
-
if (which === null)
|
|
444
|
-
return 0;
|
|
445
|
-
// At a terminal, revoking asks first and names the key: it can't be undone.
|
|
446
|
-
const pick = flags['yes'] ? null : pickIo(input);
|
|
447
|
-
if (pick) {
|
|
448
|
-
const go = await choose({ ...pick, esc: 'back' }, `Revoke ${which.name}?`, [
|
|
449
|
-
{
|
|
450
|
-
label: `Revoke ${which.name}`,
|
|
451
|
-
hint: 'anything using it stops working at once; its credit stays',
|
|
452
|
-
value: true,
|
|
453
|
-
},
|
|
454
|
-
{ label: 'Cancel', hint: 'keep it', value: false },
|
|
455
|
-
], 1);
|
|
456
|
-
if (!go) {
|
|
457
|
-
io.stderr(' Nothing was changed.\n');
|
|
458
|
-
return 0;
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
await wire(saved.base_url, 'DELETE', endpoint + '/keys/' + which.id, undefined, saved.management_credential);
|
|
462
|
-
io.stdout(showsScreen(input)
|
|
463
|
-
? keyChangeScreen('revoked', null, {
|
|
464
|
-
env,
|
|
465
|
-
color: colorOn(env, io.stdoutIsTTY),
|
|
466
|
-
}) + '\n'
|
|
467
|
-
: JSON.stringify({ revoked: true, id: which.id }) + '\n');
|
|
468
|
-
return 0;
|
|
469
|
-
}
|
|
470
|
-
if (command === 'set') {
|
|
471
|
-
// Every value is checked before the server is asked anything, so a typo changes nothing.
|
|
472
|
-
const typed = {
|
|
473
|
-
limit_usd: limitFlag(flags, 'limit', true),
|
|
474
|
-
budget_usd: limitFlag(flags, 'budget', true),
|
|
475
|
-
period_days: limitFlag(flags, 'period'),
|
|
476
|
-
rate_usd_per_min: limitFlag(flags, 'rate', true),
|
|
477
|
-
};
|
|
478
|
-
for (const k of ['name', 'policy-file'])
|
|
479
|
-
if (flags[k] === true)
|
|
480
|
-
die(`--${k} needs a value.`, 'key_usage');
|
|
481
|
-
// No change given, at a terminal: the usual change, a spending limit, as a picker. In a pipe there is no one to ask.
|
|
482
|
-
const anyChange = ['limit', 'budget', 'period', 'rate', 'name', 'policy-file', 'clear-policy'].some((k) => flags[k] !== undefined);
|
|
483
|
-
const pick = anyChange ? null : pickIo(input);
|
|
484
|
-
if (!anyChange && !pick)
|
|
485
|
-
die('Nothing was changed. Say what to change: --limit <USD|none>, --budget <USD|none> with --period <days>, --rate <USD|none>, --name <name>, --policy-file <path> or --clear-policy.', 'key_usage');
|
|
486
|
-
const which = await whichKey(input, saved, endpoint, 'change');
|
|
487
|
-
if (which === null)
|
|
488
|
-
return 0;
|
|
489
|
-
const id = which.id;
|
|
490
|
-
if (pick) {
|
|
491
|
-
const limit = await chooseLimit(pick);
|
|
492
|
-
if (limit === undefined)
|
|
493
|
-
return 0;
|
|
494
|
-
typed.limit_usd = limit;
|
|
495
|
-
}
|
|
496
|
-
const body = {};
|
|
497
|
-
for (const [field, value] of Object.entries(typed))
|
|
498
|
-
if (value !== undefined)
|
|
499
|
-
body[field] = value;
|
|
500
|
-
if (typeof flags.name === 'string')
|
|
501
|
-
body.name = flags.name;
|
|
502
|
-
if (typeof flags['policy-file'] === 'string')
|
|
503
|
-
body.route_policy = readJsonFile(flags['policy-file'], `${flags['policy-file']} is not valid JSON. It should hold a route policy, as phantom route set --file does.`);
|
|
504
|
-
if (flags['clear-policy'])
|
|
505
|
-
body.route_policy = null;
|
|
506
|
-
const result = await wire(saved.base_url, 'PATCH', endpoint + '/keys/' + id, body, saved.management_credential);
|
|
507
|
-
io.stdout(showsScreen(input)
|
|
508
|
-
? keyChangeScreen('updated', null, {
|
|
509
|
-
env,
|
|
510
|
-
color: colorOn(env, io.stdoutIsTTY),
|
|
511
|
-
}) + '\n'
|
|
512
|
-
: JSON.stringify(result) + '\n');
|
|
513
|
-
return 0;
|
|
514
|
-
}
|
|
515
|
-
if (command === 'delete') {
|
|
516
|
-
// Deleting takes the keys and saved sign-ins with it, so at a terminal it asks first and says what goes.
|
|
517
|
-
const pick = flags['yes'] ? null : pickIo(input);
|
|
518
|
-
if (pick) {
|
|
519
|
-
const go = await choose({ ...pick, esc: 'back' }, 'Delete this workspace?', [
|
|
520
|
-
{
|
|
521
|
-
label: 'Delete workspace',
|
|
522
|
-
hint: 'takes its keys and saved sign-ins with it; credit must be spent first and it cannot be undone',
|
|
523
|
-
value: true,
|
|
524
|
-
},
|
|
525
|
-
{ label: 'Cancel', hint: 'keep it', value: false },
|
|
526
|
-
], 1);
|
|
527
|
-
if (!go) {
|
|
528
|
-
io.stderr(' Nothing was changed.\n');
|
|
529
|
-
return 0;
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
const result = await wire(saved.base_url, 'DELETE', endpoint, undefined, saved.management_credential);
|
|
533
|
-
// The workspace is gone, so the credential saved here points at nothing.
|
|
534
|
-
removeSecret(credentialPath(env));
|
|
535
|
-
io.stdout(showsScreen(input)
|
|
536
|
-
? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} Workspace deleted. Its keys and saved sign-ins are gone.\n`
|
|
537
|
-
: JSON.stringify(result) + '\n');
|
|
538
|
-
return 0;
|
|
539
|
-
}
|
|
540
|
-
if (command === 'revoke-access') {
|
|
541
|
-
if (typeof flags.id !== 'string')
|
|
542
|
-
die('Use --id <management-id> from phantom workspace status.');
|
|
543
|
-
// A full id is used as it is. The start of one is looked up in the workspace's sign-ins.
|
|
544
|
-
const accessId = /^[0-9a-f]{64}$/i.test(flags.id) ? flags.id : findAccess((await wire(saved.base_url, 'GET', endpoint, undefined, saved.management_credential)).access ?? [], flags.id);
|
|
545
|
-
await wire(saved.base_url, 'DELETE', endpoint + '/access/' + accessId, undefined, saved.management_credential);
|
|
546
|
-
io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} That sign-in can no longer manage this workspace.\n` : JSON.stringify({ revoked: true, id: accessId }) + '\n');
|
|
547
|
-
return 0;
|
|
548
|
-
}
|
|
549
|
-
if (command === 'payment') {
|
|
550
|
-
if (typeof flags.id !== 'string')
|
|
551
|
-
die('Use --id <payment-id> from phantom workspace fund.');
|
|
552
|
-
const payment = await wire(saved.base_url, 'GET', endpoint + '/payments/' + flags.id, undefined, saved.management_credential);
|
|
553
|
-
io.stdout((showsScreen(input) ? paymentScreen(payment, { env, color: colorOn(env, io.stdoutIsTTY) }) : JSON.stringify(payment)) + '\n');
|
|
554
|
-
return 0;
|
|
555
|
-
}
|
|
556
|
-
if (command === 'fund') {
|
|
557
|
-
if (flags.pay)
|
|
558
|
-
die('--pay has been removed. Use --card or --coin.');
|
|
559
|
-
if (flags.coin === true)
|
|
560
|
-
die(`--coin needs usdc or usdc-base. ${FUND_EXAMPLE}`);
|
|
561
|
-
if (flags.card && flags.coin !== undefined)
|
|
562
|
-
die(`Pick one: --card or --coin, not both. ${FUND_EXAMPLE}`, 'fund_usage');
|
|
563
|
-
let amount = dollarsFlag(flags);
|
|
564
|
-
let method = flags.card ? 'card' : flags.coin;
|
|
565
|
-
// At a terminal, whatever is missing is asked for: first how much, then how to pay.
|
|
566
|
-
const pick = amount === undefined || !method ? pickIo(input) : null;
|
|
567
|
-
if (pick && amount === undefined) {
|
|
568
|
-
amount =
|
|
569
|
-
(await choose(pick, 'How much credit do you want to add?', [5, 10, 25, 50, 100].map((n) => ({ label: `$${n}`, value: n })), 1)) ?? undefined;
|
|
570
|
-
if (amount === undefined)
|
|
571
|
-
return leaveFund(input);
|
|
572
|
-
}
|
|
573
|
-
if (pick && !method) {
|
|
574
|
-
method =
|
|
575
|
-
(await choose({ ...pick, esc: 'back' }, 'How do you want to pay?', [
|
|
576
|
-
{
|
|
577
|
-
label: 'Card',
|
|
578
|
-
hint: "on Stripe's page, plus Stripe's card fee",
|
|
579
|
-
value: 'card',
|
|
580
|
-
},
|
|
581
|
-
{ label: 'USDC', hint: 'from a Solana wallet, to Stripe', value: 'usdc' },
|
|
582
|
-
])) ?? undefined;
|
|
583
|
-
if (!method)
|
|
584
|
-
return leaveFund(input);
|
|
585
|
-
}
|
|
586
|
-
if (amount === undefined || !method)
|
|
587
|
-
die(`fund needs an amount and a way to pay. ${FUND_EXAMPLE}`, 'fund_usage');
|
|
588
|
-
checkFundAmount(method, amount);
|
|
589
|
-
const answer = await wire(saved.base_url, 'POST', endpoint + '/fund', {
|
|
590
|
-
method: method === 'card' ? 'card' : 'crypto',
|
|
591
|
-
amount_usd: amount,
|
|
592
|
-
coin: method === 'card' ? 'usdc' : method,
|
|
593
|
-
}, saved.management_credential);
|
|
594
|
-
// The server fills a field a way to pay doesn't use with an empty string (a Base payment has no Solana reference). Leave those out.
|
|
595
|
-
const result = Object.fromEntries(Object.entries(answer).filter(([, value]) => value !== ''));
|
|
596
|
-
io.stdout((showsScreen(input)
|
|
597
|
-
? fundScreen(result, {
|
|
598
|
-
env,
|
|
599
|
-
color: colorOn(env, io.stdoutIsTTY),
|
|
600
|
-
opened: Boolean(result.checkout_url) && !flags['no-browser'],
|
|
601
|
-
})
|
|
602
|
-
: JSON.stringify(result)) + '\n');
|
|
603
|
-
if (result.checkout_url && !flags['no-browser'])
|
|
604
|
-
openUrl(result.checkout_url);
|
|
605
|
-
// At a terminal, wait for the payment to land, so nobody wonders whether it worked.
|
|
606
|
-
const watch = pickIo(input);
|
|
607
|
-
if (watch && result.payment_id)
|
|
608
|
-
await waitForPayment(input, watch, saved, endpoint, result.payment_id);
|
|
609
|
-
return 0;
|
|
610
|
-
}
|
|
611
|
-
const view = await wire(saved.base_url, 'GET', endpoint, undefined, saved.management_credential);
|
|
612
|
-
if (showsScreen(input)) {
|
|
613
|
-
const style = { env, color: colorOn(env, io.stdoutIsTTY) };
|
|
614
|
-
io.stdout((argv[0] === 'keys' ? keysScreen(view.keys, style) : workspaceScreen(view, style)) + '\n');
|
|
615
|
-
return 0;
|
|
616
|
-
}
|
|
617
|
-
io.stdout(JSON.stringify(argv[0] === 'keys' ? view.keys : view, null, 2) + '\n');
|
|
618
|
-
return 0;
|
|
619
|
-
}
|
|
620
|
-
/** Forget local management credentials and revoke server management access, leaving server-side keys and recovery files valid. True when there was a workspace sign-in to forget. */
|
|
621
|
-
export async function forgetWorkspace(env, baseUrl) {
|
|
622
|
-
const file = credentialPath(env);
|
|
623
|
-
if (!existsSync(file))
|
|
624
|
-
return false;
|
|
625
|
-
{
|
|
626
|
-
try {
|
|
627
|
-
const saved = JSON.parse(readSecret(env, file));
|
|
628
|
-
// `workspace import` saves the recovery file's own credential as the sign-in. Revoking that on the
|
|
629
|
-
// server would kill the recovery file, so a sign-in that is the recovery credential is only forgotten here.
|
|
630
|
-
const isRecoveryFile = saved?.recovery?.management_credential === saved?.management_credential;
|
|
631
|
-
if (saved?.workspace_id && saved?.management_credential && !isRecoveryFile) {
|
|
632
|
-
const url = httpsOnly(baseUrl || env.PHANTOM_BASE_URL || saved.base_url || DEFAULT_BASE_URL).replace(/\/$/, '');
|
|
633
|
-
await wire(url, 'POST', '/workspaces/' + encodeURIComponent(saved.workspace_id) + '/logout', {}, saved.management_credential).catch(() => { });
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
catch {
|
|
637
|
-
// Ignore read or parse errors during forget
|
|
638
|
-
}
|
|
639
|
-
removeSecret(file);
|
|
640
|
-
}
|
|
641
|
-
return true;
|
|
642
|
-
}
|
|
643
|
-
/** The working fund command every fund error shows, so one try is enough. */
|
|
644
|
-
const FUND_EXAMPLE = 'For example: phantom fund --amount 10 --card (or --coin usdc-base).';
|
|
645
|
-
/**
|
|
646
|
-
* `--amount` as dollars: `10`, `10.50` or `$10`. A bare `--amount` is
|
|
647
|
-
* usually `--amount $5` after the shell has replaced `$5` with nothing, so
|
|
648
|
-
* the message says to leave out the $.
|
|
649
|
-
*/
|
|
650
|
-
export function dollarsFlag(flags) {
|
|
651
|
-
const raw = flags['amount'];
|
|
652
|
-
if (raw === undefined)
|
|
653
|
-
return undefined;
|
|
654
|
-
if (raw === true || raw.trim() === '')
|
|
655
|
-
die(`--amount needs a number of dollars, like --amount 10. Leave out the $: the shell drops "$5". ${FUND_EXAMPLE}`, 'fund_usage');
|
|
656
|
-
const n = Number(raw.trim().replace(/^\$/, ''));
|
|
657
|
-
if (!Number.isFinite(n) || n <= 0)
|
|
658
|
-
die(`--amount must be a number of dollars above 0, not "${raw}". ${FUND_EXAMPLE}`, 'fund_usage');
|
|
659
|
-
return n;
|
|
660
|
-
}
|
|
661
|
-
/** Esc out of fund's pickers: back to the menu if it started this, otherwise say nothing was charged. */
|
|
662
|
-
function leaveFund(input) {
|
|
663
|
-
if (input.io.fromMenu)
|
|
664
|
-
throw new BackToMenu();
|
|
665
|
-
input.io.stderr(' Nothing was charged.\n');
|
|
666
|
-
return 0;
|
|
667
|
-
}
|
|
668
|
-
/** Keys that still work. A rotate or revoke leaves the old key in the list, turned off. */
|
|
669
|
-
const stillOn = (keys) => keys.filter((k) => k.is_active !== false);
|
|
670
|
-
/**
|
|
671
|
-
* The key a key command acts on. --id may be the id, its first few
|
|
672
|
-
* characters, the key's name, or the start of the key, the way people
|
|
673
|
-
* remember it. With no --id at a terminal, it asks with a picker. Null means
|
|
674
|
-
* Esc: nothing was done.
|
|
675
|
-
*/
|
|
676
|
-
async function whichKey(input, saved, endpoint, verb) {
|
|
677
|
-
const { flags } = input;
|
|
678
|
-
const view = await wire(saved.base_url, 'GET', endpoint, undefined, saved.management_credential);
|
|
679
|
-
const named = (id) => ({
|
|
680
|
-
id,
|
|
681
|
-
name: view.keys.find((k) => k.id === id)?.name ?? 'Key',
|
|
682
|
-
});
|
|
683
|
-
if (typeof flags.id === 'string')
|
|
684
|
-
return named(findKey(view.keys, flags.id));
|
|
685
|
-
const pick = pickIo(input);
|
|
686
|
-
if (!pick)
|
|
687
|
-
die(`Say which key with --id: its id, name or start. For example: phantom keys ${verb === 'change' ? 'set' : verb} --id CI${verb === 'change' ? ' --limit 5' : ''}`, 'key_usage');
|
|
688
|
-
const chosen = await choose(pick, `Which key do you want to ${verb}?`, stillOn(view.keys).map((k) => ({
|
|
689
|
-
label: k.name ?? 'Key',
|
|
690
|
-
hint: `${k.prefix ?? ''} · id ${k.id.slice(0, 8)} · spent $${(k.spent_usd ?? 0).toFixed(2)}`,
|
|
691
|
-
value: k.id,
|
|
692
|
-
})));
|
|
693
|
-
if (chosen === null && input.io.fromMenu)
|
|
694
|
-
throw new BackToMenu();
|
|
695
|
-
if (chosen === null)
|
|
696
|
-
input.io.stderr(' Nothing was changed.\n');
|
|
697
|
-
return chosen === null ? null : named(chosen);
|
|
698
|
-
}
|
|
699
|
-
/**
|
|
700
|
-
* Finds one key by id, the start of its id, its name, or the start of the key itself. Refuses when none or more than one matches.
|
|
701
|
-
* Keys that are turned off never match: after a rotate, the old key and the new one share a name.
|
|
702
|
-
*/
|
|
703
|
-
export function findKey(allKeys, typed) {
|
|
704
|
-
const keys = stillOn(allKeys);
|
|
705
|
-
const t = typed.trim().toLowerCase();
|
|
706
|
-
const matching = (list) => {
|
|
707
|
-
const hits = list.filter((k) => k.id.toLowerCase() === t);
|
|
708
|
-
return hits.length ? hits : list.filter((k) => (t.length >= 4 && k.id.toLowerCase().startsWith(t)) || k.name?.toLowerCase() === t || (t.length >= 8 && k.prefix?.toLowerCase().startsWith(t)));
|
|
709
|
-
};
|
|
710
|
-
const loose = matching(keys);
|
|
711
|
-
const label = (k) => `${k.name ?? 'Key'} (${k.id.slice(0, 8)})`;
|
|
712
|
-
if (loose.length === 1)
|
|
713
|
-
return loose[0].id;
|
|
714
|
-
if (!loose.length) {
|
|
715
|
-
const off = matching(allKeys.filter((k) => k.is_active === false));
|
|
716
|
-
if (off.length)
|
|
717
|
-
die(`"${typed}" is a key that is turned off (${off.map(label).join(', ')}). Your keys that work: ${keys.map(label).join(', ') || 'none'}.`, 'key_not_found');
|
|
718
|
-
// A few characters that do start a key's id are a start that is too short, not a wrong name.
|
|
719
|
-
const tooShort = t.length < 4 && keys.some((k) => k.id.toLowerCase().startsWith(t));
|
|
720
|
-
die(`No key matches "${typed}".${tooShort ? ' Type at least 4 characters of an id, or the key\'s name.' : ''} Your keys: ${keys.map(label).join(', ') || 'none yet'}.`, 'key_not_found');
|
|
721
|
-
}
|
|
722
|
-
die(`"${typed}" matches more than one key: ${loose.map(label).join(', ')}. Use more of the id.`, 'key_ambiguous');
|
|
723
|
-
}
|
|
724
|
-
/** The name a key with this id is saved under on this computer, if any: `default` for the login key. */
|
|
725
|
-
function savedNameFor(env, id) {
|
|
726
|
-
const hash = (key) => createHash('sha256').update(key.trim()).digest('hex');
|
|
727
|
-
if (existsSync(keyPath(env)) && hash(readSecret(env, keyPath(env))) === id)
|
|
728
|
-
return 'default';
|
|
729
|
-
for (const k of listNamedKeys(env).keys) {
|
|
730
|
-
try {
|
|
731
|
-
if (hash(readNamedKey(env, k.name)) === id)
|
|
732
|
-
return k.name;
|
|
733
|
-
}
|
|
734
|
-
catch {
|
|
735
|
-
// A saved key that can't be read is skipped: it can't be the one being rotated.
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
return null;
|
|
739
|
-
}
|
|
740
|
-
/** A limit picker: no limit, or a few round amounts. undefined means Esc. */
|
|
741
|
-
async function chooseLimit(pick) {
|
|
742
|
-
const limit = await choose({ ...pick, esc: 'back' }, 'How much may this key spend in total?', [
|
|
743
|
-
{
|
|
744
|
-
label: 'No limit',
|
|
745
|
-
hint: 'it can spend the whole workspace balance',
|
|
746
|
-
value: 'none',
|
|
747
|
-
},
|
|
748
|
-
...[5, 10, 25, 50, 100].map((n) => ({
|
|
749
|
-
label: `$${n}`,
|
|
750
|
-
hint: 'then it stops working until you raise it',
|
|
751
|
-
value: n,
|
|
752
|
-
})),
|
|
753
|
-
]);
|
|
754
|
-
return limit === null ? undefined : limit === 'none' ? null : limit;
|
|
755
|
-
}
|
|
756
|
-
/**
|
|
757
|
-
* keys create at a terminal: name the key, pick a limit, create it, and save
|
|
758
|
-
* it here. Then, on a Mac, offer to copy it to the clipboard to hand to a
|
|
759
|
-
* teammate. The key is never printed: only keys show and rotate print one.
|
|
760
|
-
*/
|
|
761
|
-
async function newKeyForm(input, pick, saved, endpoint) {
|
|
762
|
-
const { env, io } = input;
|
|
763
|
-
const name = await askText({ ...pick, esc: 'back' }, 'Name this key', {
|
|
764
|
-
placeholder: 'for example ci or dana',
|
|
765
|
-
check: (text) => (!/^[a-z0-9][a-z0-9_-]{0,31}$/i.test(text) ? 'Start with a letter or number; then letters, numbers, - and _, up to 32.' : existsSync(namedKeyPath(env, text)) ? `A key is already saved here as "${text}". Type another name.` : null),
|
|
766
|
-
});
|
|
767
|
-
if (name === null)
|
|
768
|
-
return leaveKeys(input);
|
|
769
|
-
const limit = await chooseLimit(pick);
|
|
770
|
-
if (limit === undefined)
|
|
771
|
-
return leaveKeys(input);
|
|
772
|
-
const result = await wire(saved.base_url, 'POST', endpoint + '/keys', { name, limit_usd: limit }, saved.management_credential);
|
|
773
|
-
saveIssuedKey(input, name, result.api_key, { rotated: false });
|
|
774
|
-
const style = {
|
|
775
|
-
env,
|
|
776
|
-
color: colorOn(env, io.stdoutIsTTY),
|
|
777
|
-
storage: keychainOn(env) ? 'macOS Keychain' : 'private files',
|
|
778
|
-
limit,
|
|
779
|
-
};
|
|
780
|
-
io.stdout(keyChangeScreen('created', name, style) + '\n');
|
|
781
|
-
if (process.platform === 'darwin' && onPath('pbcopy')) {
|
|
782
|
-
const copy = await choose({ ...pick, esc: 'back' }, 'Hand it to someone?', [
|
|
783
|
-
{
|
|
784
|
-
label: 'Copy the key to the clipboard',
|
|
785
|
-
hint: 'then paste it to your teammate; it is not shown here',
|
|
786
|
-
value: true,
|
|
787
|
-
},
|
|
788
|
-
{ label: 'No, keep it saved here only', value: false },
|
|
789
|
-
]);
|
|
790
|
-
if (copy) {
|
|
791
|
-
spawnSync('pbcopy', { input: result.api_key });
|
|
792
|
-
io.stderr(` ${paint(env, colorOn(env, io.isTTY)).lime('✓')} Copied. Paste it somewhere private: it works like a password.\n`);
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
return 0;
|
|
796
|
-
}
|
|
797
|
-
/**
|
|
798
|
-
* Saves a key the server has just made. When the save fails (a read-only file, a locked Keychain over
|
|
799
|
-
* SSH), this computer is the only place the key ever exists, so it goes to stderr once with how to
|
|
800
|
-
* save it, and the command exits 1. After a rotate the old key is already off, and the message says so.
|
|
801
|
-
*/
|
|
802
|
-
function saveIssuedKey(input, name, key, opts) {
|
|
803
|
-
const { env, io } = input;
|
|
804
|
-
try {
|
|
805
|
-
if (name === 'default')
|
|
806
|
-
saveApiKey(env, key);
|
|
807
|
-
else
|
|
808
|
-
saveNamedKey(env, name, key, { replace: opts.replace });
|
|
809
|
-
}
|
|
810
|
-
catch (error) {
|
|
811
|
-
const why = error instanceof Error ? error.message : String(error);
|
|
812
|
-
const how = name === 'default' ? 'phantom login --paste (paste the key when it asks)' : `phantom keys save ${name} (paste the key when it asks)`;
|
|
813
|
-
io.stderr(`\nphantom made your new key but could not save it on this computer: ${why}\n` +
|
|
814
|
-
(opts.rotated ? 'Your old key is turned off, so this new key is the only one that works.\n' : '') +
|
|
815
|
-
'This is the only time it is shown. Copy it somewhere private now; it works like a password:\n\n' +
|
|
816
|
-
` ${key}\n\n` +
|
|
817
|
-
`Save it once the problem is fixed with: ${how}\n`);
|
|
818
|
-
die('The new key was not saved here.', 'key_not_saved');
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
/** Esc out of a key form: back to the menu if it started this, otherwise say nothing changed. */
|
|
822
|
-
function leaveKeys(input) {
|
|
823
|
-
if (input.io.fromMenu)
|
|
824
|
-
throw new BackToMenu();
|
|
825
|
-
input.io.stderr(' Nothing was changed.\n');
|
|
826
|
-
return 0;
|
|
827
|
-
}
|
|
828
|
-
/** How often fund checks whether a payment has landed, and for how long, in milliseconds. */
|
|
829
|
-
const PAYMENT_POLL_MS = 2000;
|
|
830
|
-
const PAYMENT_WAIT_MS = 15 * 60 * 1000;
|
|
831
|
-
/**
|
|
832
|
-
* After fund opens the payment page: a spinner until the payment lands, then
|
|
833
|
-
* the paid screen. Esc stops waiting (the payment still goes through if it's
|
|
834
|
-
* finished); Ctrl+C stops everything.
|
|
835
|
-
*/
|
|
836
|
-
async function waitForPayment(input, pick, saved, endpoint, paymentId) {
|
|
837
|
-
const { env, io } = input;
|
|
838
|
-
const p = paint(env, colorOn(env, io.isTTY));
|
|
839
|
-
io.stderr(` ${p.dim('esc to stop waiting')}\n`);
|
|
840
|
-
const spinner = colorOn(env, io.isTTY) ? waiting(io.stderr, p, 'Waiting for your payment…', 'Payment received.') : null;
|
|
841
|
-
const cancel = cancelKeys((pick.keys ?? keyboard)());
|
|
842
|
-
const deadline = Date.now() + PAYMENT_WAIT_MS;
|
|
843
|
-
try {
|
|
844
|
-
while (Date.now() < deadline) {
|
|
845
|
-
const payment = await wire(saved.base_url, 'GET', endpoint + '/payments/' + encodeURIComponent(paymentId), undefined, saved.management_credential);
|
|
846
|
-
if (payment.status === 'completed') {
|
|
847
|
-
spinner?.done();
|
|
848
|
-
io.stdout(paymentScreen(payment, { env, color: colorOn(env, io.stdoutIsTTY) }) + '\n');
|
|
849
|
-
// The new balance right away, so nobody has to go and check that it arrived.
|
|
850
|
-
const view = await wire(saved.base_url, 'GET', endpoint, undefined, saved.management_credential);
|
|
851
|
-
if (typeof view.balance_usd === 'number')
|
|
852
|
-
io.stdout(` ${p.dim('Workspace balance now')} ${p.bold(`$${view.balance_usd.toFixed(2)}`)}\n`);
|
|
853
|
-
return;
|
|
854
|
-
}
|
|
855
|
-
const key = await Promise.race([new Promise((r) => setTimeout(() => r(null), PAYMENT_POLL_MS)), cancel.pressed]);
|
|
856
|
-
if (key === 'ctrl-c')
|
|
857
|
-
throw new Cancelled();
|
|
858
|
-
if (key) {
|
|
859
|
-
spinner?.stop();
|
|
860
|
-
io.stderr(` ${p.dim('Stopped waiting. If you finish paying, the credit still arrives: check Balance.')}\n`);
|
|
861
|
-
return;
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
spinner?.stop();
|
|
865
|
-
io.stderr(` ${p.dim('No payment yet. If you finish paying, the credit still arrives: check Balance.')}\n`);
|
|
866
|
-
}
|
|
867
|
-
finally {
|
|
868
|
-
spinner?.stop();
|
|
869
|
-
cancel.close();
|
|
870
|
-
}
|
|
871
|
-
}
|