Metadata-Version: 2.5
Name: burnedsecret
Version: 1.3.1
Summary: Official zero-knowledge SDK for burnedsecret.com
Project-URL: Homepage, https://burnedsecret.com
Project-URL: Documentation, https://burnedsecret.com/docs
Project-URL: Repository, https://github.com/JensrudJ/burnedsecret
Author: burnedsecret
License-Expression: MIT
Requires-Python: >=3.10
Requires-Dist: cryptography>=42
Requires-Dist: requests>=2.32
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: responses>=0.25; extra == 'dev'
Requires-Dist: twine>=5.0; extra == 'dev'
Description-Content-Type: text/markdown

# burnedsecret — Official Python SDK for burnedsecret.com

When you put a secret into burnedsecret, your browser (or your client library)
encrypts it on your own device before anything leaves you. The encryption key
never goes to our server. We store an opaque blob of encrypted bytes; we cannot
read it, and neither can anyone who breaches our database, subpoenas us, or
gets a court order against us. We have nothing to hand over.

This package is the official Python client. All crypto runs in your process —
the server only sees ciphertext, IVs, and (for the request flow) RSA-OAEP
wrapped keys plus a private key that is itself encrypted. The decryption
material lives in URL fragments you hold (`#k=` for secrets, `#s=` for a
request's private view link), never on our servers.

## Installation

```bash
pip install burnedsecret
```

Python 3.10 or newer is required. The SDK pulls in `cryptography>=42` and
`requests>=2.32` and nothing else.

## Quick start

### One-way secret (you share a password with someone)

```python
from burnedsecret import BurnedSecret

bs = BurnedSecret(api_key="bs_...")

url, secret_id = bs.create_secret("hunter2", ttl=86400)
# url looks like: https://burnedsecret.com/s/<id>#k=<base64url AES key>
# the part after '#' never leaves the caller's process — browsers do not
# transmit URL fragments to servers, and this SDK only sends ciphertext + IV.

plaintext = bs.read_secret(url)   # burns the secret on read
```

### Secret request (you ask someone to send you a password)

Creating a request needs your API key. It returns two links:

```python
from burnedsecret import BurnedSecret

bs = BurnedSecret(api_key="bs_...")

url, request_id, private_view_url = bs.create_request(
    prompt="Send me your AWS root key",
    webhook_url="https://acme.example/hooks/bs",
    ttl=86400,
)
# url              -> https://burnedsecret.com/r/<id>
#                     The submission link. Send it to the person answering.
# private_view_url -> https://burnedsecret.com/r/<id>/view#s=<root secret>
#                     The private view link. Keep it yourself.
```

The **private view link** is a bearer capability. Anyone who has it can read
the reply once. If you lose it, the reply cannot be recovered: the server has
no copy of the `#s=` fragment and there is no account-based recovery. Store it
like a password (for example in your secret store, keyed by `request_id`) and
never write it to ordinary logs.

Reading needs no API key. The private view link is the credential:

```python
reader = BurnedSecret()  # keyless

# Non-consuming status check: {"status": "waiting" | "ready", "expires_at": ...}
view = reader.get_request_view(private_view_url)

# The one explicit read. It consumes the reply, so it works exactly once.
if view["status"] == "ready":
    reply = reader.read_fulfillment(private_view_url)
```

When the request was created with custom fields, `read_fulfillment` returns a
`dict` mapping field name → value instead of a string:

```python
url, request_id, private_view_url = bs.create_request(
    prompt="Send me your AWS keypair",
    fields=[
        {"name": "access_key_id", "type": "text", "required": True},
        {"name": "secret_access_key", "type": "password", "required": True},
    ],
)
data = reader.read_fulfillment(private_view_url)
# data == {"access_key_id": "AKIA...", "secret_access_key": "wJal..."}
```

`read_fulfillment(private_view_url)` checks the status first and raises without
consuming anything if the reply is not ready yet or the link cannot unlock the
request. It then sends a single consume call and **never retries it**. If that
call fails in a way that leaves the outcome unknown (network error, timeout,
redirect, 5xx, or an unreadable response), it raises `RetrievalUncertainError`.
Do not retry on that error: the reply may already have been consumed.

```python
from burnedsecret import RetrievalUncertainError

try:
    reply = reader.read_fulfillment(private_view_url)
except RetrievalUncertainError:
    # Do NOT call read_fulfillment again. Check with the sender instead.
    ...
```

The SDK never polls on its own. If you check status in a loop, pace it
yourself: the private-link routes allow 60 requests per minute per IP. A
webhook (below) avoids polling altogether.

#### Breaking change

`create_request` and `read_fulfillment` changed shape in this release line.
`create_request` now returns `(url, id, private_view_url)` and no longer
returns raw PKCS8 private-key bytes. `read_fulfillment` now takes the private
view link instead of a request id and key. The private-key export/import
helpers were removed, and `api_key` is optional for private-link reads.
Private keys saved from earlier versions cannot read new requests. The next
published release needs a major-version decision; the package version has not
been bumped yet.

### Verifying webhooks

When a request is fulfilled (or a secret is burned) burnedsecret POSTs a flat
JSON event to your `webhook_url`, signed with HMAC-SHA256 over the exact body
bytes. Fetch your signing secret once from the dashboard API
(`GET /v1/keys/webhook-secret`, Firebase-session auth) and keep it server-side.

```python
from flask import Flask, request
from burnedsecret import BurnedSecret, WebhookSignatureError, verify_webhook

app = Flask(__name__)
reader = BurnedSecret()  # private-link reads need no API key

@app.post("/webhooks/burnedsecret")
def burnedsecret_hook():
    try:
        event = verify_webhook(
            request.get_data(),                    # RAW bytes — never re-serialised JSON
            request.headers.get("X-Signature"),    # "sha256=<hex>"
            WEBHOOK_SIGNING_SECRET,
        )
    except WebhookSignatureError:
        return "", 401
    # X-Webhook-ID is unique per delivery: store it and ignore repeats (idempotency).
    if event["event"] == "request.fulfilled":
        # Look up the private view link you stored when you created the request.
        private_view_url = my_secret_store.get(f"bs/req/{event['request_id']}")
        data = reader.read_fulfillment(private_view_url)   # one read, never retried
    return "", 204
```

Payloads never contain plaintext, keys, or URLs with key fragments. In
particular, neither webhook payloads nor notification emails ever contain the
private view link, so your handler must look it up from your own storage by
`event["request_id"]`:

```json
{"event": "request.fulfilled", "request_id": "...", "fulfilled_at": "2026-09-14T10:00:00Z"}
{"event": "secret.burned",     "secret_id": "...",  "burned_at":    "2026-09-14T10:00:00Z"}
```

`sign_webhook_body(body, secret)` produces the same header the server sends,
for building fixtures in your own tests. Deliveries are dispatched by a
scheduled processor and retried with backoff, so expect minutes rather than
seconds between fulfilment and delivery.

## Access restrictions

You can limit who may open a secret, or who may answer and read a request, by
IP address and country. Build an `AccessRestrictions` and pass it in:

```python
from burnedsecret import AccessRestrictions, BurnedSecret

bs = BurnedSecret(api_key="bs_...")
office = AccessRestrictions(
    allowed_cidrs=["10.0.0.0/8", "2001:db8::/32"],
    allowed_countries=["NO", "SE"],
)

# Text secret
url, id_ = bs.create_secret("hunter2", access_restrictions=office)

# File secret: same option
url, id_ = bs.create_secret(file="report.pdf", access_restrictions=office)

# Request: restrict who can reply and who can read the reply, separately
url, id_, private_view_url = bs.create_request(
    "send the AWS key",
    fulfill_restrictions=office,
    retrieve_restrictions=AccessRestrictions(allowed_cidrs=["192.0.2.0/24"]),
)
```

The example above sends
`{"allowedCidrs": ["10.0.0.0/8", "2001:db8::/32"], "geoMode": "allow", "countries": ["NO", "SE"]}`.

Rules:

- **AND composition.** When you set both IP and country rules, the caller must
  pass both.
- **Allow or block, not both.** Use `allowed_countries` or `blocked_countries`.
  Setting both raises `ValueError`.
- **Limits.** At most 50 CIDRs and 249 countries. Countries are two-letter
  ISO-3166-1 codes in either case. `/0` CIDRs are rejected. Full CIDR syntax
  is checked by the server, and a rejection surfaces as `ApiError` (400).
- **Validated before sending.** Invalid input raises `ValueError`, or
  `TypeError` if you pass something other than an `AccessRestrictions`, before
  any network call. A restriction is never silently dropped.
- **Empty means none.** `AccessRestrictions()` with all lists empty sends no
  restriction. On requests, an empty axis is not sent.
- **Denial looks like a missing secret.** A caller outside the rules gets the
  same 404 as for a secret that does not exist. A blocked request fulfiller
  also gets a 404. A blocked reader of the private view link gets 403
  `ACCESS_DENIED`, so read the reply from an allowed network.
- **Creator exemption is status-only.** The creator can still check status on
  the metadata endpoint from anywhere, but cannot read or burn the secret from
  outside the allowlist.
- **The web viewer is restricted too.** A plain-text secret opened at
  burnedsecret.com is checked against the same rules.
- **No CAPTCHA option.** CAPTCHA is a web-only feature and the SDK does not
  expose it.

## Partner API (PartnerClient)

Partners (a platform that serves its own customers) manage their own customers'
burnedsecret organizations with a partner key (`bs_ptn_...`). A partner key
only calls the `/v1/partner/*` endpoints. It never creates or reads secrets.

- **Getting a partner key.** The Owner of an organization on the partner tier
  mints partner keys in the dashboard's Partner keys section. The raw key is
  shown once.
- **Server-side only.** A partner key controls every customer org you created.
  Keep it in your backend's secret store. Never ship it in a browser, mobile
  app or any other client.
- **Separate clients.** `BurnedSecret(api_key="bs_ptn_...")` raises
  `ValueError`, and `PartnerClient` raises `ValueError` for anything that is
  not a `bs_ptn_` key.

```python
from burnedsecret import BurnedSecret, PartnerClient

partner = PartnerClient(api_key="bs_ptn_...")

# Idempotent on external_ref: a repeat call returns the existing org (created=False).
org, created = partner.create_customer_org(name="Acme AS", external_ref="crm-customer-42")

# Mint a service key for the customer. The raw key is in this response only.
key = partner.create_customer_key(org["org_id"], name="production")

# The customer key is a normal service key: use it with BurnedSecret.
customer = BurnedSecret(api_key=key["key"])
url, secret_id = customer.create_secret("hunter2")
```

| Method | Call |
|--------|------|
| `me()` | `GET /v1/partner/me` |
| `get_usage(window, cursor=None, limit=None)` | `GET /v1/partner/usage` |
| `create_customer_org(name, external_ref, key_daily_cap=None)` | `POST /v1/partner/orgs`, returns `(org, created)` |
| `list_customer_orgs(cursor=None, limit=None, external_ref=None)` | `GET /v1/partner/orgs` |
| `get_customer_org(org_id)` | `GET /v1/partner/orgs/{org_id}` |
| `update_customer_org(org_id, *, name=..., key_daily_cap=...)` | `PATCH /v1/partner/orgs/{org_id}` |
| `suspend_customer_org(org_id)` | `POST /v1/partner/orgs/{org_id}/suspend` |
| `resume_customer_org(org_id)` | `POST /v1/partner/orgs/{org_id}/resume` |
| `offboard_customer_org(org_id)` | `POST /v1/partner/orgs/{org_id}/offboard` |
| `get_customer_usage(org_id, window)` | `GET /v1/partner/orgs/{org_id}/usage` |
| `create_customer_key(org_id, name=None)` | `POST /v1/partner/orgs/{org_id}/keys` |
| `list_customer_keys(org_id)` | `GET /v1/partner/orgs/{org_id}/keys` |
| `revoke_customer_key(org_id, key_id)` | `DELETE /v1/partner/orgs/{org_id}/keys/{key_id}` |
| `get_customer_webhook_secret(org_id)` | `GET /v1/partner/orgs/{org_id}/webhook-secret` |
| `rotate_customer_webhook_secret(org_id)` | `POST /v1/partner/orgs/{org_id}/webhook-secret/rotate` |

Notes:

- `window` is 7, 30 or 90 days. Page lists by passing the previous page's
  `next_cursor` as `cursor`.
- `update_customer_org` sends only the fields you pass. `key_daily_cap=None`
  removes the cap. Passing neither field raises `ValueError`.
- **Offboarding is permanent.** `offboard_customer_org` sends the required
  `{"confirm": org_id}` itself. It revokes every customer key, burns every live
  secret and request, and deletes the signing secret. The org stays readable as
  a tombstone, and its `external_ref` can be used again for a new org.
  Offboard auditing is at least once: two concurrent first-time calls may both
  succeed, and the duplicate audit is marked `replayed: true`. Once offboarding
  is complete, a further call raises the 409 `CUSTOMER_OFFBOARDED` error.
- Suspending stops the customer's keys (403 `CUSTOMER_SUSPENDED`) without
  revoking them. Resuming makes the same keys work again.
- Use the customer org's webhook secret with `verify_webhook` to check that
  customer's deliveries.
- `revoke_customer_key` is idempotent: revoking a key that is already revoked
  returns the normal `{"id": key_id, "status": "revoked"}` result. Elsewhere a
  revoked key is an `ApiError` with status 410 and code `KEY_ALREADY_REVOKED`,
  never a `BurnedError` (that stays for burned secrets).
- Org and key ids must match `^[A-Za-z0-9_-]{1,128}$`. Any other value (for
  example `..`, `a/b` or an empty string) raises `ValueError` before a request
  is sent.
- Errors use the same classes as `BurnedSecret`: `NotFoundError` for 404
  (`ORG_NOT_FOUND` for an org that is not yours), `RateLimitError` for 429 and
  `ApiError` for the rest.
- A 429 is a `RateLimitError` whose `.code` names the limit:
  - `RATE_LIMIT_EXCEEDED` (the only code a `PartnerClient` gets): a per-key
    call limit (per minute or per day) is reached, or the partner's daily
    customer-org creation limit (org-creation limit), which every key of the
    partner shares; wait `retry_after_seconds` and retry.
  - `PARTNER_POOL_EXHAUSTED` (only on `BurnedSecret` calls made with customer
    keys): the partner's shared daily pool is used up. Partner-key calls
    never draw from it. `retry_after_seconds` is the time until the daily
    reset (UTC midnight), so wait at least that long.

## Key handling

Your decryption material never goes to our servers. For requests, the SDK
generates an RSA-4096 keypair and a random 32-byte root secret locally. It
sends the public key (SPKI DER, base64url) and the private key encrypted under
a key derived from the root secret. The root secret exists only in the `#s=`
fragment of the private view link returned to you. Reads send the server only
a separate derived retrieval token, never the root secret. Lose the private
view link and the reply is unrecoverable. That's the whole point.

The SDK never derives or stores key material outside of the values you receive
from `create_secret` (which returns the URL containing the AES key in its
fragment) and `create_request` (which returns `private_view_url`). Anything
your process needs to keep, the SDK hands you and forgets.

## Error handling

The SDK raises a small exception hierarchy:

```
BurnedSecretError
├── ApiError                  (HTTP-level failure; has .status_code, .code)
│   ├── NotFoundError         404 — secret/request not found
│   ├── BurnedError           410 — secret or fulfillment already consumed
│   ├── LegacyApiError        410 — pre-Phase-21 document, not API-accessible
│   └── RateLimitError        429 — has .retry_after_seconds
├── CryptoError               local AES/RSA failure (bad key, malformed data)
├── PassphraseRequiredError   protected secret read without a passphrase
├── RetrievalUncertainError   request consume outcome unknown; do not retry
└── WebhookSignatureError     incoming webhook failed HMAC verification (respond 401)
```

```python
from burnedsecret import (
    BurnedSecret, BurnedError, NotFoundError, RateLimitError, CryptoError,
)

bs = BurnedSecret(api_key="bs_...")
try:
    plaintext = bs.read_secret(url)
except BurnedError:
    print("Secret has already been viewed and burned.")
except NotFoundError:
    print("Secret never existed or expired.")
except RateLimitError as e:
    print(f"Too many requests — retry after {e.retry_after_seconds}s")
except CryptoError:
    print("The URL fragment is wrong or the ciphertext is corrupted.")
```

`BurnedSecret(api_key="...")` itself raises `ValueError` when a supplied API
key does not start with `bs_`. The key is optional: a keyless `BurnedSecret()`
can only call `get_request_view` and `read_fulfillment`, and `create_secret`,
`read_secret` and `create_request` raise `ValueError` before any network call
when no key was supplied.

## Test vectors and interop

The wire format — AES-256-GCM with a 12-byte IV and a 128-bit appended tag,
RSA-OAEP-SHA256 over a 4096-bit modulus, SPKI/PKCS8 DER with base64url no
padding — is pinned at `https://burnedsecret.com/api/v1/test-vectors.json`.

Any third-party Python implementation can prove conformance by round-tripping
that file. The same file lives in this repo at `web/api/v1/test-vectors.json`
and powers `tests/test_interop.py`, which asserts four invariants:

1. AES encrypt with `secret.aes_key + iv + plaintext` is byte-identical to
   `secret.ciphertext`.
2. AES decrypt of `secret.ciphertext` recovers `secret.plaintext_utf8`.
3. RSA-OAEP decrypt of `request.wrapped_key` with `request.private_key_pkcs8`
   recovers `request.content_aes_key`.
4. AES encrypt with the unwrapped key reproduces `request.ciphertext`.

If your SDK round-trips all four, it is wire-compatible with this one and with
the official JavaScript and Flutter clients.

## Crypto specification

Full algorithm parameters, key formats, and design rationale:
`.planning/design/zero-knowledge-architecture.md` in this repository.

## Development

```bash
git clone https://github.com/JensrudJ/burnedsecret
cd burnedsecret/sdk-python
pip install -e ".[dev]"
pytest -v
```

The test suite has 18 cases: 4 interop conformance + 4 crypto round-trips +
6 client wire-contract + 4 error-mapping. The RSA-4096 keygen test is marked
`@pytest.mark.slow` and runs in about three seconds; run `pytest -v -m "not slow"`
to skip it during fast inner-loop iteration.

## Releases

### 1.3.1

1.3.0 was never published; 1.3.1 is the first release with these changes.

- New `PartnerClient` for the partner API. See [Partner API (PartnerClient)](#partner-api-partnerclient).
- `BurnedSecret` now raises `ValueError` for a partner key (`bs_ptn_...`).
- New `AccessRestrictions` (exported from `burnedsecret`), `access_restrictions=` on
  `create_secret` (text and file), and keyword-only `fulfill_restrictions=` /
  `retrieve_restrictions=` on `create_request`. See [Access restrictions](#access-restrictions).
- The CLI's `burnedsecret` dependency floor must be raised to the first SDK
  release that contains `AccessRestrictions` (1.3.1 once published).
- `RateLimitError.code` carries the server code: `RATE_LIMIT_EXCEEDED` (a
  per-key call limit or the partner's org-creation limit) or
  `PARTNER_POOL_EXHAUSTED` (the partner pool); defaults to
  `RATE_LIMIT_EXCEEDED`.
  `retry_after_seconds` is unchanged.
- A 410 `KEY_ALREADY_REVOKED` raises `ApiError` (not `BurnedError`), and
  `PartnerClient.revoke_customer_key` treats an already-revoked key as success.
- `PartnerClient` validates org and key ids (`^[A-Za-z0-9_-]{1,128}$`) and
  raises `ValueError` before any request.

Releases are published from Codemagic on tags pushed to the burnedsecret repo:
- `@burnedsecret/sdk` (npm): tag matching `sdk-js-vMAJOR.MINOR.PATCH`
- `burnedsecret` (PyPI): tag matching `sdk-py-vMAJOR.MINOR.PATCH`

The version in the tag must match the version in `package.json` / `pyproject.toml`.

Every push to `dev` runs the test suite and the cross-SDK round-trip gate (D-15) but does NOT publish.

Each SDK release workflow also runs cross-SDK round trips at its own checkout
before publishing. Built packages must pass clean consumer installation checks.
A release tag must exactly match its package version; a tagged release fails
if its publishing credential is missing. Builds and publication run in Codemagic.

## License

MIT — see `LICENSE` in the repository root.


### Authenticated envelope formats

File secrets now use **BSF2**, which authenticates the complete header and each
chunk's position. Old BSF1 files are rejected; there is no legacy fallback.
This is an intentional format break for previously disposable test data.
Python 1.1.0, JavaScript 2.0.0 and the updated web file viewer use this format;
JavaScript 1.2.0 does not support it.

Unprotected text remains raw UTF-8, including literal `PP:` strings. Protected
SDK text uses a binary BSP2 marker that cannot collide with UTF-8 plaintext.
Collect a passphrase before fetching a protected secret: a missing/wrong
passphrase discovered after burn-on-read cannot be recovered by refetching.
See [the envelope specification](https://burnedsecret.com/security#crypto-envelopes) for framing and
interop vector version 3. Browser text protection is a separate flow; SDK
passphrase-protected text still requires an SDK reader.
