amazon-auth 0.2.5__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/PKG-INFO +7 -1
  2. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/README.md +6 -0
  3. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazon_auth.egg-info/PKG-INFO +7 -1
  4. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/__init__.py +1 -1
  5. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/conf.py +118 -15
  6. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/contrib/browser/playwright.py +30 -34
  7. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/session.py +31 -1
  8. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/util.py +13 -4
  9. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/tests/test_conf.py +25 -0
  10. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/tests/test_session.py +116 -0
  11. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/tests/test_util.py +10 -0
  12. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/LICENSE +0 -0
  13. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazon_auth.egg-info/SOURCES.txt +0 -0
  14. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazon_auth.egg-info/dependency_links.txt +0 -0
  15. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazon_auth.egg-info/requires.txt +0 -0
  16. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazon_auth.egg-info/top_level.txt +0 -0
  17. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/cli.py +0 -0
  18. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/constants.py +0 -0
  19. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/contrib/__init__.py +0 -0
  20. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/contrib/browser/__init__.py +0 -0
  21. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/contrib/waf/__init__.py +0 -0
  22. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/contrib/waf/anticaptcha.py +0 -0
  23. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/contrib/waf/base.py +0 -0
  24. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/contrib/waf/capsolver.py +0 -0
  25. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/contrib/waf/twocaptcha.py +0 -0
  26. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/exception.py +0 -0
  27. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/forms.py +0 -0
  28. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/py.typed +0 -0
  29. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/region_data.py +0 -0
  30. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/amazonauth/selectors.py +0 -0
  31. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/pyproject.toml +0 -0
  32. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/setup.cfg +0 -0
  33. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/tests/test_cli.py +0 -0
  34. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/tests/test_constants.py +0 -0
  35. {amazon_auth-0.2.5 → amazon_auth-0.3.0}/tests/test_package.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: amazon-auth
3
- Version: 0.2.5
3
+ Version: 0.3.0
4
4
  Summary: Sign in to Amazon's consumer website and reuse the session from Python.
5
5
  Author-email: Alex Laird <contact@alexlaird.com>
6
6
  Maintainer-email: Alex Laird <contact@alexlaird.com>
@@ -126,6 +126,12 @@ PlaywrightBrowserLogin(amazon_session).login()
126
126
 
127
127
  The session is persisted, so `AmazonSession().login()` reuses it without credentials.
128
128
 
129
+ ### Building on `amazon-auth`
130
+
131
+ `amazon-auth` is meant to be built on: packages that read more of Amazon's website, like
132
+ [`amazon-orders`](https://amazon-orders.readthedocs.io), subclass its config, session, constants and selectors, and
133
+ register its CLI commands. See [Building on `amazon-auth`](https://amazon-auth.readthedocs.io/downstream.html).
134
+
129
135
  ## Documentation
130
136
 
131
137
  For more advanced usage, `amazon-auth`'s official documentation is available
@@ -56,6 +56,12 @@ PlaywrightBrowserLogin(amazon_session).login()
56
56
 
57
57
  The session is persisted, so `AmazonSession().login()` reuses it without credentials.
58
58
 
59
+ ### Building on `amazon-auth`
60
+
61
+ `amazon-auth` is meant to be built on: packages that read more of Amazon's website, like
62
+ [`amazon-orders`](https://amazon-orders.readthedocs.io), subclass its config, session, constants and selectors, and
63
+ register its CLI commands. See [Building on `amazon-auth`](https://amazon-auth.readthedocs.io/downstream.html).
64
+
59
65
  ## Documentation
60
66
 
61
67
  For more advanced usage, `amazon-auth`'s official documentation is available
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: amazon-auth
3
- Version: 0.2.5
3
+ Version: 0.3.0
4
4
  Summary: Sign in to Amazon's consumer website and reuse the session from Python.
5
5
  Author-email: Alex Laird <contact@alexlaird.com>
6
6
  Maintainer-email: Alex Laird <contact@alexlaird.com>
@@ -126,6 +126,12 @@ PlaywrightBrowserLogin(amazon_session).login()
126
126
 
127
127
  The session is persisted, so `AmazonSession().login()` reuses it without credentials.
128
128
 
129
+ ### Building on `amazon-auth`
130
+
131
+ `amazon-auth` is meant to be built on: packages that read more of Amazon's website, like
132
+ [`amazon-orders`](https://amazon-orders.readthedocs.io), subclass its config, session, constants and selectors, and
133
+ register its CLI commands. See [Building on `amazon-auth`](https://amazon-auth.readthedocs.io/downstream.html).
134
+
129
135
  ## Documentation
130
136
 
131
137
  For more advanced usage, `amazon-auth`'s official documentation is available
@@ -1,4 +1,4 @@
1
1
  __copyright__ = "Copyright (c) 2026 Alex Laird"
2
2
  __license__ = "MIT"
3
- __version__ = "0.2.5"
3
+ __version__ = "0.3.0"
4
4
  __muppets__ = "no strings attached"
@@ -4,8 +4,10 @@ __license__ = "MIT"
4
4
  import inspect
5
5
  import logging
6
6
  import os
7
+ import re
7
8
  import threading
8
- from typing import Any, Dict, Optional, Set, Union
9
+ import warnings
10
+ from typing import Any, Dict, List, Optional, Set, Union
9
11
  from urllib.parse import urlparse
10
12
 
11
13
  import yaml
@@ -28,6 +30,16 @@ ENVIRONMENT_VARIABLE_PREFIX = "AMAZON_"
28
30
  #: The Amazon site whose session is kept in the default ``cookie_jar_path`` itself, rather than in a jar of its own.
29
31
  DEFAULT_COOKIE_JAR_SITE = "amazon.com"
30
32
 
33
+ #: The account whose sessions are kept beside the default ``cookie_jar_path`` itself, rather than in a directory of
34
+ #: its own, and the one used when no ``account`` is given.
35
+ DEFAULT_ACCOUNT = "default"
36
+
37
+ #: The directory, beside the default ``cookie_jar_path``, where each other account's sessions are kept, in a
38
+ #: directory named for the account.
39
+ ACCOUNTS_DIRECTORY = "accounts"
40
+
41
+ ACCOUNT_NAME_PATTERN = re.compile(r"^[a-z0-9_-]+$")
42
+
31
43
 
32
44
  class AmazonAuthConfig:
33
45
  """
@@ -66,7 +78,7 @@ class AmazonAuthConfig:
66
78
  #: The path to use for the config file.
67
79
  self.config_path: str = os.path.join(DEFAULT_CONFIG_DIR, "config.yml") if config_path is None else config_path
68
80
 
69
- self._data: Dict[str, Any] = self._default_data()
81
+ self._data: Dict[str, Any] = self._defaults()
70
82
  self._environment: Dict[str, Any] = self.read_environment()
71
83
  self._resolved_classes: Dict[str, Any] = {}
72
84
  self._assigned_classes: Dict[str, Any] = {}
@@ -86,6 +98,7 @@ class AmazonAuthConfig:
86
98
 
87
99
  self._validate_bs4_parser()
88
100
  self._validate_class_paths()
101
+ self._validate_account()
89
102
 
90
103
  #: The :class:`~amazonauth.constants.AuthConstants` in use, rebuilt when the domain changes.
91
104
  self.constants: Any
@@ -100,7 +113,7 @@ class AmazonAuthConfig:
100
113
  :return: The config values set in the environment, by config key.
101
114
  :raises AmazonAuthError: If the value of a key with a default is not valid YAML.
102
115
  """
103
- default_data = cls._default_data()
116
+ default_data = cls._defaults()
104
117
  environment = {}
105
118
  for name, value in os.environ.items():
106
119
  if not name.startswith(ENVIRONMENT_VARIABLE_PREFIX) or not value:
@@ -136,9 +149,10 @@ class AmazonAuthConfig:
136
149
  return self._data.get(key)
137
150
 
138
151
  @staticmethod
139
- def _default_data() -> Dict[str, Any]:
152
+ def default_data() -> Dict[str, Any]:
140
153
  """
141
- Provision the default config values.
154
+ Provision the default config values. A subclass with config keys of its own adds them here, on top of
155
+ ``AmazonAuthConfig.default_data()``.
142
156
 
143
157
  :return: The default config values.
144
158
  """
@@ -169,6 +183,21 @@ class AmazonAuthConfig:
169
183
  "max_auth_retries": 1
170
184
  }
171
185
 
186
+ @staticmethod
187
+ def _default_data() -> Dict[str, Any]:
188
+ """
189
+ Deprecated, use :func:`default_data` instead. To be removed in 1.0.
190
+ """
191
+ warnings.warn("_default_data() is deprecated and will be removed in 1.0. Override default_data() instead.",
192
+ DeprecationWarning, stacklevel=2)
193
+ return AmazonAuthConfig.default_data()
194
+
195
+ @classmethod
196
+ def _defaults(cls) -> Dict[str, Any]:
197
+ if cls._default_data is not AmazonAuthConfig._default_data:
198
+ return cls._default_data()
199
+ return cls.default_data()
200
+
172
201
  @staticmethod
173
202
  def _default_cookie_jar_path() -> str:
174
203
  return os.path.join(DEFAULT_CONFIG_DIR, "cookies.json")
@@ -196,7 +225,7 @@ class AmazonAuthConfig:
196
225
  try:
197
226
  return util.load_class(module_path.split("."), class_name)
198
227
  except ModuleNotFoundError as e:
199
- default_class_path = self._default_data()[key]
228
+ default_class_path = self._defaults()[key]
200
229
  if (class_path == default_class_path or not e.name or
201
230
  not (module_path == e.name or module_path.startswith(f"{e.name}."))):
202
231
  raise
@@ -237,6 +266,23 @@ class AmazonAuthConfig:
237
266
  source = self._environment if "bs4_parser" in self._environment else self._data
238
267
  source["bs4_parser"] = "html.parser"
239
268
 
269
+ def _validate_account(self) -> None:
270
+ account = self.account
271
+ if not ACCOUNT_NAME_PATTERN.match(account):
272
+ raise AmazonAuthError(f"\"{account}\" isn't a name an account can have. An account's name is letters, "
273
+ "digits, \"-\" and \"_\".")
274
+ if account != DEFAULT_ACCOUNT and self._get("cookie_jar_path") != self._default_cookie_jar_path():
275
+ raise AmazonAuthError(f"The \"{account}\" account can't be used with the cookie_jar_path setting, since "
276
+ "every account's session would be kept in it. Leave it unset for each account to "
277
+ "have its own.")
278
+
279
+ def _has_cookie_jar(self,
280
+ directory: str) -> bool:
281
+ root, extension = os.path.splitext(os.path.basename(self._default_cookie_jar_path()))
282
+ return os.path.isdir(directory) and any(
283
+ name == f"{root}{extension}" or (name.startswith(f"{root}.") and name.endswith(extension))
284
+ for name in os.listdir(directory))
285
+
240
286
  def _instantiate_constants(self) -> Any:
241
287
  constants_cls = self._load_configured_class("constants_class")
242
288
  # Pass ``self`` only when the constants class accepts a config arg, to keep backward
@@ -257,25 +303,80 @@ class AmazonAuthConfig:
257
303
  self._data["domain"] = domain
258
304
  self.constants = self._instantiate_constants()
259
305
 
306
+ def set_account(self,
307
+ account: Optional[str]) -> None:
308
+ """
309
+ Set the active Amazon account, whose sessions are read and saved.
310
+
311
+ :param account: The account's name, or ``None`` for the ``default`` account.
312
+ :raises AmazonAuthError: If the name isn't one an account can have, or ``cookie_jar_path`` is set.
313
+ """
314
+ previous_account = self._data.get("account")
315
+ self._data["account"] = account
316
+ try:
317
+ self._validate_account()
318
+ except AmazonAuthError:
319
+ self._data["account"] = previous_account
320
+ raise
321
+
260
322
  @property
261
323
  def site(self) -> str:
262
324
  """The active Amazon site, the host of the ``domain`` without ``www.`` (e.g. ``amazon.de``)."""
263
325
  return (urlparse(self.constants.BASE_URL).hostname or "").removeprefix("www.")
264
326
 
327
+ @property
328
+ def account(self) -> str:
329
+ """The active Amazon account's name, the ``account`` set (in lowercase), or else ``default``."""
330
+ account = self._get("account")
331
+ return DEFAULT_ACCOUNT if account in (None, "") else str(account).lower()
332
+
333
+ def accounts(self) -> List[str]:
334
+ """
335
+ Get the active account, then every other account with a saved session (a cookie jar) on any site, signed in
336
+ or not. With an explicit ``cookie_jar_path``, there's only the active account.
337
+
338
+ :return: The accounts' names.
339
+ """
340
+ accounts = [self.account]
341
+ default_cookie_jar_path = self._default_cookie_jar_path()
342
+ if self._get("cookie_jar_path") != default_cookie_jar_path:
343
+ return accounts
344
+
345
+ config_dir = os.path.dirname(default_cookie_jar_path)
346
+ account_dirs = {DEFAULT_ACCOUNT: config_dir}
347
+ accounts_dir = os.path.join(config_dir, ACCOUNTS_DIRECTORY)
348
+ if os.path.isdir(accounts_dir):
349
+ for name in sorted(os.listdir(accounts_dir)):
350
+ if name != DEFAULT_ACCOUNT and ACCOUNT_NAME_PATTERN.match(name):
351
+ account_dirs[name] = os.path.join(accounts_dir, name)
352
+
353
+ for account, directory in account_dirs.items():
354
+ if account not in accounts and self._has_cookie_jar(directory):
355
+ accounts.append(account)
356
+
357
+ return accounts
358
+
265
359
  @property
266
360
  def cookie_jar_path(self) -> str:
267
361
  """
268
- The path the session for the active ``domain`` is persisted to, since each Amazon site has its own sign-in.
269
- With the default ``cookie_jar_path``, the ``amazon.com`` session is kept there (``cookies.json``), and every
270
- other site's beside it, named for the site (e.g. ``cookies.amazon.de.json``). Any other ``cookie_jar_path``
271
- is used as-is, whatever the site.
362
+ The path the session for the active ``domain`` and ``account`` is persisted to, since each Amazon site and
363
+ account has its own sign-in. With the default ``cookie_jar_path``, the default account's ``amazon.com``
364
+ session is kept there (``cookies.json``), and every other site's beside it, named for the site (e.g.
365
+ ``cookies.amazon.de.json``). Each other account's are kept the same way, in a directory of their own (e.g.
366
+ ``accounts/spouse/cookies.json``). Any other ``cookie_jar_path`` is used as-is, whatever the site.
272
367
  """
273
368
  cookie_jar_path = self._get("cookie_jar_path")
274
- if cookie_jar_path != self._default_cookie_jar_path() or self.site == DEFAULT_COOKIE_JAR_SITE:
369
+ if cookie_jar_path != self._default_cookie_jar_path():
275
370
  return cookie_jar_path
276
371
 
277
- root, extension = os.path.splitext(cookie_jar_path)
278
- return f"{root}.{self.site}{extension}"
372
+ directory, filename = os.path.split(cookie_jar_path)
373
+ if self.account != DEFAULT_ACCOUNT:
374
+ directory = os.path.join(directory, ACCOUNTS_DIRECTORY, self.account)
375
+ if self.site != DEFAULT_COOKIE_JAR_SITE:
376
+ root, extension = os.path.splitext(filename)
377
+ filename = f"{root}.{self.site}{extension}"
378
+
379
+ return os.path.join(directory, filename)
279
380
 
280
381
  @cookie_jar_path.setter
281
382
  def cookie_jar_path(self,
@@ -286,10 +387,11 @@ class AmazonAuthConfig:
286
387
  def shared_cookie_jar_path(self) -> Optional[str]:
287
388
  """
288
389
  The default ``cookie_jar_path``, which every site's session was persisted to before each site had its own,
289
- when the active ``domain`` now has a jar of its own (see :attr:`cookie_jar_path`), otherwise ``None``.
390
+ when the active ``domain`` now has a jar of its own (see :attr:`cookie_jar_path`), otherwise ``None``. Only
391
+ the default account had sessions then, so it's always ``None`` for any other account.
290
392
  """
291
393
  shared_cookie_jar_path = self._get("cookie_jar_path")
292
- if self.cookie_jar_path == shared_cookie_jar_path:
394
+ if self.account != DEFAULT_ACCOUNT or self.cookie_jar_path == shared_cookie_jar_path:
293
395
  return None
294
396
 
295
397
  return shared_cookie_jar_path
@@ -331,6 +433,7 @@ class AmazonAuthConfig:
331
433
  try:
332
434
  self._validate_bs4_parser()
333
435
  self._validate_class_paths()
436
+ self._validate_account()
334
437
  if key in ("constants_class", "selectors_class"):
335
438
  module_path, class_name = self._class_path(key).rsplit(".", 1)
336
439
  util.load_class(module_path.split("."), class_name)
@@ -40,17 +40,6 @@ SIGN_IN_SETTLE_MS = 2000
40
40
  SIGN_IN_PREFILL_TIMEOUT_MS = 5000
41
41
 
42
42
 
43
- def _jar_cookie_attributes(pw_cookie: Dict[str, Any]) -> Dict[str, Any]:
44
- """
45
- The attributes of a browser cookie, as the session's cookie jar takes them. ``secure`` is kept, so a cookie only
46
- sent over ``https`` in the browser is only sent over ``https`` by the session too.
47
- """
48
- expires = pw_cookie.get("expires", -1)
49
- return {"domain": pw_cookie.get("domain"), "path": pw_cookie.get("path", "/"),
50
- "secure": bool(pw_cookie.get("secure", False)),
51
- "expires": int(expires) if expires and expires > 0 else None}
52
-
53
-
54
43
  class PlaywrightBrowserLauncher:
55
44
  """
56
45
  Launches the browser the config selects, from whatever Playwright supports. ``browser`` is either a browser that's
@@ -74,13 +63,15 @@ class PlaywrightBrowserLauncher:
74
63
  def launch(self,
75
64
  pw: Any,
76
65
  headless: bool,
77
- args: Optional[List[str]] = None) -> Any:
66
+ args: Optional[List[str]] = None,
67
+ env: Optional[Dict[str, str]] = None) -> Any:
78
68
  """
79
69
  Launch the browser the config selects.
80
70
 
81
71
  :param pw: The running Playwright instance.
82
72
  :param headless: Whether to launch the browser without a window.
83
73
  :param args: Command line arguments to launch the browser with, beside Playwright's own.
74
+ :param env: The browser child's environment, or ``None`` to inherit the process environment.
84
75
  :return: The launched Playwright ``Browser``.
85
76
  :raises AmazonAuthBrowserNotInstalledError: If no browser is installed to launch.
86
77
  :raises AmazonAuthError: If the browser can't be launched.
@@ -90,9 +81,9 @@ class PlaywrightBrowserLauncher:
90
81
  browser_name = self.config.browser
91
82
  executable_path = self.config.browser_executable_path
92
83
  if not browser_name and not executable_path:
93
- return self._launch_default(pw, headless, args)
84
+ return self._launch_default(pw, headless, args, env)
94
85
 
95
- launch_options = self._launch_options(headless, args)
86
+ launch_options = self._launch_options(headless, args, env)
96
87
  channel = None
97
88
  browser_type = self._browser_types(pw).get(browser_name or self.FALLBACK_BROWSER_TYPE)
98
89
  if browser_type is None:
@@ -143,10 +134,11 @@ class PlaywrightBrowserLauncher:
143
134
  def _launch_default(self,
144
135
  pw: Any,
145
136
  headless: bool,
146
- args: Optional[List[str]]) -> Any:
137
+ args: Optional[List[str]],
138
+ env: Optional[Dict[str, str]]) -> Any:
147
139
  from playwright.sync_api import Error as PlaywrightError # type: ignore[import-not-found]
148
140
 
149
- launch_options = self._launch_options(headless, args)
141
+ launch_options = self._launch_options(headless, args, env)
150
142
  for channel in (self.DEFAULT_BROWSER_CHANNEL, self.FALLBACK_BROWSER_CHANNEL):
151
143
  try:
152
144
  return pw.chromium.launch(channel=channel, **launch_options)
@@ -173,10 +165,13 @@ class PlaywrightBrowserLauncher:
173
165
 
174
166
  @staticmethod
175
167
  def _launch_options(headless: bool,
176
- args: Optional[List[str]]) -> Dict[str, Any]:
168
+ args: Optional[List[str]],
169
+ env: Optional[Dict[str, str]]) -> Dict[str, Any]:
177
170
  launch_options: Dict[str, Any] = {"headless": headless}
178
171
  if args:
179
172
  launch_options["args"] = args
173
+ if env is not None:
174
+ launch_options["env"] = env
180
175
 
181
176
  return launch_options
182
177
 
@@ -371,9 +366,7 @@ class PlaywrightAuthForm(AuthForm):
371
366
  def _harvest_cookies(self, context: Any) -> None:
372
367
  if not self.amazon_session:
373
368
  return # pragma: no cover
374
- for pw_cookie in context.cookies():
375
- self.amazon_session.session.cookies.set(pw_cookie["name"], pw_cookie["value"],
376
- **_jar_cookie_attributes(pw_cookie))
369
+ self.amazon_session._load_cookie_jar_data(context.cookies())
377
370
 
378
371
  def _save_debug_snapshot(self, page: Any, output_dir: Optional[str], name: str) -> None:
379
372
  if not output_dir:
@@ -904,13 +897,14 @@ class PlaywrightBrowserLogin:
904
897
  f"Install it with: `pip install {self.config.PACKAGE_NAME}[browser]`"
905
898
  ) from e
906
899
 
907
- self._require_display()
900
+ env = self.launch_env()
901
+ self._require_display(env)
908
902
 
909
903
  constants = self.config.constants
910
904
  sign_in_url = f"{constants.SIGN_IN_URL}?{urlencode(constants.SIGN_IN_QUERY_PARAMS)}"
911
905
 
912
906
  with sync_playwright() as pw:
913
- browser = PlaywrightBrowserLauncher(self.config).launch(pw, self.headless, self.launch_args())
907
+ browser = PlaywrightBrowserLauncher(self.config).launch(pw, self.headless, self.launch_args(), env=env)
914
908
 
915
909
  try:
916
910
  context = self.new_context(browser)
@@ -938,6 +932,15 @@ class PlaywrightBrowserLogin:
938
932
  """
939
933
  return None
940
934
 
935
+ def launch_env(self) -> Optional[Dict[str, str]]:
936
+ """
937
+ Hook for the environment to launch the browser with. By default, the browser inherits this process's. A
938
+ mapping replaces it, so copy ``os.environ`` first if the browser should inherit other variables.
939
+
940
+ :return: The child's environment, or ``None`` to inherit it.
941
+ """
942
+ return None
943
+
941
944
  def new_context(self,
942
945
  browser: Any) -> Any:
943
946
  """
@@ -986,8 +989,9 @@ class PlaywrightBrowserLogin:
986
989
  except Exception as e:
987
990
  logger.debug(f"Skipped pre-filling the username in the browser: {e}")
988
991
 
989
- def _require_display(self) -> None:
990
- if not self.headless and not has_display():
992
+ def _require_display(self,
993
+ env: Optional[Dict[str, str]]) -> None:
994
+ if not self.headless and not has_display(env):
991
995
  raise AmazonAuthError("Signing in with a browser requires a display, and this machine doesn't have one.")
992
996
 
993
997
  def wait_for_sign_in(self,
@@ -1027,21 +1031,13 @@ class PlaywrightBrowserLogin:
1027
1031
 
1028
1032
  def _amazon_cookies(self,
1029
1033
  cookies: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1030
- base_domain = (urlparse(self.config.constants.BASE_URL).hostname or "").removeprefix("www.")
1031
-
1032
- return [cookie for cookie in cookies if self._is_domain_or_subdomain(cookie["domain"], base_domain)]
1033
-
1034
- @staticmethod
1035
- def _is_domain_or_subdomain(domain: str,
1036
- parent_domain: str) -> bool:
1037
- return f".{domain.lstrip('.')}".endswith(f".{parent_domain}")
1034
+ return [cookie for cookie in cookies if self.amazon_session._is_site_cookie(cookie)]
1038
1035
 
1039
1036
  def _harvest_cookies(self,
1040
1037
  context: Any) -> None:
1041
1038
  cookie_jar = self.amazon_session.session.cookies
1042
1039
  cookie_jar.clear()
1043
- for cookie in self._amazon_cookies(context.cookies()):
1044
- cookie_jar.set(cookie["name"], cookie["value"], **_jar_cookie_attributes(cookie))
1040
+ self.amazon_session._load_cookie_jar_data(self._amazon_cookies(context.cookies()))
1045
1041
 
1046
1042
  def _verify_session(self) -> None:
1047
1043
  try:
@@ -361,6 +361,35 @@ class AmazonSession:
361
361
 
362
362
  return True
363
363
 
364
+ def import_cookies(self,
365
+ cookies: List[Dict[str, Any]],
366
+ verify: bool = True) -> None:
367
+ """
368
+ Replace this session's cookies with the given ones for the configured site, and persist them. Accepts cookies
369
+ as Playwright's ``BrowserContext.cookies()`` returns them.
370
+
371
+ By default, Amazon is asked whether it accepts the session, as :func:`check_session` does with ``verify``,
372
+ and ``is_authenticated`` is set to ``True`` if it does. If it doesn't, they still replace this session's
373
+ cookies, and may already have been saved. With ``verify=False``, no request is made.
374
+
375
+ :param cookies: Cookies with name, value and domain, and optional path, secure and expires attributes.
376
+ :param verify: Whether to verify the imported session with :func:`check_session`.
377
+ :raises AmazonAuthSignInError: If verification finds no authenticated session or Amazon rejects it.
378
+ :raises AmazonAuthError: If the verification request fails.
379
+ """
380
+ self.is_authenticated = False
381
+ self._sign_in_required = False
382
+ self.session.cookies.clear()
383
+ self._load_cookie_jar_data([cookie for cookie in cookies if self._is_site_cookie(cookie)])
384
+
385
+ if verify:
386
+ if not self.check_session(verify=True):
387
+ raise AmazonAuthSignInError("Amazon did not accept the imported session. Try signing in again.")
388
+ self.is_authenticated = True
389
+
390
+ with cookies_file_lock:
391
+ self._write_cookie_jar()
392
+
364
393
  def login(self) -> None:
365
394
  """
366
395
  Execute an Amazon login process. This will include the sign-in page, and may also include OTP (if 2FA is
@@ -445,9 +474,10 @@ class AmazonSession:
445
474
  data = [{"name": name, "value": value, "domain": domain} for name, value in data.items()]
446
475
 
447
476
  for cookie in data:
477
+ expires = cookie.get("expires")
448
478
  self.session.cookies.set(cookie["name"], cookie["value"], domain=cookie.get("domain", ""),
449
479
  path=cookie.get("path", "/"), secure=cookie.get("secure", False),
450
- expires=cookie.get("expires"))
480
+ expires=int(expires) if expires is not None and expires >= 0 else None)
451
481
 
452
482
  def _load_shared_cookie_jar(self) -> None:
453
483
  """
@@ -7,7 +7,7 @@ import os
7
7
  import re
8
8
  import sys
9
9
  import tempfile
10
- from typing import List, Union, Optional, Callable, Any
10
+ from typing import List, Union, Optional, Callable, Any, Mapping
11
11
 
12
12
  from bs4 import Tag, BeautifulSoup
13
13
  from requests import Response
@@ -115,15 +115,18 @@ def load_class(package: List[str], clazz: str) -> Union[Callable, Any]:
115
115
  return getattr(constants_mod, clazz)
116
116
 
117
117
 
118
- def has_display() -> bool:
118
+ def has_display(env: Optional[Mapping[str, str]] = None) -> bool:
119
119
  """
120
120
  Check whether a browser window can be opened here, as signing in with a browser window needs. On Linux, that
121
121
  needs a display (``DISPLAY`` or ``WAYLAND_DISPLAY``), which a server or a container usually doesn't have. Other
122
122
  platforms always have one.
123
123
 
124
+ :param env: The environment to check, or ``None`` for the process environment.
124
125
  :return: Whether there's a display.
125
126
  """
126
- return not sys.platform.startswith("linux") or bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
127
+ environment = os.environ if env is None else env
128
+ return not sys.platform.startswith("linux") or bool(
129
+ environment.get("DISPLAY") or environment.get("WAYLAND_DISPLAY"))
127
130
 
128
131
 
129
132
  def cleanup_html_text(text: str) -> str:
@@ -175,4 +178,10 @@ def make_private_dirs(path: str) -> None:
175
178
 
176
179
  :param path: The directory to create.
177
180
  """
178
- os.makedirs(path, mode=0o700, exist_ok=True)
181
+ missing_dirs = []
182
+ while path and not os.path.isdir(path):
183
+ missing_dirs.append(path)
184
+ path = os.path.dirname(path)
185
+
186
+ for directory in reversed(missing_dirs):
187
+ os.makedirs(directory, mode=0o700, exist_ok=True)
@@ -389,3 +389,28 @@ some_custom_config: {custom_config}
389
389
 
390
390
  # THEN
391
391
  self.assertEqual("/some/cookies.json", config.cookie_jar_path)
392
+
393
+ def test_downstream_config_adds_its_own_defaults(self):
394
+ # WHEN
395
+ config = DownstreamConfig(data={})
396
+
397
+ # THEN
398
+ self.assertEqual(20, config.page_size)
399
+ self.assertEqual(AmazonAuthConfig.default_data()["max_auth_attempts"], config.max_auth_attempts)
400
+
401
+ def test_downstream_config_reads_its_own_default_key_from_the_environment_as_yaml(self):
402
+ # WHEN
403
+ with patch.dict(os.environ, {"AMAZON_PAGE_SIZE": "30"}):
404
+ config = DownstreamConfig(data={})
405
+
406
+ # THEN
407
+ self.assertEqual(30, config.page_size)
408
+
409
+
410
+ class DownstreamConfig(AmazonAuthConfig):
411
+ @staticmethod
412
+ def default_data():
413
+ return {
414
+ **AmazonAuthConfig.default_data(),
415
+ "page_size": 20,
416
+ }
@@ -38,6 +38,122 @@ class TestSession(UnitTestCase):
38
38
  "some-password",
39
39
  config=self.test_config)
40
40
 
41
+ @responses.activate
42
+ def test_import_cookies_without_verification(self):
43
+ # GIVEN
44
+ self.amazon_session.session.cookies.set("old", "stale", domain=".amazon.com")
45
+ self.amazon_session.is_authenticated = True
46
+ self.amazon_session._sign_in_required = True
47
+ cookies = [{"name": "x-main", "value": "signed-in", "domain": ".amazon.com", "path": "/",
48
+ "secure": True, "expires": -1},
49
+ {"name": "session-id", "value": "session", "domain": "www.amazon.com", "path": "/orders",
50
+ "secure": True, "expires": 2000000000},
51
+ {"name": "foreign", "value": "ignored", "domain": ".amazon.de"},
52
+ {"name": "suffix", "value": "ignored", "domain": "notamazon.com"},
53
+ {"name": "prefix", "value": "ignored", "domain": "amazon.com.example.com"},
54
+ {"name": "hostless", "value": "ignored"}]
55
+
56
+ # WHEN
57
+ self.amazon_session.import_cookies(cookies, verify=False)
58
+
59
+ # THEN
60
+ self.assertEqual(0, len(responses.calls))
61
+ self.assertFalse(self.amazon_session.is_authenticated)
62
+ self.assertFalse(self.amazon_session._sign_in_required)
63
+ restored = AmazonSession(config=self.test_config)
64
+ self.assertEqual({"x-main": "signed-in", "session-id": "session"}, restored.session.cookies.get_dict())
65
+ attributes = {cookie.name: cookie for cookie in restored.session.cookies}
66
+ self.assertTrue(attributes["x-main"].secure)
67
+ self.assertIsNone(attributes["x-main"].expires)
68
+ self.assertEqual(".amazon.com", attributes["x-main"].domain)
69
+ self.assertEqual("/orders", attributes["session-id"].path)
70
+ self.assertEqual(2000000000, attributes["session-id"].expires)
71
+ if sys.platform != "win32":
72
+ self.assertEqual(0o600, os.stat(self.test_config.cookie_jar_path).st_mode & 0o777)
73
+
74
+ @responses.activate
75
+ def test_import_cookies_keeps_zero_expiry(self):
76
+ # WHEN
77
+ self.amazon_session.import_cookies(
78
+ [{"name": "expired", "value": "old", "domain": ".amazon.com", "expires": 0}], verify=False)
79
+
80
+ # THEN
81
+ restored = AmazonSession(config=self.test_config)
82
+ self.assertEqual(0, next(iter(restored.session.cookies)).expires)
83
+ request = restored.session.prepare_request(requests.Request("GET", self.test_config.constants.BASE_URL))
84
+ self.assertNotIn("expired=old", request.headers.get("Cookie", ""))
85
+ self.assertEqual(0, len(responses.calls))
86
+
87
+ @responses.activate
88
+ def test_import_cookies_verifies_by_default(self):
89
+ # GIVEN
90
+ check_response = self.given_session_check_page_exists()
91
+ self.amazon_session._sign_in_required = True
92
+
93
+ # WHEN
94
+ self.amazon_session.import_cookies([{"name": "x-main", "value": "signed-in", "domain": ".amazon.com"}])
95
+
96
+ # THEN
97
+ self.assertEqual(1, check_response.call_count)
98
+ self.assertTrue(self.amazon_session.is_authenticated)
99
+ self.assertFalse(self.amazon_session._sign_in_required)
100
+ self.assertEqual("signed-in", AmazonSession(config=self.test_config).session.cookies.get("x-main"))
101
+
102
+ @responses.activate
103
+ def test_import_cookies_rejects_missing_auth_cookies(self):
104
+ # GIVEN
105
+ self.amazon_session.is_authenticated = True
106
+
107
+ # WHEN
108
+ with self.assertRaises(AmazonAuthSignInError):
109
+ self.amazon_session.import_cookies([{"name": "x-main", "value": "foreign", "domain": ".amazon.de"}])
110
+
111
+ # THEN
112
+ self.assertFalse(self.amazon_session.is_authenticated)
113
+ self.assertEqual(0, len(responses.calls))
114
+
115
+ @responses.activate
116
+ def test_import_cookies_rejects_expired_session(self):
117
+ # GIVEN
118
+ self.given_authenticated_url_redirects_to_login()
119
+ self.given_login_responses_success()
120
+ self.amazon_session.is_authenticated = True
121
+
122
+ # WHEN
123
+ with self.assertRaises(AmazonAuthSignInError):
124
+ self.amazon_session.import_cookies([{"name": "x-main", "value": "expired", "domain": ".amazon.com"}])
125
+
126
+ # THEN
127
+ self.assertFalse(self.amazon_session.is_authenticated)
128
+ self.assertTrue(self.amazon_session._sign_in_required)
129
+
130
+ @responses.activate
131
+ def test_import_cookies_propagates_verification_error(self):
132
+ # GIVEN
133
+ self.given_session_check_page_exists(status=503)
134
+ self.amazon_session.is_authenticated = True
135
+
136
+ # WHEN
137
+ with self.assertRaises(AmazonAuthError):
138
+ self.amazon_session.import_cookies([{"name": "x-main", "value": "session", "domain": ".amazon.com"}])
139
+
140
+ # THEN
141
+ self.assertFalse(self.amazon_session.is_authenticated)
142
+
143
+ @responses.activate
144
+ def test_import_cookies_uses_configured_site(self):
145
+ # GIVEN
146
+ config = AmazonAuthConfig(data={"domain": "amazon.de"})
147
+ session = AmazonSession(config=config)
148
+
149
+ # WHEN
150
+ session.import_cookies([{"name": "x-main", "value": "de", "domain": ".amazon.de"},
151
+ {"name": "foreign", "value": "com", "domain": ".amazon.com"}], verify=False)
152
+
153
+ # THEN
154
+ self.assertEqual({"x-main": "de"}, AmazonSession(config=config).session.cookies.get_dict())
155
+ self.assertEqual(0, len(responses.calls))
156
+
41
157
  @responses.activate
42
158
  def test_login(self):
43
159
  # GIVEN
@@ -99,6 +99,16 @@ class TestUtil(UnitTestCase):
99
99
  # THEN
100
100
  self.assertIsNone(tag)
101
101
 
102
+ @patch("amazonauth.util.sys.platform", "linux")
103
+ def test_has_display_supplied_environment(self):
104
+ # GIVEN
105
+ with patch.dict(os.environ, {"DISPLAY": ":1"}):
106
+ # WHEN / THEN
107
+ self.assertFalse(has_display({}))
108
+ self.assertTrue(has_display({"DISPLAY": ":42"}))
109
+ self.assertTrue(has_display({"WAYLAND_DISPLAY": "wayland-2"}))
110
+ self.assertTrue(has_display())
111
+
102
112
  @patch.object(sys, "platform", "linux")
103
113
  def test_has_display_linux_without_display(self):
104
114
  # GIVEN
File without changes
File without changes
File without changes