File size: 15,352 Bytes
4cfab62
 
 
816fa8a
4cfab62
 
 
 
 
 
82cdb59
4cfab62
 
971c29d
 
8cbc29f
367a695
8cbc29f
367a695
89af3b2
82cdb59
 
367a695
4cfab62
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
 
 
4cfab62
 
 
 
 
82cdb59
 
 
 
89af3b2
8cbc29f
82cdb59
 
 
 
89af3b2
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
 
 
 
 
 
 
82cdb59
 
 
367a695
82cdb59
 
 
8cbc29f
82cdb59
 
 
 
 
 
 
 
 
8cbc29f
82cdb59
 
 
 
 
89af3b2
82cdb59
 
8cbc29f
82cdb59
 
 
 
 
 
 
 
4cfab62
89af3b2
 
367a695
89af3b2
82cdb59
4cfab62
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367a695
82cdb59
8cbc29f
 
 
82cdb59
 
 
 
4cfab62
82cdb59
 
 
367a695
82cdb59
4cfab62
82cdb59
 
 
89af3b2
8cbc29f
89af3b2
82cdb59
 
4cfab62
 
89af3b2
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
816fa8a
971c29d
816fa8a
4cfab62
 
 
971c29d
82cdb59
367a695
82cdb59
367a695
82cdb59
 
367a695
 
 
 
 
 
 
 
4cfab62
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
89af3b2
 
82cdb59
 
 
 
 
4cfab62
 
 
367a695
 
 
 
 
82cdb59
 
 
 
4cfab62
 
 
971c29d
4cfab62
82cdb59
4cfab62
 
367a695
 
4cfab62
816fa8a
4cfab62
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// ---------------------------------------------------------------------------
// shell/LoginPage.tsx — X5: the branded door.
//
// DESIGN.md §4.5: every step shares one panel, form width and brand anchor.
//
// NO CLIENT-SIDE BACKOFF (X5: the server owns it). The only local rule is
// single-flight — a second submit while one is in the air is dropped, which is
// double-click protection, not rate limiting.
// ---------------------------------------------------------------------------

import { useEffect, useRef, useState } from "react";
import type { FormEvent } from "react";
import { Brand } from "./Brand";
import FreezeNotice from "./FreezeNotice";
import type { FreezeNoticeState } from "../settings/settingsApi";
import { changePassword, errorMessage, login, loginReason, parseUserEnvelope, passwordPolicy, SERVER_UNAVAILABLE } from "./session";
import type { LoginOutcome, PasswordPolicy, SessionUser } from "./session";
import { API_V1, CREDENTIALS } from "../apiContract";
import SecurityPane from "../settings/SecurityPane";
import { CodeInput } from "../ui/CodeInput";
import "../styles/wave57/login-mfa.css";

type Step = "credentials" | "expired" | "mfa" | "enrol";

async function loginRememberingBrowser(username: string, password: string, mfaCode: string): Promise<LoginOutcome> {
  let response: Response;
  try {
    response = await fetch(`${API_V1}/auth/login`, {
      method: "POST", credentials: CREDENTIALS, cache: "no-store",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ username, password, mfaCode, rememberBrowser: true }),
    });
  } catch {
    return { ok: false, reason: loginReason(0, null), message: errorMessage(0, null) };
  }
  const body: unknown = await response.json().catch(() => null);
  if (!response.ok) return { ok: false, reason: loginReason(response.status, body), message: errorMessage(response.status, body) };
  const user = parseUserEnvelope(body);
  return user ? { ok: true, user } : { ok: false, reason: "server", message: SERVER_UNAVAILABLE };
}

/** The reveal toggle the host's password field ships natively (BaseWeb's eye).
 *  Two doors, one affordance. */
function EyeIcon({ off }: { off: boolean }) {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true">
      <path d="M2.2 10s2.8-4.6 7.8-4.6S17.8 10 17.8 10 15 14.6 10 14.6 2.2 10 2.2 10z" />
      <circle cx="10" cy="10" r="2.3" />
      {off ? <path d="M4 16 16 4" /> : null}
    </svg>
  );
}

export default function LoginPage({ onSignedIn, freezeNotice }: {
  onSignedIn: (user: SessionUser) => void;
  freezeNotice?: FreezeNoticeState;
}) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [reveal, setReveal] = useState(false);
  const [step, setStep] = useState<Step>("credentials");
  const [newPassword, setNewPassword] = useState<string>("");
  const [confirmPassword, setConfirmPassword] = useState<string>("");
  const [code, setCode] = useState<string>("");
  const [recovery, setRecovery] = useState(false);
  const [rememberBrowser, setRememberBrowser] = useState(false);
  const [policy, setPolicy] = useState<PasswordPolicy | null>(null);
  const [policyLoading, setPolicyLoading] = useState<boolean>(false);
  const flight = useRef<boolean>(false);
  const stepHeading = useRef<HTMLHeadingElement>(null);
  const focusCode = useRef(false);

  // The password rules belong to the server, including history. Show its
  // checklist without inventing a second policy or claiming a local green pass.
  useEffect(() => {
    if (step !== "expired") return;
    let current = true;
    setPolicy(null);
    setPolicyLoading(true);
    void passwordPolicy().then((next) => {
      if (!current) return;
      setPolicy(next);
      setPolicyLoading(false);
    });
    return () => { current = false; };
  }, [step]);

  // Initial credentials keep the original no-autofocus rule. Later steps name
  // the new task to assistive tech, and focus the heading rather than a submit.
  useEffect(() => { stepHeading.current?.focus(); }, [step]);

  // Refocus after the failed request re-enables either code field.
  useEffect(() => {
    if (step !== "mfa" || busy || !focusCode.current) return;
    focusCode.current = false;
    document.getElementById("login-mfa-code")?.focus();
  }, [busy, step, error]);

  /** Correct credentials must survive a challenge. Clearing the password on
   *  every 401 would make the second-factor POST an invalid-credentials loop.
   *  It stays only in this mounted tree, and leaves with success or Back. */
  async function accept(result: LoginOutcome) {
    if (result.ok === true) {
      setPassword("");
      setCode("");
      setRememberBrowser(false);
      onSignedIn(result.user);
      return;
    }
    setError(result.message);
    switch (result.reason) {
      case "password_expired":
        setPolicyLoading(true);
        setStep("expired");
        setCode("");
        setRememberBrowser(false);
        break;
      case "mfa_required":
      case "mfa_invalid":
        setStep("mfa");
        setCode("");
        if (result.reason === "mfa_invalid") focusCode.current = true;
        break;
      case "mfa_enrolment_required":
        setRememberBrowser(false);
        setStep("enrol");
        break;
      default:
        // Keep the current challenge on network/backoff errors so retry uses
        // the proved password. A wrong initial credential is cleared as before.
        if (step === "credentials" && result.reason === "credentials") setPassword("");
    }
  }

  async function submit(e?: FormEvent, codeOverride?: string) {
    e?.preventDefault();
    if (flight.current) return;
    if (busy) return;
    flight.current = true;
    setBusy(true);
    setError("");
    try {
      if (step === "expired") {
        if (newPassword !== confirmPassword) {
          setError("The new passwords do not match.");
          return;
        }
        const changed = await changePassword(username, password, newPassword);
        if (changed.ok === false) {
          setError(changed.message);
          return;
        }
        // Rotation invalidates the old credential. Reuse the new one right
        // away, with a retryable credentials step if the next request is lost.
        setPassword(newPassword);
        setNewPassword("");
        setConfirmPassword("");
        setStep("credentials");
        await accept(await login(username, newPassword));
      } else {
        await accept(step === "mfa" && rememberBrowser
          ? await loginRememberingBrowser(username, password, codeOverride ?? code)
          : await login(username, password, step === "mfa" ? codeOverride ?? code : undefined));
      }
    } finally {
      flight.current = false;
      setBusy(false);
    }
  }

  function back() {
    if (flight.current) return;
    setStep("credentials");
    setPassword("");
    setNewPassword("");
    setConfirmPassword("");
    setCode("");
    setRecovery(false);
    setRememberBrowser(false);
    focusCode.current = false;
    setReveal(false);
    setError("");
  }

  function switchCode() {
    if (busy || flight.current) return;
    setRecovery((value) => !value);
    setCode("");
    setError("");
  }

  // An error that survives the correction is an error that reads as sticky.
  function edit(set: (v: string) => void) {
    return (e: { target: { value: string } }) => {
      if (error) setError("");
      set(e.target.value);
    };
  }

  return (
    <div className="login-root signed-out">
      <FreezeNotice notice={freezeNotice} standalone />
      <div className="signed-out-panel signed-out-login">
      <div className="login-card">
        <Brand size={44} className="login-brand" />

        {/* One form column and one anchor across every step. The extra content
            grows downward; no alternate width, position or brand lockup. */}
        {step === "expired" || step === "mfa" ? (
          <h2 className="login-mfa-heading" ref={stepHeading} tabIndex={-1}>
            {step === "expired" ? "New password" : "Two step sign in"}
          </h2>
        ) : null}
        {step === "enrol" ? (
          <SecurityPane gate={{ username, password, onBack: back, onEnrolled: (user) => {
            setPassword("");
            setCode("");
            onSignedIn(user);
          } }} />
        ) : (
        <>
        <form className="login-form" onSubmit={submit} noValidate>
          {step === "credentials" ? (
            <>
              {/* Labels are present and hidden, not absent. `gate()` collapses them
                  because Streamlit gives no other way to get a placeholder-only
                  field; here the label exists for assistive tech and the visual is
                  identical. */}
              {/* No autoFocus: the other door cannot autofocus (Streamlit), and the
                  focus ring it would paint on load reads as a highlighted error on
                  an untouched form. */}
              <label className="lp-sr-only" htmlFor="login-username">Username</label>
              <input
                id="login-username"
                className="login-input"
                name="username"
                type="text"
                autoComplete="username"
                placeholder="Username"
                value={username}
                onChange={edit(setUsername)}
                disabled={busy}
                aria-invalid={error ? true : undefined}
              />

              <label className="lp-sr-only" htmlFor="login-password">Password</label>
              <div className="login-field">
                <input
                  id="login-password"
                  className="login-input"
                  name="password"
                  type={reveal ? "text" : "password"}
                  autoComplete="current-password"
                  placeholder="Password"
                  value={password}
                  onChange={edit(setPassword)}
                  disabled={busy}
                  aria-invalid={error ? true : undefined}
                />
                {/* tabIndex -1: Tab goes Username to Password to Log in; the reveal is
                    a mouse affordance, same as the host's. */}
                <button
                  type="button"
                  className="login-eye"
                  aria-label={reveal ? "Hide password" : "Show password"}
                  onClick={() => setReveal((v) => !v)}
                  disabled={busy}
                  tabIndex={-1}
                >
                  <EyeIcon off={reveal} />
                </button>
              </div>
            </>
          ) : null}

          {step === "expired" ? (
            <>
              {policy ? (
                <ul className="login-mfa-policy" aria-label="Password requirements">
                  {policy.rules.map((rule) => <li key={rule.rule}>{rule.message}</li>)}
                </ul>
              ) : (
                <p className="login-mfa-help" role="status">
                  {policyLoading ? "Loading password requirements…"
                    : "Password requirements could not be loaded. Submit a new password to check it."}
                </p>
              )}
              <label className="login-mfa-label" htmlFor="login-new-password">New password</label>
              <input id="login-new-password" className="login-input" type="password" autoComplete="new-password"
                value={newPassword} onChange={edit(setNewPassword)} disabled={busy}
                aria-invalid={error ? true : undefined} aria-describedby="login-message" />
              <label className="login-mfa-label" htmlFor="login-confirm-password">Confirm new password</label>
              <input id="login-confirm-password" className="login-input" type="password" autoComplete="new-password"
                value={confirmPassword} onChange={edit(setConfirmPassword)} disabled={busy}
                aria-invalid={error ? true : undefined} aria-describedby="login-message" />
            </>
          ) : null}

          {step === "mfa" ? (
            <>
              <label className="login-mfa-help" htmlFor="login-remember-browser">
                <input id="login-remember-browser" type="checkbox" checked={rememberBrowser}
                  style={{ accentColor: "var(--lp-blue-deep)", cursor: busy ? "not-allowed" : "pointer", opacity: busy ? 0.55 : 1 }}
                  disabled={busy} onChange={(event) => setRememberBrowser(event.target.checked)} />
                {" "}Remember this browser for 7 days
              </label>
              <label className="login-mfa-label" htmlFor="login-mfa-code">
                {recovery ? "Recovery code" : "Authenticator code"}
              </label>
              {recovery ? (
                <input id="login-mfa-code" className="login-input" type="text"
                  autoComplete="off" maxLength={11} value={code} onChange={edit(setCode)}
                  disabled={busy} aria-invalid={error ? true : undefined}
                  aria-describedby="login-mfa-help login-message" autoFocus />
              ) : (
                <CodeInput id="login-mfa-code" value={code}
                  onChange={(value) => edit(setCode)({ target: { value } })}
                  onKeyboardComplete={(value) => submit(undefined, value)}
                  disabled={busy} invalid={Boolean(error)}
                  describedBy="login-mfa-help login-message" autoFocus />
              )}
              <button type="button" className="login-mfa-quiet" disabled={busy} onClick={switchCode}>
                {recovery ? "Use authenticator code" : "Use a recovery code"}
              </button>
              <p className="login-mfa-help" id="login-mfa-help">
                {recovery ? "Enter one of your saved recovery codes."
                  : "Enter the 6 digit code from your authenticator app."}
              </p>
              <p className="login-mfa-help">If you have lost both, ask an administrator to reset two step sign in.</p>
            </>
          ) : null}

          {/* Disabled through THREE channels (the real attribute, the cursor and
              the opacity), never opacity alone — a control that only looks dead
              is a control that still takes the click. */}
          <button className="login-submit" type="submit" disabled={busy}>
            {busy ? (step === "expired" ? "Updating password…" : "Signing in…")
              : step === "expired" ? "Set new password" : step === "mfa" ? "Verify and sign in" : "Log in"}
          </button>
          {step !== "credentials" ? (
            <button type="button" className="login-mfa-quiet login-mfa-back" disabled={busy} onClick={back}>
              Back to sign in
            </button>
          ) : null}
        </form>

        {/* The message line is ALWAYS in the layout (min-height: 1lh) so an
            arriving error does not move the form. `role="status"` rather than
            "alert": polite announcement, no interruption. */}
        <p className="login-msg" id="login-message" role="status" aria-live="polite">
          {error}
        </p>
        </>
        )}
      </div>
      </div>
    </div>
  );
}