@osdk/oauth 0.3.0 → 0.3.2
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 +12 -0
- package/build/browser/index.js +19 -12
- package/build/browser/index.js.map +1 -1
- package/build/cjs/index.cjs +19 -12
- package/build/cjs/index.cjs.map +1 -1
- package/build/esm/common.d.ts +5 -1
- package/build/esm/common.d.ts.map +1 -1
- package/build/esm/common.test.d.ts +2 -0
- package/build/esm/common.test.d.ts.map +1 -0
- package/build/esm/createConfidentialOauthClient.d.ts.map +1 -1
- package/build/esm/createPublicOauthClient.d.ts.map +1 -1
- package/build/esm/index.js +19 -12
- package/build/esm/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @osdk/oauth
|
|
2
2
|
|
|
3
|
+
## 0.3.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 6de6c33: Add overrides for minimatch/picomatch/rollup for CVEs
|
|
8
|
+
|
|
9
|
+
## 0.3.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 75711ff: Added the ability to re-create the refresh token if the operation scopes change
|
|
14
|
+
|
|
3
15
|
## 0.3.0
|
|
4
16
|
|
|
5
17
|
### Minor Changes
|
package/build/browser/index.js
CHANGED
|
@@ -22,20 +22,19 @@ var CustomEvent = process.env.target === "browser" ? globalThis.CustomEvent : gl
|
|
|
22
22
|
return this.#detail;
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
|
-
var localStorage = globalThis.localStorage;
|
|
26
25
|
function saveLocal(client, x) {
|
|
27
|
-
localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
26
|
+
globalThis.localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
28
27
|
}
|
|
29
28
|
function removeLocal(client) {
|
|
30
|
-
localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
29
|
+
globalThis.localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
31
30
|
}
|
|
32
31
|
function readLocal(client) {
|
|
33
32
|
return JSON.parse(
|
|
34
33
|
// MUST `localStorage?` as nodejs does not have localStorage
|
|
35
|
-
localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
34
|
+
globalThis.localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
36
35
|
);
|
|
37
36
|
}
|
|
38
|
-
function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
37
|
+
function common(client, as, _signIn, oauthHttpOptions, refresh, scopes) {
|
|
39
38
|
let token;
|
|
40
39
|
const eventTarget = new TypedEventTarget();
|
|
41
40
|
function makeTokenAndSaveRefresh(resp, type) {
|
|
@@ -46,7 +45,8 @@ function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
|
46
45
|
} = resp;
|
|
47
46
|
!(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
|
|
48
47
|
saveLocal(client, {
|
|
49
|
-
refresh_token
|
|
48
|
+
refresh_token,
|
|
49
|
+
requestedScopes: scopes
|
|
50
50
|
});
|
|
51
51
|
token = {
|
|
52
52
|
refresh_token,
|
|
@@ -130,13 +130,14 @@ function createConfidentialOauthClient(client_id, client_secret, url, scopes = [
|
|
|
130
130
|
const oauthHttpOptions = {
|
|
131
131
|
[customFetch]: fetchFn
|
|
132
132
|
};
|
|
133
|
+
const joinedScopes = scopes.join(" ");
|
|
133
134
|
const {
|
|
134
135
|
getToken,
|
|
135
136
|
makeTokenAndSaveRefresh
|
|
136
|
-
} = common(client, authServer, _signIn, oauthHttpOptions, void 0);
|
|
137
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, void 0, joinedScopes);
|
|
137
138
|
async function _signIn() {
|
|
138
139
|
return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
|
|
139
|
-
scope:
|
|
140
|
+
scope: joinedScopes
|
|
140
141
|
}), oauthHttpOptions))), "signIn");
|
|
141
142
|
}
|
|
142
143
|
return getToken;
|
|
@@ -150,10 +151,11 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
150
151
|
const oauthHttpOptions = {
|
|
151
152
|
[customFetch]: fetchFn
|
|
152
153
|
};
|
|
154
|
+
let joinedScopes = [...scopes ?? ["api:read-data", "api:write-data"]].sort().join(" ");
|
|
153
155
|
const {
|
|
154
156
|
makeTokenAndSaveRefresh,
|
|
155
157
|
getToken
|
|
156
|
-
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
|
|
158
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true), joinedScopes);
|
|
157
159
|
async function go(x) {
|
|
158
160
|
if (useHistory) return window.history.replaceState({}, "", x);
|
|
159
161
|
else window.location.assign(x);
|
|
@@ -162,12 +164,17 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
162
164
|
}
|
|
163
165
|
async function maybeRefresh(expectRefreshToken) {
|
|
164
166
|
const {
|
|
165
|
-
refresh_token
|
|
167
|
+
refresh_token,
|
|
168
|
+
requestedScopes: initialRequestedScopes
|
|
166
169
|
} = readLocal(client);
|
|
167
170
|
if (!refresh_token) {
|
|
168
171
|
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
169
172
|
return;
|
|
170
173
|
}
|
|
174
|
+
if (!refresh_token || !(initialRequestedScopes != null && joinedScopes === initialRequestedScopes)) {
|
|
175
|
+
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
171
178
|
try {
|
|
172
179
|
return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
|
|
173
180
|
} catch (e) {
|
|
@@ -220,7 +227,7 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
220
227
|
redirect_uri: redirectUrl,
|
|
221
228
|
code_challenge: await calculatePKCECodeChallenge(codeVerifier),
|
|
222
229
|
code_challenge_method: "S256",
|
|
223
|
-
scope:
|
|
230
|
+
scope: `offline_access ${joinedScopes}`
|
|
224
231
|
})}`);
|
|
225
232
|
await delay(1e3);
|
|
226
233
|
throw new Error("Unable to redirect");
|
|
@@ -232,5 +239,5 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
232
239
|
}
|
|
233
240
|
|
|
234
241
|
export { createConfidentialOauthClient, createPublicOauthClient };
|
|
235
|
-
//# sourceMappingURL=
|
|
242
|
+
//# sourceMappingURL=index.js.map
|
|
236
243
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/createConfidentialOauthClient.ts","../../src/common.ts","../../src/throwIfError.ts","../../src/createPublicOauthClient.ts"],"names":["CustomEvent","getToken","customFetch"],"mappings":";AAgBA,SAAS,+BAA+B,aAAa,wCAAwC;;;ACA7F,SAAS,2BAA2B,yBAAyB;AAC7D,OAAO,eAAe;AACtB,SAAS,wBAAwB;;;ACFjC,SAAS,qBAAqB;AACvB,SAAS,aAAa,QAAQ;AACnC,MAAI,cAAc,MAAM,GAAG;AACzB,UAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,EACxD;AACA,SAAO;AACT;;;ADAA,IAAM,cAAc,QAAQ,IAAI,WAAW,YAAY,WAAW,cAAc,WAAW,eAAe,MAAMA,qBAAoB,MAAM;AAAA,EACxI;AAAA,EACA,YAAY,MAAM,SAAS;AACzB,UAAM,MAAM,OAAO;AACnB,SAAK,UAAU,SAAS,UAAU;AAAA,EACpC;AAAA,EACA,IAAI,SAAS;AAC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,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,WAAO,SAAS,OAAO,GAAG,WAAW,sBAAsB,IAAI,IAAI,gBAAgB;AAAA,MACjF;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA,cAAc;AAAA,MACd,gBAAgB,MAAM,2BAA2B,YAAY;AAAA,MAC7D,uBAAuB;AAAA,MACvB,OAAO,CAAC,kBAAkB,GAAG,MAAM,EAAE,KAAK,GAAG;AAAA,IAC/C,CAAC,CAAC,EAAE;AAGJ,UAAM,MAAM,GAAI;AAChB,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAGA,iBAAe,UAAU;AAEvB,WAAQ,MAAM,aAAa,KAErB,MAAM,sBAAsB,KAE9B,MAAM,sBAAsB;AAAA,EAClC;AACA,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 { 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 { 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 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 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 { 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 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, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], 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 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 return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, 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(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) {\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}"]}
|
|
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,GAAc,OAAQ,CAAA,GAAA,CAAI,MAAW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M,EAAE,MAAU,IAAA,MAAA,CAAO,SAAS,QAAS,EAAA,CAAA;AACpE,IAAA,SAAA,CAAU,MAAQ,EAAA;AAAA,MAChB,YAAA;AAAA,MACA,KAAA;AAAA,MACA,MAAA;AAAA,KACD,CAAA,CAAA;AACD,IAAA,MAAA,CAAO,SAAS,MAAO,CAAA,CAAA,EAAG,WAAW,sBAAsB,CAAA,CAAA,EAAI,IAAI,eAAgB,CAAA;AAAA,MACjF,SAAA;AAAA,MACA,aAAe,EAAA,MAAA;AAAA,MACf,KAAA;AAAA,MACA,YAAc,EAAA,WAAA;AAAA,MACd,cAAA,EAAgB,MAAM,0BAAA,CAA2B,YAAY,CAAA;AAAA,MAC7D,qBAAuB,EAAA,MAAA;AAAA,MACvB,KAAA,EAAO,kBAAkB,YAAY,CAAA,CAAA;AAAA,KACtC,CAAC,CAAE,CAAA,CAAA,CAAA;AAGJ,IAAA,MAAM,MAAM,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};\nexport function saveLocal(client, x) {\n // MUST `localStorage?` as nodejs does not have localStorage\n globalThis.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 globalThis.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 globalThis.localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? \"{}\");\n}\nexport function common(client, as, _signIn, oauthHttpOptions, refresh, scopes) {\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 requestedScopes: scopes\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 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 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 joinedScopes = scopes.join(\" \");\n const {\n getToken,\n makeTokenAndSaveRefresh\n } = common(client, authServer, _signIn, oauthHttpOptions, undefined, joinedScopes);\n async function _signIn() {\n return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({\n scope: joinedScopes\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, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], 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 let joinedScopes = [...(scopes ?? [\"api:read-data\", \"api:write-data\"])].sort().join(\" \");\n const {\n makeTokenAndSaveRefresh,\n getToken\n } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true), joinedScopes);\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 requestedScopes: initialRequestedScopes\n } = readLocal(client);\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n if (!refresh_token || !(initialRequestedScopes != null && joinedScopes === initialRequestedScopes)) {\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(authServer, client, await refreshTokenGrantRequest(authServer, 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(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) {\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 ${joinedScopes}`\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/build/cjs/index.cjs
CHANGED
|
@@ -29,20 +29,19 @@ var CustomEvent = process.env.target === "browser" ? globalThis.CustomEvent : gl
|
|
|
29
29
|
return this.#detail;
|
|
30
30
|
}
|
|
31
31
|
};
|
|
32
|
-
var localStorage = globalThis.localStorage;
|
|
33
32
|
function saveLocal(client, x) {
|
|
34
|
-
localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
33
|
+
globalThis.localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
35
34
|
}
|
|
36
35
|
function removeLocal(client) {
|
|
37
|
-
localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
36
|
+
globalThis.localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
38
37
|
}
|
|
39
38
|
function readLocal(client) {
|
|
40
39
|
return JSON.parse(
|
|
41
40
|
// MUST `localStorage?` as nodejs does not have localStorage
|
|
42
|
-
localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
41
|
+
globalThis.localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
43
42
|
);
|
|
44
43
|
}
|
|
45
|
-
function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
44
|
+
function common(client, as, _signIn, oauthHttpOptions, refresh, scopes) {
|
|
46
45
|
let token;
|
|
47
46
|
const eventTarget = new typescriptEventTarget.TypedEventTarget();
|
|
48
47
|
function makeTokenAndSaveRefresh(resp, type) {
|
|
@@ -53,7 +52,8 @@ function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
|
53
52
|
} = resp;
|
|
54
53
|
!(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false) : invariant__default.default(false) : void 0;
|
|
55
54
|
saveLocal(client, {
|
|
56
|
-
refresh_token
|
|
55
|
+
refresh_token,
|
|
56
|
+
requestedScopes: scopes
|
|
57
57
|
});
|
|
58
58
|
token = {
|
|
59
59
|
refresh_token,
|
|
@@ -137,13 +137,14 @@ function createConfidentialOauthClient(client_id, client_secret, url, scopes = [
|
|
|
137
137
|
const oauthHttpOptions = {
|
|
138
138
|
[oauth4webapi.customFetch]: fetchFn
|
|
139
139
|
};
|
|
140
|
+
const joinedScopes = scopes.join(" ");
|
|
140
141
|
const {
|
|
141
142
|
getToken,
|
|
142
143
|
makeTokenAndSaveRefresh
|
|
143
|
-
} = common(client, authServer, _signIn, oauthHttpOptions, void 0);
|
|
144
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, void 0, joinedScopes);
|
|
144
145
|
async function _signIn() {
|
|
145
146
|
return makeTokenAndSaveRefresh(throwIfError(await oauth4webapi.processClientCredentialsResponse(authServer, client, await oauth4webapi.clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
|
|
146
|
-
scope:
|
|
147
|
+
scope: joinedScopes
|
|
147
148
|
}), oauthHttpOptions))), "signIn");
|
|
148
149
|
}
|
|
149
150
|
return getToken;
|
|
@@ -157,10 +158,11 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
157
158
|
const oauthHttpOptions = {
|
|
158
159
|
[oauth4webapi.customFetch]: fetchFn
|
|
159
160
|
};
|
|
161
|
+
let joinedScopes = [...scopes ?? ["api:read-data", "api:write-data"]].sort().join(" ");
|
|
160
162
|
const {
|
|
161
163
|
makeTokenAndSaveRefresh,
|
|
162
164
|
getToken
|
|
163
|
-
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
|
|
165
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true), joinedScopes);
|
|
164
166
|
async function go(x) {
|
|
165
167
|
if (useHistory) return window.history.replaceState({}, "", x);
|
|
166
168
|
else window.location.assign(x);
|
|
@@ -169,12 +171,17 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
169
171
|
}
|
|
170
172
|
async function maybeRefresh(expectRefreshToken) {
|
|
171
173
|
const {
|
|
172
|
-
refresh_token
|
|
174
|
+
refresh_token,
|
|
175
|
+
requestedScopes: initialRequestedScopes
|
|
173
176
|
} = readLocal(client);
|
|
174
177
|
if (!refresh_token) {
|
|
175
178
|
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
176
179
|
return;
|
|
177
180
|
}
|
|
181
|
+
if (!refresh_token || !(initialRequestedScopes != null && joinedScopes === initialRequestedScopes)) {
|
|
182
|
+
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
178
185
|
try {
|
|
179
186
|
return makeTokenAndSaveRefresh(throwIfError(await oauth4webapi.processAuthorizationCodeOAuth2Response(authServer, client, await oauth4webapi.refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
|
|
180
187
|
} catch (e) {
|
|
@@ -227,7 +234,7 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
227
234
|
redirect_uri: redirectUrl,
|
|
228
235
|
code_challenge: await oauth4webapi.calculatePKCECodeChallenge(codeVerifier),
|
|
229
236
|
code_challenge_method: "S256",
|
|
230
|
-
scope:
|
|
237
|
+
scope: `offline_access ${joinedScopes}`
|
|
231
238
|
})}`);
|
|
232
239
|
await delay__default.default(1e3);
|
|
233
240
|
throw new Error("Unable to redirect");
|
|
@@ -240,5 +247,5 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
240
247
|
|
|
241
248
|
exports.createConfidentialOauthClient = createConfidentialOauthClient;
|
|
242
249
|
exports.createPublicOauthClient = createPublicOauthClient;
|
|
243
|
-
//# sourceMappingURL=
|
|
250
|
+
//# sourceMappingURL=index.cjs.map
|
|
244
251
|
//# sourceMappingURL=index.cjs.map
|
package/build/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/createConfidentialOauthClient.ts","../../src/common.ts","../../src/throwIfError.ts","../../src/createPublicOauthClient.ts"],"names":["CustomEvent","getToken","customFetch"],"mappings":";AAgBA,SAAS,+BAA+B,aAAa,wCAAwC;;;ACA7F,SAAS,2BAA2B,yBAAyB;AAC7D,OAAO,eAAe;AACtB,SAAS,wBAAwB;;;ACFjC,SAAS,qBAAqB;AACvB,SAAS,aAAa,QAAQ;AACnC,MAAI,cAAc,MAAM,GAAG;AACzB,UAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,EACxD;AACA,SAAO;AACT;;;ADAA,IAAM,cAAc,QAAQ,IAAI,WAAW,YAAY,WAAW,cAAc,WAAW,eAAe,MAAMA,qBAAoB,MAAM;AAAA,EACxI;AAAA,EACA,YAAY,MAAM,SAAS;AACzB,UAAM,MAAM,OAAO;AACnB,SAAK,UAAU,SAAS,UAAU;AAAA,EACpC;AAAA,EACA,IAAI,SAAS;AACX,WAAO,KAAK;AAAA,EACd;AACF;AACA,IAAM,eAAe,WAAW;AACzB,SAAS,UAAU,QAAQ,GAAG;AAEnC,gBAAc,QAAQ,2BAA2B,OAAO,SAAS,IAAI,KAAK,UAAU,CAAC,CAAC;AACxF;AACO,SAAS,YAAY,QAAQ;AAElC,gBAAc,WAAW,2BAA2B,OAAO,SAAS,EAAE;AACxE;AACO,SAAS,UAAU,QAAQ;AAChC,SAAO,KAAK;AAAA;AAAA,IAEZ,cAAc,QAAQ,2BAA2B,OAAO,SAAS,EAAE,KAAK;AAAA,EAAI;AAC9E;AACO,SAAS,OAAO,QAAQ,IAAI,SAAS,kBAAkB,SAAS;AACrE,MAAI;AACJ,QAAM,cAAc,IAAI,iBAAiB;AACzC,WAAS,wBAAwB,MAAM,MAAM;AAC3C,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,IACF,IAAI;AAC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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 { 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 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 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 { 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 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, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], 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 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 return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, 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(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) {\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}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/throwIfError.ts","../../src/common.ts","../../src/createConfidentialOauthClient.ts","../../src/createPublicOauthClient.ts"],"names":["isOAuth2Error","CustomEvent","TypedEventTarget","invariant","processRevocationResponse","revocationRequest","getToken","customFetch","processClientCredentialsResponse","clientCredentialsGrantRequest","delay","processAuthorizationCodeOAuth2Response","refreshTokenGrantRequest","authorizationCodeGrantRequest","validateAuthResponse","generateRandomState","generateRandomCodeVerifier","calculatePKCECodeChallenge"],"mappings":";;;;;;;;;;;;;AAiBO,SAAS,aAAa,MAAQ,EAAA;AACnC,EAAI,IAAAA,0BAAA,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,GAAc,OAAQ,CAAA,GAAA,CAAI,MAAW,KAAA,SAAA,GAAY,UAAW,CAAA,WAAA,GAAc,UAAW,CAAA,WAAA,IAAe,MAAMC,YAAAA,SAAoB,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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A;AAAA,MACA,YAAc,EAAA,WAAA;AAAA,MACd,cAAA,EAAgB,MAAMC,uCAAA,CAA2B,YAAY,CAAA;AAAA,MAC7D,qBAAuB,EAAA,MAAA;AAAA,MACvB,KAAA,EAAO,kBAAkB,YAAY,CAAA,CAAA;AAAA,KACtC,CAAC,CAAE,CAAA,CAAA,CAAA;AAGJ,IAAA,MAAMP,uBAAM,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.cjs","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};\nexport function saveLocal(client, x) {\n // MUST `localStorage?` as nodejs does not have localStorage\n globalThis.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 globalThis.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 globalThis.localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? \"{}\");\n}\nexport function common(client, as, _signIn, oauthHttpOptions, refresh, scopes) {\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 requestedScopes: scopes\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 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 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 joinedScopes = scopes.join(\" \");\n const {\n getToken,\n makeTokenAndSaveRefresh\n } = common(client, authServer, _signIn, oauthHttpOptions, undefined, joinedScopes);\n async function _signIn() {\n return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({\n scope: joinedScopes\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, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], 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 let joinedScopes = [...(scopes ?? [\"api:read-data\", \"api:write-data\"])].sort().join(\" \");\n const {\n makeTokenAndSaveRefresh,\n getToken\n } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true), joinedScopes);\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 requestedScopes: initialRequestedScopes\n } = readLocal(client);\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n if (!refresh_token || !(initialRequestedScopes != null && joinedScopes === initialRequestedScopes)) {\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(authServer, client, await refreshTokenGrantRequest(authServer, 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(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) {\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 ${joinedScopes}`\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/build/esm/common.d.ts
CHANGED
|
@@ -6,26 +6,30 @@ type LocalStorageState = {
|
|
|
6
6
|
codeVerifier?: never;
|
|
7
7
|
state?: never;
|
|
8
8
|
oldUrl: string;
|
|
9
|
+
requestedScopes?: string;
|
|
9
10
|
} | {
|
|
10
11
|
refresh_token?: never;
|
|
11
12
|
codeVerifier: string;
|
|
12
13
|
state: string;
|
|
13
14
|
oldUrl: string;
|
|
15
|
+
requestedScopes?: string;
|
|
14
16
|
} | {
|
|
15
17
|
refresh_token?: string;
|
|
16
18
|
codeVerifier?: never;
|
|
17
19
|
state?: never;
|
|
18
20
|
oldUrl?: never;
|
|
21
|
+
requestedScopes?: string;
|
|
19
22
|
} | {
|
|
20
23
|
refresh_token?: never;
|
|
21
24
|
codeVerifier?: never;
|
|
22
25
|
state?: never;
|
|
23
26
|
oldUrl?: never;
|
|
27
|
+
requestedScopes?: string;
|
|
24
28
|
};
|
|
25
29
|
export declare function saveLocal(client: Client, x: LocalStorageState): void;
|
|
26
30
|
export declare function removeLocal(client: Client): void;
|
|
27
31
|
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): {
|
|
32
|
+
export declare function common<R extends undefined | (() => Promise<Token | undefined>)>(client: Client, as: AuthorizationServer, _signIn: () => Promise<Token>, oauthHttpOptions: HttpRequestOptions, refresh: R, scopes: string): {
|
|
29
33
|
getToken: BaseOauthClient<keyof Events & string> & {
|
|
30
34
|
refresh: R;
|
|
31
35
|
};
|
|
@@ -1 +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,MAAM,cAAc,CAAC;AAItB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAEpE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":"AAgBA,OAAO,K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AO,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC,EAExD,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,mBAAmB,EACvB,OAAO,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,EAC7B,gBAAgB,EAAE,kBAAkB,EACpC,OAAO,EAAE,CAAC,EACV,MAAM,EAAE,MAAM,GACb;IACD,QAAQ,EAAE,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,CAkGA;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 @@
|
|
|
1
|
+
{"version":3,"file":"common.test.d.ts","sourceRoot":"","sources":["../../src/common.test.ts"],"names":[],"mappings":""}
|
|
@@ -1 +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,
|
|
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,CAkCzB"}
|
|
@@ -1 +1 @@
|
|
|
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,CAAC,EAAE,OAAO,EACpB,SAAS,CAAC,EAAE,MAAM,EAClB,aAAa,GAAE,MAAmC,EAClD,MAAM,GAAE,MAAM,EAAwC,EACtD,OAAO,GAAE,OAAO,UAAU,CAAC,KAAwB,EACnD,OAAO,GAAE,MAAqB,GAC7B,iBAAiB,
|
|
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,CAAC,EAAE,OAAO,EACpB,SAAS,CAAC,EAAE,MAAM,EAClB,aAAa,GAAE,MAAmC,EAClD,MAAM,GAAE,MAAM,EAAwC,EACtD,OAAO,GAAE,OAAO,UAAU,CAAC,KAAwB,EACnD,OAAO,GAAE,MAAqB,GAC7B,iBAAiB,CA6JnB"}
|
package/build/esm/index.js
CHANGED
|
@@ -22,20 +22,19 @@ var CustomEvent = process.env.target === "browser" ? globalThis.CustomEvent : gl
|
|
|
22
22
|
return this.#detail;
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
|
-
var localStorage = globalThis.localStorage;
|
|
26
25
|
function saveLocal(client, x) {
|
|
27
|
-
localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
26
|
+
globalThis.localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
28
27
|
}
|
|
29
28
|
function removeLocal(client) {
|
|
30
|
-
localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
29
|
+
globalThis.localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
31
30
|
}
|
|
32
31
|
function readLocal(client) {
|
|
33
32
|
return JSON.parse(
|
|
34
33
|
// MUST `localStorage?` as nodejs does not have localStorage
|
|
35
|
-
localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
34
|
+
globalThis.localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
36
35
|
);
|
|
37
36
|
}
|
|
38
|
-
function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
37
|
+
function common(client, as, _signIn, oauthHttpOptions, refresh, scopes) {
|
|
39
38
|
let token;
|
|
40
39
|
const eventTarget = new TypedEventTarget();
|
|
41
40
|
function makeTokenAndSaveRefresh(resp, type) {
|
|
@@ -46,7 +45,8 @@ function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
|
46
45
|
} = resp;
|
|
47
46
|
!(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
|
|
48
47
|
saveLocal(client, {
|
|
49
|
-
refresh_token
|
|
48
|
+
refresh_token,
|
|
49
|
+
requestedScopes: scopes
|
|
50
50
|
});
|
|
51
51
|
token = {
|
|
52
52
|
refresh_token,
|
|
@@ -130,13 +130,14 @@ function createConfidentialOauthClient(client_id, client_secret, url, scopes = [
|
|
|
130
130
|
const oauthHttpOptions = {
|
|
131
131
|
[customFetch]: fetchFn
|
|
132
132
|
};
|
|
133
|
+
const joinedScopes = scopes.join(" ");
|
|
133
134
|
const {
|
|
134
135
|
getToken,
|
|
135
136
|
makeTokenAndSaveRefresh
|
|
136
|
-
} = common(client, authServer, _signIn, oauthHttpOptions, void 0);
|
|
137
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, void 0, joinedScopes);
|
|
137
138
|
async function _signIn() {
|
|
138
139
|
return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
|
|
139
|
-
scope:
|
|
140
|
+
scope: joinedScopes
|
|
140
141
|
}), oauthHttpOptions))), "signIn");
|
|
141
142
|
}
|
|
142
143
|
return getToken;
|
|
@@ -150,10 +151,11 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
150
151
|
const oauthHttpOptions = {
|
|
151
152
|
[customFetch]: fetchFn
|
|
152
153
|
};
|
|
154
|
+
let joinedScopes = [...scopes ?? ["api:read-data", "api:write-data"]].sort().join(" ");
|
|
153
155
|
const {
|
|
154
156
|
makeTokenAndSaveRefresh,
|
|
155
157
|
getToken
|
|
156
|
-
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
|
|
158
|
+
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true), joinedScopes);
|
|
157
159
|
async function go(x) {
|
|
158
160
|
if (useHistory) return window.history.replaceState({}, "", x);
|
|
159
161
|
else window.location.assign(x);
|
|
@@ -162,12 +164,17 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
162
164
|
}
|
|
163
165
|
async function maybeRefresh(expectRefreshToken) {
|
|
164
166
|
const {
|
|
165
|
-
refresh_token
|
|
167
|
+
refresh_token,
|
|
168
|
+
requestedScopes: initialRequestedScopes
|
|
166
169
|
} = readLocal(client);
|
|
167
170
|
if (!refresh_token) {
|
|
168
171
|
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
169
172
|
return;
|
|
170
173
|
}
|
|
174
|
+
if (!refresh_token || !(initialRequestedScopes != null && joinedScopes === initialRequestedScopes)) {
|
|
175
|
+
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
171
178
|
try {
|
|
172
179
|
return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
|
|
173
180
|
} catch (e) {
|
|
@@ -220,7 +227,7 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
220
227
|
redirect_uri: redirectUrl,
|
|
221
228
|
code_challenge: await calculatePKCECodeChallenge(codeVerifier),
|
|
222
229
|
code_challenge_method: "S256",
|
|
223
|
-
scope:
|
|
230
|
+
scope: `offline_access ${joinedScopes}`
|
|
224
231
|
})}`);
|
|
225
232
|
await delay(1e3);
|
|
226
233
|
throw new Error("Unable to redirect");
|
|
@@ -232,5 +239,5 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
|
|
|
232
239
|
}
|
|
233
240
|
|
|
234
241
|
export { createConfidentialOauthClient, createPublicOauthClient };
|
|
235
|
-
//# sourceMappingURL=
|
|
242
|
+
//# sourceMappingURL=index.js.map
|
|
236
243
|
//# sourceMappingURL=index.js.map
|
package/build/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/createConfidentialOauthClient.ts","../../src/common.ts","../../src/throwIfError.ts","../../src/createPublicOauthClient.ts"],"names":["CustomEvent","getToken","customFetch"],"mappings":";AAgBA,SAAS,+BAA+B,aAAa,wCAAwC;;;ACA7F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AAS,GAAG;AACV,UAAI,SAAS,KAAK,aAAa,cAAc;AAE3C,gBAAQ,KAAK,qFAAqF,CAAC;AAAA,MACrG;AACA,kBAAY,MAAM;AAAA,IACpB;AAAA,EACF;AACA,iBAAe,wBAAwB;AACrC,QAAI,aAAa,OAAO,SAAS,SAAS,WAAW;AACnD,gBAAU,QAAQ;AAAA,QAChB,QAAQ;AAAA,MACV,CAAC;AACD,aAAO,MAAM,GAAG,SAAS;AAAA,IAC3B;AACA,UAAM,QAAQ,oBAAoB;AAClC,UAAM,eAAe,2BAA2B;AAChD,UAAM,SAAS,UAAU,MAAM,EAAE,UAAU,OAAO,SAAS,SAAS;AACpE,cAAU,QAAQ;AAAA,MAChB;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,WAAO,SAAS,OAAO,GAAG,WAAW,sBAAsB,IAAI,IAAI,gBAAgB;AAAA,MACjF;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA,cAAc;AAAA,MACd,gBAAgB,MAAM,2BAA2B,YAAY;AAAA,MAC7D,uBAAuB;AAAA,MACvB,OAAO,CAAC,kBAAkB,GAAG,MAAM,EAAE,KAAK,GAAG;AAAA,IAC/C,CAAC,CAAC,EAAE;AAGJ,UAAM,MAAM,GAAI;AAChB,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAGA,iBAAe,UAAU;AAEvB,WAAQ,MAAM,aAAa,KAErB,MAAM,sBAAsB,KAE9B,MAAM,sBAAsB;AAAA,EAClC;AACA,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 { 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 { 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 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 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 { 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 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, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], 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 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 return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, 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(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) {\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}"]}
|
|
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,GAAc,OAAQ,CAAA,GAAA,CAAI,MAAW,KAAA,SAAA,GAAY,UAAW,CAAA,WAAA,GAAc,UAAW,CAAA,WAAA,IAAe,MAAMA,YAAAA,SAAoB,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;AACO,SAAS,SAAA,CAAU,QAAQ,CAAG,EAAA;AAEnC,EAAW,UAAA,CAAA,YAAA,EAAc,QAAQ,CAA2B,wBAAA,EAAA,MAAA,CAAO,SAAS,CAAI,CAAA,EAAA,IAAA,CAAK,SAAU,CAAA,CAAC,CAAC,CAAA,CAAA;AACnG,CAAA;AACO,SAAS,YAAY,MAAQ,EAAA;AAElC,EAAA,UAAA,CAAW,YAAc,EAAA,UAAA,CAAW,CAA2B,wBAAA,EAAA,MAAA,CAAO,SAAS,CAAE,CAAA,CAAA,CAAA;AACnF,CAAA;AACO,SAAS,UAAU,MAAQ,EAAA;AAChC,EAAA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A,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};\nexport function saveLocal(client, x) {\n // MUST `localStorage?` as nodejs does not have localStorage\n globalThis.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 globalThis.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 globalThis.localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? \"{}\");\n}\nexport function common(client, as, _signIn, oauthHttpOptions, refresh, scopes) {\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 requestedScopes: scopes\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 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 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 joinedScopes = scopes.join(\" \");\n const {\n getToken,\n makeTokenAndSaveRefresh\n } = common(client, authServer, _signIn, oauthHttpOptions, undefined, joinedScopes);\n async function _signIn() {\n return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({\n scope: joinedScopes\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, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], 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 let joinedScopes = [...(scopes ?? [\"api:read-data\", \"api:write-data\"])].sort().join(\" \");\n const {\n makeTokenAndSaveRefresh,\n getToken\n } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true), joinedScopes);\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 requestedScopes: initialRequestedScopes\n } = readLocal(client);\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n if (!refresh_token || !(initialRequestedScopes != null && joinedScopes === initialRequestedScopes)) {\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(authServer, client, await refreshTokenGrantRequest(authServer, 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(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) {\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 ${joinedScopes}`\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.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -24,9 +24,9 @@
|
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"jest-extended": "^4.0.2",
|
|
27
|
-
"typescript": "^5.5.
|
|
28
|
-
"@osdk/monorepo.tsconfig": "~0.0.0",
|
|
27
|
+
"typescript": "^5.5.4",
|
|
29
28
|
"@osdk/monorepo.api-extractor": "~0.0.0",
|
|
29
|
+
"@osdk/monorepo.tsconfig": "~0.0.0",
|
|
30
30
|
"@osdk/monorepo.tsup": "~0.0.0"
|
|
31
31
|
},
|
|
32
32
|
"publishConfig": {
|