@osdk/oauth 1.8.0-beta.4 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/build/browser/Logger.js +2 -0
- package/build/browser/Logger.js.map +1 -0
- package/build/browser/createPublicOauthClient.js +5 -5
- package/build/browser/createPublicOauthClient.js.map +1 -1
- package/build/browser/index.js.map +1 -1
- package/build/browser/utils.js +2 -1
- package/build/browser/utils.js.map +1 -1
- package/build/cjs/index.cjs +7 -4
- package/build/cjs/index.cjs.map +1 -1
- package/build/cjs/index.d.cts +10 -1
- package/build/esm/Logger.js +2 -0
- package/build/esm/Logger.js.map +1 -0
- package/build/esm/createPublicOauthClient.js +5 -5
- package/build/esm/createPublicOauthClient.js.map +1 -1
- package/build/esm/index.js.map +1 -1
- package/build/esm/utils.js +2 -1
- package/build/esm/utils.js.map +1 -1
- package/build/types/Logger.d.ts +3 -0
- package/build/types/Logger.d.ts.map +1 -0
- package/build/types/createPublicOauthClient.d.ts +6 -0
- package/build/types/createPublicOauthClient.d.ts.map +1 -1
- package/build/types/index.d.ts +1 -0
- package/build/types/index.d.ts.map +1 -1
- package/build/types/utils.d.ts +3 -1
- package/build/types/utils.d.ts.map +1 -1
- package/package.json +3 -3
- package/build/browser/AuthorizationServer.test.js +0 -53
- package/build/browser/AuthorizationServer.test.js.map +0 -1
- package/build/browser/__tests__/createPublicOauthClient.test.js +0 -59
- package/build/browser/__tests__/createPublicOauthClient.test.js.map +0 -1
- package/build/browser/common.test.js +0 -68
- package/build/browser/common.test.js.map +0 -1
- package/build/browser/createAuthlessClient.test.js +0 -31
- package/build/browser/createAuthlessClient.test.js.map +0 -1
- package/build/browser/publicOauth.test.js +0 -430
- package/build/browser/publicOauth.test.js.map +0 -1
- package/build/esm/AuthorizationServer.test.js +0 -53
- package/build/esm/AuthorizationServer.test.js.map +0 -1
- package/build/esm/__tests__/createPublicOauthClient.test.js +0 -59
- package/build/esm/__tests__/createPublicOauthClient.test.js.map +0 -1
- package/build/esm/common.test.js +0 -68
- package/build/esm/common.test.js.map +0 -1
- package/build/esm/createAuthlessClient.test.js +0 -31
- package/build/esm/createAuthlessClient.test.js.map +0 -1
- package/build/esm/publicOauth.test.js +0 -430
- package/build/esm/publicOauth.test.js.map +0 -1
- package/build/types/AuthorizationServer.test.d.ts +0 -1
- package/build/types/AuthorizationServer.test.d.ts.map +0 -1
- package/build/types/__tests__/createPublicOauthClient.test.d.ts +0 -1
- package/build/types/__tests__/createPublicOauthClient.test.d.ts.map +0 -1
- package/build/types/common.test.d.ts +0 -1
- package/build/types/common.test.d.ts.map +0 -1
- package/build/types/createAuthlessClient.test.d.ts +0 -1
- package/build/types/createAuthlessClient.test.d.ts.map +0 -1
- package/build/types/publicOauth.test.d.ts +0 -1
- package/build/types/publicOauth.test.d.ts.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @osdk/oauth
|
|
2
2
|
|
|
3
|
+
## 1.8.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 322c5bc: Simulated release
|
|
8
|
+
- 05cae47: Add optional `logger` parameter to `createPublicOauthClient` for consumer-controlled warning output
|
|
9
|
+
- 4cd7389: Remove delay dependency
|
|
10
|
+
- 35f2f1a: Add Media inputs/outputs for Queries
|
|
11
|
+
- c9d954d: Add `tokenStorage` option to `createPublicOauthClient` to control refresh token storage. Supports `'localStorage'` (default), `'sessionStorage'` (recommended for shared devices), or `'none'` (most secure, re-authenticates on every page load).
|
|
12
|
+
|
|
13
|
+
## 1.8.0-beta.5
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- 05cae47: Add optional `logger` parameter to `createPublicOauthClient` for consumer-controlled warning output
|
|
18
|
+
|
|
3
19
|
## 1.8.0-beta.4
|
|
4
20
|
|
|
5
21
|
### Minor Changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Logger.js","names":[],"sources":["Logger.ts"],"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\nexport interface OauthLogger {\n warn: (...args: any[]) => void;\n}\n"],"mappings":"","ignoreList":[]}
|
|
@@ -49,6 +49,7 @@ export function createPublicOauthClient(client_id, url, redirect_uri, useHistory
|
|
|
49
49
|
let refreshTokenMarker;
|
|
50
50
|
let joinedScopes;
|
|
51
51
|
let tokenStorage;
|
|
52
|
+
let logger;
|
|
52
53
|
({
|
|
53
54
|
useHistory,
|
|
54
55
|
loginPage,
|
|
@@ -57,7 +58,8 @@ export function createPublicOauthClient(client_id, url, redirect_uri, useHistory
|
|
|
57
58
|
fetchFn,
|
|
58
59
|
ctxPath,
|
|
59
60
|
refreshTokenMarker,
|
|
60
|
-
tokenStorage
|
|
61
|
+
tokenStorage,
|
|
62
|
+
logger
|
|
61
63
|
} = processOptionsAndAssignDefaults(url, redirect_uri, useHistory, loginPage, postLoginPage, scopes, fetchFn, ctxPath));
|
|
62
64
|
const client = {
|
|
63
65
|
client_id,
|
|
@@ -119,8 +121,7 @@ export function createPublicOauthClient(client_id, url, redirect_uri, useHistory
|
|
|
119
121
|
return result;
|
|
120
122
|
} catch (e) {
|
|
121
123
|
if (process.env.NODE_ENV !== "production") {
|
|
122
|
-
|
|
123
|
-
console.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
|
|
124
|
+
logger?.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
|
|
124
125
|
}
|
|
125
126
|
removeLocal(client, storage);
|
|
126
127
|
if (expectRefreshToken) {
|
|
@@ -141,8 +142,7 @@ export function createPublicOauthClient(client_id, url, redirect_uri, useHistory
|
|
|
141
142
|
return ret;
|
|
142
143
|
} catch (e) {
|
|
143
144
|
if (process.env.NODE_ENV !== "production") {
|
|
144
|
-
|
|
145
|
-
console.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
|
|
145
|
+
logger?.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
|
|
146
146
|
}
|
|
147
147
|
removeLocal(client, storage);
|
|
148
148
|
removeSession(client);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPublicOauthClient.js","names":["authorizationCodeGrantRequest","calculatePKCECodeChallenge","customFetch","generateRandomCodeVerifier","generateRandomState","processAuthorizationCodeOAuth2Response","refreshTokenGrantRequest","validateAuthResponse","common","createAuthorizationServer","getStorage","readLocal","readSession","removeLocal","removeSession","saveLocal","saveSession","delay","throwIfError","processOptionsAndAssignDefaults","createPublicOauthClient","client_id","url","redirect_uri","useHistory","loginPage","postLoginPage","scopes","fetchFn","ctxPath","refreshTokenMarker","joinedScopes","tokenStorage","client","token_endpoint_auth_method","authServer","oauthHttpOptions","storage","makeTokenAndSaveRefresh","getToken","_signIn","maybeRefresh","maybeHandleAuthReturn","initiateLoginRedirect","bind","globalThis","go","x","window","history","replaceState","location","assign","Error","expectRefreshToken","refresh_token","lastRefreshTokenMarker","requestedScopes","initialRequestedScopes","areScopesEqual","result","pathname","URL","oldUrl","e","process","env","NODE_ENV","console","warn","state","codeVerifier","ret","href","toString","scopeString","authorization_endpoint","URLSearchParams","response_type","code_challenge","code_challenge_method","scope"],"sources":["createPublicOauthClient.ts"],"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 type { Client, HttpRequestOptions } from \"oauth4webapi\";\nimport {\n authorizationCodeGrantRequest,\n calculatePKCECodeChallenge,\n customFetch,\n generateRandomCodeVerifier,\n generateRandomState,\n processAuthorizationCodeOAuth2Response,\n refreshTokenGrantRequest,\n validateAuthResponse,\n} from \"oauth4webapi\";\nimport {\n common,\n createAuthorizationServer,\n getStorage,\n readLocal,\n readSession,\n removeLocal,\n removeSession,\n saveLocal,\n saveSession,\n} from \"./common.js\";\nimport type { TokenStorageType } from \"./common.js\";\nimport { delay } from \"./delay.js\";\nimport type { PublicOauthClient } from \"./PublicOauthClient.js\";\nimport { throwIfError } from \"./throwIfError.js\";\nimport type { Token } from \"./Token.js\";\nimport { processOptionsAndAssignDefaults } from \"./utils.js\";\n\ndeclare const process: {\n env: {\n NODE_ENV: \"production\" | \"development\";\n TARGET: \"browser\" | \"node\";\n };\n};\n\nexport interface PublicOauthClientOptions {\n /**\n * If true, uses `history.replaceState()`, otherwise uses `window.location.assign()` (defaults to true)\n */\n useHistory?: boolean;\n\n /**\n * Custom landing page URL prior to logging in\n */\n loginPage?: string;\n\n /**\n * URL to return to after completed authentication cycle (defaults to `window.location.toString()`)\n */\n postLoginPage?: string;\n\n /**\n * * @param {string[]} [scopes=[]] - OAuth scopes to request. If not provided, defaults to `[\"api:read-data\", \"api:write-data\", \"api:use-ontologies-read\", \"api:use-ontologies-write\"]`\n */\n scopes?: string[];\n\n /**\n * Custom fetch function to use for requests (defaults to `globalThis.fetch`)\n */\n fetchFn?: typeof globalThis.fetch;\n\n /**\n * Context path for the authorization server (defaults to \"multipass\")\n */\n ctxPath?: string;\n\n /**\n * Allows for an additional value to be appended to the local storage key for the refresh token.\n */\n refreshTokenMarker?: string;\n\n /**\n * Controls how refresh tokens are stored. Affects security vs. convenience tradeoff.\n *\n * - `'localStorage'` (default): Tokens persist across browser sessions.\n * Best UX but vulnerable on shared devices.\n *\n * - `'sessionStorage'`: Tokens cleared when browser/tab closes.\n * Recommended for shared devices. Users re-authenticate each browser session.\n *\n * - `'none'`: Tokens never stored. Users re-authenticate on every page load.\n * Most secure but worst UX. Does not request `offline_access` scope.\n *\n * @default 'localStorage'\n */\n tokenStorage?: TokenStorageType;\n}\n\n/**\n * Creates a PublicOauthClient for authentication.\n *\n * @param {string} clientId - The client_id from the OAuth configuration on the server\n * @param {string} url - The base URL of your Foundry server\n * @param {string} redirectUrl - The URL configured for redirect in the OAuth configuration on the server\n * @param {PublicOauthClientOptions} options - Additional options for the client\n * @returns {PublicOauthClient} A client that can be used as a token provider\n */\nexport function createPublicOauthClient(\n clientId: string,\n url: string,\n redirectUrl: string,\n options?: PublicOauthClientOptions,\n): PublicOauthClient;\n\n/**\n * Creates a PublicOauthClient for authentication.\n *\n * @param {string} clientId - The client_id from the OAuth configuration on the server\n * @param {string} url - The base URL of your Foundry server\n * @param {string} redirectUrl - The URL configured for redirect in the OAuth configuration on the server\n * @param {boolean} useHistory - If true, uses `history.replaceState()`, otherwise uses `window.location.assign()` (defaults to true)\n * @param {string} loginPage - Custom landing page URL prior to logging in\n * @param {string} postLoginPage - URL to return to after completed authentication cycle (defaults to `window.location.toString()`)\n * @param {string[]} scopes - OAuth scopes to request. If not provided, defaults to `[\"api:read-data\", \"api:write-data\", \"api:use-ontologies-read\", \"api:use-ontologies-write\"]`\n * @param {typeof globalThis.fetch} fetchFn - Custom fetch function to use for requests (defaults to `globalThis.fetch`)\n * @param {string} ctxPath - Context path for the authorization server (defaults to \"multipass\")\n * @returns {PublicOauthClient} A client that can be used as a token provider\n */\nexport function createPublicOauthClient(\n client_id: string,\n url: string,\n redirectUrl: string,\n useHistory?: boolean,\n loginPage?: string,\n postLoginPage?: string,\n scopes?: string[],\n fetchFn?: typeof globalThis.fetch,\n ctxPath?: string,\n): PublicOauthClient;\nexport function createPublicOauthClient(\n client_id: string,\n url: string,\n redirect_uri: string,\n useHistory?: boolean | PublicOauthClientOptions,\n loginPage?: string,\n postLoginPage?: string,\n scopes?: string[],\n fetchFn?: typeof globalThis.fetch,\n ctxPath?: string,\n): PublicOauthClient {\n let refreshTokenMarker: string | undefined;\n let joinedScopes: string;\n let tokenStorage: TokenStorageType;\n ({\n useHistory,\n loginPage,\n postLoginPage,\n joinedScopes,\n fetchFn,\n ctxPath,\n refreshTokenMarker,\n tokenStorage,\n } = processOptionsAndAssignDefaults(\n url,\n redirect_uri,\n useHistory,\n loginPage,\n postLoginPage,\n scopes,\n fetchFn,\n ctxPath,\n ));\n\n const client: Client = {\n client_id,\n token_endpoint_auth_method: \"none\",\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions: HttpRequestOptions = { [customFetch]: fetchFn };\n\n const storage = getStorage(tokenStorage);\n\n const { makeTokenAndSaveRefresh, getToken } = common(\n client,\n authServer,\n _signIn,\n oauthHttpOptions,\n maybeRefresh.bind(globalThis, true),\n refreshTokenMarker,\n joinedScopes,\n storage,\n );\n\n // as an arrow function, `useHistory` is known to be a boolean\n const go = async (x: string) => {\n if (useHistory) {\n window.history.replaceState({}, \"\", x);\n return;\n } else window.location.assign(x);\n\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n };\n\n async function maybeRefresh(\n expectRefreshToken?: boolean,\n ): Promise<Token | undefined> {\n if (tokenStorage === \"none\") {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n\n const {\n refresh_token,\n refreshTokenMarker: lastRefreshTokenMarker,\n requestedScopes: initialRequestedScopes,\n } = readLocal(client, storage);\n\n const areScopesEqual = initialRequestedScopes != null\n && joinedScopes === initialRequestedScopes;\n\n if (\n !refresh_token || lastRefreshTokenMarker !== refreshTokenMarker\n || !areScopesEqual\n ) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n const result = makeTokenAndSaveRefresh(\n throwIfError(\n await processAuthorizationCodeOAuth2Response(\n authServer,\n client,\n await refreshTokenGrantRequest(\n authServer,\n client,\n refresh_token,\n oauthHttpOptions,\n ),\n ),\n ),\n \"refresh\",\n );\n\n if (\n result && window.location.pathname === new URL(redirect_uri).pathname\n ) {\n const { oldUrl } = readSession(client);\n // don't block on the redirect\n void go(oldUrl ?? \"/\");\n }\n return result;\n } catch (e) {\n if (process.env.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\n \"Failed to get OAuth2 refresh token. Removing refresh token\",\n e,\n );\n }\n removeLocal(client, storage);\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n\n async function maybeHandleAuthReturn() {\n const { state, oldUrl, codeVerifier } = readSession(client);\n if (!codeVerifier) return;\n\n try {\n const ret = makeTokenAndSaveRefresh(\n throwIfError(\n await processAuthorizationCodeOAuth2Response(\n authServer,\n client,\n await authorizationCodeGrantRequest(\n authServer,\n client,\n throwIfError(\n validateAuthResponse(\n authServer,\n client,\n new URL(window.location.href),\n state,\n ),\n ),\n redirect_uri,\n codeVerifier,\n oauthHttpOptions,\n ),\n ),\n ),\n \"signIn\",\n );\n\n void 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(\n \"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\",\n e,\n );\n }\n removeLocal(client, storage);\n removeSession(client);\n throw e;\n }\n }\n\n // As an arrow function, `scopes` and `postLoginPage` are known at compile time\n const initiateLoginRedirect = async (): Promise<void> => {\n if (\n loginPage\n && window.location.href !== loginPage\n && window.location.pathname !== loginPage\n ) {\n saveLocal(client, {}, storage);\n saveSession(client, { oldUrl: postLoginPage });\n await go(loginPage);\n return;\n }\n\n const state = generateRandomState()!;\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readSession(client).oldUrl ?? window.location.toString();\n saveLocal(client, {}, storage);\n saveSession(client, { codeVerifier, state, oldUrl });\n\n // Only request offline_access (refresh tokens) if we're going to store them\n const scopeString = tokenStorage === \"none\"\n ? joinedScopes\n : `offline_access ${joinedScopes}`;\n\n window.location.assign(`${authServer\n .authorization_endpoint!}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: scopeString,\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() as unknown as Token;\n }\n\n return getToken;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SACEA,6BAA6B,EAC7BC,0BAA0B,EAC1BC,WAAW,EACXC,0BAA0B,EAC1BC,mBAAmB,EACnBC,sCAAsC,EACtCC,wBAAwB,EACxBC,oBAAoB,QACf,cAAc;AACrB,SACEC,MAAM,EACNC,yBAAyB,EACzBC,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,WAAW,EACXC,aAAa,EACbC,SAAS,EACTC,WAAW,QACN,aAAa;AAEpB,SAASC,KAAK,QAAQ,YAAY;AAElC,SAASC,YAAY,QAAQ,mBAAmB;AAEhD,SAASC,+BAA+B,QAAQ,YAAY;;AA8D5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAYA,OAAO,SAASC,uBAAuBA,CACrCC,SAAiB,EAC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ationCodeGrantRequest","calculatePKCECodeChallenge","customFetch","generateRandomCodeVerifier","generateRandomState","processAuthorizationCodeOAuth2Response","refreshTokenGrantRequest","validateAuthResponse","common","createAuthorizationServer","getStorage","readLocal","readSession","removeLocal","removeSession","saveLocal","saveSession","delay","throwIfError","processOptionsAndAssignDefaults","createPublicOauthClient","client_id","url","redirect_uri","useHistory","loginPage","postLoginPage","scopes","fetchFn","ctxPath","refreshTokenMarker","joinedScopes","tokenStorage","logger","client","token_endpoint_auth_method","authServer","oauthHttpOptions","storage","makeTokenAndSaveRefresh","getToken","_signIn","maybeRefresh","maybeHandleAuthReturn","initiateLoginRedirect","bind","globalThis","go","x","window","history","replaceState","location","assign","Error","expectRefreshToken","refresh_token","lastRefreshTokenMarker","requestedScopes","initialRequestedScopes","areScopesEqual","result","pathname","URL","oldUrl","e","process","env","NODE_ENV","warn","state","codeVerifier","ret","href","toString","scopeString","authorization_endpoint","URLSearchParams","response_type","code_challenge","code_challenge_method","scope"],"sources":["createPublicOauthClient.ts"],"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 type { Client, HttpRequestOptions } from \"oauth4webapi\";\nimport {\n authorizationCodeGrantRequest,\n calculatePKCECodeChallenge,\n customFetch,\n generateRandomCodeVerifier,\n generateRandomState,\n processAuthorizationCodeOAuth2Response,\n refreshTokenGrantRequest,\n validateAuthResponse,\n} from \"oauth4webapi\";\nimport {\n common,\n createAuthorizationServer,\n getStorage,\n readLocal,\n readSession,\n removeLocal,\n removeSession,\n saveLocal,\n saveSession,\n} from \"./common.js\";\nimport type { TokenStorageType } from \"./common.js\";\nimport { delay } from \"./delay.js\";\nimport type { OauthLogger } from \"./Logger.js\";\nimport type { PublicOauthClient } from \"./PublicOauthClient.js\";\nimport { throwIfError } from \"./throwIfError.js\";\nimport type { Token } from \"./Token.js\";\nimport { processOptionsAndAssignDefaults } from \"./utils.js\";\n\ndeclare const process: {\n env: {\n NODE_ENV: \"production\" | \"development\";\n TARGET: \"browser\" | \"node\";\n };\n};\n\nexport interface PublicOauthClientOptions {\n /**\n * If true, uses `history.replaceState()`, otherwise uses `window.location.assign()` (defaults to true)\n */\n useHistory?: boolean;\n\n /**\n * Custom landing page URL prior to logging in\n */\n loginPage?: string;\n\n /**\n * URL to return to after completed authentication cycle (defaults to `window.location.toString()`)\n */\n postLoginPage?: string;\n\n /**\n * * @param {string[]} [scopes=[]] - OAuth scopes to request. If not provided, defaults to `[\"api:read-data\", \"api:write-data\", \"api:use-ontologies-read\", \"api:use-ontologies-write\"]`\n */\n scopes?: string[];\n\n /**\n * Custom fetch function to use for requests (defaults to `globalThis.fetch`)\n */\n fetchFn?: typeof globalThis.fetch;\n\n /**\n * Context path for the authorization server (defaults to \"multipass\")\n */\n ctxPath?: string;\n\n /**\n * Allows for an additional value to be appended to the local storage key for the refresh token.\n */\n refreshTokenMarker?: string;\n\n /**\n * Controls how refresh tokens are stored. Affects security vs. convenience tradeoff.\n *\n * - `'localStorage'` (default): Tokens persist across browser sessions.\n * Best UX but vulnerable on shared devices.\n *\n * - `'sessionStorage'`: Tokens cleared when browser/tab closes.\n * Recommended for shared devices. Users re-authenticate each browser session.\n *\n * - `'none'`: Tokens never stored. Users re-authenticate on every page load.\n * Most secure but worst UX. Does not request `offline_access` scope.\n *\n * @default 'localStorage'\n */\n tokenStorage?: TokenStorageType;\n\n /**\n * Optional logger for warning messages. If not provided, warnings are silently dropped.\n * Structurally compatible with `@osdk/api`'s `Logger`.\n */\n logger?: OauthLogger;\n}\n\n/**\n * Creates a PublicOauthClient for authentication.\n *\n * @param {string} clientId - The client_id from the OAuth configuration on the server\n * @param {string} url - The base URL of your Foundry server\n * @param {string} redirectUrl - The URL configured for redirect in the OAuth configuration on the server\n * @param {PublicOauthClientOptions} options - Additional options for the client\n * @returns {PublicOauthClient} A client that can be used as a token provider\n */\nexport function createPublicOauthClient(\n clientId: string,\n url: string,\n redirectUrl: string,\n options?: PublicOauthClientOptions,\n): PublicOauthClient;\n\n/**\n * Creates a PublicOauthClient for authentication.\n *\n * @param {string} clientId - The client_id from the OAuth configuration on the server\n * @param {string} url - The base URL of your Foundry server\n * @param {string} redirectUrl - The URL configured for redirect in the OAuth configuration on the server\n * @param {boolean} useHistory - If true, uses `history.replaceState()`, otherwise uses `window.location.assign()` (defaults to true)\n * @param {string} loginPage - Custom landing page URL prior to logging in\n * @param {string} postLoginPage - URL to return to after completed authentication cycle (defaults to `window.location.toString()`)\n * @param {string[]} scopes - OAuth scopes to request. If not provided, defaults to `[\"api:read-data\", \"api:write-data\", \"api:use-ontologies-read\", \"api:use-ontologies-write\"]`\n * @param {typeof globalThis.fetch} fetchFn - Custom fetch function to use for requests (defaults to `globalThis.fetch`)\n * @param {string} ctxPath - Context path for the authorization server (defaults to \"multipass\")\n * @returns {PublicOauthClient} A client that can be used as a token provider\n */\nexport function createPublicOauthClient(\n client_id: string,\n url: string,\n redirectUrl: string,\n useHistory?: boolean,\n loginPage?: string,\n postLoginPage?: string,\n scopes?: string[],\n fetchFn?: typeof globalThis.fetch,\n ctxPath?: string,\n): PublicOauthClient;\nexport function createPublicOauthClient(\n client_id: string,\n url: string,\n redirect_uri: string,\n useHistory?: boolean | PublicOauthClientOptions,\n loginPage?: string,\n postLoginPage?: string,\n scopes?: string[],\n fetchFn?: typeof globalThis.fetch,\n ctxPath?: string,\n): PublicOauthClient {\n let refreshTokenMarker: string | undefined;\n let joinedScopes: string;\n let tokenStorage: TokenStorageType;\n let logger: OauthLogger | undefined;\n ({\n useHistory,\n loginPage,\n postLoginPage,\n joinedScopes,\n fetchFn,\n ctxPath,\n refreshTokenMarker,\n tokenStorage,\n logger,\n } = processOptionsAndAssignDefaults(\n url,\n redirect_uri,\n useHistory,\n loginPage,\n postLoginPage,\n scopes,\n fetchFn,\n ctxPath,\n ));\n\n const client: Client = {\n client_id,\n token_endpoint_auth_method: \"none\",\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions: HttpRequestOptions = { [customFetch]: fetchFn };\n\n const storage = getStorage(tokenStorage);\n\n const { makeTokenAndSaveRefresh, getToken } = common(\n client,\n authServer,\n _signIn,\n oauthHttpOptions,\n maybeRefresh.bind(globalThis, true),\n refreshTokenMarker,\n joinedScopes,\n storage,\n );\n\n // as an arrow function, `useHistory` is known to be a boolean\n const go = async (x: string) => {\n if (useHistory) {\n window.history.replaceState({}, \"\", x);\n return;\n } else window.location.assign(x);\n\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n };\n\n async function maybeRefresh(\n expectRefreshToken?: boolean,\n ): Promise<Token | undefined> {\n if (tokenStorage === \"none\") {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n\n const {\n refresh_token,\n refreshTokenMarker: lastRefreshTokenMarker,\n requestedScopes: initialRequestedScopes,\n } = readLocal(client, storage);\n\n const areScopesEqual = initialRequestedScopes != null\n && joinedScopes === initialRequestedScopes;\n\n if (\n !refresh_token || lastRefreshTokenMarker !== refreshTokenMarker\n || !areScopesEqual\n ) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n const result = makeTokenAndSaveRefresh(\n throwIfError(\n await processAuthorizationCodeOAuth2Response(\n authServer,\n client,\n await refreshTokenGrantRequest(\n authServer,\n client,\n refresh_token,\n oauthHttpOptions,\n ),\n ),\n ),\n \"refresh\",\n );\n\n if (\n result && window.location.pathname === new URL(redirect_uri).pathname\n ) {\n const { oldUrl } = readSession(client);\n // don't block on the redirect\n void go(oldUrl ?? \"/\");\n }\n return result;\n } catch (e) {\n if (process.env.NODE_ENV !== \"production\") {\n logger?.warn(\n \"Failed to get OAuth2 refresh token. Removing refresh token\",\n e,\n );\n }\n removeLocal(client, storage);\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n\n async function maybeHandleAuthReturn() {\n const { state, oldUrl, codeVerifier } = readSession(client);\n if (!codeVerifier) return;\n\n try {\n const ret = makeTokenAndSaveRefresh(\n throwIfError(\n await processAuthorizationCodeOAuth2Response(\n authServer,\n client,\n await authorizationCodeGrantRequest(\n authServer,\n client,\n throwIfError(\n validateAuthResponse(\n authServer,\n client,\n new URL(window.location.href),\n state,\n ),\n ),\n redirect_uri,\n codeVerifier,\n oauthHttpOptions,\n ),\n ),\n ),\n \"signIn\",\n );\n\n void go(oldUrl);\n return ret;\n } catch (e) {\n if (process.env.NODE_ENV !== \"production\") {\n logger?.warn(\n \"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\",\n e,\n );\n }\n removeLocal(client, storage);\n removeSession(client);\n throw e;\n }\n }\n\n // As an arrow function, `scopes` and `postLoginPage` are known at compile time\n const initiateLoginRedirect = async (): Promise<void> => {\n if (\n loginPage\n && window.location.href !== loginPage\n && window.location.pathname !== loginPage\n ) {\n saveLocal(client, {}, storage);\n saveSession(client, { oldUrl: postLoginPage });\n await go(loginPage);\n return;\n }\n\n const state = generateRandomState()!;\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readSession(client).oldUrl ?? window.location.toString();\n saveLocal(client, {}, storage);\n saveSession(client, { codeVerifier, state, oldUrl });\n\n // Only request offline_access (refresh tokens) if we're going to store them\n const scopeString = tokenStorage === \"none\"\n ? joinedScopes\n : `offline_access ${joinedScopes}`;\n\n window.location.assign(`${authServer\n .authorization_endpoint!}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: scopeString,\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() as unknown as Token;\n }\n\n return getToken;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SACEA,6BAA6B,EAC7BC,0BAA0B,EAC1BC,WAAW,EACXC,0BAA0B,EAC1BC,mBAAmB,EACnBC,sCAAsC,EACtCC,wBAAwB,EACxBC,oBAAoB,QACf,cAAc;AACrB,SACEC,MAAM,EACNC,yBAAyB,EACzBC,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,WAAW,EACXC,aAAa,EACbC,SAAS,EACTC,WAAW,QACN,aAAa;AAEpB,SAASC,KAAK,QAAQ,YAAY;AAGlC,SAASC,YAAY,QAAQ,mBAAmB;AAEhD,SAASC,+BAA+B,QAAQ,YAAY;;AAoE5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAYA,OAAO,SAASC,uBAAuBA,CACrCC,SAAiB,EACjBC,GAAW,EACXC,YAAoB,EACpBC,UAA+C,EAC/CC,SAAkB,EAClBC,aAAsB,EACtBC,MAAiB,EACjBC,OAAiC,EACjCC,OAAgB,EACG;EACnB,IAAIC,kBAAsC;EAC1C,IAAIC,YAAoB;EACxB,IAAIC,YAA8B;EAClC,IAAIC,MAA+B;EACnC,CAAC;IACCT,UAAU;IACVC,SAAS;IACTC,aAAa;IACbK,YAAY;IACZH,OAAO;IACPC,OAAO;IACPC,kBAAkB;IAClBE,YAAY;IACZC;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6C,KAAK,GAAGlE,mBAAmB,CAAC,CAAE;IACpC,MAAMmE,YAAY,GAAGpE,0BAA0B,CAAC,CAAC;IACjD,MAAM6D,MAAM,GAAGpD,WAAW,CAACsB,MAAM,CAAC,CAAC8B,MAAM,IAAIf,MAAM,CAACG,QAAQ,CAACsB,QAAQ,CAAC,CAAC;IACvE3D,SAAS,CAACmB,MAAM,EAAE,CAAC,CAAC,EAAEI,OAAO,CAAC;IAC9BtB,WAAW,CAACkB,MAAM,EAAE;MAAEqC,YAAY;MAAED,KAAK;MAAEN;IAAO,CAAC,CAAC;;IAEpD;IACA,MAAMW,WAAW,GAAG3C,YAAY,KAAK,MAAM,GACvCD,YAAY,GACZ,kBAAkBA,YAAY,EAAE;IAEpCkB,MAAM,CAACG,QAAQ,CAACC,MAAM,CAAC,GAAGjB,UAAU,CACjCwC,sBAAsB,IAAK,IAAIC,eAAe,CAAC;MAChDxD,SAAS;MACTyD,aAAa,EAAE,MAAM;MACrBR,KAAK;MACL/C,YAAY;MACZwD,cAAc,EAAE,MAAM9E,0BAA0B,CAACsE,YAAY,CAAC;MAC9DS,qBAAqB,EAAE,MAAM;MAC7BC,KAAK,EAAEN;IACT,CAAC,CAAC,EAAE,CAAC;;IAEL;IACA,MAAM1D,KAAK,CAAC,IAAI,CAAC;IACjB,MAAM,IAAIqC,KAAK,CAAC,oBAAoB,CAAC;EACvC,CAAC;EAYD,OAAOd,QAAQ;AACjB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["createConfidentialOauthClient","createPublicOauthClient"],"sources":["index.ts"],"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\nexport type { TokenStorageType } from \"./common.js\";\nexport type { ConfidentialOauthClient } from \"./ConfidentialOauthClient.js\";\nexport { createConfidentialOauthClient } from \"./createConfidentialOauthClient.js\";\nexport {\n createPublicOauthClient,\n type PublicOauthClientOptions,\n} from \"./createPublicOauthClient.js\";\nexport type { PublicOauthClient } from \"./PublicOauthClient.js\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAASA,6BAA6B,QAAQ,oCAAoC;AAClF,SACEC,uBAAuB,QAElB,8BAA8B","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["createConfidentialOauthClient","createPublicOauthClient"],"sources":["index.ts"],"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\nexport type { TokenStorageType } from \"./common.js\";\nexport type { ConfidentialOauthClient } from \"./ConfidentialOauthClient.js\";\nexport { createConfidentialOauthClient } from \"./createConfidentialOauthClient.js\";\nexport {\n createPublicOauthClient,\n type PublicOauthClientOptions,\n} from \"./createPublicOauthClient.js\";\nexport type { OauthLogger } from \"./Logger.js\";\nexport type { PublicOauthClient } from \"./PublicOauthClient.js\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAASA,6BAA6B,QAAQ,oCAAoC;AAClF,SACEC,uBAAuB,QAElB,8BAA8B","ignoreList":[]}
|
package/build/browser/utils.js
CHANGED
|
@@ -42,7 +42,8 @@ export function processOptionsAndAssignDefaults(url, redirect_uri, useHistory, l
|
|
|
42
42
|
fetchFn: options.fetchFn ?? globalThis.fetch,
|
|
43
43
|
ctxPath: options.ctxPath ?? "multipass",
|
|
44
44
|
refreshTokenMarker: options.refreshTokenMarker,
|
|
45
|
-
tokenStorage: options.tokenStorage ?? "localStorage"
|
|
45
|
+
tokenStorage: options.tokenStorage ?? "localStorage",
|
|
46
|
+
logger: options.logger
|
|
46
47
|
};
|
|
47
48
|
}
|
|
48
49
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["invariant","processOptionsAndAssignDefaults","url","redirect_uri","useHistory","loginPage","postLoginPage","scopes","fetchFn","ctxPath","options","process","env","NODE_ENV","window","location","toString","joinedScopes","sort","join","globalThis","fetch","refreshTokenMarker","tokenStorage"],"sources":["utils.ts"],"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 invariant from \"tiny-invariant\";\nimport type { TokenStorageType } from \"./common.js\";\nimport type { PublicOauthClientOptions } from \"./createPublicOauthClient.js\";\n\ninterface ProcessedPublicOauthClientOptions extends\n Omit<\n Required<PublicOauthClientOptions>,\n \"loginPage\" | \"refreshTokenMarker\" | \"scopes\" | \"tokenStorage\"\n >\n{\n loginPage?: string;\n refreshTokenMarker?: string;\n joinedScopes: string;\n tokenStorage: TokenStorageType;\n}\n\nexport function processOptionsAndAssignDefaults(\n url: string,\n redirect_uri: string,\n useHistory?: boolean | PublicOauthClientOptions,\n loginPage?: string,\n postLoginPage?: string,\n scopes?: string[],\n fetchFn?: typeof globalThis.fetch,\n ctxPath?: string,\n): ProcessedPublicOauthClientOptions {\n let options: PublicOauthClientOptions = {};\n\n if (typeof useHistory === \"object\") {\n invariant(\n !loginPage && !postLoginPage && !scopes && !fetchFn && !ctxPath,\n \"If useHistory is an object, other options should not be provided\",\n );\n options = useHistory;\n } else {\n options = {\n useHistory,\n loginPage,\n postLoginPage,\n scopes,\n fetchFn,\n ctxPath,\n };\n }\n\n invariant(url, \"url is required\");\n invariant(redirect_uri, \"redirectUrl is required\");\n\n // Assign defaults\n return {\n useHistory: options.useHistory ?? true,\n loginPage: options.loginPage,\n postLoginPage: options.postLoginPage || window.location.toString(),\n joinedScopes: [\n ...options.scopes\n ?? [\n \"api:read-data\",\n \"api:write-data\",\n \"api:use-ontologies-read\",\n \"api:use-ontologies-write\",\n ],\n ]\n .sort().join(\" \"),\n fetchFn: options.fetchFn ?? globalThis.fetch,\n ctxPath: options.ctxPath ?? \"multipass\",\n refreshTokenMarker: options.refreshTokenMarker,\n tokenStorage: options.tokenStorage ?? \"localStorage\",\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAOA,SAAS,MAAM,gBAAgB;
|
|
1
|
+
{"version":3,"file":"utils.js","names":["invariant","processOptionsAndAssignDefaults","url","redirect_uri","useHistory","loginPage","postLoginPage","scopes","fetchFn","ctxPath","options","process","env","NODE_ENV","window","location","toString","joinedScopes","sort","join","globalThis","fetch","refreshTokenMarker","tokenStorage","logger"],"sources":["utils.ts"],"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 invariant from \"tiny-invariant\";\nimport type { TokenStorageType } from \"./common.js\";\nimport type { PublicOauthClientOptions } from \"./createPublicOauthClient.js\";\nimport type { OauthLogger } from \"./Logger.js\";\n\ninterface ProcessedPublicOauthClientOptions extends\n Omit<\n Required<PublicOauthClientOptions>,\n \"loginPage\" | \"refreshTokenMarker\" | \"scopes\" | \"tokenStorage\" | \"logger\"\n >\n{\n loginPage?: string;\n refreshTokenMarker?: string;\n joinedScopes: string;\n tokenStorage: TokenStorageType;\n logger?: OauthLogger;\n}\n\nexport function processOptionsAndAssignDefaults(\n url: string,\n redirect_uri: string,\n useHistory?: boolean | PublicOauthClientOptions,\n loginPage?: string,\n postLoginPage?: string,\n scopes?: string[],\n fetchFn?: typeof globalThis.fetch,\n ctxPath?: string,\n): ProcessedPublicOauthClientOptions {\n let options: PublicOauthClientOptions = {};\n\n if (typeof useHistory === \"object\") {\n invariant(\n !loginPage && !postLoginPage && !scopes && !fetchFn && !ctxPath,\n \"If useHistory is an object, other options should not be provided\",\n );\n options = useHistory;\n } else {\n options = {\n useHistory,\n loginPage,\n postLoginPage,\n scopes,\n fetchFn,\n ctxPath,\n };\n }\n\n invariant(url, \"url is required\");\n invariant(redirect_uri, \"redirectUrl is required\");\n\n // Assign defaults\n return {\n useHistory: options.useHistory ?? true,\n loginPage: options.loginPage,\n postLoginPage: options.postLoginPage || window.location.toString(),\n joinedScopes: [\n ...options.scopes\n ?? [\n \"api:read-data\",\n \"api:write-data\",\n \"api:use-ontologies-read\",\n \"api:use-ontologies-write\",\n ],\n ]\n .sort().join(\" \"),\n fetchFn: options.fetchFn ?? globalThis.fetch,\n ctxPath: options.ctxPath ?? \"multipass\",\n refreshTokenMarker: options.refreshTokenMarker,\n tokenStorage: options.tokenStorage ?? \"localStorage\",\n logger: options.logger,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAOA,SAAS,MAAM,gBAAgB;AAkBtC,OAAO,SAASC,+BAA+BA,CAC7CC,GAAW,EACXC,YAAoB,EACpBC,UAA+C,EAC/CC,SAAkB,EAClBC,aAAsB,EACtBC,MAAiB,EACjBC,OAAiC,EACjCC,OAAgB,EACmB;EACnC,IAAIC,OAAiC,GAAG,CAAC,CAAC;EAE1C,IAAI,OAAON,UAAU,KAAK,QAAQ,EAAE;IAClC,EACE,CAACC,SAAS,IAAI,CAACC,aAAa,IAAI,CAACC,MAAM,IAAI,CAACC,OAAO,IAAI,CAACC,OAAO,IAAAE,OAAA,CAAAC,GAAA,CAAAC,QAAA,oBADjEb,SAAS,QAEP,kEAAkE,IAFpEA,SAAS;IAITU,OAAO,GAAGN,UAAU;EACtB,CAAC,MAAM;IACLM,OAAO,GAAG;MACRN,UAAU;MACVC,SAAS;MACTC,aAAa;MACbC,MAAM;MACNC,OAAO;MACPC;IACF,CAAC;EACH;EAEA,CAAUP,GAAG,GAAAS,OAAA,CAAAC,GAAA,CAAAC,QAAA,oBAAbb,SAAS,QAAM,iBAAiB,IAAhCA,SAAS;EACT,CAAUG,YAAY,GAAAQ,OAAA,CAAAC,GAAA,CAAAC,QAAA,oBAAtBb,SAAS,QAAe,yBAAyB,IAAjDA,SAAS;;EAET;EACA,OAAO;IACLI,UAAU,EAAEM,OAAO,CAACN,UAAU,IAAI,IAAI;IACtCC,SAAS,EAAEK,OAAO,CAACL,SAAS;IAC5BC,aAAa,EAAEI,OAAO,CAACJ,aAAa,IAAIQ,MAAM,CAACC,QAAQ,CAACC,QAAQ,CAAC,CAAC;IAClEC,YAAY,EAAE,CACZ,IAAGP,OAAO,CAACH,MAAM,IACZ,CACD,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,0BAA0B,CAC3B,EACJ,CACEW,IAAI,CAAC,CAAC,CAACC,IAAI,CAAC,GAAG,CAAC;IACnBX,OAAO,EAAEE,OAAO,CAACF,OAAO,IAAIY,UAAU,CAACC,KAAK;IAC5CZ,OAAO,EAAEC,OAAO,CAACD,OAAO,IAAI,WAAW;IACvCa,kBAAkB,EAAEZ,OAAO,CAACY,kBAAkB;IAC9CC,YAAY,EAAEb,OAAO,CAACa,YAAY,IAAI,cAAc;IACpDC,MAAM,EAAEd,OAAO,CAACc;EAClB,CAAC;AACH","ignoreList":[]}
|
package/build/cjs/index.cjs
CHANGED
|
@@ -1164,7 +1164,8 @@ function processOptionsAndAssignDefaults(url, redirect_uri, useHistory, loginPag
|
|
|
1164
1164
|
fetchFn: options.fetchFn ?? globalThis.fetch,
|
|
1165
1165
|
ctxPath: options.ctxPath ?? "multipass",
|
|
1166
1166
|
refreshTokenMarker: options.refreshTokenMarker,
|
|
1167
|
-
tokenStorage: options.tokenStorage ?? "localStorage"
|
|
1167
|
+
tokenStorage: options.tokenStorage ?? "localStorage",
|
|
1168
|
+
logger: options.logger
|
|
1168
1169
|
};
|
|
1169
1170
|
}
|
|
1170
1171
|
|
|
@@ -1173,6 +1174,7 @@ function createPublicOauthClient(client_id, url, redirect_uri, useHistory, login
|
|
|
1173
1174
|
let refreshTokenMarker;
|
|
1174
1175
|
let joinedScopes;
|
|
1175
1176
|
let tokenStorage;
|
|
1177
|
+
let logger;
|
|
1176
1178
|
({
|
|
1177
1179
|
useHistory,
|
|
1178
1180
|
loginPage,
|
|
@@ -1181,7 +1183,8 @@ function createPublicOauthClient(client_id, url, redirect_uri, useHistory, login
|
|
|
1181
1183
|
fetchFn,
|
|
1182
1184
|
ctxPath,
|
|
1183
1185
|
refreshTokenMarker,
|
|
1184
|
-
tokenStorage
|
|
1186
|
+
tokenStorage,
|
|
1187
|
+
logger
|
|
1185
1188
|
} = processOptionsAndAssignDefaults(url, redirect_uri, useHistory, loginPage, postLoginPage, scopes, fetchFn, ctxPath));
|
|
1186
1189
|
const client = {
|
|
1187
1190
|
client_id,
|
|
@@ -1230,7 +1233,7 @@ function createPublicOauthClient(client_id, url, redirect_uri, useHistory, login
|
|
|
1230
1233
|
return result;
|
|
1231
1234
|
} catch (e) {
|
|
1232
1235
|
if (process.env.NODE_ENV !== "production") {
|
|
1233
|
-
|
|
1236
|
+
logger?.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
|
|
1234
1237
|
}
|
|
1235
1238
|
removeLocal(client, storage);
|
|
1236
1239
|
if (expectRefreshToken) {
|
|
@@ -1251,7 +1254,7 @@ function createPublicOauthClient(client_id, url, redirect_uri, useHistory, login
|
|
|
1251
1254
|
return ret;
|
|
1252
1255
|
} catch (e) {
|
|
1253
1256
|
if (process.env.NODE_ENV !== "production") {
|
|
1254
|
-
|
|
1257
|
+
logger?.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
|
|
1255
1258
|
}
|
|
1256
1259
|
removeLocal(client, storage);
|
|
1257
1260
|
removeSession(client);
|