@bigio/better-auth-electron 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -2,7 +2,7 @@ import 'fs';
2
2
  import path from 'path';
3
3
  import { fileURLToPath } from 'url';
4
4
  import { createAuthEndpoint, sessionMiddleware, APIError, createAuthMiddleware } from 'better-auth/api';
5
- import z from 'zod';
5
+ import z, { boolean } from 'zod';
6
6
 
7
7
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
8
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -27,7 +27,8 @@ var defaultServerPluginOptions = {
27
27
  TICKET_NAME_IN_URL: "ticket",
28
28
  SCHEME_NAME_IN_URL: "scheme",
29
29
  PROVIDER_NAME_IN_URL: "provider",
30
- CHALLENGE_NAME_IN_URL: "electron_challenge",
30
+ CHALLENGE_NAME_IN_URL: "electron-challenge",
31
+ AUTH_STATUS_NAME_IN_URL: "electron-status",
31
32
  TICKET_TTL_SEC: 60 * 5,
32
33
  ELECTRON_SESSION_DURATION: 7 * 24 * 60 * 60 * 1e3
33
34
  // customPreactJS: customPreactJS,
@@ -567,6 +568,7 @@ var AES_ALGO = { name: "AES-GCM", length: 128 };
567
568
  var secretKeyCache = /* @__PURE__ */ new Map();
568
569
  var MAX_CACHE_SIZE = 50;
569
570
  var GLOBAL_ENCODER = new TextEncoder();
571
+ var GLOBAL_DECODER = new TextDecoder();
570
572
  async function getCachedKey(secret) {
571
573
  const checkSecret = okOr(secret, {
572
574
  msg: "Invalid secret input for getCachedKey",
@@ -766,7 +768,7 @@ async function decryptTicket(ticket, secret) {
766
768
  ctx: { ivLength: iv.byteLength, dataLength: data.byteLength }
767
769
  }
768
770
  );
769
- const decodedString = new TextDecoder().decode(decryptedBuffer);
771
+ const decodedString = GLOBAL_DECODER.decode(decryptedBuffer);
770
772
  const rawJson = safeTry(() => JSON.parse(decodedString), {
771
773
  msg: "JSON Parsing Decrypted payload Failed",
772
774
  ctx: { len: decodedString.length, prefix: decodedString.slice(0, 10) }
@@ -812,15 +814,22 @@ async function pkceGenerateChallenge(verifier) {
812
814
  return encode64(hashBuffer);
813
815
  }
814
816
  var REGEX_BASE64_URL = /^[a-zA-Z0-9\-_]+=*$/;
815
- function SearchParamsZod(ELECTRON_SCHEME, PROVIDERS) {
817
+ function RequiredSearchParamsBuilder(ELECTRON_SCHEME, PROVIDERS) {
816
818
  return z.object({
817
819
  scheme: z.string().min(1, "Scheme cannot be empty").regex(REGEX_BASE64_URL).refine((scheme) => scheme === ELECTRON_SCHEME, {
818
820
  message: "Invalid scheme provided"
819
821
  }),
820
822
  provider: z.enum(PROVIDERS),
821
- challenge: z.string().length(43, "Challenge must be exactly 43 characters").regex(REGEX_BASE64_URL)
823
+ challenge: z.string().length(43, "Challenge must be exactly 43 characters").regex(REGEX_BASE64_URL),
824
+ status: z.enum(["succeed", "error", "newUser"]).optional()
822
825
  });
823
826
  }
827
+ z.object({
828
+ scopes: z.array(z.string()).optional(),
829
+ loginHint: z.string().optional(),
830
+ additionalData: z.record(z.string(), z.any()).optional(),
831
+ requestSignUp: boolean().optional()
832
+ });
824
833
 
825
834
  // src/server/electron-server-plugin.ts
826
835
  var REGEX_SAMESITE_LAX = /(?:^|;)\s*SameSite\s*=\s*Lax/gi;
@@ -871,11 +880,12 @@ var electronServerPlugin = (options) => {
871
880
  SCHEME_NAME_IN_URL,
872
881
  PROVIDER_NAME_IN_URL,
873
882
  CHALLENGE_NAME_IN_URL,
883
+ AUTH_STATUS_NAME_IN_URL,
874
884
  TICKET_TTL_SEC,
875
885
  ELECTRON_SESSION_DURATION,
876
886
  PROVIDERS,
877
887
  ELECTRON_APP_HOST} = config;
878
- const searchParamsZod = SearchParamsZod(ELECTRON_SCHEME, PROVIDERS);
888
+ const searchParamsZod = RequiredSearchParamsBuilder(ELECTRON_SCHEME, PROVIDERS);
879
889
  const ticketZod = searchParamsZod.extend({
880
890
  userid: z.string().min(1, "User id cannot be empty").regex(REGEX_BASE64_URL2)
881
891
  });
@@ -905,24 +915,39 @@ var electronServerPlugin = (options) => {
905
915
  return false;
906
916
  }
907
917
  const dummyURL = new URL(location, "http://dummy");
908
- if (!dummyURL.pathname.includes(WEB_OAUTH_SIGNIN_CALLBACK_PATHNAME)) {
918
+ console.log(dummyURL.pathname);
919
+ if (dummyURL.pathname !== `/${WEB_OAUTH_SIGNIN_CALLBACK_PATHNAME}`) {
909
920
  return false;
910
921
  }
911
922
  const searchParams = safeTry(
912
923
  () => searchParamsZod.parse({
913
924
  scheme: dummyURL.searchParams.get(SCHEME_NAME_IN_URL),
914
925
  provider: dummyURL.searchParams.get(PROVIDER_NAME_IN_URL),
915
- challenge: dummyURL.searchParams.get(CHALLENGE_NAME_IN_URL)
926
+ challenge: dummyURL.searchParams.get(CHALLENGE_NAME_IN_URL),
927
+ status: dummyURL.searchParams.get(AUTH_STATUS_NAME_IN_URL)
916
928
  }),
917
929
  new APIError("BAD_REQUEST", {
918
930
  message: "Invalid OAuth callback parameters"
919
931
  })
920
932
  );
921
- const { scheme, provider, challenge } = searchParams;
922
- const currentProvider = okOr(requestUrl.pathname.split("/").pop(), {
923
- ctx: requestUrl
924
- });
925
- console.log(currentProvider, provider);
933
+ const { scheme, provider, challenge, status } = searchParams;
934
+ if (!status) {
935
+ return false;
936
+ }
937
+ const deepLinkURL = new URL(
938
+ `${ELECTRON_SCHEME}://${ELECTRON_CALLBACK_HOST_PATH}`
939
+ );
940
+ deepLinkURL.searchParams.set(AUTH_STATUS_NAME_IN_URL, status);
941
+ deepLinkURL.searchParams.set(CHALLENGE_NAME_IN_URL, challenge);
942
+ if (status === "error") {
943
+ return deepLinkURL;
944
+ }
945
+ const currentProvider = okOr(
946
+ requestUrl.pathname.split("/").filter(Boolean).pop(),
947
+ {
948
+ ctx: requestUrl
949
+ }
950
+ );
926
951
  if (provider !== currentProvider) {
927
952
  throw new APIError("FORBIDDEN", {
928
953
  message: "CurrentProvider not match electron OAuth provider"
@@ -937,6 +962,7 @@ var electronServerPlugin = (options) => {
937
962
  () => requireSetCookies(responseHeaders),
938
963
  true
939
964
  );
965
+ responseHeaders.delete("set-cookie");
940
966
  const tokenMatch = okOr(
941
967
  setCookieHeader.map((c) => c.match(SESSION_TOKEN_REGEX)).find((m) => m !== null),
942
968
  new APIError("BAD_REQUEST", {
@@ -962,7 +988,8 @@ var electronServerPlugin = (options) => {
962
988
  userid: userSession.user.id,
963
989
  scheme,
964
990
  provider,
965
- challenge
991
+ challenge,
992
+ status
966
993
  },
967
994
  ctx.context.secret,
968
995
  TICKET_TTL_SEC
@@ -973,11 +1000,7 @@ var electronServerPlugin = (options) => {
973
1000
  message: "Failed to sign ticket"
974
1001
  })
975
1002
  );
976
- const deepLinkURL = new URL(
977
- `${ELECTRON_SCHEME}://${ELECTRON_CALLBACK_HOST_PATH}`
978
- );
979
1003
  deepLinkURL.searchParams.set(TICKET_NAME_IN_URL, ticket);
980
- deepLinkURL.searchParams.set(CHALLENGE_NAME_IN_URL, challenge);
981
1004
  consoleLog("Deeplink URL:", deepLinkURL);
982
1005
  return deepLinkURL;
983
1006
  });
@@ -1008,7 +1031,6 @@ var electronServerPlugin = (options) => {
1008
1031
  if (!responseHeaders) {
1009
1032
  return;
1010
1033
  }
1011
- console.log(responseHeaders);
1012
1034
  const setCookieResult = safeTry(() => requireSetCookies(responseHeaders));
1013
1035
  if (!setCookieResult.data && setCookieResult.error) {
1014
1036
  return;
@@ -1129,7 +1151,7 @@ var electronServerPlugin = (options) => {
1129
1151
  })
1130
1152
  );
1131
1153
  const tokenConfig = ctx.context.authCookies.sessionToken;
1132
- const signIt = await safeTry(
1154
+ await safeTry(
1133
1155
  ctx.setSignedCookie(
1134
1156
  tokenConfig.name,
1135
1157
  sessionForElectron.token,
@@ -1148,7 +1170,6 @@ var electronServerPlugin = (options) => {
1148
1170
  message: "Failed to set session cookie"
1149
1171
  })
1150
1172
  );
1151
- consoleLog("Signed Cookie: ", signIt);
1152
1173
  return ctx.json({
1153
1174
  session: {
1154
1175
  createdAt: sessionForElectron.createdAt,