-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathregister-sso-provider.ts
More file actions
265 lines (246 loc) · 11 KB
/
Copy pathregister-sso-provider.ts
File metadata and controls
265 lines (246 loc) · 11 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Shared `register-sso-provider` (form) handler.
*
* `@better-auth/sso`'s `POST /sso/register` expects the OIDC protocol fields
* NESTED under `oidcConfig` ({ clientId, clientSecret, discoveryEndpoint,
* scopes, mapping }). The `sys_sso_provider` `register_sso_provider` UI action
* collects FLAT form fields (the action param schema has no nested-path
* support), so posting them straight to `/sso/register` drops
* clientId/clientSecret at the top level (Zod-stripped) and persists an
* unusable `oidc_config = null` provider that can never complete a login
* (ADR-0024).
*
* This helper reshapes the flat form body into the nested shape and
* RE-DISPATCHES it through the real `/sso/register` endpoint (via the
* better-auth universal handler passed in) so the admin gate, the
* public-routable `trustedOrigins` allowance, discovery hydration, and secret
* handling all still run — no logic is duplicated. It is the single source of
* truth for the two mount points that must stay in lockstep: the full
* `AuthPlugin` (self-host / OSS host kernel) and the cloud `AuthProxyPlugin`
* (per-environment runtime) — mirroring `runSetInitialPassword`.
*/
export interface RegisterSsoFormResult {
/** HTTP status to return to the caller. */
status: number;
/** JSON body; mirrors the `{ success, data?, error? }` envelope the client parses. */
body: {
success: boolean;
data?: { providerId: string };
error?: { code: string; message: string };
};
}
/** A better-auth universal handler: `(request) => Response`. */
export type AuthRequestHandler = (request: Request) => Promise<Response>;
/**
* Resolve the caller's active organization id by re-dispatching a
* `/get-session` through the same better-auth handler. Returns `undefined` on
* any failure / when no active org is set — callers fall back to an org-less
* (registrar-only) provider, so this is strictly best-effort. `registerUrl` is
* the resolved `…/sso/register` URL; we swap the trailing path for
* `…/get-session` on the same origin/basePath.
*/
async function resolveActiveOrganizationId(
handle: AuthRequestHandler,
registerUrl: string,
headers: Headers,
): Promise<string | undefined> {
try {
const sessionUrl = registerUrl.replace(/\/sso\/register$/, '/get-session');
if (sessionUrl === registerUrl) return undefined;
const h = new Headers({ accept: 'application/json' });
const cookie = headers.get('cookie');
if (cookie) h.set('cookie', cookie);
const authz = headers.get('authorization');
if (authz) h.set('authorization', authz);
const resp = await handle(new Request(sessionUrl, { method: 'GET', headers: h }));
if (!resp.ok) return undefined;
const data: any = await resp.json().catch(() => null);
const org = data?.session?.activeOrganizationId ?? data?.activeOrganizationId;
return typeof org === 'string' && org.length > 0 ? org : undefined;
} catch {
return undefined;
}
}
/**
* Reshape a flat SSO-provider registration form body and register it.
*
* @param handle the better-auth universal handler (`AuthManager.handleRequest`
* on the host kernel, or the resolved per-env handler in the
* cloud proxy). Used to re-dispatch the nested body to the real
* `/sso/register` route so all of its gates run.
* @param request the raw Web `Request` — its headers carry the caller's session
* cookie / bearer + Origin; its body carries the flat form
* fields ({ providerId, issuer, domain, clientId, clientSecret,
* discoveryEndpoint?, scopes?, mapId?, mapEmail?, mapName? }).
*/
export async function runRegisterSsoProviderFromForm(
handle: AuthRequestHandler,
request: Request,
): Promise<RegisterSsoFormResult> {
let body: any;
try {
body = await request.json();
} catch {
body = {};
}
const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
const providerId = str(body?.providerId);
const issuer = str(body?.issuer);
const domain = str(body?.domain);
const clientId = str(body?.clientId);
const clientSecret = str(body?.clientSecret);
const discoveryEndpoint = str(body?.discoveryEndpoint);
const scopesRaw = str(body?.scopes);
const missing = (
[
['providerId', providerId],
['issuer', issuer],
['domain', domain],
['clientId', clientId],
['clientSecret', clientSecret],
] as const
)
.filter(([, v]) => !v)
.map(([k]) => k);
if (missing.length) {
return {
status: 400,
body: { success: false, error: { code: 'invalid_request', message: `Missing required field(s): ${missing.join(', ')}` } },
};
}
const oidcConfig: Record<string, unknown> = { clientId, clientSecret };
if (discoveryEndpoint) oidcConfig.discoveryEndpoint = discoveryEndpoint;
oidcConfig.scopes = scopesRaw ? scopesRaw.split(/[\s,]+/).filter(Boolean) : ['openid', 'email', 'profile'];
oidcConfig.mapping = {
id: str(body?.mapId) || 'sub',
email: str(body?.mapEmail) || 'email',
name: str(body?.mapName) || 'name',
};
// Re-dispatch to the real /sso/register (same origin, sibling path) so the
// admin gate + public-IdP trustedOrigins allowance + discovery hydration run.
let innerUrl: string;
let origin: string;
try {
const url = new URL(request.url);
origin = url.origin;
innerUrl = `${origin}${url.pathname.replace(/\/admin\/sso\/register$/, '/sso/register')}`;
} catch {
return { status: 400, body: { success: false, error: { code: 'invalid_request', message: 'Bad request URL' } } };
}
const headers = new Headers({ 'content-type': 'application/json' });
const cookie = request.headers.get('cookie');
if (cookie) headers.set('cookie', cookie);
const authz = request.headers.get('authorization');
if (authz) headers.set('authorization', authz);
headers.set('origin', request.headers.get('origin') || origin);
// Org-scope the provider to the caller's active organization (best-effort).
// `@better-auth/sso`'s management endpoints (delete / update / domain
// verification) gate org-scoped providers on `isOrgAdmin` but gate ORG-LESS
// ones on `provider.userId === caller` — i.e. only the original registrar can
// manage them. Scoping to the org means ANY org owner/admin can manage the
// env's IdPs (the env is single-org in V1). Resolved by re-dispatching a
// `/get-session` through the same handler; falls back to org-less (no
// regression) when no active org is set.
const organizationId = await resolveActiveOrganizationId(handle, innerUrl, headers);
const innerReq = new Request(innerUrl, {
method: 'POST',
headers,
body: JSON.stringify({ providerId, issuer, domain, oidcConfig, ...(organizationId ? { organizationId } : {}) }),
});
const resp = await handle(innerReq);
let parsed: any = {};
try {
const t = await resp.text();
parsed = t ? JSON.parse(t) : {};
} catch {
parsed = {};
}
if (!resp.ok) {
return {
status: resp.status,
body: { success: false, error: { code: 'sso_register_failed', message: parsed?.message || 'SSO provider registration failed' } },
};
}
return { status: 200, body: { success: true, data: { providerId: parsed?.providerId ?? providerId } } };
}
/**
* ADR-0069 P3 — SAML 2.0 sibling of {@link runRegisterSsoProviderFromForm}.
*
* `@better-auth/sso` (samlify-backed) registers a SAML IdP via the SAME
* `/sso/register` endpoint, with the protocol fields nested under `samlConfig`
* ({ entryPoint, cert, callbackUrl, identifierFormat? }) instead of `oidcConfig`.
* The UI action collects FLAT fields; this helper reshapes them, derives the
* per-provider ACS callback URL (`/sso/saml2/sp/acs/<providerId>`), and
* re-dispatches through `/sso/register` so the admin gate + provisioning run.
* Returns the SP ACS + metadata URLs the admin must configure on the IdP.
*/
export async function runRegisterSamlProviderFromForm(
handle: AuthRequestHandler,
request: Request,
): Promise<RegisterSsoFormResult & { body: RegisterSsoFormResult['body'] & { acsUrl?: string; spMetadataUrl?: string } }> {
let body: any;
try { body = await request.json(); } catch { body = {}; }
const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
const providerId = str(body?.providerId);
const issuer = str(body?.issuer);
const domain = str(body?.domain);
const entryPoint = str(body?.entryPoint);
const cert = str(body?.cert);
const identifierFormat = str(body?.identifierFormat);
const missing = (
[
['providerId', providerId],
['issuer', issuer],
['domain', domain],
['entryPoint', entryPoint],
['cert', cert],
] as const
).filter(([, v]) => !v).map(([k]) => k);
if (missing.length) {
return { status: 400, body: { success: false, error: { code: 'invalid_request', message: `Missing required field(s): ${missing.join(', ')}` } } };
}
let origin: string;
let prefix: string;
let innerUrl: string;
try {
const url = new URL(request.url);
origin = url.origin;
prefix = url.pathname.replace(/\/admin\/sso\/register-saml$/, '');
innerUrl = `${origin}${prefix}/sso/register`;
} catch {
return { status: 400, body: { success: false, error: { code: 'invalid_request', message: 'Bad request URL' } } };
}
const acsUrl = `${origin}${prefix}/sso/saml2/sp/acs/${encodeURIComponent(providerId)}`;
const spMetadataUrl = `${origin}${prefix}/sso/saml2/sp/metadata?providerId=${encodeURIComponent(providerId)}`;
const samlConfig: Record<string, unknown> = {
entryPoint,
cert,
callbackUrl: acsUrl,
// better-auth requires an SP descriptor (its inner fields are optional). Use
// the SP metadata URL as our EntityID — the value the IdP keys this SP on.
spMetadata: { entityID: spMetadataUrl },
};
if (identifierFormat) samlConfig.identifierFormat = identifierFormat;
const headers = new Headers({ 'content-type': 'application/json' });
const cookie = request.headers.get('cookie');
if (cookie) headers.set('cookie', cookie);
const authz = request.headers.get('authorization');
if (authz) headers.set('authorization', authz);
headers.set('origin', request.headers.get('origin') || origin);
// Org-scope to the caller's active org (best-effort) so any org owner/admin
// can manage the provider — see the OIDC helper above.
const organizationId = await resolveActiveOrganizationId(handle, innerUrl, headers);
const innerReq = new Request(innerUrl, {
method: 'POST',
headers,
body: JSON.stringify({ providerId, issuer, domain, samlConfig, ...(organizationId ? { organizationId } : {}) }),
});
const resp = await handle(innerReq);
let parsed: any = {};
try { const t = await resp.text(); parsed = t ? JSON.parse(t) : {}; } catch { parsed = {}; }
if (!resp.ok) {
return { status: resp.status, body: { success: false, error: { code: 'saml_register_failed', message: parsed?.message || 'SAML provider registration failed' } } };
}
return { status: 200, body: { success: true, data: { providerId: parsed?.providerId ?? providerId }, acsUrl, spMetadataUrl } };
}