Authentication (Cognito, client-direct)
Registration, sign-in, resend, password reset, and sign out are not routes on this HTTP API — the Flutter app talks to Amazon Cognito directly for all of them, using the AWS SDK / Amplify's Cognito Identity Provider client. This API's own routes (see API reference) only ever see the result of that — a verified bearer token on every subsequent call.
This page exists because "call Cognito directly" isn't itself enough for the FE team to integrate against: it documents exactly which Cognito API calls to make, with which parameters, in which order, against which client ID.
:::caution Illustrative parameter shapes, verified against deployed dev config
Cognito API request/response shapes below are Cognito's own documented
contract (InitiateAuth, RespondToAuthChallenge, etc.), not something this
repo defines. The configuration values (User Pool ID, app client IDs, API
base URL) are real, captured from the actual dev deployment on 2026-09-17 —
not placeholders. No end-to-end sign-up/sign-in trace has been captured yet;
see Operations → Capturing real execution results.
:::
Deployed configuration (dev)
| Value | |
|---|---|
| Region | us-east-1 |
| Cognito User Pool ID | us-east-1_L8woOafje |
App client — flutter-app-default (normal sign-in) | 2ccs07cj0be3sedqne7v4m6ud1 |
App client — flutter-app-remembered ("keep me signed in") | 3u6cc24r46e8llhtu1mhqaa19k |
| HTTP API base URL | https://jaqui4ocdf.execute-api.us-east-1.amazonaws.com |
Both mobile app clients are public (no client secret — a secret cannot be
protected inside a distributed APK) and accept the flows documented below.
There is no meaningful difference between them for sign-up/sign-in
mechanics — only which one the app authenticates against changes the
refresh token's lifetime (1 day vs 90 days). A third client, server-admin
(372s6dl49t4o3ujh9gtt9hl3qk), is for Cognito-side CI/support tooling only
and must never be embedded in the Flutter app. The API authorizer accepts
its tokens in dev only (KI-18 fixed, T002-048); in prod and every
other stage they still get 401 from every route, same as before the fix.
A fourth client, web-console (T002-057, lib/auth-stack.ts), exists
for the planned web admin console — this is not relevant to the Flutter
app, documented here only so it isn't confused with the three above. It's
also public (no secret), SRP-only (USER_SRP_AUTH; no CUSTOM_AUTH, no
ADMIN_USER_PASSWORD_AUTH), with 1 h access/ID tokens and a 24 h refresh
token, preventUserExistenceErrors and token revocation both on — same
posture as the mobile clients, shorter refresh window. Its id is published
at SSM /cse-http-be/<stage>/web-client-id and the WebClientId stack
output (no real dev value captured yet). The API authorizer now accepts
its tokens in every stage (T002-058, lib/api-stack.ts) — unlike
server-admin, which is dev-only, the web console is treated as a real,
always-on surface. ApiStack also gained CORS support (allowed origins from
the webOrigins CDK context, methods, headers, allowCredentials: false,
2 h preflight cache) purely for this client's browser callers; see
Infrastructure → ApiStack for
the full CORS and throttling configuration, and
API overview → Conventions
for the client-facing contract.
Pool-level settings that affect the client (lib/auth-stack.ts):
| Setting | Value | Effect for the client |
|---|---|---|
| Self sign-up | Enabled | The app calls SignUp directly |
| Username attributes | email, phone_number | Sign in with the email. phone_number is still a pool alias only because aliases are immutable; no flow signs in by phone. The Username passed to SignUp must be the email |
| Case sensitivity | Case-insensitive | User@Example.com and user@example.com are the same account |
| Auto-verified attributes | email only | Sign-up sends an email code. The phone number is not verified (it is a plain profile attribute; nothing signs in by phone) |
| MFA | Optional, TOTP only (no SMS MFA) | A user who enrols a TOTP authenticator gets a SOFTWARE_TOKEN_MFA challenge after SRP. The Flutter app must handle it or not offer MFA enrolment |
| Account recovery | Email only | ForgotPassword codes go to the email |
preventUserExistenceErrors | true on all clients | Sign-in/reset errors don't reveal whether the account exists |
| Token revocation | Enabled | RevokeToken and GlobalSignOut invalidate refresh tokens |
| Access / ID token validity | 1 hour | Refresh before expiry |
| Refresh token validity | 1 day (flutter-app-default) / 90 days (flutter-app-remembered) | No rotation on LITE, so this is the absolute session length from sign-in; using the app never extends it. Raised from 30 to 90 days on 2026-10-12 (effective from the next deploy; sessions issued before it keep their 30-day expiry) |
| Hosted UI / Managed Login | Not used, never enable | Moves the pool to the Essentials plan; see Architecture |
Password policy (lib/auth-stack.ts): minimum 10 characters, at least
one uppercase, one lowercase and one digit; symbols not required; a
temporary password (admin-created users only, not used by any mobile flow)
is valid for 3 days. This matches what's documented under
Registration below — verify any sign-up/reset
screen copy against this table, not against a separate design spec, since
the pool is the source of truth.
Account lockout: no configurable lockout. Cognito's built-in temporary
lockout after repeated wrong passwords still applies (see the web sign-in
section below); beyond that, Cognito LITE has no configurable
failed-attempt lockout or adaptive/risk-based authentication (that requires
the Essentials/Plus feature plan's advanced security features, which this
pool deliberately doesn't use — see the Hosted UI row above for why).
preventUserExistenceErrors (above) hides whether an account exists, but this
API adds no attempt counter of its own; apart from Cognito's built-in
temporary lockout, the only throttle in this product is the email OTP
resend cooldown documented below.
If any design screen shows "account locked after N attempts" copy, that
copy doesn't correspond to anything this backend enforces today — raise it
with the design team rather than build an API capability for it.
Registration (sign up)
Cognito SignUp, called with whichever mobile client ID matches the "keep me
signed in" state the user picked (or flutter-app-default if that hasn't
been decided yet — it doesn't matter for sign-up itself).
Required attributes (User Pool schema, lib/auth-stack.ts):
| Attribute | Required | Notes |
|---|---|---|
email | Yes | Sign-in alias; auto-verified via emailed code |
phone_number | Yes | E.164 format (+92...), required by the pool schema (immutable); a plain profile attribute, never used to sign in or verified |
name | No | Copied once into this API's displayName at confirmation |
custom:terms_accepted_at | Yes (by convention). Cognito doesn't enforce it: custom attributes can't be marked required | ISO-8601 UTC timestamp the client sets at the moment of acceptance. See below |
password | Yes | Min 10 chars, at least one uppercase, one lowercase, one digit (symbols not required) |
custom:terms_accepted_at: this is how FR-002 ("record that acceptance
happened") is captured — SignUp is client-direct to Cognito and never
reaches this API's own handlers, so there is no server-side endpoint that
could stamp this itself. The client must set it explicitly, as an ISO-8601 UTC
string, at the moment the user accepts terms — not a fixed/default value. This
attribute is immutable once set. PostConfirmationFn copies it onto the
DynamoDB profile item at confirmation time. If it's missing, sign-up still
succeeds and the profile has no termsAcceptedAt. Nothing server-side
rejects a sign-up without it, so the client is the only enforcement.
Request shape (Cognito SignUp, illustrative):
{
"ClientId": "2ccs07cj0be3sedqne7v4m6ud1",
"Username": "user@example.com",
"Password": "<password entered by the user>",
"UserAttributes": [
{ "Name": "email", "Value": "user@example.com" },
{ "Name": "phone_number", "Value": "+920000000000" },
{ "Name": "name", "Value": "Example User" },
{ "Name": "custom:terms_accepted_at", "Value": "2026-09-17T10:00:00.000Z" }
]
}
On success, Cognito emails a confirmation code (auto-verify is configured for
email, not phone) and the account sits UNCONFIRMED until ConfirmSignUp
succeeds.
Confirm sign-up: Cognito ConfirmSignUp with Username + the emailed
ConfirmationCode. On success, Cognito's PostConfirmation trigger
(PostConfirmationFn) fires automatically and provisions this account's
USER#<sub>/PROFILE item in DynamoDB — the very next call this API sees for
this user (typically GET /v1/me) will already find a profile. Since
2026-11-19 it also creates the account's personal organisation
(ensurePersonalOrg, idempotent), so every account has exactly one from
sign-up; GET /v1/me reports it as personalOrg. If that
trigger somehow didn't run, GET /v1/me provisions it idempotently anyway
(see Account API), so there is no
user-visible failure mode here.
Resend confirmation code: Cognito ResendConfirmationCode with
Username. This is a different code/limit path from the email OTP
sign-in resend below — signup email verification is fully native Cognito,
with no hook into this repo's own OTP-throttle logic.
Sign-in — email + password (SRP)
Cognito USER_SRP_AUTH via InitiateAuth. SRP cannot be performed by curl,
Postman, or hand-rolled HTTP calls — it's a multi-round challenge–response
protocol requiring a real Cognito client SDK (Amplify, amazon-cognito-identity-js,
or the Cognito Identity Provider SDK's built-in SRP helper) on the client
side. This API server never sees the password.
AuthFlow:USER_SRP_AUTHClientId: whichever mobile client matches the user's "keep me signed in" choice for this sign-inAuthParameters:{ USERNAME, SRP_A }(computed by the SDK), followed by aPASSWORD_VERIFIERchallenge response the SDK also computes
On success, Cognito returns an AuthenticationResult with IdToken,
AccessToken, RefreshToken, and ExpiresIn (3600 seconds — both mobile
clients set accessTokenValidity/idTokenValidity to 1 hour). The
RefreshToken's actual validity is 1 day (flutter-app-default) or 90 days
(flutter-app-remembered) — there is no refresh token rotation on the
LITE feature plan, so this window is the session's real, absolute lifetime;
there is no server-side mechanism extending it.
Use the IdToken as this API's bearer token. The authorizer also
accepts the AccessToken, but the access token has no email claim — an
access-token call to GET /v1/me still works, falling back to a Cognito
lookup (see GET /v1/me), but
that's an extra AWS call this endpoint otherwise never makes:
Authorization: Bearer <IdToken>
Sign-in — email + one-time code (custom auth)
Owner decision OQ-09 (2026-10-27): passwordless sign-in is email OTP only.
The earlier phone + SMS code flow, its SNS SMS sending and the phone-change
routes were removed; nothing in this product sends SMS. A fully custom
CUSTOM_AUTH flow, implemented by this repo's own three Lambda triggers
(packages/api/src/handlers/{define,create,verify}-auth-challenge.ts, logic
in packages/core/src/auth/email-otp.ts and email-otp-mailer.ts) — not
Cognito's native passwordless, which requires the Essentials/Plus feature plan
(this pool is LITE). Multi-step:
Step 1 — start the flow. InitiateAuth (illustrative request):
{
"AuthFlow": "CUSTOM_AUTH",
"ClientId": "2ccs07cj0be3sedqne7v4m6ud1",
"AuthParameters": { "USERNAME": "user@example.com" }
}
USERNAME is the user's email (the email sign-in alias). Cognito invokes
DefineAuthChallengeFn, which for a fresh session issues a
CUSTOM_CHALLENGE; that invokes CreateAuthChallengeFn:
- Round 1 (no prior
EMAIL_OTPentry inevent.request.session): generates a 6-digit code withcrypto.randomInt(100_000, 1_000_000), keeps onlysha256(code + ':' + sub)(the plaintext code is never stored or logged), and — only if the account's email is verified (email_verified = true) and a sender is configured — checks the 60-second resend throttle (DynamoDB itemOTPEMAIL#<sha256(lower(email))>/OTP_THROTTLE, see Types & schemas → Database entity shapes) and emails the code through SES (subject "Your Crown Solar sign-in code"; the body says it expires in 5 minutes). - Round 2 or 3 (a retry after a wrong/expired answer): reuses round 1's code hash and issue time verbatim — no second email is sent; the user re-enters the code they already have.
An unverified email, a throttled resend, a send failure and a missing sender configuration all look identical to the client: a normal "enter the code" step that rejects whatever is submitted.
Response: ChallengeName: "CUSTOM_CHALLENGE" plus a Session token for
step 2. publicChallengeParameters is empty. The Cognito session for custom
auth expires after about 3 minutes by default, so it can expire before
the 5-minute code does; the client then starts again from step 1.
Step 2 — submit the code. RespondToAuthChallenge (illustrative):
{
"ChallengeName": "CUSTOM_CHALLENGE",
"ClientId": "2ccs07cj0be3sedqne7v4m6ud1",
"Session": "<session token from step 1>",
"ChallengeResponses": {
"USERNAME": "user@example.com",
"ANSWER": "<6-digit code from the email>"
}
}
VerifyAuthChallengeFn compares sha256(ANSWER + ':' + sub) with the stored
hash in constant time, and checks that fewer than 5 minutes have passed
since round 1's code was issued. Then:
- Correct code, not expired → tokens issued (
AuthenticationResult, same shape as the SRP flow above). - Wrong or expired → another
CUSTOM_CHALLENGE, up to 3 attempts total perInitiateAuthsession, all checked against round 1's code. - 3rd attempt still wrong →
NotAuthorizedException; start again from step 1.
:::warning Not usable by real users yet
No real email sign-in has been captured against dev. Codes are only sent
when the stack is deployed with -c otpSenderEmail=<verified SES identity>
(see Operations), and while SES is in sandbox only
verified recipient addresses receive mail. SES DKIM verification and sandbox
exit are owner actions (Known issues).
:::
:::danger Old app builds App builds that use the removed phone + SMS code sign-in stop signing in once this version is deployed. There is no transition period (owner decision). :::
Phone number stays a required, mutable profile attribute on the user
pool (pool aliases and required attributes are immutable on an existing pool),
and phone remains a sign-in alias only for that reason; nothing signs in by
phone, and no phone verification or phone-change route exists.
For an unknown email, Cognito (preventUserExistenceErrors is on) still runs
the triggers with userNotFound: true: the flow looks the same, no email is
sent, and every answer fails.
Non-disclosure: the response shape is identical at every step whether or not the email is registered, verified or throttled. Response timing can differ, because only a registered, verified address incurs the DynamoDB and SES calls (KI-5).
Observability: this flow never touches the HTTP API. The only record is
the trigger log lines (email_signin_code_issued, email_signin_throttled,
email_signin_send_failed, email_signin_unverified_address,
email_signin_sender_not_configured, email_signin_succeeded,
email_signin_failed_bad_code, email_signin_failed_expired). Neither the
email address nor the code is logged. See
Operations → Logs.
Wrong-code lockout (Audit wave 1 (2026-10-27))
Failures are counted per address in OTPEMAIL#<sha256(lower(email))> / OTP_FAILURES (failures, lastFailureAt, lockedUntil, ttl; a sliding 1-hour window).
- Wrong codes 1–9 carry no penalty. The 10th starts a 1-minute refusal; each further counted wrong code doubles it, capped at 15 minutes.
- Wrong codes entered during a refusal, and correct-but-expired codes, are not counted.
- A successful sign-in deletes the counter.
- While refused, no email is sent and the challenge cannot be matched; the client cannot tell it apart from a normal challenge.
- A resend inside the 60-second throttle no longer fails closed: the code is checked against the stored code that was already sent.
- Only the verify handler can write the counter (a write-only table policy scoped to
OTPEMAIL#*leading keys).
Known issue: anyone who knows an address can impose a ~1-minute refusal on it, and up to 15 minutes if they keep guessing.
Known gap (A10): on mobile, control of the mailbox equals control of the account — email OTP sign-in never adds TOTP. After an admin reset-mfa, whoever signs in first can enrol their own TOTP.
Web console sign-in (web-console client)
Feature 010 US7 (FR-029 to FR-032). The web console signs in client-direct
to Cognito with the web-console app client (lib/auth-stack.ts):
SRP only (authFlows.userSrp, no custom flow, so no email OTP
sign-in on the web), preventUserExistenceErrors: true,
enableTokenRevocation: true, access/ID token 1 hour, refresh token
24 hours (same as the Flutter app, 2026-11-12). No HTTP API route is involved in sign-in.
Password policy (use these exact rules in client validation and copy):
minimum 10 characters, at least one uppercase letter, one
lowercase letter and one digit. Symbols are not required. This
is the user-pool passwordPolicy (minLength: 10, requireUppercase,
requireLowercase, requireDigits, requireSymbols: false). Do not show
"at least 8 characters".
Lockout: after repeated wrong passwords Cognito temporarily blocks
sign-in and returns NotAuthorizedException (message "Password attempts
exceeded"). Show it as its own generic state, for example "Your account is
temporarily locked. Try again later." Do not promise a fixed number of
attempts or a fixed duration: the LITE plan cannot configure either, and
Cognito's back-off grows with repeated failures.
Challenges the web client must handle after USER_SRP_AUTH:
ChallengeName | When | Client action |
|---|---|---|
NEW_PASSWORD_REQUIRED | First sign-in of a support-created account (temporary password, valid 3 days) | Ask for a new password (same policy) and answer with RespondToAuthChallenge (NEW_PASSWORD) |
SOFTWARE_TOKEN_MFA | The user has an authenticator app (TOTP) turned on. SMS MFA is off for this pool | Ask for the 6-digit code and answer with SOFTWARE_TOKEN_MFA_CODE |
A support-created account never went through self sign-up confirmation, so
the post-confirmation trigger did not create its profile. The profile is
created by the first API call after sign-in (GET /v1/me/settings calls
ensureUserProfile). The Cognito PostAuthentication trigger (wired, T010-061)
also creates it at sign-in (ensureUserProfile).
Forgot password on the web uses the same native Cognito email-code flow described below. It is not production-ready until blocker B-02 (SES production access + DKIM) is closed.
Forgot / reset password
Cognito ForgotPassword (Username: email) triggers a password-reset code.
Delivery is currently Cognito's own built-in email sender — capped at
~50 emails/day, account-wide — because Amazon SES for this account is still
in sandbox mode (verified-recipients-only). Do not build a production
launch plan around password reset working for real users yet: it only
works today for SES-verified/allow-listed addresses if Cognito were pointed
at SES, and it isn't yet — see
Architecture → Important architectural decisions
and Operations → Troubleshooting.
ConfirmForgotPassword (Username, ConfirmationCode, Password) completes
the reset.
Sign out
Two levels, both client-direct to Cognito, neither an HTTP API route:
- Local sign-out: the client discards its stored tokens. Optionally, it
first calls Cognito
RevokeTokenwith the refresh token (token revocation is enabled on both clients) so that one refresh token can't be reused. Either way, the access/ID token stays valid at the API until it expires, up to 1 hour. - Global sign-out (e.g. "sign out of all devices", or a lost-device
flow): Cognito
GlobalSignOut, called with a currently-valid access token. Revokes every outstanding refresh token for that user immediately — any other signed-in session can no longer silently refresh, though its current still-valid access/ID token keeps working until that token's own expiry.
Error handling
Cognito's own errors (NotAuthorizedException, UsernameExistsException,
UserNotConfirmedException, InvalidPasswordException,
CodeMismatchException, ExpiredCodeException, LimitExceededException,
etc.) are returned directly by Cognito — they do not use this API's
{ error: { code, message } } envelope, since none of this happens through
API Gateway. Map these client-side to whatever UI the Flutter screens need;
they are a separate contract from this API's error codes.
A PostConfirmationFn failure never fails sign-up. The trigger catches and
logs its own errors (post_confirmation_provisioning_failed), and
GET /v1/me provisions the profile — and, for an account with no ACTIVE
membership, the personal organisation — as a backstop.
Server-side IdentityProvider (not used by any route)
packages/core/src/auth/identity-provider.ts defines the only interface
through which code may talk to the identity provider.
CognitoIdentityProvider is its sole implementation, and the only file
allowed to import the Cognito SDK. No HTTP handler calls it today. It
exists for support tooling, CI, and a future migration away from Cognito.
| Method | Cognito call | Notes |
|---|---|---|
verifyToken | — | Throws NotImplementedError. The gateway verifies JWTs |
createUser | AdminCreateUser | Omits the pool-required phone_number, so expect it to fail (KI-16) |
authenticate | AdminInitiateAuth ADMIN_USER_PASSWORD_AUTH via server-admin | Resulting tokens are accepted by the API authorizer in dev only (KI-18 fixed, T002-048); rejected everywhere else |
refresh | AdminInitiateAuth REFRESH_TOKEN_AUTH | Returns the caller's existing refresh token (no rotation on LITE) |
globalSignOut | AdminUserGlobalSignOut | Lost-device flow |
requestPasswordReset | ForgotPassword | |
disableUser | AdminDisableUser |