@civic/auth 0.0.1-beta.18 → 0.0.1-beta.19

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 (68) hide show
  1. package/dist/AuthProvider-Bj_Prt1x.d.ts +21 -0
  2. package/dist/AuthProvider-DUAoX4G9.d.mts +21 -0
  3. package/dist/{index-DTimUlkB.d.ts → UserProvider-CMLaYOUD.d.ts} +1 -2
  4. package/dist/{index-DvjkKpkk.d.mts → UserProvider-Cbm8MZkJ.d.mts} +1 -2
  5. package/dist/chunk-5UQQYXCX.js +1 -0
  6. package/dist/chunk-5UQQYXCX.js.map +1 -0
  7. package/dist/chunk-BFESCRFK.mjs +118 -0
  8. package/dist/chunk-BFESCRFK.mjs.map +1 -0
  9. package/dist/{chunk-G3P5TIO2.mjs → chunk-CBQ3HKRV.mjs} +123 -232
  10. package/dist/chunk-CBQ3HKRV.mjs.map +1 -0
  11. package/dist/chunk-CRTRMMJ7.js.map +1 -1
  12. package/dist/{chunk-SEKF2WZX.js → chunk-CZ3AVCKD.js} +16 -71
  13. package/dist/chunk-CZ3AVCKD.js.map +1 -0
  14. package/dist/chunk-DJFTZS4P.js +118 -0
  15. package/dist/chunk-DJFTZS4P.js.map +1 -0
  16. package/dist/chunk-HTTTZ2BP.mjs +223 -0
  17. package/dist/chunk-HTTTZ2BP.mjs.map +1 -0
  18. package/dist/{chunk-RF23Q4V6.js → chunk-O2SODTR3.js} +114 -223
  19. package/dist/chunk-O2SODTR3.js.map +1 -0
  20. package/dist/chunk-O6DPCPRH.js +223 -0
  21. package/dist/chunk-O6DPCPRH.js.map +1 -0
  22. package/dist/chunk-PMJAV4JJ.mjs +1 -0
  23. package/dist/chunk-PMJAV4JJ.mjs.map +1 -0
  24. package/dist/chunk-UADVRCHY.mjs +710 -0
  25. package/dist/chunk-UADVRCHY.mjs.map +1 -0
  26. package/dist/chunk-VJVRFKDH.js +710 -0
  27. package/dist/chunk-VJVRFKDH.js.map +1 -0
  28. package/dist/{chunk-5XL2ST72.mjs → chunk-X3FQBE22.mjs} +15 -70
  29. package/dist/chunk-X3FQBE22.mjs.map +1 -0
  30. package/dist/index.d.mts +2 -2
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +2 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/index.mjs +1 -0
  35. package/dist/nextjs/client.css +335 -0
  36. package/dist/nextjs/client.css.map +1 -0
  37. package/dist/nextjs/client.d.mts +12 -0
  38. package/dist/nextjs/client.d.ts +12 -0
  39. package/dist/nextjs/client.js +179 -0
  40. package/dist/nextjs/client.js.map +1 -0
  41. package/dist/nextjs/client.mjs +179 -0
  42. package/dist/nextjs/client.mjs.map +1 -0
  43. package/dist/nextjs.d.mts +35 -7
  44. package/dist/nextjs.d.ts +35 -7
  45. package/dist/nextjs.js +129 -42
  46. package/dist/nextjs.js.map +1 -1
  47. package/dist/nextjs.mjs +116 -29
  48. package/dist/nextjs.mjs.map +1 -1
  49. package/dist/react.d.mts +7 -31
  50. package/dist/react.d.ts +7 -31
  51. package/dist/react.js +15 -835
  52. package/dist/react.js.map +1 -1
  53. package/dist/react.mjs +47 -867
  54. package/dist/react.mjs.map +1 -1
  55. package/dist/server.d.mts +3 -24
  56. package/dist/server.d.ts +3 -24
  57. package/dist/server.js +4 -2
  58. package/dist/server.js.map +1 -1
  59. package/dist/server.mjs +4 -2
  60. package/dist/storage-B2eAQNdv.d.ts +25 -0
  61. package/dist/storage-BJPUpxhm.d.mts +25 -0
  62. package/dist/{types-b4c1koXj.d.mts → types-Bqm9OCZN.d.mts} +5 -2
  63. package/dist/{types-b4c1koXj.d.ts → types-Bqm9OCZN.d.ts} +5 -2
  64. package/package.json +24 -15
  65. package/dist/chunk-5XL2ST72.mjs.map +0 -1
  66. package/dist/chunk-G3P5TIO2.mjs.map +0 -1
  67. package/dist/chunk-RF23Q4V6.js.map +0 -1
  68. package/dist/chunk-SEKF2WZX.js.map +0 -1
@@ -0,0 +1,21 @@
1
+ import { ReactNode } from 'react';
2
+ import { C as Config, S as SessionData } from './types-HdCjGldB.js';
3
+
4
+ interface PKCEConsumer {
5
+ getCodeChallenge(): Promise<string>;
6
+ }
7
+
8
+ type AuthProviderProps = {
9
+ children: ReactNode;
10
+ clientId: string;
11
+ redirectUrl?: string;
12
+ nonce?: string;
13
+ config?: Config;
14
+ onSignIn?: (error?: Error) => void;
15
+ onSignOut?: () => Promise<void>;
16
+ pkceConsumer?: PKCEConsumer;
17
+ modalIframe?: boolean;
18
+ sessionData?: SessionData;
19
+ };
20
+
21
+ export type { AuthProviderProps as A };
@@ -0,0 +1,21 @@
1
+ import { ReactNode } from 'react';
2
+ import { C as Config, S as SessionData } from './types-HdCjGldB.mjs';
3
+
4
+ interface PKCEConsumer {
5
+ getCodeChallenge(): Promise<string>;
6
+ }
7
+
8
+ type AuthProviderProps = {
9
+ children: ReactNode;
10
+ clientId: string;
11
+ redirectUrl?: string;
12
+ nonce?: string;
13
+ config?: Config;
14
+ onSignIn?: (error?: Error) => void;
15
+ onSignOut?: () => Promise<void>;
16
+ pkceConsumer?: PKCEConsumer;
17
+ modalIframe?: boolean;
18
+ sessionData?: SessionData;
19
+ };
20
+
21
+ export type { AuthProviderProps as A };
@@ -1,6 +1,5 @@
1
- import { D as DisplayMode, U as User } from './types-HdCjGldB.js';
2
- import './types-b4c1koXj.js';
3
1
  import { JWT } from 'oslo/jwt';
2
+ import { D as DisplayMode, U as User } from './types-HdCjGldB.js';
4
3
 
5
4
  type AuthContextType = {
6
5
  signIn: (displayMode?: DisplayMode) => Promise<void>;
@@ -1,6 +1,5 @@
1
- import { D as DisplayMode, U as User } from './types-HdCjGldB.mjs';
2
- import './types-b4c1koXj.mjs';
3
1
  import { JWT } from 'oslo/jwt';
2
+ import { D as DisplayMode, U as User } from './types-HdCjGldB.mjs';
4
3
 
5
4
  type AuthContextType = {
6
5
  signIn: (displayMode?: DisplayMode) => Promise<void>;
@@ -0,0 +1 @@
1
+ "use strict";//# sourceMappingURL=chunk-5UQQYXCX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevincolgan/code/civic-auth/packages/civic-auth-client/dist/chunk-5UQQYXCX.js"],"names":[],"mappings":"AAAA","file":"/Users/kevincolgan/code/civic-auth/packages/civic-auth-client/dist/chunk-5UQQYXCX.js"}
@@ -0,0 +1,118 @@
1
+ import {
2
+ CookieStorage
3
+ } from "./chunk-HTTTZ2BP.mjs";
4
+ import {
5
+ GenericUserSession,
6
+ clearTokens
7
+ } from "./chunk-CBQ3HKRV.mjs";
8
+ import {
9
+ __async,
10
+ __spreadProps,
11
+ __spreadValues
12
+ } from "./chunk-RGHW4PYM.mjs";
13
+
14
+ // src/nextjs/cookies.ts
15
+ import { cookies } from "next/headers.js";
16
+ var createTokenCookies = (response, sessionData, config) => {
17
+ var _a, _b;
18
+ const maxAge = (_a = sessionData.expiresIn) != null ? _a : 3600;
19
+ const cookieOptions = __spreadProps(__spreadValues({}, (_b = config.cookies) == null ? void 0 : _b.tokens), {
20
+ maxAge
21
+ });
22
+ if (sessionData.accessToken) {
23
+ response.cookies.set("access_token", sessionData.accessToken, __spreadProps(__spreadValues({}, cookieOptions), {
24
+ httpOnly: true
25
+ }));
26
+ }
27
+ if (sessionData.idToken) {
28
+ response.cookies.set("id_token", sessionData.idToken, __spreadProps(__spreadValues({}, cookieOptions), {
29
+ httpOnly: true
30
+ }));
31
+ }
32
+ if (sessionData.refreshToken) {
33
+ response.cookies.set("refresh_token", sessionData.refreshToken, __spreadProps(__spreadValues({}, cookieOptions), {
34
+ httpOnly: true
35
+ }));
36
+ }
37
+ };
38
+ var createUserInfoCookie = (response, user, sessionData, config) => {
39
+ var _a, _b, _c;
40
+ if (!user) {
41
+ response.cookies.set("user", "", __spreadProps(__spreadValues({}, (_a = config.cookies) == null ? void 0 : _a.user), {
42
+ maxAge: 0
43
+ }));
44
+ return;
45
+ }
46
+ const maxAge = (_b = sessionData.expiresIn) != null ? _b : 3600;
47
+ const frontendUser = __spreadValues({}, user);
48
+ response.cookies.set("user", JSON.stringify(frontendUser), __spreadProps(__spreadValues({}, (_c = config.cookies) == null ? void 0 : _c.user), {
49
+ maxAge
50
+ }));
51
+ };
52
+ var clearAuthCookies = (config) => __async(void 0, null, function* () {
53
+ var _a;
54
+ const cookieStorage = new NextjsCookieStorage((_a = config.cookies) == null ? void 0 : _a.tokens);
55
+ clearTokens(cookieStorage);
56
+ const clientStorage = new NextjsClientStorage();
57
+ const userSession = new GenericUserSession(clientStorage);
58
+ userSession.set(null);
59
+ });
60
+ var NextjsCookieStorage = class extends CookieStorage {
61
+ constructor(config = {}) {
62
+ super({
63
+ secure: true,
64
+ httpOnly: true
65
+ });
66
+ this.config = config;
67
+ }
68
+ get(key) {
69
+ var _a;
70
+ return ((_a = cookies().get(key)) == null ? void 0 : _a.value) || null;
71
+ }
72
+ set(key, value) {
73
+ var _a;
74
+ const cookieSettings = ((_a = this.config) == null ? void 0 : _a[key]) || __spreadValues({}, this.settings);
75
+ console.log(
76
+ "NextjsCookieStorage.set",
77
+ JSON.stringify(
78
+ { key, value, config: this.config, cookieSettings },
79
+ null,
80
+ 2
81
+ )
82
+ );
83
+ cookies().set(key, value, cookieSettings);
84
+ }
85
+ };
86
+ var NextjsClientStorage = class extends CookieStorage {
87
+ constructor(config = {}) {
88
+ super(__spreadProps(__spreadValues({}, config), {
89
+ secure: false,
90
+ httpOnly: false
91
+ }));
92
+ }
93
+ get(key) {
94
+ var _a;
95
+ return ((_a = cookies().get(key)) == null ? void 0 : _a.value) || null;
96
+ }
97
+ set(key, value) {
98
+ cookies().set(key, value, this.settings);
99
+ }
100
+ };
101
+
102
+ // src/nextjs/utils.ts
103
+ var resolveCallbackUrl = (config, alternativeUrl) => {
104
+ var _a;
105
+ const baseUrl = (_a = config.appUrl) != null ? _a : alternativeUrl;
106
+ const callbackUrl = new URL(config == null ? void 0 : config.callbackUrl, baseUrl).toString();
107
+ return callbackUrl.toString();
108
+ };
109
+
110
+ export {
111
+ createTokenCookies,
112
+ createUserInfoCookie,
113
+ clearAuthCookies,
114
+ NextjsCookieStorage,
115
+ NextjsClientStorage,
116
+ resolveCallbackUrl
117
+ };
118
+ //# sourceMappingURL=chunk-BFESCRFK.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/nextjs/cookies.ts","../src/nextjs/utils.ts"],"sourcesContent":["import { SessionData, UnknownObject, User } from \"@/types\";\nimport { NextResponse } from \"next/server\";\nimport { AuthConfig, CookiesConfigObject } from \"@/nextjs/config\";\nimport { CookieStorage, CookieStorageSettings } from \"@/server\";\nimport { cookies } from \"next/headers.js\";\nimport { GenericUserSession } from \"@/shared/UserSession\";\nimport { clearTokens } from \"@/shared/util\";\nimport { CodeVerifier, OAuthTokens, TokensCookieConfig } from \"@/shared/types\";\n\n/**\n * Creates HTTP-only cookies for authentication tokens\n */\nconst createTokenCookies = (\n response: NextResponse,\n sessionData: SessionData,\n config: AuthConfig,\n) => {\n const maxAge = sessionData.expiresIn ?? 3600;\n const cookieOptions = {\n ...config.cookies?.tokens,\n maxAge,\n };\n\n if (sessionData.accessToken) {\n response.cookies.set(\"access_token\", sessionData.accessToken, {\n ...cookieOptions,\n httpOnly: true,\n });\n }\n\n if (sessionData.idToken) {\n response.cookies.set(\"id_token\", sessionData.idToken, {\n ...cookieOptions,\n httpOnly: true,\n });\n }\n\n if (sessionData.refreshToken) {\n response.cookies.set(\"refresh_token\", sessionData.refreshToken, {\n ...cookieOptions,\n httpOnly: true,\n });\n }\n};\n\n/**\n * Creates a client-readable cookie with user info\n */\nconst createUserInfoCookie = (\n response: NextResponse,\n user: User<UnknownObject> | null,\n sessionData: SessionData,\n config: AuthConfig,\n) => {\n if (!user) {\n response.cookies.set(\"user\", \"\", {\n ...config.cookies?.user,\n maxAge: 0,\n });\n return;\n }\n const maxAge = sessionData.expiresIn ?? 3600;\n\n // TODO select fields to include in the user cookie\n const frontendUser = {\n ...user,\n };\n\n // TODO make call to get user info from the\n // auth server /userinfo endpoint when it's available\n // then add to the default claims above\n\n response.cookies.set(\"user\", JSON.stringify(frontendUser), {\n ...config.cookies?.user,\n maxAge,\n });\n};\n\n/**\n * Clears all authentication cookies\n */\nconst clearAuthCookies = async (config: AuthConfig) => {\n // clear session, and tokens\n const cookieStorage = new NextjsCookieStorage(config.cookies?.tokens);\n clearTokens(cookieStorage);\n\n // clear user\n const clientStorage = new NextjsClientStorage();\n const userSession = new GenericUserSession(clientStorage);\n userSession.set(null);\n};\n\ntype KeySetter = OAuthTokens | CodeVerifier;\nclass NextjsCookieStorage extends CookieStorage {\n constructor(readonly config: Partial<TokensCookieConfig> = {}) {\n super({\n secure: true,\n httpOnly: true,\n });\n }\n\n get(key: string): string | null {\n return cookies().get(key)?.value || null;\n }\n\n set(key: KeySetter, value: string): void {\n const cookieSettings = this.config?.[key as KeySetter] || {\n ...this.settings,\n };\n console.log(\n \"NextjsCookieStorage.set\",\n JSON.stringify(\n { key, value, config: this.config, cookieSettings },\n null,\n 2,\n ),\n );\n cookies().set(key, value, cookieSettings);\n }\n}\n\nclass NextjsClientStorage extends CookieStorage {\n constructor(config: Partial<CookieStorageSettings> = {}) {\n super({\n ...config,\n secure: false,\n httpOnly: false,\n });\n }\n\n get(key: string): string | null {\n return cookies().get(key)?.value || null;\n }\n\n set(key: string, value: string): void {\n cookies().set(key, value, this.settings);\n }\n}\n\nexport {\n createTokenCookies,\n createUserInfoCookie,\n clearAuthCookies,\n NextjsCookieStorage,\n NextjsClientStorage,\n};\n","import { AuthConfigWithDefaults } from \"@/nextjs/config\";\n\nexport const resolveCallbackUrl = (\n config: AuthConfigWithDefaults,\n alternativeUrl?: string,\n): string => {\n const baseUrl = config.appUrl ?? alternativeUrl;\n const callbackUrl = new URL(config?.callbackUrl, baseUrl).toString();\n return callbackUrl.toString();\n};\n"],"mappings":";;;;;;;;;;;;;;AAIA,SAAS,eAAe;AAQxB,IAAM,qBAAqB,CACzB,UACA,aACA,WACG;AAhBL;AAiBE,QAAM,UAAS,iBAAY,cAAZ,YAAyB;AACxC,QAAM,gBAAgB,kCACjB,YAAO,YAAP,mBAAgB,SADC;AAAA,IAEpB;AAAA,EACF;AAEA,MAAI,YAAY,aAAa;AAC3B,aAAS,QAAQ,IAAI,gBAAgB,YAAY,aAAa,iCACzD,gBADyD;AAAA,MAE5D,UAAU;AAAA,IACZ,EAAC;AAAA,EACH;AAEA,MAAI,YAAY,SAAS;AACvB,aAAS,QAAQ,IAAI,YAAY,YAAY,SAAS,iCACjD,gBADiD;AAAA,MAEpD,UAAU;AAAA,IACZ,EAAC;AAAA,EACH;AAEA,MAAI,YAAY,cAAc;AAC5B,aAAS,QAAQ,IAAI,iBAAiB,YAAY,cAAc,iCAC3D,gBAD2D;AAAA,MAE9D,UAAU;AAAA,IACZ,EAAC;AAAA,EACH;AACF;AAKA,IAAM,uBAAuB,CAC3B,UACA,MACA,aACA,WACG;AArDL;AAsDE,MAAI,CAAC,MAAM;AACT,aAAS,QAAQ,IAAI,QAAQ,IAAI,kCAC5B,YAAO,YAAP,mBAAgB,OADY;AAAA,MAE/B,QAAQ;AAAA,IACV,EAAC;AACD;AAAA,EACF;AACA,QAAM,UAAS,iBAAY,cAAZ,YAAyB;AAGxC,QAAM,eAAe,mBAChB;AAOL,WAAS,QAAQ,IAAI,QAAQ,KAAK,UAAU,YAAY,GAAG,kCACtD,YAAO,YAAP,mBAAgB,OADsC;AAAA,IAEzD;AAAA,EACF,EAAC;AACH;AAKA,IAAM,mBAAmB,CAAO,WAAuB;AAjFvD;AAmFE,QAAM,gBAAgB,IAAI,qBAAoB,YAAO,YAAP,mBAAgB,MAAM;AACpE,cAAY,aAAa;AAGzB,QAAM,gBAAgB,IAAI,oBAAoB;AAC9C,QAAM,cAAc,IAAI,mBAAmB,aAAa;AACxD,cAAY,IAAI,IAAI;AACtB;AAGA,IAAM,sBAAN,cAAkC,cAAc;AAAA,EAC9C,YAAqB,SAAsC,CAAC,GAAG;AAC7D,UAAM;AAAA,MACJ,QAAQ;AAAA,MACR,UAAU;AAAA,IACZ,CAAC;AAJkB;AAAA,EAKrB;AAAA,EAEA,IAAI,KAA4B;AArGlC;AAsGI,aAAO,aAAQ,EAAE,IAAI,GAAG,MAAjB,mBAAoB,UAAS;AAAA,EACtC;AAAA,EAEA,IAAI,KAAgB,OAAqB;AAzG3C;AA0GI,UAAM,mBAAiB,UAAK,WAAL,mBAAc,SAAqB,mBACrD,KAAK;AAEV,YAAQ;AAAA,MACN;AAAA,MACA,KAAK;AAAA,QACH,EAAE,KAAK,OAAO,QAAQ,KAAK,QAAQ,eAAe;AAAA,QAClD;AAAA,QACA;AAAA,MACF;AAAA,IACF;AACA,YAAQ,EAAE,IAAI,KAAK,OAAO,cAAc;AAAA,EAC1C;AACF;AAEA,IAAM,sBAAN,cAAkC,cAAc;AAAA,EAC9C,YAAY,SAAyC,CAAC,GAAG;AACvD,UAAM,iCACD,SADC;AAAA,MAEJ,QAAQ;AAAA,MACR,UAAU;AAAA,IACZ,EAAC;AAAA,EACH;AAAA,EAEA,IAAI,KAA4B;AAlIlC;AAmII,aAAO,aAAQ,EAAE,IAAI,GAAG,MAAjB,mBAAoB,UAAS;AAAA,EACtC;AAAA,EAEA,IAAI,KAAa,OAAqB;AACpC,YAAQ,EAAE,IAAI,KAAK,OAAO,KAAK,QAAQ;AAAA,EACzC;AACF;;;ACvIO,IAAM,qBAAqB,CAChC,QACA,mBACW;AALb;AAME,QAAM,WAAU,YAAO,WAAP,YAAiB;AACjC,QAAM,cAAc,IAAI,IAAI,iCAAQ,aAAa,OAAO,EAAE,SAAS;AACnE,SAAO,YAAY,SAAS;AAC9B;","names":[]}
@@ -4,36 +4,6 @@ import {
4
4
  __spreadValues
5
5
  } from "./chunk-RGHW4PYM.mjs";
6
6
 
7
- // src/shared/storage.ts
8
- var DEFAULT_COOKIE_DURATION = 60 * 15;
9
- var CookieStorage = class {
10
- constructor(settings = {}) {
11
- var _a, _b, _c, _d, _e;
12
- this.settings = {
13
- httpOnly: (_a = settings.httpOnly) != null ? _a : true,
14
- secure: (_b = settings.secure) != null ? _b : true,
15
- // the callback request comes the auth server
16
- // 'lax' ensures the code_verifier cookie is sent with the request
17
- sameSite: (_c = settings.sameSite) != null ? _c : "lax",
18
- expires: (_d = settings.expires) != null ? _d : new Date(Date.now() + 1e3 * DEFAULT_COOKIE_DURATION),
19
- path: (_e = settings.path) != null ? _e : "/"
20
- };
21
- }
22
- };
23
-
24
- // src/constants.ts
25
- var DEFAULT_SCOPES = [
26
- "openid",
27
- "profile",
28
- "email",
29
- "forwardedTokens",
30
- "offline_access"
31
- ];
32
- var IFRAME_ID = "civic-auth-iframe";
33
- var AUTH_SERVER = "https://auth-dev.civic.com/oauth";
34
- var DEFAULT_OAUTH_GET_PARAMS = ["code", "state", "iss"];
35
- var TOKEN_EXCHANGE_TRIGGER_TEXT = "sameDomainCodeExchangeRequired";
36
-
37
7
  // src/shared/types.ts
38
8
  var OAuthTokens = /* @__PURE__ */ ((OAuthTokens2) => {
39
9
  OAuthTokens2["ID_TOKEN"] = "id_token";
@@ -65,11 +35,11 @@ var getOauthEndpoints = (oauthServer) => __async(void 0, null, function* () {
65
35
  userinfo: openIdConfig.userinfo_endpoint
66
36
  };
67
37
  });
68
- var generateState = (displayMode) => {
69
- const jsonString = JSON.stringify({
38
+ var generateState = (displayMode, serverTokenExchange) => {
39
+ const jsonString = JSON.stringify(__spreadValues({
70
40
  uuid: uuid(),
71
41
  displayMode
72
- });
42
+ }, serverTokenExchange ? { serverTokenExchange } : {}));
73
43
  return btoa(jsonString);
74
44
  };
75
45
  var displayModeFromState = (state, sessionDisplayMode) => {
@@ -81,6 +51,15 @@ var displayModeFromState = (state, sessionDisplayMode) => {
81
51
  return sessionDisplayMode;
82
52
  }
83
53
  };
54
+ var serverTokenExchangeFromState = (state) => {
55
+ try {
56
+ const jsonString = atob(state);
57
+ return JSON.parse(jsonString).serverTokenExchange;
58
+ } catch (e) {
59
+ console.error("Failed to parse serverTokenExchange from state:", state);
60
+ return void 0;
61
+ }
62
+ };
84
63
 
85
64
  // src/shared/util.ts
86
65
  import * as jose from "jose";
@@ -212,6 +191,9 @@ function clearTokens(storage) {
212
191
  Object.values(OAuthTokens).forEach((cookie) => {
213
192
  storage.set(cookie, "");
214
193
  });
194
+ Object.values("code_verifier" /* COOKIE_NAME */).forEach((cookie) => {
195
+ storage.set(cookie, "");
196
+ });
215
197
  }
216
198
  function clearUser(storage) {
217
199
  const userSession = new GenericUserSession(storage);
@@ -254,8 +236,30 @@ function validateOauth2Tokens(tokens, endpoints, oauth2Client, issuer) {
254
236
  });
255
237
  }
256
238
 
257
- // src/services/PKCE.ts
258
- import { generateCodeVerifier } from "oslo/oauth2";
239
+ // src/shared/session.ts
240
+ import { parseJWT } from "oslo/jwt";
241
+ function getUser(storage) {
242
+ return __async(this, null, function* () {
243
+ var _a, _b;
244
+ const tokens = retrieveTokens(storage);
245
+ if (!tokens) return null;
246
+ return (_b = (_a = parseJWT(tokens.id_token)) == null ? void 0 : _a.payload) != null ? _b : null;
247
+ });
248
+ }
249
+
250
+ // src/constants.ts
251
+ var DEFAULT_SCOPES = [
252
+ "openid",
253
+ "profile",
254
+ "email",
255
+ "forwardedTokens",
256
+ "offline_access"
257
+ ];
258
+ var IFRAME_ID = "civic-auth-iframe";
259
+ var AUTH_SERVER = "https://auth-dev.civic.com/oauth";
260
+ var DEFAULT_OAUTH_GET_PARAMS = ["code", "state", "iss"];
261
+ var TOKEN_EXCHANGE_TRIGGER_TEXT = "sameDomainCodeExchangeRequired";
262
+ var TOKEN_EXCHANGE_SUCCESS_TEXT = "serverSideTokenExchangeSuccess";
259
263
 
260
264
  // src/browser/storage.ts
261
265
  var LocalStorageAdapter = class {
@@ -268,6 +272,7 @@ var LocalStorageAdapter = class {
268
272
  };
269
273
 
270
274
  // src/services/PKCE.ts
275
+ import { generateCodeVerifier } from "oslo/oauth2";
271
276
  var ConfidentialClientPKCEConsumer = class {
272
277
  constructor(pkceChallengeEndpoint) {
273
278
  this.pkceChallengeEndpoint = pkceChallengeEndpoint;
@@ -289,14 +294,14 @@ var GenericPublicClientPKCEProducer = class {
289
294
  getCodeChallenge() {
290
295
  return __async(this, null, function* () {
291
296
  const verifier = generateCodeVerifier();
292
- this.storage.set("code_verifier", verifier);
297
+ this.storage.set("code_verifier" /* COOKIE_NAME */, verifier);
293
298
  return deriveCodeChallenge(verifier);
294
299
  });
295
300
  }
296
301
  // if there is already a verifier, return it,
297
302
  getCodeVerifier() {
298
303
  return __async(this, null, function* () {
299
- return this.storage.get("code_verifier");
304
+ return this.storage.get("code_verifier" /* COOKIE_NAME */);
300
305
  });
301
306
  }
302
307
  };
@@ -309,6 +314,14 @@ var BrowserPublicClientPKCEProducer = class extends GenericPublicClientPKCEProdu
309
314
  // src/services/AuthenticationService.ts
310
315
  import { OAuth2Client as OAuth2Client2 } from "oslo/oauth2";
311
316
 
317
+ // src/services/types.ts
318
+ var PopupError = class _PopupError extends Error {
319
+ constructor(message) {
320
+ super(message);
321
+ Object.setPrototypeOf(this, _PopupError.prototype);
322
+ }
323
+ };
324
+
312
325
  // src/lib/windowUtil.ts
313
326
  var isWindowInIframe = (window2) => {
314
327
  var _a;
@@ -328,19 +341,57 @@ var removeParamsWithoutReload = (paramsToRemove) => {
328
341
  paramsToRemove.forEach((param) => {
329
342
  url.searchParams.delete(param);
330
343
  });
331
- window.history.replaceState({}, "", url);
344
+ try {
345
+ window.history.replaceState({}, "", url);
346
+ } catch (error) {
347
+ console.warn("window.history.replaceState failed", error);
348
+ }
349
+ };
350
+
351
+ // src/lib/postMessage.ts
352
+ var validateLoginAppPostMessage = (event, clientId) => {
353
+ const caseEvent = event;
354
+ console.log("caseEvent", caseEvent);
355
+ if (!caseEvent.clientId || !caseEvent.data.url || !caseEvent.source || !caseEvent.type || caseEvent.clientId !== clientId || caseEvent.source !== "civicloginApp") {
356
+ return false;
357
+ }
358
+ return true;
332
359
  };
333
360
 
334
361
  // src/services/AuthenticationService.ts
335
362
  var BrowserAuthenticationInitiator = class {
336
363
  constructor(config) {
364
+ this.postMessageHandler = null;
337
365
  this.config = config;
366
+ console.log("BrowserAuthenticationInitiator constructor", this.config);
367
+ }
368
+ handleLoginAppPopupFailed(redirectUrl) {
369
+ return __async(this, null, function* () {
370
+ console.warn(
371
+ "Login app popup failed open a popup, using redirect mode instead...",
372
+ redirectUrl
373
+ );
374
+ window.location.href = redirectUrl;
375
+ });
338
376
  }
339
377
  // Use the config (Client ID, scopes OAuth Server, Endpoints, PKCEConsumer) to generate a new login url
340
378
  // and then use the display mode to decide how to send the user there
341
379
  signIn(iframeRef) {
342
380
  return __async(this, null, function* () {
343
381
  const url = yield generateOauthLoginUrl(this.config);
382
+ this.postMessageHandler = (event) => {
383
+ const thisURL = new URL(window.location.href);
384
+ if (event.origin.endsWith("civic.com") || thisURL.hostname === "localhost") {
385
+ if (!validateLoginAppPostMessage(event.data, this.config.clientId)) {
386
+ console.log("Received invalid message from login app", event.data);
387
+ return;
388
+ }
389
+ const loginMessage = event.data;
390
+ console.log("Received message from login app", event.data);
391
+ this.handleLoginAppPopupFailed(loginMessage.data.url);
392
+ }
393
+ };
394
+ window.addEventListener("message", this.postMessageHandler);
344
395
  if (this.config.displayMode === "iframe") {
345
396
  if (!iframeRef)
346
397
  throw new Error("iframeRef is required for displayMode 'iframe'");
@@ -350,7 +401,18 @@ var BrowserAuthenticationInitiator = class {
350
401
  window.location.href = url.toString();
351
402
  }
352
403
  if (this.config.displayMode === "new_tab") {
353
- window.open(url.toString(), "_blank");
404
+ try {
405
+ const popupWindow = window.open(url.toString(), "_blank");
406
+ console.log("signIn", popupWindow);
407
+ if (!popupWindow) {
408
+ throw new PopupError("Failed to open popup window");
409
+ }
410
+ } catch (error) {
411
+ console.error("popupWindow", error);
412
+ throw new PopupError(
413
+ "window.open has thrown: Failed to open popup window"
414
+ );
415
+ }
354
416
  }
355
417
  return url;
356
418
  });
@@ -364,10 +426,18 @@ var BrowserAuthenticationInitiator = class {
364
426
  return url;
365
427
  });
366
428
  }
429
+ cleanup() {
430
+ if (this.postMessageHandler) {
431
+ window.removeEventListener("message", this.postMessageHandler);
432
+ }
433
+ }
367
434
  };
368
435
  var GenericAuthenticationInitiator = class {
369
436
  constructor(config) {
370
437
  this.config = config;
438
+ console.log("GenericAuthenticationInitiator constructor", {
439
+ config
440
+ });
371
441
  }
372
442
  // Use the config (Client ID, scopes OAuth Server, Endpoints, PKCEConsumer) to generate a new login url
373
443
  // and simply return the url
@@ -385,6 +455,9 @@ var GenericAuthenticationInitiator = class {
385
455
  var BrowserAuthenticationService = class _BrowserAuthenticationService extends BrowserAuthenticationInitiator {
386
456
  // TODO WIP - perhaps we want to keep resolver and initiator separate here
387
457
  constructor(config, pkceProducer = new BrowserPublicClientPKCEProducer()) {
458
+ console.log("BrowserAuthenticationService constructor", {
459
+ config
460
+ });
388
461
  super(__spreadProps(__spreadValues({}, config), {
389
462
  state: generateState(config.displayMode),
390
463
  // Store and retrieve the PKCE challenge in local storage
@@ -437,9 +510,8 @@ var BrowserAuthenticationService = class _BrowserAuthenticationService extends B
437
510
  );
438
511
  if (parsedDisplayMode === "new_tab") {
439
512
  window.close();
440
- } else if (parsedDisplayMode === "redirect") {
441
- removeParamsWithoutReload(DEFAULT_OAUTH_GET_PARAMS);
442
513
  }
514
+ removeParamsWithoutReload(DEFAULT_OAUTH_GET_PARAMS);
443
515
  return tokens;
444
516
  });
445
517
  }
@@ -496,213 +568,32 @@ var BrowserAuthenticationService = class _BrowserAuthenticationService extends B
496
568
  }
497
569
  };
498
570
 
499
- // src/server/ServerAuthenticationResolver.ts
500
- import { OAuth2Client as OAuth2Client3 } from "oslo/oauth2";
501
- var ServerAuthenticationResolver = class _ServerAuthenticationResolver {
502
- constructor(authConfig, storage, endpointOverrides) {
503
- this.authConfig = authConfig;
504
- this.storage = storage;
505
- this.endpointOverrides = endpointOverrides;
506
- this.pkceProducer = new GenericPublicClientPKCEProducer(storage);
507
- }
508
- validateExistingSession() {
509
- throw new Error("Method not implemented.");
510
- }
511
- init() {
512
- return __async(this, null, function* () {
513
- this.endpoints = yield getEndpointsWithOverrides(
514
- this.authConfig.oauthServer,
515
- this.endpointOverrides
516
- );
517
- this.oauth2client = new OAuth2Client3(
518
- this.authConfig.clientId,
519
- this.endpoints.auth,
520
- this.endpoints.token,
521
- {
522
- redirectURI: this.authConfig.redirectUrl
523
- }
524
- );
525
- return this;
526
- });
527
- }
528
- tokenExchange(code, state) {
529
- return __async(this, null, function* () {
530
- if (!this.oauth2client) yield this.init();
531
- const codeVerifier = yield this.pkceProducer.getCodeVerifier();
532
- if (!codeVerifier) throw new Error("Code verifier not found in storage");
533
- const tokens = yield exchangeTokens(
534
- code,
535
- state,
536
- this.pkceProducer,
537
- this.oauth2client,
538
- // clean up types here to avoid the ! operator
539
- this.authConfig.oauthServer,
540
- this.endpoints
541
- // clean up types here to avoid the ! operator
542
- );
543
- storeTokens(this.storage, tokens);
544
- return tokens;
545
- });
546
- }
547
- getSessionData() {
548
- return __async(this, null, function* () {
549
- const storageData = retrieveTokens(this.storage);
550
- if (!storageData) return null;
551
- return {
552
- authenticated: !!storageData.id_token,
553
- idToken: storageData.id_token,
554
- accessToken: storageData.access_token,
555
- refreshToken: storageData.refresh_token
556
- };
557
- });
558
- }
559
- static build(authConfig, storage, endpointOverrides) {
560
- return __async(this, null, function* () {
561
- const resolver = new _ServerAuthenticationResolver(
562
- authConfig,
563
- storage,
564
- endpointOverrides
565
- );
566
- yield resolver.init();
567
- return resolver;
568
- });
569
- }
570
- };
571
-
572
- // src/server/login.ts
573
- function resolveOAuthAccessCode(code, state, storage, config) {
574
- return __async(this, null, function* () {
575
- var _a;
576
- const authSessionService = yield ServerAuthenticationResolver.build(
577
- __spreadProps(__spreadValues({}, config), {
578
- oauthServer: (_a = config.oauthServer) != null ? _a : AUTH_SERVER
579
- }),
580
- storage,
581
- config.endpointOverrides
582
- );
583
- return authSessionService.tokenExchange(code, state);
584
- });
585
- }
586
- function isLoggedIn(storage) {
587
- return !!storage.get("id_token");
588
- }
589
- function buildLoginUrl(config, storage) {
590
- return __async(this, null, function* () {
591
- var _a, _b, _c;
592
- const state = (_a = config.state) != null ? _a : Math.random().toString(36).substring(2);
593
- const scopes = (_b = config.scopes) != null ? _b : DEFAULT_SCOPES;
594
- const pkceProducer = new GenericPublicClientPKCEProducer(storage);
595
- const authInitiator = new GenericAuthenticationInitiator(__spreadProps(__spreadValues({}, config), {
596
- state,
597
- scopes,
598
- oauthServer: (_c = config.oauthServer) != null ? _c : AUTH_SERVER,
599
- // When retrieving the PKCE challenge on the server-side, we produce it and store it in the session
600
- pkceConsumer: pkceProducer
601
- }));
602
- return authInitiator.signIn();
603
- });
604
- }
605
-
606
- // src/shared/session.ts
607
- import { parseJWT } from "oslo/jwt";
608
- function getUser(storage) {
609
- return __async(this, null, function* () {
610
- var _a, _b;
611
- const tokens = retrieveTokens(storage);
612
- if (!tokens) return null;
613
- return (_b = (_a = parseJWT(tokens.id_token)) == null ? void 0 : _a.payload) != null ? _b : null;
614
- });
615
- }
616
-
617
- // src/shared/GenericAuthenticationRefresher.ts
618
- import { OAuth2Client as OAuth2Client4 } from "oslo/oauth2";
619
- var GenericAuthenticationRefresher = class _GenericAuthenticationRefresher {
620
- constructor(authConfig, storage, endpointOverrides) {
621
- this.authConfig = authConfig;
622
- this.storage = storage;
623
- this.endpointOverrides = endpointOverrides;
624
- }
625
- init() {
626
- return __async(this, null, function* () {
627
- this.endpoints = yield getEndpointsWithOverrides(
628
- this.authConfig.oauthServer,
629
- this.endpointOverrides
630
- );
631
- this.oauth2client = new OAuth2Client4(
632
- this.authConfig.clientId,
633
- this.endpoints.auth,
634
- this.endpoints.token,
635
- {
636
- redirectURI: this.authConfig.redirectUrl
637
- }
638
- );
639
- return this;
640
- });
641
- }
642
- static build(authConfig, storage, endpointOverrides) {
643
- return __async(this, null, function* () {
644
- const refresher = new _GenericAuthenticationRefresher(
645
- authConfig,
646
- storage,
647
- endpointOverrides
648
- );
649
- yield refresher.init();
650
- return refresher;
651
- });
652
- }
653
- refreshTokens() {
654
- return __async(this, null, function* () {
655
- if (!this.oauth2client) yield this.init();
656
- const tokens = retrieveTokens(this.storage);
657
- if (!(tokens == null ? void 0 : tokens.refresh_token)) throw new Error("No refresh token available");
658
- const oauth2Client = this.oauth2client;
659
- const refreshedTokens = yield oauth2Client.refreshAccessToken(
660
- tokens.refresh_token
661
- );
662
- storeTokens(this.storage, refreshedTokens);
663
- return tokens;
664
- });
665
- }
666
- };
667
-
668
- // src/server/refresh.ts
669
- function refreshTokens(storage, config) {
670
- return __async(this, null, function* () {
671
- var _a;
672
- const refresher = yield GenericAuthenticationRefresher.build(
673
- __spreadProps(__spreadValues({}, config), {
674
- oauthServer: (_a = config.oauthServer) != null ? _a : AUTH_SERVER
675
- }),
676
- storage,
677
- config.endpointOverrides
678
- );
679
- return refresher.refreshTokens();
680
- });
681
- }
682
-
683
571
  export {
684
572
  convertForwardedTokenFormat,
685
573
  GenericUserSession,
686
574
  DEFAULT_SCOPES,
687
575
  IFRAME_ID,
576
+ AUTH_SERVER,
688
577
  TOKEN_EXCHANGE_TRIGGER_TEXT,
578
+ TOKEN_EXCHANGE_SUCCESS_TEXT,
689
579
  isWindowInIframe,
690
580
  generateState,
581
+ serverTokenExchangeFromState,
691
582
  cn,
692
583
  withoutUndefined,
584
+ getEndpointsWithOverrides,
585
+ exchangeTokens,
586
+ storeTokens,
693
587
  clearTokens,
694
588
  retrieveTokens,
695
589
  LocalStorageAdapter,
696
590
  ConfidentialClientPKCEConsumer,
697
591
  GenericPublicClientPKCEProducer,
698
592
  BrowserPublicClientPKCEProducer,
593
+ PopupError,
699
594
  BrowserAuthenticationInitiator,
595
+ GenericAuthenticationInitiator,
700
596
  BrowserAuthenticationService,
701
- getUser,
702
- CookieStorage,
703
- resolveOAuthAccessCode,
704
- isLoggedIn,
705
- buildLoginUrl,
706
- refreshTokens
597
+ getUser
707
598
  };
708
- //# sourceMappingURL=chunk-G3P5TIO2.mjs.map
599
+ //# sourceMappingURL=chunk-CBQ3HKRV.mjs.map