ghost-citadel-sdk 0.1.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.
@@ -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 tracking or otherwise improving the Work,
59
+ but excludes 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 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 describing the origin of the Work and
141
+ 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 Support. While redistributing the Work or
166
+ Derivative Works thereof, You may accept and charge a fee for,
167
+ acceptance of support, warranty, indemnity, or other liability
168
+ obligations and/or rights consistent with this License. However,
169
+ in accepting such obligations, You may act only on Your own
170
+ behalf and on Your sole responsibility, not on behalf of any other
171
+ Contributor, and only if You agree to indemnify, defend, and hold
172
+ each Contributor harmless for any liability incurred by, or claims
173
+ asserted against, such Contributor by reason of your accepting any
174
+ such warranty or support.
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 name and extension be included on the same line as the
186
+ copyright notice for ease of identification within third-party
187
+ archives.
188
+
189
+ Copyright 2026 Ghost Citadel Engineering
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
200
+ implied. See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: ghost-citadel-sdk
3
+ Version: 0.1.0
4
+ Summary: The official Python SDK for Ghost Citadel — Stripe webhook automation, license verification & SaaS monetization primitives.
5
+ Author-email: Ghost Citadel Engineering <dev@api.citadel-serve.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://api.citadel-serve.com
8
+ Project-URL: Documentation, https://docs.citadel-serve.com
9
+ Project-URL: Repository, https://github.com/tgg49099-dotcom/ghostcitadelle
10
+ Project-URL: Issues, https://github.com/tgg49099-dotcom/ghostcitadelle/issues
11
+ Project-URL: Get API Key, https://api.citadel-serve.com/dashboard/signup
12
+ Keywords: stripe,webhook,billing,saas,api-key,monetization,fastapi,license,rate-limiting,self-hosted
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: requests>=2.28.0
28
+ Provides-Extra: fastapi
29
+ Requires-Dist: fastapi>=0.95.0; extra == "fastapi"
30
+ Requires-Dist: uvicorn>=0.20.0; extra == "fastapi"
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=7.0; extra == "dev"
33
+ Requires-Dist: pytest-mock>=3.10; extra == "dev"
34
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
35
+ Requires-Dist: black>=23.0; extra == "dev"
36
+ Requires-Dist: ruff>=0.0.270; extra == "dev"
37
+ Requires-Dist: mypy>=1.0; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # Ghost Citadel — Python SDK
41
+
42
+ > **The Stripe webhook manager + API key billing boilerplate for SaaS founders.**
43
+
44
+ [![Get API Key](https://img.shields.io/badge/Get%20API%20Key-https%3A%2F%2Fapi.citadel--serve.com-7c3aed?style=for-the-badge)](https://api.citadel-serve.com)
45
+ [![CI](https://github.com/tgg49099-dotcom/ghostcitadelle/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tgg49099-dotcom/ghostcitadelle/actions/workflows/ci.yml)
46
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
47
+ [![Python](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://www.python.org)
48
+ [![pip](https://img.shields.io/badge/pip-ghost--citadel--sdk-3776AB.svg)](https://pypi.org/project/ghost-citadel-sdk/)
49
+
50
+ ---
51
+
52
+ ## Why Citadel?
53
+
54
+ You're a one-person SaaS team shipping at night. Stripe webhooks eat your
55
+ weekend. License keys are issued in Notion. Rate limiting is a sticky note.
56
+ You've duct-taped your **API key billing boilerplate** together three times
57
+ already.
58
+
59
+ **Citadel** is the boring infra that lets you stop duct-taping.
60
+
61
+ - 🔁 **Stripe webhook manager** — idempotent, retried, fan-out done.
62
+ - 🔐 **License verification** — issue, verify, revoke from one endpoint.
63
+ - ⚡ **FastAPI rate limiting** — primitives wired straight into the SDK.
64
+ - 💸 **SaaS monetization** — usage-based billing, dunning, and seat
65
+ management without a sales call.
66
+ - 🏗️ **Self-serve infrastructure** — sign up, get an API key, ship.
67
+
68
+ > ⚠️ The package is open source. **Production usage requires an active
69
+ > Citadel subscription.** Get your API key instantly at
70
+ > **[https://api.citadel-serve.com](https://api.citadel-serve.com)**.
71
+ >
72
+ > Without a key, the SDK raises a styled `CitadelAuthError` pointing
73
+ > straight at the activation URL — by design.
74
+
75
+ ---
76
+
77
+ ## Quickstart
78
+
79
+ ```bash
80
+ pip install ghost-citadel-sdk
81
+ ```
82
+
83
+ ```python
84
+ from citadel import CitadelClient
85
+
86
+ client = CitadelClient(api_key="ck_live_...") # or set CITADEL_API_KEY
87
+
88
+ client.register_webhook(
89
+ url="https://your-app.com/stripe/webhook",
90
+ events=["checkout.session.completed", "invoice.paid"],
91
+ )
92
+
93
+ result = client.verify_license(
94
+ license_key="LIC-1234-ABCD",
95
+ product_id="prod_citadel",
96
+ )
97
+ print(result)
98
+ ```
99
+
100
+ ### Trying it without a key? You'll see this:
101
+
102
+ ```
103
+ ┌──────────────────────────────────────────────────────────────────────┐
104
+ │ CitadelAuthError: API Key missing or invalid. │
105
+ │ │
106
+ │ To use this SDK in production and automate your Stripe │
107
+ │ webhooks/licensing, get your API key instantly at │
108
+ │ │
109
+ │ https://api.citadel-serve.com │
110
+ │ │
111
+ │ Citadel — Stripe webhook manager · SaaS monetization │
112
+ │ primitives · Self-serve infrastructure for founders. │
113
+ └──────────────────────────────────────────────────────────────────────┘
114
+ ```
115
+
116
+ ---
117
+
118
+ ## Ready-to-use Examples
119
+
120
+ The `examples/` folder contains copy-paste-ready boilerplates tuned for the
121
+ exact stacks developers search for on GitHub:
122
+
123
+ | Folder | Stack | Keywords captured |
124
+ | ------ | ----- | ----------------- |
125
+ | [`examples/fastapi-stripe-billing/`](examples/fastapi-stripe-billing/) | FastAPI + Stripe + Citadel | FastAPI Stripe billing integration, FastAPI rate limiting |
126
+ | [`examples/nextjs-webhook-handler/`](examples/nextjs-webhook-handler/) | Next.js App Router + Stripe | Next.js Stripe webhook boilerplate |
127
+
128
+ Each example ships with a README that doubles as a landing page for search
129
+ engines — drop them in your repo, get traffic, convert on the activation CTA.
130
+
131
+ ---
132
+
133
+ ## API surface
134
+
135
+ | Method | Endpoint | Purpose |
136
+ | ------ | -------- | ------- |
137
+ | `client.verify_license(license_key, product_id)` | `POST /v1/verify-license` | Validate a license key |
138
+ | `client.register_webhook(url, events)` | `POST /v1/webhooks` | Register a Stripe webhook |
139
+ | `client.list_webhooks()` | `GET /v1/webhooks` | List webhooks for this account |
140
+ | `client.ping()` | `GET /v1/ping` | Health check + auth probe |
141
+
142
+ Full schema: [`citadel-openapi.yaml`](./citadel-openapi.yaml).
143
+
144
+ ---
145
+
146
+ ## Subscription requirement
147
+
148
+ This is open source. Running it in production — i.e. serving real Stripe
149
+ events, verifying real licenses, consuming rate-limit budget — requires an
150
+ **active Citadel API key** linked to a paying Citadel account.
151
+
152
+ - Free tier: 1,000 events / month, perfect for side projects.
153
+ - Pro tier: unlimited webhooks, seat-based pricing, priority support.
154
+ - Scale tier: dedicated infrastructure, custom SLAs.
155
+
156
+ **Activate your account → [https://api.citadel-serve.com](https://api.citadel-serve.com)**
157
+
158
+ ---
159
+
160
+ ## License
161
+
162
+ Apache-2.0. The code is yours. The production runtime is ours.
163
+
164
+ — *Ghost Citadel Engineering*
@@ -0,0 +1,125 @@
1
+ # Ghost Citadel — Python SDK
2
+
3
+ > **The Stripe webhook manager + API key billing boilerplate for SaaS founders.**
4
+
5
+ [![Get API Key](https://img.shields.io/badge/Get%20API%20Key-https%3A%2F%2Fapi.citadel--serve.com-7c3aed?style=for-the-badge)](https://api.citadel-serve.com)
6
+ [![CI](https://github.com/tgg49099-dotcom/ghostcitadelle/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tgg49099-dotcom/ghostcitadelle/actions/workflows/ci.yml)
7
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
8
+ [![Python](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://www.python.org)
9
+ [![pip](https://img.shields.io/badge/pip-ghost--citadel--sdk-3776AB.svg)](https://pypi.org/project/ghost-citadel-sdk/)
10
+
11
+ ---
12
+
13
+ ## Why Citadel?
14
+
15
+ You're a one-person SaaS team shipping at night. Stripe webhooks eat your
16
+ weekend. License keys are issued in Notion. Rate limiting is a sticky note.
17
+ You've duct-taped your **API key billing boilerplate** together three times
18
+ already.
19
+
20
+ **Citadel** is the boring infra that lets you stop duct-taping.
21
+
22
+ - 🔁 **Stripe webhook manager** — idempotent, retried, fan-out done.
23
+ - 🔐 **License verification** — issue, verify, revoke from one endpoint.
24
+ - ⚡ **FastAPI rate limiting** — primitives wired straight into the SDK.
25
+ - 💸 **SaaS monetization** — usage-based billing, dunning, and seat
26
+ management without a sales call.
27
+ - 🏗️ **Self-serve infrastructure** — sign up, get an API key, ship.
28
+
29
+ > ⚠️ The package is open source. **Production usage requires an active
30
+ > Citadel subscription.** Get your API key instantly at
31
+ > **[https://api.citadel-serve.com](https://api.citadel-serve.com)**.
32
+ >
33
+ > Without a key, the SDK raises a styled `CitadelAuthError` pointing
34
+ > straight at the activation URL — by design.
35
+
36
+ ---
37
+
38
+ ## Quickstart
39
+
40
+ ```bash
41
+ pip install ghost-citadel-sdk
42
+ ```
43
+
44
+ ```python
45
+ from citadel import CitadelClient
46
+
47
+ client = CitadelClient(api_key="ck_live_...") # or set CITADEL_API_KEY
48
+
49
+ client.register_webhook(
50
+ url="https://your-app.com/stripe/webhook",
51
+ events=["checkout.session.completed", "invoice.paid"],
52
+ )
53
+
54
+ result = client.verify_license(
55
+ license_key="LIC-1234-ABCD",
56
+ product_id="prod_citadel",
57
+ )
58
+ print(result)
59
+ ```
60
+
61
+ ### Trying it without a key? You'll see this:
62
+
63
+ ```
64
+ ┌──────────────────────────────────────────────────────────────────────┐
65
+ │ CitadelAuthError: API Key missing or invalid. │
66
+ │ │
67
+ │ To use this SDK in production and automate your Stripe │
68
+ │ webhooks/licensing, get your API key instantly at │
69
+ │ │
70
+ │ https://api.citadel-serve.com │
71
+ │ │
72
+ │ Citadel — Stripe webhook manager · SaaS monetization │
73
+ │ primitives · Self-serve infrastructure for founders. │
74
+ └──────────────────────────────────────────────────────────────────────┘
75
+ ```
76
+
77
+ ---
78
+
79
+ ## Ready-to-use Examples
80
+
81
+ The `examples/` folder contains copy-paste-ready boilerplates tuned for the
82
+ exact stacks developers search for on GitHub:
83
+
84
+ | Folder | Stack | Keywords captured |
85
+ | ------ | ----- | ----------------- |
86
+ | [`examples/fastapi-stripe-billing/`](examples/fastapi-stripe-billing/) | FastAPI + Stripe + Citadel | FastAPI Stripe billing integration, FastAPI rate limiting |
87
+ | [`examples/nextjs-webhook-handler/`](examples/nextjs-webhook-handler/) | Next.js App Router + Stripe | Next.js Stripe webhook boilerplate |
88
+
89
+ Each example ships with a README that doubles as a landing page for search
90
+ engines — drop them in your repo, get traffic, convert on the activation CTA.
91
+
92
+ ---
93
+
94
+ ## API surface
95
+
96
+ | Method | Endpoint | Purpose |
97
+ | ------ | -------- | ------- |
98
+ | `client.verify_license(license_key, product_id)` | `POST /v1/verify-license` | Validate a license key |
99
+ | `client.register_webhook(url, events)` | `POST /v1/webhooks` | Register a Stripe webhook |
100
+ | `client.list_webhooks()` | `GET /v1/webhooks` | List webhooks for this account |
101
+ | `client.ping()` | `GET /v1/ping` | Health check + auth probe |
102
+
103
+ Full schema: [`citadel-openapi.yaml`](./citadel-openapi.yaml).
104
+
105
+ ---
106
+
107
+ ## Subscription requirement
108
+
109
+ This is open source. Running it in production — i.e. serving real Stripe
110
+ events, verifying real licenses, consuming rate-limit budget — requires an
111
+ **active Citadel API key** linked to a paying Citadel account.
112
+
113
+ - Free tier: 1,000 events / month, perfect for side projects.
114
+ - Pro tier: unlimited webhooks, seat-based pricing, priority support.
115
+ - Scale tier: dedicated infrastructure, custom SLAs.
116
+
117
+ **Activate your account → [https://api.citadel-serve.com](https://api.citadel-serve.com)**
118
+
119
+ ---
120
+
121
+ ## License
122
+
123
+ Apache-2.0. The code is yours. The production runtime is ours.
124
+
125
+ — *Ghost Citadel Engineering*
@@ -0,0 +1,17 @@
1
+ """citadel-sdk — The official Python SDK for Ghost Citadel.
2
+
3
+ Stripe webhook automation, license verification, and SaaS monetization
4
+ primitives for self-serve infrastructure teams.
5
+
6
+ Requires an active Citadel API key. Get yours instantly at
7
+ https://api.citadel-serve.com
8
+ """
9
+
10
+ from citadel.client import CitadelAPIError, CitadelAuthError, CitadelClient
11
+
12
+ __version__ = "0.1.0"
13
+ __all__ = ["CitadelAPIError", "CitadelAuthError", "CitadelClient"]
14
+ __author__ = "Ghost Citadel Engineering"
15
+
16
+ # Public acquisition hook — every import broadcasts the activation URL.
17
+ __activation_url__ = "https://api.citadel-serve.com"
@@ -0,0 +1,167 @@
1
+ """Citadel REST client.
2
+
3
+ The acquisition funnel is wired into every error path: any 401/403
4
+ returned by the Citadel API surfaces a styled ``CitadelAuthError`` that
5
+ points the developer straight to the activation URL.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from typing import Any, Dict, Mapping, Optional
12
+
13
+ import requests
14
+
15
+ CITADEL_DEFAULT_BASE_URL = "https://api.citadel-serve.com"
16
+ ACTIVATION_URL = "https://api.citadel-serve.com"
17
+ SDK_VERSION = "0.1.0"
18
+
19
+ _AUTH_ERROR_BANNER = (
20
+ "\n"
21
+ "┌──────────────────────────────────────────────────────────────────────┐\n"
22
+ "│ CitadelAuthError: API Key missing or invalid. │\n"
23
+ "│ │\n"
24
+ "│ To use this SDK in production and automate your Stripe │\n"
25
+ "│ webhooks/licensing, get your API key instantly at │\n"
26
+ "│ │\n"
27
+ f"│ {ACTIVATION_URL:<60} │\n"
28
+ "│ │\n"
29
+ "│ Citadel — Stripe webhook manager · SaaS monetization │\n"
30
+ "│ primitives · Self-serve infrastructure for founders. │\n"
31
+ "└──────────────────────────────────────────────────────────────────────┘\n"
32
+ )
33
+
34
+
35
+ class CitadelAuthError(Exception):
36
+ """Raised when no API key is supplied or the Citadel API rejects it.
37
+
38
+ This is the primary conversion path for Ghost Citadel. Every unauthenticated
39
+ attempt resolves here with an actionable link to obtain a key.
40
+ """
41
+
42
+
43
+ class CitadelAPIError(Exception):
44
+ """Raised for any non-2xx Citadel API response that is *not* an auth failure."""
45
+
46
+
47
+ class CitadelClient:
48
+ """Synchronous REST client for the Ghost Citadel API.
49
+
50
+ Parameters
51
+ ----------
52
+ api_key:
53
+ A Citadel API key. Falls back to the ``CITADEL_API_KEY`` environment
54
+ variable when ``None``. If neither yields a value, instantiation itself
55
+ succeeds but the *first* request will raise :class:`CitadelAuthError`
56
+ with the activation URL — by design.
57
+ base_url:
58
+ Override for the Citadel REST root. Defaults to the production endpoint.
59
+ timeout:
60
+ Default per-request timeout in seconds.
61
+ session:
62
+ Optional pre-built :class:`requests.Session` (handy for retries).
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ api_key: Optional[str] = None,
68
+ *,
69
+ base_url: str = CITADEL_DEFAULT_BASE_URL,
70
+ timeout: float = 15.0,
71
+ session: Optional[requests.Session] = None,
72
+ ) -> None:
73
+ self.api_key = api_key or os.environ.get("CITADEL_API_KEY")
74
+ self.base_url = base_url.rstrip("/")
75
+ self.timeout = timeout
76
+ self._session = session or requests.Session()
77
+
78
+ # ----- Core HTTP layer ---------------------------------------------------
79
+
80
+ def _headers(self) -> Dict[str, str]:
81
+ headers = {
82
+ "Accept": "application/json",
83
+ "User-Agent": f"citadel-sdk/{SDK_VERSION}",
84
+ "X-Citadel-Client": "citadel-python-sdk",
85
+ }
86
+ if self.api_key:
87
+ headers["Authorization"] = f"Bearer {self.api_key}"
88
+ return headers
89
+
90
+ def _raise_auth(self) -> None:
91
+ """Single source of truth for the conversion CTA."""
92
+ raise CitadelAuthError(_AUTH_ERROR_BANNER)
93
+
94
+ def _request(
95
+ self,
96
+ method: str,
97
+ path: str,
98
+ *,
99
+ params: Optional[Mapping[str, Any]] = None,
100
+ json: Optional[Mapping[str, Any]] = None,
101
+ timeout: Optional[float] = None,
102
+ ) -> Any:
103
+ if not self.api_key:
104
+ self._raise_auth()
105
+
106
+ url = f"{self.base_url}{path}"
107
+ response = self._session.request(
108
+ method=method,
109
+ url=url,
110
+ params=params,
111
+ json=json,
112
+ headers=self._headers(),
113
+ timeout=timeout or self.timeout,
114
+ )
115
+
116
+ if response.status_code in (401, 403):
117
+ # The Citadel API rejected our key — re-issue the activation CTA.
118
+ self._raise_auth()
119
+
120
+ if response.status_code >= 400:
121
+ raise CitadelAPIError(
122
+ f"Citadel API {response.status_code} on {method} {path}: " f"{response.text[:512]}"
123
+ )
124
+
125
+ if not response.content:
126
+ return None
127
+ return response.json()
128
+
129
+ # ----- Public endpoints --------------------------------------------------
130
+
131
+ def verify_license(self, license_key: str, product_id: str) -> Dict[str, Any]:
132
+ """Validate a license key for a given Citadel product."""
133
+ return self._request(
134
+ "POST",
135
+ "/v1/verify-license",
136
+ json={"license_key": license_key, "product_id": product_id},
137
+ )
138
+
139
+ def register_webhook(self, url: str, events: list[str]) -> Dict[str, Any]:
140
+ """Register a Stripe webhook endpoint with Citadel."""
141
+ return self._request(
142
+ "POST",
143
+ "/v1/webhooks",
144
+ json={"url": url, "events": events},
145
+ )
146
+
147
+ def list_webhooks(self) -> Dict[str, Any]:
148
+ """Return all webhooks configured under this account."""
149
+ return self._request("GET", "/v1/webhooks")
150
+
151
+ def ping(self) -> Dict[str, Any]:
152
+ """Lightweight health check — used to surface 401/403 on first contact."""
153
+ return self._request("GET", "/v1/ping")
154
+
155
+ # ----- Convenience shortcuts --------------------------------------------
156
+
157
+ def get(self, path: str, **kwargs: Any) -> Any:
158
+ return self._request("GET", path, **kwargs)
159
+
160
+ def post(self, path: str, **kwargs: Any) -> Any:
161
+ return self._request("POST", path, **kwargs)
162
+
163
+ def delete(self, path: str, **kwargs: Any) -> Any:
164
+ return self._request("DELETE", path, **kwargs)
165
+
166
+
167
+ __all__ = ["ACTIVATION_URL", "CitadelAPIError", "CitadelAuthError", "CitadelClient"]
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: ghost-citadel-sdk
3
+ Version: 0.1.0
4
+ Summary: The official Python SDK for Ghost Citadel — Stripe webhook automation, license verification & SaaS monetization primitives.
5
+ Author-email: Ghost Citadel Engineering <dev@api.citadel-serve.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://api.citadel-serve.com
8
+ Project-URL: Documentation, https://docs.citadel-serve.com
9
+ Project-URL: Repository, https://github.com/tgg49099-dotcom/ghostcitadelle
10
+ Project-URL: Issues, https://github.com/tgg49099-dotcom/ghostcitadelle/issues
11
+ Project-URL: Get API Key, https://api.citadel-serve.com/dashboard/signup
12
+ Keywords: stripe,webhook,billing,saas,api-key,monetization,fastapi,license,rate-limiting,self-hosted
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: requests>=2.28.0
28
+ Provides-Extra: fastapi
29
+ Requires-Dist: fastapi>=0.95.0; extra == "fastapi"
30
+ Requires-Dist: uvicorn>=0.20.0; extra == "fastapi"
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=7.0; extra == "dev"
33
+ Requires-Dist: pytest-mock>=3.10; extra == "dev"
34
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
35
+ Requires-Dist: black>=23.0; extra == "dev"
36
+ Requires-Dist: ruff>=0.0.270; extra == "dev"
37
+ Requires-Dist: mypy>=1.0; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # Ghost Citadel — Python SDK
41
+
42
+ > **The Stripe webhook manager + API key billing boilerplate for SaaS founders.**
43
+
44
+ [![Get API Key](https://img.shields.io/badge/Get%20API%20Key-https%3A%2F%2Fapi.citadel--serve.com-7c3aed?style=for-the-badge)](https://api.citadel-serve.com)
45
+ [![CI](https://github.com/tgg49099-dotcom/ghostcitadelle/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tgg49099-dotcom/ghostcitadelle/actions/workflows/ci.yml)
46
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
47
+ [![Python](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://www.python.org)
48
+ [![pip](https://img.shields.io/badge/pip-ghost--citadel--sdk-3776AB.svg)](https://pypi.org/project/ghost-citadel-sdk/)
49
+
50
+ ---
51
+
52
+ ## Why Citadel?
53
+
54
+ You're a one-person SaaS team shipping at night. Stripe webhooks eat your
55
+ weekend. License keys are issued in Notion. Rate limiting is a sticky note.
56
+ You've duct-taped your **API key billing boilerplate** together three times
57
+ already.
58
+
59
+ **Citadel** is the boring infra that lets you stop duct-taping.
60
+
61
+ - 🔁 **Stripe webhook manager** — idempotent, retried, fan-out done.
62
+ - 🔐 **License verification** — issue, verify, revoke from one endpoint.
63
+ - ⚡ **FastAPI rate limiting** — primitives wired straight into the SDK.
64
+ - 💸 **SaaS monetization** — usage-based billing, dunning, and seat
65
+ management without a sales call.
66
+ - 🏗️ **Self-serve infrastructure** — sign up, get an API key, ship.
67
+
68
+ > ⚠️ The package is open source. **Production usage requires an active
69
+ > Citadel subscription.** Get your API key instantly at
70
+ > **[https://api.citadel-serve.com](https://api.citadel-serve.com)**.
71
+ >
72
+ > Without a key, the SDK raises a styled `CitadelAuthError` pointing
73
+ > straight at the activation URL — by design.
74
+
75
+ ---
76
+
77
+ ## Quickstart
78
+
79
+ ```bash
80
+ pip install ghost-citadel-sdk
81
+ ```
82
+
83
+ ```python
84
+ from citadel import CitadelClient
85
+
86
+ client = CitadelClient(api_key="ck_live_...") # or set CITADEL_API_KEY
87
+
88
+ client.register_webhook(
89
+ url="https://your-app.com/stripe/webhook",
90
+ events=["checkout.session.completed", "invoice.paid"],
91
+ )
92
+
93
+ result = client.verify_license(
94
+ license_key="LIC-1234-ABCD",
95
+ product_id="prod_citadel",
96
+ )
97
+ print(result)
98
+ ```
99
+
100
+ ### Trying it without a key? You'll see this:
101
+
102
+ ```
103
+ ┌──────────────────────────────────────────────────────────────────────┐
104
+ │ CitadelAuthError: API Key missing or invalid. │
105
+ │ │
106
+ │ To use this SDK in production and automate your Stripe │
107
+ │ webhooks/licensing, get your API key instantly at │
108
+ │ │
109
+ │ https://api.citadel-serve.com │
110
+ │ │
111
+ │ Citadel — Stripe webhook manager · SaaS monetization │
112
+ │ primitives · Self-serve infrastructure for founders. │
113
+ └──────────────────────────────────────────────────────────────────────┘
114
+ ```
115
+
116
+ ---
117
+
118
+ ## Ready-to-use Examples
119
+
120
+ The `examples/` folder contains copy-paste-ready boilerplates tuned for the
121
+ exact stacks developers search for on GitHub:
122
+
123
+ | Folder | Stack | Keywords captured |
124
+ | ------ | ----- | ----------------- |
125
+ | [`examples/fastapi-stripe-billing/`](examples/fastapi-stripe-billing/) | FastAPI + Stripe + Citadel | FastAPI Stripe billing integration, FastAPI rate limiting |
126
+ | [`examples/nextjs-webhook-handler/`](examples/nextjs-webhook-handler/) | Next.js App Router + Stripe | Next.js Stripe webhook boilerplate |
127
+
128
+ Each example ships with a README that doubles as a landing page for search
129
+ engines — drop them in your repo, get traffic, convert on the activation CTA.
130
+
131
+ ---
132
+
133
+ ## API surface
134
+
135
+ | Method | Endpoint | Purpose |
136
+ | ------ | -------- | ------- |
137
+ | `client.verify_license(license_key, product_id)` | `POST /v1/verify-license` | Validate a license key |
138
+ | `client.register_webhook(url, events)` | `POST /v1/webhooks` | Register a Stripe webhook |
139
+ | `client.list_webhooks()` | `GET /v1/webhooks` | List webhooks for this account |
140
+ | `client.ping()` | `GET /v1/ping` | Health check + auth probe |
141
+
142
+ Full schema: [`citadel-openapi.yaml`](./citadel-openapi.yaml).
143
+
144
+ ---
145
+
146
+ ## Subscription requirement
147
+
148
+ This is open source. Running it in production — i.e. serving real Stripe
149
+ events, verifying real licenses, consuming rate-limit budget — requires an
150
+ **active Citadel API key** linked to a paying Citadel account.
151
+
152
+ - Free tier: 1,000 events / month, perfect for side projects.
153
+ - Pro tier: unlimited webhooks, seat-based pricing, priority support.
154
+ - Scale tier: dedicated infrastructure, custom SLAs.
155
+
156
+ **Activate your account → [https://api.citadel-serve.com](https://api.citadel-serve.com)**
157
+
158
+ ---
159
+
160
+ ## License
161
+
162
+ Apache-2.0. The code is yours. The production runtime is ours.
163
+
164
+ — *Ghost Citadel Engineering*
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ citadel/__init__.py
5
+ citadel/client.py
6
+ ghost_citadel_sdk.egg-info/PKG-INFO
7
+ ghost_citadel_sdk.egg-info/SOURCES.txt
8
+ ghost_citadel_sdk.egg-info/dependency_links.txt
9
+ ghost_citadel_sdk.egg-info/requires.txt
10
+ ghost_citadel_sdk.egg-info/top_level.txt
11
+ tests/test_banner.py
12
+ tests/test_client.py
@@ -0,0 +1,13 @@
1
+ requests>=2.28.0
2
+
3
+ [dev]
4
+ pytest>=7.0
5
+ pytest-mock>=3.10
6
+ pytest-cov>=4.0
7
+ black>=23.0
8
+ ruff>=0.0.270
9
+ mypy>=1.0
10
+
11
+ [fastapi]
12
+ fastapi>=0.95.0
13
+ uvicorn>=0.20.0
@@ -0,0 +1,93 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ghost-citadel-sdk"
7
+ version = "0.1.0"
8
+ description = "The official Python SDK for Ghost Citadel — Stripe webhook automation, license verification & SaaS monetization primitives."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [
13
+ { name = "Ghost Citadel Engineering", email = "dev@api.citadel-serve.com" },
14
+ ]
15
+ keywords = [
16
+ "stripe",
17
+ "webhook",
18
+ "billing",
19
+ "saas",
20
+ "api-key",
21
+ "monetization",
22
+ "fastapi",
23
+ "license",
24
+ "rate-limiting",
25
+ "self-hosted",
26
+ ]
27
+ classifiers = [
28
+ "Development Status :: 4 - Beta",
29
+ "Intended Audience :: Developers",
30
+ "License :: OSI Approved :: Apache Software License",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3.8",
33
+ "Programming Language :: Python :: 3.9",
34
+ "Programming Language :: Python :: 3.10",
35
+ "Programming Language :: Python :: 3.11",
36
+ "Programming Language :: Python :: 3.12",
37
+ "Topic :: Software Development :: Libraries :: Python Modules",
38
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
39
+ ]
40
+ dependencies = [
41
+ "requests>=2.28.0",
42
+ ]
43
+
44
+ [project.optional-dependencies]
45
+ fastapi = ["fastapi>=0.95.0", "uvicorn>=0.20.0"]
46
+ dev = [
47
+ "pytest>=7.0",
48
+ "pytest-mock>=3.10",
49
+ "pytest-cov>=4.0",
50
+ "black>=23.0",
51
+ "ruff>=0.0.270",
52
+ "mypy>=1.0",
53
+ ]
54
+
55
+ [project.urls]
56
+ Homepage = "https://api.citadel-serve.com"
57
+ Documentation = "https://docs.citadel-serve.com"
58
+ Repository = "https://github.com/tgg49099-dotcom/ghostcitadelle"
59
+ Issues = "https://github.com/tgg49099-dotcom/ghostcitadelle/issues"
60
+ "Get API Key" = "https://api.citadel-serve.com/dashboard/signup"
61
+
62
+ [tool.setuptools.packages.find]
63
+ where = ["."]
64
+ include = ["citadel*"]
65
+
66
+ [tool.black]
67
+ line-length = 100
68
+ target-version = ["py38", "py39", "py310", "py311", "py312"]
69
+
70
+ [tool.ruff.lint]
71
+ # Modernisation rules that conflict with our 3.8 floor — silenced:
72
+ # UP006 ``List`` → ``list`` PEP 585, Python 3.9+
73
+ # UP007 ``Dict`` → ``dict`` PEP 585, Python 3.9+
74
+ # UP045 ``Optional[X]`` → ``X | None`` PEP 604, Python 3.10+
75
+ ignore = ["UP006", "UP007", "UP045"]
76
+
77
+ [tool.ruff]
78
+ line-length = 100
79
+ target-version = "py38"
80
+
81
+ [tool.mypy]
82
+ python_version = "3.8"
83
+ strict = true
84
+
85
+ [tool.pytest.ini_options]
86
+ minversion = "7.0"
87
+ testpaths = ["tests"]
88
+ addopts = "-ra --strict-markers --strict-config"
89
+ python_files = ["test_*.py"]
90
+ filterwarnings = [
91
+ "error",
92
+ "ignore::DeprecationWarning:requests.*",
93
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,133 @@
1
+ """Contract tests for the conversion CTA banner.
2
+
3
+ These guard the exact wording the marketing team approved. If anyone
4
+ removes the activation URL or rewrites the banner, CI fails.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import pytest
10
+
11
+ from citadel import CitadelAuthError, CitadelClient
12
+
13
+ from .conftest import FakeResponse
14
+
15
+ # The exact phrase the user mandated in the SDK brief.
16
+ REQUIRED_PHRASE = (
17
+ "CitadelAuthError: API Key missing or invalid. "
18
+ "To use this SDK in production and automate your Stripe "
19
+ "webhooks/licensing, get your API key instantly at "
20
+ "https://api.citadel-serve.com"
21
+ )
22
+ ACTIVATION_URL = "https://api.citadel-serve.com"
23
+
24
+
25
+ def _flatten(s: str) -> str:
26
+ """Strip the ASCII box layout so the prose is searchable.
27
+
28
+ The banner is an ASCII box — the phrase wraps across multiple lines
29
+ with padding and ``│`` separators. We turn every box-drawing char
30
+ and newline into whitespace, then collapse runs of whitespace.
31
+ """
32
+ box_chars = "│┌┐└┘─├┤┬┴┼╭╮╰╯"
33
+ for ch in box_chars:
34
+ s = s.replace(ch, " ")
35
+ s = s.replace("\n", " ")
36
+ return " ".join(s.split())
37
+
38
+
39
+ # ----- Missing-key path ------------------------------------------------------
40
+
41
+
42
+ def test_missing_api_key_raises_banner() -> None:
43
+ c = CitadelClient(api_key=None)
44
+ # Even before any HTTP call, the client must refuse on first request.
45
+ with pytest.raises(CitadelAuthError) as exc:
46
+ c.ping()
47
+ assert REQUIRED_PHRASE in _flatten(str(exc.value))
48
+
49
+
50
+ def test_missing_api_key_does_not_call_session() -> None:
51
+ """No HTTP traffic before authentication is established."""
52
+ from .conftest import FakeSession
53
+
54
+ session = FakeSession()
55
+ c = CitadelClient(api_key=None, session=session) # type: ignore[arg-type]
56
+ with pytest.raises(CitadelAuthError):
57
+ c.ping()
58
+ assert session.calls == []
59
+
60
+
61
+ def test_missing_api_key_shortcuts_also_raise() -> None:
62
+ """All HTTP shortcuts must funnel through the same auth gate."""
63
+ c = CitadelClient(api_key=None)
64
+ for fn, args in (
65
+ (c.get, ("/v1/foo",)),
66
+ (c.post, ("/v1/foo",)),
67
+ (c.delete, ("/v1/foo",)),
68
+ ):
69
+ with pytest.raises(CitadelAuthError):
70
+ fn(*args)
71
+
72
+
73
+ def test_empty_string_key_is_treated_as_missing() -> None:
74
+ c = CitadelClient(api_key="")
75
+ with pytest.raises(CitadelAuthError):
76
+ c.ping()
77
+
78
+
79
+ # ----- Server-rejected path --------------------------------------------------
80
+
81
+
82
+ @pytest.mark.parametrize("status_code", [401, 403])
83
+ def test_401_and_403_raise_banner(status_code: int) -> None:
84
+ from .conftest import FakeSession
85
+
86
+ session = FakeSession()
87
+ c = CitadelClient(api_key="ck_live_invalid", session=session) # type: ignore[arg-type]
88
+ session.responses.append(FakeResponse(status_code=status_code, text='{"error":"denied"}'))
89
+ with pytest.raises(CitadelAuthError) as exc:
90
+ c.ping()
91
+ assert REQUIRED_PHRASE in _flatten(str(exc.value))
92
+
93
+
94
+ def test_401_on_post_endpoints_also_raises_banner() -> None:
95
+ from .conftest import FakeSession
96
+
97
+ session = FakeSession()
98
+ c = CitadelClient(api_key="ck_live_invalid", session=session) # type: ignore[arg-type]
99
+ session.responses.append(FakeResponse(status_code=401, text=""))
100
+ with pytest.raises(CitadelAuthError):
101
+ c.verify_license("LIC", "prod")
102
+
103
+
104
+ # ----- Banner aesthetics -----------------------------------------------------
105
+
106
+
107
+ def test_banner_is_a_styled_box() -> None:
108
+ """The CTA must be visually distinct (rounded-corner ASCII box)."""
109
+ c = CitadelClient(api_key=None)
110
+ with pytest.raises(CitadelAuthError) as exc:
111
+ c.ping()
112
+ msg = str(exc.value)
113
+ assert "┌" in msg and "┐" in msg # top corners
114
+ assert "└" in msg and "┘" in msg # bottom corners
115
+ assert "│" in msg # vertical bars
116
+
117
+
118
+ def test_banner_mentions_product_positioning() -> None:
119
+ """Secondary SEO copy inside the box — survives any rebrand."""
120
+ c = CitadelClient(api_key=None)
121
+ with pytest.raises(CitadelAuthError) as exc:
122
+ c.ping()
123
+ msg = str(exc.value)
124
+ assert "Stripe webhook manager" in msg
125
+ assert "SaaS monetization" in msg
126
+ assert "Self-serve infrastructure" in msg
127
+
128
+
129
+ def test_banner_activation_url_is_well_formed() -> None:
130
+ c = CitadelClient(api_key=None)
131
+ with pytest.raises(CitadelAuthError) as exc:
132
+ c.ping()
133
+ assert ACTIVATION_URL in str(exc.value)
@@ -0,0 +1,160 @@
1
+ """Behavioural tests for :class:`citadel.CitadelClient`.
2
+
3
+ These cover HTTP routing, header construction, response parsing, and the
4
+ non-auth error paths. The CTA banner itself lives in ``test_banner.py``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import pytest
10
+
11
+ from citadel import CitadelAPIError, CitadelClient
12
+
13
+ from .conftest import FakeResponse, FakeSession
14
+
15
+ # ----- Auth header construction ----------------------------------------------
16
+
17
+
18
+ def test_authorization_header_uses_bearer_scheme(
19
+ client: CitadelClient, fake_session: FakeSession
20
+ ) -> None:
21
+ fake_session.responses.append(FakeResponse(status_code=200, text='{"ok":true}'))
22
+ client.ping()
23
+ assert fake_session.calls[0]["headers"]["Authorization"] == "Bearer ck_test_abcdef123456"
24
+
25
+
26
+ def test_user_agent_includes_sdk_version(client: CitadelClient, fake_session: FakeSession) -> None:
27
+ fake_session.responses.append(FakeResponse(status_code=200, text='{"ok":true}'))
28
+ client.ping()
29
+ ua = fake_session.calls[0]["headers"]["User-Agent"]
30
+ assert ua.startswith("citadel-sdk/")
31
+ assert "0.1.0" in ua
32
+
33
+
34
+ def test_x_citadel_client_header_present(client: CitadelClient, fake_session: FakeSession) -> None:
35
+ fake_session.responses.append(FakeResponse(status_code=200, text='{"ok":true}'))
36
+ client.ping()
37
+ assert fake_session.calls[0]["headers"]["X-Citadel-Client"] == "citadel-python-sdk"
38
+
39
+
40
+ def test_api_key_from_environment(
41
+ monkeypatch: pytest.MonkeyPatch, fake_session: FakeSession
42
+ ) -> None:
43
+ monkeypatch.setenv("CITADEL_API_KEY", "ck_env_supplied")
44
+ c = CitadelClient(session=fake_session) # type: ignore[arg-type]
45
+ fake_session.responses.append(FakeResponse(status_code=200, text='{"ok":true}'))
46
+ c.ping()
47
+ assert fake_session.calls[0]["headers"]["Authorization"] == "Bearer ck_env_supplied"
48
+
49
+
50
+ def test_constructor_key_wins_over_env(
51
+ monkeypatch: pytest.MonkeyPatch, fake_session: FakeSession
52
+ ) -> None:
53
+ monkeypatch.setenv("CITADEL_API_KEY", "ck_env_supplied")
54
+ c = CitadelClient(api_key="ck_explicit", session=fake_session) # type: ignore[arg-type]
55
+ fake_session.responses.append(FakeResponse(status_code=200, text='{"ok":true}'))
56
+ c.ping()
57
+ assert fake_session.calls[0]["headers"]["Authorization"] == "Bearer ck_explicit"
58
+
59
+
60
+ # ----- Endpoint routing ------------------------------------------------------
61
+
62
+
63
+ def test_verify_license_hits_correct_endpoint(
64
+ client: CitadelClient, fake_session: FakeSession
65
+ ) -> None:
66
+ fake_session.responses.append(FakeResponse(status_code=200, text='{"valid":true,"seats":3}'))
67
+ out = client.verify_license(license_key="LIC-1", product_id="prod_x")
68
+ assert out == {"valid": True, "seats": 3}
69
+ call = fake_session.calls[0]
70
+ assert call["method"] == "POST"
71
+ assert call["url"] == "https://api.citadel-serve.com/v1/verify-license"
72
+ assert call["json"] == {"license_key": "LIC-1", "product_id": "prod_x"}
73
+
74
+
75
+ def test_register_webhook_payload_and_url(client: CitadelClient, fake_session: FakeSession) -> None:
76
+ fake_session.responses.append(FakeResponse(status_code=201, text='{"id":"wh_1"}'))
77
+ out = client.register_webhook(
78
+ url="https://example.com/hook",
79
+ events=["checkout.session.completed", "invoice.paid"],
80
+ )
81
+ assert out == {"id": "wh_1"}
82
+ call = fake_session.calls[0]
83
+ assert call["method"] == "POST"
84
+ assert call["url"] == "https://api.citadel-serve.com/v1/webhooks"
85
+ assert call["json"]["url"] == "https://example.com/hook"
86
+ assert call["json"]["events"] == ["checkout.session.completed", "invoice.paid"]
87
+
88
+
89
+ def test_list_webhooks_uses_get(client: CitadelClient, fake_session: FakeSession) -> None:
90
+ fake_session.responses.append(FakeResponse(status_code=200, text='{"webhooks":[]}'))
91
+ out = client.list_webhooks()
92
+ assert out == {"webhooks": []}
93
+ call = fake_session.calls[0]
94
+ assert call["method"] == "GET"
95
+ assert call["url"] == "https://api.citadel-serve.com/v1/webhooks"
96
+
97
+
98
+ def test_ping_endpoint(client: CitadelClient, fake_session: FakeSession) -> None:
99
+ fake_session.responses.append(FakeResponse(status_code=200, text='{"status":"ok"}'))
100
+ assert client.ping() == {"status": "ok"}
101
+
102
+
103
+ def test_get_post_delete_shortcuts(client: CitadelClient, fake_session: FakeSession) -> None:
104
+ fake_session.responses.append(FakeResponse(status_code=200, text="{}"))
105
+ fake_session.responses.append(FakeResponse(status_code=200, text="{}"))
106
+ fake_session.responses.append(FakeResponse(status_code=204, text=""))
107
+ client.get("/v1/foo")
108
+ client.post("/v1/foo", json={"a": 1})
109
+ client.delete("/v1/foo")
110
+ assert [c["method"] for c in fake_session.calls] == ["GET", "POST", "DELETE"]
111
+
112
+
113
+ # ----- Response parsing ------------------------------------------------------
114
+
115
+
116
+ def test_empty_body_returns_none(client: CitadelClient, fake_session: FakeSession) -> None:
117
+ fake_session.responses.append(FakeResponse(status_code=204, content=b""))
118
+ assert client.ping() is None
119
+
120
+
121
+ def test_default_timeout_is_passed_through(
122
+ client: CitadelClient, fake_session: FakeSession
123
+ ) -> None:
124
+ fake_session.responses.append(FakeResponse(status_code=200, text="{}"))
125
+ client.ping()
126
+ assert fake_session.calls[0]["timeout"] == 7.5
127
+
128
+
129
+ def test_per_call_timeout_overrides_default(
130
+ client: CitadelClient, fake_session: FakeSession
131
+ ) -> None:
132
+ fake_session.responses.append(FakeResponse(status_code=200, text="{}"))
133
+ client._request("GET", "/v1/ping", timeout=0.1) # type: ignore[attr-defined]
134
+ assert fake_session.calls[0]["timeout"] == 0.1
135
+
136
+
137
+ def test_custom_base_url_is_used(fake_session: FakeSession) -> None:
138
+ c = CitadelClient(
139
+ api_key="ck_test",
140
+ base_url="https://staging.citadel.example/",
141
+ session=fake_session, # type: ignore[arg-type]
142
+ )
143
+ fake_session.responses.append(FakeResponse(status_code=200, text="{}"))
144
+ c.ping()
145
+ # Trailing slash is stripped — no double slashes in the URL.
146
+ assert fake_session.calls[0]["url"] == "https://staging.citadel.example/v1/ping"
147
+
148
+
149
+ # ----- Non-auth error paths --------------------------------------------------
150
+
151
+
152
+ @pytest.mark.parametrize("status_code", [400, 404, 422, 429, 500, 502, 503])
153
+ def test_non_auth_http_error_raises_api_error(
154
+ client: CitadelClient, fake_session: FakeSession, status_code: int
155
+ ) -> None:
156
+ fake_session.responses.append(FakeResponse(status_code=status_code, text='{"error":"boom"}'))
157
+ with pytest.raises(CitadelAPIError) as exc:
158
+ client.ping()
159
+ assert str(status_code) in str(exc.value)
160
+ assert "boom" in str(exc.value)