swarmauri_auth_idp_facebook 0.2.0.dev5__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart @ Swarmauri]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_auth_idp_facebook
3
+ Version: 0.2.0.dev5
4
+ Summary: Facebook OAuth 2.0 / OAuth 2.1 / OIDC 1.0 login implementations for Swarmauri
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: swarmauri,sdk,standards,identity,oauth2,oauth21,oidc,facebook,meta
8
+ Author: Jacob Stewart
9
+ Author-email: jacob@swarmauri.com
10
+ Requires-Python: >=3.10,<3.13
11
+ Classifier: Development Status :: 1 - Planning
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Natural Language :: English
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Internet :: WWW/HTTP
22
+ Classifier: Topic :: Security :: Cryptography
23
+ Requires-Dist: httpx (>=0.27)
24
+ Requires-Dist: pyjwt[crypto] (>=2.8)
25
+ Requires-Dist: swarmauri_base
26
+ Requires-Dist: swarmauri_core
27
+ Description-Content-Type: text/markdown
28
+
29
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/master/assets/swarmauri.brand.theme.svg)
30
+
31
+ <p align="center">
32
+ <a href="https://pypi.org/project/swarmauri_auth_idp_facebook/">
33
+ <img src="https://img.shields.io/pypi/dm/swarmauri_auth_idp_facebook" alt="PyPI - Downloads"/></a>
34
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_auth_idp_facebook/">
35
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_auth_idp_facebook.svg"/></a>
36
+ <a href="https://pypi.org/project/swarmauri_auth_idp_facebook/">
37
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_auth_idp_facebook" alt="PyPI - Python Version"/></a>
38
+ <a href="https://pypi.org/project/swarmauri_auth_idp_facebook/">
39
+ <img src="https://img.shields.io/pypi/l/swarmauri_auth_idp_facebook" alt="PyPI - License"/></a>
40
+ <a href="https://pypi.org/project/swarmauri_auth_idp_facebook/">
41
+ <img src="https://img.shields.io/pypi/v/swarmauri_auth_idp_facebook?label=swarmauri_auth_idp_facebook&color=green" alt="PyPI - swarmauri_auth_idp_facebook"/></a>
42
+ </p>
43
+
44
+ ---
45
+
46
+ # Swarmauri Auth IDP Facebook
47
+
48
+ Facebook (Meta) OAuth 2.0, OAuth 2.1, and OIDC 1.0 login flows packaged for Swarmauri deployments.
49
+
50
+ ## Features
51
+
52
+ - PKCE-enabled authorization URL generation with signed state payloads.
53
+ - Token exchange helpers that normalize identity data via Graph `/me` or verified ID tokens.
54
+ - Built-in retrying HTTP client tuned for Facebook authorization and Graph endpoints.
55
+ - ComponentBase-compatible models registering under `swarmauri.auth_idp` entry points.
56
+ - Support for both user-facing browser flows and confidential client OIDC integrations.
57
+
58
+ ## Installation
59
+
60
+ ### pip
61
+
62
+ ```bash
63
+ pip install swarmauri_auth_idp_facebook
64
+ ```
65
+
66
+ ### uv (project)
67
+
68
+ ```bash
69
+ uv add swarmauri_auth_idp_facebook
70
+ ```
71
+
72
+ ### uv (environment)
73
+
74
+ ```bash
75
+ uv pip install swarmauri_auth_idp_facebook
76
+ ```
77
+
78
+ ## Usage
79
+
80
+ ```python
81
+ from pydantic import SecretStr
82
+ from swarmauri_auth_idp_facebook import FacebookOAuth21Login
83
+
84
+ login = FacebookOAuth21Login(
85
+ client_id="1234567890",
86
+ client_secret=SecretStr("app-secret"),
87
+ redirect_uri="https://app.example.com/auth/callback",
88
+ state_secret=b"facebook-state-key",
89
+ )
90
+
91
+ print(login.client_id)
92
+ ```
93
+
94
+ ### Workflow Summary
95
+
96
+ 1. Call `auth_url()` and redirect the browser to the returned Facebook login URL.
97
+ 2. Persist the `state` token and validate it when handling the callback.
98
+ 3. Exchange the authorization code via `exchange_and_identity()` to obtain tokens and profile data.
99
+ 4. Persist the returned identity details to drive session and authorization workflows.
100
+
101
+ ## Entry Points
102
+
103
+ - `swarmauri.auth_idp:FacebookOAuth20Login`
104
+ - `swarmauri.auth_idp:FacebookOAuth21Login`
105
+ - `swarmauri.auth_idp:FacebookOIDC10Login`
106
+
107
+ ## Contributing
108
+
109
+ To contribute to swarmauri-sdk, review the
110
+ [guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/CONTRIBUTING.md)
111
+ which cover development workflow, testing, and coding standards.
112
+
@@ -0,0 +1,83 @@
1
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/master/assets/swarmauri.brand.theme.svg)
2
+
3
+ <p align="center">
4
+ <a href="https://pypi.org/project/swarmauri_auth_idp_facebook/">
5
+ <img src="https://img.shields.io/pypi/dm/swarmauri_auth_idp_facebook" alt="PyPI - Downloads"/></a>
6
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_auth_idp_facebook/">
7
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_auth_idp_facebook.svg"/></a>
8
+ <a href="https://pypi.org/project/swarmauri_auth_idp_facebook/">
9
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_auth_idp_facebook" alt="PyPI - Python Version"/></a>
10
+ <a href="https://pypi.org/project/swarmauri_auth_idp_facebook/">
11
+ <img src="https://img.shields.io/pypi/l/swarmauri_auth_idp_facebook" alt="PyPI - License"/></a>
12
+ <a href="https://pypi.org/project/swarmauri_auth_idp_facebook/">
13
+ <img src="https://img.shields.io/pypi/v/swarmauri_auth_idp_facebook?label=swarmauri_auth_idp_facebook&color=green" alt="PyPI - swarmauri_auth_idp_facebook"/></a>
14
+ </p>
15
+
16
+ ---
17
+
18
+ # Swarmauri Auth IDP Facebook
19
+
20
+ Facebook (Meta) OAuth 2.0, OAuth 2.1, and OIDC 1.0 login flows packaged for Swarmauri deployments.
21
+
22
+ ## Features
23
+
24
+ - PKCE-enabled authorization URL generation with signed state payloads.
25
+ - Token exchange helpers that normalize identity data via Graph `/me` or verified ID tokens.
26
+ - Built-in retrying HTTP client tuned for Facebook authorization and Graph endpoints.
27
+ - ComponentBase-compatible models registering under `swarmauri.auth_idp` entry points.
28
+ - Support for both user-facing browser flows and confidential client OIDC integrations.
29
+
30
+ ## Installation
31
+
32
+ ### pip
33
+
34
+ ```bash
35
+ pip install swarmauri_auth_idp_facebook
36
+ ```
37
+
38
+ ### uv (project)
39
+
40
+ ```bash
41
+ uv add swarmauri_auth_idp_facebook
42
+ ```
43
+
44
+ ### uv (environment)
45
+
46
+ ```bash
47
+ uv pip install swarmauri_auth_idp_facebook
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ```python
53
+ from pydantic import SecretStr
54
+ from swarmauri_auth_idp_facebook import FacebookOAuth21Login
55
+
56
+ login = FacebookOAuth21Login(
57
+ client_id="1234567890",
58
+ client_secret=SecretStr("app-secret"),
59
+ redirect_uri="https://app.example.com/auth/callback",
60
+ state_secret=b"facebook-state-key",
61
+ )
62
+
63
+ print(login.client_id)
64
+ ```
65
+
66
+ ### Workflow Summary
67
+
68
+ 1. Call `auth_url()` and redirect the browser to the returned Facebook login URL.
69
+ 2. Persist the `state` token and validate it when handling the callback.
70
+ 3. Exchange the authorization code via `exchange_and_identity()` to obtain tokens and profile data.
71
+ 4. Persist the returned identity details to drive session and authorization workflows.
72
+
73
+ ## Entry Points
74
+
75
+ - `swarmauri.auth_idp:FacebookOAuth20Login`
76
+ - `swarmauri.auth_idp:FacebookOAuth21Login`
77
+ - `swarmauri.auth_idp:FacebookOIDC10Login`
78
+
79
+ ## Contributing
80
+
81
+ To contribute to swarmauri-sdk, review the
82
+ [guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/CONTRIBUTING.md)
83
+ which cover development workflow, testing, and coding standards.
@@ -0,0 +1,87 @@
1
+ [project]
2
+ name = "swarmauri_auth_idp_facebook"
3
+ version = "0.2.0.dev5"
4
+ description = "Facebook OAuth 2.0 / OAuth 2.1 / OIDC 1.0 login implementations for Swarmauri"
5
+ license = "Apache-2.0"
6
+ readme = "README.md"
7
+ requires-python = ">=3.10,<3.13"
8
+ repository = "https://github.com/swarmauri/swarmauri-sdk"
9
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
10
+ classifiers = [
11
+ "Development Status :: 1 - Planning",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: Apache Software License",
14
+ "Natural Language :: English",
15
+ "Programming Language :: Python",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Topic :: Internet :: WWW/HTTP",
22
+ "Topic :: Security :: Cryptography",
23
+ ]
24
+ keywords = [
25
+ "swarmauri",
26
+ "sdk",
27
+ "standards",
28
+ "identity",
29
+ "oauth2",
30
+ "oauth21",
31
+ "oidc",
32
+ "facebook",
33
+ "meta",
34
+ ]
35
+ dependencies = [
36
+ "swarmauri_core",
37
+ "swarmauri_base",
38
+ "httpx>=0.27",
39
+ "pyjwt[crypto]>=2.8",
40
+ ]
41
+
42
+ [project.entry-points.'swarmauri.auth_idp']
43
+ FacebookOAuth20AppClient = "swarmauri_auth_idp_facebook:FacebookOAuth20AppClient"
44
+ FacebookOAuth20Login = "swarmauri_auth_idp_facebook:FacebookOAuth20Login"
45
+ FacebookOAuth21AppClient = "swarmauri_auth_idp_facebook:FacebookOAuth21AppClient"
46
+ FacebookOAuth21Login = "swarmauri_auth_idp_facebook:FacebookOAuth21Login"
47
+ FacebookOIDC10AppClient = "swarmauri_auth_idp_facebook:FacebookOIDC10AppClient"
48
+ FacebookOIDC10Login = "swarmauri_auth_idp_facebook:FacebookOIDC10Login"
49
+
50
+ [tool.uv.sources]
51
+ swarmauri_tests_pylicense = { workspace = true }
52
+ swarmauri_core = { workspace = true }
53
+ swarmauri_base = { workspace = true }
54
+
55
+ [tool.pytest.ini_options]
56
+ markers = [
57
+ "test: standard test",
58
+ "unit: Unit tests",
59
+ "i9n: Integration tests",
60
+ "r8n: Regression tests",
61
+ "acceptance: Acceptance tests",
62
+ "perf: Performance tests",
63
+ "example: Documentation examples",
64
+ ]
65
+ timeout = 300
66
+ log_cli = true
67
+ log_cli_level = "INFO"
68
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
69
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
70
+ asyncio_default_fixture_loop_scope = "function"
71
+ addopts = "--pylicense-accept-deps=sniffio"
72
+
73
+ [dependency-groups]
74
+ dev = [
75
+ "pytest>=8.0",
76
+ "pytest-asyncio>=0.24.0",
77
+ "pytest-xdist>=3.6.1",
78
+ "pytest-json-report>=1.5.0",
79
+ "pytest-timeout>=2.3.1",
80
+ "pytest-benchmark>=4.0.0",
81
+ "ruff>=0.9.9",
82
+ "swarmauri_tests_pylicense",
83
+ ]
84
+
85
+ [build-system]
86
+ requires = ["poetry-core>=1.0.0"]
87
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,143 @@
1
+ """Shared helpers for Facebook login implementations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Callable, Dict, Mapping
7
+
8
+ import jwt
9
+ from pydantic import ConfigDict, Field, PrivateAttr, SecretStr
10
+
11
+ from swarmauri_base.auth_idp import (
12
+ RetryingAsyncClient,
13
+ make_pkce_pair,
14
+ sign_state,
15
+ verify_state,
16
+ )
17
+
18
+ _DEFAULT_AUTH_BASE = "https://www.facebook.com/v19.0"
19
+ _DEFAULT_GRAPH_BASE = "https://graph.facebook.com/v19.0"
20
+ _GRAPH_FIELDS = "id,name,email"
21
+ _JWKS_URI = "https://www.facebook.com/.well-known/oauth/openid/jwks/"
22
+
23
+
24
+ def _load_signing_key(jwks: Mapping[str, Any], kid: str) -> Any:
25
+ """Select the signing key referenced by *kid*."""
26
+
27
+ for entry in jwks.get("keys", []):
28
+ if entry.get("kid") == kid:
29
+ serialized = json.dumps(entry)
30
+ kty = entry.get("kty", "RSA").upper()
31
+ if kty == "EC":
32
+ return jwt.algorithms.ECAlgorithm.from_jwk(serialized)
33
+ return jwt.algorithms.RSAAlgorithm.from_jwk(serialized)
34
+ raise ValueError("signing key not found")
35
+
36
+
37
+ class FacebookLoginMixin:
38
+ """Common helpers shared across Facebook OAuth/OIDC login flows."""
39
+
40
+ model_config = ConfigDict(extra="forbid")
41
+
42
+ auth_base: str = Field(default=_DEFAULT_AUTH_BASE)
43
+ graph_base: str = Field(default=_DEFAULT_GRAPH_BASE)
44
+ client_id: str
45
+ client_secret: SecretStr
46
+ redirect_uri: str
47
+ state_secret: bytes
48
+ scope: str = Field(default="email public_profile")
49
+
50
+ _http_client_factory: Callable[[], RetryingAsyncClient] = PrivateAttr(
51
+ default=RetryingAsyncClient
52
+ )
53
+
54
+ def _authorization_endpoint(self) -> str:
55
+ return f"{self.auth_base.rstrip('/')}/dialog/oauth"
56
+
57
+ def _token_endpoint(self) -> str:
58
+ return f"{self.graph_base.rstrip('/')}/oauth/access_token"
59
+
60
+ def _graph_me_endpoint(self) -> str:
61
+ return f"{self.graph_base.rstrip('/')}/me?fields={_GRAPH_FIELDS}"
62
+
63
+ def _jwks_uri(self) -> str:
64
+ return _JWKS_URI
65
+
66
+ def _client_secret_value(self) -> str:
67
+ return self.client_secret.get_secret_value()
68
+
69
+ def _state_secret(self) -> bytes:
70
+ return self.state_secret
71
+
72
+ async def _auth_payload(self) -> Dict[str, str]:
73
+ verifier, challenge = make_pkce_pair()
74
+ state = sign_state(self._state_secret(), {"verifier": verifier})
75
+ url = (
76
+ f"{self._authorization_endpoint()}?response_type=code"
77
+ f"&client_id={self.client_id}&redirect_uri={self.redirect_uri}"
78
+ f"&scope={self.scope}&state={state}"
79
+ f"&code_challenge={challenge}&code_challenge_method=S256"
80
+ )
81
+ return {"url": url, "state": state, "verifier": verifier}
82
+
83
+ async def _post_token(self, form: Mapping[str, Any]) -> Mapping[str, Any]:
84
+ async with self._http_client_factory() as client:
85
+ response = await client.post_retry(
86
+ self._token_endpoint(),
87
+ data=form,
88
+ headers={"Accept": "application/json"},
89
+ )
90
+ response.raise_for_status()
91
+ return response.json()
92
+
93
+ async def _exchange_tokens(self, code: str, state: str) -> Mapping[str, Any]:
94
+ payload = verify_state(self._state_secret(), state)
95
+ form = {
96
+ "grant_type": "authorization_code",
97
+ "code": code,
98
+ "redirect_uri": self.redirect_uri,
99
+ "client_id": self.client_id,
100
+ "client_secret": self._client_secret_value(),
101
+ "code_verifier": payload["verifier"],
102
+ }
103
+ return await self._post_token(form)
104
+
105
+ async def _fetch_profile(self, access_token: str) -> Mapping[str, Any]:
106
+ async with self._http_client_factory() as client:
107
+ response = await client.get_retry(
108
+ self._graph_me_endpoint(),
109
+ headers={
110
+ "Authorization": f"Bearer {access_token}",
111
+ "Accept": "application/json",
112
+ },
113
+ )
114
+ response.raise_for_status()
115
+ return response.json()
116
+
117
+ async def _jwks(self) -> Mapping[str, Any]:
118
+ async with self._http_client_factory() as client:
119
+ response = await client.get_retry(
120
+ self._jwks_uri(),
121
+ headers={"Accept": "application/json"},
122
+ )
123
+ response.raise_for_status()
124
+ return response.json()
125
+
126
+ async def _decode_id_token(self, id_token: str) -> Mapping[str, Any]:
127
+ jwks = await self._jwks()
128
+ header = jwt.get_unverified_header(id_token)
129
+ kid = header.get("kid")
130
+ if not kid:
131
+ raise ValueError("missing kid in id_token header")
132
+ signer = _load_signing_key(jwks, kid)
133
+ algorithm = header.get("alg", "RS256")
134
+ return jwt.decode(
135
+ id_token,
136
+ signer,
137
+ algorithms=[algorithm],
138
+ audience=self.client_id,
139
+ issuer="https://www.facebook.com",
140
+ )
141
+
142
+
143
+ __all__ = ["FacebookLoginMixin"]
@@ -0,0 +1,70 @@
1
+ """Facebook OAuth 2.0 client-credentials token helper."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Callable, Literal, Mapping, Optional, Tuple
7
+
8
+ from pydantic import ConfigDict, Field, PrivateAttr, SecretStr
9
+
10
+ from swarmauri_base.ComponentBase import ComponentBase
11
+ from swarmauri_base.auth_idp import OAuth20AppClientBase, RetryingAsyncClient
12
+
13
+
14
+ @ComponentBase.register_type(OAuth20AppClientBase, "FacebookOAuth20AppClient")
15
+ class FacebookOAuth20AppClient(OAuth20AppClientBase):
16
+ """Obtain Facebook app access tokens using the client credentials grant."""
17
+
18
+ model_config = ConfigDict(extra="forbid")
19
+
20
+ graph_base: str = Field(default="https://graph.facebook.com")
21
+ version: str = Field(default="v19.0")
22
+ client_id: str
23
+ client_secret: SecretStr
24
+ cache_skew_sec: int = Field(default=30)
25
+
26
+ type: Literal["FacebookOAuth20AppClient"] = "FacebookOAuth20AppClient"
27
+
28
+ _http_client_factory: Callable[[], RetryingAsyncClient] = PrivateAttr(
29
+ default=RetryingAsyncClient
30
+ )
31
+ _token_cache: Optional[Tuple[str, float]] = PrivateAttr(default=None)
32
+
33
+ def _client_secret_value(self) -> str:
34
+ return self.client_secret.get_secret_value()
35
+
36
+ def _token_endpoint(self) -> str:
37
+ return f"{self.graph_base.rstrip('/')}/{self.version}/oauth/access_token"
38
+
39
+ async def _request_token(self, form: Mapping[str, str]) -> Mapping[str, str]:
40
+ async with self._http_client_factory() as client:
41
+ response = await client.post_retry(
42
+ self._token_endpoint(),
43
+ data=form,
44
+ headers={"Accept": "application/json"},
45
+ )
46
+ response.raise_for_status()
47
+ return response.json()
48
+
49
+ async def access_token(self, scope: Optional[str] = None) -> str:
50
+ del scope # Facebook app tokens do not support dynamic scopes.
51
+ cached = self._token_cache
52
+ now = time.time()
53
+ if cached and now < cached[1] - self.cache_skew_sec:
54
+ return cached[0]
55
+ form = {
56
+ "grant_type": "client_credentials",
57
+ "client_id": self.client_id,
58
+ "client_secret": self._client_secret_value(),
59
+ }
60
+ token_response = await self._request_token(form)
61
+ token = token_response.get("access_token")
62
+ if not token:
63
+ raise ValueError("access_token missing from Facebook response")
64
+ expires_in = int(token_response.get("expires_in", 3600))
65
+ expiry = now + max(1, expires_in)
66
+ self._token_cache = (token, expiry)
67
+ return token
68
+
69
+
70
+ __all__ = ["FacebookOAuth20AppClient"]
@@ -0,0 +1,40 @@
1
+ """Facebook OAuth 2.0 Authorization Code login."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal, Mapping
6
+
7
+ from swarmauri_base.ComponentBase import ComponentBase
8
+ from swarmauri_base.auth_idp import OAuth20LoginBase
9
+
10
+ from .FacebookLoginMixin import FacebookLoginMixin
11
+
12
+
13
+ @ComponentBase.register_type(OAuth20LoginBase, "FacebookOAuth20Login")
14
+ class FacebookOAuth20Login(FacebookLoginMixin, OAuth20LoginBase):
15
+ """Implement the Facebook OAuth 2.0 authorization code flow."""
16
+
17
+ type: Literal["FacebookOAuth20Login"] = "FacebookOAuth20Login"
18
+
19
+ async def auth_url(self) -> Mapping[str, str]:
20
+ payload = await self._auth_payload()
21
+ return {"url": payload["url"], "state": payload["state"]}
22
+
23
+ async def exchange_and_identity(self, code: str, state: str) -> Mapping[str, Any]:
24
+ tokens = await self._exchange_tokens(code, state)
25
+ access_token = tokens.get("access_token")
26
+ profile: Mapping[str, Any] = {}
27
+ if access_token:
28
+ profile = await self._fetch_profile(access_token)
29
+ sub = str(profile.get("id")) if profile.get("id") is not None else None
30
+ return {
31
+ "issuer": "facebook-oauth20",
32
+ "tokens": tokens,
33
+ "profile": profile,
34
+ "sub": sub,
35
+ "email": profile.get("email") if profile else None,
36
+ "name": profile.get("name") if profile else None,
37
+ }
38
+
39
+
40
+ __all__ = ["FacebookOAuth20Login"]
@@ -0,0 +1,38 @@
1
+ """Facebook OAuth 2.1 client-credentials helper."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, Optional
6
+
7
+ from pydantic import ConfigDict, Field, SecretStr
8
+
9
+ from swarmauri_base.ComponentBase import ComponentBase
10
+ from swarmauri_base.auth_idp import OAuth21AppClientBase
11
+
12
+ from .FacebookOAuth20AppClient import FacebookOAuth20AppClient
13
+
14
+
15
+ @ComponentBase.register_type(OAuth21AppClientBase, "FacebookOAuth21AppClient")
16
+ class FacebookOAuth21AppClient(OAuth21AppClientBase):
17
+ """Reuse the OAuth 2.0 client credentials flow for OAuth 2.1 semantics."""
18
+
19
+ model_config = ConfigDict(extra="forbid")
20
+
21
+ graph_base: str = Field(default="https://graph.facebook.com")
22
+ version: str = Field(default="v19.0")
23
+ client_id: str
24
+ client_secret: SecretStr
25
+
26
+ type: Literal["FacebookOAuth21AppClient"] = "FacebookOAuth21AppClient"
27
+
28
+ async def access_token(self, scope: Optional[str] = None) -> str:
29
+ client = FacebookOAuth20AppClient(
30
+ graph_base=self.graph_base,
31
+ version=self.version,
32
+ client_id=self.client_id,
33
+ client_secret=self.client_secret,
34
+ )
35
+ return await client.access_token(scope=scope)
36
+
37
+
38
+ __all__ = ["FacebookOAuth21AppClient"]
@@ -0,0 +1,61 @@
1
+ """Facebook OAuth 2.1 Authorization Code login."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal, Mapping, Optional
6
+
7
+ from swarmauri_base.ComponentBase import ComponentBase
8
+ from swarmauri_base.auth_idp import OAuth21LoginBase
9
+
10
+ from .FacebookLoginMixin import FacebookLoginMixin
11
+
12
+
13
+ @ComponentBase.register_type(OAuth21LoginBase, "FacebookOAuth21Login")
14
+ class FacebookOAuth21Login(FacebookLoginMixin, OAuth21LoginBase):
15
+ """Implement the Facebook OAuth 2.1 authorization code flow."""
16
+
17
+ type: Literal["FacebookOAuth21Login"] = "FacebookOAuth21Login"
18
+
19
+ async def auth_url(self) -> Mapping[str, str]:
20
+ payload = await self._auth_payload()
21
+ return {"url": payload["url"], "state": payload["state"]}
22
+
23
+ async def _claims_from_id_token(
24
+ self, id_token: Optional[str]
25
+ ) -> Optional[Mapping[str, Any]]:
26
+ if not id_token:
27
+ return None
28
+ try:
29
+ claims = await self._decode_id_token(id_token)
30
+ except ValueError:
31
+ return None
32
+ return claims
33
+
34
+ async def exchange_and_identity(self, code: str, state: str) -> Mapping[str, Any]:
35
+ tokens = await self._exchange_tokens(code, state)
36
+ claims = await self._claims_from_id_token(tokens.get("id_token"))
37
+ if claims:
38
+ return {
39
+ "issuer": "facebook-oauth21",
40
+ "tokens": tokens,
41
+ "claims": claims,
42
+ "sub": claims.get("sub"),
43
+ "email": claims.get("email"),
44
+ "name": claims.get("name") or claims.get("given_name"),
45
+ }
46
+ access_token = tokens.get("access_token")
47
+ profile: Mapping[str, Any] = {}
48
+ if access_token:
49
+ profile = await self._fetch_profile(access_token)
50
+ sub = str(profile.get("id")) if profile.get("id") is not None else None
51
+ return {
52
+ "issuer": "facebook-oauth21",
53
+ "tokens": tokens,
54
+ "profile": profile,
55
+ "sub": sub,
56
+ "email": profile.get("email") if profile else None,
57
+ "name": profile.get("name") if profile else None,
58
+ }
59
+
60
+
61
+ __all__ = ["FacebookOAuth21Login"]
@@ -0,0 +1,26 @@
1
+ """Facebook OIDC app client placeholder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, Optional
6
+
7
+ from pydantic import ConfigDict
8
+ from swarmauri_base.auth_idp import OIDC10AppClientBase
9
+ from swarmauri_base.ComponentBase import ComponentBase
10
+
11
+
12
+ @ComponentBase.register_type(OIDC10AppClientBase, "FacebookOIDC10AppClient")
13
+ class FacebookOIDC10AppClient(OIDC10AppClientBase):
14
+ """Facebook does not support generic OIDC client credential grants."""
15
+
16
+ model_config = ConfigDict(extra="forbid")
17
+
18
+ type: Literal["FacebookOIDC10AppClient"] = "FacebookOIDC10AppClient"
19
+
20
+ async def access_token(self, scope: Optional[str] = None) -> str:
21
+ raise NotImplementedError(
22
+ "Facebook does not provide a client_credentials OIDC token flow"
23
+ )
24
+
25
+
26
+ __all__ = ["FacebookOIDC10AppClient"]
@@ -0,0 +1,173 @@
1
+ """Facebook OpenID Connect 1.0 login implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Callable, Literal, Mapping, Optional
7
+
8
+ import jwt
9
+ from pydantic import ConfigDict, Field, PrivateAttr, SecretStr
10
+
11
+ from swarmauri_base.ComponentBase import ComponentBase
12
+ from swarmauri_base.auth_idp import (
13
+ OIDC10LoginBase,
14
+ RetryingAsyncClient,
15
+ make_pkce_pair,
16
+ sign_state,
17
+ verify_state,
18
+ )
19
+
20
+
21
+ def _select_signing_key(jwks: Mapping[str, Any], kid: str) -> Any:
22
+ for entry in jwks.get("keys", []):
23
+ if entry.get("kid") == kid:
24
+ serialized = json.dumps(entry)
25
+ kty = entry.get("kty", "RSA").upper()
26
+ if kty == "EC":
27
+ return jwt.algorithms.ECAlgorithm.from_jwk(serialized)
28
+ return jwt.algorithms.RSAAlgorithm.from_jwk(serialized)
29
+ raise ValueError("signing key not found")
30
+
31
+
32
+ @ComponentBase.register_type(OIDC10LoginBase, "FacebookOIDC10Login")
33
+ class FacebookOIDC10Login(OIDC10LoginBase):
34
+ """Facebook confidential client OpenID Connect 1.0 login."""
35
+
36
+ model_config = ConfigDict(extra="forbid")
37
+
38
+ issuer: str = Field(default="https://www.facebook.com")
39
+ client_id: str
40
+ client_secret: SecretStr
41
+ redirect_uri: str
42
+ state_secret: bytes
43
+ scope: str = Field(default="openid email public_profile")
44
+
45
+ type: Literal["FacebookOIDC10Login"] = "FacebookOIDC10Login"
46
+
47
+ _discovery: Optional[Mapping[str, Any]] = PrivateAttr(default=None)
48
+ _http_client_factory: Callable[[], RetryingAsyncClient] = PrivateAttr(
49
+ default=RetryingAsyncClient
50
+ )
51
+
52
+ def _state_secret(self) -> bytes:
53
+ return self.state_secret
54
+
55
+ def _client_secret_value(self) -> str:
56
+ return self.client_secret.get_secret_value()
57
+
58
+ def _discovery_url(self) -> str:
59
+ return f"{self.issuer.rstrip('/')}/.well-known/openid-configuration"
60
+
61
+ async def _metadata(self) -> Mapping[str, Any]:
62
+ if self._discovery is None:
63
+ async with self._http_client_factory() as client:
64
+ response = await client.get_retry(
65
+ self._discovery_url(),
66
+ headers={"Accept": "application/json"},
67
+ )
68
+ response.raise_for_status()
69
+ self._discovery = response.json()
70
+ return self._discovery
71
+
72
+ async def auth_url(self) -> Mapping[str, str]:
73
+ metadata = await self._metadata()
74
+ verifier, challenge = make_pkce_pair()
75
+ state = sign_state(self._state_secret(), {"verifier": verifier})
76
+ endpoint = metadata["authorization_endpoint"]
77
+ url = (
78
+ f"{endpoint}?response_type=code"
79
+ f"&client_id={self.client_id}&redirect_uri={self.redirect_uri}"
80
+ f"&scope={self.scope}&state={state}"
81
+ f"&code_challenge={challenge}&code_challenge_method=S256"
82
+ )
83
+ return {"url": url, "state": state}
84
+
85
+ async def _token_request(
86
+ self, endpoint: str, form: Mapping[str, Any]
87
+ ) -> Mapping[str, Any]:
88
+ async with self._http_client_factory() as client:
89
+ response = await client.post_retry(
90
+ endpoint,
91
+ data=form,
92
+ headers={"Accept": "application/json"},
93
+ )
94
+ response.raise_for_status()
95
+ return response.json()
96
+
97
+ async def _jwks(self, url: str) -> Mapping[str, Any]:
98
+ async with self._http_client_factory() as client:
99
+ response = await client.get_retry(
100
+ url,
101
+ headers={"Accept": "application/json"},
102
+ )
103
+ response.raise_for_status()
104
+ return response.json()
105
+
106
+ def _decode_id_token(
107
+ self,
108
+ id_token: str,
109
+ *,
110
+ jwks: Mapping[str, Any],
111
+ issuer: str,
112
+ ) -> Mapping[str, Any]:
113
+ header = jwt.get_unverified_header(id_token)
114
+ kid = header.get("kid")
115
+ if not kid:
116
+ raise ValueError("kid missing from id_token header")
117
+ signer = _select_signing_key(jwks, kid)
118
+ alg = header.get("alg", "RS256")
119
+ return jwt.decode(
120
+ id_token,
121
+ signer,
122
+ algorithms=[alg],
123
+ audience=self.client_id,
124
+ issuer=issuer,
125
+ )
126
+
127
+ async def exchange(self, code: str, state: str) -> Mapping[str, Any]:
128
+ metadata = await self._metadata()
129
+ payload = verify_state(self._state_secret(), state)
130
+ form = {
131
+ "grant_type": "authorization_code",
132
+ "code": code,
133
+ "redirect_uri": self.redirect_uri,
134
+ "client_id": self.client_id,
135
+ "client_secret": self._client_secret_value(),
136
+ "code_verifier": payload["verifier"],
137
+ }
138
+ tokens = await self._token_request(metadata["token_endpoint"], form)
139
+ id_token = tokens.get("id_token")
140
+ if not id_token:
141
+ raise ValueError("no id_token in response")
142
+ jwks = await self._jwks(metadata["jwks_uri"])
143
+ claims = self._decode_id_token(
144
+ id_token,
145
+ jwks=jwks,
146
+ issuer=metadata.get("issuer", self.issuer),
147
+ )
148
+ email = claims.get("email")
149
+ name = claims.get("name") or claims.get("given_name")
150
+ if (not email or not name) and metadata.get("userinfo_endpoint"):
151
+ async with self._http_client_factory() as client:
152
+ response = await client.get_retry(
153
+ metadata["userinfo_endpoint"],
154
+ headers={
155
+ "Authorization": f"Bearer {tokens.get('access_token', '')}",
156
+ "Accept": "application/json",
157
+ },
158
+ )
159
+ response.raise_for_status()
160
+ userinfo = response.json()
161
+ email = email or userinfo.get("email")
162
+ name = name or userinfo.get("name")
163
+ return {
164
+ "issuer": "facebook-oidc10",
165
+ "tokens": tokens,
166
+ "claims": claims,
167
+ "sub": claims.get("sub"),
168
+ "email": email,
169
+ "name": name,
170
+ }
171
+
172
+
173
+ __all__ = ["FacebookOIDC10Login"]
@@ -0,0 +1,17 @@
1
+ """Facebook identity provider implementations."""
2
+
3
+ from .FacebookOAuth20Login import FacebookOAuth20Login
4
+ from .FacebookOAuth21Login import FacebookOAuth21Login
5
+ from .FacebookOIDC10Login import FacebookOIDC10Login
6
+ from .FacebookOAuth20AppClient import FacebookOAuth20AppClient
7
+ from .FacebookOAuth21AppClient import FacebookOAuth21AppClient
8
+ from .FacebookOIDC10AppClient import FacebookOIDC10AppClient
9
+
10
+ __all__ = [
11
+ "FacebookOAuth20AppClient",
12
+ "FacebookOAuth21AppClient",
13
+ "FacebookOIDC10AppClient",
14
+ "FacebookOAuth20Login",
15
+ "FacebookOAuth21Login",
16
+ "FacebookOIDC10Login",
17
+ ]