cnamio 1.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.
- cnamio-1.1.0/LICENSE +21 -0
- cnamio-1.1.0/PKG-INFO +70 -0
- cnamio-1.1.0/README.md +46 -0
- cnamio-1.1.0/cnamio.egg-info/PKG-INFO +70 -0
- cnamio-1.1.0/cnamio.egg-info/SOURCES.txt +8 -0
- cnamio-1.1.0/cnamio.egg-info/dependency_links.txt +1 -0
- cnamio-1.1.0/cnamio.egg-info/top_level.txt +1 -0
- cnamio-1.1.0/cnamio.py +267 -0
- cnamio-1.1.0/pyproject.toml +33 -0
- cnamio-1.1.0/setup.cfg +4 -0
cnamio-1.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cnamio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
cnamio-1.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cnamio
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: Server SDK for Cnamio: let your users connect their own custom domain to your app (DNS provider detection, automatic or guided records, propagation checks, signed webhooks). One module, standard library only.
|
|
5
|
+
Author-email: Cnamio <contato@cnamio.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://cnamio.com
|
|
8
|
+
Project-URL: Documentation, https://cnamio.com/docs
|
|
9
|
+
Project-URL: Repository, https://github.com/cnamio/sdk
|
|
10
|
+
Project-URL: For AI agents, https://cnamio.com/agent-onboarding/SKILL.md
|
|
11
|
+
Keywords: custom domains,custom domain,connect domain,dns,cname,domain verification,saas,multi-tenant,webhook,ai agents,mcp,cnamio
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Internet :: Name Service (DNS)
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# cnamio
|
|
26
|
+
|
|
27
|
+
Server SDK for [Cnamio](https://cnamio.com): let the users of your app connect their own domain (`shop.customer.com` → your app). Cnamio finds where the domain's DNS is hosted, creates the records with the user's provider token (used once, never stored) or returns the exact records to copy, confirms them on the authoritative nameservers and sends your backend a signed webhook. Existing DNS records are never deleted or overwritten.
|
|
28
|
+
|
|
29
|
+
One module, standard library only, type hints throughout, Python 3.9+. Server only: it holds your application secret.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install cnamio
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import os
|
|
37
|
+
from cnamio import Cnamio, records_for_user, verify_webhook
|
|
38
|
+
|
|
39
|
+
cnamio = Cnamio() # reads CNAMIO_APPLICATION_ID and CNAMIO_SECRET
|
|
40
|
+
# A CNAME to your hosting plus an ownership TXT unique to this user.
|
|
41
|
+
records = records_for_user(target="customers.yourapp.com", user_id=user.id, ownership_key=os.environ["CNAMIO_OWNERSHIP_KEY"])
|
|
42
|
+
|
|
43
|
+
session = cnamio.create_session(user_id=user.id, dns_records=records) # -> the browser's connect window
|
|
44
|
+
job = cnamio.connect("shop.customer.com", records, user_id=user.id) # or headless: exact records to show
|
|
45
|
+
status = cnamio.status(job["job_id"])["status"] # pending -> completed
|
|
46
|
+
ok = verify_webhook(raw_body, headers, os.environ.get("CNAMIO_WEBHOOK_SECRET")) # domain.added = connected
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
In the browser, load `https://connect.cnamio.com/sdk/v1.js` and call `window.cnamio.connectDomain({ ...session, applicationName: 'Your App' })`.
|
|
50
|
+
|
|
51
|
+
## No account yet
|
|
52
|
+
|
|
53
|
+
- **Sandbox, no account:** `curl -s -X POST https://api.cnamio.com/v1/agent/sandbox` returns a 30-minute session of a test application (no real DNS). Use it as `Authorization: Bearer <auth_token>` with header `applicationId` on the REST routes.
|
|
54
|
+
- **Free account:** sign up at https://cnamio.com/#start, or let your coding agent call `POST https://api.cnamio.com/v1/agent/signup` (MCP tool `start_signup`) with your email. You get a test application (sandbox provider) and a live one on the free plan once you open the emailed link.
|
|
55
|
+
|
|
56
|
+
## For coding agents
|
|
57
|
+
|
|
58
|
+
Paste into Claude Code, Cursor, Codex or Copilot:
|
|
59
|
+
|
|
60
|
+
> Add custom domains for my users with Cnamio: read and follow https://cnamio.com/agent-onboarding/SKILL.md. If I don't have a Cnamio account yet, start in the sandbox right away and ask me before signing me up for a free account with my email.
|
|
61
|
+
|
|
62
|
+
- Skill: https://cnamio.com/agent-onboarding/SKILL.md · Everything in one file: https://cnamio.com/llms-full.txt
|
|
63
|
+
- Recipe: [Django](https://cnamio.com/recipes/django.md) (FastAPI and Flask: the same calls; read the raw body for the webhook)
|
|
64
|
+
- MCP server: `https://api.cnamio.com/mcp` (`claude mcp add --transport http cnamio https://api.cnamio.com/mcp`)
|
|
65
|
+
|
|
66
|
+
## API
|
|
67
|
+
|
|
68
|
+
`create_session`, `check_domain`, `connect`, `connect_automatic`, `status`, `recheck`, `last_webhook`; `manage.jobs()`, `.usage()`, `.application()`, `.set_webhook_url()`, `.webhook_secret()`, `.test_webhook()`, `.create_share_link()`, `.rotate_secret()`; helpers `records_for_user`, `ownership_value`, `verify_webhook`. Errors raise `CnamioError` with `status` (and `conflicts` on 409).
|
|
69
|
+
|
|
70
|
+
Docs: https://cnamio.com/docs · OpenAPI: https://cnamio.com/openapi.json · MIT license.
|
cnamio-1.1.0/README.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# cnamio
|
|
2
|
+
|
|
3
|
+
Server SDK for [Cnamio](https://cnamio.com): let the users of your app connect their own domain (`shop.customer.com` → your app). Cnamio finds where the domain's DNS is hosted, creates the records with the user's provider token (used once, never stored) or returns the exact records to copy, confirms them on the authoritative nameservers and sends your backend a signed webhook. Existing DNS records are never deleted or overwritten.
|
|
4
|
+
|
|
5
|
+
One module, standard library only, type hints throughout, Python 3.9+. Server only: it holds your application secret.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install cnamio
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import os
|
|
13
|
+
from cnamio import Cnamio, records_for_user, verify_webhook
|
|
14
|
+
|
|
15
|
+
cnamio = Cnamio() # reads CNAMIO_APPLICATION_ID and CNAMIO_SECRET
|
|
16
|
+
# A CNAME to your hosting plus an ownership TXT unique to this user.
|
|
17
|
+
records = records_for_user(target="customers.yourapp.com", user_id=user.id, ownership_key=os.environ["CNAMIO_OWNERSHIP_KEY"])
|
|
18
|
+
|
|
19
|
+
session = cnamio.create_session(user_id=user.id, dns_records=records) # -> the browser's connect window
|
|
20
|
+
job = cnamio.connect("shop.customer.com", records, user_id=user.id) # or headless: exact records to show
|
|
21
|
+
status = cnamio.status(job["job_id"])["status"] # pending -> completed
|
|
22
|
+
ok = verify_webhook(raw_body, headers, os.environ.get("CNAMIO_WEBHOOK_SECRET")) # domain.added = connected
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
In the browser, load `https://connect.cnamio.com/sdk/v1.js` and call `window.cnamio.connectDomain({ ...session, applicationName: 'Your App' })`.
|
|
26
|
+
|
|
27
|
+
## No account yet
|
|
28
|
+
|
|
29
|
+
- **Sandbox, no account:** `curl -s -X POST https://api.cnamio.com/v1/agent/sandbox` returns a 30-minute session of a test application (no real DNS). Use it as `Authorization: Bearer <auth_token>` with header `applicationId` on the REST routes.
|
|
30
|
+
- **Free account:** sign up at https://cnamio.com/#start, or let your coding agent call `POST https://api.cnamio.com/v1/agent/signup` (MCP tool `start_signup`) with your email. You get a test application (sandbox provider) and a live one on the free plan once you open the emailed link.
|
|
31
|
+
|
|
32
|
+
## For coding agents
|
|
33
|
+
|
|
34
|
+
Paste into Claude Code, Cursor, Codex or Copilot:
|
|
35
|
+
|
|
36
|
+
> Add custom domains for my users with Cnamio: read and follow https://cnamio.com/agent-onboarding/SKILL.md. If I don't have a Cnamio account yet, start in the sandbox right away and ask me before signing me up for a free account with my email.
|
|
37
|
+
|
|
38
|
+
- Skill: https://cnamio.com/agent-onboarding/SKILL.md · Everything in one file: https://cnamio.com/llms-full.txt
|
|
39
|
+
- Recipe: [Django](https://cnamio.com/recipes/django.md) (FastAPI and Flask: the same calls; read the raw body for the webhook)
|
|
40
|
+
- MCP server: `https://api.cnamio.com/mcp` (`claude mcp add --transport http cnamio https://api.cnamio.com/mcp`)
|
|
41
|
+
|
|
42
|
+
## API
|
|
43
|
+
|
|
44
|
+
`create_session`, `check_domain`, `connect`, `connect_automatic`, `status`, `recheck`, `last_webhook`; `manage.jobs()`, `.usage()`, `.application()`, `.set_webhook_url()`, `.webhook_secret()`, `.test_webhook()`, `.create_share_link()`, `.rotate_secret()`; helpers `records_for_user`, `ownership_value`, `verify_webhook`. Errors raise `CnamioError` with `status` (and `conflicts` on 409).
|
|
45
|
+
|
|
46
|
+
Docs: https://cnamio.com/docs · OpenAPI: https://cnamio.com/openapi.json · MIT license.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cnamio
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: Server SDK for Cnamio: let your users connect their own custom domain to your app (DNS provider detection, automatic or guided records, propagation checks, signed webhooks). One module, standard library only.
|
|
5
|
+
Author-email: Cnamio <contato@cnamio.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://cnamio.com
|
|
8
|
+
Project-URL: Documentation, https://cnamio.com/docs
|
|
9
|
+
Project-URL: Repository, https://github.com/cnamio/sdk
|
|
10
|
+
Project-URL: For AI agents, https://cnamio.com/agent-onboarding/SKILL.md
|
|
11
|
+
Keywords: custom domains,custom domain,connect domain,dns,cname,domain verification,saas,multi-tenant,webhook,ai agents,mcp,cnamio
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Internet :: Name Service (DNS)
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# cnamio
|
|
26
|
+
|
|
27
|
+
Server SDK for [Cnamio](https://cnamio.com): let the users of your app connect their own domain (`shop.customer.com` → your app). Cnamio finds where the domain's DNS is hosted, creates the records with the user's provider token (used once, never stored) or returns the exact records to copy, confirms them on the authoritative nameservers and sends your backend a signed webhook. Existing DNS records are never deleted or overwritten.
|
|
28
|
+
|
|
29
|
+
One module, standard library only, type hints throughout, Python 3.9+. Server only: it holds your application secret.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install cnamio
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import os
|
|
37
|
+
from cnamio import Cnamio, records_for_user, verify_webhook
|
|
38
|
+
|
|
39
|
+
cnamio = Cnamio() # reads CNAMIO_APPLICATION_ID and CNAMIO_SECRET
|
|
40
|
+
# A CNAME to your hosting plus an ownership TXT unique to this user.
|
|
41
|
+
records = records_for_user(target="customers.yourapp.com", user_id=user.id, ownership_key=os.environ["CNAMIO_OWNERSHIP_KEY"])
|
|
42
|
+
|
|
43
|
+
session = cnamio.create_session(user_id=user.id, dns_records=records) # -> the browser's connect window
|
|
44
|
+
job = cnamio.connect("shop.customer.com", records, user_id=user.id) # or headless: exact records to show
|
|
45
|
+
status = cnamio.status(job["job_id"])["status"] # pending -> completed
|
|
46
|
+
ok = verify_webhook(raw_body, headers, os.environ.get("CNAMIO_WEBHOOK_SECRET")) # domain.added = connected
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
In the browser, load `https://connect.cnamio.com/sdk/v1.js` and call `window.cnamio.connectDomain({ ...session, applicationName: 'Your App' })`.
|
|
50
|
+
|
|
51
|
+
## No account yet
|
|
52
|
+
|
|
53
|
+
- **Sandbox, no account:** `curl -s -X POST https://api.cnamio.com/v1/agent/sandbox` returns a 30-minute session of a test application (no real DNS). Use it as `Authorization: Bearer <auth_token>` with header `applicationId` on the REST routes.
|
|
54
|
+
- **Free account:** sign up at https://cnamio.com/#start, or let your coding agent call `POST https://api.cnamio.com/v1/agent/signup` (MCP tool `start_signup`) with your email. You get a test application (sandbox provider) and a live one on the free plan once you open the emailed link.
|
|
55
|
+
|
|
56
|
+
## For coding agents
|
|
57
|
+
|
|
58
|
+
Paste into Claude Code, Cursor, Codex or Copilot:
|
|
59
|
+
|
|
60
|
+
> Add custom domains for my users with Cnamio: read and follow https://cnamio.com/agent-onboarding/SKILL.md. If I don't have a Cnamio account yet, start in the sandbox right away and ask me before signing me up for a free account with my email.
|
|
61
|
+
|
|
62
|
+
- Skill: https://cnamio.com/agent-onboarding/SKILL.md · Everything in one file: https://cnamio.com/llms-full.txt
|
|
63
|
+
- Recipe: [Django](https://cnamio.com/recipes/django.md) (FastAPI and Flask: the same calls; read the raw body for the webhook)
|
|
64
|
+
- MCP server: `https://api.cnamio.com/mcp` (`claude mcp add --transport http cnamio https://api.cnamio.com/mcp`)
|
|
65
|
+
|
|
66
|
+
## API
|
|
67
|
+
|
|
68
|
+
`create_session`, `check_domain`, `connect`, `connect_automatic`, `status`, `recheck`, `last_webhook`; `manage.jobs()`, `.usage()`, `.application()`, `.set_webhook_url()`, `.webhook_secret()`, `.test_webhook()`, `.create_share_link()`, `.rotate_secret()`; helpers `records_for_user`, `ownership_value`, `verify_webhook`. Errors raise `CnamioError` with `status` (and `conflicts` on 409).
|
|
69
|
+
|
|
70
|
+
Docs: https://cnamio.com/docs · OpenAPI: https://cnamio.com/openapi.json · MIT license.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cnamio
|
cnamio-1.1.0/cnamio.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Cnamio server SDK for Python 3.9+: one file, standard library only.
|
|
2
|
+
|
|
3
|
+
Latest: https://cnamio.com/sdk/cnamio.py · Docs: https://cnamio.com/docs
|
|
4
|
+
Use it on your server only: it holds the application secret.
|
|
5
|
+
|
|
6
|
+
from cnamio import Cnamio, records_for_user, verify_webhook
|
|
7
|
+
client = Cnamio() # reads CNAMIO_APPLICATION_ID and CNAMIO_SECRET
|
|
8
|
+
records = records_for_user(target="customers.yourapp.com", user_id=user.id, ownership_key=os.environ["CNAMIO_OWNERSHIP_KEY"])
|
|
9
|
+
session = client.create_session(user_id=user.id, dns_records=records) # send to the browser as is
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import hashlib
|
|
15
|
+
import hmac
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import time
|
|
20
|
+
import urllib.error
|
|
21
|
+
import urllib.parse
|
|
22
|
+
import urllib.request
|
|
23
|
+
from typing import Any, Mapping, Optional, Sequence
|
|
24
|
+
|
|
25
|
+
__all__ = ["Cnamio", "CnamioError", "records_for_user", "ownership_value", "verify_webhook", "VERSION"]
|
|
26
|
+
VERSION = "1.1.0"
|
|
27
|
+
DEFAULT_BASE_URL = "https://api.cnamio.com"
|
|
28
|
+
_SESSION_REUSE_SECONDS = 50 * 60 # session tokens live 60 minutes
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CnamioError(Exception):
|
|
32
|
+
"""A non-2xx answer from Cnamio. ``status`` is the HTTP status; ``conflicts`` is set on the 409 of
|
|
33
|
+
connect_automatic (reason codes as strings, e.g. ``name_occupied``). 503 means "not now": repeat the same call
|
|
34
|
+
after a few seconds."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, status: int, message: str = "", body: Any = None):
|
|
37
|
+
super().__init__(message or f"Cnamio answered {status}")
|
|
38
|
+
self.status = status
|
|
39
|
+
self.body = body
|
|
40
|
+
self.conflicts = body.get("conflicts") if isinstance(body, dict) and isinstance(body.get("conflicts"), list) else None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Cnamio:
|
|
44
|
+
def __init__(self, application_id: Optional[str] = None, secret: Optional[str] = None,
|
|
45
|
+
base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0):
|
|
46
|
+
self.application_id = application_id or os.environ.get("CNAMIO_APPLICATION_ID", "")
|
|
47
|
+
self.secret = secret or os.environ.get("CNAMIO_SECRET", "")
|
|
48
|
+
if not self.application_id or not self.secret:
|
|
49
|
+
raise ValueError("Cnamio: application_id and secret are required (or set CNAMIO_APPLICATION_ID and CNAMIO_SECRET).")
|
|
50
|
+
self.base_url = base_url.rstrip("/")
|
|
51
|
+
self.timeout = timeout
|
|
52
|
+
self._session: Optional[tuple[str, float]] = None
|
|
53
|
+
self.manage = _Manage(self)
|
|
54
|
+
|
|
55
|
+
def _request(self, method: str, path: str, body: Any = None, headers: Optional[Mapping[str, str]] = None) -> Any:
|
|
56
|
+
data = None if body is None else json.dumps(body).encode("utf-8")
|
|
57
|
+
all_headers = {"User-Agent": f"cnamio-python/{VERSION}", "Accept": "application/json"}
|
|
58
|
+
if data is not None:
|
|
59
|
+
all_headers["Content-Type"] = "application/json"
|
|
60
|
+
all_headers.update(headers or {})
|
|
61
|
+
request = urllib.request.Request(self.base_url + path, data=data, headers=all_headers, method=method)
|
|
62
|
+
try:
|
|
63
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
64
|
+
raw = response.read()
|
|
65
|
+
except urllib.error.HTTPError as error:
|
|
66
|
+
raw = error.read()
|
|
67
|
+
try:
|
|
68
|
+
payload = json.loads(raw) if raw else None
|
|
69
|
+
except ValueError:
|
|
70
|
+
payload = None
|
|
71
|
+
message = payload.get("message", "") if isinstance(payload, dict) else ""
|
|
72
|
+
raise CnamioError(error.code, message, payload) from None
|
|
73
|
+
return json.loads(raw) if raw else None
|
|
74
|
+
|
|
75
|
+
def create_session(self, user_id: Any = None, dns_records: Optional[Sequence[Mapping[str, Any]]] = None,
|
|
76
|
+
domain: Optional[str] = None) -> dict:
|
|
77
|
+
"""A session token for the connect window. Bind ``dns_records`` (and optionally ``domain``) and send the result
|
|
78
|
+
to your page as is: ``cnamio.connectDomain({...session, applicationName, locale})``."""
|
|
79
|
+
body: dict = {"applicationId": self.application_id, "secret": self.secret}
|
|
80
|
+
if user_id is not None:
|
|
81
|
+
body["userId"] = str(user_id)
|
|
82
|
+
if dns_records is not None:
|
|
83
|
+
body["dnsRecords"] = list(dns_records)
|
|
84
|
+
if domain is not None:
|
|
85
|
+
body["domain"] = domain
|
|
86
|
+
data = self._request("POST", "/token", body)
|
|
87
|
+
session = {"token": data["auth_token"], "applicationId": self.application_id, "expiresAt": int((time.time() + 3600) * 1000)}
|
|
88
|
+
if dns_records is not None:
|
|
89
|
+
session["dnsRecords"] = list(dns_records)
|
|
90
|
+
return session
|
|
91
|
+
|
|
92
|
+
def _token(self, force: bool = False) -> str:
|
|
93
|
+
if not force and self._session and self._session[1] > time.time():
|
|
94
|
+
return self._session[0]
|
|
95
|
+
token = self.create_session()["token"]
|
|
96
|
+
self._session = (token, time.time() + _SESSION_REUSE_SECONDS)
|
|
97
|
+
return token
|
|
98
|
+
|
|
99
|
+
def _session_call(self, method: str, path: str, body: Any = None) -> Any:
|
|
100
|
+
for attempt in (0, 1):
|
|
101
|
+
token = self._token(force=attempt > 0)
|
|
102
|
+
try:
|
|
103
|
+
return self._request(method, path, body, {"Authorization": f"Bearer {token}", "applicationId": self.application_id})
|
|
104
|
+
except CnamioError as error:
|
|
105
|
+
# An expired or rotated session is renewed once.
|
|
106
|
+
if attempt == 0 and error.status == 401:
|
|
107
|
+
self._session = None
|
|
108
|
+
continue
|
|
109
|
+
raise
|
|
110
|
+
raise AssertionError("unreachable")
|
|
111
|
+
|
|
112
|
+
def check_domain(self, domain: str, dns_records: Sequence[Mapping[str, Any]], check_conflicts: bool = True,
|
|
113
|
+
locale: Optional[str] = None, accept_merges: bool = False) -> dict:
|
|
114
|
+
"""Where the domain's DNS is, whether it can be automatic, conflicts and the current record state.
|
|
115
|
+
|
|
116
|
+
With accept_merges, an SPF policy to merge into the existing one comes only in recordMerges; without it, it is
|
|
117
|
+
also listed in recordConflicts as spf_merge_required (with the merged value in its "merge" field).
|
|
118
|
+
"""
|
|
119
|
+
body = {"domain": domain, "dnsRecords": list(dns_records), "checkConflicts": check_conflicts}
|
|
120
|
+
if accept_merges:
|
|
121
|
+
body["acceptMerges"] = True
|
|
122
|
+
if locale:
|
|
123
|
+
body["locale"] = locale
|
|
124
|
+
return self._session_call("POST", "/checkdomain", body)
|
|
125
|
+
|
|
126
|
+
def connect(self, domain: str, dns_records: Sequence[Mapping[str, Any]], user_id: Any = None, locale: Optional[str] = None) -> dict:
|
|
127
|
+
"""Manual setup: returns the exact records to show the user and starts watching propagation."""
|
|
128
|
+
body: dict = {"domain": domain, "dnsRecords": list(dns_records)}
|
|
129
|
+
if user_id is not None:
|
|
130
|
+
body["userId"] = str(user_id)
|
|
131
|
+
if locale:
|
|
132
|
+
body["locale"] = locale
|
|
133
|
+
return self._session_call("POST", "/connect", body)
|
|
134
|
+
|
|
135
|
+
def connect_automatic(self, domain: str, dns_records: Sequence[Mapping[str, Any]], provider_token: str, user_id: Any = None) -> dict:
|
|
136
|
+
"""Creates the records with the user's provider API token (used once, never stored). Raises CnamioError 409 or 422."""
|
|
137
|
+
body: dict = {"domain": domain, "dnsRecords": list(dns_records), "providerToken": provider_token}
|
|
138
|
+
if user_id is not None:
|
|
139
|
+
body["userId"] = str(user_id)
|
|
140
|
+
return self._session_call("POST", "/connect/automatic", body)
|
|
141
|
+
|
|
142
|
+
def status(self, job_id: str) -> dict:
|
|
143
|
+
return self._session_call("GET", f"/connect/{urllib.parse.quote(job_id, safe='')}/status")
|
|
144
|
+
|
|
145
|
+
def recheck(self, job_id: str) -> dict:
|
|
146
|
+
"""Checks propagation again now (at most once every 5 minutes per connection). A finished connection raises CnamioError 409."""
|
|
147
|
+
return self._session_call("POST", f"/connect/propagation/recheck/{urllib.parse.quote(job_id, safe='')}", {})
|
|
148
|
+
|
|
149
|
+
def last_webhook(self, job_id: str) -> dict:
|
|
150
|
+
return self._session_call("GET", f"/connect/webhooks/last/{urllib.parse.quote(job_id, safe='')}")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class _Manage:
|
|
154
|
+
"""Management API (HTTP Basic with the application credentials). Reach it as ``client.manage``."""
|
|
155
|
+
|
|
156
|
+
def __init__(self, client: Cnamio):
|
|
157
|
+
self._client = client
|
|
158
|
+
|
|
159
|
+
def _call(self, method: str, path: str, body: Any = None) -> Any:
|
|
160
|
+
basic = base64.b64encode(f"{self._client.application_id}:{self._client.secret}".encode()).decode()
|
|
161
|
+
return self._client._request(method, path, body, {"Authorization": f"Basic {basic}"})
|
|
162
|
+
|
|
163
|
+
def application(self) -> dict:
|
|
164
|
+
return self._call("GET", "/v1/manage/application")
|
|
165
|
+
|
|
166
|
+
def set_webhook_url(self, url: Optional[str]) -> dict:
|
|
167
|
+
"""HTTPS URL, or None to stop deliveries. Does not change the webhook secret."""
|
|
168
|
+
return self._call("PUT", "/v1/manage/webhook", {"url": url})
|
|
169
|
+
|
|
170
|
+
def set_record_names(self, strict: Optional[bool] = None, allowed_names: Optional[list] = None) -> dict:
|
|
171
|
+
"""Strict record names; allowed_names are relative to the zone ("@", "_dmarc"). None keeps the current value."""
|
|
172
|
+
body: dict = {}
|
|
173
|
+
if strict is not None:
|
|
174
|
+
body["strict"] = strict
|
|
175
|
+
if allowed_names is not None:
|
|
176
|
+
body["allowedNames"] = allowed_names
|
|
177
|
+
return self._call("PUT", "/v1/manage/record-names", body)
|
|
178
|
+
|
|
179
|
+
def set_monitoring(self, enabled: bool) -> dict:
|
|
180
|
+
"""Continuous monitoring of connected domains (read-only DNS checks): on or off."""
|
|
181
|
+
return self._call("PUT", "/v1/manage/monitoring", {"enabled": enabled})
|
|
182
|
+
|
|
183
|
+
def webhook_secret(self) -> dict:
|
|
184
|
+
return self._call("GET", "/v1/manage/webhook-secret")
|
|
185
|
+
|
|
186
|
+
def test_webhook(self) -> dict:
|
|
187
|
+
return self._call("POST", "/v1/manage/webhook-test", {})
|
|
188
|
+
|
|
189
|
+
def jobs(self, limit: Optional[int] = None, before: Optional[str] = None, status: Optional[str] = None,
|
|
190
|
+
domain: Optional[str] = None, health: Optional[str] = None, share_link_id: Optional[str] = None) -> dict:
|
|
191
|
+
query = {k: v for k, v in {"limit": limit, "before": before, "status": status, "domain": domain, "health": health,
|
|
192
|
+
"share_link_id": share_link_id}.items() if v is not None}
|
|
193
|
+
return self._call("GET", "/v1/manage/jobs" + (f"?{urllib.parse.urlencode(query)}" if query else ""))
|
|
194
|
+
|
|
195
|
+
def create_share_link(self, domains: list, dns_records: list, max_uses: Optional[int] = None, expires_in_days: Optional[float] = None,
|
|
196
|
+
user_id: Any = None, label: Optional[str] = None) -> dict:
|
|
197
|
+
"""A link for whoever manages the DNS (an agency, the IT team): they open `url` and connect these domains with these
|
|
198
|
+
records, without your secret. max_uses per domain (default 1), expires_in_days (default 7, at most 30).
|
|
199
|
+
`url` and `token` are returned only here: send the url to that person, do not log it."""
|
|
200
|
+
body: dict = {"domains": domains, "dnsRecords": dns_records}
|
|
201
|
+
if max_uses is not None:
|
|
202
|
+
body["maxUses"] = max_uses
|
|
203
|
+
if expires_in_days is not None:
|
|
204
|
+
body["expiresInDays"] = expires_in_days
|
|
205
|
+
if user_id is not None:
|
|
206
|
+
body["userId"] = str(user_id)
|
|
207
|
+
if label:
|
|
208
|
+
body["label"] = label
|
|
209
|
+
return self._call("POST", "/v1/manage/share-links", body)
|
|
210
|
+
|
|
211
|
+
def share_links(self, limit: Optional[int] = None, before: Optional[str] = None) -> dict:
|
|
212
|
+
"""Links of the application, newest first (never their tokens)."""
|
|
213
|
+
query = {k: v for k, v in {"limit": limit, "before": before}.items() if v is not None}
|
|
214
|
+
return self._call("GET", "/v1/manage/share-links" + (f"?{urllib.parse.urlencode(query)}" if query else ""))
|
|
215
|
+
|
|
216
|
+
def share_link(self, share_link_id: str) -> dict:
|
|
217
|
+
return self._call("GET", f"/v1/manage/share-links/{urllib.parse.quote(share_link_id, safe='')}")
|
|
218
|
+
|
|
219
|
+
def revoke_share_link(self, share_link_id: str) -> dict:
|
|
220
|
+
"""Ends the link now; connections already started go on."""
|
|
221
|
+
return self._call("POST", f"/v1/manage/share-links/{urllib.parse.quote(share_link_id, safe='')}/revoke", {})
|
|
222
|
+
|
|
223
|
+
def usage(self, month: Optional[str] = None) -> dict:
|
|
224
|
+
return self._call("GET", "/v1/manage/usage" + (f"?month={urllib.parse.quote(month)}" if month else ""))
|
|
225
|
+
|
|
226
|
+
def rotate_secret(self, grace_hours: Optional[float] = None) -> dict:
|
|
227
|
+
return self._call("POST", "/v1/manage/rotate-secret", {} if grace_hours is None else {"graceHours": grace_hours})
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def ownership_value(user_id: Any, ownership_key: str) -> str:
|
|
231
|
+
"""Stable per-user value: HMAC-SHA256(ownership_key, user_id), first 32 hex characters."""
|
|
232
|
+
return hmac.new(str(ownership_key).encode(), str(user_id).encode(), hashlib.sha256).hexdigest()[:32]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def records_for_user(target: str, user_id: Any, ownership_key: str, prefix: str = "cnamio-verify", ttl: int = 300) -> list:
|
|
236
|
+
"""A CNAME to your target plus a TXT unique to the user, so a user cannot claim a domain another user already pointed at you."""
|
|
237
|
+
if not target or user_id is None or not ownership_key:
|
|
238
|
+
raise ValueError("records_for_user: target, user_id and ownership_key are required.")
|
|
239
|
+
if not re.fullmatch(r"[a-z0-9-]{1,40}", prefix):
|
|
240
|
+
raise ValueError("records_for_user: prefix must be lowercase letters, digits or dashes.")
|
|
241
|
+
return [
|
|
242
|
+
{"type": "CNAME", "host": "{SUBDOMAIN}", "value": target, "ttl": ttl},
|
|
243
|
+
{"type": "TXT", "host": f"_{prefix}.{{SUBDOMAIN}}", "value": f"{prefix}={ownership_value(user_id, ownership_key)}", "ttl": ttl},
|
|
244
|
+
]
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def verify_webhook(raw_body: bytes | str, headers: Mapping[str, Any], secret: Optional[str], tolerance_seconds: int = 300,
|
|
248
|
+
now: Optional[float] = None) -> bool:
|
|
249
|
+
"""True when ``Cnamio-Signature`` (``sha256=<hex>`` over ``"{Cnamio-Timestamp}.{raw body}"``) and the timestamp are valid.
|
|
250
|
+
Pass the raw body exactly as received (FastAPI: ``await request.body()``; Flask: ``request.get_data()``)."""
|
|
251
|
+
def get(name: str) -> str:
|
|
252
|
+
for key in headers.keys():
|
|
253
|
+
if str(key).lower() == name:
|
|
254
|
+
value = headers[key]
|
|
255
|
+
return str(value[0] if isinstance(value, (list, tuple)) else value)
|
|
256
|
+
return ""
|
|
257
|
+
|
|
258
|
+
ts = get("cnamio-timestamp")
|
|
259
|
+
current = time.time() if now is None else now
|
|
260
|
+
if not secret or not re.fullmatch(r"\d{1,12}", ts) or abs(current - int(ts)) > tolerance_seconds:
|
|
261
|
+
return False
|
|
262
|
+
if not isinstance(raw_body, (bytes, bytearray, memoryview, str)):
|
|
263
|
+
# A parsed dict cannot be checked: its bytes are gone. Read the raw body instead.
|
|
264
|
+
raise TypeError("verify_webhook: pass the raw request body (bytes or str), not parsed JSON.")
|
|
265
|
+
body = raw_body.encode("utf-8") if isinstance(raw_body, str) else bytes(raw_body)
|
|
266
|
+
expected = "sha256=" + hmac.new(secret.encode(), ts.encode() + b"." + body, hashlib.sha256).hexdigest()
|
|
267
|
+
return hmac.compare_digest(expected.encode(), get("cnamio-signature").encode())
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cnamio"
|
|
7
|
+
version = "1.1.0"
|
|
8
|
+
description = "Server SDK for Cnamio: let your users connect their own custom domain to your app (DNS provider detection, automatic or guided records, propagation checks, signed webhooks). One module, standard library only."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Cnamio", email = "contato@cnamio.com" }]
|
|
13
|
+
keywords = ["custom domains", "custom domain", "connect domain", "dns", "cname", "domain verification", "saas", "multi-tenant", "webhook", "ai agents", "mcp", "cnamio"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 5 - Production/Stable",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Topic :: Internet :: Name Service (DNS)",
|
|
22
|
+
"Topic :: Software Development :: Libraries",
|
|
23
|
+
]
|
|
24
|
+
dependencies = []
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://cnamio.com"
|
|
28
|
+
Documentation = "https://cnamio.com/docs"
|
|
29
|
+
Repository = "https://github.com/cnamio/sdk"
|
|
30
|
+
"For AI agents" = "https://cnamio.com/agent-onboarding/SKILL.md"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools]
|
|
33
|
+
py-modules = ["cnamio"]
|
cnamio-1.1.0/setup.cfg
ADDED