Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
428 lines
15 KiB
Python
428 lines
15 KiB
Python
"""Synchronous standard-library client for Context Passport (Identity Lock).
|
|
|
|
Vendored verbatim from the canonical ``passport-sdk-python`` v0.1.0 in the
|
|
sibling Railyard repo (``railyard/apps/context-passport/sdks/python``,
|
|
commit ``6bb17294``) -- not rebuilt from scratch, same pattern as this
|
|
Menivor repo's ``apps/mint`` vendoring its crate graph from Railyard's
|
|
``apps/mint``. Keep the two copies in sync when the Context Passport API
|
|
changes. Mirrors ``@railyard/context-passport-sdk`` (the TypeScript SDK,
|
|
``apps/context-passport/sdks/typescript``) route-for-route and
|
|
error-shape-for-error-shape.
|
|
|
|
Real caller in this repo: :func:`app.services.context_passport.
|
|
fetch_locked_brand_assets`. ``app.domains.gateway.identity_lock_client``
|
|
keeps its own httpx-based client for now -- it has its own test suite built
|
|
on ``httpx.MockTransport`` dependency injection and real ownership/proof
|
|
validation layered on top; swapping its transport for this urllib-based
|
|
client is a separate, riskier change, not done here.
|
|
|
|
Lock an identity once -- a character, a brand, a persona, a voice, a style --
|
|
and reproduce it consistently on any provider.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any, Mapping, NotRequired, TypedDict
|
|
from urllib.error import HTTPError
|
|
from urllib.parse import quote, urlencode, urljoin, urlparse
|
|
from urllib.request import Request, urlopen
|
|
|
|
PassportKind = str # "character" | "brand" | "persona" | "voice" | "style"
|
|
VersionStatus = str # "draft" | "locked"
|
|
Modality = str # "image" | "voice" | "video" | "text"
|
|
|
|
|
|
class PassportApiError(RuntimeError):
|
|
"""Raised for any non-2xx response, carrying the server's stable error code."""
|
|
|
|
def __init__(self, status: int, code: str, message: str, body: Any) -> None:
|
|
super().__init__(f"Context Passport returned HTTP {status} ({code}): {message}")
|
|
self.status = status
|
|
self.code = code
|
|
self.body = body
|
|
|
|
|
|
class Rights(TypedDict, total=False):
|
|
basis: str
|
|
likeness_of: str | None
|
|
consent_obtained: bool
|
|
consent_record_ref: str | None
|
|
scope: list[str]
|
|
prohibited_uses: list[str]
|
|
term_start: str | None
|
|
term_end: str | None
|
|
territory: list[str]
|
|
revocable: bool
|
|
disclosure: str
|
|
iptc_digital_source_type: str
|
|
royalty_bps: int
|
|
|
|
|
|
class Passport(TypedDict):
|
|
id: str
|
|
kind: str
|
|
owner: str
|
|
status: str
|
|
version: int
|
|
created_at: str
|
|
updated_at: str
|
|
archived_at: NotRequired[str | None]
|
|
|
|
|
|
class PassportVersion(TypedDict):
|
|
passport_id: str
|
|
version: int
|
|
status: str
|
|
assets: dict[str, Any]
|
|
rights: Rights
|
|
content_digest: NotRequired[str | None]
|
|
created_at: str
|
|
updated_at: str
|
|
locked_at: NotRequired[str | None]
|
|
|
|
|
|
class PassportView(Passport):
|
|
"""``Passport`` flattened with its head version -- every read endpoint's shape."""
|
|
|
|
head: PassportVersion
|
|
|
|
|
|
class ConditioningPayload(TypedDict):
|
|
passport_id: str
|
|
version: int
|
|
provider: str
|
|
modality: str
|
|
reference_images: NotRequired[list[str]]
|
|
lora_ref: NotRequired[str | None]
|
|
embedding_ref: NotRequired[str | None]
|
|
avatar_ref: NotRequired[str | None]
|
|
reference_audio: NotRequired[list[str]]
|
|
voice_id: NotRequired[str | None]
|
|
style_prompt: NotRequired[str | None]
|
|
negative_prompt: NotRequired[str | None]
|
|
text_directives: NotRequired[list[str]]
|
|
extra: NotRequired[dict[str, str]]
|
|
|
|
|
|
class SettlementReceiptProof(TypedDict):
|
|
sequence: int
|
|
operation: str
|
|
operation_hash: str
|
|
amount_micros: int
|
|
receipt_hash: str
|
|
signature: str
|
|
|
|
|
|
class SettlementAttestationProof(TypedDict):
|
|
format: str
|
|
payload_base64url: str
|
|
digest_sha256: str
|
|
signer_key_id: str
|
|
signature_hex: str
|
|
|
|
|
|
class PaymentEvidence(TypedDict):
|
|
request_id: str
|
|
payer_account: str
|
|
receipt: SettlementReceiptProof
|
|
attestation: NotRequired[SettlementAttestationProof]
|
|
|
|
|
|
class GenerationRecord(TypedDict):
|
|
id: str
|
|
passport_id: str
|
|
version: int
|
|
passport_content_digest: NotRequired[str | None]
|
|
provider: str
|
|
modality: str
|
|
output_ref: str
|
|
asset_hash: NotRequired[str | None]
|
|
iptc_digital_source_type: str
|
|
disclosure_required: bool
|
|
mint_receipt_ref: NotRequired[str | None]
|
|
meter_receipt_ref: NotRequired[str | None]
|
|
royalty_receipt_ref: NotRequired[str | None]
|
|
payment_evidence: NotRequired[PaymentEvidence | None]
|
|
prompt: NotRequired[str | None]
|
|
output_text: NotRequired[str | None]
|
|
created_at: str
|
|
|
|
|
|
class TrainedArtifact(TypedDict):
|
|
id: str
|
|
passport_id: str
|
|
version: int
|
|
source_digest: NotRequired[str | None]
|
|
provider: str
|
|
kind: str
|
|
artifact_ref: NotRequired[str | None]
|
|
provider_model: NotRequired[str | None]
|
|
status: str
|
|
failure_reason: NotRequired[str | None]
|
|
created_at: str
|
|
updated_at: str
|
|
|
|
|
|
class PassportClient:
|
|
"""Dependency-free client speaking Context Passport's real ``/v1`` surface.
|
|
|
|
Keep ``api_key`` and this client server-side -- never ship a Passport API
|
|
key to a browser or mobile binary, the same rule as every other Railyard
|
|
rail client (Mint, Vend).
|
|
"""
|
|
|
|
def __init__(self, base_url: str, api_key: str, *, timeout: float = 10.0) -> None:
|
|
parsed = urlparse(base_url)
|
|
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
raise ValueError("base_url must be an absolute HTTP(S) URL")
|
|
self.base_url = base_url.rstrip("/") + "/"
|
|
self.api_key = api_key
|
|
self.timeout = timeout
|
|
|
|
def create(
|
|
self,
|
|
*,
|
|
idempotency_key: str,
|
|
kind: str,
|
|
owner: str | None = None,
|
|
assets: Mapping[str, Any] | None = None,
|
|
rights: Rights | None = None,
|
|
) -> PassportView:
|
|
"""Create a draft passport. Idempotent on ``idempotency_key``."""
|
|
if not idempotency_key.strip():
|
|
raise ValueError("idempotency_key must not be empty")
|
|
body: dict[str, Any] = {"idempotency_key": idempotency_key, "kind": kind}
|
|
if owner is not None:
|
|
body["owner"] = owner
|
|
if assets is not None:
|
|
body["assets"] = dict(assets)
|
|
if rights is not None:
|
|
body["rights"] = dict(rights)
|
|
return self._request("POST", "v1/passports", body)
|
|
|
|
def list(
|
|
self,
|
|
*,
|
|
owner: str | None = None,
|
|
kind: str | None = None,
|
|
limit: int | None = None,
|
|
include_archived: bool | None = None,
|
|
archived_only: bool | None = None,
|
|
) -> list[Passport]:
|
|
return self._request(
|
|
"GET",
|
|
f"v1/passports{_query(owner=owner, kind=kind, limit=limit, include_archived=include_archived, archived_only=archived_only)}",
|
|
)
|
|
|
|
def get(self, passport_id: str) -> PassportView:
|
|
return self._request("GET", f"v1/passports/{_segment(passport_id)}")
|
|
|
|
def update_draft(self, passport_id: str, patch: Mapping[str, Any]) -> PassportView:
|
|
"""Merge a typed patch into the head DRAFT. A locked head answers 409."""
|
|
return self._request("PATCH", f"v1/passports/{_segment(passport_id)}", dict(patch))
|
|
|
|
def lock(self, passport_id: str) -> PassportView:
|
|
"""Freeze the head version: validates rights, content-addresses it, immutable."""
|
|
return self._request("POST", f"v1/passports/{_segment(passport_id)}/lock", {})
|
|
|
|
def archive(self, passport_id: str) -> PassportView:
|
|
return self._request("POST", f"v1/passports/{_segment(passport_id)}/archive", {})
|
|
|
|
def unarchive(self, passport_id: str) -> PassportView:
|
|
return self._request("POST", f"v1/passports/{_segment(passport_id)}/unarchive", {})
|
|
|
|
def new_version(self, passport_id: str) -> PassportView:
|
|
"""Branch a new draft from the locked head."""
|
|
return self._request("POST", f"v1/passports/{_segment(passport_id)}/versions", {})
|
|
|
|
def versions(self, passport_id: str) -> list[PassportVersion]:
|
|
"""Full version history, oldest first."""
|
|
return self._request("GET", f"v1/passports/{_segment(passport_id)}/versions")
|
|
|
|
def version(self, passport_id: str, version: int) -> PassportVersion:
|
|
return self._request(
|
|
"GET", f"v1/passports/{_segment(passport_id)}/versions/{int(version)}"
|
|
)
|
|
|
|
def resolve(
|
|
self, passport_id: str, *, provider: str, modality: str, version: int | None = None
|
|
) -> ConditioningPayload:
|
|
"""Resolve a locked version into provider-specific conditioning (no generation)."""
|
|
body: dict[str, Any] = {"provider": provider, "modality": modality}
|
|
if version is not None:
|
|
body["version"] = int(version)
|
|
return self._request("POST", f"v1/passports/{_segment(passport_id)}/resolve", body)
|
|
|
|
def generate(
|
|
self,
|
|
passport_id: str,
|
|
*,
|
|
provider: str,
|
|
modality: str,
|
|
version: int | None = None,
|
|
prompt: str | None = None,
|
|
) -> GenerationRecord:
|
|
"""Generate AS this passport through Relay; records signed provenance."""
|
|
body: dict[str, Any] = {"provider": provider, "modality": modality}
|
|
if version is not None:
|
|
body["version"] = int(version)
|
|
if prompt is not None:
|
|
body["prompt"] = prompt
|
|
return self._request("POST", f"v1/passports/{_segment(passport_id)}/generate", body)
|
|
|
|
def attest(
|
|
self,
|
|
passport_id: str,
|
|
*,
|
|
provider: str,
|
|
modality: str,
|
|
output_ref: str,
|
|
payment_evidence: PaymentEvidence,
|
|
settled_at_ms: int,
|
|
version: int | None = None,
|
|
asset_hash: str | None = None,
|
|
) -> GenerationRecord:
|
|
"""Record a generation performed by another first-party surface, after
|
|
re-verifying lock + signed settlement evidence."""
|
|
body: dict[str, Any] = {
|
|
"provider": provider,
|
|
"modality": modality,
|
|
"output_ref": output_ref,
|
|
"payment_evidence": dict(payment_evidence),
|
|
"settled_at_ms": int(settled_at_ms),
|
|
}
|
|
if version is not None:
|
|
body["version"] = int(version)
|
|
if asset_hash is not None:
|
|
body["asset_hash"] = asset_hash
|
|
return self._request("POST", f"v1/passports/{_segment(passport_id)}/attest", body)
|
|
|
|
def generations(self, passport_id: str) -> list[GenerationRecord]:
|
|
return self._request("GET", f"v1/passports/{_segment(passport_id)}/generations")
|
|
|
|
def generation_manifest(self, passport_id: str, generation_id: str) -> dict[str, Any]:
|
|
"""The C2PA-aligned Content Credential manifest for one generation."""
|
|
return self._request(
|
|
"GET",
|
|
f"v1/passports/{_segment(passport_id)}/generations/{_segment(generation_id)}/manifest",
|
|
)
|
|
|
|
def register_artifact(
|
|
self,
|
|
passport_id: str,
|
|
*,
|
|
provider: str,
|
|
kind: str,
|
|
version: int | None = None,
|
|
artifact_ref: str | None = None,
|
|
provider_model: str | None = None,
|
|
status: str | None = None,
|
|
) -> TrainedArtifact:
|
|
body: dict[str, Any] = {"provider": provider, "kind": kind}
|
|
for key, value in (
|
|
("version", version),
|
|
("artifact_ref", artifact_ref),
|
|
("provider_model", provider_model),
|
|
("status", status),
|
|
):
|
|
if value is not None:
|
|
body[key] = value
|
|
return self._request("POST", f"v1/passports/{_segment(passport_id)}/artifacts", body)
|
|
|
|
def artifacts(self, passport_id: str) -> list[TrainedArtifact]:
|
|
return self._request("GET", f"v1/passports/{_segment(passport_id)}/artifacts")
|
|
|
|
def artifact(self, passport_id: str, artifact_id: str) -> TrainedArtifact:
|
|
return self._request(
|
|
"GET", f"v1/passports/{_segment(passport_id)}/artifacts/{_segment(artifact_id)}"
|
|
)
|
|
|
|
def update_artifact(
|
|
self,
|
|
passport_id: str,
|
|
artifact_id: str,
|
|
*,
|
|
status: str,
|
|
artifact_ref: str | None = None,
|
|
provider_model: str | None = None,
|
|
failure_reason: str | None = None,
|
|
) -> TrainedArtifact:
|
|
body: dict[str, Any] = {"status": status}
|
|
for key, value in (
|
|
("artifact_ref", artifact_ref),
|
|
("provider_model", provider_model),
|
|
("failure_reason", failure_reason),
|
|
):
|
|
if value is not None:
|
|
body[key] = value
|
|
return self._request(
|
|
"PATCH",
|
|
f"v1/passports/{_segment(passport_id)}/artifacts/{_segment(artifact_id)}",
|
|
body,
|
|
)
|
|
|
|
def revoke_artifact(
|
|
self, passport_id: str, artifact_id: str, *, reason: str | None = None
|
|
) -> TrainedArtifact:
|
|
body = None if reason is None else {"reason": reason}
|
|
return self._request(
|
|
"DELETE",
|
|
f"v1/passports/{_segment(passport_id)}/artifacts/{_segment(artifact_id)}",
|
|
body,
|
|
)
|
|
|
|
def healthy(self) -> bool:
|
|
try:
|
|
with urlopen(urljoin(self.base_url, "healthz"), timeout=self.timeout) as response:
|
|
return 200 <= response.status < 300
|
|
except HTTPError:
|
|
return False
|
|
|
|
def _request(self, method: str, path: str, body: Mapping[str, Any] | None = None) -> Any:
|
|
encoded = None if body is None else json.dumps(body, separators=(",", ":")).encode()
|
|
request = Request(
|
|
urljoin(self.base_url, path),
|
|
data=encoded,
|
|
method=method,
|
|
headers={
|
|
"Accept": "application/json",
|
|
"X-API-Key": self.api_key,
|
|
**({"Content-Type": "application/json"} if encoded is not None else {}),
|
|
},
|
|
)
|
|
try:
|
|
with urlopen(request, timeout=self.timeout) as response:
|
|
status = response.status
|
|
raw = response.read()
|
|
except HTTPError as error:
|
|
status = error.code
|
|
raw = error.read()
|
|
try:
|
|
payload = json.loads(raw) if raw else None
|
|
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
payload = None
|
|
if status < 200 or status >= 300 or not isinstance(payload, dict) or "data" not in payload:
|
|
raise _api_error(status, payload)
|
|
return payload["data"]
|
|
|
|
|
|
def _segment(value: str) -> str:
|
|
return quote(value, safe="")
|
|
|
|
|
|
def _query(**params: Any) -> str:
|
|
pairs = {k: str(v) for k, v in params.items() if v is not None}
|
|
return f"?{urlencode(pairs)}" if pairs else ""
|
|
|
|
|
|
def _api_error(status: int, payload: Any) -> PassportApiError:
|
|
detail = payload.get("error") if isinstance(payload, dict) else None
|
|
code = detail.get("code", "http_error") if isinstance(detail, dict) else "http_error"
|
|
message = (
|
|
detail.get("message", f"Context Passport request failed with HTTP {status}")
|
|
if isinstance(detail, dict)
|
|
else f"Context Passport request failed with HTTP {status}"
|
|
)
|
|
return PassportApiError(status, code, message, payload)
|