Skip to content

Messages & Localization ​

Every text aooth shows a user has a message code:

  • the auth workflow's form errors, banners, finish messages, button labels and set-password copy — AOOTH_MESSAGES (@aooth/auth-moost);
  • the HttpErrors auth-moost raises outside the workflow (guard, controllers, workflow trigger) — AOOTH_HTTP_MESSAGES (@aooth/auth-moost);
  • the rate limiter's 429 — RATE_LIMIT_MESSAGES (@aooth/auth), the RATE_LIMITED code;
  • the HttpErrors of the ARBAC layer (authorize interceptor, DB controller gates) — ARBAC_MESSAGES (@aooth/arbac-moost);
  • the built-in password policies — PASSWORD_POLICY_MESSAGES (@aooth/user), the PP_* codes;
  • the default messages of UserAuthError — USER_AUTH_ERROR_MESSAGES (@aooth/user), keyed by the error's code (USER_AUTH_ERROR_CODES maps each type to its code).

Each catalogue holds the English templates, with {name} placeholders filled from the message params. Localize them all with one moost translator, or reword workflow texts per app with AuthWorkflowOpts.messages.

The bundled workflow forms are translated by their text: labels, descriptions, action and option labels, and the texts their expressions build with t(…) — see Forms in the user's language.

Localizing with the moost translator ​

Register a translator once at startup, before the server listens (moost ≥ 0.7.3):

ts
import { setTranslator } from "moost";

setTranslator({
  en: {}, // the default locale: the English templates as they are
  de: {
    INVALID_CREDENTIALS: "Ungültige Anmeldedaten",
    AOOTH_RESEND_WAIT: "Bitte {seconds}s warten.",
    AOOTH_NOT_AUTHENTICATED: "Nicht angemeldet",
    PP_MIN_LENGTH: "Das Passwort muss mindestens {min} Zeichen lang sein",
  },
});

A function translator (i18next, FormatJS, …) works the same way — see the moost docs on setTranslator. Then:

  • MoostHttp picks each request's locale from Accept-Language against the translator's locales; without the header the first locale is used.
  • The workflow translates its texts in the request's locale (resolution order).
  • MoostHttp translates every error body by its code, filling params — the English message is the fallback. Untranslated codes stay English.

The catalogues are registered with moost's registerMessages on import — @aooth/auth-moost also registers RATE_LIMIT_MESSAGES, PASSWORD_POLICY_MESSAGES, and USER_AUTH_ERROR_MESSAGES. Every registered template is available to moost's translation helpers and is served, translated, in the $i18n of the workflow form schemas and of atscript-db's /meta (@atscript/moost-db ≥ 0.1.170). Registered templates are public: register only texts a user may see.

One id space, shared with other libraries ​

Codes live in one process-wide registry, shared with every package that registers templates (atscript's validator, atscript-db, atscript-ui, your app). When two catalogues register the same code with different templates, the one registered last wins: its English text replaces the other everywhere, and one translation applies to both. So aooth's codes cannot collide by name:

  • Generic names carry an aooth prefix — AOOTH_ (workflow, HTTP and UserAuthError codes, e.g. AOOTH_INVALID_CODE, AOOTH_NOT_AUTHENTICATED, AOOTH_USER_LOCKED), ARBAC_ (the ARBAC layer) or PP_ (password policies).
  • Unprefixed codes name an aooth concept — MFA, TOTP, OTP, passwords, invites, sign-in, sessions, refresh tokens, SSO, the authorization server (MFA_INVALID, INVITE_REPLACED, INVALID_REFRESH_TOKEN, …).
  • Three codes are shared on purpose, with a neutral English template that any library registering the same id must use too:
CodeTemplateShared with
NOT_FOUNDNot foundany library's "record not found" (e.g. atscript-db)
INVALID_CREDENTIALSInvalid credentialsthe sign-in workflow and UserAuthError — one meaning
RATE_LIMITEDToo many requests. Retry after {retryAfter} s.any rate limiter's 429

Translate the shared codes neutrally — NOT_FOUND: "Nicht gefunden", never "Benutzer nicht gefunden" — or another library's error reads as a user error. Give your own codes a prefix of your own for the same reason.

Your own WooksHttp

MoostHttp sets up the locale and the error-body translation only when it creates the HTTP app itself (new MoostHttp() or new MoostHttp(options)). If you pass a WooksHttp you built, add both yourself:

ts
import { createHttpApp, useAcceptLanguage } from "@wooksjs/event-http";
import { translateErrorBody } from "moost";

new MoostHttp(
  createHttpApp({
    resolveLocale: () => useAcceptLanguage().negotiate(["en", "de"], "en"),
    transformErrorBody: (body, _error, ctx) => translateErrorBody(body, ctx),
  }),
);

How a workflow text is resolved ​

For each code the workflow produces, in this order:

  1. AuthWorkflowOpts.messages — the app's override: a partial map ({ CODE: "template" }, same {name} placeholders), or a resolver (code, params) => string | undefined. undefined (or a code the map does not list) falls through.
  2. The moost translator, in the request's locale.
  3. The English template from AOOTH_MESSAGES, params filled in.
ts
import { AuthWorkflow } from "@aooth/auth-moost";

// Fixed wording for this app — wins over the translator
new AuthWorkflow(
  {
    messages: {
      INVALID_CREDENTIALS: "Wrong username or password",
      AOOTH_RESEND_WAIT: "Wait {seconds} s before asking for a new code.",
    },
  },
  users,
  auth,
  consentStore,
);

Texts are resolved when a response is rendered, never stored translated in the workflow state: a flow opened in one language and resumed in another answers in the language of the request at hand. The form-facing ctx.public projection is rebuilt in the request's language before every pause, and WfTriggerProvider strips it before the paused state is persisted (store-backed and token-backed alike); your own beforePersist hook still runs, after the strip. A flow you persist outside the trigger (e.g. mintWfToken) keeps ctx.public as a render cache — it is rebuilt on every response, so it is never shown stale. The one exception is the channel-OTP disclosure (OTP_DISCLOSURE_*), which is kept as shown because it is recorded with the user's consent.

Copy hooks return your own text, shown as is in every language: resolveSetPasswordCopy() (heading / intro, or other codes as headingCode / introCode; the default is the SET_PASSWORD_* codes), resolveAccept()'s confirmationMessage (default: AOOTH_ACCOUNT_CREATED) and resolveOtpDisclosure(). For per-language wording, override the codes through messages or the translator instead.

An unknown placeholder is left as-is. For full control — e.g. a per-tenant catalogue — override the protected msg(code, params) method on your AuthWorkflow subclass; every workflow text goes through it.

The helpers are exported for your own UI: renderAoothMessage(template, params) fills placeholders, resolveAoothMessage(code, params, messages?) applies the same order as the workflow (the translator only inside a request). Types: AoothMessageCode, AoothMessageParams, AoothMessages.

Forms in the user's language ​

With a translator, every form step of the auth workflows is served in the request's language (by @atscript/moost-wf):

WhatTranslator id
@meta.label, @meta.description, @ui.form.submit.text, action labels, static option labelsthe English text ("Username")
Validation messages of @expect.* / @meta.required, server-side and in the browserthe validator code (MIN_LENGTH)
Texts the forms' expressions build — hints, notices, MFA method labels, dynamic titles and labelsthe English text ("Code sent to {recipient}.")
Workflow errors and bannersthe AOOTH_MESSAGES code
ts
setTranslator({
  en: {},
  de: {
    Username: "Benutzername", // a form label: the text is its id
    "Forgot password?": "Passwort vergessen?", // an action label
    MIN_LENGTH: "Mindestens {min} Zeichen", // a validator message: by code
    "Code sent to {recipient}.": "Code an {recipient} gesendet.", // an expression text
    "Continue with {provider}": "Weiter mit {provider}",
    INVALID_CREDENTIALS: "Ungültige Anmeldedaten", // a workflow error: by code
  },
});

The browser only says which language it wants: <AsWfForm> sends the locale of atscript-ui's provideAsLocale as Accept-Language and merges the $i18n texts of each form schema it receives — see atscript-ui's Language & Translations.

vue
<!-- App.vue -->
<script setup lang="ts">
import { provideAsLocale } from "@atscript/vue-form";

provideAsLocale(() => userLocale.value);
</script>

Expression texts. The forms build some texts at render time from the workflow context — the "Code sent to …" hint, the MFA method labels, the SSO buttons. They call t(text, params), the last argument of every @ui.form.fn.* / @ui.form.validate expression, with a whole sentence and {name} placeholders, so a translation can reorder the words:

atscript
@ui.form.fn.value '(_, _d, ctx, _e, t) => t("Code sent to {recipient}.", { recipient: ctx.public.pincode.sentTo })'
transportHint?: ui.paragraph

The server collects the string literals of these expressions and serves their translations in the form schema's $i18n; the browser's t reads them. Nothing to register. The texts are the t("…") literals of the bundled forms' source (@aooth/auth-moost/atscript/models) — the source list for your translation files. Without a translation the English text is shown, unchanged.

Your own forms. A form you pass through setupAuthWorkflows({ forms }) (usually extends a bundled one) is translated the same way: in its expressions write t("Whole sentence {name}", { name }), never "Whole " + name. Every text expression is collected — fn.label, fn.title, fn.options, fn.attr, fn.value (a ui.paragraph's text), @ui.form.validate, …. fn.value and fn.attr results are shown as returned, so wrap their texts in t; a static @ui.form.attr text is not translated — add a @ui.form.fn.attr with t, as the bundled forms do. Compile such forms with @atscript/ui-fns ≥ 0.1.166 in your atscript config (Upgrading).

Values never change with the language: option values, the workflow state and context, the key of an MFA option. Branch on those, never on a label.

Error bodies ​

Every 4xx HttpError aooth raises carries a code and, where the text names a value, params. Branch on code in clients and tests, never on message:

json
{
  "statusCode": 403,
  "code": "AOOTH_WORKFLOW_NOT_ALLOWED",
  "params": { "workflow": "auth/x" },
  "message": "Workflow 'auth/x' is not allowed"
}
CatalogueCodeStatusParams
AOOTH_HTTP_MESSAGESAOOTH_AUTH_REQUIRED401— (guarded route, no credential)
AOOTH_CREDENTIAL_INVALID401— (guarded route, invalid credential)
AOOTH_NOT_AUTHENTICATED401— (useAuth().getUserId(), AuthController)
NO_CURRENT_SESSION401
MISSING_REFRESH_TOKEN401
INVALID_REFRESH_TOKEN401
LOGOUT_OTHERS_REQUIRED400
INVITE_NOT_FOUND404
AOOTH_MISSING_UID400
LINKED_IDENTITY_NOT_FOUND404
LAST_SIGN_IN_METHOD409
AOOTH_UNKNOWN_PROVIDER404provider
AOOTH_WORKFLOW_NOT_ALLOWED403workflow (a refused start)
AOOTH_WORKFLOW_RESUME_NOT_ALLOWED403— (a refused resume never names the stored flow)
AOOTH_CODE_LIMIT_REACHED429— (a destination's code budget is spent)
RATE_LIMIT_MESSAGESRATE_LIMITED429policy, limit, window, retryAfter (seconds)
AOOTH_MESSAGESAOOTH_USER_ALREADY_EXISTS409
INVITE_CANCELLED410
INVITE_REPLACED410
INVITE_ALREADY_ACCEPTED410
PASSWORD_CHANGED_SIGN_IN_AGAIN410
UNKNOWN_SSO_PROVIDER400
TOTP_NOT_CONFIGURED400
ARBAC_MESSAGESARBAC_INSUFFICIENT_PRIVILEGES403resource, action
ARBAC_FORBIDDEN403resource, action (evaluateOrThrow())
ARBAC_NOT_AUTHORIZED401
ARBAC_CONTROL_NOT_ALLOWED403control
ARBAC_CONTROL_VALUE_NOT_ALLOWED403control, value
ARBAC_NESTED_WRITE_NOT_ALLOWED403relation
ARBAC_ROW_OUT_OF_SCOPE403
ARBAC_REFERENCE_OUT_OF_SCOPE403fields
ARBAC_INVALID_QUERY_STRING400error (the parser's text)
USER_AUTH_ERROR_MESSAGESAOOTH_USER_POLICY_VIOLATION, …4xxsee Errors — HTTP mapping

Under a translator, a rate-limit rule's own English message is replaced by the RATE_LIMITED translation — the 429 is translated by its code. Use {limit}, {window} and {retryAfter} (seconds) in your translations.

Not coded: server errors (5xx), the 404 a row outside the caller's scope answers — it is the same answer as a missing row on purpose — and the authorization server's token endpoint, which answers OAuth's { error, error_description }.

The workflow's coded HttpErrors are resolved like any workflow text, then MoostHttp translates the error body by its code once more: for those codes a translator entry wins over AuthWorkflowOpts.messages in the error body. Override such a code in one place.

Password policies ​

The built-in policies (ppHasMinLength, ppHasUpperCase, …) carry a code and params. A policy's failure (errorMessage) is translated by its code, its rule text (description) by <code>_DESCRIPTION:

PolicyFailure codeRule codeParams
ppHasMinLength(min)PP_MIN_LENGTHPP_MIN_LENGTH_DESCRIPTIONmin
ppHasUpperCase(n)PP_UPPERCASEPP_UPPERCASE_DESCRIPTIONcount
ppHasLowerCase(n)PP_LOWERCASEPP_LOWERCASE_DESCRIPTIONcount
ppHasNumber(n)PP_NUMBERPP_NUMBER_DESCRIPTIONcount
ppHasSpecialChar(n)PP_SPECIAL_CHARPP_SPECIAL_CHAR_DESCRIPTIONcount
ppMaxRepeatedChars(m)PP_MAX_REPEATEDPP_MAX_REPEATED_DESCRIPTIONmax

The templates in PASSWORD_POLICY_MESSAGES are the plural forms ("at least {count} numbers"). Without a translation a user sees the policy's own English text, which is singular for a count of 1 — a translator that handles plurals (i18next's count) can do the same per language.

Where they are translated, in the request's locale:

  • the password rules the set-password and change-password forms list (ctx.public.password.policies), and their failure on submit;
  • userAuthErrorToHttp(): a POLICY_VIOLATION message lists the translated failures, and each entry of params.policies carries description, passed, errorMessage, code and params, so a client can render them itself.

Give your own policies a code with definePasswordPolicy({ rule, args, description, errorMessage, code, params }) and register their English templates with moost's registerMessages. A policy without a code is translated by its text. Using @aooth/user on a moost server without @aooth/auth-moost? Call registerMessages(PASSWORD_POLICY_MESSAGES) yourself.

Localized emails and SMS ​

Deliveries carry the locale of the request that sent them, so your sender can pick a template language:

EventField
AuthEmailEvent (EmailSender.send, the email outlet)locale?
AuthSmsEvent (SmsSender.send, built by your app)locale?
AuthDeliveryPayload (AuthWorkflow.deliver())locale?

locale is absent when the request has no locale (no translator and no resolveLocale) or the event is emitted outside a request. When you map a deliver() payload to your own email or SMS event, copy payload.locale across.

ts
class MyAuthWorkflow extends AuthWorkflow {
  protected override async deliver(payload: AuthDeliveryPayload): Promise<void> {
    await mailer.send(templateFor(payload.kind, payload.locale ?? "en"), payload);
  }
}

The workflow catalogue ​

GroupCodes
Sign-inINVALID_CREDENTIALS, AOOTH_ACCOUNT_LOCKED, INVALID_PASSWORD, INCORRECT_PASSWORD, SESSION_LIMIT_REACHED, PASSWORD_CHANGED_SIGN_IN_AGAIN
Codes (MFA / OTP)AOOTH_INVALID_CODE, AOOTH_CODE_EXPIRED, AOOTH_TOO_MANY_CODE_ATTEMPTS, AOOTH_RESEND_WAIT {seconds}, AOOTH_RESEND_WAIT_ANOTHER {seconds}, AOOTH_RESEND_WAIT_CHANNEL {seconds, channel}, TOTP_RESEND_NOT_APPLICABLE, TOTP_NOT_CONFIGURED
Contact addressesAOOTH_ADDRESS_REQUIRED, AOOTH_INVALID_EMAIL_ADDRESS, AOOTH_INVALID_PHONE_NUMBER, OTP_DISCLOSURE_EMAIL, OTP_DISCLOSURE_PHONE
MFA managementUNKNOWN_MFA_METHOD, AOOTH_UNKNOWN_METHOD, AOOTH_METHOD_UNAVAILABLE, AOOTH_METHOD_NOT_CHANGEABLE, KEEP_ONE_MFA_METHOD, LAST_MFA_METHOD_NOT_REMOVABLE, AOOTH_CHOOSE_OPTION, ALL_MFA_METHODS_SET_UP, NO_MFA_CHANGES, MFA_METHOD_TOTP, MFA_METHOD_EMAIL, MFA_METHOD_SMS, MFA_METHOD_ADDED {method}, MFA_METHOD_UPDATED {method}, MFA_METHOD_REMOVED {method}
PasswordsPASSWORDS_DO_NOT_MATCH, PASSWORD_CHANGE_TOO_RECENT, PASSWORD_CHANGED, PASSWORD_UPDATED_REDIRECTING, PASSWORD_UPDATED_STILL_LOCKED
Password screensCHANGE_PASSWORD_HEADING, CHANGE_PASSWORD_INTRO, SET_PASSWORD_EXPIRED_HEADING, SET_PASSWORD_EXPIRED_INTRO, SET_PASSWORD_RESET_HEADING, SET_PASSWORD_RESET_INTRO, SET_PASSWORD_INVITE_HEADING, SET_PASSWORD_INVITE_INTRO, SET_PASSWORD_INITIAL_HEADING, SET_PASSWORD_INITIAL_INTRO
Recovery / signupAOOTH_MAGIC_LINK_INVALID, SIGNUP_DISABLED, AOOTH_ALREADY_HAVE_ACCOUNT, AOOTH_ACCOUNT_LINKED, UNKNOWN_SSO_PROVIDER
InvitesAOOTH_ACCOUNT_CREATED, AOOTH_INVALID_ROLE, INVITE_ALREADY_PENDING, AOOTH_USER_ALREADY_EXISTS, DUPLICATE_INVITE_REJECTED, INVITE_CANCELLED, INVITE_REPLACED, INVITE_ALREADY_ACCEPTED, CHOOSE_USERNAME_TAKEN, USERNAME_NOT_ALLOWED
Authorization serverAUTHZ_EXPIRED, AUTHZ_BROWSER_MISMATCH, AUTHZ_FAILED
Button labelsGO_TO_SIGN_IN, BACK_TO_SIGN_IN, REQUEST_NEW_INVITE, AOOTH_BACK, AOOTH_GO_NOW

Read the English wording from the catalogues themselves (or the source) rather than copying it.

Where the codes surface ​

  • Form errors and banners — the resolved text is what the SPA renders; nothing changes on the client.
  • HttpError bodies — code and params next to the message (Error bodies).
  • Client-side confirm-password check — SetPasswordForm / ChangePasswordForm validate "passwords match" in the browser too. When PASSWORDS_DO_NOT_MATCH resolves to anything but the English default (an override or a translation), the workflow ships the text to the form (ctx.public.messages.PASSWORDS_DO_NOT_MATCH) and the validator uses it.
  • GET /auth/invite/post-redemption — that route renders the "already accepted" envelope outside the workflow, in the request's locale. With messages overrides, return the same messages value from AuthController.resolveInvitePostRedemption() so it matches. The underlying helper is buildInviteAlreadyAcceptedEnvelope({ loginUrl, alreadyAcceptedRedirectUrl, messages }).

DOs and DON'Ts ​

  • DO localize with one moost translator; keep messages for app-specific wording.
  • DO pass one messages value to both AuthWorkflowOpts and resolveInvitePostRedemption().
  • DON'T match on English strings in the SPA or in tests that may run with a translator — use the code on error bodies.
  • DO translate form texts by their English text and messages by their code — both in the same translator.
  • DON'T concatenate texts in your own form expressions: t("… {name}", { name }) keeps them translatable.
  • DO replace a form via forms.<slot> to change its English wording (see Atscript Models).

See also ​

Released under the MIT License.