@osdk/oauth 1.1.0-beta.1 → 1.1.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 +15 -0
  2. package/build/browser/AuthorizationServer.test.d.ts +2 -0
  3. package/build/browser/AuthorizationServer.test.d.ts.map +1 -0
  4. package/build/browser/AuthorizationServer.test.js +45 -0
  5. package/build/browser/AuthorizationServer.test.js.map +1 -0
  6. package/build/browser/__tests__/createPublicOauthClient.test.d.ts +2 -0
  7. package/build/browser/__tests__/createPublicOauthClient.test.d.ts.map +1 -0
  8. package/build/browser/__tests__/createPublicOauthClient.test.js +56 -0
  9. package/build/browser/__tests__/createPublicOauthClient.test.js.map +1 -0
  10. package/build/browser/common.d.ts +1 -2
  11. package/build/browser/common.d.ts.map +1 -1
  12. package/build/browser/common.js +3 -4
  13. package/build/browser/common.js.map +1 -1
  14. package/build/browser/createConfidentialOauthClient.d.ts.map +1 -1
  15. package/build/browser/createConfidentialOauthClient.js +1 -1
  16. package/build/browser/createConfidentialOauthClient.js.map +1 -1
  17. package/build/browser/createPublicOauthClient.d.ts +48 -10
  18. package/build/browser/createPublicOauthClient.d.ts.map +1 -1
  19. package/build/browser/createPublicOauthClient.js +19 -23
  20. package/build/browser/createPublicOauthClient.js.map +1 -1
  21. package/build/browser/publicOauth.test.d.ts +2 -0
  22. package/build/browser/publicOauth.test.d.ts.map +1 -0
  23. package/build/browser/publicOauth.test.js +242 -0
  24. package/build/browser/publicOauth.test.js.map +1 -0
  25. package/build/browser/utils.d.ts +6 -0
  26. package/build/browser/utils.d.ts.map +1 -0
  27. package/build/browser/utils.js +44 -0
  28. package/build/browser/utils.js.map +1 -0
  29. package/build/esm/AuthorizationServer.test.d.ts +2 -0
  30. package/build/esm/AuthorizationServer.test.d.ts.map +1 -0
  31. package/build/esm/AuthorizationServer.test.js +45 -0
  32. package/build/esm/AuthorizationServer.test.js.map +1 -0
  33. package/build/esm/__tests__/createPublicOauthClient.test.d.ts +2 -0
  34. package/build/esm/__tests__/createPublicOauthClient.test.d.ts.map +1 -0
  35. package/build/esm/__tests__/createPublicOauthClient.test.js +56 -0
  36. package/build/esm/__tests__/createPublicOauthClient.test.js.map +1 -0
  37. package/build/esm/common.d.ts +1 -2
  38. package/build/esm/common.d.ts.map +1 -1
  39. package/build/esm/common.js +3 -4
  40. package/build/esm/common.js.map +1 -1
  41. package/build/esm/createConfidentialOauthClient.d.ts.map +1 -1
  42. package/build/esm/createConfidentialOauthClient.js +1 -1
  43. package/build/esm/createConfidentialOauthClient.js.map +1 -1
  44. package/build/esm/createPublicOauthClient.d.ts +48 -10
  45. package/build/esm/createPublicOauthClient.d.ts.map +1 -1
  46. package/build/esm/createPublicOauthClient.js +19 -23
  47. package/build/esm/createPublicOauthClient.js.map +1 -1
  48. package/build/esm/publicOauth.test.d.ts +2 -0
  49. package/build/esm/publicOauth.test.d.ts.map +1 -0
  50. package/build/esm/publicOauth.test.js +242 -0
  51. package/build/esm/publicOauth.test.js.map +1 -0
  52. package/build/esm/utils.d.ts +6 -0
  53. package/build/esm/utils.d.ts.map +1 -0
  54. package/build/esm/utils.js +44 -0
  55. package/build/esm/utils.js.map +1 -0
  56. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @osdk/oauth
2
2
 
3
+ ## 1.1.0-beta.3
4
+
5
+ ### Minor Changes
6
+
7
+ - 91cfa3a: Fixing url parsing for client.
8
+ - d501104: Adds unit testing of public oauth flow
9
+ - 91cfa3a: Fixing URL parsing for custom entry points.
10
+
11
+ ## 1.1.0-beta.2
12
+
13
+ ### Minor Changes
14
+
15
+ - 33590c7: Add tests for createPublicOauthClient overload
16
+ - e00bb29: Overload createPublicOauthClient to support object of options
17
+
3
18
  ## 1.1.0-beta.1
4
19
 
5
20
  ### Minor Changes
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=AuthorizationServer.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuthorizationServer.test.d.ts","sourceRoot":"","sources":["../../src/AuthorizationServer.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,45 @@
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 { describe, expect, it } from "vitest";
17
+ import { createAuthorizationServer } from "./common.js";
18
+ describe("Create authorization server", () => {
19
+ it("works with old multipass ctx path", () => {
20
+ const authServer = createAuthorizationServer("/multipass", "https://stack.palantir.com");
21
+ expect(authServer).toEqual({
22
+ token_endpoint: "https://stack.palantir.com/multipass/api/oauth2/token",
23
+ authorization_endpoint: "https://stack.palantir.com/multipass/api/oauth2/authorize",
24
+ revocation_endpoint: "https://stack.palantir.com/multipass/api/oauth2/revoke_token",
25
+ issuer: "https://stack.palantir.com/multipass"
26
+ });
27
+ });
28
+ it("works with new multipass ctx path", () => {
29
+ const authServer = createAuthorizationServer("multipass", "https://stack.palantir.com");
30
+ expect(authServer).toEqual({
31
+ token_endpoint: "https://stack.palantir.com/multipass/api/oauth2/token",
32
+ authorization_endpoint: "https://stack.palantir.com/multipass/api/oauth2/authorize",
33
+ revocation_endpoint: "https://stack.palantir.com/multipass/api/oauth2/revoke_token",
34
+ issuer: "https://stack.palantir.com/multipass"
35
+ });
36
+ const authServerCustom = createAuthorizationServer("multipass", "https://stack.palantir.com/foo/first/someStuff");
37
+ expect(authServerCustom).toEqual({
38
+ token_endpoint: "https://stack.palantir.com/foo/first/someStuff/multipass/api/oauth2/token",
39
+ authorization_endpoint: "https://stack.palantir.com/foo/first/someStuff/multipass/api/oauth2/authorize",
40
+ revocation_endpoint: "https://stack.palantir.com/foo/first/someStuff/multipass/api/oauth2/revoke_token",
41
+ issuer: "https://stack.palantir.com/foo/first/someStuff/multipass"
42
+ });
43
+ });
44
+ });
45
+ //# sourceMappingURL=AuthorizationServer.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuthorizationServer.test.js","names":["describe","expect","it","createAuthorizationServer","authServer","toEqual","token_endpoint","authorization_endpoint","revocation_endpoint","issuer","authServerCustom"],"sources":["AuthorizationServer.test.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 { describe, expect, it, } from \"vitest\";\nimport { createAuthorizationServer } from \"./common.js\";\ndescribe(\"Create authorization server\", () => {\n it(\"works with old multipass ctx path\", () => {\n const authServer = createAuthorizationServer(\"/multipass\", \"https://stack.palantir.com\");\n expect(authServer).toEqual({\n token_endpoint: \"https://stack.palantir.com/multipass/api/oauth2/token\",\n authorization_endpoint: \"https://stack.palantir.com/multipass/api/oauth2/authorize\",\n revocation_endpoint: \"https://stack.palantir.com/multipass/api/oauth2/revoke_token\",\n issuer: \"https://stack.palantir.com/multipass\",\n });\n });\n it(\"works with new multipass ctx path\", () => {\n const authServer = createAuthorizationServer(\"multipass\", \"https://stack.palantir.com\");\n expect(authServer).toEqual({\n token_endpoint: \"https://stack.palantir.com/multipass/api/oauth2/token\",\n authorization_endpoint: \"https://stack.palantir.com/multipass/api/oauth2/authorize\",\n revocation_endpoint: \"https://stack.palantir.com/multipass/api/oauth2/revoke_token\",\n issuer: \"https://stack.palantir.com/multipass\",\n });\n const authServerCustom = createAuthorizationServer(\"multipass\", \"https://stack.palantir.com/foo/first/someStuff\");\n expect(authServerCustom).toEqual({\n token_endpoint: \"https://stack.palantir.com/foo/first/someStuff/multipass/api/oauth2/token\",\n authorization_endpoint: \"https://stack.palantir.com/foo/first/someStuff/multipass/api/oauth2/authorize\",\n revocation_endpoint: \"https://stack.palantir.com/foo/first/someStuff/multipass/api/oauth2/revoke_token\",\n issuer: \"https://stack.palantir.com/foo/first/someStuff/multipass\",\n });\n });\n});\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAS,QAAQ;AAC9C,SAASC,yBAAyB,QAAQ,aAAa;AACvDH,QAAQ,CAAC,6BAA6B,EAAE,MAAM;EAC1CE,EAAE,CAAC,mCAAmC,EAAE,MAAM;IAC1C,MAAME,UAAU,GAAGD,yBAAyB,CAAC,YAAY,EAAE,4BAA4B,CAAC;IACxFF,MAAM,CAACG,UAAU,CAAC,CAACC,OAAO,CAAC;MACvBC,cAAc,EAAE,uDAAuD;MACvEC,sBAAsB,EAAE,2DAA2D;MACnFC,mBAAmB,EAAE,8DAA8D;MACnFC,MAAM,EAAE;IACZ,CAAC,CAAC;EACN,CAAC,CAAC;EACFP,EAAE,CAAC,mCAAmC,EAAE,MAAM;IAC1C,MAAME,UAAU,GAAGD,yBAAyB,CAAC,WAAW,EAAE,4BAA4B,CAAC;IACvFF,MAAM,CAACG,UAAU,CAAC,CAACC,OAAO,CAAC;MACvBC,cAAc,EAAE,uDAAuD;MACvEC,sBAAsB,EAAE,2DAA2D;MACnFC,mBAAmB,EAAE,8DAA8D;MACnFC,MAAM,EAAE;IACZ,CAAC,CAAC;IACF,MAAMC,gBAAgB,GAAGP,yBAAyB,CAAC,WAAW,EAAE,gDAAgD,CAAC;IACjHF,MAAM,CAACS,gBAAgB,CAAC,CAACL,OAAO,CAAC;MAC7BC,cAAc,EAAE,2EAA2E;MAC3FC,sBAAsB,EAAE,+EAA+E;MACvGC,mBAAmB,EAAE,kFAAkF;MACvGC,MAAM,EAAE;IACZ,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC,CAAC","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=createPublicOauthClient.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createPublicOauthClient.test.d.ts","sourceRoot":"","sources":["../../../src/__tests__/createPublicOauthClient.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,56 @@
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 { createPublicOauthClient } from "@osdk/oauth";
17
+ import * as oauthModule from "@osdk/oauth";
18
+ import { describe, expect, it, vi } from "vitest";
19
+ import * as utilsModule from "../utils.js";
20
+ const originalCreatePublicOauthClient = oauthModule.createPublicOauthClient;
21
+ const FOUNDRY_CLIENT_ID = "example-foundry-client-id";
22
+ const FOUNDRY_URL = "http://example-foundry-url.com";
23
+ const REDIRECT_URI = "http://localhost:8080/auth/callback";
24
+ vi.stubGlobal("window", {
25
+ location: {
26
+ toString: vi.fn().mockReturnValue("http://example.com")
27
+ }
28
+ });
29
+ describe("createPublicOauthClient", () => {
30
+ it("should return the same processed options for both client creation methods", async () => {
31
+ const mockProcessOptionsAndAssignDefaults = vi.fn();
32
+ // Mock processOptionsAndAssignDefaults to call the mock function
33
+ vi.spyOn(utilsModule, "processOptionsAndAssignDefaults").mockImplementation((...args) => {
34
+ mockProcessOptionsAndAssignDefaults(...args);
35
+ return utilsModule.processOptionsAndAssignDefaults(...args);
36
+ });
37
+ // Mock createPublicOauthClient to call both the mock and the original function
38
+ vi.spyOn(oauthModule, "createPublicOauthClient").mockImplementation((...args) => {
39
+ const [_client_id, ...rest] = args;
40
+ mockProcessOptionsAndAssignDefaults(...rest);
41
+ return originalCreatePublicOauthClient(...args);
42
+ });
43
+ const authClient = createPublicOauthClient(FOUNDRY_CLIENT_ID, FOUNDRY_URL, REDIRECT_URI, true, undefined, undefined, undefined, fetch, undefined);
44
+ expect(authClient).toBeDefined();
45
+ expect(mockProcessOptionsAndAssignDefaults).toHaveBeenCalledTimes(1);
46
+ const authClientWithOptions = createPublicOauthClient(FOUNDRY_CLIENT_ID, FOUNDRY_URL, REDIRECT_URI, {
47
+ useHistory: true,
48
+ fetchFn: fetch
49
+ });
50
+ expect(authClientWithOptions).toBeDefined();
51
+ expect(mockProcessOptionsAndAssignDefaults).toHaveBeenCalledTimes(2);
52
+ const [result1, result2] = mockProcessOptionsAndAssignDefaults.mock.results;
53
+ expect(result1.value).toEqual(result2.value);
54
+ });
55
+ });
56
+ //# sourceMappingURL=createPublicOauthClient.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createPublicOauthClient.test.js","names":["createPublicOauthClient","oauthModule","describe","expect","it","vi","utilsModule","originalCreatePublicOauthClient","FOUNDRY_CLIENT_ID","FOUNDRY_URL","REDIRECT_URI","stubGlobal","location","toString","fn","mockReturnValue","mockProcessOptionsAndAssignDefaults","spyOn","mockImplementation","args","processOptionsAndAssignDefaults","_client_id","rest","authClient","undefined","fetch","toBeDefined","toHaveBeenCalledTimes","authClientWithOptions","useHistory","fetchFn","result1","result2","mock","results","value","toEqual"],"sources":["createPublicOauthClient.test.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 { createPublicOauthClient } from \"@osdk/oauth\";\nimport * as oauthModule from \"@osdk/oauth\";\nimport { describe, expect, it, vi } from \"vitest\";\nimport * as utilsModule from \"../utils.js\";\nconst originalCreatePublicOauthClient = oauthModule.createPublicOauthClient;\nconst FOUNDRY_CLIENT_ID = \"example-foundry-client-id\";\nconst FOUNDRY_URL = \"http://example-foundry-url.com\";\nconst REDIRECT_URI = \"http://localhost:8080/auth/callback\";\nvi.stubGlobal(\"window\", {\n location: {\n toString: vi.fn().mockReturnValue(\"http://example.com\"),\n },\n});\ndescribe(\"createPublicOauthClient\", () => {\n it(\"should return the same processed options for both client creation methods\", async () => {\n const mockProcessOptionsAndAssignDefaults = vi.fn();\n // Mock processOptionsAndAssignDefaults to call the mock function\n vi.spyOn(utilsModule, \"processOptionsAndAssignDefaults\").mockImplementation((...args) => {\n mockProcessOptionsAndAssignDefaults(...args);\n return utilsModule.processOptionsAndAssignDefaults(...args);\n });\n // Mock createPublicOauthClient to call both the mock and the original function\n vi.spyOn(oauthModule, \"createPublicOauthClient\").mockImplementation((...args) => {\n const [_client_id, ...rest] = args;\n mockProcessOptionsAndAssignDefaults(...rest);\n return originalCreatePublicOauthClient(...args);\n });\n const authClient = createPublicOauthClient(FOUNDRY_CLIENT_ID, FOUNDRY_URL, REDIRECT_URI, true, undefined, undefined, undefined, fetch, undefined);\n expect(authClient).toBeDefined();\n expect(mockProcessOptionsAndAssignDefaults).toHaveBeenCalledTimes(1);\n const authClientWithOptions = createPublicOauthClient(FOUNDRY_CLIENT_ID, FOUNDRY_URL, REDIRECT_URI, {\n useHistory: true,\n fetchFn: fetch,\n });\n expect(authClientWithOptions).toBeDefined();\n expect(mockProcessOptionsAndAssignDefaults).toHaveBeenCalledTimes(2);\n const [result1, result2] = mockProcessOptionsAndAssignDefaults.mock.results;\n expect(result1.value).toEqual(result2.value);\n });\n});\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,uBAAuB,QAAQ,aAAa;AACrD,OAAO,KAAKC,WAAW,MAAM,aAAa;AAC1C,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,QAAQ;AACjD,OAAO,KAAKC,WAAW,MAAM,aAAa;AAC1C,MAAMC,+BAA+B,GAAGN,WAAW,CAACD,uBAAuB;AAC3E,MAAMQ,iBAAiB,GAAG,2BAA2B;AACrD,MAAMC,WAAW,GAAG,gCAAgC;AACpD,MAAMC,YAAY,GAAG,qCAAqC;AAC1DL,EAAE,CAACM,UAAU,CAAC,QAAQ,EAAE;EACpBC,QAAQ,EAAE;IACNC,QAAQ,EAAER,EAAE,CAACS,EAAE,CAAC,CAAC,CAACC,eAAe,CAAC,oBAAoB;EAC1D;AACJ,CAAC,CAAC;AACFb,QAAQ,CAAC,yBAAyB,EAAE,MAAM;EACtCE,EAAE,CAAC,2EAA2E,EAAE,YAAY;IACxF,MAAMY,mCAAmC,GAAGX,EAAE,CAACS,EAAE,CAAC,CAAC;IACnD;IACAT,EAAE,CAACY,KAAK,CAACX,WAAW,EAAE,iCAAiC,CAAC,CAACY,kBAAkB,CAAC,CAAC,GAAGC,IAAI,KAAK;MACrFH,mCAAmC,CAAC,GAAGG,IAAI,CAAC;MAC5C,OAAOb,WAAW,CAACc,+BAA+B,CAAC,GAAGD,IAAI,CAAC;IAC/D,CAAC,CAAC;IACF;IACAd,EAAE,CAACY,KAAK,CAAChB,WAAW,EAAE,yBAAyB,CAAC,CAACiB,kBAAkB,CAAC,CAAC,GAAGC,IAAI,KAAK;MAC7E,MAAM,CAACE,UAAU,EAAE,GAAGC,IAAI,CAAC,GAAGH,IAAI;MAClCH,mCAAmC,CAAC,GAAGM,IAAI,CAAC;MAC5C,OAAOf,+BAA+B,CAAC,GAAGY,IAAI,CAAC;IACnD,CAAC,CAAC;IACF,MAAMI,UAAU,GAAGvB,uBAAuB,CAACQ,iBAAiB,EAAEC,WAAW,EAAEC,YAAY,EAAE,IAAI,EAAEc,SAAS,EAAEA,SAAS,EAAEA,SAAS,EAAEC,KAAK,EAAED,SAAS,CAAC;IACjJrB,MAAM,CAACoB,UAAU,CAAC,CAACG,WAAW,CAAC,CAAC;IAChCvB,MAAM,CAACa,mCAAmC,CAAC,CAACW,qBAAqB,CAAC,CAAC,CAAC;IACpE,MAAMC,qBAAqB,GAAG5B,uBAAuB,CAACQ,iBAAiB,EAAEC,WAAW,EAAEC,YAAY,EAAE;MAChGmB,UAAU,EAAE,IAAI;MAChBC,OAAO,EAAEL;IACb,CAAC,CAAC;IACFtB,MAAM,CAACyB,qBAAqB,CAAC,CAACF,WAAW,CAAC,CAAC;IAC3CvB,MAAM,CAACa,mCAAmC,CAAC,CAACW,qBAAqB,CAAC,CAAC,CAAC;IACpE,MAAM,CAACI,OAAO,EAAEC,OAAO,CAAC,GAAGhB,mCAAmC,CAACiB,IAAI,CAACC,OAAO;IAC3E/B,MAAM,CAAC4B,OAAO,CAACI,KAAK,CAAC,CAACC,OAAO,CAACJ,OAAO,CAACG,KAAK,CAAC;EAChD,CAAC,CAAC;AACN,CAAC,CAAC","ignoreList":[]}
@@ -1,7 +1,7 @@
1
1
  import type { AuthorizationServer, Client, HttpRequestOptions, OAuth2TokenEndpointResponse } from "oauth4webapi";
2
2
  import type { BaseOauthClient, Events } from "./BaseOauthClient.js";
3
3
  import type { Token } from "./Token.js";
4
- type LocalStorageState = {
4
+ export type LocalStorageState = {
5
5
  refresh_token?: never;
6
6
  codeVerifier?: never;
7
7
  state?: never;
@@ -32,5 +32,4 @@ export declare function common<R extends undefined | (() => Promise<Token | unde
32
32
  makeTokenAndSaveRefresh: (resp: OAuth2TokenEndpointResponse, type: "signIn" | "refresh") => Token;
33
33
  };
34
34
  export declare function createAuthorizationServer(ctxPath: string, url: string): Required<Pick<AuthorizationServer, "issuer" | "token_endpoint" | "authorization_endpoint" | "revocation_endpoint">>;
35
- export {};
36
35
  //# sourceMappingURL=common.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,mBAAmB,EACnB,MAAM,EACN,kBAAkB,EAClB,2BAA2B,EAC5B,MAAM,cAAc,CAAC;AAItB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAEpE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AA0BxC,KAAK,iBAAiB,GAElB;IACA,aAAa,CAAC,EAAE,KAAK,CAAC;IACtB,YAAY,CAAC,EAAE,KAAK,CAAC;IACrB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB,GAEC;IACA,aAAa,CAAC,EAAE,KAAK,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB,GAEC;IACA,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,KAAK,CAAC;IACrB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,MAAM,CAAC,EAAE,KAAK,CAAC;CAChB,GACC;IACA,aAAa,CAAC,EAAE,KAAK,CAAC;IACtB,YAAY,CAAC,EAAE,KAAK,CAAC;IACrB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,MAAM,CAAC,EAAE,KAAK,CAAC;CAChB,CAAC;AAEJ,wBAAgB,SA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AO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACV,QAAQ,CACT,IAAI,CACF,mBAAmB,EACjB,QAAQ,GACR,gBAAgB,GAChB,wBAAwB,GACxB,qBAAqB,CACxB,CACF,CAQA"}
@@ -20,19 +20,18 @@ import { throwIfError } from "./throwIfError.js";
20
20
  // Node 18 is supposed to have a `CustomEvent` but it is not exposed on `globalThis`
21
21
  // which creates a problem for making a single codebase for node and browser. This polyfill works around it
22
22
  const CustomEvent = globalThis.CustomEvent;
23
- const localStorage = globalThis.localStorage;
24
23
  export function saveLocal(client, x) {
25
24
  // MUST `localStorage?` as nodejs does not have localStorage
26
- localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
25
+ globalThis.localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));
27
26
  }
28
27
  export function removeLocal(client) {
29
28
  // MUST `localStorage?` as nodejs does not have localStorage
30
- localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
29
+ globalThis.localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);
31
30
  }
32
31
  export function readLocal(client) {
33
32
  return JSON.parse(
34
33
  // MUST `localStorage?` as nodejs does not have localStorage
35
- localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}");
34
+ globalThis.localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`) ?? "{}");
36
35
  }
37
36
  export function common(client, as, _signIn, oauthHttpOptions, refresh) {
38
37
  let token;
@@ -1 +1 @@
1
- {"version":3,"file":"common.js","names":["processRevocationResponse","revocationRequest","invariant","TypedEventTarget","throwIfError","CustomEvent","globalThis","localStorage","saveLocal","client","x","setItem","client_id","JSON","stringify","removeLocal","removeItem","readLocal","parse","getItem","common","as","_signIn","oauthHttpOptions","refresh","token","eventTarget","makeTokenAndSaveRefresh","resp","type","refresh_token","expires_in","access_token","process","env","NODE_ENV","expires_at","Date","now","dispatchTypedEvent","detail","refreshTimeout","rmTimeout","clearTimeout","restartRefreshTimer","evt","setTimeout","pendingSignIn","signIn","undefined","addEventListener","getTokenOrUndefined","getToken","Object","assign","signOut","result","Event","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;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,yBAAyB,EAAEC,iBAAiB,QAAQ,cAAc;AAC3E,OAAOC,SAAS,MAAM,gBAAgB;AACtC,SAASC,gBAAgB,QAAQ,yBAAyB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAChD;AACA;AACA,MAAMC,WAAW,GACXC,UAAU,CAACD,WAWR;AACT,MAAME,YAAY,GAAGD,UAAU,CAACC,YAAY;AAC5C,OAAO,SAASC,SAASA,CAACC,MAAM,EAAEC,CAAC,EAAE;EACjC;EACAH,YAAY,EAAEI,OAAO,CAAC,2BAA2BF,MAAM,CAACG,SAAS,EAAE,EAAEC,IAAI,CAACC,SAAS,CAACJ,CAAC,CAAC,CAAC;AAC3F;AACA,OAAO,SAASK,WAAWA,CAACN,MAAM,EAAE;EAChC;EACAF,YAAY,EAAES,UAAU,CAAC,2BAA2BP,MAAM,CAACG,SAAS,EAAE,CAAC;AAC3E;AACA,OAAO,SAASK,SAASA,CAACR,MAAM,EAAE;EAC9B,OAAOI,IAAI,CAACK,KAAK;EACjB;EACAX,YAAY,EAAEY,OAAO,CAAC,2BAA2BV,MAAM,CAACG,SAAS,EAAE,CAAC,IAC7D,IAAI,CAAC;AAChB;AACA,OAAO,SAASQ,MAAMA,CAACX,MAAM,EAAEY,EAAE,EAAEC,OAAO,EAAEC,gBAAgB,EAAEC,OAAO,EAAE;EACnE,IAAIC,KAAK;EACT,MAAMC,WAAW,GAAG,IAAIvB,gBAAgB,CAAC,CAAC;EAC1C,SAASwB,uBAAuBA,CAACC,IAAI,EAAEC,IAAI,EAAE;IACzC,MAAM;MAAEC,aAAa;MAAEC,UAAU;MAAEC;IAAa,CAAC,GAAGJ,IAAI;IACxD,EAAUG,UAAU,IAAI,IAAI,IAAAE,OAAA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ACH,OAAO,EAAEC,GAAG,CAAC,EAAE;EACzC,OAAO;IACHG,cAAc,EAAE,GAAGF,MAAM,mBAAmB;IAC5CG,sBAAsB,EAAE,GAAGH,MAAM,uBAAuB;IACxDI,mBAAmB,EAAE,GAAGJ,MAAM,0BAA0B;IACxDA;EACJ,CAAC;AACL","ignoreList":[]}
1
+ {"version":3,"file":"common.js","names":["processRevocationResponse","revocationRequest","invariant","TypedEventTarget","throwIfError","CustomEvent","globalThis","saveLocal","client","x","localStorage","setItem","client_id","JSON","stringify","removeLocal","removeItem","readLocal","parse","getItem","common","as","_signIn","oauthHttpOptions","refresh","token","eventTarget","makeTokenAndSaveRefresh","resp","type","refresh_token","expires_in","access_token","process","env","NODE_ENV","expires_at","Date","now","dispatchTypedEvent","detail","refreshTimeout","rmTimeout","clearTimeout","restartRefreshTimer","evt","setTimeout","pendingSignIn","signIn","undefined","addEventListener","getTokenOrUndefined","getToken","Object","assign","signOut","result","Event","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 };\nexport function saveLocal(client, x) {\n // MUST `localStorage?` as nodejs does not have localStorage\n globalThis.localStorage?.setItem(`@osdk/oauth : refresh : ${client.client_id}`, JSON.stringify(x));\n}\nexport function removeLocal(client) {\n // MUST `localStorage?` as nodejs does not have localStorage\n globalThis.localStorage?.removeItem(`@osdk/oauth : refresh : ${client.client_id}`);\n}\nexport function readLocal(client) {\n return JSON.parse(\n // MUST `localStorage?` as nodejs does not have localStorage\n globalThis.localStorage?.getItem(`@osdk/oauth : refresh : ${client.client_id}`)\n ?? \"{}\");\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;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,yBAAyB,EAAEC,iBAAiB,QAAQ,cAAc;AAC3E,OAAOC,SAAS,MAAM,gBAAgB;AACtC,SAASC,gBAAgB,QAAQ,yBAAyB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAChD;AACA;AACA,MAAMC,WAAW,GACXC,UAAU,CAACD,WAWR;AACT,OAAO,SAASE,SAASA,CAACC,MAAM,EAAEC,CAAC,EAAE;EACjC;EACAH,UAAU,CAACI,YAAY,EAAEC,OAAO,CAAC,2BAA2BH,MAAM,CAACI,SAAS,EAAE,EAAEC,IAAI,CAACC,SAAS,CAACL,CAAC,CAAC,CAAC;AACtG;AACA,OAAO,SAASM,WAAWA,CAACP,MAAM,EAAE;EAChC;EACAF,UAAU,CAACI,YAAY,EAAEM,UAAU,CAAC,2BAA2BR,MAAM,CAACI,SAAS,EAAE,CAAC;AACtF;AACA,OAAO,SAASK,SAASA,CAACT,MAAM,EAAE;EAC9B,OAAO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AY,CAACoD,MAAM,CAAC;MACpB9B,WAAW,CAACa,kBAAkB,CAAC,SAAS,EAAE,IAAIkB,KAAK,CAAC,SAAS,CAAC,CAAC;IACnE,CA8BW;IACPf,SAAS;IACTS,mBAAmB;IACnBD,gBAAgB,EAAExB,WAAW,CAACwB,gBAAgB,CAACQ,IAAI,CAAChC,WAAW,CAAC;IAChEiC,mBAAmB,EAAEjC,WAAW,CAACiC,mBAAmB,CAACD,IAAI,CAAChC,WAAW;EACzE,CAAC,CAAC;EACF,OAAO;IAAE0B,QAAQ;IAAEzB;EAAwB,CAAC;AAChD;AACA,OAAO,SAASiC,yBAAyBA,CAACC,OAAO,EAAEC,GAAG,EAAE;EACpD,MAAMC,MAAM,GAAG,GAAG,IAAIC,GAAG,CAACH,OAAO,EAAEC,GAAG,CAAC,EAAE;EACzC,OAAO;IACHG,cAAc,EAAE,GAAGF,MAAM,mBAAmB;IAC5CG,sBAAsB,EAAE,GAAGH,MAAM,uBAAuB;IACxDI,mBAAmB,EAAE,GAAGJ,MAAM,0BAA0B;IACxDA;EACJ,CAAC;AACL","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"createConfidentialOauthClient.d.ts","sourceRoot":"","sources":["../../src/createConfidentialOauthClient.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAG5E;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC3C,SAAS,EAAE,MAAM,EACjB,aAAa,EAAE,MAAM,EACrB,GAAG,EAAE,MAAM,EACX,MAAM,GAAE,MAAM,EAAwC,EACtD,OAAO,GAAE,OAAO,UAAU,CAAC,KAAwB,EACnD,OAAO,GAAE,MAAqB,GAC7B,uBAAuB,CAgCzB"}
1
+ {"version":3,"file":"createConfidentialOauthClient.d.ts","sourceRoot":"","sources":["../../src/createConfidentialOauthClient.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAG5E;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC3C,SAAS,EAAE,MAAM,EACjB,aAAa,EAAE,MAAM,EACrB,GAAG,EAAE,MAAM,EACX,MAAM,GAAE,MAAM,EAAwC,EACtD,OAAO,GAAE,OAAO,UAAU,CAAC,KAAwB,EACnD,OAAO,GAAE,MAAoB,GAC5B,uBAAuB,CAgCzB"}
@@ -25,7 +25,7 @@ import { throwIfError } from "./throwIfError.js";
25
25
  * @param ctxPath
26
26
  * @returns which can be used as a token provider
27
27
  */
28
- export function createConfidentialOauthClient(client_id, client_secret, url, scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "/multipass") {
28
+ export function createConfidentialOauthClient(client_id, client_secret, url, scopes = ["api:read-data", "api:write-data"], fetchFn = globalThis.fetch, ctxPath = "multipass") {
29
29
  const client = {
30
30
  client_id,
31
31
  client_secret
@@ -1 +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":[]}
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,WAAW,EAAE;EAC1K,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":[]}
@@ -1,15 +1,53 @@
1
1
  import type { PublicOauthClient } from "./PublicOauthClient.js";
2
+ export interface PublicOauthClientOptions {
3
+ /**
4
+ * If true, uses `history.replaceState()`, otherwise uses `window.location.assign()` (defaults to true)
5
+ */
6
+ useHistory?: boolean;
7
+ /**
8
+ * Custom landing page URL prior to logging in
9
+ */
10
+ loginPage?: string;
11
+ /**
12
+ * URL to return to after completed authentication cycle (defaults to `window.location.toString()`)
13
+ */
14
+ postLoginPage?: string;
15
+ /**
16
+ * * @param {string[]} [scopes=[]] - OAuth scopes to request. If not provided, defaults to `["api:read-data", "api:write-data"]`
17
+ */
18
+ scopes?: string[];
19
+ /**
20
+ * Custom fetch function to use for requests (defaults to `globalThis.fetch`)
21
+ */
22
+ fetchFn?: typeof globalThis.fetch;
23
+ /**
24
+ * Context path for the authorization server (defaults to "multipass")
25
+ */
26
+ ctxPath?: string;
27
+ }
2
28
  /**
3
- * @param client_id
4
- * @param url the base url of your foundry server
5
- * @param redirectUrl the url configured for redirect in the oauth configuration on the server
6
- * @param useHistory if true, when possible uses `history.replaceState()`, otherwise uses `window.location.assign()`
7
- * @param loginPage if you want a custom landing page prior to logging in, set this to that url
8
- * @param postLoginPage if you want to customize where you return to after a completed authentication cycle. defaults to the url when the page loaded
9
- * @param scopes
10
- * @param fetchFn
11
- * @param ctxPath
12
- * @returns {PublicOauthClient} which can be used as a token provider
29
+ * Creates a PublicOauthClient for authentication.
30
+ *
31
+ * @param {string} clientId - The client_id from the OAuth configuration on the server
32
+ * @param {string} url - The base URL of your Foundry server
33
+ * @param {string} redirectUrl - The URL configured for redirect in the OAuth configuration on the server
34
+ * @param {PublicOauthClientOptions} options - Additional options for the client
35
+ * @returns {PublicOauthClient} A client that can be used as a token provider
36
+ */
37
+ export declare function createPublicOauthClient(clientId: string, url: string, redirectUrl: string, options?: PublicOauthClientOptions): PublicOauthClient;
38
+ /**
39
+ * Creates a PublicOauthClient for authentication.
40
+ *
41
+ * @param {string} clientId - The client_id from the OAuth configuration on the server
42
+ * @param {string} url - The base URL of your Foundry server
43
+ * @param {string} redirectUrl - The URL configured for redirect in the OAuth configuration on the server
44
+ * @param {boolean} useHistory - If true, uses `history.replaceState()`, otherwise uses `window.location.assign()` (defaults to true)
45
+ * @param {string} loginPage - Custom landing page URL prior to logging in
46
+ * @param {string} postLoginPage - URL to return to after completed authentication cycle (defaults to `window.location.toString()`)
47
+ * @param {string[]} scopes - OAuth scopes to request. If not provided, defaults to `["api:read-data", "api:write-data"]`
48
+ * @param {typeof globalThis.fetch} fetchFn - Custom fetch function to use for requests (defaults to `globalThis.fetch`)
49
+ * @param {string} ctxPath - Context path for the authorization server (defaults to "multipass")
50
+ * @returns {PublicOauthClient} A client that can be used as a token provider
13
51
  */
14
52
  export declare function createPublicOauthClient(client_id: string, url: string, redirectUrl: string, useHistory?: boolean, loginPage?: string, postLoginPage?: string, scopes?: string[], fetchFn?: typeof globalThis.fetch, ctxPath?: string): PublicOauthClient;
15
53
  //# sourceMappingURL=createPublicOauthClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createPublicOauthClient.d.ts","sourceRoot":"","sources":["../../src/createPublicOauthClient.ts"],"names":[],"mappings":"AAmCA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAUhE;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,MAAM,EACnB,UAAU,GAAE,OAAc,EAC1B,SAAS,CAAC,EAAE,MAAM,EAClB,aAAa,GAAE,MAAmC,EAClD,MAAM,GAAE,MAAM,EAAO,EACrB,OAAO,GAAE,OAAO,UAAU,CAAC,KAAwB,EACnD,OAAO,GAAE,MAAqB,GAC7B,iBAAiB,CAiKnB"}
1
+ {"version":3,"file":"createPublicOauthClient.d.ts","sourceRoot":"","sources":["../../src/createPublicOauthClient.ts"],"names":[],"mappings":"AAmCA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAYhE,MAAM,WAAW,wBAAwB;IACvC;;OAEG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAElB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAElC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,wBAAwB,GACjC,iBAAiB,CAAC;AAErB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,MAAM,EACnB,UAAU,CAAC,EAAE,OAAO,EACpB,SAAS,CAAC,EAAE,MAAM,EAClB,aAAa,CAAC,EAAE,MAAM,EACtB,MAAM,CAAC,EAAE,MAAM,EAAE,EACjB,OAAO,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,EACjC,OAAO,CAAC,EAAE,MAAM,GACf,iBAAiB,CAAC"}
@@ -17,19 +17,16 @@ import delay from "delay";
17
17
  import { authorizationCodeGrantRequest, calculatePKCECodeChallenge, customFetch, generateRandomCodeVerifier, generateRandomState, processAuthorizationCodeOAuth2Response, refreshTokenGrantRequest, validateAuthResponse } from "oauth4webapi";
18
18
  import { common, createAuthorizationServer, readLocal, removeLocal, saveLocal } from "./common.js";
19
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") {
20
+ import { processOptionsAndAssignDefaults } from "./utils.js";
21
+ export function createPublicOauthClient(client_id, url, redirect_uri, useHistory, loginPage, postLoginPage, scopes, fetchFn, ctxPath) {
22
+ ({
23
+ useHistory,
24
+ loginPage,
25
+ postLoginPage,
26
+ scopes,
27
+ fetchFn,
28
+ ctxPath
29
+ } = processOptionsAndAssignDefaults(url, redirect_uri, useHistory, loginPage, postLoginPage, scopes, fetchFn, ctxPath));
33
30
  const client = {
34
31
  client_id,
35
32
  token_endpoint_auth_method: "none"
@@ -38,9 +35,6 @@ export function createPublicOauthClient(client_id, url, redirectUrl, useHistory
38
35
  const oauthHttpOptions = {
39
36
  [customFetch]: fetchFn
40
37
  };
41
- if (scopes.length === 0) {
42
- scopes = ["api:read-data", "api:write-data"];
43
- }
44
38
  const {
45
39
  makeTokenAndSaveRefresh,
46
40
  getToken
@@ -53,11 +47,12 @@ export function createPublicOauthClient(client_id, url, redirectUrl, useHistory
53
47
  // 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
48
  ?? (await initiateLoginRedirect());
55
49
  }, oauthHttpOptions, maybeRefresh.bind(globalThis, true));
56
- async function go(x) {
50
+ // as an arrow function, `useHistory` is known to be a boolean
51
+ const go = async x => {
57
52
  if (useHistory) return window.history.replaceState({}, "", x);else window.location.assign(x);
58
53
  await delay(1000);
59
54
  throw new Error("Unable to redirect");
60
- }
55
+ };
61
56
  async function maybeRefresh(expectRefreshToken) {
62
57
  const {
63
58
  refresh_token
@@ -70,7 +65,7 @@ export function createPublicOauthClient(client_id, url, redirectUrl, useHistory
70
65
  // note, we don't use processRefreshTokenResponse because the mp oauth implementation
71
66
  // doesn't do refresh tokens quite right and this lets us skip the id check
72
67
  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) {
68
+ if (result && window.location.pathname === new URL(redirect_uri).pathname) {
74
69
  const {
75
70
  oldUrl
76
71
  } = readLocal(client);
@@ -96,7 +91,7 @@ export function createPublicOauthClient(client_id, url, redirectUrl, useHistory
96
91
  } = readLocal(client);
97
92
  if (!codeVerifier) return;
98
93
  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");
94
+ const ret = makeTokenAndSaveRefresh(throwIfError(await processAuthorizationCodeOAuth2Response(authServer, client, await authorizationCodeGrantRequest(authServer, client, throwIfError(validateAuthResponse(authServer, client, new URL(window.location.href), state)), redirect_uri, codeVerifier, oauthHttpOptions))), "signIn");
100
95
  go(oldUrl);
101
96
  return ret;
102
97
  } catch (e) {
@@ -107,7 +102,8 @@ export function createPublicOauthClient(client_id, url, redirectUrl, useHistory
107
102
  removeLocal(client);
108
103
  }
109
104
  }
110
- async function initiateLoginRedirect() {
105
+ // As an arrow function, `scopes` and `postLoginPage` are known at compile time
106
+ const initiateLoginRedirect = async () => {
111
107
  if (loginPage && window.location.href !== loginPage && window.location.pathname !== loginPage) {
112
108
  saveLocal(client, {
113
109
  oldUrl: postLoginPage
@@ -126,7 +122,7 @@ export function createPublicOauthClient(client_id, url, redirectUrl, useHistory
126
122
  client_id,
127
123
  response_type: "code",
128
124
  state,
129
- redirect_uri: redirectUrl,
125
+ redirect_uri,
130
126
  code_challenge: await calculatePKCECodeChallenge(codeVerifier),
131
127
  code_challenge_method: "S256",
132
128
  scope: ["offline_access", ...scopes].join(" ")
@@ -134,7 +130,7 @@ export function createPublicOauthClient(client_id, url, redirectUrl, useHistory
134
130
  // Give time for redirect to happen
135
131
  await delay(1000);
136
132
  throw new Error("Unable to redirect");
137
- }
133
+ };
138
134
  return getToken;
139
135
  }
140
136
  //# sourceMappingURL=createPublicOauthClient.js.map
@@ -1 +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,mBAAmB,EAAEC,sCAAsC,EAAEC,wBAAwB,EAAEC,oBAAoB,QAAS,cAAc;AAC/O,SAASC,MAAM,EAAEC,yBAAyB,EAAEC,SAAS,EAAEC,WAAW,EAAEC,SAAS,QAAS,aAAa;AACnG,SAASC,YAAY,QAAQ,mBAAmB;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,uBAAuBA,CAACC,SAAS,EAAEC,GAAG,EAAEC,WAAW,EAAEC,UAAU,GAAG,IAAI,EAAEC,SAAS,EAAEC,aAAa,GAAGC,MAAM,CAACC,QAAQ,CAACC,QAAQ,CAAC,CAAC,EAAEC,MAAM,GAAG,EAAE,EAAEC,OAAO,GAAGC,UAAU,CAACC,KAAK,EAAEC,OAAO,GAAG,YAAY,EAAE;EAC5M,MAAMC,MAAM,GAAG;IAAEd,SAAS;IAAEe,0BAA0B,EAAE;EAAO,CAAC;EAChE,MAAMC,UAAU,GAAGtB,yBAAyB,CAACmB,OAAO,EAAEZ,GAAG,CAAC;EAC1D,MAAMgB,gBAAgB,GAAG;IAAE,CAAC9B,WAAW,GAAGuB;EAAQ,CAAC;EACnD,IAAID,MAAM,CAACS,MAAM,KAAK,CAAC,EAAE;IACr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odeChallenge","customFetch","generateRandomCodeVerifier","generateRandomState","processAuthorizationCodeOAuth2Response","refreshTokenGrantRequest","validateAuthResponse","common","createAuthorizationServer","readLocal","removeLocal","saveLocal","throwIfError","processOptionsAndAssignDefaults","createPublicOauthClient","client_id","url","redirect_uri","useHistory","loginPage","postLoginPage","scopes","fetchFn","ctxPath","client","token_endpoint_auth_method","authServer","oauthHttpOptions","makeTokenAndSaveRefresh","getToken","_signIn","maybeRefresh","maybeHandleAuthReturn","initiateLoginRedirect","bind","globalThis","go","x","window","history","replaceState","location","assign","Error","expectRefreshToken","refresh_token","result","pathname","URL","oldUrl","e","process","env","NODE_ENV","console","warn","codeVerifier","state","ret","href","toString","authorization_endpoint","URLSearchParams","response_type","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\";\nimport { processOptionsAndAssignDefaults } from \"./utils.js\";\nexport function createPublicOauthClient(client_id, url, redirect_uri, useHistory, loginPage, postLoginPage, scopes, fetchFn, ctxPath) {\n ({\n useHistory,\n loginPage,\n postLoginPage,\n scopes,\n fetchFn,\n ctxPath,\n } = processOptionsAndAssignDefaults(url, redirect_uri, useHistory, loginPage, postLoginPage, scopes, fetchFn, ctxPath));\n const client = { client_id, token_endpoint_auth_method: \"none\" };\n const authServer = createAuthorizationServer(ctxPath, url);\n const oauthHttpOptions = { [customFetch]: fetchFn };\n const { makeTokenAndSaveRefresh, getToken } = common(client, authServer, _signIn, oauthHttpOptions, maybeRefresh.bind(globalThis, true));\n // as an arrow function, `useHistory` is known to be a boolean\n const go = async (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(redirect_uri).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)), redirect_uri, 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 // As an arrow function, `scopes` and `postLoginPage` are known at compile time\n const initiateLoginRedirect = async () => {\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,\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,mBAAmB,EAAEC,sCAAsC,EAAEC,wBAAwB,EAAEC,oBAAoB,QAAS,cAAc;AAC/O,SAASC,MAAM,EAAEC,yBAAyB,EAAEC,SAAS,EAAEC,WAAW,EAAEC,SAAS,QAAS,aAAa;AACnG,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SAASC,+BAA+B,QAAQ,YAAY;AAC5D,OAAO,SAASC,uBAAuBA,CAACC,SAAS,EAAEC,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CAAC;MAC/C/C,SAAS;MACTgD,aAAa,EAAE,MAAM;MACrBN,KAAK;MACLxC,YAAY;MACZ+C,cAAc,EAAE,MAAMhE,0BAA0B,CAACwD,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,MAAMrE,KAAK,CAAC,IAAI,CAAC;IACjB,MAAM,IAAI6C,KAAK,CAAC,oBAAoB,CAAC;EACzC,CAAC;EAUD,OAAOd,QAAQ;AACnB","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=publicOauth.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publicOauth.test.d.ts","sourceRoot":"","sources":["../../src/publicOauth.test.ts"],"names":[],"mappings":""}