better-auth 1.6.6 → 1.6.8

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.
@@ -1,6 +1,7 @@
1
1
  import { parseAccountOutput } from "../../db/schema.mjs";
2
2
  import { getAccountCookie, setAccountCookie } from "../../cookies/session-store.mjs";
3
3
  import { getAwaitableValue } from "../../context/helpers.mjs";
4
+ import { missingEmailLogMessage } from "../../oauth2/errors.mjs";
4
5
  import { generateState } from "../../oauth2/state.mjs";
5
6
  import { decryptOAuthToken, setTokenUtil } from "../../oauth2/utils.mjs";
6
7
  import { freshSessionMiddleware, getSessionFromCtx, sessionMiddleware } from "./session.mjs";
@@ -133,7 +134,7 @@ const linkSocialAccount = createAuthEndpoint("/link-social", {
133
134
  }
134
135
  const linkingUserId = String(linkingUserInfo.user.id);
135
136
  if (!linkingUserInfo.user.email) {
136
- c.context.logger.error("User email not found", { provider: c.body.provider });
137
+ c.context.logger.error(missingEmailLogMessage(c.body.provider, { source: "id_token" }), { provider: c.body.provider });
137
138
  throw APIError.from("UNAUTHORIZED", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);
138
139
  }
139
140
  if ((await c.context.internalAdapter.findAccounts(session.user.id)).find((a) => a.providerId === provider.id && a.accountId === linkingUserId)) return c.json({
@@ -1,5 +1,6 @@
1
1
  import { setSessionCookie } from "../../cookies/index.mjs";
2
2
  import { getAwaitableValue } from "../../context/helpers.mjs";
3
+ import { missingEmailLogMessage } from "../../oauth2/errors.mjs";
3
4
  import { parseState } from "../../oauth2/state.mjs";
4
5
  import { setTokenUtil } from "../../oauth2/utils.mjs";
5
6
  import { handleOAuthUserInfo } from "../../oauth2/link-account.mjs";
@@ -134,7 +135,7 @@ const callbackOAuth = createAuthEndpoint("/callback/:id", {
134
135
  throw c.redirect(toRedirectTo);
135
136
  }
136
137
  if (!userInfo.email) {
137
- c.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings.");
138
+ c.context.logger.error(missingEmailLogMessage(provider.id));
138
139
  return redirectOnError("email_not_found");
139
140
  }
140
141
  const accountData = {
@@ -2,6 +2,7 @@ import { formCsrfMiddleware } from "../middlewares/origin-check.mjs";
2
2
  import { parseUserOutput } from "../../db/schema.mjs";
3
3
  import { setSessionCookie } from "../../cookies/index.mjs";
4
4
  import { getAwaitableValue } from "../../context/helpers.mjs";
5
+ import { missingEmailLogMessage } from "../../oauth2/errors.mjs";
5
6
  import { generateState } from "../../oauth2/state.mjs";
6
7
  import { handleOAuthUserInfo } from "../../oauth2/link-account.mjs";
7
8
  import { createEmailVerificationToken } from "./email-verification.mjs";
@@ -100,7 +101,7 @@ const signInSocial = () => createAuthEndpoint("/sign-in/social", {
100
101
  throw APIError.from("UNAUTHORIZED", BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);
101
102
  }
102
103
  if (!userInfo.user.email) {
103
- c.context.logger.error("User email not found", { provider: c.body.provider });
104
+ c.context.logger.error(missingEmailLogMessage(c.body.provider, { source: "id_token" }), { provider: c.body.provider });
104
105
  throw APIError.from("UNAUTHORIZED", BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);
105
106
  }
106
107
  const data = await handleOAuthUserInfo(c, {
@@ -98,16 +98,43 @@ function toAuthEndpoints(endpoints, ctx) {
98
98
  [ATTR_HTTP_ROUTE]: route,
99
99
  [ATTR_OPERATION_ID]: operationId
100
100
  }, () => endpoint(internalContext))).catch((e) => {
101
- if (isAPIError(e))
102
- /**
103
- * API Errors from response are caught
104
- * and returned to hooks
105
- */
106
- return {
107
- response: e,
108
- status: e.statusCode,
109
- headers: e.headers ? new Headers(e.headers) : null
110
- };
101
+ if (isAPIError(e)) {
102
+ /**
103
+ * API Errors from response are caught
104
+ * and returned to hooks.
105
+ *
106
+ * Headers come from two sources that must both
107
+ * survive:
108
+ * - `kAPIErrorHeaderSymbol`: ctx.responseHeaders
109
+ * accumulated via c.setCookie / c.setHeader
110
+ * before the throw.
111
+ * - `e.headers`: explicit headers on the APIError
112
+ * (e.g. `location` from c.redirect).
113
+ *
114
+ * Start from the accumulated ctx headers, then
115
+ * apply e.headers on top — appending `set-cookie`
116
+ * and setting others — so explicit APIError
117
+ * headers override while cookies accumulate.
118
+ */
119
+ const ctxHeaders = e[kAPIErrorHeaderSymbol];
120
+ const errHeaders = e.headers ? new Headers(e.headers) : null;
121
+ let headers = null;
122
+ if (ctxHeaders || errHeaders) {
123
+ headers = new Headers();
124
+ ctxHeaders?.forEach((value, key) => {
125
+ headers.append(key, value);
126
+ });
127
+ errHeaders?.forEach((value, key) => {
128
+ if (key.toLowerCase() === "set-cookie") headers.append(key, value);
129
+ else headers.set(key, value);
130
+ });
131
+ }
132
+ return {
133
+ response: e,
134
+ status: e.statusCode,
135
+ headers
136
+ };
137
+ }
111
138
  throw e;
112
139
  });
113
140
  if (result && result instanceof Response) return result;
@@ -116,7 +143,26 @@ function toAuthEndpoints(endpoints, ctx) {
116
143
  const after = await runAfterHooks(internalContext, afterHooks, endpoint, operationId);
117
144
  if (after.response) result.response = after.response;
118
145
  if (isAPIError(result.response) && shouldPublishLog(authContext.logger.level, "debug")) result.response.stack = result.response.errorStack;
119
- if (isAPIError(result.response) && !shouldReturnResponse) throw result.response;
146
+ if (isAPIError(result.response) && !shouldReturnResponse) {
147
+ /**
148
+ * Non-response path: we re-throw the raw APIError
149
+ * to callers of `auth.api.*`. `result.headers`
150
+ * holds the merged ctx + explicit headers (see
151
+ * catch block above) — rewrite
152
+ * `kAPIErrorHeaderSymbol` with the merged set so
153
+ * downstream pipelines (e.g. better-call's
154
+ * response builder, or an outer hook catch) see
155
+ * the same headers we'd have written on the
156
+ * response.
157
+ */
158
+ if (result.headers) Object.defineProperty(result.response, kAPIErrorHeaderSymbol, {
159
+ enumerable: false,
160
+ configurable: true,
161
+ writable: false,
162
+ value: result.headers
163
+ });
164
+ throw result.response;
165
+ }
120
166
  return shouldReturnResponse ? toResponse(result.response, {
121
167
  headers: result.headers,
122
168
  status: result.status
@@ -0,0 +1,12 @@
1
+ //#region src/oauth2/errors.ts
2
+ const HANDLING_DOCS_URL = "https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email";
3
+ /**
4
+ * Build the logger message shown when an OAuth provider does not return an
5
+ * email address. Kept in one place so every rejection site points users at
6
+ * the same workaround docs.
7
+ */
8
+ function missingEmailLogMessage(providerId, options) {
9
+ return `${options?.source === "generic" ? `Generic OAuth provider "${providerId}"` : `Provider "${providerId}"`} did not return an email${options?.source === "id_token" ? " in the id token" : ""}. Either request the provider's email scope, or synthesize one via \`mapProfileToUser\`. See ${HANDLING_DOCS_URL}`;
10
+ }
11
+ //#endregion
12
+ export { missingEmailLogMessage };
@@ -29,7 +29,7 @@ async function generateState(c, link, additionalData) {
29
29
  }
30
30
  }
31
31
  async function parseState(c) {
32
- const state = c.query.state || c.body.state;
32
+ const state = c.query.state || c.body?.state;
33
33
  const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;
34
34
  let parsedData;
35
35
  try {
package/dist/package.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "1.6.6";
2
+ var version = "1.6.8";
3
3
  //#endregion
4
4
  export { version };
@@ -1,4 +1,5 @@
1
1
  import { setSessionCookie } from "../../cookies/index.mjs";
2
+ import { missingEmailLogMessage } from "../../oauth2/errors.mjs";
2
3
  import { generateState, parseState } from "../../oauth2/state.mjs";
3
4
  import { setTokenUtil } from "../../oauth2/utils.mjs";
4
5
  import { sessionMiddleware } from "../../api/routes/session.mjs";
@@ -209,7 +210,7 @@ const oAuth2Callback = (options) => createAuthEndpoint("/oauth2/callback/:provid
209
210
  const mapUser = providerConfig.mapProfileToUser ? await providerConfig.mapProfileToUser(userInfo) : userInfo;
210
211
  const email = mapUser.email ? mapUser.email.toLowerCase() : userInfo.email?.toLowerCase();
211
212
  if (!email) {
212
- ctx.context.logger.error("Unable to get user info", userInfo);
213
+ ctx.context.logger.error(missingEmailLogMessage(providerConfig.providerId, { source: "generic" }), userInfo);
213
214
  throw redirectOnError("email_is_missing");
214
215
  }
215
216
  const id = mapUser.id ? String(mapUser.id) : String(userInfo.id);
@@ -396,7 +396,7 @@ declare const getOrgAdapter: <O extends OrganizationOptions>(context: AuthContex
396
396
  } ? FieldAttributeToObject<RemoveFieldsWithReturnedFalse<Field>> : {}) extends infer T_3 ? { [K_3 in keyof T_3]: T_3[K_3] } : never)[] | undefined;
397
397
  }) | null>;
398
398
  listOrganizations: (userId: string) => Promise<InferOrganization<O>[]>;
399
- createTeam: (data: Omit<TeamInput, "id">) => Promise<{
399
+ createTeam: (data: TeamInput) => Promise<{
400
400
  id: string;
401
401
  name: string;
402
402
  organizationId: string;
@@ -357,7 +357,8 @@ const getOrgAdapter = (context, options) => {
357
357
  createTeam: async (data) => {
358
358
  return await (await getCurrentAdapter(baseAdapter)).create({
359
359
  model: "team",
360
- data
360
+ data,
361
+ forceAllowId: true
361
362
  });
362
363
  },
363
364
  findTeamById: async ({ teamId, organizationId, includeTeamMembers }) => {
@@ -553,7 +554,8 @@ const getOrgAdapter = (context, options) => {
553
554
  inviterId: user.id,
554
555
  ...invitation,
555
556
  teamId: invitation.teamIds.length > 0 ? invitation.teamIds.join(",") : null
556
- }
557
+ },
558
+ forceAllowId: true
557
559
  });
558
560
  },
559
561
  findInvitationById: async (id) => {
@@ -294,7 +294,7 @@ type InvitationInput = z.input<typeof invitationSchema>;
294
294
  type MemberInput = z.input<typeof memberSchema>;
295
295
  type TeamMemberInput = z.input<typeof teamMemberSchema>;
296
296
  type OrganizationInput = z.input<typeof organizationSchema>;
297
- type TeamInput = z.infer<typeof teamSchema>;
297
+ type TeamInput = z.input<typeof teamSchema>;
298
298
  type OrganizationRole = z.infer<typeof organizationRoleSchema>;
299
299
  declare const defaultRolesSchema: z.ZodUnion<readonly [z.ZodEnum<{
300
300
  admin: "admin";
@@ -312,6 +312,11 @@ const verifyPhoneNumber = (opts) => createAuthEndpoint("/phone-number/verify", {
312
312
  [opts.phoneNumber]: ctx.body.phoneNumber,
313
313
  [opts.phoneNumberVerified]: true
314
314
  });
315
+ if (!user) throw APIError.from("INTERNAL_SERVER_ERROR", BASE_ERROR_CODES.FAILED_TO_UPDATE_USER);
316
+ await opts?.callbackOnVerification?.({
317
+ phoneNumber: ctx.body.phoneNumber,
318
+ user
319
+ }, ctx);
315
320
  return ctx.json({
316
321
  status: true,
317
322
  token: session.session.token,
@@ -1,6 +1,2 @@
1
- import { APIError } from "@better-auth/core/error";
2
-
3
- //#region src/utils/is-api-error.d.ts
4
- declare function isAPIError(error: unknown): error is APIError;
5
- //#endregion
1
+ import { isAPIError } from "@better-auth/core/utils/is-api-error";
6
2
  export { isAPIError };
@@ -1,8 +1,2 @@
1
- import { APIError } from "@better-auth/core/error";
2
- import { APIError as APIError$1 } from "better-call";
3
- //#region src/utils/is-api-error.ts
4
- function isAPIError(error) {
5
- return error instanceof APIError$1 || error instanceof APIError || error?.name === "APIError";
6
- }
7
- //#endregion
1
+ import { isAPIError } from "@better-auth/core/utils/is-api-error";
8
2
  export { isAPIError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "better-auth",
3
- "version": "1.6.6",
3
+ "version": "1.6.8",
4
4
  "description": "The most comprehensive authentication framework for TypeScript.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -489,13 +489,13 @@
489
489
  "kysely": "^0.28.14",
490
490
  "nanostores": "^1.1.1",
491
491
  "zod": "^4.3.6",
492
- "@better-auth/core": "1.6.6",
493
- "@better-auth/drizzle-adapter": "1.6.6",
494
- "@better-auth/kysely-adapter": "1.6.6",
495
- "@better-auth/memory-adapter": "1.6.6",
496
- "@better-auth/mongo-adapter": "1.6.6",
497
- "@better-auth/prisma-adapter": "1.6.6",
498
- "@better-auth/telemetry": "1.6.6"
492
+ "@better-auth/core": "1.6.8",
493
+ "@better-auth/drizzle-adapter": "1.6.8",
494
+ "@better-auth/kysely-adapter": "1.6.8",
495
+ "@better-auth/memory-adapter": "1.6.8",
496
+ "@better-auth/mongo-adapter": "1.6.8",
497
+ "@better-auth/prisma-adapter": "1.6.8",
498
+ "@better-auth/telemetry": "1.6.8"
499
499
  },
500
500
  "devDependencies": {
501
501
  "@lynx-js/react": "^0.116.3",