Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/22821-admin-password-choice.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/platform-objects': patch
---

The Setup "Create User" and "Set Password" dialogs no longer offer a "Generate Temporary Password" box the server ignores once a password is typed

Clause-②: no

The `sys_user` actions `create_user` and `set_user_password` showed two controls for one decision: a "Generate Temporary Password" box (ticked by default on Create User) and a password field labelled "leave empty to generate". With a password typed, the box did nothing, yet it was sent ticked, so its state was false whenever the field was filled.

The password field's label is now the only rule. `generatePassword` is no longer a dialog param on either action. It is sent as a constant `true` in each action's `bodyExtra`, and the endpoint's existing rule gives the label's behaviour:

- **A typed password** is the one applied, and nothing is generated.
- **An empty password** generates a temporary password, shown once in the result dialog. On Set Password this is new: the box was unticked by default there, so an empty field answered `400` unless the admin ticked it.

The endpoints `POST /api/v1/auth/admin/create-user` and `POST /api/v1/auth/admin/set-user-password` are unchanged. A caller that sends neither a password nor `generatePassword: true` still gets `400`.
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,6 @@ export const enObjects: NonNullable<TranslationData['objects']> = {
label: "Phone Number",
helpText: "Sign-in phone number (E.164, e.g. +8613800000000). Required when no email is given."
},
generatePassword: {
label: "Generate Temporary Password"
},
password: {
label: "Password (leave empty to generate)"
},
Expand All @@ -195,9 +192,6 @@ export const enObjects: NonNullable<TranslationData['objects']> = {
label: "Set Password",
successMessage: "Password updated",
params: {
generatePassword: {
label: "Generate Temporary Password"
},
newPassword: {
label: "New Password (leave empty to generate)"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,6 @@ export const esESObjects: NonNullable<TranslationData['objects']> = {
label: "Número de teléfono",
helpText: "Número de teléfono para iniciar sesión (E.164, p. ej. +8613800000000). Obligatorio si no se indica un correo."
},
generatePassword: {
label: "Generar contraseña temporal"
},
password: {
label: "Contraseña (dejar en blanco para generarla)"
},
Expand All @@ -195,9 +192,6 @@ export const esESObjects: NonNullable<TranslationData['objects']> = {
label: "Establecer contraseña",
successMessage: "Contraseña actualizada",
params: {
generatePassword: {
label: "Generar contraseña temporal"
},
newPassword: {
label: "Nueva contraseña (dejar en blanco para generarla)"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,6 @@ export const jaJPObjects: NonNullable<TranslationData['objects']> = {
label: "電話番号",
helpText: "サインイン用の電話番号(E.164 形式、例: +8613800000000)。メールアドレスを指定しない場合は必須です。"
},
generatePassword: {
label: "一時パスワードを生成"
},
password: {
label: "パスワード(空欄の場合は自動生成)"
},
Expand All @@ -195,9 +192,6 @@ export const jaJPObjects: NonNullable<TranslationData['objects']> = {
label: "パスワードを設定",
successMessage: "パスワードを更新しました",
params: {
generatePassword: {
label: "一時パスワードを生成"
},
newPassword: {
label: "新しいパスワード(空欄の場合は自動生成)"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,6 @@ export const zhCNObjects: NonNullable<TranslationData['objects']> = {
label: "手机号",
helpText: "登录手机号(E.164 格式,如 +8613800000000)。未填写邮箱时必填。"
},
generatePassword: {
label: "生成临时密码"
},
password: {
label: "密码(留空则自动生成)"
},
Expand All @@ -195,9 +192,6 @@ export const zhCNObjects: NonNullable<TranslationData['objects']> = {
label: "设置密码",
successMessage: "密码已更新",
params: {
generatePassword: {
label: "生成临时密码"
},
newPassword: {
label: "新密码(留空则自动生成)"
},
Expand Down
32 changes: 16 additions & 16 deletions packages/platform-objects/src/identity/sys-user.object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,8 @@ export const SysUser = ObjectSchema.create({
// the email-dependent invite flow. Hits the plugin-auth wrapper route
// (NOT better-auth's stock /admin/create-user): the wrapper runs the
// ADR-0068 admin gate, drives the better-auth pipeline (scrypt hash +
// credential sys_account), stamps must_change_password, and — when
// "Generate temporary password" is picked — returns the password ONCE
// credential sys_account), stamps must_change_password, and — when the
// password is left empty — returns a generated temporary password ONCE
// in the response for the result dialog. It is never persisted or logged.
name: 'create_user',
label: 'Create User',
Expand All @@ -214,6 +214,16 @@ export const SysUser = ObjectSchema.create({
requiresFeature: 'admin',
successMessage: 'User created',
refreshAfter: true,
// One rule for the admin: the password field's own label, "leave empty
// to generate". `generatePassword` is therefore a constant the dialog
// never offers, not a param: the endpoint lets a non-empty explicit
// password win over it and generates only when the password is empty,
// which is exactly what the label says. A ticked box beside a typed
// password was a control the server ignored. It is not a hidden param
// either — `visible: false` drops the value from the submission too, and
// the endpoint answers an empty password without `generatePassword: true`
// with a 400 (its contract for other callers, unchanged).
bodyExtra: { generatePassword: true },
params: [
// The endpoint requires email OR phone (phone-only users get a
// placeholder address; requires auth.plugins.phoneNumber).
Expand All @@ -231,13 +241,6 @@ export const SysUser = ObjectSchema.create({
requiresFeature: 'phoneNumber',
},
{ field: 'name', required: false },
{
name: 'generatePassword',
label: 'Generate Temporary Password',
type: 'boolean',
required: false,
defaultValue: true,
},
{ name: 'password', label: 'Password (leave empty to generate)', type: 'text', required: false },
{
name: 'mustChangePassword',
Expand Down Expand Up @@ -281,14 +284,11 @@ export const SysUser = ObjectSchema.create({
recordIdParam: 'userId',
successMessage: 'Password updated',
refreshAfter: false,
// Same one rule as `create_user` above: the new-password field's label
// ("leave empty to generate") is the whole instruction, and
// `generatePassword` rides as a constant so an empty field generates.
bodyExtra: { generatePassword: true },
params: [
{
name: 'generatePassword',
label: 'Generate Temporary Password',
type: 'boolean',
required: false,
defaultValue: false,
},
{ name: 'newPassword', label: 'New Password (leave empty to generate)', type: 'text', required: false },
{
name: 'mustChangePassword',
Expand Down
129 changes: 129 additions & 0 deletions packages/plugins/plugin-auth/src/admin-user-endpoints.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { describe, it, expect, vi } from 'vitest';
import { assertEngineUpdateDispatch } from '@objectstack/objectql';
import { SysUser } from '@objectstack/platform-objects/identity';
import {
runAdminCreateUser,
runAdminSetUserPassword,
Expand Down Expand Up @@ -146,9 +147,13 @@ describe('runAdminCreateUser', () => {
});

it('rejects when neither password nor generatePassword is provided', async () => {
// CONTROL for the Setup dialog's one password rule: a caller that is not
// the dialog and sends neither still gets the 400 — the endpoint's
// contract did not move when the dialog started sending the constant.
const m = makeDeps();
const res = await runAdminCreateUser(m.deps, makeRequest({ email: 'a@b.co' }), ACTOR);
expect(res.status).toBe(400);
expect(res.body.error?.code).toBe('INVALID_REQUEST');
expect(m.createUser).not.toHaveBeenCalled();
});

Expand Down Expand Up @@ -703,6 +708,130 @@ describe('runAdminSetUserPassword', () => {
expect(meta.event).toBe('user.admin_password_set');
expect(meta.passwordGenerated).toBe(true);
});

it('prefers an explicit newPassword over generatePassword (the dialog sends both)', async () => {
const m = makeDeps();
const res = await runAdminSetUserPassword(
m.deps,
makeRequest({ userId: 'user-9', newPassword: 'Str0ng!Pass', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
expect(m.authCtx.internalAdapter.updatePassword).toHaveBeenCalledWith('user-9', 'hashed(Str0ng!Pass)');
expect((res.body.data as any).temporaryPassword).toBeUndefined();
});

it('generates when generatePassword is true and newPassword is empty', async () => {
const m = makeDeps();
const res = await runAdminSetUserPassword(
m.deps,
makeRequest({ userId: 'user-9', newPassword: '', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const temp = (res.body.data as any).temporaryPassword as string;
expect(typeof temp).toBe('string');
expect(m.authCtx.internalAdapter.updatePassword).toHaveBeenCalledWith('user-9', `hashed(${temp})`);
});

it('rejects when neither newPassword nor generatePassword is provided', async () => {
// CONTROL, as for create-user: a caller that is not the dialog and sends
// neither still gets the 400, and nothing is written.
const m = makeDeps();
const res = await runAdminSetUserPassword(m.deps, makeRequest({ userId: 'user-9' }), ACTOR);
expect(res.status).toBe(400);
expect(res.body.error?.code).toBe('INVALID_REQUEST');
expect(m.authCtx.internalAdapter.updatePassword).not.toHaveBeenCalled();
expect(m.authCtx.internalAdapter.createAccount).not.toHaveBeenCalled();
});
});

// ── The Setup dialogs: the password field is the one rule ──────────────────
//
// `sys_user`'s `create_user` and `set_user_password` actions are this
// endpoint's first-party callers. Their dialog offers one rule — the password
// field's own label, "leave empty to generate" — so `generatePassword` is not a
// control the admin sees: it rides in `bodyExtra` as a constant, and the
// explicit-wins rule above turns that into the label's behaviour. A ticked box
// beside a typed password was a control the server ignored.
//
// These pins read the DECLARED actions and compose the request body the way
// the console does for a `type: 'api'` action: the values the dialog collected,
// the `recordIdParam`, then `bodyExtra` merged last (the spec's documented
// semantics for that key). The dialog submits only the params it shows, so a
// param left out of `params` is never on the wire — `bodyExtra` is the one
// place a constant the admin does not see can come from.
describe('Setup dialogs: one password rule (sys_user create_user / set_user_password)', () => {
function declaredAction(name: string) {
const action = (SysUser.actions ?? []).find((a) => a.name === name);
if (!action) throw new Error(`sys_user declares no action named "${name}"`);
return action;
}

function dialogBody(name: string, collected: Record<string, unknown>, recordId?: string) {
const action = declaredAction(name);
const body: Record<string, unknown> = { ...collected };
if (action.recordIdParam && recordId !== undefined) body[action.recordIdParam] = recordId;
return { ...body, ...(action.bodyExtra ?? {}) };
}

const DIALOGS = [
{
action: 'create_user',
explicitKey: 'password',
base: { email: 'a@b.co', mustChangePassword: true },
recordId: undefined,
run: (m: ReturnType<typeof makeDeps>, body: Record<string, unknown>) =>
runAdminCreateUser(m.deps, makeRequest(body), ACTOR),
appliedPassword: (m: ReturnType<typeof makeDeps>) =>
callsOf(m.createUser).map((c) => (c[0] as unknown as { body: { password: string } }).body.password),
},
{
action: 'set_user_password',
explicitKey: 'newPassword',
base: { mustChangePassword: true },
recordId: 'user-9',
run: (m: ReturnType<typeof makeDeps>, body: Record<string, unknown>) =>
runAdminSetUserPassword(m.deps, makeRequest(body), ACTOR),
appliedPassword: (m: ReturnType<typeof makeDeps>) =>
callsOf(m.authCtx.password.hash).map((c) => c[0]),
},
] as const;

for (const d of DIALOGS) {
it(`${d.action}: offers no generatePassword control and sends it as a constant`, () => {
const action = declaredAction(d.action);
const offered = (action.params ?? []).map((p) => p.name ?? p.field);
expect(offered).toContain(d.explicitKey);
expect(offered).not.toContain('generatePassword');
expect(action.bodyExtra?.generatePassword).toBe(true);
});

it(`${d.action}: a typed password is the one applied, and nothing is generated`, async () => {
const m = makeDeps();
const body = dialogBody(d.action, { ...d.base, [d.explicitKey]: 'Explicit1!' }, d.recordId);
const res = await d.run(m, body);
expect(res.status).toBe(200);
expect(d.appliedPassword(m)).toEqual(['Explicit1!']);
expect((res.body.data as any).temporaryPassword).toBeUndefined();
});

for (const [shape, collected] of [
['left untouched (absent)', {}],
['typed then cleared (empty string)', { [d.explicitKey]: '' }],
] as const) {
it(`${d.action}: a password ${shape} generates a temporary one, returned once`, async () => {
const m = makeDeps();
const body = dialogBody(d.action, { ...d.base, ...collected }, d.recordId);
const res = await d.run(m, body);
expect(res.status).toBe(200);
const temp = (res.body.data as any).temporaryPassword as string;
expect(typeof temp).toBe('string');
expect(d.appliedPassword(m)).toEqual([temp]);
expectNoPasswordLeak(m, temp);
});
}
}
});

// ── The ledger row records the admin's decisions, never a field value ──────
Expand Down
Loading