@osdk/oauth 0.4.0-beta.1 → 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.
- package/CHANGELOG.md +12 -0
- package/build/browser/BaseOauthClient.d.ts +15 -0
- package/build/browser/BaseOauthClient.d.ts.map +1 -0
- package/build/browser/BaseOauthClient.js +17 -0
- package/build/browser/BaseOauthClient.js.map +1 -0
- package/build/browser/ConfidentialOauthClient.d.ts +4 -0
- package/build/browser/ConfidentialOauthClient.d.ts.map +1 -0
- package/build/browser/ConfidentialOauthClient.js +17 -0
- package/build/browser/ConfidentialOauthClient.js.map +1 -0
- package/build/browser/PublicOauthClient.d.ts +6 -0
- package/build/browser/PublicOauthClient.d.ts.map +1 -0
- package/build/browser/PublicOauthClient.js +17 -0
- package/build/browser/PublicOauthClient.js.map +1 -0
- package/build/browser/Token.d.ts +7 -0
- package/build/browser/Token.d.ts.map +1 -0
- package/build/browser/Token.js +17 -0
- package/build/browser/Token.js.map +1 -0
- package/build/browser/common.d.ts +36 -0
- package/build/browser/common.d.ts.map +1 -0
- package/build/browser/common.js +128 -0
- package/build/browser/common.js.map +1 -0
- package/build/browser/createConfidentialOauthClient.d.ts +12 -0
- package/build/browser/createConfidentialOauthClient.d.ts.map +1 -0
- package/build/browser/createConfidentialOauthClient.js +47 -0
- package/build/browser/createConfidentialOauthClient.js.map +1 -0
- package/build/browser/createPublicOauthClient.d.ts +15 -0
- package/build/browser/createPublicOauthClient.d.ts.map +1 -0
- package/build/browser/createPublicOauthClient.js +140 -0
- package/build/browser/createPublicOauthClient.js.map +1 -0
- package/build/browser/index.d.ts +4 -0
- package/build/browser/index.d.ts.map +1 -0
- package/build/browser/index.js +17 -243
- package/build/browser/index.js.map +1 -1
- package/build/browser/throwIfError.d.ts +6 -0
- package/build/browser/throwIfError.d.ts.map +1 -0
- package/build/browser/throwIfError.js +23 -0
- package/build/browser/throwIfError.js.map +1 -0
- package/build/esm/BaseOauthClient.js +17 -0
- package/build/esm/BaseOauthClient.js.map +1 -0
- package/build/esm/ConfidentialOauthClient.js +17 -0
- package/build/esm/ConfidentialOauthClient.js.map +1 -0
- package/build/esm/PublicOauthClient.js +17 -0
- package/build/esm/PublicOauthClient.js.map +1 -0
- package/build/esm/Token.js +17 -0
- package/build/esm/Token.js.map +1 -0
- package/build/esm/common.js +137 -0
- package/build/esm/common.js.map +1 -0
- package/build/esm/createConfidentialOauthClient.js +47 -0
- package/build/esm/createConfidentialOauthClient.js.map +1 -0
- package/build/esm/createPublicOauthClient.js +140 -0
- package/build/esm/createPublicOauthClient.js.map +1 -0
- package/build/esm/index.js +17 -252
- package/build/esm/index.js.map +1 -1
- package/build/esm/throwIfError.js +23 -0
- package/build/esm/throwIfError.js.map +1 -0
- package/package.json +4 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACnF,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,YAAY,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC"}
|
package/build/browser/index.js
CHANGED
|
@@ -1,244 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
19
|
-
}
|
|
20
|
-
function removeLocal(client) {
|
|
21
|
-
localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
22
|
-
}
|
|
23
|
-
function readLocal(client) {
|
|
24
|
-
return JSON.parse(
|
|
25
|
-
// MUST `localStorage?` as nodejs does not have localStorage
|
|
26
|
-
localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}"
|
|
27
|
-
);
|
|
28
|
-
}
|
|
29
|
-
function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
30
|
-
let token;
|
|
31
|
-
const eventTarget = new TypedEventTarget();
|
|
32
|
-
function makeTokenAndSaveRefresh(resp, type) {
|
|
33
|
-
const {
|
|
34
|
-
refresh_token,
|
|
35
|
-
expires_in,
|
|
36
|
-
access_token
|
|
37
|
-
} = resp;
|
|
38
|
-
!(expires_in != null) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
|
|
39
|
-
saveLocal(client, {
|
|
40
|
-
refresh_token
|
|
41
|
-
});
|
|
42
|
-
token = {
|
|
43
|
-
refresh_token,
|
|
44
|
-
expires_in,
|
|
45
|
-
access_token,
|
|
46
|
-
expires_at: Date.now() + expires_in * 1e3
|
|
47
|
-
};
|
|
48
|
-
eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {
|
|
49
|
-
detail: token
|
|
50
|
-
}));
|
|
51
|
-
return token;
|
|
52
|
-
}
|
|
53
|
-
let refreshTimeout;
|
|
54
|
-
function rmTimeout() {
|
|
55
|
-
if (refreshTimeout) clearTimeout(refreshTimeout);
|
|
56
|
-
}
|
|
57
|
-
function restartRefreshTimer(evt) {
|
|
58
|
-
if (refresh) {
|
|
59
|
-
rmTimeout();
|
|
60
|
-
refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1e3 - 60 * 1e3);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
async function signOut() {
|
|
64
|
-
!token ? process.env.NODE_ENV !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
|
|
65
|
-
const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
|
|
66
|
-
rmTimeout();
|
|
67
|
-
removeLocal(client);
|
|
68
|
-
token = void 0;
|
|
69
|
-
throwIfError(result);
|
|
70
|
-
eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
|
|
71
|
-
}
|
|
72
|
-
let pendingSignIn;
|
|
73
|
-
async function signIn() {
|
|
74
|
-
if (pendingSignIn) {
|
|
75
|
-
return pendingSignIn;
|
|
76
|
-
}
|
|
77
|
-
try {
|
|
78
|
-
pendingSignIn = _signIn();
|
|
79
|
-
return await pendingSignIn;
|
|
80
|
-
} finally {
|
|
81
|
-
pendingSignIn = void 0;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
eventTarget.addEventListener("signIn", restartRefreshTimer);
|
|
85
|
-
eventTarget.addEventListener("refresh", restartRefreshTimer);
|
|
86
|
-
function getTokenOrUndefined() {
|
|
87
|
-
if (!token || Date.now() >= token.expires_at) {
|
|
88
|
-
return void 0;
|
|
89
|
-
}
|
|
90
|
-
return token?.access_token;
|
|
91
|
-
}
|
|
92
|
-
const getToken = Object.assign(async function getToken2() {
|
|
93
|
-
if (!token || Date.now() >= token.expires_at) {
|
|
94
|
-
token = await signIn();
|
|
95
|
-
}
|
|
96
|
-
return token.access_token;
|
|
97
|
-
}, {
|
|
98
|
-
signIn,
|
|
99
|
-
refresh,
|
|
100
|
-
signOut,
|
|
101
|
-
rmTimeout,
|
|
102
|
-
getTokenOrUndefined,
|
|
103
|
-
addEventListener: eventTarget.addEventListener.bind(eventTarget),
|
|
104
|
-
removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
|
|
105
|
-
});
|
|
106
|
-
return {
|
|
107
|
-
getToken,
|
|
108
|
-
makeTokenAndSaveRefresh
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
function createAuthorizationServer(ctxPath, url) {
|
|
112
|
-
const issuer = `${new URL(ctxPath, url)}`;
|
|
113
|
-
return {
|
|
114
|
-
token_endpoint: `${issuer}/api/oauth2/token`,
|
|
115
|
-
authorization_endpoint: `${issuer}/api/oauth2/authorize`,
|
|
116
|
-
revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
|
|
117
|
-
issuer
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// src/createConfidentialOauthClient.ts
|
|
122
|
-
function createConfidentialOauthClient(client_id, client_secret, url, scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
|
|
123
|
-
const client = {
|
|
124
|
-
client_id,
|
|
125
|
-
client_secret
|
|
126
|
-
};
|
|
127
|
-
const authServer = createAuthorizationServer(ctxPath, url);
|
|
128
|
-
const oauthHttpOptions = {
|
|
129
|
-
[customFetch]: fetchFn
|
|
130
|
-
};
|
|
131
|
-
const {
|
|
132
|
-
getToken,
|
|
133
|
-
makeTokenAndSaveRefresh
|
|
134
|
-
} = common(client, authServer, _signIn, oauthHttpOptions, void 0);
|
|
135
|
-
async function _signIn() {
|
|
136
|
-
return makeTokenAndSaveRefresh(throwIfError(await processClientCredentialsResponse(authServer, client, await clientCredentialsGrantRequest(authServer, client, new URLSearchParams({
|
|
137
|
-
scope: scopes.join(" ")
|
|
138
|
-
}), oauthHttpOptions))), "signIn");
|
|
139
|
-
}
|
|
140
|
-
return getToken;
|
|
141
|
-
}
|
|
142
|
-
function createPublicOauthClient(client_id, url, redirectUrl, useHistory = true, loginPage, postLoginPage = window.location.toString(), scopes = [], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
|
|
143
|
-
const client = {
|
|
144
|
-
client_id,
|
|
145
|
-
token_endpoint_auth_method: "none"
|
|
146
|
-
};
|
|
147
|
-
const authServer = createAuthorizationServer(ctxPath, url);
|
|
148
|
-
const oauthHttpOptions = {
|
|
149
|
-
[customFetch]: fetchFn
|
|
150
|
-
};
|
|
151
|
-
if (scopes.length === 0) {
|
|
152
|
-
scopes = ["api:read-data", "api:write-data"];
|
|
153
|
-
}
|
|
154
|
-
const {
|
|
155
|
-
makeTokenAndSaveRefresh,
|
|
156
|
-
getToken
|
|
157
|
-
} = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
|
|
158
|
-
async function go(x) {
|
|
159
|
-
if (useHistory) return window.history.replaceState({}, "", x);
|
|
160
|
-
else window.location.assign(x);
|
|
161
|
-
await delay(1e3);
|
|
162
|
-
throw new Error("Unable to redirect");
|
|
163
|
-
}
|
|
164
|
-
async function maybeRefresh(expectRefreshToken) {
|
|
165
|
-
const {
|
|
166
|
-
refresh_token
|
|
167
|
-
} = readLocal(client);
|
|
168
|
-
if (!refresh_token) {
|
|
169
|
-
if (expectRefreshToken) throw new Error("No refresh token found");
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
try {
|
|
173
|
-
const result = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await refreshTokenGrantRequest(authServer, client, refresh_token, oauthHttpOptions))), "refresh");
|
|
174
|
-
if (result && window.location.pathname === new URL(redirectUrl).pathname) {
|
|
175
|
-
const {
|
|
176
|
-
oldUrl
|
|
177
|
-
} = readLocal(client);
|
|
178
|
-
go(oldUrl ?? "/");
|
|
179
|
-
}
|
|
180
|
-
return result;
|
|
181
|
-
} catch (e) {
|
|
182
|
-
if (process?.env?.NODE_ENV !== "production") {
|
|
183
|
-
console.warn("Failed to get OAuth2 refresh token. Removing refresh token", e);
|
|
184
|
-
}
|
|
185
|
-
removeLocal(client);
|
|
186
|
-
if (expectRefreshToken) {
|
|
187
|
-
throw new Error("Could not refresh token");
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
async function maybeHandleAuthReturn() {
|
|
192
|
-
const {
|
|
193
|
-
codeVerifier,
|
|
194
|
-
state,
|
|
195
|
-
oldUrl
|
|
196
|
-
} = readLocal(client);
|
|
197
|
-
if (!codeVerifier) return;
|
|
198
|
-
try {
|
|
199
|
-
const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirectUrl, codeVerifier, oauthHttpOptions))), "signIn");
|
|
200
|
-
go(oldUrl);
|
|
201
|
-
return ret;
|
|
202
|
-
} catch (e) {
|
|
203
|
-
if (process?.env?.NODE_ENV !== "production") {
|
|
204
|
-
console.warn("Failed to get OAuth2 token using PKCE, removing PKCE and starting a new auth flow", e);
|
|
205
|
-
}
|
|
206
|
-
removeLocal(client);
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
async function initiateLoginRedirect() {
|
|
210
|
-
if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {
|
|
211
|
-
saveLocal(client, {
|
|
212
|
-
oldUrl: postLoginPage
|
|
213
|
-
});
|
|
214
|
-
return await go(loginPage);
|
|
215
|
-
}
|
|
216
|
-
const state = generateRandomState();
|
|
217
|
-
const codeVerifier = generateRandomCodeVerifier();
|
|
218
|
-
const oldUrl = readLocal(client).oldUrl ?? window.location.toString();
|
|
219
|
-
saveLocal(client, {
|
|
220
|
-
codeVerifier,
|
|
221
|
-
state,
|
|
222
|
-
oldUrl
|
|
223
|
-
});
|
|
224
|
-
window.location.assign(`${authServer.authorization_endpoint}?${new URLSearchParams({
|
|
225
|
-
client_id,
|
|
226
|
-
response_type: "code",
|
|
227
|
-
state,
|
|
228
|
-
redirect_uri: redirectUrl,
|
|
229
|
-
code_challenge: await calculatePKCECodeChallenge(codeVerifier),
|
|
230
|
-
code_challenge_method: "S256",
|
|
231
|
-
scope: ["offline_access", ...scopes].join(" ")
|
|
232
|
-
})}`);
|
|
233
|
-
await delay(1e3);
|
|
234
|
-
throw new Error("Unable to redirect");
|
|
235
|
-
}
|
|
236
|
-
async function _signIn() {
|
|
237
|
-
return await maybeRefresh() ?? await maybeHandleAuthReturn() ?? await initiateLoginRedirect();
|
|
238
|
-
}
|
|
239
|
-
return getToken;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
export { createConfidentialOauthClient, createPublicOauthClient };
|
|
243
|
-
//# 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";
|
|
244
18
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/throwIfError.ts","../../src/common.ts","../../src/createConfidentialOauthClient.ts","../../src/createPublicOauthClient.ts"],"names":["getToken","customFetch"],"mappings":";;;;;;AAiBO,SAAS,aAAa,MAAQ,EAAA;AACnC,EAAI,IAAA,aAAA,CAAc,MAAM,CAAG,EAAA;AACzB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAwB,qBAAA,EAAA,MAAA,CAAO,KAAK,CAAE,CAAA,CAAA,CAAA;AAAA,GACxD;AACA,EAAO,OAAA,MAAA,CAAA;AACT,CAAA;;;ACAA,IAAM,WAAA,GAAiD,UAAW,CAAA,WAAA,CASlE,CAAA;AACA,IAAM,eAAe,UAAW,CAAA,YAAA,CAAA;AACzB,SAAS,SAAA,CAAU,QAAQ,CAAG,EAAA;AAEnC,EAAc,YAAA,EAAA,OAAA,CAAQ,2BAA2B,MAAO,CAAA,SAAS,IAAI,IAAK,CAAA,SAAA,CAAU,CAAC,CAAC,CAAA,CAAA;AACxF,CAAA;AACO,SAAS,YAAY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,MACvB,OAAO,CAAC,gBAAA,EAAkB,GAAG,MAAM,CAAA,CAAE,KAAK,GAAG,CAAA;AAAA,KAC9C,CAAC,CAAE,CAAA,CAAA,CAAA;AAGJ,IAAA,MAAM,MAAM,GAAI,CAAA,CAAA;AAChB,IAAM,MAAA,IAAI,MAAM,oBAAoB,CAAA,CAAA;AAAA,GACtC;AAGA,EAAA,eAAe,OAAU,GAAA;AAEvB,IAAA,OAAQ,MAAM,YAAa,EAAA,IAErB,MAAM,qBAAsB,EAAA,IAE9B,MAAM,qBAAsB,EAAA,CAAA;AAAA,GAClC;AACA,EAAO,OAAA,QAAA,CAAA;AACT","file":"index.js","sourcesContent":["/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isOAuth2Error } from \"oauth4webapi\";\nexport function throwIfError(result) {\n if (isOAuth2Error(result)) {\n throw new Error(`Failed to get token: ${result.error}`);\n }\n return result;\n}","/*\n * Copyright 2024 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { processRevocationResponse, revocationRequest } from \"oauth4webapi\";\nimport invariant from \"tiny-invariant\";\nimport { TypedEventTarget } from \"typescript-event-target\";\nimport { throwIfError } from \"./throwIfError.js\";\n// Node 18 is supposed to have a `CustomEvent` but it is not exposed on `globalThis`\n// which creates a problem for making a single codebase for node and browser. This polyfill works around it\nconst CustomEvent = process.env.TARGET === \"browser\" ? globalThis.CustomEvent : globalThis.CustomEvent ?? class CustomEvent extends Event {\n #detail;\n constructor(type, options) {\n super(type, options);\n this.#detail = options?.detail ?? null;\n }\n get detail() {\n return this.#detail;\n }\n};\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,6 @@
|
|
|
1
|
+
import type { OAuth2Error } from "oauth4webapi";
|
|
2
|
+
import { isOAuth2Error } from "oauth4webapi";
|
|
3
|
+
type IsErrorInputs = Parameters<typeof isOAuth2Error>[0];
|
|
4
|
+
export declare function throwIfError<T extends IsErrorInputs>(result: T | OAuth2Error): Exclude<T, OAuth2Error>;
|
|
5
|
+
export {};
|
|
6
|
+
//# sourceMappingURL=throwIfError.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"throwIfError.d.ts","sourceRoot":"","sources":["../../src/throwIfError.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,KAAK,aAAa,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;AACzD,wBAAgB,YAAY,CAAC,CAAC,SAAS,aAAa,EAClD,MAAM,EAAE,CAAC,GAAG,WAAW,GACtB,OAAO,CAAC,CAAC,EAAE,WAAW,CAAC,CAKzB"}
|
|
@@ -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":[]}
|
|
@@ -0,0 +1,17 @@
|
|
|
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 {};
|
|
17
|
+
//# sourceMappingURL=BaseOauthClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseOauthClient.js","names":[],"sources":["BaseOauthClient.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 {};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]}
|
|
@@ -0,0 +1,17 @@
|
|
|
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 {};
|
|
17
|
+
//# sourceMappingURL=ConfidentialOauthClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ConfidentialOauthClient.js","names":[],"sources":["ConfidentialOauthClient.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 {};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]}
|
|
@@ -0,0 +1,17 @@
|
|
|
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 {};
|
|
17
|
+
//# sourceMappingURL=PublicOauthClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PublicOauthClient.js","names":[],"sources":["PublicOauthClient.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 {};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]}
|
|
@@ -0,0 +1,17 @@
|
|
|
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 {};
|
|
17
|
+
//# sourceMappingURL=Token.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Token.js","names":[],"sources":["Token.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 {};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]}
|
|
@@ -0,0 +1,137 @@
|
|
|
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 { processRevocationResponse, revocationRequest } from "oauth4webapi";
|
|
17
|
+
import invariant from "tiny-invariant";
|
|
18
|
+
import { TypedEventTarget } from "typescript-event-target";
|
|
19
|
+
import { throwIfError } from "./throwIfError.js";
|
|
20
|
+
// Node 18 is supposed to have a `CustomEvent` but it is not exposed on `globalThis`
|
|
21
|
+
// which creates a problem for making a single codebase for node and browser. This polyfill works around it
|
|
22
|
+
const CustomEvent = globalThis.CustomEvent ?? class extends Event {
|
|
23
|
+
#detail;
|
|
24
|
+
constructor(type, options) {
|
|
25
|
+
super(type, options);
|
|
26
|
+
this.#detail = options?.detail ?? null;
|
|
27
|
+
}
|
|
28
|
+
get detail() {
|
|
29
|
+
return this.#detail;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
const localStorage = globalThis.localStorage;
|
|
33
|
+
export function saveLocal(client, x) {
|
|
34
|
+
// MUST `localStorage?` as nodejs does not have localStorage
|
|
35
|
+
localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
|
|
36
|
+
}
|
|
37
|
+
export function removeLocal(client) {
|
|
38
|
+
// MUST `localStorage?` as nodejs does not have localStorage
|
|
39
|
+
localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
|
|
40
|
+
}
|
|
41
|
+
export function readLocal(client) {
|
|
42
|
+
return JSON.parse(
|
|
43
|
+
// MUST `localStorage?` as nodejs does not have localStorage
|
|
44
|
+
localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}");
|
|
45
|
+
}
|
|
46
|
+
export function common(client, as, _signIn, oauthHttpOptions, refresh) {
|
|
47
|
+
let token;
|
|
48
|
+
const eventTarget = new TypedEventTarget();
|
|
49
|
+
function makeTokenAndSaveRefresh(resp, type) {
|
|
50
|
+
const {
|
|
51
|
+
refresh_token,
|
|
52
|
+
expires_in,
|
|
53
|
+
access_token
|
|
54
|
+
} = resp;
|
|
55
|
+
!(expires_in != null) ? undefined !== "production" ? invariant(false) : invariant(false) : void 0;
|
|
56
|
+
saveLocal(client, {
|
|
57
|
+
refresh_token
|
|
58
|
+
});
|
|
59
|
+
token = {
|
|
60
|
+
refresh_token,
|
|
61
|
+
expires_in,
|
|
62
|
+
access_token,
|
|
63
|
+
expires_at: Date.now() + expires_in * 1000
|
|
64
|
+
};
|
|
65
|
+
eventTarget.dispatchTypedEvent(type, new CustomEvent(type, {
|
|
66
|
+
detail: token
|
|
67
|
+
}));
|
|
68
|
+
return token;
|
|
69
|
+
}
|
|
70
|
+
let refreshTimeout;
|
|
71
|
+
function rmTimeout() {
|
|
72
|
+
if (refreshTimeout) clearTimeout(refreshTimeout);
|
|
73
|
+
}
|
|
74
|
+
function restartRefreshTimer(evt) {
|
|
75
|
+
if (refresh) {
|
|
76
|
+
rmTimeout();
|
|
77
|
+
refreshTimeout = setTimeout(refresh, evt.detail.expires_in * 1000 - 60 * 1000);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
let pendingSignIn;
|
|
81
|
+
async function signIn() {
|
|
82
|
+
if (pendingSignIn) {
|
|
83
|
+
return pendingSignIn;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
pendingSignIn = _signIn();
|
|
87
|
+
return await pendingSignIn;
|
|
88
|
+
} finally {
|
|
89
|
+
pendingSignIn = undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
eventTarget.addEventListener("signIn", restartRefreshTimer);
|
|
93
|
+
eventTarget.addEventListener("refresh", restartRefreshTimer);
|
|
94
|
+
function getTokenOrUndefined() {
|
|
95
|
+
if (!token || Date.now() >= token.expires_at) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
return token?.access_token;
|
|
99
|
+
}
|
|
100
|
+
const getToken = Object.assign(async function getToken() {
|
|
101
|
+
if (!token || Date.now() >= token.expires_at) {
|
|
102
|
+
token = await signIn();
|
|
103
|
+
}
|
|
104
|
+
return token?.access_token;
|
|
105
|
+
}, {
|
|
106
|
+
signIn,
|
|
107
|
+
refresh,
|
|
108
|
+
signOut: async function signOut() {
|
|
109
|
+
!token ? undefined !== "production" ? invariant(false, "not signed in") : invariant(false) : void 0;
|
|
110
|
+
const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));
|
|
111
|
+
rmTimeout();
|
|
112
|
+
// Clean up
|
|
113
|
+
removeLocal(client);
|
|
114
|
+
token = undefined;
|
|
115
|
+
throwIfError(result);
|
|
116
|
+
eventTarget.dispatchTypedEvent("signOut", new Event("signOut"));
|
|
117
|
+
},
|
|
118
|
+
rmTimeout,
|
|
119
|
+
getTokenOrUndefined,
|
|
120
|
+
addEventListener: eventTarget.addEventListener.bind(eventTarget),
|
|
121
|
+
removeEventListener: eventTarget.removeEventListener.bind(eventTarget)
|
|
122
|
+
});
|
|
123
|
+
return {
|
|
124
|
+
getToken,
|
|
125
|
+
makeTokenAndSaveRefresh
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
export function createAuthorizationServer(ctxPath, url) {
|
|
129
|
+
const issuer = `${new URL(ctxPath, url)}`;
|
|
130
|
+
return {
|
|
131
|
+
token_endpoint: `${issuer}/api/oauth2/token`,
|
|
132
|
+
authorization_endpoint: `${issuer}/api/oauth2/authorize`,
|
|
133
|
+
revocation_endpoint: `${issuer}/api/oauth2/revoke_token`,
|
|
134
|
+
issuer
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=common.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common.js","names":["processRevocationResponse","revocationRequest","invariant","TypedEventTarget","throwIfError","CustomEvent","globalThis","Event","detail","constructor","type","options","localStorage","saveLocal","client","x","setItem","client_id","JSON","stringify","removeLocal","removeItem","readLocal","parse","getItem","common","as","_signIn","oauthHttpOptions","refresh","token","eventTarget","makeTokenAndSaveRefresh","resp","refresh_token","expires_in","access_token","undefined","expires_at","Date","now","dispatchTypedEvent","refreshTimeout","rmTimeout","clearTimeout","restartRefreshTimer","evt","setTimeout","pendingSignIn","signIn","addEventListener","getTokenOrUndefined","getToken","Object","assign","signOut","result","bind","removeEventListener","createAuthorizationServer","ctxPath","url","issuer","URL","token_endpoint","authorization_endpoint","revocation_endpoint"],"sources":["common.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 { 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\"\n ? globalThis.CustomEvent\n : globalThis.CustomEvent\n ?? 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 ?? \"{}\");\n}\nexport function common(client, as, _signIn, oauthHttpOptions, refresh) {\n let token;\n const eventTarget = new TypedEventTarget();\n function makeTokenAndSaveRefresh(resp, type) {\n const { refresh_token, expires_in, access_token } = resp;\n invariant(expires_in != null);\n saveLocal(client, { refresh_token });\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, { detail: token }));\n return token;\n }\n let refreshTimeout;\n function rmTimeout() {\n if (refreshTimeout)\n 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 invariant(token, \"not signed in\");\n const result = await processRevocationResponse(await revocationRequest(as, client, token.access_token, oauthHttpOptions));\n rmTimeout();\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 }\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 { getToken, makeTokenAndSaveRefresh };\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"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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