-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsystemConfig.ts
More file actions
292 lines (259 loc) · 8.02 KB
/
Copy pathsystemConfig.ts
File metadata and controls
292 lines (259 loc) · 8.02 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import type { AuthClient } from "./authClient.js";
import { scrubTokens } from "./redact.js";
export type SystemConfig = Record<string, unknown>;
// Mirrors the instance's patch schema, which is strict: a key missing here is one
// `config apply` silently drops and `config set` refuses, so the two lists have to
// stay in step.
export const WRITABLE_KEYS = [
"app_name",
"default_roles",
"available_roles",
"login_methods",
"passkey_login_fallback_enabled",
"oauth_providers",
"lockout_policy",
"authenticator_policy",
"access_token_ttl",
"session_idle_ttl",
"refresh_token_ttl",
"max_concurrent_sessions",
"rate_limit",
"delay_after",
"rpid",
"origins",
"magic_link_redirect_uris",
] as const;
const WRITABLE = new Set<string>(WRITABLE_KEYS);
export class PermissionError extends Error {
constructor(
message = "You do not have permission for this action. It requires an admin role on the instance.",
) {
super(message);
this.name = "PermissionError";
}
}
export class ConfigApiError extends Error {
constructor(message: string) {
super(message);
this.name = "ConfigApiError";
}
}
export async function getSystemConfig(
client: AuthClient,
): Promise<SystemConfig> {
const res = await client.get<SystemConfig>("/system-config/admin");
if (res.status === 403) throw new PermissionError();
if (!res.ok || !res.data) {
throw new ConfigApiError(`Could not read system config (${res.status}).`);
}
return res.data;
}
export async function getRoles(client: AuthClient): Promise<string[]> {
const res = await client.get<{ roles?: unknown[] }>("/system-config/roles");
if (res.status === 403) throw new PermissionError();
if (!res.ok) {
throw new ConfigApiError(`Could not read roles (${res.status}).`);
}
return Array.isArray(res.data?.roles)
? res.data.roles.filter((role): role is string => typeof role === "string")
: [];
}
export interface PatchResult {
success: boolean;
updatedKeys: string[];
}
export async function patchSystemConfig(
client: AuthClient,
patch: SystemConfig,
): Promise<PatchResult> {
const res = await client.request<{
success?: boolean;
updatedKeys?: string[];
error?: string;
details?: unknown;
}>("/system-config/admin", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
if (res.status === 403) throw new PermissionError();
if (res.status === 400) {
const reason = res.data?.error ?? "Invalid configuration";
const details = res.data?.details
? ` ${JSON.stringify(scrubTokens(res.data.details))}`
: "";
throw new ConfigApiError(`${reason}.${details}`);
}
if (!res.ok) {
throw new ConfigApiError(`Could not update system config (${res.status}).`);
}
return {
success: res.data?.success ?? true,
updatedKeys: Array.isArray(res.data?.updatedKeys)
? res.data.updatedKeys
: [],
};
}
export type OAuthProvider = Record<string, unknown>;
const OAUTH_PROVIDERS_PATH = "/system-config/oauth-providers";
function providerMutationError(
res: { status: number; data: { error?: string; details?: unknown } | null },
action: string,
id?: unknown,
): never {
if (res.status === 403) throw new PermissionError();
const label = id ? ` "${String(id)}"` : "";
if (res.status === 404) {
throw new ConfigApiError(`OAuth provider${label} not found.`);
}
if (res.status === 409) {
throw new ConfigApiError(
res.data?.error ?? `OAuth provider${label} already exists.`,
);
}
if (res.status === 400) {
const reason = res.data?.error ?? "Invalid OAuth provider";
const details = res.data?.details
? ` ${JSON.stringify(scrubTokens(res.data.details))}`
: "";
throw new ConfigApiError(`${reason}.${details}`);
}
throw new ConfigApiError(`Could not ${action} OAuth provider (${res.status}).`);
}
export async function listOAuthProviders(
client: AuthClient,
): Promise<OAuthProvider[]> {
const res = await client.get<{ providers?: unknown }>(OAUTH_PROVIDERS_PATH);
if (res.status === 403) throw new PermissionError();
if (!res.ok) {
throw new ConfigApiError(`Could not list OAuth providers (${res.status}).`);
}
return Array.isArray(res.data?.providers)
? (res.data.providers as OAuthProvider[])
: [];
}
export async function createOAuthProvider(
client: AuthClient,
provider: OAuthProvider,
): Promise<OAuthProvider> {
const res = await client.request<{
provider?: OAuthProvider;
error?: string;
details?: unknown;
}>(OAUTH_PROVIDERS_PATH, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(provider),
});
if (res.ok) return res.data?.provider ?? provider;
throw providerMutationError(res, "add", provider.id);
}
export async function updateOAuthProvider(
client: AuthClient,
id: string,
updates: OAuthProvider,
): Promise<OAuthProvider> {
const res = await client.request<{
provider?: OAuthProvider;
error?: string;
details?: unknown;
}>(`${OAUTH_PROVIDERS_PATH}/${encodeURIComponent(id)}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updates),
});
if (res.ok) return res.data?.provider ?? updates;
throw providerMutationError(res, "update", id);
}
export async function deleteOAuthProvider(
client: AuthClient,
id: string,
): Promise<void> {
const res = await client.request<{ error?: string; details?: unknown }>(
`${OAUTH_PROVIDERS_PATH}/${encodeURIComponent(id)}`,
{ method: "DELETE" },
);
if (res.ok) return;
throw providerMutationError(res, "remove", id);
}
// The writable keys the instance types as a plain string. Their values are never
// JSON-parsed, so `config set app_name 123` sends the string "123" rather than the
// number 123, and `config set rpid true` sends "true". Everything else (arrays,
// objects, numbers, booleans) is parsed, falling back to the raw string when the
// value is not valid JSON, which is what makes `access_token_ttl 15m` work.
const STRING_KEYS = new Set<string>([
"app_name",
"access_token_ttl",
"session_idle_ttl",
"refresh_token_ttl",
"rpid",
]);
export function isStringKey(key: string): boolean {
return STRING_KEYS.has(key);
}
export function parseValue(raw: string, key?: string): unknown {
const trimmed = raw.trim();
if (key !== undefined && STRING_KEYS.has(key)) return trimmed;
try {
return JSON.parse(trimmed);
} catch {
return raw;
}
}
export function isWritableKey(key: string): boolean {
return WRITABLE.has(key);
}
export function filterWritable(config: SystemConfig): {
patch: SystemConfig;
dropped: string[];
} {
const patch: SystemConfig = {};
const dropped: string[] = [];
for (const [key, value] of Object.entries(config)) {
if (WRITABLE.has(key)) patch[key] = value;
else dropped.push(key);
}
return { patch, dropped };
}
export function deepEqual(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (a === null || b === null) return a === b;
if (typeof a !== typeof b) return false;
if (Array.isArray(a) || Array.isArray(b)) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {
return false;
}
return a.every((item, i) => deepEqual(item, b[i]));
}
if (typeof a === "object" && typeof b === "object") {
const aKeys = Object.keys(a as object);
const bKeys = Object.keys(b as object);
if (aKeys.length !== bKeys.length) return false;
return aKeys.every(
(key) =>
Object.prototype.hasOwnProperty.call(b, key) &&
deepEqual(
(a as Record<string, unknown>)[key],
(b as Record<string, unknown>)[key],
),
);
}
return false;
}
export interface ConfigChange {
key: string;
from: unknown;
to: unknown;
}
export function diffConfig(
local: SystemConfig,
remote: SystemConfig,
): ConfigChange[] {
const changes: ConfigChange[] = [];
for (const [key, to] of Object.entries(local)) {
if (!deepEqual(remote[key], to)) {
changes.push({ key, from: remote[key], to });
}
}
return changes;
}