@osdk/oauth 0.3.0-beta.0 → 0.3.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 CHANGED
@@ -1,5 +1,12 @@
1
1
  # @osdk/oauth
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - bc89b62: Spelling fixes and spell check in CI
8
+ - b62ac80: Adds createConfidentialOauthClient
9
+
3
10
  ## 0.3.0-beta.0
4
11
 
5
12
  ### Minor Changes
@@ -1,9 +1,9 @@
1
- import delay from 'delay';
2
- import { processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, processRevocationResponse, revocationRequest, isOAuth2Error, customFetch, authorizationCodeGrantRequest, validateAuthResponse, generateRandomState, generateRandomCodeVerifier, calculatePKCECodeChallenge } from 'oauth4webapi';
1
+ import { processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, isOAuth2Error, processClientCredentialsResponse, clientCredentialsGrantRequest, customFetch, authorizationCodeGrantRequest, validateAuthResponse, generateRandomState, generateRandomCodeVerifier, calculatePKCECodeChallenge, processRevocationResponse, revocationRequest } from 'oauth4webapi';
3
2
  import invariant from 'tiny-invariant';
4
3
  import { TypedEventTarget } from 'typescript-event-target';
4
+ import delay from 'delay';
5
5
 
6
- // src/createPublicOauthClient.ts
6
+ // src/createConfidentialOauthClient.ts
7
7
  function throwIfError(result) {
8
8
  if (isOAuth2Error(result)) {
9
9
  throw new Error(`Failed to get token: ${result.error}`);
@@ -11,39 +11,33 @@ function throwIfError(result) {
11
11
  return result;
12
12
  }
13
13
 
14
- // src/createPublicOauthClient.ts
15
- var storageKey = "asdfasdfdhjlkajhgj";
16
- function saveLocal(x) {
17
- localStorage.setItem(storageKey, JSON.stringify(x));
14
+ // src/common.ts
15
+ var CustomEvent = process.env.target === "browser" ? globalThis.CustomEvent : globalThis.CustomEvent ?? class CustomEvent2 extends Event {
16
+ #detail;
17
+ constructor(type, options) {
18
+ super(type, options);
19
+ this.#detail = options?.detail ?? null;
20
+ }
21
+ get detail() {
22
+ return this.#detail;
23
+ }
24
+ };
25
+ var localStorage = globalThis.localStorage;
26
+ function saveLocal(client, x) {
27
+ localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
18
28
  }
19
- function removeLocal() {
20
- localStorage.removeItem(storageKey);
29
+ function removeLocal(client) {
30
+ localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
21
31
  }
22
- function readLocal() {
23
- return JSON.parse(localStorage.getItem(storageKey) ?? "{}");
32
+ function readLocal(client) {
33
+ return JSON.parse(
34
+ // MUST `localStorage?` as nodejs does not have localStorage
35
+ localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
36
+ );
24
37
  }
25
- function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginPage, postLoginPage = window.location.toString(), scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
26
- const oauthHttpOptions = {
27
- [customFetch]: fetchFn
28
- };
38
+ function common(client, as, _signIn, oauthHttpOptions, refresh) {
39
+ let token;
29
40
  const eventTarget = new TypedEventTarget();
30
- const issuer = `${new URL(ctxPath, url)}`;
31
- const as = {
32
- token_endpoint: `${issuer}/api/oauth2/token`,
33
- authorization_endpoint: `${issuer}/api/oauth2/authorize`,
34
- revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
35
- issuer
36
- };
37
- const client = {
38
- client_id,
39
- token_endpoint_auth_method: "none"
40
- };
41
- async function go(x) {
42
- if (useHistory) return window.history.replaceState({}, "", x);
43
- else window.location.assign(x);
44
- await delay(1e3);
45
- throw new Error("Unable to redirect");
46
- }
47
41
  function makeTokenAndSaveRefresh(resp, type) {
48
42
  const {
49
43
  refresh_token,
@@ -51,7 +45,7 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
51
45
  access_token
52
46
  } = resp;
53
47
  !(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
54
- saveLocal({
48
+ saveLocal(client, {
55
49
  refresh_token
56
50
  });
57
51
  token = {
@@ -65,21 +59,122 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
65
59
  }));
66
60
  return token;
67
61
  }
62
+ let refreshTimeout;
63
+ function rmTimeout() {
64
+ if (refreshTimeout) clearTimeout(refreshTimeout);
65
+ }
66
+ function restartRefreshTimer(evt) {
67
+ if (refresh) {
68
+ rmTimeout();
69
+ refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
70
+ }
71
+ }
72
+ async function signOut() {
73
+ !token ? process.env.NODE_ENV !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
74
+ const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
75
+ rmTimeout();
76
+ removeLocal(client);
77
+ token = void 0;
78
+ throwIfError(result);
79
+ eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
80
+ }
81
+ let pendingSignIn;
82
+ async function signIn() {
83
+ if (pendingSignIn) {
84
+ return pendingSignIn;
85
+ }
86
+ try {
87
+ pendingSignIn = _signIn();
88
+ return await pendingSignIn;
89
+ } finally {
90
+ pendingSignIn = void 0;
91
+ }
92
+ }
93
+ eventTarget.addEventListener("signIn", restartRefreshTimer);
94
+ eventTarget.addEventListener("refresh", restartRefreshTimer);
95
+ const getToken = Object.assign(async function getToken2() {
96
+ if (!token || Date.now() >= token.expires_at) {
97
+ token = await signIn();
98
+ }
99
+ return token.access_token;
100
+ }, {
101
+ signIn,
102
+ refresh,
103
+ signOut,
104
+ rmTimeout,
105
+ addEventListener: eventTarget.addEventListener.bind(eventTarget),
106
+ removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
107
+ });
108
+ return {
109
+ getToken,
110
+ makeTokenAndSaveRefresh
111
+ };
112
+ }
113
+ function createAuthorizationServer(ctxPath, url) {
114
+ const issuer = `${new URL(ctxPath, url)}`;
115
+ return {
116
+ token_endpoint: `${issuer}/api/oauth2/token`,
117
+ authorization_endpoint: `${issuer}/api/oauth2/authorize`,
118
+ revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
119
+ issuer
120
+ };
121
+ }
122
+
123
+ // src/createConfidentialOauthClient.ts
124
+ function createConfidentialOauthClient(client_id, client_secret, url, scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
125
+ const client = {
126
+ client_id,
127
+ client_secret
128
+ };
129
+ const authServer = createAuthorizationServer(ctxPath, url);
130
+ const oauthHttpOptions = {
131
+ [customFetch]: fetchFn
132
+ };
133
+ const {
134
+ getToken,
135
+ makeTokenAndSaveRefresh
136
+ } = common(client, authServer, _signIn, oauthHttpOptions, void 0);
137
+ async function _signIn() {
138
+ return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
139
+ scope: scopes.join(" ")
140
+ }), oauthHttpOptions))), "signIn");
141
+ }
142
+ return getToken;
143
+ }
144
+ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginPage, postLoginPage = window.location.toString(), scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
145
+ const client = {
146
+ client_id,
147
+ token_endpoint_auth_method: "none"
148
+ };
149
+ const authServer = createAuthorizationServer(ctxPath, url);
150
+ const oauthHttpOptions = {
151
+ [customFetch]: fetchFn
152
+ };
153
+ const {
154
+ makeTokenAndSaveRefresh,
155
+ getToken
156
+ } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
157
+ async function go(x) {
158
+ if (useHistory) return window.history.replaceState({}, "", x);
159
+ else window.location.assign(x);
160
+ await delay(1e3);
161
+ throw new Error("Unable to redirect");
162
+ }
68
163
  async function maybeRefresh(expectRefreshToken) {
69
164
  const {
70
165
  refresh_token
71
- } = readLocal();
166
+ } = readLocal(client);
72
167
  if (!refresh_token) {
73
168
  if (expectRefreshToken) throw new Error("No refresh token found");
74
169
  return;
75
170
  }
76
171
  try {
77
- return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await refreshTokenGrantRequest(as, client, refresh_token, oauthHttpOptions))), "refresh");
172
+ return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
78
173
  } catch (e) {
79
174
  if (process?.env?.NODE_ENV !== "production") {
80
175
  console.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
81
176
  }
82
- removeLocal();
177
+ removeLocal(client);
83
178
  if (expectRefreshToken) {
84
179
  throw new Error("Could not refresh token");
85
180
  }
@@ -90,35 +185,35 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
90
185
  codeVerifier,
91
186
  state,
92
187
  oldUrl
93
- } = readLocal();
188
+ } = readLocal(client);
94
189
  if (!codeVerifier) return;
95
190
  try {
96
- const ret2 = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await authorizationCodeGrantRequest(as, client, throwIfError(validateAuthResponse(as, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), "signIn");
191
+ const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), "signIn");
97
192
  go(oldUrl);
98
- return ret2;
193
+ return ret;
99
194
  } catch (e) {
100
195
  if (process?.env?.NODE_ENV !== "production") {
101
196
  console.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
102
197
  }
103
- removeLocal();
198
+ removeLocal(client);
104
199
  }
105
200
  }
106
201
  async function initiateLoginRedirect() {
107
202
  if (loginPage && window.location.href !== loginPage) {
108
- saveLocal({
203
+ saveLocal(client, {
109
204
  oldUrl: postLoginPage
110
205
  });
111
206
  return await go(loginPage);
112
207
  }
113
208
  const state = generateRandomState();
114
209
  const codeVerifier = generateRandomCodeVerifier();
115
- const oldUrl = readLocal().oldUrl ?? window.location.toString();
116
- saveLocal({
210
+ const oldUrl = readLocal(client).oldUrl ?? window.location.toString();
211
+ saveLocal(client, {
117
212
  codeVerifier,
118
213
  state,
119
214
  oldUrl
120
215
  });
121
- window.location.assign(`${as.authorization_endpoint}?${new URLSearchParams({
216
+ window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({
122
217
  client_id,
123
218
  response_type: "code",
124
219
  state,
@@ -130,57 +225,12 @@ function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginP
130
225
  await delay(1e3);
131
226
  throw new Error("Unable to redirect");
132
227
  }
133
- let refreshTimeout;
134
- function rmTimeout() {
135
- if (refreshTimeout) clearTimeout(refreshTimeout);
136
- }
137
- function restartRefreshTimer(evt) {
138
- rmTimeout();
139
- refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
140
- }
141
- const refresh = maybeRefresh.bind(globalThis, true);
142
- async function signOut() {
143
- !token ? process.env.NODE_ENV !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
144
- const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
145
- rmTimeout();
146
- removeLocal();
147
- token = void 0;
148
- throwIfError(result);
149
- eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
150
- }
151
- let pendingSignIn;
152
- async function signIn() {
153
- if (pendingSignIn) {
154
- return pendingSignIn;
155
- }
156
- try {
157
- pendingSignIn = _signIn();
158
- return await pendingSignIn;
159
- } finally {
160
- pendingSignIn = void 0;
161
- }
162
- }
163
228
  async function _signIn() {
164
- return token = await maybeRefresh() ?? await maybeHandleAuthReturn() ?? await initiateLoginRedirect();
229
+ return await maybeRefresh() ?? await maybeHandleAuthReturn() ?? await initiateLoginRedirect();
165
230
  }
166
- eventTarget.addEventListener("signIn", restartRefreshTimer);
167
- eventTarget.addEventListener("refresh", restartRefreshTimer);
168
- let token;
169
- const ret = Object.assign(async function ret2() {
170
- if (!token || Date.now() >= token.expires_at) {
171
- token = await signIn();
172
- }
173
- return token.access_token;
174
- }, {
175
- signIn,
176
- refresh,
177
- signOut,
178
- addEventListener: eventTarget.addEventListener.bind(eventTarget),
179
- removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
180
- });
181
- return ret;
231
+ return getToken;
182
232
  }
183
233
 
184
- export { createPublicOauthClient };
234
+ export { createConfidentialOauthClient, createPublicOauthClient };
185
235
  //# sourceMappingURL=out.js.map
186
236
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/createPublicOauthClient.ts","../../src/throwIfError.ts"],"names":["ret"],"mappings":";AAgBA,OAAO,WAAW;AAClB,SAAS,+BAA+B,4BAA4B,aAAa,4BAA4B,qBAAqB,wCAAwC,2BAA2B,0BAA0B,mBAAmB,4BAA4B;AAC9Q,OAAO,eAAe;AACtB,SAAS,wBAAwB;;;ACHjC,SAAS,qBAAqB;AACvB,SAAS,aAAa,QAAQ;AACnC,MAAI,cAAc,MAAM,GAAG;AACzB,UAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,EACxD;AACA,SAAO;AACT;;;ADDA,IAAM,aAAa;AACnB,SAAS,UAAU,GAAG;AACpB,eAAa,QAAQ,YAAY,KAAK,UAAU,CAAC,CAAC;AACpD;AACA,SAAS,cAAc;AACrB,eAAa,WAAW,UAAU;AACpC;AACA,SAAS,YAAY;AACnB,SAAO,KAAK,MAAM,aAAa,QAAQ,UAAU,KAAK,IAAI;AAC5D;AAcO,SAAS,wBAAwB,WAAW,KAAK,aAAa,YAAY,WAAW,gBAAgB,OAAO,SAAS,SAAS,GAAG,SAAS,CAAC,iBAAiB,gBAAgB,GAAG,UAAU,WAAW,OAAO,UAAU,cAAc;AACxO,QAAM,mBAAmB;AAAA,IACvB,CAAC,WAAW,G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AAAA,IACA;AAAA,IACA,kBAAkB,YAAY,iBAAiB,KAAK,WAAW;AAAA,IAC/D,qBAAqB,YAAY,oBAAoB,KAAK,WAAW;AAAA,EACvE,CAAC;AACD,SAAO;AACT","sourcesContent":["/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, processRevocationResponse, refreshTokenGrantRequest, revocationRequest, validateAuthResponse } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\nconst storageKey = \"asdfasdfdhjlkajhgj\";\nfunction saveLocal(x) {\n localStorage.setItem(storageKey, JSON.stringify(x));\n}\nfunction removeLocal() {\n localStorage.removeItem(storageKey);\n}\nfunction readLocal() {\n return JSON.parse(localStorage.getItem(storageKey) ?? \"{}\");\n}\n\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const eventTarget = new TypedEventTarget();\n const issuer = `${new URL(ctxPath, url)}`;\n const as = {\n token_endpoint: `${issuer}/api/oauth2/token`,\n authorization_endpoint: `${issuer}/api/oauth2/authorize`,\n revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,\n issuer\n };\n const client = {\n client_id,\n token_endpoint_auth_method: \"none\"\n };\n async function go(x) {\n if (useHistory) return window.history.replaceState({}, \"\", x);else window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n function makeTokenAndSaveRefresh(resp, type) {\n const {\n refresh_token,\n expires_in,\n access_token\n } = resp;\n !(expires_in != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n saveLocal({\n refresh_token\n });\n token = {\n refresh_token,\n expires_in,\n access_token,\n expires_at: Date.now() + expires_in * 1000\n };\n eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {\n detail: token\n }));\n return token;\n }\n async function maybeRefresh(expectRefreshToken) {\n const {\n refresh_token\n } = readLocal();\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await refreshTokenGrantRequest(as, client, refresh_token, oauthHttpOptions))), \"refresh\");\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 refresh token. Removing refresh token\", e);\n }\n removeLocal();\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n async function maybeHandleAuthReturn() {\n const {\n codeVerifier,\n state,\n oldUrl\n } = readLocal();\n if (!codeVerifier) return;\n try {\n const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(as, client, await authorizationCodeGrantRequest(as, client, throwIfError(validateAuthResponse(as, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), \"signIn\");\n go(oldUrl);\n return ret;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\", e);\n }\n removeLocal();\n }\n }\n async function initiateLoginRedirect() {\n if (loginPage && window.location.href !== loginPage) {\n saveLocal({\n oldUrl: postLoginPage\n });\n return await go(loginPage);\n }\n const state = generateRandomState();\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readLocal().oldUrl ?? window.location.toString();\n saveLocal({\n codeVerifier,\n state,\n oldUrl\n });\n window.location.assign(`${as.authorization_endpoint}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri: redirectUrl,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: [\"offline_access\", ...scopes].join(\" \")\n })}`);\n\n // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout) clearTimeout(refreshTimeout);\n }\n function restartRefreshTimer(evt) {\n rmTimeout();\n refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);\n }\n const refresh = maybeRefresh.bind(globalThis, true);\n async function signOut() {\n !token ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"not signed in\") : invariant(false) : void 0;\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\n\n // Clean up\n removeLocal();\n token = undefined;\n throwIfError(result);\n eventTarget.dispatchTypedEvent(\"signOut\", new Event(\"signOut\"));\n }\n let pendingSignIn;\n async function signIn() {\n if (pendingSignIn) {\n return pendingSignIn;\n }\n try {\n pendingSignIn = _signIn();\n return await pendingSignIn;\n } finally {\n pendingSignIn = undefined;\n }\n }\n /** Will throw if there is no token! */\n async function _signIn() {\n // 1. Check if we have a refresh token in local storage\n return token = (await maybeRefresh()\n // 2. If there is no refresh token we are likely trying to perform the callback\n ) ?? (await maybeHandleAuthReturn())\n // 3. If we haven't been able to load the token from one of the two above ways, we need to make the initial auth request\n ?? (await initiateLoginRedirect());\n }\n eventTarget.addEventListener(\"signIn\", restartRefreshTimer);\n eventTarget.addEventListener(\"refresh\", restartRefreshTimer);\n let token;\n const ret = Object.assign(async function ret() {\n if (!token || Date.now() >= token.expires_at) {\n token = await signIn();\n }\n return token.access_token;\n }, {\n signIn,\n refresh,\n signOut,\n addEventListener: eventTarget.addEventListener.bind(eventTarget),\n removeEventListener: eventTarget.removeEventListener.bind(eventTarget)\n });\n return ret;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}"]}
1
+ {"version":3,"sources":["../../src/createConfidentialOauthClient.ts","../../src/common.ts","../../src/throwIfError.ts","../../src/createPublicOauthClient.ts"],"names":["CustomEvent","getToken","customFetch"],"mappings":";AAgBA,SAAS,+BAA+B,aAAa,wCAAwC;;;ACA7F,SAAS,2BAA2B,yBAAyB;AAC7D,OAAO,eAAe;AACtB,SAAS,wBAAwB;;;ACFjC,SAAS,qBAAqB;AACvB,SAAS,aAAa,QAAQ;AACnC,MAAI,cAAc,MAAM,GAAG;AACzB,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AAwB;AACrC,QAAI,aAAa,OAAO,SAAS,SAAS,WAAW;AACnD,gBAAU,QAAQ;AAAA,QAChB,QAAQ;AAAA,MACV,CAAC;AACD,aAAO,MAAM,GAAG,SAAS;AAAA,IAC3B;AACA,UAAM,QAAQ,oBAAoB;AAClC,UAAM,eAAe,2BAA2B;AAChD,UAAM,SAAS,UAAU,MAAM,EAAE,UAAU,OAAO,SAAS,SAAS;AACpE,cAAU,QAAQ;AAAA,MAChB;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,WAAO,SAAS,OAAO,GAAG,WAAW,sBAAsB,IAAI,IAAI,gBAAgB;AAAA,MACjF;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA,cAAc;AAAA,MACd,gBAAgB,MAAM,2BAA2B,YAAY;AAAA,MAC7D,uBAAuB;AAAA,MACvB,OAAO,CAAC,kBAAkB,GAAG,MAAM,EAAE,KAAK,GAAG;AAAA,IAC/C,CAAC,CAAC,EAAE;AAGJ,UAAM,MAAM,GAAI;AAChB,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAGA,iBAAe,UAAU;AAEvB,WAAQ,MAAM,aAAa,KAErB,MAAM,sBAAsB,KAE9B,MAAM,sBAAsB;AAAA,EAClC;AACA,SAAO;AACT","sourcesContent":["/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { clientCredentialsGrantRequest, customFetch, processClientCredentialsResponse } from \"oauth4webapi\";\nimport { common, createAuthorizationServer } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n\n/**\n * @param client_id\n * @param client_secret\n * @param url the base url of your foundry server\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns which can be used as a token provider\n */\nexport function createConfidentialOauthClient(client_id, client_secret, url, scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = {\n client_id,\n client_secret\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const {\n getToken,\n makeTokenAndSaveRefresh\n } = common(client, authServer, _signIn, oauthHttpOptions, undefined);\n async function _signIn() {\n return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({\n scope: scopes.join(\" \")\n }), oauthHttpOptions))), \"signIn\");\n }\n return getToken;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { processRevocationResponse, revocationRequest } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\n// Node 18 is supposed to have a `CustomEvent` but it is not exposed on `globalThis`\n// which creates a problem for making a single codebase for node and browser. This polyfill works around it\nconst CustomEvent = process.env.target === \"browser\" ? globalThis.CustomEvent : globalThis.CustomEvent ?? class CustomEvent extends Event {\n #detail;\n constructor(type, options) {\n super(type, options);\n this.#detail = options?.detail ?? null;\n }\n get detail() {\n return this.#detail;\n }\n};\nconst localStorage = globalThis.localStorage;\nexport function saveLocal(client, x) {\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));\n}\nexport function removeLocal(client) {\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);\n}\nexport function readLocal(client) {\n return JSON.parse(\n // MUST `localStorage?` as nodejs does not have localStorage\n localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? \"{}\");\n}\nexport function common(client, as, _signIn, oauthHttpOptions, refresh) {\n let token;\n const eventTarget = new TypedEventTarget();\n function makeTokenAndSaveRefresh(resp, type) {\n const {\n refresh_token,\n expires_in,\n access_token\n } = resp;\n !(expires_in != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n saveLocal(client, {\n refresh_token\n });\n token = {\n refresh_token,\n expires_in,\n access_token,\n expires_at: Date.now() + expires_in * 1000\n };\n eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {\n detail: token\n }));\n return token;\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout) clearTimeout(refreshTimeout);\n }\n function restartRefreshTimer(evt) {\n if (refresh) {\n rmTimeout();\n refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);\n }\n }\n async function signOut() {\n !token ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"not signed in\") : invariant(false) : void 0;\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\n\n // Clean up\n removeLocal(client);\n token = undefined;\n throwIfError(result);\n eventTarget.dispatchTypedEvent(\"signOut\", new Event(\"signOut\"));\n }\n let pendingSignIn;\n async function signIn() {\n if (pendingSignIn) {\n return pendingSignIn;\n }\n try {\n pendingSignIn = _signIn();\n return await pendingSignIn;\n } finally {\n pendingSignIn = undefined;\n }\n }\n eventTarget.addEventListener(\"signIn\", restartRefreshTimer);\n eventTarget.addEventListener(\"refresh\", restartRefreshTimer);\n const getToken = Object.assign(async function getToken() {\n if (!token || Date.now() >= token.expires_at) {\n token = await signIn();\n }\n return token.access_token;\n }, {\n signIn,\n refresh,\n signOut,\n rmTimeout,\n addEventListener: eventTarget.addEventListener.bind(eventTarget),\n removeEventListener: eventTarget.removeEventListener.bind(eventTarget)\n });\n return {\n getToken,\n makeTokenAndSaveRefresh\n };\n}\nexport function createAuthorizationServer(ctxPath, url) {\n const issuer = `${new URL(ctxPath, url)}`;\n return {\n token_endpoint: `${issuer}/api/oauth2/token`,\n authorization_endpoint: `${issuer}/api/oauth2/authorize`,\n revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,\n issuer\n };\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport delay from \"delay\";\nimport { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, validateAuthResponse } from \"oauth4webapi\";\nimport { common, createAuthorizationServer, readLocal, removeLocal, saveLocal } from \"./common.js\";\nimport { throwIfError } from \"./throwIfError.js\";\n/**\n * @param client_id\n * @param url the base url of your foundry server\n * @param redirectUrl the url configured for redirect in the oauth configuration on the server\n * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`\n * @param loginPage if you want a custom landing page prior to logging in, set this to that url\n * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded\n * @param scopes\n * @param fetchFn\n * @param ctxPath\n * @returns {PublicOauthClient} which can be used as a token provider\n */\nexport function createPublicOauthClient(client_id, url, redirectUrl, useHistory, loginPage, postLoginPage = window.location.toString(), scopes = [\"api:read-data\", \"api:write-data\"], fetchFn = globalThis.fetch, ctxPath = \"/multipass\") {\n const client = {\n client_id,\n token_endpoint_auth_method: \"none\"\n };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = {\n [customFetch]: fetchFn\n };\n const {\n makeTokenAndSaveRefresh,\n getToken\n } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));\n async function go(x) {\n if (useHistory) return window.history.replaceState({}, \"\", x);else window.location.assign(x);\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n async function maybeRefresh(expectRefreshToken) {\n const {\n refresh_token\n } = readLocal(client);\n if (!refresh_token) {\n if (expectRefreshToken) throw new Error(\"No refresh token found\");\n return;\n }\n try {\n // note, we don't use processRefreshTokenResponse because the mp oauth implementation\n // doesn't do refresh tokens quite right and this lets us skip the id check\n return makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), \"refresh\");\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 refresh token. Removing refresh token\", e);\n }\n removeLocal(client);\n if (expectRefreshToken) {\n throw new Error(\"Could not refresh token\");\n }\n }\n }\n async function maybeHandleAuthReturn() {\n const {\n codeVerifier,\n state,\n oldUrl\n } = readLocal(client);\n if (!codeVerifier) return;\n try {\n const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), \"signIn\");\n go(oldUrl);\n return ret;\n } catch (e) {\n if (process?.env?.NODE_ENV !== \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\"Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow\", e);\n }\n removeLocal(client);\n }\n }\n async function initiateLoginRedirect() {\n if (loginPage && window.location.href !== loginPage) {\n saveLocal(client, {\n oldUrl: postLoginPage\n });\n return await go(loginPage);\n }\n const state = generateRandomState();\n const codeVerifier = generateRandomCodeVerifier();\n const oldUrl = readLocal(client).oldUrl ?? window.location.toString();\n saveLocal(client, {\n codeVerifier,\n state,\n oldUrl\n });\n window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({\n client_id,\n response_type: \"code\",\n state,\n redirect_uri: redirectUrl,\n code_challenge: await calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: \"S256\",\n scope: [\"offline_access\", ...scopes].join(\" \")\n })}`);\n\n // Give time for redirect to happen\n await delay(1000);\n throw new Error(\"Unable to redirect\");\n }\n\n /** Will throw if there is no token! */\n async function _signIn() {\n // 1. Check if we have a refresh token in local storage\n return (await maybeRefresh()\n // 2. If there is no refresh token we are likely trying to perform the callback\n ) ?? (await maybeHandleAuthReturn())\n // 3. If we haven't been able to load the token from one of the two above ways, we need to make the initial auth request\n ?? (await initiateLoginRedirect());\n }\n return getToken;\n}"]}