Skip to content

Commit 2ad96c7

Browse files
committed
OIDC dynamic client registration
1 parent 9f7e508 commit 2ad96c7

File tree

6 files changed

+74
-17
lines changed

6 files changed

+74
-17
lines changed

src/domain/login/CompleteOIDCLoginViewModel.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -50,18 +50,19 @@ export class CompleteOIDCLoginViewModel extends ViewModel {
5050
}
5151
const code = this._code;
5252
// TODO: cleanup settings storage
53-
const [startedAt, nonce, codeVerifier, redirectUri, homeserver, issuer] = await Promise.all([
53+
const [startedAt, nonce, codeVerifier, redirectUri, homeserver, issuer, clientId] = await Promise.all([
5454
this.platform.settingsStorage.getInt(`oidc_${this._state}_started_at`),
5555
this.platform.settingsStorage.getString(`oidc_${this._state}_nonce`),
5656
this.platform.settingsStorage.getString(`oidc_${this._state}_code_verifier`),
5757
this.platform.settingsStorage.getString(`oidc_${this._state}_redirect_uri`),
5858
this.platform.settingsStorage.getString(`oidc_${this._state}_homeserver`),
5959
this.platform.settingsStorage.getString(`oidc_${this._state}_issuer`),
60+
this.platform.settingsStorage.getString(`oidc_${this._state}_client_id`),
6061
]);
6162

6263
const oidcApi = new OidcApi({
6364
issuer,
64-
clientId: "hydrogen-web",
65+
clientId,
6566
request: this._request,
6667
encoding: this._encoding,
6768
crypto: this._crypto,

src/domain/login/StartOIDCLoginViewModel.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ export class StartOIDCLoginViewModel extends ViewModel {
2424
this._issuer = options.loginOptions.oidc.issuer;
2525
this._homeserver = options.loginOptions.homeserver;
2626
this._api = new OidcApi({
27-
clientId: "hydrogen-web",
2827
issuer: this._issuer,
2928
request: this.platform.request,
3029
encoding: this.platform.encoding,
3130
crypto: this.platform.crypto,
31+
urlCreator: this.urlCreator,
3232
});
3333
}
3434

@@ -42,20 +42,23 @@ export class StartOIDCLoginViewModel extends ViewModel {
4242
async discover() {
4343
// Ask for the metadata once so it gets discovered and cached
4444
await this._api.metadata()
45+
await this._api.ensureRegistered();
4546
}
4647

4748
async startOIDCLogin() {
4849
const p = this._api.generateParams({
4950
scope: "openid",
5051
redirectUri: this.urlCreator.createOIDCRedirectURL(),
5152
});
53+
const clientId = await this._api.clientId();
5254
await Promise.all([
5355
this.platform.settingsStorage.setInt(`oidc_${p.state}_started_at`, Date.now()),
5456
this.platform.settingsStorage.setString(`oidc_${p.state}_nonce`, p.nonce),
5557
this.platform.settingsStorage.setString(`oidc_${p.state}_code_verifier`, p.codeVerifier),
5658
this.platform.settingsStorage.setString(`oidc_${p.state}_redirect_uri`, p.redirectUri),
5759
this.platform.settingsStorage.setString(`oidc_${p.state}_homeserver`, this._homeserver),
5860
this.platform.settingsStorage.setString(`oidc_${p.state}_issuer`, this._issuer),
61+
this.platform.settingsStorage.setString(`oidc_${p.state}_client_id`, clientId),
5962
]);
6063

6164
const link = await this._api.authorizationEndpoint(p);

src/domain/navigation/URLRouter.js

+4
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,10 @@ export class URLRouter {
129129
return window.location.origin;
130130
}
131131

132+
absoluteUrlForAsset(asset) {
133+
return (new URL('/assets/' + asset, window.location.origin)).toString();
134+
}
135+
132136
normalizeUrl() {
133137
// Remove any queryParameters from the URL
134138
// Gets rid of the loginToken after SSO

src/matrix/Client.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,6 @@ export class Client {
132132
try {
133133
const oidcApi = new OidcApi({
134134
issuer,
135-
clientId: "hydrogen-web",
136135
request: this._platform.request,
137136
encoding: this._platform.encoding,
138137
crypto: this._platform.crypto,
@@ -201,6 +200,7 @@ export class Client {
201200

202201
if (loginData.oidc_issuer) {
203202
sessionInfo.oidcIssuer = loginData.oidc_issuer;
203+
sessionInfo.oidcClientId = loginData.oidc_client_id;
204204
}
205205

206206
log.set("id", sessionId);
@@ -262,7 +262,7 @@ export class Client {
262262
if (sessionInfo.oidcIssuer) {
263263
const oidcApi = new OidcApi({
264264
issuer: sessionInfo.oidcIssuer,
265-
clientId: "hydrogen-web",
265+
clientId: sessionInfo.oidcClientId,
266266
request: this._platform.request,
267267
encoding: this._platform.encoding,
268268
crypto: this._platform.crypto,

src/matrix/login/OIDCLoginMethod.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@ export class OIDCLoginMethod implements ILoginMethod {
6666
}).response();
6767

6868
const oidc_issuer = this._oidcApi.issuer;
69+
const oidc_client_id = await this._oidcApi.clientId();
6970

70-
return { oidc_issuer, access_token, refresh_token, expires_in, user_id, device_id };
71+
return { oidc_issuer, oidc_client_id, access_token, refresh_token, expires_in, user_id, device_id };
7172
}
7273
}

src/matrix/net/OidcApi.ts

+59-11
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ limitations under the License.
1515
*/
1616

1717
import type {RequestFunction} from "../../platform/types/types";
18+
import type {URLRouter} from "../../domain/navigation/URLRouter.js";
1819

1920
const WELL_KNOWN = ".well-known/openid-configuration";
2021

@@ -54,18 +55,35 @@ function assert(condition: any, message: string): asserts condition {
5455

5556
export class OidcApi {
5657
_issuer: string;
57-
_clientId: string;
5858
_requestFn: RequestFunction;
5959
_encoding: any;
6060
_crypto: any;
61+
_urlCreator: URLRouter;
6162
_metadataPromise: Promise<any>;
63+
_registrationPromise: Promise<any>;
6264

63-
constructor({ issuer, clientId, request, encoding, crypto }) {
65+
constructor({ issuer, request, encoding, crypto, urlCreator, clientId }) {
6466
this._issuer = issuer;
65-
this._clientId = clientId;
6667
this._requestFn = request;
6768
this._encoding = encoding;
6869
this._crypto = crypto;
70+
this._urlCreator = urlCreator;
71+
72+
if (clientId) {
73+
this._registrationPromise = Promise.resolve({ client_id: clientId });
74+
}
75+
}
76+
77+
get clientMetadata() {
78+
return {
79+
client_name: "Hydrogen Web",
80+
logo_uri: this._urlCreator.absoluteUrlForAsset("icon.png"),
81+
response_types: ["code"],
82+
grant_types: ["authorization_code", "refresh_token"],
83+
redirect_uris: [this._urlCreator.createOIDCRedirectURL()],
84+
id_token_signed_response_alg: "RS256",
85+
token_endpoint_auth_method: "none",
86+
};
6987
}
7088

7189
get metadataUrl() {
@@ -76,11 +94,35 @@ export class OidcApi {
7694
return this._issuer;
7795
}
7896

79-
get redirectUri() {
80-
return window.location.origin;
97+
async clientId(): Promise<string> {
98+
return (await this.registration())["client_id"];
99+
}
100+
101+
registration(): Promise<any> {
102+
if (!this._registrationPromise) {
103+
this._registrationPromise = (async () => {
104+
const headers = new Map();
105+
headers.set("Accept", "application/json");
106+
headers.set("Content-Type", "application/json");
107+
const req = this._requestFn(await this.registrationEndpoint(), {
108+
method: "POST",
109+
headers,
110+
format: "json",
111+
body: JSON.stringify(this.clientMetadata),
112+
});
113+
const res = await req.response();
114+
if (res.status >= 400) {
115+
throw new Error("failed to register client");
116+
}
117+
118+
return res.body;
119+
})();
120+
}
121+
122+
return this._registrationPromise;
81123
}
82124

83-
metadata() {
125+
metadata(): Promise<any> {
84126
if (!this._metadataPromise) {
85127
this._metadataPromise = (async () => {
86128
const headers = new Map();
@@ -105,6 +147,7 @@ export class OidcApi {
105147
const m = await this.metadata();
106148
assert(typeof m.authorization_endpoint === "string", "Has an authorization endpoint");
107149
assert(typeof m.token_endpoint === "string", "Has a token endpoint");
150+
assert(typeof m.registration_endpoint === "string", "Has a registration endpoint");
108151
assert(Array.isArray(m.response_types_supported) && m.response_types_supported.includes("code"), "Supports the code response type");
109152
assert(Array.isArray(m.response_modes_supported) && m.response_modes_supported.includes("fragment"), "Supports the fragment response mode");
110153
assert(Array.isArray(m.grant_types_supported) && m.grant_types_supported.includes("authorization_code"), "Supports the authorization_code grant type");
@@ -126,13 +169,13 @@ export class OidcApi {
126169
scope,
127170
nonce,
128171
codeVerifier,
129-
}: AuthorizationParams) {
172+
}: AuthorizationParams): Promise<string> {
130173
const metadata = await this.metadata();
131174
const url = new URL(metadata["authorization_endpoint"]);
132175
url.searchParams.append("response_mode", "fragment");
133176
url.searchParams.append("response_type", "code");
134177
url.searchParams.append("redirect_uri", redirectUri);
135-
url.searchParams.append("client_id", this._clientId);
178+
url.searchParams.append("client_id", await this.clientId());
136179
url.searchParams.append("state", state);
137180
url.searchParams.append("scope", scope);
138181
if (nonce) {
@@ -147,11 +190,16 @@ export class OidcApi {
147190
return url.toString();
148191
}
149192

150-
async tokenEndpoint() {
193+
async tokenEndpoint(): Promise<string> {
151194
const metadata = await this.metadata();
152195
return metadata["token_endpoint"];
153196
}
154197

198+
async registrationEndpoint(): Promise<string> {
199+
const metadata = await this.metadata();
200+
return metadata["registration_endpoint"];
201+
}
202+
155203
generateParams({ scope, redirectUri }: { scope: string, redirectUri: string }): AuthorizationParams {
156204
return {
157205
scope,
@@ -169,7 +217,7 @@ export class OidcApi {
169217
}: { codeVerifier: string, code: string, redirectUri: string }): Promise<BearerToken> {
170218
const params = new URLSearchParams();
171219
params.append("grant_type", "authorization_code");
172-
params.append("client_id", this._clientId);
220+
params.append("client_id", await this.clientId());
173221
params.append("code_verifier", codeVerifier);
174222
params.append("redirect_uri", redirectUri);
175223
params.append("code", code);
@@ -201,7 +249,7 @@ export class OidcApi {
201249
}: { refreshToken: string }): Promise<BearerToken> {
202250
const params = new URLSearchParams();
203251
params.append("grant_type", "refresh_token");
204-
params.append("client_id", this._clientId);
252+
params.append("client_id", await this.clientId());
205253
params.append("refresh_token", refreshToken);
206254
const body = params.toString();
207255

0 commit comments

Comments
 (0)