-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprofile.ts
More file actions
174 lines (160 loc) · 5.35 KB
/
Copy pathprofile.ts
File metadata and controls
174 lines (160 loc) · 5.35 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
import { Command } from "commander";
import {
listProfiles,
getCurrentProfile,
setCurrentProfile,
createProfile,
deleteProfile,
loadConfig,
saveConfig,
validateUrl,
} from "../config.js";
import { printSuccess, printInfo, printError, printWarning } from "../output.js";
import { getTokenStatus } from "../token.js";
import { addExamples } from "./help.js";
export function registerProfileCommands(program: Command): void {
const profile = program.command("profile").description("Manage connection profiles");
const list = profile
.command("list")
.description("List all profiles")
.action(() => {
const profiles = listProfiles();
for (const p of profiles) {
const marker = p.active ? " *" : "";
console.log(`${p.name}${marker}`);
}
});
addExamples(list, [
{
description: "List all profiles (active profile marked with *)",
command: "geonic profile list",
},
]);
const use = profile
.command("use <name>")
.description("Switch active profile (auto-refreshes expired tokens)")
.action(async (name: string) => {
try {
setCurrentProfile(name);
} catch (err) {
printError((err as Error).message);
process.exit(1);
}
const config = loadConfig(name);
const tenantLabel = config.tenantId
? ` (tenant: ${config.availableTenants?.find((t) => t.tenantId === config.tenantId)?.name ?? config.tenantId})`
: "";
// Auto-refresh expired token if refreshToken is available
if (config.token && config.refreshToken && config.url) {
const status = getTokenStatus(config.token);
if (status.isExpired || status.isExpiringSoon) {
try {
const baseUrl = validateUrl(config.url);
const url = new URL("/auth/refresh", baseUrl).toString();
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken: config.refreshToken }),
});
if (response.ok) {
const data = (await response.json()) as Record<string, unknown>;
const newToken = (data.accessToken ?? data.token) as string | undefined;
const newRefreshToken = data.refreshToken as string | undefined;
if (newToken) {
config.token = newToken;
if (newRefreshToken) config.refreshToken = newRefreshToken;
saveConfig(config, name);
printSuccess(`Switched to profile "${name}"${tenantLabel}. Token refreshed.`);
return;
}
}
printWarning("Token refresh failed. You may need to re-login.");
} catch {
printWarning("Token refresh failed. You may need to re-login.");
}
}
}
printSuccess(`Switched to profile "${name}"${tenantLabel}.`);
});
addExamples(use, [
{
description: "Switch to staging profile",
command: "geonic profile use staging",
},
]);
const profileCreate = profile
.command("create <name>")
.description("Create a new profile")
.action((name: string) => {
try {
createProfile(name);
printSuccess(`Profile "${name}" created.`);
} catch (err) {
printError((err as Error).message);
process.exit(1);
}
});
addExamples(profileCreate, [
{
description: "Create a new profile for staging",
command: "geonic profile create staging",
},
]);
const del = profile
.command("delete <name>")
.description("Delete a profile")
.action((name: string) => {
try {
deleteProfile(name);
printSuccess(`Profile "${name}" deleted.`);
} catch (err) {
printError((err as Error).message);
process.exit(1);
}
});
addExamples(del, [
{
description: "Delete a profile",
command: "geonic profile delete staging",
},
]);
const show = profile
.command("show [name]")
.description("Show profile settings")
.action((name?: string) => {
const profileName = name ?? getCurrentProfile();
const config = loadConfig(profileName);
const entries = Object.entries(config).filter(([, v]) => v !== undefined);
if (entries.length === 0) {
printInfo(`Profile "${profileName}" has no settings.`);
return;
}
for (const [key, value] of entries) {
if (
(key === "token" || key === "refreshToken" || key === "apiKey") &&
typeof value === "string"
) {
console.log(`${key}: ***`);
} else if (key === "availableTenants" && Array.isArray(value)) {
console.log(`${key}:`);
for (const t of value as { tenantId: string; name?: string; role: string }[]) {
const label = t.name ? `${t.name} (${t.tenantId})` : t.tenantId;
const current = t.tenantId === config.tenantId ? " ← current" : "";
console.log(` - ${label} [${t.role}]${current}`);
}
} else {
console.log(`${key}: ${value}`);
}
}
});
addExamples(show, [
{
description: "Show current profile settings",
command: "geonic profile show",
},
{
description: "Show settings for a specific profile",
command: "geonic profile show production",
},
]);
}