File size: 16,041 Bytes
584ed90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
363
364
365
from __future__ import annotations

from html import escape
from typing import Mapping, Sequence
from urllib.parse import unquote, urlencode, urlsplit


AUTH_STYLESHEET = "/static/auth.css?v=20260806-06"


def _first(query: Mapping[str, Sequence[str]], name: str) -> str:
    values = query.get(name, ())
    return values[0] if values else ""


def safe_return_target(query: Mapping[str, Sequence[str]]) -> str | None:
    """Return a same-origin path, never an absolute or scheme-relative URL."""
    candidate = _first(query, "openid.return_to").strip()
    if not candidate or any(ord(character) < 32 for character in candidate):
        return None
    parsed = urlsplit(candidate)
    if parsed.scheme or parsed.netloc:
        return None
    if not parsed.path.startswith("/") or parsed.path.startswith("//") or "\\" in parsed.path:
        return None
    decoded_path = parsed.path
    for _ in range(2):
        decoded_path = unquote(decoded_path)
    if (
        decoded_path.startswith("//")
        or "\\" in decoded_path
        or any(ord(character) < 32 for character in decoded_path)
    ):
        return None
    return candidate


def _logo() -> str:
    return '<a class="auth-logo" href="/" aria-label="Amazon"></a>'


def _hidden_return_target(query: Mapping[str, Sequence[str]]) -> str:
    target = safe_return_target(query)
    if target is None:
        return ""
    return (
        '<input type="hidden" name="openid.return_to" value="'
        f'{escape(target, quote=True)}">'
    )


def _return_target_suffix(query: Mapping[str, Sequence[str]]) -> str:
    target = safe_return_target(query)
    return "?" + urlencode({"openid.return_to": target}) if target else ""


def _error_notice(message: str | None) -> str:
    if not message:
        return ""
    return f'<div class="auth-error" role="alert">{escape(message)}</div>'


def _document(
    title: str,
    content: str,
    *,
    body_class: str,
    scripts: Sequence[str] = (),
) -> str:
    script_markup = "".join(
        f'<script src="{escape(source, quote=True)}" defer></script>'
        for source in scripts
    )
    return f"""<!doctype html>
<html lang="en-us">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{escape(title)}</title>
  <link rel="stylesheet" href="{AUTH_STYLESHEET}">
  {script_markup}
</head>
<body class="auth-page {escape(body_class, quote=True)}">
  <header class="auth-header">{_logo()}</header>
  <main class="auth-main">
    {content}
  </main>
  <footer class="auth-footer">
    <nav aria-label="Amazon account policies">
      <a href="/gp/help/customer/display.html?nodeId=508088">Conditions of Use</a>
      <a href="/gp/help/customer/display.html?nodeId=468496">Privacy Notice</a>
      <a href="/gp/help/customer/display.html?nodeId=508510">Help</a>
    </nav>
    <p>© 1996–2026, Amazon.com, Inc. or its affiliates</p>
  </footer>
</body>
</html>"""


def signin_page(query: Mapping[str, Sequence[str]], error: str | None = None) -> str:
    if _first(query, "stage").lower() == "password":
        content = f"""
        <section class="auth-card" aria-labelledby="auth-heading">
          <h1 id="auth-heading">Sign in</h1>
          <p class="auth-identity">Amazon account</p>
          {_error_notice(error)}
          <form method="post" action="/ap/signin">
            {_hidden_return_target(query)}
            <label for="ap-password">Password</label>
            <a class="auth-inline-link" href="/ap/forgotpassword">Forgot password?</a>
            <input id="ap-password" name="password" type="password" autocomplete="current-password" required autofocus>
            <button class="auth-primary" type="submit">Sign in</button>
          </form>
          <label class="auth-checkbox"><input name="rememberMe" type="checkbox"> Keep me signed in</label>
          <details class="auth-details"><summary>Details</summary><p>Use this option only on your personal device.</p></details>
        </section>
        """
        return _document("Amazon Sign-In", content, body_class="auth-signin auth-password-stage")

    content = f"""
    <section class="auth-card" aria-labelledby="auth-heading">
      <h1 id="auth-heading">Sign in or create account</h1>
      {_error_notice(error)}
      <form method="post" action="/ap/signin">
        {_hidden_return_target(query)}
        <label for="ap-email">Enter mobile number or email</label>
        <input id="ap-email" name="email" type="text" autocomplete="username" inputmode="email" required autofocus>
        <button class="auth-primary" type="submit">Continue</button>
      </form>
      <p class="auth-legal">By continuing, you agree to Amazon's <a href="/gp/help/customer/display.html?nodeId=508088">Conditions of Use</a> and <a href="/gp/help/customer/display.html?nodeId=468496">Privacy Notice</a>.</p>
      <details class="auth-details"><summary>Need help?</summary><a href="/ap/forgotpassword">Forgot your password?</a><a href="/ap/register{escape(_return_target_suffix(query), quote=True)}">Create your Amazon account</a></details>
      <div class="auth-business"><strong>Buying for work?</strong> <a href="/gp/navigation/amazon-business">Create a free business account</a></div>
    </section>
    """
    return _document("Amazon Sign-In", content, body_class="auth-signin auth-identifier-stage")


def register_page(
    query: Mapping[str, Sequence[str]],
    error: str | None = None,
    *,
    external_verification: bool = False,
) -> str:
    suggested_email = _first(query, "email").strip()
    verification_controls = ""
    form_attributes = ""
    submit_attributes = ""
    scripts: tuple[str, ...] = ()
    if external_verification:
        form_attributes = ' data-external-registration="true"'
        submit_attributes = ' disabled data-auth-create-account'
        scripts = ("/static/auth-verification.js",)
        verification_controls = """
        <button class="auth-secondary auth-send-code" type="button" data-auth-send-code>Send Verification Code</button>
        <section class="auth-code-panel" data-auth-code-panel hidden aria-labelledby="auth-code-heading">
          <h2 id="auth-code-heading">Verify email address</h2>
          <label for="ap-register-code">Verification code</label>
          <input id="ap-register-code" type="text"
                 autocomplete="one-time-code" inputmode="numeric"
                 pattern="[0-9]{6}" maxlength="6" data-auth-code>
          <button class="auth-secondary" type="button" data-auth-verify-code>Verify code</button>
        </section>
        <p class="auth-api-status" data-auth-verification-status role="status" aria-live="polite"></p>
        """
    content = f"""
    <section class="auth-card" aria-labelledby="auth-heading">
      <h1 id="auth-heading">Create account</h1>
      {_error_notice(error)}
      <form method="post" action="/ap/register"{form_attributes}>
        {_hidden_return_target(query)}
        <label for="ap-customer-name">Your name</label>
        <input id="ap-customer-name" name="customerName" type="text" autocomplete="name" placeholder="First and last name" required autofocus>
        <label for="ap-register-email">Mobile number or email</label>
        <input id="ap-register-email" name="email" type="email" autocomplete="email" inputmode="email" value="{escape(suggested_email, quote=True)}" required data-auth-email>
        {verification_controls}
        <label for="ap-register-password">Password</label>
        <input id="ap-register-password" name="password" type="password" autocomplete="new-password" minlength="6" placeholder="At least 6 characters" required aria-describedby="password-hint" data-auth-password>
        <p id="password-hint" class="auth-hint"><span aria-hidden="true">i</span> Passwords must be at least 6 characters.</p>
        <label for="ap-password-check">Re-enter password</label>
        <input id="ap-password-check" name="passwordCheck" type="password" autocomplete="new-password" minlength="6" required data-auth-password-check>
        <button class="auth-primary" type="submit"{submit_attributes}>Continue</button>
      </form>
      <p class="auth-legal">By creating an account, you agree to Amazon's <a href="/gp/help/customer/display.html?nodeId=508088">Conditions of Use</a> and <a href="/gp/help/customer/display.html?nodeId=468496">Privacy Notice</a>.</p>
      <hr>
      <p class="auth-existing">Already have an account? <a href="/ap/signin{escape(_return_target_suffix(query), quote=True)}">Sign in <span aria-hidden="true">›</span></a></p>
    </section>
    """
    return _document(
        "Amazon Registration",
        content,
        body_class="auth-register",
        scripts=scripts,
    )


def forgot_password_page(
    query: Mapping[str, Sequence[str]], error: str | None = None
) -> str:
    if _first(query, "stage").lower() == "reset-password":
        content = f"""
        <section class="auth-card" aria-labelledby="auth-heading">
          <h1 id="auth-heading">Create new password</h1>
          <p>We'll ask for this password whenever you sign in.</p>
          {_error_notice(error)}
          <form method="post" action="/ap/forgotpassword">
            <label for="ap-new-password">New password</label>
            <input id="ap-new-password" name="password" type="password" autocomplete="new-password" minlength="6" required autofocus>
            <label for="ap-new-password-check">Re-enter password</label>
            <input id="ap-new-password-check" name="passwordCheck" type="password" autocomplete="new-password" minlength="6" required>
            <button class="auth-primary" type="submit">Save changes and sign in</button>
          </form>
        </section>
        """
        return _document("Create New Password", content, body_class="auth-forgot auth-reset-stage")

    content = f"""
    <section class="auth-card" aria-labelledby="auth-heading">
      <h1 id="auth-heading">Password assistance</h1>
      <p>Enter the email address or mobile phone number associated with your Amazon account.</p>
      {_error_notice(error)}
      <form method="post" action="/ap/forgotpassword">
        {_hidden_return_target(query)}
        <label for="ap-forgot-email">Email or mobile phone number</label>
        <input id="ap-forgot-email" name="email" type="text" autocomplete="username" inputmode="email" required autofocus>
        <button class="auth-primary" type="submit">Continue</button>
      </form>
    </section>
    <section class="auth-support-copy">
      <h2>Has your email or mobile number changed?</h2>
      <p>If you no longer use the email address associated with your Amazon account, you may contact Customer Service for help restoring access to your account.</p>
    </section>
    """
    return _document("Amazon Password Assistance", content, body_class="auth-forgot auth-email-stage")


def _mail_delivery_status_markup(
    purpose: str,
    mail_delivery: Mapping[str, object] | None,
    mail_delivery_mode: str,
    local_inbox_url: str | None = None,
) -> str:
    status = str((mail_delivery or {}).get("status") or "")
    if status not in {
        "QUEUED",
        "LOCAL_ONLY",
        "SMTP_PENDING",
        "SMTP_SENT",
        "SMTP_FAILED",
    }:
        status = "SMTP_PENDING" if mail_delivery_mode == "SMTP" else "LOCAL_ONLY"

    descriptions = {
        "QUEUED": (
            "If an account matches that address, its verification message is "
            "being handled. Refreshing does not reveal whether an account exists."
        ),
        "LOCAL_ONLY": (
            "This message is stored only in the protected local outbox; "
            "no external email was sent."
        ),
        "SMTP_PENDING": (
            "The configured SMTP service is processing this message. "
            "Refresh to check the latest delivery result."
        ),
        "SMTP_SENT": "The configured SMTP service accepted this message.",
        "SMTP_FAILED": (
            "The SMTP attempt failed. No address or provider error is exposed here."
        ),
    }
    action_suffix = "?" + urlencode({"purpose": purpose})
    actions: list[str] = []
    if status in {"QUEUED", "SMTP_PENDING"}:
        actions.append(
            f'<a class="auth-status-link" href="/ap/cvf/verify{escape(action_suffix, quote=True)}">Refresh delivery status</a>'
        )
    if status == "SMTP_FAILED" and bool((mail_delivery or {}).get("can_retry")):
        actions.append(
            '<form class="auth-retry-form" method="post" '
            f'action="/ap/cvf/verify{escape(action_suffix, quote=True)}">'
            '<button class="auth-link-button" type="submit" name="action" '
            'value="retry-delivery">Retry email delivery</button></form>'
        )
    if local_inbox_url and status in {"SMTP_PENDING", "SMTP_SENT", "SMTP_FAILED"}:
        actions.append(
            f'<a class="auth-status-link" href="{escape(local_inbox_url, quote=True)}">'
            "Open local SMTP inbox</a>"
        )
    action_markup = (
        f'<div class="auth-delivery-actions">{"".join(actions)}</div>'
        if actions
        else ""
    )
    return (
        f'<section class="auth-delivery-status auth-delivery-{status.casefold()}" '
        'aria-live="polite"><h2>Email delivery</h2>'
        f'<p><strong>{status}</strong><span>{escape(descriptions[status])}</span></p>'
        f'{action_markup}</section>'
    )


def verification_page(
    query: Mapping[str, Sequence[str]],
    *,
    masked_destination: str | None = None,
    error: str | None = None,
    mail_delivery_mode: str = "LOCAL_ONLY",
    mail_delivery: Mapping[str, object] | None = None,
    local_inbox_url: str | None = None,
) -> str:
    purpose = _first(query, "purpose").lower()
    if purpose == "registration" and masked_destination:
        lead = (
            f"A verification code was queued for {masked_destination}. "
            "Enter it below when it arrives."
        )
    elif purpose == "registration":
        lead = "Start account creation again to request a new email verification code."
    elif purpose == "password-reset":
        lead = (
            "If an account matches that address, a verification code was queued. "
            "Enter it below if it arrives."
        )
    else:
        lead = "Enter the one-time password that was queued for you."
    action_suffix = (
        "?" + urlencode({"purpose": purpose})
        if purpose in {"registration", "password-reset"}
        else ""
    )
    delivery_status = _mail_delivery_status_markup(
        purpose,
        mail_delivery,
        mail_delivery_mode,
        local_inbox_url,
    )
    content = f"""
    <section class="auth-card" aria-labelledby="auth-heading">
      <h1 id="auth-heading">Verify email address</h1>
      <p>{escape(lead)}</p>
      {_error_notice(error)}
      <form method="post" action="/ap/cvf/verify{escape(action_suffix, quote=True)}">
        <label for="ap-code">Enter verification code</label>
        <input id="ap-code" name="code" type="text" autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]{{6}}" maxlength="6" required autofocus>
        <button class="auth-primary" type="submit">Verify</button>
      </form>
      <form class="auth-resend-form" method="post" action="/ap/cvf/verify{escape(action_suffix, quote=True)}">
        <button class="auth-link-button" type="submit" name="action" value="resend">Resend code</button>
      </form>
      {delivery_status}
    </section>
    """
    return _document("Amazon Verification", content, body_class="auth-verification")


def page_for(path: str, query: Mapping[str, Sequence[str]]) -> str:
    if path == "/ap/signin":
        return signin_page(query)
    if path == "/ap/register":
        return register_page(query)
    if path == "/ap/forgotpassword":
        return forgot_password_page(query)
    if path == "/ap/cvf/verify":
        return verification_page(query)
    raise ValueError(f"unsupported auth path: {path}")