Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (users): Add a --create-user console command that provisions an account with a role, so scripted deployments get an administrator without a browser sign-up and rotate its password with --new-password

Rostislav Dugin47b6e3996803
diff --git a/README.md b/README.md
index 770e2b40..10d6a616 100644
--- a/README.md
+++ b/README.md
@@ -277,6 +277,14 @@ docker exec -it databasus ./main --list-admins
The output names every administrator account with its email address, display name, creation date and active state, and marks the one the instance recognizes as its administrator. It prints no password material.
+To provision an account without signing up in the browser, for example from a deployment script, create it from the console:
+
+```bash
+docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin
+```
+
+`--role` is `admin` or `member`, the password needs at least 8 characters, and `--name` optionally sets the display name. On an instance that holds no account yet, the first account must use `--role=admin` and administers the instance. Running the command again for the same account changes nothing, so a deployment can run it on every rollout; rotate the password with `--new-password`.
+
### 💾 Backuping Databasus itself
After installation, it is also recommended to <a href="https://databasus.com/faq#backup-databasus">backup your Databasus itself</a> or, at least, to copy secret key used for encryption (30 seconds is needed). So you are able to restore from your encrypted backups if you lose access to the server with Databasus or it is corrupted.
diff --git a/assets/readme/README.es.md b/assets/readme/README.es.md
index 1a2855b7..95ce038f 100644
--- a/assets/readme/README.es.md
+++ b/assets/readme/README.es.md
@@ -277,6 +277,14 @@ docker exec -it databasus ./main --list-admins
La salida nombra cada cuenta de administrador con su correo electrónico, nombre visible, fecha de creación y estado de actividad, y marca la que la instancia reconoce como su administrador. No imprime ninguna contraseña ni su hash.
+Para dar de alta una cuenta sin registrarse en el navegador, por ejemplo desde un script de despliegue, créela desde la consola:
+
+```bash
+docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin
+```
+
+`--role` admite `admin` o `member`, la contraseña necesita al menos 8 caracteres y `--name` fija, si lo desea, el nombre visible. En una instancia que todavía no tiene ninguna cuenta, la primera debe usar `--role=admin` y pasa a administrar la instancia. Repetir el comando para la misma cuenta no cambia nada, así que puede incluirlo en cada despliegue; para cambiar la contraseña, use `--new-password`.
+
### 💾 Respaldar el propio Databasus
Después de instalarlo, conviene también <a href="https://databasus.com/es/faq/#backup-databasus">respaldar su propio Databasus</a> o, al menos, copiar la clave secreta que se usa para el cifrado (bastan 30 segundos). Así podrá restaurar desde sus copias cifradas si pierde el acceso al servidor con Databasus o si este se corrompe.
diff --git a/assets/readme/README.fr.md b/assets/readme/README.fr.md
index cd4056ed..3c256521 100644
--- a/assets/readme/README.fr.md
+++ b/assets/readme/README.fr.md
@@ -277,6 +277,14 @@ docker exec -it databasus ./main --list-admins
La sortie nomme chaque compte administrateur avec son adresse e-mail, son nom affiché, sa date de création et son état d'activité, et marque celui que l'instance reconnaît comme son administrateur. Aucun mot de passe ni empreinte de mot de passe n'est affiché.
+Pour ouvrir un compte sans passer par l'inscription dans le navigateur, par exemple depuis un script de déploiement, créez-le depuis la console :
+
+```bash
+docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin
+```
+
+`--role` vaut `admin` ou `member`, le mot de passe doit compter au moins 8 caractères, et `--name` permet de définir un nom affiché. Sur une instance qui n'a encore aucun compte, le premier doit utiliser `--role=admin` et administre l'instance. Relancer la commande pour le même compte ne change rien : un déploiement peut donc l'exécuter à chaque mise en production. Pour renouveler le mot de passe, utilisez `--new-password`.
+
### 💾 Sauvegarder Databasus lui-même
Après l'installation, il est aussi recommandé de <a href="https://databasus.com/fr/faq/#backup-databasus">sauvegarder Databasus lui-même</a> ou, au minimum, de copier la clé secrète utilisée pour le chiffrement (30 secondes suffisent). Vous pourrez ainsi restaurer vos sauvegardes chiffrées si vous perdez l'accès au serveur qui héberge Databasus ou s'il est corrompu.
diff --git a/assets/readme/README.pt.md b/assets/readme/README.pt.md
index 61a5c71a..0c4d7252 100644
--- a/assets/readme/README.pt.md
+++ b/assets/readme/README.pt.md
@@ -277,6 +277,14 @@ docker exec -it databasus ./main --list-admins
A saída nomeia cada conta de administrador com seu e-mail, nome de exibição, data de criação e estado de atividade, e marca aquela que a instância reconhece como seu administrador. Nenhuma senha ou hash de senha é impresso.
+Para criar uma conta sem passar pelo cadastro no navegador, por exemplo a partir de um script de deploy, use o console:
+
+```bash
+docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin
+```
+
+`--role` aceita `admin` ou `member`, a senha precisa ter pelo menos 8 caracteres e `--name` define, se quiser, o nome de exibição. Em uma instância que ainda não tem nenhuma conta, a primeira precisa usar `--role=admin` e passa a administrar a instância. Rodar o comando de novo para a mesma conta não altera nada, então um deploy pode executá-lo a cada rollout; para trocar a senha, use `--new-password`.
+
### 💾 Fazer backup do próprio Databasus
Depois de instalar, também é recomendável <a href="https://databasus.com/pt/faq/#backup-databasus">fazer backup do próprio Databasus</a> ou, no mínimo, copiar a chave secreta usada na criptografia (leva 30 segundos). Assim você consegue restaurar a partir dos seus backups criptografados se perder o acesso ao servidor com o Databasus ou se ele for corrompido.
diff --git a/assets/readme/README.ru.md b/assets/readme/README.ru.md
index 4491f0b1..574ddb0c 100644
--- a/assets/readme/README.ru.md
+++ b/assets/readme/README.ru.md
@@ -277,6 +277,14 @@ docker exec -it databasus ./main --list-admins
В выводе перечислены все учетные записи администраторов с их email, именем, датой создания и состоянием активности, а та, которую инстанс считает своим администратором, отмечена отдельно. Пароли и их хеши не выводятся.
+Чтобы завести учетную запись без регистрации в браузере, например из скрипта деплоя, создайте ее из консоли:
+
+```bash
+docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin
+```
+
+`--role` принимает `admin` или `member`, пароль должен быть не короче 8 символов, а `--name` задает отображаемое имя, если оно нужно. На инстансе, где еще нет ни одной учетной записи, первая должна создаваться с `--role=admin` и станет администратором инстанса. Повторный запуск для той же учетной записи ничего не меняет, поэтому команду можно выполнять при каждом деплое; пароль меняйте через `--new-password`.
+
### 💾 Бекап самого Databasus
После установки стоит еще и <a href="https://databasus.com/ru/faq/#backup-databasus">забекапить сам Databasus</a> или, как минимум, скопировать секретный ключ шифрования (это займет 30 секунд). Тогда вы сможете восстановиться из своих зашифрованных бекапов, даже если потеряете доступ к серверу с Databasus или он выйдет из строя.
diff --git a/assets/readme/README.zh.md b/assets/readme/README.zh.md
index 49574338..d4765f22 100644
--- a/assets/readme/README.zh.md
+++ b/assets/readme/README.zh.md
@@ -277,6 +277,14 @@ docker exec -it databasus ./main --list-admins
输出会列出每个管理员账户的邮箱、显示名称、创建日期和活动状态,并标记实例所认可的管理员。不会输出任何密码或密码哈希。
+如果不想在浏览器里注册,比如要用部署脚本开通账户,可以在控制台直接创建:
+
+```bash
+docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin
+```
+
+`--role` 取 `admin` 或 `member`,密码至少 8 个字符,`--name` 可选,用来设置显示名称。如果实例上还没有任何账户,第一个账户必须使用 `--role=admin`,它就是该实例的管理员。对同一账户再次运行命令不会做任何改动,所以部署流程可以在每次上线时都运行它;要更换密码,请使用 `--new-password`。
+
### 💾 给 Databasus 自身做备份
装好之后,建议再<a href="https://databasus.com/zh/faq/#backup-databasus">给 Databasus 自身做一次备份</a>,至少也要把用于加密的密钥复制一份(只要 30 秒)。这样即使装有 Databasus 的服务器丢失访问权限或者损坏,你依然能从加密备份中恢复。
diff --git a/backend/cmd/main.go b/backend/cmd/main.go
index 25178134..bc1c2a14 100644
--- a/backend/cmd/main.go
+++ b/backend/cmd/main.go
@@ -45,6 +45,7 @@ import (
task_cancellation "databasus-backend/internal/features/tasks/cancellation"
"databasus-backend/internal/features/telemetry"
users_controllers "databasus-backend/internal/features/users/controllers"
+ users_dto "databasus-backend/internal/features/users/dto"
users_middleware "databasus-backend/internal/features/users/middleware"
users_services "databasus-backend/internal/features/users/services"
verification_agents "databasus-backend/internal/features/verification/agents"
@@ -108,6 +109,8 @@ func main() {
listAdminsIfRequested(ctx, log, commandLineOptions)
+ createUserIfRequested(ctx, log, commandLineOptions)
+
resetPasswordIfRequested(ctx, log, commandLineOptions)
disableTwoFactorAuthIfRequested(ctx, log, commandLineOptions)
@@ -147,8 +150,12 @@ type commandLineOptions struct {
shouldTestStorage bool
shouldListAdmins bool
shouldDisableTwoFactor bool
+ shouldCreateUser bool
newPassword string
- passwordResetEmail string
+ email string
+ newUserPassword string
+ newUserRole string
+ newUserName string
}
func parseCommandLineOptions() commandLineOptions {
@@ -165,16 +172,24 @@ func parseCommandLineOptions() commandLineOptions {
false,
"Stop requiring an emailed code at sign-in",
)
+ shouldCreateUser := flag.Bool("create-user", false, "Create an account with the given email, password and role")
newPassword := flag.String("new-password", "", "Set a new password for the user")
- passwordResetEmail := flag.String("email", "", "Email of the user to reset password")
+ email := flag.String("email", "", "Email of the user to create or to reset password")
+ newUserPassword := flag.String("password", "", "Password of the account --create-user creates")
+ newUserRole := flag.String("role", "", "Role of the account --create-user creates: admin or member")
+ newUserName := flag.String("name", "", "Display name of the account --create-user creates")
flag.Parse()
return commandLineOptions{
shouldTestStorage: *shouldTestStorage,
shouldListAdmins: *shouldListAdmins,
shouldDisableTwoFactor: *shouldDisableTwoFactor,
+ shouldCreateUser: *shouldCreateUser,
newPassword: *newPassword,
- passwordResetEmail: *passwordResetEmail,
+ email: *email,
+ newUserPassword: *newUserPassword,
+ newUserRole: *newUserRole,
+ newUserName: *newUserName,
}
}
@@ -203,6 +218,50 @@ func listAdminsIfRequested(
logger.ExitAfterFlush(0)
}
+// Runs ahead of the password reset, so a --new-password passed by mistake is
+// refused here instead of resetting some account's password.
+func createUserIfRequested(
+ ctx context.Context,
+ log *slog.Logger,
+ commandLineOptions commandLineOptions,
+) {
+ if !commandLineOptions.shouldCreateUser {
+ return
+ }
+
+ if commandLineOptions.newPassword != "" {
+ log.ErrorContext(ctx, "--create-user takes the password in --password, not --new-password")
+ logger.ExitAfterFlush(1)
+ }
+
+ if commandLineOptions.email == "" {
+ log.ErrorContext(ctx, "no email provided, pass one via --email=\"[email protected]\"")
+ logger.ExitAfterFlush(1)
+ }
+
+ audit_logs.SetupDependencies()
+
+ outcome, err := users_services.GetUserService().CreateUserFromConsole(
+ ctx,
+ &users_dto.CreateConsoleAccountRequest{
+ Email: commandLineOptions.email,
+ Password: commandLineOptions.newUserPassword,
+ Role: commandLineOptions.newUserRole,
+ Name: commandLineOptions.newUserName,
+ },
+ )
+ if err != nil {
+ log.ErrorContext(ctx, "failed to create the account", "error", err)
+ logger.ExitAfterFlush(1)
+ }
+
+ // Printed rather than logged, like the administrator listing: the operator
+ // needs the address, and the logger masks it.
+ fmt.Println(users_services.RenderConsoleAccountOutcome(outcome))
+
+ logger.ExitAfterFlush(0)
+}
+
func disableTwoFactorAuthIfRequested(
ctx context.Context,
log *slog.Logger,
@@ -241,14 +300,14 @@ func resetPasswordIfRequested(
audit_logs.SetupDependencies()
log.InfoContext(ctx, "found reset password command, resetting password")
- if commandLineOptions.passwordResetEmail == "" {
+ if commandLineOptions.email == "" {
log.InfoContext(ctx, "no email provided, pass one via --email=\"[email protected]\"")
logger.ExitAfterFlush(1)
}
resetPassword(
ctx,
- commandLineOptions.passwordResetEmail,
+ commandLineOptions.email,
commandLineOptions.newPassword,
log,
)
diff --git a/backend/internal/features/users/dto/dto.go b/backend/internal/features/users/dto/dto.go
index 16268c5f..0c5922d4 100644
--- a/backend/internal/features/users/dto/dto.go
+++ b/backend/internal/features/users/dto/dto.go
@@ -15,6 +15,15 @@ type SignUpRequestDTO struct {
CloudflareTurnstileToken *string `json:"cloudflareTurnstileToken"`
}
+// CreateConsoleAccountRequest carries the console flags as typed: the role is
+// still the operator's text, so the service can refuse what it cannot parse.
+type CreateConsoleAccountRequest struct {
+ Email string
+ Password string
+ Role string
+ Name string
+}
+
type SignInRequestDTO struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
diff --git a/backend/internal/features/users/errors/errors.go b/backend/internal/features/users/errors/errors.go
index a7dd06a0..c5161f4f 100644
--- a/backend/internal/features/users/errors/errors.go
+++ b/backend/internal/features/users/errors/errors.go
@@ -1,9 +1,33 @@
package users_errors
-import "errors"
+import (
+ "errors"
+ "fmt"
+
+ users_models "databasus-backend/internal/features/users/models"
+)
var ErrInsufficientPermissionsToInviteUsers = errors.New("insufficient permissions to invite users")
+var ErrPasswordTooShort = fmt.Errorf(
+ "the password must be at least %d characters long",
+ users_models.MinPasswordLength,
+)
+
+var (
+ ErrConsoleAccountEmailInvalid = errors.New("the email is not a valid email address")
+ ErrConsoleAccountRoleInvalid = errors.New("the role must be admin or member")
+ // The first account administers the instance, so a member there would leave
+ // nobody able to grant the administrator role.
+ ErrConsoleAccountFirstMustBeAdmin = errors.New(
+ "this instance has no account yet, and its first account administers it: create it with the admin role",
+ )
+ ErrConsoleAccountExistsInAnotherState = errors.New(
+ "an account with this email already exists with another role, is deactivated, " +
+ "has not completed sign-up or has no password; nothing changed",
+ )
+)
+
var (
ErrEmailNotConfigured = errors.New("the instance has no mail server configured")
ErrAdminEmailMissing = errors.New("your account has no valid email address to send a test email to")
diff --git a/backend/internal/features/users/models/user.go b/backend/internal/features/users/models/user.go
index 4abe4f4d..3cb0bb16 100644
--- a/backend/internal/features/users/models/user.go
+++ b/backend/internal/features/users/models/user.go
@@ -8,6 +8,10 @@ import (
users_enums "databasus-backend/internal/features/users/enums"
)
+// MinPasswordLength applies to every way a password is set. The request DTOs
+// repeat it as a literal min=8, because a struct tag cannot reference a constant.
+const MinPasswordLength = 8
+
type User struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
diff --git a/backend/internal/features/users/services/console_account.go b/backend/internal/features/users/services/console_account.go
new file mode 100644
index 00000000..983ed6cd
--- /dev/null
+++ b/backend/internal/features/users/services/console_account.go
@@ -0,0 +1,182 @@
+package users_services
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/go-playground/validator/v10"
+ "github.com/google/uuid"
+ "golang.org/x/crypto/bcrypt"
+
+ audit_logs_models "databasus-backend/internal/features/audit_logs/models"
+ users_dto "databasus-backend/internal/features/users/dto"
+ users_enums "databasus-backend/internal/features/users/enums"
+ users_errors "databasus-backend/internal/features/users/errors"
+ users_models "databasus-backend/internal/features/users/models"
+)
+
+// The library and the tag the registration binding evaluates, so the console
+// accepts and refuses exactly the addresses sign-up does.
+var consoleAccountValidator = validator.New()
+
+type ConsoleAccountOutcome struct {
+ User *users_models.User
+ IsCreated bool
+}
+
+// CreateUserFromConsole provisions an account from inside the running instance,
+// so it skips the registration policy and may hand out the administrator role
+// without the bootstrap administrator: whoever runs it can already reset that
+// account's password. It never changes an existing account, and an exact match
+// is reported rather than refused, so a deployment can run it on every rollout.
+//
+// Nothing here logs. The rendered outcome and the returned errors are all the
+// command emits, which is what keeps the password out of its output.
+func (s *UserService) CreateUserFromConsole(
+ ctx context.Context,
+ request *users_dto.CreateConsoleAccountRequest,
+) (*ConsoleAccountOutcome, error) {
+ role, err := validateConsoleAccountRequest(request)
+ if err != nil {
+ return nil, err
+ }
+
+ existingUser, err := s.userRepository.GetUserByEmail(ctx, request.Email)
+ if err != nil {
+ return nil, fmt.Errorf("failed to check existing user: %w", err)
+ }
+
+ if existingUser != nil {
+ if !isSameConsoleAccount(existingUser, role) {
+ return nil, users_errors.ErrConsoleAccountExistsInAnotherState
+ }
+
+ return &ConsoleAccountOutcome{User: existingUser, IsCreated: false}, nil
+ }
+
+ // An instance never becomes empty again once it holds an account, so a
+ // registration landing after this check can only make the refusal stricter
+ // than needed, never let a member take the instance.
+ isInstanceUnclaimed, err := s.isInstanceUnclaimed()
+ if err != nil {
+ return nil, err
+ }
+
+ if isInstanceUnclaimed && role != users_enums.UserRoleAdmin {
+ return nil, users_errors.ErrConsoleAccountFirstMustBeAdmin
+ }
+
+ hashedPassword, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return nil, fmt.Errorf("failed to hash password: %w", err)
+ }
+
+ hashedPasswordStr := string(hashedPassword)
+ name := getConsoleAccountName(request)
+
+ user, err := s.createAccountClaimingEmptyInstance(
+ ctx,
+ allowConsoleAccount,
+ func(isTakingTheInstance bool) *users_models.User {
+ return buildConsoleUser(request.Email, name, hashedPasswordStr, role, isTakingTheInstance)
+ },
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ s.writeAuditLog(ctx, audit_logs_models.AuditEntry{
+ Message: fmt.Sprintf(
+ "Account created from the host console: %s (role %s)",
+ user.Email,
+ user.Role,
+ ),
+ UserID: &user.ID,
+ WorkspaceID: nil,
+ })
+
+ s.writeInstanceClaimedAuditLog(ctx, user)
+
+ return &ConsoleAccountOutcome{User: user, IsCreated: true}, nil
+}
+
+// RenderConsoleAccountOutcome is the line the operator reads. A rerun says the
+// password was not changed, because that is how a deployment learns a rerun did
+// not rotate its secret.
+func RenderConsoleAccountOutcome(outcome *ConsoleAccountOutcome) string {
+ user := outcome.User
+
+ if !outcome.IsCreated {
+ return fmt.Sprintf(
+ "Account %s already exists with the %s role. Nothing changed, and its password was not changed.",
+ user.Email,
+ user.Role,
+ )
+ }
+
+ line := fmt.Sprintf("Created account %s with the %s role.", user.Email, user.Role)
+ if user.IsRootAdmin {
+ line += " It is the administrator of this instance."
+ }
+
+ return line
+}
+
+func validateConsoleAccountRequest(
+ request *users_dto.CreateConsoleAccountRequest,
+) (users_enums.UserRole, error) {
+ if err := consoleAccountValidator.Var(request.Email, "required,email"); err != nil {
+ return "", users_errors.ErrConsoleAccountEmailInvalid
+ }
+
+ if !isPasswordLongEnough(request.Password) {
+ return "", users_errors.ErrPasswordTooShort
+ }
+
+ role := users_enums.UserRole(strings.ToUpper(request.Role))
+ if !role.IsValid() {
+ return "", users_errors.ErrConsoleAccountRoleInvalid
+ }
+
+ return role, nil
+}
+
+// A password-less account counts as another state: reporting it as ready would
+// tell a deployment the address signs in with a password it does not hold.
+func isSameConsoleAccount(user *users_models.User, role users_enums.UserRole) bool {
+ return user.IsActiveUser() && user.Role == role && user.HasPassword()
+}
+
+func getConsoleAccountName(request *users_dto.CreateConsoleAccountRequest) string {
+ if request.Name != "" {
+ return request.Name
+ }
+
+ localPart, _, _ := strings.Cut(request.Email, "@")
+
+ return localPart
+}
+
+func allowConsoleAccount(context.Context) error {
+ return nil
+}
+
+func buildConsoleUser(
+ email, name, hashedPassword string,
+ role users_enums.UserRole,
+ isTakingTheInstance bool,
+) *users_models.User {
+ return &users_models.User{
+ ID: uuid.New(),
+ Email: email,
+ Name: name,
+ HashedPassword: &hashedPassword,
+ PasswordCreationTime: time.Now().UTC(),
+ Role: role,
+ Status: users_enums.UserStatusActive,
+ IsRootAdmin: isTakingTheInstance,
+ CreatedAt: time.Now().UTC(),
+ }
+}
diff --git a/backend/internal/features/users/services/console_account_test.go b/backend/internal/features/users/services/console_account_test.go
new file mode 100644
index 00000000..be2677d5
--- /dev/null
+++ b/backend/internal/features/users/services/console_account_test.go
@@ -0,0 +1,390 @@
+package users_services_test
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ users_dto "databasus-backend/internal/features/users/dto"
+ users_enums "databasus-backend/internal/features/users/enums"
+ users_errors "databasus-backend/internal/features/users/errors"
+ users_models "databasus-backend/internal/features/users/models"
+ users_repositories "databasus-backend/internal/features/users/repositories"
+ users_services "databasus-backend/internal/features/users/services"
+ users_testing "databasus-backend/internal/features/users/testing"
+ "databasus-backend/internal/storage"
+)
+
+const consoleAccountPassword = "console-password-123"
+
+func Test_CreateUserFromConsole_WhenInstanceIsEmpty_CreatesTheBootstrapAdministrator(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ users_testing.DeleteAllUsers()
+ recorder := installAuditLogRecorder()
+ email := newConsoleEmail()
+
+ outcome, err := createConsoleAccount(t, email, consoleAccountPassword, "admin")
+ require.NoError(t, err)
+
+ assert.True(t, outcome.IsCreated)
+ assert.True(t, outcome.User.IsRootAdmin)
+ assert.Equal(t, users_enums.UserRoleAdmin, outcome.User.Role)
+ assert.Contains(t, users_services.RenderConsoleAccountOutcome(outcome), "administrator of this instance")
+ assert.True(t, recorder.HasEntryContaining("created from the host console", email, "ADMIN"))
+ assert.True(t, recorder.HasEntryContaining("First account on the instance now administers it", email))
+
+ listing, err := users_services.GetManagementService().RenderAdminListing(t.Context())
+ require.NoError(t, err)
+ assert.Contains(t, adminLineFor(t, listing, email), "bootstrap administrator")
+
+ registered, err := users_services.GetUserService().SignUp(t.Context(), &users_dto.SignUpRequestDTO{
+ Email: newConsoleEmail(),
+ Password: "registered-password-123",
+ Name: "Registered",
+ })
+ require.NoError(t, err)
+ assert.Equal(t, users_enums.UserRoleMember, registered.Role)
+ assert.False(t, registered.IsRootAdmin)
+}
+
+func Test_CreateUserFromConsole_WhenInstanceIsEmptyAndRoleIsMember_RefusesAndCreatesNothing(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ users_testing.DeleteAllUsers()
+ installAuditLogRecorder()
+
+ _, err := createConsoleAccount(t, newConsoleEmail(), consoleAccountPassword, "member")
+
+ require.ErrorIs(t, err, users_errors.ErrConsoleAccountFirstMustBeAdmin)
+
+ hasAnyUser, err := users_services.GetUserService().HasAnyUser()
+ require.NoError(t, err)
+ assert.False(t, hasAnyUser)
+}
+
+func Test_CreateUserFromConsole_WhenRegistrationClaimsTheEmptyInstanceConcurrently_LeavesOneBootstrapAdministrator(
+ t *testing.T,
+) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ installAuditLogRecorder()
+
+ for range 5 {
+ users_testing.DeleteAllUsers()
+
+ consoleEmail := newConsoleEmail()
+ registeredEmail := newConsoleEmail()
+
+ var (
+ start sync.WaitGroup
+ done sync.WaitGroup
+ consoleError error
+ signUpError error
+ )
+ start.Add(1)
+ done.Add(2)
+
+ go func() {
+ defer done.Done()
+ start.Wait()
+ _, consoleError = createConsoleAccount(t, consoleEmail, consoleAccountPassword, "admin")
+ }()
+ go func() {
+ defer done.Done()
+ start.Wait()
+ _, signUpError = users_services.GetUserService().SignUp(t.Context(), &users_dto.SignUpRequestDTO{
+ Email: registeredEmail,
+ Password: "registered-password-123",
+ Name: "Registered",
+ })
+ }()
+
+ start.Done()
+ done.Wait()
+
+ require.NoError(t, consoleError)
+ require.NoError(t, signUpError)
+
+ assert.Equal(t, int64(1), countBootstrapAdministrators(t))
+
+ consoleUser := getUserByEmail(t, consoleEmail)
+ registeredUser := getUserByEmail(t, registeredEmail)
+ assert.Equal(t, users_enums.UserRoleAdmin, consoleUser.Role)
+ assert.NotEqual(t, consoleUser.IsRootAdmin, registeredUser.IsRootAdmin)
+ }
+}
+
+func Test_CreateUserFromConsole_WhenInstanceHoldsAccounts_CreatesAnOrdinaryAdministratorThatSignsIn(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ ensureInstanceIsClaimed(t)
+ recorder := installAuditLogRecorder()
+ email := newConsoleEmail()
+
+ outcome, err := createConsoleAccount(t, email, consoleAccountPassword, "ADMIN")
+ require.NoError(t, err)
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), outcome.User.ID) })
+
+ assert.True(t, outcome.IsCreated)
+ assert.False(t, outcome.User.IsRootAdmin)
+ assert.Equal(t, users_enums.UserRoleAdmin, outcome.User.Role)
+ assert.NotContains(t, users_services.RenderConsoleAccountOutcome(outcome), "administrator of this instance")
+ assert.True(t, recorder.HasEntryContaining("created from the host console", email, "ADMIN"))
+ assert.False(t, recorder.HasEntryContaining("First account on the instance"))
+
+ require.NoError(t, signIn(t, email, consoleAccountPassword))
+}
+
+func Test_CreateUserFromConsole_WhenExternalRegistrationIsDisabled_CreatesTheMember(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ ensureInstanceIsClaimed(t)
+ users_testing.DisableExternalRegistrations(t.Context())
+ t.Cleanup(func() { users_testing.ResetSettingsToDefaults(context.Background()) })
+ installAuditLogRecorder()
+ email := newConsoleEmail()
+
+ outcome, err := createConsoleAccount(t, email, consoleAccountPassword, "member")
+ require.NoError(t, err)
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), outcome.User.ID) })
+
+ assert.Equal(t, users_enums.UserRoleMember, outcome.User.Role)
+ require.NoError(t, signIn(t, email, consoleAccountPassword))
+}
+
+func Test_CreateUserFromConsole_WhenPasswordIsResetFromTheConsole_SignsInOnlyWithTheNewPassword(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ ensureInstanceIsClaimed(t)
+ installAuditLogRecorder()
+ email := newConsoleEmail()
+
+ outcome, err := createConsoleAccount(t, email, consoleAccountPassword, "admin")
+ require.NoError(t, err)
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), outcome.User.ID) })
+
+ require.NoError(t, users_services.GetUserService().ChangeUserPasswordByEmail(
+ t.Context(),
+ email,
+ "rotated-password-456",
+ ))
+
+ require.NoError(t, signIn(t, email, "rotated-password-456"))
+ require.Error(t, signIn(t, email, consoleAccountPassword))
+}
+
+func Test_CreateUserFromConsole_WhenNameIsOmitted_NamesTheAccountAfterTheLocalPart(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ ensureInstanceIsClaimed(t)
+ installAuditLogRecorder()
+ localPart := "ops-" + uuid.New().String()[:8]
+
+ outcome, err := createConsoleAccount(t, localPart+"@example.com", consoleAccountPassword, "member")
+ require.NoError(t, err)
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), outcome.User.ID) })
+
+ assert.Equal(t, localPart, outcome.User.Name)
+}
+
+func Test_CreateUserFromConsole_WithInvalidInput_RefusesAndCreatesNothing(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ ensureInstanceIsClaimed(t)
+ installAuditLogRecorder()
+
+ testCases := []struct {
+ name string
+ email string
+ password string
+ role string
+ expected error
+ }{
+ {"not an email address", "ops", consoleAccountPassword, "admin", users_errors.ErrConsoleAccountEmailInvalid},
+ {"seven-character password", newConsoleEmail(), "seven77", "admin", users_errors.ErrPasswordTooShort},
+ {"missing role", newConsoleEmail(), consoleAccountPassword, "", users_errors.ErrConsoleAccountRoleInvalid},
+ {"unknown role", newConsoleEmail(), consoleAccountPassword, "owner", users_errors.ErrConsoleAccountRoleInvalid},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ _, err := createConsoleAccount(t, testCase.email, testCase.password, testCase.role)
+
+ require.ErrorIs(t, err, testCase.expected)
+ assert.Nil(t, findUserByEmail(t, testCase.email))
+ })
+ }
+}
+
+func Test_CreateUserFromConsole_WhenRunAgainForTheSameAccount_ChangesNothing(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ ensureInstanceIsClaimed(t)
+ recorder := installAuditLogRecorder()
+ email := newConsoleEmail()
+
+ created, err := createConsoleAccount(t, email, consoleAccountPassword, "admin")
+ require.NoError(t, err)
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), created.User.ID) })
+ entriesAfterCreation := len(recorder.GetEntries())
+
+ rerun, err := createConsoleAccount(t, email, "another-password-456", "admin")
+ require.NoError(t, err)
+
+ assert.False(t, rerun.IsCreated)
+ assert.Equal(t, created.User.ID, rerun.User.ID)
+ assert.Contains(t, users_services.RenderConsoleAccountOutcome(rerun), "password was not changed")
+ assert.Len(t, recorder.GetEntries(), entriesAfterCreation)
+
+ require.NoError(t, signIn(t, email, consoleAccountPassword))
+ require.Error(t, signIn(t, email, "another-password-456"))
+}
+
+func Test_CreateUserFromConsole_WhenAddressBelongsToAnAccountInAnotherState_RefusesAndChangesNothing(
+ t *testing.T,
+) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ ensureInstanceIsClaimed(t)
+ installAuditLogRecorder()
+
+ githubOAuthID := "github-" + uuid.New().String()
+
+ testCases := []struct {
+ name string
+ requestedRole string
+ existing *users_models.User
+ }{
+ {"member asked to become administrator", "admin", newExistingUser(
+ users_enums.UserRoleMember, users_enums.UserStatusActive, new("old-hash"), nil,
+ )},
+ {"deactivated account", "member", newExistingUser(
+ users_enums.UserRoleMember, users_enums.UserStatusInactive, new("old-hash"), nil,
+ )},
+ {"invited account", "member", newExistingUser(
+ users_enums.UserRoleMember, users_enums.UserStatusInvited, nil, nil,
+ )},
+ {"administrator without a password", "admin", newExistingUser(
+ users_enums.UserRoleAdmin, users_enums.UserStatusActive, nil, &githubOAuthID,
+ )},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ require.NoError(t, (&users_repositories.UserRepository{}).CreateUser(testCase.existing))
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), testCase.existing.ID) })
+
+ _, err := createConsoleAccount(t, testCase.existing.Email, consoleAccountPassword, testCase.requestedRole)
+
+ require.ErrorIs(t, err, users_errors.ErrConsoleAccountExistsInAnotherState)
+
+ stored := getUserByEmail(t, testCase.existing.Email)
+ assert.Equal(t, testCase.existing.Role, stored.Role)
+ assert.Equal(t, testCase.existing.Status, stored.Status)
+ assert.Equal(t, testCase.existing.HashedPassword, stored.HashedPassword)
+ })
+ }
+}
+
+func Test_CreateUserFromConsole_InEveryOutcome_EmitsNoPasswordAndNoHash(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ ensureInstanceIsClaimed(t)
+ installAuditLogRecorder()
+ email := newConsoleEmail()
+ rerunPassword := "rerun-password-456"
+
+ created, err := createConsoleAccount(t, email, consoleAccountPassword, "admin")
+ require.NoError(t, err)
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), created.User.ID) })
+
+ rerun, err := createConsoleAccount(t, email, rerunPassword, "admin")
+ require.NoError(t, err)
+
+ _, refusal := createConsoleAccount(t, newConsoleEmail(), rerunPassword, "owner")
+ require.Error(t, refusal)
+
+ storedHash := *getUserByEmail(t, email).HashedPassword
+ outputs := []string{
+ users_services.RenderConsoleAccountOutcome(created),
+ users_services.RenderConsoleAccountOutcome(rerun),
+ refusal.Error(),
+ }
+
+ for _, output := range outputs {
+ assert.NotContains(t, output, consoleAccountPassword)
+ assert.NotContains(t, output, rerunPassword)
+ assert.NotContains(t, output, storedHash)
+ assert.NotContains(t, output, "$2a$")
+ }
+}
+
+func createConsoleAccount(
+ t *testing.T,
+ email, password, role string,
+) (*users_services.ConsoleAccountOutcome, error) {
+ t.Helper()
+
+ return users_services.GetUserService().CreateUserFromConsole(
+ t.Context(),
+ &users_dto.CreateConsoleAccountRequest{Email: email, Password: password, Role: role},
+ )
+}
+
+// The slot database is shared with earlier tests, so an instance that holds an
+// account is made rather than assumed.
+func ensureInstanceIsClaimed(t *testing.T) {
+ t.Helper()
+
+ hasAnyUser, err := users_services.GetUserService().HasAnyUser()
+ require.NoError(t, err)
+
+ if !hasAnyUser {
+ users_testing.RecreateInitialAdmin(t.Context())
+ }
+}
+
+func newConsoleEmail() string {
+ return "console-" + uuid.New().String() + "@example.com"
+}
+
+func newExistingUser(
+ role users_enums.UserRole,
+ status users_enums.UserStatus,
+ hashedPassword *string,
+ githubOAuthID *string,
+) *users_models.User {
+ return &users_models.User{
+ ID: uuid.New(),
+ Email: newConsoleEmail(),
+ Name: "Existing",
+ HashedPassword: hashedPassword,
+ PasswordCreationTime: time.Now().UTC(),
+ Role: role,
+ Status: status,
+ GitHubOAuthID: githubOAuthID,
+ CreatedAt: time.Now().UTC(),
+ }
+}
+
+func findUserByEmail(t *testing.T, email string) *users_models.User {
+ t.Helper()
+
+ user, err := users_services.GetUserService().GetUserByEmail(t.Context(), email)
+ require.NoError(t, err)
+
+ return user
+}
+
+func getUserByEmail(t *testing.T, email string) *users_models.User {
+ t.Helper()
+
+ user := findUserByEmail(t, email)
+ require.NotNil(t, user)
+
+ return user
+}
+
+func countBootstrapAdministrators(t *testing.T) int64 {
+ t.Helper()
+
+ var count int64
+ require.NoError(t, storage.GetDb().Model(&users_models.User{}).Where("is_root_admin").Count(&count).Error)
+
+ return count
+}
diff --git a/backend/internal/features/users/services/user_services.go b/backend/internal/features/users/services/user_services.go
index 7b640d41..3359eb0e 100644
--- a/backend/internal/features/users/services/user_services.go
+++ b/backend/internal/features/users/services/user_services.go
@@ -9,6 +9,7 @@ import (
"log/slog"
"net/http"
"time"
+ "unicode/utf8"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
@@ -110,6 +111,7 @@ func (s *UserService) SignUp(ctx context.Context, request *users_dto.SignUpReque
user, err := s.createAccountClaimingEmptyInstance(
ctx,
+ s.checkExternalRegistrationAllowed,
func(isTakingTheInstance bool) *users_models.User {
return buildRegisteredUser(request, hashedPasswordStr, isTakingTheInstance)
},
@@ -129,6 +131,11 @@ func (s *UserService) SignUp(ctx context.Context, request *users_dto.SignUpReque
return user, nil
}
+// Counted in runes, as the min=8 binding on the request DTOs counts them.
+func isPasswordLongEnough(password string) bool {
+ return utf8.RuneCountInString(password) >= users_models.MinPasswordLength
+}
+
func isBootstrapAdminTaken(err error) bool {
var pgError *pgconn.PgError
@@ -321,6 +328,10 @@ func (s *UserService) ChangeUserPasswordByEmail(ctx context.Context, email, newP
}
func (s *UserService) ChangeUserPassword(ctx context.Context, userID uuid.UUID, newPassword string) error {
+ if !isPasswordLongEnough(newPassword) {
+ return users_errors.ErrPasswordTooShort
+ }
+
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash new password: %w", err)
@@ -703,17 +714,20 @@ func (s *UserService) checkExternalRegistrationAllowed(ctx context.Context) erro
return nil
}
-// Both entry points that insert a new account share this path. An instance
+// Every entry point that inserts a new account shares this path. An instance
// holding no account hands the account the administrator role and records it as
-// the bootstrap administrator, and the question is asked before the registration
-// policy rather than inside the insert, because an empty instance whose policy
-// forbids registration would otherwise never gain an administrator at all.
+// the bootstrap administrator, and the question is asked before the ordinary-
+// account check rather than inside the insert, because an empty instance whose
+// policy forbids registration would otherwise never gain an administrator at all.
//
// Losing the race for that record is not a failure: the partial unique index
// admits one flagged account, so the loser is built again as an ordinary
-// account - now under the registration policy it was allowed to skip.
+// account - now under the check it was allowed to skip. Registration passes the
+// registration policy as that check; the host console passes one that always
+// allows.
func (s *UserService) createAccountClaimingEmptyInstance(
ctx context.Context,
+ checkOrdinaryAccountAllowed func(ctx context.Context) error,
build func(isTakingTheInstance bool) *users_models.User,
) (*users_models.User, error) {
isTakingTheInstance, err := s.isInstanceUnclaimed()
@@ -722,7 +736,7 @@ func (s *UserService) createAccountClaimingEmptyInstance(
}
if !isTakingTheInstance {
- if err := s.checkExternalRegistrationAllowed(ctx); err != nil {
+ if err := checkOrdinaryAccountAllowed(ctx); err != nil {
return nil, err
}
}
@@ -740,7 +754,7 @@ func (s *UserService) createAccountClaimingEmptyInstance(
return nil, fmt.Errorf("failed to create user: %w", err)
}
- if err := s.checkExternalRegistrationAllowed(ctx); err != nil {
+ if err := checkOrdinaryAccountAllowed(ctx); err != nil {
return nil, err
}
@@ -1061,6 +1075,7 @@ func (s *UserService) getOrCreateUserFromOAuth(
newUser, err := s.createAccountClaimingEmptyInstance(
ctx,
+ s.checkExternalRegistrationAllowed,
func(isTakingTheInstance bool) *users_models.User {
return buildOAuthUser(email, name, githubOAuthID, googleOAuthID, isTakingTheInstance)
},
diff --git a/backend/internal/features/users/services/user_services_test.go b/backend/internal/features/users/services/user_services_test.go
index f12b7cb9..0c108542 100644
--- a/backend/internal/features/users/services/user_services_test.go
+++ b/backend/internal/features/users/services/user_services_test.go
@@ -1,13 +1,21 @@
package users_services_test
import (
+ "context"
"testing"
+ "time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ users_dto "databasus-backend/internal/features/users/dto"
+ users_enums "databasus-backend/internal/features/users/enums"
+ users_errors "databasus-backend/internal/features/users/errors"
+ users_models "databasus-backend/internal/features/users/models"
+ users_repositories "databasus-backend/internal/features/users/repositories"
users_services "databasus-backend/internal/features/users/services"
+ users_testing "databasus-backend/internal/features/users/testing"
)
func Test_ChangeUserPasswordByEmail_WhenNoAccountHoldsTheAddress_ReturnsAnError(t *testing.T) {
@@ -22,3 +30,69 @@ func Test_ChangeUserPasswordByEmail_WhenNoAccountHoldsTheAddress_ReturnsAnError(
require.Error(t, err)
assert.Contains(t, err.Error(), "does not exist")
}
+
+func Test_ChangeUserPasswordByEmail_WhenPasswordIsShorterThanEightCharacters_KeepsTheOldPassword(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ installAuditLogRecorder()
+
+ user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), user.UserID) })
+
+ const oldPassword = "old-password-123"
+ require.NoError(t, users_services.GetUserService().ChangeUserPasswordByEmail(
+ t.Context(),
+ user.Email,
+ oldPassword,
+ ))
+
+ err := users_services.GetUserService().ChangeUserPasswordByEmail(t.Context(), user.Email, "seven77")
+
+ require.ErrorIs(t, err, users_errors.ErrPasswordTooShort)
+ require.NoError(t, signIn(t, user.Email, oldPassword))
+ require.Error(t, signIn(t, user.Email, "seven77"))
+}
+
+func Test_ChangeUserPasswordByEmail_WhenAccountStillHoldsThePlaceholderAddress_SetsThePassword(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ users_testing.DeleteAllUsers()
+ installAuditLogRecorder()
+
+ placeholderAdmin := &users_models.User{
+ ID: uuid.New(),
+ Email: "admin",
+ Name: "Admin",
+ PasswordCreationTime: time.Now().UTC(),
+ CreatedAt: time.Now().UTC(),
+ Role: users_enums.UserRoleAdmin,
+ Status: users_enums.UserStatusActive,
+ IsRootAdmin: true,
+ }
+ require.NoError(t, (&users_repositories.UserRepository{}).CreateUser(placeholderAdmin))
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), placeholderAdmin.ID) })
+
+ require.NoError(t, users_services.GetUserService().ChangeUserPasswordByEmail(
+ t.Context(),
+ "admin",
+ "owner-password-123",
+ ))
+
+ require.NoError(t, signIn(t, "admin", "owner-password-123"))
+}
+
+func installAuditLogRecorder() *users_testing.RecordingAuditLogWriter {
+ recorder := users_testing.InstallAuditLogRecorder()
+ users_services.GetUserService().SetAuditLogWriter(recorder)
+
+ return recorder
+}
+
+func signIn(t *testing.T, email, password string) error {
+ t.Helper()
+
+ _, err := users_services.GetUserService().SignIn(
+ t.Context(),
+ &users_dto.SignInRequestDTO{Email: email, Password: password},
+ )
+
+ return err
+}
diff --git a/openspec/changes/archive/2026-10-10-add-console-user-creation/.openspec.yaml b/openspec/changes/archive/2026-10-10-add-console-user-creation/.openspec.yaml
new file mode 100644
index 00000000..53f62d70
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-add-console-user-creation/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-10-10
diff --git a/openspec/changes/archive/2026-10-10-add-console-user-creation/design.md b/openspec/changes/archive/2026-10-10-add-console-user-creation/design.md
new file mode 100644
index 00000000..e169f4ee
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-add-console-user-creation/design.md
@@ -0,0 +1,113 @@
+## Context
+
+See proposal.md - Why for the motivation and specs/root-admin-account/spec.md for the behavior.
+
+Console commands are flags on the server binary. `parseCommandLineOptions` (`backend/cmd/main.go:154-176`) reads them, and after migrations `main` calls one `...IfRequested` function per command (`main.go:109-113`). Each function returns at once unless its flag is set; otherwise it does its work and ends the process through `logger.ExitAfterFlush`. A command that writes to the audit log first calls `audit_logs.SetupDependencies()` (`main.go:216`, `:241`), because nothing else installs the writer on the console path (`backend/internal/features/audit_logs/di.go:41-43`).
+
+Both existing ways to create an account go through `createAccountClaimingEmptyInstance` (`backend/internal/features/users/services/user_services.go:715-754`). It decides whether the instance is empty, applies the registration policy to an ordinary account and settles the race for the bootstrap record. The partial unique index admits one flagged account, so the loser of a concurrent first insert is rebuilt as an ordinary account (`:738-753`).
+
+Registration validates its input through Gin binding tags: `email` on the address and `min=8` on the password (`backend/internal/features/users/dto/dto.go:12-13`). Gin evaluates these tags with `github.com/go-playground/validator/v10`, which `backend/go.mod:279` already requires directly. The console reset passes its password straight to `ChangeUserPasswordByEmail` (`main.go:257-269`, `user_services.go:310-321`) and checks neither.
+
+A password change moves `password_creation_time` (`backend/internal/features/users/repositories/user_repository.go:72-79`), and token validation compares against it (`user_services.go:249`). Rotating a password from the console therefore ends the account's existing sessions.
+
+Addresses are unique in the database (`backend/migrations/20250605090323_init.sql:14`) and are compared as stored, without case folding (`user_repository.go:31-41`).
+
+The design is constrained by these `backend/AGENTS.md` rules: one responsibility per file, sentinel errors in `errors.go`, tests that mirror the source split, controller tests preferred and service tests reserved for logic without an API surface, and no passwords or unmasked email addresses in logs. No accepted ADR in `adr/` governs console commands or user provisioning.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- The creation logic and every refusal live under `backend/internal/features/users/` and are tested there. `main.go` only parses flags, calls the service and prints the outcome.
+- The new path and both existing ones share a single empty-instance claim, race handling included.
+- One password minimum applies to every way a password is set.
+
+**Non-Goals:**
+
+- A general command framework or subcommand parser. The new command follows the flag style of the existing three.
+- Changing how addresses are compared or normalized.
+
+## Decisions
+
+### The command is a flag set, `--create-user` with `--email`, `--password`, `--role` and `--name`
+
+`--create-user` selects the command and `--email` names the account, the same flag the reset uses. The password goes in `--password` rather than `--new-password`, because the reset already triggers on a non-empty `--new-password` (`main.go:237`). `--role` is required and accepts `admin` or `member` in any letter case. `--name` is optional. Without it, the build callback names the account after the address's local part, the text before the `@`. Registration requires a name (`dto.go:14`), and the local part identifies the account in `--list-admins` better than the fixed `User` an invitation gets (`user_services.go:368`). When `--create-user` is combined with `--new-password`, the command refuses and points at `--password`, so a mistyped flag never silently drops the password.
+
+`createUserIfRequested` runs before `resetPasswordIfRequested` in `main`, so the combination reaches that refusal instead of resetting a password.
+
+- Rejected: a `create-user` subcommand like `healthcheck` (`main.go:73`). The other account commands are flags, and documentation and scripts would carry two styles.
+- Rejected: reusing `--new-password` for the new account's password. One flag would mean two commands, depending on whether `--create-user` is present.
+- Rejected: defaulting `--role` to member. On an empty instance that default fails, and a script that omits the role would create an account other than the one its author meant.
+
+### The empty-instance claim takes the ordinary-account check as an argument
+
+`createAccountClaimingEmptyInstance` gets a parameter: the check to run before an ordinary account is inserted. Registration and OAuth pass `checkExternalRegistrationAllowed` as today. The console passes a check that always allows, since the registration policy does not apply at host trust level. The race handling, the bootstrap flag and the retry stay in one place.
+
+- Rejected: a separate insert path for the console. It would copy the race recovery, the subtlest code in the feature, and the two copies could drift.
+- Rejected: a boolean `shouldApplyRegistrationPolicy`. At the call site it reads as an unexplained `false`, and the function would still have to know which policy it skips.
+- Rejected: calling `SignUp`. It applies the registration policy, completes invited accounts instead of refusing them, and always creates a member when the instance is not empty.
+
+### The member-as-first-account refusal is checked before the insert
+
+The console path asks whether the instance is empty before calling the shared claim, and refuses a member account on an empty instance. The check races with a registration that lands in between. It can only refuse a member that could in fact have been created; it cannot let a member become the first account. The race is harmless because no code path deletes users, so an instance never becomes empty again. An administrator account takes the instance or, if a registration wins the race, becomes an ordinary administrator through the shared retry.
+
+- Rejected: letting the build callback return an error. That widens the signature shared with the web paths for a refusal only the console has.
+- Rejected: promoting the requested member to administrator. The command would do something other than what it was told, and the operator would learn about it only from the listing.
+
+### Idempotency is decided by an exact state match before the insert
+
+The command reads the account by address first. An account that is active, holds the requested role and has a password (`HasPassword`, `backend/internal/features/users/models/user.go:57`) is reported as already existing, with exit code 0, and nothing is written, not even an audit entry. Any other account at that address is a sentinel error and exit code 1. That includes an active account without a password, such as one created through Google or GitHub (`buildOAuthUser`, `user_services.go:774-792`). Reporting success for it would tell a deployment that the address signs in with the given password when it does not. A missing account goes to the shared claim.
+
+- Rejected: always failing on an existing address. Every deployment script would have to parse `--list-admins` before calling the command.
+- Rejected: updating an existing account's password or role. That turns creation into an upsert. A rerun with a stale secret would rotate the password, and the console would change existing accounts' roles, which the exception below deliberately leaves out.
+- Rejected: accepting an account without a password and setting the given password on it. It would quietly attach a password to an identity its owner set up to sign in through an external provider.
+
+### The console may create an administrator without the bootstrap administrator, but only as a new account
+
+The main spec reserves granting the administrator role for the bootstrap administrator (`openspec/specs/root-admin-account/spec.md`, requirement "The bootstrap administrator keeps its powers over other administrators after changing address"). The delta spec exempts one case: a new account created from the host console with the administrator role. The console reset can already set a password on the bootstrap administrator's own account (`main.go:257-269`) and act as it. Creating another administrator therefore gives the host nothing it does not already have, and the audit entry records each such account. The exception stops at new accounts, which is why the idempotency check above refuses an existing member instead of promoting it.
+
+- Rejected: limiting the console to the bootstrap case, the first account on an empty instance. Every role assignment would stay inside the rule. But an owner who provisions a second operator account, or recreates an administrator on an instance someone registered on first, would be back to clicking through the interface, which is the problem the proposal sets out to remove.
+- Rejected: letting the console also grant the role to existing accounts. That is a role-management command, not provisioning, and it widens the exception without a use case.
+
+### The service renders the console lines, so their content is testable
+
+`CreateUserFromConsole` returns an outcome value that tells a created account from an existing one. A function in the same file renders that value into the line the operator sees. It names the address and role, marks a new bootstrap administrator, and for an existing account says that nothing changed and the password was not changed. `main.go` prints the rendered line and, on failure, logs the returned error. The service itself writes no log line, so the rendered lines and the error messages are everything the command can emit. Tests assert that none of them contains the password or the stored hash.
+
+- Rejected: building the lines in `main.go`. Code under `cmd/` is never tested, and the no-secret requirement would rest on a code review.
+- Rejected: a grep over `main.go` for `fmt.Print*` and `log.*` arguments. It proves nothing about the content of an error message built deeper down.
+
+### Validation uses the validator Gin already uses
+
+The address is checked with `validator.New().Var(email, "required,email")`, and the password with the same rune count as `min=8`. Both are the library and tags the sign-up binding evaluates, so the console accepts and refuses exactly what registration does. The minimum becomes a named constant in the users feature. The binding tags keep their literal `min=8`, because a struct tag cannot reference a constant.
+
+- Rejected: `net/mail.ParseAddress`, which `backend/internal/util/smtp_transport/address.go:11` uses. It accepts forms like `Ops <[email protected]>` that registration refuses.
+
+### The password minimum is enforced in `ChangeUserPassword`
+
+`ChangeUserPassword` refuses a password below the minimum before hashing. Every password change passes through it: the console reset via `ChangeUserPasswordByEmail`, the profile change (`backend/internal/features/users/controllers/user_controller.go:188`) and the emailed reset (`user_services.go:637`). The web paths already bind `min=8`, so only the console reset behaves differently. The address is not validated there, so the placeholder `admin` can still be reset.
+
+- Rejected: checking only in `main.go`. Code under `cmd/` is never tested.
+- Rejected: checking only in `ChangeUserPasswordByEmail`. The rule would hold for one caller, and the next new caller would skip it.
+
+### The code lives in its own file and is tested at the service level
+
+`CreateUserFromConsole` goes into `backend/internal/features/users/services/console_account.go`, as a `UserService` method, because it needs the user repository, the shared claim and the audit writer. Its refusals are sentinel errors in `backend/internal/features/users/errors/errors.go`. Tests live in `console_account_test.go` next to it, following `disable_two_factor_test.go` and `admin_listing_test.go`. The command has no HTTP surface, so the backend rule allows a service test. Sign-in in those tests goes through `SignIn`, the same function the sign-in endpoint calls.
+
+- Rejected: putting the logic in `main.go` next to `resetPassword`. CI runs only `./internal/...` tests.
+- Rejected: `UserManagementService`. It works on accounts that already exist, and it has no access to the claim.
+
+### The audit entry names the address and the role, never the password
+
+A created account gets the entry `Account created from the host console: <email> (role ADMIN)`, attributed to the new account. On an empty instance it also gets the existing `writeInstanceClaimedAuditLog` entry. Neither the output nor the log carries the password. The created and existing lines are printed with `fmt.Println`, as `--list-admins` does (`main.go:198-200`), because the logger masks addresses and the operator needs to read them.
+
+## Risks / Trade-offs
+
+- [The password sits in the command line and is visible in the container's process list while the command runs] → The exposure matches `--new-password`, and only someone already inside the container can see it. Reading the password from standard input is listed out of scope in the proposal.
+- [A rerun with a different password reports success and does not change the password, so a deployment can believe a rotation happened] → The output for an existing account says the password was not changed, and the documentation points to `--new-password` for rotation.
+- [Two console runs for the same address at the same moment both pass the existence check] → The unique index on `users.email` refuses the second insert, and that run exits with code 1 without corrupting anything. A deployment that retries succeeds on the existing account.
+- [`[email protected]` and `[email protected]` are different accounts] → This is how registration already behaves. The command does not change it.
+- [The minimum length now refuses short console resets an operator's script may rely on] → The proposal marks this as BREAKING. The error says what the minimum is.
+
+## Migration Plan
+
+No schema or data migration. The change ships in the server binary. Rolling back the binary removes the command and the reset's minimum; accounts created by the command remain ordinary accounts and keep working.
diff --git a/openspec/changes/archive/2026-10-10-add-console-user-creation/proposal.md b/openspec/changes/archive/2026-10-10-add-console-user-creation/proposal.md
new file mode 100644
index 00000000..df4c3cbe
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-add-console-user-creation/proposal.md
@@ -0,0 +1,46 @@
+## Why
+
+An instance gets its first account only through the registration form or a first Google or GitHub sign-in (`backend/internal/features/users/services/user_services.go:58`, `:965`). An owner who deploys Databasus from scripts therefore cannot provision an administrator without somebody opening the browser. They need an administrator that exists without a manual sign-up, so they can keep its password in a secrets vault and rotate it from the host. Everyone else still signs up as usual. The host console already lists administrators and resets passwords (`backend/cmd/main.go:184`, `:232`); creating an account is the missing third command.
+
+## Governing docs
+
+This change answers to [`AGENTS.md`](../../../AGENTS.md) at the repo root, [`backend/AGENTS.md`](../../../backend/AGENTS.md), [`website/AGENTS.md`](../../../website/AGENTS.md) and [`assets/readme/AGENTS.md`](../../../assets/readme/AGENTS.md). It touches no frontend and no verification agent code, so [`frontend/AGENTS.md`](../../../frontend/AGENTS.md) and [`agent/verification/AGENTS.md`](../../../agent/verification/AGENTS.md) do not apply.
+
+## What Changes
+
+- Add a console command that creates an account from inside the running instance: `docker exec -it databasus ./main --create-user --email="[email protected]" --password="..." --role=ADMIN`, with an optional `--name`. The account is active and holds a password from the moment it is created, so it signs in immediately and the existing `--new-password` reset rotates its password like any other account's.
+- Keep the first-account rule. The command run on an instance that holds no account creates its bootstrap administrator, with the same audit entry a first registration writes. Asked for `--role=MEMBER` there, it refuses, because a member as the first account would leave the instance with nobody able to appoint administrators.
+- Skip the registration policy. The command works with open registration switched off, since whoever runs it already has a shell inside the instance. An owner can close registration and provision accounts from the console only.
+- Let the console create an administrator on an instance that already has one, without the bootstrap administrator. Today only that account grants the role. The console already resets the bootstrap administrator's own password, so the exception adds no new power to the host. It covers new accounts only: the console never changes the role of an existing one.
+- Make a repeated run harmless. When an active account with the same address and role and a password already exists, the command reports that nothing changed and that the password was not changed, and exits successfully. Any other existing account with that address makes the command fail: one with another role, a deactivated one, an invited one, or one without a password that signs in through Google or GitHub.
+- Validate the input the way registration does: a syntactically valid email address and a password of at least eight characters.
+- Apply the same eight-character minimum to every password change, the `--new-password` console reset included. Today the console reset accepts any non-empty password (`backend/cmd/main.go:232-269`), while every web path binds `min=8` (`backend/internal/features/users/dto/dto.go:13`, `:73`, `:140`). **BREAKING** for the console reset: a password shorter than eight characters is now refused. The address check is not added to the reset, so an upgraded instance can still reset the placeholder account `admin`.
+- Record each account the command creates in the audit log, marked as created from the host console.
+- Document the command on the `/password` website page and in its five translations, and in the password section of the root `README.md` and its five translations, beside `--list-admins` and the reset.
+
+### Out of scope
+
+- Configuring accounts through the Helm chart, environment variables or a config file. The command runs inside a running instance; wiring it into a deployment is the operator's job.
+- Reading the password from standard input or an environment variable. The command takes it as an argument, the way `--new-password` does, and shares that command's exposure in the container's process list.
+- Updating an existing account from this command: its role, name, status or password. Role changes stay in the web interface, and passwords stay with `--new-password`.
+- Adding the created account to any workspace. A member created from the console joins workspaces the usual way.
+- Creating a second bootstrap administrator, or moving that record to another account. An administrator created on an instance that already holds accounts is an ordinary administrator.
+- Deleting accounts from the console.
+- A console command for the invitation flow.
+
+## Capabilities
+
+### New Capabilities
+
+None.
+
+### Modified Capabilities
+
+- `root-admin-account`: adds creating an account from the host console, including how it claims an empty instance and why it is safe to run repeatedly; exempts that creation from the rule that only the bootstrap administrator grants the administrator role, for new accounts only; adds the password minimum to the console reset; extends the documentation requirement to cover account creation.
+
+## Impact
+
+- Backend: `backend/cmd/main.go` gains the flags and the call; the creation logic and its tests live under `backend/internal/features/users/`, because CI runs the tests of `./internal/...` only. The empty-instance claim in `createAccountClaimingEmptyInstance` (`user_services.go:715`) is shared with the new path rather than duplicated.
+- No migration, no API change and no frontend change.
+- Website: `website/app/(en)/password/page.tsx` and `website/app/[lang]/password/content/{ru,es,pt,zh,fr}.tsx`.
+- README: `README.md` and `assets/readme/README.{ru,es,pt,zh,fr}.md`.
diff --git a/openspec/changes/archive/2026-10-10-add-console-user-creation/specs/root-admin-account/spec.md b/openspec/changes/archive/2026-10-10-add-console-user-creation/specs/root-admin-account/spec.md
new file mode 100644
index 00000000..60211149
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-add-console-user-creation/specs/root-admin-account/spec.md
@@ -0,0 +1,174 @@
+## ADDED Requirements
+
+### Requirement: An operator can create an account from the host
+
+An operator with shell access to the running instance SHALL be able to create an account by running a console command that takes the account's email address, its password and its role, administrator or member, and optionally a display name. When no display name is given, the account SHALL be named after the part of its address before the `@`.
+
+The created account SHALL be active and hold the given password at once: it SHALL sign in with that address and password without completing any registration or invitation step, and the console password reset SHALL change its password the way it does for any other account.
+
+The command SHALL create the account whether or not the instance allows open registration.
+
+The command SHALL refuse, creating nothing, when the address is not a syntactically valid email address, when the password is shorter than eight characters, or when the role is missing or is neither administrator nor member.
+
+Every account the command creates SHALL be recorded in the audit log with its address and role, and the entry SHALL say that the account was created from the host console.
+
+#### Scenario: Provisioning an administrator on an instance that already holds accounts
+
+- **WHEN** an operator creates an account with the administrator role from the console on an instance that already holds accounts
+- **THEN** the account holds the administrator role and is not the bootstrap administrator
+- **AND** it signs in with the given address and password
+- **AND** the audit log holds an entry naming its address and role and saying it was created from the host console
+
+#### Scenario: Provisioning while open registration is off
+
+- **WHEN** open registration is switched off and an operator creates a member account from the console
+- **THEN** the account is created and signs in
+
+#### Scenario: Rotating the password of a provisioned account
+
+- **WHEN** an operator resets the password of an account created from the console, using the console password reset
+- **THEN** the account signs in with the new password and is refused with the old one
+
+#### Scenario: Omitting the display name
+
+- **WHEN** an operator creates the account `[email protected]` without a display name
+- **THEN** the account's display name is `ops`
+
+#### Scenario: Refusing invalid input
+
+- **WHEN** an operator runs the command with a value that is not an email address, a password of seven characters, no role, or a role other than administrator or member such as `owner`
+- **THEN** the command fails, says what is wrong, and no account is created
+
+### Requirement: An account created from the host claims an empty instance under the first-account rule
+
+An account created from the console on an instance that holds no account SHALL be that instance's bootstrap administrator, exactly as a first registration is, and the audit log SHALL hold the same entry naming it as the instance's administrator.
+
+On an instance that holds no account, the command SHALL refuse to create a member account and SHALL say that the first account must be an administrator. A member as the first account would leave the instance with nobody able to grant the administrator role.
+
+When the command and a registration create the first account at the same moment, exactly one account SHALL become the bootstrap administrator. If the console-created account loses, it SHALL be created as an ordinary account with the role the operator asked for.
+
+#### Scenario: Provisioning the first administrator of a fresh instance
+
+- **WHEN** an operator creates an administrator account from the console on an instance that holds no account
+- **THEN** that account is the recorded bootstrap administrator
+- **AND** the administrator listing marks it as the bootstrap administrator
+- **AND** a person who registers afterwards gets the member role
+
+#### Scenario: The console and a registration claim an empty instance at the same moment
+
+- **WHEN** an operator creates an administrator account from the console while a registration claims the same empty instance
+- **THEN** exactly one account is the recorded bootstrap administrator
+- **AND** the console-created account exists and holds the administrator role
+
+#### Scenario: Refusing a member as the first account
+
+- **WHEN** an operator creates a member account from the console on an instance that holds no account
+- **THEN** the command fails, says the first account must be an administrator, and the instance still holds no account
+
+### Requirement: Creating the same account from the host again changes nothing
+
+Running the command for an address that already belongs to an active account holding the requested role and a password SHALL succeed. It SHALL report that the account already exists, that nothing changed and that its password was not changed, and SHALL leave that account's password, name and sessions untouched. A deployment can therefore run the command on every rollout.
+
+Running the command for an address that belongs to any other account SHALL fail and change nothing. This covers an account holding the other role, a deactivated account, an invited account that has not completed sign-up, and an account without a password, such as one created through Google or GitHub.
+
+#### Scenario: Re-running provisioning on every deployment
+
+- **WHEN** an operator runs the same create command twice, with a different password the second time
+- **THEN** the second run succeeds and reports that nothing changed and that the password was not changed
+- **AND** the account still signs in with the first password
+
+#### Scenario: The address belongs to an account with another role
+
+- **WHEN** an operator creates an administrator account for an address that a member account already holds
+- **THEN** the command fails, and that account is still a member with its old password
+
+#### Scenario: The address belongs to a deactivated account
+
+- **WHEN** an operator creates an account for an address whose account is deactivated
+- **THEN** the command fails, and the account stays deactivated
+
+#### Scenario: The address belongs to an invited account
+
+- **WHEN** an operator creates an account for an address that was invited and has not completed sign-up
+- **THEN** the command fails, and the account stays invited and without a password
+
+#### Scenario: The address belongs to an account without a password
+
+- **WHEN** an operator creates an administrator account for an address whose active administrator account signs in through Google or GitHub and has no password
+- **THEN** the command fails, and the account still has no password
+
+### Requirement: Creating an account from the host stays at host trust level and prints no secret
+
+Creating an account without registration SHALL be available only to a caller who can already execute commands inside the running instance, the same trust level the console password reset requires. The instance SHALL NOT expose it over the network.
+
+The command's output and log lines SHALL NOT contain the password or its hash.
+
+#### Scenario: Reading the command's output
+
+- **WHEN** an operator creates an account from the console, runs the same command again, and runs it once more with input it refuses
+- **THEN** none of the three outputs and no log line contains the password or a password hash
+
+### Requirement: The console password reset refuses short passwords
+
+The console password reset SHALL refuse a password shorter than eight characters and leave the stored password unchanged, matching the minimum every other way of setting a password enforces. It SHALL keep accepting any stored address, including the placeholder address `admin` that an upgraded instance can still carry.
+
+#### Scenario: Resetting to a short password
+
+- **WHEN** an operator resets an account's password from the console to a value of seven characters
+- **THEN** the command fails, and the account still signs in with its old password
+
+#### Scenario: Resetting the placeholder account
+
+- **WHEN** an operator resets the password of the account whose address is `admin` to a password of at least eight characters
+- **THEN** the account signs in with the address `admin` and the new password
+
+## MODIFIED Requirements
+
+### Requirement: The bootstrap administrator keeps its powers over other administrators after changing address
+
+Granting or revoking the administrator role, deactivating an account that holds it, and reactivating one SHALL remain reserved for the bootstrap administrator, and SHALL be permitted on the basis of the instance's record of which account that is. Changing the bootstrap administrator's email address SHALL NOT remove any of these powers, and SHALL NOT grant them to any other account.
+
+The one exception is creating a new account with the administrator role from the host console, which SHALL be permitted to a caller who can execute commands inside the running instance without the bootstrap administrator's involvement. It sits at the trust level of the console password reset, which can already take over the bootstrap administrator's own account. The exception covers only new accounts: the console SHALL NOT grant or revoke the role of an existing account, and SHALL NOT deactivate or reactivate one.
+
+#### Scenario: Appointing an administrator after the address has changed
+
+- **WHEN** the bootstrap administrator, having changed its address, grants the administrator role to another user
+- **THEN** the role is granted
+
+#### Scenario: Another administrator still cannot manage administrators
+
+- **WHEN** an account that holds the administrator role but is not the bootstrap administrator tries to grant the role, revoke it, or deactivate or reactivate an account holding it
+- **THEN** every one of those attempts is refused, whatever address the bootstrap administrator currently holds
+
+#### Scenario: The bootstrap administrator cannot be stripped of its role
+
+- **WHEN** any account attempts to revoke the administrator role from the bootstrap administrator or to deactivate it
+- **THEN** the attempt is refused, so the instance is never left without a recognized bootstrap administrator
+
+#### Scenario: The console cannot promote an existing account
+
+- **WHEN** an operator runs the console create command with the administrator role for an address that a member account already holds
+- **THEN** the command fails, and that account is still a member
+
+### Requirement: Setting up and recovering an instance are documented
+
+The product documentation SHALL describe how an instance gets its administrator - the first account created on it - and SHALL describe how to create an account from the host console, how to reset an administrator password and how to recover a forgotten administrator address, in the same place and in every language the documentation ships. The description of account creation SHALL say that the first account created from the console on an empty instance becomes its administrator, that a repeated run with the same address and role changes nothing, and that the password is then rotated with the console reset. The public documentation SHALL also answer the question of what to do when the administrator address or password is lost, and link to those steps.
+
+Documented command examples SHALL NOT present `admin` as the address an owner is expected to use, and the documentation SHALL NOT describe the instance as holding a user named `admin`. Where the placeholder address is mentioned at all, it SHALL be as the account an instance created before this change still carries until its owner replaces it.
+
+#### Scenario: An owner searches the documentation
+
+- **WHEN** an owner who cannot sign in reads the published password documentation
+- **THEN** it explains both resetting the password and listing the administrator addresses
+- **AND** the same guidance is reachable from the questions answered on the home page
+
+#### Scenario: An operator automates the first administrator
+
+- **WHEN** an operator who deploys instances from scripts reads the published password documentation in any of the six published languages
+- **THEN** it shows the command that creates an account from the console with its parameters
+- **AND** it says the command changes nothing when run again for the same account, and that the password is rotated with the reset command
+
+#### Scenario: Reading about roles
+
+- **WHEN** a reader consults the access-management documentation in any of the six published languages
+- **THEN** it describes the first account created on the instance as its administrator, without claiming that account's address is `admin`
diff --git a/openspec/changes/archive/2026-10-10-add-console-user-creation/tasks.md b/openspec/changes/archive/2026-10-10-add-console-user-creation/tasks.md
new file mode 100644
index 00000000..c08fdd88
--- /dev/null
+++ b/openspec/changes/archive/2026-10-10-add-console-user-creation/tasks.md
@@ -0,0 +1,29 @@
+## 1. Password minimum
+
+- [x] 1.1 Add the eight-character minimum as a named constant in the users feature, make `ChangeUserPassword` refuse a shorter password by rune count with a sentinel error from `users/errors/errors.go`, and add service tests for a seven-character console reset that leaves the old password working and a reset of the placeholder account `admin` that still succeeds; verify with `just test-package ./internal/features/users/...` in `backend/`
+
+## 2. Shared empty-instance claim
+
+- [x] 2.1 Give `createAccountClaimingEmptyInstance` the ordinary-account check as an argument, pass `checkExternalRegistrationAllowed` from `SignUp` and the OAuth path, and verify that the existing registration, OAuth, closed-registration and concurrent-registration tests still pass with `just test-package ./internal/features/users/...` in `backend/`
+
+## 3. Console account creation
+
+- [x] 3.1 Add the refusal sentinels to `users/errors/errors.go`: an invalid address, an invalid role, a member as the first account, and an address held by an account in another state. Add `CreateUserFromConsole` and the function that renders its outcome line in `users/services/console_account.go`. The method validates with the Gin validator, defaults the name to the address's local part, and refuses a member on an empty instance. An active account with the requested role and a password counts as an exact match and is reported as existing without any write; any other existing account is refused. Otherwise the method creates the account through the shared claim with an always-allowing check and writes the console audit entry. It writes no log line. Verify with `go build ./...` in `backend/`
+- [x] 3.2 Add `users/services/console_account_test.go` for the empty-instance cases, using `users_testing.DeleteAllUsers` and the audit recorder. Cover these scenarios: on an empty instance, the first console administrator becomes the bootstrap administrator with both audit entries, `RenderAdminListing` marks it as the bootstrap administrator, and a later registration gets the member role; a member on an empty instance is refused and the instance stays empty; `CreateUserFromConsole` with the administrator role, run concurrently with `SignUp` on an emptied instance, leaves exactly one bootstrap administrator while the console account exists with the administrator role, flagged only if it won. Verify with `just test-package ./internal/features/users/...` in `backend/`
+- [x] 3.3 Extend `console_account_test.go` with the non-empty-instance cases. Cover these scenarios: a console administrator is ordinary; creation succeeds with open registration off; the account signs in right away through `SignIn`; a console reset rotates the password and the old one is refused; the name defaults to the local part; an invalid address, a seven-character password, a missing role and the role `owner` are each refused with no account created. Verify with `just test-package ./internal/features/users/...` in `backend/`
+- [x] 3.4 Extend `console_account_test.go` with the existing-address cases: a rerun with a different password reports no change, its rendered line says the password was not changed, and the first password still signs in. A member, a deactivated account, an invited account and a password-less OAuth administrator at that address are each refused and left unchanged; the invited account stays invited without a password. Add one test that creates an account, reruns it and runs a refused input, then asserts that no rendered line and no returned error contains the password or the stored hash. Verify with `just test-package ./internal/features/users/...` in `backend/`
+
+## 4. Console wiring
+
+- [x] 4.1 Add `--create-user`, `--password`, `--role` and `--name` to `parseCommandLineOptions`, and add `createUserIfRequested` to `backend/cmd/main.go` ahead of `resetPasswordIfRequested`. It refuses a combination with `--new-password` or a missing `--email`, installs the audit writer, prints the line the service renders, and on failure logs only the returned error. Verify with `go build ./...` and `just lint` in `backend/`, and with `grep -n "Password" backend/cmd/main.go`, which must show the password reaching only the service call and the flag definitions, never `fmt.Print*` or `log.*`
+
+## 5. Documentation
+
+- [x] 5.1 Add a section on creating an account from the console to `website/app/(en)/password/page.tsx`, placed after the administrator listing. It gives the command, its parameters, the first-account rule, the no-change rerun and rotation with `--new-password`, and the eight-character minimum under the reset parameters. Extend the page's metadata description to mention account creation. Verify with `pnpm lint` and `pnpm build` in `website/`
+- [x] 5.2 Apply the same section, parameter note and metadata change to `website/app/[lang]/password/content/{ru,es,pt,zh,fr}.tsx`, keeping commands byte-identical to English. Verify with `pnpm lint` and `pnpm build` in `website/`, and with `grep -c -- "--create-user"` and `grep -c -- "--new-password"` over `website/app/(en)/password/page.tsx` and `website/app/[lang]/password/content/*.tsx`, each of which must report the same non-zero count for all six files
+- [x] 5.3 Add the create command with a short explanation to the `### 🔑 Resetting password` section of `README.md` and to all five copies in `assets/readme/`, keeping code blocks byte-identical, and verify with `grep -c -- "--create-user" README.md assets/readme/README.*.md`, which must report the same non-zero count for all six files
+
+## 6. Verification
+
+- [x] 6.1 Run `just test-package ./internal/features/users/... ./internal/features/audit_logs/...` in `backend/` and `just lint` at the repository root
+- [x] 6.2 Run `openspec validate add-console-user-creation --strict`
diff --git a/openspec/specs/root-admin-account/spec.md b/openspec/specs/root-admin-account/spec.md
index 20257414..826337e1 100644
--- a/openspec/specs/root-admin-account/spec.md
+++ b/openspec/specs/root-admin-account/spec.md
@@ -118,6 +118,8 @@ The instance SHALL record which account is the bootstrap administrator when it c
Granting or revoking the administrator role, deactivating an account that holds it, and reactivating one SHALL remain reserved for the bootstrap administrator, and SHALL be permitted on the basis of the instance's record of which account that is. Changing the bootstrap administrator's email address SHALL NOT remove any of these powers, and SHALL NOT grant them to any other account.
+The one exception is creating a new account with the administrator role from the host console, which SHALL be permitted to a caller who can execute commands inside the running instance without the bootstrap administrator's involvement. It sits at the trust level of the console password reset, which can already take over the bootstrap administrator's own account. The exception covers only new accounts: the console SHALL NOT grant or revoke the role of an existing account, and SHALL NOT deactivate or reactivate one.
+
#### Scenario: Appointing an administrator after the address has changed
- **WHEN** the bootstrap administrator, having changed its address, grants the administrator role to another user
@@ -133,6 +135,11 @@ Granting or revoking the administrator role, deactivating an account that holds
- **WHEN** any account attempts to revoke the administrator role from the bootstrap administrator or to deactivate it
- **THEN** the attempt is refused, so the instance is never left without a recognized bootstrap administrator
+#### Scenario: The console cannot promote an existing account
+
+- **WHEN** an operator runs the console create command with the administrator role for an address that a member account already holds
+- **THEN** the command fails, and that account is still a member
+
### Requirement: The bootstrap administrator can change their email address
The bootstrap administrator SHALL be able to change their email address through the same profile update every other user has, with no field locked and no explanation of why it is locked. The instance SHALL accept only a syntactically valid email address, and SHALL refuse an address another account already holds.
@@ -210,7 +217,7 @@ The listing SHALL be available only to a caller who can already execute commands
### Requirement: Setting up and recovering an instance are documented
-The product documentation SHALL describe how an instance gets its administrator - the first account created on it - and SHALL describe both how to reset an administrator password and how to recover a forgotten administrator address, in the same place and in every language the documentation ships. The public documentation SHALL also answer the question of what to do when the administrator address or password is lost, and link to those steps.
+The product documentation SHALL describe how an instance gets its administrator - the first account created on it - and SHALL describe how to create an account from the host console, how to reset an administrator password and how to recover a forgotten administrator address, in the same place and in every language the documentation ships. The description of account creation SHALL say that the first account created from the console on an empty instance becomes its administrator, that a repeated run with the same address and role changes nothing, and that the password is then rotated with the console reset. The public documentation SHALL also answer the question of what to do when the administrator address or password is lost, and link to those steps.
Documented command examples SHALL NOT present `admin` as the address an owner is expected to use, and the documentation SHALL NOT describe the instance as holding a user named `admin`. Where the placeholder address is mentioned at all, it SHALL be as the account an instance created before this change still carries until its owner replaces it.
@@ -220,7 +227,135 @@ Documented command examples SHALL NOT present `admin` as the address an owner is
- **THEN** it explains both resetting the password and listing the administrator addresses
- **AND** the same guidance is reachable from the questions answered on the home page
+#### Scenario: An operator automates the first administrator
+
+- **WHEN** an operator who deploys instances from scripts reads the published password documentation in any of the six published languages
+- **THEN** it shows the command that creates an account from the console with its parameters
+- **AND** it says the command changes nothing when run again for the same account, and that the password is rotated with the reset command
+
#### Scenario: Reading about roles
- **WHEN** a reader consults the access-management documentation in any of the six published languages
- **THEN** it describes the first account created on the instance as its administrator, without claiming that account's address is `admin`
+
+### Requirement: An operator can create an account from the host
+
+An operator with shell access to the running instance SHALL be able to create an account by running a console command that takes the account's email address, its password and its role, administrator or member, and optionally a display name. When no display name is given, the account SHALL be named after the part of its address before the `@`.
+
+The created account SHALL be active and hold the given password at once: it SHALL sign in with that address and password without completing any registration or invitation step, and the console password reset SHALL change its password the way it does for any other account.
+
+The command SHALL create the account whether or not the instance allows open registration.
+
+The command SHALL refuse, creating nothing, when the address is not a syntactically valid email address, when the password is shorter than eight characters, or when the role is missing or is neither administrator nor member.
+
+Every account the command creates SHALL be recorded in the audit log with its address and role, and the entry SHALL say that the account was created from the host console.
+
+#### Scenario: Provisioning an administrator on an instance that already holds accounts
+
+- **WHEN** an operator creates an account with the administrator role from the console on an instance that already holds accounts
+- **THEN** the account holds the administrator role and is not the bootstrap administrator
+- **AND** it signs in with the given address and password
+- **AND** the audit log holds an entry naming its address and role and saying it was created from the host console
+
+#### Scenario: Provisioning while open registration is off
+
+- **WHEN** open registration is switched off and an operator creates a member account from the console
+- **THEN** the account is created and signs in
+
+#### Scenario: Rotating the password of a provisioned account
+
+- **WHEN** an operator resets the password of an account created from the console, using the console password reset
+- **THEN** the account signs in with the new password and is refused with the old one
+
+#### Scenario: Omitting the display name
+
+- **WHEN** an operator creates the account `[email protected]` without a display name
+- **THEN** the account's display name is `ops`
+
+#### Scenario: Refusing invalid input
+
+- **WHEN** an operator runs the command with a value that is not an email address, a password of seven characters, no role, or a role other than administrator or member such as `owner`
+- **THEN** the command fails, says what is wrong, and no account is created
+
+### Requirement: An account created from the host claims an empty instance under the first-account rule
+
+An account created from the console on an instance that holds no account SHALL be that instance's bootstrap administrator, exactly as a first registration is, and the audit log SHALL hold the same entry naming it as the instance's administrator.
+
+On an instance that holds no account, the command SHALL refuse to create a member account and SHALL say that the first account must be an administrator. A member as the first account would leave the instance with nobody able to grant the administrator role.
+
+When the command and a registration create the first account at the same moment, exactly one account SHALL become the bootstrap administrator. If the console-created account loses, it SHALL be created as an ordinary account with the role the operator asked for.
+
+#### Scenario: Provisioning the first administrator of a fresh instance
+
+- **WHEN** an operator creates an administrator account from the console on an instance that holds no account
+- **THEN** that account is the recorded bootstrap administrator
+- **AND** the administrator listing marks it as the bootstrap administrator
+- **AND** a person who registers afterwards gets the member role
+
+#### Scenario: The console and a registration claim an empty instance at the same moment
+
+- **WHEN** an operator creates an administrator account from the console while a registration claims the same empty instance
+- **THEN** exactly one account is the recorded bootstrap administrator
+- **AND** the console-created account exists and holds the administrator role
+
+#### Scenario: Refusing a member as the first account
+
+- **WHEN** an operator creates a member account from the console on an instance that holds no account
+- **THEN** the command fails, says the first account must be an administrator, and the instance still holds no account
+
+### Requirement: Creating the same account from the host again changes nothing
+
+Running the command for an address that already belongs to an active account holding the requested role and a password SHALL succeed. It SHALL report that the account already exists, that nothing changed and that its password was not changed, and SHALL leave that account's password, name and sessions untouched. A deployment can therefore run the command on every rollout.
+
+Running the command for an address that belongs to any other account SHALL fail and change nothing. This covers an account holding the other role, a deactivated account, an invited account that has not completed sign-up, and an account without a password, such as one created through Google or GitHub.
+
+#### Scenario: Re-running provisioning on every deployment
+
+- **WHEN** an operator runs the same create command twice, with a different password the second time
+- **THEN** the second run succeeds and reports that nothing changed and that the password was not changed
+- **AND** the account still signs in with the first password
+
+#### Scenario: The address belongs to an account with another role
+
+- **WHEN** an operator creates an administrator account for an address that a member account already holds
+- **THEN** the command fails, and that account is still a member with its old password
+
+#### Scenario: The address belongs to a deactivated account
+
+- **WHEN** an operator creates an account for an address whose account is deactivated
+- **THEN** the command fails, and the account stays deactivated
+
+#### Scenario: The address belongs to an invited account
+
+- **WHEN** an operator creates an account for an address that was invited and has not completed sign-up
+- **THEN** the command fails, and the account stays invited and without a password
+
+#### Scenario: The address belongs to an account without a password
+
+- **WHEN** an operator creates an administrator account for an address whose active administrator account signs in through Google or GitHub and has no password
+- **THEN** the command fails, and the account still has no password
+
+### Requirement: Creating an account from the host stays at host trust level and prints no secret
+
+Creating an account without registration SHALL be available only to a caller who can already execute commands inside the running instance, the same trust level the console password reset requires. The instance SHALL NOT expose it over the network.
+
+The command's output and log lines SHALL NOT contain the password or its hash.
+
+#### Scenario: Reading the command's output
+
+- **WHEN** an operator creates an account from the console, runs the same command again, and runs it once more with input it refuses
+- **THEN** none of the three outputs and no log line contains the password or a password hash
+
+### Requirement: The console password reset refuses short passwords
+
+The console password reset SHALL refuse a password shorter than eight characters and leave the stored password unchanged, matching the minimum every other way of setting a password enforces. It SHALL keep accepting any stored address, including the placeholder address `admin` that an upgraded instance can still carry.
+
+#### Scenario: Resetting to a short password
+
+- **WHEN** an operator resets an account's password from the console to a value of seven characters
+- **THEN** the command fails, and the account still signs in with its old password
+
+#### Scenario: Resetting the placeholder account
+
+- **WHEN** an operator resets the password of the account whose address is `admin` to a password of at least eight characters
+- **THEN** the account signs in with the address `admin` and the new password
diff --git a/website/app/(en)/password/page.tsx b/website/app/(en)/password/page.tsx
index fac71219..95df0603 100644
--- a/website/app/(en)/password/page.tsx
+++ b/website/app/(en)/password/page.tsx
@@ -8,7 +8,7 @@ import DocTableOfContentComponent from "@/app/components/DocTableOfContentCompon
export const metadata: Metadata = {
title: "Reset password - Databasus Documentation",
description:
- "Learn how to reset user passwords in Databasus using the built-in command-line tool. Quick and secure password recovery for your PostgreSQL backup system.",
+ "Learn how to reset user passwords, list administrators and create accounts in Databasus using the built-in command-line tool. Quick and secure password recovery for your PostgreSQL backup system.",
keywords: [
"Databasus password reset",
"reset user password",
@@ -20,7 +20,7 @@ export const metadata: Metadata = {
openGraph: {
title: "Reset Password - Databasus Documentation",
description:
- "Learn how to reset user passwords in Databasus using the built-in command-line tool. Quick and secure password recovery for your PostgreSQL backup system.",
+ "Learn how to reset user passwords, list administrators and create accounts in Databasus using the built-in command-line tool. Quick and secure password recovery for your PostgreSQL backup system.",
type: "article",
url: "https://databasus.com/password",
},
@@ -28,7 +28,7 @@ export const metadata: Metadata = {
card: "summary",
title: "Reset Password - Databasus Documentation",
description:
- "Learn how to reset user passwords in Databasus using the built-in command-line tool. Quick and secure password recovery for your PostgreSQL backup system.",
+ "Learn how to reset user passwords, list administrators and create accounts in Databasus using the built-in command-line tool. Quick and secure password recovery for your PostgreSQL backup system.",
},
alternates: {
canonical: "https://databasus.com/password",
@@ -40,6 +40,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const createUserCommand = `docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin`;
const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
@@ -134,9 +135,9 @@ export default function PasswordResetPage() {
<ul>
<li>
- <strong>--new-password</strong>: The new password. Make sure
- it&apos;s secure and contains a mix of letters, numbers and
- special characters.
+ <strong>--new-password</strong>: The new password, at least 8
+ characters long. Make sure it&apos;s secure and contains a mix
+ of letters, numbers and special characters.
</li>
<li>
<strong>--email</strong>: The email address of the account
@@ -173,6 +174,65 @@ export default function PasswordResetPage() {
nobody has created an account yet, it reports that the instance
has no administrator.
</p>
+
+ <h2 id="create-user">Create an account from the console</h2>
+
+ <p>
+ To provision an account without signing up in the browser, for
+ example from a deployment script, create it on the server where
+ Databasus is running:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{createUserCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={createUserCommand} />
+ </div>
+ </div>
+
+ <p>The command accepts the following parameters:</p>
+
+ <ul>
+ <li>
+ <strong>--email</strong>: The email address of the new
+ account. It must be a valid email address.
+ </li>
+ <li>
+ <strong>--password</strong>: The password of the new account,
+ at least 8 characters long.
+ </li>
+ <li>
+ <strong>--role</strong>: <code>admin</code> or{" "}
+ <code>member</code>.
+ </li>
+ <li>
+ <strong>--name</strong>: An optional display name. Without it,
+ the account is named after the part of the address before the{" "}
+ <code>@</code>.
+ </li>
+ </ul>
+
+ <p>
+ The account is active at once and signs in with that address and
+ password, whether or not open registration is enabled. On an
+ instance that holds no account yet, the account you create
+ administers the instance, so the first one must use{" "}
+ <code>--role=admin</code>. An administrator created later this
+ way is an ordinary administrator.
+ </p>
+
+ <p>
+ Running the command again for an existing account with the same
+ role succeeds and changes nothing, so a deployment can run it on
+ every rollout. It does not change the password then: rotate the
+ password with the <code>--new-password</code> reset command
+ above. If the address belongs to an account with another role, a
+ deactivated or invited account, or an account that signs in
+ through Google or GitHub, the command fails and changes nothing.
+ </p>
+
<h2 id="disable-two-factor">Stop requiring a sign-in code</h2>
<p>
diff --git a/website/app/[lang]/password/content/es.tsx b/website/app/[lang]/password/content/es.tsx
index 68e7d06e..42d6b806 100644
--- a/website/app/[lang]/password/content/es.tsx
+++ b/website/app/[lang]/password/content/es.tsx
@@ -8,7 +8,7 @@ import DocTableOfContentComponent from "@/app/components/DocTableOfContentCompon
export const metadata: Metadata = {
title: "Restablecer contraseña - Documentación de Databasus",
description:
- "Aprenda a restablecer las contraseñas de usuario en Databasus con la herramienta de línea de comandos integrada. Recuperación de contraseña rápida y segura para su sistema de copias de seguridad de PostgreSQL.",
+ "Aprenda a restablecer las contraseñas de usuario, listar los administradores y crear cuentas en Databasus con la herramienta de línea de comandos integrada. Recuperación de contraseña rápida y segura para su sistema de copias de seguridad de PostgreSQL.",
keywords: [
"restablecer contraseña Databasus",
"restablecer contraseña de usuario",
@@ -20,7 +20,7 @@ export const metadata: Metadata = {
openGraph: {
title: "Restablecer contraseña - Documentación de Databasus",
description:
- "Aprenda a restablecer las contraseñas de usuario en Databasus con la herramienta de línea de comandos integrada. Recuperación de contraseña rápida y segura para su sistema de copias de seguridad de PostgreSQL.",
+ "Aprenda a restablecer las contraseñas de usuario, listar los administradores y crear cuentas en Databasus con la herramienta de línea de comandos integrada. Recuperación de contraseña rápida y segura para su sistema de copias de seguridad de PostgreSQL.",
type: "article",
url: getLocalizedUrl("es", "password"),
locale: OG_LOCALES.es,
@@ -29,7 +29,7 @@ export const metadata: Metadata = {
card: "summary",
title: "Restablecer contraseña - Documentación de Databasus",
description:
- "Aprenda a restablecer las contraseñas de usuario en Databasus con la herramienta de línea de comandos integrada. Recuperación de contraseña rápida y segura para su sistema de copias de seguridad de PostgreSQL.",
+ "Aprenda a restablecer las contraseñas de usuario, listar los administradores y crear cuentas en Databasus con la herramienta de línea de comandos integrada. Recuperación de contraseña rápida y segura para su sistema de copias de seguridad de PostgreSQL.",
},
alternates: {
canonical: getLocalizedUrl("es", "password"),
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const createUserCommand = `docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin`;
const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
@@ -137,9 +138,9 @@ export default function PasswordResetPage() {
<ul>
<li>
- <strong>--new-password</strong>: la nueva contraseña.
- Asegúrese de que sea segura y combine letras, números y
- caracteres especiales.
+ <strong>--new-password</strong>: la nueva contraseña, de al
+ menos 8 caracteres. Asegúrese de que sea segura y combine
+ letras, números y caracteres especiales.
</li>
<li>
<strong>--email</strong>: el correo electrónico de la cuenta
@@ -177,6 +178,65 @@ export default function PasswordResetPage() {
ningún token. En una instancia donde todavía nadie ha creado una
cuenta, informa de que la instancia no tiene administrador.
</p>
+
+ <h2 id="create-user">Crear una cuenta desde la consola</h2>
+
+ <p>
+ Para dar de alta una cuenta sin registrarse en el navegador, por
+ ejemplo desde un script de despliegue, créela en el servidor
+ donde se ejecuta Databasus:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{createUserCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton lang="es" text={createUserCommand} />
+ </div>
+ </div>
+
+ <p>El comando acepta los siguientes parámetros:</p>
+
+ <ul>
+ <li>
+ <strong>--email</strong>: el correo electrónico de la nueva
+ cuenta. Debe ser una dirección válida.
+ </li>
+ <li>
+ <strong>--password</strong>: la contraseña de la nueva cuenta,
+ de al menos 8 caracteres.
+ </li>
+ <li>
+ <strong>--role</strong>: <code>admin</code> o{" "}
+ <code>member</code>.
+ </li>
+ <li>
+ <strong>--name</strong>: un nombre visible opcional. Si no lo
+ indica, la cuenta recibe como nombre la parte de la dirección
+ anterior a la <code>@</code>.
+ </li>
+ </ul>
+
+ <p>
+ La cuenta queda activa de inmediato y entra con esa dirección y
+ esa contraseña, esté o no abierto el registro. En una instancia
+ que todavía no tiene ninguna cuenta, la cuenta que cree pasa a
+ administrar la instancia, así que la primera debe usar{" "}
+ <code>--role=admin</code>. Un administrador creado más tarde de
+ esta forma es un administrador corriente.
+ </p>
+
+ <p>
+ Si vuelve a ejecutar el comando para una cuenta que ya existe con
+ el mismo rol, termina sin error y no cambia nada, así que puede
+ incluirlo en cada despliegue. En ese caso la contraseña no se
+ toca: para cambiarla, use el comando de restablecimiento{" "}
+ <code>--new-password</code> descrito más arriba. Si la dirección
+ pertenece a una cuenta con otro rol, a una cuenta desactivada o
+ invitada, o a una cuenta que inicia sesión con Google o GitHub,
+ el comando falla y no cambia nada.
+ </p>
<h2 id="disable-two-factor">
Dejar de pedir un código al iniciar sesión
</h2>
diff --git a/website/app/[lang]/password/content/fr.tsx b/website/app/[lang]/password/content/fr.tsx
index 50cd5cae..a825b4d7 100644
--- a/website/app/[lang]/password/content/fr.tsx
+++ b/website/app/[lang]/password/content/fr.tsx
@@ -8,7 +8,7 @@ import DocTableOfContentComponent from "@/app/components/DocTableOfContentCompon
export const metadata: Metadata = {
title: "Réinitialiser le mot de passe - Documentation Databasus",
description:
- "Apprenez à réinitialiser les mots de passe des utilisateurs dans Databasus avec l'outil en ligne de commande intégré. Récupération rapide et sécurisée pour votre système de sauvegarde PostgreSQL.",
+ "Apprenez à réinitialiser les mots de passe des utilisateurs, lister les administrateurs et créer des comptes dans Databasus avec l'outil en ligne de commande intégré. Récupération rapide et sécurisée pour votre système de sauvegarde PostgreSQL.",
keywords: [
"réinitialisation mot de passe Databasus",
"réinitialiser mot de passe utilisateur",
@@ -20,7 +20,7 @@ export const metadata: Metadata = {
openGraph: {
title: "Réinitialiser le mot de passe - Documentation Databasus",
description:
- "Apprenez à réinitialiser les mots de passe des utilisateurs dans Databasus avec l'outil en ligne de commande intégré. Récupération rapide et sécurisée pour votre système de sauvegarde PostgreSQL.",
+ "Apprenez à réinitialiser les mots de passe des utilisateurs, lister les administrateurs et créer des comptes dans Databasus avec l'outil en ligne de commande intégré. Récupération rapide et sécurisée pour votre système de sauvegarde PostgreSQL.",
type: "article",
url: getLocalizedUrl("fr", "password"),
locale: OG_LOCALES.fr,
@@ -29,7 +29,7 @@ export const metadata: Metadata = {
card: "summary",
title: "Réinitialiser le mot de passe - Documentation Databasus",
description:
- "Apprenez à réinitialiser les mots de passe des utilisateurs dans Databasus avec l'outil en ligne de commande intégré. Récupération rapide et sécurisée pour votre système de sauvegarde PostgreSQL.",
+ "Apprenez à réinitialiser les mots de passe des utilisateurs, lister les administrateurs et créer des comptes dans Databasus avec l'outil en ligne de commande intégré. Récupération rapide et sécurisée pour votre système de sauvegarde PostgreSQL.",
},
alternates: {
canonical: getLocalizedUrl("fr", "password"),
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const createUserCommand = `docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin`;
const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
@@ -140,8 +141,8 @@ export default function PasswordResetPage() {
<ul>
<li>
- <strong>--new-password</strong> : le nouveau mot de passe.
- Assurez-vous qu&apos;il est robuste et contient un mélange de
+ <strong>--new-password</strong> : le nouveau mot de passe, d&apos;au
+ moins 8 caractères. Assurez-vous qu&apos;il est robuste et contient un mélange de
lettres, de chiffres et de caractères spéciaux.
</li>
<li>
@@ -181,6 +182,68 @@ export default function PasswordResetPage() {
personne n&apos;a encore créé de compte, elle indique que
l&apos;instance n&apos;a pas d&apos;administrateur.
</p>
+
+ <h2 id="create-user">Créer un compte depuis la console</h2>
+
+ <p>
+ Pour ouvrir un compte sans passer par l&apos;inscription dans le
+ navigateur, par exemple depuis un script de déploiement,
+ créez-le sur le serveur où Databasus tourne :
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{createUserCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={createUserCommand} lang="fr" />
+ </div>
+ </div>
+
+ <p>La commande accepte les paramètres suivants :</p>
+
+ <ul>
+ <li>
+ <strong>--email</strong> : l&apos;adresse e-mail du nouveau
+ compte. Elle doit être valide.
+ </li>
+ <li>
+ <strong>--password</strong> : le mot de passe du nouveau
+ compte, d&apos;au moins 8 caractères.
+ </li>
+ <li>
+ <strong>--role</strong> : <code>admin</code> ou{" "}
+ <code>member</code>.
+ </li>
+ <li>
+ <strong>--name</strong> : un nom affiché, facultatif. Sans
+ lui, le compte prend le nom de la partie de l&apos;adresse
+ située avant le <code>@</code>.
+ </li>
+ </ul>
+
+ <p>
+ Le compte est actif tout de suite : il se connecte avec cette
+ adresse et ce mot de passe, que l&apos;inscription libre soit
+ activée ou non. Sur une instance qui n&apos;a encore aucun
+ compte, le compte créé administre l&apos;instance, donc le
+ premier doit utiliser <code>--role=admin</code>. Un
+ administrateur créé plus tard de cette façon est un
+ administrateur ordinaire.
+ </p>
+
+ <p>
+ Relancer la commande pour un compte existant avec le même rôle
+ réussit sans rien modifier : un déploiement peut donc
+ l&apos;exécuter à chaque mise en production. Le mot de passe
+ reste alors inchangé ; pour le renouveler, utilisez la commande
+ de réinitialisation <code>--new-password</code> décrite plus
+ haut. Si l&apos;adresse appartient à un compte d&apos;un autre
+ rôle, à un compte désactivé ou invité, ou à un compte qui se
+ connecte via Google ou GitHub, la commande échoue et ne change
+ rien.
+ </p>
+
<h2 id="disable-two-factor">
Cesser de demander un code à la connexion
</h2>
diff --git a/website/app/[lang]/password/content/pt.tsx b/website/app/[lang]/password/content/pt.tsx
index cca2fc75..24f67dab 100644
--- a/website/app/[lang]/password/content/pt.tsx
+++ b/website/app/[lang]/password/content/pt.tsx
@@ -8,7 +8,7 @@ import DocTableOfContentComponent from "@/app/components/DocTableOfContentCompon
export const metadata: Metadata = {
title: "Redefinir senha - Documentação do Databasus",
description:
- "Aprenda a redefinir senhas de usuários no Databasus com a ferramenta de linha de comando integrada. Recuperação de senha rápida e segura para o seu sistema de backup PostgreSQL.",
+ "Aprenda a redefinir senhas de usuários, listar administradores e criar contas no Databasus com a ferramenta de linha de comando integrada. Recuperação de senha rápida e segura para o seu sistema de backup PostgreSQL.",
keywords: [
"redefinir senha Databasus",
"redefinir senha de usuário",
@@ -20,7 +20,7 @@ export const metadata: Metadata = {
openGraph: {
title: "Redefinir senha - Documentação do Databasus",
description:
- "Aprenda a redefinir senhas de usuários no Databasus com a ferramenta de linha de comando integrada. Recuperação de senha rápida e segura para o seu sistema de backup PostgreSQL.",
+ "Aprenda a redefinir senhas de usuários, listar administradores e criar contas no Databasus com a ferramenta de linha de comando integrada. Recuperação de senha rápida e segura para o seu sistema de backup PostgreSQL.",
type: "article",
url: getLocalizedUrl("pt", "password"),
locale: OG_LOCALES.pt,
@@ -29,7 +29,7 @@ export const metadata: Metadata = {
card: "summary",
title: "Redefinir senha - Documentação do Databasus",
description:
- "Aprenda a redefinir senhas de usuários no Databasus com a ferramenta de linha de comando integrada. Recuperação de senha rápida e segura para o seu sistema de backup PostgreSQL.",
+ "Aprenda a redefinir senhas de usuários, listar administradores e criar contas no Databasus com a ferramenta de linha de comando integrada. Recuperação de senha rápida e segura para o seu sistema de backup PostgreSQL.",
},
alternates: {
canonical: getLocalizedUrl("pt", "password"),
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const createUserCommand = `docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin`;
const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
@@ -137,9 +138,9 @@ export default function PasswordResetPage() {
<ul>
<li>
- <strong>--new-password</strong>: a nova senha. Garanta que é
- segura e contém uma mistura de letras, números e caracteres
- especiais.
+ <strong>--new-password</strong>: a nova senha, com pelo menos
+ 8 caracteres. Garanta que é segura e contém uma mistura de
+ letras, números e caracteres especiais.
</li>
<li>
<strong>--email</strong>: o endereço de email da conta cuja
@@ -176,6 +177,66 @@ export default function PasswordResetPage() {
instância onde ninguém criou uma conta ainda, ela informa que a
instância não tem administrador.
</p>
+
+ <h2 id="create-user">Criar uma conta pelo console</h2>
+
+ <p>
+ Para criar uma conta sem passar pelo cadastro no navegador, por
+ exemplo a partir de um script de deploy, execute o comando no
+ servidor onde o Databasus está rodando:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{createUserCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={createUserCommand} lang="pt" />
+ </div>
+ </div>
+
+ <p>O comando aceita os seguintes parâmetros:</p>
+
+ <ul>
+ <li>
+ <strong>--email</strong>: o endereço de e-mail da nova conta.
+ Precisa ser um endereço válido.
+ </li>
+ <li>
+ <strong>--password</strong>: a senha da nova conta, com pelo
+ menos 8 caracteres.
+ </li>
+ <li>
+ <strong>--role</strong>: <code>admin</code> ou{" "}
+ <code>member</code>.
+ </li>
+ <li>
+ <strong>--name</strong>: um nome de exibição opcional. Sem
+ ele, a conta recebe como nome a parte do endereço antes do{" "}
+ <code>@</code>.
+ </li>
+ </ul>
+
+ <p>
+ A conta já nasce ativa e entra com esse endereço e essa senha,
+ mesmo que o cadastro aberto esteja desligado. Em uma instância
+ que ainda não tem nenhuma conta, a conta criada passa a
+ administrar a instância, por isso a primeira precisa usar{" "}
+ <code>--role=admin</code>. Administradores criados assim mais
+ tarde são administradores comuns.
+ </p>
+
+ <p>
+ Rodar o comando de novo para uma conta que já existe com o mesmo
+ papel termina com sucesso e não altera nada, então um deploy
+ pode executá-lo a cada rollout. Nesse caso a senha também não
+ muda: para trocá-la, use o comando de redefinição com{" "}
+ <code>--new-password</code> descrito acima. Se o endereço
+ pertencer a uma conta com outro papel, a uma conta desativada ou
+ convidada, ou a uma conta que entra pelo Google ou pelo GitHub,
+ o comando falha sem alterar nada.
+ </p>
+
<h2 id="disable-two-factor">
Parar de pedir um código no login
</h2>
diff --git a/website/app/[lang]/password/content/ru.tsx b/website/app/[lang]/password/content/ru.tsx
index 758b1f11..96fc8b0c 100644
--- a/website/app/[lang]/password/content/ru.tsx
+++ b/website/app/[lang]/password/content/ru.tsx
@@ -8,7 +8,7 @@ import DocTableOfContentComponent from "@/app/components/DocTableOfContentCompon
export const metadata: Metadata = {
title: "Сброс пароля - документация Databasus",
description:
- "Как сбросить пароль пользователя в Databasus встроенной консольной утилитой. Быстрый и безопасный сброс пароля в вашей системе резервного копирования PostgreSQL.",
+ "Как сбросить пароль пользователя, вывести список администраторов и создать учетную запись в Databasus встроенной консольной утилитой. Быстрый и безопасный сброс пароля в вашей системе резервного копирования PostgreSQL.",
keywords: [
"сброс пароля Databasus",
"сбросить пароль пользователя",
@@ -20,7 +20,7 @@ export const metadata: Metadata = {
openGraph: {
title: "Сброс пароля - документация Databasus",
description:
- "Как сбросить пароль пользователя в Databasus встроенной консольной утилитой. Быстрый и безопасный сброс пароля в вашей системе резервного копирования PostgreSQL.",
+ "Как сбросить пароль пользователя, вывести список администраторов и создать учетную запись в Databasus встроенной консольной утилитой. Быстрый и безопасный сброс пароля в вашей системе резервного копирования PostgreSQL.",
type: "article",
url: getLocalizedUrl("ru", "password"),
locale: OG_LOCALES.ru,
@@ -29,7 +29,7 @@ export const metadata: Metadata = {
card: "summary",
title: "Сброс пароля - документация Databasus",
description:
- "Как сбросить пароль пользователя в Databasus встроенной консольной утилитой. Быстрый и безопасный сброс пароля в вашей системе резервного копирования PostgreSQL.",
+ "Как сбросить пароль пользователя, вывести список администраторов и создать учетную запись в Databasus встроенной консольной утилитой. Быстрый и безопасный сброс пароля в вашей системе резервного копирования PostgreSQL.",
},
alternates: {
canonical: getLocalizedUrl("ru", "password"),
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const createUserCommand = `docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin`;
const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
@@ -135,8 +136,9 @@ export default function PasswordResetPage() {
<ul>
<li>
- <strong>--new-password</strong>: новый пароль. Убедитесь, что
- он надежный и содержит буквы, цифры и специальные символы.
+ <strong>--new-password</strong>: новый пароль, не короче 8
+ символов. Убедитесь, что он надежный и содержит буквы, цифры и
+ специальные символы.
</li>
<li>
<strong>--email</strong>: email учетной записи, чей пароль вы
@@ -172,6 +174,66 @@ export default function PasswordResetPage() {
где еще никто не завел учетную запись, команда сообщит, что
администратора нет.
</p>
+
+ <h2 id="create-user">Создание учетной записи из консоли</h2>
+
+ <p>
+ Учетную запись можно завести без регистрации в браузере,
+ например из скрипта деплоя. Выполните команду на сервере, где
+ запущен Databasus:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{createUserCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={createUserCommand} lang="ru" />
+ </div>
+ </div>
+
+ <p>Команда принимает следующие параметры:</p>
+
+ <ul>
+ <li>
+ <strong>--email</strong>: email новой учетной записи. Адрес
+ должен быть корректным.
+ </li>
+ <li>
+ <strong>--password</strong>: пароль новой учетной записи, не
+ короче 8 символов.
+ </li>
+ <li>
+ <strong>--role</strong>: <code>admin</code> или{" "}
+ <code>member</code>.
+ </li>
+ <li>
+ <strong>--name</strong>: отображаемое имя, необязательно. Без
+ него учетная запись получит имя по части адреса до{" "}
+ <code>@</code>.
+ </li>
+ </ul>
+
+ <p>
+ Учетная запись сразу активна, и в нее можно войти с этим адресом
+ и паролем, даже если открытая регистрация выключена. На
+ инстансе, где еще нет ни одной учетной записи, созданная
+ учетная запись станет администратором инстанса, поэтому первой
+ нужно передать <code>--role=admin</code>. Администратор,
+ созданный так позже, будет обычным администратором.
+ </p>
+
+ <p>
+ Повторный запуск для существующей учетной записи с той же ролью
+ завершится успешно и ничего не изменит, так что команду можно
+ выполнять при каждом деплое. Пароль при этом тоже не меняется:
+ для смены пароля используйте команду сброса с{" "}
+ <code>--new-password</code> выше. Если адрес принадлежит
+ учетной записи с другой ролью, деактивированной или
+ приглашенной учетной записи либо той, что входит через Google
+ или GitHub, команда завершится ошибкой и ничего не изменит.
+ </p>
+
<h2 id="disable-two-factor">
Перестать запрашивать код при входе
</h2>
diff --git a/website/app/[lang]/password/content/zh.tsx b/website/app/[lang]/password/content/zh.tsx
index 96d4a167..14013767 100644
--- a/website/app/[lang]/password/content/zh.tsx
+++ b/website/app/[lang]/password/content/zh.tsx
@@ -8,7 +8,7 @@ import DocTableOfContentComponent from "@/app/components/DocTableOfContentCompon
export const metadata: Metadata = {
title: "重置密码 - Databasus 文档",
description:
- "了解如何使用内置命令行工具在 Databasus 中重置用户密码。为你的 PostgreSQL 备份系统提供快速安全的密码找回方式。",
+ "了解如何使用内置命令行工具在 Databasus 中重置用户密码、列出管理员和创建账户。为你的 PostgreSQL 备份系统提供快速安全的密码找回方式。",
keywords: [
"Databasus 重置密码",
"重置用户密码",
@@ -20,7 +20,7 @@ export const metadata: Metadata = {
openGraph: {
title: "重置密码 - Databasus 文档",
description:
- "了解如何使用内置命令行工具在 Databasus 中重置用户密码。为你的 PostgreSQL 备份系统提供快速安全的密码找回方式。",
+ "了解如何使用内置命令行工具在 Databasus 中重置用户密码、列出管理员和创建账户。为你的 PostgreSQL 备份系统提供快速安全的密码找回方式。",
type: "article",
url: getLocalizedUrl("zh", "password"),
locale: OG_LOCALES.zh,
@@ -29,7 +29,7 @@ export const metadata: Metadata = {
card: "summary",
title: "重置密码 - Databasus 文档",
description:
- "了解如何使用内置命令行工具在 Databasus 中重置用户密码。为你的 PostgreSQL 备份系统提供快速安全的密码找回方式。",
+ "了解如何使用内置命令行工具在 Databasus 中重置用户密码、列出管理员和创建账户。为你的 PostgreSQL 备份系统提供快速安全的密码找回方式。",
},
alternates: {
canonical: getLocalizedUrl("zh", "password"),
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const createUserCommand = `docker exec -it databasus ./main --create-user --email="[email protected]" --password="YourSecurePassword123" --role=admin`;
const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
@@ -131,8 +132,8 @@ export default function PasswordResetPage() {
<ul>
<li>
- <strong>--new-password</strong>:新密码。请确保密码足够
- 安全,包含字母、数字和特殊字符。
+ <strong>--new-password</strong>:新密码,至少 8
+ 个字符。请确保密码足够安全,包含字母、数字和特殊字符。
</li>
<li>
<strong>--email</strong>:要重置密码的账户邮箱(例如{" "}
@@ -162,6 +163,55 @@ export default function PasswordResetPage() {
<p>
输出会列出每个管理员账户的邮箱、显示名称、创建日期和活动状态,并标记实例所认可的管理员。不会输出任何密码、密码哈希或令牌。如果实例上还没有人创建账户,命令会提示该实例没有管理员。
</p>
+
+ <h2 id="create-user">通过控制台创建账户</h2>
+
+ <p>
+ 如果不想在浏览器里注册,比如要用部署脚本开通账户,可以在运行
+ Databasus 的服务器上直接创建:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{createUserCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={createUserCommand} lang="zh" />
+ </div>
+ </div>
+
+ <p>命令接受以下参数:</p>
+
+ <ul>
+ <li>
+ <strong>--email</strong>:新账户的邮箱,必须是有效的邮箱地址。
+ </li>
+ <li>
+ <strong>--password</strong>:新账户的密码,至少 8 个字符。
+ </li>
+ <li>
+ <strong>--role</strong>:<code>admin</code> 或{" "}
+ <code>member</code>。
+ </li>
+ <li>
+ <strong>--name</strong>:可选的显示名称。不传时,账户名取邮箱中{" "}
+ <code>@</code> 之前的部分。
+ </li>
+ </ul>
+
+ <p>
+ 账户创建后立即生效,无论是否开放注册,都可以用这个邮箱和密码登录。如果实例上还没有任何账户,新建的账户就是该实例的管理员,所以第一个账户必须使用{" "}
+ <code>--role=admin</code>
+ 。之后用这种方式创建的管理员只是普通管理员。
+ </p>
+
+ <p>
+ 对同一角色的已有账户再次运行命令会成功结束,但不做任何改动,所以部署流程可以在每次上线时都运行它。这时密码也不会改变:要更换密码,请使用上面的{" "}
+ <code>--new-password</code>{" "}
+ 重置命令。如果该邮箱属于另一角色的账户、已停用或仍在邀请中的账户,或者通过
+ Google 或 GitHub 登录的账户,命令会失败,也不做任何改动。
+ </p>
+
<h2 id="disable-two-factor">不再要求登录验证码</h2>
<p>