@osdk/oauth 0.3.0-beta.0 → 0.4.0-beta.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/CHANGELOG.md +17 -0
- package/build/browser/index.js +152 -94
- package/build/browser/index.js.map +1 -1
- package/build/esm/BaseOauthClient.d.ts +15 -0
- package/build/esm/BaseOauthClient.d.ts.map +1 -0
- package/build/esm/ConfidentialOauthClient.d.ts +4 -0
- package/build/esm/ConfidentialOauthClient.d.ts.map +1 -0
- package/build/esm/PublicOauthClient.d.ts +2 -11
- package/build/esm/PublicOauthClient.d.ts.map +1 -1
- package/build/esm/common.d.ts +36 -0
- package/build/esm/common.d.ts.map +1 -0
- package/build/esm/createConfidentialOauthClient.d.ts +12 -0
- package/build/esm/createConfidentialOauthClient.d.ts.map +1 -0
- package/build/esm/createPublicOauthClient.d.ts.map +1 -1
- package/build/esm/index.d.ts +1 -0
- package/build/esm/index.d.ts.map +1 -1
- package/build/esm/index.js +161 -94
- package/build/esm/index.js.map +1 -1
- package/package.json +2 -3
- package/build/cjs/index.cjs +0 -193
- package/build/cjs/index.cjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @osdk/oauth
|
|
2
2
|
|
|
3
|
+
## 0.4.0-beta.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- cad781e: PublicClient allows relative paths for login pages
|
|
8
|
+
- cad781e: adds getTokenOrUndefined() to oauth clients
|
|
9
|
+
- cad781e: Redirects to root when visiting an old auth callback
|
|
10
|
+
- cad781e: Fixes a bug where process.env was being emitted
|
|
11
|
+
- cad781e: Uses default scopes when provided an empty array
|
|
12
|
+
|
|
13
|
+
## 0.3.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- bc89b62: Spelling fixes and spell check in CI
|
|
18
|
+
- b62ac80: Adds createConfidentialOauthClient
|
|
19
|
+
|
|
3
20
|
## 0.3.0-beta.0
|
|
4
21
|
|
|
5
22
|
### Minor Changes
|
package/build/browser/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, processRevocationResponse, revocationRequest, isOAuth2Error, customFetch, authorizationCodeGrantRequest, validateAuthResponse, generateRandomState, generateRandomCodeVerifier, calculatePKCECodeChallenge } from 'oauth4webapi';
|
|
1
|
+
import { processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, isOAuth2Error, processClientCredentialsResponse, clientCredentialsGrantRequest, customFetch, authorizationCodeGrantRequest, validateAuthResponse, generateRandomState, generateRandomCodeVerifier, calculatePKCECodeChallenge, processRevocationResponse, revocationRequest } from 'oauth4webapi';
|
|
3
2
|
import invariant from 'tiny-invariant';
|
|
4
3
|
import { TypedEventTarget } from 'typescript-event-target';
|
|
4
|
+
import delay from 'delay';
|
|
5
5
|
|
|
6
|
-
// src/
|
|
6
|
+
// src/createConfidentialOauthClient.ts
|
|
7
7
|
function throwIfError(result) {
|
|
8
8
|
if (isOAuth2Error(result)) {
|
|
9
9
|
throw new Error(`Failed to get token: ${result.error}`);
|
|
@@ -11,39 +11,24 @@ function throwIfError(result) {
|
|
|
11
11
|
return result;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
// src/
|
|
15
|
-
var
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
// src/common.ts
|
|
15
|
+
var CustomEvent = globalThis.CustomEvent ;
|
|
16
|
+
var localStorage = globalThis.localStorage;
|
|
17
|
+
function saveLocal(client, x) {
|
|
18
|
+
localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
18
19
|
}
|
|
19
|
-
function removeLocal() {
|
|
20
|
-
localStorage
|
|
20
|
+
function removeLocal(client) {
|
|
21
|
+
localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
21
22
|
}
|
|
22
|
-
function readLocal() {
|
|
23
|
-
return JSON.parse(
|
|
23
|
+
function readLocal(client) {
|
|
24
|
+
return JSON.parse(
|
|
25
|
+
// MUST `localStorage?` as nodejs does not have localStorage
|
|
26
|
+
localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
27
|
+
);
|
|
24
28
|
}
|
|
25
|
-
function
|
|
26
|
-
|
|
27
|
-
[customFetch]: fetchFn
|
|
28
|
-
};
|
|
29
|
+
function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
30
|
+
let token;
|
|
29
31
|
const eventTarget = new TypedEventTarget();
|
|
30
|
-
const issuer = `${new URL(ctxPath, url)}`;
|
|
31
|
-
const as = {
|
|
32
|
-
token_endpoint: `${issuer}/api/oauth2/token`,
|
|
33
|
-
authorization_endpoint: `${issuer}/api/oauth2/authorize`,
|
|
34
|
-
revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
|
|
35
|
-
issuer
|
|
36
|
-
};
|
|
37
|
-
const client = {
|
|
38
|
-
client_id,
|
|
39
|
-
token_endpoint_auth_method: "none"
|
|
40
|
-
};
|
|
41
|
-
async function go(x) {
|
|
42
|
-
if (useHistory) return window.history.replaceState({}, "", x);
|
|
43
|
-
else window.location.assign(x);
|
|
44
|
-
await delay(1e3);
|
|
45
|
-
throw new Error("Unable to redirect");
|
|
46
|
-
}
|
|
47
32
|
function makeTokenAndSaveRefresh(resp, type) {
|
|
48
33
|
const {
|
|
49
34
|
refresh_token,
|
|
@@ -51,7 +36,7 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
51
36
|
access_token
|
|
52
37
|
} = resp;
|
|
53
38
|
!(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
|
|
54
|
-
saveLocal({
|
|
39
|
+
saveLocal(client, {
|
|
55
40
|
refresh_token
|
|
56
41
|
});
|
|
57
42
|
token = {
|
|
@@ -65,21 +50,139 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
65
50
|
}));
|
|
66
51
|
return token;
|
|
67
52
|
}
|
|
53
|
+
let refreshTimeout;
|
|
54
|
+
function rmTimeout() {
|
|
55
|
+
if (refreshTimeout) clearTimeout(refreshTimeout);
|
|
56
|
+
}
|
|
57
|
+
function restartRefreshTimer(evt) {
|
|
58
|
+
if (refresh) {
|
|
59
|
+
rmTimeout();
|
|
60
|
+
refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function signOut() {
|
|
64
|
+
!token ? process.env.NODE_ENV !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
|
|
65
|
+
const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
|
|
66
|
+
rmTimeout();
|
|
67
|
+
removeLocal(client);
|
|
68
|
+
token = void 0;
|
|
69
|
+
throwIfError(result);
|
|
70
|
+
eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
|
|
71
|
+
}
|
|
72
|
+
let pendingSignIn;
|
|
73
|
+
async function signIn() {
|
|
74
|
+
if (pendingSignIn) {
|
|
75
|
+
return pendingSignIn;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
pendingSignIn = _signIn();
|
|
79
|
+
return await pendingSignIn;
|
|
80
|
+
} finally {
|
|
81
|
+
pendingSignIn = void 0;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
eventTarget.addEventListener("signIn", restartRefreshTimer);
|
|
85
|
+
eventTarget.addEventListener("refresh", restartRefreshTimer);
|
|
86
|
+
function getTokenOrUndefined() {
|
|
87
|
+
if (!token || Date.now() >= token.expires_at) {
|
|
88
|
+
return void 0;
|
|
89
|
+
}
|
|
90
|
+
return token?.access_token;
|
|
91
|
+
}
|
|
92
|
+
const getToken = Object.assign(async function getToken2() {
|
|
93
|
+
if (!token || Date.now() >= token.expires_at) {
|
|
94
|
+
token = await signIn();
|
|
95
|
+
}
|
|
96
|
+
return token.access_token;
|
|
97
|
+
}, {
|
|
98
|
+
signIn,
|
|
99
|
+
refresh,
|
|
100
|
+
signOut,
|
|
101
|
+
rmTimeout,
|
|
102
|
+
getTokenOrUndefined,
|
|
103
|
+
addEventListener: eventTarget.addEventListener.bind(eventTarget),
|
|
104
|
+
removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
|
|
105
|
+
});
|
|
106
|
+
return {
|
|
107
|
+
getToken,
|
|
108
|
+
makeTokenAndSaveRefresh
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function createAuthorizationServer(ctxPath, url) {
|
|
112
|
+
const issuer = `${new URL(ctxPath, url)}`;
|
|
113
|
+
return {
|
|
114
|
+
token_endpoint: `${issuer}/api/oauth2/token`,
|
|
115
|
+
authorization_endpoint: `${issuer}/api/oauth2/authorize`,
|
|
116
|
+
revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
|
|
117
|
+
issuer
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/createConfidentialOauthClient.ts
|
|
122
|
+
function createConfidentialOauthClient(client_id, client_secret, url, scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
|
|
123
|
+
const client = {
|
|
124
|
+
client_id,
|
|
125
|
+
client_secret
|
|
126
|
+
};
|
|
127
|
+
const authServer = createAuthorizationServer(ctxPath, url);
|
|
128
|
+
const oauthHttpOptions = {
|
|
129
|
+
[customFetch]: fetchFn
|
|
130
|
+
};
|
|
131
|
+
const {
|
|
132
|
+
getToken,
|
|
133
|
+
makeTokenAndSaveRefresh
|
|
134
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, void 0);
|
|
135
|
+
async function _signIn() {
|
|
136
|
+
return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
|
|
137
|
+
scope: scopes.join(" ")
|
|
138
|
+
}), oauthHttpOptions))), "signIn");
|
|
139
|
+
}
|
|
140
|
+
return getToken;
|
|
141
|
+
}
|
|
142
|
+
function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
|
|
143
|
+
const client = {
|
|
144
|
+
client_id,
|
|
145
|
+
token_endpoint_auth_method: "none"
|
|
146
|
+
};
|
|
147
|
+
const authServer = createAuthorizationServer(ctxPath, url);
|
|
148
|
+
const oauthHttpOptions = {
|
|
149
|
+
[customFetch]: fetchFn
|
|
150
|
+
};
|
|
151
|
+
if (scopes.length === 0) {
|
|
152
|
+
scopes = ["api:read-data", "api:write-data"];
|
|
153
|
+
}
|
|
154
|
+
const {
|
|
155
|
+
makeTokenAndSaveRefresh,
|
|
156
|
+
getToken
|
|
157
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
|
|
158
|
+
async function go(x) {
|
|
159
|
+
if (useHistory) return window.history.replaceState({}, "", x);
|
|
160
|
+
else window.location.assign(x);
|
|
161
|
+
await delay(1e3);
|
|
162
|
+
throw new Error("Unable to redirect");
|
|
163
|
+
}
|
|
68
164
|
async function maybeRefresh(expectRefreshToken) {
|
|
69
165
|
const {
|
|
70
166
|
refresh_token
|
|
71
|
-
} = readLocal();
|
|
167
|
+
} = readLocal(client);
|
|
72
168
|
if (!refresh_token) {
|
|
73
169
|
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
74
170
|
return;
|
|
75
171
|
}
|
|
76
172
|
try {
|
|
77
|
-
|
|
173
|
+
const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
|
|
174
|
+
if (result && window.location.pathname === new URL(redirectUrl).pathname) {
|
|
175
|
+
const {
|
|
176
|
+
oldUrl
|
|
177
|
+
} = readLocal(client);
|
|
178
|
+
go(oldUrl ?? "/");
|
|
179
|
+
}
|
|
180
|
+
return result;
|
|
78
181
|
} catch (e) {
|
|
79
182
|
if (process?.env?.NODE_ENV !== "production") {
|
|
80
183
|
console.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
|
|
81
184
|
}
|
|
82
|
-
removeLocal();
|
|
185
|
+
removeLocal(client);
|
|
83
186
|
if (expectRefreshToken) {
|
|
84
187
|
throw new Error("Could not refresh token");
|
|
85
188
|
}
|
|
@@ -90,35 +193,35 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
90
193
|
codeVerifier,
|
|
91
194
|
state,
|
|
92
195
|
oldUrl
|
|
93
|
-
} = readLocal();
|
|
196
|
+
} = readLocal(client);
|
|
94
197
|
if (!codeVerifier) return;
|
|
95
198
|
try {
|
|
96
|
-
const
|
|
199
|
+
const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), "signIn");
|
|
97
200
|
go(oldUrl);
|
|
98
|
-
return
|
|
201
|
+
return ret;
|
|
99
202
|
} catch (e) {
|
|
100
203
|
if (process?.env?.NODE_ENV !== "production") {
|
|
101
204
|
console.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
|
|
102
205
|
}
|
|
103
|
-
removeLocal();
|
|
206
|
+
removeLocal(client);
|
|
104
207
|
}
|
|
105
208
|
}
|
|
106
209
|
async function initiateLoginRedirect() {
|
|
107
|
-
if (loginPage && window.location.href !== loginPage) {
|
|
108
|
-
saveLocal({
|
|
210
|
+
if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {
|
|
211
|
+
saveLocal(client, {
|
|
109
212
|
oldUrl: postLoginPage
|
|
110
213
|
});
|
|
111
214
|
return await go(loginPage);
|
|
112
215
|
}
|
|
113
216
|
const state = generateRandomState();
|
|
114
217
|
const codeVerifier = generateRandomCodeVerifier();
|
|
115
|
-
const oldUrl = readLocal().oldUrl ?? window.location.toString();
|
|
116
|
-
saveLocal({
|
|
218
|
+
const oldUrl = readLocal(client).oldUrl ?? window.location.toString();
|
|
219
|
+
saveLocal(client, {
|
|
117
220
|
codeVerifier,
|
|
118
221
|
state,
|
|
119
222
|
oldUrl
|
|
120
223
|
});
|
|
121
|
-
window.location.assign(`${
|
|
224
|
+
window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({
|
|
122
225
|
client_id,
|
|
123
226
|
response_type: "code",
|
|
124
227
|
state,
|
|
@@ -130,57 +233,12 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
130
233
|
await delay(1e3);
|
|
131
234
|
throw new Error("Unable to redirect");
|
|
132
235
|
}
|
|
133
|
-
let refreshTimeout;
|
|
134
|
-
function rmTimeout() {
|
|
135
|
-
if (refreshTimeout) clearTimeout(refreshTimeout);
|
|
136
|
-
}
|
|
137
|
-
function restartRefreshTimer(evt) {
|
|
138
|
-
rmTimeout();
|
|
139
|
-
refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
|
|
140
|
-
}
|
|
141
|
-
const refresh = maybeRefresh.bind(globalThis, true);
|
|
142
|
-
async function signOut() {
|
|
143
|
-
!token ? process.env.NODE_ENV !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
|
|
144
|
-
const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
|
|
145
|
-
rmTimeout();
|
|
146
|
-
removeLocal();
|
|
147
|
-
token = void 0;
|
|
148
|
-
throwIfError(result);
|
|
149
|
-
eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
|
|
150
|
-
}
|
|
151
|
-
let pendingSignIn;
|
|
152
|
-
async function signIn() {
|
|
153
|
-
if (pendingSignIn) {
|
|
154
|
-
return pendingSignIn;
|
|
155
|
-
}
|
|
156
|
-
try {
|
|
157
|
-
pendingSignIn = _signIn();
|
|
158
|
-
return await pendingSignIn;
|
|
159
|
-
} finally {
|
|
160
|
-
pendingSignIn = void 0;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
236
|
async function _signIn() {
|
|
164
|
-
return
|
|
237
|
+
return await maybeRefresh() ?? await maybeHandleAuthReturn() ?? await initiateLoginRedirect();
|
|
165
238
|
}
|
|
166
|
-
|
|
167
|
-
eventTarget.addEventListener("refresh", restartRefreshTimer);
|
|
168
|
-
let token;
|
|
169
|
-
const ret = Object.assign(async function ret2() {
|
|
170
|
-
if (!token || Date.now() >= token.expires_at) {
|
|
171
|
-
token = await signIn();
|
|
172
|
-
}
|
|
173
|
-
return token.access_token;
|
|
174
|
-
}, {
|
|
175
|
-
signIn,
|
|
176
|
-
refresh,
|
|
177
|
-
signOut,
|
|
178
|
-
addEventListener: eventTarget.addEventListener.bind(eventTarget),
|
|
179
|
-
removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
|
|
180
|
-
});
|
|
181
|
-
return ret;
|
|
239
|
+
return getToken;
|
|
182
240
|
}
|
|
183
241
|
|
|
184
|
-
export { createPublicOauthClient };
|
|
185
|
-
//# sourceMappingURL=
|
|
242
|
+
export { createConfidentialOauthClient, createPublicOauthClient };
|
|
243
|
+
//# sourceMappingURL=index.js.map
|
|
186
244
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/createPublicOauthClient.ts","../../src/throwIfError.ts"],"names":["ret"],"mappings":";AAgBA,OAAO,WAAW;AAClB,SAAS,+BAA+B,4BAA4B,aAAa,4BAA4B,qBAAqB,wCAAwC,2BAA2B,0BAA0B,mBAAmB,4BAA4B;AAC9Q,OAAO,eAAe;AACtB,SAAS,wBAAwB;;;ACHjC,SAAS,qBAAqB;AACvB,SAAS,aAAa,QAAQ;AACnC,MAAI,cAAc,MAAM,GAAG;AACzB,UAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,EACxD;AACA,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A,IACf,UAAE;AACA,sBAAgB;AAAA,IAClB;AAAA,EACF;AAEA,iBAAe,UAAU;AAEvB,WAAO,QAAS,MAAM,aAAa,KAE7B,MAAM,sBAAsB,KAE9B,MAAM,sBAAsB;AAAA,EAClC;AACA,cAAY,iBAAiB,UAAU,mBAAmB;AAC1D,cAAY,iBAAiB,WAAW,mBAAmB;AAC3D,MAAI;AACJ,QAAM,MAAM,OAAO,OAAO,eAAeA,OAAM;AAC7C,QAAI,CAAC,SAAS,KAAK,IAAI,KAAK,MAAM,YAAY;AAC5C,cAAQ,MAAM,OAAO;AAAA,IACvB;AACA,WAAO,MAAM;AAAA,EACf,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA,kBAAkB,YAAY,iBAAiB,KAAK,WAAW;AAAA,IAC/D,qBAAqB,YAAY,oBAAoB,KAAK,WAAW;AAAA,EACvE,CAAC;AACD,SAAO;AACT","sourcesContent":["/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, processRevocationResponse, refreshTokenGrantRequest, revocationRequest, validateAuthResponse } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\nconst storageKey = \"asdfasdfdhjlkajhgj\";\nfunction saveLocal(x) {\n localStorage.setItem(storageKey, JSON.stringify(x));\n}\nfunction removeLocal() {\n localStorage.removeItem(storageKey);\n}\nfunction readLocal() {\n return JSON.parse(localStorage.getItem(storageKey) ?? \"{}\");\n}\n\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const eventTarget = new TypedEventTarget();\n const issuer = `${new URL(ctxPath, url)}`;\n const as = {\n token_endpoint: `${issuer}/api/oauth2/token`,\n authorization_endpoint: `${issuer}/api/oauth2/authorize`,\n revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,\n issuer\n };\n const client = {\n client_id,\n token_endpoint_auth_method: \"none\"\n };\n async function go(x) {\n if (useHistory) return window.history.replaceState({}, \"\", x);else window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n function makeTokenAndSaveRefresh(resp, type) {\n const {\n refresh_token,\n expires_in,\n access_token\n } = resp;\n !(expires_in != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n saveLocal({\n refresh_token\n });\n token = {\n refresh_token,\n expires_in,\n access_token,\n expires_at: Date.now() + expires_in * 1000\n };\n eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {\n detail: token\n }));\n return token;\n }\n async function maybeRefresh(expectRefreshToken) {\n const {\n refresh_token\n } = readLocal();\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await refreshTokenGrantRequest(as, client, refresh_token, oauthHttpOptions))), \"refresh\");\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 refresh token. Removing refresh token\", e);\n }\n removeLocal();\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n async function maybeHandleAuthReturn() {\n const {\n codeVerifier,\n state,\n oldUrl\n } = readLocal();\n if (!codeVerifier) return;\n try {\n const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await authorizationCodeGrantRequest(as, client, throwIfError(validateAuthResponse(as, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), \"signIn\");\n go(oldUrl);\n return ret;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\", e);\n }\n removeLocal();\n }\n }\n async function initiateLoginRedirect() {\n if (loginPage && window.location.href !== loginPage) {\n saveLocal({\n oldUrl: postLoginPage\n });\n return await go(loginPage);\n }\n const state = generateRandomState();\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readLocal().oldUrl ?? window.location.toString();\n saveLocal({\n codeVerifier,\n state,\n oldUrl\n });\n window.location.assign(`${as.authorization_endpoint}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri: redirectUrl,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: [\"offline_access\", ...scopes].join(\" \")\n })}`);\n\n // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout) clearTimeout(refreshTimeout);\n }\n function restartRefreshTimer(evt) {\n rmTimeout();\n refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);\n }\n const refresh = maybeRefresh.bind(globalThis, true);\n async function signOut() {\n !token ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"not signed in\") : invariant(false) : void 0;\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\n\n // Clean up\n removeLocal();\n token = undefined;\n throwIfError(result);\n eventTarget.dispatchTypedEvent(\"signOut\", new Event(\"signOut\"));\n }\n let pendingSignIn;\n async function signIn() {\n if (pendingSignIn) {\n return pendingSignIn;\n }\n try {\n pendingSignIn = _signIn();\n return await pendingSignIn;\n } finally {\n pendingSignIn = undefined;\n }\n }\n /** Will throw if there is no token! */\n async function _signIn() {\n // 1. Check if we have a refresh token in local storage\n return token = (await maybeRefresh()\n // 2. If there is no refresh token we are likely trying to perform the callback\n ) ?? (await maybeHandleAuthReturn())\n // 3. If we haven't been able to load the token from one of the two above ways, we need to make the initial auth request\n ?? (await initiateLoginRedirect());\n }\n eventTarget.addEventListener(\"signIn\", restartRefreshTimer);\n eventTarget.addEventListener(\"refresh\", restartRefreshTimer);\n let token;\n const ret = Object.assign(async function ret() {\n if (!token || Date.now() >= token.expires_at) {\n token = await signIn();\n }\n return token.access_token;\n }, {\n signIn,\n refresh,\n signOut,\n addEventListener: eventTarget.addEventListener.bind(eventTarget),\n removeEventListener: eventTarget.removeEventListener.bind(eventTarget)\n });\n return ret;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/throwIfError.ts","../../src/common.ts","../../src/createConfidentialOauthClient.ts","../../src/createPublicOauthClient.ts"],"names":["getToken","customFetch"],"mappings":";;;;;;AAiBO,SAAS,aAAa,MAAQ,EAAA;AACnC,EAAI,IAAA,aAAA,CAAc,MAAM,CAAG,EAAA;AACzB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAwB,qBAAA,EAAA,MAAA,CAAO,KAAK,CAAE,CAAA,CAAA,CAAA;AAAA,GACxD;AACA,EAAO,OAAA,MAAA,CAAA;AACT,CAAA;;;ACAA,IAAM,WAAA,GAAiD,UAAW,CAAA,WAAA,CASlE,CAAA;AACA,IAAM,eAAe,UAAW,CAAA,YAAA,CAAA;AACzB,SAAS,SAAA,CAAU,QAAQ,CAAG,EAAA;AAEnC,EAAc,YAAA,EAAA,OAAA,CAAQ,2BAA2B,MAAO,CAAA,SAAS,IAAI,IAAK,CAAA,SAAA,CAAU,CAAC,CAAC,CAAA,CAAA;AACxF,CAAA;AACO,SAAS,YAAY,MAAQ,EAAA;AAElC,EAAA,YAAA,EAAc,UAAW,CAAA,CAAA,wBAAA,EAA2B,MAAO,CAAA,SAAS,CAAE,CAAA,CAAA,CAAA;AACxE,CAAA;AACO,SAAS,UAAU,MAAQ,EAAA;AAChC,EAAA,OAAO,IAAK,CAAA,KAAA;AAAA;AAAA,IAEZ,cAAc,OAAQ,CAAA,CAAA,wBAAA,EAA2B,MAAO,CAAA,SAAS,EAAE,CAAK,IAAA,IAAA;AAAA,GAAI,CAAA;AAC9E,CAAA;AACO,SAAS,MAAO,CAAA,MAAA,EAAQ,EAAI,EAAA,OAAA,EAAS,kBAAkB,OAAS,EAAA;AACrE,EAAI,IAAA,KAAA,CAAA;AACJ,EAAM,MAAA,WAAA,GAAc,IAAI,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the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { processRevocationResponse, revocationRequest } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\n// Node 18 is supposed to have a `CustomEvent` but it is not exposed on `globalThis`\n// which creates a problem for making a single codebase for node and browser. This polyfill works around it\nconst CustomEvent = process.env.TARGET === \"browser\" ? globalThis.CustomEvent : globalThis.CustomEvent ?? class CustomEvent extends Event {\n #detail;\n constructor(type, options) {\n super(type, options);\n this.#detail = options?.detail ?? null;\n }\n get detail() {\n return this.#detail;\n }\n};\nconst localStorage = globalThis.localStorage;\nexport function saveLocal(client, x) {\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));\n}\nexport function removeLocal(client) {\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);\n}\nexport function readLocal(client) {\n return JSON.parse(\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? \"{}\");\n}\nexport function common(client, as, _signIn, oauthHttpOptions, refresh) {\n let token;\n const eventTarget = new TypedEventTarget();\n function makeTokenAndSaveRefresh(resp, type) {\n const {\n refresh_token,\n expires_in,\n access_token\n } = resp;\n !(expires_in != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n saveLocal(client, {\n refresh_token\n });\n token = {\n refresh_token,\n expires_in,\n access_token,\n expires_at: Date.now() + expires_in * 1000\n };\n eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {\n detail: token\n }));\n return token;\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout) clearTimeout(refreshTimeout);\n }\n function restartRefreshTimer(evt) {\n if (refresh) {\n rmTimeout();\n refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);\n }\n }\n async function signOut() {\n !token ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"not signed in\") : invariant(false) : void 0;\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\n\n // Clean up\n removeLocal(client);\n token = undefined;\n throwIfError(result);\n eventTarget.dispatchTypedEvent(\"signOut\", new Event(\"signOut\"));\n }\n let pendingSignIn;\n async function signIn() {\n if (pendingSignIn) {\n return pendingSignIn;\n }\n try {\n pendingSignIn = _signIn();\n return await pendingSignIn;\n } finally {\n pendingSignIn = undefined;\n }\n }\n eventTarget.addEventListener(\"signIn\", restartRefreshTimer);\n eventTarget.addEventListener(\"refresh\", restartRefreshTimer);\n function getTokenOrUndefined() {\n if (!token || Date.now() >= token.expires_at) {\n return undefined;\n }\n return token?.access_token;\n }\n const getToken = Object.assign(async function getToken() {\n if (!token || Date.now() >= token.expires_at) {\n token = await signIn();\n }\n return token.access_token;\n }, {\n signIn,\n refresh,\n signOut,\n rmTimeout,\n getTokenOrUndefined,\n addEventListener: eventTarget.addEventListener.bind(eventTarget),\n removeEventListener: eventTarget.removeEventListener.bind(eventTarget)\n });\n return {\n getToken,\n makeTokenAndSaveRefresh\n };\n}\nexport function createAuthorizationServer(ctxPath, url) {\n const issuer = `${new URL(ctxPath, url)}`;\n return {\n token_endpoint: `${issuer}/api/oauth2/token`,\n authorization_endpoint: `${issuer}/api/oauth2/authorize`,\n revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,\n issuer\n };\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { clientCredentialsGrantRequest, customFetch, processClientCredentialsResponse } from \"oauth4webapi\";\nimport { common, createAuthorizationServer } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n\n/**\n * @param client_id\n * @param client_secret\n * @param url the base url of your foundry server\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns which can be used as a token provider\n */\nexport function createConfidentialOauthClient(client_id, client_secret, url, scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = {\n client_id,\n client_secret\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const {\n getToken,\n makeTokenAndSaveRefresh\n } = common(client, authServer, _signIn, oauthHttpOptions, undefined);\n async function _signIn() {\n return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({\n scope: scopes.join(\" \")\n }), oauthHttpOptions))), \"signIn\");\n }\n return getToken;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, validateAuthResponse } from \"oauth4webapi\";\nimport { common, createAuthorizationServer, readLocal, removeLocal, saveLocal } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = {\n client_id,\n token_endpoint_auth_method: \"none\"\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n if (scopes.length === 0) {\n scopes = [\"api:read-data\", \"api:write-data\"];\n }\n const {\n makeTokenAndSaveRefresh,\n getToken\n } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));\n async function go(x) {\n if (useHistory) return window.history.replaceState({}, \"\", x);else window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n async function maybeRefresh(expectRefreshToken) {\n const {\n refresh_token\n } = readLocal(client);\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), \"refresh\");\n if (result && window.location.pathname === new URL(redirectUrl).pathname) {\n const {\n oldUrl\n } = readLocal(client);\n go(oldUrl ?? \"/\");\n }\n return result;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 refresh token. Removing refresh token\", e);\n }\n removeLocal(client);\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n async function maybeHandleAuthReturn() {\n const {\n codeVerifier,\n state,\n oldUrl\n } = readLocal(client);\n if (!codeVerifier) return;\n try {\n const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), \"signIn\");\n go(oldUrl);\n return ret;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\", e);\n }\n removeLocal(client);\n }\n }\n async function initiateLoginRedirect() {\n if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {\n saveLocal(client, {\n oldUrl: postLoginPage\n });\n return await go(loginPage);\n }\n const state = generateRandomState();\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readLocal(client).oldUrl ?? window.location.toString();\n saveLocal(client, {\n codeVerifier,\n state,\n oldUrl\n });\n window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri: redirectUrl,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: [\"offline_access\", ...scopes].join(\" \")\n })}`);\n\n // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n\n /** Will throw if there is no token! */\n async function _signIn() {\n // 1. Check if we have a refresh token in local storage\n return (await maybeRefresh()\n // 2. If there is no refresh token we are likely trying to perform the callback\n ) ?? (await maybeHandleAuthReturn())\n // 3. If we haven't been able to load the token from one of the two above ways, we need to make the initial auth request\n ?? (await initiateLoginRedirect());\n }\n return getToken;\n}"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Token } from "./Token.js";
|
|
2
|
+
export type Events = {
|
|
3
|
+
signIn: CustomEvent<Token>;
|
|
4
|
+
signOut: Event;
|
|
5
|
+
refresh: CustomEvent<Token>;
|
|
6
|
+
};
|
|
7
|
+
export interface BaseOauthClient<K extends keyof Events & string> {
|
|
8
|
+
(): Promise<string>;
|
|
9
|
+
getTokenOrUndefined: () => string | undefined;
|
|
10
|
+
signIn: () => Promise<Token>;
|
|
11
|
+
signOut: () => Promise<void>;
|
|
12
|
+
addEventListener: <T extends K>(type: T, listener: ((evt: Events[T]) => void) | null, options?: boolean | AddEventListenerOptions) => void;
|
|
13
|
+
removeEventListener: <T extends K>(type: T, callback: ((evt: Events[T]) => void) | null, options?: EventListenerOptions | boolean) => void;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=BaseOauthClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseOauthClient.d.ts","sourceRoot":"","sources":["../../src/BaseOauthClient.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,MAAM,MAAM,MAAM,GAAG;IACnB,MAAM,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;IAC3B,OAAO,EAAE,KAAK,CAAC;IACf,OAAO,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;CAC7B,CAAC;AAEF,MAAM,WAAW,eAAe,CAAC,CAAC,SAAS,MAAM,MAAM,GAAG,MAAM;IAC9D,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAEpB,mBAAmB,EAAE,MAAM,MAAM,GAAG,SAAS,CAAC;IAC9C,MAAM,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IAC7B,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAE7B,gBAAgB,EAAE,CAAC,CAAC,SAAS,CAAC,EAC5B,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,GAAG,IAAI,EAC3C,OAAO,CAAC,EAAE,OAAO,GAAG,uBAAuB,KACxC,IAAI,CAAC;IAEV,mBAAmB,EAAE,CAAC,CAAC,SAAS,CAAC,EAC/B,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,GAAG,IAAI,EAC3C,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,KACrC,IAAI,CAAC;CACX"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ConfidentialOauthClient.d.ts","sourceRoot":"","sources":["../../src/ConfidentialOauthClient.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,MAAM,WAAW,uBACf,SAAQ,eAAe,CAAC,QAAQ,GAAG,SAAS,CAAC;CAE9C"}
|
|
@@ -1,15 +1,6 @@
|
|
|
1
|
+
import type { BaseOauthClient } from "./BaseOauthClient.js";
|
|
1
2
|
import type { Token } from "./Token.js";
|
|
2
|
-
export
|
|
3
|
-
signIn: CustomEvent<Token>;
|
|
4
|
-
signOut: Event;
|
|
5
|
-
refresh: CustomEvent<Token>;
|
|
6
|
-
};
|
|
7
|
-
export interface PublicOauthClient {
|
|
8
|
-
(): Promise<string>;
|
|
9
|
-
signIn: () => Promise<Token>;
|
|
3
|
+
export interface PublicOauthClient extends BaseOauthClient<"signIn" | "signOut" | "refresh"> {
|
|
10
4
|
refresh: () => Promise<Token | undefined>;
|
|
11
|
-
signOut: () => Promise<void>;
|
|
12
|
-
addEventListener: <T extends keyof Events & string>(type: T, listener: ((evt: Events[T]) => void) | null, options?: boolean | AddEventListenerOptions) => void;
|
|
13
|
-
removeEventListener: <T extends keyof Events & string>(type: T, callback: ((evt: Events[T]) => void) | null, options?: EventListenerOptions | boolean) => void;
|
|
14
5
|
}
|
|
15
6
|
//# sourceMappingURL=PublicOauthClient.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PublicOauthClient.d.ts","sourceRoot":"","sources":["../../src/PublicOauthClient.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"PublicOauthClient.d.ts","sourceRoot":"","sources":["../../src/PublicOauthClient.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,MAAM,WAAW,iBACf,SAAQ,eAAe,CAAC,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;IAEzD,OAAO,EAAE,MAAM,OAAO,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC;CAC3C"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { AuthorizationServer, Client, HttpRequestOptions, OAuth2TokenEndpointResponse } from "oauth4webapi";
|
|
2
|
+
import type { BaseOauthClient, Events } from "./BaseOauthClient.js";
|
|
3
|
+
import type { Token } from "./Token.js";
|
|
4
|
+
type LocalStorageState = {
|
|
5
|
+
refresh_token?: never;
|
|
6
|
+
codeVerifier?: never;
|
|
7
|
+
state?: never;
|
|
8
|
+
oldUrl: string;
|
|
9
|
+
} | {
|
|
10
|
+
refresh_token?: never;
|
|
11
|
+
codeVerifier: string;
|
|
12
|
+
state: string;
|
|
13
|
+
oldUrl: string;
|
|
14
|
+
} | {
|
|
15
|
+
refresh_token?: string;
|
|
16
|
+
codeVerifier?: never;
|
|
17
|
+
state?: never;
|
|
18
|
+
oldUrl?: never;
|
|
19
|
+
} | {
|
|
20
|
+
refresh_token?: never;
|
|
21
|
+
codeVerifier?: never;
|
|
22
|
+
state?: never;
|
|
23
|
+
oldUrl?: never;
|
|
24
|
+
};
|
|
25
|
+
export declare function saveLocal(client: Client, x: LocalStorageState): void;
|
|
26
|
+
export declare function removeLocal(client: Client): void;
|
|
27
|
+
export declare function readLocal(client: Client): LocalStorageState;
|
|
28
|
+
export declare function common<R extends undefined | (() => Promise<Token | undefined>)>(client: Client, as: AuthorizationServer, _signIn: () => Promise<Token>, oauthHttpOptions: HttpRequestOptions, refresh: R): {
|
|
29
|
+
getToken: BaseOauthClient<keyof Events & string> & {
|
|
30
|
+
refresh: R;
|
|
31
|
+
};
|
|
32
|
+
makeTokenAndSaveRefresh: (resp: OAuth2TokenEndpointResponse, type: "signIn" | "refresh") => Token;
|
|
33
|
+
};
|
|
34
|
+
export declare function createAuthorizationServer(ctxPath: string, url: string): Required<Pick<AuthorizationServer, "issuer" | "token_endpoint" | "authorization_endpoint" | "revocation_endpoint">>;
|
|
35
|
+
export {};
|
|
36
|
+
//# sourceMappingURL=common.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,mBAAmB,EACnB,MAAM,EACN,kBAAkB,EAClB,2BAA2B,EAC5B,MA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eAAe,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC,CAAA;KAAE,CAAC;IAClE,uBAAuB,EAAE,CACvB,IAAI,EAAE,2BAA2B,EACjC,IAAI,EAAE,QAAQ,GAAG,SAAS,KACvB,KAAK,CAAC;CACZ,CA0GA;AAED,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACV,QAAQ,CACT,IAAI,CACF,mBAAmB,EACjB,QAAQ,GACR,gBAAgB,GAChB,wBAAwB,GACxB,qBAAqB,CACxB,CACF,CAQA"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ConfidentialOauthClient } from "./ConfidentialOauthClient.js";
|
|
2
|
+
/**
|
|
3
|
+
* @param client_id
|
|
4
|
+
* @param client_secret
|
|
5
|
+
* @param url the base url of your foundry server
|
|
6
|
+
* @param scopes
|
|
7
|
+
* @param fetchFn
|
|
8
|
+
* @param ctxPath
|
|
9
|
+
* @returns which can be used as a token provider
|
|
10
|
+
*/
|
|
11
|
+
export declare function createConfidentialOauthClient(client_id: string, client_secret: string, url: string, scopes?: string[], fetchFn?: typeof globalThis.fetch, ctxPath?: string): ConfidentialOauthClient;
|
|
12
|
+
//# sourceMappingURL=createConfidentialOauthClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createConfidentialOauthClient.d.ts","sourceRoot":"","sources":["../../src/createConfidentialOauthClient.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAG5E;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC3C,SAAS,EAAE,MAAM,EACjB,aAAa,EAAE,MAAM,EACrB,GAAG,EAAE,MAAM,EACX,MAAM,GAAE,MAAM,EAAwC,EACtD,OAAO,GAAE,OAAO,UAAU,CAAC,KAAwB,EACnD,OAAO,GAAE,MAAqB,GAC7B,uBAAuB,CAgCzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPublicOauthClient.d.ts","sourceRoot":"","sources":["../../src/createPublicOauthClient.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"createPublicOauthClient.d.ts","sourceRoot":"","sources":["../../src/createPublicOauthClient.ts"],"names":[],"mappings":"AAmCA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAUhE;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,MAAM,EACnB,UAAU,GAAE,OAAc,EAC1B,SAAS,CAAC,EAAE,MAAM,EAClB,aAAa,GAAE,MAAmC,EAClD,MAAM,GAAE,MAAM,EAAO,EACrB,OAAO,GAAE,OAAO,UAAU,CAAC,KAAwB,EACnD,OAAO,GAAE,MAAqB,GAC7B,iBAAiB,CAiKnB"}
|
package/build/esm/index.d.ts
CHANGED
package/build/esm/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,YAAY,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACnF,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,YAAY,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC"}
|
package/build/esm/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, processRevocationResponse, revocationRequest, isOAuth2Error, customFetch, authorizationCodeGrantRequest, validateAuthResponse, generateRandomState, generateRandomCodeVerifier, calculatePKCECodeChallenge } from 'oauth4webapi';
|
|
1
|
+
import { processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, isOAuth2Error, processClientCredentialsResponse, clientCredentialsGrantRequest, customFetch, authorizationCodeGrantRequest, validateAuthResponse, generateRandomState, generateRandomCodeVerifier, calculatePKCECodeChallenge, processRevocationResponse, revocationRequest } from 'oauth4webapi';
|
|
3
2
|
import invariant from 'tiny-invariant';
|
|
4
3
|
import { TypedEventTarget } from 'typescript-event-target';
|
|
4
|
+
import delay from 'delay';
|
|
5
5
|
|
|
6
|
-
// src/
|
|
6
|
+
// src/createConfidentialOauthClient.ts
|
|
7
7
|
function throwIfError(result) {
|
|
8
8
|
if (isOAuth2Error(result)) {
|
|
9
9
|
throw new Error(`Failed to get token: ${result.error}`);
|
|
@@ -11,39 +11,33 @@ function throwIfError(result) {
|
|
|
11
11
|
return result;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
// src/
|
|
15
|
-
var
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
// src/common.ts
|
|
15
|
+
var CustomEvent = globalThis.CustomEvent ?? class CustomEvent2 extends Event {
|
|
16
|
+
#detail;
|
|
17
|
+
constructor(type, options) {
|
|
18
|
+
super(type, options);
|
|
19
|
+
this.#detail = options?.detail ?? null;
|
|
20
|
+
}
|
|
21
|
+
get detail() {
|
|
22
|
+
return this.#detail;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
var localStorage = globalThis.localStorage;
|
|
26
|
+
function saveLocal(client, x) {
|
|
27
|
+
localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
18
28
|
}
|
|
19
|
-
function removeLocal() {
|
|
20
|
-
localStorage
|
|
29
|
+
function removeLocal(client) {
|
|
30
|
+
localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
21
31
|
}
|
|
22
|
-
function readLocal() {
|
|
23
|
-
return JSON.parse(
|
|
32
|
+
function readLocal(client) {
|
|
33
|
+
return JSON.parse(
|
|
34
|
+
// MUST `localStorage?` as nodejs does not have localStorage
|
|
35
|
+
localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
36
|
+
);
|
|
24
37
|
}
|
|
25
|
-
function
|
|
26
|
-
|
|
27
|
-
[customFetch]: fetchFn
|
|
28
|
-
};
|
|
38
|
+
function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
39
|
+
let token;
|
|
29
40
|
const eventTarget = new TypedEventTarget();
|
|
30
|
-
const issuer = `${new URL(ctxPath, url)}`;
|
|
31
|
-
const as = {
|
|
32
|
-
token_endpoint: `${issuer}/api/oauth2/token`,
|
|
33
|
-
authorization_endpoint: `${issuer}/api/oauth2/authorize`,
|
|
34
|
-
revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
|
|
35
|
-
issuer
|
|
36
|
-
};
|
|
37
|
-
const client = {
|
|
38
|
-
client_id,
|
|
39
|
-
token_endpoint_auth_method: "none"
|
|
40
|
-
};
|
|
41
|
-
async function go(x) {
|
|
42
|
-
if (useHistory) return window.history.replaceState({}, "", x);
|
|
43
|
-
else window.location.assign(x);
|
|
44
|
-
await delay(1e3);
|
|
45
|
-
throw new Error("Unable to redirect");
|
|
46
|
-
}
|
|
47
41
|
function makeTokenAndSaveRefresh(resp, type) {
|
|
48
42
|
const {
|
|
49
43
|
refresh_token,
|
|
@@ -51,7 +45,7 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
51
45
|
access_token
|
|
52
46
|
} = resp;
|
|
53
47
|
!(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
|
|
54
|
-
saveLocal({
|
|
48
|
+
saveLocal(client, {
|
|
55
49
|
refresh_token
|
|
56
50
|
});
|
|
57
51
|
token = {
|
|
@@ -65,21 +59,139 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
65
59
|
}));
|
|
66
60
|
return token;
|
|
67
61
|
}
|
|
62
|
+
let refreshTimeout;
|
|
63
|
+
function rmTimeout() {
|
|
64
|
+
if (refreshTimeout) clearTimeout(refreshTimeout);
|
|
65
|
+
}
|
|
66
|
+
function restartRefreshTimer(evt) {
|
|
67
|
+
if (refresh) {
|
|
68
|
+
rmTimeout();
|
|
69
|
+
refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function signOut() {
|
|
73
|
+
!token ? process.env.NODE_ENV !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
|
|
74
|
+
const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
|
|
75
|
+
rmTimeout();
|
|
76
|
+
removeLocal(client);
|
|
77
|
+
token = void 0;
|
|
78
|
+
throwIfError(result);
|
|
79
|
+
eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
|
|
80
|
+
}
|
|
81
|
+
let pendingSignIn;
|
|
82
|
+
async function signIn() {
|
|
83
|
+
if (pendingSignIn) {
|
|
84
|
+
return pendingSignIn;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
pendingSignIn = _signIn();
|
|
88
|
+
return await pendingSignIn;
|
|
89
|
+
} finally {
|
|
90
|
+
pendingSignIn = void 0;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
eventTarget.addEventListener("signIn", restartRefreshTimer);
|
|
94
|
+
eventTarget.addEventListener("refresh", restartRefreshTimer);
|
|
95
|
+
function getTokenOrUndefined() {
|
|
96
|
+
if (!token || Date.now() >= token.expires_at) {
|
|
97
|
+
return void 0;
|
|
98
|
+
}
|
|
99
|
+
return token?.access_token;
|
|
100
|
+
}
|
|
101
|
+
const getToken = Object.assign(async function getToken2() {
|
|
102
|
+
if (!token || Date.now() >= token.expires_at) {
|
|
103
|
+
token = await signIn();
|
|
104
|
+
}
|
|
105
|
+
return token.access_token;
|
|
106
|
+
}, {
|
|
107
|
+
signIn,
|
|
108
|
+
refresh,
|
|
109
|
+
signOut,
|
|
110
|
+
rmTimeout,
|
|
111
|
+
getTokenOrUndefined,
|
|
112
|
+
addEventListener: eventTarget.addEventListener.bind(eventTarget),
|
|
113
|
+
removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
|
|
114
|
+
});
|
|
115
|
+
return {
|
|
116
|
+
getToken,
|
|
117
|
+
makeTokenAndSaveRefresh
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function createAuthorizationServer(ctxPath, url) {
|
|
121
|
+
const issuer = `${new URL(ctxPath, url)}`;
|
|
122
|
+
return {
|
|
123
|
+
token_endpoint: `${issuer}/api/oauth2/token`,
|
|
124
|
+
authorization_endpoint: `${issuer}/api/oauth2/authorize`,
|
|
125
|
+
revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
|
|
126
|
+
issuer
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/createConfidentialOauthClient.ts
|
|
131
|
+
function createConfidentialOauthClient(client_id, client_secret, url, scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
|
|
132
|
+
const client = {
|
|
133
|
+
client_id,
|
|
134
|
+
client_secret
|
|
135
|
+
};
|
|
136
|
+
const authServer = createAuthorizationServer(ctxPath, url);
|
|
137
|
+
const oauthHttpOptions = {
|
|
138
|
+
[customFetch]: fetchFn
|
|
139
|
+
};
|
|
140
|
+
const {
|
|
141
|
+
getToken,
|
|
142
|
+
makeTokenAndSaveRefresh
|
|
143
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, void 0);
|
|
144
|
+
async function _signIn() {
|
|
145
|
+
return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
|
|
146
|
+
scope: scopes.join(" ")
|
|
147
|
+
}), oauthHttpOptions))), "signIn");
|
|
148
|
+
}
|
|
149
|
+
return getToken;
|
|
150
|
+
}
|
|
151
|
+
function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
|
|
152
|
+
const client = {
|
|
153
|
+
client_id,
|
|
154
|
+
token_endpoint_auth_method: "none"
|
|
155
|
+
};
|
|
156
|
+
const authServer = createAuthorizationServer(ctxPath, url);
|
|
157
|
+
const oauthHttpOptions = {
|
|
158
|
+
[customFetch]: fetchFn
|
|
159
|
+
};
|
|
160
|
+
if (scopes.length === 0) {
|
|
161
|
+
scopes = ["api:read-data", "api:write-data"];
|
|
162
|
+
}
|
|
163
|
+
const {
|
|
164
|
+
makeTokenAndSaveRefresh,
|
|
165
|
+
getToken
|
|
166
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
|
|
167
|
+
async function go(x) {
|
|
168
|
+
if (useHistory) return window.history.replaceState({}, "", x);
|
|
169
|
+
else window.location.assign(x);
|
|
170
|
+
await delay(1e3);
|
|
171
|
+
throw new Error("Unable to redirect");
|
|
172
|
+
}
|
|
68
173
|
async function maybeRefresh(expectRefreshToken) {
|
|
69
174
|
const {
|
|
70
175
|
refresh_token
|
|
71
|
-
} = readLocal();
|
|
176
|
+
} = readLocal(client);
|
|
72
177
|
if (!refresh_token) {
|
|
73
178
|
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
74
179
|
return;
|
|
75
180
|
}
|
|
76
181
|
try {
|
|
77
|
-
|
|
182
|
+
const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
|
|
183
|
+
if (result && window.location.pathname === new URL(redirectUrl).pathname) {
|
|
184
|
+
const {
|
|
185
|
+
oldUrl
|
|
186
|
+
} = readLocal(client);
|
|
187
|
+
go(oldUrl ?? "/");
|
|
188
|
+
}
|
|
189
|
+
return result;
|
|
78
190
|
} catch (e) {
|
|
79
191
|
if (process?.env?.NODE_ENV !== "production") {
|
|
80
192
|
console.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
|
|
81
193
|
}
|
|
82
|
-
removeLocal();
|
|
194
|
+
removeLocal(client);
|
|
83
195
|
if (expectRefreshToken) {
|
|
84
196
|
throw new Error("Could not refresh token");
|
|
85
197
|
}
|
|
@@ -90,35 +202,35 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
90
202
|
codeVerifier,
|
|
91
203
|
state,
|
|
92
204
|
oldUrl
|
|
93
|
-
} = readLocal();
|
|
205
|
+
} = readLocal(client);
|
|
94
206
|
if (!codeVerifier) return;
|
|
95
207
|
try {
|
|
96
|
-
const
|
|
208
|
+
const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), "signIn");
|
|
97
209
|
go(oldUrl);
|
|
98
|
-
return
|
|
210
|
+
return ret;
|
|
99
211
|
} catch (e) {
|
|
100
212
|
if (process?.env?.NODE_ENV !== "production") {
|
|
101
213
|
console.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
|
|
102
214
|
}
|
|
103
|
-
removeLocal();
|
|
215
|
+
removeLocal(client);
|
|
104
216
|
}
|
|
105
217
|
}
|
|
106
218
|
async function initiateLoginRedirect() {
|
|
107
|
-
if (loginPage && window.location.href !== loginPage) {
|
|
108
|
-
saveLocal({
|
|
219
|
+
if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {
|
|
220
|
+
saveLocal(client, {
|
|
109
221
|
oldUrl: postLoginPage
|
|
110
222
|
});
|
|
111
223
|
return await go(loginPage);
|
|
112
224
|
}
|
|
113
225
|
const state = generateRandomState();
|
|
114
226
|
const codeVerifier = generateRandomCodeVerifier();
|
|
115
|
-
const oldUrl = readLocal().oldUrl ?? window.location.toString();
|
|
116
|
-
saveLocal({
|
|
227
|
+
const oldUrl = readLocal(client).oldUrl ?? window.location.toString();
|
|
228
|
+
saveLocal(client, {
|
|
117
229
|
codeVerifier,
|
|
118
230
|
state,
|
|
119
231
|
oldUrl
|
|
120
232
|
});
|
|
121
|
-
window.location.assign(`${
|
|
233
|
+
window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({
|
|
122
234
|
client_id,
|
|
123
235
|
response_type: "code",
|
|
124
236
|
state,
|
|
@@ -130,57 +242,12 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
130
242
|
await delay(1e3);
|
|
131
243
|
throw new Error("Unable to redirect");
|
|
132
244
|
}
|
|
133
|
-
let refreshTimeout;
|
|
134
|
-
function rmTimeout() {
|
|
135
|
-
if (refreshTimeout) clearTimeout(refreshTimeout);
|
|
136
|
-
}
|
|
137
|
-
function restartRefreshTimer(evt) {
|
|
138
|
-
rmTimeout();
|
|
139
|
-
refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
|
|
140
|
-
}
|
|
141
|
-
const refresh = maybeRefresh.bind(globalThis, true);
|
|
142
|
-
async function signOut() {
|
|
143
|
-
!token ? process.env.NODE_ENV !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
|
|
144
|
-
const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
|
|
145
|
-
rmTimeout();
|
|
146
|
-
removeLocal();
|
|
147
|
-
token = void 0;
|
|
148
|
-
throwIfError(result);
|
|
149
|
-
eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
|
|
150
|
-
}
|
|
151
|
-
let pendingSignIn;
|
|
152
|
-
async function signIn() {
|
|
153
|
-
if (pendingSignIn) {
|
|
154
|
-
return pendingSignIn;
|
|
155
|
-
}
|
|
156
|
-
try {
|
|
157
|
-
pendingSignIn = _signIn();
|
|
158
|
-
return await pendingSignIn;
|
|
159
|
-
} finally {
|
|
160
|
-
pendingSignIn = void 0;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
245
|
async function _signIn() {
|
|
164
|
-
return
|
|
246
|
+
return await maybeRefresh() ?? await maybeHandleAuthReturn() ?? await initiateLoginRedirect();
|
|
165
247
|
}
|
|
166
|
-
|
|
167
|
-
eventTarget.addEventListener("refresh", restartRefreshTimer);
|
|
168
|
-
let token;
|
|
169
|
-
const ret = Object.assign(async function ret2() {
|
|
170
|
-
if (!token || Date.now() >= token.expires_at) {
|
|
171
|
-
token = await signIn();
|
|
172
|
-
}
|
|
173
|
-
return token.access_token;
|
|
174
|
-
}, {
|
|
175
|
-
signIn,
|
|
176
|
-
refresh,
|
|
177
|
-
signOut,
|
|
178
|
-
addEventListener: eventTarget.addEventListener.bind(eventTarget),
|
|
179
|
-
removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
|
|
180
|
-
});
|
|
181
|
-
return ret;
|
|
248
|
+
return getToken;
|
|
182
249
|
}
|
|
183
250
|
|
|
184
|
-
export { createPublicOauthClient };
|
|
185
|
-
//# sourceMappingURL=
|
|
251
|
+
export { createConfidentialOauthClient, createPublicOauthClient };
|
|
252
|
+
//# sourceMappingURL=index.js.map
|
|
186
253
|
//# sourceMappingURL=index.js.map
|
package/build/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/createPublicOauthClient.ts","../../src/throwIfError.ts"],"names":["ret"],"mappings":";AAgBA,OAAO,WAAW;AAClB,SAAS,+BAA+B,4BAA4B,aAAa,4BAA4B,qBAAqB,wCAAwC,2BAA2B,0BAA0B,mBAAmB,4BAA4B;AAC9Q,OAAO,eAAe;AACtB,SAAS,wBAAwB;;;ACHjC,SAAS,qBAAqB;AACvB,SAAS,aAAa,QAAQ;AACnC,MAAI,cAAc,MAAM,GAAG;AACzB,UAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAA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AO,MAAM;AAAA,IACf,UAAE;AACA,sBAAgB;AAAA,IAClB;AAAA,EACF;AAEA,iBAAe,UAAU;AAEvB,WAAO,QAAS,MAAM,aAAa,KAE7B,MAAM,sBAAsB,KAE9B,MAAM,sBAAsB;AAAA,EAClC;AACA,cAAY,iBAAiB,UAAU,mBAAmB;AAC1D,cAAY,iBAAiB,WAAW,mBAAmB;AAC3D,MAAI;AACJ,QAAM,MAAM,OAAO,OAAO,eAAeA,OAAM;AAC7C,QAAI,CAAC,SAAS,KAAK,IAAI,KAAK,MAAM,YAAY;AAC5C,cAAQ,MAAM,OAAO;AAAA,IACvB;AACA,WAAO,MAAM;AAAA,EACf,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA,kBAAkB,YAAY,iBAAiB,KAAK,WAAW;AAAA,IAC/D,qBAAqB,YAAY,oBAAoB,KAAK,WAAW;AAAA,EACvE,CAAC;AACD,SAAO;AACT","sourcesContent":["/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, processRevocationResponse, refreshTokenGrantRequest, revocationRequest, validateAuthResponse } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\nconst storageKey = \"asdfasdfdhjlkajhgj\";\nfunction saveLocal(x) {\n localStorage.setItem(storageKey, JSON.stringify(x));\n}\nfunction removeLocal() {\n localStorage.removeItem(storageKey);\n}\nfunction readLocal() {\n return JSON.parse(localStorage.getItem(storageKey) ?? \"{}\");\n}\n\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const eventTarget = new TypedEventTarget();\n const issuer = `${new URL(ctxPath, url)}`;\n const as = {\n token_endpoint: `${issuer}/api/oauth2/token`,\n authorization_endpoint: `${issuer}/api/oauth2/authorize`,\n revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,\n issuer\n };\n const client = {\n client_id,\n token_endpoint_auth_method: \"none\"\n };\n async function go(x) {\n if (useHistory) return window.history.replaceState({}, \"\", x);else window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n function makeTokenAndSaveRefresh(resp, type) {\n const {\n refresh_token,\n expires_in,\n access_token\n } = resp;\n !(expires_in != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n saveLocal({\n refresh_token\n });\n token = {\n refresh_token,\n expires_in,\n access_token,\n expires_at: Date.now() + expires_in * 1000\n };\n eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {\n detail: token\n }));\n return token;\n }\n async function maybeRefresh(expectRefreshToken) {\n const {\n refresh_token\n } = readLocal();\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await refreshTokenGrantRequest(as, client, refresh_token, oauthHttpOptions))), \"refresh\");\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 refresh token. Removing refresh token\", e);\n }\n removeLocal();\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n async function maybeHandleAuthReturn() {\n const {\n codeVerifier,\n state,\n oldUrl\n } = readLocal();\n if (!codeVerifier) return;\n try {\n const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await authorizationCodeGrantRequest(as, client, throwIfError(validateAuthResponse(as, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), \"signIn\");\n go(oldUrl);\n return ret;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\", e);\n }\n removeLocal();\n }\n }\n async function initiateLoginRedirect() {\n if (loginPage && window.location.href !== loginPage) {\n saveLocal({\n oldUrl: postLoginPage\n });\n return await go(loginPage);\n }\n const state = generateRandomState();\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readLocal().oldUrl ?? window.location.toString();\n saveLocal({\n codeVerifier,\n state,\n oldUrl\n });\n window.location.assign(`${as.authorization_endpoint}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri: redirectUrl,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: [\"offline_access\", ...scopes].join(\" \")\n })}`);\n\n // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout) clearTimeout(refreshTimeout);\n }\n function restartRefreshTimer(evt) {\n rmTimeout();\n refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);\n }\n const refresh = maybeRefresh.bind(globalThis, true);\n async function signOut() {\n !token ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"not signed in\") : invariant(false) : void 0;\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\n\n // Clean up\n removeLocal();\n token = undefined;\n throwIfError(result);\n eventTarget.dispatchTypedEvent(\"signOut\", new Event(\"signOut\"));\n }\n let pendingSignIn;\n async function signIn() {\n if (pendingSignIn) {\n return pendingSignIn;\n }\n try {\n pendingSignIn = _signIn();\n return await pendingSignIn;\n } finally {\n pendingSignIn = undefined;\n }\n }\n /** Will throw if there is no token! */\n async function _signIn() {\n // 1. Check if we have a refresh token in local storage\n return token = (await maybeRefresh()\n // 2. If there is no refresh token we are likely trying to perform the callback\n ) ?? (await maybeHandleAuthReturn())\n // 3. If we haven't been able to load the token from one of the two above ways, we need to make the initial auth request\n ?? (await initiateLoginRedirect());\n }\n eventTarget.addEventListener(\"signIn\", restartRefreshTimer);\n eventTarget.addEventListener(\"refresh\", restartRefreshTimer);\n let token;\n const ret = Object.assign(async function ret() {\n if (!token || Date.now() >= token.expires_at) {\n token = await signIn();\n }\n return token.access_token;\n }, {\n signIn,\n refresh,\n signOut,\n addEventListener: eventTarget.addEventListener.bind(eventTarget),\n removeEventListener: eventTarget.removeEventListener.bind(eventTarget)\n });\n return ret;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/throwIfError.ts","../../src/common.ts","../../src/createConfidentialOauthClient.ts","../../src/createPublicOauthClient.ts"],"names":["CustomEvent","getToken","customFetch"],"mappings":";;;;;;AAiBO,SAAS,aAAa,MAAQ,EAAA;AACnC,EAAI,IAAA,aAAA,CAAc,MAAM,CAAG,EAAA;AACzB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAwB,qBAAA,EAAA,MAAA,CAAO,KAAK,CAAE,CAAA,CAAA,CAAA;AAAA,GACxD;AACA,EAAO,OAAA,MAAA,CAAA;AACT,CAAA;;;ACAA,IAAM,WAAA,GAA0E,WAAW,WAAe,IAAA,MAAMA,qBAAoB,KAAM,CAAA;AAAA,EACxI,OAAA,CAAA;AAAA,EACA,WAAA,CAAY,MAAM,OAAS,EAAA;AACzB,IAAA,KAAA,CAAM,MAAM,OAAO,CAAA,CAAA;AACnB,IAAK,IAAA,CAAA,OAAA,GAAU,SAAS,MAAU,IAAA,IAAA,CAAA;AAAA,GACpC;AAAA,EACA,IAAI,MAAS,GAAA;AACX,IAAA,OAAO,IAAK,CAAA,OAAA,CAAA;AAAA,GACd;AACF,CAAA,CAAA;AACA,IAAM,eAAe,UAAW,CAAA,YAAA,CAAA;AACzB,SAAS,SAAA,CAAU,QAAQ,CAAG,EAAA;AAEnC,EAAc,YAAA,EAAA,OAAA,CAAQ,2BAA2B,MAAO,CAAA,SAAS,IAAI,IAAK,CAAA,SAAA,CAAU,CAAC,CAAC,CAAA,CAAA;AACxF,CAAA;AACO,SAAS,YAAY,MAAQ,EAAA;AAElC,EAAA,YAAA,EAAc,UAAW,CAAA,CAAA,wBAAA,EAA2B,MAAO,CAAA,SAAS,CAAE,CAAA,CAAA,CAAA;AACxE,CAAA;AACO,SAAS,UAAU,MA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GAAI,CAAA,CAAA;AAChB,IAAM,MAAA,IAAI,MAAM,oBAAoB,CAAA,CAAA;AAAA,GACtC;AAGA,EAAA,eAAe,OAAU,GAAA;AAEvB,IAAA,OAAQ,MAAM,YAAa,EAAA,IAErB,MAAM,qBAAsB,EAAA,IAE9B,MAAM,qBAAsB,EAAA,CAAA;AAAA,GAClC;AACA,EAAO,OAAA,QAAA,CAAA;AACT","file":"index.js","sourcesContent":["/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { processRevocationResponse, revocationRequest } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\n// Node 18 is supposed to have a `CustomEvent` but it is not exposed on `globalThis`\n// which creates a problem for making a single codebase for node and browser. This polyfill works around it\nconst CustomEvent = process.env.TARGET === \"browser\" ? globalThis.CustomEvent : globalThis.CustomEvent ?? class CustomEvent extends Event {\n #detail;\n constructor(type, options) {\n super(type, options);\n this.#detail = options?.detail ?? null;\n }\n get detail() {\n return this.#detail;\n }\n};\nconst localStorage = globalThis.localStorage;\nexport function saveLocal(client, x) {\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));\n}\nexport function removeLocal(client) {\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);\n}\nexport function readLocal(client) {\n return JSON.parse(\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? \"{}\");\n}\nexport function common(client, as, _signIn, oauthHttpOptions, refresh) {\n let token;\n const eventTarget = new TypedEventTarget();\n function makeTokenAndSaveRefresh(resp, type) {\n const {\n refresh_token,\n expires_in,\n access_token\n } = resp;\n !(expires_in != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n saveLocal(client, {\n refresh_token\n });\n token = {\n refresh_token,\n expires_in,\n access_token,\n expires_at: Date.now() + expires_in * 1000\n };\n eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {\n detail: token\n }));\n return token;\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout) clearTimeout(refreshTimeout);\n }\n function restartRefreshTimer(evt) {\n if (refresh) {\n rmTimeout();\n refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);\n }\n }\n async function signOut() {\n !token ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"not signed in\") : invariant(false) : void 0;\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\n\n // Clean up\n removeLocal(client);\n token = undefined;\n throwIfError(result);\n eventTarget.dispatchTypedEvent(\"signOut\", new Event(\"signOut\"));\n }\n let pendingSignIn;\n async function signIn() {\n if (pendingSignIn) {\n return pendingSignIn;\n }\n try {\n pendingSignIn = _signIn();\n return await pendingSignIn;\n } finally {\n pendingSignIn = undefined;\n }\n }\n eventTarget.addEventListener(\"signIn\", restartRefreshTimer);\n eventTarget.addEventListener(\"refresh\", restartRefreshTimer);\n function getTokenOrUndefined() {\n if (!token || Date.now() >= token.expires_at) {\n return undefined;\n }\n return token?.access_token;\n }\n const getToken = Object.assign(async function getToken() {\n if (!token || Date.now() >= token.expires_at) {\n token = await signIn();\n }\n return token.access_token;\n }, {\n signIn,\n refresh,\n signOut,\n rmTimeout,\n getTokenOrUndefined,\n addEventListener: eventTarget.addEventListener.bind(eventTarget),\n removeEventListener: eventTarget.removeEventListener.bind(eventTarget)\n });\n return {\n getToken,\n makeTokenAndSaveRefresh\n };\n}\nexport function createAuthorizationServer(ctxPath, url) {\n const issuer = `${new URL(ctxPath, url)}`;\n return {\n token_endpoint: `${issuer}/api/oauth2/token`,\n authorization_endpoint: `${issuer}/api/oauth2/authorize`,\n revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,\n issuer\n };\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { clientCredentialsGrantRequest, customFetch, processClientCredentialsResponse } from \"oauth4webapi\";\nimport { common, createAuthorizationServer } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n\n/**\n * @param client_id\n * @param client_secret\n * @param url the base url of your foundry server\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns which can be used as a token provider\n */\nexport function createConfidentialOauthClient(client_id, client_secret, url, scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = {\n client_id,\n client_secret\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const {\n getToken,\n makeTokenAndSaveRefresh\n } = common(client, authServer, _signIn, oauthHttpOptions, undefined);\n async function _signIn() {\n return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({\n scope: scopes.join(\" \")\n }), oauthHttpOptions))), \"signIn\");\n }\n return getToken;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, validateAuthResponse } from \"oauth4webapi\";\nimport { common, createAuthorizationServer, readLocal, removeLocal, saveLocal } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = {\n client_id,\n token_endpoint_auth_method: \"none\"\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n if (scopes.length === 0) {\n scopes = [\"api:read-data\", \"api:write-data\"];\n }\n const {\n makeTokenAndSaveRefresh,\n getToken\n } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));\n async function go(x) {\n if (useHistory) return window.history.replaceState({}, \"\", x);else window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n async function maybeRefresh(expectRefreshToken) {\n const {\n refresh_token\n } = readLocal(client);\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), \"refresh\");\n if (result && window.location.pathname === new URL(redirectUrl).pathname) {\n const {\n oldUrl\n } = readLocal(client);\n go(oldUrl ?? \"/\");\n }\n return result;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 refresh token. Removing refresh token\", e);\n }\n removeLocal(client);\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n async function maybeHandleAuthReturn() {\n const {\n codeVerifier,\n state,\n oldUrl\n } = readLocal(client);\n if (!codeVerifier) return;\n try {\n const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), \"signIn\");\n go(oldUrl);\n return ret;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\", e);\n }\n removeLocal(client);\n }\n }\n async function initiateLoginRedirect() {\n if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {\n saveLocal(client, {\n oldUrl: postLoginPage\n });\n return await go(loginPage);\n }\n const state = generateRandomState();\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readLocal(client).oldUrl ?? window.location.toString();\n saveLocal(client, {\n codeVerifier,\n state,\n oldUrl\n });\n window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri: redirectUrl,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: [\"offline_access\", ...scopes].join(\" \")\n })}`);\n\n // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n\n /** Will throw if there is no token! */\n async function _signIn() {\n // 1. Check if we have a refresh token in local storage\n return (await maybeRefresh()\n // 2. If there is no refresh token we are likely trying to perform the callback\n ) ?? (await maybeHandleAuthReturn())\n // 3. If we haven't been able to load the token from one of the two above ways, we need to make the initial auth request\n ?? (await initiateLoginRedirect());\n }\n return getToken;\n}"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@osdk/oauth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0-beta.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -24,8 +24,7 @@
|
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"jest-extended": "^4.0.2",
|
|
27
|
-
"
|
|
28
|
-
"typescript": "^5.5.2",
|
|
27
|
+
"typescript": "^5.5.4",
|
|
29
28
|
"@osdk/monorepo.api-extractor": "~0.0.0",
|
|
30
29
|
"@osdk/monorepo.tsup": "~0.0.0",
|
|
31
30
|
"@osdk/monorepo.tsconfig": "~0.0.0"
|
package/build/cjs/index.cjs
DELETED
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var delay = require('delay');
|
|
4
|
-
var oauth4webapi = require('oauth4webapi');
|
|
5
|
-
var invariant = require('tiny-invariant');
|
|
6
|
-
var typescriptEventTarget = require('typescript-event-target');
|
|
7
|
-
|
|
8
|
-
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
9
|
-
|
|
10
|
-
var delay__default = /*#__PURE__*/_interopDefault(delay);
|
|
11
|
-
var invariant__default = /*#__PURE__*/_interopDefault(invariant);
|
|
12
|
-
|
|
13
|
-
// src/createPublicOauthClient.ts
|
|
14
|
-
function throwIfError(result) {
|
|
15
|
-
if (oauth4webapi.isOAuth2Error(result)) {
|
|
16
|
-
throw new Error(`Failed to get token: ${result.error}`);
|
|
17
|
-
}
|
|
18
|
-
return result;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// src/createPublicOauthClient.ts
|
|
22
|
-
var storageKey = "asdfasdfdhjlkajhgj";
|
|
23
|
-
function saveLocal(x) {
|
|
24
|
-
localStorage.setItem(storageKey, JSON.stringify(x));
|
|
25
|
-
}
|
|
26
|
-
function removeLocal() {
|
|
27
|
-
localStorage.removeItem(storageKey);
|
|
28
|
-
}
|
|
29
|
-
function readLocal() {
|
|
30
|
-
return JSON.parse(localStorage.getItem(storageKey) ?? "{}");
|
|
31
|
-
}
|
|
32
|
-
function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginPage, postLoginPage = window.location.toString(), scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
|
|
33
|
-
const oauthHttpOptions = {
|
|
34
|
-
[oauth4webapi.customFetch]: fetchFn
|
|
35
|
-
};
|
|
36
|
-
const eventTarget = new typescriptEventTarget.TypedEventTarget();
|
|
37
|
-
const issuer = `${new URL(ctxPath, url)}`;
|
|
38
|
-
const as = {
|
|
39
|
-
token_endpoint: `${issuer}/api/oauth2/token`,
|
|
40
|
-
authorization_endpoint: `${issuer}/api/oauth2/authorize`,
|
|
41
|
-
revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
|
|
42
|
-
issuer
|
|
43
|
-
};
|
|
44
|
-
const client = {
|
|
45
|
-
client_id,
|
|
46
|
-
token_endpoint_auth_method: "none"
|
|
47
|
-
};
|
|
48
|
-
async function go(x) {
|
|
49
|
-
if (useHistory) return window.history.replaceState({}, "", x);
|
|
50
|
-
else window.location.assign(x);
|
|
51
|
-
await delay__default.default(1e3);
|
|
52
|
-
throw new Error("Unable to redirect");
|
|
53
|
-
}
|
|
54
|
-
function makeTokenAndSaveRefresh(resp, type) {
|
|
55
|
-
const {
|
|
56
|
-
refresh_token,
|
|
57
|
-
expires_in,
|
|
58
|
-
access_token
|
|
59
|
-
} = resp;
|
|
60
|
-
!(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false) : invariant__default.default(false) : void 0;
|
|
61
|
-
saveLocal({
|
|
62
|
-
refresh_token
|
|
63
|
-
});
|
|
64
|
-
token = {
|
|
65
|
-
refresh_token,
|
|
66
|
-
expires_in,
|
|
67
|
-
access_token,
|
|
68
|
-
expires_at: Date.now() + expires_in * 1e3
|
|
69
|
-
};
|
|
70
|
-
eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {
|
|
71
|
-
detail: token
|
|
72
|
-
}));
|
|
73
|
-
return token;
|
|
74
|
-
}
|
|
75
|
-
async function maybeRefresh(expectRefreshToken) {
|
|
76
|
-
const {
|
|
77
|
-
refresh_token
|
|
78
|
-
} = readLocal();
|
|
79
|
-
if (!refresh_token) {
|
|
80
|
-
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
try {
|
|
84
|
-
return makeTokenAndSaveRefresh(throwIfError(await oauth4webapi.processAuthorizationCodeOAuth2Response(as, client, await oauth4webapi.refreshTokenGrantRequest(as, client, refresh_token, oauthHttpOptions))), "refresh");
|
|
85
|
-
} catch (e) {
|
|
86
|
-
if (process?.env?.NODE_ENV !== "production") {
|
|
87
|
-
console.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
|
|
88
|
-
}
|
|
89
|
-
removeLocal();
|
|
90
|
-
if (expectRefreshToken) {
|
|
91
|
-
throw new Error("Could not refresh token");
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
async function maybeHandleAuthReturn() {
|
|
96
|
-
const {
|
|
97
|
-
codeVerifier,
|
|
98
|
-
state,
|
|
99
|
-
oldUrl
|
|
100
|
-
} = readLocal();
|
|
101
|
-
if (!codeVerifier) return;
|
|
102
|
-
try {
|
|
103
|
-
const ret2 = makeTokenAndSaveRefresh(throwIfError(await oauth4webapi.processAuthorizationCodeOAuth2Response(as, client, await oauth4webapi.authorizationCodeGrantRequest(as, client, throwIfError(oauth4webapi.validateAuthResponse(as, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), "signIn");
|
|
104
|
-
go(oldUrl);
|
|
105
|
-
return ret2;
|
|
106
|
-
} catch (e) {
|
|
107
|
-
if (process?.env?.NODE_ENV !== "production") {
|
|
108
|
-
console.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
|
|
109
|
-
}
|
|
110
|
-
removeLocal();
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
async function initiateLoginRedirect() {
|
|
114
|
-
if (loginPage && window.location.href !== loginPage) {
|
|
115
|
-
saveLocal({
|
|
116
|
-
oldUrl: postLoginPage
|
|
117
|
-
});
|
|
118
|
-
return await go(loginPage);
|
|
119
|
-
}
|
|
120
|
-
const state = oauth4webapi.generateRandomState();
|
|
121
|
-
const codeVerifier = oauth4webapi.generateRandomCodeVerifier();
|
|
122
|
-
const oldUrl = readLocal().oldUrl ?? window.location.toString();
|
|
123
|
-
saveLocal({
|
|
124
|
-
codeVerifier,
|
|
125
|
-
state,
|
|
126
|
-
oldUrl
|
|
127
|
-
});
|
|
128
|
-
window.location.assign(`${as.authorization_endpoint}?${new URLSearchParams({
|
|
129
|
-
client_id,
|
|
130
|
-
response_type: "code",
|
|
131
|
-
state,
|
|
132
|
-
redirect_uri: redirectUrl,
|
|
133
|
-
code_challenge: await oauth4webapi.calculatePKCECodeChallenge(codeVerifier),
|
|
134
|
-
code_challenge_method: "S256",
|
|
135
|
-
scope: ["offline_access", ...scopes].join(" ")
|
|
136
|
-
})}`);
|
|
137
|
-
await delay__default.default(1e3);
|
|
138
|
-
throw new Error("Unable to redirect");
|
|
139
|
-
}
|
|
140
|
-
let refreshTimeout;
|
|
141
|
-
function rmTimeout() {
|
|
142
|
-
if (refreshTimeout) clearTimeout(refreshTimeout);
|
|
143
|
-
}
|
|
144
|
-
function restartRefreshTimer(evt) {
|
|
145
|
-
rmTimeout();
|
|
146
|
-
refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
|
|
147
|
-
}
|
|
148
|
-
const refresh = maybeRefresh.bind(globalThis, true);
|
|
149
|
-
async function signOut() {
|
|
150
|
-
!token ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, "not signed in") : invariant__default.default(false) : void 0;
|
|
151
|
-
const result = await oauth4webapi.processRevocationResponse(await oauth4webapi.revocationRequest(as, client, token.access_token, oauthHttpOptions));
|
|
152
|
-
rmTimeout();
|
|
153
|
-
removeLocal();
|
|
154
|
-
token = void 0;
|
|
155
|
-
throwIfError(result);
|
|
156
|
-
eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
|
|
157
|
-
}
|
|
158
|
-
let pendingSignIn;
|
|
159
|
-
async function signIn() {
|
|
160
|
-
if (pendingSignIn) {
|
|
161
|
-
return pendingSignIn;
|
|
162
|
-
}
|
|
163
|
-
try {
|
|
164
|
-
pendingSignIn = _signIn();
|
|
165
|
-
return await pendingSignIn;
|
|
166
|
-
} finally {
|
|
167
|
-
pendingSignIn = void 0;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
async function _signIn() {
|
|
171
|
-
return token = await maybeRefresh() ?? await maybeHandleAuthReturn() ?? await initiateLoginRedirect();
|
|
172
|
-
}
|
|
173
|
-
eventTarget.addEventListener("signIn", restartRefreshTimer);
|
|
174
|
-
eventTarget.addEventListener("refresh", restartRefreshTimer);
|
|
175
|
-
let token;
|
|
176
|
-
const ret = Object.assign(async function ret2() {
|
|
177
|
-
if (!token || Date.now() >= token.expires_at) {
|
|
178
|
-
token = await signIn();
|
|
179
|
-
}
|
|
180
|
-
return token.access_token;
|
|
181
|
-
}, {
|
|
182
|
-
signIn,
|
|
183
|
-
refresh,
|
|
184
|
-
signOut,
|
|
185
|
-
addEventListener: eventTarget.addEventListener.bind(eventTarget),
|
|
186
|
-
removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
|
|
187
|
-
});
|
|
188
|
-
return ret;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
exports.createPublicOauthClient = createPublicOauthClient;
|
|
192
|
-
//# sourceMappingURL=out.js.map
|
|
193
|
-
//# sourceMappingURL=index.cjs.map
|
package/build/cjs/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/createPublicOauthClient.ts","../../src/throwIfError.ts"],"names":["ret"],"mappings":";AAgBA,OAAO,WAAW;AAClB,SAAS,+BAA+B,4BAA4B,aAAa,4BAA4B,qBAAqB,wCAAwC,2BAA2B,0BAA0B,mBAAmB,4BAA4B;AAC9Q,OAAO,eAAe;AACtB,SAAS,wBAAwB;;;ACHjC,SAAS,qBAAqB;AACvB,SAAS,aAAa,QAAQ;AACnC,MAAI,cAAc,MAAM,GAAG;AACzB,UAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,EACxD;AACA,SAAO;AACT;;;ADDA,IAAM,aAAa;AACnB,SAAS,UAAU,GAAG;AACpB,eAAa,QA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AEvB,WAAO,QAAS,MAAM,aAAa,KAE7B,MAAM,sBAAsB,KAE9B,MAAM,sBAAsB;AAAA,EAClC;AACA,cAAY,iBAAiB,UAAU,mBAAmB;AAC1D,cAAY,iBAAiB,WAAW,mBAAmB;AAC3D,MAAI;AACJ,QAAM,MAAM,OAAO,OAAO,eAAeA,OAAM;AAC7C,QAAI,CAAC,SAAS,KAAK,IAAI,KAAK,MAAM,YAAY;AAC5C,cAAQ,MAAM,OAAO;AAAA,IACvB;AACA,WAAO,MAAM;AAAA,EACf,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA,kBAAkB,YAAY,iBAAiB,KAAK,WAAW;AAAA,IAC/D,qBAAqB,YAAY,oBAAoB,KAAK,WAAW;AAAA,EACvE,CAAC;AACD,SAAO;AACT","sourcesContent":["/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, processRevocationResponse, refreshTokenGrantRequest, revocationRequest, validateAuthResponse } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\nconst storageKey = \"asdfasdfdhjlkajhgj\";\nfunction saveLocal(x) {\n localStorage.setItem(storageKey, JSON.stringify(x));\n}\nfunction removeLocal() {\n localStorage.removeItem(storageKey);\n}\nfunction readLocal() {\n return JSON.parse(localStorage.getItem(storageKey) ?? \"{}\");\n}\n\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const eventTarget = new TypedEventTarget();\n const issuer = `${new URL(ctxPath, url)}`;\n const as = {\n token_endpoint: `${issuer}/api/oauth2/token`,\n authorization_endpoint: `${issuer}/api/oauth2/authorize`,\n revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,\n issuer\n };\n const client = {\n client_id,\n token_endpoint_auth_method: \"none\"\n };\n async function go(x) {\n if (useHistory) return window.history.replaceState({}, \"\", x);else window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n function makeTokenAndSaveRefresh(resp, type) {\n const {\n refresh_token,\n expires_in,\n access_token\n } = resp;\n !(expires_in != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n saveLocal({\n refresh_token\n });\n token = {\n refresh_token,\n expires_in,\n access_token,\n expires_at: Date.now() + expires_in * 1000\n };\n eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {\n detail: token\n }));\n return token;\n }\n async function maybeRefresh(expectRefreshToken) {\n const {\n refresh_token\n } = readLocal();\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await refreshTokenGrantRequest(as, client, refresh_token, oauthHttpOptions))), \"refresh\");\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 refresh token. Removing refresh token\", e);\n }\n removeLocal();\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n async function maybeHandleAuthReturn() {\n const {\n codeVerifier,\n state,\n oldUrl\n } = readLocal();\n if (!codeVerifier) return;\n try {\n const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await authorizationCodeGrantRequest(as, client, throwIfError(validateAuthResponse(as, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), \"signIn\");\n go(oldUrl);\n return ret;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\", e);\n }\n removeLocal();\n }\n }\n async function initiateLoginRedirect() {\n if (loginPage && window.location.href !== loginPage) {\n saveLocal({\n oldUrl: postLoginPage\n });\n return await go(loginPage);\n }\n const state = generateRandomState();\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readLocal().oldUrl ?? window.location.toString();\n saveLocal({\n codeVerifier,\n state,\n oldUrl\n });\n window.location.assign(`${as.authorization_endpoint}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri: redirectUrl,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: [\"offline_access\", ...scopes].join(\" \")\n })}`);\n\n // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout) clearTimeout(refreshTimeout);\n }\n function restartRefreshTimer(evt) {\n rmTimeout();\n refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);\n }\n const refresh = maybeRefresh.bind(globalThis, true);\n async function signOut() {\n !token ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"not signed in\") : invariant(false) : void 0;\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\n\n // Clean up\n removeLocal();\n token = undefined;\n throwIfError(result);\n eventTarget.dispatchTypedEvent(\"signOut\", new Event(\"signOut\"));\n }\n let pendingSignIn;\n async function signIn() {\n if (pendingSignIn) {\n return pendingSignIn;\n }\n try {\n pendingSignIn = _signIn();\n return await pendingSignIn;\n } finally {\n pendingSignIn = undefined;\n }\n }\n /** Will throw if there is no token! */\n async function _signIn() {\n // 1. Check if we have a refresh token in local storage\n return token = (await maybeRefresh()\n // 2. If there is no refresh token we are likely trying to perform the callback\n ) ?? (await maybeHandleAuthReturn())\n // 3. If we haven't been able to load the token from one of the two above ways, we need to make the initial auth request\n ?? (await initiateLoginRedirect());\n }\n eventTarget.addEventListener(\"signIn\", restartRefreshTimer);\n eventTarget.addEventListener(\"refresh\", restartRefreshTimer);\n let token;\n const ret = Object.assign(async function ret() {\n if (!token || Date.now() >= token.expires_at) {\n token = await signIn();\n }\n return token.access_token;\n }, {\n signIn,\n refresh,\n signOut,\n addEventListener: eventTarget.addEventListener.bind(eventTarget),\n removeEventListener: eventTarget.removeEventListener.bind(eventTarget)\n });\n return ret;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}"]}
|