@multiplatform.one/keycloak-js 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2021 [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # @multiplatform.one/keycloak-js
2
+
3
+ Vendored and patched [keycloak-js](https://www.npmjs.com/package/keycloak-js). Used by `@multiplatform.one/siwe-keycloak`, `@multiplatform.one/keycloak`, and anywhere else that needs the patched adapter (e.g. timeout overflow).
4
+
5
+ **No full keycloak-js source is committed.** Only the **patches** in `patches/` are stored in the repo. The **build script** (`pnpm build`) vendors upstream keycloak-js from `node_modules`, applies those patches to `lib/`, then copies `lib/` → `dist/` for publishing.
6
+
7
+ ## Build
8
+
9
+ ```bash
10
+ pnpm install # in repo root or this package
11
+ pnpm build # vendor keycloak-js + apply patches + copy lib/ → dist/
12
+ ```
13
+
14
+ Before first publish (or in CI), run `pnpm build` so `dist/` exists. `prepublishOnly` runs the build automatically.
15
+
16
+ ## Adding / changing patches
17
+
18
+ See **patches/README.md**. Add `*.patch` files under `patches/`; they are applied in alphabetical order. Paths in patches must be relative to the keycloak-js package root (e.g. `lib/keycloak.js`).
19
+
20
+ ## Upgrading upstream
21
+
22
+ 1. Bump `devDependencies.keycloak-js` in `package.json`.
23
+ 2. `pnpm install`
24
+ 3. Re-apply or adjust patches; run `pnpm build` and test.
25
+ 4. Bump this package version and publish.
26
+
27
+ ## Publishing
28
+
29
+ This package is published from the multiplatform.one monorepo (e.g. via Changesets). Publish includes `dist/`, `patches/`, and `README.md`; `.vendor` is not published.
@@ -0,0 +1,143 @@
1
+ /*
2
+ * MIT License
3
+ *
4
+ * Copyright 2017 Brett Epps <https://github.com/eppsilon>
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7
+ * associated documentation files (the "Software"), to deal in the Software without restriction, including
8
+ * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
10
+ * following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
13
+ * portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
16
+ * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
+ * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
19
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
+ */
21
+ import Keycloak from './keycloak.js'
22
+
23
+ export interface KeycloakAuthorizationPromise {
24
+ then: (onGrant: (rpt: string) => void, onDeny: () => void, onError: () => void) => void
25
+ }
26
+
27
+ export interface AuthorizationRequest {
28
+ /**
29
+ * An array of objects representing the resource and scopes.
30
+ */
31
+ permissions?: ResourcePermission[]
32
+
33
+ /**
34
+ * A permission ticket obtained from a resource server when using UMA authorization protocol.
35
+ */
36
+ ticket?: string
37
+
38
+ /**
39
+ * A boolean value indicating whether the server should create permission requests to the resources
40
+ * and scopes referenced by a permission ticket. This parameter will only take effect when used together
41
+ * with the ticket parameter as part of a UMA authorization process.
42
+ */
43
+ submitRequest?: boolean
44
+
45
+ /**
46
+ * Defines additional information about this authorization request in order to specify how it should be processed
47
+ * by the server.
48
+ */
49
+ metadata?: AuthorizationRequestMetadata
50
+
51
+ /**
52
+ * Defines whether or not this authorization request should include the current RPT. If set to true, the RPT will
53
+ * be sent and permissions in the current RPT will be included in the new RPT. Otherwise, only the permissions referenced in this
54
+ * authorization request will be granted in the new RPT.
55
+ */
56
+ incrementalAuthorization?: boolean
57
+ }
58
+
59
+ export interface AuthorizationRequestMetadata {
60
+ /**
61
+ * A boolean value indicating to the server if resource names should be included in the RPT’s permissions.
62
+ * If false, only the resource identifier is included.
63
+ */
64
+ responseIncludeResourceName?: any
65
+
66
+ /**
67
+ * An integer N that defines a limit for the amount of permissions an RPT can have. When used together with
68
+ * rpt parameter, only the last N requested permissions will be kept in the RPT.
69
+ */
70
+ response_permissions_limit?: number
71
+ }
72
+
73
+ export interface ResourcePermission {
74
+ /**
75
+ * The id or name of a resource.
76
+ */
77
+ id: string
78
+
79
+ /**
80
+ * An array of strings where each value is the name of a scope associated with the resource.
81
+ */
82
+ scopes?: string[]
83
+ }
84
+
85
+ /**
86
+ * @deprecated Instead of importing 'KeycloakAuthorizationInstance' you can import 'KeycloakAuthorization' directly as a type.
87
+ */
88
+ export type KeycloakAuthorizationInstance = KeycloakAuthorization
89
+
90
+ /**
91
+ * @deprecated Construct a KeycloakAuthorization instance using the `new` keyword instead.
92
+ */
93
+ declare function KeycloakAuthorization (keycloak: Keycloak): KeycloakAuthorization
94
+
95
+ declare class KeycloakAuthorization {
96
+ /**
97
+ * Creates a new Keycloak client instance.
98
+ * @param config Path to a JSON config file or a plain config object.
99
+ */
100
+ constructor (keycloak: Keycloak)
101
+
102
+ rpt: any
103
+ config: { rpt_endpoint: string }
104
+
105
+ /**
106
+ * Initializes the `KeycloakAuthorization` instance.
107
+ * @deprecated Initialization now happens automatically, calling this method is no longer required.
108
+ */
109
+ init (): void
110
+
111
+ /**
112
+ * A promise that resolves when the `KeycloakAuthorization` instance is initialized.
113
+ * @deprecated Initialization now happens automatically, using this property is no longer required.
114
+ */
115
+ ready: Promise<void>
116
+
117
+ /**
118
+ * This method enables client applications to better integrate with resource servers protected by a Keycloak
119
+ * policy enforcer using UMA protocol.
120
+ *
121
+ * The authorization request must be provided with a ticket.
122
+ *
123
+ * @param authorizationRequest An AuthorizationRequest instance with a valid permission ticket set.
124
+ * @returns A promise to set functions to be invoked on grant, deny or error.
125
+ */
126
+ authorize (authorizationRequest: AuthorizationRequest): KeycloakAuthorizationPromise
127
+
128
+ /**
129
+ * Obtains all entitlements from a Keycloak server based on a given resourceServerId.
130
+ *
131
+ * @param resourceServerId The id (client id) of the resource server to obtain permissions from.
132
+ * @param authorizationRequest An AuthorizationRequest instance.
133
+ * @returns A promise to set functions to be invoked on grant, deny or error.
134
+ */
135
+ entitlement (resourceServerId: string, authorizationRequest?: AuthorizationRequest): KeycloakAuthorizationPromise
136
+ }
137
+
138
+ export default KeycloakAuthorization
139
+
140
+ /**
141
+ * @deprecated The 'KeycloakAuthorization' namespace is deprecated, use named imports instead.
142
+ */
143
+ export as namespace KeycloakAuthorization;
@@ -0,0 +1,296 @@
1
+ /*
2
+ * Copyright 2016 Red Hat, Inc. and/or its affiliates
3
+ * and other contributors as indicated by the @author tags.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ *
17
+ */
18
+
19
+ const KeycloakAuthorization = function (keycloak, options) {
20
+ const _instance = this
21
+ this.rpt = null
22
+
23
+ // Only here for backwards compatibility, as the configuration is now loaded on demand.
24
+ // See:
25
+ // - https://github.com/keycloak/keycloak/pull/6619
26
+ // - https://issues.redhat.com/browse/KEYCLOAK-10894
27
+ // TODO: Remove both `ready` property and `init` method in a future version
28
+ Object.defineProperty(this, 'ready', {
29
+ get () {
30
+ console.warn("The 'ready' property is deprecated and will be removed in a future version. Initialization now happens automatically, using this property is no longer required.")
31
+ return Promise.resolve()
32
+ }
33
+ })
34
+
35
+ this.init = () => {
36
+ console.warn("The 'init()' method is deprecated and will be removed in a future version. Initialization now happens automatically, calling this method is no longer required.")
37
+ }
38
+
39
+ /** @type {Promise<unknown> | undefined} */
40
+ let configPromise
41
+
42
+ /**
43
+ * Initializes the configuration or re-uses the existing one if present.
44
+ * @returns {Promise<void>} A promise that resolves when the configuration is loaded.
45
+ */
46
+ async function initializeConfigIfNeeded () {
47
+ if (_instance.config) {
48
+ return _instance.config
49
+ }
50
+
51
+ if (configPromise) {
52
+ return await configPromise
53
+ }
54
+
55
+ if (!keycloak.didInitialize) {
56
+ throw new Error('The Keycloak instance has not been initialized yet.')
57
+ }
58
+
59
+ configPromise = loadConfig(keycloak.authServerUrl, keycloak.realm)
60
+ _instance.config = await configPromise
61
+ }
62
+
63
+ /**
64
+ * This method enables client applications to better integrate with resource servers protected by a Keycloak
65
+ * policy enforcer using UMA protocol.
66
+ *
67
+ * The authorization request must be provided with a ticket.
68
+ */
69
+ this.authorize = function (authorizationRequest) {
70
+ this.then = async function (onGrant, onDeny, onError) {
71
+ try {
72
+ await initializeConfigIfNeeded()
73
+ } catch (error) {
74
+ handleError(error, onError)
75
+ return
76
+ }
77
+
78
+ if (authorizationRequest && authorizationRequest.ticket) {
79
+ const request = new globalThis.XMLHttpRequest()
80
+
81
+ request.open('POST', _instance.config.token_endpoint, true)
82
+ request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
83
+ request.setRequestHeader('Authorization', 'Bearer ' + keycloak.token)
84
+
85
+ request.onreadystatechange = function () {
86
+ if (request.readyState === 4) {
87
+ const status = request.status
88
+
89
+ if (status >= 200 && status < 300) {
90
+ const rpt = JSON.parse(request.responseText).access_token
91
+ _instance.rpt = rpt
92
+ onGrant(rpt)
93
+ } else if (status === 403) {
94
+ if (onDeny) {
95
+ onDeny()
96
+ } else {
97
+ console.error('Authorization request was denied by the server.')
98
+ }
99
+ } else {
100
+ if (onError) {
101
+ onError()
102
+ } else {
103
+ console.error('Could not obtain authorization data from server.')
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ let params = 'grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&client_id=' + keycloak.clientId + '&ticket=' + authorizationRequest.ticket
110
+
111
+ if (authorizationRequest.submitRequest !== undefined) {
112
+ params += '&submit_request=' + authorizationRequest.submitRequest
113
+ }
114
+
115
+ const metadata = authorizationRequest.metadata
116
+
117
+ if (metadata) {
118
+ if (metadata.responseIncludeResourceName) {
119
+ params += '&response_include_resource_name=' + metadata.responseIncludeResourceName
120
+ }
121
+ if (metadata.responsePermissionsLimit) {
122
+ params += '&response_permissions_limit=' + metadata.responsePermissionsLimit
123
+ }
124
+ }
125
+
126
+ if (_instance.rpt && (authorizationRequest.incrementalAuthorization === undefined || authorizationRequest.incrementalAuthorization)) {
127
+ params += '&rpt=' + _instance.rpt
128
+ }
129
+
130
+ request.send(params)
131
+ }
132
+ }
133
+
134
+ return this
135
+ }
136
+
137
+ /**
138
+ * Obtains all entitlements from a Keycloak Server based on a given resourceServerId.
139
+ */
140
+ this.entitlement = function (resourceServerId, authorizationRequest) {
141
+ this.then = async function (onGrant, onDeny, onError) {
142
+ try {
143
+ await initializeConfigIfNeeded()
144
+ } catch (error) {
145
+ handleError(error, onError)
146
+ return
147
+ }
148
+
149
+ const request = new globalThis.XMLHttpRequest()
150
+
151
+ request.open('POST', _instance.config.token_endpoint, true)
152
+ request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
153
+ request.setRequestHeader('Authorization', 'Bearer ' + keycloak.token)
154
+
155
+ request.onreadystatechange = function () {
156
+ if (request.readyState === 4) {
157
+ const status = request.status
158
+
159
+ if (status >= 200 && status < 300) {
160
+ const rpt = JSON.parse(request.responseText).access_token
161
+ _instance.rpt = rpt
162
+ onGrant(rpt)
163
+ } else if (status === 403) {
164
+ if (onDeny) {
165
+ onDeny()
166
+ } else {
167
+ console.error('Authorization request was denied by the server.')
168
+ }
169
+ } else {
170
+ if (onError) {
171
+ onError()
172
+ } else {
173
+ console.error('Could not obtain authorization data from server.')
174
+ }
175
+ }
176
+ }
177
+ }
178
+
179
+ if (!authorizationRequest) {
180
+ authorizationRequest = {}
181
+ }
182
+
183
+ let params = 'grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&client_id=' + keycloak.clientId
184
+
185
+ if (authorizationRequest.claimToken) {
186
+ params += '&claim_token=' + authorizationRequest.claimToken
187
+
188
+ if (authorizationRequest.claimTokenFormat) {
189
+ params += '&claim_token_format=' + authorizationRequest.claimTokenFormat
190
+ }
191
+ }
192
+
193
+ params += '&audience=' + resourceServerId
194
+
195
+ let permissions = authorizationRequest.permissions
196
+
197
+ if (!permissions) {
198
+ permissions = []
199
+ }
200
+
201
+ for (let i = 0; i < permissions.length; i++) {
202
+ const resource = permissions[i]
203
+ let permission = resource.id
204
+
205
+ if (resource.scopes && resource.scopes.length > 0) {
206
+ permission += '#'
207
+ for (let j = 0; j < resource.scopes.length; j++) {
208
+ const scope = resource.scopes[j]
209
+ if (permission.indexOf('#') !== permission.length - 1) {
210
+ permission += ','
211
+ }
212
+ permission += scope
213
+ }
214
+ }
215
+
216
+ params += '&permission=' + permission
217
+ }
218
+
219
+ const metadata = authorizationRequest.metadata
220
+
221
+ if (metadata) {
222
+ if (metadata.responseIncludeResourceName) {
223
+ params += '&response_include_resource_name=' + metadata.responseIncludeResourceName
224
+ }
225
+ if (metadata.responsePermissionsLimit) {
226
+ params += '&response_permissions_limit=' + metadata.responsePermissionsLimit
227
+ }
228
+ }
229
+
230
+ if (_instance.rpt) {
231
+ params += '&rpt=' + _instance.rpt
232
+ }
233
+
234
+ request.send(params)
235
+ }
236
+
237
+ return this
238
+ }
239
+
240
+ return this
241
+ }
242
+
243
+ /**
244
+ * Obtains the configuration from the server.
245
+ * @param {string} serverUrl The URL of the Keycloak server.
246
+ * @param {string} realm The realm name.
247
+ * @returns {Promise<unknown>} A promise that resolves when the configuration is loaded.
248
+ */
249
+ async function loadConfig (serverUrl, realm) {
250
+ const url = `${serverUrl}/realms/${encodeURIComponent(realm)}/.well-known/uma2-configuration`
251
+
252
+ try {
253
+ return await fetchJSON(url)
254
+ } catch (error) {
255
+ throw new Error('Could not obtain configuration from server.', { cause: error })
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Fetches the JSON data from the given URL.
261
+ * @param {string} url The URL to fetch the data from.
262
+ * @returns {Promise<unknown>} A promise that resolves when the data is loaded.
263
+ */
264
+ async function fetchJSON (url) {
265
+ let response
266
+
267
+ try {
268
+ response = await fetch(url)
269
+ } catch (error) {
270
+ throw new Error('Server did not respond.', { cause: error })
271
+ }
272
+
273
+ if (!response.ok) {
274
+ throw new Error('Server responded with an invalid status.')
275
+ }
276
+
277
+ try {
278
+ return await response.json()
279
+ } catch (error) {
280
+ throw new Error('Server responded with invalid JSON.', { cause: error })
281
+ }
282
+ }
283
+
284
+ /**
285
+ * @param {unknown} error
286
+ * @param {((error: unknown) => void) | undefined} handler
287
+ */
288
+ function handleError (error, handler) {
289
+ if (handler) {
290
+ handler(error)
291
+ } else {
292
+ console.error(error)
293
+ }
294
+ }
295
+
296
+ export default KeycloakAuthorization