@osdk/oauth 0.4.0-beta.2 → 0.4.0-beta.3

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/build/browser/BaseOauthClient.d.ts +15 -0
  3. package/build/browser/BaseOauthClient.d.ts.map +1 -0
  4. package/build/browser/BaseOauthClient.js +17 -0
  5. package/build/browser/BaseOauthClient.js.map +1 -0
  6. package/build/browser/ConfidentialOauthClient.d.ts +4 -0
  7. package/build/browser/ConfidentialOauthClient.d.ts.map +1 -0
  8. package/build/browser/ConfidentialOauthClient.js +17 -0
  9. package/build/browser/ConfidentialOauthClient.js.map +1 -0
  10. package/build/browser/PublicOauthClient.d.ts +6 -0
  11. package/build/browser/PublicOauthClient.d.ts.map +1 -0
  12. package/build/browser/PublicOauthClient.js +17 -0
  13. package/build/browser/PublicOauthClient.js.map +1 -0
  14. package/build/browser/Token.d.ts +7 -0
  15. package/build/browser/Token.d.ts.map +1 -0
  16. package/build/browser/Token.js +17 -0
  17. package/build/browser/Token.js.map +1 -0
  18. package/build/browser/common.d.ts +36 -0
  19. package/build/browser/common.d.ts.map +1 -0
  20. package/build/browser/common.js +128 -0
  21. package/build/browser/common.js.map +1 -0
  22. package/build/browser/createConfidentialOauthClient.d.ts +12 -0
  23. package/build/browser/createConfidentialOauthClient.d.ts.map +1 -0
  24. package/build/browser/createConfidentialOauthClient.js +47 -0
  25. package/build/browser/createConfidentialOauthClient.js.map +1 -0
  26. package/build/browser/createPublicOauthClient.d.ts +15 -0
  27. package/build/browser/createPublicOauthClient.d.ts.map +1 -0
  28. package/build/browser/createPublicOauthClient.js +140 -0
  29. package/build/browser/createPublicOauthClient.js.map +1 -0
  30. package/build/browser/index.d.ts +4 -0
  31. package/build/browser/index.d.ts.map +1 -0
  32. package/build/browser/index.js +17 -243
  33. package/build/browser/index.js.map +1 -1
  34. package/build/browser/throwIfError.d.ts +6 -0
  35. package/build/browser/throwIfError.d.ts.map +1 -0
  36. package/build/browser/throwIfError.js +23 -0
  37. package/build/browser/throwIfError.js.map +1 -0
  38. package/build/esm/BaseOauthClient.js +17 -0
  39. package/build/esm/BaseOauthClient.js.map +1 -0
  40. package/build/esm/ConfidentialOauthClient.js +17 -0
  41. package/build/esm/ConfidentialOauthClient.js.map +1 -0
  42. package/build/esm/PublicOauthClient.js +17 -0
  43. package/build/esm/PublicOauthClient.js.map +1 -0
  44. package/build/esm/Token.js +17 -0
  45. package/build/esm/Token.js.map +1 -0
  46. package/build/esm/common.js +137 -0
  47. package/build/esm/common.js.map +1 -0
  48. package/build/esm/createConfidentialOauthClient.js +47 -0
  49. package/build/esm/createConfidentialOauthClient.js.map +1 -0
  50. package/build/esm/createPublicOauthClient.js +140 -0
  51. package/build/esm/createPublicOauthClient.js.map +1 -0
  52. package/build/esm/index.js +17 -252
  53. package/build/esm/index.js.map +1 -1
  54. package/build/esm/throwIfError.js +23 -0
  55. package/build/esm/throwIfError.js.map +1 -0
  56. package/package.json +4 -5
@@ -0,0 +1,47 @@
1
+ /*
2
+ * Copyright 2024 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { clientCredentialsGrantRequest, customFetch, processClientCredentialsResponse } from "oauth4webapi";
17
+ import { common, createAuthorizationServer } from "./common.js";
18
+ import { throwIfError } from "./throwIfError.js";
19
+ /**
20
+ * @param client_id
21
+ * @param client_secret
22
+ * @param url the base url of your foundry server
23
+ * @param scopes
24
+ * @param fetchFn
25
+ * @param ctxPath
26
+ * @returns which can be used as a token provider
27
+ */
28
+ export function createConfidentialOauthClient(client_id, client_secret, url, scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
29
+ const client = {
30
+ client_id,
31
+ client_secret
32
+ };
33
+ const authServer = createAuthorizationServer(ctxPath, url);
34
+ const oauthHttpOptions = {
35
+ [customFetch]: fetchFn
36
+ };
37
+ const {
38
+ getToken,
39
+ makeTokenAndSaveRefresh
40
+ } = common(client, authServer, async function () {
41
+ return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
42
+ scope: scopes.join(" ")
43
+ }), oauthHttpOptions))), "signIn");
44
+ }, oauthHttpOptions, undefined);
45
+ return getToken;
46
+ }
47
+ //# sourceMappingURL=createConfidentialOauthClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createConfidentialOauthClient.js","names":["clientCredentialsGrantRequest","customFetch","processClientCredentialsResponse","common","createAuthorizationServer","throwIfError","createConfidentialOauthClient","client_id","client_secret","url","scopes","fetchFn","globalThis","fetch","ctxPath","client","authServer","oauthHttpOptions","getToken","makeTokenAndSaveRefresh","URLSearchParams","scope","join","undefined"],"sources":["createConfidentialOauthClient.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 */\nimport { clientCredentialsGrantRequest, customFetch, processClientCredentialsResponse, } from \"oauth4webapi\";\nimport { common, createAuthorizationServer } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\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 = { client_id, client_secret };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = { [customFetch]: fetchFn };\n const { getToken, makeTokenAndSaveRefresh } = common(client, authServer, _signIn, oauthHttpOptions, undefined);\n async function _signIn() {\n return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({ scope: scopes.join(\" \") }), oauthHttpOptions))), \"signIn\");\n }\n return getToken;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,6BAA6B,EAAEC,WAAW,EAAEC,gCAAgC,QAAS,cAAc;AAC5G,SAASC,MAAM,EAAEC,yBAAyB,QAAQ,aAAa;AAC/D,SAASC,YAAY,QAAQ,mBAAmB;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,6BAA6BA,CAACC,SAAS,EAAEC,aAAa,EAAEC,GAAG,EAAEC,MAAM,GAAG,CAAC,eAAe,EAAE,gBAAgB,CAAC,EAAEC,OAAO,GAAGC,UAAU,CAACC,KAAK,EAAEC,OAAO,GAAG,YAAY,EAAE;EAC3K,MAAMC,MAAM,GAAG;IAAER,SAAS;IAAEC;EAAc,CAAC;EAC3C,MAAMQ,UAAU,GAAGZ,yBAAyB,CAACU,OAAO,EAAEL,GAAG,CAAC;EAC1D,MAAMQ,gBAAgB,GAAG;IAAE,CAAChB,WAAW,GAAGU;EAAQ,CAAC;EACnD,MAAM;IAAEO,QAAQ;IAAEC;EAAwB,CAAC,GAAGhB,MAAM,CAACY,MAAM,EAAEC,UAAU,EACvE,kBAAyB;IACrB,OAAOG,uBAAuB,CAACd,YAAY,CAAC,MAAMH,gCAAgC,CAACc,UAAU,EAAED,MAAM,EAAE,MAAMf,6BAA6B,CAACgB,UAAU,EAAED,MAAM,EAAE,IAAIK,eAAe,CAAC;MAAEC,KAAK,EAAEX,MAAM,CAACY,IAAI,CAAC,GAAG;IAAE,CAAC,CAAC,EAAEL,gBAAgB,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC;EACnP,CAAC,EAHiFA,gBAAgB,EAAEM,SAAS,CAAC;EAI9G,OAAOL,QAAQ;AACnB","ignoreList":[]}
@@ -0,0 +1,140 @@
1
+ /*
2
+ * Copyright 2024 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import delay from "delay";
17
+ import { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, validateAuthResponse } from "oauth4webapi";
18
+ import { common, createAuthorizationServer, readLocal, removeLocal, saveLocal } from "./common.js";
19
+ import { throwIfError } from "./throwIfError.js";
20
+ /**
21
+ * @param client_id
22
+ * @param url the base url of your foundry server
23
+ * @param redirectUrl the url configured for redirect in the oauth configuration on the server
24
+ * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`
25
+ * @param loginPage if you want a custom landing page prior to logging in, set this to that url
26
+ * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded
27
+ * @param scopes
28
+ * @param fetchFn
29
+ * @param ctxPath
30
+ * @returns {PublicOauthClient} which can be used as a token provider
31
+ */
32
+ export function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
33
+ const client = {
34
+ client_id,
35
+ token_endpoint_auth_method: "none"
36
+ };
37
+ const authServer = createAuthorizationServer(ctxPath, url);
38
+ const oauthHttpOptions = {
39
+ [customFetch]: fetchFn
40
+ };
41
+ if (scopes.length === 0) {
42
+ scopes = ["api:read-data", "api:write-data"];
43
+ }
44
+ const {
45
+ makeTokenAndSaveRefresh,
46
+ getToken
47
+ } = common(client, authServer, /** Will throw if there is no token! */
48
+ async function _signIn() {
49
+ // 1. Check if we have a refresh token in local storage
50
+ return (await maybeRefresh()
51
+ // 2. If there is no refresh token we are likely trying to perform the callback
52
+ ) ?? (await maybeHandleAuthReturn())
53
+ // 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
54
+ ?? (await initiateLoginRedirect());
55
+ }, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
56
+ async function go(x) {
57
+ if (useHistory) return window.history.replaceState({}, "", x);else window.location.assign(x);
58
+ await delay(1000);
59
+ throw new Error("Unable to redirect");
60
+ }
61
+ async function maybeRefresh(expectRefreshToken) {
62
+ const {
63
+ refresh_token
64
+ } = readLocal(client);
65
+ if (!refresh_token) {
66
+ if (expectRefreshToken) throw new Error("No refresh token found");
67
+ return;
68
+ }
69
+ try {
70
+ // note, we don't use processRefreshTokenResponse because the mp oauth implementation
71
+ // doesn't do refresh tokens quite right and this lets us skip the id check
72
+ const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
73
+ if (result && window.location.pathname === new URL(redirectUrl).pathname) {
74
+ const {
75
+ oldUrl
76
+ } = readLocal(client);
77
+ go(oldUrl ?? "/");
78
+ }
79
+ return result;
80
+ } catch (e) {
81
+ if (process?.env?.NODE_ENV !== "production") {
82
+ // eslint-disable-next-line no-console
83
+ console.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
84
+ }
85
+ removeLocal(client);
86
+ if (expectRefreshToken) {
87
+ throw new Error("Could not refresh token");
88
+ }
89
+ }
90
+ }
91
+ async function maybeHandleAuthReturn() {
92
+ const {
93
+ codeVerifier,
94
+ state,
95
+ oldUrl
96
+ } = readLocal(client);
97
+ if (!codeVerifier) return;
98
+ try {
99
+ 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");
100
+ go(oldUrl);
101
+ return ret;
102
+ } catch (e) {
103
+ if (process?.env?.NODE_ENV !== "production") {
104
+ // eslint-disable-next-line no-console
105
+ console.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
106
+ }
107
+ removeLocal(client);
108
+ }
109
+ }
110
+ async function initiateLoginRedirect() {
111
+ if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {
112
+ saveLocal(client, {
113
+ oldUrl: postLoginPage
114
+ });
115
+ return await go(loginPage);
116
+ }
117
+ const state = generateRandomState();
118
+ const codeVerifier = generateRandomCodeVerifier();
119
+ const oldUrl = readLocal(client).oldUrl ?? window.location.toString();
120
+ saveLocal(client, {
121
+ codeVerifier,
122
+ state,
123
+ oldUrl
124
+ });
125
+ window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({
126
+ client_id,
127
+ response_type: "code",
128
+ state,
129
+ redirect_uri: redirectUrl,
130
+ code_challenge: await calculatePKCECodeChallenge(codeVerifier),
131
+ code_challenge_method: "S256",
132
+ scope: ["offline_access", ...scopes].join(" ")
133
+ })}`);
134
+ // Give time for redirect to happen
135
+ await delay(1000);
136
+ throw new Error("Unable to redirect");
137
+ }
138
+ return getToken;
139
+ }
140
+ //# sourceMappingURL=createPublicOauthClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createPublicOauthClient.js","names":["delay","authorizationCodeGrantRequest","calculatePKCECodeChallenge","customFetch","generateRandomCodeVerifier","generateRandomState","processAuthorizationCodeOAuth2Response","refreshTokenGrantRequest","validateAuthResponse","common","createAuthorizationServer","readLocal","removeLocal","saveLocal","throwIfError","createPublicOauthClient","client_id","url","redirectUrl","useHistory","loginPage","postLoginPage","window","location","toString","scopes","fetchFn","globalThis","fetch","ctxPath","client","token_endpoint_auth_method","authServer","oauthHttpOptions","length","makeTokenAndSaveRefresh","getToken","_signIn","maybeRefresh","maybeHandleAuthReturn","initiateLoginRedirect","bind","go","x","history","replaceState","assign","Error","expectRefreshToken","refresh_token","result","pathname","URL","oldUrl","e","process","env","NODE_ENV","console","warn","codeVerifier","state","ret","href","authorization_endpoint","URLSearchParams","response_type","redirect_uri","code_challenge","code_challenge_method","scope","join"],"sources":["createPublicOauthClient.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 */\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, validateAuthResponse, } from \"oauth4webapi\";\nimport { common, createAuthorizationServer, readLocal, removeLocal, saveLocal, } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = { client_id, token_endpoint_auth_method: \"none\" };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = { [customFetch]: fetchFn };\n if (scopes.length === 0) {\n scopes = [\"api:read-data\", \"api:write-data\"];\n }\n const { makeTokenAndSaveRefresh, getToken } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));\n async function go(x) {\n if (useHistory)\n return window.history.replaceState({}, \"\", x);\n else\n window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n async function maybeRefresh(expectRefreshToken) {\n const { refresh_token } = readLocal(client);\n if (!refresh_token) {\n if (expectRefreshToken)\n throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), \"refresh\");\n if (result && window.location.pathname === new URL(redirectUrl).pathname) {\n const { oldUrl } = readLocal(client);\n go(oldUrl ?? \"/\");\n }\n return result;\n }\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 { codeVerifier, state, oldUrl } = readLocal(client);\n if (!codeVerifier)\n 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 }\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\n && window.location.href !== loginPage\n && window.location.pathname !== loginPage) {\n saveLocal(client, { oldUrl: postLoginPage });\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, { codeVerifier, state, oldUrl });\n window.location.assign(`${authServer\n .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 // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\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}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,6BAA6B,EAAEC,0BAA0B,EAAEC,WAAW,EAAEC,0BAA0B,EAAEC,mBA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D,MAAM,GAAG1C,SAAS,CAACmB,MAAM,CAAC,CAACuB,MAAM,IAAI/B,MAAM,CAACC,QAAQ,CAACC,QAAQ,CAAC,CAAC;IACrEX,SAAS,CAACiB,MAAM,EAAE;MAAE8B,YAAY;MAAEC,KAAK;MAAER;IAAO,CAAC,CAAC;IAClD/B,MAAM,CAACC,QAAQ,CAACuB,MAAM,CAAC,GAAGd,UAAU,CAC/BgC,sBAAsB,IAAI,IAAIC,eAAe,CAAC;MAC/CjD,SAAS;MACTkD,aAAa,EAAE,MAAM;MACrBL,KAAK;MACLM,YAAY,EAAEjD,WAAW;MACzBkD,cAAc,EAAE,MAAMlE,0BAA0B,CAAC0D,YAAY,CAAC;MAC9DS,qBAAqB,EAAE,MAAM;MAC7BC,KAAK,EAAE,CAAC,gBAAgB,EAAE,GAAG7C,MAAM,CAAC,CAAC8C,IAAI,CAAC,GAAG;IACjD,CAAC,CAAC,EAAE,CAAC;IACL;IACA,MAAMvE,KAAK,CAAC,IAAI,CAAC;IACjB,MAAM,IAAI+C,KAAK,CAAC,oBAAoB,CAAC;EACzC;EAUA,OAAOX,QAAQ;AACnB","ignoreList":[]}
@@ -1,253 +1,18 @@
1
- import { processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, isOAuth2Error, processClientCredentialsResponse, clientCredentialsGrantRequest, customFetch, authorizationCodeGrantRequest, validateAuthResponse, generateRandomState, generateRandomCodeVerifier, calculatePKCECodeChallenge, processRevocationResponse, revocationRequest } from 'oauth4webapi';
2
- import invariant from 'tiny-invariant';
3
- import { TypedEventTarget } from 'typescript-event-target';
4
- import delay from 'delay';
5
-
6
- // src/createConfidentialOauthClient.ts
7
- function throwIfError(result) {
8
- if (isOAuth2Error(result)) {
9
- throw new Error(`Failed to get token: ${result.error}`);
10
- }
11
- return result;
12
- }
13
-
14
- // src/common.ts
15
- var CustomEvent = globalThis.CustomEvent ?? class CustomEvent2 extends Event {
16
- #detail;
17
- constructor(type, options) {
18
- super(type, options);
19
- this.#detail = options?.detail ?? null;
20
- }
21
- get detail() {
22
- return this.#detail;
23
- }
24
- };
25
- var localStorage = globalThis.localStorage;
26
- function saveLocal(client, x) {
27
- localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
28
- }
29
- function removeLocal(client) {
30
- localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
31
- }
32
- function readLocal(client) {
33
- return JSON.parse(
34
- // MUST `localStorage?` as nodejs does not have localStorage
35
- localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
36
- );
37
- }
38
- function common(client, as, _signIn, oauthHttpOptions, refresh) {
39
- let token;
40
- const eventTarget = new TypedEventTarget();
41
- function makeTokenAndSaveRefresh(resp, type) {
42
- const {
43
- refresh_token,
44
- expires_in,
45
- access_token
46
- } = resp;
47
- !(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
48
- saveLocal(client, {
49
- refresh_token
50
- });
51
- token = {
52
- refresh_token,
53
- expires_in,
54
- access_token,
55
- expires_at: Date.now() + expires_in * 1e3
56
- };
57
- eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {
58
- detail: token
59
- }));
60
- return token;
61
- }
62
- let refreshTimeout;
63
- function rmTimeout() {
64
- if (refreshTimeout) clearTimeout(refreshTimeout);
65
- }
66
- function restartRefreshTimer(evt) {
67
- if (refresh) {
68
- rmTimeout();
69
- refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
70
- }
71
- }
72
- async function signOut() {
73
- !token ? process.env.NODE_ENV !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
74
- const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
75
- rmTimeout();
76
- removeLocal(client);
77
- token = void 0;
78
- throwIfError(result);
79
- eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
80
- }
81
- let pendingSignIn;
82
- async function signIn() {
83
- if (pendingSignIn) {
84
- return pendingSignIn;
85
- }
86
- try {
87
- pendingSignIn = _signIn();
88
- return await pendingSignIn;
89
- } finally {
90
- pendingSignIn = void 0;
91
- }
92
- }
93
- eventTarget.addEventListener("signIn", restartRefreshTimer);
94
- eventTarget.addEventListener("refresh", restartRefreshTimer);
95
- function getTokenOrUndefined() {
96
- if (!token || Date.now() >= token.expires_at) {
97
- return void 0;
98
- }
99
- return token?.access_token;
100
- }
101
- const getToken = Object.assign(async function getToken2() {
102
- if (!token || Date.now() >= token.expires_at) {
103
- token = await signIn();
104
- }
105
- return token?.access_token;
106
- }, {
107
- signIn,
108
- refresh,
109
- signOut,
110
- rmTimeout,
111
- getTokenOrUndefined,
112
- addEventListener: eventTarget.addEventListener.bind(eventTarget),
113
- removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
114
- });
115
- return {
116
- getToken,
117
- makeTokenAndSaveRefresh
118
- };
119
- }
120
- function createAuthorizationServer(ctxPath, url) {
121
- const issuer = `${new URL(ctxPath, url)}`;
122
- return {
123
- token_endpoint: `${issuer}/api/oauth2/token`,
124
- authorization_endpoint: `${issuer}/api/oauth2/authorize`,
125
- revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
126
- issuer
127
- };
128
- }
129
-
130
- // src/createConfidentialOauthClient.ts
131
- function createConfidentialOauthClient(client_id, client_secret, url, scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
132
- const client = {
133
- client_id,
134
- client_secret
135
- };
136
- const authServer = createAuthorizationServer(ctxPath, url);
137
- const oauthHttpOptions = {
138
- [customFetch]: fetchFn
139
- };
140
- const {
141
- getToken,
142
- makeTokenAndSaveRefresh
143
- } = common(client, authServer, _signIn, oauthHttpOptions, void 0);
144
- async function _signIn() {
145
- return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
146
- scope: scopes.join(" ")
147
- }), oauthHttpOptions))), "signIn");
148
- }
149
- return getToken;
150
- }
151
- function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
152
- const client = {
153
- client_id,
154
- token_endpoint_auth_method: "none"
155
- };
156
- const authServer = createAuthorizationServer(ctxPath, url);
157
- const oauthHttpOptions = {
158
- [customFetch]: fetchFn
159
- };
160
- if (scopes.length === 0) {
161
- scopes = ["api:read-data", "api:write-data"];
162
- }
163
- const {
164
- makeTokenAndSaveRefresh,
165
- getToken
166
- } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
167
- async function go(x) {
168
- if (useHistory) return window.history.replaceState({}, "", x);
169
- else window.location.assign(x);
170
- await delay(1e3);
171
- throw new Error("Unable to redirect");
172
- }
173
- async function maybeRefresh(expectRefreshToken) {
174
- const {
175
- refresh_token
176
- } = readLocal(client);
177
- if (!refresh_token) {
178
- if (expectRefreshToken) throw new Error("No refresh token found");
179
- return;
180
- }
181
- try {
182
- const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
183
- if (result && window.location.pathname === new URL(redirectUrl).pathname) {
184
- const {
185
- oldUrl
186
- } = readLocal(client);
187
- go(oldUrl ?? "/");
188
- }
189
- return result;
190
- } catch (e) {
191
- if (process?.env?.NODE_ENV !== "production") {
192
- console.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
193
- }
194
- removeLocal(client);
195
- if (expectRefreshToken) {
196
- throw new Error("Could not refresh token");
197
- }
198
- }
199
- }
200
- async function maybeHandleAuthReturn() {
201
- const {
202
- codeVerifier,
203
- state,
204
- oldUrl
205
- } = readLocal(client);
206
- if (!codeVerifier) return;
207
- try {
208
- const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), "signIn");
209
- go(oldUrl);
210
- return ret;
211
- } catch (e) {
212
- if (process?.env?.NODE_ENV !== "production") {
213
- console.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
214
- }
215
- removeLocal(client);
216
- }
217
- }
218
- async function initiateLoginRedirect() {
219
- if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {
220
- saveLocal(client, {
221
- oldUrl: postLoginPage
222
- });
223
- return await go(loginPage);
224
- }
225
- const state = generateRandomState();
226
- const codeVerifier = generateRandomCodeVerifier();
227
- const oldUrl = readLocal(client).oldUrl ?? window.location.toString();
228
- saveLocal(client, {
229
- codeVerifier,
230
- state,
231
- oldUrl
232
- });
233
- window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({
234
- client_id,
235
- response_type: "code",
236
- state,
237
- redirect_uri: redirectUrl,
238
- code_challenge: await calculatePKCECodeChallenge(codeVerifier),
239
- code_challenge_method: "S256",
240
- scope: ["offline_access", ...scopes].join(" ")
241
- })}`);
242
- await delay(1e3);
243
- throw new Error("Unable to redirect");
244
- }
245
- async function _signIn() {
246
- return await maybeRefresh() ?? await maybeHandleAuthReturn() ?? await initiateLoginRedirect();
247
- }
248
- return getToken;
249
- }
250
-
251
- export { createConfidentialOauthClient, createPublicOauthClient };
252
- //# sourceMappingURL=index.js.map
1
+ /*
2
+ * Copyright 2024 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export { createConfidentialOauthClient } from "./createConfidentialOauthClient.js";
17
+ export { createPublicOauthClient } from "./createPublicOauthClient.js";
253
18
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/throwIfError.ts","../../src/common.ts","../../src/createConfidentialOauthClient.ts","../../src/createPublicOauthClient.ts"],"names":["CustomEvent","getToken","customFetch"],"mappings":";;;;;;AAiBO,SAAS,aAAa,MAAQ,EAAA;AACnC,EAAI,IAAA,aAAA,CAAc,MAAM,CAAG,EAAA;AACzB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAwB,qBAAA,EAAA,MAAA,CAAO,KAAK,CAAE,CAAA,CAAA,CAAA;AAAA,GACxD;AACA,EAAO,OAAA,MAAA,CAAA;AACT,CAAA;;;ACAA,IAAM,WAAA,GAA0E,WAAW,WAAe,IAAA,MAAMA,qBAAoB,KAAM,CAAA;AAAA,EACxI,OAAA,CAAA;AAAA,EACA,WAAA,CAAY,MAAM,OAAS,EAAA;AACzB,IAAA,KAAA,CAAM,MAAM,OAAO,CAAA,CAAA;AACnB,IAAK,IAAA,CAAA,OAAA,GAAU,SAAS,MAAU,IAAA,IAAA,CAAA;AAAA,GACpC;AAAA,EACA,IAAI,MAAS,GAAA;AACX,IAAA,OAAO,IAAK,CAAA,OAAA,CAAA;AAAA,GACd;AACF,CAAA,CAAA;AACA,IAAM,eAAe,UAAW,CAAA,YAAA,CAAA;AACzB,SAAS,SAAA,CAAU,QAAQ,CAAG,EAAA;AAEnC,EAAc,YAAA,EAAA,OAAA,CAAQ,2BAA2B,MAAO,CAAA,SAAS,IAAI,IAAK,CAAA,SAAA,CAAU,CAAC,CAAC,CAAA,CAAA;AACxF,CAAA;AACO,SAAS,YAAY,MAAQ,EAAA;AAElC,EAAA,YAAA,EAAc,UAAW,CAAA,CAAA,wBAAA,EAA2B,MAAO,CAAA,SAAS,CAAE,CAAA,CAAA,CAAA;AACxE,CAAA;AACO,SAAS,UAAU,MAAQ,EAAA;AAChC,EAAA,OAAO,IAAK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,IAAI,MAAM,oBAAoB,CAAA,CAAA;AAAA,GACtC;AAGA,EAAA,eAAe,OAAU,GAAA;AAEvB,IAAA,OAAQ,MAAM,YAAa,EAAA,IAErB,MAAM,qBAAsB,EAAA,IAE9B,MAAM,qBAAsB,EAAA,CAAA;AAAA,GAClC;AACA,EAAO,OAAA,QAAA,CAAA;AACT","file":"index.js","sourcesContent":["/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { processRevocationResponse, revocationRequest } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\n// Node 18 is supposed to have a `CustomEvent` but it is not exposed on `globalThis`\n// which creates a problem for making a single codebase for node and browser. This polyfill works around it\nconst CustomEvent = process.env.TARGET === \"browser\" ? globalThis.CustomEvent : globalThis.CustomEvent ?? class CustomEvent extends Event {\n #detail;\n constructor(type, options) {\n super(type, options);\n this.#detail = options?.detail ?? null;\n }\n get detail() {\n return this.#detail;\n }\n};\nconst localStorage = globalThis.localStorage;\nexport function saveLocal(client, x) {\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));\n}\nexport function removeLocal(client) {\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);\n}\nexport function readLocal(client) {\n return JSON.parse(\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? \"{}\");\n}\nexport function common(client, as, _signIn, oauthHttpOptions, refresh) {\n let token;\n const eventTarget = new TypedEventTarget();\n function makeTokenAndSaveRefresh(resp, type) {\n const {\n refresh_token,\n expires_in,\n access_token\n } = resp;\n !(expires_in != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n saveLocal(client, {\n refresh_token\n });\n token = {\n refresh_token,\n expires_in,\n access_token,\n expires_at: Date.now() + expires_in * 1000\n };\n eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {\n detail: token\n }));\n return token;\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout) clearTimeout(refreshTimeout);\n }\n function restartRefreshTimer(evt) {\n if (refresh) {\n rmTimeout();\n refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);\n }\n }\n async function signOut() {\n !token ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"not signed in\") : invariant(false) : void 0;\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\n\n // Clean up\n removeLocal(client);\n token = undefined;\n throwIfError(result);\n eventTarget.dispatchTypedEvent(\"signOut\", new Event(\"signOut\"));\n }\n let pendingSignIn;\n async function signIn() {\n if (pendingSignIn) {\n return pendingSignIn;\n }\n try {\n pendingSignIn = _signIn();\n return await pendingSignIn;\n } finally {\n pendingSignIn = undefined;\n }\n }\n eventTarget.addEventListener(\"signIn\", restartRefreshTimer);\n eventTarget.addEventListener(\"refresh\", restartRefreshTimer);\n function getTokenOrUndefined() {\n if (!token || Date.now() >= token.expires_at) {\n return undefined;\n }\n return token?.access_token;\n }\n const getToken = Object.assign(async function getToken() {\n if (!token || Date.now() >= token.expires_at) {\n token = await signIn();\n }\n return token?.access_token;\n }, {\n signIn,\n refresh,\n signOut,\n rmTimeout,\n getTokenOrUndefined,\n addEventListener: eventTarget.addEventListener.bind(eventTarget),\n removeEventListener: eventTarget.removeEventListener.bind(eventTarget)\n });\n return {\n getToken,\n makeTokenAndSaveRefresh\n };\n}\nexport function createAuthorizationServer(ctxPath, url) {\n const issuer = `${new URL(ctxPath, url)}`;\n return {\n token_endpoint: `${issuer}/api/oauth2/token`,\n authorization_endpoint: `${issuer}/api/oauth2/authorize`,\n revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,\n issuer\n };\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { clientCredentialsGrantRequest, customFetch, processClientCredentialsResponse } from \"oauth4webapi\";\nimport { common, createAuthorizationServer } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n\n/**\n * @param client_id\n * @param client_secret\n * @param url the base url of your foundry server\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns which can be used as a token provider\n */\nexport function createConfidentialOauthClient(client_id, client_secret, url, scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = {\n client_id,\n client_secret\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const {\n getToken,\n makeTokenAndSaveRefresh\n } = common(client, authServer, _signIn, oauthHttpOptions, undefined);\n async function _signIn() {\n return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({\n scope: scopes.join(\" \")\n }), oauthHttpOptions))), \"signIn\");\n }\n return getToken;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, validateAuthResponse } from \"oauth4webapi\";\nimport { common, createAuthorizationServer, readLocal, removeLocal, saveLocal } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = {\n client_id,\n token_endpoint_auth_method: \"none\"\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n if (scopes.length === 0) {\n scopes = [\"api:read-data\", \"api:write-data\"];\n }\n const {\n makeTokenAndSaveRefresh,\n getToken\n } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));\n async function go(x) {\n if (useHistory) return window.history.replaceState({}, \"\", x);else window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n async function maybeRefresh(expectRefreshToken) {\n const {\n refresh_token\n } = readLocal(client);\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), \"refresh\");\n if (result && window.location.pathname === new URL(redirectUrl).pathname) {\n const {\n oldUrl\n } = readLocal(client);\n go(oldUrl ?? \"/\");\n }\n return result;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 refresh token. Removing refresh token\", e);\n }\n removeLocal(client);\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n async function maybeHandleAuthReturn() {\n const {\n codeVerifier,\n state,\n oldUrl\n } = readLocal(client);\n if (!codeVerifier) return;\n try {\n const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), \"signIn\");\n go(oldUrl);\n return ret;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\", e);\n }\n removeLocal(client);\n }\n }\n async function initiateLoginRedirect() {\n if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {\n saveLocal(client, {\n oldUrl: postLoginPage\n });\n return await go(loginPage);\n }\n const state = generateRandomState();\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readLocal(client).oldUrl ?? window.location.toString();\n saveLocal(client, {\n codeVerifier,\n state,\n oldUrl\n });\n window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri: redirectUrl,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: [\"offline_access\", ...scopes].join(\" \")\n })}`);\n\n // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n\n /** Will throw if there is no token! */\n async function _signIn() {\n // 1. Check if we have a refresh token in local storage\n return (await maybeRefresh()\n // 2. If there is no refresh token we are likely trying to perform the callback\n ) ?? (await maybeHandleAuthReturn())\n // 3. If we haven't been able to load the token from one of the two above ways, we need to make the initial auth request\n ?? (await initiateLoginRedirect());\n }\n return getToken;\n}"]}
1
+ {"version":3,"file":"index.js","names":["createConfidentialOauthClient","createPublicOauthClient"],"sources":["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 */\nexport { createConfidentialOauthClient } from \"./createConfidentialOauthClient.js\";\nexport { createPublicOauthClient } from \"./createPublicOauthClient.js\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,6BAA6B,QAAQ,oCAAoC;AAClF,SAASC,uBAAuB,QAAQ,8BAA8B","ignoreList":[]}
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright 2024 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { isOAuth2Error } from "oauth4webapi";
17
+ export function throwIfError(result) {
18
+ if (isOAuth2Error(result)) {
19
+ throw new Error(`Failed to get token: ${result.error}`);
20
+ }
21
+ return result;
22
+ }
23
+ //# sourceMappingURL=throwIfError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throwIfError.js","names":["isOAuth2Error","throwIfError","result","Error","error"],"sources":["throwIfError.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 */\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"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,aAAa,QAAQ,cAAc;AAC5C,OAAO,SAASC,YAAYA,CAACC,MAAM,EAAE;EACjC,IAAIF,aAAa,CAACE,MAAM,CAAC,EAAE;IACvB,MAAM,IAAIC,KAAK,CAAC,wBAAwBD,MAAM,CAACE,KAAK,EAAE,CAAC;EAC3D;EACA,OAAOF,MAAM;AACjB","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@osdk/oauth",
3
- "version": "0.4.0-beta.2",
3
+ "version": "0.4.0-beta.3",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,8 +26,8 @@
26
26
  "jest-extended": "^4.0.2",
27
27
  "typescript": "^5.5.4",
28
28
  "@osdk/monorepo.api-extractor": "~0.0.0",
29
- "@osdk/monorepo.tsconfig": "~0.0.0",
30
- "@osdk/monorepo.tsup": "~0.0.0"
29
+ "@osdk/monorepo.tsup": "~0.0.0",
30
+ "@osdk/monorepo.tsconfig": "~0.0.0"
31
31
  },
32
32
  "publishConfig": {
33
33
  "access": "public"
@@ -50,7 +50,6 @@
50
50
  "clean": "rm -rf lib dist types build tsconfig.tsbuildinfo",
51
51
  "fix-lint": "eslint . --fix && dprint fmt --config $(find-up dprint.json)",
52
52
  "lint": "eslint . && dprint check --config $(find-up dprint.json)",
53
- "transpile": "monorepo.tool.transpile",
54
- "typecheck": "monorepo.tool.typecheck esm"
53
+ "transpile": "monorepo.tool.transpile"
55
54
  }
56
55
  }