-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
249 lines (225 loc) · 8.01 KB
/
auth.ts
File metadata and controls
249 lines (225 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import { Command } from "commander";
import * as config from "../lib/config.js";
import { AUTH_PORT, getLoginUrl, performBrowserLogin, revokeToken } from "../lib/auth.js";
import { AdminClient } from "../lib/admin-client.js";
import type { App } from "../lib/admin-client.js";
import { CLIError, ErrorCode, exitWithError } from "../lib/errors.js";
import { printHuman, isJSONMode, debug } from "../lib/output.js";
import { promptAutocomplete, promptText } from "../lib/terminal-ui.js";
import { isInteractiveAllowed } from "../lib/interaction.js";
import { resolveAuthToken } from "../lib/resolve.js";
import { green, dim, bold, brand, maskIf, withSpinner } from "../lib/ui.js";
export function registerAuth(program: Command) {
const cmd = program
.command("auth")
.description("Authenticate with your Alchemy account")
.option("-y, --yes", "Skip confirmation prompt and open browser immediately");
cmd
.command("login", { isDefault: true })
.description("Log in via browser")
.option("--force", "Force re-authentication even if a valid token exists")
.option("-y, --yes", "Skip confirmation prompt and open browser immediately")
.action(async (opts: { force?: boolean; yes?: boolean }) => {
const yes = opts.yes || cmd.opts().yes;
try {
// Skip browser flow if we already have a valid token
if (!opts.force) {
const existing = resolveAuthToken();
if (existing) {
printHuman(
` ${green("✓")} Already authenticated\n` +
` ${dim("Token:")} ${maskIf(existing)}\n` +
` ${dim("Run")} alchemy auth login --force ${dim("to re-authenticate.")}\n`,
{ status: "already_authenticated" },
);
return;
}
}
// If --force, revoke the existing token server-side before re-authenticating
if (opts.force) {
const cfg = config.load();
if (cfg.auth_token) {
await revokeToken(cfg.auth_token);
config.save({ ...cfg, auth_token: undefined, auth_token_expires_at: undefined });
}
}
if (!isJSONMode()) {
console.log("");
console.log(` ${brand("◆")} ${bold("Alchemy Authentication")}`);
console.log(` ${dim("────────────────────────────────────")}`);
console.log("");
console.log(` ${dim(getLoginUrl(AUTH_PORT))}`);
console.log("");
}
if (!yes && !isJSONMode() && isInteractiveAllowed(program)) {
const answer = await promptText({
message: "Press Enter to open browser and link your Alchemy account",
cancelMessage: "Login cancelled.",
});
if (answer === null) return;
}
if (!isJSONMode()) {
console.log(` Opening browser to log in...`);
console.log(` ${dim("Waiting for authentication...")}`);
}
const result = await performBrowserLogin();
// Save token to config
const cfg = config.load();
config.save({
...cfg,
auth_token: result.token,
auth_token_expires_at: result.expiresAt,
});
const expiresAt = result.expiresAt;
printHuman(
` ${green("✓")} Logged in successfully\n` +
` ${dim("Token saved to")} ${config.configPath()}\n` +
` ${dim("Expires:")} ${expiresAt}\n`,
{
status: "authenticated",
expiresAt,
configPath: config.configPath(),
},
);
// After auth, try to fetch apps and let user select one
if (isInteractiveAllowed(program)) {
await selectAppAfterAuth(result.token);
}
process.exit(0);
} catch (err) {
exitWithError(
err instanceof CLIError
? err
: new CLIError(ErrorCode.AUTH_REQUIRED, String((err as Error).message)),
);
}
});
cmd
.command("status")
.description("Show current authentication status")
.action(() => {
try {
const cfg = config.load();
const validToken = resolveAuthToken(cfg);
if (!cfg.auth_token) {
printHuman(
` ${dim("Not authenticated. Run")} alchemy auth ${dim("to log in.")}\n`,
{ authenticated: false },
);
return;
}
if (!validToken) {
printHuman(
` ${dim("Session expired. Run")} alchemy auth ${dim("to log in again.")}\n`,
{ authenticated: false, expired: true },
);
return;
}
printHuman(
` ${green("✓")} Authenticated\n` +
` ${dim("Token:")} ${maskIf(validToken)}\n` +
` ${dim("Expires:")} ${cfg.auth_token_expires_at || "unknown"}\n`,
{
authenticated: true,
expired: false,
expiresAt: cfg.auth_token_expires_at,
},
);
} catch (err) {
exitWithError(err);
}
});
cmd
.command("logout")
.description("Clear saved authentication token")
.action(async () => {
try {
const cfg = config.load();
let revokeResult: Awaited<ReturnType<typeof revokeToken>> | undefined;
if (cfg.auth_token) {
revokeResult = await revokeToken(cfg.auth_token);
}
const { auth_token: _, auth_token_expires_at: __, ...rest } = cfg as Record<string, unknown>;
config.save(rest as config.Config);
if (!cfg.auth_token) {
printHuman(
` ${dim("No active session.")}\n`,
{ status: "no_session" },
);
} else if (revokeResult === "already_invalid") {
printHuman(
` ${green("✓")} Logged out ${dim("(token was already invalidated)")}\n`,
{ status: "logged_out", tokenAlreadyInvalid: true },
);
} else if (revokeResult === "server_error" || revokeResult === "network_error") {
printHuman(
` ${green("✓")} Logged out locally ${dim("(could not reach server to revoke token)")}\n`,
{ status: "logged_out", serverRevoked: false },
);
} else {
printHuman(
` ${green("✓")} Logged out\n`,
{ status: "logged_out" },
);
}
} catch (err) {
exitWithError(err);
}
});
}
export async function selectAppAfterAuth(authToken: string): Promise<void> {
let apps: App[];
try {
const admin = new AdminClient({ type: "auth_token", token: authToken });
const result = await withSpinner("Fetching apps…", "Apps fetched", () =>
admin.listAllApps(),
);
apps = result.apps;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
debug(`Failed to fetch apps: ${msg}`);
if (!isJSONMode()) {
console.error(` ${dim(`Could not fetch apps: ${msg}`)}`);
}
return;
}
if (apps.length === 0) {
console.log(` ${dim("No apps found. Create one at dashboard.alchemy.com")}`);
return;
}
let selectedApp: App;
if (apps.length === 1) {
selectedApp = apps[0];
console.log(` ${green("✓")} Auto-selected app: ${bold(selectedApp.name)}`);
} else {
console.log("");
const appId = await promptAutocomplete({
message: "Select an app",
placeholder: "Type to search by name",
options: apps.map((app) => ({
value: app.id,
label: app.name,
hint: `${app.chainNetworks.length} networks`,
})),
cancelMessage: "Skipped app selection.",
});
if (!appId) return;
const found = apps.find((a) => a.id === appId);
if (!found) return;
selectedApp = found;
}
// Save selected app to config
const cfg = config.load();
config.save({
...cfg,
app: {
id: selectedApp.id,
name: selectedApp.name,
apiKey: selectedApp.apiKey,
webhookApiKey: selectedApp.webhookApiKey,
},
});
console.log(
` ${dim("App")} ${selectedApp.name} ${dim("saved to config")}`,
);
}