Skip to content

better-auth adapter: update() with compound where fails (deviceAuthorization verify-claim) — no updateMany fallback #2694

Closed

Description

@beshkenadze

Summary

@zenstackhq/better-auth's update() forwards a compound (AND) where straight to ZenStack ORM update(), which requires a unique field at the top level of where. Any better-auth flow that updates by a multi-condition where therefore fails before SQL runs. This is now hit in normal usage by better-auth's deviceAuthorization plugin.

Environment

  • @zenstackhq/better-auth: 3.3.3 and 3.7.2 (latest) — same behavior
  • better-auth: 1.6.12 (regression triggered by >= 1.6.11)
  • ZenStack ORM 3.x, provider sqlite/postgresql

Repro

  1. Use zenstackAdapter as the better-auth database.
  2. Enable the deviceAuthorization plugin.
  3. Sign in, then open GET /device?user_code=... (verify step).
  4. Error:
    Invalid update args for model "DeviceCode": Validation error:
    At least one unique field or field set must be set at "where"
    

Root cause

better-auth >=1.6.11 added a verify-time ownership claim that updates with a compound where { id, status: "pending", userId: null } (https://github.com/better-auth/better-auth/blob/a6f38c72ee3423ae80b0595fec3b4a61158c374d/packages/better-auth/src/plugins/device-authorization/routes.ts#L144-L154).
The adapter's convertWhereClause() turns >=2 conditions into { AND: [...] } (

const convertWhereClause = (model: string, where?: Where[]): any => {
if (!where || !where.length) return {};
if (where.length === 1) {
const w = where[0]!;
if (!w) {
throw new BetterAuthError('Invalid where clause');
}
return {
[getFieldName({ model, field: w.field })]:
w.operator === 'eq' || !w.operator
? w.value
: {
[operatorToORMOperator(w.operator)]: w.value,
},
};
}
const and = where.filter((w) => w.connector === 'AND' || !w.connector);
const or = where.filter((w) => w.connector === 'OR');
const andClause = and.map((w) => {
return {
[getFieldName({ model, field: w.field })]:
w.operator === 'eq' || !w.operator
? w.value
: {
[operatorToORMOperator(w.operator)]: w.value,
},
};
});
const orClause = or.map((w) => {
return {
[getFieldName({ model, field: w.field })]:
w.operator === 'eq' || !w.operator
? w.value
: {
[operatorToORMOperator(w.operator)]: w.value,
},
};
});
return {
...(andClause.length ? { AND: andClause } : {}),
...(orClause.length ? { OR: orClause } : {}),
};
};
), and update() calls modelDb.update({ where }) unconditionally (
async update({ model, where, update }): Promise<any> {
const modelDb = requireModelDb(db, model);
const whereClause = convertWhereClause(model, where);
return await modelDb.update({
where: whereClause,
data: update as UpdateInput<SchemaDef, GetModels<SchemaDef>, any>,
});
). ORM update() rejects the nested unique.

Suggested fix

In update(), when the converted where is not a single top-level unique selector, fall back to the existing updateMany() (then optionally re-read by the unique field) — mirroring how better-auth's own Prisma adapter handles non-unique update where. The adapter already implements updateMany() right below update().

Activity

  1. adesege commented on Sep 23, 2026

    @adesege

    Still present in @zenstackhq/better-auth 3.9.4 and 3.9.5 — convertWhereClause() is unchanged, so >= 2 conditions still become { AND: [...] } and update() still forwards it to ORM update() unconditionally.

    Two things to add from hitting this on a different plugin.

    A second flow reaches it, and it takes out all of SSO

    @better-auth/sso >= 1.7.0 locks the provider row before mutating it:

    async function lockSSOProviderRow(context, provider) {
      const where = [...(provider.id ? [{ field: 'id', value: provider.id }] : []), { field: 'providerId', value: provider.providerId }]
      return (await getCurrentAdapter(context.adapter)).update({
        model: 'ssoProvider',
        where,
        update: { providerId: provider.providerId },
      })
    }

    It is a no-op self-write used purely as a row lock, whose second condition asserts the row still carries the provider key it was read under. Because it always sends two conditions it always fails:

    Invalid update args for model "AdminSsoProvider": Validation error:
    At least one unique field or field set must be set at "where"
    

    (AdminSsoProvider is our mapped name for the plugin's ssoProvider model.)

    Called from updateSSOProvider, deleteSSOProvider, and the SSO account-linking path, so with this adapter every SSO admin mutation and every IdP sign-in fails. Notably it fails even when the model has providerId declared unique — the condition is valid, it is just no longer at the top level after conversion.

    One detail that may be useful for the fix: this call runs inside better-auth's transaction context (runWithTransaction / getCurrentAdapter), so it goes through the adapter that transaction() builds via createCustomAdapter(tx). Fixing update() covers it, since both paths share the implementation — but it does mean a consumer-side workaround has to wrap the transaction's adapter too, not just the one returned to better-auth.

    delete() has the same problem, silently

    async delete({ model, where }) {
      const modelDb = requireModelDb(db, model);
      const whereClause = convertWhereClause(model, where);
      try {
        await modelDb.delete({ where: whereClause });
      } catch {}
    }

    A compound delete hits the identical validation error, but the bare catch {} swallows it, so the row survives while better-auth is told the delete succeeded. That is worse than the update() case — no error anywhere, just a row that should be gone. Whatever fallback update() gets, delete() needs the matching one via deleteMany(), and the swallow wants removing regardless.

    The reference implementation

    better-auth's own Prisma adapter already does exactly what the suggested fix describes — worth copying directly:

    const hasRootUniqueWhereCondition = (model, where) => { /* ... */ };
    
    async update({ model, where, update }) {
      if (!hasRootUniqueWhereCondition(model, where)) {
        const whereClause = convertWhereClause({ model, where, action: "updateMany" });
        if (!(await db[model].updateMany({ where: whereClause, data: update }))) return null;
        // re-read by the unique condition
      }
      // ...
    }

    (@better-auth/prisma-adapter, update().) It falls back to updateMany plus a re-read when the filter has no root-unique condition, which also preserves compare-and-swap semantics: zero rows updated returns falsy, which is what better-auth's conflict handling expects.

    Versions

    @zenstackhq/better-auth: 3.9.4 (3.9.5 identical)
    @zenstackhq/orm: 3.9.4
    better-auth: 1.7.5
    @better-auth/sso: 1.7.5
    provider: postgresql
    
  2. adesege commented on Sep 23, 2026

    @adesege

    @ymc9 I’m happy to open a PR with the fix if needed.

  3. ymc9 commented on Sep 24, 2026

    @ymc9
    Member

    @ymc9 I’m happy to open a PR with the fix if needed.

    Hi @adesege , I haven't got time to work on a fix yet. A PR would be much appreciated!

  4. caiotarifa commented on Nov 6, 2026

    @caiotarifa
    Contributor

    Same delete() issue on 3.10.0. In our case a DB trigger rejects deleting an organization role that is still in use, but the catch {} swallows it and delete-role returns success with the role still there.

    Workaround until a fix lands (resolve the row, delete by id, let errors propagate, and cover the transaction adapter):

    export const createAuthAdapter = db => (options) => {
      const adapter = zenstackAdapter(db, { provider: 'postgresql' })(options)
    
      return {
        ...adapter,
        delete: async (args) => {
          const record = await adapter.findOne(args)
          if (record) await db[args.model].delete({ where: { id: record.id } })
        },
        transaction: callback => db.$transaction(tx =>
          callback(createAuthAdapter(tx)(options))
        )
      }
    }
  5. ymc9 commented on Nov 19, 2026

    @ymc9
    Member

    Fixed by #2901, which ships in v3.10.3: update() and delete() in @zenstackhq/better-auth now support compound where conditions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions