-
-
Notifications
You must be signed in to change notification settings - Fork 693
Expand file tree
/
Copy pathregister.ts
More file actions
168 lines (149 loc) · 6.45 KB
/
Copy pathregister.ts
File metadata and controls
168 lines (149 loc) · 6.45 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
/*
Copyright 2023 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { type OidcClientConfig } from "./index.ts";
import { OidcError } from "./error.ts";
import { Method } from "../http-api/index.ts";
import { logger } from "../logger.ts";
import { type NonEmptyArray } from "../@types/common.ts";
/**
* Client metadata passed to registration endpoint
*/
export type OidcRegistrationClientMetadata = {
clientName: OidcRegistrationRequestBody["client_name"];
clientUri: OidcRegistrationRequestBody["client_uri"];
logoUri?: OidcRegistrationRequestBody["logo_uri"];
applicationType: OidcRegistrationRequestBody["application_type"];
redirectUris: OidcRegistrationRequestBody["redirect_uris"];
contacts: OidcRegistrationRequestBody["contacts"];
tosUri: OidcRegistrationRequestBody["tos_uri"];
policyUri: OidcRegistrationRequestBody["policy_uri"];
};
/**
* Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966
*/
interface OidcRegistrationRequestBody {
client_name?: string;
client_uri: string;
logo_uri?: string;
contacts?: string[];
tos_uri?: string;
policy_uri?: string;
redirect_uris?: NonEmptyArray<string>;
response_types?: NonEmptyArray<string>;
grant_types?: NonEmptyArray<string>;
id_token_signed_response_alg?: string;
token_endpoint_auth_method: string;
application_type: "web" | "native";
}
/**
* The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
*/
export enum OAuthGrantType {
/**
* See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant
*/
AuthorizationCode = "authorization_code",
/**
* https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant
*/
RefreshToken = "refresh_token",
/**
* The OAuth 2.0 Device Authorization Grant type identifier as per
* https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from
* [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).
*
* @experimental Note that this is UNSTABLE and may have breaking changes without notice.
*/
DeviceAuthorization = "urn:ietf:params:oauth:grant-type:device_code",
}
/**
* The name "scope" is a misnomer here as it is actually a "grant type".
*
* @deprecated use `OAuthGrantType.DeviceAuthorization` instead
*/
export const DEVICE_CODE_SCOPE: string = OAuthGrantType.DeviceAuthorization;
// Check that URIs have a common base, as per the MSC2966 definition
const urlHasCommonBase = (base: URL, urlStr?: string): boolean => {
if (!urlStr) return false;
const url = new URL(urlStr);
if (url.protocol !== base.protocol) return false;
if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;
return true;
};
/**
* Attempts dynamic registration against the configured registration endpoint.
* Will ignore any URIs that do not use client_uri as a common base as per the spec.
* @param delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}
* @param clientMetadata - The metadata for the client which to register
* @returns Promise<string> resolved with registered clientId
* @throws when registration is not supported, on failed request or invalid response
*/
export const registerOidcClient = async (
delegatedAuthConfig: OidcClientConfig,
clientMetadata: OidcRegistrationClientMetadata,
): Promise<string> => {
if (!delegatedAuthConfig.registration_endpoint) {
throw new Error(OidcError.DynamicRegistrationNotSupported);
}
const grantTypes: NonEmptyArray<string> = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];
if (grantTypes.some((scope) => !delegatedAuthConfig.grant_types_supported.includes(scope))) {
throw new Error(OidcError.DynamicRegistrationNotSupported);
}
// ask for device authorization grant if supported
if (delegatedAuthConfig.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
grantTypes.push(OAuthGrantType.DeviceAuthorization);
}
const commonBase = new URL(clientMetadata.clientUri);
// https://openid.net/specs/openid-connect-registration-1_0.html
const metadata: OidcRegistrationRequestBody = {
client_name: clientMetadata.clientName,
client_uri: clientMetadata.clientUri,
response_types: ["code"],
grant_types: grantTypes,
redirect_uris: clientMetadata.redirectUris,
id_token_signed_response_alg: "RS256",
token_endpoint_auth_method: "none",
application_type: clientMetadata.applicationType,
contacts: clientMetadata.contacts,
logo_uri: urlHasCommonBase(commonBase, clientMetadata.logoUri) ? clientMetadata.logoUri : undefined,
policy_uri: urlHasCommonBase(commonBase, clientMetadata.policyUri) ? clientMetadata.policyUri : undefined,
tos_uri: urlHasCommonBase(commonBase, clientMetadata.tosUri) ? clientMetadata.tosUri : undefined,
};
const headers = {
"Accept": "application/json",
"Content-Type": "application/json",
};
try {
const response = await fetch(delegatedAuthConfig.registration_endpoint, {
method: Method.Post,
headers,
body: JSON.stringify(metadata),
});
if (response.status >= 400) {
throw new Error(OidcError.DynamicRegistrationFailed);
}
const body = await response.json();
const clientId = body["client_id"];
if (!clientId || typeof clientId !== "string") {
throw new Error(OidcError.DynamicRegistrationInvalid);
}
return clientId;
} catch (error) {
if (Object.values(OidcError).includes((error as Error).message as OidcError)) {
throw error;
} else {
logger.error("Dynamic registration request failed", error);
throw new Error(OidcError.DynamicRegistrationFailed);
}
}
};